@myclaw163/clawclaw-cli 0.1.0
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/README.md +434 -0
- package/bin/clawclaw-cli.mjs +4 -0
- package/package.json +48 -0
- package/personas//345/217/243/346/230/257/345/277/203/351/235/236.md +50 -0
- package/personas//345/277/240/345/277/203/350/200/201/344/273/206.md +51 -0
- package/personas//346/227/240/344/272/272/350/256/276.md +1 -0
- package/personas//350/264/253/345/230/264/346/215/237/345/217/213.md +48 -0
- package/personas//350/275/257/350/220/214/350/205/271/351/273/221.md +51 -0
- package/scripts/check-skill-command-surface.mjs +118 -0
- package/scripts/check_monitor.cjs +435 -0
- package/scripts/check_monitor.test.mjs +212 -0
- package/scripts/enable_ccl_permissions.cjs +164 -0
- package/scripts/enable_ccl_permissions.test.mjs +163 -0
- package/scripts/enable_monitor.cjs +677 -0
- package/scripts/enable_monitor.test.mjs +201 -0
- package/scripts/find-hide-spots.py +157 -0
- package/scripts/postinstall.mjs +20 -0
- package/scripts/sync-bundled-skill.mjs +254 -0
- package/scripts/sync-bundled-skill.test.mjs +152 -0
- package/skills/clawclaw/.gitkeep +0 -0
- package/skills/clawclaw/SKILL.md +275 -0
- package/skills/clawclaw/references/CHATTERBOX.md +142 -0
- package/skills/clawclaw/references/CLAUDE-CODE-MONITOR.md +224 -0
- package/skills/clawclaw/references/COMMANDS.md +165 -0
- package/skills/clawclaw/references/GAME-MECHANICS.md +195 -0
- package/skills/clawclaw/references/HUB.md +48 -0
- package/skills/clawclaw/references/KNOWLEDGE.md +42 -0
- package/skills/clawclaw/references/STRATEGIES.md +59 -0
- package/skills/clawclaw/references/STREAM.md +75 -0
- package/skills/clawclaw/references/TACTICS.md +65 -0
- package/src/assets/clawclaw-ascii-map.txt +40 -0
- package/src/cli.ts +113 -0
- package/src/commands/_schema.ts +124 -0
- package/src/commands/account.test.ts +391 -0
- package/src/commands/account.ts +338 -0
- package/src/commands/competition.ts +42 -0
- package/src/commands/config.ts +30 -0
- package/src/commands/data.test.ts +33 -0
- package/src/commands/data.ts +22 -0
- package/src/commands/do.test.ts +117 -0
- package/src/commands/do.ts +195 -0
- package/src/commands/events.test.ts +144 -0
- package/src/commands/events.ts +268 -0
- package/src/commands/game-map.test.ts +28 -0
- package/src/commands/game-monitor-status.test.ts +58 -0
- package/src/commands/game-start-plan.test.ts +356 -0
- package/src/commands/game.ts +2046 -0
- package/src/commands/history-player.test.ts +105 -0
- package/src/commands/history.ts +573 -0
- package/src/commands/hub.test.ts +134 -0
- package/src/commands/hub.ts +249 -0
- package/src/commands/knowledge.test.ts +13 -0
- package/src/commands/knowledge.ts +176 -0
- package/src/commands/load.test.ts +107 -0
- package/src/commands/load.ts +26 -0
- package/src/commands/meeting-history.test.ts +106 -0
- package/src/commands/memory.ts +40 -0
- package/src/commands/peek.ts +45 -0
- package/src/commands/persona.ts +62 -0
- package/src/commands/setup/codex.ts +266 -0
- package/src/commands/setup/hermes.test.ts +96 -0
- package/src/commands/setup/hermes.ts +76 -0
- package/src/commands/setup/index.ts +13 -0
- package/src/commands/setup/openclaw.test.ts +124 -0
- package/src/commands/setup/openclaw.ts +162 -0
- package/src/commands/skill.ts +128 -0
- package/src/commands/state.ts +46 -0
- package/src/commands/strategy.test.ts +172 -0
- package/src/commands/strategy.ts +170 -0
- package/src/commands/upgrade.test.ts +82 -0
- package/src/commands/upgrade.ts +157 -0
- package/src/commands/watch.test.ts +1313 -0
- package/src/commands/watch.ts +824 -0
- package/src/lib/account-guidance.test.ts +32 -0
- package/src/lib/account-guidance.ts +62 -0
- package/src/lib/auth.test.ts +116 -0
- package/src/lib/auth.ts +189 -0
- package/src/lib/command-meta.ts +37 -0
- package/src/lib/competition.ts +79 -0
- package/src/lib/custom-tts.test.ts +387 -0
- package/src/lib/custom-tts.ts +463 -0
- package/src/lib/game-client-tts.test.ts +151 -0
- package/src/lib/game-client.test.ts +82 -0
- package/src/lib/game-client.ts +472 -0
- package/src/lib/game-context.ts +92 -0
- package/src/lib/host-config-patcher.test.ts +130 -0
- package/src/lib/host-config-patcher.ts +151 -0
- package/src/lib/http-keepalive.ts +15 -0
- package/src/lib/http-transport.test.ts +61 -0
- package/src/lib/http-transport.ts +118 -0
- package/src/lib/hub-client.test.ts +57 -0
- package/src/lib/hub-client.ts +88 -0
- package/src/lib/hub-install.test.ts +157 -0
- package/src/lib/hub-install.ts +213 -0
- package/src/lib/hub-reminder.ts +69 -0
- package/src/lib/hub-unzip.test.ts +69 -0
- package/src/lib/hub-unzip.ts +62 -0
- package/src/lib/init-command.test.ts +79 -0
- package/src/lib/init-command.ts +136 -0
- package/src/lib/knowledge-store.test.ts +170 -0
- package/src/lib/knowledge-store.ts +369 -0
- package/src/lib/load-context.test.ts +62 -0
- package/src/lib/load-context.ts +49 -0
- package/src/lib/match-state.test.ts +134 -0
- package/src/lib/match-state.ts +94 -0
- package/src/lib/normalize.ts +42 -0
- package/src/lib/persona.test.ts +84 -0
- package/src/lib/persona.ts +120 -0
- package/src/lib/room.test.ts +74 -0
- package/src/lib/room.ts +129 -0
- package/src/lib/server-registry.test.ts +54 -0
- package/src/lib/server-registry.ts +185 -0
- package/src/lib/skill-version.test.ts +48 -0
- package/src/lib/skill-version.ts +19 -0
- package/src/lib/strategy-export.test.ts +314 -0
- package/src/lib/strategy-export.ts +352 -0
- package/src/lib/user-data.test.ts +98 -0
- package/src/lib/user-data.ts +370 -0
- package/src/lib/workspace-argv.test.ts +49 -0
- package/src/lib/workspace-argv.ts +44 -0
- package/src/perception/player-history-store.test.ts +177 -0
- package/src/perception/player-history-store.ts +262 -0
- package/src/pipeline/event-format.test.ts +327 -0
- package/src/pipeline/event-format.ts +595 -0
- package/src/pipeline/event-hints.ts +204 -0
- package/src/pipeline/event-store.test.ts +28 -0
- package/src/pipeline/event-store.ts +193 -0
- package/src/pipeline/pipeline.ts +35 -0
- package/src/pipeline/player-projection.test.ts +168 -0
- package/src/pipeline/player-projection.ts +370 -0
- package/src/runtime/auto-upgrade.test.ts +66 -0
- package/src/runtime/auto-upgrade.ts +31 -0
- package/src/runtime/event-daemon.test.ts +268 -0
- package/src/runtime/event-daemon.ts +531 -0
- package/src/runtime/owner-control.ts +150 -0
- package/src/runtime/raw-ws-log.test.ts +33 -0
- package/src/runtime/raw-ws-log.ts +32 -0
- package/src/runtime/room-lobby-runtime.test.ts +95 -0
- package/src/runtime/room-lobby-runtime.ts +367 -0
- package/src/runtime/runtime-logger.ts +107 -0
- package/src/runtime/ws-client.test.ts +169 -0
- package/src/runtime/ws-client.ts +280 -0
- package/src/sdk/action.ts +155 -0
- package/src/sdk/index.ts +112 -0
- package/src/sdk/types.ts +163 -0
- package/src/strategies/avoid-lone.ts +14 -0
- package/src/strategies/avoid-players.knowledge.md +19 -0
- package/src/strategies/avoid-players.ts +18 -0
- package/src/strategies/corpse-patrol.ts +21 -0
- package/src/strategies/crab-sabotage.ts +24 -0
- package/src/strategies/custom-module.test.ts +270 -0
- package/src/strategies/find-player.ts +19 -0
- package/src/strategies/game-utils.test.ts +242 -0
- package/src/strategies/game-utils.ts +853 -0
- package/src/strategies/goals/anchor-linger.ts +77 -0
- package/src/strategies/goals/avoid-lone-top.ts +168 -0
- package/src/strategies/goals/avoid-players-top.test.ts +83 -0
- package/src/strategies/goals/avoid-players-top.ts +121 -0
- package/src/strategies/goals/conversation-goal.ts +51 -0
- package/src/strategies/goals/corpse-patrol-top.ts +113 -0
- package/src/strategies/goals/crab-octopus-reflexes.ts +101 -0
- package/src/strategies/goals/crab-sabotage-top.ts +226 -0
- package/src/strategies/goals/emergency-hunt-goal.ts +28 -0
- package/src/strategies/goals/find-player-top.ts +93 -0
- package/src/strategies/goals/flee-players-goal.ts +53 -0
- package/src/strategies/goals/follow-companion-goal.ts +106 -0
- package/src/strategies/goals/goal-manager.ts +41 -0
- package/src/strategies/goals/goal-root-strategy.ts +49 -0
- package/src/strategies/goals/goal.ts +28 -0
- package/src/strategies/goals/hide-top.ts +197 -0
- package/src/strategies/goals/keep-away-goal.ts +221 -0
- package/src/strategies/goals/kill-frenzy-top.ts +80 -0
- package/src/strategies/goals/kill-lone-top.ts +160 -0
- package/src/strategies/goals/kill-target-goal.ts +59 -0
- package/src/strategies/goals/kill-target-top.ts +109 -0
- package/src/strategies/goals/leaf-goal.ts +27 -0
- package/src/strategies/goals/linger-corpse-goal.ts +35 -0
- package/src/strategies/goals/lone-kill-core.ts +82 -0
- package/src/strategies/goals/lone-kill-goal.ts +24 -0
- package/src/strategies/goals/lone-kill-task-top.test.ts +85 -0
- package/src/strategies/goals/lone-kill-task-top.ts +133 -0
- package/src/strategies/goals/move-room-goal.ts +60 -0
- package/src/strategies/goals/normal-shrimp-top.test.ts +97 -0
- package/src/strategies/goals/normal-shrimp-top.ts +248 -0
- package/src/strategies/goals/paradise-fish-top.test.ts +126 -0
- package/src/strategies/goals/paradise-fish-top.ts +224 -0
- package/src/strategies/goals/patrol-top.ts +57 -0
- package/src/strategies/goals/report-patrol-top.ts +86 -0
- package/src/strategies/goals/safe-task-goal.ts +102 -0
- package/src/strategies/goals/social-task-top.ts +161 -0
- package/src/strategies/goals/task-kill-report-top.ts +163 -0
- package/src/strategies/goals/task-only-top.ts +57 -0
- package/src/strategies/goals/task-or-patrol-goal.ts +41 -0
- package/src/strategies/goals/task-report-top.ts +57 -0
- package/src/strategies/goals/wander-task-goal.ts +33 -0
- package/src/strategies/goals/warrior-shrimp-top.test.ts +87 -0
- package/src/strategies/goals/warrior-shrimp-top.ts +267 -0
- package/src/strategies/greeting.ts +53 -0
- package/src/strategies/hide-spots.ts +59 -0
- package/src/strategies/hide.ts +26 -0
- package/src/strategies/kill-frenzy.ts +15 -0
- package/src/strategies/kill-lone.knowledge.md +17 -0
- package/src/strategies/kill-lone.ts +16 -0
- package/src/strategies/kill-target.ts +21 -0
- package/src/strategies/knowledge-contract.ts +85 -0
- package/src/strategies/loader.test.ts +710 -0
- package/src/strategies/loader.ts +183 -0
- package/src/strategies/lone-kill-task.ts +24 -0
- package/src/strategies/meeting-gate.test.ts +59 -0
- package/src/strategies/meeting-gate.ts +28 -0
- package/src/strategies/move-room.ts +18 -0
- package/src/strategies/new-events-backfill.ts +98 -0
- package/src/strategies/off-route-points.ts +105 -0
- package/src/strategies/paradise-fish.knowledge.md +19 -0
- package/src/strategies/paradise-fish.ts +24 -0
- package/src/strategies/pathfind/clawclaw-walkable.bin +0 -0
- package/src/strategies/pathfind/distance-field.ts +150 -0
- package/src/strategies/pathfind/escape-planner.test.ts +197 -0
- package/src/strategies/pathfind/escape-planner.ts +355 -0
- package/src/strategies/pathfind/walkable-grid.ts +117 -0
- package/src/strategies/patrol.ts +14 -0
- package/src/strategies/player-targets.ts +13 -0
- package/src/strategies/report-patrol.ts +14 -0
- package/src/strategies/scanner.ts +238 -0
- package/src/strategies/shrimp-memory.knowledge.md +19 -0
- package/src/strategies/shrimp-memory.ts +24 -0
- package/src/strategies/social-task.test.ts +28 -0
- package/src/strategies/social-task.ts +52 -0
- package/src/strategies/spawn.ts +82 -0
- package/src/strategies/speech-module.ts +123 -0
- package/src/strategies/strategy-loop.test.ts +15 -0
- package/src/strategies/strategy-loop.ts +748 -0
- package/src/strategies/task-kill-report.ts +20 -0
- package/src/strategies/task-only.ts +14 -0
- package/src/strategies/task-report.ts +21 -0
- package/src/strategies/types.ts +155 -0
- package/src/strategies/warrior-memory.knowledge.md +21 -0
- package/src/strategies/warrior-memory.ts +19 -0
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
// src/lib/strategy-export.test.ts
|
|
2
|
+
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
|
3
|
+
import { existsSync, mkdirSync, writeFileSync, rmSync, readFileSync } from 'fs';
|
|
4
|
+
import { join } from 'path';
|
|
5
|
+
import { tmpdir } from 'os';
|
|
6
|
+
import {
|
|
7
|
+
rewriteBuiltinImports,
|
|
8
|
+
exportStrategy,
|
|
9
|
+
detectStaleOfficialStrategies,
|
|
10
|
+
hasUserStrategyCustomization,
|
|
11
|
+
readManifest,
|
|
12
|
+
syncOfficialStrategies,
|
|
13
|
+
} from './strategy-export.js';
|
|
14
|
+
|
|
15
|
+
describe('strategy-export', () => {
|
|
16
|
+
let testWorkspace: string;
|
|
17
|
+
let originalEnv: string | undefined;
|
|
18
|
+
|
|
19
|
+
beforeEach(() => {
|
|
20
|
+
testWorkspace = join(tmpdir(), `ccl-test-${Date.now()}`);
|
|
21
|
+
mkdirSync(testWorkspace, { recursive: true });
|
|
22
|
+
originalEnv = process.env.CLAWCLAW_WORKSPACE_DIR;
|
|
23
|
+
process.env.CLAWCLAW_WORKSPACE_DIR = testWorkspace;
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
afterEach(() => {
|
|
27
|
+
if (originalEnv !== undefined) {
|
|
28
|
+
process.env.CLAWCLAW_WORKSPACE_DIR = originalEnv;
|
|
29
|
+
} else {
|
|
30
|
+
delete process.env.CLAWCLAW_WORKSPACE_DIR;
|
|
31
|
+
}
|
|
32
|
+
rmSync(testWorkspace, { recursive: true, force: true });
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
function userStrategiesDir(): string {
|
|
36
|
+
return join(testWorkspace, 'user-data', 'strategies');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function officialManifestFile(): string {
|
|
40
|
+
return join(userStrategiesDir(), '.official-manifest.json');
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
describe('rewriteBuiltinImports', () => {
|
|
44
|
+
it('should rewrite ALL relative imports to @myclaw163/clawclaw-cli', () => {
|
|
45
|
+
const source = `
|
|
46
|
+
import type { GameState } from '../sdk/types.js';
|
|
47
|
+
import { Action } from '../sdk/action.js';
|
|
48
|
+
import { dist, killCommitRange } from './game-utils.js';
|
|
49
|
+
import { GoalRootStrategy } from './goals/goal-root-strategy.js';
|
|
50
|
+
import { TaskOnlyTop } from './goals/task-only-top.js';
|
|
51
|
+
import { parseGreetingArgs } from './greeting.js';
|
|
52
|
+
import { GREETING_TEXT_MAX_LENGTH } from '../strategies/greeting.js';
|
|
53
|
+
|
|
54
|
+
export const strategy = { id: 'test', description: 'test', create: () => ({ name: 'test', decide: () => [] }) };
|
|
55
|
+
`;
|
|
56
|
+
const rewritten = rewriteBuiltinImports(source, 'test', '0.6.31');
|
|
57
|
+
|
|
58
|
+
expect(rewritten).toContain('// Exported from test@0.6.31');
|
|
59
|
+
// All relative imports should be rewritten
|
|
60
|
+
expect(rewritten).not.toContain("'../sdk/types.js'");
|
|
61
|
+
expect(rewritten).not.toContain("'../sdk/action.js'");
|
|
62
|
+
expect(rewritten).not.toContain("'./game-utils.js'");
|
|
63
|
+
expect(rewritten).not.toContain("'./goals/goal-root-strategy.js'");
|
|
64
|
+
expect(rewritten).not.toContain("'./goals/task-only-top.js'");
|
|
65
|
+
expect(rewritten).not.toContain("'./greeting.js'");
|
|
66
|
+
expect(rewritten).not.toContain("'../strategies/greeting.js'");
|
|
67
|
+
// Verify rewritten imports use @myclaw163/clawclaw-cli
|
|
68
|
+
expect(rewritten).toContain("from '@myclaw163/clawclaw-cli'");
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it('should preserve user imports from clawclaw-cli', () => {
|
|
72
|
+
const source = `
|
|
73
|
+
import { Action } from 'clawclaw-cli';
|
|
74
|
+
import type { GameState } from '../sdk/types.js';
|
|
75
|
+
|
|
76
|
+
export const strategy = { id: 'test', description: 'test', create: () => ({ name: 'test', decide: () => [] }) };
|
|
77
|
+
`;
|
|
78
|
+
const rewritten = rewriteBuiltinImports(source, 'test', '0.6.31');
|
|
79
|
+
expect(rewritten).toContain("import { Action } from 'clawclaw-cli'");
|
|
80
|
+
expect(rewritten).toContain("from 'clawclaw-cli'");
|
|
81
|
+
});
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
describe('exportStrategy', () => {
|
|
85
|
+
it('should export a formerly goal-based strategy with its knowledge sidecar', async () => {
|
|
86
|
+
await exportStrategy('kill-lone');
|
|
87
|
+
|
|
88
|
+
const strategiesDir = userStrategiesDir();
|
|
89
|
+
expect(existsSync(join(strategiesDir, 'kill-lone.ts'))).toBe(true);
|
|
90
|
+
expect(existsSync(join(strategiesDir, 'kill-lone.knowledge.md'))).toBe(true);
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it('should export a valid strategy', async () => {
|
|
94
|
+
await exportStrategy('task-only');
|
|
95
|
+
|
|
96
|
+
const strategyFile = join(userStrategiesDir(), 'task-only.ts');
|
|
97
|
+
const manifestFile = officialManifestFile();
|
|
98
|
+
|
|
99
|
+
expect(existsSync(strategyFile)).toBe(true);
|
|
100
|
+
expect(existsSync(manifestFile)).toBe(true);
|
|
101
|
+
|
|
102
|
+
const strategy = readFileSync(strategyFile, 'utf8');
|
|
103
|
+
expect(strategy).toContain('// Exported from task-only@');
|
|
104
|
+
expect(strategy).toContain("from '@myclaw163/clawclaw-cli'");
|
|
105
|
+
|
|
106
|
+
const manifest = readManifest();
|
|
107
|
+
expect(manifest['task-only']).toBeDefined();
|
|
108
|
+
expect(manifest['task-only'].sourceHash).toBeDefined();
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
it('should reject strategy with unexported SDK symbol', async () => {
|
|
112
|
+
// Create a fake builtin strategy that imports a symbol not in the SDK
|
|
113
|
+
const fakeDir = join(testWorkspace, 'fake-builtin');
|
|
114
|
+
mkdirSync(fakeDir, { recursive: true });
|
|
115
|
+
const fakeFile = join(fakeDir, 'broken-strategy.ts');
|
|
116
|
+
writeFileSync(fakeFile, `
|
|
117
|
+
import { TotallyMissingSymbol } from 'clawclaw-cli';
|
|
118
|
+
export const strategy = {
|
|
119
|
+
id: 'broken-strategy',
|
|
120
|
+
description: 'test',
|
|
121
|
+
create: () => ({ name: 'broken', decide: () => [TotallyMissingSymbol] }),
|
|
122
|
+
};
|
|
123
|
+
`, 'utf8');
|
|
124
|
+
|
|
125
|
+
// Temporarily override locateBuiltinSource to point to our fake
|
|
126
|
+
const { rewriteBuiltinImports } = await import('./strategy-export.js');
|
|
127
|
+
const rewritten = rewriteBuiltinImports(
|
|
128
|
+
readFileSync(fakeFile, 'utf8'),
|
|
129
|
+
'broken-strategy',
|
|
130
|
+
'0.0.0'
|
|
131
|
+
);
|
|
132
|
+
|
|
133
|
+
// Validate should catch the missing symbol
|
|
134
|
+
const { validateExportable } = await import('./strategy-export.js') as any;
|
|
135
|
+
if (typeof validateExportable === 'function') {
|
|
136
|
+
const result = await validateExportable(rewritten);
|
|
137
|
+
expect(result.ok).toBe(false);
|
|
138
|
+
expect(result.error).toBeDefined();
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
it('should refuse to overwrite untracked files without --force', async () => {
|
|
143
|
+
const strategiesDir = userStrategiesDir();
|
|
144
|
+
mkdirSync(strategiesDir, { recursive: true });
|
|
145
|
+
writeFileSync(join(strategiesDir, 'task-only.ts'), '// user file', 'utf8');
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
await expect(exportStrategy('task-only')).rejects.toThrow(
|
|
149
|
+
'already exists and is not tracked. Use --force to overwrite.'
|
|
150
|
+
);
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
it('should overwrite untracked files with --force', async () => {
|
|
154
|
+
const strategiesDir = userStrategiesDir();
|
|
155
|
+
mkdirSync(strategiesDir, { recursive: true });
|
|
156
|
+
writeFileSync(join(strategiesDir, 'task-only.ts'), '// user file', 'utf8');
|
|
157
|
+
|
|
158
|
+
await exportStrategy('task-only', { force: true });
|
|
159
|
+
|
|
160
|
+
const strategy = readFileSync(join(strategiesDir, 'task-only.ts'), 'utf8');
|
|
161
|
+
expect(strategy).toContain('// Exported from task-only@');
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
it('should preserve modified tracked strategies without --force', async () => {
|
|
165
|
+
// First export
|
|
166
|
+
await exportStrategy('task-only');
|
|
167
|
+
|
|
168
|
+
const strategiesDir = userStrategiesDir();
|
|
169
|
+
const strategyFile = join(strategiesDir, 'task-only.ts');
|
|
170
|
+
|
|
171
|
+
// Modify the file
|
|
172
|
+
writeFileSync(strategyFile, '// user customized', 'utf8');
|
|
173
|
+
|
|
174
|
+
await expect(exportStrategy('task-only')).rejects.toThrow('was modified');
|
|
175
|
+
expect(readFileSync(strategyFile, 'utf8')).toBe('// user customized');
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
it('should reject non-existent strategies', async () => {
|
|
179
|
+
await expect(exportStrategy('non-existent-strategy')).rejects.toThrow(
|
|
180
|
+
"Built-in strategy 'non-existent-strategy' not found."
|
|
181
|
+
);
|
|
182
|
+
});
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
describe('syncOfficialStrategies', () => {
|
|
186
|
+
it('copies every bundled strategy into the shared user strategy directory', async () => {
|
|
187
|
+
const result = await syncOfficialStrategies();
|
|
188
|
+
|
|
189
|
+
expect(result.added).toHaveLength(20);
|
|
190
|
+
expect(existsSync(join(userStrategiesDir(), 'task-only.ts'))).toBe(true);
|
|
191
|
+
expect(existsSync(join(userStrategiesDir(), 'warrior-memory.knowledge.md'))).toBe(true);
|
|
192
|
+
expect(Object.keys(readManifest())).toHaveLength(20);
|
|
193
|
+
expect(hasUserStrategyCustomization()).toBe(false);
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
it('preserves modified, deleted, and unrelated custom strategies', async () => {
|
|
197
|
+
await syncOfficialStrategies();
|
|
198
|
+
const taskOnly = join(userStrategiesDir(), 'task-only.ts');
|
|
199
|
+
const patrol = join(userStrategiesDir(), 'patrol.ts');
|
|
200
|
+
writeFileSync(taskOnly, '// player customized', 'utf8');
|
|
201
|
+
rmSync(patrol, { force: true });
|
|
202
|
+
writeFileSync(join(userStrategiesDir(), 'my-custom.ts'), 'export const strategy = {};', 'utf8');
|
|
203
|
+
|
|
204
|
+
const result = await syncOfficialStrategies();
|
|
205
|
+
|
|
206
|
+
expect(result.preservedModified).toContain('task-only');
|
|
207
|
+
expect(result.preservedDeleted).toContain('patrol');
|
|
208
|
+
expect(readFileSync(taskOnly, 'utf8')).toBe('// player customized');
|
|
209
|
+
expect(existsSync(patrol)).toBe(false);
|
|
210
|
+
expect(readFileSync(join(userStrategiesDir(), 'my-custom.ts'), 'utf8')).toContain('strategy');
|
|
211
|
+
expect(hasUserStrategyCustomization()).toBe(true);
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
it('updates an unmodified official strategy when its recorded source baseline is stale', async () => {
|
|
215
|
+
await exportStrategy('task-only');
|
|
216
|
+
const manifestFile = officialManifestFile();
|
|
217
|
+
const manifest = JSON.parse(readFileSync(manifestFile, 'utf8'));
|
|
218
|
+
manifest['task-only'].sourceHash = 'previous-official-source';
|
|
219
|
+
writeFileSync(manifestFile, JSON.stringify(manifest, null, 2), 'utf8');
|
|
220
|
+
|
|
221
|
+
const result = await syncOfficialStrategies({ ids: ['task-only'] });
|
|
222
|
+
|
|
223
|
+
expect(result.updated).toEqual(['task-only']);
|
|
224
|
+
expect(readManifest()['task-only'].sourceHash).not.toBe('previous-official-source');
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
it('keeps a customized official strategy when a newer official baseline exists', async () => {
|
|
228
|
+
await exportStrategy('task-only');
|
|
229
|
+
const manifestFile = officialManifestFile();
|
|
230
|
+
const manifest = JSON.parse(readFileSync(manifestFile, 'utf8'));
|
|
231
|
+
manifest['task-only'].sourceHash = 'previous-official-source';
|
|
232
|
+
writeFileSync(manifestFile, JSON.stringify(manifest, null, 2), 'utf8');
|
|
233
|
+
const strategyFile = join(userStrategiesDir(), 'task-only.ts');
|
|
234
|
+
writeFileSync(strategyFile, '// player customized', 'utf8');
|
|
235
|
+
|
|
236
|
+
const result = await syncOfficialStrategies({ ids: ['task-only'] });
|
|
237
|
+
|
|
238
|
+
expect(result.preservedModified).toEqual(['task-only']);
|
|
239
|
+
expect(readFileSync(strategyFile, 'utf8')).toBe('// player customized');
|
|
240
|
+
expect(detectStaleOfficialStrategies()).toContain('task-only');
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
it('loads a custom duplicate id after the tracked official file', async () => {
|
|
244
|
+
await syncOfficialStrategies();
|
|
245
|
+
writeFileSync(join(userStrategiesDir(), 'zz-custom-task.ts'), `
|
|
246
|
+
export const strategy = {
|
|
247
|
+
id: 'task-only',
|
|
248
|
+
name: '自定义任务',
|
|
249
|
+
description: 'custom override',
|
|
250
|
+
create: () => ({ name: 'custom-task', decide: () => [] }),
|
|
251
|
+
};
|
|
252
|
+
`, 'utf8');
|
|
253
|
+
const loader = await import('../strategies/loader.js');
|
|
254
|
+
await loader.reload();
|
|
255
|
+
|
|
256
|
+
expect((await loader.getStrategyEntry('task-only'))?.description).toBe('custom override');
|
|
257
|
+
});
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
describe('detectStaleOfficialStrategies', () => {
|
|
261
|
+
it('should return empty array when no strategies are exported', () => {
|
|
262
|
+
expect(detectStaleOfficialStrategies()).toEqual([]);
|
|
263
|
+
});
|
|
264
|
+
|
|
265
|
+
it('should return empty array when all strategies are up to date', async () => {
|
|
266
|
+
await exportStrategy('task-only');
|
|
267
|
+
expect(detectStaleOfficialStrategies()).toEqual([]);
|
|
268
|
+
});
|
|
269
|
+
|
|
270
|
+
it('should return stale IDs when source hash mismatch', async () => {
|
|
271
|
+
await exportStrategy('task-only');
|
|
272
|
+
|
|
273
|
+
// Manually modify the manifest to simulate a stale hash
|
|
274
|
+
const manifestFile = officialManifestFile();
|
|
275
|
+
const manifest = JSON.parse(readFileSync(manifestFile, 'utf8'));
|
|
276
|
+
manifest['task-only'].sourceHash = 'stale-hash-value';
|
|
277
|
+
writeFileSync(manifestFile, JSON.stringify(manifest, null, 2), 'utf8');
|
|
278
|
+
|
|
279
|
+
expect(detectStaleOfficialStrategies()).toEqual(['task-only']);
|
|
280
|
+
});
|
|
281
|
+
|
|
282
|
+
it('should return multiple stale IDs', async () => {
|
|
283
|
+
await exportStrategy('task-only');
|
|
284
|
+
await exportStrategy('kill-lone');
|
|
285
|
+
|
|
286
|
+
// Make both stale
|
|
287
|
+
const manifestFile = officialManifestFile();
|
|
288
|
+
const manifest = JSON.parse(readFileSync(manifestFile, 'utf8'));
|
|
289
|
+
manifest['task-only'].sourceHash = 'stale-1';
|
|
290
|
+
manifest['kill-lone'].sourceHash = 'stale-2';
|
|
291
|
+
writeFileSync(manifestFile, JSON.stringify(manifest, null, 2), 'utf8');
|
|
292
|
+
|
|
293
|
+
const stale = detectStaleOfficialStrategies();
|
|
294
|
+
expect(stale).toContain('task-only');
|
|
295
|
+
expect(stale).toContain('kill-lone');
|
|
296
|
+
expect(stale).toHaveLength(2);
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
it('should detect stale when sidecar hash changes', async () => {
|
|
300
|
+
await exportStrategy('kill-lone');
|
|
301
|
+
|
|
302
|
+
// Verify kill-lone has a sidecar hash (it has a .knowledge.md)
|
|
303
|
+
const manifestFile = officialManifestFile();
|
|
304
|
+
const manifest = JSON.parse(readFileSync(manifestFile, 'utf8'));
|
|
305
|
+
expect(manifest['kill-lone'].sidecarHash).toBeDefined();
|
|
306
|
+
|
|
307
|
+
// Make sidecar stale
|
|
308
|
+
manifest['kill-lone'].sidecarHash = 'stale-sidecar';
|
|
309
|
+
writeFileSync(manifestFile, JSON.stringify(manifest, null, 2), 'utf8');
|
|
310
|
+
|
|
311
|
+
expect(detectStaleOfficialStrategies()).toEqual(['kill-lone']);
|
|
312
|
+
});
|
|
313
|
+
});
|
|
314
|
+
});
|
|
@@ -0,0 +1,352 @@
|
|
|
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
|
+
readdirSync,
|
|
8
|
+
readFileSync,
|
|
9
|
+
renameSync,
|
|
10
|
+
rmSync,
|
|
11
|
+
writeFileSync,
|
|
12
|
+
} from 'fs';
|
|
13
|
+
import { basename, dirname, join } from 'path';
|
|
14
|
+
import { createHash } from 'crypto';
|
|
15
|
+
import { fileURLToPath } from 'url';
|
|
16
|
+
import { getWorkspaceDir } from './init-command.js';
|
|
17
|
+
import {
|
|
18
|
+
ensureUserDataLayout,
|
|
19
|
+
getUserDataOfficialStrategiesManifestFile,
|
|
20
|
+
getUserDataStrategiesDir,
|
|
21
|
+
} from './user-data.js';
|
|
22
|
+
import { inspectStrategySource } from '../strategies/scanner.js';
|
|
23
|
+
|
|
24
|
+
export interface ManifestEntry {
|
|
25
|
+
format?: 1;
|
|
26
|
+
version?: string;
|
|
27
|
+
sourceHash: string;
|
|
28
|
+
installedHash?: string;
|
|
29
|
+
sidecarHash?: string | null;
|
|
30
|
+
installedSidecarHash?: string | null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export type Manifest = Record<string, ManifestEntry>;
|
|
34
|
+
|
|
35
|
+
export interface OfficialStrategySyncResult {
|
|
36
|
+
added: string[];
|
|
37
|
+
updated: string[];
|
|
38
|
+
unchanged: string[];
|
|
39
|
+
preservedModified: string[];
|
|
40
|
+
preservedUntracked: string[];
|
|
41
|
+
preservedDeleted: string[];
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
interface BundledStrategySource {
|
|
45
|
+
id: string;
|
|
46
|
+
path: string;
|
|
47
|
+
source: string;
|
|
48
|
+
sourceHash: string;
|
|
49
|
+
sidecarPath: string;
|
|
50
|
+
sidecarContent?: string;
|
|
51
|
+
sidecarHash: string | null;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function strategiesDir(): string {
|
|
55
|
+
const workspaceDir = getWorkspaceDir();
|
|
56
|
+
ensureUserDataLayout(workspaceDir);
|
|
57
|
+
return getUserDataStrategiesDir(workspaceDir);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function manifestPath(): string {
|
|
61
|
+
return getUserDataOfficialStrategiesManifestFile(getWorkspaceDir());
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function builtinStrategiesDir(): string {
|
|
65
|
+
return join(dirname(fileURLToPath(import.meta.url)), '..', 'strategies');
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function hashContent(content: string | Buffer): string {
|
|
69
|
+
return createHash('sha256').update(content).digest('hex').slice(0, 16);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function writeAtomic(path: string, content: string): void {
|
|
73
|
+
const tmpPath = `${path}.tmp`;
|
|
74
|
+
writeFileSync(tmpPath, content, 'utf8');
|
|
75
|
+
try {
|
|
76
|
+
renameSync(tmpPath, path);
|
|
77
|
+
} catch (error) {
|
|
78
|
+
rmSync(tmpPath, { force: true });
|
|
79
|
+
throw error;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function readManifest(): Manifest {
|
|
84
|
+
const path = manifestPath();
|
|
85
|
+
if (!existsSync(path)) return {};
|
|
86
|
+
try {
|
|
87
|
+
const parsed = JSON.parse(readFileSync(path, 'utf8'));
|
|
88
|
+
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed as Manifest : {};
|
|
89
|
+
} catch {
|
|
90
|
+
return {};
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function writeManifest(manifest: Manifest): void {
|
|
95
|
+
mkdirSync(strategiesDir(), { recursive: true });
|
|
96
|
+
writeAtomic(manifestPath(), `${JSON.stringify(manifest, null, 2)}\n`);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function readPackageVersion(): string {
|
|
100
|
+
try {
|
|
101
|
+
const pkgPath = join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'package.json');
|
|
102
|
+
const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
|
|
103
|
+
return pkg.version ?? '0.0.0';
|
|
104
|
+
} catch {
|
|
105
|
+
return '0.0.0';
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function parseStrategyId(source: string, fileName: string): string | null {
|
|
110
|
+
const marker = source.search(/export\s+const\s+strategy\b/);
|
|
111
|
+
if (marker < 0) return null;
|
|
112
|
+
const match = source.slice(marker).match(/\bid\s*:\s*['"]([^'"]+)['"]/);
|
|
113
|
+
if (!match) throw new Error(`Bundled strategy has no literal id: ${fileName}`);
|
|
114
|
+
return match[1];
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function listBundledStrategySources(): BundledStrategySource[] {
|
|
118
|
+
const dir = builtinStrategiesDir();
|
|
119
|
+
const sources: BundledStrategySource[] = [];
|
|
120
|
+
for (const fileName of readdirSync(dir).sort()) {
|
|
121
|
+
if (!fileName.endsWith('.ts') || fileName.endsWith('.test.ts') || fileName.endsWith('.d.ts')) continue;
|
|
122
|
+
const path = join(dir, fileName);
|
|
123
|
+
const source = readFileSync(path, 'utf8');
|
|
124
|
+
const id = parseStrategyId(source, fileName);
|
|
125
|
+
if (!id) continue;
|
|
126
|
+
if (basename(fileName, '.ts') !== id) {
|
|
127
|
+
throw new Error(`Bundled strategy id '${id}' must match file name '${fileName}'.`);
|
|
128
|
+
}
|
|
129
|
+
const sidecarPath = path.replace(/\.ts$/, '.knowledge.md');
|
|
130
|
+
const sidecarContent = existsSync(sidecarPath) ? readFileSync(sidecarPath, 'utf8') : undefined;
|
|
131
|
+
sources.push({
|
|
132
|
+
id,
|
|
133
|
+
path,
|
|
134
|
+
source,
|
|
135
|
+
sourceHash: hashContent(source),
|
|
136
|
+
sidecarPath,
|
|
137
|
+
sidecarContent,
|
|
138
|
+
sidecarHash: sidecarContent === undefined ? null : hashContent(sidecarContent),
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
return sources;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function locateBundledStrategy(id: string): BundledStrategySource | undefined {
|
|
145
|
+
return listBundledStrategySources().find((source) => source.id === id);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function rewriteBuiltinImports(source: string, id: string, version: string): string {
|
|
149
|
+
const rewritten = source.replace(/from\s+['"]\.\.?\/[^'"]+['"]/g, `from '@myclaw163/clawclaw-cli'`);
|
|
150
|
+
return `// Exported from ${id}@${version} — customize freely\n${rewritten}`;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async function validateExportable(rewritten: string): Promise<{ ok: boolean; error?: string }> {
|
|
154
|
+
try {
|
|
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` };
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return { ok: true };
|
|
174
|
+
} catch (error: any) {
|
|
175
|
+
return { ok: false, error: error?.message ?? String(error) };
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
let sdkExportsCache: Set<string> | null = null;
|
|
180
|
+
|
|
181
|
+
async function getSdkExports(): Promise<Set<string>> {
|
|
182
|
+
if (sdkExportsCache) return sdkExportsCache;
|
|
183
|
+
const sdkPath = join(dirname(fileURLToPath(import.meta.url)), '..', 'sdk', 'index.ts');
|
|
184
|
+
const source = readFileSync(sdkPath, 'utf8');
|
|
185
|
+
const exports = new Set<string>();
|
|
186
|
+
const exportPattern = /export\s+(?:type\s+)?\{([^}]+)\}/g;
|
|
187
|
+
let match;
|
|
188
|
+
while ((match = exportPattern.exec(source)) !== null) {
|
|
189
|
+
const names = match[1]
|
|
190
|
+
.split(',')
|
|
191
|
+
.map((name) => name.trim().replace(/^type\s+/, '').replace(/\s+as\s+.*$/, '').trim())
|
|
192
|
+
.filter(Boolean);
|
|
193
|
+
for (const name of names) exports.add(name);
|
|
194
|
+
}
|
|
195
|
+
sdkExportsCache = exports;
|
|
196
|
+
return exports;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function pairIsUnmodified(id: string, entry: ManifestEntry): boolean {
|
|
200
|
+
if (entry.format !== 1 || !entry.installedHash || entry.installedSidecarHash === undefined) return false;
|
|
201
|
+
const strategyFile = join(strategiesDir(), `${id}.ts`);
|
|
202
|
+
if (!existsSync(strategyFile)) return false;
|
|
203
|
+
if (hashContent(readFileSync(strategyFile)) !== entry.installedHash) return false;
|
|
204
|
+
|
|
205
|
+
const sidecarFile = join(strategiesDir(), `${id}.knowledge.md`);
|
|
206
|
+
if (entry.installedSidecarHash === null) return !existsSync(sidecarFile);
|
|
207
|
+
return existsSync(sidecarFile)
|
|
208
|
+
&& hashContent(readFileSync(sidecarFile)) === entry.installedSidecarHash;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function sourceMatchesManifest(source: BundledStrategySource, entry: ManifestEntry): boolean {
|
|
212
|
+
return entry.sourceHash === source.sourceHash
|
|
213
|
+
&& (entry.sidecarHash ?? null) === source.sidecarHash;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async function writeOfficialStrategy(source: BundledStrategySource, version: string): Promise<ManifestEntry> {
|
|
217
|
+
const rewritten = rewriteBuiltinImports(source.source, source.id, version);
|
|
218
|
+
const validation = await validateExportable(rewritten);
|
|
219
|
+
if (!validation.ok) throw new Error(`Validation failed for '${source.id}': ${validation.error}`);
|
|
220
|
+
|
|
221
|
+
mkdirSync(strategiesDir(), { recursive: true });
|
|
222
|
+
writeAtomic(join(strategiesDir(), `${source.id}.ts`), rewritten);
|
|
223
|
+
const sidecarFile = join(strategiesDir(), `${source.id}.knowledge.md`);
|
|
224
|
+
if (source.sidecarContent === undefined) {
|
|
225
|
+
rmSync(sidecarFile, { force: true });
|
|
226
|
+
} else {
|
|
227
|
+
writeAtomic(sidecarFile, source.sidecarContent);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
return {
|
|
231
|
+
format: 1,
|
|
232
|
+
version,
|
|
233
|
+
sourceHash: source.sourceHash,
|
|
234
|
+
installedHash: hashContent(rewritten),
|
|
235
|
+
sidecarHash: source.sidecarHash,
|
|
236
|
+
installedSidecarHash: source.sidecarHash,
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
export async function syncOfficialStrategies(options: { ids?: string[]; force?: boolean } = {}): Promise<OfficialStrategySyncResult> {
|
|
241
|
+
const selectedIds = options.ids ? new Set(options.ids) : null;
|
|
242
|
+
const allSources = listBundledStrategySources();
|
|
243
|
+
const sources = selectedIds ? allSources.filter((source) => selectedIds.has(source.id)) : allSources;
|
|
244
|
+
if (selectedIds) {
|
|
245
|
+
const found = new Set(sources.map((source) => source.id));
|
|
246
|
+
const missing = [...selectedIds].filter((id) => !found.has(id));
|
|
247
|
+
if (missing.length > 0) throw new Error(`Built-in strategy '${missing[0]}' not found.`);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const result: OfficialStrategySyncResult = {
|
|
251
|
+
added: [],
|
|
252
|
+
updated: [],
|
|
253
|
+
unchanged: [],
|
|
254
|
+
preservedModified: [],
|
|
255
|
+
preservedUntracked: [],
|
|
256
|
+
preservedDeleted: [],
|
|
257
|
+
};
|
|
258
|
+
const manifest = readManifest();
|
|
259
|
+
const version = readPackageVersion();
|
|
260
|
+
|
|
261
|
+
for (const source of sources) {
|
|
262
|
+
const strategyFile = join(strategiesDir(), `${source.id}.ts`);
|
|
263
|
+
const exists = existsSync(strategyFile);
|
|
264
|
+
const entry = manifest[source.id];
|
|
265
|
+
|
|
266
|
+
if (options.force) {
|
|
267
|
+
manifest[source.id] = await writeOfficialStrategy(source, version);
|
|
268
|
+
writeManifest(manifest);
|
|
269
|
+
(exists ? result.updated : result.added).push(source.id);
|
|
270
|
+
continue;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
if (!entry) {
|
|
274
|
+
if (exists) {
|
|
275
|
+
result.preservedUntracked.push(source.id);
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
manifest[source.id] = await writeOfficialStrategy(source, version);
|
|
279
|
+
writeManifest(manifest);
|
|
280
|
+
result.added.push(source.id);
|
|
281
|
+
continue;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
if (!exists) {
|
|
285
|
+
result.preservedDeleted.push(source.id);
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
288
|
+
if (!pairIsUnmodified(source.id, entry)) {
|
|
289
|
+
result.preservedModified.push(source.id);
|
|
290
|
+
continue;
|
|
291
|
+
}
|
|
292
|
+
if (sourceMatchesManifest(source, entry)) {
|
|
293
|
+
result.unchanged.push(source.id);
|
|
294
|
+
continue;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
manifest[source.id] = await writeOfficialStrategy(source, version);
|
|
298
|
+
writeManifest(manifest);
|
|
299
|
+
result.updated.push(source.id);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
return result;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
export async function exportStrategy(id: string, { force = false } = {}): Promise<void> {
|
|
306
|
+
const source = locateBundledStrategy(id);
|
|
307
|
+
if (!source) throw new Error(`Built-in strategy '${id}' not found.`);
|
|
308
|
+
const result = await syncOfficialStrategies({ ids: [id], force });
|
|
309
|
+
if (result.preservedUntracked.includes(id)) {
|
|
310
|
+
throw new Error(`${join(strategiesDir(), `${id}.ts`)} already exists and is not tracked. Use --force to overwrite.`);
|
|
311
|
+
}
|
|
312
|
+
if (result.preservedModified.includes(id)) {
|
|
313
|
+
throw new Error(`${join(strategiesDir(), `${id}.ts`)} was modified. Use --force to overwrite.`);
|
|
314
|
+
}
|
|
315
|
+
if (result.preservedDeleted.includes(id)) {
|
|
316
|
+
throw new Error(`${join(strategiesDir(), `${id}.ts`)} was deleted after export. Use --force to restore.`);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
export function detectStaleOfficialStrategies(): string[] {
|
|
321
|
+
const manifest = readManifest();
|
|
322
|
+
const sources = new Map(listBundledStrategySources().map((source) => [source.id, source]));
|
|
323
|
+
const stale: string[] = [];
|
|
324
|
+
for (const [id, entry] of Object.entries(manifest)) {
|
|
325
|
+
const source = sources.get(id);
|
|
326
|
+
if (!source || !sourceMatchesManifest(source, entry)) stale.push(id);
|
|
327
|
+
}
|
|
328
|
+
return stale;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
export function hasUserStrategyCustomization(): boolean {
|
|
332
|
+
const dir = strategiesDir();
|
|
333
|
+
const manifest = readManifest();
|
|
334
|
+
let files: string[];
|
|
335
|
+
try {
|
|
336
|
+
files = readdirSync(dir);
|
|
337
|
+
} catch {
|
|
338
|
+
return false;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
for (const file of files) {
|
|
342
|
+
if (file.startsWith('_')) continue;
|
|
343
|
+
if (!/\.(?:ts|tsx|js)$/.test(file) || file.endsWith('.d.ts') || file.endsWith('.test.ts')) continue;
|
|
344
|
+
const id = file.endsWith('.ts') ? basename(file, '.ts') : '';
|
|
345
|
+
if (!id || !manifest[id] || file !== `${id}.ts`) return true;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
for (const [id, entry] of Object.entries(manifest)) {
|
|
349
|
+
if (!pairIsUnmodified(id, entry)) return true;
|
|
350
|
+
}
|
|
351
|
+
return false;
|
|
352
|
+
}
|