@soleur/opencode 3.359.18 → 3.360.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.
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env bash
2
2
  # pencil-setup dependency checker with four-tier MCP detection
3
- # Priority: (0) Headless CLI, (1) pencil CLI, (2) Desktop binary, (3) IDE extension
3
+ # Priority: (0) Headless CLI (@pen.dev/cli), (1) pencil CLI, (2) Desktop binary, (3) IDE extension
4
4
  # No set -euo pipefail: soft dependency checks and install failures
5
5
  # must not abort the script. Each check uses explicit if/then.
6
6
 
7
7
  case "$-" in
8
8
  *x*)
9
- if [ -n "${PENCIL_CLI_KEY:+x}" ]; then
9
+ if [ -n "${PEN_CLI_KEY:+x}" ] || [ -n "${PENCIL_CLI_KEY:+x}" ]; then
10
10
  printf '[FATAL] refusing to trace with a live credential set (see #7797)\n' >&2
11
11
  exit 78
12
12
  fi
@@ -22,87 +22,78 @@ for arg in "$@"; do
22
22
  esac
23
23
  done
24
24
 
25
- # -- Adapter drift check (early short-circuit) --
26
- #
27
- # Compares the installed adapter at PENCIL_ADAPTER_INSTALL_DIR (default
28
- # ~/.local/share/pencil-adapter) against the repo source. Returns:
29
- # exit 0 + OK — hashes match
30
- # exit 3 + DRIFT — hashes differ (unless --auto, which re-copies then exits 0)
31
- # exit 0 + NOT_INSTALLED — install dir absent
32
- #
33
- # Exists because the installed adapter had drifted 24 days behind repo source,
34
- # masking error-classification fixes and producing the #2630 silent-drop.
35
- # Rule: cq-pencil-mcp-silent-drop-diagnosis-checklist.
36
-
37
- if [[ "$CHECK_ADAPTER_DRIFT" == "true" ]]; then
38
- script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
39
- install_dir="${PENCIL_ADAPTER_INSTALL_DIR:-$HOME/.local/share/pencil-adapter}"
40
- installed_adapter="$install_dir/pencil-mcp-adapter.mjs"
41
- repo_adapter="$script_dir/pencil-mcp-adapter.mjs"
25
+ # Headless engine: @pen.dev/cli at an EXACT pin, installed from the committed lockfile pair in
26
+ # ./pen-cli/ into its own prefix. A separate prefix (not ~/.local) means the deprecated
27
+ # engine's old `pencil` bin link can never be reached through the new engine's bin names, and an
28
+ # old adapter copy can never find the new engine. The pin below, pen-cli/package.json and
29
+ # pen-cli/package-lock.json move together; bumping it requires a green engine-contract-probe.sh
30
+ # run first (see SKILL.md) and re-capturing the transcript fixture (a test pins its header to this).
31
+ PEN_CLI_VERSION="0.3.13"
32
+ PEN_CLI_PACKAGE="@pen.dev/cli"
33
+ PEN_CLI_PREFIX="$HOME/.local/share/pen-cli"
34
+ # Node floor, from the package's `engines.node` (>=22.19.0). One definition, compared numerically.
35
+ NODE_FLOOR_MAJOR=22
36
+ NODE_FLOOR_MINOR=19
37
+ NODE_FLOOR_PATCH=0
38
+ NODE_FLOOR="${NODE_FLOOR_MAJOR}.${NODE_FLOOR_MINOR}.${NODE_FLOOR_PATCH}"
39
+ CHECK_DEPS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
42
40
 
43
- if [[ ! -d "$install_dir" ]] || [[ ! -f "$installed_adapter" ]]; then
44
- echo "NOT_INSTALLED: $install_dir"
45
- exit 0
41
+ # Portable sha256 of a file (GNU sha256sum, else macOS/perl shasum). Prints the hex digest only;
42
+ # prints nothing and fails when neither tool exists or the file is unreadable.
43
+ sha256_of() { # <file>
44
+ if command -v sha256sum >/dev/null 2>&1; then
45
+ sha256sum -- "$1" 2>/dev/null | awk '{print $1}'
46
+ elif command -v shasum >/dev/null 2>&1; then
47
+ shasum -a 256 -- "$1" 2>/dev/null | awk '{print $1}'
48
+ else
49
+ return 1
46
50
  fi
51
+ }
47
52
 
48
- if [[ ! -f "$repo_adapter" ]]; then
49
- echo "ERROR: repo adapter not found at $repo_adapter" >&2
50
- exit 2
51
- fi
53
+ # Both installs record the sha256 of the package-lock.json they were built from in a stamp file
54
+ # inside node_modules; a node_modules whose stamp differs from (or lacks) the lockfile that sits next
55
+ # to it was not built from that lockfile. copy_adapter.sh writes the adapter's stamp, this script
56
+ # writes the engine's.
57
+ LOCK_STAMP_NAME=".soleur-package-lock.sha256"
52
58
 
53
- # `--` terminators prevent user-supplied paths beginning with `-` (e.g.,
54
- # PENCIL_ADAPTER_INSTALL_DIR=--help) from being interpreted as flags by
55
- # sha256sum / cp. Defense-in-depth; the path quoting already blocks shell
56
- # injection.
57
- installed_sha=$(sha256sum -- "$installed_adapter" | awk '{print $1}')
58
- repo_sha=$(sha256sum -- "$repo_adapter" | awk '{print $1}')
59
-
60
- # Compare EVERY runtime module copy_adapter.sh installs, not only the main
61
- # file: a stale sibling (the save sentinel, the REPL surface table) next to a
62
- # fresh adapter is exactly the state this check exists to catch. The list is
63
- # read from copy_adapter.sh so the two cannot disagree. (A while-read loop, not
64
- # mapfile: this script also runs on macOS bash 3.2.)
65
- drifted=""
66
- compared=0
59
+ # Compare EVERY runtime file copy_adapter.sh installs against an install dir, not only the main
60
+ # adapter: a stale sibling (the save sentinel, the REPL surface table) or a stale dependency
61
+ # manifest (package.json / package-lock.json) next to a fresh adapter is exactly the state the
62
+ # drift check exists to catch. The list is read from copy_adapter.sh so the two cannot disagree.
63
+ # Sets ADAPTER_COMPARED (count) and ADAPTER_DRIFTED (space-prefixed names of differing or missing
64
+ # files). Returns 2 when no file name could be parsed: an unreadable list must never read as "no
65
+ # drift". (A while-read loop, not mapfile: this script also runs on macOS bash 3.2.)
66
+ adapter_drifted_modules() { # <install_dir>
67
+ local install_dir="$1" module
68
+ ADAPTER_COMPARED=0
69
+ ADAPTER_DRIFTED=""
67
70
  while IFS= read -r module; do
68
71
  [[ -n "$module" ]] || continue
69
- compared=$((compared + 1))
70
- if [[ ! -f "$install_dir/$module" ]] || ! cmp -s -- "$script_dir/$module" "$install_dir/$module"; then
71
- drifted="$drifted $module"
72
+ ADAPTER_COMPARED=$((ADAPTER_COMPARED + 1))
73
+ if [[ ! -f "$install_dir/$module" ]] || ! cmp -s -- "$CHECK_DEPS_DIR/$module" "$install_dir/$module"; then
74
+ ADAPTER_DRIFTED="$ADAPTER_DRIFTED $module"
72
75
  fi
73
- done < <(sed -n '/^ADAPTER_FILES=(/,/^)/p' "$script_dir/copy_adapter.sh" | grep -o '"[^"]*\.mjs"' | tr -d '"')
74
- if [[ "$compared" -eq 0 ]]; then
75
- # An unreadable module list must not read as "no drift": it would compare nothing.
76
- echo "ERROR: no adapter modules parsed from $script_dir/copy_adapter.sh ADAPTER_FILES" >&2
77
- exit 2
76
+ done < <(sed -n '/^ADAPTER_FILES=(/,/^)/p' "$CHECK_DEPS_DIR/copy_adapter.sh" 2>/dev/null | grep -oE '"[^"]*\.(mjs|json)"' | tr -d '"')
77
+ [[ "$ADAPTER_COMPARED" -gt 0 ]] || return 2
78
+ # `npm ci` deletes node_modules before it installs, so an interrupted or offline copy leaves the
79
+ # new files with NO node_modules, and the adapter then dies at its first dependency import. A
80
+ # dependency manifest with no node_modules beside it is therefore drift, never "nothing to compare".
81
+ if [[ -f "$install_dir/package.json" && ! -d "$install_dir/node_modules" ]]; then
82
+ ADAPTER_DRIFTED="$ADAPTER_DRIFTED node_modules(missing: the dependency install did not complete)"
78
83
  fi
79
-
80
- if [[ -z "$drifted" ]]; then
81
- echo "OK: installed adapter matches repo (sha ${repo_sha:0:12})"
82
- exit 0
83
- fi
84
-
85
- if [[ "$AUTO_INSTALL" == "true" ]]; then
86
- # Delegate the full sync to copy_adapter.sh — it copies the adapter
87
- # AND its sibling pure modules (pencil-response-classify.mjs,
88
- # pencil-save-gate.mjs, etc.) AND runs npm ci when the install dir
89
- # has a package.json but no node_modules. A bare `cp` here would
90
- # leave the adapter ahead of its dependencies.
91
- if PENCIL_ADAPTER_INSTALL_DIR="$install_dir" bash "$script_dir/copy_adapter.sh"; then
92
- new_sha=$(sha256sum -- "$installed_adapter" | awk '{print $1}')
93
- echo "OK: re-copied adapter (was ${installed_sha:0:12} → now ${new_sha:0:12})"
94
- exit 0
95
- else
96
- echo "ERROR: copy_adapter.sh failed during drift auto-repair" >&2
97
- exit 2
84
+ # The files can all match while node_modules was built from an older lockfile (a bumped
85
+ # dependency that never got installed): compare the stamp with the lockfile in place.
86
+ if [[ -d "$install_dir/node_modules" && -f "$install_dir/package-lock.json" ]]; then
87
+ local want have=""
88
+ want=$(sha256_of "$install_dir/package-lock.json")
89
+ [[ -f "$install_dir/node_modules/$LOCK_STAMP_NAME" ]] && have=$(cat "$install_dir/node_modules/$LOCK_STAMP_NAME" 2>/dev/null)
90
+ if [[ -n "$want" && "$want" != "$have" ]]; then
91
+ ADAPTER_DRIFTED="$ADAPTER_DRIFTED node_modules(built from a different package-lock.json)"
98
92
  fi
99
93
  fi
94
+ return 0
95
+ }
100
96
 
101
- echo "DRIFT: installed ${installed_sha:0:12} != repo ${repo_sha:0:12}; differing or missing:${drifted}"
102
- echo " Run: bash $(basename "${BASH_SOURCE[0]}") --check-adapter-drift --auto"
103
- echo " Or re-run /soleur:pencil-setup to refresh the installed adapter."
104
- exit 3
105
- fi
106
97
 
107
98
  # Detect OS and architecture for platform-specific checks
108
99
  _UNAME=$(uname -s)
@@ -151,16 +142,40 @@ find_extracted_mcp_binary() {
151
142
 
152
143
  # -- Detection Functions --
153
144
 
154
- # Find a Node binary >= 22.9.0 (checks system, nvm, fnm)
145
+ # Numeric dotted-version compare against the Node floor (never lexical: 22.100.0 is above the
146
+ # floor, an older minor is below it). Accepts an optional leading "v" and ignores a prerelease/build suffix.
147
+ # Anything that is not major.minor.patch fails closed.
148
+ node_version_ok() {
149
+ local v="${1#v}" major minor patch rest
150
+ [[ "$v" =~ ^[0-9]+\.[0-9]+\.[0-9]+ ]] || return 1
151
+ major=${v%%.*}
152
+ rest=${v#*.}
153
+ minor=${rest%%.*}
154
+ patch=${rest#*.}
155
+ patch=${patch%%[!0-9]*}
156
+ major=$((10#$major)); minor=$((10#$minor)); patch=$((10#$patch))
157
+ if (( major != NODE_FLOOR_MAJOR )); then
158
+ (( major > NODE_FLOOR_MAJOR )); return
159
+ fi
160
+ if (( minor != NODE_FLOOR_MINOR )); then
161
+ (( minor > NODE_FLOOR_MINOR )); return
162
+ fi
163
+ (( patch >= NODE_FLOOR_PATCH ))
164
+ }
165
+
166
+ # Print the version of a node binary, or nothing.
167
+ _node_version() {
168
+ "$1" --version 2>/dev/null | sed 's/^v//'
169
+ }
170
+
171
+ # Find a Node binary >= the floor (checks system, nvm, fnm)
155
172
  find_node22() {
156
- local node_bin version major minor
173
+ local node_bin version
157
174
  # Check system node first
158
175
  node_bin=$(command -v node 2>/dev/null)
159
176
  if [[ -n "$node_bin" ]]; then
160
- version=$("$node_bin" --version 2>/dev/null | sed 's/^v//')
161
- major=${version%%.*}
162
- minor=$(echo "$version" | cut -d. -f2)
163
- if [[ "$major" -gt 22 || ("$major" -eq 22 && "$minor" -ge 9) ]]; then
177
+ version=$(_node_version "$node_bin")
178
+ if node_version_ok "$version"; then
164
179
  echo "$node_bin"
165
180
  return 0
166
181
  fi
@@ -171,10 +186,8 @@ find_node22() {
171
186
  local nvm_node
172
187
  for nvm_node in "$nvm_dir"/versions/node/v2[2-9]*/bin/node "$nvm_dir"/versions/node/v[3-9]*/bin/node; do
173
188
  [[ -x "$nvm_node" ]] || continue
174
- version=$("$nvm_node" --version 2>/dev/null | sed 's/^v//')
175
- major=${version%%.*}
176
- minor=$(echo "$version" | cut -d. -f2)
177
- if [[ "$major" -gt 22 || ("$major" -eq 22 && "$minor" -ge 9) ]]; then
189
+ version=$(_node_version "$nvm_node")
190
+ if node_version_ok "$version"; then
178
191
  echo "$nvm_node"
179
192
  return 0
180
193
  fi
@@ -186,10 +199,8 @@ find_node22() {
186
199
  local fnm_node
187
200
  for fnm_node in "$fnm_dir"/node-versions/v2[2-9]*/installation/bin/node "$fnm_dir"/node-versions/v[3-9]*/installation/bin/node; do
188
201
  [[ -x "$fnm_node" ]] || continue
189
- version=$("$fnm_node" --version 2>/dev/null | sed 's/^v//')
190
- major=${version%%.*}
191
- minor=$(echo "$version" | cut -d. -f2)
192
- if [[ "$major" -gt 22 || ("$major" -eq 22 && "$minor" -ge 9) ]]; then
202
+ version=$(_node_version "$fnm_node")
203
+ if node_version_ok "$version"; then
193
204
  echo "$fnm_node"
194
205
  return 0
195
206
  fi
@@ -198,28 +209,274 @@ find_node22() {
198
209
  return 1
199
210
  }
200
211
 
201
- # Detect headless CLI installed at ~/.local/node_modules/.bin/pencil
202
- # Does NOT run the binary (requires Node 22+) — checks existence and symlink target
203
- detect_headless_cli() {
204
- local pencil_bin="$HOME/.local/node_modules/.bin/pencil"
205
- [[ -e "$pencil_bin" ]] || return 1
206
- # Verify it's the headless CLI package by checking the symlink target
207
- # The headless CLI links to @pencil.dev/cli/dist/index.cjs
208
- local target
209
- target=$(readlink -f "$pencil_bin" 2>/dev/null) || return 1
210
- # Must contain the pencil CLI package path (not Desktop CLI)
211
- [[ "$target" == *"@pencil.dev/cli"* || "$target" == *"pencil-cli"* ]] || return 1
212
+ # Absolute, symlink-resolved path. The GNU-only link-resolving readlink flag is not portable to
213
+ # macOS, so: realpath when present (GNU, macOS 13+), else Node's fs.realpathSync. Prints nothing and
214
+ # fails when the path does not exist.
215
+ _realpath() {
216
+ if command -v realpath >/dev/null 2>&1; then
217
+ realpath -- "$1" 2>/dev/null
218
+ return
219
+ fi
220
+ local n
221
+ n=$(command -v node 2>/dev/null) || return 1
222
+ "$n" -e 'try{process.stdout.write(require("fs").realpathSync(process.argv[1]))}catch{process.exit(1)}' "$1" 2>/dev/null
223
+ }
224
+
225
+ # The credential, resolved once as PEN_CLI_KEY, else the deprecated PENCIL_CLI_KEY. An empty or
226
+ # whitespace-only value counts as unset. Prints the value; callers must never echo it.
227
+ resolve_pen_key() {
228
+ local k="${PEN_CLI_KEY:-}"
229
+ k="${k#"${k%%[![:space:]]*}"}"; k="${k%"${k##*[![:space:]]}"}"
230
+ if [[ -z "$k" ]]; then
231
+ k="${PENCIL_CLI_KEY:-}"
232
+ k="${k#"${k%%[![:space:]]*}"}"; k="${k%"${k##*[![:space:]]}"}"
233
+ fi
234
+ printf '%s' "$k"
235
+ }
236
+
237
+ # Print "<package name>\n<bin.pen>\n<version>" from a package.json. Any JSON-capable node will do
238
+ # (parsing needs no 22.19 features); the path is argv, never interpolated into code.
239
+ _pen_pkg_facts() {
240
+ local n
241
+ n=$(command -v node 2>/dev/null) || return 1
242
+ "$n" -e '
243
+ try {
244
+ const p = JSON.parse(require("fs").readFileSync(process.argv[1], "utf8"));
245
+ const b = p.bin && typeof p.bin === "object" ? p.bin.pen : "";
246
+ console.log(String(p.name || "")); console.log(typeof b === "string" ? b : ""); console.log(String(p.version || ""));
247
+ } catch { process.exit(1); }
248
+ ' "$1" 2>/dev/null
249
+ }
250
+
251
+ # The home directory the passwd database assigns this user (not $HOME, which a project settings
252
+ # env block can redirect). Prints nothing when it cannot be determined.
253
+ _passwd_home() {
254
+ local n
255
+ n=$(command -v node 2>/dev/null) || return 0
256
+ "$n" -e 'try{process.stdout.write(require("os").userInfo().homedir)}catch{}' 2>/dev/null
257
+ }
258
+
259
+ # "<uid> <octal mode>" of a path (Node's statSync: `stat` flags differ between GNU and BSD).
260
+ _pen_stat() {
261
+ local n
262
+ n=$(command -v node 2>/dev/null) || return 1
263
+ "$n" -e 'try{const s=require("fs").statSync(process.argv[1]);console.log(s.uid+" "+(s.mode&0o7777).toString(8))}catch{process.exit(1)}' "$1" 2>/dev/null
264
+ }
265
+
266
+ # True when <path> is <root> or lies under it, on a separator boundary.
267
+ _pen_path_inside() { # <root> <path>
268
+ [[ "$1" != "/" && ( "$2" == "$1" || "$2" == "$1"/* ) ]]
269
+ }
270
+
271
+ # Trust rule for where the engine lives, mirroring the adapter's findPenBinary(): the package
272
+ # directory must be outside the working directory and CLAUDE_PROJECT_DIR (a project cannot supply
273
+ # the binary), owned by this user, and not group- or world-writable. A project root that CONTAINS
274
+ # the home directory is the user's own tree and is exempt ONLY for the passwd home; for a $HOME the
275
+ # environment supplied that exemption is never granted (a project env block can set HOME inside the
276
+ # project). Prints the refusal cause and fails when untrusted.
277
+ _pen_trust_why() { # <real package dir> <home exempt from the ancestor rule, or empty> <engine prefix, for the remedy>
278
+ local real_pkg="$1" exempt_home="${2:-}" prefix="${3:-$PEN_CLI_PREFIX}" root realhome="" roots=() r st uid mode
279
+ if [[ -n "$exempt_home" ]]; then realhome=$(_realpath "$exempt_home"); fi
280
+ for r in "$(pwd -P 2>/dev/null)" "${CLAUDE_PROJECT_DIR:-}"; do
281
+ [[ -n "$r" ]] || continue
282
+ root=$(_realpath "$r") || continue
283
+ [[ -n "$root" && "$root" != "/" ]] || continue
284
+ if [[ -n "$realhome" ]] && _pen_path_inside "$root" "$realhome"; then continue; fi
285
+ roots+=("$root")
286
+ done
287
+ for root in ${roots[@]+"${roots[@]}"}; do
288
+ if _pen_path_inside "$root" "$real_pkg"; then
289
+ echo "the package directory is inside the working directory or the project directory"
290
+ return 1
291
+ fi
292
+ done
293
+ st=$(_pen_stat "$real_pkg") || { echo "the package directory cannot be inspected"; return 1; }
294
+ uid=${st%% *}
295
+ mode=${st##* }
296
+ if [[ "$uid" != "$(id -u)" ]]; then
297
+ echo "the package directory is not owned by the current user"
298
+ return 1
299
+ fi
300
+ if (( (8#$mode & 8#022) != 0 )); then
301
+ echo "the package directory is group- or world-writable (a umask of 002 does this); fix with: chmod -R go-w $prefix/node_modules"
302
+ return 1
303
+ fi
304
+ return 0
305
+ }
306
+
307
+ # Identity rule for the headless engine (Guard 2). The credential is only ever handed to a binary
308
+ # that is the installed @pen.dev/cli package's OWN declared bin.pen, in a package directory that
309
+ # passes the trust rule above:
310
+ # - <prefix>/node_modules/.bin/pen exists, and the package.json beside it names @pen.dev/cli;
311
+ # - realpath(.bin/pen) is EQUAL to realpath(<package dir>/<declared bin.pen>), and that target
312
+ # is a regular file inside the package directory on a separator boundary (no sibling-prefix
313
+ # match, no escape);
314
+ # - only `pen` is read: the `pencil` alias is never a candidate and there is no PATH fallback.
315
+ # Prints one line: "OK<TAB><resolved binary>", "NOTINSTALLED<TAB><cause>" or "WHY<TAB><cause>"; always
316
+ # returns 0. Does NOT run the binary. The adapter's findPenBinary() applies the same rule (shared
317
+ # table: test/fixtures/pen-identity-cases.tsv).
318
+ _pen_inspect_prefix() { # <prefix> <home exempt from the ancestor rule, or empty>
319
+ local prefix="$1" exempt_home="${2:-}"
320
+ local bin="$prefix/node_modules/.bin/pen"
321
+ local pkgdir="$prefix/node_modules/$PEN_CLI_PACKAGE"
322
+ local pkgjson="$pkgdir/package.json"
323
+ local facts name declared real_bin real_pkg expected why
324
+ if ! real_pkg=$(_realpath "$pkgdir") || [[ -z "$real_pkg" ]]; then
325
+ printf 'NOTINSTALLED\t%s is not installed under %s\n' "$PEN_CLI_PACKAGE" "$prefix"; return 0
326
+ fi
327
+ if ! why=$(_pen_trust_why "$real_pkg" "$exempt_home" "$prefix"); then printf 'WHY\t%s\n' "$why"; return 0; fi
328
+ [[ -f "$pkgjson" ]] || { printf 'WHY\tits package.json is unreadable\n'; return 0; }
329
+ if ! facts=$(_pen_pkg_facts "$pkgjson"); then printf 'WHY\tits package.json is unreadable\n'; return 0; fi
330
+ name=$(printf '%s\n' "$facts" | sed -n 1p)
331
+ declared=$(printf '%s\n' "$facts" | sed -n 2p)
332
+ [[ "$name" == "$PEN_CLI_PACKAGE" ]] || { printf 'WHY\tthe package name is not %s\n' "$PEN_CLI_PACKAGE"; return 0; }
333
+ [[ -n "$declared" ]] || { printf 'WHY\tthe package declares no pen bin\n'; return 0; }
334
+ if ! expected=$(_realpath "$real_pkg/$declared") || [[ -z "$expected" ]]; then
335
+ printf 'WHY\tthe declared pen bin is missing\n'; return 0
336
+ fi
337
+ [[ "$expected" == "$real_pkg"/* ]] || { printf 'WHY\tthe declared pen bin resolves outside the package directory\n'; return 0; }
338
+ [[ -f "$expected" ]] || { printf 'WHY\tthe declared pen bin is not a regular file\n'; return 0; }
339
+ if ! real_bin=$(_realpath "$bin") || [[ -z "$real_bin" ]]; then printf 'WHY\t.bin/pen is missing\n'; return 0; fi
340
+ [[ "$real_bin" == "$expected" ]] || { printf 'WHY\t.bin/pen does not point at the package'"'"'s declared pen bin\n'; return 0; }
341
+ printf 'OK\t%s\n' "$real_bin"
342
+ }
343
+
344
+ # Which engine prefix is used, mirroring findPenBinary(): the PASSWD home's prefix first (the ancestor
345
+ # exemption applies to it alone), then $HOME's when it differs (never exempt: a project env block can
346
+ # set HOME inside the project). The first candidate that passes wins; when none does, the cause comes
347
+ # from the first candidate that has a package installed, else from $HOME's (so the advice names a
348
+ # path the --auto install actually writes). An explicit prefix (the install staging directory) is
349
+ # inspected on its own, with the exemption only when $HOME is the passwd home.
350
+ _pen_inspect() { # [prefix] (default: the candidate prefixes, passwd home first)
351
+ local passwd_home line first_why="" last="" prefixes=() exempts=() i
352
+ passwd_home=$(_passwd_home)
353
+ if [[ -n "${1:-}" ]]; then
354
+ if [[ -n "$passwd_home" && "$HOME" == "$passwd_home" ]]; then
355
+ _pen_inspect_prefix "$1" "$HOME"
356
+ else
357
+ _pen_inspect_prefix "$1" ""
358
+ fi
359
+ return 0
360
+ fi
361
+ if [[ -n "$passwd_home" ]]; then prefixes+=("$passwd_home/.local/share/pen-cli"); exempts+=("$passwd_home"); fi
362
+ if [[ "$HOME" != "$passwd_home" ]]; then prefixes+=("$PEN_CLI_PREFIX"); exempts+=(""); fi
363
+ for i in "${!prefixes[@]}"; do
364
+ line=$(_pen_inspect_prefix "${prefixes[$i]}" "${exempts[$i]}")
365
+ case "${line%%$'\t'*}" in
366
+ OK) printf '%s\n' "$line"; return 0 ;;
367
+ WHY) [[ -n "$first_why" ]] || first_why="$line" ;;
368
+ esac
369
+ last="$line"
370
+ done
371
+ # None passed: the first installed-but-refused candidate explains it; else "not installed" under the
372
+ # last candidate ($HOME's when it differs from the passwd home, the one --auto writes to).
373
+ printf '%s\n' "${first_why:-$last}"
374
+ }
375
+
376
+ # Prints the resolved binary path and succeeds when the engine passes the identity rule.
377
+ detect_headless_cli() { # [prefix]
378
+ local line
379
+ line=$(_pen_inspect "${1:-}")
380
+ [[ "${line%%$'\t'*}" == "OK" ]] || return 1
381
+ printf '%s\n' "${line#*$'\t'}"
382
+ }
383
+
384
+ # The installed @pen.dev/cli version (empty when the package.json is missing or unreadable).
385
+ pen_cli_installed_version() {
386
+ local pkgjson="$PEN_CLI_PREFIX/node_modules/$PEN_CLI_PACKAGE/package.json" facts
387
+ [[ -f "$pkgjson" ]] || return 0
388
+ facts=$(_pen_pkg_facts "$pkgjson") || return 0
389
+ printf '%s\n' "$facts" | sed -n 3p
390
+ }
391
+
392
+ # True when an install exists at a version other than the pin. Without --auto that is only
393
+ # reported; under --auto it counts as "needs install" (the lockfile is the way back to the pin).
394
+ pen_cli_pin_drifted() {
395
+ local installed
396
+ installed=$(pen_cli_installed_version)
397
+ [[ -n "$installed" && "$installed" != "$PEN_CLI_VERSION" ]]
398
+ }
399
+
400
+ # The sha256 of the committed engine lockfile (what the install is built from).
401
+ pen_cli_lock_sha() {
402
+ sha256_of "$CHECK_DEPS_DIR/pen-cli/package-lock.json"
403
+ }
404
+
405
+ # True when the installed engine tree was built from the lockfile now committed (its stamp equals
406
+ # the lockfile hash). A tree with no stamp predates the stamp: an old install at the right VERSION
407
+ # still lacks later lockfile changes (the undici `overrides` entry), so it counts as not current.
408
+ pen_cli_lock_current() { # [prefix]
409
+ local prefix="${1:-$PEN_CLI_PREFIX}" want have=""
410
+ want=$(pen_cli_lock_sha)
411
+ [[ -n "$want" ]] || return 1
412
+ [[ -f "$prefix/node_modules/$LOCK_STAMP_NAME" ]] && have=$(cat "$prefix/node_modules/$LOCK_STAMP_NAME" 2>/dev/null)
413
+ [[ "$want" == "$have" ]]
414
+ }
415
+
416
+ # An engine swap interrupted between its two renames leaves no engine at the prefix and the only
417
+ # working one in `<prefix>.old`. Put it back; nothing is deleted. Safe to call at any time.
418
+ restore_interrupted_engine_swap() {
419
+ local old="$PEN_CLI_PREFIX.old"
420
+ if [[ ! -e "$PEN_CLI_PREFIX" && -d "$old" ]]; then
421
+ if mv -- "$old" "$PEN_CLI_PREFIX"; then
422
+ echo " [info] restored the previous $PEN_CLI_PACKAGE engine from $old (an earlier reinstall was interrupted before the swap finished)"
423
+ else
424
+ echo " [FAILED] cannot restore the previous engine from $old to $PEN_CLI_PREFIX"
425
+ return 1
426
+ fi
427
+ fi
428
+ return 0
429
+ }
430
+
431
+ # True when --auto has something to do for the engine: not installed (or not trusted), off the
432
+ # pin, or built from another lockfile than the committed one.
433
+ pen_cli_needs_install() {
434
+ ! detect_headless_cli >/dev/null || pen_cli_pin_drifted || ! pen_cli_lock_current
435
+ }
436
+
437
+ # One-line advisories about the install state. Never fatal, never uses the deprecated package.
438
+ warn_pen_cli_state() {
439
+ local legacy_pkg="$HOME/.local/node_modules/@pencil.dev/cli"
440
+ if [[ -d "$legacy_pkg" ]]; then
441
+ # "It is not used" is only true of an adapter that targets the new engine. A stale installed
442
+ # adapter may still resolve the deprecated package, so say how to sync it instead.
443
+ local install_dir="${PENCIL_ADAPTER_INSTALL_DIR:-$HOME/.local/share/pencil-adapter}"
444
+ if [[ -f "$install_dir/pencil-mcp-adapter.mjs" ]] && { ! adapter_drifted_modules "$install_dir" || [[ -n "$ADAPTER_DRIFTED" ]]; }; then
445
+ echo " [warn] Deprecated @pencil.dev/cli found under ~/.local/node_modules, and the installed adapter at $install_dir is out of date (it may still target it). Sync with: bash check_deps.sh --check-adapter-drift --auto"
446
+ else
447
+ echo " [warn] Deprecated @pencil.dev/cli found under ~/.local/node_modules: it is not used. The headless tier runs $PEN_CLI_PACKAGE from $PEN_CLI_PREFIX. Remove with: npm uninstall --prefix ~/.local @pencil.dev/cli"
448
+ fi
449
+ fi
450
+ local installed
451
+ installed=$(pen_cli_installed_version)
452
+ if [[ -n "$installed" && "$installed" != "$PEN_CLI_VERSION" ]]; then
453
+ if [[ "$AUTO_INSTALL" == "true" ]]; then
454
+ echo " [warn] $PEN_CLI_PACKAGE $installed is installed but the pin is $PEN_CLI_VERSION; re-installing from the lockfile"
455
+ else
456
+ echo " [warn] $PEN_CLI_PACKAGE $installed is installed but the pin is $PEN_CLI_VERSION; re-run with --auto to reinstall from the lockfile"
457
+ fi
458
+ elif [[ -n "$installed" ]] && ! pen_cli_lock_current; then
459
+ # At the pin, but built from an older lockfile (or before the lock stamp existed): later lockfile
460
+ # changes (a dependency override) are missing. Without --auto the engine is used as it is; with
461
+ # --auto it is reinstalled (~1 GB), so say which of the two will happen.
462
+ if [[ "$AUTO_INSTALL" == "true" ]]; then
463
+ echo " [warn] $PEN_CLI_PACKAGE $installed predates the committed lockfile (its lock stamp is missing or differs); --auto is re-installing it from the lockfile (~1 GB)"
464
+ else
465
+ echo " [warn] $PEN_CLI_PACKAGE $installed predates the committed lockfile (its lock stamp is missing or differs); it is used as it is, and --auto will reinstall it from the lockfile (~1 GB)"
466
+ fi
467
+ fi
212
468
  return 0
213
469
  }
214
470
 
215
471
  # Check if the pencil CLI in PATH is pencil.dev (not evolus/pencil)
216
472
  detect_pencil_cli() {
217
473
  command -v pencil >/dev/null 2>&1 || return 1
218
- # Negative guard: if the PATH pencil resolves to the headless CLI package,
474
+ # Negative guard: if the PATH pencil resolves to either headless CLI package (the deprecated
475
+ # @pencil.dev/cli or the maintained @pen.dev/cli, whose second bin is also named `pencil`),
219
476
  # skip it for Tier 1 (handled by Tier 0)
220
477
  local resolved
221
- resolved=$(readlink -f "$(command -v pencil)" 2>/dev/null)
222
- if [[ "$resolved" == *"@pencil.dev/cli"* || "$resolved" == *"pencil-cli"* ]]; then
478
+ resolved=$(_realpath "$(command -v pencil)")
479
+ if [[ "$resolved" == *"@pencil.dev/cli"* || "$resolved" == *"@pen.dev/cli"* || "$resolved" == *"pencil-cli"* ]]; then
223
480
  return 1
224
481
  fi
225
482
  # Guard against evolus/pencil name collision
@@ -415,23 +672,70 @@ auto_launch_desktop() {
415
672
  # -- Tier Functions (early-exit pattern) --
416
673
 
417
674
  try_headless_cli_tier() {
418
- detect_headless_cli || return 1
675
+ local pen_bin inspected
676
+ if ! pen_bin=$(detect_headless_cli); then
677
+ # Say why the tier was skipped (the specific cause, not a generic message); a silent skip leaves
678
+ # the user guessing. Under --auto the install already ran, so the hint would only repeat what
679
+ # its own output says.
680
+ inspected=$(_pen_inspect)
681
+ if [[ "${inspected%%$'\t'*}" == "WHY" ]]; then
682
+ echo " [skip] $PEN_CLI_PACKAGE at $PEN_CLI_PREFIX failed the identity check: ${inspected#*$'\t'}"
683
+ if [[ "$AUTO_INSTALL" == "true" ]]; then
684
+ echo " (the --auto reinstall above did not fix it)"
685
+ else
686
+ echo " Re-run with --auto to reinstall it from the committed lockfile"
687
+ fi
688
+ elif [[ "$AUTO_INSTALL" != "true" ]]; then
689
+ echo " [info] Headless CLI ($PEN_CLI_PACKAGE) not installed; re-run with --auto to install it from the committed lockfile"
690
+ fi
691
+ return 1
692
+ fi
419
693
  # Node version gate
420
694
  local node_bin
421
695
  node_bin=$(find_node22)
422
696
  if [[ -z "$node_bin" ]]; then
423
- echo " [skip] Headless CLI found but Node >= 22.9.0 not available"
424
- echo " Install Node 22+ via nvm: nvm install 22"
697
+ echo " [skip] Headless CLI found but Node >= $NODE_FLOOR not available"
698
+ echo " Install Node 22+ via nvm: nvm install 22 (the engine requires >= $NODE_FLOOR)"
425
699
  return 1
426
700
  fi
427
- # Auth check — must use the found Node 22+ binary to run pencil
428
- local pencil_bin="$HOME/.local/node_modules/.bin/pencil"
429
- local pencil_target
430
- pencil_target=$(readlink -f "$pencil_bin" 2>/dev/null)
431
- if ! PENCIL_CLI_KEY="${PENCIL_CLI_KEY:-}" "$node_bin" "$pencil_target" status >/dev/null 2>&1; then
432
- echo " [skip] Headless CLI found but auth failed"
433
- echo " Run: $pencil_bin login"
434
- echo " Or set PENCIL_CLI_KEY environment variable"
701
+ # Auth check: PEN_CLI_KEY (or the deprecated PENCIL_CLI_KEY fallback; empty counts as unset) is
702
+ # handed to `pen status` as PEN_CLI_KEY only. A fail-open engine still runs with a bad key, so
703
+ # exit 0 is not enough: the reply must report Active. Output carries account details and is
704
+ # never printed.
705
+ local key status_out
706
+ key=$(resolve_pen_key)
707
+ if [[ -z "$key" ]]; then
708
+ echo " [skip] Headless CLI found but auth failed: PEN_CLI_KEY is not set"
709
+ echo " Set the PEN_CLI_KEY environment variable (the adapter needs it; a pen login is not enough)"
710
+ return 1
711
+ fi
712
+ # The key reaches the child through a subshell's environment, never through an argument list:
713
+ # `env NAME=value cmd` would put it in env's argv, readable by any local user via ps. The child
714
+ # also gets a minimal environment (no unrelated tokens, no deprecated name), keeping what it
715
+ # needs to run and reach the network.
716
+ local esc
717
+ esc=$(printf '\033')
718
+ # `timeout` (GNU coreutils; `gtimeout` on macOS with coreutils) bounds an unreachable engine; with
719
+ # neither installed the probe runs unbounded, as before.
720
+ local tmo=""
721
+ if command -v timeout >/dev/null 2>&1; then tmo="timeout 20"; elif command -v gtimeout >/dev/null 2>&1; then tmo="gtimeout 20"; fi
722
+ if status_out=$(
723
+ unset PENCIL_CLI_KEY
724
+ for v in $(compgen -e); do
725
+ case "$v" in
726
+ HOME|PATH|LANG|LC_*|TERM|TMPDIR|TMP|TEMP|USER|LOGNAME|SHELL|XDG_*|*_PROXY|*_proxy|NODE_EXTRA_CA_CERTS|SSL_CERT_FILE|SSL_CERT_DIR|NO_COLOR|PEN_CLI_KEY) ;;
727
+ *) unset "$v" 2>/dev/null ;;
728
+ esac
729
+ done
730
+ PEN_CLI_KEY="$key"
731
+ export PEN_CLI_KEY
732
+ # shellcheck disable=SC2086 # $tmo is "timeout 20", "gtimeout 20" or empty
733
+ exec $tmo "$node_bin" "$pen_bin" status 2>&1
734
+ ) && grep -q 'Active' < <(printf '%s' "$status_out" | LC_ALL=C sed "s/${esc}\[[0-9;?:<=>]*[@-~]//g"); then
735
+ :
736
+ else
737
+ echo " [skip] Headless CLI found but could not confirm Active (key invalid or engine unreachable)"
738
+ echo " Set a valid PEN_CLI_KEY environment variable (PENCIL_CLI_KEY is still read as a deprecated fallback)"
435
739
  return 1
436
740
  fi
437
741
  echo " [ok] Headless CLI (Tier 0)"
@@ -453,7 +757,7 @@ attempt_headless_install() {
453
757
  local node_bin
454
758
  node_bin=$(find_node22)
455
759
  if [[ -z "$node_bin" ]]; then
456
- echo " [skip] Cannot auto-install headless CLI: Node >= 22.9.0 not available"
760
+ echo " [skip] Cannot auto-install headless CLI: Node >= $NODE_FLOOR not available"
457
761
  return 1
458
762
  fi
459
763
  local npm_bin
@@ -463,20 +767,80 @@ attempt_headless_install() {
463
767
  echo " [skip] Cannot auto-install headless CLI: npm not found"
464
768
  return 1
465
769
  fi
466
- echo " [installing] Headless CLI to ~/.local..."
467
- # Package name is @pencil.dev/cli (not @anthropic-ai/pencil-cli — that 404s).
468
- # The detect_headless_cli function on line 182 already expects @pencil.dev/cli
469
- # in the symlink target; the previous install command was inconsistent.
470
- # Pinned to 0.2.9: the adapter's REPL surface table (pencil-repl-surface.mjs)
471
- # is that version's signature list. Bumping this pin requires running
472
- # engine-contract-probe.sh first (see #11143; migration tracked in #11156).
473
- if "$npm_bin" install --prefix "$HOME/.local" @pencil.dev/cli@0.2.9 2>&1; then
474
- detect_headless_cli && return 0
475
- echo " [FAILED] Install succeeded but binary not found"
476
- else
477
- echo " [FAILED] npm install returned non-zero"
770
+ local src_dir
771
+ src_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/pen-cli"
772
+ [[ "$src_dir" == /* && "$PEN_CLI_PREFIX" == /* ]] || { echo " [FAILED] install paths are not absolute"; return 1; }
773
+ if [[ ! -f "$src_dir/package.json" || ! -f "$src_dir/package-lock.json" ]]; then
774
+ echo " [FAILED] Missing committed lockfile pair in $src_dir (package.json, package-lock.json)"
775
+ return 1
478
776
  fi
479
- return 1
777
+ echo " [installing] Headless CLI $PEN_CLI_PACKAGE@$PEN_CLI_VERSION to $PEN_CLI_PREFIX (lockfile, scripts ignored; ~1 GB, up to a few minutes on a cold cache)..."
778
+ # Install into a STAGING prefix and swap it in only after it passes the identity rule: a failed
779
+ # reinstall (offline, a bad lockfile) must never remove an engine that works. The staging tree is
780
+ # a sibling of the prefix so the swap is a rename on one filesystem.
781
+ local stage="$PEN_CLI_PREFIX.new" old="$PEN_CLI_PREFIX.old"
782
+ # `$old` is NOT cleared here: after an interrupted swap it holds the only working engine, so it
783
+ # is restored first and is deleted only once the new install has been accepted (below).
784
+ restore_interrupted_engine_swap || return 1
785
+ rm -rf -- "$stage"
786
+ (umask 022; mkdir -p "$stage") || { echo " [FAILED] cannot create $stage"; return 1; }
787
+ local f
788
+ for f in package.json package-lock.json; do
789
+ install -m 0644 -- "$src_dir/$f" "$stage/$f" || { echo " [FAILED] cannot copy $f"; rm -rf -- "$stage"; return 1; }
790
+ done
791
+ # `npm ci` from the pinned lockfile: every transitive version and integrity hash is fixed, and
792
+ # the credential is removed from the environment so install-time code never sees it. Lifecycle
793
+ # scripts are ignored (verified: the engine opens, exports and screenshots without them, see
794
+ # engine-contract-probe.sh). The old ~/.local/node_modules tree is deliberately left alone.
795
+ # Node's directory goes first on PATH so npm's `#!/usr/bin/env node` uses the vetted binary.
796
+ # umask 022 (and the chmod below) because the adapter refuses a group- or world-writable package
797
+ # directory: under a umask of 002 npm would otherwise create exactly that and lock the user out.
798
+ # Only the tail of npm's output is shown (a failing resolve can print screens of it); the exit
799
+ # status is the command's own, captured before the output is trimmed.
800
+ local npm_out npm_rc
801
+ npm_out=$(umask 022; cd "$stage" && env -u PEN_CLI_KEY -u PENCIL_CLI_KEY PATH="$(dirname "$node_bin"):$PATH" "$npm_bin" ci --ignore-scripts 2>&1)
802
+ npm_rc=$?
803
+ [[ -z "$npm_out" ]] || printf '%s\n' "$npm_out" | tail -20
804
+ if [[ "$npm_rc" -ne 0 ]]; then
805
+ echo " [FAILED] npm ci returned non-zero"
806
+ rm -rf -- "$stage"
807
+ [[ ! -e "$PEN_CLI_PREFIX" ]] || echo " The engine already installed at $PEN_CLI_PREFIX was left untouched."
808
+ return 1
809
+ fi
810
+ # Whatever npm created (a hard-coded 775 included), nothing may stay group- or world-writable.
811
+ chmod -R go-w "$stage/node_modules" 2>/dev/null || true
812
+ local why
813
+ if ! detect_headless_cli "$stage" >/dev/null; then
814
+ why=$(_pen_inspect "$stage")
815
+ echo " [FAILED] Install succeeded but the $PEN_CLI_PACKAGE binary was not found or failed the identity check: ${why#*$'\t'}"
816
+ rm -rf -- "$stage"
817
+ [[ ! -e "$PEN_CLI_PREFIX" ]] || echo " The engine already installed at $PEN_CLI_PREFIX was left untouched."
818
+ return 1
819
+ fi
820
+ (umask 022; pen_cli_lock_sha > "$stage/node_modules/$LOCK_STAMP_NAME") 2>/dev/null || true
821
+ # The new tree is proven. Only now is an `$old` left by an earlier attempt expendable.
822
+ rm -rf -- "$old"
823
+ if [[ -e "$PEN_CLI_PREFIX" ]]; then
824
+ mv -- "$PEN_CLI_PREFIX" "$old" || { echo " [FAILED] cannot move the existing engine aside"; rm -rf -- "$stage"; return 1; }
825
+ fi
826
+ if ! mv -- "$stage" "$PEN_CLI_PREFIX"; then
827
+ echo " [FAILED] cannot move the new engine into place"
828
+ [[ ! -e "$old" ]] || mv -- "$old" "$PEN_CLI_PREFIX"
829
+ rm -rf -- "$stage"
830
+ return 1
831
+ fi
832
+ if ! detect_headless_cli >/dev/null; then
833
+ why=$(_pen_inspect)
834
+ echo " [FAILED] Installed, but $PEN_CLI_PREFIX does not pass the identity check: ${why#*$'\t'}"
835
+ # Roll back: the previous engine (if there was one) goes back; a rejected new tree is not kept.
836
+ if [[ -d "$old" ]]; then
837
+ rm -rf -- "$PEN_CLI_PREFIX"
838
+ mv -- "$old" "$PEN_CLI_PREFIX" && echo " The previous engine was restored."
839
+ fi
840
+ return 1
841
+ fi
842
+ rm -rf -- "$old"
843
+ return 0
480
844
  }
481
845
 
482
846
  try_cli_tier() {
@@ -536,27 +900,128 @@ try_ide_tier() {
536
900
  return 0
537
901
  }
538
902
 
903
+ # Sourced (by tests): expose the functions without running any tier.
904
+ if [[ "${BASH_SOURCE[0]}" != "$0" ]]; then
905
+ return 0
906
+ fi
907
+
908
+ # -- Adapter drift check (short-circuits the tier flow) --
909
+ #
910
+ # Compares the installed adapter files at PENCIL_ADAPTER_INSTALL_DIR (default
911
+ # ~/.local/share/pencil-adapter) against the repo source. Exits:
912
+ # 0 + OK - every file matches
913
+ # 3 + DRIFT - a file differs or is missing, or node_modules was not built from the
914
+ # package-lock.json in place (unless --auto: installs the engine FIRST when it
915
+ # is missing, off the pin or built from another lockfile, then re-copies the
916
+ # adapter and its dependencies, then exits 0)
917
+ # 0 + NOT_INSTALLED - install dir absent
918
+ # 2 - the file list is unreadable, or an --auto repair step failed (engine
919
+ # install: the installed adapter is left unchanged; adapter dependency
920
+ # install: the cause is printed)
921
+ #
922
+ # Exists because the installed adapter had drifted 24 days behind repo source, masking
923
+ # error-classification fixes and producing the #2630 silent-drop.
924
+ # Rule: ex-cq-pencil-mcp-silent-drop-diagnosis-checklist (retired id, kept as the provenance).
925
+ run_adapter_drift_check() {
926
+ local install_dir="${PENCIL_ADAPTER_INSTALL_DIR:-$HOME/.local/share/pencil-adapter}"
927
+ local installed_adapter="$install_dir/pencil-mcp-adapter.mjs"
928
+ local repo_adapter="$CHECK_DEPS_DIR/pencil-mcp-adapter.mjs"
929
+
930
+ if [[ ! -d "$install_dir" ]] || [[ ! -f "$installed_adapter" ]]; then
931
+ echo "NOT_INSTALLED: $install_dir"
932
+ exit 0
933
+ fi
934
+
935
+ if [[ ! -f "$repo_adapter" ]]; then
936
+ echo "ERROR: repo adapter not found at $repo_adapter" >&2
937
+ exit 2
938
+ fi
939
+
940
+ # `--` terminators prevent user-supplied paths beginning with `-` (e.g.,
941
+ # PENCIL_ADAPTER_INSTALL_DIR=--help) from being interpreted as flags by
942
+ # sha256sum / cp. Defense-in-depth; the path quoting already blocks shell
943
+ # injection.
944
+ local installed_sha repo_sha
945
+ installed_sha=$(sha256_of "$installed_adapter")
946
+ repo_sha=$(sha256_of "$repo_adapter")
947
+
948
+ if ! adapter_drifted_modules "$install_dir"; then
949
+ echo "ERROR: no adapter modules parsed from $CHECK_DEPS_DIR/copy_adapter.sh ADAPTER_FILES" >&2
950
+ exit 2
951
+ fi
952
+
953
+ if [[ -z "$ADAPTER_DRIFTED" ]]; then
954
+ echo "OK: installed adapter matches repo (sha ${repo_sha:0:12})"
955
+ exit 0
956
+ fi
957
+
958
+ if [[ "$AUTO_INSTALL" == "true" ]]; then
959
+ # Engine FIRST: the new adapter refuses to start without its engine, so the adapter is never
960
+ # copied ahead of it. A failed engine install leaves the installed adapter (and any engine
961
+ # that already worked, see attempt_headless_install) exactly as they were.
962
+ if pen_cli_needs_install; then
963
+ echo " [info] Headless engine missing, not at the pin $PEN_CLI_VERSION, or built from another lockfile: installing it before the adapter is updated"
964
+ if ! attempt_headless_install; then
965
+ echo "ERROR: the headless engine ($PEN_CLI_PACKAGE@$PEN_CLI_VERSION) could not be installed; the installed adapter was NOT changed. Fix the cause above and re-run: bash check_deps.sh --check-adapter-drift --auto" >&2
966
+ exit 2
967
+ fi
968
+ fi
969
+ # Delegate the full sync to copy_adapter.sh: it copies the adapter AND its sibling modules
970
+ # and manifests, and runs npm ci when the lockfile changed. A bare `cp` would leave the
971
+ # adapter ahead of its dependencies.
972
+ local copy_rc=0
973
+ PENCIL_ADAPTER_INSTALL_DIR="$install_dir" bash "$CHECK_DEPS_DIR/copy_adapter.sh" || copy_rc=$?
974
+ if [[ "$copy_rc" -ne 0 ]]; then
975
+ case "$copy_rc" in
976
+ 3) echo "ERROR: copy_adapter.sh could not install the adapter's dependencies (npm ci failed, see above); the installed adapter and its node_modules were left unchanged. Re-run: bash check_deps.sh --check-adapter-drift --auto" >&2 ;;
977
+ *) echo "ERROR: copy_adapter.sh failed (exit $copy_rc) during drift auto-repair" >&2 ;;
978
+ esac
979
+ exit 2
980
+ fi
981
+ local new_sha
982
+ new_sha=$(sha256_of "$installed_adapter")
983
+ echo "OK: re-copied adapter (was ${installed_sha:0:12} -> now ${new_sha:0:12})"
984
+ exit 0
985
+ fi
986
+
987
+ echo "DRIFT: installed ${installed_sha:0:12} != repo ${repo_sha:0:12}; differing or missing:${ADAPTER_DRIFTED}"
988
+ echo " Run: bash $(basename "${BASH_SOURCE[0]}") --check-adapter-drift --auto (also installs the engine when it is missing)"
989
+ echo " Or re-run /soleur:pencil-setup to refresh the installed adapter."
990
+ exit 3
991
+ }
992
+
993
+ if [[ "$CHECK_ADAPTER_DRIFT" == "true" ]]; then
994
+ run_adapter_drift_check
995
+ fi
996
+
539
997
  # -- Main Flow --
540
998
 
541
999
  echo "=== Pencil Setup Dependency Check ==="
542
1000
  echo
543
1001
 
1002
+ # An interrupted engine reinstall may have left the working engine in <prefix>.old
1003
+ restore_interrupted_engine_swap || true
1004
+
1005
+ # Leftover deprecated engine / version drift against the pin (advisory only)
1006
+ warn_pen_cli_state
1007
+
544
1008
  # Warn about evolus/pencil collision
545
- if ! detect_pencil_cli && ! detect_headless_cli && command -v pencil >/dev/null 2>&1; then
1009
+ if ! detect_pencil_cli && ! detect_headless_cli >/dev/null && command -v pencil >/dev/null 2>&1; then
546
1010
  echo " [info] pencil CLI found but is not pencil.dev (possible evolus/pencil)"
547
1011
  fi
548
1012
 
549
1013
  # Try tiers in priority order -- first success wins
550
- # Tier 0: Headless CLI (no GUI required)
1014
+ # Tier 0: Headless CLI, @pen.dev/cli (no GUI required)
551
1015
  # Tier 1: Desktop CLI (needs Desktop running)
552
1016
  # Tier 2: Desktop binary (needs Desktop running)
553
1017
  # Tier 3: IDE extension
554
- if ! try_headless_cli_tier; then
555
- # Auto-install headless CLI if --auto
556
- if [[ "$AUTO_INSTALL" == "true" ]] && ! detect_headless_cli; then
557
- attempt_headless_install && try_headless_cli_tier
558
- fi
1018
+ # --auto installs when the engine is missing, not trusted, installed at a version other than the pin
1019
+ # (the version advice would otherwise be a dead end) or built from another lockfile than the
1020
+ # committed one; the lockfile is the way back to the pin.
1021
+ if [[ "$AUTO_INSTALL" == "true" ]] && pen_cli_needs_install; then
1022
+ attempt_headless_install || true
559
1023
  fi
1024
+ try_headless_cli_tier || true
560
1025
  [[ -n "$PREFERRED_MODE" ]] || try_cli_tier || try_desktop_tier || try_ide_tier
561
1026
 
562
1027
  # -- Result --