@myclaw163/clawclaw-cli 0.6.111 → 0.6.112
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/package.json +2 -2
- package/src/commands/hub.test.ts +23 -2
- package/src/commands/hub.ts +9 -4
- package/src/commands/load.test.ts +23 -1
- package/src/commands/strategy.test.ts +19 -0
- package/src/commands/strategy.ts +6 -28
- package/src/lib/strategy-export.ts +17 -36
- package/src/strategies/loader.test.ts +68 -36
- package/src/strategies/loader.ts +68 -97
- package/src/strategies/scanner.ts +238 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@myclaw163/clawclaw-cli",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.112",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "ClawClaw social deduction game CLI",
|
|
6
6
|
"bin": {
|
|
@@ -36,13 +36,13 @@
|
|
|
36
36
|
"esbuild": "~0.28.0",
|
|
37
37
|
"skills": "1.5.1",
|
|
38
38
|
"tsx": "^4.0.0",
|
|
39
|
+
"typescript": "^5.4.0",
|
|
39
40
|
"undici": "^6.21.3",
|
|
40
41
|
"ws": "^8.16.0"
|
|
41
42
|
},
|
|
42
43
|
"devDependencies": {
|
|
43
44
|
"@types/node": "^20.0.0",
|
|
44
45
|
"@types/ws": "^8.5.10",
|
|
45
|
-
"typescript": "^5.4.0",
|
|
46
46
|
"vitest": "^3.1.0"
|
|
47
47
|
}
|
|
48
48
|
}
|
package/src/commands/hub.test.ts
CHANGED
|
@@ -1,11 +1,18 @@
|
|
|
1
1
|
// src/commands/hub.test.ts
|
|
2
2
|
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
|
3
|
-
import { mkdtempSync, rmSync } from 'fs';
|
|
3
|
+
import { existsSync, mkdtempSync, rmSync } from 'fs';
|
|
4
4
|
import { tmpdir } from 'os';
|
|
5
5
|
import { join } from 'path';
|
|
6
6
|
import { createHubCommand } from './hub.js';
|
|
7
7
|
import type { ResourceListResult, ResourceDetail } from '../lib/hub-client.js';
|
|
8
8
|
|
|
9
|
+
const STRATEGY_ARTIFACT = `export const strategy = {
|
|
10
|
+
id: 'hub-kill',
|
|
11
|
+
name: '抢刀',
|
|
12
|
+
description: '贴脸抢刀',
|
|
13
|
+
create: () => ({ name: 'hub-kill', decide: () => [] }),
|
|
14
|
+
};`;
|
|
15
|
+
|
|
9
16
|
let ws: string;
|
|
10
17
|
let logs: string[];
|
|
11
18
|
let errs: string[];
|
|
@@ -40,7 +47,7 @@ function fakeClient(over: any = {}) {
|
|
|
40
47
|
downloadUrl: '/dl', likedByMe: false, createdAt: '', updatedAt: '',
|
|
41
48
|
artifact: { fileName: 'kill.ts', downloadUrl: '/dl' },
|
|
42
49
|
})),
|
|
43
|
-
downloadArtifact: vi.fn(async () => Buffer.from(
|
|
50
|
+
downloadArtifact: vi.fn(async () => Buffer.from(STRATEGY_ARTIFACT)),
|
|
44
51
|
...over,
|
|
45
52
|
};
|
|
46
53
|
}
|
|
@@ -80,6 +87,20 @@ describe('hub install', () => {
|
|
|
80
87
|
expect(out.ref).toBe('strategy/ab12');
|
|
81
88
|
expect(out.installedPath).toMatch(/strategies[\\/]aggressive-kill__ab12\.ts/);
|
|
82
89
|
});
|
|
90
|
+
it('does not execute downloaded top-level code while installing and reloading', async () => {
|
|
91
|
+
const marker = join(ws, 'hub-install-marker.txt');
|
|
92
|
+
const artifact = `
|
|
93
|
+
import { writeFileSync } from 'fs';
|
|
94
|
+
writeFileSync(${JSON.stringify(marker)}, 'executed', 'utf8');
|
|
95
|
+
export const strategy = {
|
|
96
|
+
id: 'hub-marker',
|
|
97
|
+
name: 'Hub Marker',
|
|
98
|
+
description: 'static metadata',
|
|
99
|
+
create: () => ({ name: 'hub-marker', decide: () => [] }),
|
|
100
|
+
};`;
|
|
101
|
+
await run(fakeClient({ downloadArtifact: vi.fn(async () => Buffer.from(artifact)) }), ['install', 'strategy/ab12']);
|
|
102
|
+
expect(existsSync(marker)).toBe(false);
|
|
103
|
+
});
|
|
83
104
|
});
|
|
84
105
|
|
|
85
106
|
describe('hub installed / uninstall', () => {
|
package/src/commands/hub.ts
CHANGED
|
@@ -9,6 +9,7 @@ import { HubClient, parseResourceRef } from '../lib/hub-client.js';
|
|
|
9
9
|
import type { ListOptions } from '../lib/hub-client.js';
|
|
10
10
|
import { installResource, uninstallResource, listInstalled, readLockfile } from '../lib/hub-install.js';
|
|
11
11
|
import { getWorkspaceDir } from '../lib/init-command.js';
|
|
12
|
+
import { inspectStrategySource } from '../strategies/scanner.js';
|
|
12
13
|
|
|
13
14
|
const require = createRequire(import.meta.url);
|
|
14
15
|
|
|
@@ -144,15 +145,19 @@ export function createHubCommand(deps: HubCommandDeps = {}): Command {
|
|
|
144
145
|
const client = getClient(deps);
|
|
145
146
|
const detail = await client.getResource(type, id);
|
|
146
147
|
const artifact = await client.downloadArtifact(type, id);
|
|
148
|
+
const strategySummary = type === 'strategy'
|
|
149
|
+
? inspectStrategySource(artifact.toString('utf8'), detail.fileName || detail.artifact?.fileName || `${id}.ts`)
|
|
150
|
+
: undefined;
|
|
151
|
+
if (type === 'strategy' && !strategySummary) {
|
|
152
|
+
throw new Error('Downloaded strategy must export static id, name/description, and create metadata.');
|
|
153
|
+
}
|
|
147
154
|
const res = installResource(detail, artifact, { force: opts.force });
|
|
148
|
-
// Reload strategy
|
|
149
|
-
// then extract the exported id from source to tell the user what to run.
|
|
155
|
+
// Reload the static strategy catalog so the new file is picked up immediately.
|
|
150
156
|
let strategyId: string | undefined;
|
|
151
157
|
if (res.type === 'strategy') {
|
|
152
158
|
const { reload } = await import('../strategies/loader.js');
|
|
153
159
|
await reload();
|
|
154
|
-
|
|
155
|
-
strategyId = m ? m[1] : undefined;
|
|
160
|
+
strategyId = strategySummary?.id;
|
|
156
161
|
}
|
|
157
162
|
|
|
158
163
|
// For skills: auto-register with the agent via `ccl skill install`.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
-
import { existsSync, mkdtempSync, rmSync } from 'fs';
|
|
2
|
+
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs';
|
|
3
3
|
import { tmpdir } from 'os';
|
|
4
4
|
import { join } from 'path';
|
|
5
5
|
|
|
@@ -73,6 +73,28 @@ describe('load command', () => {
|
|
|
73
73
|
expect(errorSpy).toHaveBeenCalledWith('[clawclaw-cli] auto-upgrade installed 0.6.39');
|
|
74
74
|
});
|
|
75
75
|
|
|
76
|
+
it('does not execute workspace strategy top-level code while loading summaries', async () => {
|
|
77
|
+
const strategiesDir = join(workspaceDir, 'user-data', 'strategies');
|
|
78
|
+
const marker = join(workspaceDir, 'load-marker.txt');
|
|
79
|
+
mkdirSync(strategiesDir, { recursive: true });
|
|
80
|
+
writeFileSync(join(strategiesDir, 'load-marker.ts'), `
|
|
81
|
+
import { writeFileSync } from 'fs';
|
|
82
|
+
writeFileSync(${JSON.stringify(marker)}, 'executed', 'utf8');
|
|
83
|
+
export const strategy = {
|
|
84
|
+
id: 'load-marker',
|
|
85
|
+
name: 'Load Marker',
|
|
86
|
+
description: 'static metadata',
|
|
87
|
+
create: () => ({ name: 'load-marker', decide: () => [] }),
|
|
88
|
+
};`, 'utf8');
|
|
89
|
+
|
|
90
|
+
const cmd = createLoadCommand();
|
|
91
|
+
await cmd.parseAsync(['node', 'load'], { from: 'node' });
|
|
92
|
+
|
|
93
|
+
const output = JSON.parse(String(logSpy.mock.calls[0][0]));
|
|
94
|
+
expect(output.strategies).toEqual(expect.arrayContaining([expect.objectContaining({ id: 'load-marker' })]));
|
|
95
|
+
expect(existsSync(marker)).toBe(false);
|
|
96
|
+
});
|
|
97
|
+
|
|
76
98
|
it('turns missing-account load errors into registration guidance', async () => {
|
|
77
99
|
vi.mocked(loadContext).mockImplementation(() => {
|
|
78
100
|
throw new Error('Not logged in.');
|
|
@@ -132,6 +132,25 @@ describe('strategy command', () => {
|
|
|
132
132
|
expect(errs[0]).toContain('unknown_strategy');
|
|
133
133
|
expect(errs[0]).toContain('non-existent');
|
|
134
134
|
});
|
|
135
|
+
|
|
136
|
+
it('does not execute top-level code while reading strategy info', async () => {
|
|
137
|
+
const marker = join(ws, 'strategy-info-marker.txt');
|
|
138
|
+
mkdirSync(userStrategiesDir(), { recursive: true });
|
|
139
|
+
writeFileSync(join(userStrategiesDir(), 'info-marker.ts'), `
|
|
140
|
+
import { writeFileSync } from 'fs';
|
|
141
|
+
writeFileSync(${JSON.stringify(marker)}, 'executed', 'utf8');
|
|
142
|
+
export const strategy = {
|
|
143
|
+
id: 'info-marker',
|
|
144
|
+
name: 'Info Marker',
|
|
145
|
+
description: 'static metadata',
|
|
146
|
+
create: () => ({ name: 'info-marker', decide: () => [] }),
|
|
147
|
+
};`, 'utf8');
|
|
148
|
+
const { reload } = await import('../strategies/loader.js');
|
|
149
|
+
await reload();
|
|
150
|
+
await run(['--info', 'info-marker']);
|
|
151
|
+
expect(JSON.parse(logs[0]).id).toBe('info-marker');
|
|
152
|
+
expect(existsSync(marker)).toBe(false);
|
|
153
|
+
});
|
|
135
154
|
});
|
|
136
155
|
|
|
137
156
|
describe('--list', () => {
|
package/src/commands/strategy.ts
CHANGED
|
@@ -4,8 +4,6 @@ import { getProfileStateDir, getWorkspaceDir } from '../lib/init-command.js';
|
|
|
4
4
|
import { AuthStore } from '../lib/auth.js';
|
|
5
5
|
import { sendOwnerControlRequest } from '../runtime/owner-control.js';
|
|
6
6
|
import { ensureUserDataLayout, getUserDataStrategiesDir } from '../lib/user-data.js';
|
|
7
|
-
import { KnowledgeStore, buildKnowledgeView } from '../lib/knowledge-store.js';
|
|
8
|
-
import type { KnowledgeReview } from '../strategies/types.js';
|
|
9
7
|
|
|
10
8
|
const KILL_STRATEGIES = new Set([
|
|
11
9
|
'kill-frenzy', 'kill-lone', 'kill-target', 'warrior-memory',
|
|
@@ -42,10 +40,10 @@ Official and custom strategies:
|
|
|
42
40
|
})
|
|
43
41
|
.action(async (name: string | undefined, args: string[], opts: { list?: boolean; stop?: boolean; info?: string; export?: string; force?: boolean }) => {
|
|
44
42
|
if (opts.info) {
|
|
45
|
-
const {
|
|
46
|
-
const entry = await
|
|
43
|
+
const { getStrategySummary, getStrategyKnowledgeDoc, listStrategySummaries } = await import('../strategies/loader.js');
|
|
44
|
+
const entry = await getStrategySummary(opts.info);
|
|
47
45
|
if (!entry) {
|
|
48
|
-
const available = await
|
|
46
|
+
const available = await listStrategySummaries();
|
|
49
47
|
console.error(JSON.stringify({
|
|
50
48
|
error: 'unknown_strategy',
|
|
51
49
|
message: `Unknown strategy '${opts.info}'.`,
|
|
@@ -115,10 +113,10 @@ Official and custom strategies:
|
|
|
115
113
|
return;
|
|
116
114
|
}
|
|
117
115
|
|
|
118
|
-
const {
|
|
119
|
-
const entry = await
|
|
116
|
+
const { listStrategySummaries, getStrategySummary } = await import('../strategies/loader.js');
|
|
117
|
+
const entry = await getStrategySummary(name);
|
|
120
118
|
if (!entry) {
|
|
121
|
-
const available = await
|
|
119
|
+
const available = await listStrategySummaries();
|
|
122
120
|
console.error(JSON.stringify({
|
|
123
121
|
error: 'unknown_strategy',
|
|
124
122
|
message: `Unknown strategy '${name}'.`,
|
|
@@ -127,17 +125,6 @@ Official and custom strategies:
|
|
|
127
125
|
process.exit(1);
|
|
128
126
|
}
|
|
129
127
|
|
|
130
|
-
try {
|
|
131
|
-
entry.create(args.length > 0 ? args : undefined);
|
|
132
|
-
} catch (err: any) {
|
|
133
|
-
console.error(JSON.stringify({
|
|
134
|
-
error: 'strategy_create_failed',
|
|
135
|
-
message: err?.message ?? String(err),
|
|
136
|
-
strategy: name,
|
|
137
|
-
}, null, 2));
|
|
138
|
-
process.exit(1);
|
|
139
|
-
}
|
|
140
|
-
|
|
141
128
|
if (KILL_STRATEGIES.has(entry.id)) {
|
|
142
129
|
try {
|
|
143
130
|
const client = GameClient.fromAuth();
|
|
@@ -171,20 +158,11 @@ Official and custom strategies:
|
|
|
171
158
|
}, null, 2));
|
|
172
159
|
process.exit(1);
|
|
173
160
|
}
|
|
174
|
-
// knowledge 不随切换策略清空(按对局作用域)。让新策略审视现有知识,告知玩家哪些已失效。
|
|
175
|
-
let knowledgeReview: KnowledgeReview | undefined;
|
|
176
|
-
if (entry.reviewKnowledge) {
|
|
177
|
-
try {
|
|
178
|
-
const review = entry.reviewKnowledge(buildKnowledgeView(KnowledgeStore.forActiveAccount().list()));
|
|
179
|
-
if ((review.stale?.length ?? 0) > 0 || (review.notes?.length ?? 0) > 0) knowledgeReview = review;
|
|
180
|
-
} catch {}
|
|
181
|
-
}
|
|
182
161
|
console.log(JSON.stringify({
|
|
183
162
|
message: `Strategy started: ${entry.id}`,
|
|
184
163
|
name: entry.name ?? entry.id,
|
|
185
164
|
description: entry.description,
|
|
186
165
|
pid: response.pid,
|
|
187
|
-
...(knowledgeReview ? { knowledge_review: knowledgeReview } : {}),
|
|
188
166
|
}, null, 2));
|
|
189
167
|
});
|
|
190
168
|
|
|
@@ -4,7 +4,6 @@
|
|
|
4
4
|
import {
|
|
5
5
|
existsSync,
|
|
6
6
|
mkdirSync,
|
|
7
|
-
mkdtempSync,
|
|
8
7
|
readdirSync,
|
|
9
8
|
readFileSync,
|
|
10
9
|
renameSync,
|
|
@@ -12,7 +11,6 @@ import {
|
|
|
12
11
|
writeFileSync,
|
|
13
12
|
} from 'fs';
|
|
14
13
|
import { basename, dirname, join } from 'path';
|
|
15
|
-
import { tmpdir } from 'os';
|
|
16
14
|
import { createHash } from 'crypto';
|
|
17
15
|
import { fileURLToPath } from 'url';
|
|
18
16
|
import { getWorkspaceDir } from './init-command.js';
|
|
@@ -21,7 +19,7 @@ import {
|
|
|
21
19
|
getUserDataOfficialStrategiesManifestFile,
|
|
22
20
|
getUserDataStrategiesDir,
|
|
23
21
|
} from './user-data.js';
|
|
24
|
-
import {
|
|
22
|
+
import { inspectStrategySource } from '../strategies/scanner.js';
|
|
25
23
|
|
|
26
24
|
export interface ManifestEntry {
|
|
27
25
|
format?: 1;
|
|
@@ -154,42 +152,25 @@ export function rewriteBuiltinImports(source: string, id: string, version: strin
|
|
|
154
152
|
|
|
155
153
|
async function validateExportable(rewritten: string): Promise<{ ok: boolean; error?: string }> {
|
|
156
154
|
try {
|
|
157
|
-
const
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
return { ok: false, error: `create() failed: ${message}` };
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
const sdkExports = await getSdkExports();
|
|
176
|
-
const importPattern = /import\s+(?:type\s+)?\{([^}]+)\}\s+from\s+['"](?:@myclaw163\/)?clawclaw-cli['"]/g;
|
|
177
|
-
let match;
|
|
178
|
-
while ((match = importPattern.exec(rewritten)) !== null) {
|
|
179
|
-
const names = match[1]
|
|
180
|
-
.split(',')
|
|
181
|
-
.map((name) => name.trim().replace(/^type\s+/, '').replace(/\s+as\s+.*$/, '').trim())
|
|
182
|
-
.filter(Boolean);
|
|
183
|
-
for (const name of names) {
|
|
184
|
-
if (!sdkExports.has(name)) {
|
|
185
|
-
return { ok: false, error: `'${name}' is not exported by @myclaw163/clawclaw-cli SDK` };
|
|
186
|
-
}
|
|
155
|
+
const summary = inspectStrategySource(rewritten, 'strategy.ts');
|
|
156
|
+
if (!summary) {
|
|
157
|
+
return { ok: false, error: 'Missing static strategy id/name/description or create definition' };
|
|
158
|
+
}
|
|
159
|
+
const sdkExports = await getSdkExports();
|
|
160
|
+
const importPattern = /import\s+(?:type\s+)?\{([^}]+)\}\s+from\s+['"](?:@myclaw163\/)?clawclaw-cli['"]/g;
|
|
161
|
+
let match;
|
|
162
|
+
while ((match = importPattern.exec(rewritten)) !== null) {
|
|
163
|
+
const names = match[1]
|
|
164
|
+
.split(',')
|
|
165
|
+
.map((name) => name.trim().replace(/^type\s+/, '').replace(/\s+as\s+.*$/, '').trim())
|
|
166
|
+
.filter(Boolean);
|
|
167
|
+
for (const name of names) {
|
|
168
|
+
if (!sdkExports.has(name)) {
|
|
169
|
+
return { ok: false, error: `'${name}' is not exported by @myclaw163/clawclaw-cli SDK` };
|
|
187
170
|
}
|
|
188
171
|
}
|
|
189
|
-
return { ok: true };
|
|
190
|
-
} finally {
|
|
191
|
-
rmSync(tmpDir, { recursive: true, force: true });
|
|
192
172
|
}
|
|
173
|
+
return { ok: true };
|
|
193
174
|
} catch (error: any) {
|
|
194
175
|
return { ok: false, error: error?.message ?? String(error) };
|
|
195
176
|
}
|
|
@@ -120,6 +120,49 @@ describe('strategy loader', () => {
|
|
|
120
120
|
expect(entries[0].id).toBe('test-strat');
|
|
121
121
|
});
|
|
122
122
|
|
|
123
|
+
it('does not execute strategy top-level code while listing metadata', async () => {
|
|
124
|
+
const marker = join(tmpDir, 'strategy-list-marker.txt');
|
|
125
|
+
writeStratFile('marker.ts', `
|
|
126
|
+
import { writeFileSync } from 'fs';
|
|
127
|
+
writeFileSync(${JSON.stringify(marker)}, 'executed', 'utf8');
|
|
128
|
+
export const strategy = {
|
|
129
|
+
id: 'marker-strategy',
|
|
130
|
+
name: 'Marker',
|
|
131
|
+
description: 'must stay static',
|
|
132
|
+
create: () => ({ name: 'marker-strategy', decide: () => [] }),
|
|
133
|
+
};
|
|
134
|
+
`);
|
|
135
|
+
const loader = await import('./loader.js');
|
|
136
|
+
expect(await loader.listStrategySummaries()).toEqual([{
|
|
137
|
+
id: 'marker-strategy',
|
|
138
|
+
name: 'Marker',
|
|
139
|
+
description: 'must stay static',
|
|
140
|
+
}]);
|
|
141
|
+
expect(realFs.existsSync(marker)).toBe(false);
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
it('executes only the explicitly selected strategy module', async () => {
|
|
145
|
+
const selectedMarker = join(tmpDir, 'selected-marker.txt');
|
|
146
|
+
const unrelatedMarker = join(tmpDir, 'unrelated-marker.txt');
|
|
147
|
+
const source = (id: string, marker: string) => `
|
|
148
|
+
import { writeFileSync } from 'fs';
|
|
149
|
+
writeFileSync(${JSON.stringify(marker)}, 'executed', 'utf8');
|
|
150
|
+
export const strategy = {
|
|
151
|
+
id: '${id}',
|
|
152
|
+
name: '${id}',
|
|
153
|
+
description: '${id}',
|
|
154
|
+
create: () => ({ name: '${id}', decide: () => [] }),
|
|
155
|
+
};`;
|
|
156
|
+
writeStratFile('selected.ts', source('selected', selectedMarker));
|
|
157
|
+
writeStratFile('unrelated.ts', source('unrelated', unrelatedMarker));
|
|
158
|
+
|
|
159
|
+
const loader = await import('./loader.js');
|
|
160
|
+
await loader.getStrategyEntry('selected');
|
|
161
|
+
|
|
162
|
+
expect(realFs.existsSync(selectedMarker)).toBe(true);
|
|
163
|
+
expect(realFs.existsSync(unrelatedMarker)).toBe(false);
|
|
164
|
+
});
|
|
165
|
+
|
|
123
166
|
it('rewrites clawclaw-cli imports during loading', async () => {
|
|
124
167
|
const srcWithImport = `
|
|
125
168
|
import { Action } from 'clawclaw-cli';
|
|
@@ -303,7 +346,7 @@ export const strategy = {
|
|
|
303
346
|
spy.mockRestore();
|
|
304
347
|
});
|
|
305
348
|
|
|
306
|
-
it('
|
|
349
|
+
it('lists require() source without executing it and rejects it only when selected', async () => {
|
|
307
350
|
const srcRequire = `
|
|
308
351
|
export const strategy = {
|
|
309
352
|
id: 'require-test',
|
|
@@ -317,18 +360,13 @@ export const strategy = {
|
|
|
317
360
|
}),
|
|
318
361
|
};
|
|
319
362
|
`;
|
|
320
|
-
const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
321
363
|
writeStratFile('require.ts', srcRequire);
|
|
322
364
|
const loader = await import('./loader.js');
|
|
323
365
|
const entries = await loader.listStrategyEntries();
|
|
324
|
-
expect(entries).toHaveLength(
|
|
325
|
-
expect(
|
|
326
|
-
|
|
327
|
-
);
|
|
328
|
-
expect(spy).toHaveBeenCalledWith(
|
|
329
|
-
expect.stringContaining("require('clawclaw-cli') is not supported"),
|
|
366
|
+
expect(entries).toHaveLength(1);
|
|
367
|
+
await expect(loader.getStrategyEntry('require-test')).rejects.toThrow(
|
|
368
|
+
/require\('clawclaw-cli'\) is not supported/,
|
|
330
369
|
);
|
|
331
|
-
spy.mockRestore();
|
|
332
370
|
});
|
|
333
371
|
|
|
334
372
|
it('does not rewrite from clawclaw-cli when it appears in a comment', async () => {
|
|
@@ -416,9 +454,9 @@ export const strategy = {
|
|
|
416
454
|
import { helperValue } from './helper.js';
|
|
417
455
|
export const strategy = {
|
|
418
456
|
id: 'relative-import-test',
|
|
419
|
-
description: 'test relative import
|
|
457
|
+
description: 'test relative import',
|
|
420
458
|
create: () => ({
|
|
421
|
-
name:
|
|
459
|
+
name: helperValue,
|
|
422
460
|
decide: () => [],
|
|
423
461
|
}),
|
|
424
462
|
};
|
|
@@ -428,7 +466,8 @@ export const strategy = {
|
|
|
428
466
|
const entries = await loader.listStrategyEntries();
|
|
429
467
|
expect(entries).toHaveLength(1);
|
|
430
468
|
expect(entries[0].id).toBe('relative-import-test');
|
|
431
|
-
expect(entries[0].description).toBe('test relative import
|
|
469
|
+
expect(entries[0].description).toBe('test relative import');
|
|
470
|
+
expect((await loader.getStrategyEntry('relative-import-test'))?.create().name).toBe('from-helper');
|
|
432
471
|
});
|
|
433
472
|
|
|
434
473
|
it('bundles nested relative imports from helper files', async () => {
|
|
@@ -445,9 +484,9 @@ export const strategy = {
|
|
|
445
484
|
import { greeting } from './intermediate.js';
|
|
446
485
|
export const strategy = {
|
|
447
486
|
id: 'nested-import-test',
|
|
448
|
-
description:
|
|
487
|
+
description: 'nested import test',
|
|
449
488
|
create: () => ({
|
|
450
|
-
name:
|
|
489
|
+
name: greeting,
|
|
451
490
|
decide: () => [],
|
|
452
491
|
}),
|
|
453
492
|
};
|
|
@@ -456,7 +495,8 @@ export const strategy = {
|
|
|
456
495
|
const loader = await import('./loader.js');
|
|
457
496
|
const entries = await loader.listStrategyEntries();
|
|
458
497
|
expect(entries).toHaveLength(1);
|
|
459
|
-
expect(entries[0].description).toBe('
|
|
498
|
+
expect(entries[0].description).toBe('nested import test');
|
|
499
|
+
expect((await loader.getStrategyEntry('nested-import-test'))?.create().name).toBe('hello world');
|
|
460
500
|
});
|
|
461
501
|
|
|
462
502
|
it('redirects clawclaw-cli imports in helper files too', async () => {
|
|
@@ -469,9 +509,9 @@ export const strategy = {
|
|
|
469
509
|
import { hasDist } from './sdk-helper.js';
|
|
470
510
|
export const strategy = {
|
|
471
511
|
id: 'helper-sdk-test',
|
|
472
|
-
description: '
|
|
512
|
+
description: 'helper sdk test',
|
|
473
513
|
create: () => ({
|
|
474
|
-
name:
|
|
514
|
+
name: String(hasDist),
|
|
475
515
|
decide: () => [],
|
|
476
516
|
}),
|
|
477
517
|
};
|
|
@@ -481,6 +521,7 @@ export const strategy = {
|
|
|
481
521
|
const entries = await loader.listStrategyEntries();
|
|
482
522
|
expect(entries).toHaveLength(1);
|
|
483
523
|
expect(entries[0].id).toBe('helper-sdk-test');
|
|
524
|
+
expect((await loader.getStrategyEntry('helper-sdk-test'))?.create().name).toBe('true');
|
|
484
525
|
});
|
|
485
526
|
});
|
|
486
527
|
|
|
@@ -555,7 +596,7 @@ export const strategy = {
|
|
|
555
596
|
expect(entries).toHaveLength(0);
|
|
556
597
|
});
|
|
557
598
|
|
|
558
|
-
it('logs error
|
|
599
|
+
it('logs an inspection error for invalid strategy source', async () => {
|
|
559
600
|
writeStratFile('broken.ts', 'this is not valid TypeScript {{{');
|
|
560
601
|
writeStratFile('good.ts', VALID_SRC);
|
|
561
602
|
const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
@@ -564,50 +605,41 @@ export const strategy = {
|
|
|
564
605
|
expect(entries).toHaveLength(1);
|
|
565
606
|
expect(entries[0].id).toBe('test-strat');
|
|
566
607
|
expect(spy).toHaveBeenCalledWith(
|
|
567
|
-
expect.stringContaining('Failed to
|
|
608
|
+
expect.stringContaining('Failed to inspect user strategy broken.ts'),
|
|
568
609
|
);
|
|
569
610
|
spy.mockRestore();
|
|
570
611
|
});
|
|
571
612
|
|
|
572
|
-
it('includes
|
|
613
|
+
it('includes the static parser diagnostic for syntax errors', async () => {
|
|
573
614
|
writeStratFile('bad-syntax.ts', 'this is not valid TypeScript {{{');
|
|
574
615
|
const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
575
616
|
const loader = await import('./loader.js');
|
|
576
617
|
await loader.listStrategyEntries();
|
|
577
|
-
// Error should contain the esbuild diagnostic: filename, line:col, and description
|
|
578
618
|
const errorCalls = spy.mock.calls.map(c => String(c[0]));
|
|
579
|
-
const buildError = errorCalls.find(m => m.includes('Failed to
|
|
619
|
+
const buildError = errorCalls.find(m => m.includes('Failed to inspect user strategy bad-syntax.ts'));
|
|
580
620
|
expect(buildError).toBeDefined();
|
|
581
621
|
expect(buildError).toContain('bad-syntax.ts');
|
|
582
|
-
expect(buildError).toMatch(/\d+:\d+/);
|
|
622
|
+
expect(buildError).toMatch(/\d+:\d+/);
|
|
583
623
|
spy.mockRestore();
|
|
584
624
|
});
|
|
585
625
|
|
|
586
|
-
it('
|
|
626
|
+
it('does not resolve npm imports while listing and fails only when selected', async () => {
|
|
587
627
|
const srcNpm = `
|
|
588
628
|
import { something } from 'lodash';
|
|
589
629
|
export const strategy = {
|
|
590
630
|
id: 'npm-test',
|
|
591
|
-
description: 'test npm import
|
|
631
|
+
description: 'test npm import',
|
|
592
632
|
create: () => ({
|
|
593
|
-
name:
|
|
633
|
+
name: String(something),
|
|
594
634
|
decide: () => [],
|
|
595
635
|
}),
|
|
596
636
|
};
|
|
597
637
|
`;
|
|
598
|
-
const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
599
638
|
writeStratFile('npm-strat.ts', srcNpm);
|
|
600
639
|
const loader = await import('./loader.js');
|
|
601
640
|
const entries = await loader.listStrategyEntries();
|
|
602
|
-
expect(entries).toHaveLength(
|
|
603
|
-
|
|
604
|
-
const loadError = errorCalls.find(m => m.includes('Failed to load user strategy npm-strat.ts'));
|
|
605
|
-
expect(loadError).toBeDefined();
|
|
606
|
-
// Must be a runtime resolution failure (Node cannot find 'lodash' from temp dir),
|
|
607
|
-
// not an esbuild build failure. The `something` reference MUST stay used
|
|
608
|
-
// to prevent tree-shaking from removing the import entirely.
|
|
609
|
-
expect(loadError).toMatch(/Cannot find package|cannot be resolved/i);
|
|
610
|
-
spy.mockRestore();
|
|
641
|
+
expect(entries).toHaveLength(1);
|
|
642
|
+
await expect(loader.getStrategyEntry('npm-test')).rejects.toThrow(/Cannot find package|cannot be resolved/i);
|
|
611
643
|
});
|
|
612
644
|
|
|
613
645
|
it('handles readdirSync errors gracefully', async () => {
|
package/src/strategies/loader.ts
CHANGED
|
@@ -1,30 +1,27 @@
|
|
|
1
|
-
import { existsSync,
|
|
1
|
+
import { existsSync, readFileSync, realpathSync, mkdtempSync, writeFileSync, rmSync } from 'fs';
|
|
2
2
|
import { dirname, join, resolve, basename } from 'path';
|
|
3
3
|
import { tmpdir } from 'os';
|
|
4
4
|
import { fileURLToPath, pathToFileURL } from 'url';
|
|
5
5
|
import { getWorkspaceDir } from '../lib/init-command.js';
|
|
6
6
|
import { ensureUserDataLayout, getUserDataStrategiesDir } from '../lib/user-data.js';
|
|
7
|
+
import { scanStrategyDirectory } from './scanner.js';
|
|
8
|
+
import type { StrategyDescriptor, StrategySummary } from './scanner.js';
|
|
7
9
|
import type { Plugin, OnResolveArgs } from 'esbuild';
|
|
8
10
|
import type { Strategy, StrategyEntry } from './types.js';
|
|
9
11
|
|
|
12
|
+
export type { StrategySummary } from './scanner.js';
|
|
13
|
+
|
|
10
14
|
const __filename = fileURLToPath(import.meta.url);
|
|
11
15
|
const __dirname = dirname(__filename);
|
|
12
16
|
|
|
13
|
-
// Resolve SDK path for
|
|
14
|
-
// realpathSync ensures dedup against built-in strategies even under --preserve-symlinks.
|
|
17
|
+
// Resolve SDK path for the one selected strategy import (raw filesystem path, not URL).
|
|
15
18
|
const SDK_PATH = realpathSync(resolve(__dirname, '../sdk/index.ts'));
|
|
16
19
|
|
|
17
|
-
const
|
|
18
|
-
const
|
|
19
|
-
let
|
|
20
|
+
const strategyCatalog = new Map<string, StrategyDescriptor>();
|
|
21
|
+
const runtimeEntryCache = new Map<string, StrategyEntry>();
|
|
22
|
+
let catalogLoaded = false;
|
|
20
23
|
let loadedWorkspaceDir: string | undefined;
|
|
21
24
|
|
|
22
|
-
export interface StrategySummary {
|
|
23
|
-
id: string;
|
|
24
|
-
name: string;
|
|
25
|
-
description: string;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
25
|
function resolveUserStrategiesDir(): string | undefined {
|
|
29
26
|
const workspaceDir = getWorkspaceDir();
|
|
30
27
|
if (!existsSync(workspaceDir)) return undefined;
|
|
@@ -34,18 +31,8 @@ function resolveUserStrategiesDir(): string | undefined {
|
|
|
34
31
|
return strategiesDir;
|
|
35
32
|
}
|
|
36
33
|
|
|
37
|
-
/**
|
|
38
|
-
* Create an esbuild plugin that intercepts `@myclaw163/clawclaw-cli` and
|
|
39
|
-
* `@myclaw163/clawclaw-cli/*` imports (and the legacy bare `clawclaw-cli`
|
|
40
|
-
* name for backward compat) and redirects them to the local SDK path
|
|
41
|
-
* (marked external so Node resolves the same module instance at runtime).
|
|
42
|
-
*
|
|
43
|
-
* `require()` calls fail the build with a clear error, since `require` is
|
|
44
|
-
* unavailable in ESM output and would otherwise crash at runtime.
|
|
45
|
-
*/
|
|
46
34
|
function createSdkPlugin(): { plugin: Plugin } {
|
|
47
35
|
const sdkUrl = pathToFileURL(SDK_PATH).href;
|
|
48
|
-
|
|
49
36
|
const plugin: Plugin = {
|
|
50
37
|
name: 'clawclaw-cli-sdk',
|
|
51
38
|
setup(build) {
|
|
@@ -61,12 +48,10 @@ function createSdkPlugin(): { plugin: Plugin } {
|
|
|
61
48
|
});
|
|
62
49
|
},
|
|
63
50
|
};
|
|
64
|
-
|
|
65
51
|
return { plugin };
|
|
66
52
|
}
|
|
67
53
|
|
|
68
|
-
|
|
69
|
-
// Module type, but both are cast to StrategyEntry via `as` in loadFromDir.
|
|
54
|
+
/** Import exactly one strategy selected for execution. Catalog discovery never calls this. */
|
|
70
55
|
export async function importUserFile(filePath: string): Promise<Record<string, unknown>> {
|
|
71
56
|
const { plugin } = createSdkPlugin();
|
|
72
57
|
const { build } = await import('esbuild');
|
|
@@ -85,8 +70,6 @@ export async function importUserFile(filePath: string): Promise<Record<string, u
|
|
|
85
70
|
plugins: [plugin],
|
|
86
71
|
});
|
|
87
72
|
|
|
88
|
-
// Write to temporary file so Node's module cache deduplicates the SDK —
|
|
89
|
-
// data URLs load as separate module instances, breaking instanceof checks.
|
|
90
73
|
const tmpDir = mkdtempSync(join(tmpdir(), 'ccl-strategy-'));
|
|
91
74
|
const tmpFile = join(tmpDir, basename(filePath).replace(/\.(ts|js)$/, '.mjs'));
|
|
92
75
|
try {
|
|
@@ -97,55 +80,14 @@ export async function importUserFile(filePath: string): Promise<Record<string, u
|
|
|
97
80
|
}
|
|
98
81
|
}
|
|
99
82
|
|
|
100
|
-
async function
|
|
101
|
-
let files: string[];
|
|
102
|
-
try {
|
|
103
|
-
files = readdirSync(dir).filter(f => {
|
|
104
|
-
if (f.startsWith('_')) return false;
|
|
105
|
-
const match = f.match(/^(.+)\.(ts|js)$/);
|
|
106
|
-
if (!match) return false;
|
|
107
|
-
if (match[1].endsWith('.d')) return false;
|
|
108
|
-
if (match[1].endsWith('.test')) return false;
|
|
109
|
-
return true;
|
|
110
|
-
}).sort((a, b) => {
|
|
111
|
-
const aId = a.replace(/\.(?:ts|js)$/, '');
|
|
112
|
-
const bId = b.replace(/\.(?:ts|js)$/, '');
|
|
113
|
-
const aOfficial = a === `${aId}.ts` && officialIds.has(aId);
|
|
114
|
-
const bOfficial = b === `${bId}.ts` && officialIds.has(bId);
|
|
115
|
-
if (aOfficial !== bOfficial) return aOfficial ? -1 : 1;
|
|
116
|
-
return a.localeCompare(b);
|
|
117
|
-
});
|
|
118
|
-
} catch {
|
|
119
|
-
return;
|
|
120
|
-
}
|
|
121
|
-
for (const file of files) {
|
|
122
|
-
try {
|
|
123
|
-
const filePath = realpathSync(join(dir, file));
|
|
124
|
-
const mod = await importUserFile(filePath);
|
|
125
|
-
const entry: StrategyEntry | undefined = mod.strategy as StrategyEntry | undefined;
|
|
126
|
-
if (entry?.id && typeof entry.description === 'string' && typeof entry.create === 'function') {
|
|
127
|
-
strategyMap.set(entry.id, entry);
|
|
128
|
-
const sidecar = filePath.replace(/\.(ts|js)$/, '.knowledge.md');
|
|
129
|
-
if (existsSync(sidecar)) knowledgeDocMap.set(entry.id, sidecar);
|
|
130
|
-
else knowledgeDocMap.delete(entry.id);
|
|
131
|
-
}
|
|
132
|
-
} catch (err) {
|
|
133
|
-
// Strip temp-dir paths from error messages — they leak internal
|
|
134
|
-
// implementation details (e.g., /tmp/ccl-strategy-XXXX/strategy.mjs)
|
|
135
|
-
const raw = err instanceof Error ? err.message : String(err);
|
|
136
|
-
const cleaned = raw.replace(/\S*ccl-strategy-[^/]*\//g, '');
|
|
137
|
-
console.error(`[ccl] Failed to load user strategy ${file}: ${cleaned}`);
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
async function ensureLoaded(): Promise<void> {
|
|
83
|
+
async function ensureCatalog(): Promise<void> {
|
|
143
84
|
const workspaceDir = getWorkspaceDir();
|
|
144
|
-
if (
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
85
|
+
if (catalogLoaded && loadedWorkspaceDir === workspaceDir) return;
|
|
86
|
+
strategyCatalog.clear();
|
|
87
|
+
runtimeEntryCache.clear();
|
|
88
|
+
catalogLoaded = true;
|
|
148
89
|
loadedWorkspaceDir = workspaceDir;
|
|
90
|
+
|
|
149
91
|
let officialIds = new Set<string>();
|
|
150
92
|
try {
|
|
151
93
|
const { readManifest, syncOfficialStrategies } = await import('../lib/strategy-export.js');
|
|
@@ -155,39 +97,68 @@ async function ensureLoaded(): Promise<void> {
|
|
|
155
97
|
const message = error instanceof Error ? error.message : String(error);
|
|
156
98
|
console.error(`[ccl] Failed to initialize official strategies: ${message}`);
|
|
157
99
|
}
|
|
100
|
+
|
|
158
101
|
const userDir = resolveUserStrategiesDir();
|
|
159
|
-
if (userDir)
|
|
102
|
+
if (!userDir) return;
|
|
103
|
+
const scan = scanStrategyDirectory(userDir, officialIds);
|
|
104
|
+
for (const error of scan.errors) {
|
|
105
|
+
console.error(`[ccl] Failed to inspect user strategy ${error.file}: ${error.message}`);
|
|
106
|
+
}
|
|
107
|
+
for (const descriptor of scan.descriptors) strategyCatalog.set(descriptor.id, descriptor);
|
|
160
108
|
}
|
|
161
109
|
|
|
162
|
-
|
|
163
|
-
await
|
|
164
|
-
const byId =
|
|
110
|
+
async function findStrategyDescriptor(idOrName: string): Promise<StrategyDescriptor | undefined> {
|
|
111
|
+
await ensureCatalog();
|
|
112
|
+
const byId = strategyCatalog.get(idOrName);
|
|
165
113
|
if (byId) return byId;
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
for (const entry of strategyMap.values()) {
|
|
169
|
-
if (entry.name === idOrName) return entry;
|
|
114
|
+
for (const descriptor of strategyCatalog.values()) {
|
|
115
|
+
if (descriptor.name === idOrName) return descriptor;
|
|
170
116
|
}
|
|
171
117
|
return undefined;
|
|
172
118
|
}
|
|
173
119
|
|
|
174
|
-
export async function
|
|
175
|
-
await
|
|
176
|
-
|
|
120
|
+
export async function getStrategySummary(idOrName: string): Promise<StrategySummary | undefined> {
|
|
121
|
+
const descriptor = await findStrategyDescriptor(idOrName);
|
|
122
|
+
if (!descriptor) return undefined;
|
|
123
|
+
return { id: descriptor.id, name: descriptor.name, description: descriptor.description };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Load only the strategy explicitly selected by id or display name. */
|
|
127
|
+
export async function getStrategyEntry(idOrName: string): Promise<StrategyEntry | undefined> {
|
|
128
|
+
const descriptor = await findStrategyDescriptor(idOrName);
|
|
129
|
+
if (!descriptor) return undefined;
|
|
130
|
+
const cached = runtimeEntryCache.get(descriptor.filePath);
|
|
131
|
+
if (cached) return cached;
|
|
132
|
+
|
|
133
|
+
const mod = await importUserFile(descriptor.filePath);
|
|
134
|
+
const entry = mod.strategy as StrategyEntry | undefined;
|
|
135
|
+
if (!entry?.id || typeof entry.description !== 'string' || typeof entry.create !== 'function') {
|
|
136
|
+
throw new Error(`Strategy '${descriptor.id}' does not export a valid strategy object.`);
|
|
137
|
+
}
|
|
138
|
+
if (entry.id !== descriptor.id) {
|
|
139
|
+
throw new Error(`Strategy metadata changed while loading '${descriptor.id}'. Run the command again.`);
|
|
140
|
+
}
|
|
141
|
+
runtimeEntryCache.set(descriptor.filePath, entry);
|
|
142
|
+
return entry;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Compatibility name for internal callers: returns static metadata and never executes modules. */
|
|
146
|
+
export async function listStrategyEntries(): Promise<StrategySummary[]> {
|
|
147
|
+
return listStrategySummaries();
|
|
177
148
|
}
|
|
178
149
|
|
|
179
150
|
export async function listStrategySummaries(): Promise<StrategySummary[]> {
|
|
180
|
-
|
|
181
|
-
return
|
|
182
|
-
id:
|
|
183
|
-
name:
|
|
184
|
-
description:
|
|
151
|
+
await ensureCatalog();
|
|
152
|
+
return [...strategyCatalog.values()].map(descriptor => ({
|
|
153
|
+
id: descriptor.id,
|
|
154
|
+
name: descriptor.name,
|
|
155
|
+
description: descriptor.description,
|
|
185
156
|
}));
|
|
186
157
|
}
|
|
187
158
|
|
|
188
159
|
export async function getStrategyKnowledgeDoc(id: string): Promise<string | undefined> {
|
|
189
|
-
await
|
|
190
|
-
const path =
|
|
160
|
+
const descriptor = await findStrategyDescriptor(id);
|
|
161
|
+
const path = descriptor?.knowledgeDocPath;
|
|
191
162
|
if (!path || !existsSync(path)) return undefined;
|
|
192
163
|
try {
|
|
193
164
|
return readFileSync(path, 'utf8');
|
|
@@ -202,11 +173,11 @@ export async function resolveStrategy(id: string, args?: string[]): Promise<Stra
|
|
|
202
173
|
return entry.create(args);
|
|
203
174
|
}
|
|
204
175
|
|
|
205
|
-
/** Reset and re-scan
|
|
176
|
+
/** Reset and statically re-scan after a strategy file is installed, removed, or replaced. */
|
|
206
177
|
export async function reload(): Promise<void> {
|
|
207
|
-
|
|
178
|
+
catalogLoaded = false;
|
|
208
179
|
loadedWorkspaceDir = undefined;
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
await
|
|
180
|
+
strategyCatalog.clear();
|
|
181
|
+
runtimeEntryCache.clear();
|
|
182
|
+
await ensureCatalog();
|
|
212
183
|
}
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
import { existsSync, readFileSync, readdirSync, realpathSync } from 'fs';
|
|
2
|
+
import { basename, dirname, join } from 'path';
|
|
3
|
+
import ts from 'typescript';
|
|
4
|
+
|
|
5
|
+
export interface StrategySummary {
|
|
6
|
+
id: string;
|
|
7
|
+
name: string;
|
|
8
|
+
description: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface StrategyDescriptor extends StrategySummary {
|
|
12
|
+
filePath: string;
|
|
13
|
+
knowledgeDocPath?: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface StrategyScanError {
|
|
17
|
+
file: string;
|
|
18
|
+
message: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface StrategyScanResult {
|
|
22
|
+
descriptors: StrategyDescriptor[];
|
|
23
|
+
errors: StrategyScanError[];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function unwrapExpression(expression: ts.Expression): ts.Expression {
|
|
27
|
+
let current = expression;
|
|
28
|
+
while (
|
|
29
|
+
ts.isParenthesizedExpression(current)
|
|
30
|
+
|| ts.isAsExpression(current)
|
|
31
|
+
|| ts.isTypeAssertionExpression(current)
|
|
32
|
+
|| ts.isSatisfiesExpression(current)
|
|
33
|
+
|| ts.isNonNullExpression(current)
|
|
34
|
+
) {
|
|
35
|
+
current = current.expression;
|
|
36
|
+
}
|
|
37
|
+
return current;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function propertyNameText(name: ts.PropertyName | ts.BindingName | undefined): string | undefined {
|
|
41
|
+
if (!name) return undefined;
|
|
42
|
+
if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) return name.text;
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function collectTopLevelBindings(sourceFile: ts.SourceFile): Map<string, ts.Expression> {
|
|
47
|
+
const bindings = new Map<string, ts.Expression>();
|
|
48
|
+
for (const statement of sourceFile.statements) {
|
|
49
|
+
if (!ts.isVariableStatement(statement)) continue;
|
|
50
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
51
|
+
if (ts.isIdentifier(declaration.name) && declaration.initializer) {
|
|
52
|
+
bindings.set(declaration.name.text, declaration.initializer);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return bindings;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function exportedStrategyInitializer(sourceFile: ts.SourceFile): ts.Expression | undefined {
|
|
60
|
+
for (const statement of sourceFile.statements) {
|
|
61
|
+
if (!ts.isVariableStatement(statement)) continue;
|
|
62
|
+
const exported = statement.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.ExportKeyword) ?? false;
|
|
63
|
+
if (!exported) continue;
|
|
64
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
65
|
+
if (ts.isIdentifier(declaration.name) && declaration.name.text === 'strategy') return declaration.initializer;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return undefined;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function parseDiagnostic(sourceFile: ts.SourceFile): string | undefined {
|
|
72
|
+
const diagnostics = (sourceFile as ts.SourceFile & { parseDiagnostics?: readonly ts.Diagnostic[] }).parseDiagnostics ?? [];
|
|
73
|
+
const diagnostic = diagnostics[0];
|
|
74
|
+
if (!diagnostic) return undefined;
|
|
75
|
+
const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n');
|
|
76
|
+
if (diagnostic.start === undefined) return message;
|
|
77
|
+
const position = sourceFile.getLineAndCharacterOfPosition(diagnostic.start);
|
|
78
|
+
return `${sourceFile.fileName}:${position.line + 1}:${position.character + 1}: ${message}`;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function staticString(
|
|
82
|
+
expression: ts.Expression | undefined,
|
|
83
|
+
bindings: Map<string, ts.Expression>,
|
|
84
|
+
visiting = new Set<string>(),
|
|
85
|
+
): string | undefined {
|
|
86
|
+
if (!expression) return undefined;
|
|
87
|
+
const current = unwrapExpression(expression);
|
|
88
|
+
if (ts.isStringLiteral(current) || ts.isNoSubstitutionTemplateLiteral(current)) return current.text;
|
|
89
|
+
if (ts.isBinaryExpression(current) && current.operatorToken.kind === ts.SyntaxKind.PlusToken) {
|
|
90
|
+
const left = staticString(current.left, bindings, visiting);
|
|
91
|
+
const right = staticString(current.right, bindings, visiting);
|
|
92
|
+
return left === undefined || right === undefined ? undefined : left + right;
|
|
93
|
+
}
|
|
94
|
+
if (ts.isIdentifier(current)) {
|
|
95
|
+
if (visiting.has(current.text)) return undefined;
|
|
96
|
+
const value = bindings.get(current.text);
|
|
97
|
+
if (!value) return undefined;
|
|
98
|
+
const nextVisiting = new Set(visiting);
|
|
99
|
+
nextVisiting.add(current.text);
|
|
100
|
+
return staticString(value, bindings, nextVisiting);
|
|
101
|
+
}
|
|
102
|
+
return undefined;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function findObjectProperty(
|
|
106
|
+
expression: ts.Expression,
|
|
107
|
+
key: string,
|
|
108
|
+
bindings: Map<string, ts.Expression>,
|
|
109
|
+
visiting = new Set<string>(),
|
|
110
|
+
): ts.ObjectLiteralElementLike | undefined {
|
|
111
|
+
const current = unwrapExpression(expression);
|
|
112
|
+
if (ts.isIdentifier(current)) {
|
|
113
|
+
if (visiting.has(current.text)) return undefined;
|
|
114
|
+
const value = bindings.get(current.text);
|
|
115
|
+
if (!value) return undefined;
|
|
116
|
+
const nextVisiting = new Set(visiting);
|
|
117
|
+
nextVisiting.add(current.text);
|
|
118
|
+
return findObjectProperty(value, key, bindings, nextVisiting);
|
|
119
|
+
}
|
|
120
|
+
if (!ts.isObjectLiteralExpression(current)) return undefined;
|
|
121
|
+
|
|
122
|
+
let found: ts.ObjectLiteralElementLike | undefined;
|
|
123
|
+
for (const property of current.properties) {
|
|
124
|
+
if (ts.isSpreadAssignment(property)) {
|
|
125
|
+
const spreadProperty = findObjectProperty(property.expression, key, bindings, visiting);
|
|
126
|
+
if (spreadProperty) found = spreadProperty;
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
if (propertyNameText(property.name) === key) found = property;
|
|
130
|
+
}
|
|
131
|
+
return found;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function propertyExpression(property: ts.ObjectLiteralElementLike | undefined): ts.Expression | undefined {
|
|
135
|
+
if (!property) return undefined;
|
|
136
|
+
if (ts.isPropertyAssignment(property)) return property.initializer;
|
|
137
|
+
if (ts.isShorthandPropertyAssignment(property)) return property.name;
|
|
138
|
+
return undefined;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Parse fixed strategy metadata without evaluating or importing the source module. */
|
|
142
|
+
export function inspectStrategySource(source: string, fileName = 'strategy.ts'): StrategySummary | undefined {
|
|
143
|
+
const sourceFile = ts.createSourceFile(
|
|
144
|
+
fileName,
|
|
145
|
+
source,
|
|
146
|
+
ts.ScriptTarget.Latest,
|
|
147
|
+
true,
|
|
148
|
+
fileName.endsWith('.js') ? ts.ScriptKind.JS : ts.ScriptKind.TS,
|
|
149
|
+
);
|
|
150
|
+
if (parseDiagnostic(sourceFile)) return undefined;
|
|
151
|
+
const initializer = exportedStrategyInitializer(sourceFile);
|
|
152
|
+
if (!initializer) return undefined;
|
|
153
|
+
const bindings = collectTopLevelBindings(sourceFile);
|
|
154
|
+
const id = staticString(propertyExpression(findObjectProperty(initializer, 'id', bindings)), bindings);
|
|
155
|
+
const description = staticString(propertyExpression(findObjectProperty(initializer, 'description', bindings)), bindings);
|
|
156
|
+
const create = findObjectProperty(initializer, 'create', bindings);
|
|
157
|
+
if (!id || description === undefined || !create) return undefined;
|
|
158
|
+
const name = staticString(propertyExpression(findObjectProperty(initializer, 'name', bindings)), bindings) ?? id;
|
|
159
|
+
return { id, name, description };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function strategyFiles(dir: string, officialIds: Set<string>): string[] {
|
|
163
|
+
return readdirSync(dir).filter(file => {
|
|
164
|
+
if (file.startsWith('_')) return false;
|
|
165
|
+
const match = file.match(/^(.+)\.(ts|js)$/);
|
|
166
|
+
if (!match) return false;
|
|
167
|
+
if (match[1].endsWith('.d') || match[1].endsWith('.test')) return false;
|
|
168
|
+
return true;
|
|
169
|
+
}).sort((a, b) => {
|
|
170
|
+
const aId = a.replace(/\.(?:ts|js)$/, '');
|
|
171
|
+
const bId = b.replace(/\.(?:ts|js)$/, '');
|
|
172
|
+
const aOfficial = a === `${aId}.ts` && officialIds.has(aId);
|
|
173
|
+
const bOfficial = b === `${bId}.ts` && officialIds.has(bId);
|
|
174
|
+
if (aOfficial !== bOfficial) return aOfficial ? -1 : 1;
|
|
175
|
+
return a.localeCompare(b);
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Scan one strategy directory. Reading and AST parsing are the only source operations performed. */
|
|
180
|
+
export function scanStrategyDirectory(dir: string, officialIds: Set<string> = new Set()): StrategyScanResult {
|
|
181
|
+
const descriptors: StrategyDescriptor[] = [];
|
|
182
|
+
const errors: StrategyScanError[] = [];
|
|
183
|
+
let files: string[];
|
|
184
|
+
try {
|
|
185
|
+
files = strategyFiles(dir, officialIds);
|
|
186
|
+
} catch {
|
|
187
|
+
return { descriptors, errors };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
let realDir: string;
|
|
191
|
+
try {
|
|
192
|
+
realDir = realpathSync(dir);
|
|
193
|
+
} catch {
|
|
194
|
+
return { descriptors, errors };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
for (const file of files) {
|
|
198
|
+
try {
|
|
199
|
+
const filePath = realpathSync(join(dir, file));
|
|
200
|
+
if (dirname(filePath) !== realDir) throw new Error('strategy file resolves outside the strategies directory');
|
|
201
|
+
const source = readFileSync(filePath, 'utf8');
|
|
202
|
+
const sourceFile = ts.createSourceFile(
|
|
203
|
+
file,
|
|
204
|
+
source,
|
|
205
|
+
ts.ScriptTarget.Latest,
|
|
206
|
+
true,
|
|
207
|
+
file.endsWith('.js') ? ts.ScriptKind.JS : ts.ScriptKind.TS,
|
|
208
|
+
);
|
|
209
|
+
const syntaxError = parseDiagnostic(sourceFile);
|
|
210
|
+
if (syntaxError) throw new Error(syntaxError);
|
|
211
|
+
if (!exportedStrategyInitializer(sourceFile)) continue;
|
|
212
|
+
const summary = inspectStrategySource(source, file);
|
|
213
|
+
if (!summary) {
|
|
214
|
+
throw new Error('expected exported strategy metadata with static id, name/description, and create');
|
|
215
|
+
}
|
|
216
|
+
const knowledgeCandidate = filePath.replace(/\.(ts|js)$/, '.knowledge.md');
|
|
217
|
+
let knowledgeDocPath: string | undefined;
|
|
218
|
+
if (existsSync(knowledgeCandidate)) {
|
|
219
|
+
knowledgeDocPath = realpathSync(knowledgeCandidate);
|
|
220
|
+
if (dirname(knowledgeDocPath) !== realDir) {
|
|
221
|
+
throw new Error('strategy knowledge file resolves outside the strategies directory');
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
descriptors.push({
|
|
225
|
+
...summary,
|
|
226
|
+
filePath,
|
|
227
|
+
...(knowledgeDocPath ? { knowledgeDocPath } : {}),
|
|
228
|
+
});
|
|
229
|
+
} catch (error) {
|
|
230
|
+
errors.push({ file, message: error instanceof Error ? error.message : String(error) });
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
return { descriptors, errors };
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
export function strategyFileName(filePath: string): string {
|
|
237
|
+
return basename(filePath);
|
|
238
|
+
}
|