@myclaw163/clawclaw-cli 0.8.5 → 0.8.6

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 (110) hide show
  1. package/README.md +1 -1
  2. package/docs/custom-modules/behavior.md +7 -18
  3. package/package.json +9 -3
  4. package/scripts/find-hide-spots.py +2 -2
  5. package/skills/clawclaw/SKILL.md +15 -13
  6. package/skills/clawclaw/references/BEHAVIORS.md +12 -8
  7. package/skills/clawclaw/references/COMMANDS.md +15 -27
  8. package/skills/clawclaw/references/TACTICS.md +1 -1
  9. package/src/lib/hub-reminder.ts +3 -5
  10. package/src/runtime/clawclaw/behavior-read-api.ts +1 -1
  11. package/src/{strategies/pathfind → runtime/clawclaw/navigation}/astar-path.ts +1 -1
  12. package/src/{strategies/pathfind → runtime/clawclaw/navigation}/escape-planner.ts +1 -1
  13. package/src/{strategies → runtime/clawclaw/navigation}/hide-spots.ts +2 -2
  14. package/src/{strategies → runtime/clawclaw/navigation}/off-route-points.ts +6 -3
  15. package/src/{strategies/pathfind → runtime/clawclaw/navigation}/walkable-grid.ts +1 -1
  16. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +1 -1
  17. package/src/runtime/framework/modules/runtime-module-loader.ts +0 -54
  18. package/src/sdk/behavior-toolkit/escape.ts +2 -2
  19. package/scripts/build-official-hub-behaviors.mjs +0 -136
  20. package/scripts/build-official-hub-behaviors.test.mjs +0 -178
  21. package/scripts/compare-perception-replays.test.ts +0 -188
  22. package/scripts/enable_ccl_permissions.test.mjs +0 -167
  23. package/scripts/enable_monitor.test.mjs +0 -201
  24. package/scripts/sync-bundled-skill.test.mjs +0 -87
  25. package/scripts/watch-perception-events.test.ts +0 -43
  26. package/src/behaviors/official-finite/do-task.ts +0 -211
  27. package/src/behaviors/official-finite/evade.ts +0 -78
  28. package/src/behaviors/official-finite/find-player.ts +0 -50
  29. package/src/behaviors/official-finite/follow-player.ts +0 -70
  30. package/src/behaviors/official-finite/go-to.ts +0 -69
  31. package/src/behaviors/official-finite/hide-temporarily.ts +0 -77
  32. package/src/behaviors/official-finite/hold-position.ts +0 -48
  33. package/src/behaviors/official-finite/hunt-player.ts +0 -47
  34. package/src/behaviors/official-finite/index.ts +0 -44
  35. package/src/behaviors/official-finite/inspect-corpse.ts +0 -64
  36. package/src/behaviors/official-finite/patrol-area.ts +0 -80
  37. package/src/behaviors/official-finite/report-corpse.ts +0 -73
  38. package/src/behaviors/official-finite/seek-kill-opportunity.ts +0 -152
  39. package/src/behaviors/official-finite/shared.ts +0 -27
  40. package/src/hub-official-behaviors/kill-lone.ts +0 -138
  41. package/src/hub-official-behaviors/patrol.ts +0 -30
  42. package/src/hub-official-behaviors/shared.ts +0 -125
  43. package/src/hub-official-behaviors/task-only.ts +0 -158
  44. package/src/runtime/clawclaw/plugins/behavior/official-goal-behavior.ts +0 -757
  45. package/src/strategies/avoid-lone.ts +0 -32
  46. package/src/strategies/avoid-players.ts +0 -43
  47. package/src/strategies/corpse-patrol.ts +0 -50
  48. package/src/strategies/crab-sabotage.ts +0 -48
  49. package/src/strategies/find-player.ts +0 -49
  50. package/src/strategies/game-utils.ts +0 -927
  51. package/src/strategies/goals/anchor-linger.ts +0 -77
  52. package/src/strategies/goals/avoid-lone-top.ts +0 -189
  53. package/src/strategies/goals/avoid-players-top.ts +0 -122
  54. package/src/strategies/goals/conversation-goal.ts +0 -51
  55. package/src/strategies/goals/corpse-patrol-top.ts +0 -120
  56. package/src/strategies/goals/crab-octopus-reflexes.ts +0 -109
  57. package/src/strategies/goals/crab-sabotage-top.ts +0 -139
  58. package/src/strategies/goals/emergency-hunt-goal.ts +0 -40
  59. package/src/strategies/goals/find-player-top.ts +0 -136
  60. package/src/strategies/goals/flee-players-goal.ts +0 -55
  61. package/src/strategies/goals/follow-companion-goal.ts +0 -130
  62. package/src/strategies/goals/goal-manager.ts +0 -41
  63. package/src/strategies/goals/goal-root-strategy.ts +0 -49
  64. package/src/strategies/goals/goal.ts +0 -28
  65. package/src/strategies/goals/hide-top.ts +0 -240
  66. package/src/strategies/goals/keep-away-goal.ts +0 -243
  67. package/src/strategies/goals/kill-frenzy-top.ts +0 -90
  68. package/src/strategies/goals/kill-lone-top.ts +0 -166
  69. package/src/strategies/goals/kill-target-goal.ts +0 -69
  70. package/src/strategies/goals/kill-target-top.ts +0 -121
  71. package/src/strategies/goals/leaf-goal.ts +0 -27
  72. package/src/strategies/goals/linger-corpse-goal.ts +0 -43
  73. package/src/strategies/goals/lone-kill-core.ts +0 -86
  74. package/src/strategies/goals/lone-kill-goal.ts +0 -24
  75. package/src/strategies/goals/lone-kill-task-top.ts +0 -133
  76. package/src/strategies/goals/move-room-goal.ts +0 -102
  77. package/src/strategies/goals/normal-shrimp-top.ts +0 -248
  78. package/src/strategies/goals/paradise-fish-top.ts +0 -234
  79. package/src/strategies/goals/patrol-top.ts +0 -68
  80. package/src/strategies/goals/report-patrol-top.ts +0 -97
  81. package/src/strategies/goals/safe-task-goal.ts +0 -130
  82. package/src/strategies/goals/social-task-top.ts +0 -192
  83. package/src/strategies/goals/task-kill-report-top.ts +0 -187
  84. package/src/strategies/goals/task-only-top.ts +0 -64
  85. package/src/strategies/goals/task-or-patrol-goal.ts +0 -59
  86. package/src/strategies/goals/task-report-top.ts +0 -57
  87. package/src/strategies/goals/wander-task-goal.ts +0 -33
  88. package/src/strategies/goals/warrior-shrimp-top.ts +0 -293
  89. package/src/strategies/greeting.ts +0 -60
  90. package/src/strategies/hide.ts +0 -51
  91. package/src/strategies/kill-frenzy.ts +0 -32
  92. package/src/strategies/kill-lone.ts +0 -52
  93. package/src/strategies/kill-target.ts +0 -48
  94. package/src/strategies/lone-kill-task.ts +0 -48
  95. package/src/strategies/meeting-gate.ts +0 -28
  96. package/src/strategies/move-room.ts +0 -46
  97. package/src/strategies/paradise-fish.ts +0 -70
  98. package/src/strategies/patrol.ts +0 -32
  99. package/src/strategies/player-targets.ts +0 -18
  100. package/src/strategies/report-patrol.ts +0 -32
  101. package/src/strategies/shrimp-memory.ts +0 -87
  102. package/src/strategies/social-task.ts +0 -67
  103. package/src/strategies/speech-module.ts +0 -123
  104. package/src/strategies/task-kill-report.ts +0 -49
  105. package/src/strategies/task-only.ts +0 -34
  106. package/src/strategies/task-report.ts +0 -50
  107. package/src/strategies/types.ts +0 -116
  108. package/src/strategies/warrior-memory.ts +0 -54
  109. /package/src/{strategies/pathfind → runtime/clawclaw/navigation}/clawclaw-walkable.bin +0 -0
  110. /package/src/{strategies/pathfind → runtime/clawclaw/navigation}/distance-field.ts +0 -0
@@ -1,136 +0,0 @@
1
- #!/usr/bin/env node
2
- import { build } from 'esbuild';
3
- import { createHash } from 'node:crypto';
4
- import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
5
- import { dirname, join, resolve } from 'node:path';
6
- import { fileURLToPath, pathToFileURL } from 'node:url';
7
-
8
- const scriptDir = dirname(fileURLToPath(import.meta.url));
9
- const packageRoot = resolve(scriptDir, '..');
10
- const PUBLIC_BEHAVIOR_PLUGIN = '@myclaw163/clawclaw-cli/behavior-plugin';
11
-
12
- export const OFFICIAL_HUB_BEHAVIORS = Object.freeze([
13
- { id: 'task-only', resourceId: '24b6cdd8-4766-40e8-b1c4-e669db00a3ed', className: 'TaskOnlyStrategy', source: 'src/hub-official-behaviors/task-only.ts' },
14
- { id: 'patrol', resourceId: 'a73edbd3-5476-4d23-9164-03d2655fc7c3', className: 'PatrolStrategy', source: 'src/hub-official-behaviors/patrol.ts' },
15
- { id: 'do_task', resourceId: 'fbbbc2b1-9b71-49d1-9c48-5e5392f551dc', className: 'DoTaskBehavior', source: 'src/behaviors/official-finite/do-task.ts' },
16
- { id: 'kill-lone', resourceId: '5dc062b3-aa53-4155-ab56-15b7b20eaf63', className: 'KillLoneStrategy', source: 'src/hub-official-behaviors/kill-lone.ts' },
17
- { id: 'report_corpse', resourceId: '59bdc29e-1b8a-4ac4-99dc-9df359ce3b42', className: 'ReportCorpseBehavior', source: 'src/behaviors/official-finite/report-corpse.ts' },
18
- { id: 'hunt_player', resourceId: 'd3f15d94-edca-4acb-accc-a0d0b6583ad7', className: 'HuntPlayerBehavior', source: 'src/behaviors/official-finite/hunt-player.ts' },
19
- ]);
20
-
21
- function externalizePublicBehaviorPlugin() {
22
- return {
23
- name: 'externalize-public-behavior-plugin',
24
- setup(buildApi) {
25
- buildApi.onResolve({ filter: /sdk[\\/]behavior-plugin[\\/]index\.js$/ }, () => ({
26
- path: PUBLIC_BEHAVIOR_PLUGIN,
27
- external: true,
28
- }));
29
- },
30
- };
31
- }
32
-
33
- function restoreStaticDefaultClass(source, definition) {
34
- const declaration = new RegExp(
35
- `var\\s+${definition.className}\\s*=\\s*class\\s+extends\\s+ClawclawBehavior`,
36
- );
37
- if (!declaration.test(source)) {
38
- throw new Error(`bundled_default_class_not_found:${definition.id}`);
39
- }
40
- const restored = source
41
- .replace(
42
- declaration,
43
- `export default class ${definition.className} extends ClawclawBehavior`,
44
- )
45
- .replace(
46
- new RegExp(`\\nexport\\s*\\{\\s*${definition.className}\\s+as\\s+default\\s*\\};?\\s*$`),
47
- '\n',
48
- );
49
- if (!restored.includes(`export default class ${definition.className} extends ClawclawBehavior`)) {
50
- throw new Error(`bundled_default_class_restore_failed:${definition.id}`);
51
- }
52
- return restored;
53
- }
54
-
55
- function assertSelfContained(source, definition) {
56
- if (/clawclaw-internal:/.test(source)) {
57
- throw new Error(`bundled_internal_alias_remaining:${definition.id}`);
58
- }
59
- const imports = [...source.matchAll(/(?:from\s+|import\s*)["']([^"']+)["']/g)]
60
- .map((match) => match[1]);
61
- const unsupported = imports.filter((specifier) => specifier !== PUBLIC_BEHAVIOR_PLUGIN);
62
- if (unsupported.length > 0) {
63
- throw new Error(`bundled_external_import_remaining:${definition.id}:${unsupported.join(',')}`);
64
- }
65
- if (!source.includes(`id: "${definition.id}"`) && !source.includes(`id: '${definition.id}'`)) {
66
- throw new Error(`bundled_manifest_id_missing:${definition.id}`);
67
- }
68
- }
69
-
70
- export async function buildOfficialHubBehaviors(outDir) {
71
- const outputRoot = resolve(outDir);
72
- rmSync(outputRoot, { recursive: true, force: true });
73
- mkdirSync(outputRoot, { recursive: true });
74
- const built = [];
75
- for (const definition of OFFICIAL_HUB_BEHAVIORS) {
76
- const outputPath = join(outputRoot, `${definition.id}.ts`);
77
- await build({
78
- entryPoints: [resolve(packageRoot, definition.source)],
79
- outfile: outputPath,
80
- bundle: true,
81
- write: true,
82
- format: 'esm',
83
- platform: 'node',
84
- target: 'node22',
85
- charset: 'utf8',
86
- legalComments: 'none',
87
- sourcemap: false,
88
- minify: false,
89
- treeShaking: true,
90
- external: [PUBLIC_BEHAVIOR_PLUGIN],
91
- plugins: [externalizePublicBehaviorPlugin()],
92
- banner: {
93
- js: `// Self-contained official Hub Behavior '${definition.id}'.\n// Generated from ${definition.source}; only the public Behavior SDK remains external.`,
94
- },
95
- });
96
- const bundled = restoreStaticDefaultClass(readFileSync(outputPath, 'utf8'), definition);
97
- assertSelfContained(bundled, definition);
98
- writeFileSync(outputPath, bundled, 'utf8');
99
- built.push({
100
- ...definition,
101
- outputPath,
102
- bytes: Buffer.byteLength(bundled),
103
- sha256: createHash('sha256').update(bundled).digest('hex'),
104
- });
105
- }
106
- writeFileSync(join(outputRoot, 'manifest.json'), `${JSON.stringify({
107
- schema: 'clawclaw.official-hub-behaviors.v1',
108
- generatedAt: new Date().toISOString(),
109
- behaviors: built.map(({ id, resourceId, source, outputPath, bytes, sha256 }) => ({
110
- id,
111
- resourceId,
112
- source,
113
- file: outputPath.slice(outputRoot.length + 1).replaceAll('\\', '/'),
114
- bytes,
115
- sha256,
116
- })),
117
- }, null, 2)}\n`, 'utf8');
118
- return built;
119
- }
120
-
121
- function parseOutDir(argv) {
122
- const index = argv.indexOf('--out-dir');
123
- if (index < 0 || !argv[index + 1]) {
124
- throw new Error('Usage: npm run build:hub-official-behaviors -- --out-dir <directory>');
125
- }
126
- return argv[index + 1];
127
- }
128
-
129
- const entry = process.argv[1] ? pathToFileURL(resolve(process.argv[1])).href : '';
130
- if (import.meta.url === entry) {
131
- const built = await buildOfficialHubBehaviors(parseOutDir(process.argv.slice(2)));
132
- process.stdout.write(`${JSON.stringify({
133
- output_dir: resolve(parseOutDir(process.argv.slice(2))),
134
- behaviors: built.map(({ id, outputPath, bytes, sha256 }) => ({ id, path: outputPath, bytes, sha256 })),
135
- }, null, 2)}\n`);
136
- }
@@ -1,178 +0,0 @@
1
- import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
2
- import { tmpdir } from 'node:os';
3
- import { join } from 'node:path';
4
- import { afterEach, describe, expect, it } from 'vitest';
5
- import {
6
- buildOfficialHubBehaviors,
7
- OFFICIAL_HUB_BEHAVIORS,
8
- } from './build-official-hub-behaviors.mjs';
9
- import { listClawclawBehaviorSources } from '../src/runtime/clawclaw/plugins/behavior/behavior-source.js';
10
- import { loadClawclawBehaviorModule } from '../src/runtime/clawclaw/plugins/behavior/behavior-module-loader.js';
11
-
12
- const roots = [];
13
- const rooms = [{
14
- name: '厨房',
15
- polygon: [[100, 0], [200, 0], [200, 100], [100, 100]],
16
- bbox: { left: 100, top: 0, right: 200, bottom: 100 },
17
- }, {
18
- name: '酒吧',
19
- polygon: [[300, 0], [400, 0], [400, 100], [300, 100]],
20
- bbox: { left: 300, top: 0, right: 400, bottom: 100 },
21
- }];
22
-
23
- function api() {
24
- const distance = (from, to) => Math.hypot(from.x - to.x, from.y - to.y);
25
- return {
26
- spatial: {
27
- xPositive: 'right', yPositive: 'down', playerBodyLengthPx: 64, rooms,
28
- roomAt: () => null, sideInRoom: () => null, placeLabel: () => '',
29
- transitionIsMapped: () => true,
30
- },
31
- navigation: {
32
- pathDistance: async (from, to) => distance(from, to),
33
- pathDistances: async (queries) => queries.map(({ from, to }) => distance(from, to)),
34
- },
35
- observation: {
36
- lastSeenPlayer: () => undefined,
37
- lastSeenCorpse: () => undefined,
38
- },
39
- };
40
- }
41
-
42
- function state(overrides = {}) {
43
- return {
44
- game_id: 'game', tick: 1, phase: 'wandering',
45
- you: {
46
- player: { seat: 1, name: 'Self', is_alive: true },
47
- x: 0, y: 0, room: '走廊', role: 'shrimp_generic', faction: 'lobster',
48
- is_alive: true, activity: { kind: 'idle' }, tasks: [],
49
- },
50
- players: [], visible_players: [], visible_corpses: [],
51
- ...overrides,
52
- };
53
- }
54
-
55
- function frame(gameState, input, epochId = 1) {
56
- return {
57
- epochId,
58
- scope: { sessionId: 'session', segmentId: 'segment' },
59
- nowMs: 1_000,
60
- gameState,
61
- events: [],
62
- input,
63
- };
64
- }
65
-
66
- afterEach(() => {
67
- for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
68
- });
69
-
70
- describe('official Hub Behavior bundling', () => {
71
- it('builds six statically discoverable and dynamically loadable self-contained modules', async () => {
72
- const root = mkdtempSync(join(tmpdir(), 'official-hub-behaviors-'));
73
- roots.push(root);
74
- const built = await buildOfficialHubBehaviors(root);
75
- expect(built.map(({ id }) => id)).toEqual(OFFICIAL_HUB_BEHAVIORS.map(({ id }) => id));
76
- expect(built.every(({ bytes }) => bytes < 50_000)).toBe(true);
77
-
78
- const sources = listClawclawBehaviorSources(root);
79
- expect(sources.map(({ id }) => id).sort()).toEqual(
80
- OFFICIAL_HUB_BEHAVIORS.map(({ id }) => id).sort(),
81
- );
82
- const classes = new Map();
83
- for (const source of sources) {
84
- const text = readFileSync(source.sourcePath, 'utf8');
85
- expect(text).not.toContain('clawclaw-internal:');
86
- expect(text).not.toContain('clawclaw-walkable.bin');
87
- expect(text).not.toContain('clawclaw-map.json');
88
- expect(text).not.toMatch(/from\s+["']\.\.?\//);
89
- const loaded = await loadClawclawBehaviorModule(source);
90
- expect(loaded.manifest.id).toBe(source.id);
91
- expect(typeof loaded.BehaviorClass.prototype.decide).toBe('function');
92
- classes.set(source.id, loaded.BehaviorClass);
93
- }
94
-
95
- const patrol = new (classes.get('patrol'))();
96
- await expect(patrol.decide(frame(state(), {}), api())).resolves.toEqual(
97
- expect.objectContaining({ status: expect.any(Object) }),
98
- );
99
-
100
- const taskOnly = new (classes.get('task-only'))();
101
- const longTaskState = state({
102
- you: {
103
- ...state().you,
104
- tasks: [{ task_id: 'wires', name: '接线', room: '走廊', x: 5, y: 0, is_fake_shrimp: false, status: 'normal' }],
105
- },
106
- });
107
- await expect(taskOnly.decide(frame(longTaskState, {}), api())).resolves.toEqual(
108
- expect.objectContaining({
109
- actions: [expect.objectContaining({ action: 'task', task_name: '接线' })],
110
- }),
111
- );
112
-
113
- const doTask = new (classes.get('do_task'))();
114
- const taskState = state({
115
- you: {
116
- ...state().you,
117
- tasks: [{ task_id: 'wires', name: '接线', room: '走廊', x: 5, y: 0, is_fake_shrimp: false, status: 'normal' }],
118
- },
119
- });
120
- await expect(doTask.decide(frame(taskState, { task: 'wires', timeout_ms: 60_000 }), api()))
121
- .resolves.toEqual(expect.objectContaining({
122
- actions: [expect.objectContaining({ action: 'task', task_name: '接线' })],
123
- }));
124
-
125
- const report = new (classes.get('report_corpse'))();
126
- const corpseState = state({
127
- visible_corpses: [{ corpse_id: 'corpse-2', player: { seat: 2, name: 'Dead' }, x: 10, y: 0, room: '走廊', distance: 10 }],
128
- });
129
- await expect(report.decide(frame(corpseState, { corpse_seat: 2, timeout_ms: 45_000 }), api()))
130
- .resolves.toEqual(expect.objectContaining({
131
- actions: [expect.objectContaining({ action: 'report' })],
132
- }));
133
-
134
- const hunt = new (classes.get('hunt_player'))();
135
- const huntingState = state({
136
- you: { ...state().you, role: 'crab_generic', faction: 'crab', kills_remaining: 1, crab_teammates: [] },
137
- players: [{ seat: 2, name: 'Target', known_status: { is_alive: true } }],
138
- visible_players: [{ player: { seat: 2, name: 'Target' }, x: 10, y: 0, room: '走廊', distance: 10, is_alive: true }],
139
- });
140
- await expect(hunt.decide(frame(huntingState, {
141
- player_seat: 2,
142
- after_kill: 'replan',
143
- timeout_ms: 60_000,
144
- }), api())).resolves.toEqual(expect.objectContaining({
145
- actions: [expect.objectContaining({ action: 'kill', target_seat: 2 })],
146
- }));
147
-
148
- const killLone = new (classes.get('kill-lone'))();
149
- await expect(killLone.decide(frame(huntingState, {
150
- protectedTargets: [],
151
- huntTargets: [],
152
- }), api())).resolves.toEqual(expect.objectContaining({
153
- actions: [expect.objectContaining({ action: 'kill', target_seat: 2 })],
154
- }));
155
-
156
- const protectedKillLone = new (classes.get('kill-lone'))();
157
- const protectedDecision = await protectedKillLone.decide(frame(huntingState, {
158
- protectedTargets: [2],
159
- huntTargets: [2],
160
- }), api());
161
- expect(protectedDecision?.actions ?? []).not.toContainEqual(expect.objectContaining({ action: 'kill' }));
162
-
163
- const huntCrowd = new (classes.get('kill-lone'))();
164
- const crowdState = state({
165
- ...huntingState,
166
- visible_players: [
167
- ...huntingState.visible_players,
168
- { player: { seat: 3, name: 'Other' }, x: 20, y: 0, room: '走廊', distance: 20, is_alive: true },
169
- ],
170
- });
171
- await expect(huntCrowd.decide(frame(crowdState, {
172
- protectedTargets: [],
173
- huntTargets: [2],
174
- }), api())).resolves.toEqual(expect.objectContaining({
175
- actions: [expect.objectContaining({ action: 'kill', target_seat: 2 })],
176
- }));
177
- }, 30_000);
178
- });
@@ -1,188 +0,0 @@
1
- import { describe, expect, it } from 'vitest';
2
- import {
3
- comparePerceptionReplays,
4
- type ParsedReplay,
5
- type ReplayProposal,
6
- } from './compare-perception-replays.js';
7
-
8
- function proposal(
9
- type: string,
10
- tick: number,
11
- data: Record<string, unknown>,
12
- ): ReplayProposal {
13
- return {
14
- type,
15
- emittedAtFrameSeq: 2,
16
- emittedAtTick: tick,
17
- payload: {
18
- from_tick: tick,
19
- to_tick: tick,
20
- actors: [5],
21
- text: '',
22
- data,
23
- },
24
- };
25
- }
26
-
27
- function replay(candidate = false): ParsedReplay {
28
- const visible = proposal('visual.player_entered', 3, {
29
- player_id: 'seat:7',
30
- side: '左',
31
- place: '厨房左侧',
32
- });
33
- const route = proposal('visual.player_turned', 12, {
34
- player_id: 'seat:5',
35
- direction: candidate ? '左' : '左上',
36
- });
37
- const movement = candidate
38
- ? [proposal('visual.player_moved', 20, { player_id: 'seat:5', path_length_px: 90 })]
39
- : [
40
- proposal('visual.player_moved', 10, { player_id: 'seat:5', path_length_px: 60 }),
41
- proposal('visual.player_moved', 20, { player_id: 'seat:5', path_length_px: 40 }),
42
- ];
43
- const modules = [
44
- { id: 'visual.motion', produces: ['visual.player_moved', 'visual.player_motion_changed'] },
45
- { id: 'visual.route', produces: ['visual.player_turned', 'visual.player_reversed', 'visual.player_wandering'] },
46
- { id: 'visual.stop', produces: candidate
47
- ? ['visual.player_stopped', 'visual.player_resumed']
48
- : ['visual.player_stopped', 'visual.player_resumed', 'visual.no_significant_stop'] },
49
- { id: 'visual.visibility', produces: ['visual.player_entered', 'visual.player_left'] },
50
- ];
51
- return {
52
- scope: candidate
53
- ? { session_id: 'session', account_id: 'account' }
54
- : { account_id: 'account', session_id: 'session' },
55
- selection: candidate
56
- ? { to_tick: 20, from_tick: 1 }
57
- : { from_tick: 1, to_tick: 20 },
58
- modules: candidate ? [modules[2], modules[0], modules[3], modules[1]] : modules,
59
- frames: candidate
60
- ? [
61
- { frameSeq: 1, perceptionFrame: { observation: { players: [{ observer: true, id: 'seat:5' }] }, tickDelta: 1, tick: 1 } },
62
- { frameSeq: 2, perceptionFrame: { observation: { players: [{ id: 'seat:5', observer: true }] }, tick: 20, tickDelta: 19 } },
63
- ]
64
- : [
65
- { frameSeq: 1, perceptionFrame: { tick: 1, tickDelta: 1, observation: { players: [{ id: 'seat:5', observer: true }] } } },
66
- { frameSeq: 2, perceptionFrame: { tickDelta: 19, tick: 20, observation: { players: [{ observer: true, id: 'seat:5' }] } } },
67
- ],
68
- generated_proposals_covering_selection: [visible, route, ...movement],
69
- };
70
- }
71
-
72
- describe('compare-perception-replays gates', () => {
73
- it('passes a valid reduction with reordered module IDs and changed produces declarations', () => {
74
- const report = comparePerceptionReplays(replay(), replay(true));
75
-
76
- expect(report.inputs.equivalence_checks).toEqual({
77
- scope: true,
78
- selection: true,
79
- module_ids: true,
80
- selected_frame_seqs: true,
81
- perception_frames: true,
82
- });
83
- expect(report.change.motion_path_coverage.percent).toBe(90);
84
- expect(report.passed).toBe(true);
85
- });
86
-
87
- it('fails when a module is deleted even if the remaining proposals are unchanged', () => {
88
- const before = replay();
89
- const after = replay(true);
90
- after.modules = after.modules.filter((module) => module.id !== 'visual.stop');
91
-
92
- const report = comparePerceptionReplays(before, after);
93
-
94
- expect(report.inputs.equivalence_checks.module_ids).toBe(false);
95
- expect(report.gates.same_replay_input).toBe(false);
96
- expect(report.passed).toBe(false);
97
- });
98
-
99
- it('fails when perception frame content changes behind the same frame sequence', () => {
100
- const before = replay();
101
- const after = replay(true);
102
- after.frames[0].perceptionFrame!.observation!.players![0].observer = false;
103
-
104
- const report = comparePerceptionReplays(before, after);
105
-
106
- expect(report.inputs.evidence.before.perception_frames_digest)
107
- .not.toBe(report.inputs.evidence.after.perception_frames_digest);
108
- expect(report.inputs.equivalence_checks.selected_frame_seqs).toBe(true);
109
- expect(report.inputs.equivalence_checks.perception_frames).toBe(false);
110
- expect(report.gates.same_replay_input).toBe(false);
111
- expect(report.passed).toBe(false);
112
- });
113
-
114
- it('fails when motion proposals are deleted instead of compacted', () => {
115
- const before = replay();
116
- const after = replay(true);
117
- after.generated_proposals_covering_selection = after.generated_proposals_covering_selection
118
- .filter((event) => event.type !== 'visual.player_moved');
119
-
120
- const report = comparePerceptionReplays(before, after);
121
-
122
- expect(report.gates.proposal_count_not_increased).toBe(true);
123
- expect(report.change.motion_path_coverage.percent).toBe(0);
124
- expect(report.gates.motion_path_coverage_at_least_90_percent).toBe(false);
125
- expect(report.passed).toBe(false);
126
- });
127
-
128
- it('treats route events as exact high-value signatures', () => {
129
- const before = replay();
130
- const after = replay(true);
131
- after.generated_proposals_covering_selection = after.generated_proposals_covering_selection
132
- .filter((event) => event.type !== 'visual.player_turned');
133
-
134
- const report = comparePerceptionReplays(before, after);
135
-
136
- expect(report.high_value_signature_changes.missing).toHaveLength(1);
137
- expect(report.gates.high_value_signatures_preserved).toBe(false);
138
- expect(report.passed).toBe(false);
139
- });
140
-
141
- it('allows a corrected visibility side label while preserving the transition and place', () => {
142
- const before = replay();
143
- const after = replay(true);
144
- const entered = after.generated_proposals_covering_selection.find(
145
- (event) => event.type === 'visual.player_entered',
146
- )!;
147
- entered.payload.data.side = '右';
148
-
149
- const report = comparePerceptionReplays(before, after);
150
-
151
- expect(report.high_value_signature_changes.missing).toEqual([]);
152
- expect(report.passed).toBe(true);
153
- });
154
-
155
- it('counts flip-flops carried by fused data.direction_change facts', () => {
156
- const before = replay(true);
157
- const after = replay(true);
158
- after.generated_proposals_covering_selection.push(
159
- proposal('visual.player_moved', 30, {
160
- player_id: 'seat:5',
161
- path_length_px: 10,
162
- direction_change: {
163
- from_direction: '左',
164
- to_direction: '右',
165
- to_tick: 30,
166
- },
167
- }),
168
- proposal('visual.player_moved', 34, {
169
- player_id: 'seat:5',
170
- path_length_px: 10,
171
- direction_change: {
172
- from_direction: '右',
173
- to_direction: '左',
174
- to_tick: 34,
175
- },
176
- }),
177
- );
178
-
179
- const report = comparePerceptionReplays(before, after);
180
-
181
- expect(report.after.direction_flip_flop_count).toBe(1);
182
- expect(report.after.direction_flip_flop_examples[0]).toMatchObject({
183
- subject: 'seat:5',
184
- ticks: [30, 34],
185
- directions: ['左', '右', '左'],
186
- });
187
- });
188
- });
@@ -1,167 +0,0 @@
1
- import { spawnSync } from 'node:child_process';
2
- import {
3
- existsSync,
4
- mkdirSync,
5
- mkdtempSync,
6
- readFileSync,
7
- rmSync,
8
- writeFileSync,
9
- } from 'node:fs';
10
- import { tmpdir } from 'node:os';
11
- import { dirname, join, resolve } from 'node:path';
12
- import { afterEach, describe, expect, it } from 'vitest';
13
-
14
- const scriptPath = resolve('scripts', 'enable_ccl_permissions.cjs');
15
- const tempRoots = [];
16
- const requiredAllow = [
17
- 'Bash(ccl)',
18
- 'Bash(ccl *)',
19
- 'PowerShell(ccl)',
20
- 'PowerShell(ccl *)',
21
- 'Bash(clawclaw-cli)',
22
- 'Bash(clawclaw-cli *)',
23
- 'PowerShell(clawclaw-cli)',
24
- 'PowerShell(clawclaw-cli *)',
25
- 'Skill(clawclaw)',
26
- 'Skill(clawclaw *)',
27
- 'Read(~/.claude/skills/clawclaw/**)',
28
- 'Read(~/.agents/skills/clawclaw/**)',
29
- 'Edit(~/.clawclaw/user-data/accounts/**/personas/local/**)',
30
- 'Edit(~/.clawclaw/user-data/accounts/**/personas/hub/**)',
31
- 'Edit(~/.clawclaw/user-data/accounts/**/memory.md)',
32
- 'Edit(~/AppData/Roaming/clawclaw/user-data/accounts/**/personas/local/**)',
33
- 'Edit(~/AppData/Roaming/clawclaw/user-data/accounts/**/personas/hub/**)',
34
- 'Edit(~/AppData/Roaming/clawclaw/user-data/accounts/**/memory.md)',
35
- ];
36
-
37
- function makeRoot(prefix) {
38
- const root = mkdtempSync(join(tmpdir(), prefix));
39
- tempRoots.push(root);
40
- return root;
41
- }
42
-
43
- function writeJson(file, value) {
44
- mkdirSync(dirname(file), { recursive: true });
45
- writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
46
- }
47
-
48
- function readJson(file) {
49
- return JSON.parse(readFileSync(file, 'utf8'));
50
- }
51
-
52
- function runScript(args) {
53
- return spawnSync(process.execPath, [scriptPath, ...args], {
54
- cwd: resolve('.'),
55
- encoding: 'utf8',
56
- });
57
- }
58
-
59
- afterEach(() => {
60
- while (tempRoots.length) {
61
- rmSync(tempRoots.pop(), { recursive: true, force: true });
62
- }
63
- });
64
-
65
- describe('enable_ccl_permissions.cjs', () => {
66
- it('adds only missing ClawClaw permission entries and preserves existing settings', () => {
67
- const root = makeRoot('enable-ccl-perms-');
68
- const settingsPath = join(root, '.claude', 'settings.json');
69
- const original = {
70
- env: { KEEP_ME: 'yes' },
71
- permissions: {
72
- allow: ['Bash(node *)', 'Bash(ccl)'],
73
- deny: ['Bash(rm *)'],
74
- },
75
- theme: 'dark',
76
- };
77
- writeJson(settingsPath, original);
78
-
79
- const result = runScript(['--settings', settingsPath]);
80
-
81
- expect(result.status).toBe(0);
82
- const settings = readJson(settingsPath);
83
- expect(settings.env).toEqual(original.env);
84
- expect(settings.permissions.deny).toEqual(original.permissions.deny);
85
- expect(settings.theme).toBe(original.theme);
86
- expect(settings.permissions.allow).toEqual([
87
- 'Bash(node *)',
88
- ...requiredAllow,
89
- ]);
90
- });
91
-
92
- it('allows both the Claude skill link and canonical skill target with portable paths', () => {
93
- const root = makeRoot('enable-ccl-perms-paths-');
94
- const settingsPath = join(root, '.claude', 'settings.json');
95
-
96
- const result = runScript(['--settings', settingsPath]);
97
-
98
- expect(result.status).toBe(0);
99
- const allow = readJson(settingsPath).permissions.allow;
100
- expect(allow).toContain('Read(~/.claude/skills/clawclaw/**)');
101
- expect(allow).toContain('Read(~/.agents/skills/clawclaw/**)');
102
- expect(allow).toContain('Edit(~/.clawclaw/user-data/accounts/**/personas/local/**)');
103
- expect(allow).toContain('Edit(~/.clawclaw/user-data/accounts/**/personas/hub/**)');
104
- expect(allow).toContain('Edit(~/.clawclaw/user-data/accounts/**/memory.md)');
105
- expect(allow).toContain('Edit(~/AppData/Roaming/clawclaw/user-data/accounts/**/personas/local/**)');
106
- expect(allow).toContain('Edit(~/AppData/Roaming/clawclaw/user-data/accounts/**/personas/hub/**)');
107
- expect(allow).toContain('Edit(~/AppData/Roaming/clawclaw/user-data/accounts/**/memory.md)');
108
- expect(allow.filter((entry) => /^(?:Read|Edit)\(/.test(entry))).not.toContainEqual(
109
- expect.stringContaining('\\'),
110
- );
111
- });
112
-
113
- it('is idempotent', () => {
114
- const root = makeRoot('enable-ccl-perms-idem-');
115
- const settingsPath = join(root, '.claude', 'settings.json');
116
- writeJson(settingsPath, { permissions: { allow: requiredAllow } });
117
-
118
- const first = runScript(['--settings', settingsPath]);
119
- const afterFirst = readFileSync(settingsPath, 'utf8');
120
- const second = runScript(['--settings', settingsPath]);
121
- const afterSecond = readFileSync(settingsPath, 'utf8');
122
-
123
- expect(first.status).toBe(0);
124
- expect(second.status).toBe(0);
125
- expect(second.stdout).toContain('already allowed');
126
- expect(afterSecond).toBe(afterFirst);
127
- });
128
-
129
- it('creates a minimal settings file when missing', () => {
130
- const root = makeRoot('enable-ccl-perms-missing-');
131
- const settingsPath = join(root, '.claude', 'settings.json');
132
-
133
- const result = runScript(['--settings', settingsPath]);
134
-
135
- expect(result.status).toBe(0);
136
- expect(existsSync(settingsPath)).toBe(true);
137
- expect(readJson(settingsPath)).toEqual({
138
- permissions: { allow: requiredAllow },
139
- });
140
- });
141
-
142
- it('dry-run does not write', () => {
143
- const root = makeRoot('enable-ccl-perms-dry-');
144
- const settingsPath = join(root, '.claude', 'settings.json');
145
- const original = { permissions: { allow: [] } };
146
- writeJson(settingsPath, original);
147
-
148
- const result = runScript(['--dry-run', '--settings', settingsPath]);
149
-
150
- expect(result.status).toBe(0);
151
- expect(result.stdout).toContain('[DRY RUN]');
152
- expect(readJson(settingsPath)).toEqual(original);
153
- });
154
-
155
- it('fails without writing when permissions.allow is not an array', () => {
156
- const root = makeRoot('enable-ccl-perms-bad-');
157
- const settingsPath = join(root, '.claude', 'settings.json');
158
- const original = { permissions: { allow: 'Bash(ccl)' } };
159
- writeJson(settingsPath, original);
160
-
161
- const result = runScript(['--settings', settingsPath]);
162
-
163
- expect(result.status).toBe(1);
164
- expect(result.stdout).toContain('permissions.allow must be an array');
165
- expect(readJson(settingsPath)).toEqual(original);
166
- });
167
- });