@myclaw163/clawclaw-cli 0.6.110 → 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.
@@ -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
+ }