@capyclaw/capyclaw 0.2.0 → 0.3.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.
@@ -27,12 +27,18 @@ export function normalizeEnvironmentManifest(raw) {
27
27
  }
28
28
  return { name: item.name, spec: item.spec, platforms: [...new Set(platforms)], required: item.required !== false }
29
29
  })
30
+ const removeRaw = raw.remove === undefined ? [] : raw.remove
31
+ if (!Array.isArray(removeRaw) || removeRaw.some((n) => typeof n !== 'string' || !n.trim())) {
32
+ throw new TypeError('remove must be an array of package names')
33
+ }
34
+ const remove = [...new Set(removeRaw.map((n) => n.trim()))]
30
35
  return {
31
36
  schemaVersion: 1,
32
37
  name: String(raw.name || 'Imported environment'),
33
38
  dsh: raw.dsh && typeof raw.dsh === 'object' ? { ...raw.dsh } : {},
34
39
  packages,
35
40
  bundles: Array.isArray(raw.bundles) ? raw.bundles.filter((x) => typeof x === 'string') : [],
41
+ remove,
36
42
  }
37
43
  }
38
44
 
@@ -67,18 +73,86 @@ function isInstalled(spec, desiredSpec, name) {
67
73
  return spec === desiredSpec
68
74
  }
69
75
 
70
- export function planEnvironment({ manifest, platform = detectPlatform(), installed = {}, dshVersion, allowUpgrade = false }) {
76
+ function parseVersion(version) {
77
+ const dash = version.indexOf('-')
78
+ const core = (dash === -1 ? version : version.slice(0, dash)).split('.').map(Number)
79
+ const pre = dash === -1 ? null : version.slice(dash + 1).split('.')
80
+ return { core, pre }
81
+ }
82
+
83
+ /** Semver precedence for exact pins (no build metadata). Returns -1, 0, or 1. */
84
+ export function compareVersions(a, b) {
85
+ const left = parseVersion(a)
86
+ const right = parseVersion(b)
87
+ for (let i = 0; i < 3; i += 1) {
88
+ if (left.core[i] !== right.core[i]) return left.core[i] < right.core[i] ? -1 : 1
89
+ }
90
+ if (left.pre === null && right.pre === null) return 0
91
+ if (left.pre === null) return 1
92
+ if (right.pre === null) return -1
93
+ const len = Math.max(left.pre.length, right.pre.length)
94
+ for (let i = 0; i < len; i += 1) {
95
+ const x = left.pre[i]
96
+ const y = right.pre[i]
97
+ if (x === undefined) return -1
98
+ if (y === undefined) return 1
99
+ const xNum = /^\d+$/.test(x)
100
+ const yNum = /^\d+$/.test(y)
101
+ if (xNum && yNum) {
102
+ const diff = Number(x) - Number(y)
103
+ if (diff !== 0) return diff < 0 ? -1 : 1
104
+ } else if (xNum !== yNum) {
105
+ return xNum ? -1 : 1
106
+ } else if (x !== y) {
107
+ return x < y ? -1 : 1
108
+ }
109
+ }
110
+ return 0
111
+ }
112
+
113
+ export function planEnvironment({ manifest, platform = detectPlatform(), installed = {}, local = {}, dshVersion, allowUpgrade = false }) {
71
114
  const normalized = normalizeEnvironmentManifest(manifest)
72
115
  const actions = []
73
116
  const skipped = []
74
117
  for (const item of normalized.packages) {
118
+ // Machine-local development dependencies (link:/file:/path) are sacred:
119
+ // never replace them with registry versions, even with allowUpgrade=true.
120
+ if (Object.prototype.hasOwnProperty.call(local, item.name)) {
121
+ actions.push({ ...item, current: local[item.name], action: 'keep', local: true, destructive: false })
122
+ continue
123
+ }
75
124
  if (!item.platforms.includes(platform)) {
76
125
  skipped.push({ name: item.name, reason: 'unsupported-platform', platforms: item.platforms })
77
126
  continue
78
127
  }
79
128
  const current = installed[item.name]
80
129
  const action = current == null ? 'install' : isInstalled(current, item.spec, item.name) ? 'keep' : 'version-change'
81
- actions.push({ ...item, current: current ?? null, action, destructive: action === 'version-change' })
130
+ const entry = { ...item, current: current ?? null, action, destructive: action === 'version-change' }
131
+ if (action === 'version-change') {
132
+ const from = installedPackageVersion(current)
133
+ const to = requestedVersion(item.spec, item.name)
134
+ entry.direction = from && to && compareVersions(to, from) > 0 ? 'upgrade' : 'downgrade'
135
+ }
136
+ actions.push(entry)
137
+ }
138
+ // Explicit removals: only installed registry packages, never machine-local dev links,
139
+ // and never anything the manifest did not name.
140
+ const removeBlockers = []
141
+ for (const name of normalized.remove) {
142
+ if (Object.prototype.hasOwnProperty.call(local, name)) {
143
+ removeBlockers.push(`Cannot remove machine-local development package ${name}`)
144
+ continue
145
+ }
146
+ if (normalized.packages.some((p) => p.name === name)) {
147
+ removeBlockers.push(`${name} cannot be both installed and removed`)
148
+ continue
149
+ }
150
+ const current = installed[name]
151
+ if (current == null) {
152
+ skipped.push({ name, reason: 'not-installed', action: 'remove' })
153
+ continue
154
+ }
155
+ actions.push({ name, current, action: 'remove', destructive: true })
82
156
  }
83
157
  const invalidPackages = normalized.packages.filter((item) => {
84
158
  if (!item.spec.startsWith(`${item.name}@`)) return true
@@ -94,12 +168,14 @@ export function planEnvironment({ manifest, platform = detectPlatform(), install
94
168
  dsh: { required: requiredDsh, current: dshVersion ?? null, mismatch: dshMismatch },
95
169
  actions,
96
170
  skipped,
97
- ready: !unsupportedRequired && !invalidPackages.length && !dshMismatch && !missingDshVersion && !actions.some((a) => a.action === 'version-change' && !allowUpgrade),
171
+ localPackages: Object.entries(local).map(([name, spec]) => ({ name, spec })),
172
+ ready: !unsupportedRequired && !invalidPackages.length && !dshMismatch && !missingDshVersion && !removeBlockers.length && !actions.some((a) => a.action === 'version-change' && !allowUpgrade),
98
173
  blockers: [
99
174
  ...(unsupportedRequired ? ['Unsupported operating system'] : []),
100
175
  ...invalidPackages.map((name) => `${name} must use an exact package@version registry spec`),
101
176
  ...(dshMismatch ? [`DSH ${requiredDsh} required, found ${dshVersion}`] : []),
102
177
  ...(missingDshVersion ? [`Cannot verify required DSH version ${requiredDsh}`] : []),
178
+ ...removeBlockers,
103
179
  ...actions.filter((a) => a.action === 'version-change' && !allowUpgrade).map((a) => `${a.name} requires an explicit version change confirmation`),
104
180
  ],
105
181
  }
package/lib/jobs.mjs ADDED
@@ -0,0 +1,116 @@
1
+ import { randomUUID } from 'node:crypto'
2
+
3
+ /**
4
+ * In-memory job engine for the setup wizard. A scan produces a plan; an apply
5
+ * consumes a completed scan (server-side consent binding) and reports per-item
6
+ * progress. Jobs launch asynchronously and are polled by id; only one apply runs
7
+ * at a time. Jobs are pruned to the last `maxJobs`.
8
+ */
9
+ export function createJobEngine({ runScan, runApply, cancelInstall, maxJobs = 20 }) {
10
+ const jobs = new Map()
11
+ const order = []
12
+ let running = null
13
+
14
+ function remember(job) {
15
+ jobs.set(job.id, job)
16
+ order.push(job.id)
17
+ while (order.length > maxJobs) jobs.delete(order.shift())
18
+ }
19
+
20
+ function publicJob(job) {
21
+ return job ? { ...job, items: job.items ? { ...job.items } : undefined } : null
22
+ }
23
+
24
+ function get(id) { return publicJob(jobs.get(id)) }
25
+ function list() { return order.map((id) => publicJob(jobs.get(id))).filter(Boolean) }
26
+
27
+ function startScan(opts = {}) {
28
+ const job = { id: randomUUID(), kind: 'scan', status: 'running', phase: 'scanning', percent: 0, createdAt: Date.now() }
29
+ remember(job)
30
+ ;(async () => {
31
+ try {
32
+ const plan = await runScan(opts)
33
+ job.plan = plan
34
+ job.status = 'done'
35
+ job.phase = 'ready'
36
+ job.percent = 100
37
+ job.finishedAt = Date.now()
38
+ } catch (error) {
39
+ job.status = 'failed'
40
+ job.phase = 'error'
41
+ job.error = String(error?.message || error)
42
+ job.finishedAt = Date.now()
43
+ }
44
+ })()
45
+ return publicJob(job)
46
+ }
47
+
48
+ function startApply({ scanId, allowVersionChange = true, exclude = [] } = {}) {
49
+ const scan = jobs.get(scanId)
50
+ if (!scan || scan.kind !== 'scan' || scan.status !== 'done' || !scan.plan) {
51
+ throw new Error('A completed scan is required before applying')
52
+ }
53
+ if (running) throw new Error('Another apply is already running')
54
+ const plan = scan.plan
55
+ const excluded = new Set(Array.isArray(exclude) ? exclude : [])
56
+ const filteredPlan = { ...plan, actions: plan.actions.filter((a) => a.action === 'keep' || !excluded.has(a.name)) }
57
+ const actionable = filteredPlan.actions.filter((a) => a.action !== 'keep')
58
+ const total = Math.max(1, actionable.length + (plan.manifest?.bundles?.length || 0))
59
+ const items = {}
60
+ for (const a of actionable) items[a.name] = { name: a.name, action: a.action, state: 'pending', phase: null }
61
+ const requestId = randomUUID()
62
+ const job = {
63
+ id: randomUUID(), kind: 'apply', status: 'running', phase: 'preparing', percent: 0,
64
+ createdAt: Date.now(), scanId, requestId, items, total, completed: 0, allowVersionChange, exclude: [...excluded],
65
+ }
66
+ remember(job)
67
+ running = { jobId: job.id, requestId }
68
+ let completed = 0
69
+ const onProgress = (ev) => {
70
+ const it = items[ev.name] || (items[ev.name] = { name: ev.name, action: ev.action, state: 'pending' })
71
+ if (ev.action) it.action = ev.action
72
+ it.state = ev.state
73
+ it.phase = ev.phase ?? null
74
+ if (ev.error) it.error = ev.error
75
+ if (ev.application) it.application = ev.application
76
+ if (ev.state === 'done' || ev.state === 'failed') {
77
+ completed += 1
78
+ job.completed = completed
79
+ job.percent = Math.min(99, Math.round((completed / total) * 100))
80
+ }
81
+ if (ev.state === 'running') job.phase = ev.phase || 'working'
82
+ }
83
+ ;(async () => {
84
+ try {
85
+ const results = await runApply(filteredPlan, { onProgress, requestId, allowVersionChange })
86
+ job.results = results
87
+ const ok = results.every((r) => r.ok)
88
+ job.ok = ok
89
+ job.status = ok ? 'done' : 'failed'
90
+ job.phase = ok ? 'done' : 'error'
91
+ job.percent = 100
92
+ job.restartRequired = results.some((r) => r.application === 'restart-required')
93
+ job.finishedAt = Date.now()
94
+ } catch (error) {
95
+ job.ok = false
96
+ job.status = 'failed'
97
+ job.phase = 'error'
98
+ job.error = String(error?.message || error)
99
+ job.percent = 100
100
+ job.finishedAt = Date.now()
101
+ } finally {
102
+ running = null
103
+ }
104
+ })()
105
+ return publicJob(job)
106
+ }
107
+
108
+ async function cancel(jobId) {
109
+ const job = jobs.get(jobId)
110
+ if (!job || job.kind !== 'apply' || job.status !== 'running' || !cancelInstall) return { status: 'not-running' }
111
+ const result = await cancelInstall(job.requestId)
112
+ return result || { status: 'not-running' }
113
+ }
114
+
115
+ return { startScan, startApply, cancel, get, list, isRunning: () => Boolean(running) }
116
+ }
package/locale/en.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "CapyClaw environment manager",
4
- "description": "Detects Windows, macOS, or Linux and previews or applies portable DSH profile setup and migration plans."
4
+ "description": "Detects Windows, macOS, or Linux. After install it scans the environment, shows a consent dialog listing what will be installed/updated/removed, then displays download and install progress. Portable DSH profile setup and migration plans can also be previewed or applied."
5
5
  }
6
- }
6
+ }
package/locale/zh.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "CapyClaw 环境管理器",
4
- "description": "自动识别 Windows、macOS 或 Linux,预览或应用可移植的 DSH profile 环境搭建与迁移计划。"
4
+ "description": "自动识别 Windows、macOS 或 Linux。安装后扫描环境,弹窗列出要安装/更新/卸载的插件供你确认,同意后显示下载与安装进度。也可预览或应用可移植的 DSH profile 环境搭建与迁移计划。"
5
5
  }
6
- }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capyclaw/capyclaw",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Portable DSH environment setup and profile migration for Windows, macOS, and Linux.",
5
5
  "type": "module",
6
6
  "main": "./index.js",
@@ -9,6 +9,8 @@
9
9
  "./runtime": "./index.js",
10
10
  "./manifest": "./manifest.js",
11
11
  "./environment": "./lib/environment.mjs",
12
+ "./jobs": "./lib/jobs.mjs",
13
+ "./client": "./client/client.js",
12
14
  "./locale/*.json": "./locale/*.json",
13
15
  "./icon": "./icon.svg",
14
16
  "./package.json": "./package.json"
@@ -18,7 +20,11 @@
18
20
  "patch": "./cordis.patch.yml"
19
21
  },
20
22
  "category": "tool",
21
- "platform": "both"
23
+ "platform": "both",
24
+ "client": {
25
+ "platform": "web",
26
+ "immediately": true
27
+ }
22
28
  },
23
29
  "meta": {
24
30
  "title": "CapyClaw environment manager",
@@ -28,6 +34,7 @@
28
34
  "index.js",
29
35
  "manifest.js",
30
36
  "lib/",
37
+ "client/",
31
38
  "test/",
32
39
  "locale/",
33
40
  "icon.svg",
@@ -36,7 +43,7 @@
36
43
  ],
37
44
  "scripts": {
38
45
  "test": "node --test test/*.test.mjs",
39
- "check": "node --check index.js && node --check lib/environment.mjs"
46
+ "check": "node --check index.js && node --check lib/environment.mjs && node --check lib/jobs.mjs && node --check client/client.js"
40
47
  },
41
48
  "dependencies": {
42
49
  "@capyclaw/foundation": "^0.1.10",
@@ -1,5 +1,8 @@
1
1
  import test from 'node:test'
2
2
  import assert from 'node:assert/strict'
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
3
6
  import { apply, executeEnvironmentPlan } from '../index.js'
4
7
 
5
8
  function harness({ bundles = [], installResult = { application: 'applied' } } = {}) {
@@ -38,7 +41,11 @@ test('explicit apply installs the planned package through the native manager', a
38
41
  assert.equal(results[0].ok, true)
39
42
  assert.equal(h.calls[0][0], 'install')
40
43
  assert.equal(h.calls[0][1], 'demo@1.2.3')
41
- assert.deepEqual(h.calls[0][2].expected, { name: 'demo', version: '1.2.3' })
44
+ // No `expected` guard: the manager rejects the install when any other direct dep is
45
+ // touched by pnpm, which false-positives on dev profiles full of file:/link: deps.
46
+ // saveExact pins the requested version; installBundle's after-read verifies the bundle.
47
+ assert.equal(h.calls[0][2].expected, undefined)
48
+ assert.equal(h.calls[0][2].saveExact, true)
42
49
  })
43
50
 
44
51
  test('does not re-enable bundles that are already enabled', async () => {
@@ -99,3 +106,74 @@ test('enables a selected bundle when installation did not already enable it', as
99
106
  assert.deepEqual(calls, [['install', 'demo@1.2.3'], ['enable', 'demo', true]])
100
107
  assert.equal(results.some((r) => r.action === 'enable' && r.ok), true)
101
108
  })
109
+
110
+ test('export keeps exact registry pins and omits machine-local link/file dependencies', async () => {
111
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'capyclaw-export-'))
112
+ try {
113
+ fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({
114
+ dependencies: { 'reg-pkg': '^1.0.0', 'local-pkg': 'link:../local-pkg', 'file-pkg': 'file:../file-pkg' },
115
+ }))
116
+ for (const [name, version] of [['reg-pkg', '1.2.3'], ['local-pkg', '9.9.9'], ['file-pkg', '8.8.8']]) {
117
+ fs.mkdirSync(path.join(dir, 'node_modules', name), { recursive: true })
118
+ fs.writeFileSync(path.join(dir, 'node_modules', name, 'package.json'), JSON.stringify({ name, version }))
119
+ }
120
+ const tools = new Map()
121
+ const ctx = {
122
+ profileContext: { dir },
123
+ tools: { register(tool) { tools.set(tool.name, tool); return () => tools.delete(tool.name) } },
124
+ pluginManager: { async listBundles() { return [{ name: 'reg-pkg', enabled: true }] } },
125
+ }
126
+ const dispose = apply(ctx)
127
+ const outputPath = path.join(dir, 'exported.json')
128
+ const result = await tools.get('capyclaw_export_environment').execute({ outputPath })
129
+ const exported = JSON.parse(fs.readFileSync(outputPath, 'utf8'))
130
+ assert.equal(result.ok, true)
131
+ assert.equal(result.omittedLocalLinks, 2)
132
+ assert.deepEqual(exported.packages.map((p) => p.spec), ['reg-pkg@1.2.3'])
133
+ assert.deepEqual(exported.bundles, ['reg-pkg'])
134
+ dispose()
135
+ } finally {
136
+ fs.rmSync(dir, { recursive: true, force: true })
137
+ }
138
+ })
139
+
140
+ test('local development link dependencies are never replaced by registry versions, even with allowUpgrade', async () => {
141
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'capyclaw-local-protect-'))
142
+ try {
143
+ const linkSpec = 'link:../my-dev-checkout'
144
+ fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ dependencies: { 'dev-pkg': linkSpec } }))
145
+ fs.mkdirSync(path.join(dir, 'node_modules', 'dev-pkg'), { recursive: true })
146
+ fs.writeFileSync(path.join(dir, 'node_modules', 'dev-pkg', 'package.json'), JSON.stringify({ name: 'dev-pkg', version: '9.9.9' }))
147
+ const manifestPath = path.join(dir, 'want-old.json')
148
+ fs.writeFileSync(manifestPath, JSON.stringify({
149
+ schemaVersion: 1, name: 'older registry set',
150
+ packages: [{ name: 'dev-pkg', spec: 'dev-pkg@1.0.0' }], bundles: [],
151
+ }))
152
+ const calls = []
153
+ const tools = new Map()
154
+ const ctx = {
155
+ profileContext: { dir },
156
+ tools: { register(tool) { tools.set(tool.name, tool); return () => tools.delete(tool.name) } },
157
+ pluginManager: {
158
+ async listBundles() { return [] },
159
+ async installBundle(...args) { calls.push(['install', ...args]); return { application: 'applied' } },
160
+ async setBundleEnabled(...args) { calls.push(['enable', ...args]); return { application: 'applied' } },
161
+ },
162
+ }
163
+ const dispose = apply(ctx)
164
+ const preview = await tools.get('capyclaw_sync').execute({ manifestPath })
165
+ assert.equal(preview.mode, 'preview')
166
+ assert.equal(preview.actions[0].action, 'keep')
167
+ assert.equal(preview.actions[0].local, true)
168
+ assert.equal(preview.actions[0].current, linkSpec)
169
+ assert.deepEqual(preview.localPackages, [{ name: 'dev-pkg', spec: linkSpec }])
170
+ const applied = await tools.get('capyclaw_sync').execute({ manifestPath, apply: true, allowUpgrade: true })
171
+ assert.equal(applied.mode, 'applied')
172
+ assert.equal(applied.ok, true)
173
+ assert.deepEqual(calls, [])
174
+ assert.equal(JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')).dependencies['dev-pkg'], linkSpec)
175
+ dispose()
176
+ } finally {
177
+ fs.rmSync(dir, { recursive: true, force: true })
178
+ }
179
+ })