@myclaw163/clawclaw-cli 0.6.82 → 0.6.84

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.
Files changed (37) hide show
  1. package/README.md +4 -4
  2. package/package.json +1 -1
  3. package/personas//345/217/243/346/230/257/345/277/203/351/235/236.md +50 -0
  4. package/personas//345/277/240/345/277/203/350/200/201/344/273/206.md +51 -0
  5. package/personas//350/264/253/345/230/264/346/215/237/345/217/213.md +48 -0
  6. package/personas//350/275/257/350/220/214/350/205/271/351/273/221.md +51 -0
  7. package/skills/clawclaw/.gitkeep +0 -0
  8. package/skills/clawclaw/SKILL.md +9 -8
  9. package/skills/clawclaw/references/CLAUDE-CODE-MONITOR.md +1 -1
  10. package/skills/clawclaw/references/COMMANDS.md +2 -3
  11. package/skills/clawclaw/references/HUB.md +5 -5
  12. package/skills/clawclaw/references/STREAM.md +2 -2
  13. package/src/commands/game-start-plan.test.ts +10 -0
  14. package/src/commands/game.ts +33 -25
  15. package/src/commands/hub.test.ts +17 -0
  16. package/src/commands/hub.ts +15 -5
  17. package/src/commands/persona.ts +15 -10
  18. package/src/commands/watch.test.ts +42 -0
  19. package/src/commands/watch.ts +5 -1
  20. package/src/lib/game-client.test.ts +44 -0
  21. package/src/lib/game-client.ts +7 -2
  22. package/src/lib/http-transport.test.ts +19 -0
  23. package/src/lib/http-transport.ts +8 -3
  24. package/src/lib/hub-client.test.ts +1 -0
  25. package/src/lib/hub-client.ts +4 -4
  26. package/src/lib/hub-install.test.ts +39 -1
  27. package/src/lib/hub-install.ts +43 -5
  28. package/src/lib/persona.ts +32 -1
  29. package/src/pipeline/event-format.test.ts +4 -0
  30. package/src/pipeline/event-format.ts +7 -1
  31. package/src/runtime/event-daemon.test.ts +17 -1
  32. package/src/runtime/event-daemon.ts +8 -0
  33. package/personas//347/220/206/346/231/272/346/270/251/345/222/214.md +0 -23
  34. package/personas//350/200/201/350/260/213/346/267/261/347/256/227.md +0 -22
  35. package/personas//350/257/232/346/201/263/347/233/264/347/216/207.md +0 -22
  36. package/personas//350/275/273/346/235/276/346/264/273/346/263/274.md +0 -22
  37. package/personas//351/207/216/346/200/247/345/217/233/351/200/206.md +0 -23
@@ -71,12 +71,12 @@ async function registerSkill(absPath: string): Promise<boolean> {
71
71
  }
72
72
 
73
73
  export function createHubCommand(deps: HubCommandDeps = {}): Command {
74
- const hub = new Command('hub').description('Browse and install ClawClaw strategies and skills from clawclawhub');
74
+ const hub = new Command('hub').description('Browse and install ClawClaw strategies, skills, and personas from clawclawhub');
75
75
 
76
76
  // search
77
77
  hub.command('search [query]')
78
78
  .description('Search/browse the hub (no query = top packages)')
79
- .option('--type <type>', 'skill | strategy')
79
+ .option('--type <type>', 'skill | strategy | persona')
80
80
  .option('--sort <sort>', 'latest | downloads | stars', 'latest')
81
81
  .option('--limit <n>', 'max results', '20')
82
82
  .option('--page <n>', 'page number', '1')
@@ -135,7 +135,7 @@ export function createHubCommand(deps: HubCommandDeps = {}): Command {
135
135
 
136
136
  // install
137
137
  hub.command('install <type/id>')
138
- .description('Download and install a package (strategy -> user-data/strategies/, skill -> skills/)')
138
+ .description('Download and install a package (strategy -> user-data/strategies/, skill -> skills/, persona -> personas/)')
139
139
  .option('--force', 'overwrite an existing untracked file/dir')
140
140
  .option('--json', 'machine-readable output')
141
141
  .action(async (raw: string, opts: any) => {
@@ -161,8 +161,15 @@ export function createHubCommand(deps: HubCommandDeps = {}): Command {
161
161
  skillRegistered = await registerSkill(res.installedPath);
162
162
  }
163
163
 
164
+ // For personas: extract the preset name (filename minus .md) for the ccl persona use hint.
165
+ let personaSlug: string | undefined;
166
+ if (res.type === 'persona') {
167
+ const m = res.installedPath.match(/(?:^|[\\/])personas[\\/]([^/\\]+)\.md$/);
168
+ personaSlug = m ? m[1] : undefined;
169
+ }
170
+
164
171
  if (opts.json) {
165
- console.log(JSON.stringify({ ...res, strategyId: strategyId ?? null, skillRegistered }, null, 2));
172
+ console.log(JSON.stringify({ ...res, strategyId: strategyId ?? null, skillRegistered, personaSlug: personaSlug ?? null }, null, 2));
166
173
  return;
167
174
  }
168
175
  console.log('Installed ' + res.ref + ' "' + res.title + '" [' + res.type + ']');
@@ -177,6 +184,9 @@ export function createHubCommand(deps: HubCommandDeps = {}): Command {
177
184
  } else if (res.type === 'skill') {
178
185
  console.log('Register manually: ccl skill install ' + res.installedPath);
179
186
  }
187
+ if (personaSlug) {
188
+ console.log('Apply with: ccl persona use ' + personaSlug);
189
+ }
180
190
  } catch (err) { handleError(err); }
181
191
  });
182
192
 
@@ -218,7 +228,7 @@ export function createHubCommand(deps: HubCommandDeps = {}): Command {
218
228
  // installed
219
229
  hub.command('installed')
220
230
  .description('List locally installed hub packages')
221
- .option('--type <type>', 'filter: skill | strategy')
231
+ .option('--type <type>', 'filter: skill | strategy | persona')
222
232
  .option('--json', 'machine-readable output')
223
233
  .action(async (opts: any) => {
224
234
  try {
@@ -3,7 +3,10 @@ import {
3
3
  applyPersonaPreset,
4
4
  ensurePersonaFile,
5
5
  getActivePersonaFile,
6
- listPersonaPresets,
6
+ getBundledPersonaDir,
7
+ getWorkspacePersonaDir,
8
+ listAllPersonaPresets,
9
+ findPersonaPresetAnywhere,
7
10
  } from '../lib/persona.js';
8
11
  import { loadPersonaSnapshot } from '../lib/load-context.js';
9
12
 
@@ -15,9 +18,9 @@ export function createPersonaCommand(): Command {
15
18
 
16
19
  persona
17
20
  .command('list')
18
- .description('List bundled persona presets')
21
+ .description('List all persona presets (bundled and hub-installed)')
19
22
  .action(() => {
20
- const presets = listPersonaPresets().map(({ id, name }) => ({ id, name }));
23
+ const presets = listAllPersonaPresets().map(({ id, name, source }) => ({ id, name, source }));
21
24
  console.log(JSON.stringify({ presets }, null, 2));
22
25
  });
23
26
 
@@ -39,17 +42,19 @@ export function createPersonaCommand(): Command {
39
42
 
40
43
  persona
41
44
  .command('use <preset>')
42
- .description('Copy a bundled persona preset into the active account persona file')
45
+ .description('Copy a persona preset (hub-installed or bundled) into the active account persona file')
43
46
  .action((presetName: string) => {
44
47
  const path = getActivePersonaFile();
45
- const preset = applyPersonaPreset(presetName, path);
48
+ const found = findPersonaPresetAnywhere(presetName);
49
+ if (!found) {
50
+ const available = listAllPersonaPresets().map(p => p.name).join(', ') || 'none';
51
+ throw new Error(`Persona preset "${presetName}" not found. Available: ${available}`);
52
+ }
53
+ applyPersonaPreset(found.name, path, found.source === 'bundled' ? getBundledPersonaDir() : getWorkspacePersonaDir());
46
54
  console.log(JSON.stringify({
47
55
  path,
48
- preset: {
49
- id: preset.id,
50
- name: preset.name,
51
- },
52
- message: `Persona "${preset.name}" copied to active account.`,
56
+ preset: { id: found.id, name: found.name, source: found.source },
57
+ message: `Persona "${found.name}" (${found.source}) copied to active account.`,
53
58
  }, null, 2));
54
59
  });
55
60
 
@@ -494,6 +494,48 @@ describe('runStreaming — emission shape', () => {
494
494
  expect(obj.messages[0]).toContain('vote_speech_phase_ended');
495
495
  });
496
496
 
497
+ it('surfaces game_mode on game_started monitor output and message text', async () => {
498
+ const { feedPath, sessionPath } = makeTmpFiles();
499
+ writeFileSync(
500
+ feedPath,
501
+ JSON.stringify({
502
+ phase: 'wandering',
503
+ you: { name: 'me' },
504
+ urgent: {},
505
+ }),
506
+ );
507
+ const lines: string[] = [];
508
+ const ctrl = new AbortController();
509
+
510
+ const run = runStreaming({
511
+ feedPath,
512
+ sessionPath,
513
+ stdout: (s) => lines.push(s),
514
+ signal: ctrl.signal,
515
+ pollIntervalMs: 20,
516
+ });
517
+
518
+ appendFileSync(
519
+ sessionPath,
520
+ JSON.stringify({
521
+ type: 'game_started',
522
+ tick: 0,
523
+ player_count: 10,
524
+ game_mode: 'competition',
525
+ }) + '\n',
526
+ );
527
+
528
+ await new Promise((r) => setTimeout(r, 80));
529
+ ctrl.abort();
530
+ await run;
531
+
532
+ expect(lines.length).toBeGreaterThanOrEqual(1);
533
+ const obj = JSON.parse(lines[0]);
534
+ expect(obj.events).toContain('game_started');
535
+ expect(obj.game_mode).toBe('competition');
536
+ expect(obj.messages[0]).toContain('竞赛模式');
537
+ });
538
+
497
539
  it('expands nested new_events from action wrapper records', async () => {
498
540
  const { feedPath, sessionPath } = makeTmpFiles();
499
541
  writeFileSync(
@@ -442,9 +442,12 @@ export async function runStreaming(opts: RunStreamingOptions): Promise<void> {
442
442
  if (sumCaller && e.caller && sumCaller !== e.caller) return e;
443
443
  return { ...e, speech_order: so };
444
444
  };
445
- const sourceEvents = events.length > 0
445
+ const sourceEvents: GameEvent[] = events.length > 0
446
446
  ? sortEventsForMonitor(events).map(enrichMeetingBriefing)
447
447
  : triggers.map((type) => ({ type }));
448
+ const gameMode = sourceEvents.find(
449
+ (event) => event.game_mode === 'match' || event.game_mode === 'competition',
450
+ )?.game_mode;
448
451
  const context = {
449
452
  summary,
450
453
  seats: readSeatMapForMonitor(currentSessionPath),
@@ -452,6 +455,7 @@ export async function runStreaming(opts: RunStreamingOptions): Promise<void> {
452
455
  };
453
456
  return {
454
457
  events: sourceEvents.map((event) => event.type),
458
+ ...(gameMode ? { game_mode: gameMode } : {}),
455
459
  messages: sourceEvents.map((event) => formatEventMessage(event, context)),
456
460
  state: shortStateText(summary),
457
461
  };
@@ -0,0 +1,44 @@
1
+ // src/lib/game-client.test.ts
2
+ import { describe, it, expect, vi, afterEach } from 'vitest';
3
+ import { GameClient } from './game-client.js';
4
+
5
+ afterEach(() => { vi.restoreAllMocks(); });
6
+
7
+ function makeClient(): GameClient {
8
+ return new GameClient({ lobbyUrl: 'https://lobby.example', apiKey: 'key' });
9
+ }
10
+
11
+ describe('GameClient.joinQueue X-Agent-Type', () => {
12
+ it('sends X-Agent-Type header when agentType is provided', async () => {
13
+ let captured: any;
14
+ vi.stubGlobal('fetch', vi.fn(async (url: string, init: any) => {
15
+ captured = { url, headers: init.headers, body: init.body };
16
+ return new Response('{"status":"queued"}', { status: 200 });
17
+ }));
18
+ await makeClient().joinQueue({ gameType: 'clawclaw', mode: 'competition', agentType: 'claude-code' });
19
+ expect(captured.url).toBe('https://lobby.example/api/v1/queue/join');
20
+ expect(captured.headers['X-Agent-Type']).toBe('claude-code');
21
+ // mode still travels in the request body, not the header
22
+ expect(JSON.parse(captured.body)).toEqual({ game_type: 'clawclaw', mode: 'competition' });
23
+ });
24
+
25
+ it('omits X-Agent-Type header when agentType is absent', async () => {
26
+ let captured: any;
27
+ vi.stubGlobal('fetch', vi.fn(async (_url: string, init: any) => {
28
+ captured = init.headers;
29
+ return new Response('{"status":"queued"}', { status: 200 });
30
+ }));
31
+ await makeClient().joinQueue({ gameType: 'clawclaw', mode: 'match' });
32
+ expect('X-Agent-Type' in captured).toBe(false);
33
+ });
34
+
35
+ it('omits X-Agent-Type for the legacy string form', async () => {
36
+ let captured: any;
37
+ vi.stubGlobal('fetch', vi.fn(async (_url: string, init: any) => {
38
+ captured = init.headers;
39
+ return new Response('{"status":"queued"}', { status: 200 });
40
+ }));
41
+ await makeClient().joinQueue('clawclaw');
42
+ expect('X-Agent-Type' in captured).toBe(false);
43
+ });
44
+ });
@@ -160,10 +160,15 @@ export class GameClient {
160
160
 
161
161
 
162
162
 
163
- async joinQueue(options: string | { gameType?: string; mode?: QueueMode } = 'clawclaw'): Promise<any> {
163
+ async joinQueue(options: string | { gameType?: string; mode?: QueueMode; agentType?: string } = 'clawclaw'): Promise<any> {
164
164
  const gameType = typeof options === 'string' ? options : (options.gameType ?? 'clawclaw');
165
165
  const mode = typeof options === 'string' ? 'match' : (options.mode ?? 'match');
166
- const result = await this.http.post('/api/v1/queue/join', { game_type: gameType, mode });
166
+ const agentType = typeof options === 'string' ? undefined : options.agentType;
167
+ // X-Agent-Type reports the agent platform (e.g. claude-code, openclaw) and
168
+ // is only consumed by /queue/join, so it is attached per-request rather than
169
+ // to every call.
170
+ const headers = agentType ? { 'X-Agent-Type': agentType } : undefined;
171
+ const result = await this.http.post('/api/v1/queue/join', { game_type: gameType, mode }, headers);
167
172
  this.registry.updateFromQueueResponse(result);
168
173
  return result;
169
174
  }
@@ -40,3 +40,22 @@ describe('HttpTransport extraHeaders', () => {
40
40
  expect(captured['X-Hub-Auth-Type']).toBe('clawkey');
41
41
  });
42
42
  });
43
+
44
+ describe('HttpTransport per-request headers', () => {
45
+ it('merges per-request headers into request() headers', async () => {
46
+ let captured: any;
47
+ vi.stubGlobal('fetch', vi.fn(async (_url: string, init: any) => { captured = init.headers; return new Response('{}', { status: 200 }); }));
48
+ const t = new HttpTransport('key', registry);
49
+ await t.post('/api/v1/queue/join', { game_type: 'clawclaw' }, { 'X-Agent-Type': 'claude-code' });
50
+ expect(captured['X-Agent-Type']).toBe('claude-code');
51
+ expect(captured['Authorization']).toBe('Bearer key');
52
+ });
53
+
54
+ it('per-request headers override extraHeaders', async () => {
55
+ let captured: any;
56
+ vi.stubGlobal('fetch', vi.fn(async (_url: string, init: any) => { captured = init.headers; return new Response('{}', { status: 200 }); }));
57
+ const t = new HttpTransport('key', registry, { 'X-Agent-Type': 'default' });
58
+ await t.request('POST', '/x', undefined, { 'X-Agent-Type': 'override' });
59
+ expect(captured['X-Agent-Type']).toBe('override');
60
+ });
61
+ });
@@ -50,8 +50,10 @@ export class HttpTransport {
50
50
  /**
51
51
  * Generic HTTP request. Supports JSON body and FormData.
52
52
  * Adds Authorization header when apiKey is non-empty.
53
+ * `perRequestHeaders` are merged last (highest precedence) so a caller can
54
+ * attach a header to a single endpoint without polluting every request.
53
55
  */
54
- async request<T = any>(method: string, path: string, body?: any): Promise<T> {
56
+ async request<T = any>(method: string, path: string, body?: any, perRequestHeaders?: Record<string, string>): Promise<T> {
55
57
  const url = this.registry.baseUrlFor(path) + path;
56
58
  const headers: Record<string, string> = {};
57
59
 
@@ -61,6 +63,9 @@ export class HttpTransport {
61
63
  }
62
64
 
63
65
  for (const [k, v] of Object.entries(this.extraHeaders)) headers[k] = v;
66
+ if (perRequestHeaders) {
67
+ for (const [k, v] of Object.entries(perRequestHeaders)) headers[k] = v;
68
+ }
64
69
 
65
70
  let fetchBody: BodyInit | undefined;
66
71
  if (body !== undefined) {
@@ -92,8 +97,8 @@ export class HttpTransport {
92
97
  }
93
98
  }
94
99
 
95
- async post<T = any>(path: string, body?: any): Promise<T> {
96
- return this.request<T>('POST', path, body);
100
+ async post<T = any>(path: string, body?: any, perRequestHeaders?: Record<string, string>): Promise<T> {
101
+ return this.request<T>('POST', path, body, perRequestHeaders);
97
102
  }
98
103
 
99
104
  /** GET raw bytes (binary artifacts). Throws ApiError on non-ok. */
@@ -19,6 +19,7 @@ describe('parseResourceRef', () => {
19
19
  it('splits type/id', () => {
20
20
  expect(parseResourceRef('strategy/ab12cd')).toEqual({ type: 'strategy', id: 'ab12cd' });
21
21
  expect(parseResourceRef('skill/xyz')).toEqual({ type: 'skill', id: 'xyz' });
22
+ expect(parseResourceRef('persona/abc')).toEqual({ type: 'persona', id: 'abc' });
22
23
  });
23
24
  it('rejects bad type', () => {
24
25
  expect(() => parseResourceRef('plugin/abc')).toThrow(/invalid resource ref/);
@@ -3,7 +3,7 @@ import { AuthStore } from './auth.js';
3
3
  import { ServerRegistry } from './server-registry.js';
4
4
  import { HttpTransport } from './http-transport.js';
5
5
 
6
- export type ResourceType = 'skill' | 'strategy';
6
+ export type ResourceType = 'skill' | 'strategy' | 'persona';
7
7
 
8
8
  export interface ResourceStats { downloadCount: number; starCount: number; commentCount: number; }
9
9
 
@@ -43,10 +43,10 @@ export interface ListOptions {
43
43
  const BASE = '/api/client/v1';
44
44
  const DEFAULT_HUB_URL = 'https://myclaw.163.com/hub';
45
45
 
46
- /** Parse a `<type>/<id>` resource ref (type ∈ skill|strategy). */
46
+ /** Parse a `<type>/<id>` resource ref (type ∈ skill|strategy|persona). */
47
47
  export function parseResourceRef(ref: string): { type: ResourceType; id: string } {
48
- const m = ref.match(/^(skill|strategy)\/([^/\s]+)$/);
49
- if (!m) throw new Error(`invalid resource ref '${ref}' (expected <skill|strategy>/<id>)`);
48
+ const m = ref.match(/^(skill|strategy|persona)\/([^/\s]+)$/);
49
+ if (!m) throw new Error(`invalid resource ref '${ref}' (expected <skill|strategy|persona>/<id>)`);
50
50
  return { type: m[1] as ResourceType, id: m[2] };
51
51
  }
52
52
 
@@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
2
2
  import { mkdtempSync, rmSync, existsSync, readFileSync, mkdirSync, writeFileSync } from 'fs';
3
3
  import { tmpdir } from 'os';
4
4
  import { join } from 'path';
5
- import { placementRelPath, slugify, installResource, uninstallResource, listInstalled, readLockfile } from './hub-install.js';
5
+ import { placementRelPath, slugify, installResource, uninstallResource, listInstalled, readLockfile, readPersonaLockfile } from './hub-install.js';
6
6
  import type { ResourceDetail } from './hub-client.js';
7
7
 
8
8
  let ws: string;
@@ -51,6 +51,9 @@ describe('placementRelPath', () => {
51
51
  it('skill → skills/<slug>', () => {
52
52
  expect(placementRelPath(detail({ type: 'skill', title: 'Cool Helper' })).split('\\').join('/')).toBe('skills/cool-helper');
53
53
  });
54
+ it('persona → personas/<slug>__<id>.md', () => {
55
+ expect(placementRelPath(detail({ type: 'persona', title: 'Aggressive Persona' })).split('\\').join('/')).toBe('personas/aggressive-persona__ab12.md');
56
+ });
54
57
  it('rejects unsafe id', () => {
55
58
  expect(() => placementRelPath(detail({ id: '..' }))).toThrow(/unsafe id/);
56
59
  });
@@ -86,6 +89,32 @@ describe('installResource (skill)', () => {
86
89
  });
87
90
  });
88
91
 
92
+ describe('installResource (persona)', () => {
93
+ it('writes .md file to personas/ + lockfile', () => {
94
+ const res = installResource(detail({ type: 'persona', title: 'My Persona' }), Buffer.from('# persona content'));
95
+ expect(existsSync(res.installedPath)).toBe(true);
96
+ expect(res.installedPath.split('\\').join('/')).toContain('personas/my-persona__ab12.md');
97
+ expect(readFileSync(res.installedPath, 'utf8')).toBe('# persona content');
98
+ expect(readPersonaLockfile()['persona/ab12'].title).toBe('My Persona');
99
+ });
100
+ });
101
+
102
+ describe('lockfile merge isolation', () => {
103
+ it('installing a skill preserves persona entries and vice versa', () => {
104
+ // Install a persona first
105
+ installResource(detail({ type: 'persona', id: 'p1', title: 'P1' }), Buffer.from('p'));
106
+ // Then install a skill
107
+ const zip = storeZip({ 'SKILL.md': '# s' });
108
+ installResource(detail({ id: 'sk1', type: 'skill', title: 'My Skill', fileName: 'pkg.zip' }), zip);
109
+ // Both should be in the merged lockfile
110
+ const all = listInstalled();
111
+ expect(all.map(e => `${e.type}/${e.id}`).sort()).toEqual(['persona/p1', 'skill/sk1']);
112
+ // Uninstall skill — persona should survive
113
+ uninstallResource('skill/sk1');
114
+ expect(listInstalled().map(e => `${e.type}/${e.id}`)).toEqual(['persona/p1']);
115
+ });
116
+ });
117
+
89
118
  describe('uninstall / list', () => {
90
119
  it('lists then removes', () => {
91
120
  installResource(detail({}), Buffer.from('x'));
@@ -95,4 +124,13 @@ describe('uninstall / list', () => {
95
124
  expect(existsSync(r.path!)).toBe(false);
96
125
  expect(listInstalled()).toEqual([]);
97
126
  });
127
+
128
+ it('uninstalls persona and removes from lockfile', () => {
129
+ installResource(detail({ type: 'persona', id: 'p2', title: 'P2' }), Buffer.from('p'));
130
+ expect(listInstalled().map(e => `${e.type}/${e.id}`)).toContain('persona/p2');
131
+ const r = uninstallResource('persona/p2');
132
+ expect(r.removed).toBe(true);
133
+ expect(existsSync(r.path!)).toBe(false);
134
+ expect(listInstalled()).toEqual([]);
135
+ });
98
136
  });
@@ -34,6 +34,12 @@ export function readSkillLockfile(): Lockfile {
34
34
  );
35
35
  }
36
36
 
37
+ export function readPersonaLockfile(): Lockfile {
38
+ return Object.fromEntries(
39
+ Object.entries(readJsonLockfile(lockfilePath())).filter(([, entry]) => entry.type === 'persona'),
40
+ );
41
+ }
42
+
37
43
  export function readStrategyLockfile(): Lockfile {
38
44
  ensureUserDataLayout(getWorkspaceDir());
39
45
  return Object.fromEntries(
@@ -42,12 +48,26 @@ export function readStrategyLockfile(): Lockfile {
42
48
  }
43
49
 
44
50
  export function readLockfile(): Lockfile {
45
- return { ...readSkillLockfile(), ...readStrategyLockfile() };
51
+ return { ...readSkillLockfile(), ...readPersonaLockfile(), ...readStrategyLockfile() };
46
52
  }
47
53
 
48
- function writeSkillLockfile(lock: Lockfile): void {
54
+ /** Merge entries of the given types into hub/installed.json, preserving entries of other types. */
55
+ function writeWorkspaceLockfile(lock: Lockfile, types: Set<string>): void {
56
+ const existing = readJsonLockfile(lockfilePath());
57
+ const preserved = Object.fromEntries(
58
+ Object.entries(existing).filter(([, e]) => !types.has(e.type)),
59
+ );
60
+ const merged = { ...preserved, ...lock };
49
61
  mkdirSync(hubDir(), { recursive: true });
50
- writeFileSync(lockfilePath(), JSON.stringify(lock, null, 2) + '\n', 'utf8');
62
+ writeFileSync(lockfilePath(), JSON.stringify(merged, null, 2) + '\n', 'utf8');
63
+ }
64
+
65
+ function writeSkillLockfile(lock: Lockfile): void {
66
+ writeWorkspaceLockfile(lock, new Set(['skill']));
67
+ }
68
+
69
+ function writePersonaLockfile(lock: Lockfile): void {
70
+ writeWorkspaceLockfile(lock, new Set(['persona']));
51
71
  }
52
72
 
53
73
  function writeStrategyLockfile(lock: Lockfile): void {
@@ -58,6 +78,7 @@ function writeStrategyLockfile(lock: Lockfile): void {
58
78
 
59
79
  export function writeLockfile(lock: Lockfile): void {
60
80
  writeSkillLockfile(Object.fromEntries(Object.entries(lock).filter(([, entry]) => entry.type === 'skill')));
81
+ writePersonaLockfile(Object.fromEntries(Object.entries(lock).filter(([, entry]) => entry.type === 'persona')));
61
82
  writeStrategyLockfile(Object.fromEntries(Object.entries(lock).filter(([, entry]) => entry.type === 'strategy')));
62
83
  }
63
84
 
@@ -83,6 +104,11 @@ export function placementRelPath(detail: { type: ResourceType; id: string; title
83
104
  const base = slug ? `${slug}__${detail.id}` : detail.id;
84
105
  return join('strategies', `${base}${ext}`);
85
106
  }
107
+ if (detail.type === 'persona') {
108
+ const slug = slugify(detail.title);
109
+ const base = slug ? `${slug}__${detail.id}` : detail.id;
110
+ return join('personas', `${base}.md`);
111
+ }
86
112
  const slug = slugify(detail.title) || detail.id;
87
113
  assertSafeSegment('skill dir', slug);
88
114
  return join('skills', slug);
@@ -99,7 +125,9 @@ export function installResource(detail: ResourceDetail, artifact: Buffer, opts:
99
125
  const relPath = placementRelPath(detail);
100
126
  const rootDir = detail.type === 'strategy' ? getUserDataDir(ws) : ws;
101
127
  const absPath = join(rootDir, relPath);
102
- const lock = detail.type === 'strategy' ? readStrategyLockfile() : readSkillLockfile();
128
+ const lock = detail.type === 'strategy' ? readStrategyLockfile()
129
+ : detail.type === 'persona' ? readPersonaLockfile()
130
+ : readSkillLockfile();
103
131
  const tracked = lock[ref] !== undefined;
104
132
 
105
133
  if (detail.type === 'strategy') {
@@ -108,6 +136,12 @@ export function installResource(detail: ResourceDetail, artifact: Buffer, opts:
108
136
  }
109
137
  mkdirSync(getUserDataStrategiesDir(ws), { recursive: true });
110
138
  writeFileSync(absPath, artifact);
139
+ } else if (detail.type === 'persona') {
140
+ if (existsSync(absPath) && !tracked && !opts.force) {
141
+ throw new Error(`${relPath} already exists and is not tracked by hub; re-run with --force to overwrite`);
142
+ }
143
+ mkdirSync(join(ws, 'personas'), { recursive: true });
144
+ writeFileSync(absPath, artifact);
111
145
  } else {
112
146
  if (existsSync(absPath) && !tracked && !opts.force) {
113
147
  throw new Error(`skills/${slugify(detail.title) || detail.id} already exists and is not tracked by hub; re-run with --force to overwrite`);
@@ -136,13 +170,16 @@ export function installResource(detail: ResourceDetail, artifact: Buffer, opts:
136
170
  installedAt: new Date().toISOString(),
137
171
  };
138
172
  if (detail.type === 'strategy') writeStrategyLockfile(lock);
173
+ else if (detail.type === 'persona') writePersonaLockfile(lock);
139
174
  else writeSkillLockfile(lock);
140
175
  return { ref, type: detail.type, id: detail.id, title: detail.title, installedPath: absPath };
141
176
  }
142
177
 
143
178
  export function uninstallResource(ref: string): { removed: boolean; path?: string } {
144
179
  const type = ref.split('/')[0] as ResourceType;
145
- const lock = type === 'strategy' ? readStrategyLockfile() : readSkillLockfile();
180
+ const lock = type === 'strategy' ? readStrategyLockfile()
181
+ : type === 'persona' ? readPersonaLockfile()
182
+ : readSkillLockfile();
146
183
  const entry = lock[ref];
147
184
  if (!entry) return { removed: false };
148
185
  const ws = getWorkspaceDir();
@@ -151,6 +188,7 @@ export function uninstallResource(ref: string): { removed: boolean; path?: strin
151
188
  if (existsSync(abs)) rmSync(abs, { recursive: true, force: true });
152
189
  delete lock[ref];
153
190
  if (type === 'strategy') writeStrategyLockfile(lock);
191
+ else if (type === 'persona') writePersonaLockfile(lock);
154
192
  else writeSkillLockfile(lock);
155
193
  return { removed: true, path: abs };
156
194
  }
@@ -2,7 +2,7 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync, copyFi
2
2
  import { dirname, join, resolve, basename } from 'path';
3
3
  import { fileURLToPath } from 'url';
4
4
  import { AuthStore } from './auth.js';
5
- import { getProfilePersonaFile } from './init-command.js';
5
+ import { getProfilePersonaFile, getWorkspaceDir } from './init-command.js';
6
6
 
7
7
  const __filename = fileURLToPath(import.meta.url);
8
8
  const __dirname = dirname(__filename);
@@ -84,6 +84,37 @@ export function ensureDefaultPersonaPlaceholder(authStore = new AuthStore(), dir
84
84
  return { path, preset, applied: true };
85
85
  }
86
86
 
87
+ export function getWorkspacePersonaDir(): string {
88
+ return join(getWorkspaceDir(), 'personas');
89
+ }
90
+
91
+ /** List presets from both bundled and workspace (hub-installed) sources. */
92
+ export function listAllPersonaPresets(): (PersonaPreset & { source: 'bundled' | 'workspace' })[] {
93
+ const results: (PersonaPreset & { source: 'bundled' | 'workspace' })[] = [];
94
+ for (const p of listPersonaPresets(getBundledPersonaDir())) {
95
+ results.push({ ...p, source: 'bundled' });
96
+ }
97
+ const wsDir = getWorkspacePersonaDir();
98
+ if (existsSync(wsDir)) {
99
+ for (const p of listPersonaPresets(wsDir)) {
100
+ results.push({ ...p, source: 'workspace' });
101
+ }
102
+ }
103
+ return results;
104
+ }
105
+
106
+ /** Find a preset by name, searching workspace (hub-installed) first, then bundled. */
107
+ export function findPersonaPresetAnywhere(name: string): (PersonaPreset & { source: 'bundled' | 'workspace' }) | null {
108
+ const wsDir = getWorkspacePersonaDir();
109
+ if (existsSync(wsDir)) {
110
+ const ws = findPersonaPreset(name, wsDir);
111
+ if (ws) return { ...ws, source: 'workspace' };
112
+ }
113
+ const bundled = findPersonaPreset(name);
114
+ if (bundled) return { ...bundled, source: 'bundled' };
115
+ return null;
116
+ }
117
+
87
118
  function normalizePersonaName(value: string): string {
88
119
  return value.trim().replace(/\.md$/i, '').toLowerCase();
89
120
  }
@@ -177,17 +177,20 @@ describe('event-format', () => {
177
177
  type: 'game_started',
178
178
  tick: 0,
179
179
  player_count: 10,
180
+ game_mode: 'competition',
180
181
  hint: 'Game started with 10 players. Long backend opening hint.',
181
182
  });
182
183
  const formatted = compactEventFields({
183
184
  type: 'game_started',
184
185
  tick: 0,
185
186
  player_count: 10,
187
+ game_mode: 'competition',
186
188
  hint: 'Game started with 10 players. Long backend opening hint.',
187
189
  });
188
190
 
189
191
  expect(notice).toContain('t0 game_started');
190
192
  expect(notice).toContain('10');
193
+ expect(notice).toContain('竞赛模式');
191
194
  expect(notice).toContain('ccl events game_started');
192
195
  expect(notice).toContain('ccl events role_assigned');
193
196
  expect(notice).not.toContain('Long backend opening hint');
@@ -195,6 +198,7 @@ describe('event-format', () => {
195
198
  type: 'game_started',
196
199
  tick: 0,
197
200
  player_count: 10,
201
+ game_mode: 'competition',
198
202
  hint: expect.stringContaining('ccl events game_started'),
199
203
  });
200
204
  });
@@ -185,7 +185,13 @@ function shortBody(event: Record<string, any>, ctx: EventFormatContext): string
185
185
  case 'game_started': {
186
186
  const playerCount = numberValue(event.player_count);
187
187
  const countText = playerCount === undefined ? '对局开始' : `对局开始:${playerCount}名玩家`;
188
- return `${countText}。地图/座位查 ccl events game_started,身份/任务查 ccl events role_assigned。`;
188
+ const modeText = event.game_mode === 'competition'
189
+ ? '竞赛模式'
190
+ : event.game_mode === 'match'
191
+ ? '普通匹配'
192
+ : '';
193
+ const prefixText = modeText ? `${countText}(${modeText})` : countText;
194
+ return `${prefixText}。地图/座位查 ccl events game_started,身份/任务查 ccl events role_assigned。`;
189
195
  }
190
196
  case 'role_assigned': {
191
197
  const start = ctx.isFirstVisibleEvent ? '对局开始。' : '';
@@ -6,13 +6,14 @@ import { buildMeetingStateProjection, EventRuntime } from './event-daemon.js';
6
6
 
7
7
  const tempDirs: string[] = [];
8
8
 
9
- function makeRuntimeHarness() {
9
+ function makeRuntimeHarness(options: ConstructorParameters<typeof EventRuntime>[0] = {}) {
10
10
  const dir = mkdtempSync(join(tmpdir(), 'ccl-event-runtime-'));
11
11
  tempDirs.push(dir);
12
12
  const appended: Record<string, any>[] = [];
13
13
  const stops: string[] = [];
14
14
  const runtime = new EventRuntime({
15
15
  onStop: (stop) => stops.push(stop.reason),
16
+ ...options,
16
17
  });
17
18
  (runtime as any).events = { append: vi.fn((event) => appended.push(event)) };
18
19
  (runtime as any).feedPath = join(dir, 'feed.json');
@@ -188,6 +189,21 @@ describe('EventRuntime user-left-game detection', () => {
188
189
  });
189
190
 
190
191
  describe('EventRuntime event dedup', () => {
192
+ it('adds game_mode to game_started when the owner runtime knows it', () => {
193
+ const { runtime, appended } = makeRuntimeHarness({
194
+ getGameMode: () => 'competition',
195
+ });
196
+
197
+ (runtime as any).handleEvent({ type: 'game_started', tick: 0, player_count: 10 });
198
+
199
+ expect(appended).toEqual(expect.arrayContaining([
200
+ expect.objectContaining({
201
+ type: 'game_started',
202
+ game_mode: 'competition',
203
+ }),
204
+ ]));
205
+ });
206
+
191
207
  it('does not append repeated runtime events with the same key', () => {
192
208
  const { runtime, appended } = makeRuntimeHarness();
193
209