dsh-version-manager 0.0.0-stage → 0.1.1

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,303 @@
1
+ /**
2
+ * Compatibility, computed the way the host computes it.
3
+ *
4
+ * The host decides whether a bundle may load by comparing the plugin manifest
5
+ * against the running DSH version: `engines.dsh` when the manifest declares it,
6
+ * otherwise the `@deepseek-ai/dsh*` peer dependencies. It evaluates with
7
+ * prereleases included, so `0.2.2-rc.1` satisfies `>=0.2.0`.
8
+ *
9
+ * This module does not depend on `semver`: a profile is not guaranteed to have
10
+ * one on its resolution path, and importing a peer at request time would make
11
+ * the whole panel fail on a host that moved it. The range grammar below covers
12
+ * what plugin manifests actually write. Anything it cannot read returns `null`,
13
+ * and `null` becomes "unknown" rather than a guess — a version panel that
14
+ * invents a verdict is worse than one that admits it does not know.
15
+ *
16
+ * @module dsh-version-manager/lib/host/compat
17
+ */
18
+
19
+ /** Dependency names that tie a plugin to a DSH version. */
20
+ const DSH_PEER = /^@deepseek-ai\/dsh(?:-|$)/
21
+
22
+ /**
23
+ * Split a version into comparable parts.
24
+ *
25
+ * @param {unknown} value
26
+ * @returns {{ major: number, minor: number, patch: number, prerelease: string[] } | null}
27
+ */
28
+ export function parseVersion(value) {
29
+ if (typeof value !== 'string') return null
30
+ const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(value.trim())
31
+ if (match === null) return null
32
+ return {
33
+ major: Number(match[1]),
34
+ minor: Number(match[2]),
35
+ patch: Number(match[3]),
36
+ prerelease: match[4] === undefined ? [] : match[4].split('.'),
37
+ }
38
+ }
39
+
40
+ /**
41
+ * @param {string[]} left
42
+ * @param {string[]} right
43
+ * @returns {number}
44
+ */
45
+ function comparePrerelease(left, right) {
46
+ // A release outranks any prerelease of the same version.
47
+ if (left.length === 0 && right.length === 0) return 0
48
+ if (left.length === 0) return 1
49
+ if (right.length === 0) return -1
50
+ for (let index = 0; index < Math.max(left.length, right.length); index += 1) {
51
+ const a = left[index]
52
+ const b = right[index]
53
+ if (a === undefined) return -1
54
+ if (b === undefined) return 1
55
+ const numericA = /^\d+$/.test(a)
56
+ const numericB = /^\d+$/.test(b)
57
+ if (numericA && numericB) {
58
+ const diff = Number(a) - Number(b)
59
+ if (diff !== 0) return diff < 0 ? -1 : 1
60
+ continue
61
+ }
62
+ if (numericA !== numericB) return numericA ? -1 : 1
63
+ if (a !== b) return a < b ? -1 : 1
64
+ }
65
+ return 0
66
+ }
67
+
68
+ /**
69
+ * @param {ReturnType<typeof parseVersion>} left
70
+ * @param {ReturnType<typeof parseVersion>} right
71
+ * @returns {number}
72
+ */
73
+ function compareVersions(left, right) {
74
+ for (const key of ['major', 'minor', 'patch']) {
75
+ if (left[key] !== right[key]) return left[key] < right[key] ? -1 : 1
76
+ }
77
+ return comparePrerelease(left.prerelease, right.prerelease)
78
+ }
79
+
80
+ /**
81
+ * One comparator against one version.
82
+ *
83
+ * @param {string} version
84
+ * @param {string} token - a single range term such as `>=2.0.0` or `^1.2.3`
85
+ * @returns {boolean | null}
86
+ */
87
+ function satisfiesTerm(version, token) {
88
+ const trimmed = token.trim()
89
+ if (trimmed === '' || trimmed === '*' || trimmed === 'x' || trimmed === 'X') return true
90
+
91
+ const match = /^(>=|<=|>|<|=|\^|~)?\s*(.+)$/.exec(trimmed)
92
+ if (match === null) return null
93
+ const operator = match[1] ?? '='
94
+ const target = parseVersion(match[2])
95
+ if (target === null) return null
96
+
97
+ switch (operator) {
98
+ case '=':
99
+ return compareVersions(version, target) === 0
100
+ case '>':
101
+ return compareVersions(version, target) > 0
102
+ case '>=':
103
+ return compareVersions(version, target) >= 0
104
+ case '<':
105
+ return compareVersions(version, target) < 0
106
+ case '<=':
107
+ return compareVersions(version, target) <= 0
108
+ case '^': {
109
+ // ^0.2.3 stays inside 0.2.x; ^1.2.3 stays inside 1.x. Prereleases of a
110
+ // later minor are not inside the caret range, which is what the host's
111
+ // semver means too.
112
+ if (compareVersions(version, target) < 0) return false
113
+ const ceiling =
114
+ target.major > 0
115
+ ? { major: target.major + 1, minor: 0, patch: 0, prerelease: [] }
116
+ : target.minor > 0
117
+ ? { major: 0, minor: target.minor + 1, patch: 0, prerelease: [] }
118
+ : { major: 0, minor: 0, patch: target.patch + 1, prerelease: [] }
119
+ return compareVersions(version, ceiling) < 0
120
+ }
121
+ case '~': {
122
+ if (compareVersions(version, target) < 0) return false
123
+ const ceiling = { major: target.major, minor: target.minor + 1, patch: 0, prerelease: [] }
124
+ return compareVersions(version, ceiling) < 0
125
+ }
126
+ default:
127
+ return null
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Does `version` satisfy `range`?
133
+ *
134
+ * Supports `||` unions, whitespace-separated conjunctions, and the comparators
135
+ * npm accepts in a manifest. Unreadable input returns `null`, never `false`.
136
+ *
137
+ * @param {string} version
138
+ * @param {string} range
139
+ * @returns {boolean | null}
140
+ */
141
+ export function satisfiesRange(version, range) {
142
+ const parsed = parseVersion(version)
143
+ if (parsed === null) return null
144
+ if (typeof range !== 'string' || range.trim() === '') return null
145
+
146
+ let sawUnknown = false
147
+ for (const alternative of range.split('||')) {
148
+ const terms = alternative.trim().split(/\s+/).filter((term) => term !== '')
149
+ let all = true
150
+ for (const term of terms) {
151
+ const result = satisfiesTerm(parsed, term)
152
+ if (result === null) {
153
+ sawUnknown = true
154
+ all = false
155
+ break
156
+ }
157
+ if (result === false) {
158
+ all = false
159
+ break
160
+ }
161
+ }
162
+ if (all) return true
163
+ }
164
+ return sawUnknown ? null : false
165
+ }
166
+
167
+ /**
168
+ * Which requirements the manifest places on the runtime.
169
+ *
170
+ * Mirrors the host: `engines.dsh` wins outright when present; only when it is
171
+ * absent does the host consult `@deepseek-ai/dsh*` peers. `workspace:` ranges
172
+ * are always satisfied — the host treats them as internal links.
173
+ *
174
+ * @param {any} manifest
175
+ * @returns {{ field: string, range: string }[]}
176
+ */
177
+ export function dshRequirements(manifest) {
178
+ if (manifest === null || typeof manifest !== 'object') return []
179
+ const engines = manifest.engines
180
+ if (engines !== null && typeof engines === 'object' && typeof engines.dsh === 'string') {
181
+ if (engines.dsh.trim() !== '') return [{ field: 'engines.dsh', range: engines.dsh }]
182
+ return []
183
+ }
184
+ const peers = manifest.peerDependencies
185
+ if (peers === null || typeof peers !== 'object') return []
186
+ const requirements = []
187
+ for (const [name, range] of Object.entries(peers)) {
188
+ if (!DSH_PEER.test(name)) continue
189
+ if (typeof range !== 'string') continue
190
+ requirements.push({ field: `peerDependencies.${name}`, range })
191
+ }
192
+ return requirements
193
+ }
194
+
195
+ /**
196
+ * @param {string} range
197
+ * @returns {boolean}
198
+ */
199
+ function isWorkspaceRange(range) {
200
+ return range.startsWith('workspace:')
201
+ }
202
+
203
+ /**
204
+ * Evaluate one manifest against the runtime.
205
+ *
206
+ * @param {object} input
207
+ * @param {any} input.manifest - the installed package manifest, or null
208
+ * @param {string | null} input.runtimeVersion
209
+ * @param {Record<string, string[]>} [input.exemptions] - from the profile's compatibility.json
210
+ * @param {string | null} [input.packageVersion]
211
+ * @param {string | undefined} [input.exemptionKey]
212
+ * @returns {{ verdict: 'satisfied' | 'unsatisfied' | 'exempted' | 'unknown', requirements: { field: string, range: string }[], unmet: { field: string, range: string }[], runtimeVersion: string | null, reason: string | null }}
213
+ */
214
+ export function evaluateCompatibility(input) {
215
+ const { manifest, runtimeVersion, exemptions, packageVersion, exemptionKey } = input
216
+ const requirements = dshRequirements(manifest)
217
+
218
+ if (manifest === null || typeof manifest !== 'object') {
219
+ return {
220
+ verdict: 'unknown',
221
+ requirements: [],
222
+ unmet: [],
223
+ runtimeVersion: runtimeVersion ?? null,
224
+ reason: 'The installed package manifest could not be read.',
225
+ }
226
+ }
227
+ if (requirements.length === 0) {
228
+ // No claim about DSH at all: the host accepts it, and so do we.
229
+ return {
230
+ verdict: 'satisfied',
231
+ requirements: [],
232
+ unmet: [],
233
+ runtimeVersion: runtimeVersion ?? null,
234
+ reason: null,
235
+ }
236
+ }
237
+ if (runtimeVersion === null || runtimeVersion === undefined) {
238
+ return {
239
+ verdict: 'unknown',
240
+ requirements,
241
+ unmet: [],
242
+ runtimeVersion: null,
243
+ reason: 'The running DSH version is not readable from inside this host.',
244
+ }
245
+ }
246
+
247
+ /** @type {{ field: string, range: string }[]} */
248
+ const unmet = []
249
+ let undecidable = null
250
+ for (const requirement of requirements) {
251
+ if (isWorkspaceRange(requirement.range)) continue
252
+ const satisfied = satisfiesRange(runtimeVersion, requirement.range)
253
+ if (satisfied === null) {
254
+ undecidable = requirement
255
+ continue
256
+ }
257
+ if (!satisfied) unmet.push(requirement)
258
+ }
259
+
260
+ if (undecidable !== null && unmet.length === 0) {
261
+ return {
262
+ verdict: 'unknown',
263
+ requirements,
264
+ unmet: [],
265
+ runtimeVersion,
266
+ reason: `This plugin cannot evaluate the range "${undecidable.range}" without the host's semver.`,
267
+ }
268
+ }
269
+ if (unmet.length === 0) {
270
+ return { verdict: 'satisfied', requirements, unmet: [], runtimeVersion, reason: null }
271
+ }
272
+
273
+ // The profile may carry an exact-version exemption granted with
274
+ // `dsh plugin allow-version`. When it does, the host loads the bundle anyway,
275
+ // so the panel must not report it as blocked.
276
+ if (exemptions !== undefined && exemptions !== null && packageVersion) {
277
+ const key = exemptionKey ?? `${input.packageName ?? ''}@${packageVersion}`
278
+ const granted = exemptions[key]
279
+ if (Array.isArray(granted) && granted.includes(runtimeVersion)) {
280
+ return { verdict: 'exempted', requirements, unmet, runtimeVersion, reason: null }
281
+ }
282
+ }
283
+
284
+ return {
285
+ verdict: 'unsatisfied',
286
+ requirements,
287
+ unmet,
288
+ runtimeVersion,
289
+ reason: null,
290
+ }
291
+ }
292
+
293
+ /**
294
+ * Read a version out of a package manifest without trusting its shape.
295
+ *
296
+ * @param {unknown} manifest
297
+ * @returns {string | null}
298
+ */
299
+ export function manifestVersion(manifest) {
300
+ if (manifest === null || typeof manifest !== 'object') return null
301
+ const version = manifest.version
302
+ return typeof version === 'string' && version !== '' ? version : null
303
+ }
@@ -0,0 +1,376 @@
1
+ /**
2
+ * HTTP handlers for the Git-managed Skill surface.
3
+ *
4
+ * These live beside `routes.js` rather than inside it because they share no
5
+ * state with the plugin-version half of the panel, and because a 1,600-line
6
+ * file is harder to review than two focused ones.
7
+ *
8
+ * Every handler receives the profile context that `routes.js` already resolved
9
+ * and a parsed body; none of them trusts a path from the request. A directory
10
+ * is always looked up in the host's own catalog, or derived from the profile
11
+ * home when the caller asked this plugin to create it.
12
+ *
13
+ * @module lib/host/git-routes
14
+ */
15
+
16
+ import { join } from 'node:path'
17
+
18
+ import {
19
+ applyGitUpdate,
20
+ describeRegistry,
21
+ previewGitUpdate,
22
+ readRegistry,
23
+ registerGitSkill,
24
+ restoreGitRevision,
25
+ unregisterGitSkill,
26
+ } from './git-skill.js'
27
+ import { beginOperation, transition } from './operations.js'
28
+ import { readSkills } from './skills.js'
29
+
30
+ /** A Skill name is one path segment, so it can never walk out of a root. */
31
+ const NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/
32
+
33
+ /**
34
+ * Where a Skill named `name` lives, according to the host.
35
+ *
36
+ * @param {any} ctx
37
+ * @param {{ home: string | null, id: string, cwd: string | null }} profile
38
+ * @param {string} name
39
+ * @param {{ create?: boolean }} [options]
40
+ * @returns {Promise<{ ok: true, directory: string, source: string | null, listed: boolean }
41
+ * | { ok: false, status: number, body: object }>}
42
+ */
43
+ export async function resolveSkillDirectory(ctx, profile, name, options = {}) {
44
+ if (profile.home === null || profile.id === 'unknown') {
45
+ return { ok: false, status: 409, body: { error: 'profile-identity-unknown' } }
46
+ }
47
+ if (typeof name !== 'string' || name.trim() === '') {
48
+ return { ok: false, status: 400, body: { error: 'missing-name' } }
49
+ }
50
+ const trimmed = name.trim()
51
+ const catalog = await readSkills(ctx, { cwd: profile.cwd })
52
+ const listed = catalog.skills.find((entry) => entry.name === trimmed)
53
+ if (listed !== undefined) {
54
+ if (listed.directory === null) {
55
+ return {
56
+ ok: false,
57
+ status: 409,
58
+ body: { error: 'no-directory', message: 'This Skill is a single file, so there is no directory to manage.' },
59
+ }
60
+ }
61
+ return { ok: true, directory: listed.directory, source: listed.source ?? null, listed: true }
62
+ }
63
+ if (options.create === true) {
64
+ if (!NAME_PATTERN.test(trimmed)) {
65
+ return {
66
+ ok: false,
67
+ status: 400,
68
+ body: {
69
+ error: 'bad-name',
70
+ message: 'A Skill name becomes a directory name, so it may only contain letters, digits, dot, dash and underscore.',
71
+ },
72
+ }
73
+ }
74
+ return { ok: true, directory: join(profile.home, 'skills', trimmed), source: null, listed: false }
75
+ }
76
+ return {
77
+ ok: false,
78
+ status: 404,
79
+ body: {
80
+ error: 'unknown-skill',
81
+ message: catalog.available
82
+ ? 'That Skill is not in the host catalog. Register it with create:true to let this plugin make the directory.'
83
+ : catalog.reason,
84
+ },
85
+ }
86
+ }
87
+
88
+ /**
89
+ * Everything the Git half of the Skills tab needs, without writing anything.
90
+ *
91
+ * @param {any} ctx
92
+ * @param {{ home: string | null, id: string, cwd: string | null }} profile
93
+ * @returns {Promise<{ status: number, body: object }>}
94
+ */
95
+ export async function listGitSkills(ctx, profile) {
96
+ if (profile.home === null || profile.id === 'unknown') {
97
+ return { status: 409, body: { error: 'profile-identity-unknown' } }
98
+ }
99
+ try {
100
+ const registry = await readRegistry(profile.home, profile.id)
101
+ return {
102
+ status: 200,
103
+ body: {
104
+ schemaVersion: 1,
105
+ observedAt: new Date().toISOString(),
106
+ profile: { id: profile.id, dir: profile.dir, home: profile.home },
107
+ skills: await describeRegistry(registry),
108
+ },
109
+ }
110
+ } catch (error) {
111
+ return { status: 500, body: { error: 'git-list-failed', message: messageOf(error) } }
112
+ }
113
+ }
114
+
115
+ /**
116
+ * Record that a Skill comes from one subtree of one repository.
117
+ *
118
+ * Registration writes the registry only: the files in the directory are left
119
+ * untouched. That is deliberate — a claim about intent should not be able to
120
+ * destroy content if the claim turns out to be wrong.
121
+ *
122
+ * @param {any} ctx
123
+ * @param {object} profile
124
+ * @param {{ name?: string, remote?: string, subpath?: string, ref?: string, create?: boolean }} body
125
+ * @returns {Promise<{ status: number, body: object }>}
126
+ */
127
+ export async function registerGitRoute(ctx, profile, body) {
128
+ const name = typeof body.name === 'string' ? body.name.trim() : ''
129
+ const located = await resolveSkillDirectory(ctx, profile, name, { create: body.create === true })
130
+ if (!located.ok) return { status: located.status, body: located.body }
131
+ if (located.source === 'bundled') {
132
+ // A bundled Skill is DSH's own file tree; pointing a Git registration at it
133
+ // would make the next update overwrite the host's own files.
134
+ return { status: 409, body: { error: 'bundled-skill', message: null } }
135
+ }
136
+ try {
137
+ const result = await registerGitSkill({
138
+ dshHome: profile.home,
139
+ profileId: profile.id,
140
+ name,
141
+ remote: typeof body.remote === 'string' ? body.remote : '',
142
+ subpath: typeof body.subpath === 'string' ? body.subpath : '',
143
+ ref: typeof body.ref === 'string' && body.ref.trim() !== '' ? body.ref.trim() : 'HEAD',
144
+ directory: located.directory,
145
+ })
146
+ if (!result.ok) {
147
+ return { status: 409, body: { error: result.reason, message: result.message, entry: null } }
148
+ }
149
+ return {
150
+ status: 200,
151
+ body: {
152
+ ok: true,
153
+ entry: result.entry,
154
+ // Said out loud because the caller may expect registration to download
155
+ // the tree. It pins a revision; the bytes arrive on the first update.
156
+ note: 'Registration records where future content comes from and pins the revision the directory currently matches. It does not copy files. Run an update to fetch that revision.',
157
+ },
158
+ }
159
+ } catch (error) {
160
+ return { status: 500, body: { error: 'register-failed', message: messageOf(error) } }
161
+ }
162
+ }
163
+
164
+ /**
165
+ * Forget a registration. Files are left exactly as they are.
166
+ *
167
+ * @param {object} profile
168
+ * @param {{ name?: string }} body
169
+ * @returns {Promise<{ status: number, body: object }>}
170
+ */
171
+ export async function unregisterGitRoute(profile, body) {
172
+ const name = typeof body.name === 'string' ? body.name.trim() : ''
173
+ if (name === '') return { status: 400, body: { error: 'missing-name' } }
174
+ try {
175
+ const result = await unregisterGitSkill({ dshHome: profile.home, profileId: profile.id, name })
176
+ if (!result.ok) return { status: 409, body: { error: result.reason, message: null } }
177
+ return {
178
+ status: 200,
179
+ body: { ok: true, note: 'The registration is gone. The Skill directory was not changed.' },
180
+ }
181
+ } catch (error) {
182
+ return { status: 500, body: { error: 'unregister-failed', message: messageOf(error) } }
183
+ }
184
+ }
185
+
186
+ /**
187
+ * Say what an update would change, without changing it.
188
+ *
189
+ * This fetches into the plugin's own bare cache, which is why it is a POST: it
190
+ * is not free, and a GET that reaches the network is a lie about safety. It
191
+ * still writes nothing the user owns.
192
+ *
193
+ * @param {object} profile
194
+ * @param {{ name?: string, ref?: string }} body
195
+ * @returns {Promise<{ status: number, body: object }>}
196
+ */
197
+ export async function previewGitRoute(profile, body) {
198
+ const name = typeof body.name === 'string' ? body.name.trim() : ''
199
+ if (name === '') return { status: 400, body: { error: 'missing-name' } }
200
+ try {
201
+ const result = await previewGitUpdate({
202
+ dshHome: profile.home,
203
+ profileId: profile.id,
204
+ name,
205
+ ref: typeof body.ref === 'string' && body.ref.trim() !== '' ? body.ref.trim() : undefined,
206
+ })
207
+ // A refusal here is an answer, not a failure of the request: the panel reads
208
+ // `ok` and shows the reason next to the Skill.
209
+ return { status: 200, body: { ok: result.ok, reason: result.reason, message: result.message, detail: result.detail } }
210
+ } catch (error) {
211
+ return { status: 500, body: { error: 'git-preview-failed', message: messageOf(error) } }
212
+ }
213
+ }
214
+
215
+ /**
216
+ * Apply the newest revision of a registered Skill.
217
+ *
218
+ * @param {object} profile
219
+ * @param {{ name?: string, ref?: string }} body
220
+ * @returns {Promise<{ status: number, body: object }>}
221
+ */
222
+ export async function updateGitRoute(profile, body) {
223
+ const name = typeof body.name === 'string' ? body.name.trim() : ''
224
+ if (name === '') return { status: 400, body: { error: 'missing-name' } }
225
+ const ref = typeof body.ref === 'string' && body.ref.trim() !== '' ? body.ref.trim() : undefined
226
+ let record
227
+ try {
228
+ const preview = await previewGitUpdate({ dshHome: profile.home, profileId: profile.id, name, ref })
229
+ if (!preview.ok) {
230
+ return { status: 409, body: { error: preview.reason, message: preview.message, detail: null } }
231
+ }
232
+ const { detail } = preview
233
+ if (detail.alreadyAtRevision) {
234
+ return { status: 200, body: { ok: false, error: 'already-at-revision', message: null, detail } }
235
+ }
236
+ record = await beginOperation({
237
+ dshHome: profile.home,
238
+ profileId: profile.id,
239
+ target: {
240
+ kind: 'skill',
241
+ targetId: name,
242
+ installedVersion: detail.from.revision,
243
+ declaredSpec: `git:${detail.remote}#${detail.subpath === '' ? '.' : detail.subpath}`,
244
+ source: { kind: 'git' },
245
+ },
246
+ toVersion: detail.to.revision,
247
+ })
248
+ await transition(profile.home, profile.id, record, 'applying')
249
+ const result = await applyGitUpdate({ dshHome: profile.home, profileId: profile.id, name, ref })
250
+ if (!result.ok) {
251
+ await transition(profile.home, profile.id, record, 'failed', { error: result.reason })
252
+ return {
253
+ status: 409,
254
+ body: {
255
+ ok: false,
256
+ error: result.reason,
257
+ message: result.message,
258
+ evidence: result.evidence,
259
+ operationId: record.id,
260
+ snapshot: result.snapshot,
261
+ detail,
262
+ },
263
+ }
264
+ }
265
+ await transition(profile.home, profile.id, record, 'succeeded', { snapshotId: result.snapshot?.file ?? null })
266
+ const after = await describeOne(profile, name)
267
+ return {
268
+ status: 200,
269
+ body: {
270
+ ok: true,
271
+ operationId: record.id,
272
+ name,
273
+ fromRevision: result.fromRevision,
274
+ toRevision: result.toRevision,
275
+ changed: detail.changeCount,
276
+ evidence: result.evidence,
277
+ snapshot: result.snapshot,
278
+ message: null,
279
+ current: after,
280
+ },
281
+ }
282
+ } catch (error) {
283
+ if (record !== undefined) {
284
+ await transition(profile.home, profile.id, record, 'failed', { error: 'handler-failed' }).catch(() => {})
285
+ }
286
+ return { status: 500, body: { error: 'git-update-failed', message: messageOf(error) } }
287
+ }
288
+ }
289
+
290
+ /**
291
+ * Put a Skill back to an earlier commit of its own tree.
292
+ *
293
+ * @param {object} profile
294
+ * @param {{ name?: string, revision?: string }} body
295
+ * @returns {Promise<{ status: number, body: object }>}
296
+ */
297
+ export async function restoreGitRoute(profile, body) {
298
+ const name = typeof body.name === 'string' ? body.name.trim() : ''
299
+ const revision = typeof body.revision === 'string' ? body.revision.trim() : ''
300
+ if (name === '') return { status: 400, body: { error: 'missing-name' } }
301
+ if (revision === '') return { status: 400, body: { error: 'missing-revision' } }
302
+ let record
303
+ try {
304
+ record = await beginOperation({
305
+ dshHome: profile.home,
306
+ profileId: profile.id,
307
+ target: {
308
+ kind: 'skill',
309
+ targetId: name,
310
+ installedVersion: null,
311
+ declaredSpec: null,
312
+ source: { kind: 'git' },
313
+ },
314
+ toVersion: revision.slice(0, 12),
315
+ })
316
+ await transition(profile.home, profile.id, record, 'applying')
317
+ const result = await restoreGitRevision({ dshHome: profile.home, profileId: profile.id, name, revision })
318
+ if (!result.ok) {
319
+ await transition(profile.home, profile.id, record, 'failed', { error: result.reason })
320
+ return {
321
+ status: 409,
322
+ body: {
323
+ ok: false,
324
+ error: result.reason,
325
+ message: result.message,
326
+ evidence: result.evidence,
327
+ operationId: record.id,
328
+ snapshot: result.snapshot,
329
+ },
330
+ }
331
+ }
332
+ await transition(profile.home, profile.id, record, 'succeeded', { snapshotId: result.snapshot?.file ?? null })
333
+ return {
334
+ status: 200,
335
+ body: {
336
+ ok: true,
337
+ operationId: record.id,
338
+ name,
339
+ fromRevision: result.fromRevision,
340
+ toRevision: result.toRevision,
341
+ evidence: result.evidence,
342
+ snapshot: result.snapshot,
343
+ message: null,
344
+ current: await describeOne(profile, name),
345
+ },
346
+ }
347
+ } catch (error) {
348
+ if (record !== undefined) {
349
+ await transition(profile.home, profile.id, record, 'failed', { error: 'handler-failed' }).catch(() => {})
350
+ }
351
+ return { status: 500, body: { error: 'git-restore-failed', message: messageOf(error) } }
352
+ }
353
+ }
354
+
355
+ /**
356
+ * One registry row after a write, so the panel can render the new state without
357
+ * a second request.
358
+ *
359
+ * @param {object} profile
360
+ * @param {string} name
361
+ * @returns {Promise<object | null>}
362
+ */
363
+ async function describeOne(profile, name) {
364
+ const registry = await readRegistry(profile.home, profile.id)
365
+ const rows = await describeRegistry(registry.filter((entry) => entry.name === name))
366
+ return rows[0] ?? null
367
+ }
368
+
369
+ /**
370
+ * @param {unknown} error
371
+ * @returns {string}
372
+ */
373
+ function messageOf(error) {
374
+ if (error instanceof Error) return error.message
375
+ return String(error)
376
+ }