glasspane-install 1.25.2 → 1.27.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.
Files changed (4) hide show
  1. package/README.md +5 -1
  2. package/cli.js +357 -62
  3. package/glasspane.js +89 -1
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -17,7 +17,11 @@ npx glasspane-install
17
17
 
18
18
  # 2) Fetch, then run: install.sh clones the pinned release tag. Two steps on
19
19
  # purpose — piped into `sh`, a curl that fails leaves stdin empty and the pipeline exits 0.
20
- curl -fsSL https://raw.githubusercontent.com/jingzhao-l/GlassPane/main/install.sh -o /tmp/gp-install.sh && sh /tmp/gp-install.sh
20
+ # The landing file comes from `mktemp`: `/tmp` is mode 1777, and the sticky bit only stops
21
+ # another account from deleting *your* file — it does not stop them from creating
22
+ # `/tmp/gp-install.sh -> ~/.bashrc` first, and `curl -o` follows that link and truncates
23
+ # the target as *you*.
24
+ GP="$(mktemp "${TMPDIR:-/tmp/}gp-install.XXXXXXXX")" && curl -fsSL https://raw.githubusercontent.com/jingzhao-l/GlassPane/main/install.sh -o "$GP" && sh "$GP" && rm -f "$GP"
21
25
 
22
26
  # 3) From an existing checkout
23
27
  node installer/cli.js
package/cli.js CHANGED
@@ -27,6 +27,44 @@ import path from 'node:path'
27
27
  import process from 'node:process'
28
28
  import net from 'node:net'
29
29
 
30
+ /**
31
+ * One value, quoted as one shell word — the installer-side copy of the product rule.
32
+ *
33
+ * The rule already has three executable bodies in this product (`mcp-shell/src/errors.ts`'s
34
+ * `quoteShellArg`, `engine/Sources/GlassPaneEngine/StateRoot.swift`'s `RemedyCommand.quote`,
35
+ * `updater/lib/shell-quote.js`), and a fourth is legitimate here for the same reason the third
36
+ * one is: this package ships standalone — `installer/package.json`'s `files` is `cli.js` +
37
+ * `glasspane.js`, and `npx glasspane-install` installs nothing beside it, so importing
38
+ * `mcp-shell/dist` from here is impossible. What the packages share is therefore the *gate*:
39
+ * `mcp-shell/test/remedy-shell-quoting.test.mjs` scans `installer/*.js` with the same
40
+ * argument-position judgement it applies to `src/` and `updater/`, so a bare interpolation at a
41
+ * command operand reddens all three sides in one run, and `installer/test/shell-quoting.test.mjs`
42
+ * pins this table against the shipped behaviour.
43
+ *
44
+ * Why it was needed at all: every one of these commands interpolates a path this process did
45
+ * not author — `tree.cli` / `update.updaterCli` come from `--repo`, `GLASSPANE_REPO` and
46
+ * `GLASSPANE_INSTALL_DIR` — and they were wrapped in DOUBLE quotes. Double quotes are not inert:
47
+ * `$(` and a backtick still expand inside them, so "run this restore command" became "run what
48
+ * the directory name says", with the agent's own privileges.
49
+ */
50
+
51
+ /** Characters a shell cannot act on inside an unquoted word. */
52
+ const SHELL_INERT_WORD = /^[A-Za-z0-9@%+=:,./_-]+$/
53
+
54
+ /**
55
+ * `value` as one shell word: left bare when it is made only of characters a shell cannot act on,
56
+ * single-quoted with `'\''` splices for anything else — a space, a quote, a dollar sign, a glob,
57
+ * the empty string (an argument that vanished is a different command line), or a leading hyphen
58
+ * (read as an option otherwise). Same table as `updater/lib/shell-quote.js` and
59
+ * `mcp-shell/src/errors.ts`.
60
+ */
61
+ export function quoteShellArg(value) {
62
+ const text = String(value)
63
+ return SHELL_INERT_WORD.test(text) && !text.startsWith('-')
64
+ ? text
65
+ : `'${text.split("'").join("'\\''")}'`
66
+ }
67
+
30
68
  // 显式常量,避免散落魔法字符串。
31
69
  export const MIN_NODE_MAJOR = 18
32
70
  export const SOCKET_DIR_NAME = '.glasspane'
@@ -70,7 +108,7 @@ export const INSTALL_SH_URL =
70
108
  /** 发布线锚点(版本真源 = 根 package.json,由 scripts/set-version.mjs 统一改写,
71
109
  * 勿手改):npx 形态下本地没有仓库时,引导 clone 的就是这个 tag,与 install.sh
72
110
  * 的 `GLASSPANE_RELEASE` 同值——两条一键入口必须拿到同一份源码。 */
73
- export const RELEASE_VERSION = '1.25.2'
111
+ export const RELEASE_VERSION = '1.27.0'
74
112
  /** 发布 ref(tag 名)。GLASSPANE_REF 环境变量可覆盖(追主干用 `main`)。 */
75
113
  export const REPO_REF = `v${RELEASE_VERSION}`
76
114
 
@@ -160,7 +198,14 @@ export function paint(text, color, enabled = process.stdout.isTTY) {
160
198
  // 纯逻辑层(可单测)
161
199
  // ---------------------------------------------------------------------------
162
200
 
163
- /** 解析 CLI 参数;未知/带值参数缺参时返回 { error }。 */
201
+ /** 解析 CLI 参数;未知/带值参数缺参时返回 `{ error, errorKind }`。
202
+ *
203
+ * 返回的 `options` 是**已经读到的那一部分**(不是 defaults)——入口要在"--help 与用法错同时
204
+ * 出现时谁赢"这条规则上看得见 help 有没有被真的给出来(2026-10-31 P1)。
205
+ * `errorKind` 也只有两个取值:`'repo-value'`=这一层自己就说不通的用法错(`--repo` 没接到取值、
206
+ * 或取值是旗标形状),`'unknown'`=只有本文件认得的旗标清单才能判定的错。两个 kind 与
207
+ * `--help` 的先后关系不同,规则写在入口的 `if (isMain)` 那一块上面。
208
+ */
164
209
  export function parseArgs(argv) {
165
210
  const defaults = {
166
211
  repoDir: null,
@@ -186,13 +231,21 @@ export function parseArgs(argv) {
186
231
  case '-h':
187
232
  opts.help = true
188
233
  break
189
- case '--repo':
190
- index += 1
191
- if (index >= rest.length || rest[index].startsWith('--')) {
192
- return { options: defaults, error: '--repo 需要一个目录参数' }
234
+ case '--repo': {
235
+ // 取值的两条判据与 install.sh 的 2c' 同一句,且**不以 `--` 为界**:单横线的 `-x` 同样是
236
+ // 一面旗标的形状。从前这里只否 `--` 前缀,于是 `--repo -x` 被当成一个目录收下继续跑,
237
+ // 而同一个文件的 unsafeArgvValue 对 clone 目标却否 `-` 前缀——一处两套口径(2026-10-31 P1)。
238
+ const value = rest[index + 1]
239
+ if (value === undefined) {
240
+ return { options: opts, error: '--repo 需要一个目录参数(后面没有取值)', errorKind: 'repo-value' }
193
241
  }
194
- opts.repoDir = rest[index]
242
+ if (value.startsWith('-')) {
243
+ return { options: opts, error: `--repo 需要一个目录参数(收到的是旗标:${value})`, errorKind: 'repo-value' }
244
+ }
245
+ index += 1
246
+ opts.repoDir = value
195
247
  break
248
+ }
196
249
  case '--no-prompt':
197
250
  opts.prompt = false
198
251
  break
@@ -232,19 +285,65 @@ export function parseArgs(argv) {
232
285
  opts.acceptUnverifiedSignature = true
233
286
  break
234
287
  default:
235
- return { options: defaults, error: `未知参数:${arg}(--help 查看用法)` }
288
+ return { options: opts, error: `未知参数:${arg}(--help 查看用法)`, errorKind: 'unknown' }
236
289
  }
237
290
  }
238
- return { options: opts, error: null }
291
+ return { options: opts, error: null, errorKind: null }
292
+ }
293
+
294
+ /** "这一棵是不是 GlassPane 仓库"的**唯一一份**判据(两个 marker 的相对路径)。
295
+ * install.sh 的 `looks_like_repo` 测的就是这两个路径,两处由
296
+ * `installer/test/daily-20261029-installer-lane7.test.mjs` 逐值对照——在那之前"两条入口的判据
297
+ * 同源"只是两句注释互相指认,脚本里那份是没人对照的第二份抄本。 */
298
+ export const REPO_MARKERS = Object.freeze(['engine/Package.swift', 'mcp-shell/package.json'])
299
+
300
+ /** 只问**这一层目录**,一律不向上走:`looksLikeRepoHere(<外层repo>/vendored)` 答 false,
301
+ * 而 {@link resolveProjectRoot} 会答出外层那一棵。S7-1(2026-10-29,P0)修的就是这个差别——
302
+ * 判断"目标是不是仓库"时向上走,别人的仓库子目录就被读成"既有 clone",随后 fetch/checkout
303
+ * 动的是外层那棵树。 */
304
+ export function looksLikeRepoHere(dir) {
305
+ if (typeof dir !== 'string' || dir === '') return false
306
+ return REPO_MARKERS.every((rel) => fs.existsSync(path.join(dir, rel)))
307
+ }
308
+
309
+ /** 显式定位位(`--repo` / `GLASSPANE_REPO`)交进来的那一条路径的**第一字节之前的闸**(纯函数)。
310
+ *
311
+ * 存在的理由(2026-10-31 P0,实测):`install()` 从前对这两个值只测 `fs.existsSync`,于是
312
+ * `npx glasspane-install --repo <一个存在的非仓库目录>` 真的把那个目录当项目根——`npm install`
313
+ * 以它为 cwd 跑起来(往里写 `node_modules`),一路撞到 `swift build` 才回 1。同一串输入
314
+ * `install.sh` 在 2e 那一支回 1 且"没有 clone、没有写入任何东西"。两条一键入口对同一串 argv
315
+ * 必须同判,而"先写再拒"本身就违背本仓的规矩:能拒绝的守卫要在第一字节之前拒
316
+ * (同一族的先例:`GP_E_SOCKET_TRUST` 写在写位之前、`install.sh` 的 `looks_like_repo`)。
317
+ *
318
+ * 判据两条,拒时都要点名(缺了哪一条也要点名,否则读者不知道该补什么):
319
+ * 1. 目录存在;
320
+ * 2. 目录里同时有 {@link REPO_MARKERS} 那两个文件(与 `install.sh` 的 `looks_like_repo` 同一份)。
321
+ * 文案与 `install.sh` 的 2e/2f 两支逐句对齐,由 `installer/test/daily-20261030-entry-parity.test.mjs`
322
+ * 按同一串输入逐值对照——那句"两条入口同答"从前只写在注释里。
323
+ *
324
+ * @returns {string|null} 拒绝正文(调用方抛错即可,一条字节都不必已经写出);放行时是 null。
325
+ */
326
+ export function locatedRootRefusal({ label, dir, ref = '' }) {
327
+ if (typeof dir !== 'string' || dir === '') return null
328
+ const exists = fs.existsSync(dir)
329
+ if (exists && looksLikeRepoHere(dir)) return null
330
+ const missing = REPO_MARKERS.filter((rel) => !fs.existsSync(path.join(dir, rel)))
331
+ return [
332
+ `${label} 给了这个目录,而它不合判据:${dir}`,
333
+ ` 判据(两条都要在,与 looks_like_repo 同一份):目录要存在;目录里要同时有 ${REPO_MARKERS.join(' 与 ')}。`,
334
+ ` 现在缺的是:${exists ? `${missing.join('、')} 不在` : '目录不存在'}`,
335
+ // 这一句是这条闸的**承诺**,不是装饰:它排在 ensureLogDir 与 npm 之前,所以拒绝之后
336
+ // 家目录里不会多出 .glasspane,指定目录里不会多出 node_modules。
337
+ '本轮没有 clone、没有写入任何东西。',
338
+ `下一步:${label} 指一棵真的仓库(上面两条判据都在),或去掉 ${label} 让它 clone 一份${ref ? `(ref: ${ref})` : ''}。`,
339
+ ].join('\n')
239
340
  }
240
341
 
241
342
  /** 从起始目录向上逐级寻找含 engine/Package.swift 与 mcp-shell/package.json 的根目录。 */
242
343
  export function resolveProjectRoot(startDir = process.cwd()) {
243
344
  let dir = path.resolve(startDir)
244
345
  while (true) {
245
- const hasEngine = fs.existsSync(path.join(dir, 'engine', 'Package.swift'))
246
- const hasShell = fs.existsSync(path.join(dir, 'mcp-shell', 'package.json'))
247
- if (hasEngine && hasShell) {
346
+ if (looksLikeRepoHere(dir)) {
248
347
  return dir
249
348
  }
250
349
  const parent = path.dirname(dir)
@@ -414,6 +513,40 @@ export function platformRefusal(platform = process.platform) {
414
513
  + '要在别的系统上用 GlassPane,等它把引擎搬到那一侧再说——现在这一步没有可绕的旗标。'
415
514
  }
416
515
 
516
+ /**
517
+ * 入口那一条 if/else 链的**纯函数形状**(2026-10-31):次序里有一档只在非 darwin 主机上才走到,
518
+ * 而 CI 的两条 lane 正好各跑一种(ubuntu 的 root workspace gate、macOS 的 darwin-only 套件)。
519
+ * 把判据留在 `if (isMain)` 里,本机就永远证不到那一档——上一轮正是这样把"同一串 argv 两入口
520
+ * 两个码"发到了 main 上(Linux runner 现形:install.sh 回 1,cli.js 回 2)。抽出来之后,
521
+ * 次序矩阵在任一台机器上都能整表跑,包括那台跑不到的。
522
+ *
523
+ * 次序(同一份规则写在 install.sh 的 2c'/2e 与 `if (isMain)` 上面):
524
+ * 1. `--repo` 的两类用法错(缺取值 / 取值是旗标形状)——这串 argv 自己就不通,先于 --help;
525
+ * 2. 显式定位位(`--repo` / `GLASSPANE_REPO`)交的目录不合仓库判据——**与主机无关**,
526
+ * 所以它排在平台判据之前,两条入口在 Linux 与 macOS 上给同一句、同一个码;
527
+ * 3. `--help` / `-h`:0(CI 的 install-gate 与两份 README 钉的就是这个 0);
528
+ * 4. 平台判据:跑不了这个产品的机器上第一句说的是"这里跑不了"(1)。未知参数只有本文件判得
529
+ * 出来(install.sh 没有旗标清单,也不许抄一份),所以那一档在平台判据**之后**:否则
530
+ * 同一串 argv 在 Linux 上就成了 install.sh=1 / cli.js=2;
531
+ * 5. 未知参数:2 + usage 页;
532
+ * 6. `--restore-launchd` / 正常安装。
533
+ */
534
+ export function entryDecision({ options, error = null, errorKind = null,
535
+ platform = process.platform, env = process.env }) {
536
+ const repoValueError = errorKind === 'repo-value'
537
+ const located = (repoValueError || options.help || options.restoreLaunchd)
538
+ ? null : explicitLocatedRootRefusal(options, env)
539
+ const platformRefuse = (repoValueError || options.help || located !== null || options.restoreLaunchd)
540
+ ? null : platformRefusal(platform)
541
+ if (repoValueError) return { kind: 'usage-error', message: error, exitCode: 2 }
542
+ if (located !== null) return { kind: 'located-root', message: located, exitCode: 1 }
543
+ if (options.help) return { kind: 'help', exitCode: 0 }
544
+ if (platformRefuse) return { kind: 'platform', message: platformRefuse, exitCode: 1 }
545
+ if (error) return { kind: 'usage-error', message: error, exitCode: 2 }
546
+ if (options.restoreLaunchd) return { kind: 'restore-launchd', exitCode: 0 }
547
+ return { kind: 'install', exitCode: 0 }
548
+ }
549
+
417
550
  /** 汇总预检结果:缺项按严重程度排序返回可读描述(空数组 = 全部通过)。 */
418
551
  export function preflightIssues(env) {
419
552
  const issues = []
@@ -738,37 +871,56 @@ export function bundlesToReplace({ plan, exists = fs.existsSync } = {}) {
738
871
  .map(([, target]) => target)
739
872
  }
740
873
 
874
+ export function explicitLocatedRootRefusal(options, env = process.env) {
875
+ const explicitRoot = options.repoDir ? path.resolve(options.repoDir) : null
876
+ const envRoot = env.GLASSPANE_REPO ? path.resolve(env.GLASSPANE_REPO) : null
877
+ const ref = resolvePinRef(env)
878
+ for (const located of [
879
+ { label: '--repo', dir: explicitRoot },
880
+ { label: 'GLASSPANE_REPO', dir: envRoot },
881
+ ]) {
882
+ const refusal = locatedRootRefusal({ ...located, ref })
883
+ if (refusal) return refusal
884
+ }
885
+ return null
886
+ }
887
+
741
888
  /** 安置一份 bundle 时那条"没落地"的拒绝:说清动到哪一步、旧的一份还在不在、下一步跑什么。
742
889
  * finding C9(2026-10-24):从前这里只把 `cpSync` 的 errno 原样抛出去——读的人既不知道
743
890
  * 旧 bundle 是否还在(旧实现是先 `rm -rf` 再拷,中途失败就是"旧的没了、新的是半棵"),
744
891
  * 也没有一句下一步。现在每一种失败各自点名"原件在不在",并给一条真能跑的命令。 */
745
- function bundlePlacementFailureText({ source, target, staged, retired, error, step, stagedRemoved = true }) {
892
+ export function bundlePlacementFailureText({ source, target, staged, retired, error, step, stagedRemoved = true }) {
746
893
  const raw = String(error?.message ?? error)
747
894
  const errno = error?.code && !raw.startsWith(String(error.code)) ? `${error.code}: ${raw}` : raw
748
895
  const head = `安置 ${target} 失败(来源 ${source}):${errno}`
749
- const dir = JSON.stringify(path.dirname(target))
750
- const q = (p) => JSON.stringify(p)
896
+ // 命令位上的每一份路径都**就地**走本包自己的 `quoteShellArg`(2026-10-31:这里原来是一个
897
+ // `const dir = JSON.stringify(...)` 与一个 `q = (p) => JSON.stringify(p)`——那是双引号,
898
+ // `$(` 与反引号在双引号里照常展开,"照着这条命令修磁盘"就变成"照着目录名执行"。判据在
899
+ // `installer/test/shell-quoting.test.mjs` 的行为半边与
900
+ // `mcp-shell/test/remedy-shell-quoting.test.mjs` 的参数位扫描里;扫描按**名字**放行,所以
901
+ // 这里不保留 `dir`/`q` 这类别名:一个别名就是一次让闸看不见这处调用的改写。)
751
902
  if (step === 'copy' || step === 'retire') {
752
903
  return `${head}\n`
753
904
  + `新的一份只走到暂存位置就断了,原件还在原位——${target} 仍是上一轮那份**完整**的 bundle,`
754
- + `本轮没有任何一步动过它的内容。下一步:空间不够看 \`df -h ${dir}\`,权限/旗标看 `
755
- + `\`ls -ld ${dir}\` 与 \`ls -lO ${q(target)}\`(macOS 的 immutable 旗标 uchg 会让改名与覆盖都失败),`
905
+ + `本轮没有任何一步动过它的内容。下一步:空间不够看 \`df -h ${quoteShellArg(path.dirname(target))}\`,权限/旗标看 `
906
+ + `\`ls -ld ${quoteShellArg(path.dirname(target))}\` 与 \`ls -lO ${quoteShellArg(target)}\`(macOS 的 immutable 旗标 uchg 会让改名与覆盖都失败),`
756
907
  + `腾出来或修好之后重跑 install.sh。`
757
908
  + (stagedRemoved
758
909
  ? `本轮的暂存副本 ${staged} 已删,不需要手工清理。`
759
- : `本轮的暂存副本 ${staged} 没能删掉(同一个错误也挡住了它),重跑前手工 \`rm -rf ${q(staged)}\` 即可。`)
910
+ : `本轮的暂存副本 ${staged} 没能删掉(同一个错误也挡住了它),重跑前手工 \`rm -rf ${quoteShellArg(staged)}\` 即可。`)
760
911
  }
761
912
  if (step === 'restore') {
762
913
  return `${head}\n`
763
914
  + `这一步之后本机已经没有 ${target} 了:新的一份在 ${staged},上一轮那份完整的备份在 ${retired},`
764
915
  + `而把它们放回原位的改名也被同一个错误挡住。这一步归人(安装器不发放提权命令):`
765
- + `先 \`mv ${q(retired)} ${q(target)}\` 把旧的一份放回原位,或 \`mv ${q(staged)} ${q(target)}\` 用本轮新的一份;`
766
- + `两个都跑不通就是 ${path.dirname(target)} 的权限问题,看 \`ls -ld ${dir}\`,修好后重跑 install.sh。`
916
+ + `先 \`mv ${quoteShellArg(retired)} ${quoteShellArg(target)}\` 把旧的一份放回原位,`
917
+ + `或 \`mv ${quoteShellArg(staged)} ${quoteShellArg(target)}\` 用本轮新的一份;`
918
+ + `两个都跑不通就是 ${path.dirname(target)} 的权限问题,看 \`ls -ld ${quoteShellArg(path.dirname(target))}\`,修好后重跑 install.sh。`
767
919
  }
768
920
  // step === 'place':新的一份没能落位,旧的一份已经被挪回原位——机器上此刻仍是完整的一版。
769
921
  return `${head}\n`
770
922
  + `${target} 已经放回上一轮那一份(先把备份 ${retired} 挪回原位再报错),本轮新的一份留在 ${staged}——`
771
- + `本机现在不是"半棵",是旧的那版在位。下一步:\`ls -ld ${dir}\` 看这个目录当前账号能不能写`
923
+ + `本机现在不是"半棵",是旧的那版在位。下一步:\`ls -ld ${quoteShellArg(path.dirname(target))}\` 看这个目录当前账号能不能写`
772
924
  + `(EACCES 通常是目录属主不是您,或这卷不保存权限位),修好后重跑 install.sh;`
773
925
  + `两处残留 ${staged} 与 ${retired} 想清就 \`rm -rf\`,留着也不影响下一轮。`
774
926
  }
@@ -1485,7 +1637,7 @@ export function tagVerifyDecision({ sig, pinRef, repoDir, acceptUnverified = fal
1485
1637
  + `git -C "${repoDir}" tag -v ${pinRef}\n`
1486
1638
  + '确实在没有 gpg 的机器上要装,就修好工具链再重跑(`brew install gnupg` 或 `xcode-select --install`);'
1487
1639
  + '理解风险、决定就在这一档缺结论的情况下继续,才显式带上放行旗标重跑:\n'
1488
- + ` node installer/cli.js --repo "${repoDir}" --accept-unverified-signature\n`
1640
+ + ` node installer/cli.js --repo ${quoteShellArg(repoDir)} --accept-unverified-signature\n`
1489
1641
  + ` curl -fsSL ${INSTALL_SH_URL} | sh -s -- --accept-unverified-signature\n`
1490
1642
  + '它与 updater 的 `--consent unsigned-release` 同一形态:只批"缺证明",'
1491
1643
  + '签名存在而验不过(invalid)永不被它覆盖;`--no-prompt` 也不是这里说的同意。',
@@ -1804,7 +1956,7 @@ export async function registerAutoUpdate({
1804
1956
  caRoots: outcome.state && outcome.state.caRoots ? outcome.state.caRoots : null,
1805
1957
  }
1806
1958
  if (registered) {
1807
- say(`每日自动更新已注册(${agentLabel},${summary.scheduleMeasured ? `在册作业跑在 ${schedule}` : `默认 ${schedule}——这一档没能从在册作业读回实际时刻,所以下一句是默认值而不是实测`},状态根 ${stateRoot};指针 ${written.path})——一键关:node "${tree.cli}" disable`)
1959
+ say(`每日自动更新已注册(${agentLabel},${summary.scheduleMeasured ? `在册作业跑在 ${schedule}` : `默认 ${schedule}——这一档没能从在册作业读回实际时刻,所以下一句是默认值而不是实测`},状态根 ${stateRoot};指针 ${written.path})——一键关:node ${quoteShellArg(tree.cli)} disable`)
1808
1960
  // "已注册"这三个字的证据是 updater 把在册作业读回来核对过。launchd 装载成功但读不回在册作业时,
1809
1961
  // 这句话只能算一半成立,而那另一半(原话)必须跟着说出来——否则这台机器看起来有每日作业,实际
1810
1962
  // 有没有人跑没人知道。措辞仍来自唯一作者 outcome.message,这里只转述。
@@ -1824,13 +1976,13 @@ export async function registerAutoUpdate({
1824
1976
  } else if (ca) {
1825
1977
  say(paint(`注意(自动更新的网络这一跳):${outcome.message}`, 'yellow'))
1826
1978
  } else {
1827
- say(paint(`注意:这份 updater 没有回报根证书束的导出结果(旧版本);若本机 HTTPS 被中间人替换,每日检查会在第一道校验上失败,跑 node "${tree.cli}" enable 可重新导出。`, 'yellow'))
1979
+ say(paint(`注意:这份 updater 没有回报根证书束的导出结果(旧版本);若本机 HTTPS 被中间人替换,每日检查会在第一道校验上失败,跑 node ${quoteShellArg(tree.cli)} enable 可重新导出。`, 'yellow'))
1828
1980
  }
1829
1981
  } else {
1830
1982
  say(
1831
1983
  `自动更新已关闭(${switchedOffByEnv ? 'updater 报环境变量已关,见下面它自己的原话' : '--no-auto-update'}):`
1832
1984
  + `${agentLabel} 未注册/已卸载,状态里记 disabled=true——面板显示"自动更新已关闭(上次检查 …)"而不是"从未检查"。`
1833
- + `手动 node "${tree.cli}" check / apply 仍可用;重开:node "${tree.cli}" enable。`
1985
+ + `手动 node ${quoteShellArg(tree.cli)} check / apply 仍可用;重开:node ${quoteShellArg(tree.cli)} enable。`
1834
1986
  + `(updater 原话:${outcome.message})`,
1835
1987
  )
1836
1988
  }
@@ -1855,7 +2007,7 @@ export function updateGuidanceText(update) {
1855
2007
  if (update.state === 'registered') {
1856
2008
  const ca = update.caRoots
1857
2009
  const caLine = !ca
1858
- ? ` ⚠ 这份 updater 没有回报 node 要用的系统根证书束(旧版本);本机 HTTPS 若被中间人替换,每日检查会在第一道校验上失败。补上:node "${update.updaterCli}" enable。`
2010
+ ? ` ⚠ 这份 updater 没有回报 node 要用的系统根证书束(旧版本);本机 HTTPS 若被中间人替换,每日检查会在第一道校验上失败。补上:node ${quoteShellArg(update.updaterCli)} enable。`
1859
2011
  : ca.status === 'ok'
1860
2012
  ? ` node 用本机导出的系统根证书束 ${ca.certs} 张(${ca.path},已写进作业的 NODE_EXTRA_CA_CERTS)。`
1861
2013
  : ` ⚠ 本机没能导出 node 要用的系统根证书束(${ca.status});HTTPS 被中间人替换的机器上,每日检查会在第一道校验上失败,`
@@ -1865,7 +2017,7 @@ export function updateGuidanceText(update) {
1865
2017
  ` (作业 ${update.agentLabel},RunAtLoad=false,日志 ${update.stateRoot}/update.log);`,
1866
2018
  ' 只在 daemon 空闲应答探针、且候选发布版的八道校验全部通过时才换版,major 永远等人点按钮。',
1867
2019
  ...(caLine ? [caLine] : []),
1868
- ` 一键关:node "${update.updaterCli}" disable(卸该作业 + 状态记 disabled=true);重开:enable。`,
2020
+ ` 一键关:node ${quoteShellArg(update.updaterCli)} disable(卸该作业 + 状态记 disabled=true);重开:enable。`,
1869
2021
  ` 卸载本机安装时:bootout daemon 作业的同时**也必须** bootout ${update.agentLabel} 并删它的 plist。`,
1870
2022
  ]
1871
2023
  }
@@ -1873,7 +2025,7 @@ export function updateGuidanceText(update) {
1873
2025
  `6. 自动更新:已关闭(${update.reason === 'env' ? 'updater 判定环境变量为关,安装器没有第二套解读' : '--no-auto-update'})。`,
1874
2026
  ` ${update.agentLabel} 未注册,状态记 disabled=true:面板显示"自动更新已关闭(上次检查 …)",`,
1875
2027
  ' 不会静默消失;手动检查/安装仍是同一条 CLI(面板上那两个按钮也是它)。',
1876
- ` 重开:node "${update.updaterCli}" enable${update.reason === 'env' ? '(先把那个环境变量去掉,否则 updater 会拒绝注册)' : ''}。`,
2028
+ ` 重开:node ${quoteShellArg(update.updaterCli)} enable${update.reason === 'env' ? '(先把那个环境变量去掉,否则 updater 会拒绝注册)' : ''}。`,
1877
2029
  ` 它也负责卸载:bootout ${update.agentLabel} + 删 ~/Library/LaunchAgents 下那份 plist。`,
1878
2030
  ]
1879
2031
  }
@@ -2192,7 +2344,10 @@ export function usageText() {
2192
2344
  '用法: node installer/cli.js [选项]',
2193
2345
  '',
2194
2346
  '选项:',
2195
- ' --repo <目录> 指定项目根目录(默认自动向上查找)',
2347
+ ' --repo <目录> 指定项目根目录(默认自动向上查找)。这一枚与 GLASSPANE_REPO 都要先过',
2348
+ ' 判据(目录存在 + 目录里同时有 engine/Package.swift 与 mcp-shell/package.json):',
2349
+ ' 不合就当场拒绝,且拒在任何写入之前——从前它只测"目录在不在",于是',
2350
+ ' 一个存在的非仓库目录会被当成项目根去跑 npm install(2026-10-31 修)',
2196
2351
  ' --no-prompt 跳过破坏性步骤的确认(脚本/自动化场景)。被它拦住的是三件:',
2197
2352
  ' ① bootout 已加载的 launchd daemon 作业(会打断正在跑的 act;',
2198
2353
  ' install 与 --restore-launchd 走的是同一道门);',
@@ -2231,16 +2386,29 @@ export function usageText() {
2231
2386
  '退出码(脚本/agent 调用方读这个,别读屏幕文案):',
2232
2387
  ' 0 安装完成且 daemon 实测应答 hello;或本轮按要求压根不该有 daemon',
2233
2388
  ' (--no-daemon 且 --no-launchd)',
2234
- ' 1 收尾未通过 hello 校验(daemon 没起来/不应答),或构建/产物/launchd 出错',
2389
+ ' 1 收尾未通过 hello 校验(daemon 没起来/不应答),或构建/产物/launchd 出错;',
2390
+ ' 也包括这两条**什么都没构建就停下**的支路——它们同样回 1,按 rc 分叉的调用方别把 1',
2391
+ ' 读成"跑过但没成":① 平台拒绝(`process.platform` 不是 darwin,见 platformRefusal),',
2392
+ ' ② 环境预检未通过(缺 node/swift/npm 那一族,`checkEnvironment` 报的每条都列在输出里)。',
2393
+ ' 这两条的正文各自点名了下一步,读正文才知道该装什么。',
2235
2394
  ' 2 命令行参数错误',
2395
+ ' 用法错与 --help 同时出现时谁赢(install.sh 的 2c\' 那一节写的是同一份规则):',
2396
+ ' `--repo` 没接到取值、或接到的是旗标(`-` 开头,单双横线都算)——这一类**先赢**,仍旧退 2;',
2397
+ ' "未知参数"这一类**让位**:给了 --help 就打这一页并退 0,因为入口脚本没有本文件的旗标',
2398
+ ' 清单、判不出"未知",抄一份就是下一处没人对照的孪生抄本。',
2399
+ ' 还有一档**让位**(2026-10-31 定下,与 install.sh 的平台闸同一口径):主机不是 macOS 时,',
2400
+ ' "未知参数"先撞平台闸并回 1——那台机器就算 argv 写对了也跑不了,第一句该说的是这件事。',
2401
+ ' 所以在 Linux runner 上 `--no-such-flag` 回 1 而不是 2;要读这一页在两种主机上都用 --help(0)。',
2236
2402
  ' 跨二进制的用法错对照(**这是在记录一处已知分歧,不是修它**——那些码都是发出去的契约,',
2237
2403
  ' 本轮一个都没改):同样是"命令行参数错误",`node updater/cli.js` 回 2(与本文件一致),',
2238
2404
  ' 后台服务 `glasspaned` 回 64(并把整块用法打出去)。按 rc 分支的脚本要把 2 与 64 都当用法错。',
2239
2405
  ' 注:install.sh 用 exec 委托本文件,所以**脚本自己跑完了**之后,退出码原样透传。',
2240
2406
  ' 但 `curl … | sh` 的 $? 只在 curl 成功时才是这里的结论:curl 取不到脚本时 sh 读到的',
2241
2407
  ' 是空输入,直接 EOF 退 0(本机实测 curl 退 7、管道退 0);中途断流时 sh 只执行了',
2242
- ' 收到的前半截,回的是最后一条命令的状态。要拿退出码当结论就分两步跑:',
2243
- ' curl -fsSL <install.sh> -o /tmp/gp-install.sh && sh /tmp/gp-install.sh',
2408
+ ' 收到的前半截,回的是最后一条命令的状态。要拿退出码当结论就分两步跑,且落点必须是',
2409
+ ' 一次性文件(`/tmp` 是 1777:sticky 只挡住别人删你的目录项,挡不住他先建一个',
2410
+ ' `/tmp/gp-install.sh -> ~/.bashrc`,而 curl -o 会跟随那个符号链接、以你的 uid 截断覆写它):',
2411
+ ' GP="$(mktemp "${TMPDIR:-/tmp/}gp-install.XXXXXXXX")" && curl -fsSL <install.sh> -o "$GP" && sh "$GP" && rm -f "$GP"',
2244
2412
  '',
2245
2413
  ].join('\n')
2246
2414
  }
@@ -2292,7 +2460,7 @@ export function nextStepsText({
2292
2460
  // 已经拿到 rootDir),印 "<仓库目录>" 占位符等于没给可执行的东西。
2293
2461
  ...(daemonVerified ? [] : [
2294
2462
  paint('⚠ 后台服务未通过 hello 校验:下面第 1 步接好的 MCP 客户端会连不上 daemon。', 'red'),
2295
- ` 先修这一步:node "${path.join(rootDir, 'installer', 'cli.js')}" --restore-launchd`,
2463
+ ` 先修这一步:node ${quoteShellArg(path.join(rootDir, 'installer', 'cli.js'))} --restore-launchd`,
2296
2464
  '',
2297
2465
  ]),
2298
2466
  '1. MCP 客户端(Claude Desktop / Cursor / 任意 MCP host)接入配置片段:',
@@ -2324,7 +2492,7 @@ export function nextStepsText({
2324
2492
  '3. daemon 已注册 launchd 开机自启(--no-launchd 可跳过);维护命令:',
2325
2493
  ' glasspaned --approval-audit / --approval-verify / --prune-evidence / --evidence-stats',
2326
2494
  ` 作业被 bootout(等授权期间常发生)后的恢复**不需要手敲 launchctl**:`,
2327
- ` node "${path.join(rootDir, 'installer', 'cli.js')}" --restore-launchd`,
2495
+ ` node ${quoteShellArg(path.join(rootDir, 'installer', 'cli.js'))} --restore-launchd`,
2328
2496
  ` (检测→bootstrap→hello 校验自报席位;勾完 TCC 框重跑即自动换进程复验)`,
2329
2497
  `4. 主体名核对:设置面板「Daemon 状态 → 主体」应与上面「${entryName}」一致;不一致说明连到了别的构建实例。`,
2330
2498
  '5. registry 发布形态:MCP 服务器已可独立安装(`npm i -g glasspane-mcp`,命令名',
@@ -2504,8 +2672,8 @@ export function writePrivatePlist(plistPath, xml, {
2504
2672
 
2505
2673
  /** clone 失败的归因(finding 9):把 **git 自己的原话**交给读者,而不是把任何非零退出
2506
2674
  * 都算成"网络不可达或该发布 tag 不存在"。"destination path … already exists and is not an
2507
- * empty directory" 是真能走到的(bootstrapPlan 只拒绝"存在且父目录也不是仓库"的那种),
2508
- * 被归因成网络问题时读者会一直重试一条永远不通的路。 */
2675
+ * empty directory" 是真能走到的(bootstrapPlan 只拒绝"这一层目录自己不是 GlassPane 仓库"的那种,
2676
+ * 判据见 looksLikeRepoHere),被归因成网络问题时读者会一直重试一条永远不通的路。 */
2509
2677
  export function cloneFailureText({ ref, status, stderr = '', targetDir }) {
2510
2678
  const detail = String(stderr ?? '').trim()
2511
2679
  const head = `git clone 失败(ref '${ref}',目标 ${targetDir},退出码 ${status ?? 'null'})。`
@@ -2550,7 +2718,11 @@ export function bootstrapPlan({
2550
2718
  return { error: '无法确定用户主目录(HOME 为空),不知道把源码 clone 到哪里' }
2551
2719
  }
2552
2720
  const targetDir = installDir || path.join(homeDir, 'glasspane')
2553
- if (fs.existsSync(targetDir) && resolveProjectRoot(targetDir) === null) {
2721
+ // 只问这一层,不向上走(S7-1,2026-10-29 P0)。这里从前用的是 `resolveProjectRoot(targetDir)`,
2722
+ // 而它会一路向上找到外层的仓库:`<外层repo>/vendored` 于是"是一个仓库",躲过这条拒绝,
2723
+ // 后面的 fetch/checkout 就全落在外层那一棵上(同一条输入 install.sh 的答案是"目标目录已存在
2724
+ // 且不是 GlassPane 仓库"+ rc 1——两条一键入口对着同一个目录给两种结论,修的就是这一类)。
2725
+ if (fs.existsSync(targetDir) && !looksLikeRepoHere(targetDir)) {
2554
2726
  return {
2555
2727
  error: `目标目录已存在且不是 GlassPane 仓库:${targetDir}(用 --repo 指定仓库,或清理该目录后重试)`,
2556
2728
  }
@@ -2578,6 +2750,59 @@ export function bootstrapPlan({
2578
2750
  }
2579
2751
  }
2580
2752
 
2753
+ /**
2754
+ * 两条路径是不是同一个东西。`git rev-parse --show-toplevel` 打的是**物理路径**(macOS 上
2755
+ * `/var` → `/private/var`、家目录里的软链都会被解开),所以两侧都要过一遍 realpath 才可比;
2756
+ * 路径不存在时 realpathSync 抛,退回 `path.resolve`——不存在的那一侧本来就答不出仓库根。
2757
+ */
2758
+ function canonicalPath(p) {
2759
+ try {
2760
+ return fs.realpathSync(p)
2761
+ } catch {
2762
+ return path.resolve(p)
2763
+ }
2764
+ }
2765
+
2766
+ /** 问一次「这一带最近的仓库根在哪」,把答案作为数据交回去(不判定)。 */
2767
+ export function readRepoToplevel({ dir, spawn = spawnSync } = {}) {
2768
+ const res = spawn('git', ['-C', dir, 'rev-parse', '--show-toplevel'], { encoding: 'utf8' })
2769
+ const answer = String(res?.stdout ?? '').trim()
2770
+ if (res?.status !== 0 || answer === '') {
2771
+ return { read: false, toplevel: null }
2772
+ }
2773
+ return { read: true, toplevel: answer }
2774
+ }
2775
+
2776
+ /**
2777
+ * 纯判定:要动手的那一棵,是不是说话人指的那一棵?(S7-1,2026-10-29,P0)
2778
+ * `git -C <dir>` 对**任何**目录都按"离它最近的那棵树"答话,所以 `git -C <外层repo>/vendored
2779
+ * status` 与 `checkout --detach` 动的都是外层那棵树——本轮实测把外层 main detach 了。
2780
+ * 只答两种"不是同一棵":答不出(`unreadable`,那目录不是任何仓库的一部分,或 git 没答话),
2781
+ * 与答的是别处(`outside`)。相等就回 null。
2782
+ */
2783
+ export function toplevelProblemFor({ targetDir, toplevel = null, readOk = false } = {}) {
2784
+ if (!readOk) return { kind: 'unreadable' }
2785
+ if (canonicalPath(toplevel) === canonicalPath(targetDir)) return null
2786
+ return { kind: 'outside', toplevel }
2787
+ }
2788
+
2789
+ /** 两种"不是同一棵"各说一句;两处调用(纯判据、IO 步)共用这一份,不发明第二套说法。 */
2790
+ export function toplevelRefuseText({ targetDir, problem }) {
2791
+ if (problem?.kind === 'outside') {
2792
+ return `${targetDir} 自己不是一棵 git 仓库的根:git 说这一带最近的根在 **${problem.toplevel}**。`
2793
+ + `\n本轮要是动手,动的就是 ${problem.toplevel} 那一棵,而不是你指的 ${targetDir}——那是别人的仓库,`
2794
+ + '安装器不在它上面 fetch、不切它的分支、不碰它的工作树。'
2795
+ + `\n下一步(两条都做得动,且不销毁任何东西):`
2796
+ + `\n a) 换一处不属于任何仓库的落点:GLASSPANE_INSTALL_DIR=<空目录> 重跑一键安装`
2797
+ + '(那个目录自己要能让 git -C <目录> rev-parse --show-toplevel 答不出才算它自己);'
2798
+ + `\n b) 要装的那一棵在别处就用 --repo / GLASSPANE_REPO 指过去,指的目录必须自己就是仓库根。`
2799
+ }
2800
+ return `${targetDir} 答不出 git 仓库根(这一带它不是 git 仓库,或 git 本身没答话):`
2801
+ + '连"要动的是哪一棵"都判不出来,就不动它,也不装它。'
2802
+ + `\n下一步:确认 ${targetDir} 是一棵 git 仓库(git -C "${targetDir}" rev-parse --show-toplevel 能不能答话);`
2803
+ + '要一份全新的 clone 就 GLASSPANE_INSTALL_DIR=<空目录> 重跑一键安装。'
2804
+ }
2805
+
2581
2806
  /**
2582
2807
  * 既有 clone 的结论(纯判定,可单测)。
2583
2808
  *
@@ -2588,6 +2813,9 @@ export function bootstrapPlan({
2588
2813
  * "destination path … already exists and is not an empty directory" 拒掉,读者只剩"换目录"这一条死路。
2589
2814
  *
2590
2815
  * 判据按那个人 2026-10-26 选的形状:
2816
+ * · 先问「要动的是不是这一棵」(`toplevelProblem`,见 `readRepoToplevel`):答不出或答的是
2817
+ * 别处 ⇒ 拒绝,点名要动的到底是哪一棵——这一问排在脏/干净之前,因为"这棵树干净"是对着
2818
+ * 别人的仓库说的结论(S7-1,2026-10-29 P0);
2591
2819
  * · 干净(`git status --porcelain` 空)且 HEAD 已经是那个 tag ⇒ 就用;
2592
2820
  * · 干净但不是那个 tag ⇒ 前进(fetch + detached checkout —— 这是移动**产品自己的 clone**,
2593
2821
  * 不是移动任何人的工作树);
@@ -2602,7 +2830,17 @@ export function bootstrapPlan({
2602
2830
  * 现在 tag 缺席归到"前进"里:fetch 不成仍由 `advanceExistingClone` 拒,并交出 git 的原话;
2603
2831
  * HEAD 读不出照旧是拒。前者是能补的事实缺口,后者是判据本身没了。
2604
2832
  */
2605
- export function existingCloneDecision({ targetDir, ref, head = null, tagCommit = null, blocking = [] }) {
2833
+ export function existingCloneDecision({ targetDir, ref, head = null, tagCommit = null, blocking = [], toplevelProblem = null }) {
2834
+ // 「要动的是哪一棵」问在「这棵树脏不脏」之前:判不出对象的时候,后面每一条结论都是对着
2835
+ // 别人的仓库说的(S7-1 的实测形状:外层 main 被 detach,然后回一句 advance: use)。
2836
+ if (toplevelProblem) {
2837
+ return {
2838
+ action: 'refuse',
2839
+ blocking: [],
2840
+ toplevelProblem,
2841
+ text: toplevelRefuseText({ targetDir, problem: toplevelProblem }),
2842
+ }
2843
+ }
2606
2844
  const dirty = blocking.map((line) => String(line).trim()).filter((line) => line !== '')
2607
2845
  if (dirty.length > 0) {
2608
2846
  const shown = dirty.slice(0, 10)
@@ -2663,6 +2901,9 @@ export function existingCloneDecision({ targetDir, ref, head = null, tagCommit =
2663
2901
  * `git status --porcelain` 的行,以及这份 clone 是不是浅仓。判据一律在 `existingCloneDecision`,
2664
2902
  * 两处调用(bootstrap 的纯计划、前进这一步的复判)共用同一份读数,避免出现第二个"什么算脏"的说法。
2665
2903
  *
2904
+ * 这四份事实之前还有一问:`rev-parse --show-toplevel`——它决定"这四份事实到底是谁的事实"。
2905
+ * 答不出或答的是别处时**一份都不给**(见上面的 S7-1 注释),调用方拿到的就是 head=null。
2906
+ *
2666
2907
  * `shallow` 是给 fetch 挑形状的:`--depth 1` 会把一棵**完整**的 clone 变成浅仓(`.git/shallow`
2667
2908
  * 一旦落下,之后的遍历都撞上人为边界,要恢复得 `git fetch --unshallow`)。旧写法对任何树都带
2668
2909
  * `--depth 1`,而注释写的是"只往 .git 里加对象"——那句话对完整 clone 不成立,它加的是一个边界。
@@ -2670,6 +2911,15 @@ export function existingCloneDecision({ targetDir, ref, head = null, tagCommit =
2670
2911
  * 一点也不给人家的历史加边界。
2671
2912
  */
2672
2913
  export function readCloneFacts({ targetDir, ref, spawn = spawnSync, fetchHead = false } = {}) {
2914
+ // 开头先问「要动的是不是这一棵」(S7-1)。`git -C <dir>` 对别人仓库的子目录一样答话,
2915
+ // 所以后面的 status / rev-parse 读回来的其实是**外层那棵树**的事实:外层干净、外层 HEAD 在
2916
+ // 某一笔上,于是这一棵被读成"干净的既有 clone",下一步 fetch/checkout 就 detach 了外层的 main。
2917
+ // 答不出或答的是别处 ⇒ 一条事实也不给(head 为 null),判据那一侧只能落到"拒"。
2918
+ const top = readRepoToplevel({ dir: targetDir, spawn })
2919
+ const toplevelProblem = toplevelProblemFor({ targetDir, toplevel: top.toplevel, readOk: top.read })
2920
+ if (toplevelProblem) {
2921
+ return { head: null, tagCommit: null, blocking: [], shallow: null, toplevelProblem, toplevel: top.toplevel }
2922
+ }
2673
2923
  const read = (args) => spawn('git', ['-C', targetDir, ...args], { encoding: 'utf8' })
2674
2924
  const sha = (what) => {
2675
2925
  const res = read(['rev-parse', '--verify', what])
@@ -2722,16 +2972,8 @@ export function resolveRemoteName({ remotes = [] } = {}) {
2722
2972
  /**
2723
2973
  * 把既有 clone 前进到钉住的 ref(IO 步;判据全在 `existingCloneDecision` 里)。
2724
2974
  *
2725
- * 只有这几种 git 动作:`status --porcelain`、两次 `rev-parse --verify`、`rev-parse
2726
- * --is-shallow-repository`(全是读),`fetch --tags [origin <ref>]`(只往 .git 里加对象;
2727
- * 带不带 `--depth 1` 由 git 自己答的那句"是不是浅仓"决定,见 `readCloneFacts`),以及
2728
- * `checkout --detach <ref>`(只在树干净时执行)。没有 `-f`、没有 `stash`、没有 `clean`、
2729
- * 没有 `reset --hard`:一个 installer 不该有能把别人的未提交工作抹掉的那一格。
2730
- */
2731
- /**
2732
- * 把既有 clone 前进到钉住的 ref(IO 步;判据全在 `existingCloneDecision` 里)。
2733
- *
2734
- * 只有这几种 git 动作:`status --porcelain`、`remote`、几次 `rev-parse --verify`、`rev-parse
2975
+ * 只有这几种 git 动作:开头一次 `rev-parse --show-toplevel`(问"要动的是不是这一棵",见下面的
2976
+ * S7-1 注释)、`status --porcelain`、`remote`、几次 `rev-parse --verify`、`rev-parse
2735
2977
  * --is-shallow-repository`(全是读),`fetch --tags [remote <ref>]`(只往 .git 里加对象;
2736
2978
  * 带不带 `--depth 1` 由 git 自己答的那句"是不是浅仓"决定,见 `readCloneFacts`),以及
2737
2979
  * `checkout --detach <那个 commit 的 sha>`(只在树干净时执行)。没有 `-f`、没有 `stash`、没有
@@ -2742,6 +2984,22 @@ export function resolveRemoteName({ remotes = [] } = {}) {
2742
2984
  * 拒绝;而那次 fetch 的落点(FETCH_HEAD)就是一个 sha,切它才是这一句本来的意思。
2743
2985
  */
2744
2986
  export function advanceExistingClone({ repoDir, ref, spawn = spawnSync } = {}) {
2987
+ // 第一件事不是"这棵树脏不脏",而是"要动的是不是这一棵"(S7-1,2026-10-29 P0):
2988
+ // `git -C <dir> …` 会落到离它最近的那棵树,所以从前这一支对着 `<外层repo>/vendored` 跑
2989
+ // `checkout --detach` 时,切走的是**外层的 main**(本轮实测:detach 完还回一句 advance: use)。
2990
+ // 这一问在这里独立跑一次,不靠 `readCloneFacts` 内部那道——两个函数都可能被单独调用,
2991
+ // 守卫住在各自开头才算各自守得住。
2992
+ const top = readRepoToplevel({ dir: repoDir, spawn })
2993
+ const toplevelProblem = toplevelProblemFor({ targetDir: repoDir, toplevel: top.toplevel, readOk: top.read })
2994
+ if (toplevelProblem) {
2995
+ return {
2996
+ action: 'refuse',
2997
+ blocking: [],
2998
+ toplevelProblem,
2999
+ toplevel: top.toplevel,
3000
+ text: toplevelRefuseText({ targetDir: repoDir, problem: toplevelProblem }),
3001
+ }
3002
+ }
2745
3003
  const read = (args) => spawn('git', ['-C', repoDir, ...args], { encoding: 'utf8' })
2746
3004
  const remoteNames = () => {
2747
3005
  const res = read(['remote'])
@@ -2955,7 +3213,7 @@ export function panelOpenHint({ panel, rootDir, settingsApp = null, exists = (p)
2955
3213
  runnable: true,
2956
3214
  target,
2957
3215
  text: info.viaBundle
2958
- ? `open "${target}"`
3216
+ ? `open ${quoteShellArg(target)}`
2959
3217
  : `直接执行裸二进制面板:"${target}"(当前没有 .app bundle,所以不经 open、没有 bundle 身份)`,
2960
3218
  }
2961
3219
  }
@@ -2988,7 +3246,7 @@ export function verificationFailureText({
2988
3246
  ? `安装未完成:socket 在(${socketPath}),但 daemon 没有正确应答 hello——见 ${daemonLog}`
2989
3247
  : `安装未完成:没有等到 daemon 在 ${socketPath} 应答 hello——见 ${daemonLog}`,
2990
3248
  `本命令退出码 ${exitCode}:install.sh 与调用它的脚本/agent 按安装失败处理,先别接 MCP。`,
2991
- `补救(不需要手敲 launchctl):node "${cliPath}" --restore-launchd`,
3249
+ `补救(不需要手敲 launchctl):node ${quoteShellArg(cliPath)} --restore-launchd`,
2992
3250
  '修好后重跑安装器即可(它会覆盖式重建产物与 plist)。',
2993
3251
  ].join('\n')
2994
3252
  }
@@ -3016,6 +3274,18 @@ export async function install({
3016
3274
  const homeDir = guard.home
3017
3275
  const pinRef = resolvePinRef(env)
3018
3276
 
3277
+ // 2026-10-31 P0:两个**显式**定位位排在 `fs.existsSync` 之前先过 looksLikeRepoHere。
3278
+ // 从前这里只问"在不在",于是一个存在的非仓库目录会被当成项目根交给 npm(见
3279
+ // locatedRootRefusal 的注释),而同一串 argv 在 install.sh 那一头回 1 且一个字节都没写。
3280
+ // 两条一键入口对同一串输入必须同判,且"能拒的守卫要在第一字节之前拒"是本仓的规矩。
3281
+ // 判据本体在 explicitLocatedRootRefusal 里——入口也调它一次,这样"这棵 argv 自己就不通"
3282
+ // 这件事不与主机平台有关(CI 的 Linux 那一格实测过:从前 install.sh 按判据拒、cli.js 按
3283
+ // "只支持 macOS"拒,同一串输入两句话)。
3284
+ {
3285
+ const refusal = explicitLocatedRootRefusal(options, env)
3286
+ if (refusal) throw new Error(refusal)
3287
+ }
3288
+
3019
3289
  let rootDir = explicitRoot ?? envRoot ?? resolveProjectRoot()
3020
3290
 
3021
3291
  if (!rootDir || !fs.existsSync(rootDir)) {
@@ -3066,7 +3336,9 @@ export async function install({
3066
3336
  })}\n\n${repoMissingText()}`,
3067
3337
  )
3068
3338
  }
3069
- if (resolveProjectRoot(plan.targetDir) === null) {
3339
+ // 核对的也是**这一层**:clone 出来的目录自己得有 marker。从前这里用 resolveProjectRoot,
3340
+ // 它会向上走,于是一棵内容不完整的 clone 只要落在某个仓库里就能被判成"结构完整"。
3341
+ if (!looksLikeRepoHere(plan.targetDir)) {
3070
3342
  throw new Error(`clone 完成但目录结构不完整:${plan.targetDir}\n\n${repoMissingText()}`)
3071
3343
  }
3072
3344
  rootDir = plan.targetDir
@@ -3444,24 +3716,47 @@ if (isMain) {
3444
3716
  // --restore-launchd/环境预检这四条还留着 `process.exit()`;Linux runner 上就是
3445
3717
  // 从这里现形的(那台机器没有 swift,预检拒绝必然走到,而测试原本指望走到 install
3446
3718
  // 的拒绝分支——一条依赖机器状态的断言)。
3447
- const { options, error } = parseArgs(process.argv.slice(2))
3719
+ const { options, error, errorKind } = parseArgs(process.argv.slice(2))
3720
+ // **两入口对同一串 argv 的用法错规则**(2026-10-31 P1;同一份规则写在 install.sh 的 2c' 上面):
3721
+ // 1. `--repo` 没接到取值、或接到的是一面旗标(`-` 开头,单双横线都算)——这是"这一层自己就
3722
+ // 说不通"的用法错,**先于 --help**:两条入口都退 2、都说那一句、都随后打 usage 页。
3723
+ // 带 --help 也一样退 2,因为 argv 在 --repo 那一枚上根本没写完。
3724
+ // 2. "未知参数"只有读了本文件的旗标清单才判得出来,而 install.sh 没有那份清单(也不许抄一份,
3725
+ // 那正是本仓反复修的"两份抄本没人对照")。所以这一档在 --help 面前**让位**:给了 --help
3726
+ // 就是要这一页,两条入口都退 0 并打出各自那一页;没给 --help 时由这里退 2。
3727
+ // 3. 单独的 --help / -h 仍旧退 0(CI 的 install-gate 与两份 README 钉的就是那个 0)。
3728
+ // 从前这里是 `else if (error)` 排在 `else if (options.help)` 前面,两个 kind 一起压过 help,
3729
+ // 于是 `--help --no-such-flag` 在这一头退 2、在 install.sh 那一头退 0(实测)——同一串 argv
3730
+ // 两个码,而按 rc 分叉的调用方读到的"2 = 命令行写错了"在两条入口之间漂移。
3448
3731
  // 平台判据住在 cli.js 这一侧才是权威的:`uname` 是 PATH 上一个可以被换掉的程序(本轮实测:
3449
3732
  // 桩一个 `uname` 说 Linux,install.sh 那一道只管挡"要 clone 的那一趟",源码在手边时一路走到
3450
3733
  // `exec node cli.js`,npm ci / tsc / swift build / launchd 注册全部真的发生),而
3451
- // `process.platform` 是 node 向主机问来的,桩不掉。放在 --help / 参数错误 / --restore-launchd
3452
- // 之后判:CI 的 install-gate 那一格跑在非 macOS 上,它读的正是 usage 与预检那几句。
3453
- const refusal = (error || options.help || options.restoreLaunchd) ? null : platformRefusal()
3454
- if (refusal) {
3455
- process.stderr.write(paint(`\n${refusal}\n`, 'red'))
3456
- process.exitCode = 1
3457
- } else if (error) {
3458
- process.stderr.write(`\n${paint(`参数错误:${error}`, 'red')}\n\n`)
3734
+ // `process.platform` 是 node 向主机问来的,桩不掉。
3735
+ // 但它**只压过"未知参数"那一档,不压 --help / --repo 的两类用法错 / 显式定位位的判据**
3736
+ // (2026-10-31,CI 的 Linux 那一格现形):从前这里把 `error` 也算进"跳过平台判据"的条件,
3737
+ // 于是 `--no-such-flag` 在非 macOS 上这头退 2、install.sh 那头退 1——而 install.sh 在把 argv
3738
+ // 交给本文件之前,只判得了它自己那份旗标(未知参数那一档必须由本文件回答)。同一串 argv
3739
+ // 两个码,按 rc 分叉的调用方就读了个寂寞。留下来的规则是:一台跑不了这个产品的机器上,
3740
+ // 第一句该说的是"这里跑不了"(rc 1),参数打错是它之后的事;`--help` 仍旧先赢(0)。
3741
+ const decision = entryDecision({ options, error, errorKind })
3742
+ // 每一支的退出码在这里**写死成字面量**:次序由 `entryDecision` 决定(那台跑不到的主机上的
3743
+ // 那一档因此可在本机整表验证),而"每条退出都走事件循环、每条分支都还在"由
3744
+ // `test/failure-exit.test.mjs` 扫这几行钉住——它认的是字面量,改成 `= decision.exitCode`
3745
+ // 会让那条闸看不见分支被删。
3746
+ if (decision.kind === 'usage-error') {
3747
+ process.stderr.write(`\n${paint(`参数错误:${decision.message}`, 'red')}\n\n`)
3459
3748
  process.stderr.write(usageText())
3460
3749
  process.exitCode = 2
3461
- } else if (options.help) {
3750
+ } else if (decision.kind === 'located-root') {
3751
+ process.stderr.write(`\n${paint(decision.message, 'red')}\n`)
3752
+ process.exitCode = 1
3753
+ } else if (decision.kind === 'help') {
3462
3754
  process.stdout.write(usageText())
3463
3755
  process.exitCode = 0
3464
- } else if (options.restoreLaunchd) {
3756
+ } else if (decision.kind === 'platform') {
3757
+ process.stderr.write(paint(`\n${decision.message}\n`, 'red'))
3758
+ process.exitCode = 1
3759
+ } else if (decision.kind === 'restore-launchd') {
3465
3760
  // 审计项④:恢复 + 校验全机器化,退出码即判定(0=daemon 就位且已按实际
3466
3761
  // 自报如实报告;1=作业/服务面失败),agent 可直接执行并按 message 续办。
3467
3762
  // finding C3:这一支也可能 bootout 一个已加载作业,所以它读同一个同意门——
package/glasspane.js CHANGED
@@ -37,9 +37,95 @@ export const VERBS = Object.freeze(['update', 'doctor', 'status', 'help'])
37
37
  export const VERB_ALIASES = Object.freeze({ '-h': 'help', '--help': 'help' })
38
38
  export const DAEMON_JOB_LABEL = 'com.glasspane.daemon'
39
39
  export const NPM_PACKAGES = Object.freeze(['glasspane-mcp', 'glasspane-install'])
40
+ /**
41
+ * The one line the npm remedy prints. It carries **no version placeholder on purpose**: the previous
42
+ * shape pinned each package to a version written inside angle brackets, and that opening bracket is a
43
+ * shell redirection — `/bin/sh -c '<那整行>'` fails with a syntax error (measured 2026-10-29, exit 2),
44
+ * so an agent copying the remedy could not even start the command. No version means "the registry's
45
+ * latest", which is what a missing package wants; pinning is a separate, explicit step
46
+ * (`npm view <pkg> versions`), and the remedy says so in prose instead of shipping an uncopyable token.
47
+ * Named and exported so a test can assert that *what is printed* is *what runs* — never a second copy
48
+ * of the command living in a template string.
49
+ */
50
+ export const NPM_GLOBAL_INSTALL_CMD = `npm install -g ${NPM_PACKAGES.join(' ')}`
40
51
  /** The three answers a read may give. `unverified` is the one that used to be missing everywhere. */
41
52
  export const READS = Object.freeze({ available: 'available', absent: 'absent', unverified: 'unverified' })
42
53
 
54
+ /** 要印进"可照抄的一行"里的原文,先剥掉 shell 元字符:npm 自己的原话带着 `'`、`<`、`|` 时,
55
+ * 那句话就不再能被 /bin/sh 解析了(S7-5 测的正是这一族)。裁的是元字符,不是信息。 */
56
+ function shellSafe(text) {
57
+ return String(text ?? '').replace(/[\n\r]/g, ' ').replace(/[<>&|;'"`\\$()]/g, '')
58
+ }
59
+
60
+ /**
61
+ * Is this machine's global npm prefix writable by *this* user? Three answers, same rule as READS:
62
+ * the claim printed in the remedy ("不需要权限") used to be backed by no probe at all — neither
63
+ * `npm prefix -g` nor a W_OK check happened anywhere in this file (or in the whole installer shard).
64
+ * `unverified` is therefore an answer of its own: "I could not look" is not "you do not need permission",
65
+ * and it is certainly not an escalation command.
66
+ */
67
+ export function probeGlobalNpmPrefix({
68
+ spawn = spawnSync,
69
+ exists = (p) => fs.existsSync(p),
70
+ writable = (p) => {
71
+ try {
72
+ fs.accessSync(p, fs.constants.W_OK)
73
+ return true
74
+ } catch {
75
+ return false
76
+ }
77
+ },
78
+ } = {}) {
79
+ const res = spawn('npm', ['prefix', '-g'], { encoding: 'utf8', timeout: 30_000 })
80
+ const status = typeof res?.status === 'number' ? res.status : null
81
+ if (status !== 0) {
82
+ return {
83
+ read: READS.unverified,
84
+ prefix: null,
85
+ target: null,
86
+ writable: null,
87
+ reason: status === null
88
+ ? `npm prefix -g 没答话(${res?.error?.message ?? String(res?.error ?? '没有退出码')})`
89
+ : `npm prefix -g 退出 ${status}`,
90
+ }
91
+ }
92
+ const prefix = String(res.stdout ?? '').trim()
93
+ if (prefix === '') return { read: READS.unverified, prefix: null, target: null, writable: null, reason: 'npm prefix -g 退 0 而答案是空的' }
94
+ // npm 真正落包的是 `<prefix>/lib/node_modules`;那一级不存在时退到 `lib`、再退到前缀本身——
95
+ // 要判的是"这一趟能不能写进去",所以问的是盘上真在的那一级。
96
+ const target = [path.join(prefix, 'lib', 'node_modules'), path.join(prefix, 'lib'), prefix].find((p) => exists(p)) ?? null
97
+ if (target === null) {
98
+ return { read: READS.unverified, prefix, target: null, writable: null, reason: `全局前缀 ${prefix} 在盘上不存在(lib/node_modules、lib、前缀本身三级都没读到目录)` }
99
+ }
100
+ return { read: READS.available, prefix, target, writable: writable(target) === true, reason: null }
101
+ }
102
+
103
+ /**
104
+ * The remedy line, composed from the probe's answer (pure: the three shapes are unit-testable without
105
+ * touching a machine). Never an escalation: when the prefix is not ours to write, the sentence names the
106
+ * prefix and the directory that refused W_OK and points at moving the prefix under the user — it does
107
+ * not hand out a privileged command (SECURITY.md §3, and this file's own header).
108
+ */
109
+ export function npmGlobalRemedy({ missing = [], prefixState } = {}) {
110
+ const named = missing.map((name) => shellSafe(name)).join(' ')
111
+ const cmd = NPM_GLOBAL_INSTALL_CMD
112
+ if (!prefixState || prefixState.read !== READS.available) {
113
+ const why = prefixState?.reason ?? '这一问没有答案'
114
+ return `补法(全局 npm 前缀的可写性**未验证**——${shellSafe(why)};这一问没答案,所以这一条不替你保证免权限):`
115
+ + `先让 npm prefix -g 能答话,再照这一行装 ${cmd}。不带版本号=取 registry 最新发布物,`
116
+ + `要钉版本先跑 npm view glasspane-mcp versions。缺的是 ${named || '(没读出来)'}。`
117
+ }
118
+ if (prefixState.writable === true) {
119
+ return `补法(不需要权限——本机探测过:全局前缀 ${shellSafe(prefixState.target)} 对本账号可写 W_OK):${cmd}。`
120
+ + `不带版本号=取 registry 最新发布物,要钉版本先跑 npm view glasspane-mcp versions。缺的是 ${named}。`
121
+ }
122
+ return `补法(**不给升权命令**:这台机器的全局 npm 前缀不可写——前缀 ${shellSafe(prefixState.prefix)},`
123
+ + `探测的是 ${shellSafe(prefixState.target)},它对 W_OK 答"不可写")。装进系统前缀不是这一层能替你做的事。`
124
+ + `下一步:先 npm config set prefix 指到一个你自己可写的目录(或用一个自带前缀的 Node 版本,nvm 就是这一档),`
125
+ + `再跑 ${cmd}(不带版本号=取 registry 最新发布物,要钉版本先跑 npm view glasspane-mcp versions)。缺的是 ${named}。`
126
+ }
127
+
128
+
43
129
  const POINTER_NAME = 'update-install.json'
44
130
  const STATE_NAME = 'update-state.json'
45
131
 
@@ -281,12 +367,14 @@ export function doctorReadings({
281
367
  const deps = npm.json.dependencies ?? {}
282
368
  const seen = NPM_PACKAGES.map((name) => `${name}=${deps[name]?.version ?? '没装'}`)
283
369
  const missing = NPM_PACKAGES.filter((name) => !deps[name])
370
+ // 缺包时要不要说"不需要权限",由这台机器答,不由这句话答(S7-5):先探一次全局前缀。
371
+ // 探测排在读完全局包之后、只在真要给出补法时才问——都在位时没人需要这一行。
284
372
  out.push({
285
373
  name: '全局 npm 包',
286
374
  read: missing.length === 0 ? READS.available : READS.absent,
287
375
  detail: seen.join(' '),
288
376
  remedy: missing.length === 0 ? null
289
- : `补法(不需要权限,取的是 registry 的发布物):npm install -g ${NPM_PACKAGES.map((n) => `${n}@<版本>`).join(' ')}`,
377
+ : npmGlobalRemedy({ missing, prefixState: probeGlobalNpmPrefix({ spawn, exists }) }),
290
378
  })
291
379
  }
292
380
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "glasspane-install",
3
- "version": "1.25.2",
3
+ "version": "1.27.0",
4
4
  "description": "GlassPane one-command installer: terminal onboarding → install deps → build TS + Swift engine → start daemon → open settings GUI for permission guide",
5
5
  "type": "module",
6
6
  "license": "MIT",