@orkestrel/scaffold 0.0.115 → 0.0.117

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.
Files changed (70) hide show
  1. package/dist/bin/main.js +138 -16
  2. package/dist/bin/main.js.map +1 -1
  3. package/dist/host/agents/skills/orkestrel-publish/references/wave.md +1 -1
  4. package/dist/host/claude/agents/orkestrel.md +2 -2
  5. package/dist/host/claude/rules/names.md +3 -1
  6. package/dist/host/guides/abort.md +17 -17
  7. package/dist/host/guides/agent.md +445 -445
  8. package/dist/host/guides/brief.md +143 -143
  9. package/dist/host/guides/browser.md +731 -731
  10. package/dist/host/guides/budget.md +39 -39
  11. package/dist/host/guides/capture.md +298 -298
  12. package/dist/host/guides/console.md +109 -109
  13. package/dist/host/guides/contract.md +335 -335
  14. package/dist/host/guides/csv.md +30 -30
  15. package/dist/host/guides/database.md +163 -163
  16. package/dist/host/guides/emitter.md +17 -17
  17. package/dist/host/guides/form.md +99 -99
  18. package/dist/host/guides/guide.md +368 -183
  19. package/dist/host/guides/html.md +49 -49
  20. package/dist/host/guides/indexeddb.md +40 -40
  21. package/dist/host/guides/interpret.md +139 -139
  22. package/dist/host/guides/lsp.md +114 -114
  23. package/dist/host/guides/markdown.md +68 -68
  24. package/dist/host/guides/mcp.md +3745 -3745
  25. package/dist/host/guides/middleware.md +170 -170
  26. package/dist/host/guides/msg.md +95 -95
  27. package/dist/host/guides/ndjson.md +8 -8
  28. package/dist/host/guides/ollama.md +56 -56
  29. package/dist/host/guides/pool.md +21 -21
  30. package/dist/host/guides/probe.md +82 -82
  31. package/dist/host/guides/process.md +99 -99
  32. package/dist/host/guides/program.md +98 -96
  33. package/dist/host/guides/qualifier.md +70 -70
  34. package/dist/host/guides/queue.md +37 -37
  35. package/dist/host/guides/rater.md +38 -38
  36. package/dist/host/guides/reason.md +308 -308
  37. package/dist/host/guides/relation.md +50 -50
  38. package/dist/host/guides/router.md +58 -58
  39. package/dist/host/guides/scaffold.md +558 -419
  40. package/dist/host/guides/sea.md +128 -128
  41. package/dist/host/guides/server.md +100 -100
  42. package/dist/host/guides/sqlite.md +28 -28
  43. package/dist/host/guides/sse.md +20 -20
  44. package/dist/host/guides/study.md +444 -444
  45. package/dist/host/guides/table.md +82 -82
  46. package/dist/host/guides/template.md +41 -41
  47. package/dist/host/guides/terminal.md +121 -121
  48. package/dist/host/guides/test.md +273 -273
  49. package/dist/host/guides/timeout.md +18 -18
  50. package/dist/host/guides/tool.md +27 -27
  51. package/dist/host/guides/toolbox.md +166 -166
  52. package/dist/host/guides/websocket.md +54 -54
  53. package/dist/host/guides/worker.md +24 -24
  54. package/dist/host/guides/workflow.md +187 -187
  55. package/dist/host/guides/workspace.md +55 -55
  56. package/dist/host/manifest.json +55 -55
  57. package/dist/host/tests/setupPolicy.ts +5 -3
  58. package/dist/src/core/index.cjs +90 -4
  59. package/dist/src/core/index.cjs.map +1 -1
  60. package/dist/src/core/index.d.cts +229 -144
  61. package/dist/src/core/index.d.ts +229 -144
  62. package/dist/src/core/index.js +88 -5
  63. package/dist/src/core/index.js.map +1 -1
  64. package/dist/src/server/index.cjs +295 -66
  65. package/dist/src/server/index.cjs.map +1 -1
  66. package/dist/src/server/index.d.cts +193 -6
  67. package/dist/src/server/index.d.ts +193 -6
  68. package/dist/src/server/index.js +290 -69
  69. package/dist/src/server/index.js.map +1 -1
  70. package/package.json +5 -4
@@ -1,6 +1,6 @@
1
1
  import { createRequire } from "node:module";
2
- import { andOf, arrayOf, attempt, boundsOf, compareValues, compileGuard, holds, isArray, isBoolean, isDefined, isError, isFunction, isInteger, isNonNegativeInteger, isNumber, isRecord, isString, parseJSON, parseJSONAs, parseStringField, recordOf, recordShape, stringOf, stringShape, unionOf, whereOf } from "@orkestrel/contract";
3
- import { CANON_PATHS, CATALOG_AGENT_PATH, CATALOG_END_MARKER, CATALOG_START_MARKER, CONTROL_CHARACTER_PATTERN, DEPENDENCY_NAME_PATTERN, EXECUTABLE_PATHS, HOST_INVENTORY_PATH, HOST_PATHS, MAX_ARTIFACT_BYTES, MAX_COLLECTION_ITEMS, MAX_DEPENDENCY_NAME_LENGTH, MAX_MANIFEST_BYTES, MAX_PATH_LENGTH, MAX_RANGE_LENGTH, MAX_REGISTRY_BYTES, MAX_TOTAL_ARTIFACT_BYTES, MAX_TOTAL_REGISTRY_BYTES, REFERENCE_PATHS, ScaffoldError, bytesToHex, catalogToLayers, cloneValue, compareVersions, computeBytes, computeTotal, contentToHex, extractRangeMajor, extractVersion, inferGroup, insertManifestDependencies, isAudit, isCatalogEntry, isCollection, isDependency, isDependencyName, isFloorPath, isHex, isManifestScript, isMirror, isPath, isPlan, isRetainedPath, isSnapshot, iterateAnswers, matchesDriftReachability, matchesRange, nameToGuide, planToFindings, renderSkillPointer, replaceManifestOverrides, replaceManifestRanges, replaceManifestScripts } from "../core/index.js";
2
+ import { andOf, arrayOf, attempt, boundsOf, compareValues, compileGuard, holds, isArray, isBoolean, isDefined, isError, isFunction, isInteger, isNonNegativeInteger, isNumber, isObject, isRecord, isString, parseJSON, parseJSONAs, parseStringField, recordOf, recordShape, stringOf, stringShape, unionOf, whereOf } from "@orkestrel/contract";
3
+ import { CANON_PATHS, CATALOG_AGENT_PATH, CATALOG_END_MARKER, CATALOG_START_MARKER, CONTROL_CHARACTER_PATTERN, DEPENDENCY_NAME_PATTERN, EXECUTABLE_PATHS, HOST_INVENTORY_PATH, HOST_PATHS, MAX_ARTIFACT_BYTES, MAX_COLLECTION_ITEMS, MAX_DEPENDENCY_NAME_LENGTH, MAX_MANIFEST_BYTES, MAX_PATH_LENGTH, MAX_RANGE_LENGTH, MAX_REGISTRY_BYTES, MAX_TOTAL_ARTIFACT_BYTES, MAX_TOTAL_REGISTRY_BYTES, REFERENCE_PATHS, ScaffoldError, bytesToHex, catalogToLayers, cloneValue, collectSurfaceCollisions, collectSurfaceConflicts, compareSurfaceCollisions, compareVersions, computeBytes, computeTotal, contentToHex, extractRangeMajor, extractVersion, inferGroup, insertManifestDependencies, isAudit, isCatalogEntry, isCollection, isDependency, isDependencyName, isFloorPath, isHex, isManifestScript, isMirror, isPath, isPlan, isRetainedPath, isSnapshot, iterateAnswers, manifestToName, matchesDriftReachability, matchesRange, nameToGuide, planToFindings, renderSkillPointer, replaceManifestOverrides, replaceManifestRanges, replaceManifestScripts } from "../core/index.js";
4
4
  import { createHash, randomUUID } from "node:crypto";
5
5
  import { chmodSync, closeSync, constants, copyFileSync, fstatSync, linkSync, lstatSync, mkdirSync, mkdtempSync, openSync, opendirSync, readSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, rmdirSync, writeFileSync } from "node:fs";
6
6
  import { tmpdir } from "node:os";
@@ -1286,9 +1286,8 @@ function readHostManifest(host, name = MANIFEST_NAME) {
1286
1286
  */
1287
1287
  function readHostFloor(root) {
1288
1288
  const location = fileURLToPath(import.meta.url);
1289
- const module = dirname(location);
1290
1289
  const source = root === void 0 && extname(location) === ".ts";
1291
- const host = root ?? resolve(module, source ? "../.." : "../../host");
1290
+ const host = root ?? resolveHostRoot();
1292
1291
  if (!isPhysicalDirectory(host)) throw new ScaffoldError("TARGET", `The vendored host root is not readable at ${host}`, { host });
1293
1292
  const manifest = readHostManifest(host, source ? HOST_INVENTORY_PATH : MANIFEST_NAME);
1294
1293
  if (manifest === void 0) throw new ScaffoldError("TARGET", `The vendored host carries no manifest at ${host}`, { host });
@@ -1671,10 +1670,13 @@ function stageHost(checkout, host, options) {
1671
1670
  };
1672
1671
  });
1673
1672
  const collisions = readSurfaceCollisions(join(root, "guides"));
1674
- const growth = published === void 0 ? [] : [...collisions].flatMap(([name, owners]) => {
1675
- const record = published.get(name);
1676
- return record !== void 0 && owners.every((owner) => record.includes(owner)) ? [] : [`${name} staged (${owners.join(", ")}), recorded (${record?.join(", ") ?? "absent"})`];
1677
- });
1673
+ const growth = published === void 0 ? [] : compareSurfaceCollisions([...collisions].map(([name, owners]) => ({
1674
+ name,
1675
+ owners
1676
+ })), [...published].map(([name, owners]) => ({
1677
+ name,
1678
+ owners
1679
+ }))).filter(({ standing }) => standing === "error").map(({ name, owners }) => `${name} staged (${owners.join(", ")}), recorded (${published.get(name)?.join(", ") ?? "absent"})`);
1678
1680
  if (growth.length > 0) throw new ScaffoldError("TARGET", `Staged Surface collisions differ from the inventory: ${growth.join("; ")}`, {
1679
1681
  checkout: source,
1680
1682
  host: root,
@@ -1727,26 +1729,202 @@ function stageHost(checkout, host, options) {
1727
1729
  * ```
1728
1730
  */
1729
1731
  function readSurfaceCollisions(root) {
1730
- if (!isPhysicalDirectory(root)) throw new ScaffoldError("TARGET", `Surface guide directory is not readable at ${root}`, { root });
1731
- const loaded = attempt(() => createRequire(import.meta.url)("@orkestrel/guide"));
1732
- if (!loaded.success) throw new ScaffoldError("TARGET", "Surface reflection requires the module @orkestrel/guide", {
1733
- root,
1734
- error: loaded.error
1732
+ return new Map(collectSurfaceCollisions(readSurfaceClaims(root)).map(({ name, owners }) => [name, owners]));
1733
+ }
1734
+ /**
1735
+ * Resolves the bundled host root from the executing module's location.
1736
+ *
1737
+ * @example
1738
+ * ```ts
1739
+ * import { resolveHostRoot } from '@orkestrel/scaffold/server'
1740
+ * resolveHostRoot() // the checkout in source, or the installed dist/host directory
1741
+ * ```
1742
+ */
1743
+ function resolveHostRoot() {
1744
+ const location = fileURLToPath(import.meta.url);
1745
+ return resolve(dirname(location), extname(location) === ".ts" ? "../.." : "../../host");
1746
+ }
1747
+ /**
1748
+ * Loads and validates the guide functions required by surface reflection.
1749
+ *
1750
+ * @param loader - The module resolver. Default: Node resolution from this module.
1751
+ * @throws Thrown with TARGET when the module is absent or lacks a required function.
1752
+ * @example
1753
+ * ```ts
1754
+ * import { readSurfaceModule } from '@orkestrel/scaffold/server'
1755
+ * readSurfaceModule().createGuide('# Sample').surface() // []
1756
+ * ```
1757
+ */
1758
+ function readSurfaceModule(loader = createRequire(import.meta.url)) {
1759
+ const loaded = attempt(() => loader("@orkestrel/guide"));
1760
+ if (!loaded.success || !isSurfaceModule(loaded.value)) throw new ScaffoldError("TARGET", "Surface reflection requires @orkestrel/guide with createGuide, createSource, extractSourceLines, and isGuideError. Supply that module in scaffold's resolution path.", { ...!loaded.success ? { error: loaded.error } : {} });
1761
+ return loaded.value;
1762
+ }
1763
+ /**
1764
+ * Reads one guide's claims and reports parser refusals with its owner and source.
1765
+ *
1766
+ * @param source - The source label or path to name in a refusal.
1767
+ * @throws Thrown with TARGET when the module is unusable or the guide parser refuses the guide
1768
+ * with an error its `isGuideError` guard accepts; every other parser error propagates unchanged.
1769
+ * @example
1770
+ * ```ts
1771
+ * import { readSurfaceGuide } from '@orkestrel/scaffold/server'
1772
+ * readSurfaceGuide('# Sample', 'sample', 'live guides/sample.md') // { owner: 'sample', names: [] }
1773
+ * ```
1774
+ */
1775
+ function readSurfaceGuide(text, owner, source, loader) {
1776
+ const guide = readSurfaceModule(loader);
1777
+ const parsed = attempt(() => guide.createGuide(text).surface().map(({ name }) => name));
1778
+ if (parsed.success) return {
1779
+ owner,
1780
+ names: parsed.value
1781
+ };
1782
+ if (!guide.isGuideError(parsed.error)) throw parsed.error;
1783
+ throw new ScaffoldError("TARGET", `Surface guide for ${JSON.stringify(owner.slice(0, 512))} from ${JSON.stringify(source.slice(0, 512))} was refused: ${parsed.error.message}`, {
1784
+ owner,
1785
+ source,
1786
+ code: parsed.error.code
1735
1787
  });
1736
- const guide = loaded.value;
1737
- const claims = listFiles(root).filter((path) => !path.includes("/") && extname(path) === ".md" && path !== "README.md").flatMap((path) => {
1788
+ }
1789
+ /**
1790
+ * Reads each immediate package guide's bare names under its file owner.
1791
+ *
1792
+ * @param root - The directory containing the package guides; README.md is excluded.
1793
+ * @param loader - The module resolver used by the shared validated guide loader.
1794
+ * @throws Thrown when the directory, a guide, or the lazily loaded @orkestrel/guide module is unreadable.
1795
+ *
1796
+ * @example
1797
+ * ```ts
1798
+ * import { readSurfaceClaims } from '@orkestrel/scaffold/server'
1799
+ *
1800
+ * readSurfaceClaims('./guides') // owners and the names their guides claim
1801
+ * ```
1802
+ */
1803
+ function readSurfaceClaims(root, loader) {
1804
+ if (!isPhysicalDirectory(root)) throw new ScaffoldError("TARGET", `Surface guide directory is not readable at ${root}`, { root });
1805
+ readSurfaceModule(loader);
1806
+ return listFiles(root).filter((path) => !path.includes("/") && extname(path) === ".md" && path !== "README.md").map((path) => {
1738
1807
  const text = readFileText(root, path);
1739
1808
  if (text === void 0) throw new ScaffoldError("TARGET", `Surface guide cannot be read at ${path}`, {
1740
1809
  root,
1741
1810
  path
1742
1811
  });
1743
- return guide.createGuide(text).surface().map((symbol) => [symbol.name, basename(path, ".md")]);
1812
+ return readSurfaceGuide(text, basename(path, ".md"), join(root, path), loader);
1744
1813
  });
1745
- const grouped = Map.groupBy(claims, ([name]) => name);
1746
- return new Map([...grouped.keys()].sort().flatMap((name) => {
1747
- const owners = [...new Set((grouped.get(name) ?? []).map(([, owner]) => owner))];
1748
- return owners.length > 1 ? [[name, owners.sort()]] : [];
1814
+ }
1815
+ /**
1816
+ * Reads a checkout's combined guide and barrel claims under its manifest owner.
1817
+ *
1818
+ * @remarks
1819
+ * Removes the @orkestrel/ scope from the manifest name. Reflects each immediate
1820
+ * src environment through @orkestrel/guide, loaded only when called, and reports each
1821
+ * name two or more environments export as a conflict.
1822
+ * Reads only .ts files and refuses barrel statements outside relative .js star exports.
1823
+ * A present unreadable guide refuses the candidate even when src exists.
1824
+ * `loader` selects the resolver used by the shared validated guide loader.
1825
+ * @throws Thrown when the manifest is unreadable, both claim sources are absent,
1826
+ * a source cannot be read, or @orkestrel/guide cannot be loaded.
1827
+ *
1828
+ * @example
1829
+ * ```ts
1830
+ * import { readSurfaceCandidate } from '@orkestrel/scaffold/server'
1831
+ *
1832
+ * readSurfaceCandidate('.') // the working checkout's owner and combined names
1833
+ * ```
1834
+ */
1835
+ function readSurfaceCandidate(root, loader) {
1836
+ const manifest = readFileText(root, "package.json", MAX_MANIFEST_BYTES);
1837
+ const name = manifest === void 0 ? void 0 : manifestToName(manifest);
1838
+ if (name === void 0) throw new ScaffoldError("TARGET", `Surface candidate ${JSON.stringify(root.slice(0, 512))} needs package.json with a valid name.`, { root });
1839
+ const owner = name.replace(/^@orkestrel\//u, "");
1840
+ const guide = readSurfaceFile(root, owner, "candidate", loader);
1841
+ const source = join(root, "src");
1842
+ if (guide === void 0 && !isPhysicalDirectory(source)) throw new ScaffoldError("TARGET", `Surface candidate ${JSON.stringify(root.slice(0, 512))} has neither ${JSON.stringify(`guides/${owner}.md`)} nor src/. Add its guide or source directory before checking its claims.`, { root });
1843
+ const reflection = readSurfaceModule(loader);
1844
+ const files = Object.fromEntries(listFiles(source).filter((file) => file.endsWith(".ts")).map((file) => {
1845
+ const text = readFileText(source, file);
1846
+ if (text === void 0) throw new ScaffoldError("TARGET", `Surface candidate ${JSON.stringify(root.slice(0, 512))} cannot read ${JSON.stringify(`src/${file}`.slice(0, 512))}. Restore a readable source file before checking its claims.`, {
1847
+ root,
1848
+ path: file
1849
+ });
1850
+ return [`src/${file}`, text];
1749
1851
  }));
1852
+ for (const [file, text] of Object.entries(files)) {
1853
+ if (!file.endsWith("/index.ts")) continue;
1854
+ for (const line of reflection.extractSourceLines(text)) {
1855
+ if (line.code.trim() === "" || /^\s*export\s+\*\s+from\s+(?:'(\.\.?\/[^']+\.js)'|"(\.\.?\/[^"]+\.js)")\s*;?\s*$/u.test(line.code)) continue;
1856
+ throw new ScaffoldError("TARGET", `Surface candidate barrel ${JSON.stringify(join(root, file).slice(0, 512))} refuses statement ${JSON.stringify(line.source.trim().slice(0, 512))}; use only export * from './module.js' declarations.`, {
1857
+ root,
1858
+ path: file
1859
+ });
1860
+ }
1861
+ }
1862
+ const exports = Object.fromEntries(listDirectories(source).filter((directory) => !directory.includes("/")).map((directory) => [directory, reflection.createSource({
1863
+ files,
1864
+ module: `src/${directory}`
1865
+ }).surface().map((symbol) => symbol.name)]));
1866
+ return {
1867
+ owner,
1868
+ names: [.../* @__PURE__ */ new Set([...guide?.names ?? [], ...Object.values(exports).flat()])].sort(),
1869
+ conflicts: collectSurfaceConflicts(owner, exports)
1870
+ };
1871
+ }
1872
+ /**
1873
+ * Reads one owner's `guides/<owner>.md` under a root, or from a verified host value, as a claim.
1874
+ *
1875
+ * @param root - The checkout or data root holding the guide, or a verified host whose bytes
1876
+ * carry it at that destination.
1877
+ * @param owner - The unscoped package name the guide file is named for.
1878
+ * @param label - The source word a refusal names beside the path, such as `candidate` or `floor`.
1879
+ * @param loader - The module resolver used by the shared validated guide loader.
1880
+ * @returns The claim, or `undefined` when no file sits at the path or the host declares none.
1881
+ * @throws Thrown with TARGET when the file or the declared bytes are not UTF-8 text, when the
1882
+ * file exceeds the artifact bound, or when the guide module or its parser refuses the guide.
1883
+ *
1884
+ * @example
1885
+ * ```ts
1886
+ * import { readSurfaceFile } from '@orkestrel/scaffold/server'
1887
+ *
1888
+ * readSurfaceFile('.', 'scaffold', 'candidate')?.names // the names the checkout's guide claims
1889
+ * ```
1890
+ */
1891
+ function readSurfaceFile(root, owner, label, loader) {
1892
+ const destination = `guides/${owner}.md`;
1893
+ if (!isString(root)) {
1894
+ const hex = root.bytes[destination];
1895
+ const declared = hex === void 0 ? void 0 : decodeHexText(hex);
1896
+ if (hex !== void 0 && declared === void 0) throw new ScaffoldError("TARGET", `Surface guide cannot be read at ${JSON.stringify(destination)}`, { path: destination });
1897
+ return declared === void 0 ? void 0 : readSurfaceGuide(declared, owner, `${label} ${destination}`, loader);
1898
+ }
1899
+ const path = join(root, "guides", `${owner}.md`);
1900
+ const text = readFileText(root, destination);
1901
+ if (text === void 0 && isExactCaseFile(path)) throw new ScaffoldError("TARGET", `Surface guide cannot be read at ${JSON.stringify(path.slice(0, 512))}`, {
1902
+ root,
1903
+ path: `guides/${owner}.md`
1904
+ });
1905
+ return text === void 0 ? void 0 : readSurfaceGuide(text, owner, `${label} ${path}`, loader);
1906
+ }
1907
+ /**
1908
+ * Reads a data root's verified collision record.
1909
+ *
1910
+ * @param root - The data root holding `manifest.json` or `host.json`.
1911
+ * @remarks
1912
+ * Reads `manifest.json` first, then `host.json` when no built manifest exists.
1913
+ * Reads only local files and never contacts upstream or writes an inventory.
1914
+ * @throws Thrown with TARGET when neither inventory exists, and as `readHostManifest`
1915
+ * throws when one is unreadable, malformed, or inconsistent with its digest.
1916
+ *
1917
+ * @example
1918
+ * ```ts
1919
+ * import { readSurfaceRecord, resolveHostRoot } from '@orkestrel/scaffold/server'
1920
+ *
1921
+ * readSurfaceRecord(resolveHostRoot()) // the bundled collision record
1922
+ * ```
1923
+ */
1924
+ function readSurfaceRecord(root) {
1925
+ const record = readSurfaceBaseline(root, "manifest.json") ?? readSurfaceBaseline(root);
1926
+ if (record === void 0) throw new ScaffoldError("TARGET", `Surface data root ${JSON.stringify(root.slice(0, 512))} needs manifest.json or host.json with a surface record. Supply an inventoried root with --from.`, { root });
1927
+ return record;
1750
1928
  }
1751
1929
  /**
1752
1930
  * Reads the Surface collision baseline from a committed inventory.
@@ -1991,6 +2169,18 @@ function matchesPrecondition(precondition) {
1991
2169
  }
1992
2170
  // src/server/validators.ts
1993
2171
  /**
2172
+ * Narrows a value to the callable guide functions surface reflection requires.
2173
+ *
2174
+ * @example
2175
+ * ```ts
2176
+ * import { isSurfaceModule } from '@orkestrel/scaffold/server'
2177
+ * isSurfaceModule({}) // false
2178
+ * ```
2179
+ */
2180
+ function isSurfaceModule(value) {
2181
+ return holds(() => isObject(value) && "createGuide" in value && isFunction(value.createGuide) && "createSource" in value && isFunction(value.createSource) && "extractSourceLines" in value && isFunction(value.extractSourceLines) && "isGuideError" in value && isFunction(value.isGuideError));
2182
+ }
2183
+ /**
1994
2184
  * Narrows a value to a path naming a location on this host.
1995
2185
  *
1996
2186
  * @param value - The candidate host path.
@@ -4101,7 +4291,7 @@ var Upstream = class {
4101
4291
  const observed = this.#accept(current, isSnapshot, "current");
4102
4292
  if (accepted.length === 0) return [];
4103
4293
  const allowance = new ReadAllowance(this.#budget);
4104
- const inventory = await this.#inventory(allowance);
4294
+ const inventory = await this.inventory(allowance);
4105
4295
  return this.#gather(accepted, (path) => this.#file(path, inventory, observed, allowance));
4106
4296
  }
4107
4297
  /**
@@ -4120,7 +4310,9 @@ var Upstream = class {
4120
4310
  * unreadable list would otherwise be written into a target's catalog table as
4121
4311
  * a fleet with no packages in it. A package whose own version lookup then
4122
4312
  * fails still keeps its row, carrying the cause instead of a version, because
4123
- * the list already proved the package is published.
4313
+ * the list already proved the package is published. The `FETCH` failure's
4314
+ * context carries `unreachable: true` only when the list request produced no
4315
+ * HTTP response.
4124
4316
  *
4125
4317
  * @example
4126
4318
  * ```ts
@@ -4138,6 +4330,56 @@ var Upstream = class {
4138
4330
  return this.#gather(names, (name) => this.#entry(name, allowance));
4139
4331
  }
4140
4332
  /**
4333
+ * Reads the verified upstream inventory and its collision record.
4334
+ *
4335
+ * @param allowance - A shared call allowance; omitted calls open their own budget.
4336
+ * @returns A found inventory with its surface, or an unfound verdict with empty collections,
4337
+ * carrying `unreachable: true` only when the request produced no HTTP response.
4338
+ * @throws Thrown with DESTROYED when the reader has been torn down.
4339
+ * @example
4340
+ * ```ts
4341
+ * import { Upstream } from '@orkestrel/scaffold/server'
4342
+ * const upstream = new Upstream()
4343
+ * const inventory = await upstream.inventory()
4344
+ * inventory.surface // the verified record when lookup is found
4345
+ * upstream.destroy()
4346
+ * ```
4347
+ */
4348
+ async inventory(allowance = new ReadAllowance(this.#budget)) {
4349
+ this.#assertAlive();
4350
+ const url = this.#vendorURL(HOST_INVENTORY_PATH);
4351
+ const empty = {
4352
+ digests: /* @__PURE__ */ new Map(),
4353
+ duplicates: /* @__PURE__ */ new Set(),
4354
+ surface: []
4355
+ };
4356
+ const outcome = await this.#readWithRetries(url, this.#repositoryTimeout, allowance);
4357
+ if (outcome.lookup !== "found") return {
4358
+ ...empty,
4359
+ lookup: outcome.lookup,
4360
+ note: outcome.lookup === "missing" ? `the vendored inventory at ${url} is not published there` : `the vendored inventory at ${url} produced no answer: ${outcome.note}`,
4361
+ ...outcome.unreachable === true ? { unreachable: true } : {}
4362
+ };
4363
+ const manifest = parseJSONAs(outcome.content, isHostManifest);
4364
+ if (manifest === void 0) return {
4365
+ ...empty,
4366
+ lookup: "failed",
4367
+ note: `the vendored inventory at ${url} is not a readable manifest`
4368
+ };
4369
+ if (manifest.digest !== computeManifestDigest(manifest.entries, manifest.roots, manifest.surface)) return {
4370
+ ...empty,
4371
+ lookup: "failed",
4372
+ note: `the vendored inventory at ${url} does not match its own membership digest`
4373
+ };
4374
+ return {
4375
+ lookup: "found",
4376
+ digests: new Map(manifest.entries.map((entry) => [entry.destination, entry.digest])),
4377
+ duplicates: new Set(manifest.entries.map((entry) => entry.destination).filter((destination, index, destinations) => destinations.indexOf(destination) !== index)),
4378
+ surface: manifest.surface,
4379
+ note: ""
4380
+ };
4381
+ }
4382
+ /**
4141
4383
  * Tears the reader down, aborting every request in flight. Teardown is idempotent.
4142
4384
  *
4143
4385
  * @returns Nothing.
@@ -4279,36 +4521,6 @@ var Upstream = class {
4279
4521
  ...carried
4280
4522
  };
4281
4523
  }
4282
- async #inventory(allowance) {
4283
- const url = this.#vendorURL(HOST_INVENTORY_PATH);
4284
- const empty = {
4285
- digests: /* @__PURE__ */ new Map(),
4286
- duplicates: /* @__PURE__ */ new Set()
4287
- };
4288
- const outcome = await this.#readWithRetries(url, this.#repositoryTimeout, allowance);
4289
- if (outcome.lookup !== "found") return {
4290
- ...empty,
4291
- lookup: outcome.lookup,
4292
- note: outcome.lookup === "missing" ? `the vendored inventory at ${url} is not published there` : `the vendored inventory at ${url} produced no answer: ${outcome.note}`
4293
- };
4294
- const manifest = parseJSONAs(outcome.content, isHostManifest);
4295
- if (manifest === void 0) return {
4296
- ...empty,
4297
- lookup: "failed",
4298
- note: `the vendored inventory at ${url} is not a readable manifest`
4299
- };
4300
- if (manifest.digest !== computeManifestDigest(manifest.entries, manifest.roots, manifest.surface)) return {
4301
- ...empty,
4302
- lookup: "failed",
4303
- note: `the vendored inventory at ${url} does not match its own membership digest`
4304
- };
4305
- return {
4306
- lookup: "found",
4307
- digests: new Map(manifest.entries.map((entry) => [entry.destination, entry.digest])),
4308
- duplicates: new Set(manifest.entries.map((entry) => entry.destination).filter((destination, index, destinations) => destinations.indexOf(destination) !== index)),
4309
- note: ""
4310
- };
4311
- }
4312
4524
  async #entry(name, allowance) {
4313
4525
  const outcome = await this.#readWithRetries(this.#registryURL(name), this.#registryTimeout, allowance, PACKUMENT_MEDIA_TYPE);
4314
4526
  const version = outcome.lookup === "found" ? this.#latest(outcome.content) : void 0;
@@ -4344,7 +4556,8 @@ var Upstream = class {
4344
4556
  const outcome = await this.#readWithRetries(url, this.#registryTimeout, allowance);
4345
4557
  if (outcome.lookup !== "found") throw this.#error("FETCH", `The organization package list at ${url} produced no answer.`, {
4346
4558
  url,
4347
- note: outcome.note
4559
+ note: outcome.note,
4560
+ ...outcome.unreachable === true ? { unreachable: true } : {}
4348
4561
  });
4349
4562
  const parsed = parseJSON(outcome.content);
4350
4563
  if (!isRecord(parsed)) throw this.#error("FETCH", `The organization package list at ${url} is not a record.`, { url });
@@ -4404,15 +4617,7 @@ var Upstream = class {
4404
4617
  url,
4405
4618
  note
4406
4619
  });
4407
- return binary ? {
4408
- lookup: "failed",
4409
- hex: "",
4410
- note
4411
- } : {
4412
- lookup: "failed",
4413
- content: "",
4414
- note
4415
- };
4620
+ return outcome;
4416
4621
  }
4417
4622
  async #request(url, timeout, allowance, accept, binary = false) {
4418
4623
  if (allowance.remaining <= 0) {
@@ -4427,12 +4632,28 @@ var Upstream = class {
4427
4632
  note
4428
4633
  };
4429
4634
  }
4635
+ const fetched = await fetch(url, {
4636
+ signal: AbortSignal.any([this.#controller.signal, AbortSignal.timeout(timeout)]),
4637
+ redirect: "manual",
4638
+ ...accept === void 0 ? {} : { headers: { accept } }
4639
+ }).then((response) => ({ response }), (error) => ({ error }));
4640
+ if ("error" in fetched) {
4641
+ this.#assertAlive();
4642
+ const note = this.#note(fetched.error);
4643
+ return binary ? {
4644
+ lookup: "failed",
4645
+ hex: "",
4646
+ note,
4647
+ unreachable: true
4648
+ } : {
4649
+ lookup: "failed",
4650
+ content: "",
4651
+ note,
4652
+ unreachable: true
4653
+ };
4654
+ }
4430
4655
  try {
4431
- const response = await fetch(url, {
4432
- signal: AbortSignal.any([this.#controller.signal, AbortSignal.timeout(timeout)]),
4433
- redirect: "manual",
4434
- ...accept === void 0 ? {} : { headers: { accept } }
4435
- });
4656
+ const response = fetched.response;
4436
4657
  if (response.status === 404) {
4437
4658
  await response.body?.cancel();
4438
4659
  return binary ? {
@@ -4558,7 +4779,7 @@ var Upstream = class {
4558
4779
  #note(error) {
4559
4780
  if (!isError(error)) return "the request failed for an unreported reason";
4560
4781
  const cause = error.cause;
4561
- const code = isRecord(cause) && isString(cause.code) ? cause.code : void 0;
4782
+ const code = isObject(cause) && "code" in cause && isString(cause.code) ? cause.code : void 0;
4562
4783
  const message = `${error.name}: ${error.message}`;
4563
4784
  return code === void 0 ? message : `${message} (${code})`;
4564
4785
  }
@@ -4600,6 +4821,6 @@ var Upstream = class {
4600
4821
  return error;
4601
4822
  }
4602
4823
  };
4603
- export { BRANCH_PATTERN, DEFAULT_BRANCH, DEFAULT_REGISTRY_BASE, DEFAULT_REPOSITORY_BASE, DEFAULT_UPSTREAM_CONCURRENCY, DEFAULT_UPSTREAM_RETRIES, DEFAULT_UPSTREAM_TIMEOUT, DIGEST_PATTERN, DRIVE_PATTERN, INVALID_SEGMENT_CHARACTER_PATTERN, MANIFEST_NAME, MAX_BRANCH_LENGTH, MAX_ENDPOINT_LENGTH, MAX_INVENTORY_PATHS, MAX_PATH_DEPTH, MAX_PATH_SEGMENT_BYTES, MAX_UPSTREAM_CONCURRENCY, MAX_UPSTREAM_RETRIES, MAX_UPSTREAM_TIMEOUT, Materializer, ORKESTREL_SCOPE, PACKUMENT_MEDIA_TYPE, RESERVED_SEGMENT_PATTERN, ReadAllowance, SCAFFOLD_REPOSITORY, UNREADABLE_VERSION_NOTE, Upstream, WriteTransaction, climbRealPath, collectIndexed, computeDigest, computeFileDigest, computeManifestDigest, decodeHexText, filesToHost, hexToDigest, isBranch, isCatalogEntries, isDependencies, isDependencyNames, isDigest, isEndpoint, isExactCaseFile, isFilesystemPath, isHost, isHostManifest, isInventory, isManifestEntry, isManifestRegionSet, isMaterializerHooks, isMaterializerOptions, isMirrors, isPaths, isPhysicalDirectory, isPhysicalFile, isTimeout, isUpstreamHooks, isUpstreamOptions, isVacant, isWorktree, listAncestors, listCanonPaths, listDirectories, listFiles, matchesAnchor, matchesExecutablePath, matchesExpectation, matchesGitPath, matchesMissingPath, matchesPrecondition, matchesProtectedPath, matchesSensitivePath, pathToStorage, pruneEmptiedDirectories, readAnchor, readExpectation, readFileHex, readFileText, readHostFloor, readHostManifest, readManifestEntry, readSnapshot, readSurfaceBaseline, readSurfaceCollisions, resolveContainedPath, resolveRealPath, stageBytes, stageHost, stageInventory };
4824
+ export { BRANCH_PATTERN, DEFAULT_BRANCH, DEFAULT_REGISTRY_BASE, DEFAULT_REPOSITORY_BASE, DEFAULT_UPSTREAM_CONCURRENCY, DEFAULT_UPSTREAM_RETRIES, DEFAULT_UPSTREAM_TIMEOUT, DIGEST_PATTERN, DRIVE_PATTERN, INVALID_SEGMENT_CHARACTER_PATTERN, MANIFEST_NAME, MAX_BRANCH_LENGTH, MAX_ENDPOINT_LENGTH, MAX_INVENTORY_PATHS, MAX_PATH_DEPTH, MAX_PATH_SEGMENT_BYTES, MAX_UPSTREAM_CONCURRENCY, MAX_UPSTREAM_RETRIES, MAX_UPSTREAM_TIMEOUT, Materializer, ORKESTREL_SCOPE, PACKUMENT_MEDIA_TYPE, RESERVED_SEGMENT_PATTERN, ReadAllowance, SCAFFOLD_REPOSITORY, UNREADABLE_VERSION_NOTE, Upstream, WriteTransaction, climbRealPath, collectIndexed, computeDigest, computeFileDigest, computeManifestDigest, decodeHexText, filesToHost, hexToDigest, isBranch, isCatalogEntries, isDependencies, isDependencyNames, isDigest, isEndpoint, isExactCaseFile, isFilesystemPath, isHost, isHostManifest, isInventory, isManifestEntry, isManifestRegionSet, isMaterializerHooks, isMaterializerOptions, isMirrors, isPaths, isPhysicalDirectory, isPhysicalFile, isSurfaceModule, isTimeout, isUpstreamHooks, isUpstreamOptions, isVacant, isWorktree, listAncestors, listCanonPaths, listDirectories, listFiles, matchesAnchor, matchesExecutablePath, matchesExpectation, matchesGitPath, matchesMissingPath, matchesPrecondition, matchesProtectedPath, matchesSensitivePath, pathToStorage, pruneEmptiedDirectories, readAnchor, readExpectation, readFileHex, readFileText, readHostFloor, readHostManifest, readManifestEntry, readSnapshot, readSurfaceBaseline, readSurfaceCandidate, readSurfaceClaims, readSurfaceCollisions, readSurfaceFile, readSurfaceGuide, readSurfaceModule, readSurfaceRecord, resolveContainedPath, resolveHostRoot, resolveRealPath, stageBytes, stageHost, stageInventory };
4604
4825
 
4605
4826
  //# sourceMappingURL=index.js.map