@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,134 @@
|
|
|
1
|
+
// src/commands/hub.test.ts
|
|
2
|
+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
|
3
|
+
import { existsSync, mkdtempSync, rmSync } from 'fs';
|
|
4
|
+
import { tmpdir } from 'os';
|
|
5
|
+
import { join } from 'path';
|
|
6
|
+
import { createHubCommand } from './hub.js';
|
|
7
|
+
import type { ResourceListResult, ResourceDetail } from '../lib/hub-client.js';
|
|
8
|
+
|
|
9
|
+
const STRATEGY_ARTIFACT = `export const strategy = {
|
|
10
|
+
id: 'hub-kill',
|
|
11
|
+
name: '抢刀',
|
|
12
|
+
description: '贴脸抢刀',
|
|
13
|
+
create: () => ({ name: 'hub-kill', decide: () => [] }),
|
|
14
|
+
};`;
|
|
15
|
+
|
|
16
|
+
let ws: string;
|
|
17
|
+
let logs: string[];
|
|
18
|
+
let errs: string[];
|
|
19
|
+
beforeEach(() => {
|
|
20
|
+
ws = mkdtempSync(join(tmpdir(), 'ccl-cmd-'));
|
|
21
|
+
process.env.CLAWCLAW_WORKSPACE_DIR = ws;
|
|
22
|
+
logs = []; errs = [];
|
|
23
|
+
vi.spyOn(console, 'log').mockImplementation((...a) => { logs.push(a.join(' ')); });
|
|
24
|
+
vi.spyOn(console, 'error').mockImplementation((...a) => { errs.push(a.join(' ')); });
|
|
25
|
+
});
|
|
26
|
+
afterEach(() => {
|
|
27
|
+
delete process.env.CLAWCLAW_WORKSPACE_DIR;
|
|
28
|
+
vi.restoreAllMocks();
|
|
29
|
+
rmSync(ws, { recursive: true, force: true });
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
function fakeClient(over: any = {}) {
|
|
33
|
+
return {
|
|
34
|
+
list: vi.fn(async (): Promise<ResourceListResult> => ({
|
|
35
|
+
items: [{
|
|
36
|
+
id: 'ab12', type: 'strategy', title: 'Aggressive Kill', description: '贴脸抢刀',
|
|
37
|
+
creator: 'alice', creatorType: 'clawkey', creatorDisplayName: 'Alice', creatorAvatarUrl: null,
|
|
38
|
+
fileName: 'kill.ts', stats: { downloadCount: 42, starCount: 7, commentCount: 0 },
|
|
39
|
+
downloadUrl: '/dl', likedByMe: false, createdAt: '', updatedAt: '',
|
|
40
|
+
}], total: 1,
|
|
41
|
+
pagination: { mode: 'page', page: 1, limit: 20, hasMore: false },
|
|
42
|
+
})),
|
|
43
|
+
getResource: vi.fn(async (): Promise<ResourceDetail> => ({
|
|
44
|
+
id: 'ab12', type: 'strategy', title: 'Aggressive Kill', description: '贴脸抢刀',
|
|
45
|
+
creator: 'alice', creatorType: 'clawkey', creatorDisplayName: 'Alice', creatorAvatarUrl: null,
|
|
46
|
+
fileName: 'kill.ts', stats: { downloadCount: 42, starCount: 7, commentCount: 0 },
|
|
47
|
+
downloadUrl: '/dl', likedByMe: false, createdAt: '', updatedAt: '',
|
|
48
|
+
artifact: { fileName: 'kill.ts', downloadUrl: '/dl' },
|
|
49
|
+
})),
|
|
50
|
+
downloadArtifact: vi.fn(async () => Buffer.from(STRATEGY_ARTIFACT)),
|
|
51
|
+
...over,
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function run(client: any, argv: string[]) {
|
|
56
|
+
const cmd = createHubCommand({ clientFactory: () => client as any });
|
|
57
|
+
await cmd.parseAsync(['node', 'ccl', ...argv]);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
describe('hub search', () => {
|
|
61
|
+
it('emits JSON with --json', async () => {
|
|
62
|
+
const c = fakeClient();
|
|
63
|
+
await run(c, ['search', '抢刀', '--type', 'strategy', '--json']);
|
|
64
|
+
expect(c.list).toHaveBeenCalledWith(expect.objectContaining({ q: '抢刀', type: 'strategy' }));
|
|
65
|
+
const out = JSON.parse(logs.join('\n'));
|
|
66
|
+
expect(out.items[0].id).toBe('ab12');
|
|
67
|
+
expect(out.items[0].type).toBe('strategy');
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
describe('hub info', () => {
|
|
72
|
+
it('prints the copy-paste install command', async () => {
|
|
73
|
+
await run(fakeClient(), ['info', 'strategy/ab12']);
|
|
74
|
+
expect(logs.join('\n')).toContain('ccl hub install strategy/ab12');
|
|
75
|
+
});
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
describe('hub install', () => {
|
|
79
|
+
it('downloads + places the package and prints the path', async () => {
|
|
80
|
+
await run(fakeClient(), ['install', 'strategy/ab12']);
|
|
81
|
+
const out = logs.join('\n');
|
|
82
|
+
expect(out).toMatch(/strategies[\\/]aggressive-kill__ab12\.ts/);
|
|
83
|
+
});
|
|
84
|
+
it('emits JSON with --json', async () => {
|
|
85
|
+
await run(fakeClient(), ['install', 'strategy/ab12', '--json']);
|
|
86
|
+
const out = JSON.parse(logs.join('\n'));
|
|
87
|
+
expect(out.ref).toBe('strategy/ab12');
|
|
88
|
+
expect(out.installedPath).toMatch(/strategies[\\/]aggressive-kill__ab12\.ts/);
|
|
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
|
+
});
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
describe('hub installed / uninstall', () => {
|
|
107
|
+
it('lists then removes an installed package', async () => {
|
|
108
|
+
await run(fakeClient(), ['install', 'strategy/ab12']);
|
|
109
|
+
logs.length = 0;
|
|
110
|
+
await run(fakeClient(), ['installed', '--json']);
|
|
111
|
+
const listed = JSON.parse(logs.join('\n'));
|
|
112
|
+
expect(listed.items.map((e: any) => e.type + '/' + e.id)).toContain('strategy/ab12');
|
|
113
|
+
logs.length = 0;
|
|
114
|
+
await run(fakeClient(), ['uninstall', 'strategy/ab12']);
|
|
115
|
+
expect(logs.join('\n')).toMatch(/Removed strategy\/ab12/);
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
it('installs persona and prints persona use hint', async () => {
|
|
119
|
+
const c = fakeClient({
|
|
120
|
+
getResource: vi.fn(async (): Promise<ResourceDetail> => ({
|
|
121
|
+
id: 'p1', type: 'persona', title: 'My Persona', description: 'A persona',
|
|
122
|
+
creator: 'alice', creatorType: 'clawkey', creatorDisplayName: 'Alice', creatorAvatarUrl: null,
|
|
123
|
+
fileName: 'my-persona.md', stats: { downloadCount: 1, starCount: 0, commentCount: 0 },
|
|
124
|
+
downloadUrl: '/dl', likedByMe: false, createdAt: '', updatedAt: '',
|
|
125
|
+
artifact: { fileName: 'my-persona.md', downloadUrl: '/dl' },
|
|
126
|
+
})),
|
|
127
|
+
downloadArtifact: vi.fn(async () => Buffer.from('# persona')),
|
|
128
|
+
});
|
|
129
|
+
await run(c, ['install', 'persona/p1']);
|
|
130
|
+
const out = logs.join('\n');
|
|
131
|
+
expect(out).toMatch(/personas[\\/]my-persona\.md/);
|
|
132
|
+
expect(out).toContain('ccl persona use my-persona');
|
|
133
|
+
});
|
|
134
|
+
});
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
// src/commands/hub.ts
|
|
2
|
+
import { Command } from 'commander';
|
|
3
|
+
import { spawnSync } from 'child_process';
|
|
4
|
+
import { existsSync, readdirSync, statSync } from 'fs';
|
|
5
|
+
import { join } from 'path';
|
|
6
|
+
import { createRequire } from 'module';
|
|
7
|
+
import { ApiError, formatApiError } from '../lib/http-transport.js';
|
|
8
|
+
import { HubClient, parseResourceRef } from '../lib/hub-client.js';
|
|
9
|
+
import type { ListOptions } from '../lib/hub-client.js';
|
|
10
|
+
import { installResource, uninstallResource, listInstalled, readLockfile } from '../lib/hub-install.js';
|
|
11
|
+
import { getWorkspaceDir } from '../lib/init-command.js';
|
|
12
|
+
import { inspectStrategySource } from '../strategies/scanner.js';
|
|
13
|
+
|
|
14
|
+
const require = createRequire(import.meta.url);
|
|
15
|
+
|
|
16
|
+
export interface HubCommandDeps {
|
|
17
|
+
clientFactory?: () => HubClient;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function getClient(deps: HubCommandDeps): HubClient {
|
|
21
|
+
return (deps.clientFactory ?? (() => HubClient.fromAuth()))();
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function fail(payload: Record<string, unknown>): never {
|
|
25
|
+
console.error(JSON.stringify(payload, null, 2));
|
|
26
|
+
process.exit(1);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function handleError(err: unknown): never {
|
|
30
|
+
if (err instanceof ApiError) {
|
|
31
|
+
fail({ error: 'api_error', status: err.status, message: formatApiError(err) });
|
|
32
|
+
}
|
|
33
|
+
fail({ error: 'hub_error', message: (err as any)?.message ?? String(err) });
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Find the real skill root: if SKILL.md is not at root but a single subdirectory contains it, use that. */
|
|
37
|
+
function findSkillRoot(absPath: string): string {
|
|
38
|
+
if (existsSync(join(absPath, 'SKILL.md'))) return absPath;
|
|
39
|
+
let entries: string[];
|
|
40
|
+
try { entries = readdirSync(absPath); } catch { return absPath; }
|
|
41
|
+
const dirs = entries.filter(e => {
|
|
42
|
+
try { return statSync(join(absPath, e)).isDirectory() && !e.startsWith('.'); } catch { return false; }
|
|
43
|
+
});
|
|
44
|
+
if (dirs.length === 1 && existsSync(join(absPath, dirs[0], 'SKILL.md'))) {
|
|
45
|
+
return join(absPath, dirs[0]);
|
|
46
|
+
}
|
|
47
|
+
return absPath;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Best-effort skill registration via the skills CLI. Returns true on success; false means manual ccl skill install is needed. */
|
|
51
|
+
async function registerSkill(absPath: string): Promise<boolean> {
|
|
52
|
+
try {
|
|
53
|
+
const root = findSkillRoot(absPath);
|
|
54
|
+
// Guard against a hub skill overwriting the built-in clawclaw skill.
|
|
55
|
+
const { readSkillName } = await import('./skill.js');
|
|
56
|
+
if (readSkillName(root) === 'clawclaw') {
|
|
57
|
+
console.error('warning: this skill is named "clawclaw" which would overwrite the built-in clawclaw skill; install manually if intended.');
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
const bin = require.resolve('skills/bin/cli.mjs');
|
|
61
|
+
const result = spawnSync(process.execPath, [bin, 'add', root, '-y', '-g'], {
|
|
62
|
+
stdio: 'pipe',
|
|
63
|
+
timeout: 30_000,
|
|
64
|
+
});
|
|
65
|
+
// Forward CLI output to stderr so --json stdout stays clean.
|
|
66
|
+
if (result.stdout?.length) process.stderr.write(result.stdout);
|
|
67
|
+
if (result.stderr?.length) process.stderr.write(result.stderr);
|
|
68
|
+
return result.status === 0 && !result.error;
|
|
69
|
+
} catch {
|
|
70
|
+
return false;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function createHubCommand(deps: HubCommandDeps = {}): Command {
|
|
75
|
+
const hub = new Command('hub').description('Browse and install ClawClaw strategies, skills, and personas from clawclawhub');
|
|
76
|
+
|
|
77
|
+
// search
|
|
78
|
+
hub.command('search [query]')
|
|
79
|
+
.description('Search/browse the hub (no query = top packages)')
|
|
80
|
+
.option('--type <type>', 'skill | strategy | persona')
|
|
81
|
+
.option('--sort <sort>', 'latest | downloads | stars', 'latest')
|
|
82
|
+
.option('--limit <n>', 'max results', '20')
|
|
83
|
+
.option('--page <n>', 'page number', '1')
|
|
84
|
+
.option('--json', 'machine-readable output')
|
|
85
|
+
.action(async (query: string | undefined, opts: any) => {
|
|
86
|
+
try {
|
|
87
|
+
const search: ListOptions = {
|
|
88
|
+
q: query,
|
|
89
|
+
type: opts.type,
|
|
90
|
+
sort: opts.sort,
|
|
91
|
+
limit: Number(opts.limit),
|
|
92
|
+
page: Number(opts.page),
|
|
93
|
+
};
|
|
94
|
+
const res = await getClient(deps).list(search);
|
|
95
|
+
if (opts.json) {
|
|
96
|
+
console.log(JSON.stringify(res, null, 2));
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
if (res.items.length === 0) {
|
|
100
|
+
console.log('No packages found.');
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
for (const p of res.items) {
|
|
104
|
+
const isStrategy = p.type === 'strategy';
|
|
105
|
+
const code = isStrategy ? ' ⚠code' : '';
|
|
106
|
+
console.log(p.type + '/' + p.id + ' [' + p.type + code + '] ↓' + p.stats.downloadCount + ' ★' + p.stats.starCount);
|
|
107
|
+
console.log(' ' + p.title + ' — ' + p.description);
|
|
108
|
+
if (p.creatorDisplayName) console.log(' by ' + p.creatorDisplayName + ' (' + p.creator + ')');
|
|
109
|
+
}
|
|
110
|
+
console.log('\n' + res.items.length + ' of ' + res.total + '. Install: ccl hub install <type>/<id>');
|
|
111
|
+
} catch (err) { handleError(err); }
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
// info
|
|
115
|
+
hub.command('info <type/id>')
|
|
116
|
+
.description('Show package detail and the install command')
|
|
117
|
+
.option('--json', 'machine-readable output')
|
|
118
|
+
.action(async (ref: string, opts: any) => {
|
|
119
|
+
try {
|
|
120
|
+
const { type, id } = parseResourceRef(ref);
|
|
121
|
+
const d = await getClient(deps).getResource(type, id);
|
|
122
|
+
if (opts.json) {
|
|
123
|
+
console.log(JSON.stringify(d, null, 2));
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
const codeStr = d.type === 'strategy' ? ' ⚠code' : '';
|
|
127
|
+
console.log(d.type + '/' + d.id + ' [' + d.type + codeStr + '] ↓' + d.stats.downloadCount + ' ★' + d.stats.starCount);
|
|
128
|
+
console.log(d.title);
|
|
129
|
+
console.log(d.description);
|
|
130
|
+
if (d.creatorDisplayName) console.log('by ' + d.creatorDisplayName + ' (' + d.creator + ')');
|
|
131
|
+
if (d.fileName) console.log('file: ' + d.fileName);
|
|
132
|
+
if (d.type === 'strategy') console.log('⚠ contains executable code — source: ' + (d.creatorDisplayName || d.creator));
|
|
133
|
+
console.log('\nInstall: ccl hub install ' + d.type + '/' + d.id);
|
|
134
|
+
} catch (err) { handleError(err); }
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
// install
|
|
138
|
+
hub.command('install <type/id>')
|
|
139
|
+
.description('Download and install a package (strategy -> user-data/strategies/, skill -> skills/, persona -> personas/)')
|
|
140
|
+
.option('--force', 'overwrite an existing untracked file/dir')
|
|
141
|
+
.option('--json', 'machine-readable output')
|
|
142
|
+
.action(async (raw: string, opts: any) => {
|
|
143
|
+
try {
|
|
144
|
+
const { type, id } = parseResourceRef(raw);
|
|
145
|
+
const client = getClient(deps);
|
|
146
|
+
const detail = await client.getResource(type, id);
|
|
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
|
+
}
|
|
154
|
+
const res = installResource(detail, artifact, { force: opts.force });
|
|
155
|
+
// Reload the static strategy catalog so the new file is picked up immediately.
|
|
156
|
+
let strategyId: string | undefined;
|
|
157
|
+
if (res.type === 'strategy') {
|
|
158
|
+
const { reload } = await import('../strategies/loader.js');
|
|
159
|
+
await reload();
|
|
160
|
+
strategyId = strategySummary?.id;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// For skills: auto-register with the agent via `ccl skill install`.
|
|
164
|
+
let skillRegistered = false;
|
|
165
|
+
if (res.type === 'skill') {
|
|
166
|
+
skillRegistered = await registerSkill(res.installedPath);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// For personas: extract the preset name (filename minus .md) for the ccl persona use hint.
|
|
170
|
+
let personaSlug: string | undefined;
|
|
171
|
+
if (res.type === 'persona') {
|
|
172
|
+
const m = res.installedPath.match(/(?:^|[\\/])personas[\\/]([^/\\]+)\.md$/);
|
|
173
|
+
personaSlug = m ? m[1] : undefined;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
if (opts.json) {
|
|
177
|
+
console.log(JSON.stringify({ ...res, strategyId: strategyId ?? null, skillRegistered, personaSlug: personaSlug ?? null }, null, 2));
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
console.log('Installed ' + res.ref + ' "' + res.title + '" [' + res.type + ']');
|
|
181
|
+
console.log(' → ' + res.installedPath);
|
|
182
|
+
if (strategyId) {
|
|
183
|
+
console.log('Run with: ccl strategy ' + strategyId);
|
|
184
|
+
} else if (res.type === 'strategy') {
|
|
185
|
+
console.log('Run with: ccl strategy <id> (see: ccl strategy --list)');
|
|
186
|
+
}
|
|
187
|
+
if (skillRegistered) {
|
|
188
|
+
console.log('Skill registered with agent.');
|
|
189
|
+
} else if (res.type === 'skill') {
|
|
190
|
+
console.log('Register manually: ccl skill install ' + res.installedPath);
|
|
191
|
+
}
|
|
192
|
+
if (personaSlug) {
|
|
193
|
+
console.log('Apply with: ccl persona use ' + personaSlug);
|
|
194
|
+
}
|
|
195
|
+
} catch (err) { handleError(err); }
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
// uninstall
|
|
199
|
+
hub.command('uninstall <type/id>')
|
|
200
|
+
.description('Remove a hub-installed package')
|
|
201
|
+
.action(async (ref: string) => {
|
|
202
|
+
try {
|
|
203
|
+
// For skills: auto-unregister from the agent before deleting files.
|
|
204
|
+
const { type } = parseResourceRef(ref);
|
|
205
|
+
if (type === 'skill') {
|
|
206
|
+
const lock = readLockfile();
|
|
207
|
+
const entry = lock[ref];
|
|
208
|
+
if (entry) {
|
|
209
|
+
const { readSkillName } = await import('./skill.js');
|
|
210
|
+
const skillDir = join(getWorkspaceDir(), entry.path);
|
|
211
|
+
const name = readSkillName(skillDir);
|
|
212
|
+
if (name) {
|
|
213
|
+
const bin = require.resolve('skills/bin/cli.mjs');
|
|
214
|
+
const r2 = spawnSync(process.execPath, [bin, 'remove', name, '-y', '-g'], { timeout: 30_000 });
|
|
215
|
+
if (r2.status !== 0 || r2.error) {
|
|
216
|
+
console.error('warning: skills remove failed (status=' + (r2.status ?? 'error') + '); files will still be deleted');
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const r = uninstallResource(ref);
|
|
223
|
+
if (!r.removed) { console.log(ref + ' is not installed.'); return; }
|
|
224
|
+
// Reload the strategy map so the removed strategy disappears immediately.
|
|
225
|
+
if (type === 'strategy') {
|
|
226
|
+
const { reload } = await import('../strategies/loader.js');
|
|
227
|
+
await reload();
|
|
228
|
+
}
|
|
229
|
+
console.log('Removed ' + ref + '\n → ' + r.path);
|
|
230
|
+
} catch (err) { handleError(err); }
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
// installed
|
|
234
|
+
hub.command('installed')
|
|
235
|
+
.description('List locally installed hub packages')
|
|
236
|
+
.option('--type <type>', 'filter: skill | strategy | persona')
|
|
237
|
+
.option('--json', 'machine-readable output')
|
|
238
|
+
.action(async (opts: any) => {
|
|
239
|
+
try {
|
|
240
|
+
let items = listInstalled();
|
|
241
|
+
if (opts.type) items = items.filter(e => e.type === opts.type);
|
|
242
|
+
if (opts.json) { console.log(JSON.stringify({ items }, null, 2)); return; }
|
|
243
|
+
if (items.length === 0) { console.log('No hub packages installed' + (opts.type ? ' for type "' + opts.type + '"' : '') + '.'); return; }
|
|
244
|
+
for (const e of items) console.log(e.type + '/' + e.id + ' "' + e.title + '" [' + e.type + '] ' + e.path);
|
|
245
|
+
} catch (err) { handleError(err); }
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
return hub;
|
|
249
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { normalizePlayerMark } from './knowledge.js';
|
|
3
|
+
|
|
4
|
+
describe('knowledge player marks', () => {
|
|
5
|
+
it('accepts only the two canonical mark names', () => {
|
|
6
|
+
expect(normalizePlayerMark('hostile')).toBe('hostile');
|
|
7
|
+
expect(normalizePlayerMark('trusted')).toBe('trusted');
|
|
8
|
+
// suspect 不再是可设标记:未标记 = 默认被怀疑。
|
|
9
|
+
expect(normalizePlayerMark('suspect')).toBeNull();
|
|
10
|
+
expect(normalizePlayerMark('impostor')).toBeNull();
|
|
11
|
+
expect(normalizePlayerMark('avoid')).toBeNull();
|
|
12
|
+
});
|
|
13
|
+
});
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { Command } from 'commander';
|
|
2
|
+
import { DROPPED_PLAYER_MARK_TAGS, KnowledgeStore, type KnowledgeSetInput, type PlayerMark } from '../lib/knowledge-store.js';
|
|
3
|
+
import { AuthStore } from '../lib/auth.js';
|
|
4
|
+
import { getProfileStateDir } from '../lib/init-command.js';
|
|
5
|
+
import { sendOwnerControlRequest } from '../runtime/owner-control.js';
|
|
6
|
+
|
|
7
|
+
// 玩家只标两档:hostile(坏人)/ trusted(好人)。未标记的默认「被怀疑」,无需也无法显式标。
|
|
8
|
+
const PLAYER_MARKS = new Set<PlayerMark>(['hostile', 'trusted']);
|
|
9
|
+
const LEGACY_MARK_TAGS = ['kill_if_armed', 'cleared', 'protected', 'do_not_kill'];
|
|
10
|
+
|
|
11
|
+
export function normalizePlayerMark(mark?: string): PlayerMark | null {
|
|
12
|
+
const normalized = mark?.trim().toLowerCase() as PlayerMark | undefined;
|
|
13
|
+
return normalized && PLAYER_MARKS.has(normalized) ? normalized : null;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** "true"/"false"/数字 自动转类型,其余按字符串。 */
|
|
17
|
+
function coerceValue(raw: string | undefined): unknown {
|
|
18
|
+
if (raw == null) return true;
|
|
19
|
+
if (raw === 'true') return true;
|
|
20
|
+
if (raw === 'false') return false;
|
|
21
|
+
if (raw !== '' && !Number.isNaN(Number(raw))) return Number(raw);
|
|
22
|
+
return raw;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function collectTag(value: string, prev: string[]): string[] {
|
|
26
|
+
return [...prev, value];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function print(data: unknown): void {
|
|
30
|
+
console.log(JSON.stringify(data, null, 2));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function fail(error: string, message: string): never {
|
|
34
|
+
console.error(JSON.stringify({ error, message }, null, 2));
|
|
35
|
+
process.exit(1);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function setPlayerMark(store: KnowledgeStore, player: string, mark: PlayerMark, opts: { note?: string }) {
|
|
39
|
+
const removeTags = [
|
|
40
|
+
...[...PLAYER_MARKS].filter(candidate => candidate !== mark),
|
|
41
|
+
...LEGACY_MARK_TAGS,
|
|
42
|
+
...DROPPED_PLAYER_MARK_TAGS, // 顺手清掉旧数据残留的 suspect/avoid raw tag,别再从 get/subject() 漏出去
|
|
43
|
+
];
|
|
44
|
+
return store.set({
|
|
45
|
+
type: 'player',
|
|
46
|
+
selector: player,
|
|
47
|
+
tags: [mark],
|
|
48
|
+
removeTags,
|
|
49
|
+
note: opts.note,
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** 通过 owner-control snapshot 拿当前正在运行的策略 id;无 owner / 未在跑策略时返回 null。 */
|
|
54
|
+
async function currentStrategyId(): Promise<string | null> {
|
|
55
|
+
try {
|
|
56
|
+
const profile = new AuthStore().getActive();
|
|
57
|
+
if (!profile) return null;
|
|
58
|
+
const res = await sendOwnerControlRequest(getProfileStateDir(profile), 'snapshot');
|
|
59
|
+
const strategy = res?.summary?.automation?.strategy;
|
|
60
|
+
return typeof strategy === 'string' ? strategy : null;
|
|
61
|
+
} catch {
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* 按当前策略校验一条待写入知识。校验不通过返回 warning 文本(写入照常发生,只提示玩家
|
|
68
|
+
* 这条对当前策略无效);通过、拿不到当前策略 / 策略未实现校验、或校验器抛错时返回 undefined(放行)。
|
|
69
|
+
*/
|
|
70
|
+
async function knowledgeWarning(input: KnowledgeSetInput): Promise<string | undefined> {
|
|
71
|
+
const id = await currentStrategyId();
|
|
72
|
+
if (!id) return undefined;
|
|
73
|
+
const { getStrategyEntry } = await import('../strategies/loader.js');
|
|
74
|
+
const entry = await getStrategyEntry(id);
|
|
75
|
+
if (!entry?.validateKnowledge) return undefined;
|
|
76
|
+
try {
|
|
77
|
+
const result = entry.validateKnowledge(input);
|
|
78
|
+
return result.ok ? undefined : (result.message ?? `当前策略「${entry.name ?? id}」不会使用这条知识。`);
|
|
79
|
+
} catch {
|
|
80
|
+
// 用户策略的校验器抛错不能阻断写入(契约:ok:false 时写入照常发生),视为放行,与 reviewKnowledge 的容错一致。
|
|
81
|
+
return undefined;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function createKnowledgeCommand(): Command {
|
|
86
|
+
const cmd = new Command('knowledge')
|
|
87
|
+
.alias('kn')
|
|
88
|
+
.description('Per-game structured knowledge that a running strategy can query (no restart needed)');
|
|
89
|
+
|
|
90
|
+
cmd
|
|
91
|
+
.command('set [type] [selector] [key] [value]', { hidden: true })
|
|
92
|
+
.description('Advanced: upsert arbitrary facts/tags. Use `knowledge mark` for player strategy behavior.')
|
|
93
|
+
.option('--tag <tag>', 'Custom tag, repeatable', collectTag, [])
|
|
94
|
+
.option('--note <text>', 'Free-text reason')
|
|
95
|
+
.option('--json <json>', 'Provide the whole input object as JSON instead of positional args')
|
|
96
|
+
.action(async (type: string | undefined, selector: string | undefined, key: string | undefined, value: string | undefined, opts: {
|
|
97
|
+
tag: string[]; note?: string; json?: string;
|
|
98
|
+
}) => {
|
|
99
|
+
try {
|
|
100
|
+
const store = KnowledgeStore.forActiveAccount();
|
|
101
|
+
let input: KnowledgeSetInput;
|
|
102
|
+
if (opts.json) {
|
|
103
|
+
input = JSON.parse(opts.json) as KnowledgeSetInput;
|
|
104
|
+
} else {
|
|
105
|
+
if (!type || !selector) {
|
|
106
|
+
fail('missing_args', 'Usage: ccl knowledge set <type> <selector> [key] [value] [--tag ...] — or: ccl knowledge set --json "{...}"');
|
|
107
|
+
}
|
|
108
|
+
input = {
|
|
109
|
+
type,
|
|
110
|
+
selector,
|
|
111
|
+
key,
|
|
112
|
+
value: key != null ? coerceValue(value) : undefined,
|
|
113
|
+
tags: opts.tag.length > 0 ? opts.tag : undefined,
|
|
114
|
+
note: opts.note,
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
const warning = await knowledgeWarning(input);
|
|
118
|
+
const entry = store.set(input);
|
|
119
|
+
print({ ok: !warning, gameId: store.gameId ?? null, subject: entry, ...(warning ? { warning } : {}) });
|
|
120
|
+
} catch (e) {
|
|
121
|
+
fail('knowledge_set_failed', e instanceof Error ? e.message : String(e));
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
cmd
|
|
126
|
+
.command('mark <player> <mark>')
|
|
127
|
+
.description('Set the strategy mark for a player: hostile | trusted (unmarked players are suspected by default)')
|
|
128
|
+
.option('--note <text>', 'Free-text reason')
|
|
129
|
+
.action(async (player: string, rawMark: string, opts: { note?: string }) => {
|
|
130
|
+
const mark = normalizePlayerMark(rawMark);
|
|
131
|
+
if (!mark) fail('invalid_mark', `Unknown mark '${rawMark}'. Use: hostile | trusted. (Unmarked = suspected by default.)`);
|
|
132
|
+
try {
|
|
133
|
+
const store = KnowledgeStore.forActiveAccount();
|
|
134
|
+
const warning = await knowledgeWarning({ type: 'player', selector: player, tags: [mark] });
|
|
135
|
+
const entry = setPlayerMark(store, player, mark, opts);
|
|
136
|
+
print({ ok: !warning, gameId: store.gameId ?? null, mark, subject: entry, ...(warning ? { warning } : {}) });
|
|
137
|
+
} catch (e) {
|
|
138
|
+
fail('knowledge_mark_failed', e instanceof Error ? e.message : String(e));
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
cmd
|
|
143
|
+
.command('get [type] [selector]')
|
|
144
|
+
.description('Read knowledge: all, all of a type, or one subject')
|
|
145
|
+
.action((type: string | undefined, selector: string | undefined) => {
|
|
146
|
+
const store = KnowledgeStore.forActiveAccount();
|
|
147
|
+
const file = store.list();
|
|
148
|
+
if (type && selector) {
|
|
149
|
+
print({ gameId: file.gameId ?? null, subject: file.subjects[`${type}:${selector}`] ?? null });
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
const subjects = Object.values(file.subjects).filter((s) => !type || s.type === type);
|
|
153
|
+
print({ gameId: file.gameId ?? null, count: subjects.length, subjects });
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
cmd
|
|
157
|
+
.command('del <type> <selector> [key]')
|
|
158
|
+
.description('Delete a subject, or just one fact (key) / tag (--tag)')
|
|
159
|
+
.option('--tag <tag>', 'Delete only this tag')
|
|
160
|
+
.action((type: string, selector: string, key: string | undefined, opts: { tag?: string }) => {
|
|
161
|
+
const store = KnowledgeStore.forActiveAccount();
|
|
162
|
+
const removed = store.del(type, selector, { key, tag: opts.tag });
|
|
163
|
+
print({ ok: removed, gameId: store.gameId ?? null });
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
cmd
|
|
167
|
+
.command('clear')
|
|
168
|
+
.description('Clear all knowledge for the current game')
|
|
169
|
+
.action(() => {
|
|
170
|
+
const store = KnowledgeStore.forActiveAccount();
|
|
171
|
+
store.clear();
|
|
172
|
+
print({ ok: true, gameId: store.gameId ?? null });
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
return cmd;
|
|
176
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs';
|
|
3
|
+
import { tmpdir } from 'os';
|
|
4
|
+
import { join } from 'path';
|
|
5
|
+
|
|
6
|
+
vi.mock('../lib/load-context.js', () => ({
|
|
7
|
+
loadContext: vi.fn(() => ({ persona: { exists: true }, memory: { exists: false } })),
|
|
8
|
+
}));
|
|
9
|
+
|
|
10
|
+
vi.mock('../runtime/auto-upgrade.js', () => ({
|
|
11
|
+
runAutoUpgradeOnLoad: vi.fn(),
|
|
12
|
+
}));
|
|
13
|
+
|
|
14
|
+
import { runAutoUpgradeOnLoad } from '../runtime/auto-upgrade.js';
|
|
15
|
+
import { noAccountMessage } from '../lib/account-guidance.js';
|
|
16
|
+
import { loadContext } from '../lib/load-context.js';
|
|
17
|
+
import { createLoadCommand } from './load.js';
|
|
18
|
+
|
|
19
|
+
describe('load command', () => {
|
|
20
|
+
let logSpy: ReturnType<typeof vi.spyOn>;
|
|
21
|
+
let errorSpy: ReturnType<typeof vi.spyOn>;
|
|
22
|
+
let workspaceDir: string;
|
|
23
|
+
let oldWorkspaceDir: string | undefined;
|
|
24
|
+
|
|
25
|
+
beforeEach(() => {
|
|
26
|
+
workspaceDir = mkdtempSync(join(tmpdir(), 'ccl-load-command-'));
|
|
27
|
+
oldWorkspaceDir = process.env.CLAWCLAW_WORKSPACE_DIR;
|
|
28
|
+
process.env.CLAWCLAW_WORKSPACE_DIR = workspaceDir;
|
|
29
|
+
vi.mocked(runAutoUpgradeOnLoad).mockClear();
|
|
30
|
+
vi.mocked(loadContext).mockReset();
|
|
31
|
+
vi.mocked(loadContext).mockReturnValue({ persona: { exists: true }, memory: { exists: false } } as any);
|
|
32
|
+
logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
|
|
33
|
+
errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
afterEach(() => {
|
|
37
|
+
if (oldWorkspaceDir === undefined) delete process.env.CLAWCLAW_WORKSPACE_DIR;
|
|
38
|
+
else process.env.CLAWCLAW_WORKSPACE_DIR = oldWorkspaceDir;
|
|
39
|
+
logSpy.mockRestore();
|
|
40
|
+
errorSpy.mockRestore();
|
|
41
|
+
rmSync(workspaceDir, { recursive: true, force: true });
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it('runs auto-upgrade check before printing JSON load context', async () => {
|
|
45
|
+
const cmd = createLoadCommand();
|
|
46
|
+
await cmd.parseAsync(['node', 'load'], { from: 'node' });
|
|
47
|
+
|
|
48
|
+
expect(runAutoUpgradeOnLoad).toHaveBeenCalledOnce();
|
|
49
|
+
expect(logSpy).toHaveBeenCalledOnce();
|
|
50
|
+
const output = JSON.parse(String(logSpy.mock.calls[0][0]));
|
|
51
|
+
expect(output).toMatchObject({
|
|
52
|
+
persona: { exists: true },
|
|
53
|
+
memory: { exists: false },
|
|
54
|
+
});
|
|
55
|
+
expect(output.strategies).toEqual(expect.arrayContaining([
|
|
56
|
+
expect.objectContaining({
|
|
57
|
+
id: 'task-only',
|
|
58
|
+
name: '纯任务',
|
|
59
|
+
description: expect.any(String),
|
|
60
|
+
}),
|
|
61
|
+
]));
|
|
62
|
+
expect(existsSync(join(workspaceDir, 'user-data', 'strategies', 'task-only.ts'))).toBe(true);
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it('routes auto-upgrade notifications to stderr', async () => {
|
|
66
|
+
vi.mocked(runAutoUpgradeOnLoad).mockImplementation(({ notify }: any) => {
|
|
67
|
+
notify('[clawclaw-cli] auto-upgrade installed 0.6.39');
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
const cmd = createLoadCommand();
|
|
71
|
+
await cmd.parseAsync(['node', 'load'], { from: 'node' });
|
|
72
|
+
|
|
73
|
+
expect(errorSpy).toHaveBeenCalledWith('[clawclaw-cli] auto-upgrade installed 0.6.39');
|
|
74
|
+
});
|
|
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
|
+
|
|
98
|
+
it('turns missing-account load errors into registration guidance', async () => {
|
|
99
|
+
vi.mocked(loadContext).mockImplementation(() => {
|
|
100
|
+
throw new Error('Not logged in.');
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
const cmd = createLoadCommand();
|
|
104
|
+
await expect(cmd.parseAsync(['node', 'load'], { from: 'node' }))
|
|
105
|
+
.rejects.toThrow(noAccountMessage('load'));
|
|
106
|
+
});
|
|
107
|
+
});
|