@myclaw163/clawclaw-cli 0.6.101 → 0.6.107

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.
@@ -76,6 +76,24 @@ describe('installResource (strategy)', () => {
76
76
  expect(() => installResource(detail({}), Buffer.from('new'))).toThrow(/already exists/);
77
77
  expect(() => installResource(detail({}), Buffer.from('new'), { force: true })).not.toThrow();
78
78
  });
79
+ it('updates an unmodified tracked strategy and records the new baseline', () => {
80
+ const first = installResource(detail({}), Buffer.from('v1'));
81
+ expect(() => installResource(detail({}), Buffer.from('v2'))).not.toThrow();
82
+ expect(readFileSync(first.installedPath, 'utf8')).toBe('v2');
83
+ expect(readLockfile()['strategy/ab12'].contentHash).toBeDefined();
84
+ });
85
+ it('preserves a modified or deleted tracked strategy unless force is explicit', () => {
86
+ const first = installResource(detail({}), Buffer.from('v1'));
87
+ writeFileSync(first.installedPath, 'player edit', 'utf8');
88
+ expect(() => installResource(detail({}), Buffer.from('v2'))).toThrow(/was modified/);
89
+ expect(readFileSync(first.installedPath, 'utf8')).toBe('player edit');
90
+ expect(() => installResource(detail({}), Buffer.from('v2'), { force: true })).not.toThrow();
91
+ expect(readFileSync(first.installedPath, 'utf8')).toBe('v2');
92
+
93
+ rmSync(first.installedPath, { force: true });
94
+ expect(() => installResource(detail({}), Buffer.from('v3'))).toThrow(/was deleted/);
95
+ expect(existsSync(first.installedPath)).toBe(false);
96
+ });
79
97
  });
80
98
 
81
99
  describe('installResource (skill)', () => {
@@ -1,5 +1,6 @@
1
1
  // src/lib/hub-install.ts
2
2
  import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs';
3
+ import { createHash } from 'crypto';
3
4
  import { dirname, extname, join } from 'path';
4
5
  import { getWorkspaceDir } from './init-command.js';
5
6
  import type { ResourceType, ResourceDetail } from './hub-client.js';
@@ -11,7 +12,7 @@ import {
11
12
  getUserDataStrategiesDir,
12
13
  } from './user-data.js';
13
14
 
14
- export interface InstalledEntry { type: ResourceType; id: string; title: string; path: string; installedAt: string; }
15
+ export interface InstalledEntry { type: ResourceType; id: string; title: string; path: string; installedAt: string; contentHash?: string; }
15
16
  export type Lockfile = Record<string, InstalledEntry>; // keyed by "<type>/<id>"
16
17
 
17
18
  export function hubDir(): string { return join(getWorkspaceDir(), 'hub'); }
@@ -116,6 +117,10 @@ export function placementRelPath(detail: { type: ResourceType; id: string; title
116
117
 
117
118
  function makeRef(type: ResourceType, id: string): string { return `${type}/${id}`; }
118
119
 
120
+ function contentHash(content: Buffer): string {
121
+ return createHash('sha256').update(content).digest('hex').slice(0, 16);
122
+ }
123
+
119
124
  export interface InstallResult { ref: string; type: ResourceType; id: string; title: string; installedPath: string; }
120
125
 
121
126
  export function installResource(detail: ResourceDetail, artifact: Buffer, opts: { force?: boolean } = {}): InstallResult {
@@ -134,6 +139,15 @@ export function installResource(detail: ResourceDetail, artifact: Buffer, opts:
134
139
  if (existsSync(absPath) && !tracked && !opts.force) {
135
140
  throw new Error(`${relPath} already exists and is not tracked by hub; re-run with --force to overwrite`);
136
141
  }
142
+ if (tracked && !opts.force) {
143
+ if (!existsSync(absPath)) {
144
+ throw new Error(`${relPath} was deleted after hub install; re-run with --force to restore`);
145
+ }
146
+ const installedHash = lock[ref]?.contentHash;
147
+ if (!installedHash || contentHash(readFileSync(absPath)) !== installedHash) {
148
+ throw new Error(`${relPath} was modified after hub install; re-run with --force to overwrite`);
149
+ }
150
+ }
137
151
  mkdirSync(getUserDataStrategiesDir(ws), { recursive: true });
138
152
  writeFileSync(absPath, artifact);
139
153
  } else if (detail.type === 'persona') {
@@ -168,6 +182,7 @@ export function installResource(detail: ResourceDetail, artifact: Buffer, opts:
168
182
  title: detail.title,
169
183
  path: relPath.split('\\').join('/'),
170
184
  installedAt: new Date().toISOString(),
185
+ ...(detail.type === 'strategy' ? { contentHash: contentHash(artifact) } : {}),
171
186
  };
172
187
  if (detail.type === 'strategy') writeStrategyLockfile(lock);
173
188
  else if (detail.type === 'persona') writePersonaLockfile(lock);
@@ -2,39 +2,27 @@
2
2
  // judgement at the close of a post-game debrief. By debrief time the agent had
3
3
  // often read SKILL.md much earlier and the reminder could get dropped. Instead
4
4
  // the CLI emits it at the firing moment, with account-history gating here.
5
- import { existsSync, readdirSync, readFileSync, writeFileSync, mkdirSync } from 'fs';
5
+ import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';
6
6
  import { join } from 'path';
7
- import { getWorkspaceDir, getProfileStateDir } from './init-command.js';
7
+ import { getProfileStateDir } from './init-command.js';
8
8
  import { listInstalled } from './hub-install.js';
9
9
  import { AuthStore } from './auth.js';
10
- import { ensureUserDataLayout, getUserDataStrategiesDir } from './user-data.js';
10
+ import { hasUserStrategyCustomization } from './strategy-export.js';
11
11
 
12
12
  export const HUB_URL = 'https://myclaw.163.com/hub';
13
13
 
14
14
  /**
15
- * True when CCL can only see the bundled default customization surface: no
16
- * hub-installed skill, no hub-installed strategy, and no user strategy file in
17
- * `<workspace>/user-data/strategies`.
15
+ * True when CCL can only see the default customization surface: no
16
+ * hub-installed skill/strategy and no custom or modified strategy in
17
+ * `<workspace>/user-data/strategies`. Materialized official strategies that
18
+ * still match their manifest baseline count as defaults.
18
19
  */
19
20
  export function usesOnlyDefaultSkillAndStrategies(): boolean {
20
21
  try {
21
22
  if (listInstalled().some((e) => e.type === 'skill' || e.type === 'strategy')) return false;
22
23
  } catch {}
23
24
  try {
24
- const workspaceDir = getWorkspaceDir();
25
- ensureUserDataLayout(workspaceDir);
26
- const dir = getUserDataStrategiesDir(workspaceDir);
27
- if (existsSync(dir)) {
28
- const hasUserStrategy = readdirSync(dir).some((f) => {
29
- if (f.startsWith('_')) return false;
30
- const m = f.match(/^(.+)\.(ts|js)$/);
31
- if (!m) return false;
32
- if (m[1].endsWith('.d')) return false;
33
- if (m[1].endsWith('.test')) return false;
34
- return true;
35
- });
36
- if (hasUserStrategy) return false;
37
- }
25
+ if (hasUserStrategyCustomization()) return false;
38
26
  } catch {}
39
27
  return true;
40
28
  }
@@ -1,6 +1,6 @@
1
1
  import { describe, expect, it } from 'vitest';
2
2
  import { join, resolve } from 'path';
3
- import { CLAWCLAW_WORKSPACE_DIR, resolveWorkspaceDir } from './init-command.js';
3
+ import { CLAWCLAW_WORKSPACE_DIR, getWorkspaceConfigFile, resolveWorkspaceDir } from './init-command.js';
4
4
 
5
5
  describe('resolveWorkspaceDir', () => {
6
6
  it('uses an absolute env override as-is', () => {
@@ -72,4 +72,8 @@ describe('resolveWorkspaceDir', () => {
72
72
  }),
73
73
  ).toBe(join('/home/test', '.clawclaw'));
74
74
  });
75
+
76
+ it('resolves the shared workspace config path without assuming its contents', () => {
77
+ expect(getWorkspaceConfigFile('/tmp/clawclaw')).toBe(join('/tmp/clawclaw', 'config.json'));
78
+ });
75
79
  });
@@ -13,6 +13,7 @@ import {
13
13
  const ACCOUNT_DIRS = ['state', 'logs', 'games'];
14
14
 
15
15
  export const CLAWCLAW_WORKSPACE_DIR = 'CLAWCLAW_WORKSPACE_DIR';
16
+ export const WORKSPACE_CONFIG_FILE = 'config.json';
16
17
 
17
18
  export type ResolveWorkspaceDirOptions = {
18
19
  env?: Record<string, string | undefined>;
@@ -49,9 +50,14 @@ export function getWorkspaceDir(): string {
49
50
  return resolveWorkspaceDir();
50
51
  }
51
52
 
53
+ export function getWorkspaceConfigFile(workspaceDir = getWorkspaceDir()): string {
54
+ return join(workspaceDir, WORKSPACE_CONFIG_FILE);
55
+ }
56
+
52
57
  export function cmdInit(force = false): { created: boolean; path: string } {
53
58
  const workspaceDir = getWorkspaceDir();
54
- const alreadyExists = existsSync(join(workspaceDir, 'config.json'));
59
+ const configFile = getWorkspaceConfigFile(workspaceDir);
60
+ const alreadyExists = existsSync(configFile);
55
61
 
56
62
  if (alreadyExists && !force) {
57
63
  return { created: false, path: workspaceDir };
@@ -63,7 +69,7 @@ export function cmdInit(force = false): { created: boolean; path: string } {
63
69
 
64
70
  if (!alreadyExists) {
65
71
  writeFileSync(
66
- join(workspaceDir, 'config.json'),
72
+ configFile,
67
73
  JSON.stringify({}, null, 2),
68
74
  );
69
75
  }
@@ -7,7 +7,9 @@ import {
7
7
  rewriteBuiltinImports,
8
8
  exportStrategy,
9
9
  detectStaleOfficialStrategies,
10
+ hasUserStrategyCustomization,
10
11
  readManifest,
12
+ syncOfficialStrategies,
11
13
  } from './strategy-export.js';
12
14
 
13
15
  describe('strategy-export', () => {
@@ -35,7 +37,7 @@ describe('strategy-export', () => {
35
37
  }
36
38
 
37
39
  function officialManifestFile(): string {
38
- return join(testWorkspace, 'runtime', 'official-strategies', 'manifest.json');
40
+ return join(userStrategiesDir(), '.official-manifest.json');
39
41
  }
40
42
 
41
43
  describe('rewriteBuiltinImports', () => {
@@ -159,7 +161,7 @@ export const strategy = {
159
161
  expect(strategy).toContain('// Exported from task-only@');
160
162
  });
161
163
 
162
- it('should allow re-exporting tracked strategies without --force', async () => {
164
+ it('should preserve modified tracked strategies without --force', async () => {
163
165
  // First export
164
166
  await exportStrategy('task-only');
165
167
 
@@ -169,11 +171,8 @@ export const strategy = {
169
171
  // Modify the file
170
172
  writeFileSync(strategyFile, '// user customized', 'utf8');
171
173
 
172
- // Re-export without --force (should succeed because it's tracked)
173
- await exportStrategy('task-only');
174
-
175
- const strategy = readFileSync(strategyFile, 'utf8');
176
- expect(strategy).toContain('// Exported from task-only@');
174
+ await expect(exportStrategy('task-only')).rejects.toThrow('was modified');
175
+ expect(readFileSync(strategyFile, 'utf8')).toBe('// user customized');
177
176
  });
178
177
 
179
178
  it('should reject non-existent strategies', async () => {
@@ -183,6 +182,81 @@ export const strategy = {
183
182
  });
184
183
  });
185
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
+
186
260
  describe('detectStaleOfficialStrategies', () => {
187
261
  it('should return empty array when no strategies are exported', () => {
188
262
  expect(detectStaleOfficialStrategies()).toEqual([]);