superbee 0.1.5 → 0.1.6

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.
package/dist/superbee.mjs CHANGED
@@ -44,7 +44,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
44
44
  var define_SUPERBEE_BUILD_IDENTITY_default;
45
45
  var init_define_SUPERBEE_BUILD_IDENTITY = __esm({
46
46
  "<define:__SUPERBEE_BUILD_IDENTITY__>"() {
47
- define_SUPERBEE_BUILD_IDENTITY_default = { schema: "superbee.build-identity.v1", package: { name: "superbee", version: "0.1.5" }, source: { commit: "ffeb9c61f8ae42b215b4913725c564afbbd19402", dirty: false }, artifact: { channel: "npm-package" }, compatibility_contracts: { skill: 1, hook: 1, mcp: 1 } };
47
+ define_SUPERBEE_BUILD_IDENTITY_default = { schema: "superbee.build-identity.v1", package: { name: "superbee", version: "0.1.6" }, source: { commit: "f1d6619026f0532f676c9cc22e31793a186b7cf6", dirty: false }, artifact: { channel: "npm-package" }, compatibility_contracts: { skill: 1, hook: 1, mcp: 1 } };
48
48
  }
49
49
  });
50
50
 
@@ -3604,8 +3604,8 @@ var require_js_yaml2 = __commonJS({
3604
3604
  "use strict";
3605
3605
  init_define_SUPERBEE_BUILD_IDENTITY();
3606
3606
  init_define_SUPERBEE_UPDATE_POLICY();
3607
- var yaml3 = require_js_yaml();
3608
- module2.exports = yaml3;
3607
+ var yaml4 = require_js_yaml();
3608
+ module2.exports = yaml4;
3609
3609
  }
3610
3610
  });
3611
3611
 
@@ -4020,6 +4020,70 @@ var require_gray_matter = __commonJS({
4020
4020
  }
4021
4021
  });
4022
4022
 
4023
+ // ../core/src/frontmatter-contract.ts
4024
+ function isUsableTimestamp(value) {
4025
+ return typeof value === "string" && value.trim() !== "";
4026
+ }
4027
+ var MalformedDocumentError;
4028
+ var init_frontmatter_contract = __esm({
4029
+ "../core/src/frontmatter-contract.ts"() {
4030
+ "use strict";
4031
+ init_define_SUPERBEE_BUILD_IDENTITY();
4032
+ init_define_SUPERBEE_UPDATE_POLICY();
4033
+ MalformedDocumentError = class extends Error {
4034
+ name = "MalformedDocumentError";
4035
+ context;
4036
+ detail;
4037
+ constructor(context, cause) {
4038
+ const detail = ((cause instanceof Error ? cause.message : String(cause)).split("\n")[0] ?? "").trim();
4039
+ super(
4040
+ `malformed frontmatter${context ? ` in '${context}'` : ""}: ${detail} \u2014 fix the YAML or remove the file`
4041
+ );
4042
+ if (context !== void 0) this.context = context;
4043
+ this.detail = detail;
4044
+ if (cause !== void 0) this.cause = cause;
4045
+ }
4046
+ };
4047
+ }
4048
+ });
4049
+
4050
+ // ../core/src/frontmatter-splitter.ts
4051
+ function delimiterLineEnd(input, offset) {
4052
+ if (!input.startsWith("---", offset)) return null;
4053
+ const suffix = offset + 3;
4054
+ if (suffix === input.length) return suffix;
4055
+ if (input[suffix] === "\n") return suffix + 1;
4056
+ if (input[suffix] === "\r" && input[suffix + 1] === "\n") return suffix + 2;
4057
+ return null;
4058
+ }
4059
+ function splitLeadingFrontmatter(raw, context) {
4060
+ const input = raw.startsWith("\uFEFF") ? raw.slice(1) : raw;
4061
+ const openingEnd = delimiterLineEnd(input, 0);
4062
+ if (openingEnd === null) return { body: input };
4063
+ let lineStart = openingEnd;
4064
+ while (lineStart < input.length) {
4065
+ const closingEnd = delimiterLineEnd(input, lineStart);
4066
+ if (closingEnd !== null) {
4067
+ return {
4068
+ yamlSource: input.slice(openingEnd, lineStart),
4069
+ body: input.slice(closingEnd)
4070
+ };
4071
+ }
4072
+ const nextLineFeed = input.indexOf("\n", lineStart);
4073
+ if (nextLineFeed === -1) break;
4074
+ lineStart = nextLineFeed + 1;
4075
+ }
4076
+ throw new MalformedDocumentError(context, new Error("unterminated YAML frontmatter delimiter"));
4077
+ }
4078
+ var init_frontmatter_splitter = __esm({
4079
+ "../core/src/frontmatter-splitter.ts"() {
4080
+ "use strict";
4081
+ init_define_SUPERBEE_BUILD_IDENTITY();
4082
+ init_define_SUPERBEE_UPDATE_POLICY();
4083
+ init_frontmatter_contract();
4084
+ }
4085
+ });
4086
+
4023
4087
  // ../core/src/frontmatter.ts
4024
4088
  function requireYamlTimestampType() {
4025
4089
  const type = import_js_yaml.default.DEFAULT_SAFE_SCHEMA.implicit.find(
@@ -4042,21 +4106,16 @@ function normalizeFrontmatter(data) {
4042
4106
  return out;
4043
4107
  }
4044
4108
  function parseMarkdown(raw, context) {
4045
- if (/^---(?:\r?\n|$)/.test(raw)) {
4046
- const firstLineEnd = raw.indexOf("\n");
4047
- const afterOpening = firstLineEnd === -1 ? "" : raw.slice(firstLineEnd + 1);
4048
- if (!/^---\r?$/m.test(afterOpening)) {
4049
- throw new MalformedDocumentError(context, new Error("unterminated YAML frontmatter delimiter"));
4050
- }
4051
- }
4109
+ const split = splitLeadingFrontmatter(raw, context);
4110
+ if (!("yamlSource" in split)) return { frontmatter: {}, body: split.body };
4052
4111
  let parsed;
4053
4112
  try {
4054
- parsed = (0, import_gray_matter.default)(raw, { engines: { yaml: yamlEngine } });
4113
+ parsed = yamlEngine.parse(split.yamlSource);
4055
4114
  } catch (err) {
4056
4115
  throw new MalformedDocumentError(context, err);
4057
4116
  }
4058
- const frontmatter = normalizeFrontmatter(parsed.data ?? {});
4059
- return { frontmatter, body: parsed.content };
4117
+ const frontmatter = normalizeFrontmatter(parsed);
4118
+ return { frontmatter, body: split.body };
4060
4119
  }
4061
4120
  function normalizeDocumentBodyForStorage(body) {
4062
4121
  return body.endsWith("\n") ? body : `${body}
@@ -4064,22 +4123,19 @@ function normalizeDocumentBodyForStorage(body) {
4064
4123
  }
4065
4124
  function stringifyWithData(data, body) {
4066
4125
  const engines2 = import_gray_matter.default.engines;
4067
- const yaml3 = engines2.yaml.stringify(data).trim();
4126
+ const yaml4 = engines2.yaml.stringify(data).trim();
4068
4127
  const content3 = body ?? "";
4069
4128
  const newline = (value) => value.endsWith("\n") ? value : `${value}
4070
4129
  `;
4071
- if (yaml3 === "{}") return normalizeDocumentBodyForStorage(content3);
4130
+ if (yaml4 === "{}") return normalizeDocumentBodyForStorage(content3);
4072
4131
  return `---
4073
- ${newline(yaml3)}---
4132
+ ${newline(yaml4)}---
4074
4133
  ${normalizeDocumentBodyForStorage(content3)}`;
4075
4134
  }
4076
4135
  function stringifyDoc(frontmatter, body) {
4077
4136
  return stringifyWithData(frontmatter, body);
4078
4137
  }
4079
- function isUsableTimestamp(value) {
4080
- return typeof value === "string" && value.trim() !== "";
4081
- }
4082
- var import_gray_matter, import_js_yaml, YAML_TIMESTAMP_TAG, yamlTimestampType, stringTimestampType, losslessDateSchema, yamlEngine, MalformedDocumentError;
4138
+ var import_gray_matter, import_js_yaml, YAML_TIMESTAMP_TAG, yamlTimestampType, stringTimestampType, losslessDateSchema, yamlEngine;
4083
4139
  var init_frontmatter = __esm({
4084
4140
  "../core/src/frontmatter.ts"() {
4085
4141
  "use strict";
@@ -4087,6 +4143,9 @@ var init_frontmatter = __esm({
4087
4143
  init_define_SUPERBEE_UPDATE_POLICY();
4088
4144
  import_gray_matter = __toESM(require_gray_matter(), 1);
4089
4145
  import_js_yaml = __toESM(require_js_yaml2(), 1);
4146
+ init_frontmatter_contract();
4147
+ init_frontmatter_splitter();
4148
+ init_frontmatter_contract();
4090
4149
  YAML_TIMESTAMP_TAG = "tag:yaml.org,2002:timestamp";
4091
4150
  yamlTimestampType = requireYamlTimestampType();
4092
4151
  stringTimestampType = new import_js_yaml.default.Type(YAML_TIMESTAMP_TAG, {
@@ -4103,22 +4162,6 @@ var init_frontmatter = __esm({
4103
4162
  return import_js_yaml.default.safeLoad(input, { schema: losslessDateSchema }) ?? {};
4104
4163
  }
4105
4164
  };
4106
- MalformedDocumentError = class extends Error {
4107
- name = "MalformedDocumentError";
4108
- /** The document id/path the malformed content belongs to (when the caller supplied one). */
4109
- context;
4110
- /** The underlying parser message, first line only — for compact per-doc reporting. */
4111
- detail;
4112
- constructor(context, cause) {
4113
- const detail = ((cause instanceof Error ? cause.message : String(cause)).split("\n")[0] ?? "").trim();
4114
- super(
4115
- `malformed frontmatter${context ? ` in '${context}'` : ""}: ${detail} \u2014 fix the YAML or remove the file`
4116
- );
4117
- if (context !== void 0) this.context = context;
4118
- this.detail = detail;
4119
- if (cause !== void 0) this.cause = cause;
4120
- }
4121
- };
4122
4165
  }
4123
4166
  });
4124
4167
 
@@ -5137,6 +5180,38 @@ var init_mutation_attribution = __esm({
5137
5180
  }
5138
5181
  });
5139
5182
 
5183
+ // ../core/src/version-transport.ts
5184
+ function stripETagWrapper(raw) {
5185
+ let value = raw.trim();
5186
+ if (value.startsWith("W/")) value = value.slice(2);
5187
+ if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) {
5188
+ value = value.slice(1, -1);
5189
+ }
5190
+ return value;
5191
+ }
5192
+ var VersionConflict;
5193
+ var init_version_transport = __esm({
5194
+ "../core/src/version-transport.ts"() {
5195
+ "use strict";
5196
+ init_define_SUPERBEE_BUILD_IDENTITY();
5197
+ init_define_SUPERBEE_UPDATE_POLICY();
5198
+ VersionConflict = class extends Error {
5199
+ name = "VersionConflict";
5200
+ id;
5201
+ expected;
5202
+ actual;
5203
+ constructor(id, expected, actual) {
5204
+ super(
5205
+ `version conflict on '${id}': expected ${expected ?? "absent"}, found ${actual ?? "none"} (the document changed since you read it \u2014 re-read and retry)`
5206
+ );
5207
+ this.id = id;
5208
+ this.expected = expected;
5209
+ this.actual = actual;
5210
+ }
5211
+ };
5212
+ }
5213
+ });
5214
+
5140
5215
  // ../core/src/versioning.ts
5141
5216
  import { createHash as createHash4 } from "node:crypto";
5142
5217
  function sha256Hex(input) {
@@ -5151,39 +5226,16 @@ function versionOfBytes(raw) {
5151
5226
  function blobVersion(bytes) {
5152
5227
  return `sha256:${createHash4("sha256").update(bytes).digest("hex")}`;
5153
5228
  }
5154
- function stripETagWrapper(raw) {
5155
- let v2 = raw.trim();
5156
- if (v2.startsWith("W/")) v2 = v2.slice(2);
5157
- if (v2.length >= 2 && v2.startsWith('"') && v2.endsWith('"')) v2 = v2.slice(1, -1);
5158
- return v2;
5159
- }
5160
5229
  function defaultActor() {
5161
5230
  return process.env.USER?.trim() || process.env.USERNAME?.trim() || process.env.LOGNAME?.trim() || "local";
5162
5231
  }
5163
- var VersionConflict;
5164
5232
  var init_versioning = __esm({
5165
5233
  "../core/src/versioning.ts"() {
5166
5234
  "use strict";
5167
5235
  init_define_SUPERBEE_BUILD_IDENTITY();
5168
5236
  init_define_SUPERBEE_UPDATE_POLICY();
5169
5237
  init_frontmatter();
5170
- VersionConflict = class extends Error {
5171
- name = "VersionConflict";
5172
- /** The concept id whose write was rejected. */
5173
- id;
5174
- /** The version the caller expected the backend to currently hold (`null` = expected absent). */
5175
- expected;
5176
- /** The version the backend actually holds (`null` if the document does not exist). */
5177
- actual;
5178
- constructor(id, expected, actual) {
5179
- super(
5180
- `version conflict on '${id}': expected ${expected ?? "absent"}, found ${actual ?? "none"} (the document changed since you read it \u2014 re-read and retry)`
5181
- );
5182
- this.id = id;
5183
- this.expected = expected;
5184
- this.actual = actual;
5185
- }
5186
- };
5238
+ init_version_transport();
5187
5239
  }
5188
5240
  });
5189
5241
 
@@ -5534,17 +5586,6 @@ var init_document_write_policy = __esm({
5534
5586
  }
5535
5587
  });
5536
5588
 
5537
- // ../core/src/index-marker.ts
5538
- var GENERATED_INDEX_MARKER;
5539
- var init_index_marker = __esm({
5540
- "../core/src/index-marker.ts"() {
5541
- "use strict";
5542
- init_define_SUPERBEE_BUILD_IDENTITY();
5543
- init_define_SUPERBEE_UPDATE_POLICY();
5544
- GENERATED_INDEX_MARKER = "<!-- agentstate-lite:generated-index:v1 -->";
5545
- }
5546
- });
5547
-
5548
5589
  // ../core/src/links.ts
5549
5590
  function normalizeSegments(segments) {
5550
5591
  const out = [];
@@ -5581,9 +5622,45 @@ function isExternalHref(href) {
5581
5622
  }
5582
5623
  function extractMarkdownLinks(body) {
5583
5624
  const out = [];
5584
- for (const m2 of body.matchAll(MD_LINK_RE)) {
5585
- if (typeof m2.index === "number" && m2.index > 0 && body[m2.index - 1] === "!") continue;
5586
- out.push({ text: m2[1] ?? "", href: m2[2] ?? "" });
5625
+ let textOpen = -1;
5626
+ let afterClose;
5627
+ let hrefFirst;
5628
+ let hrefRest;
5629
+ for (let cursor = 0; cursor < body.length; cursor++) {
5630
+ const char = body[cursor];
5631
+ if (hrefRest) {
5632
+ if (char === ")") {
5633
+ if (hrefRest.open === 0 || body[hrefRest.open - 1] !== "!") {
5634
+ out.push({
5635
+ text: body.slice(hrefRest.open + 1, hrefRest.close),
5636
+ href: body.slice(hrefRest.hrefStart, cursor)
5637
+ });
5638
+ }
5639
+ textOpen = -1;
5640
+ afterClose = void 0;
5641
+ hrefFirst = void 0;
5642
+ hrefRest = void 0;
5643
+ continue;
5644
+ }
5645
+ if (char.trim() === "") hrefRest = void 0;
5646
+ }
5647
+ if (hrefFirst) {
5648
+ if (char !== ")" && char.trim() !== "" && !hrefRest) {
5649
+ hrefRest = hrefFirst;
5650
+ }
5651
+ hrefFirst = void 0;
5652
+ }
5653
+ if (afterClose) {
5654
+ if (char === "(") {
5655
+ hrefFirst = { ...afterClose, hrefStart: cursor + 1 };
5656
+ }
5657
+ afterClose = void 0;
5658
+ }
5659
+ if (textOpen >= 0 && char === "]") {
5660
+ afterClose = { open: textOpen, close: cursor };
5661
+ textOpen = -1;
5662
+ }
5663
+ if (char === "[" && textOpen < 0) textOpen = cursor;
5587
5664
  }
5588
5665
  return out;
5589
5666
  }
@@ -5631,7 +5708,6 @@ function parseLinksFromDoc(doc2) {
5631
5708
  }
5632
5709
  return links;
5633
5710
  }
5634
- var MD_LINK_RE;
5635
5711
  var init_links = __esm({
5636
5712
  "../core/src/links.ts"() {
5637
5713
  "use strict";
@@ -5639,7 +5715,34 @@ var init_links = __esm({
5639
5715
  init_define_SUPERBEE_UPDATE_POLICY();
5640
5716
  init_paths();
5641
5717
  init_errors();
5642
- MD_LINK_RE = /\[([^\]]*)\]\(([^)\s]+)\)/g;
5718
+ }
5719
+ });
5720
+
5721
+ // ../core/src/portable-frontmatter.ts
5722
+ function parseLeadingFrontmatter(raw, context) {
5723
+ const split = splitLeadingFrontmatter(raw, context);
5724
+ if (!("yamlSource" in split)) return {};
5725
+ try {
5726
+ const parsed = import_js_yaml2.default.safeLoad(split.yamlSource);
5727
+ if (parsed === void 0 || parsed === null) return {};
5728
+ if (typeof parsed !== "object" || Array.isArray(parsed)) {
5729
+ throw new TypeError("YAML frontmatter must be a mapping");
5730
+ }
5731
+ return parsed;
5732
+ } catch (error51) {
5733
+ if (error51 instanceof MalformedDocumentError) throw error51;
5734
+ throw new MalformedDocumentError(context, error51);
5735
+ }
5736
+ }
5737
+ var import_js_yaml2;
5738
+ var init_portable_frontmatter = __esm({
5739
+ "../core/src/portable-frontmatter.ts"() {
5740
+ "use strict";
5741
+ init_define_SUPERBEE_BUILD_IDENTITY();
5742
+ init_define_SUPERBEE_UPDATE_POLICY();
5743
+ import_js_yaml2 = __toESM(require_js_yaml2(), 1);
5744
+ init_frontmatter_contract();
5745
+ init_frontmatter_splitter();
5643
5746
  }
5644
5747
  });
5645
5748
 
@@ -5669,47 +5772,13 @@ var init_query_filter = __esm({
5669
5772
  }
5670
5773
  });
5671
5774
 
5672
- // ../core/src/bundle.ts
5673
- import path4 from "node:path";
5674
- function backendFor(bundle) {
5675
- return bundle.backend ?? new FilesystemBackend(bundle.root);
5676
- }
5677
- async function readBundleOkfVersion(bundle) {
5678
- const index2 = await backendFor(bundle).readReserved("", "index.md");
5775
+ // ../core/src/engine.ts
5776
+ async function readBundleOkfVersion(backend) {
5777
+ const index2 = await backend.readReserved("", "index.md");
5679
5778
  if (!index2) return void 0;
5680
- const value = parseMarkdown(index2.content, "index.md").frontmatter.okf_version;
5779
+ const value = parseLeadingFrontmatter(index2.content, "index.md").okf_version;
5681
5780
  return typeof value === "string" && value.trim() !== "" ? value : void 0;
5682
5781
  }
5683
- function resolveOkfAuthoringVersion(requested) {
5684
- const version2 = requested ?? DEFAULT_OKF_AUTHORING_VERSION;
5685
- if (!SUPPORTED_OKF_AUTHORING_VERSIONS.includes(version2)) {
5686
- throw new InvalidInputError(
5687
- `Unsupported OKF authoring version '${version2}'. This build can author ${SUPPORTED_OKF_AUTHORING_VERSIONS.join(" and ")}; bundles declaring other versions can still be read or transported.`
5688
- );
5689
- }
5690
- return version2;
5691
- }
5692
- async function initBundle(root, options2 = {}) {
5693
- const okfVersion = resolveOkfAuthoringVersion(options2.okfVersion);
5694
- const resolved = path4.resolve(root);
5695
- const backend = new FilesystemBackend(resolved);
5696
- if (options2.expectNew || await backend.readReserved("", "index.md") === null) {
5697
- const name = path4.basename(resolved);
5698
- const body = `${GENERATED_INDEX_MARKER}
5699
- # ${name}
5700
-
5701
- An Open Knowledge Format bundle.
5702
- `;
5703
- try {
5704
- await backend.writeReserved("", "index.md", stringifyWithData({ okf_version: okfVersion }, body), {
5705
- expectedVersion: null
5706
- });
5707
- } catch (err) {
5708
- if (options2.expectNew || !(err instanceof VersionConflict)) throw err;
5709
- }
5710
- }
5711
- return { root: resolved };
5712
- }
5713
5782
  function assertWritableConceptDocument(doc2) {
5714
5783
  assertSafeConceptId(doc2.id);
5715
5784
  const rel = pathFromConceptId(doc2.id);
@@ -5726,16 +5795,7 @@ function assertWritableConceptDocument(doc2) {
5726
5795
  }
5727
5796
  return type;
5728
5797
  }
5729
- async function writeDocVersioned(bundle, doc2, options2) {
5730
- const type = assertWritableConceptDocument(doc2);
5731
- const okfVersion = await readBundleOkfVersion(bundle) ?? "0.1";
5732
- return persistDocForEdition(bundle, doc2, type, okfVersion, options2);
5733
- }
5734
- async function writeDocVersionedForEdition(bundle, doc2, okfVersion, options2) {
5735
- const type = assertWritableConceptDocument(doc2);
5736
- return persistDocForEdition(bundle, doc2, type, okfVersion, options2);
5737
- }
5738
- async function persistDocForEdition(bundle, doc2, type, okfVersion, options2) {
5798
+ async function persistDocForEdition(backend, doc2, type, okfVersion, options2) {
5739
5799
  let saved;
5740
5800
  if (okfVersion === "0.1") {
5741
5801
  const existingTimestamp = doc2.frontmatter.timestamp;
@@ -5744,43 +5804,49 @@ async function persistDocForEdition(bundle, doc2, type, okfVersion, options2) {
5744
5804
  } else {
5745
5805
  saved = normalizeV02DocumentForWrite(doc2, type);
5746
5806
  }
5747
- const version2 = await backendFor(bundle).write(doc2.id, saved, options2);
5807
+ const version2 = await backend.write(doc2.id, saved, options2);
5748
5808
  return { doc: saved, version: version2 };
5749
5809
  }
5750
- async function readDocVersioned(bundle, id) {
5751
- assertSafeConceptId(id);
5752
- const rel = pathFromConceptId(id);
5753
- if (isReservedFile(rel)) {
5754
- throw new InvalidInputError(`'${id}' is a reserved file (index.md / log.md), not a concept document.`);
5755
- }
5756
- return backendFor(bundle).read(id);
5810
+ async function writeDocVersioned(backend, doc2, options2) {
5811
+ const type = assertWritableConceptDocument(doc2);
5812
+ const okfVersion = await readBundleOkfVersion(backend) ?? "0.1";
5813
+ return persistDocForEdition(backend, doc2, type, okfVersion, options2);
5757
5814
  }
5758
- async function readDoc(bundle, id) {
5759
- return (await readDocVersioned(bundle, id)).doc;
5815
+ async function writeDocVersionedForEdition(backend, doc2, okfVersion, options2) {
5816
+ return persistDocForEdition(backend, doc2, assertWritableConceptDocument(doc2), okfVersion, options2);
5760
5817
  }
5761
- async function existsDoc(bundle, id) {
5818
+ function assertReadableConceptId(id) {
5762
5819
  assertSafeConceptId(id);
5763
5820
  const rel = pathFromConceptId(id);
5764
5821
  if (isReservedFile(rel)) {
5765
5822
  throw new InvalidInputError(`'${id}' is a reserved file (index.md / log.md), not a concept document.`);
5766
5823
  }
5767
- return backendFor(bundle).exists(id);
5768
5824
  }
5769
- async function docVersions(bundle, id) {
5770
- assertSafeConceptId(id);
5771
- const rel = pathFromConceptId(id);
5772
- if (isReservedFile(rel)) {
5773
- throw new InvalidInputError(`'${id}' is a reserved file (index.md / log.md), not a concept document.`);
5774
- }
5775
- return backendFor(bundle).versions(id);
5825
+ async function readDocVersioned(backend, id) {
5826
+ assertReadableConceptId(id);
5827
+ return backend.read(id);
5828
+ }
5829
+ async function readDoc(backend, id) {
5830
+ return (await readDocVersioned(backend, id)).doc;
5831
+ }
5832
+ async function existsDoc(backend, id) {
5833
+ assertReadableConceptId(id);
5834
+ return backend.exists(id);
5835
+ }
5836
+ async function docVersions(backend, id) {
5837
+ assertReadableConceptId(id);
5838
+ return backend.versions(id);
5776
5839
  }
5777
- async function deleteDoc(bundle, id, options2) {
5840
+ async function deleteDoc(backend, id, options2) {
5778
5841
  assertSafeConceptId(id);
5779
5842
  const rel = pathFromConceptId(id);
5780
5843
  if (isReservedFile(rel)) {
5781
5844
  throw new InvalidInputError(`'${id}' is a reserved file (${rel}); reserved files cannot be deleted.`);
5782
5845
  }
5783
- return backendFor(bundle).delete(id, options2);
5846
+ return backend.delete(id, options2);
5847
+ }
5848
+ function isEnoent(err) {
5849
+ return typeof err === "object" && err !== null && err.code === "ENOENT";
5784
5850
  }
5785
5851
  async function readManyExisting(backend, ids, onMalformed) {
5786
5852
  try {
@@ -5792,13 +5858,13 @@ async function readManyExisting(backend, ids, onMalformed) {
5792
5858
  for (const id of ids) {
5793
5859
  try {
5794
5860
  out.push(await backend.read(id));
5795
- } catch (e) {
5796
- if (isEnoent(e)) continue;
5797
- if (e instanceof MalformedDocumentError && onMalformed) {
5798
- onMalformed({ id, reason: e.detail });
5861
+ } catch (candidate) {
5862
+ if (isEnoent(candidate)) continue;
5863
+ if (candidate instanceof MalformedDocumentError && onMalformed) {
5864
+ onMalformed({ id, reason: candidate.detail });
5799
5865
  continue;
5800
5866
  }
5801
- throw e;
5867
+ throw candidate;
5802
5868
  }
5803
5869
  }
5804
5870
  return out;
@@ -5808,27 +5874,27 @@ async function scanMatching(backend, filter, onSkip) {
5808
5874
  const ids = await backend.list(filter.prefix);
5809
5875
  const results = [];
5810
5876
  for (const result3 of await readManyExisting(backend, ids, onSkip)) {
5811
- if (!matchesFilter(result3.doc, filter)) continue;
5812
- results.push(result3);
5877
+ if (matchesFilter(result3.doc, filter)) results.push(result3);
5813
5878
  }
5814
5879
  results.sort((a, b) => a.doc.id.localeCompare(b.doc.id));
5815
5880
  return results;
5816
5881
  }
5817
- async function query(bundle, filter = {}, options2 = {}) {
5818
- const scanned = await scanMatching(backendFor(bundle), filter, options2.onSkip);
5819
- return scanned.map((r2) => r2.doc);
5882
+ async function query(backend, filter = {}, options2 = {}) {
5883
+ return (await scanMatching(backend, filter, options2.onSkip)).map((result3) => result3.doc);
5820
5884
  }
5821
- async function queryHeads(bundle, filter = {}, options2 = {}) {
5822
- const backend = backendFor(bundle);
5885
+ async function queryHeads(backend, filter = {}, options2 = {}) {
5823
5886
  if (backend.queryHeads) {
5824
- const rows = (await backend.queryHeads(filter)).filter((r2) => matchesFilter(r2, filter));
5887
+ const rows = (await backend.queryHeads(filter)).filter((row2) => matchesFilter(row2, filter));
5825
5888
  rows.sort((a, b) => a.id.localeCompare(b.id));
5826
5889
  return rows;
5827
5890
  }
5828
- const scanned = await scanMatching(backend, filter, options2.onSkip);
5829
- return scanned.map(({ doc: doc2, version: version2 }) => ({ id: doc2.id, frontmatter: doc2.frontmatter, version: version2 }));
5891
+ return (await scanMatching(backend, filter, options2.onSkip)).map(({ doc: doc2, version: version2 }) => ({
5892
+ id: doc2.id,
5893
+ frontmatter: doc2.frontmatter,
5894
+ version: version2
5895
+ }));
5830
5896
  }
5831
- function parseLinks(_bundle, doc2) {
5897
+ function parseLinks(doc2) {
5832
5898
  return parseLinksFromDoc(doc2);
5833
5899
  }
5834
5900
  function normalizeEdgeSelector(raw) {
@@ -5842,25 +5908,19 @@ function normalizeEdgeSelector(raw) {
5842
5908
  }
5843
5909
  function matchesEdgeSelector(value, selectors) {
5844
5910
  if (selectors === void 0) return true;
5845
- for (const normalized of selectors) {
5846
- if (normalized.endsWith("/")) {
5847
- if (value.startsWith(normalized)) return true;
5848
- } else if (value === normalized) {
5849
- return true;
5850
- }
5851
- }
5852
- return false;
5911
+ return selectors.some(
5912
+ (selector2) => selector2.endsWith("/") ? value.startsWith(selector2) : value === selector2
5913
+ );
5853
5914
  }
5854
- function toSelectorList(v2) {
5855
- if (v2 === void 0) return void 0;
5856
- return Array.isArray(v2) ? v2 : [v2];
5915
+ function toSelectorList(value) {
5916
+ if (value === void 0) return void 0;
5917
+ return Array.isArray(value) ? value : [value];
5857
5918
  }
5858
- async function queryEdges(bundle, filter = {}) {
5919
+ async function queryEdges(backend, filter = {}) {
5859
5920
  const fromSelectors = toSelectorList(filter.from)?.map(normalizeEdgeSelector);
5860
5921
  const toSelectors = toSelectorList(filter.to)?.map(normalizeEdgeSelector);
5861
- const docs = await query(bundle);
5862
5922
  const edges = [];
5863
- for (const doc2 of docs) {
5923
+ for (const doc2 of await query(backend)) {
5864
5924
  for (const link3 of parseLinksFromDoc(doc2)) {
5865
5925
  if (!matchesEdgeSelector(link3.from, fromSelectors)) continue;
5866
5926
  if (!matchesEdgeSelector(link3.to, toSelectors)) continue;
@@ -5871,40 +5931,145 @@ async function queryEdges(bundle, filter = {}) {
5871
5931
  edges.sort((a, b) => a.from.localeCompare(b.from) || a.to.localeCompare(b.to) || a.text.localeCompare(b.text));
5872
5932
  return edges;
5873
5933
  }
5874
- async function backlinks(bundle, target) {
5934
+ async function backlinks(backend, target) {
5875
5935
  if (target.endsWith("/")) return [];
5876
- return queryEdges(bundle, { to: target });
5936
+ return queryEdges(backend, { to: target });
5937
+ }
5938
+ async function readBlob(backend, key) {
5939
+ return backend.readBlob(key);
5940
+ }
5941
+ async function writeBlob(backend, key, bytes, contentType, options2) {
5942
+ return backend.writeBlob(key, bytes, contentType, options2);
5943
+ }
5944
+ async function listBlobs(backend, prefix) {
5945
+ return backend.listBlobs(prefix);
5946
+ }
5947
+ async function deleteBlob(backend, key, options2) {
5948
+ return backend.deleteBlob(key, options2);
5949
+ }
5950
+ var init_engine = __esm({
5951
+ "../core/src/engine.ts"() {
5952
+ "use strict";
5953
+ init_define_SUPERBEE_BUILD_IDENTITY();
5954
+ init_define_SUPERBEE_UPDATE_POLICY();
5955
+ init_document_write_policy();
5956
+ init_errors();
5957
+ init_frontmatter_contract();
5958
+ init_links();
5959
+ init_paths();
5960
+ init_portable_frontmatter();
5961
+ init_query_filter();
5962
+ }
5963
+ });
5964
+
5965
+ // ../core/src/index-marker.ts
5966
+ var GENERATED_INDEX_MARKER;
5967
+ var init_index_marker = __esm({
5968
+ "../core/src/index-marker.ts"() {
5969
+ "use strict";
5970
+ init_define_SUPERBEE_BUILD_IDENTITY();
5971
+ init_define_SUPERBEE_UPDATE_POLICY();
5972
+ GENERATED_INDEX_MARKER = "<!-- agentstate-lite:generated-index:v1 -->";
5973
+ }
5974
+ });
5975
+
5976
+ // ../core/src/bundle.ts
5977
+ import path4 from "node:path";
5978
+ function backendFor(bundle) {
5979
+ return bundle.backend ?? new FilesystemBackend(bundle.root);
5980
+ }
5981
+ async function readBundleOkfVersion2(bundle) {
5982
+ return readBundleOkfVersion(backendFor(bundle));
5983
+ }
5984
+ function resolveOkfAuthoringVersion(requested) {
5985
+ const version2 = requested ?? DEFAULT_OKF_AUTHORING_VERSION;
5986
+ if (!SUPPORTED_OKF_AUTHORING_VERSIONS.includes(version2)) {
5987
+ throw new InvalidInputError(
5988
+ `Unsupported OKF authoring version '${version2}'. This build can author ${SUPPORTED_OKF_AUTHORING_VERSIONS.join(" and ")}; bundles declaring other versions can still be read or transported.`
5989
+ );
5990
+ }
5991
+ return version2;
5992
+ }
5993
+ async function initBundle(root, options2 = {}) {
5994
+ const okfVersion = resolveOkfAuthoringVersion(options2.okfVersion);
5995
+ const resolved = path4.resolve(root);
5996
+ const backend = new FilesystemBackend(resolved);
5997
+ if (options2.expectNew || await backend.readReserved("", "index.md") === null) {
5998
+ const name = path4.basename(resolved);
5999
+ const body = `${GENERATED_INDEX_MARKER}
6000
+ # ${name}
6001
+
6002
+ An Open Knowledge Format bundle.
6003
+ `;
6004
+ try {
6005
+ await backend.writeReserved("", "index.md", stringifyWithData({ okf_version: okfVersion }, body), {
6006
+ expectedVersion: null
6007
+ });
6008
+ } catch (err) {
6009
+ if (options2.expectNew || !(err instanceof VersionConflict)) throw err;
6010
+ }
6011
+ }
6012
+ return { root: resolved };
6013
+ }
6014
+ async function writeDocVersionedForEdition2(bundle, doc2, okfVersion, options2) {
6015
+ return writeDocVersionedForEdition(backendFor(bundle), doc2, okfVersion, options2);
6016
+ }
6017
+ async function readDocVersioned2(bundle, id) {
6018
+ return readDocVersioned(backendFor(bundle), id);
6019
+ }
6020
+ async function readDoc2(bundle, id) {
6021
+ return readDoc(backendFor(bundle), id);
6022
+ }
6023
+ async function existsDoc2(bundle, id) {
6024
+ return existsDoc(backendFor(bundle), id);
6025
+ }
6026
+ async function docVersions2(bundle, id) {
6027
+ return docVersions(backendFor(bundle), id);
5877
6028
  }
5878
- async function readBlob(bundle, key) {
5879
- return backendFor(bundle).readBlob(key);
6029
+ async function deleteDoc2(bundle, id, options2) {
6030
+ return deleteDoc(backendFor(bundle), id, options2);
5880
6031
  }
5881
- async function writeBlob(bundle, key, bytes, contentType, options2) {
5882
- return backendFor(bundle).writeBlob(key, bytes, contentType, options2);
6032
+ async function query2(bundle, filter = {}, options2 = {}) {
6033
+ return query(backendFor(bundle), filter, options2);
5883
6034
  }
5884
- async function listBlobs(bundle, prefix) {
5885
- return backendFor(bundle).listBlobs(prefix);
6035
+ async function queryHeads2(bundle, filter = {}, options2 = {}) {
6036
+ return queryHeads(backendFor(bundle), filter, options2);
5886
6037
  }
5887
- async function deleteBlob(bundle, key, options2) {
5888
- return backendFor(bundle).deleteBlob(key, options2);
6038
+ function parseLinks2(_bundle, doc2) {
6039
+ return parseLinks(doc2);
5889
6040
  }
5890
- var SUPPORTED_OKF_AUTHORING_VERSIONS, DEFAULT_OKF_AUTHORING_VERSION, isEnoent;
6041
+ async function queryEdges2(bundle, filter = {}) {
6042
+ return queryEdges(backendFor(bundle), filter);
6043
+ }
6044
+ async function backlinks2(bundle, target) {
6045
+ return backlinks(backendFor(bundle), target);
6046
+ }
6047
+ async function readBlob2(bundle, key) {
6048
+ return readBlob(backendFor(bundle), key);
6049
+ }
6050
+ async function writeBlob2(bundle, key, bytes, contentType, options2) {
6051
+ return writeBlob(backendFor(bundle), key, bytes, contentType, options2);
6052
+ }
6053
+ async function listBlobs2(bundle, prefix) {
6054
+ return listBlobs(backendFor(bundle), prefix);
6055
+ }
6056
+ async function deleteBlob2(bundle, key, options2) {
6057
+ return deleteBlob(backendFor(bundle), key, options2);
6058
+ }
6059
+ var SUPPORTED_OKF_AUTHORING_VERSIONS, DEFAULT_OKF_AUTHORING_VERSION;
5891
6060
  var init_bundle = __esm({
5892
6061
  "../core/src/bundle.ts"() {
5893
6062
  "use strict";
5894
6063
  init_define_SUPERBEE_BUILD_IDENTITY();
5895
6064
  init_define_SUPERBEE_UPDATE_POLICY();
5896
6065
  init_backend();
5897
- init_document_write_policy();
6066
+ init_engine();
6067
+ init_errors();
5898
6068
  init_frontmatter();
5899
6069
  init_index_marker();
5900
- init_links();
5901
- init_paths();
5902
- init_errors();
5903
- init_query_filter();
5904
6070
  init_versioning();
5905
6071
  SUPPORTED_OKF_AUTHORING_VERSIONS = ["0.1", "0.2"];
5906
6072
  DEFAULT_OKF_AUTHORING_VERSION = "0.2";
5907
- isEnoent = (err) => err?.code === "ENOENT";
5908
6073
  }
5909
6074
  });
5910
6075
 
@@ -6176,6 +6341,11 @@ function retryDelayMs(attempt) {
6176
6341
  function delay2(ms) {
6177
6342
  return new Promise((resolve2) => setTimeout(resolve2, ms));
6178
6343
  }
6344
+ function trimTrailingSlashes(value) {
6345
+ let end = value.length;
6346
+ while (end > 0 && value[end - 1] === "/") end -= 1;
6347
+ return value.slice(0, end);
6348
+ }
6179
6349
  function encodeId(id) {
6180
6350
  return id.split("/").map((seg) => encodeURIComponent(seg)).join("/");
6181
6351
  }
@@ -6191,7 +6361,7 @@ var init_remote_backend = __esm({
6191
6361
  init_content_type();
6192
6362
  init_errors();
6193
6363
  init_paths();
6194
- init_versioning();
6364
+ init_version_transport();
6195
6365
  RemoteError = class extends Error {
6196
6366
  /** The envelope's `code` field, or a status-derived guess when the envelope is missing/unparseable. */
6197
6367
  code;
@@ -6215,7 +6385,7 @@ var init_remote_backend = __esm({
6215
6385
  authToken;
6216
6386
  maxRetries;
6217
6387
  constructor(options2) {
6218
- this.baseUrl = options2.baseUrl.replace(/\/+$/, "");
6388
+ this.baseUrl = trimTrailingSlashes(options2.baseUrl);
6219
6389
  this.bundle = options2.bundle;
6220
6390
  this.fetchImpl = options2.fetchImpl ?? ((request) => globalThis.fetch(request));
6221
6391
  this.authToken = options2.authToken;
@@ -7376,7 +7546,7 @@ var init_kinds = __esm({
7376
7546
  ["owner_field", "ownerField"],
7377
7547
  ["state_field", "stateField"]
7378
7548
  ];
7379
- H1_RE = /^#\s+(.+?)\s*$/gm;
7549
+ H1_RE = /^#\s+(\S.*)$/gm;
7380
7550
  HORIZON_RE = /^(\d+)(m|h|d)$/;
7381
7551
  HORIZON_UNIT_MS = { m: 6e4, h: 36e5, d: 864e5 };
7382
7552
  }
@@ -7493,7 +7663,7 @@ async function mutateDocument(opts) {
7493
7663
  const compareTimestamp = opts.compareTimestamp ?? false;
7494
7664
  const persistActor = opts.persistActor ?? false;
7495
7665
  const seedClock = opts.seedGenerationClock ?? true;
7496
- const okfVersion = await readBundleOkfVersion(opts.bundle) ?? "0.1";
7666
+ const okfVersion = await readBundleOkfVersion2(opts.bundle) ?? "0.1";
7497
7667
  if (okfVersion !== "0.1" && okfVersion !== "0.2") {
7498
7668
  throw new InvalidInputError(
7499
7669
  `Unsupported OKF mutation version '${okfVersion}'. This build can mutate 0.1 and 0.2 bundles.`
@@ -7517,7 +7687,7 @@ async function mutateDocument(opts) {
7517
7687
  );
7518
7688
  const candidate = withV02Metadata(attributed, void 0, okfVersion, opts.registry, decisionNow, seedClock);
7519
7689
  const { warnings } = validateCandidate(opts.id, candidate, opts.registry, opts.strict, okfVersion, decisionNow);
7520
- const { doc: doc2, version: version2 } = await writeDocVersionedForEdition(opts.bundle, { id: opts.id, ...candidate }, okfVersion, {
7690
+ const { doc: doc2, version: version2 } = await writeDocVersionedForEdition2(opts.bundle, { id: opts.id, ...candidate }, okfVersion, {
7521
7691
  expectedVersion: null,
7522
7692
  actor: opts.actor
7523
7693
  });
@@ -7526,7 +7696,7 @@ async function mutateDocument(opts) {
7526
7696
  let lastReadVersion = null;
7527
7697
  const readExisting = async () => {
7528
7698
  try {
7529
- const { doc: doc2, version: version2 } = await readDocVersioned(opts.bundle, opts.id);
7699
+ const { doc: doc2, version: version2 } = await readDocVersioned2(opts.bundle, opts.id);
7530
7700
  lastReadVersion = version2;
7531
7701
  return { state: doc2, version: version2 };
7532
7702
  } catch (error51) {
@@ -7578,7 +7748,7 @@ async function mutateDocument(opts) {
7578
7748
  return { action: "write", next: { id: opts.id, ...candidate }, result: {} };
7579
7749
  },
7580
7750
  write: async (next, expectedVersion) => {
7581
- const written = await writeDocVersionedForEdition(opts.bundle, next, okfVersion, {
7751
+ const written = await writeDocVersionedForEdition2(opts.bundle, next, okfVersion, {
7582
7752
  expectedVersion,
7583
7753
  actor: opts.actor
7584
7754
  });
@@ -7634,7 +7804,7 @@ async function mutateDocument(opts) {
7634
7804
  return { action: "write", next: { id: opts.id, ...candidate }, result: { warnings } };
7635
7805
  },
7636
7806
  write: async (next, expectedVersion) => {
7637
- const written = await writeDocVersionedForEdition(opts.bundle, next, okfVersion, {
7807
+ const written = await writeDocVersionedForEdition2(opts.bundle, next, okfVersion, {
7638
7808
  expectedVersion: hardCas ? opts.expectedVersion : expectedVersion,
7639
7809
  actor: opts.actor
7640
7810
  });
@@ -7963,7 +8133,7 @@ var init_index_projection = __esm({
7963
8133
  // ../core/src/kinds-load.ts
7964
8134
  async function loadKinds(bundle) {
7965
8135
  const warnings = [];
7966
- const docs = await query(bundle, { prefix: CONVENTIONS_PREFIX, type: CONVENTION_TYPE }, {
8136
+ const docs = await query2(bundle, { prefix: CONVENTIONS_PREFIX, type: CONVENTION_TYPE }, {
7967
8137
  onSkip: ({ id, reason }) => warnings.push({
7968
8138
  code: "KIND_CONVENTION_MALFORMED",
7969
8139
  message: `skipped kind convention '${id}' with unparseable frontmatter: ${reason}`,
@@ -8027,6 +8197,34 @@ function firstGitLine(f2) {
8027
8197
  const line2 = f2.stderr.split("\n").find((l) => l.trim().length > 0) ?? f2.stdout.split("\n").find((l) => l.trim().length > 0) ?? "";
8028
8198
  return line2.trim();
8029
8199
  }
8200
+ function hasRejectedReason(text4, reasons) {
8201
+ for (const line2 of text4.split("\n")) {
8202
+ const lower = line2.toLowerCase();
8203
+ const marker = lower.indexOf("[rejected]");
8204
+ if (marker === -1) continue;
8205
+ if (reasons.some((reason) => lower.indexOf(`(${reason.toLowerCase()})`, marker) !== -1)) return true;
8206
+ }
8207
+ return false;
8208
+ }
8209
+ function hasUnmergeableOriginRef(text4) {
8210
+ const suffix = " - not something we can merge";
8211
+ for (const line2 of text4.split("\n")) {
8212
+ const lower = line2.toLowerCase();
8213
+ const at = lower.indexOf(suffix);
8214
+ if (at <= 0) continue;
8215
+ const ref = lower.slice(0, at);
8216
+ let runStart = 0;
8217
+ for (let i = ref.length - 1; i >= 0; i -= 1) {
8218
+ if (/\s/.test(ref[i])) {
8219
+ runStart = i + 1;
8220
+ break;
8221
+ }
8222
+ }
8223
+ const start = ref.indexOf("origin/", runStart);
8224
+ if (start !== -1 && ref.length - start > "origin/".length) return true;
8225
+ }
8226
+ return false;
8227
+ }
8030
8228
  function classifyGitError(f2) {
8031
8229
  const op = f2.args[0] ?? "git";
8032
8230
  const text4 = `${f2.stderr}
@@ -8049,14 +8247,14 @@ ${f2.stdout}`;
8049
8247
  { details: { op, retryable: true } }
8050
8248
  );
8051
8249
  }
8052
- if (op === "push" && (/\[rejected\].*\((?:fetch first|non-fast-forward)\)/i.test(text4) || /Updates were rejected because (?:the remote contains work|the tip of your current branch is behind)/i.test(text4))) {
8250
+ if (op === "push" && (hasRejectedReason(text4, ["fetch first", "non-fast-forward"]) || /Updates were rejected because (?:the remote contains work|the tip of your current branch is behind)/i.test(text4))) {
8053
8251
  return new BoardGitError(
8054
8252
  "TRANSIENT",
8055
8253
  "a teammate pushed to the board at the same time \u2014 re-run sync to incorporate their changes and retry",
8056
8254
  { details: { op, retryable: true, reason: "non-fast-forward" } }
8057
8255
  );
8058
8256
  }
8059
- if (/'origin' does not appear to be a git repository/i.test(text4) || /No such remote:? '?origin'?/i.test(text4) || /invalid upstream ['"]?origin\//i.test(text4) || /origin\/[^\s]+ - not something we can merge/i.test(text4) || /couldn'?t find remote ref/i.test(text4) || /src refspec [^\s]+ does not match any/i.test(text4)) {
8257
+ if (/'origin' does not appear to be a git repository/i.test(text4) || /No such remote:? '?origin'?/i.test(text4) || /invalid upstream ['"]?origin\//i.test(text4) || hasUnmergeableOriginRef(text4) || /couldn'?t find remote ref/i.test(text4) || /src refspec [^\s]+ does not match any/i.test(text4)) {
8060
8258
  return new BoardGitError(
8061
8259
  "NO_UPSTREAM",
8062
8260
  "the board branch isn't linked to a remote yet \u2014 sync can't share it",
@@ -8122,6 +8320,18 @@ var init_errors2 = __esm({
8122
8320
  }
8123
8321
  });
8124
8322
 
8323
+ // ../board-git/src/git-path.ts
8324
+ function normalizeGitLexicalPath(gitPath, dialect) {
8325
+ return dialect.normalize(gitPath);
8326
+ }
8327
+ var init_git_path = __esm({
8328
+ "../board-git/src/git-path.ts"() {
8329
+ "use strict";
8330
+ init_define_SUPERBEE_BUILD_IDENTITY();
8331
+ init_define_SUPERBEE_UPDATE_POLICY();
8332
+ }
8333
+ });
8334
+
8125
8335
  // ../board-git/src/porcelain.ts
8126
8336
  import { spawnSync } from "node:child_process";
8127
8337
  import {
@@ -8253,7 +8463,12 @@ function mustGit(dir, args, opts = {}) {
8253
8463
  return r2.stdout;
8254
8464
  }
8255
8465
  function slugifyActor(actor) {
8256
- const slug = actor.toLowerCase().replace(/[^a-z0-9.-]+/g, "-").replace(/^-+|-+$/g, "");
8466
+ const collapsed = actor.toLowerCase().replace(/[^a-z0-9.-]+/g, "-");
8467
+ let start = 0;
8468
+ let end = collapsed.length;
8469
+ while (start < end && collapsed[start] === "-") start += 1;
8470
+ while (end > start && collapsed[end - 1] === "-") end -= 1;
8471
+ const slug = collapsed.slice(start, end);
8257
8472
  return slug.length > 0 ? slug : IDENTITY_FALLBACK_ACTOR;
8258
8473
  }
8259
8474
  function hasResolvableIdentity(dir) {
@@ -8287,7 +8502,7 @@ function probeRepoTopLevel(dir) {
8287
8502
  };
8288
8503
  }
8289
8504
  const top = r2.stdout.trim();
8290
- return top.length > 0 ? { kind: "repo", top } : { kind: "unavailable", reason: "git repository discovery returned an empty top level" };
8505
+ return top.length > 0 ? { kind: "repo", top: normalizeGitLexicalPath(top, path5) } : { kind: "unavailable", reason: "git repository discovery returned an empty top level" };
8291
8506
  }
8292
8507
  function repoTopLevel(dir) {
8293
8508
  const result3 = probeRepoTopLevel(dir);
@@ -9179,6 +9394,7 @@ var init_porcelain = __esm({
9179
9394
  init_define_SUPERBEE_UPDATE_POLICY();
9180
9395
  init_src();
9181
9396
  init_errors2();
9397
+ init_git_path();
9182
9398
  BOARD_BRANCH = "board";
9183
9399
  BOARD_REMOTE = "origin";
9184
9400
  BOARD_REF = `${BOARD_REMOTE}/${BOARD_BRANCH}`;
@@ -9530,13 +9746,25 @@ var init_diff = __esm({
9530
9746
  import { readFile } from "node:fs/promises";
9531
9747
  import { createHash as createHash5 } from "node:crypto";
9532
9748
  import { basename, join as join3, resolve } from "node:path";
9749
+ function trimTrailing(value, char) {
9750
+ let end = value.length;
9751
+ while (end > 0 && value[end - 1] === char) end -= 1;
9752
+ return value.slice(0, end);
9753
+ }
9754
+ function trimLeading(value, char) {
9755
+ let start = 0;
9756
+ while (start < value.length && value[start] === char) start += 1;
9757
+ return value.slice(start);
9758
+ }
9533
9759
  function normalizeRemoteUrl(url2) {
9534
- let u2 = url2.trim().replace(/\/+$/, "");
9760
+ let u2 = trimTrailing(url2.trim(), "/");
9535
9761
  if (u2.endsWith(".git")) u2 = u2.slice(0, -".git".length);
9536
9762
  return u2;
9537
9763
  }
9538
9764
  function normalizeSubpath(subpath) {
9539
- return subpath.trim().replace(/^\.\//, "").replace(/^\/+/, "").replace(/\/+$/, "");
9765
+ const trimmed = subpath.trim();
9766
+ const relative2 = trimmed.startsWith("./") ? trimmed.slice(2) : trimmed;
9767
+ return trimTrailing(trimLeading(relative2, "/"), "/");
9540
9768
  }
9541
9769
  function bundleKey(src) {
9542
9770
  if ("remoteUrl" in src) {
@@ -9878,7 +10106,7 @@ function provisionAnnouncement(outcome) {
9878
10106
  }
9879
10107
  return Object.keys(announcement).length > 0 ? announcement : void 0;
9880
10108
  }
9881
- var init_engine = __esm({
10109
+ var init_engine2 = __esm({
9882
10110
  "../board-git/src/engine.ts"() {
9883
10111
  "use strict";
9884
10112
  init_define_SUPERBEE_BUILD_IDENTITY();
@@ -10007,7 +10235,7 @@ var init_autopull = __esm({
10007
10235
  init_define_SUPERBEE_UPDATE_POLICY();
10008
10236
  init_porcelain();
10009
10237
  init_diff();
10010
- init_engine();
10238
+ init_engine2();
10011
10239
  AUTO_PULL_STALE_MS = 5 * 6e4;
10012
10240
  AUTO_PULL_BUDGET_MS = 2e3;
10013
10241
  AUTO_PULL_CONNECT_TIMEOUT_SECONDS = 2;
@@ -10131,7 +10359,7 @@ var init_intree = __esm({
10131
10359
  init_porcelain();
10132
10360
  init_diff();
10133
10361
  init_errors2();
10134
- init_engine();
10362
+ init_engine2();
10135
10363
  IN_TREE_CURSOR_TIER = "git-intree";
10136
10364
  }
10137
10365
  });
@@ -10147,7 +10375,7 @@ var init_src2 = __esm({
10147
10375
  init_channel();
10148
10376
  init_diff();
10149
10377
  init_cursor();
10150
- init_engine();
10378
+ init_engine2();
10151
10379
  init_flow();
10152
10380
  init_autopull();
10153
10381
  init_intree();
@@ -10583,15 +10811,8 @@ async function inspectUserStateMarker(root, input) {
10583
10811
  async function hasExactUserStateMarker(root, input) {
10584
10812
  return (await inspectUserStateMarker(root, input)).recognized;
10585
10813
  }
10586
- async function writeFileAtomic0600(dir, fileName2, content3, options2 = {}, input) {
10814
+ async function publishFileAtomic0600(dir, fileName2, content3, options2 = {}, input) {
10587
10815
  const policy = resolveUserStatePolicy(input);
10588
- try {
10589
- await mkdir(dir, { recursive: true, mode: DIR_MODE });
10590
- } catch (error51) {
10591
- if (errno(error51) !== "EEXIST") throw error51;
10592
- }
10593
- await assertRealDirectory(dir);
10594
- if (policy.containment === "posix-owner-mode") await chmod(dir, DIR_MODE);
10595
10816
  const file2 = join4(dir, fileName2);
10596
10817
  const temporary = join4(dir, `.${fileName2}.${randomBytes(8).toString("hex")}.tmp`);
10597
10818
  const handle = await open(temporary, "wx", FILE_MODE);
@@ -10613,6 +10834,17 @@ async function writeFileAtomic0600(dir, fileName2, content3, options2 = {}, inpu
10613
10834
  throw error51;
10614
10835
  }
10615
10836
  }
10837
+ async function writeFileAtomic0600(dir, fileName2, content3, options2 = {}, input) {
10838
+ const policy = resolveUserStatePolicy(input);
10839
+ try {
10840
+ await mkdir(dir, { recursive: true, mode: DIR_MODE });
10841
+ } catch (error51) {
10842
+ if (errno(error51) !== "EEXIST") throw error51;
10843
+ }
10844
+ await assertRealDirectory(dir);
10845
+ if (policy.containment === "posix-owner-mode") await chmod(dir, DIR_MODE);
10846
+ await publishFileAtomic0600(dir, fileName2, content3, options2, input);
10847
+ }
10616
10848
  async function ensureStateRootGitignore(root, input) {
10617
10849
  try {
10618
10850
  if (await readPrivateStateFile(join4(root, STATE_ROOT_GITIGNORE_FILE_NAME), 64, void 0, input) === STATE_ROOT_GITIGNORE_BYTES) return;
@@ -10623,10 +10855,7 @@ async function ensureStateRootGitignore(root, input) {
10623
10855
  } catch {
10624
10856
  }
10625
10857
  }
10626
- async function initializeCanonicalRoot(root, input) {
10627
- const policy = resolveUserStatePolicy(input);
10628
- const parent = dirname3(root);
10629
- await ensureParentDirectory(parent);
10858
+ async function publishCanonicalRoot(root, input, hooks) {
10630
10859
  let created = false;
10631
10860
  try {
10632
10861
  await mkdir(root, { mode: DIR_MODE });
@@ -10637,6 +10866,7 @@ async function initializeCanonicalRoot(root, input) {
10637
10866
  await assertRealDirectory(root);
10638
10867
  if (created) {
10639
10868
  try {
10869
+ await hooks.beforeMarkerPublication?.();
10640
10870
  await writeFileAtomic0600(root, USER_STATE_MARKER_FILE_NAME, USER_STATE_MARKER_BYTES, {}, input);
10641
10871
  } catch (error51) {
10642
10872
  await rmdir(root).catch(() => {
@@ -10644,11 +10874,17 @@ async function initializeCanonicalRoot(root, input) {
10644
10874
  throw error51;
10645
10875
  }
10646
10876
  }
10647
- if (!created) {
10648
- for (let attempt = 0; attempt < 50 && !await hasExactUserStateMarker(root, input); attempt += 1) {
10649
- await new Promise((resolve2) => setTimeout(resolve2, 5));
10650
- }
10877
+ const marker = await inspectUserStateMarker(root, input);
10878
+ if (!marker.recognized) {
10879
+ throw new Error("canonical Superbee user-state root is not owned by this product");
10651
10880
  }
10881
+ }
10882
+ async function initializeCanonicalRoot(root, input, hooks = {}) {
10883
+ const policy = resolveUserStatePolicy(input);
10884
+ const parent = dirname3(root);
10885
+ await ensureParentDirectory(parent);
10886
+ const lockOptions = hooks.lockRoot === void 0 ? { portableRoot: root } : { portableRoot: root, lockRoot: hooks.lockRoot };
10887
+ await withFilesystemMutationLock(root, () => publishCanonicalRoot(root, input, hooks), lockOptions);
10652
10888
  const marker = await inspectUserStateMarker(root, input);
10653
10889
  if (!marker.recognized) {
10654
10890
  throw new Error("canonical Superbee user-state root is not owned by this product");
@@ -10711,6 +10947,21 @@ async function inspectCanonicalUserStateRootDetail(input = homedir3()) {
10711
10947
  async function inspectCanonicalUserStateRoot(input = homedir3()) {
10712
10948
  return (await inspectCanonicalUserStateRootDetail(input)).state;
10713
10949
  }
10950
+ async function assertCanonicalUserStateRootReady(input) {
10951
+ if (await inspectCanonicalUserStateRoot(input) !== "ready") {
10952
+ throw new Error("canonical Superbee user-state root is not owned by this product");
10953
+ }
10954
+ }
10955
+ async function writeReadyUserStateFileAtomic0600(input, fileName2, content3) {
10956
+ const root = canonicalUserStateDir(input);
10957
+ await assertCanonicalUserStateRootReady(input);
10958
+ await publishFileAtomic0600(root, fileName2, content3, {
10959
+ beforeCommit: async () => {
10960
+ await assertCanonicalUserStateRootReady(input);
10961
+ return true;
10962
+ }
10963
+ }, input);
10964
+ }
10714
10965
  function missingStateError(file2) {
10715
10966
  return Object.assign(new Error("private user-state record is absent"), { code: "ENOENT", path: file2 });
10716
10967
  }
@@ -10954,6 +11205,7 @@ var init_user_state = __esm({
10954
11205
  "use strict";
10955
11206
  init_define_SUPERBEE_BUILD_IDENTITY();
10956
11207
  init_define_SUPERBEE_UPDATE_POLICY();
11208
+ init_src();
10957
11209
  init_build_identity();
10958
11210
  SUPERBEE_USER_STATE_PATH_SEGMENTS = Object.freeze([".superbee-state"]);
10959
11211
  SUPERSEDED_USER_STATE_PATH_SEGMENTS = Object.freeze([
@@ -12941,6 +13193,18 @@ var init_managed_authority = __esm({
12941
13193
  }
12942
13194
  });
12943
13195
 
13196
+ // ../core/src/storage.ts
13197
+ var init_storage = __esm({
13198
+ "../core/src/storage.ts"() {
13199
+ "use strict";
13200
+ init_define_SUPERBEE_BUILD_IDENTITY();
13201
+ init_define_SUPERBEE_UPDATE_POLICY();
13202
+ init_errors();
13203
+ init_paths();
13204
+ init_version_transport();
13205
+ }
13206
+ });
13207
+
12944
13208
  // ../server/src/router.ts
12945
13209
  function isEnoent2(err) {
12946
13210
  return typeof err === "object" && err !== null && err.code === "ENOENT";
@@ -12981,14 +13245,14 @@ function errorFromCaught(err) {
12981
13245
  return errorResponse(412, "VERSION_CONFLICT", err.message, { expected: err.expected, actual: err.actual });
12982
13246
  }
12983
13247
  if (isEnoent2(err)) {
12984
- return errorResponse(404, "NOT_FOUND", err instanceof Error ? err.message : "not found");
13248
+ return errorResponse(404, "NOT_FOUND", "document or blob not found");
12985
13249
  }
12986
13250
  if (err instanceof InvalidInputError) {
12987
13251
  return errorResponse(400, "USAGE", err.message);
12988
13252
  }
12989
- return errorResponse(500, "RUNTIME", err instanceof Error ? err.message : String(err));
13253
+ return errorResponse(500, "RUNTIME", "internal server error");
12990
13254
  }
12991
- function writeOptionsFromHeaders(req) {
13255
+ function writeOptionsFromRequest(req, attribution) {
12992
13256
  const options2 = {};
12993
13257
  if (req.headers.get("If-None-Match") === "*") {
12994
13258
  options2.expectedVersion = null;
@@ -12996,10 +13260,8 @@ function writeOptionsFromHeaders(req) {
12996
13260
  const ifMatch = req.headers.get("If-Match");
12997
13261
  if (ifMatch !== null) options2.expectedVersion = stripETagWrapper(ifMatch);
12998
13262
  }
12999
- const actor = req.headers.get("X-Actor");
13000
- if (actor) options2.actor = actor;
13001
- const agent = req.headers.get("X-Agent");
13002
- if (agent) options2.agent = agent;
13263
+ options2.actor = attribution.actor;
13264
+ if (attribution.agent !== void 0) options2.agent = attribution.agent;
13003
13265
  return options2;
13004
13266
  }
13005
13267
  function deleteOptionsFromHeaders(req) {
@@ -13009,37 +13271,136 @@ function deleteOptionsFromHeaders(req) {
13009
13271
  function versionHeaders(version2) {
13010
13272
  return { "X-Version": version2, ETag: `"${version2}"` };
13011
13273
  }
13012
- function matchWireResources(pathname) {
13013
- if (pathname === "/v0/capabilities") return [{ resource: "capabilities" }];
13014
- const match = BUNDLE_PATH_RE.exec(pathname);
13015
- if (!match) return [];
13016
- const rest = match[2] ?? "";
13017
- if (rest === "docs") return [{ resource: "docs" }];
13018
- if (rest === "docs:read-many") return [{ resource: "docs-read-many" }];
13019
- if (rest.startsWith("docs/")) {
13020
- const tail = rest.slice("docs/".length);
13021
- return tail.endsWith("/versions") ? [
13022
- { resource: "doc-versions", value: tail.slice(0, -"/versions".length) },
13023
- { resource: "doc", value: tail }
13024
- ] : [{ resource: "doc", value: tail }];
13025
- }
13026
- if (rest.startsWith("reserved/")) {
13027
- return [{ resource: "reserved", value: rest.slice("reserved/".length) }];
13028
- }
13029
- if (rest === "blobs") return [{ resource: "blobs" }];
13030
- if (rest.startsWith("blobs/")) return [{ resource: "blob", value: rest.slice("blobs/".length) }];
13031
- return [];
13274
+ function isCanonicalBundleId(value) {
13275
+ return BUNDLE_ID_RE.test(value);
13276
+ }
13277
+ function literalSpecificity(path41) {
13278
+ return path41.split("/").filter((segment) => segment !== "" && !segment.startsWith("{")).length;
13279
+ }
13280
+ function matchTemplate(template, pathname) {
13281
+ const templateSegments = template.split("/");
13282
+ const pathSegments = pathname.split("/");
13283
+ const params = {};
13284
+ let pathIndex = 0;
13285
+ for (let templateIndex = 0; templateIndex < templateSegments.length; templateIndex++, pathIndex++) {
13286
+ const expected = templateSegments[templateIndex];
13287
+ const actual = pathSegments[pathIndex];
13288
+ if (expected.startsWith("{") && expected.endsWith("...}")) {
13289
+ const suffixLength = templateSegments.length - templateIndex - 1;
13290
+ const captureEnd = pathSegments.length - suffixLength;
13291
+ if (actual === void 0 || actual === "" || captureEnd <= pathIndex) return void 0;
13292
+ params[expected.slice(1, -4)] = pathSegments.slice(pathIndex, captureEnd).join("/");
13293
+ pathIndex = captureEnd - 1;
13294
+ continue;
13295
+ }
13296
+ if (actual === void 0) return void 0;
13297
+ if (expected.startsWith("{") && expected.endsWith("}")) {
13298
+ if (actual === "") return void 0;
13299
+ params[expected.slice(1, -1)] = actual;
13300
+ } else if (expected !== actual) {
13301
+ return void 0;
13302
+ }
13303
+ }
13304
+ return pathIndex === pathSegments.length ? params : void 0;
13305
+ }
13306
+ function resourceFromMatch(resource, params, searchParams) {
13307
+ switch (resource) {
13308
+ case "capabilities":
13309
+ return { kind: "capabilities" };
13310
+ case "docs":
13311
+ return { kind: "docs" };
13312
+ case "docs-read-many":
13313
+ return { kind: "docs-read-many" };
13314
+ case "doc": {
13315
+ const id = decodeId(params.id);
13316
+ assertValidDocId(id);
13317
+ return { kind: "doc", id };
13318
+ }
13319
+ case "doc-versions": {
13320
+ const id = decodeId(params.id);
13321
+ assertValidDocId(id);
13322
+ return { kind: "doc-versions", id };
13323
+ }
13324
+ case "reserved": {
13325
+ const name = params.name;
13326
+ if (name !== "index.md" && name !== "log.md") {
13327
+ throw new InvalidInputError(`reserved file name must be index.md or log.md, got '${name}'`);
13328
+ }
13329
+ const dir = searchParams.get("dir") ?? "";
13330
+ assertSafeReservedDir(dir);
13331
+ return { kind: "reserved", dir, name };
13332
+ }
13333
+ case "blobs":
13334
+ return { kind: "blobs" };
13335
+ case "blob": {
13336
+ const key = decodeBlobKey(params.key);
13337
+ assertSafeBlobKey(key);
13338
+ return { kind: "blob", key };
13339
+ }
13340
+ }
13032
13341
  }
13033
- function resolveWireEndpoint(resources, method) {
13034
- for (const match of resources) {
13035
- const endpoint = WIRE_ENDPOINTS.find((row2) => row2.resource === match.resource && row2.method === method);
13036
- if (endpoint) return { endpoint, match };
13342
+ function invalidBundleFromPath(pathname) {
13343
+ const prefix = "/v0/bundles/";
13344
+ if (!pathname.startsWith(prefix)) return void 0;
13345
+ const rawBundle = pathname.slice(prefix.length).split("/", 1)[0] ?? "";
13346
+ if (!isCanonicalBundleId(rawBundle)) {
13347
+ return new WireRequestResolutionError(400, "USAGE", `invalid bundle id '${rawBundle}'`);
13037
13348
  }
13038
13349
  return void 0;
13039
13350
  }
13040
- function unsupportedMethodResponse(method, match) {
13351
+ function resolvePathAndMethod(pathname, searchParams, method) {
13352
+ const bundleError = invalidBundleFromPath(pathname);
13353
+ if (bundleError) throw bundleError;
13354
+ const shapeMatches = WIRE_ENDPOINTS.flatMap((endpoint) => {
13355
+ const params = matchTemplate(endpoint.path, pathname);
13356
+ return params ? [{ endpoint, params }] : [];
13357
+ });
13358
+ if (shapeMatches.length === 0) {
13359
+ throw new WireRequestResolutionError(404, "NOT_FOUND", `no route for ${pathname}`);
13360
+ }
13361
+ const methodMatches = shapeMatches.filter(({ endpoint }) => endpoint.method === method).sort((a, b) => literalSpecificity(b.endpoint.path) - literalSpecificity(a.endpoint.path));
13362
+ const selected = methodMatches[0];
13363
+ if (!selected) {
13364
+ throw new WireRequestResolutionError(
13365
+ 400,
13366
+ "USAGE",
13367
+ `unsupported method ${method} for ${routeLabel(shapeMatches[0].endpoint.resource)}`
13368
+ );
13369
+ }
13370
+ try {
13371
+ const resource = resourceFromMatch(selected.endpoint.resource, selected.params, searchParams);
13372
+ if (selected.endpoint.id === "capabilities") {
13373
+ return {
13374
+ scope: "deployment",
13375
+ endpointId: "capabilities",
13376
+ accessClass: "public",
13377
+ resource: { kind: "capabilities" },
13378
+ searchParams
13379
+ };
13380
+ }
13381
+ const bundleId = selected.params.bundle;
13382
+ if (!isCanonicalBundleId(bundleId)) {
13383
+ throw new WireRequestResolutionError(400, "USAGE", `invalid bundle id '${bundleId}'`);
13384
+ }
13385
+ return {
13386
+ scope: "bundle",
13387
+ bundleId,
13388
+ endpointId: selected.endpoint.id,
13389
+ accessClass: selected.endpoint.accessClass,
13390
+ resource,
13391
+ searchParams
13392
+ };
13393
+ } catch (error51) {
13394
+ if (error51 instanceof WireRequestResolutionError) throw error51;
13395
+ if (error51 instanceof InvalidInputError) {
13396
+ throw new WireRequestResolutionError(400, "USAGE", error51.message);
13397
+ }
13398
+ throw error51;
13399
+ }
13400
+ }
13401
+ function routeLabel(resource) {
13041
13402
  let label;
13042
- switch (match.resource) {
13403
+ switch (resource) {
13043
13404
  case "docs":
13044
13405
  label = "/docs";
13045
13406
  break;
@@ -13063,33 +13424,45 @@ function unsupportedMethodResponse(method, match) {
13063
13424
  label = "/v0/capabilities";
13064
13425
  break;
13065
13426
  }
13066
- return errorResponse(400, "USAGE", `unsupported method ${method} for ${label}`);
13427
+ return label;
13428
+ }
13429
+ function responseForMethod(isHead, response) {
13430
+ if (!isHead) return response;
13431
+ return new Response(null, {
13432
+ status: response.status,
13433
+ statusText: response.statusText,
13434
+ headers: response.headers
13435
+ });
13067
13436
  }
13068
13437
  function registeredWireRouter(dispatch) {
13069
13438
  return async function handle(req) {
13439
+ const isHead = req.method === "HEAD";
13440
+ let response;
13070
13441
  let url2;
13071
13442
  try {
13072
- url2 = new URL(req.url);
13073
- } catch {
13074
- return errorResponse(400, "USAGE", "invalid request URL");
13075
- }
13076
- const resources = matchWireResources(url2.pathname);
13077
- if (resources.length === 0) return errorResponse(404, "NOT_FOUND", `no route for ${url2.pathname}`);
13078
- const resolved = resolveWireEndpoint(resources, req.method);
13079
- if (!resolved) return unsupportedMethodResponse(req.method, resources[0]);
13080
- try {
13081
- return await dispatch(req, { ...resolved, searchParams: url2.searchParams });
13443
+ try {
13444
+ url2 = new URL(req.url);
13445
+ } catch {
13446
+ throw new WireRequestResolutionError(400, "USAGE", "invalid request URL");
13447
+ }
13448
+ const resolved = resolvePathAndMethod(url2.pathname, url2.searchParams, req.method);
13449
+ response = await dispatch(req, { resolved });
13082
13450
  } catch (err) {
13083
- return errorFromCaught(err);
13451
+ if (err instanceof WireRequestResolutionError) {
13452
+ const message = err.status === 404 ? `no route for ${url2.pathname}` : err.message;
13453
+ response = errorResponse(err.status, err.code, message);
13454
+ } else {
13455
+ response = errorFromCaught(err);
13456
+ }
13084
13457
  }
13458
+ return responseForMethod(isHead, response);
13085
13459
  };
13086
13460
  }
13087
- function createRouter(bundle) {
13088
- return buildRouter(bundle.backend ?? new FilesystemBackend(bundle.root));
13461
+ function createRouter(options2) {
13462
+ return buildRouter(options2);
13089
13463
  }
13090
- function buildRouter(backend) {
13091
- const bundle = { root: "", backend };
13092
- async function handleReadDoc(id) {
13464
+ function buildRouter(options2) {
13465
+ async function handleReadDoc(backend, id) {
13093
13466
  assertValidDocId(id);
13094
13467
  try {
13095
13468
  const { doc: doc2, version: version2 } = await backend.read(id);
@@ -13099,7 +13472,7 @@ function buildRouter(backend) {
13099
13472
  throw err;
13100
13473
  }
13101
13474
  }
13102
- async function handleHeadDoc(id) {
13475
+ async function handleHeadDoc(backend, id) {
13103
13476
  try {
13104
13477
  assertValidDocId(id);
13105
13478
  } catch {
@@ -13113,7 +13486,7 @@ function buildRouter(backend) {
13113
13486
  throw err;
13114
13487
  }
13115
13488
  }
13116
- async function handleWriteDoc(id, req) {
13489
+ async function handleWriteDoc(backend, attribution, id, req) {
13117
13490
  let payload;
13118
13491
  try {
13119
13492
  payload = await req.json();
@@ -13126,27 +13499,27 @@ function buildRouter(backend) {
13126
13499
  if (payload.body !== void 0 && typeof payload.body !== "string") {
13127
13500
  return errorResponse(400, "USAGE", "request body field body must be a string when present");
13128
13501
  }
13129
- const options2 = writeOptionsFromHeaders(req);
13502
+ const writeOptions = writeOptionsFromRequest(req, attribution);
13130
13503
  const result3 = await writeDocVersioned(
13131
- bundle,
13504
+ backend,
13132
13505
  { id, frontmatter: payload.frontmatter, body: payload.body ?? "" },
13133
- options2
13506
+ writeOptions
13134
13507
  );
13135
- const status2 = options2.expectedVersion === null ? 201 : 200;
13508
+ const status2 = writeOptions.expectedVersion === null ? 201 : 200;
13136
13509
  return jsonResponse(status2, { version: result3.version }, versionHeaders(result3.version));
13137
13510
  }
13138
- async function handleDeleteDoc(id, req) {
13511
+ async function handleDeleteDoc(backend, id, req) {
13139
13512
  assertValidDocId(id);
13140
- const options2 = deleteOptionsFromHeaders(req);
13141
- const deleted = await backend.delete(id, options2);
13513
+ const options3 = deleteOptionsFromHeaders(req);
13514
+ const deleted = await backend.delete(id, options3);
13142
13515
  return jsonResponse(200, { deleted });
13143
13516
  }
13144
- async function handleVersions(id) {
13517
+ async function handleVersions(backend, id) {
13145
13518
  assertValidDocId(id);
13146
13519
  const history = await backend.versions(id);
13147
13520
  return jsonResponse(200, { versions: history });
13148
13521
  }
13149
- async function handleReadMany(req) {
13522
+ async function handleReadMany(backend, req) {
13150
13523
  let payload;
13151
13524
  try {
13152
13525
  payload = await req.json();
@@ -13161,8 +13534,8 @@ function buildRouter(backend) {
13161
13534
  for (const id of ids) {
13162
13535
  try {
13163
13536
  assertValidDocId(id);
13164
- } catch (err) {
13165
- return errorResponse(400, "USAGE", err instanceof Error ? err.message : `invalid id '${id}'`, { id });
13537
+ } catch {
13538
+ return errorResponse(400, "USAGE", `invalid document id '${id}'`, { id });
13166
13539
  }
13167
13540
  }
13168
13541
  const existsFlags = await Promise.all(ids.map((id) => backend.exists(id)));
@@ -13175,7 +13548,7 @@ function buildRouter(backend) {
13175
13548
  results: results.map((r2) => ({ id: r2.doc.id, frontmatter: r2.doc.frontmatter, body: r2.doc.body, version: r2.version }))
13176
13549
  });
13177
13550
  }
13178
- async function handleList(searchParams) {
13551
+ async function handleList(backend, searchParams) {
13179
13552
  const prefix = searchParams.get("prefix") ?? void 0;
13180
13553
  const type = searchParams.get("type") ?? void 0;
13181
13554
  const tags = searchParams.getAll("tag");
@@ -13184,7 +13557,7 @@ function buildRouter(backend) {
13184
13557
  const parsedLimit = limitParam ? parseInt(limitParam, 10) : NaN;
13185
13558
  const limit = Number.isFinite(parsedLimit) && parsedLimit > 0 ? parsedLimit : DEFAULT_LIST_LIMIT;
13186
13559
  const cursor = searchParams.get("cursor") ?? void 0;
13187
- const heads = await queryHeads(bundle, { prefix, type, tags });
13560
+ const heads = await queryHeads(backend, { prefix, type, tags });
13188
13561
  const count = heads.length;
13189
13562
  let page = heads;
13190
13563
  if (cursor) {
@@ -13204,13 +13577,13 @@ function buildRouter(backend) {
13204
13577
  );
13205
13578
  return jsonResponse(200, { count, docs, next_cursor: nextCursor });
13206
13579
  }
13207
- async function handleReadReserved(dir, name) {
13580
+ async function handleReadReserved(backend, dir, name) {
13208
13581
  assertSafeReservedDir(dir);
13209
13582
  const result3 = await backend.readReserved(dir, name);
13210
13583
  if (result3 === null) return errorResponse(404, "NOT_FOUND", `no reserved file '${name}' at dir '${dir}'`);
13211
13584
  return jsonResponse(200, { content: result3.content }, versionHeaders(result3.version));
13212
13585
  }
13213
- async function handleWriteReserved(dir, name, req) {
13586
+ async function handleWriteReserved(backend, attribution, dir, name, req) {
13214
13587
  assertSafeReservedDir(dir);
13215
13588
  let payload;
13216
13589
  try {
@@ -13221,12 +13594,12 @@ function buildRouter(backend) {
13221
13594
  if (typeof payload.content !== "string") {
13222
13595
  return errorResponse(400, "USAGE", "request body must include a content: string field");
13223
13596
  }
13224
- const options2 = writeOptionsFromHeaders(req);
13225
- const version2 = await backend.writeReserved(dir, name, payload.content, options2);
13226
- const status2 = options2.expectedVersion === null ? 201 : 200;
13597
+ const writeOptions = writeOptionsFromRequest(req, attribution);
13598
+ const version2 = await backend.writeReserved(dir, name, payload.content, writeOptions);
13599
+ const status2 = writeOptions.expectedVersion === null ? 201 : 200;
13227
13600
  return jsonResponse(status2, { version: version2 }, versionHeaders(version2));
13228
13601
  }
13229
- async function handleReadBlob(key) {
13602
+ async function handleReadBlob(backend, key) {
13230
13603
  assertSafeBlobKey(key);
13231
13604
  const result3 = await backend.readBlob(key);
13232
13605
  if (result3 === null) return errorResponse(404, "NOT_FOUND", `no blob '${key}'`);
@@ -13235,7 +13608,7 @@ function buildRouter(backend) {
13235
13608
  headers: { "content-type": result3.contentType, ...versionHeaders(result3.version) }
13236
13609
  });
13237
13610
  }
13238
- async function handleHeadBlob(key) {
13611
+ async function handleHeadBlob(backend, key) {
13239
13612
  try {
13240
13613
  assertSafeBlobKey(key);
13241
13614
  } catch {
@@ -13248,23 +13621,23 @@ function buildRouter(backend) {
13248
13621
  headers: { "content-type": result3.contentType, ...versionHeaders(result3.version) }
13249
13622
  });
13250
13623
  }
13251
- async function handleWriteBlob(key, req) {
13624
+ async function handleWriteBlob(backend, attribution, key, req) {
13252
13625
  assertSafeBlobKey(key);
13253
13626
  const bytes = new Uint8Array(await req.arrayBuffer());
13254
13627
  const contentTypeHeader = req.headers.get("content-type");
13255
13628
  const contentType = contentTypeHeader && contentTypeHeader.trim() !== "" ? contentTypeHeader : void 0;
13256
- const options2 = writeOptionsFromHeaders(req);
13257
- const version2 = await backend.writeBlob(key, bytes, contentType, options2);
13258
- const status2 = options2.expectedVersion === null ? 201 : 200;
13629
+ const writeOptions = writeOptionsFromRequest(req, attribution);
13630
+ const version2 = await backend.writeBlob(key, bytes, contentType, writeOptions);
13631
+ const status2 = writeOptions.expectedVersion === null ? 201 : 200;
13259
13632
  return jsonResponse(status2, { version: version2 }, versionHeaders(version2));
13260
13633
  }
13261
- async function handleDeleteBlob(key, req) {
13634
+ async function handleDeleteBlob(backend, key, req) {
13262
13635
  assertSafeBlobKey(key);
13263
- const options2 = deleteOptionsFromHeaders(req);
13264
- const deleted = await backend.deleteBlob(key, options2);
13636
+ const options3 = deleteOptionsFromHeaders(req);
13637
+ const deleted = await backend.deleteBlob(key, options3);
13265
13638
  return jsonResponse(200, { deleted });
13266
13639
  }
13267
- async function handleListBlobs(searchParams) {
13640
+ async function handleListBlobs(backend, searchParams) {
13268
13641
  const prefix = searchParams.get("prefix") ?? void 0;
13269
13642
  const limitParam = searchParams.get("limit");
13270
13643
  const parsedLimit = limitParam ? parseInt(limitParam, 10) : NaN;
@@ -13282,15 +13655,7 @@ function buildRouter(backend) {
13282
13655
  return jsonResponse(200, { count, keys: limited, next_cursor: nextCursor });
13283
13656
  }
13284
13657
  function handleCapabilities() {
13285
- const declared = backend.capabilities?.();
13286
- const caps = declared ?? {
13287
- enforced_cas: backend instanceof MemoryBackend,
13288
- blobs: true,
13289
- // v0.1 — PUT/GET/HEAD /blobs/{key} + GET /blobs (list)
13290
- projections: true,
13291
- backlinks: false
13292
- // deferred to v1 (docs/WIRE-PROTOCOL.md)
13293
- };
13658
+ const caps = options2.capabilities;
13294
13659
  return jsonResponse(200, {
13295
13660
  history: caps.history ?? caps.enforced_cas,
13296
13661
  enforced_cas: caps.enforced_cas,
@@ -13299,97 +13664,232 @@ function buildRouter(backend) {
13299
13664
  blobs: caps.blobs
13300
13665
  });
13301
13666
  }
13302
- return registeredWireRouter(async (req, { endpoint, match, searchParams }) => {
13303
- switch (endpoint.id) {
13667
+ return registeredWireRouter(async (req, { resolved }) => {
13668
+ if (resolved.scope === "deployment") return handleCapabilities();
13669
+ const context = await options2.resolveContext(req, resolved);
13670
+ if (context instanceof Response) return context;
13671
+ const { backend, attribution } = context;
13672
+ switch (resolved.endpointId) {
13304
13673
  case "capabilities":
13305
- return handleCapabilities();
13674
+ throw new Error("deployment route reached bundle dispatch");
13306
13675
  case "docs-list":
13307
- return await handleList(searchParams);
13676
+ return await handleList(backend, resolved.searchParams);
13308
13677
  case "docs-read-many":
13309
- return await handleReadMany(req);
13678
+ return await handleReadMany(backend, req);
13310
13679
  case "doc-versions":
13311
- return await handleVersions(decodeId(match.value));
13680
+ return await handleVersions(backend, resolved.resource.id);
13312
13681
  case "doc-read":
13313
- return await handleReadDoc(decodeId(match.value));
13682
+ return await handleReadDoc(backend, resolved.resource.id);
13314
13683
  case "doc-write":
13315
- return await handleWriteDoc(decodeId(match.value), req);
13684
+ return await handleWriteDoc(
13685
+ backend,
13686
+ attribution,
13687
+ resolved.resource.id,
13688
+ req
13689
+ );
13316
13690
  case "doc-head":
13317
- return await handleHeadDoc(decodeId(match.value));
13691
+ return await handleHeadDoc(backend, resolved.resource.id);
13318
13692
  case "doc-delete":
13319
- return await handleDeleteDoc(decodeId(match.value), req);
13320
- case "reserved-read":
13693
+ return await handleDeleteDoc(backend, resolved.resource.id, req);
13694
+ case "reserved-read": {
13695
+ const resource = resolved.resource;
13696
+ return await handleReadReserved(backend, resource.dir, resource.name);
13697
+ }
13321
13698
  case "reserved-write": {
13322
- const name = match.value;
13323
- if (name !== "index.md" && name !== "log.md") {
13324
- return errorResponse(400, "USAGE", `reserved file name must be index.md or log.md, got '${name}'`);
13325
- }
13326
- const dir = searchParams.get("dir") ?? "";
13327
- return endpoint.id === "reserved-read" ? await handleReadReserved(dir, name) : await handleWriteReserved(dir, name, req);
13699
+ const resource = resolved.resource;
13700
+ return await handleWriteReserved(backend, attribution, resource.dir, resource.name, req);
13328
13701
  }
13329
13702
  case "blobs-list":
13330
- return await handleListBlobs(searchParams);
13703
+ return await handleListBlobs(backend, resolved.searchParams);
13331
13704
  case "blob-read":
13332
- return await handleReadBlob(decodeBlobKey(match.value));
13705
+ return await handleReadBlob(backend, resolved.resource.key);
13333
13706
  case "blob-write":
13334
- return await handleWriteBlob(decodeBlobKey(match.value), req);
13707
+ return await handleWriteBlob(
13708
+ backend,
13709
+ attribution,
13710
+ resolved.resource.key,
13711
+ req
13712
+ );
13335
13713
  case "blob-head":
13336
- return await handleHeadBlob(decodeBlobKey(match.value));
13714
+ return await handleHeadBlob(backend, resolved.resource.key);
13337
13715
  case "blob-delete":
13338
- return await handleDeleteBlob(decodeBlobKey(match.value), req);
13716
+ return await handleDeleteBlob(backend, resolved.resource.key, req);
13339
13717
  }
13340
13718
  });
13341
13719
  }
13342
- var DEFAULT_LIST_LIMIT, BUNDLE_PATH_RE, WIRE_ENDPOINTS;
13720
+ var DEFAULT_LIST_LIMIT, WIRE_ENDPOINTS, WireRequestResolutionError, BUNDLE_ID_RE;
13343
13721
  var init_router = __esm({
13344
13722
  "../server/src/router.ts"() {
13345
13723
  "use strict";
13346
13724
  init_define_SUPERBEE_BUILD_IDENTITY();
13347
13725
  init_define_SUPERBEE_UPDATE_POLICY();
13348
- init_src();
13726
+ init_storage();
13727
+ init_engine();
13349
13728
  DEFAULT_LIST_LIMIT = 50;
13350
- BUNDLE_PATH_RE = /^\/v0\/bundles\/([^/]+)\/(.*)$/;
13351
13729
  WIRE_ENDPOINTS = [
13352
- { id: "capabilities", resource: "capabilities", method: "GET", path: "/v0/capabilities" },
13353
- { id: "docs-list", resource: "docs", method: "GET", path: "/v0/bundles/{bundle}/docs" },
13730
+ {
13731
+ id: "capabilities",
13732
+ resource: "capabilities",
13733
+ method: "GET",
13734
+ path: "/v0/capabilities",
13735
+ accessClass: "public"
13736
+ },
13737
+ {
13738
+ id: "docs-list",
13739
+ resource: "docs",
13740
+ method: "GET",
13741
+ path: "/v0/bundles/{bundle}/docs",
13742
+ accessClass: "read"
13743
+ },
13354
13744
  {
13355
13745
  id: "docs-read-many",
13356
13746
  resource: "docs-read-many",
13357
13747
  method: "POST",
13358
- path: "/v0/bundles/{bundle}/docs:read-many"
13748
+ path: "/v0/bundles/{bundle}/docs:read-many",
13749
+ accessClass: "read"
13750
+ },
13751
+ {
13752
+ id: "doc-read",
13753
+ resource: "doc",
13754
+ method: "GET",
13755
+ path: "/v0/bundles/{bundle}/docs/{id...}",
13756
+ accessClass: "read"
13757
+ },
13758
+ {
13759
+ id: "doc-write",
13760
+ resource: "doc",
13761
+ method: "PUT",
13762
+ path: "/v0/bundles/{bundle}/docs/{id...}",
13763
+ accessClass: "write"
13764
+ },
13765
+ {
13766
+ id: "doc-head",
13767
+ resource: "doc",
13768
+ method: "HEAD",
13769
+ path: "/v0/bundles/{bundle}/docs/{id...}",
13770
+ accessClass: "read"
13771
+ },
13772
+ {
13773
+ id: "doc-delete",
13774
+ resource: "doc",
13775
+ method: "DELETE",
13776
+ path: "/v0/bundles/{bundle}/docs/{id...}",
13777
+ accessClass: "write"
13359
13778
  },
13360
- { id: "doc-read", resource: "doc", method: "GET", path: "/v0/bundles/{bundle}/docs/{id...}" },
13361
- { id: "doc-write", resource: "doc", method: "PUT", path: "/v0/bundles/{bundle}/docs/{id...}" },
13362
- { id: "doc-head", resource: "doc", method: "HEAD", path: "/v0/bundles/{bundle}/docs/{id...}" },
13363
- { id: "doc-delete", resource: "doc", method: "DELETE", path: "/v0/bundles/{bundle}/docs/{id...}" },
13364
13779
  {
13365
13780
  id: "doc-versions",
13366
13781
  resource: "doc-versions",
13367
13782
  method: "GET",
13368
- path: "/v0/bundles/{bundle}/docs/{id...}/versions"
13783
+ path: "/v0/bundles/{bundle}/docs/{id...}/versions",
13784
+ accessClass: "read"
13369
13785
  },
13370
13786
  {
13371
13787
  id: "reserved-read",
13372
13788
  resource: "reserved",
13373
13789
  method: "GET",
13374
- path: "/v0/bundles/{bundle}/reserved/{name}"
13790
+ path: "/v0/bundles/{bundle}/reserved/{name}",
13791
+ accessClass: "read"
13375
13792
  },
13376
13793
  {
13377
13794
  id: "reserved-write",
13378
13795
  resource: "reserved",
13379
13796
  method: "PUT",
13380
- path: "/v0/bundles/{bundle}/reserved/{name}"
13797
+ path: "/v0/bundles/{bundle}/reserved/{name}",
13798
+ accessClass: "write"
13799
+ },
13800
+ {
13801
+ id: "blobs-list",
13802
+ resource: "blobs",
13803
+ method: "GET",
13804
+ path: "/v0/bundles/{bundle}/blobs",
13805
+ accessClass: "read"
13806
+ },
13807
+ {
13808
+ id: "blob-read",
13809
+ resource: "blob",
13810
+ method: "GET",
13811
+ path: "/v0/bundles/{bundle}/blobs/{key...}",
13812
+ accessClass: "read"
13813
+ },
13814
+ {
13815
+ id: "blob-write",
13816
+ resource: "blob",
13817
+ method: "PUT",
13818
+ path: "/v0/bundles/{bundle}/blobs/{key...}",
13819
+ accessClass: "write"
13820
+ },
13821
+ {
13822
+ id: "blob-head",
13823
+ resource: "blob",
13824
+ method: "HEAD",
13825
+ path: "/v0/bundles/{bundle}/blobs/{key...}",
13826
+ accessClass: "read"
13381
13827
  },
13382
- { id: "blobs-list", resource: "blobs", method: "GET", path: "/v0/bundles/{bundle}/blobs" },
13383
- { id: "blob-read", resource: "blob", method: "GET", path: "/v0/bundles/{bundle}/blobs/{key...}" },
13384
- { id: "blob-write", resource: "blob", method: "PUT", path: "/v0/bundles/{bundle}/blobs/{key...}" },
13385
- { id: "blob-head", resource: "blob", method: "HEAD", path: "/v0/bundles/{bundle}/blobs/{key...}" },
13386
13828
  {
13387
13829
  id: "blob-delete",
13388
13830
  resource: "blob",
13389
13831
  method: "DELETE",
13390
- path: "/v0/bundles/{bundle}/blobs/{key...}"
13832
+ path: "/v0/bundles/{bundle}/blobs/{key...}",
13833
+ accessClass: "write"
13391
13834
  }
13392
13835
  ];
13836
+ WireRequestResolutionError = class extends Error {
13837
+ status;
13838
+ code;
13839
+ constructor(status2, code3, message) {
13840
+ super(message);
13841
+ this.name = "WireRequestResolutionError";
13842
+ this.status = status2;
13843
+ this.code = code3;
13844
+ }
13845
+ };
13846
+ BUNDLE_ID_RE = /^bnd_[0-9a-f]{32}$/;
13847
+ }
13848
+ });
13849
+
13850
+ // ../server/src/legacy-router.ts
13851
+ function capabilitiesForBackend(backend) {
13852
+ return backend.capabilities?.() ?? {
13853
+ enforced_cas: backend instanceof MemoryBackend,
13854
+ blobs: true,
13855
+ projections: true,
13856
+ backlinks: false
13857
+ };
13858
+ }
13859
+ function legacyAttribution(request) {
13860
+ const actor = request.headers.get("X-Actor")?.trim();
13861
+ const agent = request.headers.get("X-Agent")?.trim();
13862
+ return {
13863
+ actor: actor || "unknown",
13864
+ ...agent ? { agent } : {}
13865
+ };
13866
+ }
13867
+ function canonicalizeLegacyBundleRoute(request) {
13868
+ const url2 = new URL(request.url);
13869
+ const match = /^\/v0\/bundles\/([^/]+)\/(.*)$/.exec(url2.pathname);
13870
+ if (!match) return request;
13871
+ url2.pathname = `/v0/bundles/${LEGACY_INTERNAL_BUNDLE_ID}/${match[2]}`;
13872
+ return new Request(url2, request);
13873
+ }
13874
+ function buildLegacyRouter(backend) {
13875
+ const workerRouter = createRouter({
13876
+ capabilities: capabilitiesForBackend(backend),
13877
+ resolveContext: (request) => ({ backend, attribution: legacyAttribution(request) })
13878
+ });
13879
+ return (request) => workerRouter(canonicalizeLegacyBundleRoute(request));
13880
+ }
13881
+ function createRouter2(bundle) {
13882
+ return buildLegacyRouter(bundle.backend ?? new FilesystemBackend(bundle.root));
13883
+ }
13884
+ var LEGACY_INTERNAL_BUNDLE_ID;
13885
+ var init_legacy_router = __esm({
13886
+ "../server/src/legacy-router.ts"() {
13887
+ "use strict";
13888
+ init_define_SUPERBEE_BUILD_IDENTITY();
13889
+ init_define_SUPERBEE_UPDATE_POLICY();
13890
+ init_src();
13891
+ init_router();
13892
+ LEGACY_INTERNAL_BUNDLE_ID = "bnd_00000000000000000000000000000000";
13393
13893
  }
13394
13894
  });
13395
13895
 
@@ -13454,7 +13954,7 @@ async function writeResponseToServerResponse(res, response) {
13454
13954
  res.end(bytes);
13455
13955
  }
13456
13956
  function serve(options2) {
13457
- const router = createRouter(options2.bundle);
13957
+ const router = createRouter2(options2.bundle);
13458
13958
  const host = options2.host ?? "127.0.0.1";
13459
13959
  return new Promise((resolve2, reject) => {
13460
13960
  const server = createServer((req, res) => {
@@ -13487,7 +13987,7 @@ var init_serve = __esm({
13487
13987
  "use strict";
13488
13988
  init_define_SUPERBEE_BUILD_IDENTITY();
13489
13989
  init_define_SUPERBEE_UPDATE_POLICY();
13490
- init_router();
13990
+ init_legacy_router();
13491
13991
  RequestBodyTooLargeError = class extends Error {
13492
13992
  limitBytes;
13493
13993
  constructor(limitBytes) {
@@ -13505,7 +14005,7 @@ var init_src3 = __esm({
13505
14005
  "use strict";
13506
14006
  init_define_SUPERBEE_BUILD_IDENTITY();
13507
14007
  init_define_SUPERBEE_UPDATE_POLICY();
13508
- init_router();
14008
+ init_legacy_router();
13509
14009
  init_serve();
13510
14010
  }
13511
14011
  });
@@ -13536,7 +14036,7 @@ async function resolveConceptIdCliArgument(bundle, raw, options2 = {}) {
13536
14036
  if (isReservedFile(pathFromConceptId(alias))) return alias;
13537
14037
  if (!trimmed.endsWith(".md")) return alias;
13538
14038
  const literal2 = withPrefix(conceptIdFromPath(`${trimmed}.md`), options2.prefix);
13539
- return literal2 !== alias && await existsDoc(bundle, literal2) ? literal2 : alias;
14039
+ return literal2 !== alias && await existsDoc2(bundle, literal2) ? literal2 : alias;
13540
14040
  }
13541
14041
  var init_concept_id = __esm({
13542
14042
  "src/concept-id.ts"() {
@@ -13906,7 +14406,7 @@ function sameEntry(existing, source) {
13906
14406
  }
13907
14407
  async function readRegistrationIfPresent(bundle, viewId) {
13908
14408
  try {
13909
- return await readDocVersioned(bundle, viewId);
14409
+ return await readDocVersioned2(bundle, viewId);
13910
14410
  } catch (error51) {
13911
14411
  if (error51?.code === "ENOENT") return null;
13912
14412
  throw error51;
@@ -13937,7 +14437,7 @@ async function persistTransientView(bundle, source, input, revalidateSource, opt
13937
14437
  body: ""
13938
14438
  };
13939
14439
  const [existingEntry, existingRegistry] = await Promise.all([
13940
- readBlob(bundle, entry),
14440
+ readBlob2(bundle, entry),
13941
14441
  readRegistrationIfPresent(bundle, viewId)
13942
14442
  ]);
13943
14443
  if (existingEntry !== null && !sameEntry(existingEntry, source)) {
@@ -13956,7 +14456,7 @@ async function persistTransientView(bundle, source, input, revalidateSource, opt
13956
14456
  entryVersion = existingEntry.version;
13957
14457
  } else {
13958
14458
  try {
13959
- entryVersion = await writeBlob(
14459
+ entryVersion = await writeBlob2(
13960
14460
  bundle,
13961
14461
  entry,
13962
14462
  source.bytes,
@@ -13965,7 +14465,7 @@ async function persistTransientView(bundle, source, input, revalidateSource, opt
13965
14465
  );
13966
14466
  entryCreated = true;
13967
14467
  } catch (error51) {
13968
- const winner = await readBlob(bundle, entry);
14468
+ const winner = await readBlob2(bundle, entry);
13969
14469
  if (!sameEntry(winner, source)) {
13970
14470
  if (!(error51 instanceof VersionConflict)) {
13971
14471
  throw new TransientViewSaveError(
@@ -14040,7 +14540,7 @@ async function persistTransientView(bundle, source, input, revalidateSource, opt
14040
14540
  }
14041
14541
  }
14042
14542
  const [finalEntry, finalRegistry, finalSourceIsCurrent] = await Promise.all([
14043
- readBlob(bundle, entry),
14543
+ readBlob2(bundle, entry),
14044
14544
  readRegistrationIfPresent(bundle, viewId),
14045
14545
  revalidateSource().catch(() => false)
14046
14546
  ]);
@@ -14064,7 +14564,7 @@ async function persistTransientView(bundle, source, input, revalidateSource, opt
14064
14564
  };
14065
14565
  } catch (error51) {
14066
14566
  const [currentEntry, currentRegistry] = await Promise.all([
14067
- readBlob(bundle, entry).catch(() => null),
14567
+ readBlob2(bundle, entry).catch(() => null),
14068
14568
  readRegistrationIfPresent(bundle, viewId).catch(() => null)
14069
14569
  ]);
14070
14570
  if (error51 instanceof TransientViewSaveError) {
@@ -14212,7 +14712,7 @@ function cachedAdmission(admitEntry) {
14212
14712
  };
14213
14713
  }
14214
14714
  async function admitBundleEntry(bundle, entry, expectedVersion) {
14215
- const blob = await readBlob(bundle, entry);
14715
+ const blob = await readBlob2(bundle, entry);
14216
14716
  if (blob === null) return false;
14217
14717
  if (expectedVersion && expectedVersion !== blob.version) return false;
14218
14718
  admitActiveView(blob.bytes, blob.contentType);
@@ -14240,7 +14740,7 @@ async function projectViewCatalog(heads, options2) {
14240
14740
  }
14241
14741
  async function listViewCatalog(bundle) {
14242
14742
  const skipped = [];
14243
- const heads = await queryHeads(bundle, { type: "View" }, { onSkip: (row2) => skipped.push(row2) });
14743
+ const heads = await queryHeads2(bundle, { type: "View" }, { onSkip: (row2) => skipped.push(row2) });
14244
14744
  return projectViewCatalog(heads, {
14245
14745
  skippedDocuments: skipped.length,
14246
14746
  admitEntry: (entry, expectedVersion) => admitBundleEntry(bundle, entry, expectedVersion)
@@ -14254,7 +14754,7 @@ async function listViewCatalogPage(bundle, options2) {
14254
14754
  throw new Error("View catalog scan limit must be a safe integer at least as large as the page limit");
14255
14755
  }
14256
14756
  const skipped = [];
14257
- const heads = await queryHeads(bundle, { type: "View" }, { onSkip: (row2) => skipped.push(row2) });
14757
+ const heads = await queryHeads2(bundle, { type: "View" }, { onSkip: (row2) => skipped.push(row2) });
14258
14758
  const { candidates, invalidRegistrations } = projectCandidates(heads);
14259
14759
  const supported = new Set(options2.access);
14260
14760
  const compatible = candidates.filter((candidate) => supported.has(candidate.row.access));
@@ -14516,13 +15016,13 @@ var init_bridge = __esm({
14516
15016
  let outcome;
14517
15017
  try {
14518
15018
  outcome = await this.execute(before, request);
14519
- } catch (error51) {
15019
+ } catch {
14520
15020
  outcome = {
14521
15021
  reply: fail(
14522
15022
  request.id,
14523
15023
  request.bridge,
14524
15024
  "RUNTIME",
14525
- error51 instanceof Error ? error51.message : String(error51)
15025
+ "the View request failed"
14526
15026
  )
14527
15027
  };
14528
15028
  }
@@ -14566,11 +15066,8 @@ var init_bridge = __esm({
14566
15066
  let next;
14567
15067
  try {
14568
15068
  next = await this.subscriptionSnapshot();
14569
- } catch (error51) {
14570
- return this.reload(
14571
- launchId,
14572
- error51 instanceof Error ? error51.message : String(error51)
14573
- );
15069
+ } catch {
15070
+ return this.reload(launchId, "the View subscription could not be refreshed");
14574
15071
  }
14575
15072
  const after = await this.options.launches.resolve(launchId, true);
14576
15073
  if (!after) return this.reload(launchId, "the View changed while its subscription was polled");
@@ -14605,7 +15102,7 @@ var init_bridge = __esm({
14605
15102
  return { status: "reload-required", message };
14606
15103
  }
14607
15104
  async subscriptionSnapshot() {
14608
- const rows = await queryHeads(this.options.bundle, {});
15105
+ const rows = await queryHeads2(this.options.bundle, {});
14609
15106
  if (rows.length > MAX_SUBSCRIPTION_HEADS) {
14610
15107
  throw new Error("the bundle is too large for the experimental View polling snapshot");
14611
15108
  }
@@ -14620,7 +15117,7 @@ var init_bridge = __esm({
14620
15117
  return { reply: null, openPageId: request.pageId };
14621
15118
  }
14622
15119
  try {
14623
- const target = await readDocVersioned(this.options.bundle, request.pageId);
15120
+ const target = await readDocVersioned2(this.options.bundle, request.pageId);
14624
15121
  if (!isAnyRegistryId(target.doc.id) || !parseRegistration(target.doc.id, target.doc.frontmatter)) {
14625
15122
  throw new Error("invalid View target");
14626
15123
  }
@@ -14641,13 +15138,13 @@ var init_bridge = __esm({
14641
15138
  };
14642
15139
  }
14643
15140
  if (request.type === "query") {
14644
- const rows = await queryHeads(this.options.bundle, {
15141
+ const rows = await queryHeads2(this.options.bundle, {
14645
15142
  ...request.params.type ? { type: request.params.type } : {},
14646
15143
  ...request.params.prefix ? { prefix: request.params.prefix } : {}
14647
15144
  });
14648
15145
  const [registry2, okfVersion] = await Promise.all([
14649
15146
  loadKinds(this.options.bundle),
14650
- readBundleOkfVersion(this.options.bundle)
15147
+ readBundleOkfVersion2(this.options.bundle)
14651
15148
  ]);
14652
15149
  const result3 = boundedRows(
14653
15150
  rows,
@@ -14662,9 +15159,9 @@ var init_bridge = __esm({
14662
15159
  }
14663
15160
  if (request.type === "read" || request.type === "read-versioned") {
14664
15161
  const [result3, registry2, okfVersion] = await Promise.all([
14665
- readDocVersioned(this.options.bundle, request.docId),
15162
+ readDocVersioned2(this.options.bundle, request.docId),
14666
15163
  loadKinds(this.options.bundle),
14667
- readBundleOkfVersion(this.options.bundle)
15164
+ readBundleOkfVersion2(this.options.bundle)
14668
15165
  ]);
14669
15166
  if (Buffer.byteLength(result3.doc.body, "utf8") > MAX_DOCUMENT_BODY_BYTES) {
14670
15167
  return { reply: fail(request.id, request.bridge, "TOO_LARGE", "the document body exceeded the 1 MiB View limit") };
@@ -14683,7 +15180,7 @@ var init_bridge = __esm({
14683
15180
  if (request.type === "render-document") {
14684
15181
  let result3;
14685
15182
  try {
14686
- result3 = await readDocVersioned(this.options.bundle, request.docId);
15183
+ result3 = await readDocVersioned2(this.options.bundle, request.docId);
14687
15184
  } catch (error51) {
14688
15185
  if (error51?.code === "ENOENT") {
14689
15186
  return {
@@ -14710,7 +15207,7 @@ var init_bridge = __esm({
14710
15207
  };
14711
15208
  }
14712
15209
  if (request.type === "edges") {
14713
- const edges = await queryEdges(this.options.bundle, request.params);
15210
+ const edges = await queryEdges2(this.options.bundle, request.params);
14714
15211
  if (edges.length > MAX_EDGE_ROWS) {
14715
15212
  return { reply: fail(request.id, request.bridge, "TOO_LARGE", `the edge query exceeded ${MAX_EDGE_ROWS} rows`) };
14716
15213
  }
@@ -14776,13 +15273,13 @@ async function launchIsCurrent(bundle, launch) {
14776
15273
  return launch.bundleIdentity === bundle.root && blobVersion(launch.bytes) === launch.contentVersion;
14777
15274
  }
14778
15275
  try {
14779
- const registryRead = await readDocVersioned(bundle, launch.registryId);
15276
+ const registryRead = await readDocVersioned2(bundle, launch.registryId);
14780
15277
  if (registryRead.version !== launch.registryVersion) return false;
14781
15278
  const registration = parseRegistration(registryRead.doc.id, registryRead.doc.frontmatter);
14782
15279
  if (!registration || registration.type !== launch.registryType || registration.entry !== launch.entryKey || resolveDeclaredAccess(registryRead.doc.frontmatter) !== launch.capability) {
14783
15280
  return false;
14784
15281
  }
14785
- const blob = await readBlob(bundle, launch.entryKey);
15282
+ const blob = await readBlob2(bundle, launch.entryKey);
14786
15283
  if (blob === null) return false;
14787
15284
  if (registration.entryVersion && registration.entryVersion !== blob.version) return false;
14788
15285
  const admitted = admitActiveView(blob.bytes, blob.contentType);
@@ -14794,14 +15291,14 @@ async function launchIsCurrent(bundle, launch) {
14794
15291
  async function mintActiveViewLaunch(bundle, launches, registryId) {
14795
15292
  let registryRead;
14796
15293
  try {
14797
- registryRead = await readDocVersioned(bundle, registryId);
15294
+ registryRead = await readDocVersioned2(bundle, registryId);
14798
15295
  } catch (error51) {
14799
15296
  if (error51?.code === "ENOENT") {
14800
15297
  throw new ViewNotFoundError(registryId, error51);
14801
15298
  }
14802
15299
  throw new RegisteredViewLaunchError(
14803
15300
  "VIEW_REGISTRY_READ_FAILED",
14804
- error51 instanceof Error ? error51.message : String(error51),
15301
+ "the View registration could not be read",
14805
15302
  registryId,
14806
15303
  void 0,
14807
15304
  error51
@@ -14817,11 +15314,11 @@ async function mintActiveViewLaunch(bundle, launches, registryId) {
14817
15314
  }
14818
15315
  let blob;
14819
15316
  try {
14820
- blob = await readBlob(bundle, registration.entry);
15317
+ blob = await readBlob2(bundle, registration.entry);
14821
15318
  } catch (error51) {
14822
15319
  throw new RegisteredViewLaunchError(
14823
15320
  "VIEW_ENTRY_READ_FAILED",
14824
- error51 instanceof Error ? error51.message : String(error51),
15321
+ "the View entry could not be read",
14825
15322
  registryId,
14826
15323
  registration.entry,
14827
15324
  error51
@@ -14846,10 +15343,10 @@ async function mintActiveViewLaunch(bundle, launches, registryId) {
14846
15343
  let admitted;
14847
15344
  try {
14848
15345
  admitted = admitActiveView(blob.bytes, blob.contentType);
14849
- } catch (error51) {
15346
+ } catch {
14850
15347
  throw new RegisteredViewLaunchError(
14851
15348
  "VIEW_ADMISSION_REJECTED",
14852
- error51 instanceof Error ? error51.message : String(error51),
15349
+ "the View entry must be bounded UTF-8 text/html",
14853
15350
  registryId,
14854
15351
  registration.entry
14855
15352
  );
@@ -15139,8 +15636,8 @@ var init_src4 = __esm({
15139
15636
  let action;
15140
15637
  try {
15141
15638
  action = parseDocumentSetFieldAction(rawAction);
15142
- } catch (error51) {
15143
- return rejected(error51 instanceof Error ? error51.message : String(error51));
15639
+ } catch {
15640
+ return rejected("the action request is invalid");
15144
15641
  }
15145
15642
  if (["type", "timestamp", "actor"].includes(action.field)) return rejected(`field '${action.field}' is shell-managed and cannot be proposed`);
15146
15643
  if (launch.documentVersions && (!Object.hasOwn(launch.documentVersions, action.docId) || launch.documentVersions[action.docId] !== action.expectedVersion)) {
@@ -15148,10 +15645,10 @@ var init_src4 = __esm({
15148
15645
  }
15149
15646
  let target;
15150
15647
  try {
15151
- target = await readDocVersioned(this.bundle, action.docId);
15648
+ target = await readDocVersioned2(this.bundle, action.docId);
15152
15649
  } catch (error51) {
15153
15650
  if (error51?.code === "ENOENT") return rejected(`document '${action.docId}' does not exist`);
15154
- return { status: "failed", action: "document.set-field", message: error51 instanceof Error ? error51.message : String(error51) };
15651
+ return { status: "failed", action: "document.set-field", message: "the target document could not be read" };
15155
15652
  }
15156
15653
  if (target.version !== action.expectedVersion) {
15157
15654
  return {
@@ -15168,10 +15665,10 @@ var init_src4 = __esm({
15168
15665
  try {
15169
15666
  [registry2, okfVersion] = await Promise.all([
15170
15667
  loadKinds(this.bundle),
15171
- readBundleOkfVersion(this.bundle)
15668
+ readBundleOkfVersion2(this.bundle)
15172
15669
  ]);
15173
- } catch (error51) {
15174
- return { status: "failed", action: "document.set-field", message: error51 instanceof Error ? error51.message : String(error51) };
15670
+ } catch {
15671
+ return { status: "failed", action: "document.set-field", message: "the governing Kind could not be read" };
15175
15672
  }
15176
15673
  const targetType = String(target.doc.frontmatter.type ?? "");
15177
15674
  const kind2 = registry2.kinds.get(targetType);
@@ -15220,9 +15717,9 @@ var init_src4 = __esm({
15220
15717
  if (violations.length > 0) return rejected(violations.map((warning) => warning.message).join("; "));
15221
15718
  let kindVersion;
15222
15719
  try {
15223
- kindVersion = (await readDocVersioned(this.bundle, kind2.id)).version;
15224
- } catch (error51) {
15225
- return { status: "failed", action: "document.set-field", message: error51 instanceof Error ? error51.message : String(error51) };
15720
+ kindVersion = (await readDocVersioned2(this.bundle, kind2.id)).version;
15721
+ } catch {
15722
+ return { status: "failed", action: "document.set-field", message: "the governing Kind version could not be read" };
15226
15723
  }
15227
15724
  this.sweepExpired();
15228
15725
  if (this.pending.size >= this.maxApprovals) return rejected("the trusted shell has too many pending confirmations; cancel one and try again");
@@ -15278,7 +15775,7 @@ var init_src4 = __esm({
15278
15775
  return { status: "revoked", action: "document.set-field", docId: pending.action.docId, field: pending.action.field };
15279
15776
  }
15280
15777
  try {
15281
- const target = await readDocVersioned(this.bundle, pending.action.docId);
15778
+ const target = await readDocVersioned2(this.bundle, pending.action.docId);
15282
15779
  if (target.version !== pending.action.expectedVersion) {
15283
15780
  return {
15284
15781
  status: "conflict",
@@ -15291,7 +15788,7 @@ var init_src4 = __esm({
15291
15788
  }
15292
15789
  const [registry2, okfVersion] = await Promise.all([
15293
15790
  loadKinds(this.bundle),
15294
- readBundleOkfVersion(this.bundle)
15791
+ readBundleOkfVersion2(this.bundle)
15295
15792
  ]);
15296
15793
  if (okfVersion !== pending.okfVersion) {
15297
15794
  return { status: "revoked", action: "document.set-field", message: "the bundle OKF edition changed" };
@@ -15302,7 +15799,7 @@ var init_src4 = __esm({
15302
15799
  if (!fieldCoordinate || fieldCoordinate.storageField !== pending.storageField) {
15303
15800
  return { status: "revoked", action: "document.set-field", message: "the governing Kind field mapping changed" };
15304
15801
  }
15305
- const currentKindVersion = (await readDocVersioned(this.bundle, kind2.id)).version;
15802
+ const currentKindVersion = (await readDocVersioned2(this.bundle, kind2.id)).version;
15306
15803
  if (currentKindVersion !== pending.kindVersion || kindDigest(kind2) !== pending.kindDigest) {
15307
15804
  return { status: "revoked", action: "document.set-field", message: "the governing Kind changed" };
15308
15805
  }
@@ -15365,12 +15862,12 @@ var init_src4 = __esm({
15365
15862
  return { status: "conflict", action: "document.set-field", docId: pending.action.docId, field: pending.action.field, expectedVersion: pending.action.expectedVersion, actualVersion: null };
15366
15863
  }
15367
15864
  if (error51 instanceof KindConformanceError) {
15368
- return { status: "rejected", action: "document.set-field", docId: pending.action.docId, field: pending.action.field, message: error51.message };
15865
+ return { status: "rejected", action: "document.set-field", docId: pending.action.docId, field: pending.action.field, message: "the document no longer conforms to its governing Kind" };
15369
15866
  }
15370
15867
  if (error51 instanceof ActionBundleEditionChanged) {
15371
- return { status: "revoked", action: "document.set-field", docId: pending.action.docId, field: pending.action.field, message: error51.message };
15868
+ return { status: "revoked", action: "document.set-field", docId: pending.action.docId, field: pending.action.field, message: "the bundle OKF edition changed" };
15372
15869
  }
15373
- return { status: "failed", action: "document.set-field", docId: pending.action.docId, field: pending.action.field, message: error51 instanceof Error ? error51.message : String(error51) };
15870
+ return { status: "failed", action: "document.set-field", docId: pending.action.docId, field: pending.action.field, message: "the trusted action could not be committed" };
15374
15871
  }
15375
15872
  }
15376
15873
  size() {
@@ -15432,8 +15929,8 @@ async function proxyToRemote(request, remoteBase, apiKey, signal) {
15432
15929
  let upstream;
15433
15930
  try {
15434
15931
  upstream = await fetch(new Request(target, { method, headers, body: bodyBytes, signal }));
15435
- } catch (err) {
15436
- return freshErrorResponse(502, "RUNTIME", `could not reach remote ${remoteBase} (${err instanceof Error ? err.message : String(err)})`);
15932
+ } catch {
15933
+ return freshErrorResponse(502, "RUNTIME", "could not reach remote bundle server");
15437
15934
  }
15438
15935
  return new Response(upstream.body, {
15439
15936
  status: upstream.status,
@@ -15528,19 +16025,19 @@ function isEmptyChange(e) {
15528
16025
  return e.docs.changed.length === 0 && e.docs.removed.length === 0 && e.blobs.changed.length === 0 && e.blobs.removed.length === 0;
15529
16026
  }
15530
16027
  async function snapshotBundle(bundle) {
15531
- const heads = await queryHeads(bundle, {});
16028
+ const heads = await queryHeads2(bundle, {});
15532
16029
  const docs = new Map(heads.map((h2) => [h2.id, h2.version]));
15533
16030
  const blobs2 = /* @__PURE__ */ new Map();
15534
16031
  const keys = [];
15535
16032
  for (const prefix of PAGE_BLOB_PREFIXES) {
15536
16033
  try {
15537
- keys.push(...await listBlobs(bundle, prefix));
16034
+ keys.push(...await listBlobs2(bundle, prefix));
15538
16035
  } catch {
15539
16036
  }
15540
16037
  }
15541
16038
  for (const key of keys) {
15542
16039
  try {
15543
- const r2 = await readBlob(bundle, key);
16040
+ const r2 = await readBlob2(bundle, key);
15544
16041
  if (r2) blobs2.set(key, r2.version);
15545
16042
  } catch {
15546
16043
  }
@@ -15796,8 +16293,7 @@ async function servePageBytes(options2, runtime, nonce) {
15796
16293
  }
15797
16294
  function mintFailureResponse(options2, registryId, error51) {
15798
16295
  if (error51 instanceof ViewNotFoundError) {
15799
- const detail = error51.storageCause instanceof Error ? error51.storageCause.message : error51.message;
15800
- return jsonError(404, "RUNTIME", detail);
16296
+ return jsonError(404, "RUNTIME", error51.message);
15801
16297
  }
15802
16298
  if (error51 instanceof RegisteredViewLaunchError) {
15803
16299
  switch (error51.code) {
@@ -15821,7 +16317,7 @@ function mintFailureResponse(options2, registryId, error51) {
15821
16317
  return jsonError(403, "FORBIDDEN", error51.message);
15822
16318
  }
15823
16319
  }
15824
- return jsonError(500, "RUNTIME", error51 instanceof Error ? error51.message : String(error51));
16320
+ return jsonError(500, "RUNTIME", "the View could not be launched");
15825
16321
  }
15826
16322
  async function handleMint(req, runtime, options2) {
15827
16323
  let payload;
@@ -15842,18 +16338,18 @@ async function handleMint(req, runtime, options2) {
15842
16338
  if (!registryId && legacyKey) {
15843
16339
  try {
15844
16340
  assertSafeBlobKey(legacyKey);
15845
- } catch (error51) {
15846
- return jsonError(400, "USAGE", error51 instanceof Error ? error51.message : String(error51));
16341
+ } catch {
16342
+ return jsonError(400, "USAGE", "the View entry key is invalid");
15847
16343
  }
15848
16344
  const matches = [];
15849
16345
  try {
15850
- const heads = await queryHeads(options2.bundle, { type: "View" });
16346
+ const heads = await queryHeads2(options2.bundle, { type: "View" });
15851
16347
  for (const head of heads) {
15852
16348
  const registration = parseRegistration(head.id, head.frontmatter);
15853
16349
  if (registration?.entry === legacyKey) matches.push(registration.id);
15854
16350
  }
15855
- } catch (error51) {
15856
- return jsonError(502, "RUNTIME", `could not read the View registry (${error51 instanceof Error ? error51.message : String(error51)})`);
16351
+ } catch {
16352
+ return jsonError(502, "RUNTIME", "could not read the View registry");
15857
16353
  }
15858
16354
  registryId = matches.sort()[0] ?? "";
15859
16355
  if (!registryId) return jsonError(403, "FORBIDDEN", `'${legacyKey}' is not the entry of any valid registered View`);
@@ -15936,10 +16432,10 @@ async function sharingSummary(options2) {
15936
16432
  if (!options2.loadSharingSummary) return null;
15937
16433
  try {
15938
16434
  return await options2.loadSharingSummary();
15939
- } catch (err) {
16435
+ } catch {
15940
16436
  return {
15941
16437
  kind: "unavailable",
15942
- reason: err instanceof Error ? err.message : String(err),
16438
+ reason: "sharing status could not be loaded",
15943
16439
  as_of: (/* @__PURE__ */ new Date()).toISOString()
15944
16440
  };
15945
16441
  }
@@ -15958,7 +16454,7 @@ async function kindsResponse(options2) {
15958
16454
  try {
15959
16455
  const [registry2, version2] = await Promise.all([
15960
16456
  loadKinds(options2.bundle),
15961
- readBundleOkfVersion(options2.bundle)
16457
+ readBundleOkfVersion2(options2.bundle)
15962
16458
  ]);
15963
16459
  kinds2 = Array.from(registry2.kinds.values());
15964
16460
  okfVersion = version2 ?? "0.1";
@@ -15983,11 +16479,11 @@ async function viewsResponse(options2) {
15983
16479
  status: 200,
15984
16480
  headers: { "content-type": "application/json; charset=utf-8" }
15985
16481
  });
15986
- } catch (error51) {
16482
+ } catch {
15987
16483
  return jsonError(
15988
16484
  502,
15989
16485
  "RUNTIME",
15990
- `could not read the View catalog (${error51 instanceof Error ? error51.message : String(error51)})`
16486
+ "could not read the View catalog"
15991
16487
  );
15992
16488
  }
15993
16489
  }
@@ -16001,9 +16497,9 @@ async function edgesResponse(options2, url2) {
16001
16497
  if (text4) filter.text = text4;
16002
16498
  let links;
16003
16499
  try {
16004
- links = await queryEdges(options2.bundle, filter);
16005
- } catch (err) {
16006
- return jsonError(502, "RUNTIME", `could not read the bundle's edges (${err instanceof Error ? err.message : String(err)})`);
16500
+ links = await queryEdges2(options2.bundle, filter);
16501
+ } catch {
16502
+ return jsonError(502, "RUNTIME", "could not read the bundle's edges");
16007
16503
  }
16008
16504
  const edges = links.map((l) => ({ from: l.from, to: l.to, text: l.text }));
16009
16505
  return new Response(JSON.stringify({ edges, count: edges.length }), {
@@ -16304,10 +16800,10 @@ async function bootUiServer(options2) {
16304
16800
  return new Promise((resolve2, reject) => {
16305
16801
  const inFlight = /* @__PURE__ */ new Set();
16306
16802
  const server = createServer2((req, res) => {
16307
- const handled = handleRequest(req, res, options2, runtime, sessionSecret).catch((err) => {
16803
+ const handled = handleRequest(req, res, options2, runtime, sessionSecret).catch(() => {
16308
16804
  try {
16309
16805
  res.writeHead(500, { "content-type": "application/json; charset=utf-8" });
16310
- res.end(JSON.stringify({ error: { code: "RUNTIME", message: err instanceof Error ? err.message : String(err) } }));
16806
+ res.end(JSON.stringify({ error: { code: "RUNTIME", message: "internal server error" } }));
16311
16807
  } catch {
16312
16808
  res.destroy();
16313
16809
  }
@@ -54345,7 +54841,7 @@ function nonEmptyString2(value) {
54345
54841
  }
54346
54842
  async function deriveBundleDisplayName(bundle) {
54347
54843
  try {
54348
- const doc2 = await readDoc(bundle, BUNDLE_NAME_DOC_ID);
54844
+ const doc2 = await readDoc2(bundle, BUNDLE_NAME_DOC_ID);
54349
54845
  if (nonEmptyString2(doc2.frontmatter.type) === BUNDLE_NAME_DOC_TYPE) {
54350
54846
  const explicit = nonEmptyString2(doc2.frontmatter.name) ?? nonEmptyString2(doc2.frontmatter.title);
54351
54847
  if (explicit) return { name: explicit, source: "explicit" };
@@ -54619,7 +55115,7 @@ async function mutateCatalog(decide, options2) {
54619
55115
  schema_version: CATALOG_SCHEMA_VERSION,
54620
55116
  entries: [...result3.next.entries].sort((a, b) => a.label.localeCompare(b.label))
54621
55117
  };
54622
- await writeUserStateFileAtomic0600(home2, catalogDir(home2), CATALOG_FILE_NAME, JSON.stringify(next, null, 2) + "\n");
55118
+ await writeReadyUserStateFileAtomic0600(home2, CATALOG_FILE_NAME, JSON.stringify(next, null, 2) + "\n");
54623
55119
  }
54624
55120
  return { value: result3.value, changed: result3.changed };
54625
55121
  } finally {
@@ -56583,7 +57079,7 @@ async function runManagedDocumentUi({ values, positionals }, deps) {
56583
57079
  const bundle = route.bundle;
56584
57080
  const documentId = await resolveConceptIdCliArgument(bundle, rawDocumentId);
56585
57081
  try {
56586
- await readDocVersioned(bundle, documentId);
57082
+ await readDocVersioned2(bundle, documentId);
56587
57083
  } catch (error51) {
56588
57084
  throw readErrorToCliError(error51, documentId, void 0);
56589
57085
  }
@@ -56711,7 +57207,7 @@ async function runUi({ values, positionals }, deps, entry) {
56711
57207
  rootLabel = base;
56712
57208
  } else {
56713
57209
  bundle = deps.localBundle ?? await openBundle(values.dir);
56714
- const router = createRouter(bundle);
57210
+ const router = createRouter2(bundle);
56715
57211
  options2 = {
56716
57212
  mode: "dir",
56717
57213
  port,
@@ -56729,7 +57225,7 @@ async function runUi({ values, positionals }, deps, entry) {
56729
57225
  const resolvedDocumentId = await resolveConceptIdCliArgument(bundle, rawDocumentId);
56730
57226
  documentId = resolvedDocumentId;
56731
57227
  try {
56732
- await readDocVersioned(bundle, resolvedDocumentId);
57228
+ await readDocVersioned2(bundle, resolvedDocumentId);
56733
57229
  } catch (error51) {
56734
57230
  throw readErrorToCliError(error51, resolvedDocumentId, values.remote);
56735
57231
  }
@@ -59117,21 +59613,21 @@ async function createRecipeDocument(bundle, doc2, okfVersion, now) {
59117
59613
  return result3.doc;
59118
59614
  }
59119
59615
  async function findLegacyViewConvention(bundle) {
59120
- const conventions = await query(bundle, { prefix: CONVENTIONS_PREFIX, type: "Convention" });
59616
+ const conventions = await query2(bundle, { prefix: CONVENTIONS_PREFIX, type: "Convention" });
59121
59617
  for (const doc2 of conventions) {
59122
59618
  if (governsKind(doc2, LEGACY_VIEW_KIND_NAME)) return doc2.id;
59123
59619
  }
59124
59620
  return null;
59125
59621
  }
59126
59622
  async function applyRecipe(bundle, recipe2, now = (/* @__PURE__ */ new Date()).toISOString()) {
59127
- const okfVersion = await readBundleOkfVersion(bundle) ?? "0.1";
59623
+ const okfVersion = await readBundleOkfVersion2(bundle) ?? "0.1";
59128
59624
  recipe2 = materializeRecipeForEdition(recipe2, okfVersion);
59129
59625
  await assertPortableTargetsCompatible(bundle, recipe2, now, okfVersion);
59130
59626
  const legacyConventionId = recipe2.docs.some((d2) => governsKind(d2, VIEW_KIND_NAME)) ? await findLegacyViewConvention(bundle) : null;
59131
59627
  let legacyRegistryDocs = null;
59132
59628
  const legacyRegistryDoc = async (id) => {
59133
59629
  legacyRegistryDocs ??= new Map(
59134
- (await query(bundle, { prefix: PAGE_REGISTRY_PREFIX })).map((doc2) => [doc2.id, doc2])
59630
+ (await query2(bundle, { prefix: PAGE_REGISTRY_PREFIX })).map((doc2) => [doc2.id, doc2])
59135
59631
  );
59136
59632
  return legacyRegistryDocs.get(id);
59137
59633
  };
@@ -59155,7 +59651,7 @@ async function applyRecipe(bundle, recipe2, now = (/* @__PURE__ */ new Date()).t
59155
59651
  doc2 = await createRecipeDocument(bundle, doc2, okfVersion, now);
59156
59652
  } catch (err) {
59157
59653
  if (err instanceof VersionConflict) {
59158
- const existing = await readDoc(bundle, doc2.id);
59654
+ const existing = await readDoc2(bundle, doc2.id);
59159
59655
  if (!sameInstalledDoc(existing, doc2, okfVersion)) {
59160
59656
  sourceDiffers2 = true;
59161
59657
  migrationWarnings.push({
@@ -59177,7 +59673,7 @@ async function applyRecipe(bundle, recipe2, now = (/* @__PURE__ */ new Date()).t
59177
59673
  const entryAlias = legacyEntryAlias(page.entry);
59178
59674
  const aliasDoc = registryAlias !== null && entryAlias !== null ? await legacyRegistryDoc(registryAlias) : void 0;
59179
59675
  if (registryAlias !== null && entryAlias !== null && aliasDoc !== void 0) {
59180
- const legacyBlob = await readBlob(bundle, entryAlias);
59676
+ const legacyBlob = await readBlob2(bundle, entryAlias);
59181
59677
  if (legacyBlob !== null) {
59182
59678
  const registers = parseRegistration(aliasDoc.id, aliasDoc.frontmatter) !== null;
59183
59679
  if (registers) {
@@ -59210,10 +59706,10 @@ async function applyRecipe(bundle, recipe2, now = (/* @__PURE__ */ new Date()).t
59210
59706
  const desiredBytes = Buffer.from(page.html, "utf8");
59211
59707
  let entryChanged = true;
59212
59708
  try {
59213
- await writeBlob(bundle, page.entry, desiredBytes, void 0, { expectedVersion: null });
59709
+ await writeBlob2(bundle, page.entry, desiredBytes, void 0, { expectedVersion: null });
59214
59710
  } catch (err) {
59215
59711
  if (!(err instanceof VersionConflict)) throw err;
59216
- const existing = await readBlob(bundle, page.entry);
59712
+ const existing = await readBlob2(bundle, page.entry);
59217
59713
  const sameBytes = existing !== null && Buffer.from(existing.bytes).equals(desiredBytes);
59218
59714
  const sameContentType = existing?.contentType === resolveContentType(page.entry);
59219
59715
  if (!sameBytes || !sameContentType) throw recipeAssetConflict(recipe2.id, page.entry);
@@ -59225,7 +59721,7 @@ async function applyRecipe(bundle, recipe2, now = (/* @__PURE__ */ new Date()).t
59225
59721
  registry2 = await createRecipeDocument(bundle, registry2, okfVersion, now);
59226
59722
  } catch (err) {
59227
59723
  if (!(err instanceof VersionConflict)) throw err;
59228
- const existing = await readDoc(bundle, registry2.id);
59724
+ const existing = await readDoc2(bundle, registry2.id);
59229
59725
  if (!sameInstalledDoc(existing, registry2, okfVersion)) throw recipeAssetConflict(recipe2.id, `${registry2.id}.md`);
59230
59726
  registryChanged = false;
59231
59727
  }
@@ -59245,7 +59741,7 @@ async function applyRecipe(bundle, recipe2, now = (/* @__PURE__ */ new Date()).t
59245
59741
  desired = await createRecipeDocument(bundle, desired, okfVersion, now);
59246
59742
  } catch (err) {
59247
59743
  if (!(err instanceof VersionConflict)) throw err;
59248
- const existing = await readDoc(bundle, desired.id);
59744
+ const existing = await readDoc2(bundle, desired.id);
59249
59745
  if (!sameInstalledDoc(existing, desired, okfVersion)) throw recipeAssetConflict(recipe2.id, `${desired.id}.md`);
59250
59746
  changed = false;
59251
59747
  }
@@ -59282,12 +59778,12 @@ async function assertPortableTargetsCompatible(bundle, recipe2, now, okfVersion)
59282
59778
  const registries = /* @__PURE__ */ new Map();
59283
59779
  if (recipe2.pages.length > 0) {
59284
59780
  for (const prefix of [PAGE_REGISTRY_PREFIX, VIEW_REGISTRY_PREFIX]) {
59285
- const registryDocs = await query(bundle, { prefix });
59781
+ const registryDocs = await query2(bundle, { prefix });
59286
59782
  for (const doc2 of registryDocs) registries.set(doc2.id, doc2);
59287
59783
  }
59288
59784
  }
59289
59785
  for (const page of recipe2.pages) {
59290
- const existingBlob = await readBlob(bundle, page.entry);
59786
+ const existingBlob = await readBlob2(bundle, page.entry);
59291
59787
  if (existingBlob) {
59292
59788
  const desiredBytes = Buffer.from(page.html, "utf8");
59293
59789
  const sameBytes = Buffer.from(existingBlob.bytes).equals(desiredBytes);
@@ -59304,7 +59800,7 @@ async function assertPortableTargetsCompatible(bundle, recipe2, now, okfVersion)
59304
59800
  }
59305
59801
  const installedReferences = /* @__PURE__ */ new Map();
59306
59802
  if (recipe2.references.length > 0) {
59307
- const referenceDocs = await query(bundle, { prefix: "references/" });
59803
+ const referenceDocs = await query2(bundle, { prefix: "references/" });
59308
59804
  for (const doc2 of referenceDocs) installedReferences.set(doc2.id, doc2);
59309
59805
  }
59310
59806
  for (const reference of recipe2.references) {
@@ -59337,7 +59833,7 @@ function recipeAssetConflict(recipeId, key) {
59337
59833
  );
59338
59834
  }
59339
59835
  async function appliedConventionDocs(bundle) {
59340
- const docs = await query(bundle, { prefix: CONVENTIONS_PREFIX });
59836
+ const docs = await query2(bundle, { prefix: CONVENTIONS_PREFIX });
59341
59837
  return new Map(docs.map((d2) => [d2.id, d2]));
59342
59838
  }
59343
59839
  function recipeDrifts(recipe2, installed, okfVersion, now) {
@@ -60082,19 +60578,34 @@ var init_recipe_source_builtin = __esm({
60082
60578
  });
60083
60579
 
60084
60580
  // src/recipe-source-filesystem.ts
60085
- import { promises as fs4 } from "node:fs";
60581
+ import { constants as constants4, promises as fs4 } from "node:fs";
60086
60582
  import path22 from "node:path";
60583
+ async function readContainedFile(real) {
60584
+ const opened = await fs4.open(real, CONTAINED_FLAGS).then(
60585
+ (handle2) => ({ handle: handle2 }),
60586
+ (error51) => ({ code: error51.code })
60587
+ );
60588
+ if (!("handle" in opened)) return { refusal: opened.code === "ELOOP" ? "irregular" : "unreadable" };
60589
+ const handle = opened.handle;
60590
+ try {
60591
+ if (!(await handle.stat()).isFile()) return { refusal: "irregular" };
60592
+ return { text: await handle.readFile("utf8") };
60593
+ } catch {
60594
+ return { refusal: "unreadable" };
60595
+ } finally {
60596
+ await handle.close();
60597
+ }
60598
+ }
60087
60599
  async function readRecipeDir(root) {
60088
60600
  const files = [];
60089
60601
  const rootReal = await fs4.realpath(root);
60090
60602
  const manifestPath = path22.join(root, "recipe.md");
60091
60603
  const manifestStat = await fs4.stat(manifestPath).catch(() => null);
60092
60604
  if (manifestStat?.isFile()) {
60093
- const manifestReal = await fs4.realpath(manifestPath).catch(() => null);
60094
- if (!manifestReal || manifestReal !== rootReal && !manifestReal.startsWith(rootReal + path22.sep)) {
60095
- throw new RecipeUnsafePathSignal("recipe.md");
60096
- }
60097
- const bytes = await fs4.readFile(manifestPath, "utf8");
60605
+ const manifestReal = await containedRealpath(manifestPath, rootReal, "recipe.md");
60606
+ const read = await readContainedFile(manifestReal);
60607
+ if ("refusal" in read) throw new RecipeUnsafePathSignal("recipe.md", read.refusal);
60608
+ const bytes = read.text;
60098
60609
  files.push({ path: "recipe.md", bytes });
60099
60610
  const { frontmatter } = parseMarkdown(bytes);
60100
60611
  if (frontmatter.content_policy === "definitions-only" || frontmatter.pages !== void 0) {
@@ -60123,13 +60634,10 @@ async function walkRecipeFiles(dir, relPrefix, rootReal, out, skip) {
60123
60634
  continue;
60124
60635
  }
60125
60636
  if (!entry.isFile() && !entry.isSymbolicLink()) continue;
60126
- const real = await fs4.realpath(abs).catch(() => null);
60127
- if (!real || real !== rootReal && !real.startsWith(rootReal + path22.sep)) {
60128
- throw new RecipeUnsafePathSignal(rel);
60129
- }
60130
- const stat6 = await fs4.stat(real).catch(() => null);
60131
- if (!stat6?.isFile()) throw new RecipeUnsafePathSignal(rel);
60132
- out.push({ path: rel, bytes: await fs4.readFile(abs, "utf8") });
60637
+ const real = await containedRealpath(abs, rootReal, rel);
60638
+ const read = await readContainedFile(real);
60639
+ if ("refusal" in read) throw new RecipeUnsafePathSignal(rel, read.refusal);
60640
+ out.push({ path: rel, bytes: read.text });
60133
60641
  }
60134
60642
  }
60135
60643
  async function walkConventions(dir, relPrefix, rootReal, out) {
@@ -60143,11 +60651,32 @@ async function walkConventions(dir, relPrefix, rootReal, out) {
60143
60651
  }
60144
60652
  if (!entry.isFile() && !entry.isSymbolicLink()) continue;
60145
60653
  if (!rel.endsWith(".md")) continue;
60146
- const real = await fs4.realpath(abs).catch(() => null);
60147
- if (!real || real !== rootReal && !real.startsWith(rootReal + path22.sep)) {
60148
- throw new RecipeUnsafePathSignal(rel);
60149
- }
60150
- out.push({ path: rel, bytes: await fs4.readFile(abs, "utf8") });
60654
+ const real = await containedRealpath(abs, rootReal, rel);
60655
+ const read = await readContainedFile(real);
60656
+ if ("refusal" in read) throw new RecipeUnsafePathSignal(rel, read.refusal);
60657
+ out.push({ path: rel, bytes: read.text });
60658
+ }
60659
+ }
60660
+ async function containedRealpath(abs, rootReal, rel) {
60661
+ const real = await fs4.realpath(abs).catch(() => null);
60662
+ if (!real) throw new RecipeUnsafePathSignal(rel, "unresolvable");
60663
+ if (real !== rootReal && !real.startsWith(rootReal + path22.sep)) {
60664
+ throw new RecipeUnsafePathSignal(rel, "symlink-escape");
60665
+ }
60666
+ return real;
60667
+ }
60668
+ function refusalMessage(ref, err) {
60669
+ switch (err.reason) {
60670
+ case "dot-entry":
60671
+ return `recipe folder '${ref}' contains a dot-prefixed path, which the recipe grammar can never accept: '${err.rel}'`;
60672
+ case "irregular":
60673
+ return `recipe folder '${ref}' contains a path that is not a regular file: '${err.rel}'`;
60674
+ case "unreadable":
60675
+ return `recipe folder '${ref}' contains a file that could not be opened for reading (check its permissions): '${err.rel}'`;
60676
+ case "symlink-escape":
60677
+ return `recipe folder '${ref}' contains a symlink escaping the recipe root: '${err.rel}'`;
60678
+ case "unresolvable":
60679
+ return `recipe folder '${ref}' contains a path that does not resolve, most often a symlink whose target is gone: '${err.rel}'`;
60151
60680
  }
60152
60681
  }
60153
60682
  function filesRecipeSource() {
@@ -60169,7 +60698,7 @@ function filesRecipeSource() {
60169
60698
  files = await readRecipeDir(real);
60170
60699
  } catch (err) {
60171
60700
  if (err instanceof RecipeUnsafePathSignal) {
60172
- const message = err.reason === "dot-entry" ? `recipe folder '${ref}' contains a dot-prefixed path, which the recipe grammar can never accept: '${err.rel}'` : `recipe folder '${ref}' contains a symlink escaping the recipe root: '${err.rel}'`;
60701
+ const message = refusalMessage(ref, err);
60173
60702
  return { ok: false, error: { code: "RECIPE_UNSAFE_PATH", message } };
60174
60703
  }
60175
60704
  throw err;
@@ -60178,7 +60707,7 @@ function filesRecipeSource() {
60178
60707
  }
60179
60708
  };
60180
60709
  }
60181
- var RecipeUnsafePathSignal;
60710
+ var CONTAINED_FLAGS, RecipeUnsafePathSignal;
60182
60711
  var init_recipe_source_filesystem = __esm({
60183
60712
  "src/recipe-source-filesystem.ts"() {
60184
60713
  "use strict";
@@ -60187,6 +60716,7 @@ var init_recipe_source_filesystem = __esm({
60187
60716
  init_src();
60188
60717
  init_recipe_parser();
60189
60718
  init_recipe_ref();
60719
+ CONTAINED_FLAGS = constants4.O_RDONLY | (constants4.O_NOFOLLOW ?? 0) | (constants4.O_NONBLOCK ?? 0);
60190
60720
  RecipeUnsafePathSignal = class extends Error {
60191
60721
  rel;
60192
60722
  reason;
@@ -60537,9 +61067,9 @@ function computeDroppedLinks(existingLinks, nextLinks) {
60537
61067
  return dropped;
60538
61068
  }
60539
61069
  function droppedLinks(bundle, existing, nextBody) {
60540
- const existingLinks = parseLinks(bundle, existing);
61070
+ const existingLinks = parseLinks2(bundle, existing);
60541
61071
  if (existingLinks.length === 0) return [];
60542
- return computeDroppedLinks(existingLinks, parseLinks(bundle, { ...existing, body: nextBody }));
61072
+ return computeDroppedLinks(existingLinks, parseLinks2(bundle, { ...existing, body: nextBody }));
60543
61073
  }
60544
61074
  function guardDroppedLinks(bundle, existing, nextBody, replaceLinks) {
60545
61075
  if (replaceLinks) return;
@@ -60596,7 +61126,7 @@ async function docExistsForMode(bundle, id, mode) {
60596
61126
  if (mode === "patch") return true;
60597
61127
  if (mode === "create-only") return false;
60598
61128
  try {
60599
- await readDoc(bundle, id);
61129
+ await readDoc2(bundle, id);
60600
61130
  return true;
60601
61131
  } catch {
60602
61132
  return false;
@@ -61441,7 +61971,7 @@ async function docReadInner(argv2, deps) {
61441
61971
  let parsed;
61442
61972
  let version2;
61443
61973
  try {
61444
- ({ doc: parsed, version: version2 } = await readDocVersioned(bundle, id));
61974
+ ({ doc: parsed, version: version2 } = await readDocVersioned2(bundle, id));
61445
61975
  } catch (err) {
61446
61976
  throw readErrorToCliError(err, id, values.remote);
61447
61977
  }
@@ -61481,7 +62011,7 @@ async function docReadInner(argv2, deps) {
61481
62011
  let parsed;
61482
62012
  let version2;
61483
62013
  try {
61484
- ({ doc: parsed, version: version2 } = await readDocVersioned(bundle, id));
62014
+ ({ doc: parsed, version: version2 } = await readDocVersioned2(bundle, id));
61485
62015
  } catch (err) {
61486
62016
  throw readErrorToCliError(err, id, values.remote);
61487
62017
  }
@@ -61514,7 +62044,7 @@ async function docReadInner(argv2, deps) {
61514
62044
  let parsed;
61515
62045
  let version2;
61516
62046
  try {
61517
- ({ doc: parsed, version: version2 } = await readDocVersioned(bundle, id));
62047
+ ({ doc: parsed, version: version2 } = await readDocVersioned2(bundle, id));
61518
62048
  } catch (err) {
61519
62049
  throw readErrorToCliError(err, id, values.remote);
61520
62050
  }
@@ -61531,7 +62061,7 @@ async function docReadInner(argv2, deps) {
61531
62061
  let parsed;
61532
62062
  let version2;
61533
62063
  try {
61534
- ({ doc: parsed, version: version2 } = await readDocVersioned(bundle, id));
62064
+ ({ doc: parsed, version: version2 } = await readDocVersioned2(bundle, id));
61535
62065
  } catch (err) {
61536
62066
  throw readErrorToCliError(err, id, values.remote);
61537
62067
  }
@@ -61563,7 +62093,7 @@ async function docReadInner(argv2, deps) {
61563
62093
  if (bundle.backend) {
61564
62094
  let parsed;
61565
62095
  try {
61566
- parsed = await readDoc(bundle, id);
62096
+ parsed = await readDoc2(bundle, id);
61567
62097
  } catch (err) {
61568
62098
  throw readErrorToCliError(err, id, values.remote);
61569
62099
  }
@@ -61696,7 +62226,7 @@ async function docHistory(argv2, deps) {
61696
62226
  id = await resolveConceptIdCliArgument(bundle, rawId);
61697
62227
  let versions;
61698
62228
  try {
61699
- versions = await docVersions(bundle, id);
62229
+ versions = await docVersions2(bundle, id);
61700
62230
  } catch (err) {
61701
62231
  throw readErrorToCliError(err, id, values.remote);
61702
62232
  }
@@ -61812,7 +62342,7 @@ async function docDelete(argv2, deps) {
61812
62342
  const expectedVersion = rawExpected?.trim();
61813
62343
  let deleted;
61814
62344
  try {
61815
- deleted = await deleteDoc(bundle, id, expectedVersion ? { expectedVersion } : void 0);
62345
+ deleted = await deleteDoc2(bundle, id, expectedVersion ? { expectedVersion } : void 0);
61816
62346
  } catch (err) {
61817
62347
  if (err instanceof VersionConflict) {
61818
62348
  throw new CliError(
@@ -62055,7 +62585,7 @@ async function promoteBlob(file2, key, bundle, opts, stdout, mode, remoteUrl) {
62055
62585
  }
62056
62586
  let version2;
62057
62587
  try {
62058
- version2 = await writeBlob(bundle, key, bytes, opts.contentType, { expectedVersion: opts.expectedVersion });
62588
+ version2 = await writeBlob2(bundle, key, bytes, opts.contentType, { expectedVersion: opts.expectedVersion });
62059
62589
  } catch (err) {
62060
62590
  throw promoteWriteErrorToCliError(err, key, file2, remoteUrl);
62061
62591
  }
@@ -62195,7 +62725,7 @@ async function pullDoc(bundle, key, remoteUrl) {
62195
62725
  const id = conceptIdFromPath(canonicalPath);
62196
62726
  let result3;
62197
62727
  try {
62198
- result3 = await readDocVersioned(bundle, id);
62728
+ result3 = await readDocVersioned2(bundle, id);
62199
62729
  } catch (err) {
62200
62730
  throw readErrorToCliError(err, id, remoteUrl);
62201
62731
  }
@@ -62215,7 +62745,7 @@ async function pullDoc(bundle, key, remoteUrl) {
62215
62745
  async function pullBlob(bundle, key, remoteUrl) {
62216
62746
  let result3;
62217
62747
  try {
62218
- result3 = await readBlob(bundle, key);
62748
+ result3 = await readBlob2(bundle, key);
62219
62749
  } catch (err) {
62220
62750
  throw classifyBundleError(err, remoteUrl);
62221
62751
  }
@@ -62398,7 +62928,7 @@ async function blobs(argv2, deps = {}) {
62398
62928
  limit = Number(raw);
62399
62929
  }
62400
62930
  const bundle = await openBundle(values.dir, await resolveRemoteFlag(values.remote, values.dir));
62401
- const keys = (await listBlobs(bundle, values.prefix?.trim() || void 0)).slice().sort();
62931
+ const keys = (await listBlobs2(bundle, values.prefix?.trim() || void 0)).slice().sort();
62402
62932
  const total = keys.length;
62403
62933
  const shownKeys = limit > 0 ? keys.slice(0, limit) : keys;
62404
62934
  const truncated = shownKeys.length < total;
@@ -62500,9 +63030,9 @@ async function deleteCommand(argv2, deps = {}) {
62500
63030
  if (docRoute) {
62501
63031
  const canonicalPath = key.slice(0, -3) + ".md";
62502
63032
  const id = conceptIdFromPath(canonicalPath);
62503
- deleted = await deleteDoc(bundle, id, expectedVersion ? { expectedVersion } : void 0);
63033
+ deleted = await deleteDoc2(bundle, id, expectedVersion ? { expectedVersion } : void 0);
62504
63034
  } else {
62505
- deleted = await deleteBlob(bundle, key, expectedVersion ? { expectedVersion } : void 0);
63035
+ deleted = await deleteBlob2(bundle, key, expectedVersion ? { expectedVersion } : void 0);
62506
63036
  }
62507
63037
  } catch (err) {
62508
63038
  throw deleteErrorToCliError(err, key, values.remote);
@@ -62609,7 +63139,7 @@ async function lintLinkType(bundle, args, registry2) {
62609
63139
  let targetType;
62610
63140
  let targetResolved = true;
62611
63141
  try {
62612
- targetType = docType(await readDoc(bundle, args.to));
63142
+ targetType = docType(await readDoc2(bundle, args.to));
62613
63143
  } catch (err) {
62614
63144
  if (err?.code === "ENOENT") {
62615
63145
  targetResolved = false;
@@ -62649,7 +63179,7 @@ async function lintLinkType(bundle, args, registry2) {
62649
63179
  async function assertTargetNotAlias(bundle, to, remoteUrl) {
62650
63180
  if (remoteUrl !== void 0) return;
62651
63181
  try {
62652
- await readDoc(bundle, to);
63182
+ await readDoc2(bundle, to);
62653
63183
  } catch (err) {
62654
63184
  if (err instanceof FilesystemIdentityAliasError) throw err;
62655
63185
  }
@@ -62657,7 +63187,7 @@ async function assertTargetNotAlias(bundle, to, remoteUrl) {
62657
63187
  async function targetAbsentWarning(bundle, to, remoteUrl) {
62658
63188
  if (remoteUrl !== void 0) return void 0;
62659
63189
  try {
62660
- await readDoc(bundle, to);
63190
+ await readDoc2(bundle, to);
62661
63191
  return void 0;
62662
63192
  } catch (err) {
62663
63193
  if (err?.code !== "ENOENT") throw err;
@@ -62725,7 +63255,7 @@ async function addLink(bundle, from, to, opts = {}) {
62725
63255
  buildCandidate: (source, context) => {
62726
63256
  const existing = source;
62727
63257
  sourceTypeAtWrite = docType(existing);
62728
- const already = parseLinks(bundle, existing).some((l) => l.to === normalizedTo && l.text === text4);
63258
+ const already = parseLinks2(bundle, existing).some((l) => l.to === normalizedTo && l.text === text4);
62729
63259
  if (already) return { frontmatter: { ...existing.frontmatter }, body: existing.body };
62730
63260
  const trimmed = existing.body.replace(/\s*$/, "");
62731
63261
  const nextBody = `${trimmed}${trimmed ? "\n\n" : ""}[${text4}](${href})
@@ -62899,8 +63429,8 @@ async function linkShow(argv2, stdout, autoPull) {
62899
63429
  let exists2 = !impossibleExactId;
62900
63430
  if (!impossibleExactId) {
62901
63431
  try {
62902
- const source = await readDoc(bundle, id);
62903
- outbound = parseLinks(bundle, source).map((l) => ({ to: l.to, text: l.text, href: l.href }));
63432
+ const source = await readDoc2(bundle, id);
63433
+ outbound = parseLinks2(bundle, source).map((l) => ({ to: l.to, text: l.text, href: l.href }));
62904
63434
  } catch (err) {
62905
63435
  if (err?.code !== "ENOENT") {
62906
63436
  throw classifyBundleError(err, values.remote);
@@ -62908,7 +63438,7 @@ async function linkShow(argv2, stdout, autoPull) {
62908
63438
  exists2 = false;
62909
63439
  }
62910
63440
  }
62911
- const inbound = await backlinks(bundle, id);
63441
+ const inbound = await backlinks2(bundle, id);
62912
63442
  const textsPresent = textFilter === void 0 ? [] : [...new Set([...outbound, ...inbound].map((l) => l.text))].sort((a, b) => a.localeCompare(b));
62913
63443
  if (textFilter !== void 0) {
62914
63444
  outbound = outbound.filter((l) => l.text === textFilter);
@@ -63012,7 +63542,7 @@ async function linkList(argv2, stdout) {
63012
63542
  if (toSelectors.length > 0) scopeFilter.to = toSelectors;
63013
63543
  let scopedEdges;
63014
63544
  try {
63015
- scopedEdges = await queryEdges(bundle, scopeFilter);
63545
+ scopedEdges = await queryEdges2(bundle, scopeFilter);
63016
63546
  } catch (err) {
63017
63547
  throw classifyBundleError(err, values.remote);
63018
63548
  }
@@ -63271,7 +63801,7 @@ async function list2(argv2, deps = {}) {
63271
63801
  if (!remote) await (deps.autoPull ?? maybeAutoPull2)(values.dir);
63272
63802
  const bundle = await openBundle(values.dir, remote);
63273
63803
  const skipped = [];
63274
- let docs = await queryHeads(bundle, filter, { onSkip: (s) => skipped.push(s) });
63804
+ let docs = await queryHeads2(bundle, filter, { onSkip: (s) => skipped.push(s) });
63275
63805
  let registryCache;
63276
63806
  const getRegistry = async () => {
63277
63807
  registryCache ??= await loadKinds(bundle);
@@ -63281,7 +63811,7 @@ async function list2(argv2, deps = {}) {
63281
63811
  let okfVersionCache;
63282
63812
  const getOkfVersion = async () => {
63283
63813
  if (!okfVersionLoaded) {
63284
- okfVersionCache = await readBundleOkfVersion(bundle);
63814
+ okfVersionCache = await readBundleOkfVersion2(bundle);
63285
63815
  okfVersionLoaded = true;
63286
63816
  }
63287
63817
  return okfVersionCache;
@@ -63814,7 +64344,7 @@ async function newCommand(argv2, deps = {}) {
63814
64344
  if (route) await assertResolvedLocalRouteIdentity(route);
63815
64345
  const [registry2, okfVersion] = await Promise.all([
63816
64346
  loadKinds(bundle),
63817
- readBundleOkfVersion(bundle)
64347
+ readBundleOkfVersion2(bundle)
63818
64348
  ]);
63819
64349
  const resolvedKind = registry2.kinds.get(kindName);
63820
64350
  const kind2 = resolvedKind && (pre.values.help || kindDeclaresAnything(resolvedKind)) ? resolvedKind : void 0;
@@ -64199,7 +64729,7 @@ async function kinds(argv2, deps = {}) {
64199
64729
  const bundle = await openBundle(values.dir, await resolveRemoteFlag(values.remote, values.dir));
64200
64730
  const [registry2, okfVersion] = await Promise.all([
64201
64731
  loadKinds(bundle),
64202
- readBundleOkfVersion(bundle)
64732
+ readBundleOkfVersion2(bundle)
64203
64733
  ]);
64204
64734
  const rows = [...registry2.kinds.values()].sort((a, b) => a.governs.localeCompare(b.governs)).map((kind2) => toRow(kind2, okfVersion));
64205
64735
  const out = { count: rows.length, kinds: rows };
@@ -64338,7 +64868,7 @@ function inferredBody(type, count) {
64338
64868
  }
64339
64869
  async function prepareDraftPlan(bundle, type) {
64340
64870
  const inv = cliInvocation();
64341
- const [registry2, okfVersionRead] = await Promise.all([loadKinds(bundle), readBundleOkfVersion(bundle)]);
64871
+ const [registry2, okfVersionRead] = await Promise.all([loadKinds(bundle), readBundleOkfVersion2(bundle)]);
64342
64872
  const okfVersion = okfVersionRead ?? "0.1";
64343
64873
  const existing = registry2.kinds.get(type);
64344
64874
  if (existing && kindDeclaresAnything(existing)) {
@@ -64348,7 +64878,7 @@ async function prepareDraftPlan(bundle, type) {
64348
64878
  { help: `${inv} kind field ${commandQuoted(type)} add <name>` }
64349
64879
  );
64350
64880
  }
64351
- const instances = (await query(bundle, { type })).sort((a, b) => a.id.localeCompare(b.id));
64881
+ const instances = (await query2(bundle, { type })).sort((a, b) => a.id.localeCompare(b.id));
64352
64882
  if (instances.length === 0) {
64353
64883
  throw new CliError(
64354
64884
  "USAGE",
@@ -64513,7 +65043,7 @@ async function kindDismissCommand(type, values, stdout) {
64513
65043
  const inv = cliInvocation();
64514
65044
  const suffix = targetSuffix(values);
64515
65045
  const bundle = await openBundle(values.dir, await resolveRemoteFlag(values.remote, values.dir));
64516
- const [registry2, okfVersionRead] = await Promise.all([loadKinds(bundle), readBundleOkfVersion(bundle)]);
65046
+ const [registry2, okfVersionRead] = await Promise.all([loadKinds(bundle), readBundleOkfVersion2(bundle)]);
64517
65047
  const okfVersion = okfVersionRead ?? "0.1";
64518
65048
  const existing = registry2.kinds.get(type);
64519
65049
  if (existing && kindDeclaresAnything(existing)) {
@@ -64776,7 +65306,7 @@ async function kind(argv2, deps = {}) {
64776
65306
  }
64777
65307
  }
64778
65308
  const bundle = await openBundle(values.dir, await resolveRemoteFlag(values.remote, values.dir));
64779
- const [registry2, okfVersion] = await Promise.all([loadKinds(bundle), readBundleOkfVersion(bundle)]);
65309
+ const [registry2, okfVersion] = await Promise.all([loadKinds(bundle), readBundleOkfVersion2(bundle)]);
64780
65310
  const target = registry2.kinds.get(kindName);
64781
65311
  if (!target) {
64782
65312
  const known = [...registry2.kinds.keys()].sort();
@@ -65051,7 +65581,7 @@ async function recipes(argv2, deps = {}) {
65051
65581
  const bundle = await optionalBundle(values, resolvedDeps);
65052
65582
  const installed = bundle ? await appliedConventionDocs(bundle) : void 0;
65053
65583
  const appliedIds = installed === void 0 ? void 0 : new Set(installed.keys());
65054
- const okfVersion = bundle ? await readBundleOkfVersion(bundle) ?? "0.1" : void 0;
65584
+ const okfVersion = bundle ? await readBundleOkfVersion2(bundle) ?? "0.1" : void 0;
65055
65585
  const now = (/* @__PURE__ */ new Date()).toISOString();
65056
65586
  const inv = cliInvocation();
65057
65587
  const rows = [];
@@ -65254,7 +65784,7 @@ function additiveConventionCandidate(existing, desired, blockers) {
65254
65784
  }
65255
65785
  async function readRecipeDocIfPresent(bundle, id) {
65256
65786
  try {
65257
- return await readDocVersioned(bundle, id);
65787
+ return await readDocVersioned2(bundle, id);
65258
65788
  } catch (error51) {
65259
65789
  if (error51 instanceof DocumentNotFoundError || error51?.code === "ENOENT") return null;
65260
65790
  throw error51;
@@ -65344,7 +65874,7 @@ function evolutionPlanToken(input) {
65344
65874
  return `sha256:${createHash9("sha256").update(JSON.stringify(input), "utf8").digest("hex")}`;
65345
65875
  }
65346
65876
  async function prepareRecipeEvolution(bundle, sourceRecipe) {
65347
- const okfVersion = await readBundleOkfVersion(bundle) ?? "0.1";
65877
+ const okfVersion = await readBundleOkfVersion2(bundle) ?? "0.1";
65348
65878
  const recipe2 = materializeRecipeForEdition(sourceRecipe, okfVersion);
65349
65879
  const blockers = recipe2.warnings.map((warning) => ({
65350
65880
  code: warning.code,
@@ -65357,7 +65887,7 @@ async function prepareRecipeEvolution(bundle, sourceRecipe) {
65357
65887
  const proofs = [];
65358
65888
  const desiredKinds = /* @__PURE__ */ new Map();
65359
65889
  const skippedConventions = [];
65360
- const installedConventions = await query(bundle, { prefix: CONVENTIONS_PREFIX, type: "Convention" }, {
65890
+ const installedConventions = await query2(bundle, { prefix: CONVENTIONS_PREFIX, type: "Convention" }, {
65361
65891
  onSkip: (skipped) => skippedConventions.push(skipped)
65362
65892
  });
65363
65893
  for (const skipped of skippedConventions) {
@@ -65541,7 +66071,7 @@ async function prepareRecipeEvolution(bundle, sourceRecipe) {
65541
66071
  for (const reference of recipe2.references) await assetDocProof("reference", reference.doc);
65542
66072
  for (const page of recipe2.pages) {
65543
66073
  await assetDocProof("view-registry", page.registry);
65544
- const existing = await readBlob(bundle, page.entry);
66074
+ const existing = await readBlob2(bundle, page.entry);
65545
66075
  const wantedBytes = Buffer.from(page.html, "utf8");
65546
66076
  const wanted = blobVersion(wantedBytes);
65547
66077
  proofs.push({ kind: "view-entry", id: page.entry, current_version: existing?.version ?? null, desired_version: wanted });
@@ -65566,7 +66096,7 @@ async function prepareRecipeEvolution(bundle, sourceRecipe) {
65566
66096
  const instanceProofs = [];
65567
66097
  if (changingKinds.length > 0) {
65568
66098
  const skippedInstances = [];
65569
- const docs = await query(bundle, {}, { onSkip: (skipped) => skippedInstances.push(skipped) });
66099
+ const docs = await query2(bundle, {}, { onSkip: (skipped) => skippedInstances.push(skipped) });
65570
66100
  for (const skipped of skippedInstances) {
65571
66101
  evolutionBlocker(
65572
66102
  blockers,
@@ -66034,14 +66564,14 @@ async function status(argv2, deps = {}) {
66034
66564
  const malformedRows = [];
66035
66565
  const [registry2, docs, legacyBlobKeys, viewBlobKeys, okfVersionRead] = await Promise.all([
66036
66566
  loadKinds(bundle),
66037
- query(bundle, {}, { onSkip: (s) => malformedRows.push({ id: s.id, reason: s.reason }) }),
66567
+ query2(bundle, {}, { onSkip: (s) => malformedRows.push({ id: s.id, reason: s.reason }) }),
66038
66568
  // legacy_naming audit (below): blob keys still under the legacy pages/ prefix — one extra
66039
66569
  // prefix-scoped listing on a command that is already an explicit whole-bundle read.
66040
- listBlobs(bundle, LEGACY_PAGE_BLOB_PREFIX),
66570
+ listBlobs2(bundle, LEGACY_PAGE_BLOB_PREFIX),
66041
66571
  // dangling_view_entries (below): the views/ half of the entry-key existence set (the pages/
66042
66572
  // half is the legacy listing above — the only two prefixes a valid entry key can name).
66043
- listBlobs(bundle, VIEW_ENTRY_PREFIX),
66044
- readBundleOkfVersion(bundle).then((version2) => ({ version: version2 })).catch((error51) => {
66573
+ listBlobs2(bundle, VIEW_ENTRY_PREFIX),
66574
+ readBundleOkfVersion2(bundle).then((version2) => ({ version: version2 })).catch((error51) => {
66045
66575
  if (!(error51 instanceof MalformedDocumentError)) throw error51;
66046
66576
  return { version: void 0, malformed: { id: "index.md", reason: error51.message } };
66047
66577
  })
@@ -90938,11 +91468,11 @@ var require_codegen = __commonJS({
90938
91468
  const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`;
90939
91469
  return `${varKind} ${this.name}${rhs};` + _n;
90940
91470
  }
90941
- optimizeNames(names, constants4) {
91471
+ optimizeNames(names, constants6) {
90942
91472
  if (!names[this.name.str])
90943
91473
  return;
90944
91474
  if (this.rhs)
90945
- this.rhs = optimizeExpr(this.rhs, names, constants4);
91475
+ this.rhs = optimizeExpr(this.rhs, names, constants6);
90946
91476
  return this;
90947
91477
  }
90948
91478
  get names() {
@@ -90959,10 +91489,10 @@ var require_codegen = __commonJS({
90959
91489
  render({ _n }) {
90960
91490
  return `${this.lhs} = ${this.rhs};` + _n;
90961
91491
  }
90962
- optimizeNames(names, constants4) {
91492
+ optimizeNames(names, constants6) {
90963
91493
  if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)
90964
91494
  return;
90965
- this.rhs = optimizeExpr(this.rhs, names, constants4);
91495
+ this.rhs = optimizeExpr(this.rhs, names, constants6);
90966
91496
  return this;
90967
91497
  }
90968
91498
  get names() {
@@ -91023,8 +91553,8 @@ var require_codegen = __commonJS({
91023
91553
  optimizeNodes() {
91024
91554
  return `${this.code}` ? this : void 0;
91025
91555
  }
91026
- optimizeNames(names, constants4) {
91027
- this.code = optimizeExpr(this.code, names, constants4);
91556
+ optimizeNames(names, constants6) {
91557
+ this.code = optimizeExpr(this.code, names, constants6);
91028
91558
  return this;
91029
91559
  }
91030
91560
  get names() {
@@ -91053,12 +91583,12 @@ var require_codegen = __commonJS({
91053
91583
  }
91054
91584
  return nodes.length > 0 ? this : void 0;
91055
91585
  }
91056
- optimizeNames(names, constants4) {
91586
+ optimizeNames(names, constants6) {
91057
91587
  const { nodes } = this;
91058
91588
  let i = nodes.length;
91059
91589
  while (i--) {
91060
91590
  const n = nodes[i];
91061
- if (n.optimizeNames(names, constants4))
91591
+ if (n.optimizeNames(names, constants6))
91062
91592
  continue;
91063
91593
  subtractNames(names, n.names);
91064
91594
  nodes.splice(i, 1);
@@ -91111,12 +91641,12 @@ var require_codegen = __commonJS({
91111
91641
  return void 0;
91112
91642
  return this;
91113
91643
  }
91114
- optimizeNames(names, constants4) {
91644
+ optimizeNames(names, constants6) {
91115
91645
  var _a3;
91116
- this.else = (_a3 = this.else) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants4);
91117
- if (!(super.optimizeNames(names, constants4) || this.else))
91646
+ this.else = (_a3 = this.else) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants6);
91647
+ if (!(super.optimizeNames(names, constants6) || this.else))
91118
91648
  return;
91119
- this.condition = optimizeExpr(this.condition, names, constants4);
91649
+ this.condition = optimizeExpr(this.condition, names, constants6);
91120
91650
  return this;
91121
91651
  }
91122
91652
  get names() {
@@ -91139,10 +91669,10 @@ var require_codegen = __commonJS({
91139
91669
  render(opts) {
91140
91670
  return `for(${this.iteration})` + super.render(opts);
91141
91671
  }
91142
- optimizeNames(names, constants4) {
91143
- if (!super.optimizeNames(names, constants4))
91672
+ optimizeNames(names, constants6) {
91673
+ if (!super.optimizeNames(names, constants6))
91144
91674
  return;
91145
- this.iteration = optimizeExpr(this.iteration, names, constants4);
91675
+ this.iteration = optimizeExpr(this.iteration, names, constants6);
91146
91676
  return this;
91147
91677
  }
91148
91678
  get names() {
@@ -91178,10 +91708,10 @@ var require_codegen = __commonJS({
91178
91708
  render(opts) {
91179
91709
  return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
91180
91710
  }
91181
- optimizeNames(names, constants4) {
91182
- if (!super.optimizeNames(names, constants4))
91711
+ optimizeNames(names, constants6) {
91712
+ if (!super.optimizeNames(names, constants6))
91183
91713
  return;
91184
- this.iterable = optimizeExpr(this.iterable, names, constants4);
91714
+ this.iterable = optimizeExpr(this.iterable, names, constants6);
91185
91715
  return this;
91186
91716
  }
91187
91717
  get names() {
@@ -91223,11 +91753,11 @@ var require_codegen = __commonJS({
91223
91753
  (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();
91224
91754
  return this;
91225
91755
  }
91226
- optimizeNames(names, constants4) {
91756
+ optimizeNames(names, constants6) {
91227
91757
  var _a3, _b;
91228
- super.optimizeNames(names, constants4);
91229
- (_a3 = this.catch) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants4);
91230
- (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants4);
91758
+ super.optimizeNames(names, constants6);
91759
+ (_a3 = this.catch) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants6);
91760
+ (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants6);
91231
91761
  return this;
91232
91762
  }
91233
91763
  get names() {
@@ -91528,7 +92058,7 @@ var require_codegen = __commonJS({
91528
92058
  function addExprNames(names, from) {
91529
92059
  return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;
91530
92060
  }
91531
- function optimizeExpr(expr, names, constants4) {
92061
+ function optimizeExpr(expr, names, constants6) {
91532
92062
  if (expr instanceof code_1.Name)
91533
92063
  return replaceName(expr);
91534
92064
  if (!canOptimize(expr))
@@ -91543,14 +92073,14 @@ var require_codegen = __commonJS({
91543
92073
  return items;
91544
92074
  }, []));
91545
92075
  function replaceName(n) {
91546
- const c = constants4[n.str];
92076
+ const c = constants6[n.str];
91547
92077
  if (c === void 0 || names[n.str] !== 1)
91548
92078
  return n;
91549
92079
  delete names[n.str];
91550
92080
  return c;
91551
92081
  }
91552
92082
  function canOptimize(e) {
91553
- return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants4[c.str] !== void 0);
92083
+ return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants6[c.str] !== void 0);
91554
92084
  }
91555
92085
  }
91556
92086
  function subtractNames(names, from) {
@@ -94050,9 +94580,9 @@ var require_schemes = __commonJS({
94050
94580
  wsComponent.secure = void 0;
94051
94581
  }
94052
94582
  if (wsComponent.resourceName) {
94053
- const [path41, query2] = wsComponent.resourceName.split("?");
94583
+ const [path41, query3] = wsComponent.resourceName.split("?");
94054
94584
  wsComponent.path = path41 && path41 !== "/" ? path41 : void 0;
94055
- wsComponent.query = query2;
94585
+ wsComponent.query = query3;
94056
94586
  wsComponent.resourceName = void 0;
94057
94587
  }
94058
94588
  wsComponent.fragment = void 0;
@@ -99488,7 +100018,7 @@ function createMcpBundleRuntime(context, options2 = {}) {
99488
100018
  }
99489
100019
  async function presentDocument(bundle, docId, pendingDocuments) {
99490
100020
  try {
99491
- const result3 = await readDocVersioned(bundle, docId);
100021
+ const result3 = await readDocVersioned2(bundle, docId);
99492
100022
  const rendered = renderDocumentToStaticHtml({
99493
100023
  id: result3.doc.id,
99494
100024
  body: result3.doc.body
@@ -104053,6 +104583,61 @@ var init_install_scope = __esm({
104053
104583
  }
104054
104584
  });
104055
104585
 
104586
+ // src/nofollow-read.ts
104587
+ import { closeSync as closeSync3, constants as constants5, fstatSync as fstatSync4, lstatSync as lstatSync6, openSync as openSync3, readFileSync as readFileSync11 } from "node:fs";
104588
+ function leafIdentity(filePath) {
104589
+ try {
104590
+ const leaf = lstatSync6(filePath);
104591
+ if (!leaf.isFile()) return null;
104592
+ return { dev: leaf.dev, ino: leaf.ino };
104593
+ } catch (error51) {
104594
+ return error51.code === "ENOENT" ? "missing" : null;
104595
+ }
104596
+ }
104597
+ function readRegularFileNoFollowSync(filePath) {
104598
+ return readLeafSync(filePath, READ_FLAGS, HAS_NOFOLLOW);
104599
+ }
104600
+ function readLeafSync(filePath, flags, hasNoFollow) {
104601
+ let expected = null;
104602
+ if (!hasNoFollow) {
104603
+ const identity = leafIdentity(filePath);
104604
+ if (identity === null) return { state: "unsafe" };
104605
+ if (identity === "missing") return { state: "missing" };
104606
+ expected = identity;
104607
+ }
104608
+ let descriptor;
104609
+ try {
104610
+ descriptor = openSync3(filePath, flags);
104611
+ } catch (error51) {
104612
+ return error51.code === "ENOENT" ? { state: "missing" } : { state: "unsafe" };
104613
+ }
104614
+ try {
104615
+ const opened = fstatSync4(descriptor);
104616
+ if (!opened.isFile()) return { state: "unsafe" };
104617
+ if (expected && (opened.dev !== expected.dev || opened.ino !== expected.ino)) return { state: "unsafe" };
104618
+ return { state: "present", bytes: readFileSync11(descriptor) };
104619
+ } catch {
104620
+ return { state: "unsafe" };
104621
+ } finally {
104622
+ closeSync3(descriptor);
104623
+ }
104624
+ }
104625
+ function readRegularFileTextNoFollowSync(filePath) {
104626
+ const read = readRegularFileNoFollowSync(filePath);
104627
+ if (read.state !== "present") return read;
104628
+ return { state: "present", text: read.bytes.toString("utf8") };
104629
+ }
104630
+ var READ_FLAGS, HAS_NOFOLLOW;
104631
+ var init_nofollow_read = __esm({
104632
+ "src/nofollow-read.ts"() {
104633
+ "use strict";
104634
+ init_define_SUPERBEE_BUILD_IDENTITY();
104635
+ init_define_SUPERBEE_UPDATE_POLICY();
104636
+ READ_FLAGS = constants5.O_RDONLY | (constants5.O_NOFOLLOW ?? 0) | (constants5.O_NONBLOCK ?? 0);
104637
+ HAS_NOFOLLOW = (constants5.O_NOFOLLOW ?? 0) !== 0;
104638
+ }
104639
+ });
104640
+
104056
104641
  // src/integration-receipt.ts
104057
104642
  function integrationChangeReceipt(changedByHost) {
104058
104643
  const affected_hosts = HOST_ORDER.filter((host) => changedByHost[host] === true);
@@ -104073,9 +104658,9 @@ var init_integration_receipt = __esm({
104073
104658
  import {
104074
104659
  existsSync as existsSync6,
104075
104660
  linkSync as linkSync3,
104076
- lstatSync as lstatSync6,
104661
+ lstatSync as lstatSync7,
104077
104662
  readlinkSync as readlinkSync3,
104078
- readFileSync as readFileSync11,
104663
+ readFileSync as readFileSync12,
104079
104664
  renameSync as renameSync5,
104080
104665
  rmSync as rmSync3,
104081
104666
  symlinkSync
@@ -104305,7 +104890,7 @@ function targetSets(bases, deps) {
104305
104890
  function readSettings(path41) {
104306
104891
  if (!existsSync6(path41)) return {};
104307
104892
  try {
104308
- return JSON.parse(readFileSync11(path41, "utf8"));
104893
+ return JSON.parse(readFileSync12(path41, "utf8"));
104309
104894
  } catch {
104310
104895
  return {};
104311
104896
  }
@@ -104317,7 +104902,7 @@ function readSettingsForInstall(path41) {
104317
104902
  if (!existsSync6(path41)) return { ok: true, settings: {} };
104318
104903
  let raw;
104319
104904
  try {
104320
- raw = readFileSync11(path41, "utf8");
104905
+ raw = readFileSync12(path41, "utf8");
104321
104906
  } catch (err) {
104322
104907
  return { ok: false, reason: `unreadable (${err instanceof Error ? err.message : String(err)})` };
104323
104908
  }
@@ -104526,7 +105111,7 @@ function normalizedGeneratedSource(source) {
104526
105111
  function readOpenCodeHookStatus(path41, expectedSource) {
104527
105112
  let entry;
104528
105113
  try {
104529
- entry = lstatSync6(path41);
105114
+ entry = lstatSync7(path41);
104530
105115
  } catch {
104531
105116
  return { installed: false, compatibility: { state: "absent", reason: "plugin file is absent" } };
104532
105117
  }
@@ -104542,12 +105127,14 @@ function readOpenCodeHookStatus(path41, expectedSource) {
104542
105127
  if (!entry.isFile()) {
104543
105128
  return { installed: false, compatibility: { state: "unmanaged", reason: "plugin path is not a regular file" } };
104544
105129
  }
104545
- let source;
104546
- try {
104547
- source = readFileSync11(path41, "utf8");
104548
- } catch {
105130
+ const read = readRegularFileTextNoFollowSync(path41);
105131
+ if (read.state === "missing") {
105132
+ return { installed: false, compatibility: { state: "absent", reason: "plugin file is absent" } };
105133
+ }
105134
+ if (read.state === "unsafe") {
104549
105135
  return { installed: false, compatibility: { state: "unmanaged", reason: "plugin file is unreadable" } };
104550
105136
  }
105137
+ const source = read.text;
104551
105138
  const comparableSource = normalizedGeneratedSource(source);
104552
105139
  if (expectedSource !== void 0 && comparableSource === normalizedGeneratedSource(expectedSource)) {
104553
105140
  return {
@@ -104638,7 +105225,7 @@ function openCodeClaimPath(path41) {
104638
105225
  }
104639
105226
  function restoreOpenCodeClaim(claim, path41) {
104640
105227
  try {
104641
- const entry = lstatSync6(claim);
105228
+ const entry = lstatSync7(claim);
104642
105229
  if (entry.isSymbolicLink()) symlinkSync(readlinkSync3(claim), path41);
104643
105230
  else if (entry.isFile()) linkSync3(claim, path41);
104644
105231
  else throw new Error("claimed entry is not a regular file or symlink");
@@ -104898,7 +105485,7 @@ async function hook(argv2, deps = {}) {
104898
105485
  }
104899
105486
  const codexConfigPath = targets.codexConfig;
104900
105487
  try {
104901
- const current = existsSync6(codexConfigPath) ? readFileSync11(codexConfigPath, "utf8") : "";
105488
+ const current = existsSync6(codexConfigPath) ? readFileSync12(codexConfigPath, "utf8") : "";
104902
105489
  const [updated, changed2] = computeCodexConfigUpdate(current);
104903
105490
  if (changed2) atomicWriteFileSync(codexConfigPath, updated);
104904
105491
  changedByHost.codex = changedByHost.codex === true || changed2;
@@ -104998,6 +105585,7 @@ var init_hook = __esm({
104998
105585
  init_hook_compatibility();
104999
105586
  init_install_authority();
105000
105587
  init_install_scope();
105588
+ init_nofollow_read();
105001
105589
  init_integration_receipt();
105002
105590
  HOOK_USAGE = `superbee hook \u2014 manage the SessionStart board-aware hook
105003
105591
 
@@ -105695,7 +106283,7 @@ var init_establish_committed = __esm({
105695
106283
  });
105696
106284
 
105697
106285
  // src/commands/sync/establish.ts
105698
- import { existsSync as existsSync7, lstatSync as lstatSync7, readdirSync as readdirSync2, renameSync as renameSync6, rmSync as rmSync4 } from "node:fs";
106286
+ import { existsSync as existsSync7, lstatSync as lstatSync8, readdirSync as readdirSync2, renameSync as renameSync6, rmSync as rmSync4 } from "node:fs";
105699
106287
  import path35 from "node:path";
105700
106288
  function establishNextSteps(inv) {
105701
106289
  return [
@@ -105713,7 +106301,7 @@ function assertPlainBundleShape(bundlePath, inv) {
105713
106301
  { help: runInitHelp }
105714
106302
  );
105715
106303
  }
105716
- const root = lstatSync7(bundlePath);
106304
+ const root = lstatSync8(bundlePath);
105717
106305
  if (root.isSymbolicLink() || !root.isDirectory()) {
105718
106306
  throw new CliError(
105719
106307
  "RUNTIME",
@@ -105739,7 +106327,7 @@ function assertPlainBundleShape(bundlePath, inv) {
105739
106327
  { help: runInitHelp }
105740
106328
  );
105741
106329
  }
105742
- const index2 = lstatSync7(indexPath);
106330
+ const index2 = lstatSync8(indexPath);
105743
106331
  if (index2.isSymbolicLink() || !index2.isFile()) {
105744
106332
  throw new CliError("RUNTIME", `'${indexPath}' must be a real file \u2014 establish never follows it through a symlink`);
105745
106333
  }
@@ -105917,7 +106505,7 @@ async function publishLocalBoardBranch(top, boardPath, inv, mode, stdout, deps)
105917
106505
  }
105918
106506
  }
105919
106507
  const indexPath = path35.join(boardPath, "index.md");
105920
- if (!existsSync7(indexPath) || lstatSync7(indexPath).isSymbolicLink() || !lstatSync7(indexPath).isFile()) {
106508
+ if (!existsSync7(indexPath) || lstatSync8(indexPath).isSymbolicLink() || !lstatSync8(indexPath).isFile()) {
105921
106509
  throw new CliError("RUNTIME", `the local '${BOARD_BRANCH}' worktree is not a valid bundle (root index.md missing)`);
105922
106510
  }
105923
106511
  pushBoardUpstream(boardPath);
@@ -106053,7 +106641,7 @@ async function loadClaimPolicy(boardPath) {
106053
106641
  const originSha = resolveOriginRef(boardPath);
106054
106642
  if (originSha === null) return INACTIVE_POLICY;
106055
106643
  const bundle = { root: boardPath };
106056
- const [registry2, okfVersion] = await Promise.all([loadKinds(bundle), readBundleOkfVersion(bundle)]);
106644
+ const [registry2, okfVersion] = await Promise.all([loadKinds(bundle), readBundleOkfVersion2(bundle)]);
106057
106645
  if (registry2.kinds.size === 0) return INACTIVE_POLICY;
106058
106646
  const resolved = /* @__PURE__ */ new Map();
106059
106647
  return {
@@ -106118,7 +106706,7 @@ var init_claim_conflict = __esm({
106118
106706
  });
106119
106707
 
106120
106708
  // src/commands/sync/converge.ts
106121
- import { readFileSync as readFileSync12 } from "node:fs";
106709
+ import { readFileSync as readFileSync13 } from "node:fs";
106122
106710
  function cap2(rows, limit) {
106123
106711
  const bounded = limit > 0 ? rows.slice(0, limit) : rows;
106124
106712
  return { shown: bounded.length, total: rows.length, rows: bounded };
@@ -106216,7 +106804,7 @@ function analyzeConflict(boardPath, c, policy) {
106216
106804
  const keptOnly = { meta: meta3, frontmatterDiffers: [] };
106217
106805
  if (c.exportPath === null || !c.landed) return keptOnly;
106218
106806
  try {
106219
- const local = parseMarkdown(readFileSync12(c.exportPath, "utf8"), c.relPath);
106807
+ const local = parseMarkdown(readFileSync13(c.exportPath, "utf8"), c.relPath);
106220
106808
  const localFm = local.frontmatter;
106221
106809
  const keys = /* @__PURE__ */ new Set([...Object.keys(localFm), ...Object.keys(keptFm)]);
106222
106810
  keys.delete("timestamp");
@@ -107439,7 +108027,7 @@ var init_skill_compatibility = __esm({
107439
108027
 
107440
108028
  // src/commands/skill.ts
107441
108029
  import { createHash as createHash10 } from "node:crypto";
107442
- import { existsSync as existsSync8, lstatSync as lstatSync8, readFileSync as readFileSync13, readdirSync as readdirSync3, realpathSync as realpathSync15, renameSync as renameSync7, rmSync as rmSync5, rmdirSync as rmdirSync3 } from "node:fs";
108030
+ import { existsSync as existsSync8, lstatSync as lstatSync9, readFileSync as readFileSync14, readdirSync as readdirSync3, realpathSync as realpathSync15, renameSync as renameSync7, rmSync as rmSync5, rmdirSync as rmdirSync3 } from "node:fs";
107443
108031
  import { homedir as homedir17 } from "node:os";
107444
108032
  import path38 from "node:path";
107445
108033
  import { dirname as dirname6, join as join12 } from "node:path";
@@ -107479,7 +108067,7 @@ function resolveSkillAssets(executable) {
107479
108067
  const fileSha256 = Object.fromEntries(
107480
108068
  files.map((relativePath) => [
107481
108069
  relativePath,
107482
- `sha256:${createHash10("sha256").update(readFileSync13(join12(root, relativePath))).digest("hex")}`
108070
+ `sha256:${createHash10("sha256").update(readFileSync14(join12(root, relativePath))).digest("hex")}`
107483
108071
  ])
107484
108072
  );
107485
108073
  return {
@@ -107549,7 +108137,7 @@ function skillTargetPairIdentity(canonicalDir, legacyDir, platform = process.pla
107549
108137
  function nonDirectoryRefusal(dir) {
107550
108138
  let stats;
107551
108139
  try {
107552
- stats = lstatSync8(dir);
108140
+ stats = lstatSync9(dir);
107553
108141
  } catch {
107554
108142
  return void 0;
107555
108143
  }
@@ -107559,7 +108147,7 @@ function nonDirectoryRefusal(dir) {
107559
108147
  }
107560
108148
  function isSymlink(p2) {
107561
108149
  try {
107562
- return lstatSync8(p2).isSymbolicLink();
108150
+ return lstatSync9(p2).isSymbolicLink();
107563
108151
  } catch {
107564
108152
  return false;
107565
108153
  }
@@ -107586,13 +108174,16 @@ function readManifest(dir) {
107586
108174
  const manifestPath = join12(dir, SKILL_MANIFEST_FILENAME);
107587
108175
  let manifestStats;
107588
108176
  try {
107589
- manifestStats = lstatSync8(manifestPath);
108177
+ manifestStats = lstatSync9(manifestPath);
107590
108178
  } catch {
107591
108179
  return void 0;
107592
108180
  }
107593
108181
  if (manifestStats.isSymbolicLink() || !manifestStats.isFile()) return null;
108182
+ const read = readRegularFileTextNoFollowSync(manifestPath);
108183
+ if (read.state === "missing") return void 0;
108184
+ if (read.state === "unsafe") return null;
107594
108185
  try {
107595
- return parseOwnedSkillManifest(JSON.parse(readFileSync13(manifestPath, "utf8")));
108186
+ return parseOwnedSkillManifest(JSON.parse(read.text));
107596
108187
  } catch {
107597
108188
  return null;
107598
108189
  }
@@ -107633,7 +108224,7 @@ function unmanagedExtras(dir, managed) {
107633
108224
  }
107634
108225
  function isDirectory(p2) {
107635
108226
  try {
107636
- return lstatSync8(p2).isDirectory();
108227
+ return lstatSync9(p2).isDirectory();
107637
108228
  } catch {
107638
108229
  return false;
107639
108230
  }
@@ -107705,19 +108296,25 @@ function installIntoDir(dir, assets, prepared) {
107705
108296
  atomicWriteFileSync(manifestPath, content3);
107706
108297
  changed = true;
107707
108298
  };
107708
- const currentManifest = !isSymlink(manifestPath) && existsSync8(manifestPath) ? readFileSync13(manifestPath, "utf8") : void 0;
108299
+ const readManifestText = () => {
108300
+ const read = readRegularFileTextNoFollowSync(manifestPath);
108301
+ return read.state === "present" ? read.text : void 0;
108302
+ };
108303
+ const currentManifest = readManifestText();
107709
108304
  if (currentManifest !== transitionalManifest && currentManifest !== finalManifest) {
107710
108305
  writeManifest(transitionalManifest);
107711
108306
  }
107712
108307
  const wanted = new Set(assets.files);
107713
108308
  for (const relativePath of assets.files) {
107714
- const bytes = readFileSync13(join12(assets.root, relativePath));
108309
+ const bytes = readFileSync14(join12(assets.root, relativePath));
107715
108310
  const destPath = join12(dir, ...relativePath.split("/"));
107716
108311
  const destIsLink = isSymlink(destPath);
107717
108312
  const destIsDir = !destIsLink && isDirectory(destPath);
107718
- const current = !destIsLink && !destIsDir && existsSync8(destPath) ? readFileSync13(destPath) : void 0;
107719
- if (destIsLink || destIsDir || current === void 0 || !bytes.equals(current)) {
107720
- if (destIsLink) rmSync5(destPath, { force: true });
108313
+ const read = destIsLink || destIsDir ? void 0 : readRegularFileNoFollowSync(destPath);
108314
+ const destIsIrregular = read?.state === "unsafe";
108315
+ const current = read?.state === "present" ? read.bytes : void 0;
108316
+ if (destIsLink || destIsDir || destIsIrregular || current === void 0 || !bytes.equals(current)) {
108317
+ if (destIsLink || destIsIrregular) rmSync5(destPath, { force: true });
107721
108318
  if (destIsDir) rmdirSync3(destPath);
107722
108319
  atomicWriteFileSync(destPath, bytes);
107723
108320
  changed = true;
@@ -107729,7 +108326,7 @@ function installIntoDir(dir, assets, prepared) {
107729
108326
  changed = true;
107730
108327
  }
107731
108328
  }
107732
- const manifestAfterConverge = existsSync8(manifestPath) ? readFileSync13(manifestPath, "utf8") : void 0;
108329
+ const manifestAfterConverge = readManifestText();
107733
108330
  if (manifestAfterConverge !== finalManifest) {
107734
108331
  writeManifest(finalManifest);
107735
108332
  }
@@ -107817,19 +108414,14 @@ function skillStatusForDir(dir, assets, installCommand = `${cliInvocation()} ski
107817
108414
  receiptDigestsMatch = manifest.kind === "legacy" || manifest.receipt_valid && manifest.file_sha256 !== null;
107818
108415
  for (const relativePath of assets.files) {
107819
108416
  const installedPath = join12(dir, ...relativePath.split("/"));
107820
- let regularFile = false;
107821
- try {
107822
- regularFile = lstatSync8(installedPath).isFile();
107823
- } catch {
107824
- regularFile = false;
107825
- }
107826
- if (!regularFile) {
108417
+ const read = readRegularFileNoFollowSync(installedPath);
108418
+ if (read.state !== "present") {
107827
108419
  assetsMatch = false;
107828
108420
  receiptDigestsMatch = false;
107829
108421
  break;
107830
108422
  }
107831
- const installed = readFileSync13(installedPath);
107832
- const shipped = readFileSync13(join12(assets.root, relativePath));
108423
+ const installed = read.bytes;
108424
+ const shipped = readFileSync14(join12(assets.root, relativePath));
107833
108425
  if (!installed.equals(shipped)) assetsMatch = false;
107834
108426
  if (manifest.kind === "v2" && manifest.file_sha256?.[relativePath] !== `sha256:${createHash10("sha256").update(installed).digest("hex")}`) {
107835
108427
  receiptDigestsMatch = false;
@@ -108195,6 +108787,7 @@ var init_skill = __esm({
108195
108787
  init_skill_compatibility();
108196
108788
  init_install_authority();
108197
108789
  init_install_scope();
108790
+ init_nofollow_read();
108198
108791
  init_integration_receipt();
108199
108792
  SKILL_USAGE = `superbee skill \u2014 install this package's Agent Skill into host skill folders
108200
108793
 
@@ -108296,7 +108889,7 @@ async function defaultSummarizeBundle(dir, route) {
108296
108889
  return { root, unreadable: true };
108297
108890
  }
108298
108891
  try {
108299
- const docs = await queryHeads(bundle);
108892
+ const docs = await queryHeads2(bundle);
108300
108893
  const { name, source } = await deriveBundleDisplayName(bundle);
108301
108894
  return { name, nameSource: source, ...summarizeDocs(docs, collapseHomeDirectory(bundle.root)) };
108302
108895
  } catch {
@@ -109360,7 +109953,7 @@ async function indexCommand(argv2, deps = {}) {
109360
109953
  const bundle = await openBundle(values.dir);
109361
109954
  const [{ name: displayName }, heads] = await Promise.all([
109362
109955
  deriveBundleDisplayName(bundle),
109363
- queryHeads(bundle)
109956
+ queryHeads2(bundle)
109364
109957
  ]);
109365
109958
  const plan = planIndexProjection(displayName, heads);
109366
109959
  const prepared = await prepareIndexProjection(bundle, plan, { force: values.force });
@@ -109543,7 +110136,7 @@ async function artifact(argv2, deps = {}) {
109543
110136
  }
109544
110137
  let prior;
109545
110138
  try {
109546
- prior = await readDoc(bundle, supersedes);
110139
+ prior = await readDoc2(bundle, supersedes);
109547
110140
  } catch {
109548
110141
  prior = void 0;
109549
110142
  }
@@ -109561,8 +110154,8 @@ async function artifact(argv2, deps = {}) {
109561
110154
  const body = supersedes ? `[supersedes](${supersedes.slice("artifacts/".length)}.md)
109562
110155
  ` : "";
109563
110156
  const [recordHeads, blobKeys] = await Promise.all([
109564
- queryHeads(bundle, { prefix: "artifacts/" }),
109565
- listBlobs(bundle, "artifacts/")
110157
+ queryHeads2(bundle, { prefix: "artifacts/" }),
110158
+ listBlobs2(bundle, "artifacts/")
109566
110159
  ]);
109567
110160
  const taken = /* @__PURE__ */ new Set([
109568
110161
  ...recordHeads.map((h2) => h2.id),
@@ -109573,7 +110166,7 @@ async function artifact(argv2, deps = {}) {
109573
110166
  let entryVersion;
109574
110167
  try {
109575
110168
  if (route) await assertResolvedLocalRouteIdentity(route);
109576
- entryVersion = await writeBlob(bundle, entryKey, bytes, "text/html", { expectedVersion: null });
110169
+ entryVersion = await writeBlob2(bundle, entryKey, bytes, "text/html", { expectedVersion: null });
109577
110170
  } catch (err) {
109578
110171
  throw new CliError("RUNTIME", `could not write the artifact blob '${entryKey}': ${err instanceof Error ? err.message : String(err)}`);
109579
110172
  }