Repository navigation
Expand file tree
/
Copy pathdocker-entrypoint.sh
More file actions
executable file
·498 lines (463 loc) · 29.3 KB
/
Copy pathdocker-entrypoint.sh
File metadata and controls
executable file
·498 lines (463 loc) · 29.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
#!/bin/bash
#
# Docker Entrypoint Script
#
# Validates native modules before starting the application.
# This prevents confusing runtime errors from NODE_MODULE_VERSION mismatches.
#
# Also rebuilds dist/ on first container start in git worktrees, where the
# .:/app bind mount erases image-layer dist/ (dist/ is gitignored on host).
#
# Usage: Set as ENTRYPOINT in Dockerfile or docker-compose.yml
#
# Reference: ADR-012 (Native Module Version Management)
# Reference: SMI-2621 (Worktree Docker dist/ fix)
#
set -e
# SMI-5784: per-package native-module seeding/validation split out per
# CLAUDE.md's 500-line file-length convention (this file grew from 310 to
# 510 lines adding that logic — new debt from this PR, not pre-existing).
# Sourced early (mirrors scripts/rebase-worktree.sh's own
# source-its-helpers-near-the-top convention) so validate_native_module() —
# SHARED with the root-only NATIVE_MODULES validation loop below, not just
# the per-package call sites — is available wherever either needs it.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=docker-entrypoint-native-per-package.sh
source "$SCRIPT_DIR/docker-entrypoint-native-per-package.sh"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# ---------------------------------------------------------------------------
# SMI-5570/SMI-5074: container-side symlink correction for worktree containers.
#
# Worktree-gated via /app/.git being a FILE (git's worktree marker): the
# main-repo container has REAL per-package node_modules and a REAL
# node_modules directory under /app (populated by `npm install` against the
# actual checkout, before any mount lands there), so none of this applies —
# confirmed via direct inspection (no symlink, no escape) on skillsmith-dev-1.
# See scripts/lib/repair-worktree-container-symlinks.sh for the mechanism.
#
# SMI-5685: the second arg names the Compose-declared mount target
# (/app/node_modules — see docker-compose.yml and the worktree override's
# tmpfs targets) directly, rather than relying on the bare /node_modules
# path a healthy worktree's symlinked host node_modules happens to clamp a
# bind mount onto (a real but underdocumented mount(2) side effect,
# scripts/_lib.sh's enumerate_compose_node_modules_mounts header). On a
# State-B worktree (host node_modules is a real, non-symlink directory —
# SMI-5689 fixes that) the clamp never fires, so the old /node_modules arg
# looked in the wrong, unpopulated place and the @skillsmith/@smith-horn
# alias repair silently no-op'd on every boot. /app/node_modules resolves
# identically on a healthy worktree and is the only target Compose itself
# ever declares.
# ---------------------------------------------------------------------------
if [ -f "/app/.git" ]; then
bash /app/scripts/lib/repair-worktree-container-symlinks.sh /app/packages /app/node_modules
else
echo -e "${GREEN}[entrypoint] Main checkout — no worktree symlink repair needed (SMI-5570/SMI-5074 no-op)${NC}"
fi
# ---------------------------------------------------------------------------
# SMI-5650: seed writable native-module named volumes (worktree only).
# The worktree container's /app/node_modules is a read-only view of the
# (possibly macOS) host tree, so the SMI-5351 rebuild loop below cannot write
# a rebuilt .node binary. scripts/_lib.sh emits a writable Docker-managed
# named volume (NOT tmpfs — see _lib.sh's enumerate_compose_node_modules_mounts
# comment for why: Compose's tmpfs volume type hardcodes noexec, which broke
# native module loading) at /app/node_modules/<module> for each of these; seed it from the image's
# /opt/native-seed stash (built during the image's own Linux npm rebuild) so a
# `docker compose restart dev` self-heal is deterministic and offline.
# This module list is referenced inline (rather than from NATIVE_MODULES,
# which is declared later, below the dist check) — keep it in sync with that
# array, scripts/_lib.sh's NATIVE_MODULES_FOR_OVERLAY, and the Dockerfile stash
# (a cross-file sync-check test enforces this).
#
# @esbuild is a SCOPE, not a flat module — confirmed live it is REQUIRED
# alongside the flat `esbuild` entry: esbuild's own JS API does not contain
# the native binary it spawns at runtime; that lives in the separate
# platform-arch package (@esbuild/<platform>-<arch>) inside this scope. It
# has no package.json of its own (only its children do), so "already seeded"
# is checked via "non-empty directory" instead of the flat entries'
# "package.json present" check.
#
# Disable: SKILLSMITH_WORKTREE_NATIVE_SEED_DISABLE=1 (registered in
# docs/internal/process/guards-and-opt-outs.md).
# ---------------------------------------------------------------------------
if [ -f "/app/.git" ] && [ "${SKILLSMITH_WORKTREE_NATIVE_SEED_DISABLE:-}" != "1" ]; then
for module in better-sqlite3 onnxruntime-node esbuild hnswlib-node @esbuild; do
seed="/opt/native-seed/${module}"
target="/app/node_modules/${module}"
already_seeded=1
case "$module" in
@*) [ -n "$(ls -A "$target" 2>/dev/null)" ] && already_seeded=0 ;;
*) [ -f "$target/package.json" ] && already_seeded=0 ;;
esac
if [ ! -d "$seed" ]; then
echo -e "${YELLOW}[entrypoint] No native seed for ${module} — image predates SMI-5650; falling back to npm rebuild if validation fails. Rebuild the image (docker compose build) to pick up the seed.${NC}"
elif [ "$already_seeded" -eq 1 ]; then
if cp -a "$seed/." "$target/" 2>/dev/null; then
echo -e "${GREEN} ✓ Seeded ${module} into writable overlay (SMI-5650)${NC}"
else
echo -e "${YELLOW}[entrypoint] Could not seed ${module} — the named volume mount is likely missing (stale override, pre-SMI-5650). Run scripts/repair-worktrees.sh on host, recreate container.${NC}"
fi
fi
done
fi
# SMI-5784: per-package boot-time seed step — split out per CLAUDE.md's
# 500-line file-length convention. See
# docker-entrypoint-native-per-package.sh's
# seed_per_package_native_modules_boot() for the full block + rationale
# (companion to the root-only loop above; same disable-var gate).
seed_per_package_native_modules_boot
# ---------------------------------------------------------------------------
# Dist check: rebuild if dist/ is missing (common on first container start
# in a git worktree, where .:/app bind mount erases image-layer dist/).
#
# In fresh worktrees the host has no dist/ (gitignored). The .:/app bind
# mount overlays /app at container start, leaving packages/*/dist/ absent.
#
# Four sentinels (core, mcp-server, doc-retrieval-mcp, cli — SMI-5957 added
# the latter two, matching BUILD_FILTER below exactly so the freshness
# check and the build scope can never silently drift apart) catch both
# fresh-worktree (all dist/ absent) and partial-build scenarios (some
# packages were previously built, one wasn't). Turbo builds core first
# (dependsOn: ["^build"]), so a successful build guarantees all four are
# compiled.
#
# Note: set -e + explicit exit 1 below is intentional belt-and-suspenders —
# set -e handles unexpected failures; exit 1 here provides a human-readable
# message before aborting.
# ---------------------------------------------------------------------------
CORE_DIST_ENTRY="/app/packages/core/dist/src/index.js"
MCP_DIST_ENTRY="/app/packages/mcp-server/dist/src/index.js"
DOC_RETRIEVAL_DIST_ENTRY="/app/packages/doc-retrieval-mcp/dist/src/server.js"
CLI_DIST_ENTRY="/app/packages/cli/dist/cli.js"
echo -e "${YELLOW}[entrypoint] Checking dist/ outputs...${NC}"
# Pre-check: node_modules must be initialised before build can succeed
if [ ! -f "/app/node_modules/.package-lock.json" ] || [ ! -x "/app/node_modules/.bin/turbo" ]; then
echo -e "${RED} ✗ node_modules not initialised (or partial install) — run: npm install inside this container${NC}"
exit 1
fi
if [ ! -f "$CORE_DIST_ENTRY" ] || [ ! -f "$MCP_DIST_ENTRY" ] || [ ! -f "$DOC_RETRIEVAL_DIST_ENTRY" ] || [ ! -f "$CLI_DIST_ENTRY" ]; then
echo -e "${YELLOW} ✗ dist/ not found (first container start) — building packages...${NC}"
echo -e "${YELLOW} This is a one-time cost per worktree (until dist/ is manually removed).${NC}"
# SMI-5957: scope this build to what CORE_DIST_ENTRY/MCP_DIST_ENTRY
# actually check, plus every package with a currently-live cold-start
# consumer: scripts/mcp-doc-retrieval-launcher.sh hard-requires
# packages/doc-retrieval-mcp/dist/src/server.js; .husky/post-commit
# silently skips the reindex hook when its dist/cli.js is absent;
# private-registry-e2e.yml's spec shells out to the real `skillsmith
# registry install` CLI subprocess, so @skillsmith/cli must be fresh
# here too — deliberately in THIS single invocation, not a second,
# separate one (see below for why that matters).
# Applied unconditionally (worktree AND full checkout) — @skillsmith/website
# is excluded in both because neither this gate nor any live consumer
# needs it fresh, and (fresh-checkout case) its `astro` dependency is
# installed non-hoisted to packages/website/node_modules, which has no
# named-volume protection against docker-compose.yml's `.:/app` bind
# mount on a cold `docker compose up` — a website build failure there is
# FATAL to this script (see the exit 1 below), and combined with
# `restart: unless-stopped` produces an unrecoverable crash-restart loop
# (confirmed via live repro, SMI-5957).
#
# MUST invoke `turbo` directly, not route the filter through
# `npm run build --`: npm appends `--`-args to the END of the whole
# `&&`-chained root build script ("turbo run build && bash
# scripts/lib/check-dist-fresh.sh --write-sentinel", package.json), not
# to `turbo` specifically — the filter previously used here (worktree-only,
# `--filter=!@skillsmith/website`) was silently landing on
# check-dist-fresh.sh instead and has been dead code since the `&&` chain
# was introduced (commit 3c8655c18, SMI-5548). Worktree containers' actual
# immunity to a website-build failure has never come from that filter — it
# comes from docker-compose.override.yml separately bind-mounting the main
# checkout's already-populated packages/website/node_modules read-only.
# SMI-4739 (the virtiofs/Astro cache-path issue this filter was originally
# written for) remains genuinely untested, not superseded by this change.
#
# @skillsmith/cli is built HERE, in this one call, rather than via a
# second, separate `docker exec ... turbo run build` invocation later
# (private-registry-e2e.yml's original design) for two independently
# confirmed reasons (SMI-5957 live CI verification, not local repro
# alone — a genuine gap between this session's local Docker environment
# and a real GH-hosted Linux runner): (1) mcp-server's composite/
# incremental tsconfig with a TS project reference to core means a
# SECOND `tsc` invocation against mcp-server in the same container
# incorrectly reports a real-looking zod type error (SMI-5960, a
# genuinely pre-existing TS incremental-compile bug); (2) a separate
# `docker exec` invocation of cli's own build, run via `docker exec`
# AFTER this entrypoint's own build already completed, was observed to
# fail with "Cannot find module '@skillsmith/core'" against a real CI
# runner despite core's dist/ already being present and correct — the
# `@skillsmith/*` workspace symlinks a second, separately-invoked
# process needs for plain (non-project-reference) import resolution are
# not reliably visible in that scenario. Building cli in this SAME,
# SINGLE turbo call sidesteps both: mcp-server's compiler still runs
# only once overall, and cli resolves `@skillsmith/core` within the
# same process invocation that just built it.
BUILD_FILTER='--filter=@skillsmith/core --filter=@skillsmith/mcp-server --filter=@skillsmith/doc-retrieval-mcp --filter=@skillsmith/cli'
# SMI-5957 correction #3 (from a SECOND real-CI failure, again never
# reproduced locally): even after correction #2, a live CI run reported
# this build succeeding (script continued past this `if`, container
# reached healthy) while `packages/core/dist/src/index.js` was actually
# absent afterward -- a turbo cache-hit ("cache hit, replaying logs")
# that does not reliably restore the cached dist/** output to this
# specific bind-mounted, cold `docker compose up` filesystem, even
# though the build task itself reports success. `--force` makes every
# task in this filter execute fresh, bypassing turbo's local cache
# (both the one baked into the image at `docker compose build` time and
# any it tries to reuse at runtime) entirely, so there is no cache
# entry whose restore-to-disk step can silently no-op.
if npx turbo run build --force $BUILD_FILTER && bash scripts/lib/check-dist-fresh.sh --write-sentinel; then
echo -e "${GREEN} ✓ Build complete.${NC}"
else
echo -e "${RED} ✗ Build failed — run npm run build inside this container to see details.${NC}"
# SMI-4689: worktree-aware hint. /app/.git as a regular file (not dir)
# is git's worktree marker. If the build failed inside a worktree
# container, the most likely cause is a stale or missing per-package
# node_modules bind-mount block in docker-compose.override.yml.
if [ -f "/app/.git" ]; then
echo -e "${YELLOW} Worktree detected. If the failure looks like 'Could not resolve <dep>' or${NC}"
echo -e "${YELLOW} 'Cannot find module <pkg>', the per-package node_modules bind mounts may${NC}"
echo -e "${YELLOW} be missing or stale. From the host main repo, run:${NC}"
echo -e "${YELLOW} ./scripts/repair-worktrees.sh${NC}"
echo -e "${YELLOW} Then restart this container: docker compose --profile dev down && up -d${NC}"
echo -e "${YELLOW} See CLAUDE.md § Worktrees and SMI-4689 for context.${NC}"
fi
exit 1
fi
else
echo -e "${GREEN} ✓ dist/ found — skipping build.${NC}"
fi
echo -e "${GREEN}[entrypoint] dist/ outputs ready.${NC}"
# ---------------------------------------------------------------------------
# SMI-5144: worktree git-discovery advisory (non-fatal).
# A worktree's /app/.git is a pointer FILE targeting a HOST absolute path
# (<host>/.git/worktrees/<name>) that does not exist in this container — only
# the worktree subtree is bind-mounted at /app, so the main repo's .git is
# absent. `git` run from /app therefore cannot discover the repo (exit 128,
# "not a git repository"). This is expected and unsupported: run git on the
# host, and keep tests hermetic (a self-created fixture repo, never
# process.cwd()) — see SMI-5140 (the hermetic-test fix) and SMI-5144. The
# main-repo container is unaffected: there /app/.git is a directory, so the
# `-f` test is false and this block is skipped entirely.
# ---------------------------------------------------------------------------
if [ -f "/app/.git" ] && ! git -C /app rev-parse --git-dir >/dev/null 2>&1; then
echo -e "${YELLOW}[entrypoint] In-container git discovery from this worktree is unavailable (expected for worktree containers; non-fatal). Run git on the host; keep tests hermetic — see SMI-5144.${NC}"
fi
echo -e "${YELLOW}[entrypoint] Validating native modules...${NC}"
# validate_native_module() — including its SMI-5784 path-aware extension for
# per-package targets — now lives in docker-entrypoint-native-per-package.sh
# (sourced near the top of this file), split out per CLAUDE.md's 500-line
# file-length convention. SHARED: called both by the root-only loop
# immediately below and by the per-package validate/rebuild function called
# later in this file.
# List of native modules to validate.
# Must match the `RUN npm rebuild …` line in the Dockerfile (the NATIVE_MODULES
# array is the canonical source; keep both in sync). With .npmrc ignore-scripts=true
# (SMI-4672), plain `npm rebuild` is a verified no-op — it exits 0 but leaves
# the binary byte-identical (SMI-5351 ground-truth investigation). ALL four
# modules therefore require --ignore-scripts=false in the rebuild loop, not just
# hnswlib-node. This includes prebuilt-binary packages (better-sqlite3,
# onnxruntime-node, esbuild): their CDN download hooks (prebuild-install) ARE
# install scripts and are blocked by ignore-scripts=true exactly as node-gyp is.
# On the already-failed path, re-downloading the prebuilt IS the intended
# self-heal. Source-only packages (hnswlib-node) have always needed the override
# so node-gyp runs (SMI-5200); this change extends that to all four modules.
# The override is scoped to the rebuild loop only (inside the
# VALIDATION_FAILED guard) so healthy restarts pay nothing.
NATIVE_MODULES=("better-sqlite3" "onnxruntime-node" "esbuild" "hnswlib-node" "@esbuild")
# Track validation status
VALIDATION_FAILED=0
for module in "${NATIVE_MODULES[@]}"; do
if validate_native_module "$module"; then
echo -e "${GREEN} ✓ ${module}${NC}"
else
echo -e "${RED} ✗ ${module} - validation failed${NC}"
VALIDATION_FAILED=1
fi
done
# If validation failed, attempt rebuild
if [ $VALIDATION_FAILED -eq 1 ]; then
echo -e "${YELLOW}[entrypoint] Native module mismatch detected. Attempting rebuild...${NC}"
for module in "${NATIVE_MODULES[@]}"; do
# All four modules require --ignore-scripts=false: plain `npm rebuild` is a
# no-op under .npmrc ignore-scripts=true, verified SMI-5351 (exits 0 but
# leaves the binary byte-identical). This applies to prebuilt-binary packages
# (better-sqlite3, onnxruntime-node, esbuild) just as much as to the
# source-only package (hnswlib-node, SMI-5200) — CDN download hooks
# (prebuild-install) are install scripts and are blocked by ignore-scripts=true.
# Re-downloading a prebuilt only happens on this already-failed path and IS
# the intended self-heal. The --ignore-scripts=false override is scoped here,
# inside the VALIDATION_FAILED guard, so healthy restarts pay nothing.
echo -e "${YELLOW} Rebuilding ${module} (first run may fetch a prebuilt)...${NC}"
# SMI-5650 (worktree): re-seed from the image stash first —
# deterministic and offline, vs npm rebuild's registry dependency.
# Falls through to npm rebuild if the seed is missing/stale/absent OR if
# SKILLSMITH_WORKTREE_NATIVE_SEED_DISABLE=1 (the SAME guard as the
# boot-time seed step above — both call-sites must honor it identically,
# else the disable var would silently no-op half of this behavior and the
# offline-path verification would not actually exercise the offline path).
if [ -f "/app/.git" ] && [ "${SKILLSMITH_WORKTREE_NATIVE_SEED_DISABLE:-}" != "1" ] && [ -d "/opt/native-seed/${module}" ]; then
rm -rf "/app/node_modules/${module:?}"/* 2>/dev/null || true
cp -a "/opt/native-seed/${module}/." "/app/node_modules/${module}/" 2>/dev/null || true
if validate_native_module "$module"; then
echo -e "${GREEN} ✓ ${module} restored from image seed (SMI-5650)${NC}"
continue
fi
fi
npm rebuild "${module}" --ignore-scripts=false || echo -e "${YELLOW} ↳ npm rebuild exited non-zero for ${module} (see output above)${NC}"
done
# Re-validate after rebuild
REBUILD_FAILED=0
FAILED_MODULES=""
for module in "${NATIVE_MODULES[@]}"; do
if ! validate_native_module "$module"; then
echo -e "${RED} ✗ ${module} - still failing after rebuild${NC}"
REBUILD_FAILED=1
FAILED_MODULES="${FAILED_MODULES:+$FAILED_MODULES }${module}"
fi
done
if [ $REBUILD_FAILED -eq 1 ]; then
echo -e "${RED}[entrypoint] Native module validation failed after rebuild.${NC}"
echo -e "${YELLOW}For verbose rebuild output (run on host): docker exec -w /app skillsmith-dev-1 sh -c 'sh scripts/lib/node-modules-mount-gate.sh && npm rebuild ${FAILED_MODULES} --ignore-scripts=false'${NC}"
# Probe CDN reachability before recommending a network-dependent recovery path.
# --max-time 5 is mandatory: a CDN hang must not stall container start (M11/F2).
if curl -fsS --max-time 5 https://registry.npmjs.org/ >/dev/null 2>&1; then
echo -e "${YELLOW}Try: docker compose down && docker compose build --no-cache${NC}"
else
echo -e "${YELLOW}Network unreachable — reconnect to the internet, then: docker compose restart dev${NC}"
fi
exit 1
fi
echo -e "${GREEN}[entrypoint] Native modules rebuilt successfully.${NC}"
fi
# SMI-5784: validate + self-heal PER-PACKAGE native-module overlays — split
# out per CLAUDE.md's 500-line file-length convention. See
# docker-entrypoint-native-per-package.sh's
# validate_and_rebuild_per_package_native_modules() for the full block +
# rationale. Deliberately a SIBLING call to the VALIDATION_FAILED block
# above, not nested inside it: nesting inside `if [ $VALIDATION_FAILED -eq 1
# ]` would skip per-package validation entirely whenever every ROOT module
# happens to validate cleanly, which is exactly the failure mode this
# section exists to catch.
validate_and_rebuild_per_package_native_modules
echo -e "${GREEN}[entrypoint] All native modules validated.${NC}"
# ---------------------------------------------------------------------------
# SMI-6050 Wave 2: restore Tier-B (build-tool / compiler platform binaries —
# turbo, Rollup/Rolldown, Astro's compiler, Lightning CSS, Tailwind Oxide,
# ruvector, workerd, etc.) binaries from the image's /opt/native-seed/tier-b
# stash (built at image-build time, see the Dockerfile's Wave 2 seed block)
# into their identical-relative-path mount targets under /app/, mirroring
# the SMI-5650 self-heal semantics above.
#
# Worktree-gated via /app/.git being a FILE (same test as the SMI-5650 seed
# block above): the main-repo container's /app/node_modules is a real,
# container-internal named volume populated by its OWN Linux `npm ci` (see
# docker-compose.yml — no host bind-mount for the main checkout), so it
# already gets correct Tier-B binaries from that install and needs no
# restore here.
#
# The seed layout mirrors the real node_modules-relative hierarchy exactly
# (Dockerfile Wave 2 fix — no flattened/sanitized names), so no path
# translation or lookup table is needed: each seed directory's path relative
# to /opt/native-seed/tier-b IS its /app/ mount target. Enumerated via the
# `.version` marker files the seed step writes (one per seeded package,
# sibling to the seeded directory) rather than a raw directory walk — this
# is what "skip .version files as data, not restore targets" means: each
# marker anchors exactly one real package directory and supplies its
# staleness-detection version, so intermediate directories (e.g. a nested
# `node_modules/astro/node_modules`, which is itself a real directory but
# not a package to restore) are never misidentified as restore targets.
#
# Version-marker-aware (the plan-review fix, "What Changes" #2/#4): a plain
# "copy only if the target is empty" is NOT sufficient — a named volume
# persists across restarts and even a `docker compose build` of a newer
# image, so a Tier-B package's version bump in package-lock.json would
# silently keep serving the OLD binary forever under an empty-only check.
# This loop compares the seed's `.version` marker against a marker it writes
# into the target itself after every successful restore
# (`<target>/.smi6050-seed-version`) and re-seeds whenever they differ
# (including the very first boot, when no target marker exists yet) or the
# target is otherwise empty/missing.
#
# Fails SOFT: in THIS wave's world (Wave 3 not yet landed), nothing in
# scripts/_lib.sh has declared a writable named volume at any of these
# targets yet — /app/<tier-b path> currently resolves through the ordinary
# read-only host bind-mount, so the restore-copy below will very likely be a
# no-op or fail outright (EROFS). That is EXPECTED and correct for this
# wave (ships the mechanism inert) — log a warning and move on, never treat
# it as fatal.
#
# Disable: SKILLSMITH_TIER_B_SEED_DISABLE=1 (registered in
# docs/internal/process/guards-and-opt-outs.md in a later wave).
# ---------------------------------------------------------------------------
if [ "${SKILLSMITH_TIER_B_SEED_DISABLE:-}" = "1" ]; then
echo -e "${YELLOW}[entrypoint] Tier-B restore disabled via SKILLSMITH_TIER_B_SEED_DISABLE=1 (SMI-6050)${NC}"
elif [ -f "/app/.git" ] && [ -d "/opt/native-seed/tier-b" ]; then
echo -e "${YELLOW}[entrypoint] Restoring Tier-B platform binaries (SMI-6050)...${NC}"
tier_b_restored=0
tier_b_current=0
tier_b_failed=0
while IFS= read -r version_file; do
[ -z "$version_file" ] && continue
seed_dir="${version_file%.version}"
rel_path="${seed_dir#/opt/native-seed/tier-b/}"
target="/app/${rel_path}"
target_marker="${target}/.smi6050-seed-version"
# Corrupted/partial seed guard (post-merge review finding): an empty
# seed directory would otherwise make `cp -a seed/. target/` succeed
# trivially (copying zero files is not an error) and then stamp the
# target "current" without restoring any real content — a silent
# false-success indistinguishable from a healthy restore. Treat an
# empty seed exactly like a missing one: skip and count as failed,
# never as restored or current.
if [ ! -d "$seed_dir" ] || [ -z "$(ls -A "$seed_dir" 2>/dev/null)" ]; then
echo -e "${YELLOW} ↳ Skipping tier-b ${rel_path} — seed directory is missing or empty (corrupted/partial image build, SMI-6050). Rebuild the image (docker compose build).${NC}"
tier_b_failed=$((tier_b_failed + 1))
continue
fi
seed_version="$(cat "$version_file" 2>/dev/null || echo "")"
current_version=""
[ -f "$target_marker" ] && current_version="$(cat "$target_marker" 2>/dev/null || echo "")"
needs_restore=0
if [ ! -d "$target" ] || [ -z "$(ls -A "$target" 2>/dev/null)" ]; then
needs_restore=1
elif [ "$current_version" != "$seed_version" ]; then
needs_restore=1
fi
if [ "$needs_restore" -eq 1 ]; then
# Clear the target's CONTENTS (not the directory itself — it may
# be an active Docker named-volume mountpoint, which can't be
# rmdir'd while mounted) before restoring. Post-merge review
# finding: `cp -a` only adds/overwrites, it never deletes — a
# version bump that REMOVES a file would otherwise leave that
# stale file behind in the target forever. `find -delete`
# failing (e.g. still the read-only host bind-mount, matching
# the existing fail-soft case) correctly breaks this `&&` chain
# into the same non-fatal warning path below.
if mkdir -p "$target" 2>/dev/null \
&& find "$target" -mindepth 1 -delete 2>/dev/null \
&& cp -a "$seed_dir/." "$target/" 2>/dev/null \
&& printf '%s' "$seed_version" >"$target_marker" 2>/dev/null; then
echo -e "${GREEN} ✓ Restored tier-b ${rel_path}@${seed_version} (SMI-6050)${NC}"
tier_b_restored=$((tier_b_restored + 1))
else
echo -e "${YELLOW} ↳ Could not restore tier-b ${rel_path} — target is likely still the read-only host bind-mount (expected until Wave 3's named-volume mount lands, SMI-6050). Non-fatal.${NC}"
tier_b_failed=$((tier_b_failed + 1))
fi
else
tier_b_current=$((tier_b_current + 1))
fi
done < <(find /opt/native-seed/tier-b -type f -name '*.version' 2>/dev/null | sort)
echo -e "${GREEN}[entrypoint] Tier-B restore: ${tier_b_restored} restored, ${tier_b_current} seed marker current, ${tier_b_failed} skipped (read-only target, non-fatal) (SMI-6050)${NC}"
elif [ -f "/app/.git" ]; then
echo -e "${YELLOW}[entrypoint] No Tier-B seed found at /opt/native-seed/tier-b — image predates SMI-6050 Wave 2; rebuild the image (docker compose build) to pick up the seed.${NC}"
fi
# SMI-7201 pair check, run as its own process: a missing or broken lib cannot stop boot.
tbp_nonce="$(cat /proc/sys/kernel/random/uuid 2>/dev/null || echo "$$-$RANDOM-$(date +%s%N)")"; tbp_rc=0; TBP_NONCE="$tbp_nonce" RED="$RED" YELLOW="$YELLOW" GREEN="$GREEN" NC="$NC" bash /app/scripts/lib/entrypoint-tier-b-pairs.sh /app/scripts/lib/check-tier-b-pairs.mjs /run/skillsmith/tier-b-pairs.state "$([ -f /app/.git ] && echo worktree || echo main)" || tbp_rc=$?
if [ "$tbp_rc" != 42 ] || [ "$(cat /run/skillsmith/.tier-b-pairs.done 2>/dev/null)" != "$tbp_nonce" ]; then # completion needs exit 42 AND this boot's nonce written by the lib; else UNAVAILABLE
echo -e "${YELLOW}[entrypoint] Tier-B pair check UNAVAILABLE (SMI-7201): scripts/lib/entrypoint-tier-b-pairs.sh is missing or failed; pairs NOT verified.${NC}"
{ mkdir -p /run/skillsmith && printf 'state=unavailable\nsource=boot\n[tier-b-pairs] UNAVAILABLE entrypoint library missing or failed\n' >/run/skillsmith/.tier-b-pairs.tmp && chmod 644 /run/skillsmith/.tier-b-pairs.tmp && mv -f /run/skillsmith/.tier-b-pairs.tmp /run/skillsmith/tier-b-pairs.state; } 2>/dev/null || echo -e "${RED}[entrypoint] Tier-B pair check: could not write the state flag /run/skillsmith/tier-b-pairs.state (state=unavailable).${NC}"
fi
# Execute the main command
exec "$@"