hob-bot 0.0.0-stage → 1.0.2
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.
- package/LICENSE +21 -0
- package/README.md +111 -2
- package/README.zh-CN.md +112 -0
- package/bin/hob.mjs +7 -0
- package/dist/web/assets/index-D88l35PH.css +1 -0
- package/dist/web/assets/index-DUs8nN3E.js +218 -0
- package/dist/web/favicon.ico +0 -0
- package/dist/web/fonts/inter-latin.woff2 +0 -0
- package/dist/web/fonts/jetbrains-mono-latin.woff2 +0 -0
- package/dist/web/icons/apple-touch-icon-180.png +0 -0
- package/dist/web/icons/favicon-32.png +0 -0
- package/dist/web/icons/icon-192.png +0 -0
- package/dist/web/icons/icon-512.png +0 -0
- package/dist/web/icons/icon-maskable-512.png +0 -0
- package/dist/web/index.html +32 -0
- package/dist/web/manifest.webmanifest +16 -0
- package/dist/web/sw.js +131 -0
- package/package.json +62 -4
- package/server/src/actions.ts +230 -0
- package/server/src/boot.ts +85 -0
- package/server/src/bus.ts +21 -0
- package/server/src/config.ts +123 -0
- package/server/src/cron-text.ts +49 -0
- package/server/src/delegations.ts +113 -0
- package/server/src/files.ts +142 -0
- package/server/src/http.ts +802 -0
- package/server/src/ids.ts +19 -0
- package/server/src/image.ts +218 -0
- package/server/src/imports.ts +302 -0
- package/server/src/jobs.ts +730 -0
- package/server/src/main.ts +69 -0
- package/server/src/memory.ts +272 -0
- package/server/src/models.ts +358 -0
- package/server/src/overview.ts +116 -0
- package/server/src/pages.ts +54 -0
- package/server/src/password.ts +23 -0
- package/server/src/pi.ts +273 -0
- package/server/src/prompt.ts +227 -0
- package/server/src/providers.ts +532 -0
- package/server/src/push.ts +285 -0
- package/server/src/router-tools.ts +549 -0
- package/server/src/router.ts +841 -0
- package/server/src/routines.ts +129 -0
- package/server/src/runtime.ts +104 -0
- package/server/src/search.ts +91 -0
- package/server/src/secrets.ts +46 -0
- package/server/src/settings.ts +452 -0
- package/server/src/skills.ts +150 -0
- package/server/src/store.ts +324 -0
- package/server/src/text.ts +14 -0
- package/server/src/time.ts +42 -0
- package/server/src/transcript.ts +272 -0
- package/server/src/worker-tools.ts +129 -0
- package/shared/command.ts +42 -0
- package/shared/files.ts +141 -0
- package/shared/media.ts +17 -0
- package/shared/model-note.ts +32 -0
- package/shared/page-shell.ts +108 -0
- package/shared/search.ts +19 -0
- package/shared/skills.ts +37 -0
- package/shared/sprites.ts +422 -0
- package/shared/thinking.ts +118 -0
- package/shared/types.ts +631 -0
- package/vendor/lore-pi-extension/README.md +28 -0
- package/vendor/lore-pi-extension/api.ts +140 -0
- package/vendor/lore-pi-extension/formatters.ts +204 -0
- package/vendor/lore-pi-extension/hooks.ts +195 -0
- package/vendor/lore-pi-extension/index.ts +25 -0
- package/vendor/lore-pi-extension/package.json +23 -0
- package/vendor/lore-pi-extension/skills.ts +447 -0
- package/vendor/lore-pi-extension/tools.ts +344 -0
- package/vendor/lore-pi-extension/uri.ts +67 -0
- package/vendor/lore-pi-extension/vendor/skill-workcopy/index.d.mts +266 -0
- package/vendor/lore-pi-extension/vendor/skill-workcopy/index.mjs +1328 -0
- package/vendor/lore-pi-extension/vendor/skill-workcopy/skills-sync.d.mts +33 -0
- package/vendor/lore-pi-extension/vendor/skill-workcopy/skills-sync.mjs +202 -0
|
@@ -0,0 +1,1328 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lore Skill work-copy core.
|
|
3
|
+
* dependency-free Node ESM (Node 20+). Schema: lore.skill.workcopy.v1
|
|
4
|
+
*
|
|
5
|
+
* Contract:
|
|
6
|
+
* - The Core/server skill package is the source of truth.
|
|
7
|
+
* - getSkill ensures a local work copy: it downloads the complete server package
|
|
8
|
+
* when missing, updates the server-managed package files when the server version
|
|
9
|
+
* differs, and reuses the local copy when the version matches and the managed
|
|
10
|
+
* files are intact.
|
|
11
|
+
* - Server-managed package files (those listed in marker.managed_files) are
|
|
12
|
+
* read-only (0444 on POSIX). The installed skill directory itself stays writable
|
|
13
|
+
* (0755) so agents can create local outputs, artifacts, and cache files directly
|
|
14
|
+
* inside the same copy. Those extra local files are valid, local-only, never
|
|
15
|
+
* uploaded, and survive getSkill calls and version upgrades.
|
|
16
|
+
* - Integrity/tamper checks cover ONLY the server-managed paths from the marker;
|
|
17
|
+
* extra local files never make a copy tampered.
|
|
18
|
+
* - On upgrade, only obsolete server-managed paths are removed and incoming
|
|
19
|
+
* server-managed files are written; extra local files are preserved. If an
|
|
20
|
+
* obsolete managed path or a new managed path conflicts with a local artifact
|
|
21
|
+
* (file/dir shape or same path), the upgrade fails safely with no damage.
|
|
22
|
+
* - No separate artifact directory and no artifact-create tool.
|
|
23
|
+
* - No session-start bulk reconcile/download; all download/update is on-demand
|
|
24
|
+
* via getSkill. Recall is identity-only and never injects local paths.
|
|
25
|
+
* - Server-managed files are chmod 0444 on POSIX (the package model has no
|
|
26
|
+
* executable bit, so managed scripts are invoked through their interpreter).
|
|
27
|
+
*
|
|
28
|
+
* Canonical source of truth lives in shared/skill-workcopy/.
|
|
29
|
+
* Plugin adapters import generated copies under <plugin>/vendor/skill-workcopy/.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
import * as crypto from 'node:crypto';
|
|
33
|
+
import * as fs from 'node:fs';
|
|
34
|
+
import * as os from 'node:os';
|
|
35
|
+
import * as path from 'node:path';
|
|
36
|
+
|
|
37
|
+
export const LORE_SKILL_MARKER = '.lore-skill-marker.json';
|
|
38
|
+
export const LEGACY_LORE_SKILL_MARKER = '.lore-skill.json';
|
|
39
|
+
export const LORE_SKILL_SCHEMA = 'lore.skill.workcopy.v1';
|
|
40
|
+
export const LEGACY_MIRROR_SCHEMA = 'lore.skill.mirror.v1';
|
|
41
|
+
export const SKILL_MD = 'SKILL.md';
|
|
42
|
+
|
|
43
|
+
const WORK_FILE_MODE = 0o644; // staging / backup trees (writable)
|
|
44
|
+
const WORK_DIR_MODE = 0o755; // installed directories (writable for local outputs)
|
|
45
|
+
const READONLY_FILE_MODE = 0o444; // installed server-managed files + marker
|
|
46
|
+
|
|
47
|
+
// ---- path / home helpers ----
|
|
48
|
+
|
|
49
|
+
export function resolveLoreHome(env = process.env) {
|
|
50
|
+
const fromEnv = typeof env.LORE_HOME === 'string' ? env.LORE_HOME.trim() : '';
|
|
51
|
+
if (fromEnv) return path.resolve(fromEnv);
|
|
52
|
+
return path.join(os.homedir(), '.lore');
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function workCopiesRoot(loreHome) {
|
|
56
|
+
return path.join(loreHome, 'skills');
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function projectWorkCopyRoot(loreHome, projectId) {
|
|
60
|
+
return path.join(workCopiesRoot(loreHome), sanitizeSegment(projectId));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** @deprecated Prefer projectWorkCopyRoot. */
|
|
64
|
+
export function skillsRoot(loreHome, projectId) {
|
|
65
|
+
return projectWorkCopyRoot(loreHome, projectId);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** @deprecated Prefer projectWorkCopyRoot. */
|
|
69
|
+
export function installedRoot(loreHome, projectId) {
|
|
70
|
+
return projectWorkCopyRoot(loreHome, projectId);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function stagingRoot(loreHome, projectId) {
|
|
74
|
+
return path.join(workCopiesRoot(loreHome), '.staging', sanitizeSegment(projectId));
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function skillInstallPath(loreHome, projectId, skillName) {
|
|
78
|
+
return path.join(projectWorkCopyRoot(loreHome, projectId), sanitizeSegment(skillName));
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function sanitizeSegment(value) {
|
|
82
|
+
const cleaned = String(value || '').trim();
|
|
83
|
+
if (!cleaned) throw new Error('path segment is required');
|
|
84
|
+
if (cleaned === '.' || cleaned === '..') throw new Error(`invalid path segment: ${cleaned}`);
|
|
85
|
+
if (!/^[A-Za-z0-9._-]+$/.test(cleaned) || cleaned.includes('\0')) {
|
|
86
|
+
throw new Error(`invalid path segment: ${cleaned}`);
|
|
87
|
+
}
|
|
88
|
+
return cleaned;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Validate a skill-relative file path. Rejects absolute paths, traversal, and empty segments.
|
|
93
|
+
* Returns the normalized relative path using forward slashes.
|
|
94
|
+
*/
|
|
95
|
+
export function validateSafeRelativePath(rawPath) {
|
|
96
|
+
const raw = String(rawPath || '').trim();
|
|
97
|
+
if (raw.includes('\\')) throw new Error(`backslashes are not allowed in file paths: ${rawPath}`);
|
|
98
|
+
const input = raw;
|
|
99
|
+
if (!input) throw new Error('file path is required');
|
|
100
|
+
if (path.isAbsolute(input) || input.startsWith('/') || /^[A-Za-z]:\//.test(input)) {
|
|
101
|
+
throw new Error(`absolute paths are not allowed: ${rawPath}`);
|
|
102
|
+
}
|
|
103
|
+
if (input.includes('\0')) throw new Error('null bytes are not allowed in file paths');
|
|
104
|
+
const segments = input.split('/');
|
|
105
|
+
if (segments.length === 0 || segments.some((segment) => segment.length === 0)) {
|
|
106
|
+
throw new Error(`empty path segments are not allowed: ${rawPath}`);
|
|
107
|
+
}
|
|
108
|
+
for (const segment of segments) {
|
|
109
|
+
if (segment === '.' || segment === '..') {
|
|
110
|
+
throw new Error(`path traversal is not allowed: ${rawPath}`);
|
|
111
|
+
}
|
|
112
|
+
if (segment.includes('\0')) throw new Error('null bytes are not allowed in file paths');
|
|
113
|
+
}
|
|
114
|
+
return segments.join('/');
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function skillIdOf(value) {
|
|
118
|
+
return String(value?.skill_id || value?.id || '').trim();
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function skillVersionOf(value) {
|
|
122
|
+
// Prefer canonical version; fall back to legacy expected_version aliases only when absent.
|
|
123
|
+
if (value?.version !== undefined && value?.version !== null && value?.version !== '') {
|
|
124
|
+
return value.version;
|
|
125
|
+
}
|
|
126
|
+
return value?.expected_version;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function skillRevisionOf(value) {
|
|
130
|
+
// Prefer canonical revision_hash over legacy expected_revision_hash.
|
|
131
|
+
const canonical = String(value?.revision_hash || '').trim();
|
|
132
|
+
if (canonical) return canonical;
|
|
133
|
+
return String(value?.expected_revision_hash || '').trim();
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Validate a list of managed relative paths for a mirror marker/payload.
|
|
138
|
+
* Rejects unsafe paths, duplicates, marker self-reference, and parent/child tree collisions.
|
|
139
|
+
*/
|
|
140
|
+
export function validateManagedFileList(rawPaths, opts) {
|
|
141
|
+
if (!Array.isArray(rawPaths)) {
|
|
142
|
+
throw new Error('managed_files must be an array');
|
|
143
|
+
}
|
|
144
|
+
const seen = new Set();
|
|
145
|
+
const out = [];
|
|
146
|
+
let hasSkillMd = false;
|
|
147
|
+
for (const item of rawPaths) {
|
|
148
|
+
if (typeof item !== 'string') {
|
|
149
|
+
throw new Error('managed_files entries must be strings');
|
|
150
|
+
}
|
|
151
|
+
const rel = validateSafeRelativePath(item);
|
|
152
|
+
if (rel === LORE_SKILL_MARKER || rel === LEGACY_LORE_SKILL_MARKER) {
|
|
153
|
+
throw new Error(`${rel} may not appear in managed_files`);
|
|
154
|
+
}
|
|
155
|
+
if (seen.has(rel)) {
|
|
156
|
+
throw new Error(`duplicate managed file path: ${rel}`);
|
|
157
|
+
}
|
|
158
|
+
seen.add(rel);
|
|
159
|
+
if (rel === SKILL_MD) hasSkillMd = true;
|
|
160
|
+
out.push(rel);
|
|
161
|
+
}
|
|
162
|
+
for (const rel of seen) {
|
|
163
|
+
const segments = rel.split('/');
|
|
164
|
+
for (let i = 1; i < segments.length; i += 1) {
|
|
165
|
+
const parent = segments.slice(0, i).join('/');
|
|
166
|
+
if (seen.has(parent)) {
|
|
167
|
+
throw new Error(`managed file path ${rel} conflicts with parent path ${parent}`);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
if (opts?.requireSkillMd !== false && !hasSkillMd) {
|
|
172
|
+
throw new Error('managed_files must include SKILL.md');
|
|
173
|
+
}
|
|
174
|
+
return out.sort();
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function normalizeSkillFile(file) {
|
|
178
|
+
return {
|
|
179
|
+
...file,
|
|
180
|
+
size: Number.isFinite(file.size_bytes) ? Number(file.size_bytes) : file.size,
|
|
181
|
+
sha256: String(file.content_sha256 || file.sha256 || '').trim() || undefined,
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export function normalizeSkillSummary(value) {
|
|
186
|
+
return {
|
|
187
|
+
...value,
|
|
188
|
+
id: skillIdOf(value),
|
|
189
|
+
version: skillVersionOf(value),
|
|
190
|
+
revision_hash: skillRevisionOf(value) || undefined,
|
|
191
|
+
manifest_hash: typeof value?.manifest_hash === 'string' ? value.manifest_hash : undefined,
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
export function normalizeSkillDetail(value) {
|
|
196
|
+
return {
|
|
197
|
+
...normalizeSkillSummary(value),
|
|
198
|
+
files: Array.isArray(value?.files) ? value.files.map(normalizeSkillFile) : [],
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export function normalizeSkillCandidate(value) {
|
|
203
|
+
return {
|
|
204
|
+
...value,
|
|
205
|
+
id: skillIdOf(value),
|
|
206
|
+
version: skillVersionOf(value),
|
|
207
|
+
revision_hash: skillRevisionOf(value) || undefined,
|
|
208
|
+
manifest_hash: typeof value?.manifest_hash === 'string' ? value.manifest_hash : undefined,
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
export function sha256Buffer(buf) {
|
|
213
|
+
return crypto.createHash('sha256').update(buf).digest('hex');
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export function sha256Text(text) {
|
|
217
|
+
return sha256Buffer(Buffer.from(text, 'utf-8'));
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
export function decodeSkillFileContent(file) {
|
|
221
|
+
if (typeof file.content_base64 === 'string') {
|
|
222
|
+
return Buffer.from(file.content_base64, 'base64');
|
|
223
|
+
}
|
|
224
|
+
if (typeof file.content === 'string') {
|
|
225
|
+
return Buffer.from(file.content, 'utf-8');
|
|
226
|
+
}
|
|
227
|
+
throw new Error(`skill file missing content: ${file.path || '(unknown)'}`);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
export function computeManifestHash(files) {
|
|
231
|
+
const normalized = files
|
|
232
|
+
.map((f) => ({
|
|
233
|
+
path: validateSafeRelativePath(f.path),
|
|
234
|
+
sha256: String(f.sha256 || '').toLowerCase(),
|
|
235
|
+
size: Number.isFinite(f.size) ? Number(f.size) : 0,
|
|
236
|
+
}))
|
|
237
|
+
.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
|
|
238
|
+
const payload = normalized.map((f) => `${f.path}\n${f.sha256}\n${f.size}\n`).join('');
|
|
239
|
+
return sha256Text(payload);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// ---- marker / local work-copy inspection ----
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Read and validate a mirror marker. Invalid / unsafe markers return null so callers never
|
|
246
|
+
* act on traversal paths or corrupt managed_files lists.
|
|
247
|
+
*/
|
|
248
|
+
export function readWorkCopyMarker(dir) {
|
|
249
|
+
const markerPath = path.join(dir, LORE_SKILL_MARKER);
|
|
250
|
+
try {
|
|
251
|
+
// Marker itself must be a regular file (not a symlink).
|
|
252
|
+
const markerStat = fs.lstatSync(markerPath);
|
|
253
|
+
if (markerStat.isSymbolicLink() || !markerStat.isFile()) return null;
|
|
254
|
+
|
|
255
|
+
const raw = fs.readFileSync(markerPath, 'utf-8');
|
|
256
|
+
const data = JSON.parse(raw);
|
|
257
|
+
if (!data || typeof data !== 'object' || Array.isArray(data)) return null;
|
|
258
|
+
if (typeof data.schema !== 'string') return null;
|
|
259
|
+
if (typeof data.project_id !== 'string' || !data.project_id.trim()) return null;
|
|
260
|
+
if (typeof data.skill_id !== 'string' || !data.skill_id.trim()) return null;
|
|
261
|
+
if (typeof data.name !== 'string' || !data.name.trim()) return null;
|
|
262
|
+
if (data.version === undefined || data.version === null || data.version === '') return null;
|
|
263
|
+
|
|
264
|
+
const isLegacy = data.schema === LEGACY_MIRROR_SCHEMA;
|
|
265
|
+
const isWorkcopy = data.schema === LORE_SKILL_SCHEMA;
|
|
266
|
+
if (!isLegacy && !isWorkcopy) return null;
|
|
267
|
+
|
|
268
|
+
let managed_files = [];
|
|
269
|
+
if (isWorkcopy) {
|
|
270
|
+
// New schema: managed_files is authoritative and must be fully validated.
|
|
271
|
+
try {
|
|
272
|
+
managed_files = validateManagedFileList(data.managed_files, { requireSkillMd: true });
|
|
273
|
+
} catch {
|
|
274
|
+
return null;
|
|
275
|
+
}
|
|
276
|
+
} else {
|
|
277
|
+
// Legacy schema may omit managed_files; do not invent unsafe paths from the marker.
|
|
278
|
+
// If present, still validate when provided; invalid legacy managed_files => null.
|
|
279
|
+
if (data.managed_files !== undefined) {
|
|
280
|
+
try {
|
|
281
|
+
managed_files = validateManagedFileList(data.managed_files, { requireSkillMd: false });
|
|
282
|
+
} catch {
|
|
283
|
+
return null;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
return {
|
|
289
|
+
schema: data.schema,
|
|
290
|
+
project_id: data.project_id,
|
|
291
|
+
skill_id: data.skill_id,
|
|
292
|
+
name: data.name,
|
|
293
|
+
version: data.version,
|
|
294
|
+
managed_files,
|
|
295
|
+
synced_at: typeof data.synced_at === 'string' ? data.synced_at : '',
|
|
296
|
+
revision_hash: typeof data.revision_hash === 'string' ? data.revision_hash : undefined,
|
|
297
|
+
manifest_hash: typeof data.manifest_hash === 'string' ? data.manifest_hash : undefined,
|
|
298
|
+
readonly: data.readonly === true,
|
|
299
|
+
// Present when a host adapter (adapt) changed the written file set: the server-side
|
|
300
|
+
// manifest of the unadapted payload, used to detect server-side updates.
|
|
301
|
+
...(typeof data.source_manifest_hash === 'string' ? { source_manifest_hash: data.source_manifest_hash } : {}),
|
|
302
|
+
};
|
|
303
|
+
} catch {
|
|
304
|
+
return null;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** @deprecated Prefer readWorkCopyMarker. */
|
|
309
|
+
export const readMirrorMarker = readWorkCopyMarker;
|
|
310
|
+
|
|
311
|
+
function listDirectoryNames(dir) {
|
|
312
|
+
try {
|
|
313
|
+
return fs.readdirSync(dir, { withFileTypes: true })
|
|
314
|
+
.filter((entry) => entry.isDirectory())
|
|
315
|
+
.map((entry) => entry.name)
|
|
316
|
+
.sort();
|
|
317
|
+
} catch {
|
|
318
|
+
return [];
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function pathExists(target) {
|
|
323
|
+
try {
|
|
324
|
+
fs.lstatSync(target);
|
|
325
|
+
return true;
|
|
326
|
+
} catch {
|
|
327
|
+
return false;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function lstatOrNull(target) {
|
|
332
|
+
try {
|
|
333
|
+
return fs.lstatSync(target);
|
|
334
|
+
} catch {
|
|
335
|
+
return null;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* Hash ONLY the server-managed files listed in the work-copy marker.
|
|
341
|
+
* Extra local files are never hashed, so they cannot trigger tamper.
|
|
342
|
+
* Throws when a managed file is missing or is not a regular file.
|
|
343
|
+
*/
|
|
344
|
+
export function hashLocalSkillFiles(dir) {
|
|
345
|
+
const marker = readWorkCopyMarker(dir);
|
|
346
|
+
if (!marker) throw new Error(`missing or invalid work-copy marker: ${dir}`);
|
|
347
|
+
const files = [];
|
|
348
|
+
for (const rel of marker.managed_files) {
|
|
349
|
+
const full = path.join(dir, ...rel.split('/'));
|
|
350
|
+
const st = lstatOrNull(full);
|
|
351
|
+
if (!st) throw new Error(`missing managed file: ${rel}`);
|
|
352
|
+
if (st.isSymbolicLink() || !st.isFile()) {
|
|
353
|
+
throw new Error(`managed path is not a regular file: ${rel}`);
|
|
354
|
+
}
|
|
355
|
+
const buf = fs.readFileSync(full);
|
|
356
|
+
files.push({ path: rel, sha256: sha256Buffer(buf), size: buf.length });
|
|
357
|
+
}
|
|
358
|
+
return { files, manifest_hash: computeManifestHash(files) };
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function ensureDir(dir, mode = WORK_DIR_MODE) {
|
|
362
|
+
fs.mkdirSync(dir, { recursive: true, mode });
|
|
363
|
+
if (process.platform !== 'win32') {
|
|
364
|
+
try { fs.chmodSync(dir, mode); } catch { /* ignore */ }
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
function makeTreeWritable(root) {
|
|
369
|
+
if (!pathExists(root)) return;
|
|
370
|
+
const walk = (current) => {
|
|
371
|
+
try {
|
|
372
|
+
const st = fs.lstatSync(current);
|
|
373
|
+
if (st.isSymbolicLink()) return;
|
|
374
|
+
if (st.isDirectory()) {
|
|
375
|
+
try { fs.chmodSync(current, WORK_DIR_MODE); } catch { /* ignore */ }
|
|
376
|
+
for (const entry of fs.readdirSync(current)) walk(path.join(current, entry));
|
|
377
|
+
} else if (st.isFile()) {
|
|
378
|
+
try { fs.chmodSync(current, WORK_FILE_MODE); } catch { /* ignore */ }
|
|
379
|
+
}
|
|
380
|
+
} catch {
|
|
381
|
+
// ignore unreadable nodes
|
|
382
|
+
}
|
|
383
|
+
};
|
|
384
|
+
walk(root);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
function rmrf(target) {
|
|
388
|
+
makeTreeWritable(target);
|
|
389
|
+
fs.rmSync(target, { recursive: true, force: true });
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* Apply installed permissions (POSIX only):
|
|
394
|
+
* - Installed skill directory and managed-file ancestors stay writable (0755) so
|
|
395
|
+
* agents can create local outputs directly inside the same copy.
|
|
396
|
+
* - Server-managed files and the marker are chmod 0444 (read-only).
|
|
397
|
+
* - Extra local files/directories keep whatever mode they were created with.
|
|
398
|
+
*/
|
|
399
|
+
function applyInstalledModes(dir, managedFiles) {
|
|
400
|
+
if (process.platform === 'win32') return;
|
|
401
|
+
try { fs.chmodSync(dir, WORK_DIR_MODE); } catch { /* ignore */ }
|
|
402
|
+
try { fs.chmodSync(path.join(dir, LORE_SKILL_MARKER), READONLY_FILE_MODE); } catch { /* ignore */ }
|
|
403
|
+
const ancestorDirs = new Set();
|
|
404
|
+
for (const rel of managedFiles) {
|
|
405
|
+
try { fs.chmodSync(path.join(dir, ...rel.split('/')), READONLY_FILE_MODE); } catch { /* ignore */ }
|
|
406
|
+
const segments = rel.split('/');
|
|
407
|
+
for (let i = 1; i < segments.length; i += 1) {
|
|
408
|
+
ancestorDirs.add(segments.slice(0, i).join('/'));
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
for (const rel of ancestorDirs) {
|
|
412
|
+
try { fs.chmodSync(path.join(dir, ...rel.split('/')), WORK_DIR_MODE); } catch { /* ignore */ }
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* Copy a directory tree (used to seed a fresh stage from an existing valid work copy).
|
|
418
|
+
* Symlinks inside extra local files are copied verbatim; managed files are overwritten
|
|
419
|
+
* or removed during materialization regardless.
|
|
420
|
+
*/
|
|
421
|
+
function copyTree(src, dest) {
|
|
422
|
+
fs.cpSync(src, dest, {
|
|
423
|
+
recursive: true,
|
|
424
|
+
force: true,
|
|
425
|
+
errorOnExist: false,
|
|
426
|
+
verbatimSymlinks: true,
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/** Set of directory paths that are strict ancestors of managed files. */
|
|
431
|
+
function managedDirPrefixes(managedSet) {
|
|
432
|
+
const prefixes = new Set();
|
|
433
|
+
for (const rel of managedSet) {
|
|
434
|
+
const segments = rel.split('/');
|
|
435
|
+
for (let i = 1; i < segments.length; i += 1) {
|
|
436
|
+
prefixes.add(segments.slice(0, i).join('/'));
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
return prefixes;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
function conflictError(message, code = 'LOCAL_ARTIFACT_CONFLICT') {
|
|
443
|
+
const err = new Error(message);
|
|
444
|
+
err.code = code;
|
|
445
|
+
return err;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/**
|
|
449
|
+
* Validate ancestors of marker-owned paths before copying, chmodding, or deleting.
|
|
450
|
+
* An intermediate symlink would make ordinary path operations escape the work-copy
|
|
451
|
+
* root; a non-directory ancestor is structural tamper. Exact managed paths are not
|
|
452
|
+
* checked here because materialization restores those safely from server state.
|
|
453
|
+
*/
|
|
454
|
+
function assertManagedPathAncestorsSafe(root, managedFiles) {
|
|
455
|
+
for (const rel of managedFiles) {
|
|
456
|
+
const segments = rel.split('/');
|
|
457
|
+
for (let i = 1; i < segments.length; i += 1) {
|
|
458
|
+
const ancestor = segments.slice(0, i).join('/');
|
|
459
|
+
const st = lstatOrNull(path.join(root, ...segments.slice(0, i)));
|
|
460
|
+
if (!st) continue;
|
|
461
|
+
if (st.isSymbolicLink()) {
|
|
462
|
+
throw conflictError(
|
|
463
|
+
`managed path ${rel} has symlink ancestor ${ancestor}; refusing out-of-copy access`,
|
|
464
|
+
);
|
|
465
|
+
}
|
|
466
|
+
if (!st.isDirectory()) {
|
|
467
|
+
throw conflictError(
|
|
468
|
+
`managed path ${rel} has non-directory ancestor ${ancestor}`,
|
|
469
|
+
);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/**
|
|
476
|
+
* Remove obsolete managed files from the staged tree (files that were managed in the
|
|
477
|
+
* old marker but are not part of the incoming package). The marker owns these exact
|
|
478
|
+
* paths, so regular files and symlinks at them are removed. An empty directory at a
|
|
479
|
+
* formerly-managed file path is structural tamper and is removed; a non-empty directory
|
|
480
|
+
* may contain local outputs, so it fails safely instead of deleting them.
|
|
481
|
+
*/
|
|
482
|
+
function removeObsoleteManaged(stageRoot, oldManaged, newManagedSet) {
|
|
483
|
+
const obsolete = oldManaged.filter((rel) => !newManagedSet.has(rel));
|
|
484
|
+
if (obsolete.length === 0) return;
|
|
485
|
+
// Remove deepest first so nested obsolete files disappear before their parents.
|
|
486
|
+
obsolete
|
|
487
|
+
.sort((a, b) => b.split('/').length - a.split('/').length)
|
|
488
|
+
.forEach((rel) => {
|
|
489
|
+
const full = path.join(stageRoot, ...rel.split('/'));
|
|
490
|
+
const st = lstatOrNull(full);
|
|
491
|
+
if (!st) return;
|
|
492
|
+
if (st.isDirectory()) {
|
|
493
|
+
if (fs.readdirSync(full).length > 0) {
|
|
494
|
+
throw conflictError(
|
|
495
|
+
`obsolete managed path ${rel} is now a non-empty local directory (local artifact)`,
|
|
496
|
+
);
|
|
497
|
+
}
|
|
498
|
+
fs.rmdirSync(full);
|
|
499
|
+
return;
|
|
500
|
+
}
|
|
501
|
+
// The old marker owns this exact path. A symlink here is tamper, not an extra.
|
|
502
|
+
fs.rmSync(full, { force: true });
|
|
503
|
+
});
|
|
504
|
+
|
|
505
|
+
// Prune empty directories that were managed ancestors (never extras).
|
|
506
|
+
const prefixes = managedDirPrefixes(new Set(oldManaged));
|
|
507
|
+
const sorted = [...prefixes].sort((a, b) => b.split('/').length - a.split('/').length);
|
|
508
|
+
for (const rel of sorted) {
|
|
509
|
+
const full = path.join(stageRoot, ...rel.split('/'));
|
|
510
|
+
const st = lstatOrNull(full);
|
|
511
|
+
if (!st || !st.isDirectory()) continue;
|
|
512
|
+
try {
|
|
513
|
+
if (fs.readdirSync(full).length === 0) fs.rmdirSync(full);
|
|
514
|
+
} catch { /* ignore */ }
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/**
|
|
519
|
+
* Detect conflicts between incoming managed files and preserved local extras in the
|
|
520
|
+
* staged tree. Throws (leaving the stage untouched and the install intact) when:
|
|
521
|
+
* - a new managed path already exists as an extra file/dir/symlink, or
|
|
522
|
+
* - a new managed path must live under an ancestor that is a file/symlink.
|
|
523
|
+
* Managed paths already owned by the old marker are restored from server state: regular
|
|
524
|
+
* files are overwritten, symlinks are unlinked, and empty replacement directories are
|
|
525
|
+
* removed. A non-empty replacement directory fails safely because it may contain outputs.
|
|
526
|
+
*/
|
|
527
|
+
function assertNoManagedExtraConflicts(stageRoot, newManagedFiles, oldManagedSet) {
|
|
528
|
+
for (const rel of newManagedFiles) {
|
|
529
|
+
const full = path.join(stageRoot, ...rel.split('/'));
|
|
530
|
+
const st = lstatOrNull(full);
|
|
531
|
+
if (st) {
|
|
532
|
+
if (oldManagedSet.has(rel)) {
|
|
533
|
+
if (st.isSymbolicLink()) {
|
|
534
|
+
fs.unlinkSync(full);
|
|
535
|
+
} else if (st.isDirectory()) {
|
|
536
|
+
if (fs.readdirSync(full).length > 0) {
|
|
537
|
+
throw conflictError(
|
|
538
|
+
`managed path ${rel} is now a non-empty local directory (local artifact)`,
|
|
539
|
+
);
|
|
540
|
+
}
|
|
541
|
+
fs.rmdirSync(full);
|
|
542
|
+
} else if (!st.isFile()) {
|
|
543
|
+
throw conflictError(`managed path ${rel} is an unsupported local filesystem entry`);
|
|
544
|
+
}
|
|
545
|
+
// A regular file at an old managed path is overwritten below.
|
|
546
|
+
} else if (st.isDirectory()) {
|
|
547
|
+
throw conflictError(
|
|
548
|
+
`new managed path ${rel} conflicts with an existing local directory (local artifact)`,
|
|
549
|
+
);
|
|
550
|
+
} else {
|
|
551
|
+
throw conflictError(
|
|
552
|
+
`new managed path ${rel} conflicts with an existing local file (local artifact)`,
|
|
553
|
+
);
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
const segments = rel.split('/');
|
|
557
|
+
for (let i = 1; i < segments.length; i += 1) {
|
|
558
|
+
const ancestor = segments.slice(0, i).join('/');
|
|
559
|
+
const ancSt = lstatOrNull(path.join(stageRoot, ...ancestor.split('/')));
|
|
560
|
+
if (ancSt && !ancSt.isDirectory()) {
|
|
561
|
+
throw conflictError(
|
|
562
|
+
`new managed path ${rel} must live under ${ancestor}, which is a local file (local artifact)`,
|
|
563
|
+
);
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/**
|
|
570
|
+
* Assert installPath is either absent, or a valid managed mirror directory.
|
|
571
|
+
* Refuses files, symlinks, special entries, and unmanaged directories.
|
|
572
|
+
*/
|
|
573
|
+
function assertInstallPathReplaceable(installPath) {
|
|
574
|
+
const st = lstatOrNull(installPath);
|
|
575
|
+
if (!st) return null;
|
|
576
|
+
|
|
577
|
+
if (st.isSymbolicLink()) {
|
|
578
|
+
const err = new Error(`unmanaged local symlink blocks install: ${installPath}`);
|
|
579
|
+
err.code = 'UNMANAGED_CONFLICT';
|
|
580
|
+
throw err;
|
|
581
|
+
}
|
|
582
|
+
if (!st.isDirectory()) {
|
|
583
|
+
const err = new Error(`unmanaged local file blocks install: ${installPath}`);
|
|
584
|
+
err.code = 'UNMANAGED_CONFLICT';
|
|
585
|
+
throw err;
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
const marker = readWorkCopyMarker(installPath);
|
|
589
|
+
if (!marker) {
|
|
590
|
+
const markerPath = path.join(installPath, LORE_SKILL_MARKER);
|
|
591
|
+
if (pathExists(markerPath)) {
|
|
592
|
+
const err = new Error(`invalid work-copy marker blocks install: ${installPath}`);
|
|
593
|
+
err.code = 'INVALID_MARKER';
|
|
594
|
+
throw err;
|
|
595
|
+
}
|
|
596
|
+
const err = new Error(`unmanaged local directory blocks install: ${installPath}`);
|
|
597
|
+
err.code = 'UNMANAGED_CONFLICT';
|
|
598
|
+
throw err;
|
|
599
|
+
}
|
|
600
|
+
return marker;
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
/**
|
|
604
|
+
* Materialize (or upgrade/migrate) a local work copy from server detail.
|
|
605
|
+
*
|
|
606
|
+
* - Missing install: full stage + atomic move.
|
|
607
|
+
* - Existing managed work copy (marker with managed_files): the stage is seeded from
|
|
608
|
+
* the existing copy so extra local files are preserved. Obsolete managed files are
|
|
609
|
+
* removed, incoming managed files are written, and the marker is refreshed.
|
|
610
|
+
* - Legacy markers (no managed_files boundary) have no preserved extras: they are
|
|
611
|
+
* rematerialized fresh from server state.
|
|
612
|
+
* - A new managed path that conflicts with a preserved local artifact (file/dir shape
|
|
613
|
+
* or same path) fails safely with no damage to the installed copy.
|
|
614
|
+
* - Unmanaged file/symlink/directory or invalid marker: refused.
|
|
615
|
+
* - Installed directories are writable (0755, POSIX); server-managed files and the
|
|
616
|
+
* marker are 0444. Stage and backup stay writable internally.
|
|
617
|
+
*/
|
|
618
|
+
export function materializeSkillWorkCopy(opts) {
|
|
619
|
+
const { loreHome, projectId, detail } = opts;
|
|
620
|
+
const skillName = sanitizeSegment(String(detail.name || ''));
|
|
621
|
+
return materializeSkillWorkCopyAt({
|
|
622
|
+
installPath: skillInstallPath(loreHome, projectId, skillName),
|
|
623
|
+
stagingBase: stagingRoot(loreHome, projectId),
|
|
624
|
+
projectId,
|
|
625
|
+
detail,
|
|
626
|
+
});
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
/** @deprecated Prefer materializeSkillWorkCopy. */
|
|
630
|
+
export function writeSkillMirrorAtomic(opts) {
|
|
631
|
+
return materializeSkillWorkCopy(opts);
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
/**
|
|
635
|
+
* Materialize a work copy at an explicit install path and staging base (both must be
|
|
636
|
+
* on the same filesystem for the rename-based atomic swap). `sourceManifestHash`
|
|
637
|
+
* records the server-side manifest of the unadapted payload when a host adapter
|
|
638
|
+
* modified the written file set, so later syncs can distinguish "server has a new
|
|
639
|
+
* version" from "local managed files were changed". Omitted/equal values are not
|
|
640
|
+
* stored, keeping markers byte-identical to the non-adapted path.
|
|
641
|
+
*/
|
|
642
|
+
export function materializeSkillWorkCopyAt(opts) {
|
|
643
|
+
const { installPath, stagingBase, projectId, detail, sourceManifestHash } = opts;
|
|
644
|
+
const skillName = sanitizeSegment(String(detail.name || ''));
|
|
645
|
+
const { files, manifest_hash } = validateSkillPayload(detail);
|
|
646
|
+
const managedFiles = validateManagedFileList(files.map((f) => f.path), { requireSkillMd: true });
|
|
647
|
+
const serverVersion = skillVersionOf(detail) ?? '';
|
|
648
|
+
const serverRevision = skillRevisionOf(detail) || undefined;
|
|
649
|
+
const skillId = skillIdOf(detail);
|
|
650
|
+
|
|
651
|
+
const existingMarker = assertInstallPathReplaceable(installPath);
|
|
652
|
+
const existingManaged = existingMarker && existingMarker.schema === LORE_SKILL_SCHEMA
|
|
653
|
+
? existingMarker.managed_files
|
|
654
|
+
: [];
|
|
655
|
+
|
|
656
|
+
// This must happen before copyTree, chmod, or obsolete-path removal: path operations
|
|
657
|
+
// must never traverse a symlinked ancestor outside the installed work copy.
|
|
658
|
+
if (existingManaged.length > 0) {
|
|
659
|
+
assertManagedPathAncestorsSafe(installPath, existingManaged);
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
// The stage must live on the same filesystem as the install (rename-based swap).
|
|
663
|
+
ensureDir(stagingBase, WORK_DIR_MODE);
|
|
664
|
+
const stageId = `${skillName}-${Date.now()}-${crypto.randomBytes(4).toString('hex')}`;
|
|
665
|
+
const stagePath = path.join(stagingBase, stageId);
|
|
666
|
+
const finalStage = path.join(stagingBase, `${stageId}.final`);
|
|
667
|
+
|
|
668
|
+
try {
|
|
669
|
+
ensureDir(stagePath, WORK_DIR_MODE);
|
|
670
|
+
|
|
671
|
+
// Seed the stage from the existing valid managed copy (preserves local extras).
|
|
672
|
+
// Legacy markers have no managed_files boundary, so build fresh instead.
|
|
673
|
+
if (existingMarker && existingMarker.schema === LORE_SKILL_SCHEMA && pathExists(installPath)) {
|
|
674
|
+
copyTree(installPath, stagePath);
|
|
675
|
+
// Seeded server-managed files + marker are 0444; make them writable in the stage
|
|
676
|
+
// so they can be replaced/removed. Extra local files keep their original modes.
|
|
677
|
+
for (const rel of [...existingManaged, LORE_SKILL_MARKER]) {
|
|
678
|
+
const seeded = path.join(stagePath, ...rel.split('/'));
|
|
679
|
+
const seededStat = lstatOrNull(seeded);
|
|
680
|
+
if (seededStat && seededStat.isFile()) {
|
|
681
|
+
try { fs.chmodSync(seeded, WORK_FILE_MODE); } catch { /* ignore */ }
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
const newManagedSet = new Set(managedFiles);
|
|
687
|
+
removeObsoleteManaged(stagePath, existingManaged, newManagedSet);
|
|
688
|
+
assertNoManagedExtraConflicts(stagePath, managedFiles, new Set(existingManaged));
|
|
689
|
+
|
|
690
|
+
// Write incoming managed files.
|
|
691
|
+
for (const file of files) {
|
|
692
|
+
const dest = path.join(stagePath, ...file.path.split('/'));
|
|
693
|
+
ensureDir(path.dirname(dest), WORK_DIR_MODE);
|
|
694
|
+
fs.writeFileSync(dest, file.buffer, { mode: WORK_FILE_MODE });
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
const sourceManifest = typeof sourceManifestHash === 'string'
|
|
698
|
+
&& sourceManifestHash.trim().toLowerCase() !== manifest_hash
|
|
699
|
+
? sourceManifestHash.trim().toLowerCase()
|
|
700
|
+
: undefined;
|
|
701
|
+
const marker = {
|
|
702
|
+
schema: LORE_SKILL_SCHEMA,
|
|
703
|
+
project_id: projectId,
|
|
704
|
+
skill_id: skillId,
|
|
705
|
+
name: skillName,
|
|
706
|
+
version: serverVersion,
|
|
707
|
+
managed_files: managedFiles,
|
|
708
|
+
revision_hash: serverRevision,
|
|
709
|
+
manifest_hash,
|
|
710
|
+
...(sourceManifest ? { source_manifest_hash: sourceManifest } : {}),
|
|
711
|
+
readonly: true,
|
|
712
|
+
synced_at: new Date().toISOString(),
|
|
713
|
+
};
|
|
714
|
+
fs.writeFileSync(path.join(stagePath, LORE_SKILL_MARKER), `${JSON.stringify(marker, null, 2)}\n`, {
|
|
715
|
+
mode: WORK_FILE_MODE,
|
|
716
|
+
encoding: 'utf-8',
|
|
717
|
+
});
|
|
718
|
+
|
|
719
|
+
if (pathExists(finalStage)) rmrf(finalStage);
|
|
720
|
+
fs.renameSync(stagePath, finalStage);
|
|
721
|
+
|
|
722
|
+
const installedBase = path.dirname(installPath);
|
|
723
|
+
ensureDir(installedBase, WORK_DIR_MODE);
|
|
724
|
+
const backupPath = path.join(stagingBase, `${skillName}.backup-${Date.now()}`);
|
|
725
|
+
if (pathExists(installPath)) {
|
|
726
|
+
// Only rename a previously validated managed directory. Make it writable first
|
|
727
|
+
// so legacy 0555 read-only installs can be renamed/rolled back on all POSIX.
|
|
728
|
+
makeTreeWritable(installPath);
|
|
729
|
+
fs.renameSync(installPath, backupPath);
|
|
730
|
+
}
|
|
731
|
+
try {
|
|
732
|
+
fs.renameSync(finalStage, installPath);
|
|
733
|
+
} catch (error) {
|
|
734
|
+
if (pathExists(backupPath) && !pathExists(installPath)) {
|
|
735
|
+
try {
|
|
736
|
+
fs.renameSync(backupPath, installPath);
|
|
737
|
+
} catch { /* ignore */ }
|
|
738
|
+
}
|
|
739
|
+
throw error;
|
|
740
|
+
}
|
|
741
|
+
if (pathExists(backupPath)) rmrf(backupPath);
|
|
742
|
+
applyInstalledModes(installPath, managedFiles);
|
|
743
|
+
return { installPath, marker };
|
|
744
|
+
} finally {
|
|
745
|
+
if (pathExists(stagePath)) rmrf(stagePath);
|
|
746
|
+
if (pathExists(finalStage)) rmrf(finalStage);
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
/**
|
|
751
|
+
* Inspect a local work copy. Returns 'tampered' only when a server-managed file
|
|
752
|
+
* (from marker.managed_files) is missing, is not a regular file, or its hash does not
|
|
753
|
+
* match the marker manifest_hash. Extra local files never trigger tamper.
|
|
754
|
+
*/
|
|
755
|
+
export function inspectLocalWorkCopy(loreHome, projectId, skillName, expected) {
|
|
756
|
+
const dir = skillInstallPath(loreHome, projectId, skillName);
|
|
757
|
+
const rootStat = lstatOrNull(dir);
|
|
758
|
+
if (!rootStat) {
|
|
759
|
+
return { name: skillName, skill_id: expected?.skill_id, state: 'missing', message: 'mirror not installed' };
|
|
760
|
+
}
|
|
761
|
+
// Symlinks at install root are never treated as mirror directories.
|
|
762
|
+
if (rootStat.isSymbolicLink()) {
|
|
763
|
+
return {
|
|
764
|
+
name: skillName,
|
|
765
|
+
skill_id: expected?.skill_id,
|
|
766
|
+
state: 'unmanaged',
|
|
767
|
+
path: dir,
|
|
768
|
+
message: 'install path is a symlink; left untouched',
|
|
769
|
+
};
|
|
770
|
+
}
|
|
771
|
+
if (!rootStat.isDirectory()) {
|
|
772
|
+
return {
|
|
773
|
+
name: skillName,
|
|
774
|
+
skill_id: expected?.skill_id,
|
|
775
|
+
state: 'unmanaged',
|
|
776
|
+
path: dir,
|
|
777
|
+
message: 'install path exists and is not a managed mirror directory',
|
|
778
|
+
};
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
const marker = readWorkCopyMarker(dir);
|
|
782
|
+
if (!marker) {
|
|
783
|
+
const markerPath = path.join(dir, LORE_SKILL_MARKER);
|
|
784
|
+
if (pathExists(markerPath)) {
|
|
785
|
+
return {
|
|
786
|
+
name: skillName,
|
|
787
|
+
state: 'invalid',
|
|
788
|
+
path: dir,
|
|
789
|
+
message: 'mirror marker is missing, corrupt, or contains unsafe managed_files',
|
|
790
|
+
};
|
|
791
|
+
}
|
|
792
|
+
return {
|
|
793
|
+
name: skillName,
|
|
794
|
+
state: 'unmanaged',
|
|
795
|
+
path: dir,
|
|
796
|
+
message: `directory exists without ${LORE_SKILL_MARKER}; left untouched`,
|
|
797
|
+
};
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
if (marker.schema !== LORE_SKILL_SCHEMA && marker.schema !== LEGACY_MIRROR_SCHEMA) {
|
|
801
|
+
return {
|
|
802
|
+
name: skillName,
|
|
803
|
+
skill_id: marker.skill_id,
|
|
804
|
+
state: 'invalid',
|
|
805
|
+
path: dir,
|
|
806
|
+
version: marker.version,
|
|
807
|
+
message: `unsupported mirror marker schema: ${marker.schema}`,
|
|
808
|
+
};
|
|
809
|
+
}
|
|
810
|
+
if (marker.project_id !== projectId || marker.name !== skillName) {
|
|
811
|
+
return {
|
|
812
|
+
name: skillName,
|
|
813
|
+
skill_id: marker.skill_id,
|
|
814
|
+
state: 'invalid',
|
|
815
|
+
path: dir,
|
|
816
|
+
version: marker.version,
|
|
817
|
+
message: 'mirror marker identity does not match its managed path',
|
|
818
|
+
};
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
const skillMd = path.join(dir, SKILL_MD);
|
|
822
|
+
const skillMdStat = lstatOrNull(skillMd);
|
|
823
|
+
if (!skillMdStat || skillMdStat.isSymbolicLink() || !skillMdStat.isFile()) {
|
|
824
|
+
return {
|
|
825
|
+
name: skillName,
|
|
826
|
+
skill_id: marker.skill_id,
|
|
827
|
+
state: 'tampered',
|
|
828
|
+
path: dir,
|
|
829
|
+
version: marker.version,
|
|
830
|
+
revision_hash: marker.revision_hash,
|
|
831
|
+
message: 'SKILL.md missing',
|
|
832
|
+
};
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
// Integrity: hash ONLY the managed files from the marker (extras are ignored).
|
|
836
|
+
if (marker.manifest_hash) {
|
|
837
|
+
let localHash;
|
|
838
|
+
try {
|
|
839
|
+
localHash = hashLocalSkillFiles(dir).manifest_hash;
|
|
840
|
+
} catch (error) {
|
|
841
|
+
return {
|
|
842
|
+
name: skillName,
|
|
843
|
+
skill_id: marker.skill_id,
|
|
844
|
+
state: 'tampered',
|
|
845
|
+
path: dir,
|
|
846
|
+
version: marker.version,
|
|
847
|
+
revision_hash: marker.revision_hash,
|
|
848
|
+
message: error?.message || 'failed to verify managed files',
|
|
849
|
+
};
|
|
850
|
+
}
|
|
851
|
+
if (localHash !== marker.manifest_hash) {
|
|
852
|
+
return {
|
|
853
|
+
name: skillName,
|
|
854
|
+
skill_id: marker.skill_id,
|
|
855
|
+
state: 'tampered',
|
|
856
|
+
path: dir,
|
|
857
|
+
version: marker.version,
|
|
858
|
+
revision_hash: marker.revision_hash,
|
|
859
|
+
message: 'managed file hashes do not match marker manifest_hash',
|
|
860
|
+
};
|
|
861
|
+
}
|
|
862
|
+
} else {
|
|
863
|
+
// Pre-manifest workcopy markers cannot be integrity-checked; rematerialize once.
|
|
864
|
+
return {
|
|
865
|
+
name: skillName,
|
|
866
|
+
skill_id: marker.skill_id,
|
|
867
|
+
state: 'tampered',
|
|
868
|
+
path: dir,
|
|
869
|
+
version: marker.version,
|
|
870
|
+
message: 'mirror marker missing manifest_hash; rematerialize required',
|
|
871
|
+
};
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
// Work copies are keyed by name. A different skill_id means the old skill was
|
|
875
|
+
// archived or deleted and a new one took its name, so replace the copy.
|
|
876
|
+
if (expected?.skill_id && marker.skill_id !== expected.skill_id) {
|
|
877
|
+
return {
|
|
878
|
+
name: skillName,
|
|
879
|
+
skill_id: marker.skill_id,
|
|
880
|
+
state: 'outdated',
|
|
881
|
+
path: dir,
|
|
882
|
+
version: marker.version,
|
|
883
|
+
revision_hash: marker.revision_hash,
|
|
884
|
+
message: `skill_id mismatch: local ${marker.skill_id} vs expected ${expected.skill_id}`,
|
|
885
|
+
};
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
if (expected?.revision_hash && marker.revision_hash !== expected.revision_hash) {
|
|
889
|
+
return {
|
|
890
|
+
name: skillName,
|
|
891
|
+
skill_id: marker.skill_id,
|
|
892
|
+
state: 'outdated',
|
|
893
|
+
path: dir,
|
|
894
|
+
version: marker.version,
|
|
895
|
+
revision_hash: marker.revision_hash,
|
|
896
|
+
message: `revision outdated: local ${marker.revision_hash} vs expected ${expected.revision_hash}`,
|
|
897
|
+
};
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
if (expected?.version !== undefined && String(marker.version) !== String(expected.version)) {
|
|
901
|
+
return {
|
|
902
|
+
name: skillName,
|
|
903
|
+
skill_id: marker.skill_id,
|
|
904
|
+
state: 'outdated',
|
|
905
|
+
path: dir,
|
|
906
|
+
version: marker.version,
|
|
907
|
+
revision_hash: marker.revision_hash,
|
|
908
|
+
message: `version outdated: local ${marker.version} vs expected ${expected.version}`,
|
|
909
|
+
};
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
if (expected?.manifest_hash && marker.manifest_hash !== expected.manifest_hash) {
|
|
913
|
+
return {
|
|
914
|
+
name: skillName,
|
|
915
|
+
skill_id: marker.skill_id,
|
|
916
|
+
state: 'outdated',
|
|
917
|
+
path: dir,
|
|
918
|
+
version: marker.version,
|
|
919
|
+
revision_hash: marker.revision_hash,
|
|
920
|
+
message: 'manifest_hash outdated',
|
|
921
|
+
};
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
return {
|
|
925
|
+
name: skillName,
|
|
926
|
+
skill_id: marker.skill_id,
|
|
927
|
+
state: 'ready',
|
|
928
|
+
path: dir,
|
|
929
|
+
version: marker.version,
|
|
930
|
+
revision_hash: marker.revision_hash,
|
|
931
|
+
};
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
/** @deprecated Prefer inspectLocalWorkCopy. */
|
|
935
|
+
export const inspectLocalMirror = inspectLocalWorkCopy;
|
|
936
|
+
|
|
937
|
+
// ---- transport validation ----
|
|
938
|
+
|
|
939
|
+
export function validateSkillPayload(detail) {
|
|
940
|
+
const name = String(detail.name || '').trim();
|
|
941
|
+
if (!name) throw new Error('skill detail missing name');
|
|
942
|
+
const skillId = skillIdOf(detail);
|
|
943
|
+
if (!skillId) throw new Error('skill detail missing skill_id');
|
|
944
|
+
|
|
945
|
+
const rawFiles = Array.isArray(detail.files) ? detail.files : [];
|
|
946
|
+
if (rawFiles.length === 0) throw new Error('skill detail has no files');
|
|
947
|
+
|
|
948
|
+
const files = [];
|
|
949
|
+
const seenPaths = new Set();
|
|
950
|
+
let hasSkillMd = false;
|
|
951
|
+
for (const file of rawFiles) {
|
|
952
|
+
const rel = validateSafeRelativePath(String(file.path || ''));
|
|
953
|
+
if (seenPaths.has(rel)) throw new Error(`duplicate skill file path: ${rel}`);
|
|
954
|
+
seenPaths.add(rel);
|
|
955
|
+
if (rel === SKILL_MD) hasSkillMd = true;
|
|
956
|
+
if (rel === LORE_SKILL_MARKER || rel === LEGACY_LORE_SKILL_MARKER) {
|
|
957
|
+
throw new Error(`${rel} may not be supplied as a skill file`);
|
|
958
|
+
}
|
|
959
|
+
const buffer = decodeSkillFileContent(file);
|
|
960
|
+
const sha = sha256Buffer(buffer);
|
|
961
|
+
if (file.sha256) {
|
|
962
|
+
const expected = String(file.sha256).toLowerCase();
|
|
963
|
+
if (expected !== sha) {
|
|
964
|
+
throw new Error(`sha256 mismatch for ${rel}: expected ${expected}, got ${sha}`);
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
if (Number.isFinite(file.size) && Number(file.size) !== buffer.length) {
|
|
968
|
+
throw new Error(`size mismatch for ${rel}: expected ${file.size}, got ${buffer.length}`);
|
|
969
|
+
}
|
|
970
|
+
files.push({ path: rel, buffer, sha256: sha, media_type: file.media_type });
|
|
971
|
+
}
|
|
972
|
+
if (!hasSkillMd) throw new Error('skill must include SKILL.md');
|
|
973
|
+
for (const rel of seenPaths) {
|
|
974
|
+
const segments = rel.split('/');
|
|
975
|
+
for (let i = 1; i < segments.length; i += 1) {
|
|
976
|
+
const parent = segments.slice(0, i).join('/');
|
|
977
|
+
if (seenPaths.has(parent)) throw new Error(`skill file path ${rel} conflicts with parent file ${parent}`);
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
const serverManifest = typeof detail.manifest_hash === 'string' ? detail.manifest_hash.toLowerCase() : '';
|
|
982
|
+
const manifest_hash = computeManifestHash(files.map((f) => ({ path: f.path, sha256: f.sha256, size: f.buffer.length })));
|
|
983
|
+
if (serverManifest && serverManifest !== manifest_hash) {
|
|
984
|
+
throw new Error(`manifest_hash mismatch: expected ${serverManifest}, got ${manifest_hash}`);
|
|
985
|
+
}
|
|
986
|
+
return { files, manifest_hash };
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
/**
|
|
990
|
+
* Ensure a local work copy for the skill and return local SKILL.md + absolute skill_dir.
|
|
991
|
+
*
|
|
992
|
+
* - Missing, outdated (version/revision/manifest differs), tampered (managed files
|
|
993
|
+
* modified), or legacy copies are rematerialized from the fetched server detail.
|
|
994
|
+
* Rematerialization preserves extra local files in the same copy.
|
|
995
|
+
* - Same version with intact managed files reuses the local copy (no overwrite);
|
|
996
|
+
* extra local files survive.
|
|
997
|
+
* - Unmanaged / invalid roots error (fail-closed).
|
|
998
|
+
*
|
|
999
|
+
* Transport is injected:
|
|
1000
|
+
* loadSkill(skillId) → Promise<SkillDetail>
|
|
1001
|
+
* loadCatalog?.() → Promise<{ project_id: string, catalog_revision?: string }>
|
|
1002
|
+
*/
|
|
1003
|
+
export async function ensureSkillWorkCopy(opts) {
|
|
1004
|
+
const loreHome = opts.loreHome || resolveLoreHome();
|
|
1005
|
+
if (typeof opts.loadSkill !== 'function') {
|
|
1006
|
+
throw new Error('ensureSkillWorkCopy requires async loadSkill(skillId)');
|
|
1007
|
+
}
|
|
1008
|
+
const detail = normalizeSkillDetail(await opts.loadSkill(opts.skillId));
|
|
1009
|
+
let projectId = String(
|
|
1010
|
+
opts.projectId
|
|
1011
|
+
|| detail.project_id
|
|
1012
|
+
|| '',
|
|
1013
|
+
).trim();
|
|
1014
|
+
if (!projectId) {
|
|
1015
|
+
if (typeof opts.loadCatalog !== 'function') {
|
|
1016
|
+
throw new Error('unable to determine project_id for skill mirror');
|
|
1017
|
+
}
|
|
1018
|
+
const catalog = await opts.loadCatalog();
|
|
1019
|
+
projectId = String(catalog?.project_id || '').trim();
|
|
1020
|
+
if (!projectId) throw new Error('unable to determine project_id for skill mirror');
|
|
1021
|
+
return ensureSkillWorkCopy({ ...opts, projectId, loreHome });
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
const skillName = sanitizeSegment(String(detail.name || ''));
|
|
1025
|
+
const serverVersion = skillVersionOf(detail);
|
|
1026
|
+
const serverRevision = skillRevisionOf(detail) || undefined;
|
|
1027
|
+
const serverManifest = typeof detail.manifest_hash === 'string' ? detail.manifest_hash : undefined;
|
|
1028
|
+
const skillId = skillIdOf(detail) || opts.skillId;
|
|
1029
|
+
const installPath = skillInstallPath(loreHome, projectId, skillName);
|
|
1030
|
+
|
|
1031
|
+
const status = inspectLocalWorkCopy(loreHome, projectId, skillName, {
|
|
1032
|
+
skill_id: skillId,
|
|
1033
|
+
version: serverVersion,
|
|
1034
|
+
revision_hash: serverRevision,
|
|
1035
|
+
manifest_hash: serverManifest,
|
|
1036
|
+
});
|
|
1037
|
+
|
|
1038
|
+
if (status.state === 'unmanaged') {
|
|
1039
|
+
const err = new Error(status.message || `unmanaged path blocks skill mirror: ${installPath}`);
|
|
1040
|
+
err.code = 'UNMANAGED_CONFLICT';
|
|
1041
|
+
throw err;
|
|
1042
|
+
}
|
|
1043
|
+
if (status.state === 'invalid') {
|
|
1044
|
+
const err = new Error(status.message || `invalid local mirror: ${installPath}`);
|
|
1045
|
+
err.code = 'INVALID_WORK_COPY';
|
|
1046
|
+
throw err;
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
let downloaded = false;
|
|
1050
|
+
let skillDir = installPath;
|
|
1051
|
+
let activeMarker = null;
|
|
1052
|
+
|
|
1053
|
+
if (status.state === 'ready' && status.path) {
|
|
1054
|
+
// Inspect verified identity/version/integrity. Legacy same-version mirrors migrate.
|
|
1055
|
+
const marker = readWorkCopyMarker(status.path);
|
|
1056
|
+
if (!marker) {
|
|
1057
|
+
const err = new Error(`invalid local mirror marker: ${status.path}`);
|
|
1058
|
+
err.code = 'INVALID_WORK_COPY';
|
|
1059
|
+
throw err;
|
|
1060
|
+
}
|
|
1061
|
+
if (marker.schema === LEGACY_MIRROR_SCHEMA) {
|
|
1062
|
+
// Same version legacy → rematerialize to managed_files workcopy.
|
|
1063
|
+
const result = materializeSkillWorkCopy({ loreHome, projectId, detail });
|
|
1064
|
+
skillDir = result.installPath;
|
|
1065
|
+
activeMarker = result.marker;
|
|
1066
|
+
downloaded = true;
|
|
1067
|
+
} else if (marker.schema === LORE_SKILL_SCHEMA) {
|
|
1068
|
+
skillDir = status.path;
|
|
1069
|
+
activeMarker = marker;
|
|
1070
|
+
downloaded = false;
|
|
1071
|
+
} else {
|
|
1072
|
+
const err = new Error(`unsupported local mirror schema: ${marker.schema}`);
|
|
1073
|
+
err.code = 'INVALID_WORK_COPY';
|
|
1074
|
+
throw err;
|
|
1075
|
+
}
|
|
1076
|
+
} else {
|
|
1077
|
+
// missing, outdated, or tampered → rematerialize from server state (extras preserved).
|
|
1078
|
+
const result = materializeSkillWorkCopy({ loreHome, projectId, detail });
|
|
1079
|
+
skillDir = result.installPath;
|
|
1080
|
+
activeMarker = result.marker;
|
|
1081
|
+
downloaded = true;
|
|
1082
|
+
}
|
|
1083
|
+
|
|
1084
|
+
if (!activeMarker) {
|
|
1085
|
+
throw new Error('failed to materialize skill mirror');
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
// Final identity check after materialize/return path.
|
|
1089
|
+
if (activeMarker.project_id !== projectId || activeMarker.skill_id !== skillId || activeMarker.name !== skillName) {
|
|
1090
|
+
throw new Error(
|
|
1091
|
+
`mirror identity mismatch after ensure: project=${activeMarker.project_id} skill=${activeMarker.skill_id} name=${activeMarker.name}`,
|
|
1092
|
+
);
|
|
1093
|
+
}
|
|
1094
|
+
|
|
1095
|
+
const skillMdPath = path.join(skillDir, SKILL_MD);
|
|
1096
|
+
const skillMdStat = lstatOrNull(skillMdPath);
|
|
1097
|
+
if (!skillMdStat || skillMdStat.isSymbolicLink() || !skillMdStat.isFile()) {
|
|
1098
|
+
throw new Error(`SKILL.md missing or not a regular file in mirror: ${skillDir}`);
|
|
1099
|
+
}
|
|
1100
|
+
const skill_md = fs.readFileSync(skillMdPath, 'utf-8');
|
|
1101
|
+
return {
|
|
1102
|
+
skill_dir: path.resolve(skillDir),
|
|
1103
|
+
skill_md,
|
|
1104
|
+
skill_md_path: path.resolve(skillMdPath),
|
|
1105
|
+
marker: activeMarker,
|
|
1106
|
+
project_id: projectId,
|
|
1107
|
+
skill: detail,
|
|
1108
|
+
server_version: serverVersion,
|
|
1109
|
+
local_version: activeMarker.version,
|
|
1110
|
+
downloaded,
|
|
1111
|
+
};
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
export function listLocalWorkCopyStatuses(loreHome, projectId) {
|
|
1115
|
+
if (!projectId) return [];
|
|
1116
|
+
return listDirectoryNames(projectWorkCopyRoot(loreHome, projectId)).map((name) =>
|
|
1117
|
+
inspectLocalWorkCopy(loreHome, projectId, name),
|
|
1118
|
+
);
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
// ---- skills-directory sync (host-native skills/ directories) ----
|
|
1122
|
+
|
|
1123
|
+
const SYNC_STAGING_DIR = '.lore-sync-staging';
|
|
1124
|
+
|
|
1125
|
+
/**
|
|
1126
|
+
* True when the marker identity matches the server summary (skill_id, version, and
|
|
1127
|
+
* server manifest when the summary carries one). `source_manifest_hash` (recorded
|
|
1128
|
+
* when adapt changed the written set) is compared against the server manifest so an
|
|
1129
|
+
* adapted copy is not considered outdated just because its written files differ.
|
|
1130
|
+
*/
|
|
1131
|
+
function markerMatchesSummary(marker, summary) {
|
|
1132
|
+
if (String(marker.skill_id) !== String(skillIdOf(summary))) return false;
|
|
1133
|
+
const summaryVersion = skillVersionOf(summary);
|
|
1134
|
+
if (summaryVersion !== undefined && summaryVersion !== '' && String(marker.version) !== String(summaryVersion)) {
|
|
1135
|
+
return false;
|
|
1136
|
+
}
|
|
1137
|
+
const serverManifest = typeof summary.manifest_hash === 'string' ? summary.manifest_hash.trim().toLowerCase() : '';
|
|
1138
|
+
if (serverManifest) {
|
|
1139
|
+
const localSource = String(marker.source_manifest_hash || marker.manifest_hash || '').trim().toLowerCase();
|
|
1140
|
+
if (localSource !== serverManifest) return false;
|
|
1141
|
+
}
|
|
1142
|
+
return true;
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
/**
|
|
1146
|
+
* Remove the managed files and marker of a work copy, preserving local artifacts.
|
|
1147
|
+
* The directory itself is removed only when nothing local remains in it.
|
|
1148
|
+
*/
|
|
1149
|
+
function removeManagedWorkCopy(dir, marker) {
|
|
1150
|
+
assertManagedPathAncestorsSafe(dir, marker.managed_files);
|
|
1151
|
+
for (const rel of [...marker.managed_files, LORE_SKILL_MARKER]) {
|
|
1152
|
+
const full = path.join(dir, ...rel.split('/'));
|
|
1153
|
+
const st = lstatOrNull(full);
|
|
1154
|
+
if (!st) continue;
|
|
1155
|
+
if (st.isDirectory()) continue; // a local artifact took over the managed path
|
|
1156
|
+
fs.rmSync(full, { force: true });
|
|
1157
|
+
}
|
|
1158
|
+
const prefixes = [...managedDirPrefixes(new Set(marker.managed_files))]
|
|
1159
|
+
.sort((a, b) => b.split('/').length - a.split('/').length);
|
|
1160
|
+
for (const rel of prefixes) {
|
|
1161
|
+
const full = path.join(dir, ...rel.split('/'));
|
|
1162
|
+
const st = lstatOrNull(full);
|
|
1163
|
+
if (st?.isDirectory()) {
|
|
1164
|
+
try {
|
|
1165
|
+
if (fs.readdirSync(full).length === 0) fs.rmdirSync(full);
|
|
1166
|
+
} catch { /* ignore */ }
|
|
1167
|
+
}
|
|
1168
|
+
}
|
|
1169
|
+
try {
|
|
1170
|
+
if (fs.readdirSync(dir).length === 0) fs.rmdirSync(dir);
|
|
1171
|
+
} catch { /* ignore */ }
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
/**
|
|
1175
|
+
* Reconcile a host-native skills directory with the server catalog.
|
|
1176
|
+
*
|
|
1177
|
+
* - root/<sanitize(name)>/ is the install target for each summary.
|
|
1178
|
+
* - Directories without a Lore marker, or whose marker belongs to another project,
|
|
1179
|
+
* are never touched and are reported as conflicts.
|
|
1180
|
+
* - Matching skill_id + version + server manifest_hash with intact managed files is
|
|
1181
|
+
* unchanged: no detail request is made.
|
|
1182
|
+
* - Otherwise the detail is fetched (loadSkill), optionally adapted for the host
|
|
1183
|
+
* (adapt), and materialized with the shared semantics: managed files 0444, local
|
|
1184
|
+
* artifacts preserved, safe conflict errors, atomic swap. The marker records the
|
|
1185
|
+
* server-side manifest separately (source_manifest_hash) so adapted copies are not
|
|
1186
|
+
* flagged as tampered or outdated on the next sync.
|
|
1187
|
+
* - Directories carrying a this-project marker that the catalog no longer claims
|
|
1188
|
+
* (archived/disabled/renamed) lose their managed files and marker; local artifacts
|
|
1189
|
+
* keep the directory alive.
|
|
1190
|
+
* - Staging lives in a hidden directory inside root (same filesystem) and is cleaned
|
|
1191
|
+
* up afterwards.
|
|
1192
|
+
*
|
|
1193
|
+
* Returns { created, updated, unchanged, removed, conflicts, errors } (name arrays;
|
|
1194
|
+
* errors entries carry { name, message }).
|
|
1195
|
+
*/
|
|
1196
|
+
export async function syncSkillsToDir(opts) {
|
|
1197
|
+
const { root, projectId, skills, loadSkill, adapt } = opts;
|
|
1198
|
+
if (!root) throw new Error('syncSkillsToDir requires root');
|
|
1199
|
+
const projectIdStr = String(projectId || '').trim();
|
|
1200
|
+
if (!projectIdStr) throw new Error('syncSkillsToDir requires projectId');
|
|
1201
|
+
if (typeof loadSkill !== 'function') {
|
|
1202
|
+
throw new Error('syncSkillsToDir requires async loadSkill(skillId)');
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
const result = { created: [], updated: [], unchanged: [], removed: [], conflicts: [], errors: [] };
|
|
1206
|
+
const rootPath = path.resolve(String(root));
|
|
1207
|
+
fs.mkdirSync(rootPath, { recursive: true, mode: WORK_DIR_MODE });
|
|
1208
|
+
|
|
1209
|
+
const stagingBase = path.join(rootPath, SYNC_STAGING_DIR);
|
|
1210
|
+
try {
|
|
1211
|
+
const listedIds = new Set(); // skill_ids present in the server catalog
|
|
1212
|
+
for (const raw of (Array.isArray(skills) ? skills : [])) {
|
|
1213
|
+
const summary = normalizeSkillSummary(raw);
|
|
1214
|
+
let name = String(summary.name || '');
|
|
1215
|
+
try {
|
|
1216
|
+
name = sanitizeSegment(name);
|
|
1217
|
+
const skillId = skillIdOf(summary);
|
|
1218
|
+
if (!skillId) throw new Error('skill summary missing skill_id');
|
|
1219
|
+
listedIds.add(String(skillId));
|
|
1220
|
+
|
|
1221
|
+
const installPath = path.join(rootPath, name);
|
|
1222
|
+
const existingStat = lstatOrNull(installPath);
|
|
1223
|
+
if (existingStat && (existingStat.isSymbolicLink() || !existingStat.isDirectory())) {
|
|
1224
|
+
result.conflicts.push(name);
|
|
1225
|
+
continue;
|
|
1226
|
+
}
|
|
1227
|
+
if (existingStat) {
|
|
1228
|
+
const marker = readWorkCopyMarker(installPath);
|
|
1229
|
+
if (!marker || marker.project_id !== projectIdStr) {
|
|
1230
|
+
result.conflicts.push(name);
|
|
1231
|
+
continue;
|
|
1232
|
+
}
|
|
1233
|
+
if (markerMatchesSummary(marker, summary)) {
|
|
1234
|
+
let intact = false;
|
|
1235
|
+
try {
|
|
1236
|
+
intact = hashLocalSkillFiles(installPath).manifest_hash === marker.manifest_hash;
|
|
1237
|
+
} catch {
|
|
1238
|
+
intact = false;
|
|
1239
|
+
}
|
|
1240
|
+
if (intact) {
|
|
1241
|
+
result.unchanged.push(name);
|
|
1242
|
+
continue;
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
const detail = normalizeSkillDetail(await loadSkill(skillId));
|
|
1248
|
+
// Validate the server payload before any host adaptation so transport
|
|
1249
|
+
// corruption is caught against the server's own manifest_hash.
|
|
1250
|
+
const validated = validateSkillPayload(detail);
|
|
1251
|
+
const sourceManifest = (
|
|
1252
|
+
typeof detail.manifest_hash === 'string' ? detail.manifest_hash.trim().toLowerCase() : ''
|
|
1253
|
+
) || validated.manifest_hash;
|
|
1254
|
+
let payload = detail;
|
|
1255
|
+
if (typeof adapt === 'function') {
|
|
1256
|
+
const adapted = await adapt(detail);
|
|
1257
|
+
if (adapted && adapted !== detail) {
|
|
1258
|
+
// The written file set may differ from the server manifest; the server
|
|
1259
|
+
// value is recorded separately instead of failing payload validation.
|
|
1260
|
+
payload = { ...adapted, manifest_hash: undefined };
|
|
1261
|
+
}
|
|
1262
|
+
}
|
|
1263
|
+
materializeSkillWorkCopyAt({
|
|
1264
|
+
installPath,
|
|
1265
|
+
stagingBase,
|
|
1266
|
+
projectId: projectIdStr,
|
|
1267
|
+
detail: payload,
|
|
1268
|
+
sourceManifestHash: sourceManifest,
|
|
1269
|
+
});
|
|
1270
|
+
(existingStat ? result.updated : result.created).push(name);
|
|
1271
|
+
} catch (error) {
|
|
1272
|
+
result.errors.push({ name, message: error instanceof Error ? error.message : String(error) });
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
// Remove copies this project owns but whose skill_id is no longer listed
|
|
1277
|
+
// (archived/disabled/no longer visible). Unmarked directories (e.g. skills
|
|
1278
|
+
// bundled with the plugin itself) are never touched, and a skill whose detail
|
|
1279
|
+
// fetch failed keeps its existing copy.
|
|
1280
|
+
let entries = [];
|
|
1281
|
+
try {
|
|
1282
|
+
entries = fs.readdirSync(rootPath, { withFileTypes: true });
|
|
1283
|
+
} catch {
|
|
1284
|
+
entries = [];
|
|
1285
|
+
}
|
|
1286
|
+
for (const entry of entries) {
|
|
1287
|
+
if (!entry.isDirectory() || entry.isSymbolicLink()) continue;
|
|
1288
|
+
if (entry.name === SYNC_STAGING_DIR) continue;
|
|
1289
|
+
const dir = path.join(rootPath, entry.name);
|
|
1290
|
+
const marker = readWorkCopyMarker(dir);
|
|
1291
|
+
if (!marker || marker.project_id !== projectIdStr) continue;
|
|
1292
|
+
if (listedIds.has(String(marker.skill_id))) continue;
|
|
1293
|
+
try {
|
|
1294
|
+
removeManagedWorkCopy(dir, marker);
|
|
1295
|
+
result.removed.push(entry.name);
|
|
1296
|
+
} catch (error) {
|
|
1297
|
+
result.errors.push({
|
|
1298
|
+
name: entry.name,
|
|
1299
|
+
message: error instanceof Error ? error.message : String(error),
|
|
1300
|
+
});
|
|
1301
|
+
}
|
|
1302
|
+
}
|
|
1303
|
+
return result;
|
|
1304
|
+
} finally {
|
|
1305
|
+
if (pathExists(stagingBase)) rmrf(stagingBase);
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
|
|
1310
|
+
/**
|
|
1311
|
+
* List work copies from every project under LORE_HOME. This is intentionally
|
|
1312
|
+
* local-only and never calls Core, so status remains useful before a session
|
|
1313
|
+
* has established project identity.
|
|
1314
|
+
*/
|
|
1315
|
+
export function listAllLocalWorkCopyStatuses(loreHome) {
|
|
1316
|
+
const root = workCopiesRoot(loreHome);
|
|
1317
|
+
const out = [];
|
|
1318
|
+
for (const projectId of listDirectoryNames(root)) {
|
|
1319
|
+
if (projectId === '.staging') continue;
|
|
1320
|
+
for (const status of listLocalWorkCopyStatuses(loreHome, projectId)) {
|
|
1321
|
+
out.push({ project_id: projectId, ...status });
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
return out;
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1327
|
+
/** @deprecated Prefer listLocalWorkCopyStatuses. */
|
|
1328
|
+
export const listLocalMirrorStatuses = listLocalWorkCopyStatuses;
|