@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.
@@ -0,0 +1,219 @@
1
+ import test from 'node:test'
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'
6
+ import { EventEmitter } from 'node:events'
7
+ import { executeEnvironmentPlan, wizardHandler } from '../index.js'
8
+ import { compareVersions, planEnvironment } from '../lib/environment.mjs'
9
+ import { createJobEngine } from '../lib/jobs.mjs'
10
+
11
+ const delay = (ms) => new Promise((r) => setTimeout(r, ms))
12
+ async function waitFor(fn, tries = 200) {
13
+ for (let i = 0; i < tries; i += 1) { if (fn()) return; await delay(5) }
14
+ throw new Error('waitFor timed out')
15
+ }
16
+
17
+ // ---------- version comparator ----------
18
+ test('compareVersions follows semver precedence for exact pins', () => {
19
+ assert.equal(compareVersions('1.0.0', '1.0.0'), 0)
20
+ assert.equal(compareVersions('2.0.0', '1.9.9'), 1)
21
+ assert.equal(compareVersions('0.9.9', '0.10.0'), -1)
22
+ assert.equal(compareVersions('1.0.0', '1.0.0-rc.1'), 1)
23
+ assert.equal(compareVersions('1.0.0-rc.1', '1.0.0-rc.2'), -1)
24
+ assert.equal(compareVersions('1.0.0-alpha', '1.0.0-beta'), -1)
25
+ assert.equal(compareVersions('1.0.0-1', '1.0.0-alpha'), -1)
26
+ assert.equal(compareVersions('1.0.0-rc.1', '1.0.0-rc'), 1)
27
+ })
28
+
29
+ // ---------- planner removals ----------
30
+ test('planner removes only named installed registry packages and protects local links', () => {
31
+ const base = { schemaVersion: 1, packages: [], bundles: [] }
32
+ const removed = planEnvironment({ manifest: { ...base, remove: ['old'] }, installed: { old: 'old@1.0.0' } })
33
+ assert.equal(removed.actions[0].action, 'remove')
34
+ assert.equal(removed.actions[0].destructive, true)
35
+ const localBlocked = planEnvironment({ manifest: { ...base, remove: ['dev'] }, local: { dev: 'link:../dev' } })
36
+ assert.equal(localBlocked.ready, false)
37
+ assert.ok(localBlocked.blockers.some((b) => b.includes('machine-local')))
38
+ const absent = planEnvironment({ manifest: { ...base, remove: ['ghost'] }, installed: {} })
39
+ assert.ok(absent.skipped.some((s) => s.name === 'ghost' && s.reason === 'not-installed'))
40
+ const overlap = planEnvironment({ manifest: { ...base, packages: [{ name: 'x', spec: 'x@1.0.0' }], remove: ['x'] } })
41
+ assert.equal(overlap.ready, false)
42
+ })
43
+
44
+ // ---------- executor native paths ----------
45
+ function managerMock() {
46
+ const calls = []
47
+ return {
48
+ calls,
49
+ async listBundles() { return [] },
50
+ async installBundle(spec, opts) { calls.push(['install', spec, opts]); return { application: 'applied' } },
51
+ async updateBundle(name, version, opts) { calls.push(['update', name, version, opts]); return { from: '1.0.0', to: version, step: 'install', result: { application: 'applied' } } },
52
+ async removeBundle(name) { calls.push(['remove', name]); return { stage: 'remove', application: 'applied' } },
53
+ async setBundleEnabled(name, on) { calls.push(['enable', name, on]); return { application: 'applied' } },
54
+ }
55
+ }
56
+
57
+ test('upgrade uses native updateBundle, downgrade uses remove+install, remove uses removeBundle', async () => {
58
+ const mgr = managerMock()
59
+ const ctx = { pluginManager: mgr }
60
+ const events = []
61
+ const plan = {
62
+ manifest: { bundles: [] },
63
+ actions: [
64
+ { name: 'up', spec: 'up@2.0.0', action: 'version-change', direction: 'upgrade' },
65
+ { name: 'down', spec: 'down@1.0.0', action: 'version-change', direction: 'downgrade' },
66
+ { name: 'gone', action: 'remove' },
67
+ ],
68
+ }
69
+ const results = await executeEnvironmentPlan(ctx, plan, { onProgress: (e) => events.push(e), requestId: 'req-1' })
70
+ assert.ok(results.every((r) => r.ok))
71
+ assert.deepEqual(mgr.calls.map((c) => c[0]), ['update', 'remove', 'install', 'remove'])
72
+ assert.equal(mgr.calls[0][1], 'up')
73
+ assert.equal(mgr.calls[0][2], '2.0.0')
74
+ assert.equal(mgr.calls[0][3].requestId, 'req-1')
75
+ assert.ok(events.some((e) => e.name === 'up' && e.state === 'running' && e.phase === 'updating'))
76
+ assert.ok(events.some((e) => e.name === 'up' && e.state === 'done'))
77
+ })
78
+
79
+ // ---------- job engine ----------
80
+ const scanPlan = { ready: true, blockers: [], actions: [{ name: 'a', spec: 'a@1.0.0', action: 'install' }], manifest: { bundles: [] } }
81
+
82
+ test('apply requires a completed scan and reports per-item progress to 100%', async () => {
83
+ const engine = createJobEngine({
84
+ runScan: async () => scanPlan,
85
+ runApply: async (plan, { onProgress }) => {
86
+ onProgress({ name: 'a', action: 'install', state: 'running', phase: 'installing' })
87
+ await delay(10)
88
+ onProgress({ name: 'a', action: 'install', state: 'done', application: 'applied' })
89
+ return [{ name: 'a', ok: true, application: 'applied' }]
90
+ },
91
+ })
92
+ assert.throws(() => engine.startApply({ scanId: 'nope' }), /completed scan/)
93
+ const scan = engine.startScan({})
94
+ await waitFor(() => engine.get(scan.id)?.status === 'done')
95
+ const apply = engine.startApply({ scanId: scan.id })
96
+ await waitFor(() => engine.get(apply.id)?.status === 'done')
97
+ const job = engine.get(apply.id)
98
+ assert.equal(job.ok, true)
99
+ assert.equal(job.percent, 100)
100
+ assert.equal(job.items.a.state, 'done')
101
+ })
102
+
103
+ test('exclude filters items out of the apply plan', async () => {
104
+ let received
105
+ const engine = createJobEngine({
106
+ runScan: async () => scanPlan,
107
+ runApply: async (plan) => { received = plan; return [] },
108
+ })
109
+ const scan = engine.startScan({})
110
+ await waitFor(() => engine.get(scan.id)?.status === 'done')
111
+ const apply = engine.startApply({ scanId: scan.id, exclude: ['a'] })
112
+ await waitFor(() => engine.get(apply.id)?.status === 'done')
113
+ assert.equal(received.actions.filter((a) => a.action !== 'keep').length, 0)
114
+ })
115
+
116
+ test('only one apply runs at a time and cancel forwards the requestId', async () => {
117
+ let release
118
+ const gate = new Promise((r) => { release = r })
119
+ let cancelledId
120
+ const engine = createJobEngine({
121
+ runScan: async () => scanPlan,
122
+ runApply: async () => { await gate; return [{ name: 'a', ok: true, application: 'applied' }] },
123
+ cancelInstall: async (id) => { cancelledId = id; return { status: 'cancelled' } },
124
+ })
125
+ const scan = engine.startScan({})
126
+ await waitFor(() => engine.get(scan.id)?.status === 'done')
127
+ const first = engine.startApply({ scanId: scan.id })
128
+ assert.throws(() => engine.startApply({ scanId: scan.id }), /already running/)
129
+ const cancelResult = await engine.cancel(first.id)
130
+ assert.equal(cancelResult.status, 'cancelled')
131
+ assert.equal(cancelledId, first.requestId)
132
+ release()
133
+ await waitFor(() => engine.get(first.id)?.status === 'done')
134
+ })
135
+
136
+ test('job store prunes to maxJobs', async () => {
137
+ const engine = createJobEngine({ runScan: async () => scanPlan, runApply: async () => [], maxJobs: 3 })
138
+ for (let i = 0; i < 6; i += 1) engine.startScan({})
139
+ await delay(20)
140
+ assert.ok(engine.list().length <= 3)
141
+ })
142
+
143
+ // ---------- wizard HTTP handler ----------
144
+ function handlerHarness() {
145
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'capyclaw-wizard-'))
146
+ fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ dependencies: {} }))
147
+ const ctx = { profileContext: { dir }, pluginManager: { async listBundles() { return [] } } }
148
+ const engine = createJobEngine({
149
+ runScan: async () => scanPlan,
150
+ runApply: async (plan, { onProgress }) => {
151
+ for (const a of plan.actions.filter((x) => x.action !== 'keep')) onProgress({ name: a.name, action: a.action, state: 'done', application: 'applied' })
152
+ return plan.actions.filter((x) => x.action !== 'keep').map((a) => ({ name: a.name, ok: true, application: 'applied' }))
153
+ },
154
+ })
155
+ const handler = wizardHandler({ ctx, engine })
156
+ function request(method, route, body) {
157
+ return new Promise((resolve, reject) => {
158
+ const req = new EventEmitter()
159
+ req.method = method
160
+ req.url = '/capyclaw/environment/api/' + route
161
+ const res = {
162
+ writeHead(code) { this.code = code },
163
+ end(payload) { resolve({ code: this.code, body: JSON.parse(payload) }) },
164
+ }
165
+ handler(req, res).catch(reject)
166
+ if (body !== undefined) { req.emit('data', JSON.stringify(body)); req.emit('end') }
167
+ })
168
+ }
169
+ return { dir, request }
170
+ }
171
+
172
+ test('wizard routes scan, bind consent to a completed scan, apply, and mark onboarding', async () => {
173
+ const h = handlerHarness()
174
+ const state0 = await h.request('GET', 'state')
175
+ assert.equal(state0.body.ok, true)
176
+ assert.equal(state0.body.onboarded, false)
177
+ const scan = await h.request('POST', 'scan', {})
178
+ const scanId = scan.body.job.id
179
+ let job
180
+ for (let i = 0; i < 100; i += 1) { job = (await h.request('GET', 'jobs/' + scanId)).body.job; if (job.status === 'done') break; await delay(5) }
181
+ assert.equal(job.status, 'done')
182
+ const apply = await h.request('POST', 'apply', { scanId, exclude: [] })
183
+ const applyId = apply.body.job.id
184
+ let applied
185
+ for (let i = 0; i < 100; i += 1) { applied = (await h.request('GET', 'jobs/' + applyId)).body.job; if (applied.status === 'done' || applied.status === 'failed') break; await delay(5) }
186
+ assert.equal(applied.status, 'done')
187
+ const state1 = await h.request('GET', 'state')
188
+ assert.equal(state1.body.onboarded, true)
189
+ const missing = await h.request('GET', 'jobs/does-not-exist')
190
+ assert.equal(missing.code, 404)
191
+ const unknown = await h.request('GET', 'bogus')
192
+ assert.equal(unknown.code, 404)
193
+ fs.rmSync(h.dir, { recursive: true, force: true })
194
+ })
195
+
196
+ test('dismiss marks onboarding without applying', async () => {
197
+ const h = handlerHarness()
198
+ await h.request('POST', 'dismiss', {})
199
+ const state = await h.request('GET', 'state')
200
+ assert.equal(state.body.onboarded, true)
201
+ fs.rmSync(h.dir, { recursive: true, force: true })
202
+ })
203
+
204
+ // ---------- client artifact structure ----------
205
+ test('client artifact registers the wizard overlay and a composer dock launcher', async () => {
206
+ let captured
207
+ globalThis.window = { __ModuleLoader__: { load: (m) => { captured = m } } }
208
+ await import('../client/client.js?wizard-test')
209
+ const ReactStub = { createElement: () => null, useState: () => [], useEffect: () => {}, useRef: () => ({}), useCallback: (f) => f }
210
+ const mod = captured.factory((name) => (name === 'react' ? ReactStub : {}))
211
+ assert.deepEqual(mod.inject, ['slots'])
212
+ const registrations = []
213
+ const fakeCtx = { slots: { inject: (owner, fn) => fn(), register: (meta) => { registrations.push(meta); return () => {} } } }
214
+ mod.apply(fakeCtx)
215
+ const names = registrations.map((r) => r.name)
216
+ assert.ok(names.includes('shell.overlay'))
217
+ assert.ok(names.includes('conversation.composer.dock'))
218
+ delete globalThis.window
219
+ })