@myclaw163/clawclaw-cli 0.6.100 → 0.6.105

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.
@@ -1,75 +1,155 @@
1
- // src/lib/strategy-export.ts
2
- // Export official strategies to workspace for customization.
3
- import { existsSync, readFileSync, writeFileSync, mkdirSync, renameSync, mkdtempSync, rmSync } from 'fs';
4
- import { join, dirname } from 'path';
1
+ // Materialize bundled official strategies into the persistent user strategy
2
+ // directory. Official and custom strategies are loaded from the same path;
3
+ // the manifest records only files written by CCL so updates can preserve edits.
4
+ import {
5
+ existsSync,
6
+ mkdirSync,
7
+ mkdtempSync,
8
+ readdirSync,
9
+ readFileSync,
10
+ renameSync,
11
+ rmSync,
12
+ writeFileSync,
13
+ } from 'fs';
14
+ import { basename, dirname, join } from 'path';
5
15
  import { tmpdir } from 'os';
6
- import { fileURLToPath } from 'url';
7
16
  import { createHash } from 'crypto';
17
+ import { fileURLToPath } from 'url';
8
18
  import { getWorkspaceDir } from './init-command.js';
9
19
  import {
10
20
  ensureUserDataLayout,
11
- getRuntimeOfficialStrategiesDir,
12
- getRuntimeOfficialStrategiesManifestFile,
21
+ getUserDataOfficialStrategiesManifestFile,
13
22
  getUserDataStrategiesDir,
14
23
  } from './user-data.js';
15
24
  import { importUserFile } from '../strategies/loader.js';
16
25
 
17
- // ── Constants ──────────────────────────────────────────────────────
18
- // ── Types ──────────────────────────────────────────────────────────
19
26
  export interface ManifestEntry {
27
+ format?: 1;
28
+ version?: string;
20
29
  sourceHash: string;
21
- sidecarHash?: string;
30
+ installedHash?: string;
31
+ sidecarHash?: string | null;
32
+ installedSidecarHash?: string | null;
22
33
  }
23
34
 
24
35
  export type Manifest = Record<string, ManifestEntry>;
25
36
 
26
- // ── Helpers ────────────────────────────────────────────────────────
37
+ export interface OfficialStrategySyncResult {
38
+ added: string[];
39
+ updated: string[];
40
+ unchanged: string[];
41
+ preservedModified: string[];
42
+ preservedUntracked: string[];
43
+ preservedDeleted: string[];
44
+ }
45
+
46
+ interface BundledStrategySource {
47
+ id: string;
48
+ path: string;
49
+ source: string;
50
+ sourceHash: string;
51
+ sidecarPath: string;
52
+ sidecarContent?: string;
53
+ sidecarHash: string | null;
54
+ }
55
+
27
56
  function strategiesDir(): string {
28
57
  const workspaceDir = getWorkspaceDir();
29
58
  ensureUserDataLayout(workspaceDir);
30
59
  return getUserDataStrategiesDir(workspaceDir);
31
60
  }
32
61
 
33
- function officialDir(): string {
34
- return getRuntimeOfficialStrategiesDir(getWorkspaceDir());
62
+ function manifestPath(): string {
63
+ return getUserDataOfficialStrategiesManifestFile(getWorkspaceDir());
64
+ }
65
+
66
+ function builtinStrategiesDir(): string {
67
+ return join(dirname(fileURLToPath(import.meta.url)), '..', 'strategies');
35
68
  }
36
69
 
37
- function manifestPath(): string {
38
- return getRuntimeOfficialStrategiesManifestFile(getWorkspaceDir());
70
+ function hashContent(content: string | Buffer): string {
71
+ return createHash('sha256').update(content).digest('hex').slice(0, 16);
72
+ }
73
+
74
+ function writeAtomic(path: string, content: string): void {
75
+ const tmpPath = `${path}.tmp`;
76
+ writeFileSync(tmpPath, content, 'utf8');
77
+ try {
78
+ renameSync(tmpPath, path);
79
+ } catch (error) {
80
+ rmSync(tmpPath, { force: true });
81
+ throw error;
82
+ }
39
83
  }
40
84
 
41
85
  export function readManifest(): Manifest {
42
86
  const path = manifestPath();
43
87
  if (!existsSync(path)) return {};
44
88
  try {
45
- return JSON.parse(readFileSync(path, 'utf8')) as Manifest;
89
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
90
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed as Manifest : {};
46
91
  } catch {
47
92
  return {};
48
93
  }
49
94
  }
50
95
 
51
96
  function writeManifest(manifest: Manifest): void {
52
- mkdirSync(officialDir(), { recursive: true });
53
- writeFileSync(manifestPath(), JSON.stringify(manifest, null, 2) + '\n', 'utf8');
97
+ mkdirSync(strategiesDir(), { recursive: true });
98
+ writeAtomic(manifestPath(), `${JSON.stringify(manifest, null, 2)}\n`);
54
99
  }
55
100
 
56
- function locateBuiltinSource(id: string): string | null {
57
- const currentDir = dirname(fileURLToPath(import.meta.url));
58
- const strategiesDir = join(currentDir, '..', 'strategies');
59
- const filePath = join(strategiesDir, `${id}.ts`);
60
- return existsSync(filePath) ? filePath : null;
101
+ function readPackageVersion(): string {
102
+ try {
103
+ const pkgPath = join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'package.json');
104
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
105
+ return pkg.version ?? '0.0.0';
106
+ } catch {
107
+ return '0.0.0';
108
+ }
61
109
  }
62
110
 
63
- function hashContent(content: string): string {
64
- return createHash('sha256').update(content).digest('hex').slice(0, 16);
111
+ function parseStrategyId(source: string, fileName: string): string | null {
112
+ const marker = source.search(/export\s+const\s+strategy\b/);
113
+ if (marker < 0) return null;
114
+ const match = source.slice(marker).match(/\bid\s*:\s*['"]([^'"]+)['"]/);
115
+ if (!match) throw new Error(`Bundled strategy has no literal id: ${fileName}`);
116
+ return match[1];
117
+ }
118
+
119
+ function listBundledStrategySources(): BundledStrategySource[] {
120
+ const dir = builtinStrategiesDir();
121
+ const sources: BundledStrategySource[] = [];
122
+ for (const fileName of readdirSync(dir).sort()) {
123
+ if (!fileName.endsWith('.ts') || fileName.endsWith('.test.ts') || fileName.endsWith('.d.ts')) continue;
124
+ const path = join(dir, fileName);
125
+ const source = readFileSync(path, 'utf8');
126
+ const id = parseStrategyId(source, fileName);
127
+ if (!id) continue;
128
+ if (basename(fileName, '.ts') !== id) {
129
+ throw new Error(`Bundled strategy id '${id}' must match file name '${fileName}'.`);
130
+ }
131
+ const sidecarPath = path.replace(/\.ts$/, '.knowledge.md');
132
+ const sidecarContent = existsSync(sidecarPath) ? readFileSync(sidecarPath, 'utf8') : undefined;
133
+ sources.push({
134
+ id,
135
+ path,
136
+ source,
137
+ sourceHash: hashContent(source),
138
+ sidecarPath,
139
+ sidecarContent,
140
+ sidecarHash: sidecarContent === undefined ? null : hashContent(sidecarContent),
141
+ });
142
+ }
143
+ return sources;
144
+ }
145
+
146
+ function locateBundledStrategy(id: string): BundledStrategySource | undefined {
147
+ return listBundledStrategySources().find((source) => source.id === id);
65
148
  }
66
149
 
67
150
  export function rewriteBuiltinImports(source: string, id: string, version: string): string {
68
- // Rewrite ALL relative imports (./... and ../...) to '@myclaw163/clawclaw-cli'.
69
- // The SDK must export every symbol used; validateExportable catches gaps.
70
151
  const rewritten = source.replace(/from\s+['"]\.\.?\/[^'"]+['"]/g, `from '@myclaw163/clawclaw-cli'`);
71
- const provenance = `// Exported from ${id}@${version} — customize freely\n`;
72
- return provenance + rewritten;
152
+ return `// Exported from ${id}@${version} — customize freely\n${rewritten}`;
73
153
  }
74
154
 
75
155
  async function validateExportable(rewritten: string): Promise<{ ok: boolean; error?: string }> {
@@ -80,39 +160,26 @@ async function validateExportable(rewritten: string): Promise<{ ok: boolean; err
80
160
  writeFileSync(tmpFile, rewritten, 'utf8');
81
161
  const mod = await importUserFile(tmpFile);
82
162
  const entry = mod.strategy as any;
83
- if (!entry || typeof entry !== 'object') {
84
- return { ok: false, error: 'Missing or invalid strategy export' };
85
- }
86
- if (typeof entry.id !== 'string') {
87
- return { ok: false, error: 'strategy.id must be a string' };
88
- }
89
- if (typeof entry.description !== 'string') {
90
- return { ok: false, error: 'strategy.description must be a string' };
91
- }
92
- if (typeof entry.create !== 'function') {
93
- return { ok: false, error: 'strategy.create must be a function' };
94
- }
95
- // Try calling create() to catch runtime errors.
96
- // Some strategies require args (move-room, social-task, etc.) — those throw
97
- // "requires X" errors, which are expected and not validation failures.
163
+ if (!entry || typeof entry !== 'object') return { ok: false, error: 'Missing or invalid strategy export' };
164
+ if (typeof entry.id !== 'string') return { ok: false, error: 'strategy.id must be a string' };
165
+ if (typeof entry.description !== 'string') return { ok: false, error: 'strategy.description must be a string' };
166
+ if (typeof entry.create !== 'function') return { ok: false, error: 'strategy.create must be a function' };
98
167
  try {
99
168
  entry.create();
100
- } catch (err: any) {
101
- const msg = err?.message ?? String(err);
102
- if (msg.includes('requires') || msg.includes('argument') || msg.includes('param')) {
103
- // Expected: strategy needs args, but the import resolution worked.
104
- } else {
105
- return { ok: false, error: `create() failed: ${msg}` };
169
+ } catch (error: any) {
170
+ const message = error?.message ?? String(error);
171
+ if (!message.includes('requires') && !message.includes('argument') && !message.includes('param')) {
172
+ return { ok: false, error: `create() failed: ${message}` };
106
173
  }
107
174
  }
108
- // Static check: parse imports from 'clawclaw-cli' and verify each symbol
109
- // is actually exported by the SDK. esbuild/tsx don't validate named exports
110
- // at link time (missing symbols resolve to undefined, not errors).
111
175
  const sdkExports = await getSdkExports();
112
176
  const importPattern = /import\s+(?:type\s+)?\{([^}]+)\}\s+from\s+['"](?:@myclaw163\/)?clawclaw-cli['"]/g;
113
177
  let match;
114
178
  while ((match = importPattern.exec(rewritten)) !== null) {
115
- const names = match[1].split(',').map(s => s.trim().replace(/^type\s+/, '').replace(/\s+as\s+.*$/, '').trim()).filter(Boolean);
179
+ const names = match[1]
180
+ .split(',')
181
+ .map((name) => name.trim().replace(/^type\s+/, '').replace(/\s+as\s+.*$/, '').trim())
182
+ .filter(Boolean);
116
183
  for (const name of names) {
117
184
  if (!sdkExports.has(name)) {
118
185
  return { ok: false, error: `'${name}' is not exported by @myclaw163/clawclaw-cli SDK` };
@@ -123,12 +190,11 @@ async function validateExportable(rewritten: string): Promise<{ ok: boolean; err
123
190
  } finally {
124
191
  rmSync(tmpDir, { recursive: true, force: true });
125
192
  }
126
- } catch (err: any) {
127
- return { ok: false, error: err?.message ?? String(err) };
193
+ } catch (error: any) {
194
+ return { ok: false, error: error?.message ?? String(error) };
128
195
  }
129
196
  }
130
197
 
131
- // Cache SDK exports to avoid re-parsing on every validation.
132
198
  let sdkExportsCache: Set<string> | null = null;
133
199
 
134
200
  async function getSdkExports(): Promise<Set<string>> {
@@ -136,112 +202,170 @@ async function getSdkExports(): Promise<Set<string>> {
136
202
  const sdkPath = join(dirname(fileURLToPath(import.meta.url)), '..', 'sdk', 'index.ts');
137
203
  const source = readFileSync(sdkPath, 'utf8');
138
204
  const exports = new Set<string>();
139
- // Match: export { X, Y, Z } from '...'
140
205
  const exportPattern = /export\s+(?:type\s+)?\{([^}]+)\}/g;
141
206
  let match;
142
207
  while ((match = exportPattern.exec(source)) !== null) {
143
- const names = match[1].split(',').map(s => s.trim().replace(/^type\s+/, '').replace(/\s+as\s+.*$/, '').trim()).filter(Boolean);
144
- for (const name of names) {
145
- exports.add(name);
146
- }
208
+ const names = match[1]
209
+ .split(',')
210
+ .map((name) => name.trim().replace(/^type\s+/, '').replace(/\s+as\s+.*$/, '').trim())
211
+ .filter(Boolean);
212
+ for (const name of names) exports.add(name);
147
213
  }
148
214
  sdkExportsCache = exports;
149
215
  return exports;
150
216
  }
151
217
 
152
- function writeAtomic(path: string, content: string): void {
153
- const tmpPath = path + '.tmp';
154
- writeFileSync(tmpPath, content, 'utf8');
155
- renameSync(tmpPath, path);
218
+ function pairIsUnmodified(id: string, entry: ManifestEntry): boolean {
219
+ if (entry.format !== 1 || !entry.installedHash || entry.installedSidecarHash === undefined) return false;
220
+ const strategyFile = join(strategiesDir(), `${id}.ts`);
221
+ if (!existsSync(strategyFile)) return false;
222
+ if (hashContent(readFileSync(strategyFile)) !== entry.installedHash) return false;
223
+
224
+ const sidecarFile = join(strategiesDir(), `${id}.knowledge.md`);
225
+ if (entry.installedSidecarHash === null) return !existsSync(sidecarFile);
226
+ return existsSync(sidecarFile)
227
+ && hashContent(readFileSync(sidecarFile)) === entry.installedSidecarHash;
156
228
  }
157
229
 
158
- function readPackageVersion(): string {
159
- try {
160
- const currentDir = dirname(fileURLToPath(import.meta.url));
161
- const pkgDir = join(currentDir, '..', '..');
162
- const pkgPath = join(pkgDir, 'package.json');
163
- const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
164
- return pkg.version ?? '0.0.0';
165
- } catch {
166
- return '0.0.0';
167
- }
230
+ function sourceMatchesManifest(source: BundledStrategySource, entry: ManifestEntry): boolean {
231
+ return entry.sourceHash === source.sourceHash
232
+ && (entry.sidecarHash ?? null) === source.sidecarHash;
168
233
  }
169
234
 
170
- // ── Main API ───────────────────────────────────────────────────────
171
- export async function exportStrategy(id: string, { force = false } = {}): Promise<void> {
172
- const sourcePath = locateBuiltinSource(id);
173
- if (!sourcePath) {
174
- throw new Error(`Built-in strategy '${id}' not found.`);
235
+ async function writeOfficialStrategy(source: BundledStrategySource, version: string): Promise<ManifestEntry> {
236
+ const rewritten = rewriteBuiltinImports(source.source, source.id, version);
237
+ const validation = await validateExportable(rewritten);
238
+ if (!validation.ok) throw new Error(`Validation failed for '${source.id}': ${validation.error}`);
239
+
240
+ mkdirSync(strategiesDir(), { recursive: true });
241
+ writeAtomic(join(strategiesDir(), `${source.id}.ts`), rewritten);
242
+ const sidecarFile = join(strategiesDir(), `${source.id}.knowledge.md`);
243
+ if (source.sidecarContent === undefined) {
244
+ rmSync(sidecarFile, { force: true });
245
+ } else {
246
+ writeAtomic(sidecarFile, source.sidecarContent);
175
247
  }
176
248
 
177
- const strategyFile = join(strategiesDir(), `${id}.ts`);
178
- const manifest = readManifest();
249
+ return {
250
+ format: 1,
251
+ version,
252
+ sourceHash: source.sourceHash,
253
+ installedHash: hashContent(rewritten),
254
+ sidecarHash: source.sidecarHash,
255
+ installedSidecarHash: source.sidecarHash,
256
+ };
257
+ }
179
258
 
180
- if (existsSync(strategyFile) && !manifest[id] && !force) {
181
- throw new Error(`${strategyFile} already exists and is not tracked. Use --force to overwrite.`);
259
+ export async function syncOfficialStrategies(options: { ids?: string[]; force?: boolean } = {}): Promise<OfficialStrategySyncResult> {
260
+ const selectedIds = options.ids ? new Set(options.ids) : null;
261
+ const allSources = listBundledStrategySources();
262
+ const sources = selectedIds ? allSources.filter((source) => selectedIds.has(source.id)) : allSources;
263
+ if (selectedIds) {
264
+ const found = new Set(sources.map((source) => source.id));
265
+ const missing = [...selectedIds].filter((id) => !found.has(id));
266
+ if (missing.length > 0) throw new Error(`Built-in strategy '${missing[0]}' not found.`);
182
267
  }
183
268
 
184
- const source = readFileSync(sourcePath, 'utf8');
269
+ const result: OfficialStrategySyncResult = {
270
+ added: [],
271
+ updated: [],
272
+ unchanged: [],
273
+ preservedModified: [],
274
+ preservedUntracked: [],
275
+ preservedDeleted: [],
276
+ };
277
+ const manifest = readManifest();
185
278
  const version = readPackageVersion();
186
- const rewritten = rewriteBuiltinImports(source, id, version);
187
279
 
188
- const validation = await validateExportable(rewritten);
189
- if (!validation.ok) {
190
- throw new Error(`Validation failed: ${validation.error}`);
191
- }
280
+ for (const source of sources) {
281
+ const strategyFile = join(strategiesDir(), `${source.id}.ts`);
282
+ const exists = existsSync(strategyFile);
283
+ const entry = manifest[source.id];
192
284
 
193
- // Compute content hashes for staleness detection.
194
- const sourceHash = hashContent(source);
195
- const sidecarSource = sourcePath.replace(/\.ts$/, '.knowledge.md');
196
- const sidecarHash = existsSync(sidecarSource) ? hashContent(readFileSync(sidecarSource, 'utf8')) : undefined;
285
+ if (options.force) {
286
+ manifest[source.id] = await writeOfficialStrategy(source, version);
287
+ writeManifest(manifest);
288
+ (exists ? result.updated : result.added).push(source.id);
289
+ continue;
290
+ }
197
291
 
198
- // Write metadata first, then strategy file last.
199
- mkdirSync(officialDir(), { recursive: true });
292
+ if (!entry) {
293
+ if (exists) {
294
+ result.preservedUntracked.push(source.id);
295
+ continue;
296
+ }
297
+ manifest[source.id] = await writeOfficialStrategy(source, version);
298
+ writeManifest(manifest);
299
+ result.added.push(source.id);
300
+ continue;
301
+ }
302
+
303
+ if (!exists) {
304
+ result.preservedDeleted.push(source.id);
305
+ continue;
306
+ }
307
+ if (!pairIsUnmodified(source.id, entry)) {
308
+ result.preservedModified.push(source.id);
309
+ continue;
310
+ }
311
+ if (sourceMatchesManifest(source, entry)) {
312
+ result.unchanged.push(source.id);
313
+ continue;
314
+ }
200
315
 
201
- const entry: ManifestEntry = { sourceHash };
202
- if (sidecarHash !== undefined) entry.sidecarHash = sidecarHash;
203
- manifest[id] = entry;
204
- writeManifest(manifest);
316
+ manifest[source.id] = await writeOfficialStrategy(source, version);
317
+ writeManifest(manifest);
318
+ result.updated.push(source.id);
319
+ }
205
320
 
206
- mkdirSync(strategiesDir(), { recursive: true });
207
- writeAtomic(strategyFile, rewritten);
321
+ return result;
322
+ }
208
323
 
209
- // Copy the knowledge sidecar (<id>.knowledge.md) so the exported strategy
210
- // keeps its contract — otherwise `ccl strategy --info` returns null for it.
211
- if (sidecarHash !== undefined) {
212
- writeAtomic(join(strategiesDir(), `${id}.knowledge.md`), readFileSync(sidecarSource, 'utf8'));
324
+ export async function exportStrategy(id: string, { force = false } = {}): Promise<void> {
325
+ const source = locateBundledStrategy(id);
326
+ if (!source) throw new Error(`Built-in strategy '${id}' not found.`);
327
+ const result = await syncOfficialStrategies({ ids: [id], force });
328
+ if (result.preservedUntracked.includes(id)) {
329
+ throw new Error(`${join(strategiesDir(), `${id}.ts`)} already exists and is not tracked. Use --force to overwrite.`);
330
+ }
331
+ if (result.preservedModified.includes(id)) {
332
+ throw new Error(`${join(strategiesDir(), `${id}.ts`)} was modified. Use --force to overwrite.`);
333
+ }
334
+ if (result.preservedDeleted.includes(id)) {
335
+ throw new Error(`${join(strategiesDir(), `${id}.ts`)} was deleted after export. Use --force to restore.`);
213
336
  }
214
337
  }
215
338
 
216
339
  export function detectStaleOfficialStrategies(): string[] {
217
340
  const manifest = readManifest();
218
- const staleIds: string[] = [];
219
-
341
+ const sources = new Map(listBundledStrategySources().map((source) => [source.id, source]));
342
+ const stale: string[] = [];
220
343
  for (const [id, entry] of Object.entries(manifest)) {
221
- const sourcePath = locateBuiltinSource(id);
222
- if (!sourcePath) {
223
- // Built-in strategy was removed — mark as stale so user can clean up.
224
- staleIds.push(id);
225
- continue;
226
- }
344
+ const source = sources.get(id);
345
+ if (!source || !sourceMatchesManifest(source, entry)) stale.push(id);
346
+ }
347
+ return stale;
348
+ }
227
349
 
228
- const currentSourceHash = hashContent(readFileSync(sourcePath, 'utf8'));
229
- if (currentSourceHash !== entry.sourceHash) {
230
- staleIds.push(id);
231
- continue;
232
- }
350
+ export function hasUserStrategyCustomization(): boolean {
351
+ const dir = strategiesDir();
352
+ const manifest = readManifest();
353
+ let files: string[];
354
+ try {
355
+ files = readdirSync(dir);
356
+ } catch {
357
+ return false;
358
+ }
233
359
 
234
- const sidecarSource = sourcePath.replace(/\.ts$/, '.knowledge.md');
235
- if (existsSync(sidecarSource)) {
236
- const currentSidecarHash = hashContent(readFileSync(sidecarSource, 'utf8'));
237
- if (currentSidecarHash !== entry.sidecarHash) {
238
- staleIds.push(id);
239
- }
240
- } else if (entry.sidecarHash !== undefined) {
241
- // Sidecar was removed in the new version.
242
- staleIds.push(id);
243
- }
360
+ for (const file of files) {
361
+ if (file.startsWith('_')) continue;
362
+ if (!/\.(?:ts|tsx|js)$/.test(file) || file.endsWith('.d.ts') || file.endsWith('.test.ts')) continue;
363
+ const id = file.endsWith('.ts') ? basename(file, '.ts') : '';
364
+ if (!id || !manifest[id] || file !== `${id}.ts`) return true;
244
365
  }
245
366
 
246
- return staleIds;
367
+ for (const [id, entry] of Object.entries(manifest)) {
368
+ if (!pairIsUnmodified(id, entry)) return true;
369
+ }
370
+ return false;
247
371
  }
@@ -94,4 +94,5 @@ describe('user-data layout migration', () => {
94
94
 
95
95
  expect(readFileSync(getUserDataPersonaFile(ws, { apiKey }), 'utf8')).toBe('new persona');
96
96
  });
97
+
97
98
  });
@@ -76,6 +76,10 @@ export function getUserDataStrategiesDir(workspaceDir: string): string {
76
76
  return join(getUserDataDir(workspaceDir), 'strategies');
77
77
  }
78
78
 
79
+ export function getUserDataOfficialStrategiesManifestFile(workspaceDir: string): string {
80
+ return join(getUserDataStrategiesDir(workspaceDir), '.official-manifest.json');
81
+ }
82
+
79
83
  export function getUserDataHubDir(workspaceDir: string): string {
80
84
  return join(getUserDataDir(workspaceDir), 'hub');
81
85
  }
@@ -84,14 +88,6 @@ export function getUserDataHubStrategyLockfile(workspaceDir: string): string {
84
88
  return join(getUserDataHubDir(workspaceDir), 'installed-strategies.json');
85
89
  }
86
90
 
87
- export function getRuntimeOfficialStrategiesDir(workspaceDir: string): string {
88
- return join(getRuntimeDir(workspaceDir), 'official-strategies');
89
- }
90
-
91
- export function getRuntimeOfficialStrategiesManifestFile(workspaceDir: string): string {
92
- return join(getRuntimeOfficialStrategiesDir(workspaceDir), 'manifest.json');
93
- }
94
-
95
91
  function ensureDir(path: string): void {
96
92
  mkdirSync(path, { recursive: true });
97
93
  }
@@ -17,8 +17,7 @@ const SDK_PATH = realpathSync(resolve(__dirname, '../sdk/index.ts'));
17
17
  const strategyMap = new Map<string, StrategyEntry>();
18
18
  const knowledgeDocMap = new Map<string, string>();
19
19
  let loaded = false;
20
-
21
- const INFRA_FILES = new Set(['loader', 'types', 'game-utils', 'player-targets', 'greeting', 'spawn', 'strategy-loop', 'new-events-backfill']);
20
+ let loadedWorkspaceDir: string | undefined;
22
21
 
23
22
  function resolveUserStrategiesDir(): string | undefined {
24
23
  const workspaceDir = getWorkspaceDir();
@@ -92,7 +91,7 @@ export async function importUserFile(filePath: string): Promise<Record<string, u
92
91
  }
93
92
  }
94
93
 
95
- async function loadFromDir(dir: string, skipInfra: boolean): Promise<void> {
94
+ async function loadFromDir(dir: string, officialIds: Set<string> = new Set()): Promise<void> {
96
95
  let files: string[];
97
96
  try {
98
97
  files = readdirSync(dir).filter(f => {
@@ -101,7 +100,14 @@ async function loadFromDir(dir: string, skipInfra: boolean): Promise<void> {
101
100
  if (!match) return false;
102
101
  if (match[1].endsWith('.d')) return false;
103
102
  if (match[1].endsWith('.test')) return false;
104
- return !skipInfra || !INFRA_FILES.has(match[1]);
103
+ return true;
104
+ }).sort((a, b) => {
105
+ const aId = a.replace(/\.(?:ts|js)$/, '');
106
+ const bId = b.replace(/\.(?:ts|js)$/, '');
107
+ const aOfficial = a === `${aId}.ts` && officialIds.has(aId);
108
+ const bOfficial = b === `${bId}.ts` && officialIds.has(bId);
109
+ if (aOfficial !== bOfficial) return aOfficial ? -1 : 1;
110
+ return a.localeCompare(b);
105
111
  });
106
112
  } catch {
107
113
  return;
@@ -109,33 +115,42 @@ async function loadFromDir(dir: string, skipInfra: boolean): Promise<void> {
109
115
  for (const file of files) {
110
116
  try {
111
117
  const filePath = realpathSync(join(dir, file));
112
- const mod = skipInfra
113
- ? await import(pathToFileURL(filePath).href)
114
- : await importUserFile(filePath);
118
+ const mod = await importUserFile(filePath);
115
119
  const entry: StrategyEntry | undefined = mod.strategy as StrategyEntry | undefined;
116
120
  if (entry?.id && typeof entry.description === 'string' && typeof entry.create === 'function') {
117
121
  strategyMap.set(entry.id, entry);
118
122
  const sidecar = filePath.replace(/\.(ts|js)$/, '.knowledge.md');
119
123
  if (existsSync(sidecar)) knowledgeDocMap.set(entry.id, sidecar);
124
+ else knowledgeDocMap.delete(entry.id);
120
125
  }
121
126
  } catch (err) {
122
- if (!skipInfra) {
123
- // Strip temp-dir paths from error messages — they leak internal
124
- // implementation details (e.g., /tmp/ccl-strategy-XXXX/strategy.mjs)
125
- const raw = err instanceof Error ? err.message : String(err);
126
- const cleaned = raw.replace(/\S*ccl-strategy-[^/]*\//g, '');
127
- console.error(`[ccl] Failed to load user strategy ${file}: ${cleaned}`);
128
- }
127
+ // Strip temp-dir paths from error messages — they leak internal
128
+ // implementation details (e.g., /tmp/ccl-strategy-XXXX/strategy.mjs)
129
+ const raw = err instanceof Error ? err.message : String(err);
130
+ const cleaned = raw.replace(/\S*ccl-strategy-[^/]*\//g, '');
131
+ console.error(`[ccl] Failed to load user strategy ${file}: ${cleaned}`);
129
132
  }
130
133
  }
131
134
  }
132
135
 
133
136
  async function ensureLoaded(): Promise<void> {
134
- if (loaded) return;
137
+ const workspaceDir = getWorkspaceDir();
138
+ if (loaded && loadedWorkspaceDir === workspaceDir) return;
139
+ strategyMap.clear();
140
+ knowledgeDocMap.clear();
135
141
  loaded = true;
136
- await loadFromDir(__dirname, true);
142
+ loadedWorkspaceDir = workspaceDir;
143
+ let officialIds = new Set<string>();
144
+ try {
145
+ const { readManifest, syncOfficialStrategies } = await import('../lib/strategy-export.js');
146
+ await syncOfficialStrategies();
147
+ officialIds = new Set(Object.keys(readManifest()));
148
+ } catch (error) {
149
+ const message = error instanceof Error ? error.message : String(error);
150
+ console.error(`[ccl] Failed to initialize official strategies: ${message}`);
151
+ }
137
152
  const userDir = resolveUserStrategiesDir();
138
- if (userDir) await loadFromDir(userDir, false);
153
+ if (userDir) await loadFromDir(userDir, officialIds);
139
154
  }
140
155
 
141
156
  export async function getStrategyEntry(idOrName: string): Promise<StrategyEntry | undefined> {
@@ -175,6 +190,7 @@ export async function resolveStrategy(id: string, args?: string[]): Promise<Stra
175
190
  /** Reset and re-scan — call after a new strategy file is placed, so the next list/get picks it up. */
176
191
  export async function reload(): Promise<void> {
177
192
  loaded = false;
193
+ loadedWorkspaceDir = undefined;
178
194
  strategyMap.clear();
179
195
  knowledgeDocMap.clear();
180
196
  await ensureLoaded();