@stll/oxlint-config 0.10.0 → 0.12.0

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.
@@ -0,0 +1,3302 @@
1
+ //#region \0rolldown/runtime.js
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
22
+ //#endregion
23
+ let node_fs = require("node:fs");
24
+ let node_child_process = require("node:child_process");
25
+ let node_path = require("node:path");
26
+ node_path = __toESM(node_path, 1);
27
+ let semver = require("semver");
28
+ let picomatch = require("picomatch");
29
+ picomatch = __toESM(picomatch, 1);
30
+ let smol_toml = require("smol-toml");
31
+ let yaml = require("yaml");
32
+ //#region src/cloud-setup-install.ts
33
+ const packageInstall = String.raw`
34
+ # Prevent package maintainer scripts from starting unmanaged system services.
35
+ apt_install() (
36
+ # EXIT runs after function locals expire; this subshell owns the trap state.
37
+ backup=''
38
+ policy_state=untouched
39
+ [[ ! -L /var/lock/stll-cloud-apt.lock ]] || fail 'Invalid package install lock'
40
+ exec 8>/var/lock/stll-cloud-apt.lock
41
+ flock -x -w 120 8 || fail 'Another package installation is active'
42
+ [[ ! -L /usr/sbin/policy-rc.d ]] || fail 'Unsupported service-start policy symlink'
43
+ [[ ! -e /usr/sbin/policy-rc.d || -f /usr/sbin/policy-rc.d ]] || fail 'Unsupported service-start policy file'
44
+ backup="$(mktemp -d)"
45
+ cleanup_package_policy() {
46
+ local status=$?
47
+ trap - EXIT HUP INT TERM
48
+ if [[ "$policy_state" == installed ]]; then
49
+ if [[ -f "$backup/original" ]]; then
50
+ if ! cp -p "$backup/original" /usr/sbin/policy-rc.d; then status=1; fi
51
+ else
52
+ if ! rm -f /usr/sbin/policy-rc.d; then status=1; fi
53
+ fi
54
+ fi
55
+ rm -rf -- "$backup"
56
+ exit "$status"
57
+ }
58
+ trap cleanup_package_policy EXIT
59
+ trap 'exit 129' HUP
60
+ trap 'exit 130' INT
61
+ trap 'exit 143' TERM
62
+ if [[ -e /usr/sbin/policy-rc.d ]]; then cp -p /usr/sbin/policy-rc.d "$backup/original"; fi
63
+ policy_state=installed
64
+ printf '%s\n' '#!/bin/sh' 'exit 101' > /usr/sbin/policy-rc.d
65
+ chmod 755 /usr/sbin/policy-rc.d
66
+ DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends "$@"
67
+ )
68
+
69
+ `;
70
+ const postgresSourceLine = "deb [signed-by=/usr/share/keyrings/stll-pgdg.asc] https://apt.postgresql.org/pub/repos/apt noble-pgdg main";
71
+ const postgresSigningFingerprint = "B97B0AFCAA1A47F044F244A07FCC7D46ACCC4CF8";
72
+ const postgresSources = String.raw`
73
+ pgdg_key_fingerprint() {
74
+ gpg --batch --show-keys --with-colons "$1" | awk -F: '$1 == "pub" { primary = 1 } $1 == "sub" { primary = 0 } $1 == "fpr" && primary { print toupper($10); primary = 0 }'
75
+ }
76
+ pgdg_sources_ready() {
77
+ local managed="$1" file mode records suite keyring override fingerprint selected_keyring=''
78
+ shift
79
+ PGDG_SOURCE_STATE=missing
80
+ [[ ! -L "$managed" ]] || fail "Managed PGDG source must not be a symlink: $managed"
81
+ for file in "$@"; do
82
+ [[ -e "$file" ]] || continue
83
+ [[ -f "$file" ]] || fail "APT source must be a regular file: $file"
84
+ case "$file" in *.sources) mode=sources ;; *) mode=list ;; esac
85
+ records="$(awk -v mode="$mode" '
86
+ function trim(value) { gsub(/^[[:space:]]+|[[:space:]]+$/, "", value); return value }
87
+ function pgdg_uri(uri) {
88
+ uri = tolower(uri)
89
+ if (uri !~ /^[a-z][a-z0-9+.-]*:\/\//) return 0
90
+ sub(/^[a-z][a-z0-9+.-]*:\/\//, "", uri)
91
+ sub(/[\/?#].*$/, "", uri)
92
+ sub(/^.*@/, "", uri)
93
+ sub(/:.*$/, "", uri)
94
+ return uri == "apt.postgresql.org" || uri == "apt.postgresql.org."
95
+ }
96
+ function contains_pgdg(value, tokens, count, token_index) {
97
+ count = split(value, tokens, /[[:space:]]+/)
98
+ for (token_index = 1; token_index <= count; token_index++) if (pgdg_uri(tokens[token_index])) return 1
99
+ return 0
100
+ }
101
+ function unsafe_field(name) {
102
+ return name ~ /^(trusted|allow-insecure|allow-weak|allow-downgrade-to-insecure)$/
103
+ }
104
+ function disabled_override(value) {
105
+ value = tolower(trim(value))
106
+ gsub(/^["\047]|["\047]$/, "", value)
107
+ return value ~ /^(no|false|without|off|disable|0)$/
108
+ }
109
+ function stanza(override_index) {
110
+ override = 0
111
+ for (override_index = 1; override_index <= override_count; override_index++) {
112
+ if (!disabled_override(override_values[override_index])) override = 1
113
+ delete override_values[override_index]
114
+ }
115
+ if (tolower(trim(enabled)) != "no" && pgdg) print (trim(suites) == "" ? "-" : trim(suites)) "\t" (trim(keyring) == "" ? "-" : trim(keyring)) "\t" (override ? "unsafe" : "safe")
116
+ enabled = ""; pgdg = 0; field = ""; suites = ""; keyring = ""; override = 0; override_count = 0
117
+ }
118
+ /^[[:space:]]*#/ { if (mode == "list" || $0 ~ /^#/) next }
119
+ {
120
+ line = $0
121
+ if (mode == "list") {
122
+ sub(/[[:space:]]*#.*$/, "", line)
123
+ if (line !~ /^[[:space:]]*deb(-src)?[[:space:]]/ || !contains_pgdg(line)) next
124
+ keyring = ""; override = 0
125
+ if (match(line, /\[[^]]*\]/)) {
126
+ options = substr(line, RSTART + 1, RLENGTH - 2)
127
+ count = split(options, tokens, /[[:space:]]+/)
128
+ for (token_index = 1; token_index <= count; token_index++) {
129
+ if (tolower(tokens[token_index]) ~ /^signed-by=/) { keyring = tokens[token_index]; sub(/^[^=]*=/, "", keyring) }
130
+ option_name = tolower(tokens[token_index]); sub(/=.*/, "", option_name)
131
+ option_value = tokens[token_index]; sub(/^[^=]*=/, "", option_value)
132
+ if (unsafe_field(option_name) && !disabled_override(option_value)) override = 1
133
+ }
134
+ sub(/\[[^]]*\]/, "", line)
135
+ }
136
+ count = split(line, tokens, /[[:space:]]+/)
137
+ for (token_index = 1; token_index <= count; token_index++) if (pgdg_uri(tokens[token_index])) print (tokens[token_index + 1] == "" ? "-" : tokens[token_index + 1]) "\t" (keyring == "" ? "-" : keyring) "\t" (override ? "unsafe" : "safe")
138
+ next
139
+ }
140
+ if (line ~ /^[[:space:]]*$/) { stanza(); next }
141
+ if (line ~ /^[[:space:]]/) {
142
+ if (field == "uris" && contains_pgdg(line)) pgdg = 1
143
+ if (field == "enabled") enabled = enabled " " line
144
+ if (field == "suites") suites = suites " " line
145
+ if (field == "signed-by") keyring = keyring " " line
146
+ if (unsafe_field(field)) override_values[override_count] = override_values[override_count] " " line
147
+ next
148
+ }
149
+ field = tolower(line)
150
+ sub(/:.*/, "", field)
151
+ value = line
152
+ sub(/^[^:]*:[[:space:]]*/, "", value)
153
+ if (field == "uris" && contains_pgdg(value)) pgdg = 1
154
+ if (field == "enabled") enabled = value
155
+ if (field == "suites") suites = value
156
+ if (field == "signed-by") keyring = value
157
+ if (unsafe_field(field)) override_values[++override_count] = value
158
+ }
159
+ END { if (mode == "sources") stanza() }
160
+ ' "$file")" || fail "Cannot inspect APT source: $file"
161
+ if [[ "$file" == "$managed" && -z "$records" ]]; then
162
+ fail "Managed PGDG source has no active PGDG entry: $file"
163
+ fi
164
+ while IFS=$'\t' read -r suite keyring override; do
165
+ [[ -n "$suite" ]] || continue
166
+ [[ "$override" == safe ]] || fail "PGDG source enables an unsafe trust override: $file"
167
+ [[ "$suite" == noble-pgdg && "$keyring" == /* && ! "$keyring" =~ [[:space:],] ]] || fail "PGDG source requires noble-pgdg and one Signed-By keyring: $file"
168
+ [[ -z "$selected_keyring" || "$selected_keyring" == "$keyring" ]] || fail "Conflicting PGDG Signed-By keyrings: $file"
169
+ fingerprint="$(pgdg_key_fingerprint "$keyring")" || fail "Cannot verify PGDG Signed-By keyring: $file"
170
+ [[ "$fingerprint" == @PGDG_FINGERPRINT@ ]] || fail "PGDG Signed-By fingerprint mismatch: $file"
171
+ selected_keyring="$keyring"
172
+ PGDG_SOURCE_STATE=reuse
173
+ done <<< "$records"
174
+ done
175
+ }
176
+ `;
177
+ const postgresInstall = String.raw`
178
+ postgres_ready() {
179
+ local binary
180
+ for binary in postgres initdb pg_ctl psql createdb; do
181
+ [[ -x "/usr/lib/postgresql/@POSTGRES@/bin/$binary" ]] || return 1
182
+ done
183
+ /usr/lib/postgresql/@POSTGRES@/bin/postgres --version | grep -Eq '^postgres \(PostgreSQL\) @POSTGRES@\.'
184
+ }
185
+ if ! postgres_ready; then
186
+ pgdg_sources_ready /etc/apt/sources.list.d/stll-pgdg.list /etc/apt/sources.list /etc/apt/sources.list.d/*.list /etc/apt/sources.list.d/*.sources
187
+ if [[ "$PGDG_SOURCE_STATE" == missing ]]; then
188
+ local key key_fingerprint
189
+ key="$(mktemp)"
190
+ curl --fail --silent --show-error --location --proto '=https' --proto-redir '=https' --tlsv1.2 https://www.postgresql.org/media/keys/ACCC4CF8.asc -o "$key"
191
+ key_fingerprint="$(pgdg_key_fingerprint "$key")"
192
+ [[ "$key_fingerprint" == @PGDG_FINGERPRINT@ ]] || fail 'PostgreSQL signing key mismatch'
193
+ install -d -m 755 /usr/share/keyrings
194
+ install -m 644 "$key" /usr/share/keyrings/stll-pgdg.asc
195
+ rm -- "$key"
196
+ printf '%s\n' '@PGDG_SOURCE@' > /etc/apt/sources.list.d/stll-pgdg.list
197
+ fi
198
+ apt-get update
199
+ apt_install postgresql-@POSTGRES@ postgresql-client-@POSTGRES@
200
+ fi
201
+ postgres_ready || fail 'PostgreSQL toolchain is incomplete or differs from the policy major'
202
+ `;
203
+ const valkeyInstall = String.raw`
204
+ if ! command -v valkey-server >/dev/null || [[ "$(valkey-server --version | sed -nE 's/.*v=([0-9.]+).*/\1/p')" != '@VALKEY@' ]] || ! command -v valkey-cli >/dev/null || [[ "$(valkey-cli --version)" != 'valkey-cli @VALKEY@' ]]; then
205
+ local scratch server_url server_sha tools_url tools_sha package
206
+ scratch="$(mktemp -d)"
207
+ chmod 755 "$scratch"
208
+ case "$ARCH" in
209
+ amd64) server_url='@AMD64_SERVER_URL@'; server_sha='@AMD64_SERVER_SHA@'; tools_url='@AMD64_TOOLS_URL@'; tools_sha='@AMD64_TOOLS_SHA@' ;;
210
+ arm64) server_url='@ARM64_SERVER_URL@'; server_sha='@ARM64_SERVER_SHA@'; tools_url='@ARM64_TOOLS_URL@'; tools_sha='@ARM64_TOOLS_SHA@' ;;
211
+ *) fail 'Unsupported Valkey architecture' ;;
212
+ esac
213
+ curl --fail --silent --show-error --location --proto '=https' --proto-redir '=https' --tlsv1.2 "$server_url" -o "$scratch/valkey-server.deb"
214
+ curl --fail --silent --show-error --location --proto '=https' --proto-redir '=https' --tlsv1.2 "$tools_url" -o "$scratch/valkey-tools.deb"
215
+ (cd "$scratch"; printf '%s %s\n' "$server_sha" valkey-server.deb "$tools_sha" valkey-tools.deb | sha256sum --strict -c -)
216
+ for package in valkey-server valkey-tools; do
217
+ [[ "$(dpkg-deb -f "$scratch/$package.deb" Package)" == "$package" ]] || fail 'Valkey artifact package mismatch'
218
+ [[ "$(dpkg-deb -f "$scratch/$package.deb" Version)" == '@VALKEY@-1.noble' ]] || fail 'Valkey artifact version mismatch'
219
+ [[ "$(dpkg-deb -f "$scratch/$package.deb" Architecture)" == "$ARCH" ]] || fail 'Valkey artifact architecture mismatch'
220
+ done
221
+ apt-get update
222
+ apt_install "$scratch/valkey-server.deb" "$scratch/valkey-tools.deb"
223
+ rm -rf -- "$scratch"
224
+ fi
225
+ [[ "$(valkey-server --version | sed -nE 's/.*v=([0-9.]+).*/\1/p')" == '@VALKEY@' ]] || fail 'Valkey version differs from policy'
226
+ [[ "$(valkey-cli --version)" == 'valkey-cli @VALKEY@' ]] || fail 'Valkey client version differs from policy'
227
+ `;
228
+ const state = String.raw`
229
+ service_account_ready() {
230
+ local uid gid shell
231
+ uid="$(id -u stll-cloud)" || fail 'Service user is unavailable; run install'
232
+ gid="$(id -g stll-cloud)"
233
+ shell="$(getent passwd stll-cloud | cut -d: -f7)"
234
+ [[ "$uid" =~ ^[1-9][0-9]*$ && "$gid" =~ ^[1-9][0-9]*$ && "$shell" == /usr/sbin/nologin ]] || fail 'Service user must be unprivileged with no login shell'
235
+ }
236
+ prepare_state() {
237
+ service_account_ready
238
+ [[ ! -L /var/lib/stll-cloud ]] || fail 'Service state root must not be a symlink'
239
+ if [[ -e /var/lib/stll-cloud ]]; then
240
+ [[ -d /var/lib/stll-cloud && "$(stat -c '%u:%a' /var/lib/stll-cloud)" == 0:755 ]] || fail 'Invalid service state root'
241
+ else
242
+ install -d -m 755 -o root -g root /var/lib/stll-cloud
243
+ fi
244
+ STATE="/var/lib/stll-cloud/$(printf '%s' "$REPO_ROOT" | sha256sum | cut -d' ' -f1)"
245
+ [[ ! -L "$STATE" ]] || fail 'Service state must not be a symlink'
246
+ if [[ -e "$STATE" ]]; then
247
+ [[ -d "$STATE" && "$(stat -c '%u:%a' "$STATE")" == 0:710 && "$(stat -c '%g' "$STATE")" == "$(id -g stll-cloud)" ]] || fail 'Invalid service state ownership'
248
+ else
249
+ install -d -m 710 -o root -g stll-cloud "$STATE"
250
+ fi
251
+ [[ ! -L "$STATE/lock" ]] || fail 'Service lock must not be a symlink'
252
+ exec 9>"$STATE/lock"
253
+ flock -x -w 10 9 || fail 'Another setup process owns the service state'
254
+ }
255
+ `;
256
+ const renderCloudServiceInstall = ({ services, postgres, valkey, valkeyArtifacts }) => {
257
+ const parts = services.map((service) => {
258
+ switch (service) {
259
+ case "postgres": return postgresInstall.replaceAll("@POSTGRES@", postgres).replaceAll("@PGDG_SOURCE@", postgresSourceLine).replaceAll("@PGDG_FINGERPRINT@", postgresSigningFingerprint);
260
+ case "valkey": {
261
+ const replacements = /* @__PURE__ */ new Map([
262
+ ["@VALKEY@", valkey],
263
+ ["@AMD64_SERVER_URL@", valkeyArtifacts.amd64.server.url],
264
+ ["@AMD64_SERVER_SHA@", valkeyArtifacts.amd64.server.sha256],
265
+ ["@AMD64_TOOLS_URL@", valkeyArtifacts.amd64.tools.url],
266
+ ["@AMD64_TOOLS_SHA@", valkeyArtifacts.amd64.tools.sha256],
267
+ ["@ARM64_SERVER_URL@", valkeyArtifacts.arm64.server.url],
268
+ ["@ARM64_SERVER_SHA@", valkeyArtifacts.arm64.server.sha256],
269
+ ["@ARM64_TOOLS_URL@", valkeyArtifacts.arm64.tools.url],
270
+ ["@ARM64_TOOLS_SHA@", valkeyArtifacts.arm64.tools.sha256]
271
+ ]);
272
+ return valkeyInstall.replace(/@[A-Z0-9_]+@/g, (token) => {
273
+ const value = replacements.get(token);
274
+ if (value === void 0) throw new Error(`Missing Valkey artifact field: ${token}`);
275
+ return value;
276
+ });
277
+ }
278
+ default: throw new Error(`Unsupported service: ${String(service)}`);
279
+ }
280
+ });
281
+ const user = services.length === 0 ? "" : " if ! id stll-cloud >/dev/null 2>&1; then useradd --system --user-group --no-create-home --shell /usr/sbin/nologin stll-cloud; fi\n service_account_ready\n";
282
+ return `${packageInstall}\n${services.includes("postgres") ? postgresSources.replaceAll("@PGDG_FINGERPRINT@", postgresSigningFingerprint) : ""}\n${services.length === 0 ? "prepare_state() { :; }\n" : state}\ninstall_services() {\n${user}${parts.join("")}\n :\n}\n`;
283
+ };
284
+ //#endregion
285
+ //#region src/cloud-setup-schema.ts
286
+ const cloudServices = ["postgres", "valkey"];
287
+ const cloudInstallCommand = "bun install --frozen-lockfile";
288
+ const cloudService = (value) => cloudServices.some((service) => value === service);
289
+ /** Parse an explicit declaration without assuming services for undeclared repositories. */
290
+ const parseCloudSetup = (input) => {
291
+ if (input === void 0) return void 0;
292
+ if (typeof input !== "object" || input === null || Array.isArray(input)) throw new Error("cloud must be an object");
293
+ for (const key of Object.keys(input)) if (key !== "services" && key !== "install" && key !== "envFile") throw new Error(`unsupported cloud key: ${key}`);
294
+ if (!("services" in input) || !Array.isArray(input.services)) throw new Error("cloud.services must be an explicit array");
295
+ if (!("install" in input) || input.install !== "bun install --frozen-lockfile") throw new Error(`cloud.install must be exactly ${cloudInstallCommand}`);
296
+ if (!("envFile" in input) || typeof input.envFile !== "string") throw new Error("cloud.envFile must be a canonical repository-relative path");
297
+ const envFile = input.envFile;
298
+ if (envFile.startsWith("/") || /^[A-Za-z]:/.test(envFile) || envFile.includes("\\") || /\p{Cc}/u.test(envFile) || envFile.split("/").some((part) => part === "" || part === "." || part === "..")) throw new Error("cloud.envFile must be a canonical repository-relative path");
299
+ const seen = /* @__PURE__ */ new Set();
300
+ return {
301
+ services: Array.from(input.services, (service) => {
302
+ if (!cloudService(service)) throw new Error("cloud.services contains an unsupported service");
303
+ if (seen.has(service)) throw new Error(`cloud.services contains duplicate service: ${service}`);
304
+ seen.add(service);
305
+ return service;
306
+ }),
307
+ install: cloudInstallCommand,
308
+ envFile
309
+ };
310
+ };
311
+ //#endregion
312
+ //#region src/cloud-setup-services.ts
313
+ const common = String.raw`
314
+ service_file() {
315
+ local file="$1" owner="$2"
316
+ [[ ! -L "$file" ]] || fail "Service state must not contain symbolic links"
317
+ if [[ -e "$file" ]]; then
318
+ [[ -f "$file" && "$(stat -c '%u:%a' "$file")" == "$owner:600" ]] || fail "Invalid service state file"
319
+ fi
320
+ }
321
+ service_directory() {
322
+ local directory="$1"
323
+ [[ ! -L "$directory" ]] || fail "Service directory must not be a symbolic link"
324
+ if [[ -e "$directory" ]]; then
325
+ [[ -d "$directory" && "$(stat -c '%u:%a' "$directory")" == "$SERVICE_UID:700" ]] || fail "Invalid service directory"
326
+ else
327
+ root install -d -m 700 -o stll-cloud -g stll-cloud "$directory"
328
+ fi
329
+ }
330
+ service_password() {
331
+ local file="$1"
332
+ service_file "$file" 0
333
+ if [[ ! -e "$file" ]]; then
334
+ (umask 077; openssl rand -hex 32 > "$file")
335
+ root chown root:root "$file"
336
+ fi
337
+ [[ "$(cat "$file")" =~ ^[0-9a-f]{64}$ ]] || fail "Invalid service credential state"
338
+ }
339
+ service_process_matches() {
340
+ local pid="$1" executable="$2" owner actual expected
341
+ [[ "$pid" =~ ^[1-9][0-9]*$ && -d "/proc/$pid" ]] || return 1
342
+ owner="$(stat -c '%u' "/proc/$pid" 2>/dev/null)" || return 2
343
+ [[ "$owner" =~ ^[0-9]+$ ]] || return 2
344
+ [[ "$owner" == "$SERVICE_UID" ]] || return 1
345
+ actual="$(readlink -f "/proc/$pid/exe" 2>/dev/null)" || return 2
346
+ expected="$(readlink -f "$executable")" || return 2
347
+ [[ -n "$actual" && -n "$expected" && "$actual" != *' (deleted)' ]] || return 2
348
+ [[ "$actual" == "$expected" ]]
349
+ }
350
+ service_process() {
351
+ service_process_matches "$1" "$2" || fail "Managed service process identity differs from the recorded state"
352
+ }
353
+ service_prune_pid() {
354
+ local file="$1" executable="$2" service="$3" pid identity
355
+ [[ -e "$file" ]] || return 0
356
+ pid="$(head -n 1 "$file")"
357
+ # PostgreSQL encodes a standalone backend with a negative PID.
358
+ if [[ "$service" == postgres ]]; then pid="$(printf '%s' "$pid" | sed 's/^-//')"; fi
359
+ if service_process_matches "$pid" "$executable"; then return 0; else identity=$?; fi
360
+ [[ "$identity" != 2 ]] || fail "Cannot verify recorded live service process; retaining its PID file"
361
+ # Let PostgreSQL check orphan shared memory before removing a dead-PID lock.
362
+ if [[ "$service" == postgres && "$pid" =~ ^[1-9][0-9]*$ && ! -d "/proc/$pid" ]]; then return 0; fi
363
+ if [[ "$service" == postgres ]]; then
364
+ [[ "$pid" =~ ^[1-9][0-9]*$ && "$SERVICE_UID" != 0 ]] || fail "Cannot safely recover PostgreSQL PID state"
365
+ # The root controller is not our nonroot postgres. Preserve the remaining
366
+ # lock rows so PostgreSQL's EPERM/ancestor path still checks orphan memory.
367
+ root sed -i "1s/.*/$$/" "$file"
368
+ return 0
369
+ fi
370
+ # Restored state can name an unrelated live process; never signal that PID.
371
+ root rm -- "$file"
372
+ }
373
+ `;
374
+ const postgresStart = String.raw`
375
+ local pg_bin='/usr/lib/postgresql/@POSTGRES@/bin' pg_data="$STATE/postgres" pg_password pg_details pg_pid pg_version
376
+ service_password "$STATE/postgres.password"
377
+ pg_password="$(cat "$STATE/postgres.password")"
378
+ service_directory "$pg_data"
379
+ for file in PG_VERSION postmaster.pid postgresql.conf pg_hba.conf pg_ident.conf postgresql.auto.conf; do
380
+ service_file "$pg_data/$file" "$SERVICE_UID"
381
+ done
382
+ if [[ ! -e "$pg_data/PG_VERSION" ]]; then
383
+ [[ -z "$(ls -A "$pg_data")" ]] || fail "PostgreSQL data directory is not initialized"
384
+ service_file "$STATE/postgres.init-password" "$SERVICE_UID"
385
+ (umask 077; printf '%s\n' "$pg_password" > "$STATE/postgres.init-password")
386
+ root chown stll-cloud:stll-cloud "$STATE/postgres.init-password"
387
+ service_run env PGHOST=127.0.0.1 PGHOSTADDR=127.0.0.1 "$pg_bin/initdb" -D "$pg_data" --username=stll_cloud --auth-host=scram-sha-256 --auth-local=scram-sha-256 --pwfile="$STATE/postgres.init-password" --encoding=UTF8 --locale=C --set=unix_socket_directories= >/dev/null || fail "PostgreSQL initialization failed"
388
+ root rm "$STATE/postgres.init-password"
389
+ fi
390
+ [[ -f "$pg_data/PG_VERSION" && "$(cat "$pg_data/PG_VERSION")" == '@POSTGRES@' ]] || fail "PostgreSQL data has a different major version"
391
+ service_prune_pid "$pg_data/postmaster.pid" "$pg_bin/postgres" postgres
392
+ if ! service_run env PGHOST=127.0.0.1 PGHOSTADDR=127.0.0.1 "$pg_bin/pg_ctl" -D "$pg_data" status >/dev/null 2>&1; then
393
+ service_run env PGHOST=127.0.0.1 PGHOSTADDR=127.0.0.1 "$pg_bin/pg_ctl" -D "$pg_data" -l "$pg_data/cloud.log" -o "-h 127.0.0.1 -p 55432 -c unix_socket_directories=" -t 10 -w start >/dev/null || fail "PostgreSQL start failed; port 55432 must be available"
394
+ fi
395
+ pg_details="$(env -u PGSERVICE -u PGSERVICEFILE -u PGOPTIONS PGHOSTADDR=127.0.0.1 PGPASSWORD="$pg_password" PGCONNECT_TIMEOUT=2 "$pg_bin/psql" -X -h 127.0.0.1 -p 55432 -U stll_cloud -d postgres -At -v ON_ERROR_STOP=1 -c "SELECT current_setting('data_directory'), current_setting('listen_addresses'), current_setting('port'), current_setting('server_version_num'), current_setting('unix_socket_directories')")" || fail "PostgreSQL authenticated readiness failed"
396
+ pg_version="$(printf '%s\n' "$pg_details" | cut -d '|' -f4)"
397
+ [[ "$pg_details" == "$pg_data|127.0.0.1|55432|$pg_version|" && "$pg_version" =~ ^[0-9]{6}$ ]] || fail "PostgreSQL endpoint does not match managed data and listener"
398
+ (( pg_version / 10000 == @POSTGRES@ )) || fail "PostgreSQL endpoint has a different major version"
399
+ pg_pid="$(head -n 1 "$pg_data/postmaster.pid")"
400
+ service_process "$pg_pid" "$pg_bin/postgres"
401
+ [[ "$(env -u PGSERVICE -u PGSERVICEFILE -u PGOPTIONS PGHOSTADDR=127.0.0.1 PGPASSWORD="$pg_password" PGCONNECT_TIMEOUT=2 "$pg_bin/psql" -X -h 127.0.0.1 -p 55432 -U stll_cloud -d postgres -At -v ON_ERROR_STOP=1 -c "SELECT count(*) FROM pg_database WHERE datname = 'cloud_test'")" == 1 ]] || env -u PGSERVICE -u PGSERVICEFILE -u PGOPTIONS PGHOSTADDR=127.0.0.1 PGPASSWORD="$pg_password" PGCONNECT_TIMEOUT=2 "$pg_bin/createdb" -h 127.0.0.1 -p 55432 -U stll_cloud cloud_test || fail "PostgreSQL test database creation failed"
402
+ DATABASE_URL="postgresql://stll_cloud:$pg_password@127.0.0.1:55432/cloud_test"
403
+ `;
404
+ const valkeyStart = String.raw`
405
+ local vk_data="$STATE/valkey" vk_password vk_config vk_info vk_pid vk_expected ready=0
406
+ service_password "$STATE/valkey.password"
407
+ vk_password="$(cat "$STATE/valkey.password")"
408
+ service_directory "$vk_data"
409
+ vk_config="$vk_data/valkey.conf"
410
+ service_file "$vk_config" "$SERVICE_UID"
411
+ for file in valkey.pid valkey.log dump.rdb; do
412
+ [[ ! -L "$vk_data/$file" ]] || fail "Valkey state must not contain symbolic links"
413
+ if [[ -e "$vk_data/$file" ]]; then
414
+ [[ -f "$vk_data/$file" && "$(stat -c '%u' "$vk_data/$file")" == "$SERVICE_UID" ]] || fail "Invalid Valkey state file"
415
+ fi
416
+ done
417
+ vk_expected="$(printf '%s\n' 'bind 127.0.0.1' 'port 56379' 'protected-mode yes' 'daemonize yes' "requirepass $vk_password" "dir $vk_data" "pidfile $vk_data/valkey.pid" "logfile $vk_data/valkey.log" 'save ""' 'appendonly no')"
418
+ if [[ ! -e "$vk_config" ]]; then
419
+ (umask 077; printf '%s\n' "$vk_expected" > "$vk_config")
420
+ root chown stll-cloud:stll-cloud "$vk_config"
421
+ fi
422
+ [[ "$(cat "$vk_config")" == "$vk_expected" ]] || fail "Valkey configuration differs from managed settings"
423
+ service_prune_pid "$vk_data/valkey.pid" "$(command -v valkey-server)" valkey
424
+ if [[ ! -e "$vk_data/valkey.pid" ]]; then
425
+ service_run valkey-server "$vk_config" || fail "Valkey start failed; port 56379 must be available"
426
+ fi
427
+ for ((attempt=0; attempt<20; attempt++)); do
428
+ if vk_info="$(VALKEYCLI_AUTH="$vk_password" timeout 0.2 valkey-cli -h 127.0.0.1 -p 56379 --raw INFO server 2>/dev/null)"; then
429
+ if [[ "$vk_info" == *$'valkey_version:@VALKEY@\r\n'* && "$vk_info" == *"config_file:$vk_config"$'\r\n'* ]]; then ready=1; break; fi
430
+ fi
431
+ sleep 0.25
432
+ done
433
+ [[ "$ready" == 1 ]] || fail "Valkey authenticated readiness or managed version/configuration check failed"
434
+ [[ -f "$vk_data/valkey.pid" ]] || fail "Valkey managed process identifier is unavailable"
435
+ vk_pid="$(cat "$vk_data/valkey.pid")"
436
+ service_process "$vk_pid" "$(command -v valkey-server)"
437
+ [[ "$vk_info" == *"process_id:$vk_pid"$'\r\n'* ]] || fail "Valkey endpoint has a different process identifier"
438
+ [[ "$(VALKEYCLI_AUTH="$vk_password" timeout 2 valkey-cli -h 127.0.0.1 -p 56379 --raw CONFIG GET bind)" == $'bind\n127.0.0.1' ]] || fail "Valkey endpoint must bind only loopback"
439
+ [[ "$(VALKEYCLI_AUTH="$vk_password" timeout 2 valkey-cli -h 127.0.0.1 -p 56379 --raw CONFIG GET dir)" == "$(printf 'dir\n%s' "$vk_data")" ]] || fail "Valkey endpoint has a different data directory"
440
+ REDIS_URL="redis://:$vk_password@127.0.0.1:56379/0"
441
+ `;
442
+ /** Render only declared services; installation and environment-file ownership stay with the caller. */
443
+ const renderCloudServiceStart = ({ services, postgres, valkey }) => {
444
+ if (!/^[1-9][0-9]*$/.test(postgres) || !/^\d+\.\d+\.\d+$/.test(valkey)) throw new Error("Invalid cloud service runtime policy");
445
+ if (services.length === 0) return "start_services() { :; }\n";
446
+ const bodies = services.map((service) => {
447
+ switch (service) {
448
+ case "postgres": return postgresStart.replaceAll("@POSTGRES@", postgres);
449
+ case "valkey": return valkeyStart.replaceAll("@VALKEY@", valkey);
450
+ default: throw new Error(`Unsupported cloud service: ${String(service)}`);
451
+ }
452
+ });
453
+ return `${common}\nstart_services() {\n local SERVICE_UID file attempt\n SERVICE_UID="$(id -u stll-cloud)"\n [[ -d "$STATE" && ! -L "$STATE" && "$(stat -c '%u' "$STATE")" == 0 ]] || fail "Invalid cloud service state directory"\n${bodies.join("")}\n}\n`;
454
+ };
455
+ //#endregion
456
+ //#region src/toolchain-node.ts
457
+ const numericComponent = "(?:0|[1-9]\\d*)";
458
+ const policyPattern = new RegExp(`^${numericComponent}\\.x$`);
459
+ const selectorPattern = new RegExp(`^(${numericComponent})(?:\\.(?:x|${numericComponent}(?:\\.${numericComponent})?))?$`);
460
+ /** A Node policy selects the complete stable release series of one major. */
461
+ const nodePolicyValid = (value) => policyPattern.test(value) && (0, semver.validRange)(value) !== null;
462
+ /** Static selectors may narrow that series, but cannot float across majors. */
463
+ const nodeSelectorMatches = (value, policy) => {
464
+ if (!nodePolicyValid(policy) || typeof value !== "string") return false;
465
+ const major = selectorPattern.exec(value)?.[1];
466
+ return major !== void 0 && major === policy.slice(0, -2) && (0, semver.validRange)(value) !== null;
467
+ };
468
+ /** Engines must support every stable release in the approved major series. */
469
+ const nodeSupportRangeMatches = (policy, range) => {
470
+ if (!nodePolicyValid(policy)) return false;
471
+ try {
472
+ return (0, semver.subset)(policy, range);
473
+ } catch {
474
+ return false;
475
+ }
476
+ };
477
+ //#endregion
478
+ //#region src/cloud-setup.ts
479
+ const cloudSetupPath = ".agents/cloud-setup.sh";
480
+ const cloudEnvironmentMarker = "# Generated by stll-cloud-setup; disposable local test services.";
481
+ const script = String.raw`#!/usr/bin/env bash
482
+ # Generated by stll-cloud-setup. Regenerate with stll-cloud-setup.
483
+ # Networked installation and offline service startup are separate lifecycle steps.
484
+ # Cached filesystems may not preserve processes; run start at every session start.
485
+ # Supported platform: Ubuntu 24.04 (noble), amd64/arm64, root or passwordless sudo.
486
+ set -euo pipefail
487
+
488
+ usage() { echo 'Usage: cloud-setup.sh install|start' >&2; exit 2; }
489
+ [[ "$#" == 1 ]] || usage
490
+ case "$1" in install|start) MODE="$1" ;; *) usage ;; esac
491
+ fail() { echo "cloud-setup: $*" >&2; exit 1; }
492
+ trap 'echo "cloud-setup: command failed at line $LINENO" >&2' ERR
493
+ [[ -f /etc/os-release ]] || fail 'Ubuntu 24.04 is required'
494
+ . /etc/os-release
495
+ [[ "$ID" == ubuntu && "$VERSION_ID" == 24.04 && "$VERSION_CODENAME" == noble ]] || fail 'Only Ubuntu 24.04 (noble) is supported'
496
+ SCRIPT="$(realpath -- "$0")"
497
+ REPO_ROOT="$(cd -- "$(dirname -- "$SCRIPT")/.." && pwd -P)"
498
+ [[ "$SCRIPT" == "$REPO_ROOT/.agents/cloud-setup.sh" ]] || fail 'Run the generated repository script'
499
+ if [[ "$(id -u)" != 0 ]]; then
500
+ command -v sudo >/dev/null && sudo -n true || fail 'Root or passwordless sudo is required'
501
+ exec sudo -n -- bash "$SCRIPT" "$MODE"
502
+ fi
503
+ OUTPUT_UID="$(printenv SUDO_UID || id -u)"
504
+ [[ "$OUTPUT_UID" =~ ^[0-9]+$ ]] || fail 'Invalid invoking user'
505
+ OUTPUT_GID="$(getent passwd "$OUTPUT_UID" | cut -d: -f4)"
506
+ [[ "$OUTPUT_GID" =~ ^[0-9]+$ ]] || fail 'Invoking user is unavailable'
507
+ OUTPUT_USER="$(getent passwd "$OUTPUT_UID" | cut -d: -f1)"
508
+ OUTPUT_HOME="$(getent passwd "$OUTPUT_UID" | cut -d: -f6)"
509
+ [[ -n "$OUTPUT_USER" && "$OUTPUT_HOME" == /* && -d "$OUTPUT_HOME" ]] || fail 'Invoking user requires an existing home directory'
510
+ root() { "$@"; }
511
+ service_run() { runuser -u stll-cloud -- "$@" 9>&-; }
512
+ BUN_VERSION='@BUN@'
513
+ NODE_VERSION='@NODE@'
514
+ NODE_DIR="/opt/stll-cloud/node/$NODE_VERSION"
515
+ BUN_DIR="/opt/stll-cloud/bun/$BUN_VERSION"
516
+ export PATH="$NODE_DIR/bin:$BUN_DIR:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
517
+ BUN_CACHE="/var/cache/stll-cloud/bun/$OUTPUT_UID"
518
+ ENV_FILE=@ENV_FILE@
519
+ ENV_MARKER='@ENV_MARKER@'
520
+ [[ -f "$REPO_ROOT/.node-version" && ! -L "$REPO_ROOT/.node-version" ]] || fail 'A regular root .node-version is required'
521
+ [[ "$(awk 'NF { if (++count > 1 || NF != 1) exit 1; value=$1 } END { if (count != 1) exit 1; print value }' "$REPO_ROOT/.node-version")" == "$NODE_VERSION" ]] || fail 'Node selector changed; regenerate cloud-setup.sh'
522
+ cd -- "$REPO_ROOT"
523
+ case "$(uname -m)" in
524
+ x86_64) ARCH=amd64; NODE_ARCH=x64; BUN_ARCH=x64 ;;
525
+ aarch64|arm64) ARCH=arm64; NODE_ARCH=arm64; BUN_ARCH=aarch64 ;;
526
+ *) fail 'Only amd64 and arm64 are supported' ;;
527
+ esac
528
+
529
+ runtime_ready() {
530
+ [[ -x "$NODE_DIR/bin/node" && "$($NODE_DIR/bin/node --version)" == "v$NODE_VERSION" ]] || fail 'Pinned Node is unavailable; run install'
531
+ [[ -x "$BUN_DIR/bun" && "$($BUN_DIR/bun --version)" == "$BUN_VERSION" ]] || fail 'Pinned Bun is unavailable; run install'
532
+ }
533
+ install_runtimes() {
534
+ if ! command -v curl >/dev/null || ! command -v unzip >/dev/null || ! command -v xz >/dev/null || ! command -v openssl >/dev/null || ! command -v gpg >/dev/null; then
535
+ apt-get update
536
+ DEBIAN_FRONTEND=noninteractive apt_install ca-certificates curl unzip xz-utils openssl gnupg util-linux
537
+ fi
538
+ local scratch node_archive bun_archive bun_folder
539
+ scratch="$(mktemp -d)"
540
+ trap 'rm -rf -- "$scratch"' RETURN
541
+ if [[ ! -x "$NODE_DIR/bin/node" ]] || [[ "$($NODE_DIR/bin/node --version)" != "v$NODE_VERSION" ]]; then
542
+ node_archive="node-v$NODE_VERSION-linux-$NODE_ARCH.tar.xz"
543
+ curl --fail --silent --show-error --location --proto '=https' --proto-redir '=https' --tlsv1.2 "https://nodejs.org/dist/v$NODE_VERSION/$node_archive" -o "$scratch/$node_archive"
544
+ curl --fail --silent --show-error --location --proto '=https' --proto-redir '=https' --tlsv1.2 "https://nodejs.org/dist/v$NODE_VERSION/SHASUMS256.txt" -o "$scratch/node-sums"
545
+ (cd "$scratch"; awk -v name="$node_archive" '$2 == name { print; count++ } END { if (count != 1) exit 1 }' node-sums | sha256sum --strict -c -)
546
+ install -d -m 755 "$NODE_DIR"
547
+ tar -xJf "$scratch/$node_archive" --strip-components=1 -C "$NODE_DIR"
548
+ fi
549
+ if [[ ! -x "$BUN_DIR/bun" ]] || [[ "$($BUN_DIR/bun --version)" != "$BUN_VERSION" ]]; then
550
+ bun_folder="bun-linux-$BUN_ARCH"
551
+ bun_archive="$bun_folder.zip"
552
+ curl --fail --silent --show-error --location --proto '=https' --proto-redir '=https' --tlsv1.2 "https://github.com/oven-sh/bun/releases/download/bun-v$BUN_VERSION/$bun_archive" -o "$scratch/$bun_archive"
553
+ curl --fail --silent --show-error --location --proto '=https' --proto-redir '=https' --tlsv1.2 "https://github.com/oven-sh/bun/releases/download/bun-v$BUN_VERSION/SHASUMS256.txt" -o "$scratch/bun-sums"
554
+ (cd "$scratch"; awk -v name="$bun_archive" '$2 == name || $2 == "*" name { print $1 " " name; count++ } END { if (count != 1) exit 1 }' bun-sums | sha256sum --strict -c -)
555
+ unzip -q "$scratch/$bun_archive" -d "$scratch/bun"
556
+ install -d -m 755 "$BUN_DIR"
557
+ install -m 755 "$scratch/bun/$bun_folder/bun" "$BUN_DIR/bun"
558
+ fi
559
+ runtime_ready
560
+ ln -sfnT -- "$NODE_DIR/bin/node" /usr/local/bin/node
561
+ ln -sfnT -- "$NODE_DIR/bin/npm" /usr/local/bin/npm
562
+ ln -sfnT -- "$NODE_DIR/bin/npx" /usr/local/bin/npx
563
+ ln -sfnT -- "$BUN_DIR/bun" /usr/local/bin/bun
564
+ rm -rf -- "$scratch"
565
+ trap - RETURN
566
+ }
567
+
568
+ dependency_install() {
569
+ local directory
570
+ for directory in /var/cache/stll-cloud /var/cache/stll-cloud/bun; do
571
+ [[ ! -L "$directory" ]] || fail 'Dependency cache parent must not be a symlink'
572
+ if [[ -e "$directory" ]]; then
573
+ [[ -d "$directory" && "$(stat -c '%u' "$directory")" == 0 ]] || fail 'Dependency cache parent must be root-owned'
574
+ fi
575
+ install -d -m 755 -o root -g root "$directory"
576
+ done
577
+ [[ ! -L "$BUN_CACHE" ]] || fail 'Dependency cache must not be a symlink'
578
+ if [[ -e "$BUN_CACHE" ]]; then
579
+ [[ -d "$BUN_CACHE" && "$(stat -c '%u' "$BUN_CACHE")" == "$OUTPUT_UID" ]] || fail 'Dependency cache ownership differs from the invoking user'
580
+ fi
581
+ install -d -m 700 -o "$OUTPUT_UID" -g "$OUTPUT_GID" "$BUN_CACHE"
582
+ runuser -u "$OUTPUT_USER" -- env HOME="$OUTPUT_HOME" BUN_INSTALL_CACHE_DIR="$BUN_CACHE" PATH="$PATH" "$BUN_DIR/bun" install --frozen-lockfile
583
+ }
584
+
585
+ @SERVICE_INSTALL@
586
+ @SERVICE_START@
587
+
588
+ validate_environment() {
589
+ local part target="$REPO_ROOT" env_path="$REPO_ROOT/$ENV_FILE" first_line temporary
590
+ while IFS= read -r part; do
591
+ target="$target/$part"
592
+ [[ ! -L "$target" ]] || fail 'Environment path must not contain symbolic links'
593
+ done < <(printf '%s\n' "$ENV_FILE" | tr '/' '\n')
594
+ [[ -d "$(dirname -- "$env_path")" ]] || fail 'Environment parent directory is missing'
595
+ if [[ -e "$env_path" ]]; then
596
+ [[ -f "$env_path" ]] || fail 'Environment target must be a regular file'
597
+ IFS= read -r first_line < "$env_path" || fail 'Refusing to overwrite an unowned environment file'
598
+ [[ "$first_line" == "$ENV_MARKER" ]] || fail 'Refusing to overwrite an unowned environment file'
599
+ fi
600
+ }
601
+ write_environment() {
602
+ validate_environment
603
+ local env_path="$REPO_ROOT/$ENV_FILE" temporary
604
+ temporary="$(mktemp "$(dirname -- "$env_path")/.stll-cloud-env.XXXXXX")"
605
+ chmod 600 "$temporary"
606
+ {
607
+ printf '%s\n' "$ENV_MARKER" 'NODE_ENV=test'
608
+ if [[ -n "$DATABASE_URL" ]]; then printf 'DATABASE_URL=%s\n' "$DATABASE_URL"; fi
609
+ if [[ -n "$REDIS_URL" ]]; then printf 'REDIS_URL=%s\n' "$REDIS_URL"; fi
610
+ } > "$temporary"
611
+ chown "$OUTPUT_UID:$OUTPUT_GID" "$temporary"
612
+ mv -f -- "$temporary" "$env_path"
613
+ }
614
+
615
+ if [[ "$MODE" == install ]]; then
616
+ install_runtimes
617
+ install_services
618
+ dependency_install
619
+ exit 0
620
+ fi
621
+ runtime_ready
622
+ DATABASE_URL=''
623
+ REDIS_URL=''
624
+ validate_environment
625
+ prepare_state
626
+ start_services
627
+ write_environment
628
+ `;
629
+ const shellQuote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
630
+ const generateCloudSetup = ({ policy, cloud, nodeVersion }) => {
631
+ const selected = parseCloudSetup(cloud);
632
+ if (selected === void 0) throw new Error("cloud declaration is required");
633
+ const exactNode = nodeVersion.trim();
634
+ if ((0, semver.valid)(exactNode) !== exactNode || !nodeSelectorMatches(exactNode, policy.node)) throw new Error("cloud requires a tracked exact .node-version within the shared Node series");
635
+ const services = cloudServices.filter((service) => selected.services.includes(service));
636
+ const replacements = /* @__PURE__ */ new Map([
637
+ ["@BUN@", policy.bun],
638
+ ["@NODE@", exactNode],
639
+ ["@ENV_FILE@", shellQuote(selected.envFile)],
640
+ ["@ENV_MARKER@", cloudEnvironmentMarker],
641
+ ["@SERVICE_INSTALL@", renderCloudServiceInstall({
642
+ services,
643
+ postgres: policy.postgres,
644
+ valkey: policy.valkey,
645
+ valkeyArtifacts: policy.valkeyArtifacts
646
+ })],
647
+ ["@SERVICE_START@", renderCloudServiceStart({
648
+ services,
649
+ postgres: policy.postgres,
650
+ valkey: policy.valkey
651
+ })]
652
+ ]);
653
+ return script.replace(/@[A-Z0-9_]+@/g, (token) => {
654
+ const value = replacements.get(token);
655
+ if (value === void 0) throw new Error(`Missing cloud setup field: ${token}`);
656
+ return value;
657
+ });
658
+ };
659
+ //#endregion
660
+ //#region src/toolchain-container-inputs.ts
661
+ const record$6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
662
+ /** Filename class recognized by Dependabot's Docker Compose fetcher. */
663
+ const isComposeDefinitionPath = (file) => /^\.?(?:docker-)?compose(?:-[\w]+)?(?:\.[\w-]+)?\.ya?ml$/i.test(file.split("/").at(-1) ?? "");
664
+ /** Candidate YAML files are classified by their document shape after reading. */
665
+ const isKubernetesDefinitionPath = (file) => /^[^.].*\.ya?ml$/i.test(file.split("/").at(-1) ?? "");
666
+ const kubernetesPodSpecPaths = {
667
+ Pod: ["spec"],
668
+ Deployment: [
669
+ "spec",
670
+ "template",
671
+ "spec"
672
+ ],
673
+ DaemonSet: [
674
+ "spec",
675
+ "template",
676
+ "spec"
677
+ ],
678
+ StatefulSet: [
679
+ "spec",
680
+ "template",
681
+ "spec"
682
+ ],
683
+ ReplicaSet: [
684
+ "spec",
685
+ "template",
686
+ "spec"
687
+ ],
688
+ ReplicationController: [
689
+ "spec",
690
+ "template",
691
+ "spec"
692
+ ],
693
+ Job: [
694
+ "spec",
695
+ "template",
696
+ "spec"
697
+ ],
698
+ CronJob: [
699
+ "spec",
700
+ "jobTemplate",
701
+ "spec",
702
+ "template",
703
+ "spec"
704
+ ]
705
+ };
706
+ /** Shared semantic image enumeration for runtime checks and update-root generation. */
707
+ const containerDocumentImages = (document, file) => {
708
+ if (!record$6(document)) return void 0;
709
+ const services = document["services"];
710
+ if (isComposeDefinitionPath(file) && record$6(services)) {
711
+ const images = [];
712
+ for (const [name, service] of Object.entries(services)) if (record$6(service) && service["image"] !== void 0) images.push({
713
+ image: service["image"],
714
+ path: [
715
+ "services",
716
+ name,
717
+ "image"
718
+ ]
719
+ });
720
+ return {
721
+ ecosystem: "docker-compose",
722
+ images
723
+ };
724
+ }
725
+ if (typeof document["apiVersion"] !== "string" || typeof document["kind"] !== "string") return void 0;
726
+ const images = [];
727
+ const visited = /* @__PURE__ */ new Set();
728
+ const walkResource = (resource, prefix) => {
729
+ if (visited.has(resource)) return;
730
+ visited.add(resource);
731
+ if (typeof resource["apiVersion"] !== "string" || typeof resource["kind"] !== "string") return;
732
+ if (resource["kind"] === "List" && Array.isArray(resource["items"])) {
733
+ for (const [index, item] of resource["items"].entries()) if (record$6(item)) walkResource(item, [
734
+ ...prefix,
735
+ "items",
736
+ index
737
+ ]);
738
+ return;
739
+ }
740
+ const specPath = Object.entries(kubernetesPodSpecPaths).find(([kind]) => kind === resource["kind"])?.[1];
741
+ if (specPath === void 0) return;
742
+ let spec = resource;
743
+ for (const key of specPath) spec = record$6(spec) ? spec[key] : void 0;
744
+ if (!record$6(spec)) return;
745
+ for (const key of [
746
+ "containers",
747
+ "initContainers",
748
+ "ephemeralContainers"
749
+ ]) {
750
+ const containers = spec[key];
751
+ if (!Array.isArray(containers)) continue;
752
+ for (const [index, container] of containers.entries()) if (record$6(container) && container["image"] !== void 0) images.push({
753
+ image: container["image"],
754
+ path: [
755
+ ...prefix,
756
+ ...specPath,
757
+ key,
758
+ index,
759
+ "image"
760
+ ]
761
+ });
762
+ }
763
+ };
764
+ walkResource(document, []);
765
+ return images.length === 0 ? void 0 : {
766
+ ecosystem: "docker",
767
+ images
768
+ };
769
+ };
770
+ //#endregion
771
+ //#region src/toolchain-images.ts
772
+ /** Docker Hub spellings accepted by the shared runtime policy. */
773
+ const dockerHubRegistries = [
774
+ "docker.io",
775
+ "index.docker.io",
776
+ "registry-1.docker.io"
777
+ ];
778
+ /** Expand the full accepted repository alias class without parsing Dockerfile instructions. */
779
+ const ownedDockerImageAliases = (images) => {
780
+ const aliases = /* @__PURE__ */ new Set();
781
+ for (const image of images) for (const repository of [image, `library/${image}`]) {
782
+ aliases.add(repository);
783
+ for (const registry of dockerHubRegistries) aliases.add(`${registry}/${repository}`);
784
+ }
785
+ return [...aliases].sort();
786
+ };
787
+ /** Preserve tag/digest spelling while normalizing registry and namespace aliases. */
788
+ const canonicalDockerRuntime = (image) => {
789
+ const registry = dockerHubRegistries.find((entry) => image.toLowerCase().startsWith(`${entry}/`));
790
+ return (registry === void 0 ? image : image.slice(registry.length + 1)).replace(/^library\//i, "");
791
+ };
792
+ //#endregion
793
+ //#region src/toolchain-inputs.ts
794
+ const excludedInputPath = (file) => file === "" || file.split("/").some((part) => part === "node_modules" || part === "vendor");
795
+ const javascriptDependencyLockfiles = [
796
+ "bun.lock",
797
+ "package-lock.json",
798
+ "yarn.lock",
799
+ "pnpm-lock.yaml"
800
+ ];
801
+ /** Match project, environment, local, and fragment filenames recognized by mise. */
802
+ const isMiseConfigPath = (file) => !excludedInputPath(file) && (/(?:^|\/)\.?mise(?:\.[^./][^/]*)?\.toml$/.test(file) || /(?:^|\/)(?:\.?mise|\.config\/mise)\/config(?:\.[^./][^/]*)?\.toml$/.test(file) || /(?:^|\/)(?:\.?mise|\.config\/mise)\/conf\.d\/[^./][^/]*\.toml$/.test(file));
803
+ /** GitHub action metadata may live at the repository root or in any directory. */
804
+ const githubAutomationFileKind = (file) => {
805
+ if (file === "") return void 0;
806
+ if (/^\.github\/workflows\/[^/]+\.ya?ml$/.test(file)) return "workflow";
807
+ if (/(?:^|\/)action\.ya?ml$/.test(file)) return "action";
808
+ };
809
+ /** Dependabot updates workflows and repository-root action metadata. */
810
+ const isDependabotGithubActionsPath = (file) => {
811
+ const kind = githubAutomationFileKind(file);
812
+ return kind === "workflow" || kind === "action" && !file.includes("/");
813
+ };
814
+ /** Use one filename discriminator for reader selection and Python ecosystem decisions. */
815
+ const pythonDependencyManifestKind = (file) => {
816
+ if (excludedInputPath(file)) return void 0;
817
+ const name = file.split("/").at(-1);
818
+ if (name === "pyproject.toml") return "project";
819
+ if (name === "Pipfile") return "pipfile";
820
+ if (name === "Pipfile.lock") return "pipfile-lock";
821
+ if (name === "setup.py" || name === "setup.cfg") return "setup";
822
+ if (name !== void 0 && /^requirements[^/]*\.(?:txt|in)$/.test(name)) return "requirements";
823
+ };
824
+ const isPythonDependencyManifest = (file) => pythonDependencyManifestKind(file) !== void 0;
825
+ /** Docker definition names use dot-delimited variants, excluding source and documentation. */
826
+ const isDockerDefinitionPath = (file) => {
827
+ if (excludedInputPath(file)) return false;
828
+ const name = file.split("/").at(-1) ?? "";
829
+ if (/\.(?:[cm]?[jt]sx?|mdx?|rst|txt|html?|py|rs|go|java|sh|c|cc|cpp|cxx|h|hpp|cs|rb|php|swift|kt|css|scss)$/i.test(name)) return false;
830
+ return /^(?:[^./]+\.)*(?:dockerfile|containerfile)(?:\.[^./]+)*$/i.test(name);
831
+ };
832
+ /** Lockfiles establish ecosystem presence without reading their dependency graphs. */
833
+ const toolchainInputKind = (file) => {
834
+ if (file === ".agents/cloud-setup.sh") return "config";
835
+ if (githubAutomationFileKind(file) !== void 0) return "config";
836
+ if (excludedInputPath(file)) return void 0;
837
+ if (pythonDependencyManifestKind(file) === "pipfile-lock" || javascriptDependencyLockfiles.some((name) => file.split("/").at(-1) === name) || /(?:^|\/)uv\.lock$/.test(file)) return "presence";
838
+ if (githubAutomationFileKind(file) !== void 0 || isMiseConfigPath(file) || isPythonDependencyManifest(file) || isDockerDefinitionPath(file) || isComposeDefinitionPath(file) || isKubernetesDefinitionPath(file) || /(?:^|\/)(?:package\.json|pnpm-workspace\.yaml|stll-toolchain\.json|\.bun-version|\.node-version|\.nvmrc|\.python-version|rust-toolchain(?:\.toml)?|\.tool-versions|\.?mise\.toml|uv\.toml|\.uv\.toml|\.github\/dependabot\.ya?ml|Cargo\.toml)$/.test(file)) return "config";
839
+ };
840
+ //#endregion
841
+ //#region src/toolchain-workspaces.ts
842
+ /** Match manifest directories with the same positive and negative workspace patterns. */
843
+ const workspaceContains = ({ directory, file, patterns, rootMembership }) => {
844
+ const relative = node_path.default.posix.relative(directory, node_path.default.posix.dirname(file));
845
+ if (relative === "" && rootMembership === "implicit") return true;
846
+ if (relative === ".." || relative.startsWith("../")) return false;
847
+ if (!Array.isArray(patterns)) return false;
848
+ const normalize = (pattern) => node_path.default.posix.normalize(pattern);
849
+ const selected = patterns.filter((value) => typeof value === "string");
850
+ return (0, picomatch.default)(selected.filter((pattern) => !pattern.startsWith("!")).map(normalize))(relative) && !(0, picomatch.default)(selected.filter((pattern) => pattern.startsWith("!")).map((pattern) => normalize(pattern.slice(1))))(relative);
851
+ };
852
+ //#endregion
853
+ //#region src/toolchain-dependabot.ts
854
+ const dependabotRules = ["dependabot-policy"];
855
+ const record$5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
856
+ const strings = (value) => Array.isArray(value) && value.every((entry) => typeof entry === "string");
857
+ const sameStrings = (value, expected) => {
858
+ if (!strings(value) || value.length !== expected.length) return false;
859
+ const sortedExpected = [...expected].sort();
860
+ return [...value].sort().every((entry, index) => entry === sortedExpected[index]);
861
+ };
862
+ const directoryOf = (file) => {
863
+ const directory = node_path.default.posix.dirname(file);
864
+ return directory === "." ? "/" : `/${directory}`;
865
+ };
866
+ const workspaceManifests = {
867
+ npm: "package.json",
868
+ cargo: "Cargo.toml",
869
+ uv: "pyproject.toml"
870
+ };
871
+ const workspaceTable = (parsed, ecosystem) => {
872
+ switch (ecosystem) {
873
+ case "npm": return parsed["workspaces"];
874
+ case "cargo": return parsed["workspace"];
875
+ case "uv": {
876
+ const tool = parsed["tool"];
877
+ const uv = record$5(tool) ? tool["uv"] : void 0;
878
+ return record$5(uv) ? uv["workspace"] : void 0;
879
+ }
880
+ default: throw new Error("unknown workspace ecosystem", { cause: ecosystem });
881
+ }
882
+ };
883
+ /** Installable workspace members share their update root; own-lock projects stay discoverable. */
884
+ const workspaceRoots = (files, ecosystem) => {
885
+ const manifests = Object.keys(files).filter((file) => node_path.default.posix.basename(file) === workspaceManifests[ecosystem] || ecosystem === "npm" && node_path.default.posix.basename(file) === "pnpm-workspace.yaml");
886
+ const workspaces = /* @__PURE__ */ new Map();
887
+ const npmWorkspaceErrors = /* @__PURE__ */ new Map();
888
+ for (const file of manifests) {
889
+ if (ecosystem === "npm") {
890
+ const directory = node_path.default.posix.dirname(file);
891
+ const workspaceFile = node_path.default.posix.join(directory, "pnpm-workspace.yaml");
892
+ const text = files[workspaceFile];
893
+ if (text !== void 0) {
894
+ try {
895
+ const document = (0, yaml.parseDocument)(text);
896
+ if (document.errors.length > 0) throw new Error(`${workspaceFile}:1: invalid pnpm workspace YAML`);
897
+ const parsed = document.toJS({ maxAliasCount: 100 });
898
+ if (!record$5(parsed)) throw new Error(`${workspaceFile}:1: pnpm workspace must contain an object`);
899
+ const patterns = parsed["packages"] ?? [];
900
+ if (!strings(patterns)) throw new Error(`${workspaceFile}:1: pnpm packages must be a string array`);
901
+ workspaces.set(directory, patterns.map((pattern) => pattern.startsWith("!") ? `!${node_path.default.posix.normalize(pattern.slice(1))}` : node_path.default.posix.normalize(pattern)));
902
+ } catch (error) {
903
+ npmWorkspaceErrors.set(directory, error instanceof Error ? error : new Error(String(error)));
904
+ }
905
+ continue;
906
+ }
907
+ }
908
+ try {
909
+ const parsed = ecosystem === "npm" ? JSON.parse(files[file] ?? "") : (0, smol_toml.parse)(files[file] ?? "");
910
+ if (!record$5(parsed)) continue;
911
+ if (ecosystem === "npm" && typeof parsed["packageManager"] === "string" && parsed["packageManager"].startsWith("pnpm@")) continue;
912
+ const value = workspaceTable(parsed, ecosystem);
913
+ const patterns = record$5(value) ? value[ecosystem === "npm" ? "packages" : "members"] : value;
914
+ const members = ecosystem === "cargo" && record$5(value) && patterns === void 0 ? [] : patterns;
915
+ if (strings(members)) {
916
+ const excluded = ecosystem !== "npm" && record$5(value) && strings(value["exclude"]) ? value["exclude"].map((pattern) => `!${pattern}`) : [];
917
+ workspaces.set(node_path.default.posix.dirname(file), [...members, ...excluded]);
918
+ }
919
+ } catch {}
920
+ }
921
+ const implicitCargoMembers = /* @__PURE__ */ new Map();
922
+ const declaredMember = (root, patterns, directory) => {
923
+ const relative = node_path.default.posix.relative(root, directory);
924
+ if (relative === "" || relative === ".." || relative.startsWith("../")) return false;
925
+ return workspaceContains({
926
+ directory: root,
927
+ file: node_path.default.posix.join(directory, "package.json"),
928
+ patterns,
929
+ rootMembership: "patterns"
930
+ });
931
+ };
932
+ const installable = /* @__PURE__ */ new Set(["."]);
933
+ if (ecosystem === "npm") {
934
+ for (const file of manifests) {
935
+ const directory = node_path.default.posix.dirname(file);
936
+ if (javascriptDependencyLockfiles.some((name) => files[node_path.default.posix.join(directory, name)] !== void 0)) installable.add(directory);
937
+ }
938
+ let changed = true;
939
+ while (changed) {
940
+ changed = false;
941
+ for (const [root, patterns] of workspaces) {
942
+ if (!installable.has(root)) continue;
943
+ for (const file of manifests) {
944
+ const directory = node_path.default.posix.dirname(file);
945
+ if (installable.has(directory) || !declaredMember(root, patterns, directory)) continue;
946
+ installable.add(directory);
947
+ changed = true;
948
+ }
949
+ }
950
+ }
951
+ }
952
+ if (ecosystem === "npm") {
953
+ for (const [directory, error] of npmWorkspaceErrors) if (installable.has(directory)) throw error;
954
+ }
955
+ if (ecosystem === "cargo") for (const [root, patterns] of workspaces) {
956
+ const includes = patterns.filter((pattern) => !pattern.startsWith("!"));
957
+ const excludes = patterns.filter((pattern) => pattern.startsWith("!"));
958
+ const memberDirectories = /* @__PURE__ */ new Set([root]);
959
+ for (const file of manifests) {
960
+ const directory = node_path.default.posix.dirname(file);
961
+ const relative = node_path.default.posix.relative(root, directory);
962
+ if (includes.some((pattern) => picomatch.default.isMatch(relative, pattern)) && !excludes.some((pattern) => picomatch.default.isMatch(relative, pattern.slice(1)))) memberDirectories.add(directory);
963
+ }
964
+ for (const directory of memberDirectories) try {
965
+ const parsed = (0, smol_toml.parse)(files[node_path.default.posix.join(directory, "Cargo.toml")] ?? "");
966
+ const workspace = (0, smol_toml.parse)(files[node_path.default.posix.join(root, "Cargo.toml")] ?? "")["workspace"];
967
+ const inherited = record$5(workspace) ? workspace["dependencies"] : void 0;
968
+ const dependencyOwners = [parsed];
969
+ const targets = parsed["target"];
970
+ if (record$5(targets)) {
971
+ for (const target of Object.values(targets)) if (record$5(target)) dependencyOwners.push(target);
972
+ }
973
+ for (const owner of dependencyOwners) for (const key of [
974
+ "dependencies",
975
+ "dev-dependencies",
976
+ "build-dependencies"
977
+ ]) {
978
+ const dependencies = owner[key];
979
+ if (!record$5(dependencies)) continue;
980
+ for (const [name, dependency] of Object.entries(dependencies)) {
981
+ if (!record$5(dependency)) continue;
982
+ const isInherited = dependency["workspace"] === true;
983
+ const resolved = isInherited && record$5(inherited) ? inherited[name] : dependency;
984
+ if (!record$5(resolved) || typeof resolved["path"] !== "string") continue;
985
+ if (node_path.default.posix.isAbsolute(resolved["path"]) || /\\|\$|^[A-Za-z]:/.test(resolved["path"])) continue;
986
+ const target = node_path.default.posix.normalize(node_path.default.posix.join(isInherited ? root : directory, resolved["path"]));
987
+ const relative = node_path.default.posix.relative(root, target);
988
+ if (relative.startsWith("../") || relative === ".." || files[node_path.default.posix.join(target, "Cargo.toml")] === void 0 || excludes.some((pattern) => picomatch.default.isMatch(relative, pattern.slice(1)))) continue;
989
+ memberDirectories.add(target);
990
+ }
991
+ }
992
+ } catch {}
993
+ implicitCargoMembers.set(root, memberDirectories);
994
+ }
995
+ return manifests.filter((file) => ecosystem !== "npm" || installable.has(node_path.default.posix.dirname(file))).filter((file) => {
996
+ const directory = node_path.default.posix.dirname(file);
997
+ return ![...workspaces].some(([root, patterns]) => {
998
+ if (ecosystem === "npm" && !installable.has(root)) return false;
999
+ const relative = node_path.default.posix.relative(root, directory);
1000
+ if (relative === "" || relative.startsWith("../")) return false;
1001
+ const includes = patterns.filter((pattern) => !pattern.startsWith("!"));
1002
+ const excludes = patterns.filter((pattern) => pattern.startsWith("!"));
1003
+ return (implicitCargoMembers.get(root)?.has(directory) === true || (ecosystem === "npm" ? declaredMember(root, patterns, directory) : includes.some((pattern) => picomatch.default.isMatch(relative, pattern)))) && !excludes.some((pattern) => picomatch.default.isMatch(relative, pattern.slice(1)));
1004
+ });
1005
+ }).map(directoryOf).filter((directory, index, values) => values.indexOf(directory) === index);
1006
+ };
1007
+ const javascriptEcosystem = (directory, files) => {
1008
+ const root = directory === "/" ? "." : directory.slice(1);
1009
+ if (files[node_path.default.posix.join(root, "bun.lock")] !== void 0) return "bun";
1010
+ try {
1011
+ const manifest = JSON.parse(files[node_path.default.posix.join(root, "package.json")] ?? "{}");
1012
+ if (record$5(manifest) && typeof manifest["packageManager"] === "string" && manifest["packageManager"].startsWith("bun@")) return "bun";
1013
+ } catch {}
1014
+ return "npm";
1015
+ };
1016
+ const pythonEcosystem = (file, files) => {
1017
+ const manifestKind = pythonDependencyManifestKind(file);
1018
+ if (manifestKind === "pipfile" || manifestKind === "pipfile-lock" || manifestKind === "setup") return "pip";
1019
+ const root = node_path.default.posix.dirname(file);
1020
+ if (files[node_path.default.posix.join(root, "uv.lock")] !== void 0 || files[node_path.default.posix.join(root, "uv.toml")] !== void 0) return "uv";
1021
+ const pyproject = files[node_path.default.posix.join(root, "pyproject.toml")];
1022
+ if (pyproject !== void 0) try {
1023
+ const tool = (0, smol_toml.parse)(pyproject)["tool"];
1024
+ if (record$5(tool) && record$5(tool["uv"])) return "uv";
1025
+ } catch {}
1026
+ return "pip";
1027
+ };
1028
+ const ecosystemRoots = (files) => {
1029
+ const roots = /* @__PURE__ */ new Map();
1030
+ const requireRoot = (ecosystem, directory) => {
1031
+ const directories = roots.get(ecosystem) ?? /* @__PURE__ */ new Set();
1032
+ directories.add(directory);
1033
+ roots.set(ecosystem, directories);
1034
+ };
1035
+ for (const directory of workspaceRoots(files, "npm")) requireRoot(javascriptEcosystem(directory, files), directory);
1036
+ for (const directory of workspaceRoots(files, "cargo")) requireRoot("cargo", directory);
1037
+ for (const directory of workspaceRoots(files, "uv")) {
1038
+ const root = directory === "/" ? "." : directory.slice(1);
1039
+ requireRoot(pythonEcosystem(node_path.default.posix.join(root, "pyproject.toml"), files), directory);
1040
+ }
1041
+ for (const file of Object.keys(files)) {
1042
+ if (isDependabotGithubActionsPath(file)) requireRoot("github-actions", "/");
1043
+ const name = node_path.default.posix.basename(file);
1044
+ if (isDockerDefinitionPath(file)) requireRoot("docker", directoryOf(file));
1045
+ if (isComposeDefinitionPath(file) || isKubernetesDefinitionPath(file)) for (const document of (0, yaml.parseAllDocuments)(files[file] ?? "", { merge: true })) {
1046
+ if (document.errors.length > 0) continue;
1047
+ try {
1048
+ const classified = containerDocumentImages(document.toJS({ maxAliasCount: 100 }), file);
1049
+ if (classified !== void 0) requireRoot(classified.ecosystem, directoryOf(file));
1050
+ } catch {}
1051
+ }
1052
+ if (name === "uv.lock" || name === "uv.toml" || name !== "pyproject.toml" && isPythonDependencyManifest(file)) requireRoot(pythonEcosystem(file, files), directoryOf(file));
1053
+ }
1054
+ return roots;
1055
+ };
1056
+ const ignoredFor = (ecosystem, policy) => {
1057
+ if (ecosystem === "npm" || ecosystem === "bun") return policy.ignoredPackages;
1058
+ if (ecosystem === "github-actions") return policy.ignoredActions;
1059
+ if (ecosystem === "docker" || ecosystem === "docker-compose") return ownedDockerImageAliases(policy.ignoredImages);
1060
+ return [];
1061
+ };
1062
+ /** Validate the shared update policy against a hermetic tracked-file snapshot. */
1063
+ const checkDependabot = ({ files, policy }) => {
1064
+ const roots = ecosystemRoots(files);
1065
+ const paths = [".github/dependabot.yml", ".github/dependabot.yaml"].filter((file) => files[file] !== void 0);
1066
+ if (roots.size === 0 && paths.length === 0) return [];
1067
+ const file = paths.at(0) ?? ".github/dependabot.yml";
1068
+ const diagnostics = [];
1069
+ const add = (message, line = 1) => {
1070
+ diagnostics.push({
1071
+ rule: "dependabot-policy",
1072
+ path: file,
1073
+ line,
1074
+ message
1075
+ });
1076
+ };
1077
+ if (paths.length === 0) {
1078
+ add("add a Dependabot configuration for the repository's package ecosystems");
1079
+ return diagnostics;
1080
+ }
1081
+ if (paths.length > 1) add("keep one Dependabot configuration file");
1082
+ const lineCounter = new yaml.LineCounter();
1083
+ const document = (0, yaml.parseDocument)(files[file] ?? "", { lineCounter });
1084
+ if (document.errors.length > 0) {
1085
+ for (const error of document.errors) add(`invalid Dependabot YAML: ${error.message}`, lineCounter.linePos(error.pos[0]).line);
1086
+ return diagnostics;
1087
+ }
1088
+ let parsed;
1089
+ try {
1090
+ parsed = document.toJS({ maxAliasCount: 100 });
1091
+ } catch {
1092
+ add("cannot resolve Dependabot YAML aliases");
1093
+ return diagnostics;
1094
+ }
1095
+ if (!record$5(parsed) || parsed["version"] !== 2 || !Array.isArray(parsed["updates"])) {
1096
+ add("Dependabot must declare version: 2 and an updates array");
1097
+ return diagnostics;
1098
+ }
1099
+ const covered = /* @__PURE__ */ new Map();
1100
+ let legacy;
1101
+ try {
1102
+ const legacyDocument = (0, yaml.parseDocument)(files[file] ?? "", {
1103
+ version: "1.1",
1104
+ schema: "yaml-1.1"
1105
+ });
1106
+ if (legacyDocument.errors.length === 0) legacy = legacyDocument.toJS({ maxAliasCount: 100 });
1107
+ } catch {}
1108
+ const legacyUpdates = record$5(legacy) && Array.isArray(legacy["updates"]) ? legacy["updates"] : [];
1109
+ const rootClaims = /* @__PURE__ */ new Map();
1110
+ const directoryClaims = /* @__PURE__ */ new Map();
1111
+ for (const [index, update] of parsed["updates"].entries()) {
1112
+ const lineOf = (key) => {
1113
+ const node = document.getIn([
1114
+ "updates",
1115
+ index,
1116
+ key
1117
+ ], true);
1118
+ const offset = (0, yaml.isNode)(node) ? node.range?.[0] : void 0;
1119
+ return offset === void 0 ? 1 : lineCounter.linePos(offset).line;
1120
+ };
1121
+ const report = (key, message) => add(message, lineOf(key));
1122
+ if (!record$5(update) || typeof update["package-ecosystem"] !== "string") {
1123
+ report("package-ecosystem", "each Dependabot update must declare a package ecosystem");
1124
+ continue;
1125
+ }
1126
+ const ecosystem = update["package-ecosystem"];
1127
+ if (update["target-branch"] !== void 0) report("target-branch", `${ecosystem}: shared updates must target the default branch`);
1128
+ if (update["open-pull-requests-limit"] === 0) report("open-pull-requests-limit", `${ecosystem}: version updates must remain enabled`);
1129
+ const single = update["directory"];
1130
+ const multiple = update["directories"];
1131
+ let directories = [];
1132
+ if (typeof single === "string" && multiple === void 0) directories = [single];
1133
+ else if (single === void 0 && strings(multiple)) directories = multiple;
1134
+ const validDirectories = directories.filter((directory) => directory.startsWith("/") && !directory.split("/").includes(".."));
1135
+ if (directories.length === 0 || validDirectories.length !== directories.length) report("directory", `${ecosystem}: declare directory or nonempty directories with absolute repository paths`);
1136
+ const normalizedDirectories = Array.from(new Set(validDirectories.map((value) => node_path.default.posix.normalize(value).replace(/\/+$/, "") || "/")));
1137
+ const matches = covered.get(ecosystem) ?? /* @__PURE__ */ new Set();
1138
+ const claimedDirectories = directoryClaims.get(ecosystem) ?? /* @__PURE__ */ new Map();
1139
+ for (const directory of normalizedDirectories) {
1140
+ const previous = claimedDirectories.get(directory);
1141
+ if (previous !== void 0) report(multiple === void 0 ? "directory" : "directories", `${ecosystem}: directory ${directory} overlaps update entry ${previous + 1}`);
1142
+ else claimedDirectories.set(directory, index);
1143
+ }
1144
+ directoryClaims.set(ecosystem, claimedDirectories);
1145
+ const claimedRoots = rootClaims.get(ecosystem) ?? /* @__PURE__ */ new Map();
1146
+ for (const root of roots.get(ecosystem) ?? []) if (normalizedDirectories.some((directory) => directory === root || multiple !== void 0 && picomatch.default.isMatch(root, directory))) {
1147
+ const previous = claimedRoots.get(root);
1148
+ if (previous !== void 0) report(multiple === void 0 ? "directory" : "directories", `${ecosystem}: update root ${root} overlaps update entry ${previous + 1}`);
1149
+ else claimedRoots.set(root, index);
1150
+ matches.add(root);
1151
+ }
1152
+ rootClaims.set(ecosystem, claimedRoots);
1153
+ covered.set(ecosystem, matches);
1154
+ const schedule = update["schedule"];
1155
+ const legacyUpdate = legacyUpdates.at(index);
1156
+ const legacySchedule = record$5(legacyUpdate) ? legacyUpdate["schedule"] : void 0;
1157
+ if (record$5(schedule) && schedule["time"] === policy.schedule.time && (!record$5(legacySchedule) || legacySchedule["time"] !== policy.schedule.time)) report("schedule", `${ecosystem}: quote schedule time to preserve its string value in YAML 1.1`);
1158
+ if (!record$5(schedule) || Object.keys(schedule).length !== Object.keys(policy.schedule).length || Object.entries(policy.schedule).some(([key, value]) => schedule[key] !== value)) report("schedule", `${ecosystem}: schedule must match the shared policy`);
1159
+ const cooldown = update["cooldown"];
1160
+ if (!record$5(cooldown) || Object.keys(cooldown).length !== 1 || cooldown["default-days"] !== policy.cooldown.defaultDays) report("cooldown", `${ecosystem}: cooldown must contain only default-days: ${policy.cooldown.defaultDays}`);
1161
+ const groups = update["groups"];
1162
+ if (!record$5(groups) || Object.keys(groups).length !== Object.keys(policy.groups).length || Object.entries(policy.groups).some(([name, expected]) => {
1163
+ const group = groups[name];
1164
+ return !record$5(group) || Object.keys(group).length !== 2 || !sameStrings(group["patterns"], expected.patterns) || !sameStrings(group["update-types"], expected.updateTypes);
1165
+ })) report("groups", `${ecosystem}: groups must match the shared policy`);
1166
+ const ignored = ignoredFor(ecosystem, policy);
1167
+ const ignore = update["ignore"];
1168
+ if (ignore !== void 0 && (!Array.isArray(ignore) || ignore.length === 0)) report("ignore", `${ecosystem}: omit ignore or provide a nonempty array`);
1169
+ if (Array.isArray(ignore) && ignore.some((entry) => !record$5(entry) || typeof entry["dependency-name"] !== "string" || !ignored.includes(entry["dependency-name"]))) report("ignore", `${ecosystem}: ignore only packages owned by the shared policy`);
1170
+ for (const name of ignored) if (!Array.isArray(ignore) || !ignore.some((entry) => record$5(entry) && entry["dependency-name"] === name && Object.keys(entry).length === 1)) report("ignore", `${ecosystem}: ignore all updates for shared pin ${name}`);
1171
+ }
1172
+ for (const [ecosystem, directories] of roots) for (const directory of directories) if (!covered.get(ecosystem)?.has(directory)) add(`add a ${ecosystem} update entry covering ${directory}`);
1173
+ return diagnostics;
1174
+ };
1175
+ //#endregion
1176
+ //#region src/toolchain-engine-floors.ts
1177
+ const record$4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1178
+ const repositoryPath = (value) => typeof value === "string" && value !== "" && !/^[A-Za-z]:/.test(value) && !/[\\\s]/.test(value) && !Array.from(value).some((character) => character.charCodeAt(0) < 32) && value.split("/").every((part) => part !== "" && part !== "." && part !== "..");
1179
+ const parseEngineFloors = (input) => {
1180
+ if (input === void 0) return [];
1181
+ if (!Array.isArray(input)) throw new Error("engineFloors must be an array");
1182
+ const result = [];
1183
+ const jobs = /* @__PURE__ */ new Set();
1184
+ for (const entry of input) {
1185
+ if (!record$4(entry) || Object.keys(entry).some((key) => ![
1186
+ "package",
1187
+ "workflow",
1188
+ "job"
1189
+ ].includes(key)) || entry["package"] !== "." && !repositoryPath(entry["package"]) || !repositoryPath(entry["workflow"]) || !/^\.github\/workflows\/[^/]+\.ya?ml$/.test(entry["workflow"]) || typeof entry["job"] !== "string" || entry["job"].trim() === "") throw new Error("each engine floor requires a repository package directory, workflow path and job");
1190
+ const key = `${entry["workflow"]}:${entry["job"]}`;
1191
+ if (jobs.has(key)) throw new Error("engine floor workflow jobs must be unique");
1192
+ jobs.add(key);
1193
+ result.push({
1194
+ package: entry["package"],
1195
+ workflow: entry["workflow"],
1196
+ job: entry["job"]
1197
+ });
1198
+ }
1199
+ return result;
1200
+ };
1201
+ const resolveEngineFloor = (entry, files) => {
1202
+ const manifestText = files[node_path.default.posix.join(entry.package, "package.json")];
1203
+ const workflowText = files[entry.workflow];
1204
+ if (manifestText === void 0 || workflowText === void 0) throw new Error("engine floor package and workflow must be tracked");
1205
+ const manifest = JSON.parse(manifestText);
1206
+ if (!record$4(manifest) || manifest["private"] === true || typeof manifest["name"] !== "string" || manifest["name"].trim() === "" || !record$4(manifest["engines"]) || typeof manifest["engines"]["node"] !== "string") throw new Error("engine floor package must be published and declare engines.node");
1207
+ const range = manifest["engines"]["node"];
1208
+ const minimum = (0, semver.validRange)(range) === null ? null : (0, semver.minVersion)(range);
1209
+ if (minimum === null || minimum.prerelease.length !== 0) throw new Error("engine floor engines.node must declare a stable minimum");
1210
+ const document = (0, yaml.parseDocument)(workflowText, { merge: true });
1211
+ if (document.errors.length !== 0) throw new Error("engine floor workflow must be valid YAML");
1212
+ const workflow = document.toJS({ maxAliasCount: 100 });
1213
+ if (!record$4(workflow) || !record$4(workflow["jobs"])) throw new Error("engine floor job must exist in its tracked workflow");
1214
+ const job = workflow["jobs"][entry.job];
1215
+ if (!record$4(job)) throw new Error("engine floor job must exist in its tracked workflow");
1216
+ if (!Array.isArray(job["steps"]) || Object.hasOwn(job, "uses")) throw new Error("engine floor job must declare steps and cannot reuse a workflow");
1217
+ return {
1218
+ ...entry,
1219
+ range,
1220
+ major: minimum.major
1221
+ };
1222
+ };
1223
+ const engineFloorSelectorMatches = (value, floor) => {
1224
+ if (typeof value !== "string" || !/^\d+\.\d+\.\d+$/.test(value) || (0, semver.valid)(value) !== value) return false;
1225
+ return Number(value.split(".").at(0)) === floor.major && (0, semver.satisfies)(value, floor.range);
1226
+ };
1227
+ //#endregion
1228
+ //#region src/toolchain-packages.ts
1229
+ const packageRules = [
1230
+ "bun-pins",
1231
+ "package-pins",
1232
+ "typescript-layout",
1233
+ "node-engine"
1234
+ ];
1235
+ const record$3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1236
+ const shellSubstitutions = (command) => {
1237
+ const frames = [{
1238
+ kind: "root",
1239
+ start: 0,
1240
+ depth: 0,
1241
+ quote: void 0
1242
+ }];
1243
+ const bodies = [];
1244
+ for (let index = 0; index < command.length; index += 1) {
1245
+ const frame = frames.at(-1);
1246
+ if (frame === void 0) break;
1247
+ const character = command.at(index);
1248
+ if (character === "\\" && frame.quote !== "'") {
1249
+ index += 1;
1250
+ continue;
1251
+ }
1252
+ if (character === "`" && frame.kind === "backticks") {
1253
+ bodies.push(command.slice(frame.start, index));
1254
+ frames.pop();
1255
+ continue;
1256
+ }
1257
+ if (character === frame.quote) {
1258
+ frame.quote = void 0;
1259
+ continue;
1260
+ }
1261
+ if (frame.quote === "'") continue;
1262
+ if (character === "$" && command.at(index + 1) === "(") {
1263
+ frames.push({
1264
+ kind: "parentheses",
1265
+ start: index + 2,
1266
+ depth: 1,
1267
+ quote: void 0
1268
+ });
1269
+ index += 1;
1270
+ continue;
1271
+ }
1272
+ if (character === "`") {
1273
+ frames.push({
1274
+ kind: "backticks",
1275
+ start: index + 1,
1276
+ depth: 0,
1277
+ quote: void 0
1278
+ });
1279
+ continue;
1280
+ }
1281
+ if (frame.quote !== void 0) continue;
1282
+ if (character === "'" || character === "\"") {
1283
+ frame.quote = character;
1284
+ continue;
1285
+ }
1286
+ if (frame.kind !== "parentheses") continue;
1287
+ if (character === "(") frame.depth += 1;
1288
+ if (character === ")" && --frame.depth === 0) {
1289
+ bodies.push(command.slice(frame.start, index));
1290
+ frames.pop();
1291
+ }
1292
+ }
1293
+ for (const frame of frames.slice(1)) bodies.push(command.slice(frame.start));
1294
+ return bodies;
1295
+ };
1296
+ const compilerCommandSegments = (command) => {
1297
+ const segments = [[]];
1298
+ for (const source of [command, ...shellSubstitutions(command)]) {
1299
+ segments.push([]);
1300
+ const shellWords = source.match(/(?:[^\s"'\\;&|()]|\\[^\n]|"(?:[^"\\]|\\.)*"|'[^']*')+|&&|\|\||[();&|\n]/g);
1301
+ for (const word of shellWords ?? []) if (/^(?:&&|\|\||[;&|\n])$/.test(word)) segments.push([]);
1302
+ else segments.at(-1)?.push(word);
1303
+ }
1304
+ return segments.map((words) => {
1305
+ let start = 0;
1306
+ const skipAssignments = () => {
1307
+ while (/^[A-Za-z_][A-Za-z\d_]*=/.test(words.at(start) ?? "")) start += 1;
1308
+ };
1309
+ skipAssignments();
1310
+ while (/^(?:\/usr\/bin\/|\/bin\/)?env$/.test(words.at(start) ?? "")) {
1311
+ start += 1;
1312
+ while (start < words.length) {
1313
+ const option = words.at(start);
1314
+ if (option === "--") {
1315
+ start += 1;
1316
+ break;
1317
+ }
1318
+ if (option === "-u" || option === "--unset") {
1319
+ start += 2;
1320
+ continue;
1321
+ }
1322
+ if (option === "-" || option === "-i" || option === "--ignore-environment" || /^--unset=.+|^-u.+/.test(option ?? "")) {
1323
+ start += 1;
1324
+ continue;
1325
+ }
1326
+ break;
1327
+ }
1328
+ skipAssignments();
1329
+ }
1330
+ return words.slice(start);
1331
+ });
1332
+ };
1333
+ const launcherValueOptions = new Map(Object.entries({
1334
+ npx: [
1335
+ "-p",
1336
+ "--package",
1337
+ "-c",
1338
+ "--call",
1339
+ "--cache",
1340
+ "--registry",
1341
+ "--userconfig"
1342
+ ],
1343
+ bunx: ["-p", "--package"],
1344
+ pnpm: [
1345
+ "--filter",
1346
+ "-F",
1347
+ "--dir",
1348
+ "-C",
1349
+ "--package"
1350
+ ],
1351
+ yarn: [
1352
+ "--cwd",
1353
+ "--cache-folder",
1354
+ "--mutex",
1355
+ "--use-yarnrc",
1356
+ "--modules-folder",
1357
+ "--registry"
1358
+ ],
1359
+ bun: [
1360
+ "--cwd",
1361
+ "--filter",
1362
+ "-F",
1363
+ "--config",
1364
+ "-c",
1365
+ "--env-file",
1366
+ "-e",
1367
+ "--eval",
1368
+ "-p",
1369
+ "--print"
1370
+ ],
1371
+ node: [
1372
+ "-e",
1373
+ "--eval",
1374
+ "-p",
1375
+ "--print",
1376
+ "--conditions",
1377
+ "-C",
1378
+ "--inspect-port",
1379
+ "--max-old-space-size",
1380
+ "--stack-size",
1381
+ "--title",
1382
+ "--icu-data-dir",
1383
+ "--openssl-config",
1384
+ "--input-type"
1385
+ ]
1386
+ }).map(([launcher, options]) => [launcher, new Set(options)]));
1387
+ const invokesCompiler = (words) => {
1388
+ const literal = (word) => {
1389
+ let result = "";
1390
+ let quote;
1391
+ for (let index = 0; index < word.length; index += 1) {
1392
+ const character = word.at(index);
1393
+ if (character === quote) {
1394
+ quote = void 0;
1395
+ continue;
1396
+ }
1397
+ if (quote === void 0 && (character === "'" || character === "\"")) {
1398
+ quote = character;
1399
+ continue;
1400
+ }
1401
+ const next = word.at(index + 1);
1402
+ if (character === "\\" && next !== void 0 && quote !== "'" && (quote === void 0 || /[$`"\\\n]/.test(next))) {
1403
+ result += next;
1404
+ index += 1;
1405
+ } else result += character;
1406
+ }
1407
+ return result;
1408
+ };
1409
+ const tokens = words.map(literal);
1410
+ const compiler = (word) => /(?:^|\/)(?:tsc|tsgo)(?:\.js)?$/.test(word);
1411
+ let start = 0;
1412
+ const skipOptions = (index, launcher) => {
1413
+ while (tokens.at(index)?.startsWith("-")) {
1414
+ const option = tokens.at(index);
1415
+ index += 1;
1416
+ if (option === "--") break;
1417
+ if (option !== void 0 && launcherValueOptions.get(launcher)?.has(option)) index += 1;
1418
+ }
1419
+ return index;
1420
+ };
1421
+ while (start < tokens.length) {
1422
+ const launcher = tokens.at(start);
1423
+ if (launcher === void 0 || !launcherValueOptions.has(launcher)) break;
1424
+ start = skipOptions(start + 1, launcher);
1425
+ if (launcher === "bun" && tokens.at(start) === "check") return true;
1426
+ const subcommand = tokens.at(start);
1427
+ if (launcher === "bun" && (subcommand === "x" || subcommand === "run") || launcher === "pnpm" && (subcommand === "exec" || subcommand === "dlx") || launcher === "yarn" && (subcommand === "exec" || subcommand === "dlx" || subcommand === "run")) start = skipOptions(start + 1, launcher);
1428
+ }
1429
+ return tokens.slice(start).some((word, index) => compiler(word) || word === "bun" && tokens.at(skipOptions(start + index + 1, "bun")) === "check");
1430
+ };
1431
+ /** Validate manifests and catalog resolutions from a tracked-file snapshot. */
1432
+ const checkPackageFiles = ({ files, policy }) => {
1433
+ const sources = new Map(Object.entries(files));
1434
+ const diagnostics = [];
1435
+ const pins = new Map(Object.entries({
1436
+ ...policy.packages,
1437
+ "bun-types": policy.bun
1438
+ }));
1439
+ const manifests = /* @__PURE__ */ new Map();
1440
+ const yamlLocations = /* @__PURE__ */ new Map();
1441
+ const reportedLines = /* @__PURE__ */ new Map();
1442
+ const add = ({ file, rule, key, value, message }) => {
1443
+ const source = sources.get(file);
1444
+ if (source === void 0) throw new Error(`Missing package diagnostic source: ${file}`);
1445
+ const serialized = value === void 0 ? void 0 : JSON.stringify(value);
1446
+ const locationKey = `${file}:${key}:${serialized ?? ""}`;
1447
+ const previous = reportedLines.get(locationKey) ?? -1;
1448
+ const yamlLine = yamlLocations.get(locationKey)?.shift();
1449
+ const index = source.split(/\r?\n/).findIndex((line, lineIndex) => lineIndex > previous && line.includes(JSON.stringify(key)) && (serialized === void 0 || line.includes(serialized)));
1450
+ if (index >= 0) reportedLines.set(locationKey, index);
1451
+ diagnostics.push({
1452
+ rule,
1453
+ path: file,
1454
+ line: yamlLine ?? Math.max(1, index + 1),
1455
+ message
1456
+ });
1457
+ };
1458
+ for (const [file, text] of sources) {
1459
+ const pnpm = node_path.default.posix.basename(file) === "pnpm-workspace.yaml";
1460
+ if (!pnpm && node_path.default.posix.basename(file) !== "package.json") continue;
1461
+ try {
1462
+ const lineCounter = new yaml.LineCounter();
1463
+ const document = pnpm ? (0, yaml.parseDocument)(text, { lineCounter }) : void 0;
1464
+ if (document !== void 0 && document.errors.length > 0) throw new Error("invalid YAML");
1465
+ const json = document === void 0 ? JSON.parse(text) : document.toJS();
1466
+ if (!record$3(json)) throw new Error("manifest must be an object");
1467
+ if (pnpm) {
1468
+ if (json["catalog"] !== void 0 && !record$3(json["catalog"])) throw new Error("catalog must be a mapping");
1469
+ if (json["catalogs"] !== void 0 && (!record$3(json["catalogs"]) || Object.values(json["catalogs"]).some((catalog) => !record$3(catalog)))) throw new Error("named catalogs must be mappings");
1470
+ if (json["packages"] !== void 0 && (!Array.isArray(json["packages"]) || !json["packages"].every((pattern) => typeof pattern === "string"))) throw new Error("workspace packages must be patterns");
1471
+ }
1472
+ manifests.set(file, json);
1473
+ if (document === void 0) continue;
1474
+ const catalogEntries = [
1475
+ {
1476
+ catalog: json["catalog"],
1477
+ prefix: ["catalog"]
1478
+ },
1479
+ {
1480
+ catalog: json["overrides"],
1481
+ prefix: ["overrides"]
1482
+ },
1483
+ ...record$3(json["catalogs"]) ? Object.entries(json["catalogs"]).map(([name, catalog]) => ({
1484
+ catalog,
1485
+ prefix: ["catalogs", name]
1486
+ })) : []
1487
+ ];
1488
+ for (const { catalog, prefix } of catalogEntries) {
1489
+ if (!record$3(catalog)) continue;
1490
+ for (const [name, value] of Object.entries(catalog)) {
1491
+ const node = document.getIn([...prefix, name], true);
1492
+ if (!(0, yaml.isNode)(node) || node.range === void 0 || node.range === null) continue;
1493
+ const key = `${file}:${name}:${JSON.stringify(value)}`;
1494
+ const lines = yamlLocations.get(key) ?? [];
1495
+ lines.push(lineCounter.linePos(node.range[0]).line);
1496
+ yamlLocations.set(key, lines);
1497
+ }
1498
+ }
1499
+ } catch {
1500
+ add({
1501
+ file,
1502
+ rule: "package-pins",
1503
+ key: "",
1504
+ message: pnpm ? "invalid pnpm-workspace.yaml object" : "invalid package.json object"
1505
+ });
1506
+ }
1507
+ }
1508
+ const catalogSources = (json) => [json, ...record$3(json["workspaces"]) ? [json["workspaces"]] : []];
1509
+ const pnpmWorkspaceFor = (file) => {
1510
+ let directory = node_path.default.posix.dirname(file);
1511
+ while (true) {
1512
+ const workspace = manifests.get(node_path.default.posix.join(directory, "pnpm-workspace.yaml"));
1513
+ if (workspace !== void 0) return {
1514
+ directory,
1515
+ workspace
1516
+ };
1517
+ if (directory === ".") return void 0;
1518
+ directory = node_path.default.posix.dirname(directory);
1519
+ }
1520
+ };
1521
+ const catalogFor = (file, name) => {
1522
+ const owner = pnpmWorkspaceFor(file);
1523
+ if (owner !== void 0) {
1524
+ const { directory, workspace } = owner;
1525
+ if (node_path.default.posix.basename(file) === "package.json" && !workspaceContains({
1526
+ directory,
1527
+ file,
1528
+ patterns: workspace["packages"],
1529
+ rootMembership: "implicit"
1530
+ })) return void 0;
1531
+ if (name === "" || name === "default") return workspace["catalog"] ?? (record$3(workspace["catalogs"]) ? workspace["catalogs"]["default"] : void 0);
1532
+ return record$3(workspace["catalogs"]) ? workspace["catalogs"][name] : void 0;
1533
+ }
1534
+ let directory = node_path.default.posix.dirname(file);
1535
+ while (true) {
1536
+ const manifest = manifests.get(node_path.default.posix.join(directory, "package.json"));
1537
+ if (manifest !== void 0) {
1538
+ for (const source of catalogSources(manifest)) {
1539
+ if (name === "" && source["catalog"] !== void 0) return source["catalog"];
1540
+ if (record$3(source["catalogs"]) && source["catalogs"][name] !== void 0) return source["catalogs"][name];
1541
+ }
1542
+ if (manifest["workspaces"] !== void 0) return void 0;
1543
+ }
1544
+ if (directory === ".") return void 0;
1545
+ directory = node_path.default.posix.dirname(directory);
1546
+ }
1547
+ };
1548
+ const resolve = (file, name, value) => {
1549
+ const visited = /* @__PURE__ */ new Set();
1550
+ while (typeof value === "string" && value.startsWith("catalog:")) {
1551
+ if (visited.has(value)) return void 0;
1552
+ visited.add(value);
1553
+ const catalog = catalogFor(file, value.slice(8));
1554
+ value = record$3(catalog) ? catalog[name] : void 0;
1555
+ }
1556
+ return value;
1557
+ };
1558
+ const workspaceOwnerFor = (file) => {
1559
+ const pnpm = pnpmWorkspaceFor(file);
1560
+ if (pnpm !== void 0) return {
1561
+ directory: pnpm.directory,
1562
+ patterns: pnpm.workspace["packages"],
1563
+ source: "pnpm"
1564
+ };
1565
+ let directory = node_path.default.posix.dirname(file);
1566
+ while (true) {
1567
+ const workspaces = manifests.get(node_path.default.posix.join(directory, "package.json"))?.["workspaces"];
1568
+ if (workspaces !== void 0) return {
1569
+ directory,
1570
+ patterns: record$3(workspaces) ? workspaces["packages"] : workspaces,
1571
+ source: "json"
1572
+ };
1573
+ if (directory === ".") return void 0;
1574
+ directory = node_path.default.posix.dirname(directory);
1575
+ }
1576
+ };
1577
+ const workspaceResolution = ({ file, name, pin }) => {
1578
+ const owner = workspaceOwnerFor(file);
1579
+ if (owner === void 0) return "nonmember";
1580
+ const { directory, patterns, source } = owner;
1581
+ if (source === "json" && !Array.isArray(patterns)) return "mismatch";
1582
+ if (!workspaceContains({
1583
+ directory,
1584
+ file,
1585
+ patterns,
1586
+ rootMembership: "implicit"
1587
+ })) return "nonmember";
1588
+ const candidates = [...manifests.entries()].filter(([candidate, json]) => node_path.default.posix.basename(candidate) === "package.json" && json["name"] === name && workspaceContains({
1589
+ directory,
1590
+ file: candidate,
1591
+ patterns,
1592
+ rootMembership: source === "json" ? "patterns" : "implicit"
1593
+ }));
1594
+ return candidates.length === 1 && candidates.every(([, json]) => json["version"] === pin) ? "matched" : "mismatch";
1595
+ };
1596
+ const tsSpecifiers = /* @__PURE__ */ new Map();
1597
+ for (const layout of policy.typescriptInstallLayouts) {
1598
+ const values = tsSpecifiers.get(layout.compilerPackage) ?? /* @__PURE__ */ new Set();
1599
+ values.add(layout.compilerSpecifier);
1600
+ tsSpecifiers.set(layout.compilerPackage, values);
1601
+ if (layout.type !== "split-compatibility") continue;
1602
+ const compatibility = tsSpecifiers.get(layout.compatibilityPackage) ?? /* @__PURE__ */ new Set();
1603
+ compatibility.add(layout.compatibilitySpecifier);
1604
+ tsSpecifiers.set(layout.compatibilityPackage, compatibility);
1605
+ }
1606
+ tsSpecifiers.set(policy.typescript6Compatibility.packageAlias, /* @__PURE__ */ new Set([`npm:typescript@${policy.typescript6Compatibility.version}`]));
1607
+ const layoutFor = (specifiers) => policy.typescriptInstallLayouts.find((layout) => {
1608
+ const compiler = specifiers.get(layout.compilerPackage);
1609
+ if (compiler?.size !== 1 || !compiler.has(layout.compilerSpecifier)) return false;
1610
+ if (layout.type === "split-compatibility") {
1611
+ const compatibility = specifiers.get(layout.compatibilityPackage);
1612
+ return compatibility?.size === 1 && compatibility.has(layout.compatibilitySpecifier);
1613
+ }
1614
+ return policy.typescriptInstallLayouts.every((other) => other.compilerPackage === layout.compilerPackage || !specifiers.has(other.compilerPackage));
1615
+ });
1616
+ const peerRange = (value) => typeof value === "string" && (0, semver.valid)(value) === null && (0, semver.validRange)(value) !== null;
1617
+ const toolchainEntries = (file, json) => {
1618
+ const entries = [];
1619
+ for (const section of [
1620
+ "dependencies",
1621
+ "devDependencies",
1622
+ "optionalDependencies",
1623
+ "peerDependencies"
1624
+ ]) {
1625
+ const dependencies = json[section];
1626
+ if (!record$3(dependencies)) continue;
1627
+ for (const [name, value] of Object.entries(dependencies)) {
1628
+ if (!tsSpecifiers.has(name)) continue;
1629
+ const resolved = resolve(file, name, value);
1630
+ if (section === "peerDependencies" && peerRange(resolved)) continue;
1631
+ entries.push({
1632
+ section,
1633
+ name,
1634
+ value: resolved
1635
+ });
1636
+ }
1637
+ }
1638
+ return entries;
1639
+ };
1640
+ const specifierMap = (entries) => {
1641
+ const specifiers = /* @__PURE__ */ new Map();
1642
+ for (const { name, value } of entries) {
1643
+ const values = specifiers.get(name) ?? /* @__PURE__ */ new Set();
1644
+ values.add(value);
1645
+ specifiers.set(name, values);
1646
+ }
1647
+ return specifiers;
1648
+ };
1649
+ const workspaceLayouts = /* @__PURE__ */ new Map();
1650
+ const workspaceLayoutFor = (file) => {
1651
+ const owner = workspaceOwnerFor(file);
1652
+ if (owner === void 0 || !workspaceContains({
1653
+ ...owner,
1654
+ file,
1655
+ rootMembership: "implicit"
1656
+ })) return void 0;
1657
+ const key = `${owner.source}:${owner.directory}`;
1658
+ const cached = workspaceLayouts.get(key);
1659
+ if (cached !== void 0) return cached;
1660
+ const entries = [];
1661
+ for (const [candidate, member] of manifests) {
1662
+ if (node_path.default.posix.basename(candidate) !== "package.json") continue;
1663
+ const memberOwner = workspaceOwnerFor(candidate);
1664
+ if (memberOwner?.directory !== owner.directory || memberOwner.source !== owner.source || !workspaceContains({
1665
+ ...owner,
1666
+ file: candidate,
1667
+ rootMembership: "implicit"
1668
+ })) continue;
1669
+ entries.push(...toolchainEntries(candidate, member).filter(({ section }) => section === "devDependencies"));
1670
+ }
1671
+ const result = {
1672
+ layout: layoutFor(specifierMap(entries)),
1673
+ directory: owner.directory
1674
+ };
1675
+ workspaceLayouts.set(key, result);
1676
+ return result;
1677
+ };
1678
+ for (const [file, json] of manifests) {
1679
+ const manager = json["packageManager"];
1680
+ if (manager !== void 0 && manager !== `bun@${policy.bun}`) add({
1681
+ file,
1682
+ rule: "bun-pins",
1683
+ key: "packageManager",
1684
+ value: manager,
1685
+ message: `packageManager Bun version must be ${policy.bun}, found ${JSON.stringify(manager)}`
1686
+ });
1687
+ const checkEntries = (entries, location) => {
1688
+ if (!record$3(entries)) return;
1689
+ for (const [name, raw] of Object.entries(entries)) {
1690
+ const value = resolve(file, name, raw);
1691
+ const tsAllowed = tsSpecifiers.get(name);
1692
+ if (tsAllowed !== void 0) {
1693
+ if (typeof value !== "string" || !tsAllowed.has(value)) add({
1694
+ file,
1695
+ rule: "typescript-layout",
1696
+ key: location?.key ?? name,
1697
+ value: location === void 0 ? raw : location.value,
1698
+ message: `${name} must use a declared TypeScript specifier, found ${String(value)}`
1699
+ });
1700
+ continue;
1701
+ }
1702
+ const pin = pins.get(name);
1703
+ if (pin === void 0) continue;
1704
+ if (value === pin) continue;
1705
+ const workspace = value === "workspace:*" ? workspaceResolution({
1706
+ file,
1707
+ name,
1708
+ pin
1709
+ }) : void 0;
1710
+ if (workspace === "matched") continue;
1711
+ add({
1712
+ file,
1713
+ rule: name === "bun-types" ? "bun-pins" : "package-pins",
1714
+ key: location?.key ?? name,
1715
+ value: location === void 0 ? raw : location.value,
1716
+ message: workspace === "nonmember" ? `${name} workspace:* consumer is not a member of its nearest workspace` : `${name} must be ${pin}, found ${String(value)}`
1717
+ });
1718
+ }
1719
+ };
1720
+ for (const key of [
1721
+ "dependencies",
1722
+ "devDependencies",
1723
+ "optionalDependencies"
1724
+ ]) checkEntries(json[key]);
1725
+ if (record$3(json["peerDependencies"])) {
1726
+ for (const [name, value] of Object.entries(json["peerDependencies"])) if (tsSpecifiers.has(name) && !peerRange(resolve(file, name, value))) checkEntries({ [name]: value });
1727
+ }
1728
+ for (const source of catalogSources(json)) {
1729
+ checkEntries(source["catalog"]);
1730
+ if (!record$3(source["catalogs"])) continue;
1731
+ for (const catalog of Object.values(source["catalogs"])) checkEntries(catalog);
1732
+ }
1733
+ const ownedNames = /* @__PURE__ */ new Set([...pins.keys(), ...tsSpecifiers.keys()]);
1734
+ const resolutionDependencies = {};
1735
+ const resolutionRoot = manifests.get(node_path.default.posix.join(node_path.default.posix.dirname(file), "package.json"));
1736
+ if (resolutionRoot !== void 0) for (const section of [
1737
+ "dependencies",
1738
+ "devDependencies",
1739
+ "optionalDependencies"
1740
+ ]) {
1741
+ const entries = resolutionRoot[section];
1742
+ if (!record$3(entries)) continue;
1743
+ for (const [name, value] of Object.entries(entries)) resolutionDependencies[name] = resolve(file, name, value);
1744
+ }
1745
+ const affectedSpecifiers = /* @__PURE__ */ new Map();
1746
+ const owner = workspaceOwnerFor(file);
1747
+ for (const [candidate, member] of manifests) {
1748
+ if (node_path.default.posix.basename(candidate) !== "package.json") continue;
1749
+ const memberOwner = workspaceOwnerFor(candidate);
1750
+ if (!(candidate === node_path.default.posix.join(node_path.default.posix.dirname(file), "package.json")) && !(owner !== void 0 && owner.directory === node_path.default.posix.dirname(file) && memberOwner?.directory === owner.directory && memberOwner.source === owner.source && workspaceContains({
1751
+ directory: owner.directory,
1752
+ file: candidate,
1753
+ patterns: owner.patterns,
1754
+ rootMembership: "implicit"
1755
+ }))) continue;
1756
+ for (const section of [
1757
+ "dependencies",
1758
+ "devDependencies",
1759
+ "optionalDependencies"
1760
+ ]) {
1761
+ const entries = member[section];
1762
+ if (!record$3(entries)) continue;
1763
+ for (const [name, value] of Object.entries(entries)) {
1764
+ if (!tsSpecifiers.has(name)) continue;
1765
+ const values = affectedSpecifiers.get(name) ?? /* @__PURE__ */ new Set();
1766
+ values.add(resolve(candidate, name, value));
1767
+ affectedSpecifiers.set(name, values);
1768
+ }
1769
+ }
1770
+ }
1771
+ const checkResolutionMap = (entries, parent) => {
1772
+ if (!record$3(entries)) return;
1773
+ for (const [selector, replacement] of Object.entries(entries)) {
1774
+ const target = selector === "." ? parent : selector;
1775
+ if (target === void 0) continue;
1776
+ let pattern = target.split(/>\s*(?=[@A-Za-z_*]|$)/).at(-1)?.trim() ?? "";
1777
+ const version = pattern.lastIndexOf("@");
1778
+ let qualifier;
1779
+ if (version > pattern.lastIndexOf("/")) {
1780
+ qualifier = pattern.slice(version + 1).replace(/^npm:/, "");
1781
+ pattern = pattern.slice(0, version);
1782
+ }
1783
+ const parts = pattern.split("/");
1784
+ pattern = parts.at(-2)?.startsWith("@") ? parts.slice(-2).join("/") : parts.at(-1) ?? "";
1785
+ if (pattern === "") {
1786
+ add({
1787
+ file,
1788
+ rule: "package-pins",
1789
+ key: selector,
1790
+ value: replacement,
1791
+ message: "resolution selector must name a package"
1792
+ });
1793
+ continue;
1794
+ }
1795
+ if (record$3(replacement)) {
1796
+ checkResolutionMap(replacement, target);
1797
+ continue;
1798
+ }
1799
+ for (const name of ownedNames) {
1800
+ if (!(0, picomatch.default)(pattern)(name)) continue;
1801
+ let value = replacement;
1802
+ if (typeof replacement === "string" && replacement.startsWith("$")) {
1803
+ const reference = replacement.slice(1);
1804
+ value = resolutionDependencies[reference];
1805
+ }
1806
+ const resolved = resolve(file, name, value);
1807
+ checkEntries({ [name]: value }, {
1808
+ key: selector,
1809
+ value: replacement
1810
+ });
1811
+ if (tsSpecifiers.has(name) && [...affectedSpecifiers.get(name) ?? []].some((specifier) => {
1812
+ if (resolved === specifier) return false;
1813
+ if (qualifier === void 0 || (0, semver.validRange)(qualifier) === null) return true;
1814
+ if (typeof specifier !== "string") return false;
1815
+ const release = (0, semver.valid)(specifier.startsWith("npm:") ? specifier.slice(specifier.lastIndexOf("@") + 1) : specifier);
1816
+ return release !== null && (0, semver.satisfies)(release, qualifier);
1817
+ }) && typeof resolved === "string" && tsSpecifiers.get(name)?.has(resolved)) add({
1818
+ file,
1819
+ rule: "typescript-layout",
1820
+ key: selector,
1821
+ value: replacement,
1822
+ message: `${name} resolution must preserve its declared TypeScript install specifier`
1823
+ });
1824
+ }
1825
+ }
1826
+ };
1827
+ checkResolutionMap(json["overrides"]);
1828
+ checkResolutionMap(json["resolutions"]);
1829
+ if (record$3(json["pnpm"])) checkResolutionMap(json["pnpm"]["overrides"]);
1830
+ const localEntries = toolchainEntries(file, json);
1831
+ const usesCompiler = policy.typescriptInstallLayouts.some((layout) => localEntries.some(({ name }) => name === layout.compilerPackage));
1832
+ let selectedLayout = layoutFor(specifierMap(localEntries));
1833
+ if (usesCompiler) {
1834
+ if (layoutFor(specifierMap(localEntries.filter(({ section }) => section !== "peerDependencies"))) === void 0) selectedLayout = void 0;
1835
+ if (selectedLayout === void 0) {
1836
+ const workspace = workspaceLayoutFor(file);
1837
+ const layout = workspace?.layout;
1838
+ if (workspace !== void 0 && layout !== void 0) {
1839
+ const expected = /* @__PURE__ */ new Map([[layout.compilerPackage, layout.compilerSpecifier]]);
1840
+ if (layout.type === "split-compatibility") expected.set(layout.compatibilityPackage, layout.compatibilitySpecifier);
1841
+ expected.set(policy.typescript6Compatibility.packageAlias, `npm:typescript@${policy.typescript6Compatibility.version}`);
1842
+ const developmentOnly = localEntries.every(({ section, name, value }) => section === "devDependencies" && expected.get(name) === value);
1843
+ const runtimeCompatibilityOnly = layout.type === "split-compatibility" && node_path.default.posix.dirname(file) !== workspace.directory && localEntries.every(({ section, name, value }) => (section === "dependencies" || section === "devDependencies" || section === "peerDependencies") && name === layout.compatibilityPackage && value === layout.compatibilitySpecifier);
1844
+ if (developmentOnly || runtimeCompatibilityOnly) selectedLayout = layout;
1845
+ }
1846
+ }
1847
+ if (selectedLayout === void 0) add({
1848
+ file,
1849
+ rule: "typescript-layout",
1850
+ key: "dependencies",
1851
+ message: "TypeScript compiler and compatibility packages must match one complete declared install layout"
1852
+ });
1853
+ const command = record$3(json["scripts"]) ? json["scripts"]["typecheck"] : void 0;
1854
+ if (selectedLayout !== void 0 && typeof command === "string") {
1855
+ const normalizedExpected = selectedLayout.typecheckCommand.replace(/\s+/g, " ").trim();
1856
+ for (const words of compilerCommandSegments(command)) {
1857
+ if (!invokesCompiler(words)) continue;
1858
+ const normalized = words.join(" ");
1859
+ if (!words.some((word) => word === "(" || word === ")") && shellSubstitutions(normalized).length === 0 && (normalized === normalizedExpected || normalized.startsWith(`${normalizedExpected} `))) continue;
1860
+ add({
1861
+ file,
1862
+ rule: "typescript-layout",
1863
+ key: "typecheck",
1864
+ value: command,
1865
+ message: `typecheck compiler invocation must use ${selectedLayout.typecheckCommand}`
1866
+ });
1867
+ break;
1868
+ }
1869
+ }
1870
+ }
1871
+ if (record$3(json["peerDependencies"])) {
1872
+ const peerLayout = selectedLayout ?? workspaceLayoutFor(file)?.layout;
1873
+ for (const [name, raw] of Object.entries(json["peerDependencies"])) {
1874
+ if (!tsSpecifiers.has(name)) continue;
1875
+ const range = resolve(file, name, raw);
1876
+ if (!peerRange(range)) continue;
1877
+ const releases = /* @__PURE__ */ new Set();
1878
+ for (const layout of policy.typescriptInstallLayouts) {
1879
+ if (layout.compilerPackage !== name && !(layout.type === "split-compatibility" && layout.compatibilityPackage === name)) continue;
1880
+ const specifier = layout.compilerSpecifier;
1881
+ releases.add(specifier.startsWith("npm:") ? specifier.slice(specifier.lastIndexOf("@") + 1) : specifier);
1882
+ }
1883
+ if (name === policy.typescript6Compatibility.packageAlias) releases.add(policy.typescript6Compatibility.version);
1884
+ if (peerLayout?.type === "split-compatibility" && name === peerLayout.compatibilityPackage) releases.add(peerLayout.compatibilitySpecifier);
1885
+ if ([...releases].every((release) => (0, semver.satisfies)(release, range))) continue;
1886
+ add({
1887
+ file,
1888
+ rule: "typescript-layout",
1889
+ key: name,
1890
+ value: raw,
1891
+ message: `${name} peer support range must include ${[...releases].join(" and ")}, found ${range}`
1892
+ });
1893
+ }
1894
+ }
1895
+ if (record$3(json["engines"]) && json["engines"]["node"] !== void 0 && (typeof json["engines"]["node"] !== "string" || !nodeSupportRangeMatches(policy.node, json["engines"]["node"]))) add({
1896
+ file,
1897
+ rule: "node-engine",
1898
+ key: "node",
1899
+ value: json["engines"]["node"],
1900
+ message: `engines.node must support ${policy.node}, found ${JSON.stringify(json["engines"]["node"])}`
1901
+ });
1902
+ }
1903
+ return diagnostics;
1904
+ };
1905
+ //#endregion
1906
+ //#region src/toolchain-runtime.ts
1907
+ const runtimeRules = [
1908
+ "bun-pins",
1909
+ "node-version",
1910
+ "python-version",
1911
+ "rust-version",
1912
+ "runtime-manager",
1913
+ "runtime-docker",
1914
+ "runtime-workflow",
1915
+ "action-pins"
1916
+ ];
1917
+ const record$2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1918
+ const pythonSelectorMatches = (value, expected) => value === expected || typeof value === "string" && /^\d+\.\d+$/.test(expected) && value.startsWith(`${expected}.`) && /^\d+\.\d+\.\d+$/.test(value);
1919
+ const compareRelease = (left, right) => {
1920
+ for (let index = 0; index < Math.max(left.length, right.length); index++) {
1921
+ const difference = (left.at(index) ?? 0) - (right.at(index) ?? 0);
1922
+ if (difference !== 0) return Math.sign(difference);
1923
+ }
1924
+ return 0;
1925
+ };
1926
+ const pythonSeriesRequirementMatches = ({ current, operator, target, wildcard }) => {
1927
+ const prefixCovers = (prefix) => prefix.length <= 2 && prefix.every((part, index) => current.at(index) === part);
1928
+ const prefixOverlaps = target.slice(0, 2).every((part, index) => current.at(index) === part) && target.slice(3).every((part) => part === 0);
1929
+ if (wildcard) {
1930
+ if (operator === "==") return prefixCovers(target);
1931
+ if (operator === "!=") return !prefixOverlaps;
1932
+ return false;
1933
+ }
1934
+ const minimumComparison = compareRelease(current, target);
1935
+ const seriesComparison = compareRelease(current.slice(0, 2), target.slice(0, 2));
1936
+ switch (operator) {
1937
+ case "==": return false;
1938
+ case "!=": return !(seriesComparison === 0 && target.slice(3).every((part) => part === 0));
1939
+ case ">=": return minimumComparison >= 0;
1940
+ case ">": return minimumComparison > 0;
1941
+ case "<=":
1942
+ case "<": return seriesComparison < 0;
1943
+ case "~=": return target.length >= 2 && minimumComparison >= 0 && prefixCovers(target.slice(0, -1));
1944
+ default: return false;
1945
+ }
1946
+ };
1947
+ /** Evaluate final-release Python constraints against the complete selected version set. */
1948
+ const pythonRequirementMatches = (requirement, version) => {
1949
+ if (typeof requirement !== "string" || requirement.trim() === "") return false;
1950
+ const current = version.split(".").map(Number);
1951
+ return requirement.split(",").every((clause) => {
1952
+ const match = /^(~=|==|!=|<=|>=|<|>)\s*(\d+(?:\.\d+)*)(\.\*)?$/.exec(clause.trim());
1953
+ if (match === null) return false;
1954
+ const operator = match[1];
1955
+ const release = match[2];
1956
+ if (release === void 0 || operator === void 0) return false;
1957
+ const target = release.split(".").map(Number);
1958
+ if (current.length === 2) return pythonSeriesRequirementMatches({
1959
+ current,
1960
+ operator,
1961
+ target,
1962
+ wildcard: match[3] !== void 0
1963
+ });
1964
+ const comparison = compareRelease(current, target);
1965
+ if (match[3] !== void 0) {
1966
+ if (operator !== "==" && operator !== "!=") return false;
1967
+ const prefix = target.every((part, index) => (current.at(index) ?? 0) === part);
1968
+ return operator === "==" ? prefix : !prefix;
1969
+ }
1970
+ switch (operator) {
1971
+ case "==": return comparison === 0;
1972
+ case "!=": return comparison !== 0;
1973
+ case "<=": return comparison <= 0;
1974
+ case ">=": return comparison >= 0;
1975
+ case "<": return comparison < 0;
1976
+ case ">": return comparison > 0;
1977
+ case "~=": {
1978
+ if (target.length < 2) return false;
1979
+ const prefix = target.slice(0, -1);
1980
+ return comparison >= 0 && prefix.every((part, index) => (current.at(index) ?? 0) === part);
1981
+ }
1982
+ default: return false;
1983
+ }
1984
+ });
1985
+ };
1986
+ /** Check runtime declarations only in the files that declare or configure them. */
1987
+ const checkRuntimeFile = ({ file, text, policy, trackedFiles, readFile, repository, onDelegated, engineFloors = [], onEngineFloor }) => {
1988
+ const diagnostics = [];
1989
+ const name = node_path.default.posix.basename(file);
1990
+ const lines = text.split(/\r?\n/);
1991
+ const add = ({ rule, line, message }) => {
1992
+ diagnostics.push({
1993
+ rule,
1994
+ path: file,
1995
+ line,
1996
+ message
1997
+ });
1998
+ };
1999
+ const lineOf = (key) => Math.max(1, lines.findIndex((line) => line.includes(key)) + 1);
2000
+ const pin = ({ rule, value, expected, label, line = 1, selector }) => {
2001
+ let matches = value === expected;
2002
+ if (selector === "node") matches = nodeSelectorMatches(value, expected);
2003
+ else if (label.includes("python")) matches = pythonSelectorMatches(value, expected);
2004
+ if (!matches) add({
2005
+ rule,
2006
+ line,
2007
+ message: `${label} must be ${expected}, found ${String(value)}`
2008
+ });
2009
+ };
2010
+ const toml = (rule) => {
2011
+ try {
2012
+ return (0, smol_toml.parse)(text);
2013
+ } catch {
2014
+ add({
2015
+ rule,
2016
+ line: 1,
2017
+ message: "invalid TOML"
2018
+ });
2019
+ return;
2020
+ }
2021
+ };
2022
+ const versions = {
2023
+ ...policy.packages,
2024
+ ...Object.fromEntries(Object.entries(policy.packages).map(([tool, version]) => [`npm:${tool}`, version])),
2025
+ bun: policy.bun,
2026
+ node: policy.node,
2027
+ nodejs: policy.node,
2028
+ python: policy.python,
2029
+ rust: policy.rust,
2030
+ "core:node": policy.node,
2031
+ "core:python": policy.python,
2032
+ "core:rust": policy.rust,
2033
+ "core:bun": policy.bun
2034
+ };
2035
+ const nodeTools = /* @__PURE__ */ new Set([
2036
+ "node",
2037
+ "nodejs",
2038
+ "core:node"
2039
+ ]);
2040
+ if (name === ".bun-version") pin({
2041
+ rule: "bun-pins",
2042
+ value: text.trim(),
2043
+ expected: policy.bun,
2044
+ label: name
2045
+ });
2046
+ if (name === ".node-version" || name === ".nvmrc") pin({
2047
+ rule: "node-version",
2048
+ selector: "node",
2049
+ value: text.trim(),
2050
+ expected: policy.node,
2051
+ label: name
2052
+ });
2053
+ if (name === ".python-version") pin({
2054
+ rule: "python-version",
2055
+ value: text.trim(),
2056
+ expected: policy.python,
2057
+ label: name
2058
+ });
2059
+ const firstContent = lines.find((line) => line.trim() !== "" && !line.trimStart().startsWith("#"));
2060
+ const rustToml = name === "rust-toolchain.toml" || name === "rust-toolchain" && firstContent?.trimStart().startsWith("[");
2061
+ if (name === "rust-toolchain" && !rustToml) pin({
2062
+ rule: "rust-version",
2063
+ value: text.trim(),
2064
+ expected: policy.rust,
2065
+ label: name
2066
+ });
2067
+ if (rustToml) {
2068
+ const parsed = toml("rust-version");
2069
+ if (parsed !== void 0) {
2070
+ const toolchain = parsed["toolchain"];
2071
+ const components = record$2(toolchain) ? toolchain["components"] : void 0;
2072
+ const expected = Array.isArray(components) && components.includes("rustc-dev") ? policy.rustCompilerDevelopment : policy.rust;
2073
+ pin({
2074
+ rule: "rust-version",
2075
+ value: record$2(toolchain) ? toolchain["channel"] : void 0,
2076
+ expected,
2077
+ label: "Rust channel",
2078
+ line: lineOf("channel")
2079
+ });
2080
+ }
2081
+ }
2082
+ if (name === "Cargo.toml") {
2083
+ const parsed = toml("rust-version");
2084
+ const rustFloor = (value) => {
2085
+ const parts = typeof value === "string" && /^(?:0|[1-9]\d*)(?:\.(?:0|[1-9]\d*)){0,2}$/.test(value) ? value.split(".").map(Number) : void 0;
2086
+ if (parts === void 0 || !parts.every(Number.isSafeInteger) || compareRelease(parts, policy.rust.split(".").map(Number)) > 0) add({
2087
+ rule: "rust-version",
2088
+ line: lineOf("rust-version"),
2089
+ message: `Cargo rust-version must be a bare support floor at or below Rust ${policy.rust}`
2090
+ });
2091
+ };
2092
+ const readManifest = (candidate) => {
2093
+ if (candidate === file) return parsed;
2094
+ if (!trackedFiles.has(candidate)) return void 0;
2095
+ try {
2096
+ return (0, smol_toml.parse)(readFile(candidate) ?? "");
2097
+ } catch {
2098
+ return;
2099
+ }
2100
+ };
2101
+ if (parsed !== void 0) {
2102
+ const workspace = parsed["workspace"];
2103
+ const defaults = record$2(workspace) ? workspace["package"] : void 0;
2104
+ if (record$2(defaults) && defaults["rust-version"] !== void 0) rustFloor(defaults["rust-version"]);
2105
+ const pkg = parsed["package"];
2106
+ const version = record$2(pkg) ? pkg["rust-version"] : void 0;
2107
+ if (version !== void 0) if (!record$2(version)) rustFloor(version);
2108
+ else {
2109
+ let inherited;
2110
+ if (version["workspace"] === true && record$2(pkg)) {
2111
+ const explicit = pkg["workspace"];
2112
+ let directory = node_path.default.posix.dirname(file);
2113
+ const explicitPath = typeof explicit === "string" && !explicit.includes("\\") && !explicit.includes(":") && !explicit.includes("${{") && !node_path.default.posix.isAbsolute(explicit) ? node_path.default.posix.normalize(node_path.default.posix.join(directory, explicit)) : void 0;
2114
+ if (explicit === void 0 || explicitPath !== void 0 && explicitPath !== ".." && !explicitPath.startsWith("../")) {
2115
+ if (explicitPath !== void 0) directory = explicitPath;
2116
+ while (true) {
2117
+ const table = readManifest(node_path.default.posix.join(directory, "Cargo.toml"))?.["workspace"];
2118
+ if (record$2(table)) {
2119
+ const fields = table["package"];
2120
+ inherited = record$2(fields) ? fields["rust-version"] : void 0;
2121
+ break;
2122
+ }
2123
+ if (explicit !== void 0 || directory === ".") break;
2124
+ directory = node_path.default.posix.dirname(directory);
2125
+ }
2126
+ }
2127
+ }
2128
+ rustFloor(inherited);
2129
+ }
2130
+ }
2131
+ }
2132
+ if (name === "Pipfile") {
2133
+ const requires = toml("python-version")?.["requires"];
2134
+ if (record$2(requires)) {
2135
+ const minor = requires["python_version"];
2136
+ if (minor !== void 0 && minor !== policy.python.split(".").slice(0, 2).join(".")) add({
2137
+ rule: "python-version",
2138
+ line: lineOf("python_version"),
2139
+ message: `Pipfile python_version must select Python ${policy.python}`
2140
+ });
2141
+ const full = requires["python_full_version"];
2142
+ if (full !== void 0 && !(typeof full === "string" && /^\d+\.\d+\.\d+$/.test(full) && pythonSelectorMatches(full, policy.python))) add({
2143
+ rule: "python-version",
2144
+ line: lineOf("python_full_version"),
2145
+ message: `Pipfile python_full_version must select Python ${policy.python}`
2146
+ });
2147
+ }
2148
+ }
2149
+ if (name === "pyproject.toml" || name === "uv.toml") {
2150
+ const parsed = toml("python-version");
2151
+ if (parsed !== void 0) {
2152
+ const project = parsed["project"];
2153
+ if (record$2(project) && project["requires-python"] !== void 0) {
2154
+ if (!pythonRequirementMatches(project["requires-python"], policy.python)) add({
2155
+ rule: "python-version",
2156
+ line: lineOf("requires-python"),
2157
+ message: `requires-python must include Python ${policy.python}; unsupported constraints must use final-release version specifiers`
2158
+ });
2159
+ }
2160
+ const tool = parsed["tool"];
2161
+ const configuredUv = record$2(tool) ? tool["uv"] : void 0;
2162
+ const uv = name === "uv.toml" ? parsed : configuredUv;
2163
+ if (record$2(uv) && uv["python"] !== void 0) pin({
2164
+ rule: "python-version",
2165
+ value: uv["python"],
2166
+ expected: policy.python,
2167
+ label: "uv python",
2168
+ line: lineOf("python")
2169
+ });
2170
+ }
2171
+ }
2172
+ if (isMiseConfigPath(file)) {
2173
+ const tools = toml("runtime-manager")?.["tools"];
2174
+ if (record$2(tools)) for (const [tool, expected] of Object.entries(versions)) {
2175
+ const configured = tools[tool];
2176
+ if (configured !== void 0) pin({
2177
+ rule: "runtime-manager",
2178
+ value: record$2(configured) ? configured["version"] : configured,
2179
+ expected,
2180
+ selector: nodeTools.has(tool) ? "node" : void 0,
2181
+ label: `mise ${tool}`,
2182
+ line: lineOf(tool)
2183
+ });
2184
+ }
2185
+ }
2186
+ if (name === ".tool-versions") lines.forEach((line, index) => {
2187
+ const fields = line.replace(/#.*$/, "").trim().split(/\s+/);
2188
+ const tool = fields.at(0);
2189
+ if (tool === void 0 || !(tool in versions)) return;
2190
+ const expected = Object.entries(versions).find(([key]) => key === tool)?.[1];
2191
+ if (expected !== void 0) pin({
2192
+ rule: "runtime-manager",
2193
+ value: fields.slice(1).join(" "),
2194
+ expected,
2195
+ selector: nodeTools.has(tool) ? "node" : void 0,
2196
+ label: `.tool-versions ${tool}`,
2197
+ line: index + 1
2198
+ });
2199
+ });
2200
+ const checkRuntimeImage = ({ image, line, label }) => {
2201
+ if (typeof image !== "string" || image.includes("$")) {
2202
+ add({
2203
+ rule: "runtime-docker",
2204
+ line,
2205
+ message: `cannot determine ${label} runtime; use a static image or a reasoned runtime-docker opt-out`
2206
+ });
2207
+ return;
2208
+ }
2209
+ const runtime = /^(node|python|oven\/bun)(?::([^@]+))?(?:@.*)?$/i.exec(canonicalDockerRuntime(image));
2210
+ if (runtime === null) return;
2211
+ const tool = runtime[1]?.toLowerCase();
2212
+ if (image.includes("@")) {
2213
+ add({
2214
+ rule: tool === "oven/bun" ? "bun-pins" : "runtime-docker",
2215
+ line,
2216
+ message: `${label} ${tool} digest requires an approved digest policy; use a tag-only runtime image`
2217
+ });
2218
+ return;
2219
+ }
2220
+ const tag = runtime[2];
2221
+ const variantSuffix = tool === "oven/bun" ? /-(?:alpine|slim|debian)$/ : /-(?:alpine(?:\d+(?:\.\d+)*)?|(?:bookworm|bullseye|trixie|buster)(?:-slim)?|slim)$/;
2222
+ const version = tag?.replace(variantSuffix, "");
2223
+ let expected = policy.bun;
2224
+ if (tool === "node") expected = policy.node;
2225
+ else if (tool === "python") expected = policy.python;
2226
+ pin({
2227
+ rule: tool === "oven/bun" ? "bun-pins" : "runtime-docker",
2228
+ value: version,
2229
+ expected,
2230
+ selector: tool === "node" ? "node" : void 0,
2231
+ label: `${label} ${tool}`,
2232
+ line
2233
+ });
2234
+ };
2235
+ if (isDockerDefinitionPath(file)) {
2236
+ const variables = /* @__PURE__ */ new Map();
2237
+ const escape = /^\s*#\s*escape\s*=\s*([\\`])\s*$/m.exec(text)?.[1] ?? "\\";
2238
+ const continuation = new RegExp(`${escape === "`" ? "`" : "\\\\"}\\s*$`);
2239
+ const stages = /* @__PURE__ */ new Set();
2240
+ let argumentScope = "global";
2241
+ const heredocs = [];
2242
+ let instruction = "";
2243
+ let startLine = 1;
2244
+ const expand = (value) => {
2245
+ for (let count = 0; count <= variables.size; count++) {
2246
+ const next = value.replace(/\$(?:\{([A-Za-z_][A-Za-z_\d]*)\}|([A-Za-z_][A-Za-z_\d]*))/g, (reference, braced, plain) => variables.get(braced ?? plain ?? "") ?? reference);
2247
+ if (next === value) return next;
2248
+ value = next;
2249
+ }
2250
+ return value;
2251
+ };
2252
+ const collectHeredocs = (content, line) => {
2253
+ let quote;
2254
+ for (let index = 0; index < content.length; index++) {
2255
+ const character = content.at(index);
2256
+ if (quote !== void 0) {
2257
+ if (character === quote) quote = void 0;
2258
+ else if (quote === "\"" && character === "\\") index++;
2259
+ continue;
2260
+ }
2261
+ if (character === "\\") {
2262
+ index++;
2263
+ continue;
2264
+ }
2265
+ if (character === "'" || character === "\"") {
2266
+ quote = character;
2267
+ continue;
2268
+ }
2269
+ if (character === "#" && (index === 0 || /[\s;&|()]/.test(content.at(index - 1) ?? ""))) break;
2270
+ if (character !== "<" || content.at(index + 1) !== "<") continue;
2271
+ if (content.at(index + 2) === "<") {
2272
+ index += 2;
2273
+ continue;
2274
+ }
2275
+ index += 2;
2276
+ const stripTabs = content.at(index) === "-";
2277
+ if (stripTabs) index++;
2278
+ while (/\s/.test(content.at(index) ?? "")) index++;
2279
+ if (content.at(index) === "#") {
2280
+ add({
2281
+ rule: "runtime-docker",
2282
+ line,
2283
+ message: "invalid Docker heredoc delimiter"
2284
+ });
2285
+ break;
2286
+ }
2287
+ let delimiter = "";
2288
+ let delimiterQuote;
2289
+ for (; index < content.length; index++) {
2290
+ const part = content.at(index);
2291
+ if (delimiterQuote !== void 0) {
2292
+ if (part === delimiterQuote) delimiterQuote = void 0;
2293
+ else if (delimiterQuote === "\"" && part === "\\" && /[$"\\]/.test(content.at(index + 1) ?? "")) delimiter += content.at(++index);
2294
+ else delimiter += part;
2295
+ continue;
2296
+ }
2297
+ if (part === "'" || part === "\"") {
2298
+ delimiterQuote = part;
2299
+ continue;
2300
+ }
2301
+ if (part === "\\" && content.at(index + 1) !== void 0) {
2302
+ delimiter += content.at(++index);
2303
+ continue;
2304
+ }
2305
+ if (/[\s;&|<>()]/.test(part ?? "")) break;
2306
+ delimiter += part;
2307
+ }
2308
+ if (delimiter !== "" && delimiterQuote === void 0) heredocs.push({
2309
+ delimiter,
2310
+ stripTabs,
2311
+ line
2312
+ });
2313
+ else add({
2314
+ rule: "runtime-docker",
2315
+ line,
2316
+ message: "invalid Docker heredoc delimiter"
2317
+ });
2318
+ index--;
2319
+ }
2320
+ };
2321
+ const checkInstruction = (content, line) => {
2322
+ const argument = /^\s*ARG\s+([A-Za-z_][A-Za-z_\d]*)(?:=(.*))?$/i.exec(content);
2323
+ if (argument !== null) {
2324
+ if (argumentScope === "stage") return;
2325
+ const key = argument[1];
2326
+ const value = argument[2];
2327
+ if (key !== void 0 && value !== void 0) variables.set(key, expand(value.replace(/^(["'])(.*)\1$/, "$2")));
2328
+ return;
2329
+ }
2330
+ if (/^\s*(?:RUN|COPY)\s+/i.test(content)) {
2331
+ collectHeredocs(content, line);
2332
+ return;
2333
+ }
2334
+ const from = /^\s*FROM\s+(?:--platform=\S+\s+)?(\S+)(?:\s+AS\s+(\S+))?/i.exec(content);
2335
+ if (from === null || from[1] === void 0) return;
2336
+ argumentScope = "stage";
2337
+ const image = expand(from[1]);
2338
+ if (image.includes("$")) {
2339
+ add({
2340
+ rule: "runtime-docker",
2341
+ line,
2342
+ message: "cannot determine FROM runtime; declare an image ARG default or a reasoned runtime-docker opt-out"
2343
+ });
2344
+ return;
2345
+ }
2346
+ const stage = from[2]?.toLowerCase();
2347
+ const previousStage = stages.has(image.toLowerCase());
2348
+ if (stage !== void 0) stages.add(stage);
2349
+ if (previousStage) return;
2350
+ checkRuntimeImage({
2351
+ image,
2352
+ line,
2353
+ label: "FROM"
2354
+ });
2355
+ };
2356
+ lines.forEach((line, index) => {
2357
+ const heredoc = heredocs.at(0);
2358
+ if (heredoc !== void 0) {
2359
+ if ((heredoc.stripTabs ? line.replace(/^\t+/, "") : line) === heredoc.delimiter) heredocs.shift();
2360
+ return;
2361
+ }
2362
+ if (line.trimStart().startsWith("#")) return;
2363
+ if (instruction === "") startLine = index + 1;
2364
+ instruction += line.replace(continuation, " ");
2365
+ if (continuation.test(line)) return;
2366
+ checkInstruction(instruction, startLine);
2367
+ instruction = "";
2368
+ });
2369
+ if (instruction !== "") checkInstruction(instruction, startLine);
2370
+ for (const heredoc of heredocs) add({
2371
+ rule: "runtime-docker",
2372
+ line: heredoc.line,
2373
+ message: `unterminated Docker heredoc ${heredoc.delimiter}`
2374
+ });
2375
+ }
2376
+ if (isComposeDefinitionPath(file) || isKubernetesDefinitionPath(file)) {
2377
+ const lineCounter = new yaml.LineCounter();
2378
+ for (const containerDocument of (0, yaml.parseAllDocuments)(text, {
2379
+ lineCounter,
2380
+ merge: true,
2381
+ uniqueKeys: true
2382
+ })) {
2383
+ const contents = containerDocument.contents;
2384
+ const declaredResource = (0, yaml.isMap)(contents) && (0, yaml.isScalar)(contents.get("apiVersion", true)) && (0, yaml.isScalar)(contents.get("kind", true));
2385
+ const recognizedContainer = isComposeDefinitionPath(file) || declaredResource;
2386
+ if (containerDocument.errors.length > 0) {
2387
+ if (recognizedContainer) add({
2388
+ rule: "runtime-docker",
2389
+ line: 1,
2390
+ message: "invalid container YAML"
2391
+ });
2392
+ continue;
2393
+ }
2394
+ try {
2395
+ const classified = containerDocumentImages(containerDocument.toJS({ maxAliasCount: 100 }), file);
2396
+ for (const entry of classified?.images ?? []) {
2397
+ const node = containerDocument.getIn(entry.path, true);
2398
+ const line = ((0, yaml.isMap)(node) || (0, yaml.isScalar)(node) || (0, yaml.isSeq)(node) || (0, yaml.isAlias)(node)) && node.range !== void 0 && node.range !== null ? lineCounter.linePos(node.range[0]).line : 1;
2399
+ checkRuntimeImage({
2400
+ image: entry.image,
2401
+ line,
2402
+ label: classified?.ecosystem === "docker-compose" ? "Compose image" : "Kubernetes image"
2403
+ });
2404
+ }
2405
+ } catch {
2406
+ if (recognizedContainer) add({
2407
+ rule: "runtime-docker",
2408
+ line: 1,
2409
+ message: "invalid container YAML aliases"
2410
+ });
2411
+ }
2412
+ }
2413
+ }
2414
+ const automationKind = githubAutomationFileKind(file);
2415
+ if (automationKind === void 0) return diagnostics;
2416
+ const document = (0, yaml.parseDocument)(text, {
2417
+ uniqueKeys: true,
2418
+ merge: true
2419
+ });
2420
+ if (document.errors.length > 0) {
2421
+ add({
2422
+ rule: "runtime-workflow",
2423
+ line: 1,
2424
+ message: "invalid workflow YAML"
2425
+ });
2426
+ return diagnostics;
2427
+ }
2428
+ const nodeLine = (node) => {
2429
+ if (!record$2(node) || !Array.isArray(node["range"])) return 1;
2430
+ const offset = node["range"].at(0);
2431
+ return typeof offset === "number" ? text.slice(0, offset).split("\n").length : 1;
2432
+ };
2433
+ let checkoutBindings = [];
2434
+ let checkoutDestinations = /* @__PURE__ */ new Map();
2435
+ let unknownCheckoutDestination = false;
2436
+ const staticRepositoryPath = (value) => typeof value === "string" && value !== "" && !value.includes("${{") && !value.includes("\\") && !value.includes(":") && !node_path.default.posix.isAbsolute(value) && !value.split("/").includes("..");
2437
+ const normalizeCheckoutPath = (prefix) => node_path.default.posix.normalize(prefix).replace(/\/$/, "") || ".";
2438
+ const checkReference = ({ value, tool, line }) => {
2439
+ const allowed = {
2440
+ node: [".node-version", ".nvmrc"],
2441
+ python: [".python-version"],
2442
+ bun: ["package.json"]
2443
+ }[tool];
2444
+ const rule = tool === "bun" ? "bun-pins" : "runtime-workflow";
2445
+ const selector = staticRepositoryPath(value) ? node_path.default.posix.normalize(value) : void 0;
2446
+ const binding = selector === void 0 ? void 0 : checkoutBindings.findLast((entry) => entry.path === "." || selector === entry.path || selector.startsWith(`${entry.path}/`));
2447
+ if (selector === void 0) {
2448
+ add({
2449
+ rule,
2450
+ line,
2451
+ message: `setup-${tool} must reference a tracked ${allowed.join(" or ")}`
2452
+ });
2453
+ return;
2454
+ }
2455
+ if (unknownCheckoutDestination || [...checkoutDestinations].some(([prefix, count]) => count > 1 && (prefix === "." || selector === prefix || selector.startsWith(`${prefix}/`)))) {
2456
+ add({
2457
+ rule,
2458
+ line,
2459
+ message: `setup-${tool} version-file selector has untrusted checkout provenance: checkout destinations must be static and have exactly one writer`
2460
+ });
2461
+ return;
2462
+ }
2463
+ if (binding?.source === "untrusted") {
2464
+ add({
2465
+ rule,
2466
+ line: binding.line,
2467
+ message: `setup-${tool} version-file selector cannot use this checkout: ${binding.reason}`
2468
+ });
2469
+ return;
2470
+ }
2471
+ const target = binding === void 0 || binding.path === "." ? selector : node_path.default.posix.relative(binding.path, selector);
2472
+ if (!allowed.includes(node_path.default.posix.basename(target)) || binding?.source !== "delegated" && !trackedFiles.has(target)) {
2473
+ add({
2474
+ rule,
2475
+ line,
2476
+ message: `setup-${tool} must reference a tracked ${allowed.join(" or ")}`
2477
+ });
2478
+ return;
2479
+ }
2480
+ if (binding !== void 0 && (binding.sparse.mode === "invalid" || binding.sparse.mode === "files" && !binding.sparse.paths.has(target))) {
2481
+ add({
2482
+ rule,
2483
+ line,
2484
+ message: `checkout sparse-checkout must explicitly list ${target} without dynamic, glob, or negation patterns`
2485
+ });
2486
+ return;
2487
+ }
2488
+ if (binding?.source === "delegated") {
2489
+ onDelegated?.({
2490
+ path: file,
2491
+ line,
2492
+ tool,
2493
+ selector,
2494
+ checkoutPath: binding.path,
2495
+ ref: binding.ref
2496
+ });
2497
+ return;
2498
+ }
2499
+ const content = readFile(target);
2500
+ if (tool === "bun") {
2501
+ try {
2502
+ const manifest = JSON.parse(content ?? "");
2503
+ pin({
2504
+ rule,
2505
+ value: record$2(manifest) ? manifest["packageManager"] : void 0,
2506
+ expected: `bun@${policy.bun}`,
2507
+ label: "setup-bun version file packageManager",
2508
+ line
2509
+ });
2510
+ } catch {
2511
+ add({
2512
+ rule,
2513
+ line,
2514
+ message: "bun-version-file must reference a readable package.json object"
2515
+ });
2516
+ }
2517
+ return;
2518
+ }
2519
+ pin({
2520
+ rule,
2521
+ value: content?.trim(),
2522
+ expected: policy[tool],
2523
+ selector: tool === "node" ? "node" : void 0,
2524
+ label: `setup-${tool} version file`,
2525
+ line
2526
+ });
2527
+ };
2528
+ const resolveNode = (node) => {
2529
+ const visited = /* @__PURE__ */ new Set();
2530
+ while ((0, yaml.isAlias)(node)) {
2531
+ if (visited.has(node)) throw new Error("cyclic YAML alias");
2532
+ visited.add(node);
2533
+ node = node.resolve(document);
2534
+ }
2535
+ return node;
2536
+ };
2537
+ const approvedActions = new Map(Object.entries(policy.actions).map(([action, approved]) => [action.toLowerCase(), approved]));
2538
+ const mergedMaps = (node) => {
2539
+ node = resolveNode(node);
2540
+ if (!(0, yaml.isMap)(node)) return [];
2541
+ const maps = [];
2542
+ for (const pair of node.items) {
2543
+ if (!(0, yaml.isScalar)(pair.key) || typeof pair.key.value !== "symbol" || pair.key.source !== "<<") continue;
2544
+ const merge = resolveNode(pair.value);
2545
+ maps.push(...(0, yaml.isSeq)(merge) ? merge.items : [merge]);
2546
+ }
2547
+ return maps;
2548
+ };
2549
+ const keysOf = (node, visited = /* @__PURE__ */ new Set()) => {
2550
+ node = resolveNode(node);
2551
+ if (!(0, yaml.isMap)(node)) return /* @__PURE__ */ new Set();
2552
+ if (visited.has(node)) throw new Error("cyclic YAML merge");
2553
+ const next = new Set(visited);
2554
+ next.add(node);
2555
+ const keys = new Set(node.items.flatMap((pair) => (0, yaml.isScalar)(pair.key) && typeof pair.key.value === "string" ? [pair.key.value] : []));
2556
+ for (const merged of mergedMaps(node)) for (const key of keysOf(merged, next)) keys.add(key);
2557
+ return keys;
2558
+ };
2559
+ const sourceMap = ({ node, key, visited = /* @__PURE__ */ new Set() }) => {
2560
+ node = resolveNode(node);
2561
+ if (!(0, yaml.isMap)(node)) return void 0;
2562
+ if (node.has(key)) return node;
2563
+ if (visited.has(node)) throw new Error("cyclic YAML merge");
2564
+ const next = new Set(visited);
2565
+ next.add(node);
2566
+ for (const merged of mergedMaps(node)) {
2567
+ const source = sourceMap({
2568
+ node: merged,
2569
+ key,
2570
+ visited: next
2571
+ });
2572
+ if (source !== void 0) return source;
2573
+ }
2574
+ };
2575
+ const getNode = (node, key) => {
2576
+ const source = sourceMap({
2577
+ node,
2578
+ key
2579
+ });
2580
+ return (0, yaml.isMap)(source) ? resolveNode(source.get(key, true)) : void 0;
2581
+ };
2582
+ const actionInputs = /* @__PURE__ */ new Map();
2583
+ const inputsOf = (node) => {
2584
+ node = resolveNode(node);
2585
+ const cached = actionInputs.get(node);
2586
+ if (cached !== void 0) return cached;
2587
+ const options = getNode(node, "with");
2588
+ const inputs = /* @__PURE__ */ new Map();
2589
+ for (const key of keysOf(options)) {
2590
+ const folded = key.toUpperCase();
2591
+ const value = getNode(options, key);
2592
+ if (inputs.has(folded)) add({
2593
+ rule: "action-pins",
2594
+ line: nodeLine(value),
2595
+ message: `action input ${key} collides after case-folding`
2596
+ });
2597
+ if (/(?:^|-)VERSION(?:-FILE)?$/.test(folded) && key !== folded.toLowerCase()) add({
2598
+ rule: "action-pins",
2599
+ line: nodeLine(value),
2600
+ message: `selector input ${key} must use canonical lowercase casing`
2601
+ });
2602
+ inputs.set(folded, value);
2603
+ }
2604
+ actionInputs.set(node, inputs);
2605
+ return inputs;
2606
+ };
2607
+ const getInput = (node, key) => inputsOf(node).get(key.toUpperCase());
2608
+ const dynamicRefBody = (value) => {
2609
+ if (typeof value !== "string" || !value.startsWith("${{")) return void 0;
2610
+ let quote;
2611
+ for (let index = 3; index < value.length; index++) {
2612
+ const character = value.at(index);
2613
+ if (quote !== void 0) {
2614
+ if (character === quote) if (quote === "'" && value.at(index + 1) === "'") index++;
2615
+ else quote = void 0;
2616
+ else if (quote === "\"" && character === "\\") index++;
2617
+ continue;
2618
+ }
2619
+ if (character === "'" || character === "\"") quote = character;
2620
+ else if (value.startsWith("${{", index)) return void 0;
2621
+ else if (character === "}" && value.at(index + 1) === "}") return index === value.length - 2 ? value.slice(3, index).trim() : void 0;
2622
+ }
2623
+ };
2624
+ const checkoutPrefixOf = (node) => {
2625
+ const destination = getInput(node, "path");
2626
+ if (destination === void 0) return ".";
2627
+ return (0, yaml.isScalar)(destination) ? destination.value : void 0;
2628
+ };
2629
+ const sparseCheckoutOf = (node) => {
2630
+ const sparseKeys = [...inputsOf(node).keys()].filter((key) => key.startsWith("SPARSE-CHECKOUT"));
2631
+ if (sparseKeys.length === 0) return { mode: "all" };
2632
+ if (sparseKeys.some((key) => key !== "SPARSE-CHECKOUT" && key !== "SPARSE-CHECKOUT-CONE-MODE")) return { mode: "invalid" };
2633
+ const value = getInput(node, "sparse-checkout");
2634
+ const cone = getInput(node, "sparse-checkout-cone-mode");
2635
+ if (!(0, yaml.isScalar)(value) || typeof value.value !== "string" || cone !== void 0 && (!(0, yaml.isScalar)(cone) || cone.value !== true && cone.value !== false && cone.value !== "true" && cone.value !== "false")) return { mode: "invalid" };
2636
+ const paths = value.value.split(/\r?\n/).map((entry) => entry.trim()).filter((entry) => entry !== "");
2637
+ if (paths.length === 0 || paths.some((entry) => !staticRepositoryPath(entry) || entry.startsWith("!") || /[*?[\]]/.test(entry))) return { mode: "invalid" };
2638
+ return {
2639
+ mode: "files",
2640
+ paths: new Set(paths)
2641
+ };
2642
+ };
2643
+ let currentEngineFloor;
2644
+ const checkAction = (node) => {
2645
+ node = resolveNode(node);
2646
+ if (!(0, yaml.isMap)(node)) return;
2647
+ inputsOf(node);
2648
+ const uses = getNode(node, "uses");
2649
+ if (uses === void 0) return;
2650
+ const line = nodeLine(uses);
2651
+ if (!(0, yaml.isScalar)(uses) || typeof uses.value !== "string") {
2652
+ add({
2653
+ rule: "action-pins",
2654
+ line,
2655
+ message: "action uses must be a string containing a full commit SHA"
2656
+ });
2657
+ return;
2658
+ }
2659
+ const value = uses.value;
2660
+ if (value.startsWith("$/")) {
2661
+ if (value.length === 2 || /\s/.test(value) || value.includes("@") || value.includes("${{") || value.includes("\\") || value.split("/").includes("..")) add({
2662
+ rule: "action-pins",
2663
+ line,
2664
+ message: "self-repository actions must use a static repository path without a ref suffix"
2665
+ });
2666
+ return;
2667
+ }
2668
+ if (value.startsWith("./")) {
2669
+ const selector = staticRepositoryPath(value) ? node_path.default.posix.normalize(value) : void 0;
2670
+ const binding = selector === void 0 ? void 0 : checkoutBindings.findLast((entry) => entry.path === "." || selector === entry.path || selector.startsWith(`${entry.path}/`));
2671
+ if (selector === void 0 || unknownCheckoutDestination || binding !== void 0 && binding.source !== "tracked" || [...checkoutDestinations].some(([prefix, count]) => count > 1 && (prefix === "." || selector === prefix || selector.startsWith(`${prefix}/`)))) add({
2672
+ rule: "action-pins",
2673
+ line,
2674
+ message: "local actions require an unambiguous checkout of the current source snapshot"
2675
+ });
2676
+ return;
2677
+ }
2678
+ if (value.startsWith("docker://")) {
2679
+ add({
2680
+ rule: "action-pins",
2681
+ line,
2682
+ message: "Docker image actions require a reasoned action-pins opt-out"
2683
+ });
2684
+ checkRuntimeImage({
2685
+ image: value.slice(9),
2686
+ line,
2687
+ label: "Docker action image"
2688
+ });
2689
+ return;
2690
+ }
2691
+ const remote = /^([^./][^\s@]*\/[^\s@]+)@([^\s]+)$/.exec(value);
2692
+ if (remote === null) {
2693
+ add({
2694
+ rule: "action-pins",
2695
+ line,
2696
+ message: "remote actions must use a full commit SHA"
2697
+ });
2698
+ return;
2699
+ }
2700
+ const action = remote[1]?.toLowerCase();
2701
+ const ref = remote[2];
2702
+ const approved = action === void 0 ? void 0 : approvedActions.get(action) ?? approvedActions.get(action.split("/").slice(0, 2).join("/"));
2703
+ if (ref === void 0 || !/^[a-f0-9]{40}$/.test(ref)) add({
2704
+ rule: "action-pins",
2705
+ line,
2706
+ message: "remote actions must use a full commit SHA"
2707
+ });
2708
+ else if (approved !== void 0 && ref !== approved.sha) add({
2709
+ rule: "action-pins",
2710
+ line,
2711
+ message: `${action} must use ${approved.sha}`
2712
+ });
2713
+ const declaration = sourceMap({
2714
+ node,
2715
+ key: "uses"
2716
+ });
2717
+ const comment = uses.comment ?? ((0, yaml.isMap)(declaration) ? declaration.comment : void 0) ?? "";
2718
+ if (approved !== void 0 && !comment.trim().split(/\s+/).includes(approved.version)) add({
2719
+ rule: "action-pins",
2720
+ line,
2721
+ message: `${action} requires a # ${approved.version} version comment`
2722
+ });
2723
+ if (action === "actions/checkout") {
2724
+ const checkoutRepository = getInput(node, "repository");
2725
+ const checkoutRef = getInput(node, "ref");
2726
+ const prefix = checkoutPrefixOf(node);
2727
+ let repo;
2728
+ if (checkoutRepository !== void 0) repo = (0, yaml.isScalar)(checkoutRepository) ? checkoutRepository.value : null;
2729
+ const self = repo === void 0 || repo === "${{ github.repository }}" || typeof repo === "string" && repository !== void 0 && repo.toLowerCase() === repository.toLowerCase();
2730
+ const workflowSource = repo === "${{ job.workflow_repository }}" && (0, yaml.isScalar)(checkoutRef) && checkoutRef.value === "${{ job.workflow_sha }}";
2731
+ const currentSource = self && checkoutRef === void 0;
2732
+ const refValue = (0, yaml.isScalar)(checkoutRef) ? checkoutRef.value : void 0;
2733
+ const dynamicRef = dynamicRefBody(refValue);
2734
+ const delegatedSource = (self || repo === "${{ job.workflow_repository }}") && dynamicRef !== void 0 && dynamicRef !== "" && !/^(?:'(?:[^']|'')*'|"(?:[^"\\]|\\.)*"|(?:true|false|null)|-?(?:0x[\da-f]+|(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?))$/i.test(dynamicRef) && !/^(?:github\s*(?:\.\s*sha|\[\s*['"]sha['"]\s*\])|job\s*(?:\.\s*workflow_sha|\[\s*['"]workflow_sha['"]\s*\]))$/i.test(dynamicRef);
2735
+ if (!staticRepositoryPath(prefix)) checkoutBindings.push({
2736
+ path: ".",
2737
+ source: "untrusted",
2738
+ reason: "checkout destination must be a static repository path",
2739
+ line,
2740
+ sparse: { mode: "invalid" }
2741
+ });
2742
+ else {
2743
+ const destination = normalizeCheckoutPath(prefix);
2744
+ const trustedWriter = ref === approved?.sha && sourceMap({
2745
+ node,
2746
+ key: "if"
2747
+ }) === void 0 && sourceMap({
2748
+ node,
2749
+ key: "continue-on-error"
2750
+ }) === void 0 && checkoutDestinations.get(destination) === 1 && !unknownCheckoutDestination;
2751
+ if (trustedWriter && delegatedSource && typeof refValue === "string") checkoutBindings.push({
2752
+ path: destination,
2753
+ sparse: sparseCheckoutOf(node),
2754
+ source: "delegated",
2755
+ ref: refValue
2756
+ });
2757
+ else if (trustedWriter && (workflowSource || currentSource)) checkoutBindings.push({
2758
+ path: destination,
2759
+ sparse: sparseCheckoutOf(node),
2760
+ source: "tracked"
2761
+ });
2762
+ else {
2763
+ let reason = "checkout does not select a trusted repository source snapshot";
2764
+ if (ref !== approved?.sha) reason = "actions/checkout must use the approved action SHA";
2765
+ else if (sourceMap({
2766
+ node,
2767
+ key: "if"
2768
+ }) !== void 0 || sourceMap({
2769
+ node,
2770
+ key: "continue-on-error"
2771
+ }) !== void 0) reason = "checkout must be unconditional and omit continue-on-error";
2772
+ else if (checkoutDestinations.get(destination) !== 1 || unknownCheckoutDestination) reason = "checkout destination must have exactly one static writer";
2773
+ checkoutBindings.push({
2774
+ path: destination,
2775
+ sparse: sparseCheckoutOf(node),
2776
+ source: "untrusted",
2777
+ reason,
2778
+ line
2779
+ });
2780
+ }
2781
+ }
2782
+ }
2783
+ let tool;
2784
+ switch (action) {
2785
+ case "actions/setup-node":
2786
+ tool = "node";
2787
+ break;
2788
+ case "actions/setup-python":
2789
+ tool = "python";
2790
+ break;
2791
+ case "oven-sh/setup-bun":
2792
+ tool = "bun";
2793
+ break;
2794
+ default: return;
2795
+ }
2796
+ const literal = getInput(node, `${tool}-version`);
2797
+ if (tool === "node" && currentEngineFloor !== void 0) {
2798
+ const reference = getInput(node, "node-version-file");
2799
+ if (reference === void 0 && (0, yaml.isScalar)(literal) && engineFloorSelectorMatches(literal.value, currentEngineFloor)) {
2800
+ onEngineFloor?.(currentEngineFloor, "matched");
2801
+ return;
2802
+ }
2803
+ onEngineFloor?.(currentEngineFloor, "mismatch");
2804
+ add({
2805
+ rule: "runtime-workflow",
2806
+ line: nodeLine(literal ?? reference ?? uses),
2807
+ message: `engine floor job must select an exact Node patch satisfying ${currentEngineFloor.range} with minimum major ${currentEngineFloor.major}`
2808
+ });
2809
+ return;
2810
+ }
2811
+ if (literal !== void 0) add({
2812
+ rule: tool === "bun" ? "bun-pins" : "runtime-workflow",
2813
+ line: nodeLine(literal),
2814
+ message: `setup-${tool} must use ${tool}-version-file`
2815
+ });
2816
+ const reference = getInput(node, `${tool}-version-file`);
2817
+ checkReference({
2818
+ value: (0, yaml.isScalar)(reference) ? reference.value : void 0,
2819
+ tool,
2820
+ line: reference === void 0 ? line : nodeLine(reference)
2821
+ });
2822
+ };
2823
+ const checkContainer = (node) => {
2824
+ node = resolveNode(node);
2825
+ if (node === void 0) return;
2826
+ const image = (0, yaml.isMap)(node) ? getNode(node, "image") : node;
2827
+ checkRuntimeImage({
2828
+ image: (0, yaml.isScalar)(image) ? image.value : void 0,
2829
+ line: nodeLine(image ?? node),
2830
+ label: "container image"
2831
+ });
2832
+ };
2833
+ const checkSteps = (node, floor) => {
2834
+ currentEngineFloor = void 0;
2835
+ checkoutBindings = [];
2836
+ checkoutDestinations = /* @__PURE__ */ new Map();
2837
+ unknownCheckoutDestination = false;
2838
+ node = resolveNode(node);
2839
+ if (!(0, yaml.isSeq)(node)) return;
2840
+ for (const step of node.items) {
2841
+ const uses = getNode(step, "uses");
2842
+ if (!(0, yaml.isScalar)(uses) || typeof uses.value !== "string" || !uses.value.toLowerCase().startsWith("actions/checkout@")) continue;
2843
+ const prefix = checkoutPrefixOf(step);
2844
+ if (!staticRepositoryPath(prefix)) {
2845
+ unknownCheckoutDestination = true;
2846
+ continue;
2847
+ }
2848
+ const destination = normalizeCheckoutPath(prefix);
2849
+ checkoutDestinations.set(destination, (checkoutDestinations.get(destination) ?? 0) + 1);
2850
+ }
2851
+ currentEngineFloor = floor;
2852
+ try {
2853
+ for (const step of node.items) checkAction(step);
2854
+ } finally {
2855
+ currentEngineFloor = void 0;
2856
+ }
2857
+ };
2858
+ try {
2859
+ document.toJS({ maxAliasCount: 100 });
2860
+ if (automationKind === "workflow") {
2861
+ const jobs = getNode(document.contents, "jobs");
2862
+ if ((0, yaml.isMap)(jobs)) for (const key of keysOf(jobs)) {
2863
+ checkoutBindings = [];
2864
+ checkoutDestinations = /* @__PURE__ */ new Map();
2865
+ unknownCheckoutDestination = false;
2866
+ currentEngineFloor = void 0;
2867
+ const job = getNode(jobs, key);
2868
+ checkAction(job);
2869
+ checkContainer(getNode(job, "container"));
2870
+ const services = getNode(job, "services");
2871
+ if ((0, yaml.isMap)(services)) for (const service of keysOf(services)) checkContainer(getNode(services, service));
2872
+ checkSteps(getNode(job, "steps"), engineFloors.find((entry) => entry.job === key));
2873
+ }
2874
+ } else {
2875
+ const runs = getNode(document.contents, "runs");
2876
+ const using = getNode(runs, "using");
2877
+ if ((0, yaml.isScalar)(using) && using.value === "composite") checkSteps(getNode(runs, "steps"));
2878
+ if ((0, yaml.isScalar)(using) && using.value === "docker") {
2879
+ const image = getNode(runs, "image");
2880
+ const value = (0, yaml.isScalar)(image) ? image.value : void 0;
2881
+ if (typeof value === "string" && value.startsWith("docker://")) {
2882
+ add({
2883
+ rule: "action-pins",
2884
+ line: nodeLine(image),
2885
+ message: "Docker image actions require a reasoned action-pins opt-out"
2886
+ });
2887
+ checkRuntimeImage({
2888
+ image: value.slice(9),
2889
+ line: nodeLine(image),
2890
+ label: "Docker action image"
2891
+ });
2892
+ } else if (typeof value !== "string" || value.includes("${{") || value.includes("\\") || value.includes(":") || node_path.default.posix.isAbsolute(value) || node_path.default.posix.normalize(node_path.default.posix.join(node_path.default.posix.dirname(file), value)).split("/").at(0) === ".." || node_path.default.posix.basename(value) !== "Dockerfile") add({
2893
+ rule: "action-pins",
2894
+ line: nodeLine(image),
2895
+ message: "Docker actions must reference a local Dockerfile or declare a reasoned action-pins opt-out for an external image"
2896
+ });
2897
+ }
2898
+ }
2899
+ } catch {
2900
+ add({
2901
+ rule: "runtime-workflow",
2902
+ line: 1,
2903
+ message: "cannot resolve workflow YAML aliases"
2904
+ });
2905
+ }
2906
+ return diagnostics;
2907
+ };
2908
+ //#endregion
2909
+ //#region src/toolchain-schema.ts
2910
+ const packagePinKeys = [
2911
+ "oxlint",
2912
+ "oxlint-tsgolint",
2913
+ "@oxlint/plugins",
2914
+ "@stll/oxlint-plugin",
2915
+ "oxfmt",
2916
+ "lefthook"
2917
+ ];
2918
+ const valkeyArchitectures = ["amd64", "arm64"];
2919
+ const valkeyArtifactPackages = {
2920
+ server: "valkey-server",
2921
+ tools: "valkey-tools"
2922
+ };
2923
+ const record$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2924
+ const artifactRecord = (value, keys) => {
2925
+ if (!record$1(value) || Object.keys(value).some((key) => !keys.includes(key)) || keys.some((key) => !Object.hasOwn(value, key))) throw new Error("valkeyArtifacts requires complete, closed artifact objects");
2926
+ return value;
2927
+ };
2928
+ const parseValkeyArtifacts = (input, version) => {
2929
+ const architectures = artifactRecord(input, valkeyArchitectures);
2930
+ const line = version.split(".").slice(0, 2).join(".");
2931
+ const parseArchitecture = (architecture) => {
2932
+ const packages = artifactRecord(architectures[architecture], Object.keys(valkeyArtifactPackages));
2933
+ const parseArtifact = (kind) => {
2934
+ const artifact = artifactRecord(packages[kind], ["url", "sha256"]);
2935
+ const url = artifact["url"];
2936
+ const sha256 = artifact["sha256"];
2937
+ const expected = `https://download.valkey.io/packaging/valkey-${line}/deb/ubuntu2404/${architecture}/${valkeyArtifactPackages[kind]}_${version}-1.noble_${architecture}.deb`;
2938
+ if (typeof url !== "string" || url !== expected) throw new Error("valkeyArtifacts URL must select the exact official versioned Ubuntu artifact");
2939
+ if (typeof sha256 !== "string" || !/^[a-f0-9]{64}$/.test(sha256)) throw new Error("valkeyArtifacts requires a lowercase SHA256 pin");
2940
+ return {
2941
+ url,
2942
+ sha256
2943
+ };
2944
+ };
2945
+ return {
2946
+ server: parseArtifact("server"),
2947
+ tools: parseArtifact("tools")
2948
+ };
2949
+ };
2950
+ return {
2951
+ amd64: parseArchitecture("amd64"),
2952
+ arm64: parseArchitecture("arm64")
2953
+ };
2954
+ };
2955
+ /** Reject unsupported or incomplete installed policies before inspecting a consumer. */
2956
+ const parseToolchainPolicy = (input) => {
2957
+ if (!record$1(input) || input["schemaVersion"] !== 1) throw new Error("toolchain.json must use schemaVersion 1");
2958
+ const string = (object, key) => {
2959
+ const value = object[key];
2960
+ if (typeof value !== "string" || value.trim() === "") throw new Error(`toolchain.json requires a nonempty ${key}`);
2961
+ return value;
2962
+ };
2963
+ const packages = {};
2964
+ for (const key of packagePinKeys) packages[key] = string(input, key);
2965
+ const bun = string(input, "bun");
2966
+ const typescript = string(input, "typescript");
2967
+ const node = string(input, "node");
2968
+ const python = string(input, "python");
2969
+ const postgres = string(input, "postgres");
2970
+ const valkey = string(input, "valkey");
2971
+ const rust = string(input, "rust");
2972
+ const rustCompilerDevelopment = string(input, "rustCompilerDevelopment");
2973
+ for (const [name, value] of Object.entries({
2974
+ ...packages,
2975
+ bun,
2976
+ typescript
2977
+ })) if ((0, semver.valid)(value) !== value) throw new Error(`toolchain.json ${name} must be an exact release`);
2978
+ if (!/^[1-9]\d*$/.test(postgres) || !Number.isSafeInteger(Number(postgres))) throw new Error("PostgreSQL must be a canonical positive major");
2979
+ if ((0, semver.valid)(valkey) !== valkey || !/^\d+\.\d+\.\d+$/.test(valkey)) throw new Error("Valkey must be an exact stable release");
2980
+ const valkeyArtifacts = parseValkeyArtifacts(input["valkeyArtifacts"], valkey);
2981
+ if (!nodePolicyValid(node)) throw new Error("Node must be a canonical major N.x series");
2982
+ if (!/^\d+\.\d+(?:\.\d+)?$/.test(python)) throw new Error("Python must be an exact minor or patch release");
2983
+ if (!/^\d+\.\d+\.\d+$/.test(rust)) throw new Error("Rust must be an exact stable release");
2984
+ if (!/^nightly-\d{4}-\d{2}-\d{2}$/.test(rustCompilerDevelopment)) throw new Error("Rust compiler development must be a dated nightly");
2985
+ const compatibility = input["typescript6Compatibility"];
2986
+ if (!record$1(compatibility)) throw new Error("missing TypeScript compatibility policy");
2987
+ const version = string(compatibility, "version");
2988
+ const packageAlias = string(compatibility, "packageAlias");
2989
+ if ((0, semver.valid)(version) !== version) throw new Error("TypeScript compatibility must be an exact release");
2990
+ const layouts = input["typescriptInstallLayouts"];
2991
+ if (!Array.isArray(layouts) || layouts.length === 0) throw new Error("missing TypeScript install layouts");
2992
+ const typescriptInstallLayouts = layouts.map((layout) => {
2993
+ if (!record$1(layout)) throw new Error("invalid TypeScript install layout");
2994
+ const compilerPackage = string(layout, "compilerPackage");
2995
+ const compilerSpecifier = string(layout, "compilerSpecifier");
2996
+ const typecheckCommand = string(layout, "typecheckCommand");
2997
+ switch (layout["type"]) {
2998
+ case "direct":
2999
+ if (compilerSpecifier !== typescript || compilerPackage !== "typescript") throw new Error("direct TypeScript layout differs from shared version");
3000
+ return {
3001
+ type: "direct",
3002
+ compilerPackage,
3003
+ compilerSpecifier,
3004
+ typecheckCommand
3005
+ };
3006
+ case "split-compatibility": {
3007
+ const compatibilityPackage = string(layout, "compatibilityPackage");
3008
+ const compatibilitySpecifier = string(layout, "compatibilitySpecifier");
3009
+ if (compilerSpecifier !== `npm:typescript@${typescript}` || compatibilitySpecifier !== version) throw new Error("split TypeScript layout differs from shared versions");
3010
+ return {
3011
+ type: "split-compatibility",
3012
+ compilerPackage,
3013
+ compilerSpecifier,
3014
+ compatibilityPackage,
3015
+ compatibilitySpecifier,
3016
+ typecheckCommand
3017
+ };
3018
+ }
3019
+ default: throw new Error("unsupported TypeScript install layout");
3020
+ }
3021
+ });
3022
+ const actionsInput = input["actions"];
3023
+ if (!record$1(actionsInput) || Object.keys(actionsInput).length === 0) throw new Error("missing approved actions");
3024
+ const actions = {};
3025
+ for (const [name, action] of Object.entries(actionsInput)) {
3026
+ if (!record$1(action)) throw new Error(`invalid action policy: ${name}`);
3027
+ const sha = string(action, "sha");
3028
+ const actionVersion = string(action, "version");
3029
+ if (!/^[a-f0-9]{40}$/.test(sha) || !/^v\d+(?:\.\d+)*$/.test(actionVersion)) throw new Error(`invalid action SHA/version: ${name}`);
3030
+ actions[name] = {
3031
+ sha,
3032
+ version: actionVersion
3033
+ };
3034
+ }
3035
+ const dependabotInput = input["dependabot"];
3036
+ if (!record$1(dependabotInput) || !record$1(dependabotInput["schedule"]) || !record$1(dependabotInput["cooldown"]) || !record$1(dependabotInput["groups"])) throw new Error("missing Dependabot policy");
3037
+ const scheduleInput = dependabotInput["schedule"];
3038
+ const schedule = {
3039
+ interval: string(scheduleInput, "interval"),
3040
+ day: string(scheduleInput, "day"),
3041
+ time: string(scheduleInput, "time"),
3042
+ timezone: string(scheduleInput, "timezone")
3043
+ };
3044
+ const defaultDays = dependabotInput["cooldown"]["defaultDays"];
3045
+ if (typeof defaultDays !== "number" || !Number.isInteger(defaultDays) || defaultDays < 5) throw new Error("Dependabot cooldown must be at least five days");
3046
+ const strings = (value) => {
3047
+ if (!Array.isArray(value) || !value.every((entry) => typeof entry === "string")) throw new Error("Dependabot group values must be string arrays");
3048
+ return value;
3049
+ };
3050
+ const groups = {};
3051
+ for (const [name, group] of Object.entries(dependabotInput["groups"])) {
3052
+ if (!record$1(group)) throw new Error(`invalid Dependabot group: ${name}`);
3053
+ groups[name] = {
3054
+ patterns: strings(group["patterns"]),
3055
+ updateTypes: strings(group["updateTypes"])
3056
+ };
3057
+ }
3058
+ return {
3059
+ bun,
3060
+ typescript,
3061
+ node,
3062
+ postgres,
3063
+ valkey,
3064
+ valkeyArtifacts,
3065
+ python,
3066
+ rust,
3067
+ rustCompilerDevelopment,
3068
+ packages,
3069
+ actions,
3070
+ typescriptInstallLayouts,
3071
+ typescript6Compatibility: {
3072
+ version,
3073
+ packageAlias
3074
+ },
3075
+ dependabot: {
3076
+ schedule,
3077
+ cooldown: { defaultDays },
3078
+ groups,
3079
+ ignoredPackages: [.../* @__PURE__ */ new Set([
3080
+ ...Object.keys(packages),
3081
+ ...typescriptInstallLayouts.flatMap((layout) => layout.type === "direct" ? [layout.compilerPackage] : [layout.compilerPackage, layout.compatibilityPackage]),
3082
+ packageAlias,
3083
+ "bun-types"
3084
+ ])],
3085
+ ignoredActions: Object.keys(actions),
3086
+ ignoredImages: [
3087
+ "node",
3088
+ "python",
3089
+ "oven/bun"
3090
+ ]
3091
+ }
3092
+ };
3093
+ };
3094
+ //#endregion
3095
+ //#region src/toolchain-guard.ts
3096
+ const toolchainRules = [.../* @__PURE__ */ new Set([
3097
+ ...packageRules,
3098
+ ...runtimeRules,
3099
+ ...dependabotRules,
3100
+ "cloud-setup-drift"
3101
+ ])];
3102
+ const record = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3103
+ const array = (value) => Array.isArray(value);
3104
+ /** Repository-owned declarations are explicit; malformed decisions fail closed. */
3105
+ const parseToolchainConfiguration = (input) => {
3106
+ if (!record(input) || Object.keys(input).some((key) => key !== "optOuts" && key !== "cloud" && key !== "engineFloors") || input["optOuts"] !== void 0 && !array(input["optOuts"])) throw new Error("stll-toolchain.json accepts only optOuts, cloud and engineFloors declarations");
3107
+ const disabled = /* @__PURE__ */ new Set();
3108
+ const optOuts = input["optOuts"] ?? [];
3109
+ if (!array(optOuts)) throw new Error("optOuts must be an array");
3110
+ for (const entry of optOuts) {
3111
+ if (!record(entry) || Object.keys(entry).some((key) => key !== "rule" && key !== "reason") || typeof entry["rule"] !== "string" || !toolchainRules.some((rule) => rule === entry["rule"]) || typeof entry["reason"] !== "string" || entry["reason"].trim() === "" || disabled.has(entry["rule"])) throw new Error("each opt-out requires a unique known rule and a nonempty reason");
3112
+ if (entry["rule"] === "node-engine") throw new Error("node-engine cannot be opted out; engines.node must support the shared Node series");
3113
+ if (entry["rule"] === "cloud-setup-drift") throw new Error("cloud-setup-drift cannot be opted out; generated setup must match shared policy");
3114
+ disabled.add(entry["rule"]);
3115
+ }
3116
+ return {
3117
+ disabled,
3118
+ cloud: parseCloudSetup(input["cloud"]),
3119
+ engineFloors: parseEngineFloors(input["engineFloors"])
3120
+ };
3121
+ };
3122
+ /** Read one tracked configuration snapshot for guards and policy generation. */
3123
+ const readToolchainInputs = (root) => {
3124
+ const diagnostics = [];
3125
+ const tracked = (0, node_child_process.execFileSync)("git", [
3126
+ "ls-files",
3127
+ "-z",
3128
+ "--cached"
3129
+ ], {
3130
+ cwd: root,
3131
+ encoding: "utf8"
3132
+ }).split("\0").filter((file) => file !== "");
3133
+ const files = {};
3134
+ const trackedFiles = new Set(tracked);
3135
+ const resolvedRoot = (0, node_fs.realpathSync)(root);
3136
+ for (const file of tracked) {
3137
+ const kind = toolchainInputKind(file);
3138
+ if (kind === void 0) continue;
3139
+ if (kind === "presence") {
3140
+ files[file] = "";
3141
+ continue;
3142
+ }
3143
+ try {
3144
+ const resolvedFile = (0, node_fs.realpathSync)(node_path.default.join(resolvedRoot, file));
3145
+ const relative = node_path.default.relative(resolvedRoot, resolvedFile);
3146
+ if (node_path.default.isAbsolute(relative) || relative.split(node_path.default.sep).at(0) === ".." || !trackedFiles.has(relative.split(node_path.default.sep).join("/"))) throw new Error("Configuration target is outside the tracked tree");
3147
+ files[file] = (0, node_fs.readFileSync)(resolvedFile, "utf8");
3148
+ } catch {
3149
+ diagnostics.push({
3150
+ rule: "configuration",
3151
+ path: file,
3152
+ line: 1,
3153
+ message: "cannot read tracked configuration file"
3154
+ });
3155
+ }
3156
+ }
3157
+ return {
3158
+ files,
3159
+ trackedFiles,
3160
+ diagnostics
3161
+ };
3162
+ };
3163
+ const checkToolchain = ({ root, policy, onDelegated }) => {
3164
+ const { files, trackedFiles, diagnostics } = readToolchainInputs(root);
3165
+ let repository;
3166
+ try {
3167
+ const origin = (0, node_child_process.execFileSync)("git", [
3168
+ "remote",
3169
+ "get-url",
3170
+ "origin"
3171
+ ], {
3172
+ cwd: root,
3173
+ encoding: "utf8",
3174
+ stdio: [
3175
+ "ignore",
3176
+ "pipe",
3177
+ "ignore"
3178
+ ]
3179
+ }).trim();
3180
+ repository = /^(?:https?:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([^/]+\/[^/]+?)(?:\.git)?\/?$/.exec(origin)?.[1];
3181
+ } catch {}
3182
+ let disabled = /* @__PURE__ */ new Set();
3183
+ let cloud;
3184
+ const engineFloors = [];
3185
+ if (files["stll-toolchain.json"] !== void 0) try {
3186
+ const configuration = parseToolchainConfiguration(JSON.parse(files["stll-toolchain.json"]));
3187
+ disabled = configuration.disabled;
3188
+ cloud = configuration.cloud;
3189
+ for (const entry of configuration.engineFloors) engineFloors.push(resolveEngineFloor(entry, files));
3190
+ } catch (error) {
3191
+ diagnostics.push({
3192
+ rule: "configuration",
3193
+ path: "stll-toolchain.json",
3194
+ line: 1,
3195
+ message: error instanceof Error ? error.message : String(error)
3196
+ });
3197
+ }
3198
+ const script = files[cloudSetupPath];
3199
+ if (cloud === void 0 && trackedFiles.has(".agents/cloud-setup.sh")) diagnostics.push({
3200
+ rule: "cloud-setup-drift",
3201
+ path: cloudSetupPath,
3202
+ line: 1,
3203
+ message: "cloud setup script requires an explicit cloud declaration in stll-toolchain.json"
3204
+ });
3205
+ if (cloud !== void 0) try {
3206
+ const nodeVersion = files[".node-version"];
3207
+ if (nodeVersion === void 0) throw new Error("cloud setup requires a tracked root .node-version with an exact stable release");
3208
+ if (script !== generateCloudSetup({
3209
+ policy,
3210
+ cloud,
3211
+ nodeVersion: nodeVersion.trim()
3212
+ })) diagnostics.push({
3213
+ rule: "cloud-setup-drift",
3214
+ path: cloudSetupPath,
3215
+ line: 1,
3216
+ message: "cloud setup script is missing or differs from shared policy; run stll-cloud-setup"
3217
+ });
3218
+ } catch (error) {
3219
+ diagnostics.push({
3220
+ rule: "cloud-setup-drift",
3221
+ path: cloudSetupPath,
3222
+ line: 1,
3223
+ message: error instanceof Error ? error.message : String(error)
3224
+ });
3225
+ }
3226
+ const exercisedFloors = /* @__PURE__ */ new Set();
3227
+ const mismatchedFloors = /* @__PURE__ */ new Set();
3228
+ diagnostics.push(...checkPackageFiles({
3229
+ files,
3230
+ policy
3231
+ }));
3232
+ for (const [file, text] of Object.entries(files)) diagnostics.push(...checkRuntimeFile({
3233
+ file,
3234
+ text,
3235
+ policy: {
3236
+ ...policy,
3237
+ packages: {
3238
+ ...policy.packages,
3239
+ typescript: policy.typescript
3240
+ }
3241
+ },
3242
+ trackedFiles,
3243
+ repository,
3244
+ onDelegated,
3245
+ engineFloors: engineFloors.filter((entry) => entry.workflow === file),
3246
+ onEngineFloor: (entry, status) => {
3247
+ if (status === "mismatch") mismatchedFloors.add(entry);
3248
+ else exercisedFloors.add(entry);
3249
+ },
3250
+ readFile: (target) => files[target]
3251
+ }));
3252
+ for (const entry of engineFloors) if (!exercisedFloors.has(entry) || mismatchedFloors.has(entry)) diagnostics.push({
3253
+ rule: "configuration",
3254
+ path: "stll-toolchain.json",
3255
+ line: 1,
3256
+ message: `engine floor ${entry.workflow}:${entry.job} requires a setup-node exact patch satisfying ${entry.package} engines.node minimum major ${entry.major}`
3257
+ });
3258
+ diagnostics.push(...checkDependabot({
3259
+ files,
3260
+ policy: policy.dependabot
3261
+ }));
3262
+ return diagnostics.filter((diagnostic) => !disabled.has(diagnostic.rule));
3263
+ };
3264
+ //#endregion
3265
+ Object.defineProperty(exports, "checkToolchain", {
3266
+ enumerable: true,
3267
+ get: function() {
3268
+ return checkToolchain;
3269
+ }
3270
+ });
3271
+ Object.defineProperty(exports, "cloudSetupPath", {
3272
+ enumerable: true,
3273
+ get: function() {
3274
+ return cloudSetupPath;
3275
+ }
3276
+ });
3277
+ Object.defineProperty(exports, "generateCloudSetup", {
3278
+ enumerable: true,
3279
+ get: function() {
3280
+ return generateCloudSetup;
3281
+ }
3282
+ });
3283
+ Object.defineProperty(exports, "parseToolchainConfiguration", {
3284
+ enumerable: true,
3285
+ get: function() {
3286
+ return parseToolchainConfiguration;
3287
+ }
3288
+ });
3289
+ Object.defineProperty(exports, "parseToolchainPolicy", {
3290
+ enumerable: true,
3291
+ get: function() {
3292
+ return parseToolchainPolicy;
3293
+ }
3294
+ });
3295
+ Object.defineProperty(exports, "readToolchainInputs", {
3296
+ enumerable: true,
3297
+ get: function() {
3298
+ return readToolchainInputs;
3299
+ }
3300
+ });
3301
+
3302
+ //# sourceMappingURL=toolchain-guard.cjs.map