Open
feat: #16 安装脚本事务管线(预检查/备份/失败回滚) #3
grape_botAdd on Oct 20
feat: #16 安装脚本事务管线(预检查/备份/失败回滚) #3
Open
grape_botAdd on Oct 20
Merged fromfeat/issue-16intomain
Total: 7 files changed+954-76
MREADME.md+20-0
@@ -41,6 +41,26 @@ node ~/.dsh/skills/cutting-board/scripts/install.mjs <DSH检出目录>
41 41 
42脚本幂等,可重复运行;也可按 `assets/hub-sink.patch.md` 手动安装。42脚本幂等,可重复运行;也可按 `assets/hub-sink.patch.md` 手动安装。
43 43 
44+### 安装行为(事务管线)
45+ 
46+安装脚本在修改目标文件前会做预检查与备份,失败时自动回滚:
47+ 
48+1. **预检查**(零副作用):校验源资产、DSH checkout、`hub.ts` 双锚点、`tsc`/`pnpm` 可用性。
49+ 失败时不修改任何目标文件即退出(退出码 1)。
50+2. **备份**:将已存在的目标文件快照到系统临时目录(`os.tmpdir()`)下的时间戳目录,
51+ 安装成功/失败时均输出备份绝对路径。
52+3. **变更**:复制源码 → 注入 hub → 类型构建 → 重建 bundle。任一步失败触发回滚。
53+4. **回滚**:恢复已备份文件、清理本次新建文件;回滚失败时逐路径列出未恢复文件(退出码 3)。
54+ 
55+| 退出码 | 含义 |
56+|--------|------|
57+| 0 | 安装成功 |
58+| 1 | 预检查失败(未修改任何文件) |
59+| 2 | 变更失败,已回滚(目标文件恢复到安装前状态) |
60+| 3 | 变更失败且回滚不完整(未恢复路径见 stderr) |
61+ 
62+> 断电/跨进程等非当次失败不在回滚保证范围内;回滚在当次进程内同步完成。
63+ 
44## 生效与验证64## 生效与验证
45 65 
46DSH 服务器按请求从磁盘提供插件 bundle(`/plugins/<包名>/client.js`),且 client-hmr66DSH 服务器按请求从磁盘提供插件 bundle(`/plugins/<包名>/client.js`),且 client-hmr
@@ -35,6 +35,10 @@ whenToUse: 用户提到 剪切板/剪贴板 记录、cutting-board,或要求
35 (已注入则跳过;锚点不匹配则报错并指向 `assets/hub-sink.patch.md` 手动补丁);35 (已注入则跳过;锚点不匹配则报错并指向 `assets/hub-sink.patch.md` 手动补丁);
36 3. `tsc -b tsconfig.client.json` 类型构建;36 3. `tsc -b tsconfig.client.json` 类型构建;
37 4. `pnpm --filter @deepseek-ai/dsh-client-ui-conversation run bundle` 重建浏览器 bundle。37 4. `pnpm --filter @deepseek-ai/dsh-client-ui-conversation run bundle` 重建浏览器 bundle。
38+ 
39+ 安装脚本采用事务管线:预检查(零副作用)→ 备份(系统临时目录时间戳目录)→ 变更 → 失败回滚。
40+ 退出码:0=成功 / 1=预检查失败 / 2=变更失败已回滚 / 3=回滚不完整(未恢复路径见 stderr)。
41+ 安装成功或失败时均输出备份绝对路径。
383. **生效方式**:DSH 服务器按请求从磁盘提供 `/plugins/<包名>/client.js`,且 client-hmr423. **生效方式**:DSH 服务器按请求从磁盘提供 `/plugins/<包名>/client.js`,且 client-hmr
39 会在 bundle 变化后热重载已打开的页面 —— 一般无需重启服务器;让用户刷新一次页面最稳妥。43 会在 bundle 变化后热重载已打开的页面 —— 一般无需重启服务器;让用户刷新一次页面最稳妥。
40 **已知边界**:安装引发的热替换若恰好发生在对话进行中,输入框可能消失(框架热替换的表现,44 **已知边界**:安装引发的热替换若恰好发生在对话进行中,输入框可能消失(框架热替换的表现,
@@ -0,0 +1,75 @@
1+# Implementation Plan: Issue #16 — 安装脚本事务管线
2+ 
3+## Overview
4+将 `scripts/install.mjs` 从「直接写入」线性流程重构为 **预检查 → 备份 → 变更 → 失败回滚** 的类事务流水线,保持现有安装功能与幂等性零回归。
5+ 
6+## Architecture Decisions
7+ 
8+| 决策 | 选择 | 理由 |
9+|------|------|------|
10+| 备份位置 | `os.tmpdir()` 时间戳目录 | 不污染 DSH checkout 的 git 状态;当次进程内同步回滚 |
11+| 失败信号 | 返回值 `{ ok, exitCode, ... }`,CLI 入口退出 | 可测试(不直接 `process.exit`);调用方按退出码区分失败类型 |
12+| 退出码 | 0=成功 / 1=预检查失败 / 2=变更失败(已回滚) / 3=回滚失败(部分未恢复) | 区分失败层级,便于脚本/Agent 判断 |
13+| tsc 产物 | 不纳入备份 | 源码可再生,回滚源文件后重跑构建即可 |
14+| bundle 产物 | best-effort 备份 | 存在则备份+回滚恢复;不存在则报告中注明 |
15+| 重装幂等 | 一律备份 | 已有文件可能含用户修改,备份与幂等不冲突 |
16+| 测试注入 | `options.run` / `options.assetsDir` / `options.backupRoot` 可覆盖 | 零外部依赖即可模拟构建失败、源资产缺失等场景 |
17+ 
18+## Pipeline 设计
19+ 
20+```
21+┌─────────────────────────────────────────────────────────┐
22+│ 1. precheck(零副作用) │
23+│ 源资产存在 / checkout 有效 / hub.ts 存在 │
24+│ hub 双锚点可命中(或已打补丁)/ tsc 存在 / pnpm 可用 │
25+│ 任一失败 → return { ok:false, exitCode:1 } │
26+├─────────────────────────────────────────────────────────┤
27+│ 2. backup │
28+│ mkdir tmpdir/cutting-board-backup-{stamp}-{pid} │
29+│ 已存在文件 → copy 到 backup dir (backedUp[]) │
30+│ 不存在文件 → 记入 newFiles[] │
31+│ bundle 产物 best-effort 备份 │
32+│ log 备份位置 │
33+├─────────────────────────────────────────────────────────┤
34+│ 3. changes(try 块,异常统一捕获) │
35+│ mkdir clipboardDir │
36+│ copy 4 assets │
37+│ patch hub.ts(已打补丁则跳过) │
38+│ run tsc -b │
39+│ run pnpm bundle │
40+│ 任一失败 → catch → 进入 rollback │
41+├─────────────────────────────────────────────────────────┤
42+│ 4a. rollback(失败时) │
43+│ 恢复 backedUp 文件 / 删除 newFiles │
44+│ 失败路径收集到 failures[] │
45+│ failures 非空 → exitCode:3 │
46+│ failures 空 → exitCode:2 │
47+├─────────────────────────────────────────────────────────┤
48+│ 4b. success(成功时) │
49+│ log 备份位置 + 手动恢复提示 │
50+│ return { ok:true, backupDir } │
51+└─────────────────────────────────────────────────────────┘
52+```
53+ 
54+## 函数签名
55+ 
56+```javascript
57+export function install(checkout, options = {}) {
58+ // options: { log, err, run, backupRoot, assetsDir }
59+ // returns: { ok:true, backupDir } | { ok:false, exitCode, message, backupDir?, rollbackFailures? }
60+}
61+```
62+ 
63+- `run(command, args, cwd)` → `{ status }`(spawnSync 兼容),默认用 `spawnSync`,测试可注入 mock。
64+- CLI 入口 `cli()` 解析 argv、调用 `install()`、按 `exitCode` 退出。
65+ 
66+## Risks and Mitigations
67+| Risk | Impact | Mitigation |
68+|------|--------|------------|
69+| DSH checkout 布局变化导致锚点失效 | Med | 预检查显式报锚点缺失,保留手工补丁指引 |
70+| 临时目录被清理导致备份丢失 | Low | 回滚在当次进程内同步完成;成功路径输出恢复提示 |
71+| 构建产物未恢复造成源/产物不一致 | Med | 回滚报告注明 bundle 状态与再生成方式 |
72+| 回滚自身失败 | Med | 逐文件独立恢复,失败路径显式列出,exitCode:3 |
73+ 
74+## Open Questions
75+无。
@@ -0,0 +1,65 @@
1+# Spec: Issue #16 — 安装脚本增加文件备份与失败回滚机制
2+ 
3+## Objective
4+为 `scripts/install.mjs` 增加安装前预检查、修改前备份、失败自动回滚机制,在不改变现有安装功能与幂等性行为的前提下,消除三类风险:重复安装覆盖用户修改、失败后状态不一致、无恢复机制。
5+ 
6+- 用户:在 DSH checkout 上安装/重复安装 cutting-board 技能的用户(含其他 Agent / 其他机器)。
7+- 成功标准:注入或构建失败后目标源文件恢复到安装前状态;备份位置有明确输出;现有功能零回归。
8+ 
9+## Tech Stack
10+- Node.js ≥ 18(ESM `.mjs`),仅使用内置模块:`node:child_process`、`node:fs`、`node:os`、`node:path`、`node:url`。
11+- 测试:Node 内置 `node:test` + `node:assert/strict`(零外部依赖)。
12+- 无新增外部依赖,不引入 package.json 的运行时依赖。
13+ 
14+## Commands
15+```bash
16+# 安装(用户侧)
17+node scripts/install.mjs [dsh-checkout-dir]
18+ 
19+# 测试(开发侧)
20+node --test scripts/
21+```
22+ 
23+## Project Structure
24+```
25+scripts/
26+├── install.mjs # 安装器(事务管线:precheck → backup → change → rollback)
27+└── install.test.mjs # 安装器测试(4 类失败场景 + 成功路径 + 幂等性)
28+docs/issue-16/
29+├── spec.md # 本文件(需求文档)
30+├── plan.md # 方案设计
31+└── task.md # 任务拆解
32+```
33+ 
34+## Code Style
35+- ESM `.mjs`,与现有 `install.mjs` 一致:`import` 语句、`const` 常量、函数式风格。
36+- 错误通过返回值 `{ ok, exitCode, message, ... }` 表达(不直接 `process.exit`),CLI 入口负责退出码。
37+- 注释仅在非显然处添加(事务边界、回滚语义)。
38+ 
39+## Testing Strategy
40+- 框架:`node:test`(内置),测试文件 `scripts/install.test.mjs`。
41+- 层级:集成测试(Medium)—— 用 `mkdtempSync` 构造临时 DSH checkout,注入 mock `run` 函数模拟构建命令。
42+- 覆盖场景:
43+ 1. 预检查失败(源资产缺失 / checkout 无效 / hub 锚点缺失 / tsc 缺失 / pnpm 缺失)→ 零文件改动
44+ 2. 注入失败(hub 写入异常)→ hub.ts 恢复
45+ 3. 构建失败(tsc / pnpm 非零退出)→ 已覆盖文件恢复、新建文件清理
46+ 4. 回滚失败(备份文件被删)→ 未恢复路径显式列出
47+ 5. 成功路径 → 备份位置输出
48+ 6. 幂等性 → 重复安装先备份再覆盖
49+ 
50+## Boundaries
51+- **Always:** 修改前先备份;失败后回滚;回滚失败显式列路径;保留现有幂等性。
52+- **Ask first:** 改变退出码语义、引入新依赖。
53+- **Never:** 修改 `assets/` 运行时代码、修改 hub.ts 注入内容、写入 token/密钥到文件。
54+ 
55+## Success Criteria
56+- [ ] 预检查失败时未修改任何目标文件即终止
57+- [ ] 重复安装先备份再覆盖,输出备份位置
58+- [ ] 注入/构建失败后源文件恢复到安装前状态
59+- [ ] 新建文件回滚时清理
60+- [ ] 回滚失败逐路径列出未恢复文件
61+- [ ] 现有功能与幂等性零回归
62+- [ ] 新增测试覆盖四类失败场景
63+ 
64+## Open Questions
65+无(Spec 已由 issue agent 确认为 ready)。
@@ -0,0 +1,74 @@
1+# Task List: Issue #16 — 安装脚本事务管线
2+ 
3+## Task 1: 重构 install.mjs 为事务管线
4+ 
5+**Description:** 将 `scripts/install.mjs` 从线性直接写入重构为 precheck → backup → change → rollback 管线,导出 `install()` 函数供测试调用。
6+ 
7+**Acceptance criteria:**
8+- [ ] 预检查覆盖:4 源资产 / checkout 有效 / hub.ts 存在 / 双锚点(或已打补丁)/ tsc 存在 / pnpm 可用
9+- [ ] 预检查失败时未修改任何目标文件
10+- [ ] 备份到 `os.tmpdir()` 时间戳目录,输出绝对路径
11+- [ ] 变更阶段(copy/inject/build)包入 try 块,异常统一捕获
12+- [ ] 回滚:恢复已备份文件 + 删除新建文件
13+- [ ] 回滚失败逐路径列出
14+- [ ] 退出码:0/1/2/3 区分
15+- [ ] 幂等:已打补丁 hub 跳过注入,已有文件仍先备份
16+- [ ] 现有 CLI 行为(argv 解析、detectCheckout、log 输出)不变
17+ 
18+**Verify:** `node scripts/install.mjs --help` 不报语法错;`node --check scripts/install.mjs` 通过
19+ 
20+**Dependencies:** None
21+ 
22+**Files:** `scripts/install.mjs`
23+ 
24+**Estimated scope:** Medium(单文件,~200 行)
25+ 
26+---
27+ 
28+## Task 2: 新增测试覆盖四类失败场景
29+ 
30+**Description:** 用 `node:test` + 临时目录构造 fake DSH checkout,覆盖预检查失败 / 注入失败 / 构建失败 / 回滚失败 + 成功路径 + 幂等性。
31+ 
32+**Acceptance criteria:**
33+- [ ] 预检查失败:源资产缺失 / checkout 无效 / hub 缺失 / 锚点缺失 / tsc 缺失 / pnpm 缺失 → 零文件改动
34+- [ ] 注入失败:hub.ts 恢复到安装前内容
35+- [ ] 构建失败(tsc 非零):clipboard 资产恢复 / 新建文件清理
36+- [ ] 构建失败(pnpm 非零):同上
37+- [ ] 回滚失败:备份文件被删 → 未恢复路径列出
38+- [ ] 成功路径:4 资产复制 / hub 注入 / 备份位置输出
39+- [ ] 幂等性:重复安装先备份再覆盖,已打补丁 hub 跳过注入
40+ 
41+**Verify:** `node --test scripts/` 全部通过
42+ 
43+**Dependencies:** Task 1
44+ 
45+**Files:** `scripts/install.test.mjs`
46+ 
47+**Estimated scope:** Medium(单文件,~300 行)
48+ 
49+---
50+ 
51+## Task 3: 文档更新
52+ 
53+**Description:** 更新 README.md / SKILL.md 中安装脚本行为说明(备份位置输出、失败回滚、退出码语义)。
54+ 
55+**Acceptance criteria:**
56+- [ ] README.md 安装一节注明事务行为与备份位置输出
57+- [ ] SKILL.md 安装流程说明保持一致
58+- [ ] 不夸大(断电/跨进程失败不在保证范围)
59+ 
60+**Verify:** 文档审阅
61+ 
62+**Dependencies:** Task 1
63+ 
64+**Files:** `README.md`, `SKILL.md`
65+ 
66+**Estimated scope:** Small
67+ 
68+---
69+ 
70+## Checkpoint: Complete
71+- [ ] 所有测试通过:`node --test scripts/`
72+- [ ] 语法检查:`node --check scripts/install.mjs`
73+- [ ] 自审查 5 轴通过
74+- [ ] 准备创建 PR
@@ -1,12 +1,16 @@
1#!/usr/bin/env node1#!/usr/bin/env node
2/**2/**
3- * cutting-board skill installer.3+ * cutting-board skill installer (transactional).
4 *4 *
5- * Copies the clipboard-panel sources bundled in this skill into a DSH5+ * Pipeline: precheck (zero side-effects) → backup → changes (copy/inject/build) →
6- * checkout's ui-conversation package, injects the composer-trigger hook into6+ * rollback on failure. Idempotent: safe to run repeatedly; an already-patched hub
7- * the input hub, type-builds, and rebuilds the client bundle. Idempotent:7+ * skips injection but existing target files are still backed up before overwrite.
8- * safe to run repeatedly (existing files are overwritten; an already-patched8+ *
9- * hub is left alone).9+ * Exit codes:
10+ * 0 install succeeded
11+ * 1 precheck failed (no target file was modified)
12+ * 2 change phase failed and rollback succeeded (target restored)
13+ * 3 change phase failed and rollback was incomplete (unrestored paths listed)
10 *14 *
11 * Usage:15 * Usage:
12 * node install.mjs [dsh-checkout-dir]16 * node install.mjs [dsh-checkout-dir]
@@ -15,9 +19,17 @@
15 * looking for packages/client/ui-conversation/package.json.19 * looking for packages/client/ui-conversation/package.json.
16 */20 */
17import { spawnSync } from 'node:child_process'21import { spawnSync } from 'node:child_process'
18-import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'22+import {
23+ copyFileSync,
24+ existsSync,
25+ mkdirSync,
26+ readFileSync,
27+ rmSync,
28+ writeFileSync,
29+} from 'node:fs'
30+import { tmpdir } from 'node:os'
19import { dirname, join, resolve } from 'node:path'31import { dirname, join, resolve } from 'node:path'
20-import { fileURLToPath } from 'node:url'32+import { fileURLToPath, pathToFileURL } from 'node:url'
21 33 
22const scriptDir = dirname(fileURLToPath(import.meta.url))34const scriptDir = dirname(fileURLToPath(import.meta.url))
23const skillRoot = dirname(scriptDir)35const skillRoot = dirname(scriptDir)
@@ -25,18 +37,28 @@ const assetsDir = join(skillRoot, 'assets')
25const ASSETS = ['history.ts', 'recorder.ts', 'panel.tsx', 'panel.module.css']37const ASSETS = ['history.ts', 'recorder.ts', 'panel.tsx', 'panel.module.css']
26const HUB_RELATIVE = join('packages', 'client', 'ui-conversation', 'src', 'client', 'input', 'hub.ts')38const HUB_RELATIVE = join('packages', 'client', 'ui-conversation', 'src', 'client', 'input', 'hub.ts')
27const CLIPBOARD_DIR_RELATIVE = join('packages', 'client', 'ui-conversation', 'src', 'client', 'clipboard')39const CLIPBOARD_DIR_RELATIVE = join('packages', 'client', 'ui-conversation', 'src', 'client', 'clipboard')
40+const BUNDLE_RELATIVE = join('packages', 'client', 'ui-conversation', 'lib', 'client.js')
41+const TSC_RELATIVE = join('node_modules', 'typescript', 'bin', 'tsc')
28 42 
29-function log(message) {43+const ANCHOR_IMPORT = "import { queueReadFaceOf } from './queue-store.ts'"
44+const ANCHOR_SINK = " if (text === '' && attachmentIds.length === 0) return Promise.resolve({ kind: 'success' })"
45+const PATCH_MARKER = 'isClipboardTrigger'
46+ 
47+export const EXIT_OK = 0
48+export const EXIT_PRECHECK = 1
49+export const EXIT_CHANGE = 2
50+export const EXIT_ROLLBACK = 3
51+ 
52+function defaultLog(message) {
30 process.stdout.write(`[cutting-board] ${message}\n`)53 process.stdout.write(`[cutting-board] ${message}\n`)
31}54}
32 55 
33-function fail(message) {56+function defaultErr(message) {
34 process.stderr.write(`[cutting-board] ERROR: ${message}\n`)57 process.stderr.write(`[cutting-board] ERROR: ${message}\n`)
35- process.exit(1)
36}58}
37 59 
38/** Walk up from startDir looking for a DSH checkout. */60/** Walk up from startDir looking for a DSH checkout. */
39-function detectCheckout(startDir) {61+export function detectCheckout(startDir) {
40 let current = resolve(startDir)62 let current = resolve(startDir)
41 for (;;) {63 for (;;) {
42 if (existsSync(join(current, 'packages', 'client', 'ui-conversation', 'package.json'))) return current64 if (existsSync(join(current, 'packages', 'client', 'ui-conversation', 'package.json'))) return current
@@ -46,77 +68,215 @@ function detectCheckout(startDir) {
46 }68 }
47}69}
48 70 
49-function run(command, args, cwd) {71+function defaultRun(command, args, cwd) {
50- log(`$ ${command} ${args.join(' ')} (cwd: ${cwd})`)72+ return spawnSync(command, args, { cwd, stdio: 'inherit', shell: process.platform === 'win32' })
51- const result = spawnSync(command, args, { cwd, stdio: 'inherit', shell: process.platform === 'win32' })
52- if (result.status !== 0) fail(`command failed with exit code ${String(result.status)}: ${command} ${args.join(' ')}`)
53}73}
54 74 
55-// --- 1. resolve the target checkout ---------------------------------------75+/**
76+ * Run the transactional install pipeline.
77+ *
78+ * @param {string} checkout - absolute path to DSH checkout root
79+ * @param {object} [options]
80+ * @param {function} [options.log] - logger for normal output
81+ * @param {function} [options.err] - logger for error output
82+ * @param {function} [options.run] - (command, args, cwd) => { status } spawnSync-like
83+ * @param {string} [options.backupRoot] - override backup parent dir (testing)
84+ * @param {string} [options.assetsDir] - override source assets dir (testing)
85+ * @returns {{ ok: true, backupDir: string } | { ok: false, exitCode: number, message: string, backupDir?: string, rollbackFailures?: string[] }}
86+ */
87+export function install(checkout, options = {}) {
88+ const log = options.log ?? defaultLog
89+ const err = options.err ?? defaultErr
90+ const run = options.run ?? defaultRun
91+ const backupRoot = options.backupRoot ?? tmpdir()
92+ const srcAssetsDir = options.assetsDir ?? assetsDir
56 93 
57-const checkout = resolve(process.argv[2] ?? detectCheckout(process.cwd()) ?? '')94+ const clipboardDir = join(checkout, CLIPBOARD_DIR_RELATIVE)
58-if (!existsSync(join(checkout, 'packages', 'client', 'ui-conversation', 'package.json'))) {95+ const hubPath = join(checkout, HUB_RELATIVE)
59- fail(`no DSH checkout at "${checkout}" — pass the checkout directory that contains packages/client/ui-conversation`)96+ const bundlePath = join(checkout, BUNDLE_RELATIVE)
60-}97+ const tscPath = join(checkout, TSC_RELATIVE)
61-log(`target checkout: ${checkout}`)
62 98 
63-// --- 2. copy the clipboard panel sources ----------------------------------99+ // --- 1. precheck (zero side-effects) ------------------------------------
64 100 
65-const clipboardDir = join(checkout, CLIPBOARD_DIR_RELATIVE)101+ const precheckFail = (msg) => ({ ok: false, exitCode: EXIT_PRECHECK, message: msg })
66-mkdirSync(clipboardDir, { recursive: true })102+ 
67-for (const asset of ASSETS) {103+ for (const asset of ASSETS) {
68- const source = join(assetsDir, asset)104+ if (!existsSync(join(srcAssetsDir, asset))) {
69- if (!existsSync(source)) fail(`skill asset missing: ${source}`)105+ return precheckFail(`skill asset missing: ${join(srcAssetsDir, asset)}`)
70- copyFileSync(source, join(clipboardDir, asset))106+ }
71- log(`copied ${asset}`)107+ }
108+ if (!existsSync(join(checkout, 'packages', 'client', 'ui-conversation', 'package.json'))) {
109+ return precheckFail(`no DSH checkout at "${checkout}" — pass the checkout directory that contains packages/client/ui-conversation`)
110+ }
111+ if (!existsSync(hubPath)) return precheckFail(`input hub not found: ${hubPath}`)
112+ 
113+ const hubOriginal = readFileSync(hubPath, 'utf8')
114+ const alreadyPatched = hubOriginal.includes(PATCH_MARKER)
115+ if (!alreadyPatched) {
116+ if (!hubOriginal.includes(ANCHOR_IMPORT)) {
117+ return precheckFail('hub.ts anchor for imports not found; patch manually per assets/hub-sink.patch.md')
118+ }
119+ if (!hubOriginal.includes(ANCHOR_SINK)) {
120+ return precheckFail('hub.ts anchor for the sink guard not found; patch manually per assets/hub-sink.patch.md')
121+ }
122+ }
123+ 
124+ if (!existsSync(tscPath)) {
125+ return precheckFail(`typescript compiler not found: ${tscPath} (run pnpm install in the checkout first)`)
126+ }
127+ const pnpmProbe = run('pnpm', ['--version'])
128+ if (pnpmProbe.status !== 0) {
129+ return precheckFail('pnpm not available on PATH (install pnpm before running this installer)')
130+ }
131+ 
132+ log(`target checkout: ${checkout}`)
133+ 
134+ // --- 2. backup ----------------------------------------------------------
135+ 
136+ const stamp = new Date().toISOString().replace(/[:.]/g, '-')
137+ const backupDir = join(backupRoot, `cutting-board-backup-${stamp}-${process.pid}`)
138+ mkdirSync(backupDir, { recursive: true })
139+ 
140+ /** Files that existed before install and were snapshotted. */
141+ const backedUp = []
142+ /** Files that did not exist before install and should be deleted on rollback. */
143+ const newFiles = []
144+ 
145+ for (const asset of ASSETS) {
146+ const dest = join(clipboardDir, asset)
147+ if (existsSync(dest)) {
148+ const backup = join(backupDir, `clipboard__${asset}.bak`)
149+ copyFileSync(dest, backup)
150+ backedUp.push({ dest, backup })
151+ } else {
152+ newFiles.push(dest)
153+ }
154+ }
155+ 
156+ // hub.ts always exists (precheck passed) — always back up.
157+ const hubBackup = join(backupDir, 'hub.ts.bak')
158+ copyFileSync(hubPath, hubBackup)
159+ backedUp.push({ dest: hubPath, backup: hubBackup })
160+ 
161+ // bundle artifact: best-effort.
162+ let bundleBackedUp = false
163+ if (existsSync(bundlePath)) {
164+ try {
165+ const bundleBackup = join(backupDir, 'client.js.bak')
166+ copyFileSync(bundlePath, bundleBackup)
167+ backedUp.push({ dest: bundlePath, backup: bundleBackup })
168+ bundleBackedUp = true
169+ } catch {
170+ log('bundle artifact backup failed (best-effort, skipped)')
171+ }
172+ }
173+ 
174+ log(`backup: ${backedUp.length} file(s) → ${backupDir}`)
175+ 
176+ // --- 3. changes (copy / inject / build, unified try) --------------------
177+ 
178+ const rollback = () => {
179+ const failures = []
180+ for (const { dest, backup } of backedUp) {
181+ try {
182+ copyFileSync(backup, dest)
183+ } catch {
184+ failures.push(dest)
185+ }
186+ }
187+ for (const dest of newFiles) {
188+ try {
189+ rmSync(dest, { force: true })
190+ } catch {
191+ failures.push(dest)
192+ }
193+ }
194+ return failures
195+ }
196+ 
197+ try {
198+ mkdirSync(clipboardDir, { recursive: true })
199+ for (const asset of ASSETS) {
200+ copyFileSync(join(srcAssetsDir, asset), join(clipboardDir, asset))
201+ log(`copied ${asset}`)
202+ }
203+ 
204+ if (alreadyPatched) {
205+ log('hub.ts already patched — skipping injection')
206+ } else {
207+ let hub = hubOriginal
208+ const importInjection = [
209+ ANCHOR_IMPORT,
210+ "import { isClipboardTrigger } from '../clipboard/history.ts'",
211+ "import { openClipboardPanel } from '../clipboard/panel.tsx'",
212+ ].join('\n')
213+ hub = hub.replace(ANCHOR_IMPORT, importInjection)
214+ 
215+ const sinkInjection = [
216+ ANCHOR_SINK,
217+ ' if (attachmentIds.length === 0 && isClipboardTrigger(text)) {',
218+ ' openClipboardPanel()',
219+ " return Promise.resolve({ kind: 'success' })",
220+ ' }',
221+ ].join('\n')
222+ hub = hub.replace(ANCHOR_SINK, sinkInjection)
223+ 
224+ writeFileSync(hubPath, hub, 'utf8')
225+ log('patched hub.ts (clipboard trigger + panel open)')
226+ }
227+ 
228+ log('type-building client packages (tsc -b tsconfig.client.json)…')
229+ const tscResult = run(process.execPath, [tscPath, '-b', 'tsconfig.client.json'], checkout)
230+ if (tscResult.status !== 0) throw new Error(`tsc failed with exit code ${String(tscResult.status)}`)
231+ 
232+ log('rebuilding the ui-conversation client bundle…')
233+ const bundleResult = run('pnpm', ['--filter', '@deepseek-ai/dsh-client-ui-conversation', 'run', 'bundle'], checkout)
234+ if (bundleResult.status !== 0) throw new Error(`pnpm bundle failed with exit code ${String(bundleResult.status)}`)
235+ } catch (e) {
236+ err(`change phase failed: ${e.message}`)
237+ err('rolling back target files to pre-install state…')
238+ const failures = rollback()
239+ if (failures.length > 0) {
240+ err('rollback could not restore the following files (manual recovery needed):')
241+ for (const f of failures) err(` - ${f}`)
242+ err(`backup retained at: ${backupDir}`)
243+ return { ok: false, exitCode: EXIT_ROLLBACK, message: e.message, backupDir, rollbackFailures: failures }
244+ }
245+ err('rollback complete — target files restored to pre-install state.')
246+ err(`backup retained at: ${backupDir}`)
247+ if (!bundleBackedUp) {
248+ err('note: bundle artifact was not backed up (did not exist pre-install); rebuild it via the install command after fixing the root cause.')
249+ }
250+ return { ok: false, exitCode: EXIT_CHANGE, message: e.message, backupDir }
251+ }
252+ 
253+ // --- 4. success ---------------------------------------------------------
254+ 
255+ log('install complete.')
256+ log(`backup retained at: ${backupDir} (use it to restore files if needed).`)
257+ log('usage: type 显示剪切板 / 打开剪切板 in the Web GUI composer and press Enter.')
258+ log('IMPORTANT: have the user refresh the Web GUI page once after this install.')
259+ log('The rebuild hot-swaps the conversation plugin; if a turn was running during')
260+ log('the swap, the composer can vanish until that refresh. This is a framework')
261+ log('hot-swap quirk, unrelated to the clipboard feature itself.')
262+ return { ok: true, backupDir }
72}263}
73 264 
74-// --- 3. patch the input hub ------------------------------------------------265+// --- CLI entry ------------------------------------------------------------
75 266 
76-const hubPath = join(checkout, HUB_RELATIVE)267+function cli() {
77-if (!existsSync(hubPath)) fail(`input hub not found: ${hubPath}`)268+ const checkout = resolve(process.argv[2] ?? detectCheckout(process.cwd()) ?? '')
78-let hub = readFileSync(hubPath, 'utf8')269+ const result = install(checkout)
79- 270+ if (result.ok) {
80-if (hub.includes('isClipboardTrigger')) {271+ process.exit(EXIT_OK)
81- log('hub.ts already patched — skipping injection')272+ }
82-} else {273+ // Precheck failures: install() did not print the error, so print it here.
83- const anchorImport = "import { queueReadFaceOf } from './queue-store.ts'"274+ // Change/rollback failures: install() already printed full context via err().
84- const importInjection = [275+ if (result.exitCode === EXIT_PRECHECK) {
85- anchorImport,276+ defaultErr(result.message)
86- "import { isClipboardTrigger } from '../clipboard/history.ts'",277+ }
87- "import { openClipboardPanel } from '../clipboard/panel.tsx'",278+ process.exit(result.exitCode)
88- ].join('\n')
89- if (!hub.includes(anchorImport)) fail('hub.ts anchor for imports not found; patch manually per assets/hub-sink.patch.md')
90- hub = hub.replace(anchorImport, importInjection)
91- 
92- const anchorSink = " if (text === '' && attachmentIds.length === 0) return Promise.resolve({ kind: 'success' })"
93- const sinkInjection = [
94- anchorSink,
95- ' if (attachmentIds.length === 0 && isClipboardTrigger(text)) {',
96- ' openClipboardPanel()',
97- " return Promise.resolve({ kind: 'success' })",
98- ' }',
99- ].join('\n')
100- if (!hub.includes(anchorSink)) fail('hub.ts anchor for the sink guard not found; patch manually per assets/hub-sink.patch.md')
101- hub = hub.replace(anchorSink, sinkInjection)
102- 
103- writeFileSync(hubPath, hub, 'utf8')
104- log('patched hub.ts (clipboard trigger + panel open)')
105}279}
106 280 
107-// --- 4. build ---------------------------------------------------------------281+const isMain = import.meta.url === pathToFileURL(process.argv[1]).href
108- 282+if (isMain) cli()
109-log('type-building client packages (tsc -b tsconfig.client.json)…')
110-run(process.execPath, ['./node_modules/typescript/bin/tsc', '-b', 'tsconfig.client.json'], checkout)
111- 
112-log('rebuilding the ui-conversation client bundle…')
113-run('pnpm', ['--filter', '@deepseek-ai/dsh-client-ui-conversation', 'run', 'bundle'], checkout)
114- 
115-// --- 5. done ----------------------------------------------------------------
116- 
117-log('install complete.')
118-log('usage: type 显示剪切板 / 打开剪切板 in the Web GUI composer and press Enter.')
119-log('IMPORTANT: have the user refresh the Web GUI page once after this install.')
120-log('The rebuild hot-swaps the conversation plugin; if a turn was running during')
121-log('the swap, the composer can vanish until that refresh. This is a framework')
122-log('hot-swap quirk, unrelated to the clipboard feature itself.')
@@ -0,0 +1,480 @@
1+import { test } from 'node:test'
2+import assert from 'node:assert/strict'
3+import {
4+ chmodSync,
5+ copyFileSync,
6+ existsSync,
7+ mkdirSync,
8+ mkdtempSync,
9+ readdirSync,
10+ readFileSync,
11+ rmSync,
12+ writeFileSync,
13+} from 'node:fs'
14+import { tmpdir } from 'node:os'
15+import { dirname, join } from 'node:path'
16+import { fileURLToPath } from 'node:url'
17+ 
18+import { install, detectCheckout, EXIT_OK, EXIT_PRECHECK, EXIT_CHANGE, EXIT_ROLLBACK } from './install.mjs'
19+ 
20+const __dirname = dirname(fileURLToPath(import.meta.url))
21+const realAssetsDir = join(__dirname, '..', 'assets')
22+const ASSETS = ['history.ts', 'recorder.ts', 'panel.tsx', 'panel.module.css']
23+ 
24+const ANCHOR_IMPORT = "import { queueReadFaceOf } from './queue-store.ts'"
25+const ANCHOR_SINK = " if (text === '' && attachmentIds.length === 0) return Promise.resolve({ kind: 'success' })"
26+ 
27+const HUB_TEMPLATE = [
28+ "// fake hub.ts for testing",
29+ ANCHOR_IMPORT,
30+ "",
31+ "export class InputHub {",
32+ " private sink() {",
33+ ` ${ANCHOR_SINK.trim()}`,
34+ " return this.conversation().sendSession()",
35+ " }",
36+ "}",
37+].join('\n')
38+ 
39+const HUB_PATCHED = [
40+ "// fake hub.ts already patched",
41+ "import { isClipboardTrigger } from '../clipboard/history.ts'",
42+ ANCHOR_IMPORT,
43+ "",
44+ "export class InputHub {",
45+ " private sink() {",
46+ ` ${ANCHOR_SINK.trim()}`,
47+ " if (attachmentIds.length === 0 && isClipboardTrigger(text)) {",
48+ " openClipboardPanel()",
49+ " return Promise.resolve({ kind: 'success' })",
50+ " }",
51+ " return this.conversation().sendSession()",
52+ " }",
53+ "}",
54+].join('\n')
55+ 
56+/** Temp dirs created during tests; removed after the suite. */
57+const tempDirs = []
58+ 
59+/**
60+ * Build a fake DSH checkout in a temp directory.
61+ *
62+ * @param {object} [opts]
63+ * @param {boolean} [opts.hubPatched=false] hub.ts already has isClipboardTrigger
64+ * @param {string} [opts.hubContent] override hub.ts content entirely
65+ * @param {boolean} [opts.noHub=false] omit hub.ts entirely
66+ * @param {boolean} [opts.noTsc=false] omit node_modules/typescript/bin/tsc
67+ * @param {boolean} [opts.noPackageJson=false] omit ui-conversation/package.json
68+ * @param {boolean} [opts.existingClipboard=false] pre-create clipboard dir with assets (simulates reinstall)
69+ * @returns {{ root: string, hubPath: string, clipboardDir: string, tscPath: string }}
70+ */
71+function makeFakeCheckout(opts = {}) {
72+ const root = mkdtempSync(join(tmpdir(), 'cb-checkout-'))
73+ tempDirs.push(root)
74+ 
75+ const uiDir = join(root, 'packages', 'client', 'ui-conversation')
76+ const srcDir = join(uiDir, 'src', 'client')
77+ const inputDir = join(srcDir, 'input')
78+ const clipboardDir = join(srcDir, 'clipboard')
79+ 
80+ mkdirSync(inputDir, { recursive: true })
81+ 
82+ if (!opts.noPackageJson) {
83+ writeFileSync(join(uiDir, 'package.json'), '{"name":"@deepseek-ai/dsh-client-ui-conversation"}')
84+ }
85+ 
86+ const hubPath = join(inputDir, 'hub.ts')
87+ if (!opts.noHub) {
88+ const content = opts.hubContent ?? (opts.hubPatched ? HUB_PATCHED : HUB_TEMPLATE)
89+ writeFileSync(hubPath, content)
90+ }
91+ 
92+ if (!opts.noTsc) {
93+ const tscDir = join(root, 'node_modules', 'typescript', 'bin')
94+ mkdirSync(tscDir, { recursive: true })
95+ writeFileSync(join(tscDir, 'tsc'), '#!/usr/bin/env node\n// dummy tsc')
96+ }
97+ 
98+ if (opts.existingClipboard) {
99+ mkdirSync(clipboardDir, { recursive: true })
100+ for (const asset of ASSETS) {
101+ writeFileSync(join(clipboardDir, asset), `// user-modified ${asset}`)
102+ }
103+ }
104+ 
105+ const tscPath = join(root, 'node_modules', 'typescript', 'bin', 'tsc')
106+ return { root, hubPath, clipboardDir, tscPath }
107+}
108+ 
109+/**
110+ * Build a fake assets dir in a temp directory (4 dummy source files).
111+ * @param {object} [opts]
112+ * @param {string} [opts.missingAsset] name of an asset to omit
113+ * @param {string} [opts.unreadableAsset] name of an asset to chmod 000
114+ * @returns {string} path to the fake assets dir
115+ */
116+function makeFakeAssets(opts = {}) {
117+ const dir = mkdtempSync(join(tmpdir(), 'cb-assets-'))
118+ tempDirs.push(dir)
119+ for (const asset of ASSETS) {
120+ if (asset === opts.missingAsset) continue
121+ const dest = join(dir, asset)
122+ writeFileSync(dest, `// fake source ${asset}`)
123+ if (asset === opts.unreadableAsset) chmodSync(dest, 0o000)
124+ }
125+ return dir
126+}
127+ 
128+/**
129+ * Build a mock `run` function for install().
130+ * @param {object} [opts]
131+ * @param {number} [opts.pnpmStatus=0] status for `pnpm --version`
132+ * @param {number} [opts.tscStatus=0] status for tsc build
133+ * @param {number} [opts.bundleStatus=0] status for pnpm bundle
134+ * @param {function} [opts.onTsc] callback invoked when tsc is called (can delete backups etc.)
135+ * @returns {function}
136+ */
137+function makeRun(opts = {}) {
138+ const pnpmStatus = opts.pnpmStatus ?? 0
139+ const tscStatus = opts.tscStatus ?? 0
140+ const bundleStatus = opts.bundleStatus ?? 0
141+ return (command, args) => {
142+ if (command === 'pnpm' && args.length === 1 && args[0] === '--version') {
143+ return { status: pnpmStatus }
144+ }
145+ if (command === 'pnpm' && args[0] === '--filter') {
146+ return { status: bundleStatus }
147+ }
148+ if (command === process.execPath && typeof args[0] === 'string' && args[0].includes('typescript') && args[0].endsWith('tsc')) {
149+ if (typeof opts.onTsc === 'function') opts.onTsc()
150+ return { status: tscStatus }
151+ }
152+ return { status: 0 }
153+ }
154+}
155+ 
156+const noop = () => {}
157+const noopLog = noop
158+const noopErr = noop
159+ 
160+// ---------------------------------------------------------------------------
161+// 1. precheck failures — zero target files modified
162+// ---------------------------------------------------------------------------
163+ 
164+test('precheck: missing source asset → exitCode 1, no target files created', () => {
165+ const assets = makeFakeAssets({ missingAsset: 'history.ts' })
166+ const { root } = makeFakeCheckout()
167+ const result = install(root, {
168+ log: noopLog, err: noopErr,
169+ run: makeRun(),
170+ assetsDir: assets,
171+ })
172+ assert.equal(result.ok, false)
173+ assert.equal(result.exitCode, EXIT_PRECHECK)
174+ // no clipboard dir created
175+ const clipboardDir = join(root, 'packages', 'client', 'ui-conversation', 'src', 'client', 'clipboard')
176+ assert.equal(existsSync(clipboardDir), false, 'clipboard dir must not be created on precheck failure')
177+})
178+ 
179+test('precheck: invalid checkout (no package.json) → exitCode 1', () => {
180+ const assets = makeFakeAssets()
181+ const { root } = makeFakeCheckout({ noPackageJson: true })
182+ const result = install(root, {
183+ log: noopLog, err: noopErr,
184+ run: makeRun(),
185+ assetsDir: assets,
186+ })
187+ assert.equal(result.ok, false)
188+ assert.equal(result.exitCode, EXIT_PRECHECK)
189+ assert.match(result.message, /no DSH checkout/)
190+})
191+ 
192+test('precheck: hub.ts missing → exitCode 1', () => {
193+ const assets = makeFakeAssets()
194+ const { root } = makeFakeCheckout({ noHub: true })
195+ const result = install(root, {
196+ log: noopLog, err: noopErr,
197+ run: makeRun(),
198+ assetsDir: assets,
199+ })
200+ assert.equal(result.ok, false)
201+ assert.equal(result.exitCode, EXIT_PRECHECK)
202+ assert.match(result.message, /input hub not found/)
203+})
204+ 
205+test('precheck: hub.ts import anchor missing → exitCode 1, points to manual patch', () => {
206+ const assets = makeFakeAssets()
207+ const { root } = makeFakeCheckout({ hubContent: '// no anchors here\n' })
208+ const result = install(root, {
209+ log: noopLog, err: noopErr,
210+ run: makeRun(),
211+ assetsDir: assets,
212+ })
213+ assert.equal(result.ok, false)
214+ assert.equal(result.exitCode, EXIT_PRECHECK)
215+ assert.match(result.message, /anchor for imports not found/)
216+ assert.match(result.message, /hub-sink\.patch\.md/)
217+})
218+ 
219+test('precheck: hub.ts sink anchor missing → exitCode 1', () => {
220+ const assets = makeFakeAssets()
221+ const hubContent = `// has import anchor but no sink anchor\n${ANCHOR_IMPORT}\n`
222+ const { root } = makeFakeCheckout({ hubContent })
223+ const result = install(root, {
224+ log: noopLog, err: noopErr,
225+ run: makeRun(),
226+ assetsDir: assets,
227+ })
228+ assert.equal(result.ok, false)
229+ assert.equal(result.exitCode, EXIT_PRECHECK)
230+ assert.match(result.message, /anchor for the sink guard not found/)
231+})
232+ 
233+test('precheck: tsc binary missing → exitCode 1', () => {
234+ const assets = makeFakeAssets()
235+ const { root } = makeFakeCheckout({ noTsc: true })
236+ const result = install(root, {
237+ log: noopLog, err: noopErr,
238+ run: makeRun(),
239+ assetsDir: assets,
240+ })
241+ assert.equal(result.ok, false)
242+ assert.equal(result.exitCode, EXIT_PRECHECK)
243+ assert.match(result.message, /typescript compiler not found/)
244+})
245+ 
246+test('precheck: pnpm unavailable → exitCode 1', () => {
247+ const assets = makeFakeAssets()
248+ const { root } = makeFakeCheckout()
249+ const result = install(root, {
250+ log: noopLog, err: noopErr,
251+ run: makeRun({ pnpmStatus: 1 }),
252+ assetsDir: assets,
253+ })
254+ assert.equal(result.ok, false)
255+ assert.equal(result.exitCode, EXIT_PRECHECK)
256+ assert.match(result.message, /pnpm not available/)
257+})
258+ 
259+// ---------------------------------------------------------------------------
260+// 2. copy/inject failure → rollback succeeds
261+// ---------------------------------------------------------------------------
262+ 
263+test('copy failure: unreadable source asset → exitCode 2, rollback restores hub.ts', () => {
264+ const assets = makeFakeAssets({ unreadableAsset: 'history.ts' })
265+ const { root, hubPath } = makeFakeCheckout()
266+ const hubBefore = readFileSync(hubPath, 'utf8')
267+ 
268+ const result = install(root, {
269+ log: noopLog, err: noopErr,
270+ run: makeRun(),
271+ assetsDir: assets,
272+ })
273+ assert.equal(result.ok, false)
274+ assert.equal(result.exitCode, EXIT_CHANGE)
275+ assert.match(result.message, /history\.ts/)
276+ 
277+ // hub.ts unchanged (copy failed before injection)
278+ const hubAfter = readFileSync(hubPath, 'utf8')
279+ assert.equal(hubAfter, hubBefore, 'hub.ts must be unchanged after rollback')
280+ 
281+ // no clipboard assets left behind
282+ const clipboardDir = join(root, 'packages', 'client', 'ui-conversation', 'src', 'client', 'clipboard')
283+ for (const asset of ASSETS) {
284+ assert.equal(existsSync(join(clipboardDir, asset)), false, `${asset} must be cleaned up on rollback`)
285+ }
286+})
287+ 
288+// ---------------------------------------------------------------------------
289+// 3. build failure (tsc / pnpm) → rollback restores to pre-install state
290+// ---------------------------------------------------------------------------
291+ 
292+test('tsc failure: exitCode 2, clipboard assets restored and hub.ts reverted', () => {
293+ const assets = makeFakeAssets()
294+ const { root, hubPath } = makeFakeCheckout({ existingClipboard: true })
295+ const hubBefore = readFileSync(hubPath, 'utf8')
296+ const clipboardDir = join(root, 'packages', 'client', 'ui-conversation', 'src', 'client', 'clipboard')
297+ const assetBefore = readFileSync(join(clipboardDir, 'history.ts'), 'utf8')
298+ 
299+ const result = install(root, {
300+ log: noopLog, err: noopErr,
301+ run: makeRun({ tscStatus: 1 }),
302+ assetsDir: assets,
303+ })
304+ assert.equal(result.ok, false)
305+ assert.equal(result.exitCode, EXIT_CHANGE)
306+ assert.match(result.message, /tsc failed/)
307+ 
308+ // hub.ts restored to original (injection was done, then rolled back)
309+ assert.equal(readFileSync(hubPath, 'utf8'), hubBefore, 'hub.ts must be restored after rollback')
310+ 
311+ // clipboard assets restored to user-modified content
312+ assert.equal(readFileSync(join(clipboardDir, 'history.ts'), 'utf8'), assetBefore, 'clipboard asset must be restored')
313+ 
314+ // backup dir retained
315+ assert.ok(result.backupDir, 'backupDir must be reported')
316+ assert.equal(existsSync(result.backupDir), true, 'backup dir must exist after rollback')
317+})
318+ 
319+test('pnpm bundle failure: exitCode 2, files restored', () => {
320+ const assets = makeFakeAssets()
321+ const { root, hubPath } = makeFakeCheckout()
322+ const hubBefore = readFileSync(hubPath, 'utf8')
323+ 
324+ const result = install(root, {
325+ log: noopLog, err: noopErr,
326+ run: makeRun({ bundleStatus: 1 }),
327+ assetsDir: assets,
328+ })
329+ assert.equal(result.ok, false)
330+ assert.equal(result.exitCode, EXIT_CHANGE)
331+ assert.match(result.message, /pnpm bundle failed/)
332+ 
333+ // hub.ts reverted (was injected, then rolled back)
334+ assert.equal(readFileSync(hubPath, 'utf8'), hubBefore, 'hub.ts must be restored')
335+ 
336+ // new clipboard files cleaned up
337+ const clipboardDir = join(root, 'packages', 'client', 'ui-conversation', 'src', 'client', 'clipboard')
338+ for (const asset of ASSETS) {
339+ assert.equal(existsSync(join(clipboardDir, asset)), false, `${asset} must be cleaned up`)
340+ }
341+})
342+ 
343+// ---------------------------------------------------------------------------
344+// 4. rollback failure → exitCode 3, unrestored paths listed
345+// ---------------------------------------------------------------------------
346+ 
347+test('rollback failure: backup deleted before restore → exitCode 3, failures listed', () => {
348+ const assets = makeFakeAssets()
349+ const backupRoot = mkdtempSync(join(tmpdir(), 'cb-backuproot-'))
350+ tempDirs.push(backupRoot)
351+ 
352+ const { root, hubPath } = makeFakeCheckout({ existingClipboard: true })
353+ const clipboardDir = join(root, 'packages', 'client', 'ui-conversation', 'src', 'client', 'clipboard')
354+ 
355+ // When tsc runs, delete the entire backup directory so restore fails.
356+ const deleteBackupOnTsc = () => {
357+ const dirs = readdirSync(backupRoot).filter(d => d.startsWith('cutting-board-backup-'))
358+ for (const d of dirs) {
359+ rmSync(join(backupRoot, d), { recursive: true, force: true })
360+ }
361+ }
362+ 
363+ const result = install(root, {
364+ log: noopLog, err: noopErr,
365+ run: makeRun({ tscStatus: 1, onTsc: deleteBackupOnTsc }),
366+ assetsDir: assets,
367+ backupRoot,
368+ })
369+ assert.equal(result.ok, false)
370+ assert.equal(result.exitCode, EXIT_ROLLBACK)
371+ assert.ok(Array.isArray(result.rollbackFailures), 'rollbackFailures must be an array')
372+ assert.ok(result.rollbackFailures.length > 0, 'at least one failure path must be listed')
373+ 
374+ // hub.ts and clipboard assets should appear in the failure list (backups were deleted)
375+ const allFailures = result.rollbackFailures.join('\n')
376+ assert.ok(allFailures.includes(hubPath) || allFailures.includes('hub.ts'), 'hub.ts path in failures')
377+ assert.ok(
378+ result.rollbackFailures.some(f => f.includes('history.ts')),
379+ 'a clipboard asset path in failures',
380+ )
381+})
382+ 
383+// ---------------------------------------------------------------------------
384+// 5. success path
385+// ---------------------------------------------------------------------------
386+ 
387+test('success: assets copied, hub injected, backup reported', () => {
388+ const assets = makeFakeAssets()
389+ const { root, hubPath, clipboardDir } = makeFakeCheckout()
390+ 
391+ const result = install(root, {
392+ log: noopLog, err: noopErr,
393+ run: makeRun(),
394+ assetsDir: assets,
395+ })
396+ assert.equal(result.ok, true)
397+ assert.ok(result.backupDir, 'backupDir must be reported on success')
398+ assert.equal(existsSync(result.backupDir), true, 'backup dir must exist')
399+ 
400+ // assets copied
401+ for (const asset of ASSETS) {
402+ assert.equal(existsSync(join(clipboardDir, asset)), true, `${asset} must be copied`)
403+ }
404+ 
405+ // hub patched
406+ const hubAfter = readFileSync(hubPath, 'utf8')
407+ assert.ok(hubAfter.includes('isClipboardTrigger'), 'hub must contain isClipboardTrigger after patch')
408+ assert.ok(hubAfter.includes('openClipboardPanel'), 'hub must contain openClipboardPanel after patch')
409+})
410+ 
411+// ---------------------------------------------------------------------------
412+// 6. idempotency — repeated install backs up then overwrites, skips injection
413+// ---------------------------------------------------------------------------
414+ 
415+test('idempotency: second run backs up existing files and skips injection', () => {
416+ const assets = makeFakeAssets()
417+ const { root, hubPath, clipboardDir } = makeFakeCheckout()
418+ 
419+ // first install
420+ const r1 = install(root, {
421+ log: noopLog, err: noopErr,
422+ run: makeRun(),
423+ assetsDir: assets,
424+ })
425+ assert.equal(r1.ok, true, 'first install must succeed')
426+ const hubAfterFirst = readFileSync(hubPath, 'utf8')
427+ 
428+ // second install (hub already patched)
429+ const r2 = install(root, {
430+ log: noopLog, err: noopErr,
431+ run: makeRun(),
432+ assetsDir: assets,
433+ })
434+ assert.equal(r2.ok, true, 'second install must succeed')
435+ assert.ok(r2.backupDir, 'second install must report a backup dir')
436+ 
437+ // hub content unchanged (injection skipped, content identical)
438+ const hubAfterSecond = readFileSync(hubPath, 'utf8')
439+ assert.equal(hubAfterSecond, hubAfterFirst, 'hub.ts must be unchanged on second (idempotent) run')
440+ 
441+ // clipboard assets still present
442+ for (const asset of ASSETS) {
443+ assert.equal(existsSync(join(clipboardDir, asset)), true, `${asset} must still exist after second run`)
444+ }
445+})
446+ 
447+// ---------------------------------------------------------------------------
448+// 7. detectCheckout helper
449+// ---------------------------------------------------------------------------
450+ 
451+test('detectCheckout: walks up to find ui-conversation package.json', () => {
452+ const { root } = makeFakeCheckout()
453+ const deepDir = join(root, 'packages', 'client', 'ui-conversation', 'src', 'client', 'input')
454+ const detected = detectCheckout(deepDir)
455+ assert.equal(detected, root, 'detectCheckout must resolve the checkout root from a deep subdir')
456+})
457+ 
458+test('detectCheckout: returns undefined when no checkout found', () => {
459+ const tmp = mkdtempSync(join(tmpdir(), 'cb-nocheckout-'))
460+ tempDirs.push(tmp)
461+ const detected = detectCheckout(tmp)
462+ assert.equal(detected, undefined, 'detectCheckout must return undefined when no checkout is found')
463+})
464+ 
465+// ---------------------------------------------------------------------------
466+// cleanup
467+// ---------------------------------------------------------------------------
468+ 
469+test.after(() => {
470+ for (const dir of tempDirs) {
471+ // chmod any 000 files back to writable so rmSync can clean them
472+ try {
473+ const items = readdirSync(dir)
474+ for (const item of items) {
475+ try { chmodSync(join(dir, item), 0o644) } catch { /* ignore */ }
476+ }
477+ } catch { /* ignore */ }
478+ try { rmSync(dir, { recursive: true, force: true }) } catch { /* ignore */ }
479+ }
480+})