@ship.zone/runner 0.1.1 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist_npm/mod.js CHANGED
@@ -95,7 +95,7 @@ var init_errors = __esm({
95
95
  });
96
96
 
97
97
  // ts/plugins.ts
98
- import { ciSpecStatus, runnerProtocolBasePath, runnerProtocolIdentifier } from "@foss.global/ci-spec";
98
+ import { ciSpecStatus, maximumArchivePathMetadataBytes, runnerProtocolBasePath, runnerProtocolIdentifier } from "@foss.global/ci-spec";
99
99
  import { Ajv2020 } from "ajv/dist/2020.js";
100
100
  import runnerJobSchema from "@foss.global/ci-spec/runner-job.schema.json" with { type: "json" };
101
101
  var init_plugins = __esm({
@@ -2090,7 +2090,7 @@ var init_mod = __esm({
2090
2090
 
2091
2091
  // ts/transfer-archive.ts
2092
2092
  import { createHash } from "node:crypto";
2093
- async function* tarChunks(entries, root, rootDevice, signal) {
2093
+ async function* tarChunks(entries, root, rootDevice, openRead, signal) {
2094
2094
  let index = 0;
2095
2095
  for (const entry of entries) {
2096
2096
  if (signal?.aborted) throw signal.reason;
@@ -2132,34 +2132,39 @@ async function* tarChunks(entries, root, rootDevice, signal) {
2132
2132
  const type = entry.type === "directory" ? "5" : entry.type === "symlink" ? "2" : "0";
2133
2133
  yield tarHeader(pathField, type, entry.sizeBytes, entry.executable, linkField);
2134
2134
  if (entry.type === "file") {
2135
- const file = await Deno.open(entry.absolutePath, {
2136
- read: true
2137
- });
2135
+ const file = await openRead(entry.absolutePath);
2138
2136
  let fileError;
2139
2137
  try {
2140
- await assertOpenFileSnapshot(file, entry.snapshot);
2141
- const buffer = new Uint8Array(streamBufferBytes);
2142
- let emitted = 0;
2143
- while (true) {
2144
- if (signal?.aborted) throw signal.reason;
2145
- const read = await file.read(buffer);
2146
- if (read === null) break;
2147
- emitted = checkedAdd(emitted, read, "Workspace export file length overflow");
2148
- if (emitted > entry.sizeBytes) {
2149
- throw new RunnerError("Workspace export file grew during archive creation");
2138
+ {
2139
+ using _fileOwner = {
2140
+ [Symbol.dispose]: () => file.close()
2141
+ };
2142
+ try {
2143
+ await assertOpenFileSnapshot(file, entry.snapshot);
2144
+ const buffer = new Uint8Array(streamBufferBytes);
2145
+ let emitted = 0;
2146
+ while (true) {
2147
+ if (signal?.aborted) throw signal.reason;
2148
+ const read = await file.read(buffer);
2149
+ if (read === null) break;
2150
+ emitted = checkedAdd(emitted, read, "Workspace export file length overflow");
2151
+ if (emitted > entry.sizeBytes) {
2152
+ throw new RunnerError("Workspace export file grew during archive creation");
2153
+ }
2154
+ yield buffer.slice(0, read);
2155
+ }
2156
+ if (emitted !== entry.sizeBytes) {
2157
+ throw new RunnerError("Workspace export file shrank during archive creation");
2158
+ }
2159
+ await assertOpenFileSnapshot(file, entry.snapshot);
2160
+ } catch (error) {
2161
+ fileError = error;
2162
+ throw error;
2150
2163
  }
2151
- yield buffer.slice(0, read);
2152
- }
2153
- if (emitted !== entry.sizeBytes) {
2154
- throw new RunnerError("Workspace export file shrank during archive creation");
2155
2164
  }
2156
- await assertOpenFileSnapshot(file, entry.snapshot);
2157
2165
  } catch (error) {
2158
- fileError = error;
2159
- }
2160
- try {
2161
- file.close();
2162
- } catch (cleanupError) {
2166
+ if (error === fileError) throw error;
2167
+ const cleanupError = error instanceof SuppressedError ? error.error : error;
2163
2168
  throw new ResourceCleanupError("Workspace export file cleanup failed", fileError === void 0 ? [
2164
2169
  cleanupError
2165
2170
  ] : [
@@ -2167,7 +2172,6 @@ async function* tarChunks(entries, root, rootDevice, signal) {
2167
2172
  cleanupError
2168
2173
  ]);
2169
2174
  }
2170
- if (fileError !== void 0) throw fileError;
2171
2175
  await assertSnapshot(entry.absolutePath, entry.snapshot);
2172
2176
  const padding = paddingFor(entry.sizeBytes);
2173
2177
  if (padding.byteLength) yield padding;
@@ -2181,15 +2185,17 @@ async function* tarChunks(entries, root, rootDevice, signal) {
2181
2185
  yield zeroBlock;
2182
2186
  yield zeroBlock;
2183
2187
  }
2184
- var tarBlockSize, maximumPaxHeaderBytes, maximumPathBytes, maximumPathSegmentBytes, streamBufferBytes, zeroBlock, textEncoder, utf8Decoder, asciiDecoder, sha256Pattern2, checkedInteger, checkedAdd, checkedMultiply, defaultFileOperations, removePathIfPresent, cleanupForPath, ensureStagingCapacity, validateTransferMetadata2, assertTransferMetadataEqual, cancelBody, writeAll, stageTransferDownload, pathSegments, validateRelativeSelections, compareUtf8, decodeTarText, parseTarNumber, verifyTarChecksum, parsePaxRecords, StreamBytes, allZero, normalizeArchivePath, parseLinkTarget, isComponentPrefix, validateSymlinkSet, assertArchiveStructure, maximumTarStreamBytes, assertEmptyDirectory, parseTarGzip, extractTarGzipArchive, snapshotFor, typeForStat, assertSnapshot, selectedMembership, collectArchiveEntries, writeAscii, writeTarNumber, ustarPath, tarHeader, paxRecord, paddingFor, assertSafeAncestors, assertOpenFileSnapshot, iteratorStream, createTarGzipArchive, validTimestamp, validateTransferRecord;
2188
+ var tarBlockSize, maximumPaxHeaderBytes, maximumPathBytes, maximumPathSegmentBytes, maximumRetainedSymlinkPathComponents, streamBufferBytes, zeroBlock, textEncoder, utf8Decoder, asciiDecoder, sha256Pattern2, checkedInteger, checkedAdd, checkedMultiply, defaultFileOperations, removePathIfPresent, cleanupForPath, ensureStagingCapacity, validateTransferMetadata2, assertTransferMetadataEqual, cancelBody, writeAll, stageTransferDownload, pathSegments, validateRelativeSelections, compareUtf8Bytes, compareUtf8, yieldToEventLoop, orderByUtf8Bytes, decodeTarText, parseTarNumber, verifyTarChecksum, parsePaxRecords, StreamBytes, allZero, normalizeArchivePath, validateLinkTarget, validateSymlinkSet, recordArchiveStructure, orderArchiveHierarchy, validateArchiveStructure, addPathMetadataBytes, effectivePathMetadataLimit, effectiveMaterializedEntryLimit, maximumTarStreamBytes, assertEmptyDirectory, parseTarGzip, extractTarGzipArchive, snapshotFor, typeForStat, assertSnapshot, selectedMembership, collectArchiveEntries, writeAscii, writeTarNumber, ustarPath, tarHeader, paxRecord, paddingFor, assertSafeAncestors, assertOpenFileSnapshot, iteratorStream, createTarGzipArchive, validTimestamp, validateTransferRecord;
2185
2189
  var init_transfer_archive = __esm({
2186
2190
  "ts/transfer-archive.ts"() {
2187
2191
  init_mod();
2192
+ init_plugins();
2188
2193
  init_errors();
2189
2194
  tarBlockSize = 512;
2190
2195
  maximumPaxHeaderBytes = 16 * 1024;
2191
2196
  maximumPathBytes = 4096;
2192
2197
  maximumPathSegmentBytes = 255;
2198
+ maximumRetainedSymlinkPathComponents = 1e6;
2193
2199
  streamBufferBytes = 64 * 1024;
2194
2200
  zeroBlock = new Uint8Array(tarBlockSize);
2195
2201
  textEncoder = new TextEncoder();
@@ -2219,7 +2225,10 @@ var init_transfer_archive = __esm({
2219
2225
  defaultFileOperations = {
2220
2226
  makeTempFile: /* @__PURE__ */ __name((options) => Deno.makeTempFile(options), "makeTempFile"),
2221
2227
  chmod: /* @__PURE__ */ __name((path, mode) => Deno.chmod(path, mode), "chmod"),
2222
- remove: /* @__PURE__ */ __name((path, options) => Deno.remove(path, options), "remove")
2228
+ remove: /* @__PURE__ */ __name((path, options) => Deno.remove(path, options), "remove"),
2229
+ openRead: /* @__PURE__ */ __name((path) => Deno.open(path, {
2230
+ read: true
2231
+ }), "openRead")
2223
2232
  };
2224
2233
  removePathIfPresent = /* @__PURE__ */ __name(async (path, recursive = false, remove = defaultFileOperations.remove) => {
2225
2234
  try {
@@ -2493,15 +2502,61 @@ var init_transfer_archive = __esm({
2493
2502
  ...paths
2494
2503
  ];
2495
2504
  }, "validateRelativeSelections");
2496
- compareUtf8 = /* @__PURE__ */ __name((left, right) => {
2497
- const leftBytes = textEncoder.encode(left);
2498
- const rightBytes = textEncoder.encode(right);
2505
+ compareUtf8Bytes = /* @__PURE__ */ __name((leftBytes, rightBytes) => {
2499
2506
  const length = Math.min(leftBytes.byteLength, rightBytes.byteLength);
2500
2507
  for (let index = 0; index < length; index++) {
2501
2508
  if (leftBytes[index] !== rightBytes[index]) return leftBytes[index] - rightBytes[index];
2502
2509
  }
2503
2510
  return leftBytes.byteLength - rightBytes.byteLength;
2504
- }, "compareUtf8");
2511
+ }, "compareUtf8Bytes");
2512
+ compareUtf8 = /* @__PURE__ */ __name((left, right) => compareUtf8Bytes(textEncoder.encode(left), textEncoder.encode(right)), "compareUtf8");
2513
+ yieldToEventLoop = /* @__PURE__ */ __name(() => new Promise((resolvePromise) => setTimeout(resolvePromise, 0)), "yieldToEventLoop");
2514
+ orderByUtf8Bytes = /* @__PURE__ */ __name(async (values, bytesFor, signal) => {
2515
+ const ordered = [];
2516
+ const pending = [
2517
+ {
2518
+ values,
2519
+ offset: 0
2520
+ }
2521
+ ];
2522
+ let operationsUntilYield = 262144;
2523
+ while (pending.length > 0) {
2524
+ if (signal?.aborted) throw signal.reason;
2525
+ const group = pending.pop();
2526
+ if (group.values.length === 1) {
2527
+ ordered.push(group.values[0]);
2528
+ continue;
2529
+ }
2530
+ const buckets = /* @__PURE__ */ new Map();
2531
+ for (const value of group.values) {
2532
+ const bytes = bytesFor(value);
2533
+ const code = group.offset < bytes.byteLength ? bytes[group.offset] + 1 : 0;
2534
+ const bucket = buckets.get(code);
2535
+ if (bucket) bucket.push(value);
2536
+ else buckets.set(code, [
2537
+ value
2538
+ ]);
2539
+ operationsUntilYield--;
2540
+ if (operationsUntilYield === 0) {
2541
+ await yieldToEventLoop();
2542
+ if (signal?.aborted) throw signal.reason;
2543
+ operationsUntilYield = 262144;
2544
+ }
2545
+ }
2546
+ const ended = buckets.get(0);
2547
+ if (ended) ordered.push(...ended);
2548
+ const codes = [
2549
+ ...buckets.keys()
2550
+ ].filter((code) => code > 0).sort((left, right) => left - right);
2551
+ for (let index = codes.length - 1; index >= 0; index--) {
2552
+ pending.push({
2553
+ values: buckets.get(codes[index]),
2554
+ offset: group.offset + 1
2555
+ });
2556
+ }
2557
+ }
2558
+ return ordered;
2559
+ }, "orderByUtf8Bytes");
2505
2560
  decodeTarText = /* @__PURE__ */ __name((bytes, field2) => {
2506
2561
  const nul = bytes.indexOf(0);
2507
2562
  const valueBytes = nul === -1 ? bytes : bytes.subarray(0, nul);
@@ -2705,73 +2760,289 @@ var init_transfer_archive = __esm({
2705
2760
  }
2706
2761
  return pathSegments(normalized, maximumPathBytes, "Tar archive").join("/");
2707
2762
  }, "normalizeArchivePath");
2708
- parseLinkTarget = /* @__PURE__ */ __name((target) => {
2763
+ validateLinkTarget = /* @__PURE__ */ __name((target) => {
2709
2764
  if (!target || target.startsWith("/") || target.includes("\\") || target.includes("\0") || textEncoder.encode(target).byteLength > maximumPathBytes) {
2710
2765
  throw new ProtocolError("Tar symlink target is unsafe");
2711
2766
  }
2712
- const segments = target.split("/");
2713
- if (segments.some((segment) => !segment || textEncoder.encode(segment).byteLength > maximumPathSegmentBytes)) {
2714
- throw new ProtocolError("Tar symlink target is unsafe");
2767
+ let offset = 0;
2768
+ while (offset <= target.length) {
2769
+ const separator = target.indexOf("/", offset);
2770
+ const segment = target.slice(offset, separator === -1 ? target.length : separator);
2771
+ if (!segment || textEncoder.encode(segment).byteLength > maximumPathSegmentBytes) {
2772
+ throw new ProtocolError("Tar symlink target is unsafe");
2773
+ }
2774
+ if (separator === -1) break;
2775
+ offset = separator + 1;
2776
+ }
2777
+ }, "validateLinkTarget");
2778
+ validateSymlinkSet = /* @__PURE__ */ __name(async (symlinks, signal) => {
2779
+ if (symlinks.length === 0) return;
2780
+ let operationsUntilYield = 262144;
2781
+ const accountOperations = /* @__PURE__ */ __name(async (operations) => {
2782
+ operationsUntilYield -= operations;
2783
+ if (operationsUntilYield > 0) return;
2784
+ await yieldToEventLoop();
2785
+ if (signal?.aborted) throw signal.reason;
2786
+ operationsUntilYield = 262144;
2787
+ }, "accountOperations");
2788
+ const edgeFactor = maximumRetainedSymlinkPathComponents + 1;
2789
+ const segmentIds = /* @__PURE__ */ new Map();
2790
+ const edges = /* @__PURE__ */ new Map();
2791
+ const parents = [
2792
+ 0
2793
+ ];
2794
+ const depths = [
2795
+ 0
2796
+ ];
2797
+ const segmentId = /* @__PURE__ */ __name((segment) => {
2798
+ const existing = segmentIds.get(segment);
2799
+ if (existing !== void 0) return existing;
2800
+ const identifier = segmentIds.size + 1;
2801
+ if (identifier > maximumRetainedSymlinkPathComponents) {
2802
+ throw new ProtocolError("Tar archive exceeds the retained symlink path component limit");
2803
+ }
2804
+ segmentIds.set(segment, identifier);
2805
+ return identifier;
2806
+ }, "segmentId");
2807
+ const pathNodeForChild = /* @__PURE__ */ __name((parent, segment) => {
2808
+ const key = parent * edgeFactor + segmentId(segment);
2809
+ const existing = edges.get(key);
2810
+ if (existing !== void 0) return existing;
2811
+ const node = parents.length;
2812
+ if (node > maximumRetainedSymlinkPathComponents) {
2813
+ throw new ProtocolError("Tar archive exceeds the retained symlink path component limit");
2814
+ }
2815
+ parents.push(parent);
2816
+ depths.push(depths[parent] + 1);
2817
+ edges.set(key, node);
2818
+ return node;
2819
+ }, "pathNodeForChild");
2820
+ const pathNode = /* @__PURE__ */ __name((segments) => {
2821
+ let current = 0;
2822
+ for (const segment of segments) current = pathNodeForChild(current, segment);
2823
+ return current;
2824
+ }, "pathNode");
2825
+ const withinScope = /* @__PURE__ */ __name((path, scope) => {
2826
+ let current = path;
2827
+ while (depths[current] > depths[scope]) current = parents[current];
2828
+ return current === scope;
2829
+ }, "withinScope");
2830
+ const symlinkByPath = /* @__PURE__ */ new Map();
2831
+ const nodeBySymlink = /* @__PURE__ */ new Map();
2832
+ const symlinksByScope = /* @__PURE__ */ new Map();
2833
+ for (const symlink of symlinks) {
2834
+ const pathSegments2 = symlink.path.split("/");
2835
+ const path = pathNode(pathSegments2);
2836
+ const scope = pathNode(symlink.scope);
2837
+ symlinkByPath.set(path, symlink);
2838
+ nodeBySymlink.set(symlink, path);
2839
+ const scoped = symlinksByScope.get(scope);
2840
+ if (scoped) scoped.push(symlink);
2841
+ else symlinksByScope.set(scope, [
2842
+ symlink
2843
+ ]);
2844
+ await accountOperations(pathSegments2.length + symlink.scope.length);
2715
2845
  }
2716
- return segments;
2717
- }, "parseLinkTarget");
2718
- isComponentPrefix = /* @__PURE__ */ __name((prefix, value) => prefix.length <= value.length && prefix.every((component, index) => component === value[index]), "isComponentPrefix");
2719
- validateSymlinkSet = /* @__PURE__ */ __name((symlinks) => {
2720
- const byPath = new Map(symlinks.map((entry) => [
2721
- entry.path,
2722
- entry
2723
- ]));
2724
- const resolveTarget = /* @__PURE__ */ __name((base, target, scope, active) => {
2725
- let current = [
2726
- ...base
2727
- ];
2728
- for (const segment of parseLinkTarget(target)) {
2729
- if (segment === ".") continue;
2730
- if (segment === "..") {
2731
- if (current.length <= scope.length) {
2732
- throw new ProtocolError("Tar symlink target escapes its collection root");
2846
+ const beginFrame = /* @__PURE__ */ __name((entry, scope) => {
2847
+ const path = nodeBySymlink.get(entry);
2848
+ const current = parents[path];
2849
+ if (!withinScope(current, scope)) {
2850
+ throw new ProtocolError("Tar symlink target escapes its collection root");
2851
+ }
2852
+ return {
2853
+ path,
2854
+ scope,
2855
+ current,
2856
+ target: entry.target,
2857
+ offset: 0
2858
+ };
2859
+ }, "beginFrame");
2860
+ for (const [scope, scopedSymlinks] of symlinksByScope) {
2861
+ const resolutions = /* @__PURE__ */ new Map();
2862
+ for (const symlink of scopedSymlinks) {
2863
+ const path = nodeBySymlink.get(symlink);
2864
+ if (resolutions.get(path)?.status === "resolved") continue;
2865
+ resolutions.set(path, {
2866
+ status: "visiting"
2867
+ });
2868
+ const frames = [
2869
+ beginFrame(symlink, scope)
2870
+ ];
2871
+ while (frames.length > 0) {
2872
+ const frame = frames[frames.length - 1];
2873
+ if (frame.waitingFor) {
2874
+ const resolution = resolutions.get(frame.waitingFor);
2875
+ if (resolution?.status !== "resolved") {
2876
+ throw new ProtocolError("Tar symlink resolution did not complete");
2877
+ }
2878
+ frame.current = resolution.path;
2879
+ frame.waitingFor = void 0;
2880
+ continue;
2733
2881
  }
2734
- current.pop();
2735
- } else {
2736
- current.push(segment);
2737
- const linkedPath = current.join("/");
2738
- const linked = byPath.get(linkedPath);
2739
- if (linked) {
2740
- if (active.has(linkedPath)) throw new ProtocolError("Tar symlink chain is cyclic");
2741
- const nextActive = new Set(active);
2742
- nextActive.add(linkedPath);
2743
- current = resolveTarget(linkedPath.split("/").slice(0, -1), linked.target, scope, nextActive);
2882
+ if (frame.offset > frame.target.length) {
2883
+ resolutions.set(frame.path, {
2884
+ status: "resolved",
2885
+ path: frame.current
2886
+ });
2887
+ frames.pop();
2888
+ continue;
2889
+ }
2890
+ const separator = frame.target.indexOf("/", frame.offset);
2891
+ const segment = frame.target.slice(frame.offset, separator === -1 ? frame.target.length : separator);
2892
+ frame.offset = separator === -1 ? frame.target.length + 1 : separator + 1;
2893
+ await accountOperations(1);
2894
+ if (segment === ".") continue;
2895
+ if (segment === "..") {
2896
+ if (depths[frame.current] <= depths[frame.scope]) {
2897
+ throw new ProtocolError("Tar symlink target escapes its collection root");
2898
+ }
2899
+ frame.current = parents[frame.current];
2900
+ } else {
2901
+ frame.current = pathNodeForChild(frame.current, segment);
2902
+ const linked = symlinkByPath.get(frame.current);
2903
+ if (linked) {
2904
+ const linkedPath = nodeBySymlink.get(linked);
2905
+ const resolution = resolutions.get(linkedPath);
2906
+ if (resolution?.status === "visiting") {
2907
+ throw new ProtocolError("Tar symlink chain is cyclic");
2908
+ }
2909
+ if (resolution?.status === "resolved") {
2910
+ frame.current = resolution.path;
2911
+ } else {
2912
+ resolutions.set(linkedPath, {
2913
+ status: "visiting"
2914
+ });
2915
+ frame.waitingFor = linkedPath;
2916
+ frames.push(beginFrame(linked, frame.scope));
2917
+ }
2918
+ }
2744
2919
  }
2745
- }
2746
- if (!isComponentPrefix(scope, current)) {
2747
- throw new ProtocolError("Tar symlink target escapes its collection root");
2748
2920
  }
2749
2921
  }
2750
- return current;
2751
- }, "resolveTarget");
2752
- for (const symlink of symlinks) {
2753
- const active = /* @__PURE__ */ new Set([
2754
- symlink.path
2755
- ]);
2756
- resolveTarget(symlink.path.split("/").slice(0, -1), symlink.target, symlink.scope, active);
2757
2922
  }
2758
2923
  }, "validateSymlinkSet");
2759
- assertArchiveStructure = /* @__PURE__ */ __name((seen, path, type) => {
2760
- if (seen.has(path)) throw new ProtocolError("Tar archive contains a duplicate path");
2761
- const segments = path.split("/");
2762
- for (let length = 1; length < segments.length; length++) {
2763
- const ancestor = seen.get(segments.slice(0, length).join("/"));
2764
- if (ancestor && ancestor !== "directory") {
2765
- throw new ProtocolError("Tar archive contains entries below a non-directory");
2924
+ recordArchiveStructure = /* @__PURE__ */ __name((byPath, entries, path, type) => {
2925
+ if (byPath.has(path)) throw new ProtocolError("Tar archive contains a duplicate path");
2926
+ const entry = {
2927
+ path,
2928
+ type,
2929
+ order: entries.length
2930
+ };
2931
+ byPath.set(path, entry);
2932
+ entries.push(entry);
2933
+ }, "recordArchiveStructure");
2934
+ orderArchiveHierarchy = /* @__PURE__ */ __name(async (entries, signal) => {
2935
+ const ordered = [];
2936
+ const pending = [
2937
+ {
2938
+ entries,
2939
+ offset: 0
2940
+ }
2941
+ ];
2942
+ let operationsUntilYield = 262144;
2943
+ while (pending.length > 0) {
2944
+ if (signal?.aborted) throw signal.reason;
2945
+ const group = pending.pop();
2946
+ if (group.entries.length === 1) {
2947
+ ordered.push(group.entries[0]);
2948
+ continue;
2949
+ }
2950
+ const buckets = /* @__PURE__ */ new Map();
2951
+ for (const entry of group.entries) {
2952
+ let code = 0;
2953
+ if (group.offset < entry.path.length) {
2954
+ const character = entry.path.charCodeAt(group.offset);
2955
+ code = character === 47 ? 1 : character + 2;
2956
+ }
2957
+ const bucket = buckets.get(code);
2958
+ if (bucket) bucket.push(entry);
2959
+ else buckets.set(code, [
2960
+ entry
2961
+ ]);
2962
+ operationsUntilYield--;
2963
+ if (operationsUntilYield === 0) {
2964
+ await yieldToEventLoop();
2965
+ if (signal?.aborted) throw signal.reason;
2966
+ operationsUntilYield = 262144;
2967
+ }
2968
+ }
2969
+ const ended = buckets.get(0);
2970
+ if (ended) ordered.push(...ended);
2971
+ const descendants = buckets.get(1);
2972
+ const following = [];
2973
+ if (descendants) following.push(descendants);
2974
+ for (const [code, bucket] of buckets) {
2975
+ if (code > 1) following.push(bucket);
2976
+ }
2977
+ for (let index = following.length - 1; index >= 0; index--) {
2978
+ pending.push({
2979
+ entries: following[index],
2980
+ offset: group.offset + 1
2981
+ });
2766
2982
  }
2767
2983
  }
2768
- if ([
2769
- ...seen.keys()
2770
- ].some((candidate) => candidate.startsWith(`${path}/`))) {
2771
- throw new ProtocolError("Tar archive declares an ancestor after its descendants");
2772
- }
2773
- seen.set(path, type);
2774
- }, "assertArchiveStructure");
2984
+ return ordered;
2985
+ }, "orderArchiveHierarchy");
2986
+ validateArchiveStructure = /* @__PURE__ */ __name(async (entries, maximumMaterializedEntries, signal) => {
2987
+ const orderedEntries = await orderArchiveHierarchy(entries, signal);
2988
+ const ancestors = [];
2989
+ let previousDirectories = [];
2990
+ let materializedDirectories = 0;
2991
+ let nonDirectories = 0;
2992
+ let operationsUntilYield = 262144;
2993
+ for (const entry of orderedEntries) {
2994
+ while (ancestors.length > 0 && !entry.path.startsWith(`${ancestors[ancestors.length - 1].path}/`)) {
2995
+ ancestors.pop();
2996
+ }
2997
+ const ancestor = ancestors.at(-1);
2998
+ if (ancestor?.type !== void 0 && ancestor.type !== "directory") {
2999
+ throw new ProtocolError("Tar archive contains entries below a non-directory");
3000
+ }
3001
+ if (ancestor && ancestor.order > entry.order) {
3002
+ throw new ProtocolError("Tar archive declares an ancestor after its descendants");
3003
+ }
3004
+ const segments = entry.path.split("/");
3005
+ const directoryDepth = segments.length - (entry.type === "directory" ? 0 : 1);
3006
+ let commonDirectories = 0;
3007
+ while (commonDirectories < directoryDepth && commonDirectories < previousDirectories.length && segments[commonDirectories] === previousDirectories[commonDirectories]) {
3008
+ commonDirectories++;
3009
+ }
3010
+ materializedDirectories = checkedAdd(materializedDirectories, directoryDepth - commonDirectories, "Tar materialized directory count overflow");
3011
+ previousDirectories = segments.slice(0, directoryDepth);
3012
+ if (entry.type !== "directory") nonDirectories++;
3013
+ const materializedEntries = checkedAdd(materializedDirectories, nonDirectories, "Tar materialized entry count overflow");
3014
+ if (materializedEntries > maximumMaterializedEntries) {
3015
+ throw new ProtocolError("Tar archive exceeds the effective workspace entry limit");
3016
+ }
3017
+ ancestors.push(entry);
3018
+ operationsUntilYield -= entry.path.length + segments.length;
3019
+ if (operationsUntilYield <= 0) {
3020
+ await yieldToEventLoop();
3021
+ if (signal?.aborted) throw signal.reason;
3022
+ operationsUntilYield = 262144;
3023
+ }
3024
+ }
3025
+ return materializedDirectories + nonDirectories;
3026
+ }, "validateArchiveStructure");
3027
+ addPathMetadataBytes = /* @__PURE__ */ __name((current, value, maximum) => {
3028
+ const next = checkedAdd(current, textEncoder.encode(value).byteLength, "Archive path metadata byte count overflow");
3029
+ if (next > maximum) {
3030
+ throw new ProtocolError("Archive exceeds the effective path metadata byte limit");
3031
+ }
3032
+ return next;
3033
+ }, "addPathMetadataBytes");
3034
+ effectivePathMetadataLimit = /* @__PURE__ */ __name((configured) => {
3035
+ const limit = configured ?? maximumArchivePathMetadataBytes;
3036
+ checkedInteger(limit, "Maximum archive path metadata bytes", false);
3037
+ if (limit > maximumArchivePathMetadataBytes) {
3038
+ throw new ProtocolError("Maximum archive path metadata bytes exceeds the protocol ceiling");
3039
+ }
3040
+ return limit;
3041
+ }, "effectivePathMetadataLimit");
3042
+ effectiveMaterializedEntryLimit = /* @__PURE__ */ __name((options) => {
3043
+ const limit = options.maximumMaterializedEntries ?? checkedMultiply(options.maximumEntries, 2, "Maximum materialized archive entries overflow");
3044
+ return checkedInteger(limit, "Maximum materialized archive entries");
3045
+ }, "effectiveMaterializedEntryLimit");
2775
3046
  maximumTarStreamBytes = /* @__PURE__ */ __name((maximumExtractedBytes, maximumEntries) => {
2776
3047
  const perEntryOverhead = maximumPaxHeaderBytes + tarBlockSize * 4;
2777
3048
  return checkedAdd(checkedAdd(maximumExtractedBytes, checkedMultiply(maximumEntries, perEntryOverhead, "Tar structural limit overflow"), "Tar structural limit overflow"), maximumPaxHeaderBytes + tarBlockSize * 4, "Tar structural limit overflow");
@@ -2793,6 +3064,8 @@ var init_transfer_archive = __esm({
2793
3064
  }, "assertEmptyDirectory");
2794
3065
  parseTarGzip = /* @__PURE__ */ __name(async (options, destination, extract) => {
2795
3066
  const allowedPaths = options.allowedPaths ? validateRelativeSelections(options.allowedPaths, "Cache declaration") : void 0;
3067
+ const maximumPathMetadataBytes = effectivePathMetadataLimit(options.maximumPathMetadataBytes);
3068
+ const maximumMaterializedEntries = effectiveMaterializedEntryLimit(options);
2796
3069
  const archive = await Deno.open(options.archivePath, {
2797
3070
  read: true
2798
3071
  }).catch((error) => {
@@ -2816,13 +3089,15 @@ var init_transfer_archive = __esm({
2816
3089
  cause: error
2817
3090
  });
2818
3091
  }
2819
- const bytes = new StreamBytes(decompressed, maximumTarStreamBytes(options.maximumExtractedBytes, options.maximumEntries), options.signal);
2820
- const seen = /* @__PURE__ */ new Map();
3092
+ const bytes = new StreamBytes(decompressed, maximumTarStreamBytes(options.expectedMetadata.extractedSizeBytes, options.expectedMetadata.entryCount), options.signal);
3093
+ const archiveStructure = /* @__PURE__ */ new Map();
3094
+ const archiveEntries = [];
2821
3095
  const symlinks = [];
2822
3096
  let localPax;
2823
3097
  let globalPaxSeen = false;
2824
3098
  let logicalBytes = 0;
2825
3099
  let entryCount = 0;
3100
+ let pathMetadataBytes = 0;
2826
3101
  let complete = false;
2827
3102
  let primaryError;
2828
3103
  let result;
@@ -2870,7 +3145,7 @@ var init_transfer_archive = __esm({
2870
3145
  }
2871
3146
  const records = parsePaxRecords(content);
2872
3147
  if (type === "g") {
2873
- if (globalPaxSeen || localPax || seen.size > 0 || records.size !== 1 || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(records.get("comment") ?? "")) {
3148
+ if (globalPaxSeen || localPax || entryCount > 0 || records.size !== 1 || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(records.get("comment") ?? "")) {
2874
3149
  throw new ProtocolError("Tar global PAX metadata is unsupported");
2875
3150
  }
2876
3151
  globalPaxSeen = true;
@@ -2896,14 +3171,15 @@ var init_transfer_archive = __esm({
2896
3171
  throw new ProtocolError("Tar archive contains a hardlink, special, or unsupported entry");
2897
3172
  }
2898
3173
  entryCount = checkedAdd(entryCount, 1, "Tar entry count overflow");
2899
- if (entryCount > options.maximumEntries) {
3174
+ if (entryCount > options.maximumEntries || entryCount > options.expectedMetadata.entryCount) {
2900
3175
  throw new ProtocolError("Tar archive exceeds the effective entry limit");
2901
3176
  }
2902
3177
  const entryPax = localPax;
2903
3178
  localPax = void 0;
2904
3179
  const path = normalizeArchivePath(entryPax?.path ?? headerPath, type);
3180
+ pathMetadataBytes = addPathMetadataBytes(pathMetadataBytes, path, maximumPathMetadataBytes);
2905
3181
  const entryType = type === "5" ? "directory" : type === "2" ? "symlink" : "file";
2906
- assertArchiveStructure(seen, path, entryType);
3182
+ recordArchiveStructure(archiveStructure, archiveEntries, path, entryType);
2907
3183
  if (allowedPaths) {
2908
3184
  const selected = allowedPaths.some((allowed) => path === allowed || path.startsWith(`${allowed}/`));
2909
3185
  const requiredAncestor = entryType === "directory" && allowedPaths.some((allowed) => allowed.startsWith(`${path}/`));
@@ -2929,7 +3205,8 @@ var init_transfer_archive = __esm({
2929
3205
  }
2930
3206
  if (sizeBytes !== 0) throw new ProtocolError("Tar symlink has a non-zero size");
2931
3207
  const linkTarget = entryPax?.linkpath ?? decodeTarText(header.subarray(157, 257), "link name");
2932
- parseLinkTarget(linkTarget);
3208
+ validateLinkTarget(linkTarget);
3209
+ pathMetadataBytes = addPathMetadataBytes(pathMetadataBytes, linkTarget, maximumPathMetadataBytes);
2933
3210
  symlinks.push({
2934
3211
  path,
2935
3212
  target: linkTarget,
@@ -2940,7 +3217,7 @@ var init_transfer_archive = __esm({
2940
3217
  throw new ProtocolError("Tar regular file has link metadata");
2941
3218
  }
2942
3219
  logicalBytes = checkedAdd(logicalBytes, sizeBytes, "Tar logical byte count overflow");
2943
- if (logicalBytes > options.maximumExtractedBytes) {
3220
+ if (logicalBytes > options.maximumExtractedBytes || logicalBytes > options.expectedMetadata.extractedSizeBytes) {
2944
3221
  throw new ProtocolError("Tar archive exceeds the effective extracted byte limit");
2945
3222
  }
2946
3223
  let output;
@@ -2983,10 +3260,11 @@ var init_transfer_archive = __esm({
2983
3260
  }
2984
3261
  }
2985
3262
  if (localPax) throw new ProtocolError("Tar archive ends with unused PAX metadata");
2986
- validateSymlinkSet(symlinks);
3263
+ const materializedEntryCount = await validateArchiveStructure(archiveEntries, maximumMaterializedEntries, options.signal);
3264
+ await validateSymlinkSet(symlinks, options.signal);
2987
3265
  if (allowedPaths && options.requireAllowedPaths) {
2988
3266
  for (const allowed of allowedPaths) {
2989
- if (!seen.has(allowed)) {
3267
+ if (!archiveStructure.has(allowed)) {
2990
3268
  throw new ProtocolError("Cache archive omits a declared path");
2991
3269
  }
2992
3270
  }
@@ -2996,6 +3274,7 @@ var init_transfer_archive = __esm({
2996
3274
  }
2997
3275
  if (extract) {
2998
3276
  for (const symlink of symlinks) {
3277
+ if (options.signal?.aborted) throw options.signal.reason;
2999
3278
  const target = join3(destination, ...symlink.path.split("/"));
3000
3279
  await Deno.mkdir(dirname3(target), {
3001
3280
  recursive: true,
@@ -3007,7 +3286,8 @@ var init_transfer_archive = __esm({
3007
3286
  complete = true;
3008
3287
  result = {
3009
3288
  logicalBytes,
3010
- entryCount
3289
+ entryCount,
3290
+ materializedEntryCount
3011
3291
  };
3012
3292
  } catch (error) {
3013
3293
  primaryError = error;
@@ -3032,11 +3312,17 @@ var init_transfer_archive = __esm({
3032
3312
  extractTarGzipArchive = /* @__PURE__ */ __name(async (options) => {
3033
3313
  checkedInteger(options.maximumExtractedBytes, "Maximum extracted bytes");
3034
3314
  checkedInteger(options.maximumEntries, "Maximum archive entries");
3315
+ checkedInteger(options.expectedMetadata.extractedSizeBytes, "Declared extracted bytes");
3316
+ checkedInteger(options.expectedMetadata.entryCount, "Declared archive entries");
3317
+ effectiveMaterializedEntryLimit(options);
3318
+ checkedInteger(options.reserveBytes ?? 0, "Archive staging byte reserve");
3319
+ checkedInteger(options.reserveInodes ?? 0, "Archive staging inode reserve");
3035
3320
  if (options.expectedMetadata.extractedSizeBytes > options.maximumExtractedBytes || options.expectedMetadata.entryCount > options.maximumEntries) {
3036
3321
  throw new ProtocolError("Transfer metadata exceeds the effective extraction limits");
3037
3322
  }
3038
3323
  const destination = await assertEmptyDirectory(options.destinationPath);
3039
- await parseTarGzip(options, destination, false);
3324
+ const inspected = await parseTarGzip(options, destination, false);
3325
+ await ensureStagingCapacity(destination, inspected.logicalBytes, inspected.materializedEntryCount, options.reserveBytes ?? 0, options.reserveInodes ?? 0);
3040
3326
  return await parseTarGzip(options, destination, true);
3041
3327
  }, "extractTarGzipArchive");
3042
3328
  snapshotFor = /* @__PURE__ */ __name((stat, type, label) => {
@@ -3075,16 +3361,24 @@ var init_transfer_archive = __esm({
3075
3361
  if (selected) {
3076
3362
  return {
3077
3363
  accepted: true,
3078
- scope: path === selected ? selected.split("/").slice(0, -1) : selected.split("/")
3364
+ selected
3079
3365
  };
3080
3366
  }
3081
3367
  return {
3082
- accepted: type === "directory" && selections.some((candidate) => candidate.startsWith(`${path}/`)),
3083
- scope: []
3368
+ accepted: type === "directory" && selections.some((candidate) => candidate.startsWith(`${path}/`))
3084
3369
  };
3085
3370
  }, "selectedMembership");
3086
3371
  collectArchiveEntries = /* @__PURE__ */ __name(async (options) => {
3372
+ if (options.signal?.aborted) throw options.signal.reason;
3087
3373
  const selections = validateRelativeSelections(options.selections, "Workspace export selection");
3374
+ const scopesBySelection = /* @__PURE__ */ new Map();
3375
+ for (const selection of selections) {
3376
+ const descendantScope = selection.split("/");
3377
+ scopesBySelection.set(selection, {
3378
+ descendantScope,
3379
+ selectedEntryScope: descendantScope.slice(0, -1)
3380
+ });
3381
+ }
3088
3382
  const root = await Deno.realPath(options.sourcePath).catch((error) => {
3089
3383
  throw new RunnerError("Unable to resolve workspace export root", {
3090
3384
  cause: error
@@ -3098,9 +3392,50 @@ var init_transfer_archive = __esm({
3098
3392
  const entries = [];
3099
3393
  const present = /* @__PURE__ */ new Set();
3100
3394
  let logicalBytes = 0;
3395
+ let pathMetadataBytes = 0;
3396
+ let pendingPathMetadataBytes = 0;
3397
+ let pendingEntries = 0;
3398
+ const maximumPathMetadataBytes = effectivePathMetadataLimit(options.maximumPathMetadataBytes);
3399
+ const retainPathMetadata = /* @__PURE__ */ __name((value) => {
3400
+ const next = addPathMetadataBytes(pathMetadataBytes, value, maximumPathMetadataBytes);
3401
+ const retained = checkedAdd(next, pendingPathMetadataBytes, "Workspace export retained path metadata overflow");
3402
+ if (retained > maximumPathMetadataBytes) {
3403
+ throw new ProtocolError("Archive exceeds the effective path metadata byte limit");
3404
+ }
3405
+ pathMetadataBytes = next;
3406
+ }, "retainPathMetadata");
3407
+ const collectChildren = /* @__PURE__ */ __name(async (absolutePath, parentPath) => {
3408
+ const children = [];
3409
+ for await (const child of Deno.readDir(absolutePath)) {
3410
+ if (options.signal?.aborted) throw options.signal.reason;
3411
+ const childPath = parentPath ? `${parentPath}/${child.name}` : child.name;
3412
+ pathSegments(childPath, maximumPathBytes, "Workspace export");
3413
+ const nameBytes = textEncoder.encode(child.name);
3414
+ const pathBytes = textEncoder.encode(childPath).byteLength;
3415
+ const nextPendingEntries = checkedAdd(pendingEntries, 1, "Workspace export pending entry count overflow");
3416
+ const retainedEntries = checkedAdd(entries.length, nextPendingEntries, "Workspace export retained entry count overflow");
3417
+ if (retainedEntries > options.maximumEntries || retainedEntries > options.expectedMetadata.entryCount) {
3418
+ throw new ProtocolError("Workspace export exceeds the effective entry limit");
3419
+ }
3420
+ const nextPendingPathMetadataBytes = checkedAdd(pendingPathMetadataBytes, pathBytes, "Workspace export pending path metadata overflow");
3421
+ const retainedPathMetadataBytes = checkedAdd(pathMetadataBytes, nextPendingPathMetadataBytes, "Workspace export retained path metadata overflow");
3422
+ if (retainedPathMetadataBytes > maximumPathMetadataBytes) {
3423
+ throw new ProtocolError("Archive exceeds the effective path metadata byte limit");
3424
+ }
3425
+ pendingEntries = nextPendingEntries;
3426
+ pendingPathMetadataBytes = nextPendingPathMetadataBytes;
3427
+ children.push({
3428
+ name: child.name,
3429
+ nameBytes,
3430
+ pathBytes
3431
+ });
3432
+ }
3433
+ return await orderByUtf8Bytes(children, (child) => child.nameBytes, options.signal);
3434
+ }, "collectChildren");
3101
3435
  const visit = /* @__PURE__ */ __name(async (path) => {
3102
3436
  if (options.signal?.aborted) throw options.signal.reason;
3103
3437
  pathSegments(path, maximumPathBytes, "Workspace export");
3438
+ retainPathMetadata(path);
3104
3439
  const absolutePath = join3(root, ...path.split("/"));
3105
3440
  const stat = await Deno.lstat(absolutePath);
3106
3441
  const type = typeForStat(stat);
@@ -3119,13 +3454,17 @@ var init_transfer_archive = __esm({
3119
3454
  throw new RunnerError("Workspace export contains a symbolic link");
3120
3455
  }
3121
3456
  let linkTarget;
3457
+ let symlinkScope;
3122
3458
  if (type === "symlink") {
3123
3459
  linkTarget = await Deno.readLink(absolutePath);
3124
- parseLinkTarget(linkTarget);
3460
+ validateLinkTarget(linkTarget);
3461
+ retainPathMetadata(linkTarget);
3462
+ const selectionScopes = scopesBySelection.get(membership.selected);
3463
+ symlinkScope = path === membership.selected ? selectionScopes.selectedEntryScope : selectionScopes.descendantScope;
3125
3464
  }
3126
3465
  const sizeBytes = type === "file" ? snapshot.size : 0;
3127
3466
  logicalBytes = checkedAdd(logicalBytes, sizeBytes, "Workspace export byte count overflow");
3128
- if (logicalBytes > options.maximumExtractedBytes) {
3467
+ if (logicalBytes > options.maximumExtractedBytes || logicalBytes > options.expectedMetadata.logicalBytes) {
3129
3468
  throw new ProtocolError("Workspace export exceeds the effective extracted byte limit");
3130
3469
  }
3131
3470
  entries.push({
@@ -3137,26 +3476,37 @@ var init_transfer_archive = __esm({
3137
3476
  ...linkTarget === void 0 ? {} : {
3138
3477
  linkTarget
3139
3478
  },
3140
- symlinkScope: membership.scope,
3479
+ ...symlinkScope === void 0 ? {} : {
3480
+ symlinkScope
3481
+ },
3141
3482
  snapshot
3142
3483
  });
3143
3484
  present.add(path);
3144
- if (entries.length > options.maximumEntries) {
3485
+ if (entries.length > options.maximumEntries || entries.length > options.expectedMetadata.entryCount) {
3145
3486
  throw new ProtocolError("Workspace export exceeds the effective entry limit");
3146
3487
  }
3147
3488
  if (type === "directory") {
3148
- const children = [];
3149
- for await (const child of Deno.readDir(absolutePath)) children.push(child.name);
3150
- children.sort(compareUtf8);
3151
- for (const child of children) await visit(`${path}/${child}`);
3489
+ const children = await collectChildren(absolutePath, path);
3490
+ for (let index = 0; index < children.length; index++) {
3491
+ if (options.signal?.aborted) throw options.signal.reason;
3492
+ const child = children[index];
3493
+ children[index] = void 0;
3494
+ pendingEntries--;
3495
+ pendingPathMetadataBytes -= child.pathBytes;
3496
+ await visit(`${path}/${child.name}`);
3497
+ }
3152
3498
  await assertSnapshot(absolutePath, snapshot);
3153
3499
  }
3154
3500
  }, "visit");
3155
- const roots = [];
3156
- for await (const entry of Deno.readDir(root)) roots.push(entry.name);
3157
- roots.sort(compareUtf8);
3158
- for (const path of roots) await visit(path);
3159
- entries.sort((left, right) => compareUtf8(left.path, right.path));
3501
+ const roots = await collectChildren(root, "");
3502
+ for (let index = 0; index < roots.length; index++) {
3503
+ if (options.signal?.aborted) throw options.signal.reason;
3504
+ const rootEntry = roots[index];
3505
+ roots[index] = void 0;
3506
+ pendingEntries--;
3507
+ pendingPathMetadataBytes -= rootEntry.pathBytes;
3508
+ await visit(rootEntry.name);
3509
+ }
3160
3510
  if (options.requireAllSelections !== false) {
3161
3511
  for (const selection of selections) {
3162
3512
  if (!present.has(selection)) throw new RunnerError("Workspace export omits a selected path");
@@ -3165,11 +3515,11 @@ var init_transfer_archive = __esm({
3165
3515
  if (logicalBytes !== options.expectedMetadata.logicalBytes || entries.length !== options.expectedMetadata.entryCount) {
3166
3516
  throw new ProtocolError("Workspace exporter returned mismatched tree metadata");
3167
3517
  }
3168
- validateSymlinkSet(entries.filter((entry) => entry.type === "symlink").map((entry) => ({
3518
+ await validateSymlinkSet(entries.filter((entry) => entry.type === "symlink").map((entry) => ({
3169
3519
  path: entry.path,
3170
3520
  target: entry.linkTarget,
3171
3521
  scope: entry.symlinkScope
3172
- })));
3522
+ })), options.signal);
3173
3523
  await assertSnapshot(root, rootSnapshot);
3174
3524
  return {
3175
3525
  entries,
@@ -3326,7 +3676,7 @@ var init_transfer_archive = __esm({
3326
3676
  truncate: true
3327
3677
  });
3328
3678
  const compressor = new CompressionStream("gzip");
3329
- const compressed = iteratorStream(tarChunks(collected.entries, collected.root, collected.rootSnapshot.dev, options.signal)).pipeThrough(compressor);
3679
+ const compressed = iteratorStream(tarChunks(collected.entries, collected.root, collected.rootSnapshot.dev, fileOperations.openRead ?? defaultFileOperations.openRead, options.signal)).pipeThrough(compressor);
3330
3680
  reader = compressed.getReader();
3331
3681
  while (true) {
3332
3682
  if (options.signal?.aborted) throw options.signal.reason;
@@ -3340,7 +3690,10 @@ var init_transfer_archive = __esm({
3340
3690
  await writeAll(output, value);
3341
3691
  }
3342
3692
  await assertSnapshot(collected.root, collected.rootSnapshot);
3343
- for (const entry of collected.entries) await assertSnapshot(entry.absolutePath, entry.snapshot);
3693
+ for (const entry of collected.entries) {
3694
+ if (options.signal?.aborted) throw options.signal.reason;
3695
+ await assertSnapshot(entry.absolutePath, entry.snapshot);
3696
+ }
3344
3697
  archiveSnapshot = snapshotFor(await Deno.lstat(path), "file", "Prepared transfer archive");
3345
3698
  } catch (error) {
3346
3699
  const errors = [
@@ -3793,7 +4146,10 @@ var init_cache_manager = __esm({
3793
4146
  async restore(context) {
3794
4147
  const limits = validateCaches(this.config, context.job);
3795
4148
  let workspaceBytes = context.job.source.extractedSizeBytes;
3796
- let workspaceEntries = context.job.source.entryCount;
4149
+ let workspaceEntries = context.workspaceEntryCount;
4150
+ if (!Number.isSafeInteger(workspaceEntries) || workspaceEntries < 0 || workspaceEntries > limits.workspaceEntries) {
4151
+ throw new ProtocolError("Current workspace entry count exceeds its effective limit");
4152
+ }
3797
4153
  for (const cache of context.job.caches) {
3798
4154
  if (context.signal.aborted) throw context.signal.reason;
3799
4155
  const download = await this.api.downloadCache(context.identity, cache.name, context.signal);
@@ -3825,18 +4181,20 @@ var init_cache_manager = __esm({
3825
4181
  recursive: true,
3826
4182
  mode: 448
3827
4183
  });
3828
- await ensureStagingCapacity(restoreRoot, staged.metadata.extractedSizeBytes, staged.metadata.entryCount + 1, this.config.transferStagingReserveBytes, this.config.transferStagingReserveInodes);
3829
4184
  restorePath = await Deno.makeTempDir({
3830
4185
  dir: restoreRoot,
3831
4186
  prefix: "cache-"
3832
4187
  });
3833
4188
  await Deno.chmod(restorePath, 448);
3834
- await extractTarGzipArchive({
4189
+ const extracted = await extractTarGzipArchive({
3835
4190
  archivePath: staged.path,
3836
4191
  destinationPath: restorePath,
3837
4192
  expectedMetadata: staged.metadata,
3838
4193
  maximumExtractedBytes: Math.min(cache.maximumExtractedBytes, remainingWorkspaceBytes),
3839
4194
  maximumEntries: Math.min(cache.maximumEntries, remainingWorkspaceEntries),
4195
+ maximumMaterializedEntries: remainingWorkspaceEntries,
4196
+ reserveBytes: this.config.transferStagingReserveBytes,
4197
+ reserveInodes: this.config.transferStagingReserveInodes,
3840
4198
  allowSymlinks: false,
3841
4199
  allowedPaths: cache.paths,
3842
4200
  requireAllowedPaths: true,
@@ -3844,7 +4202,7 @@ var init_cache_manager = __esm({
3844
4202
  });
3845
4203
  await restoreSelectedPaths(restorePath, context.workspacePath, cache);
3846
4204
  workspaceBytes = checkedAdd2(workspaceBytes, staged.metadata.extractedSizeBytes, "Restored workspace byte count overflow");
3847
- workspaceEntries = checkedAdd2(workspaceEntries, staged.metadata.entryCount, "Restored workspace entry count overflow");
4205
+ workspaceEntries = checkedAdd2(workspaceEntries, extracted.materializedEntryCount, "Restored workspace entry count overflow");
3848
4206
  } catch (error) {
3849
4207
  primaryError = error;
3850
4208
  }
@@ -4561,7 +4919,7 @@ var init_deno = __esm({
4561
4919
  "deno.json"() {
4562
4920
  deno_default = {
4563
4921
  name: "@ship.zone/runner",
4564
- version: "0.1.1",
4922
+ version: "0.2.1",
4565
4923
  exports: "./mod.ts",
4566
4924
  nodeModulesDir: "none",
4567
4925
  tasks: {
@@ -4593,8 +4951,9 @@ var init_deno = __esm({
4593
4951
  strict: true
4594
4952
  },
4595
4953
  imports: {
4596
- "@foss.global/ci-spec": "npm:@foss.global/ci-spec@0.1.0",
4597
- "@foss.global/ci-spec/runner-job.schema.json": "npm:@foss.global/ci-spec@0.1.0/runner-job.schema.json",
4954
+ "@foss.global/ci-spec": "npm:@foss.global/ci-spec@0.2.0",
4955
+ "@foss.global/ci-spec/archive-cases.json": "npm:@foss.global/ci-spec@0.2.0/archive-cases.json",
4956
+ "@foss.global/ci-spec/runner-job.schema.json": "npm:@foss.global/ci-spec@0.2.0/runner-job.schema.json",
4598
4957
  "@std/assert": "jsr:@std/assert@^1.0.14",
4599
4958
  "@std/path": "jsr:@std/path@^1.1.2",
4600
4959
  "ajv/dist/2020.js": "npm:ajv@8.20.0/dist/2020.js"
@@ -8047,6 +8406,7 @@ var init_runner = __esm({
8047
8406
  if (lease.job.caches.length > 0) {
8048
8407
  await this.dependencies.cacheManager.restore({
8049
8408
  workspacePath: stagingWorkspace.path,
8409
+ workspaceEntryCount: stagingWorkspace.materializedEntryCount,
8050
8410
  job: lease.job,
8051
8411
  identity,
8052
8412
  signal: executionSignal
@@ -8356,11 +8716,15 @@ var init_source_workspace = __esm({
8356
8716
  init_mod();
8357
8717
  init_errors();
8358
8718
  init_transfer_archive();
8359
- effectiveSourceLimits = /* @__PURE__ */ __name((config, context) => ({
8360
- archiveBytes: Math.min(config.maximumSourceArchiveBytes, context.job.requirements.limits.maximumSourceArchiveBytes),
8361
- extractedBytes: Math.min(config.maximumSourceExtractedBytes, config.oci.workspaceSizeBytes, context.job.requirements.limits.maximumSourceExtractedBytes, context.job.requirements.limits.maximumWorkspaceBytes),
8362
- entries: Math.min(config.maximumSourceEntries, config.maximumWorkspaceEntries, context.job.requirements.limits.maximumSourceEntries, context.job.requirements.limits.maximumWorkspaceEntries)
8363
- }), "effectiveSourceLimits");
8719
+ effectiveSourceLimits = /* @__PURE__ */ __name((config, context) => {
8720
+ const workspaceEntries = Math.min(config.maximumWorkspaceEntries, context.job.requirements.limits.maximumWorkspaceEntries);
8721
+ return {
8722
+ archiveBytes: Math.min(config.maximumSourceArchiveBytes, context.job.requirements.limits.maximumSourceArchiveBytes),
8723
+ extractedBytes: Math.min(config.maximumSourceExtractedBytes, config.oci.workspaceSizeBytes, context.job.requirements.limits.maximumSourceExtractedBytes, context.job.requirements.limits.maximumWorkspaceBytes),
8724
+ entries: Math.min(config.maximumSourceEntries, context.job.requirements.limits.maximumSourceEntries, workspaceEntries),
8725
+ workspaceEntries
8726
+ };
8727
+ }, "effectiveSourceLimits");
8364
8728
  cleanupFailure = /* @__PURE__ */ __name(async (error, cleanups, message) => {
8365
8729
  const cleanupErrors = [];
8366
8730
  for (const cleanup of cleanups) {
@@ -8429,7 +8793,6 @@ var init_source_workspace = __esm({
8429
8793
  });
8430
8794
  let workspacePath;
8431
8795
  try {
8432
- await ensureStagingCapacity(workspaceRoot, source.extractedSizeBytes, source.entryCount + 1, this.config.transferStagingReserveBytes, this.config.transferStagingReserveInodes);
8433
8796
  workspacePath = await Deno.makeTempDir({
8434
8797
  dir: workspaceRoot,
8435
8798
  prefix: "attempt-"
@@ -8441,6 +8804,9 @@ var init_source_workspace = __esm({
8441
8804
  expectedMetadata: staged.metadata,
8442
8805
  maximumExtractedBytes: limits.extractedBytes,
8443
8806
  maximumEntries: limits.entries,
8807
+ maximumMaterializedEntries: limits.workspaceEntries,
8808
+ reserveBytes: this.config.transferStagingReserveBytes,
8809
+ reserveInodes: this.config.transferStagingReserveInodes,
8444
8810
  allowSymlinks: true,
8445
8811
  signal: context.signal
8446
8812
  });
@@ -8450,7 +8816,11 @@ var init_source_workspace = __esm({
8450
8816
  const ownedWorkspacePath = workspacePath;
8451
8817
  return {
8452
8818
  path: ownedWorkspacePath,
8453
- metadata,
8819
+ metadata: {
8820
+ logicalBytes: metadata.logicalBytes,
8821
+ entryCount: metadata.entryCount
8822
+ },
8823
+ materializedEntryCount: metadata.materializedEntryCount,
8454
8824
  cleanup: /* @__PURE__ */ __name(() => {
8455
8825
  if (cleaned) return Promise.resolve();
8456
8826
  cleanupPromise ??= removePathIfPresent(ownedWorkspacePath, true).then(() => {