@myclaw163/clawclaw-cli 0.6.91 → 0.6.92

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.
@@ -1,130 +1,130 @@
1
- import { mkdtempSync, readFileSync, writeFileSync, existsSync, readdirSync } from 'fs';
2
- import { tmpdir } from 'os';
3
- import { dirname, join } from 'path';
4
- import { describe, expect, it } from 'vitest';
5
- import { runHostConfigSetup, unionArrayField, type HostConfigPatcher } from './host-config-patcher.js';
6
-
7
- function tmpConfig(initial: unknown): string {
8
- const dir = mkdtempSync(join(tmpdir(), 'host-cfg-'));
9
- const p = join(dir, 'config.json');
10
- writeFileSync(p, JSON.stringify(initial, null, 2));
11
- return p;
12
- }
13
-
14
- const dummyHost: HostConfigPatcher<{ value: string }> = {
15
- hostName: 'dummy',
16
- resolveConfigPath: () => '/tmp/never-used',
17
- computePatch: (current, opts) => {
18
- const cur = (current as Record<string, unknown> | null) ?? {};
19
- const before = (cur.values as string[] | undefined) ?? [];
20
- if (before.includes(opts.value)) return { next: cur, changes: [], warnings: [] };
21
- return {
22
- next: { ...cur, values: [...before, opts.value] },
23
- changes: [`add ${opts.value} to values`],
24
- warnings: [],
25
- };
26
- },
27
- };
28
-
29
- describe('runHostConfigSetup', () => {
30
- it('prints recommended patch in --print mode without touching disk', () => {
31
- const r = runHostConfigSetup(dummyHost, { value: 'x' }, { print: true });
32
- expect(r.exitCode).toBe(0);
33
- expect(r.output.join('\n')).toContain('"values"');
34
- });
35
-
36
- it('reports missing config file gracefully', () => {
37
- const r = runHostConfigSetup(dummyHost, { value: 'x' }, { configPath: '/no/such/file.json' });
38
- expect(r.exitCode).toBe(0);
39
- expect(r.output.some((l) => l.includes('not found'))).toBe(true);
40
- });
41
-
42
- it('reports malformed JSON with exit 1', () => {
43
- const dir = mkdtempSync(join(tmpdir(), 'host-cfg-bad-'));
44
- const p = join(dir, 'config.json');
45
- writeFileSync(p, '{ not: valid json');
46
- const r = runHostConfigSetup(dummyHost, { value: 'x' }, { configPath: p });
47
- expect(r.exitCode).toBe(1);
48
- expect(r.output.join('\n')).toMatch(/Failed to parse/);
49
- });
50
-
51
- it('returns exit 2 with diff in dry-run when changes pending', () => {
52
- const p = tmpConfig({ values: ['a'] });
53
- const r = runHostConfigSetup(dummyHost, { value: 'b' }, { configPath: p });
54
- expect(r.exitCode).toBe(2);
55
- const txt = r.output.join('\n');
56
- expect(txt).toMatch(/Pending changes/);
57
- expect(txt).toMatch(/Re-run with -y to apply/);
58
- // file unchanged
59
- expect(JSON.parse(readFileSync(p, 'utf-8'))).toEqual({ values: ['a'] });
60
- });
61
-
62
- it('returns exit 0 no-op when already up to date', () => {
63
- const p = tmpConfig({ values: ['a'] });
64
- const r = runHostConfigSetup(dummyHost, { value: 'a' }, { configPath: p });
65
- expect(r.exitCode).toBe(0);
66
- expect(r.output.join('\n')).toMatch(/already up to date/);
67
- });
68
-
69
- it('applies changes atomically with backup when -y', () => {
70
- const p = tmpConfig({ values: ['a'] });
71
- const r = runHostConfigSetup(dummyHost, { value: 'b' }, { configPath: p, yes: true });
72
- expect(r.exitCode).toBe(0);
73
- expect(JSON.parse(readFileSync(p, 'utf-8'))).toEqual({ values: ['a', 'b'] });
74
- const files = readdirSync(dirname(p));
75
- expect(files.some((f) => f.startsWith('config.json.bak.'))).toBe(true);
76
- });
77
-
78
- it('--no-backup skips backup file', () => {
79
- const p = tmpConfig({ values: ['a'] });
80
- const r = runHostConfigSetup(dummyHost, { value: 'b' }, { configPath: p, yes: true, backup: false });
81
- expect(r.exitCode).toBe(0);
82
- const files = readdirSync(dirname(p));
83
- expect(files.some((f) => f.startsWith('config.json.bak.'))).toBe(false);
84
- });
85
-
86
- it('does not leave .tmp file behind on success', () => {
87
- const p = tmpConfig({ values: ['a'] });
88
- runHostConfigSetup(dummyHost, { value: 'b' }, { configPath: p, yes: true, backup: false });
89
- const files = readdirSync(dirname(p));
90
- expect(files.some((f) => f.includes('.tmp.'))).toBe(false);
91
- });
92
-
93
- it('preserves CRLF line endings when original file uses CRLF', () => {
94
- const dir = mkdtempSync(join(tmpdir(), 'host-cfg-crlf-'));
95
- const p = join(dir, 'config.json');
96
- writeFileSync(p, '{\r\n "values": [\r\n "a"\r\n ]\r\n}\r\n');
97
- runHostConfigSetup(dummyHost, { value: 'b' }, { configPath: p, yes: true, backup: false });
98
- const after = readFileSync(p, 'utf-8');
99
- expect(after.includes('\r\n')).toBe(true);
100
- expect(after.replace(/\r\n/g, '<EOL>').includes('\n')).toBe(false);
101
- });
102
-
103
- it('preserves LF line endings when original file uses LF', () => {
104
- const dir = mkdtempSync(join(tmpdir(), 'host-cfg-lf-'));
105
- const p = join(dir, 'config.json');
106
- writeFileSync(p, '{\n "values": [\n "a"\n ]\n}\n');
107
- runHostConfigSetup(dummyHost, { value: 'b' }, { configPath: p, yes: true, backup: false });
108
- const after = readFileSync(p, 'utf-8');
109
- expect(after.includes('\r\n')).toBe(false);
110
- });
111
- });
112
-
113
- describe('unionArrayField', () => {
114
- it('creates new array when field missing', () => {
115
- expect(unionArrayField(undefined, 'x')).toEqual({ next: ['x'], added: true });
116
- });
117
-
118
- it('returns warning when existing value is not an array', () => {
119
- const r = unionArrayField('not-an-array', 'x');
120
- expect(r).toEqual({ warning: 'existing value is not an array, refusing to overwrite' });
121
- });
122
-
123
- it('returns added=false when entry already present', () => {
124
- expect(unionArrayField(['a', 'b'], 'a')).toEqual({ next: ['a', 'b'], added: false });
125
- });
126
-
127
- it('appends entry when missing from array', () => {
128
- expect(unionArrayField(['a'], 'b')).toEqual({ next: ['a', 'b'], added: true });
129
- });
130
- });
1
+ import { mkdtempSync, readFileSync, writeFileSync, existsSync, readdirSync } from 'fs';
2
+ import { tmpdir } from 'os';
3
+ import { dirname, join } from 'path';
4
+ import { describe, expect, it } from 'vitest';
5
+ import { runHostConfigSetup, unionArrayField, type HostConfigPatcher } from './host-config-patcher.js';
6
+
7
+ function tmpConfig(initial: unknown): string {
8
+ const dir = mkdtempSync(join(tmpdir(), 'host-cfg-'));
9
+ const p = join(dir, 'config.json');
10
+ writeFileSync(p, JSON.stringify(initial, null, 2));
11
+ return p;
12
+ }
13
+
14
+ const dummyHost: HostConfigPatcher<{ value: string }> = {
15
+ hostName: 'dummy',
16
+ resolveConfigPath: () => '/tmp/never-used',
17
+ computePatch: (current, opts) => {
18
+ const cur = (current as Record<string, unknown> | null) ?? {};
19
+ const before = (cur.values as string[] | undefined) ?? [];
20
+ if (before.includes(opts.value)) return { next: cur, changes: [], warnings: [] };
21
+ return {
22
+ next: { ...cur, values: [...before, opts.value] },
23
+ changes: [`add ${opts.value} to values`],
24
+ warnings: [],
25
+ };
26
+ },
27
+ };
28
+
29
+ describe('runHostConfigSetup', () => {
30
+ it('prints recommended patch in --print mode without touching disk', () => {
31
+ const r = runHostConfigSetup(dummyHost, { value: 'x' }, { print: true });
32
+ expect(r.exitCode).toBe(0);
33
+ expect(r.output.join('\n')).toContain('"values"');
34
+ });
35
+
36
+ it('reports missing config file gracefully', () => {
37
+ const r = runHostConfigSetup(dummyHost, { value: 'x' }, { configPath: '/no/such/file.json' });
38
+ expect(r.exitCode).toBe(0);
39
+ expect(r.output.some((l) => l.includes('not found'))).toBe(true);
40
+ });
41
+
42
+ it('reports malformed JSON with exit 1', () => {
43
+ const dir = mkdtempSync(join(tmpdir(), 'host-cfg-bad-'));
44
+ const p = join(dir, 'config.json');
45
+ writeFileSync(p, '{ not: valid json');
46
+ const r = runHostConfigSetup(dummyHost, { value: 'x' }, { configPath: p });
47
+ expect(r.exitCode).toBe(1);
48
+ expect(r.output.join('\n')).toMatch(/Failed to parse/);
49
+ });
50
+
51
+ it('returns exit 2 with diff in dry-run when changes pending', () => {
52
+ const p = tmpConfig({ values: ['a'] });
53
+ const r = runHostConfigSetup(dummyHost, { value: 'b' }, { configPath: p });
54
+ expect(r.exitCode).toBe(2);
55
+ const txt = r.output.join('\n');
56
+ expect(txt).toMatch(/Pending changes/);
57
+ expect(txt).toMatch(/Re-run with -y to apply/);
58
+ // file unchanged
59
+ expect(JSON.parse(readFileSync(p, 'utf-8'))).toEqual({ values: ['a'] });
60
+ });
61
+
62
+ it('returns exit 0 no-op when already up to date', () => {
63
+ const p = tmpConfig({ values: ['a'] });
64
+ const r = runHostConfigSetup(dummyHost, { value: 'a' }, { configPath: p });
65
+ expect(r.exitCode).toBe(0);
66
+ expect(r.output.join('\n')).toMatch(/already up to date/);
67
+ });
68
+
69
+ it('applies changes atomically with backup when -y', () => {
70
+ const p = tmpConfig({ values: ['a'] });
71
+ const r = runHostConfigSetup(dummyHost, { value: 'b' }, { configPath: p, yes: true });
72
+ expect(r.exitCode).toBe(0);
73
+ expect(JSON.parse(readFileSync(p, 'utf-8'))).toEqual({ values: ['a', 'b'] });
74
+ const files = readdirSync(dirname(p));
75
+ expect(files.some((f) => f.startsWith('config.json.bak.'))).toBe(true);
76
+ });
77
+
78
+ it('--no-backup skips backup file', () => {
79
+ const p = tmpConfig({ values: ['a'] });
80
+ const r = runHostConfigSetup(dummyHost, { value: 'b' }, { configPath: p, yes: true, backup: false });
81
+ expect(r.exitCode).toBe(0);
82
+ const files = readdirSync(dirname(p));
83
+ expect(files.some((f) => f.startsWith('config.json.bak.'))).toBe(false);
84
+ });
85
+
86
+ it('does not leave .tmp file behind on success', () => {
87
+ const p = tmpConfig({ values: ['a'] });
88
+ runHostConfigSetup(dummyHost, { value: 'b' }, { configPath: p, yes: true, backup: false });
89
+ const files = readdirSync(dirname(p));
90
+ expect(files.some((f) => f.includes('.tmp.'))).toBe(false);
91
+ });
92
+
93
+ it('preserves CRLF line endings when original file uses CRLF', () => {
94
+ const dir = mkdtempSync(join(tmpdir(), 'host-cfg-crlf-'));
95
+ const p = join(dir, 'config.json');
96
+ writeFileSync(p, '{\r\n "values": [\r\n "a"\r\n ]\r\n}\r\n');
97
+ runHostConfigSetup(dummyHost, { value: 'b' }, { configPath: p, yes: true, backup: false });
98
+ const after = readFileSync(p, 'utf-8');
99
+ expect(after.includes('\r\n')).toBe(true);
100
+ expect(after.replace(/\r\n/g, '<EOL>').includes('\n')).toBe(false);
101
+ });
102
+
103
+ it('preserves LF line endings when original file uses LF', () => {
104
+ const dir = mkdtempSync(join(tmpdir(), 'host-cfg-lf-'));
105
+ const p = join(dir, 'config.json');
106
+ writeFileSync(p, '{\n "values": [\n "a"\n ]\n}\n');
107
+ runHostConfigSetup(dummyHost, { value: 'b' }, { configPath: p, yes: true, backup: false });
108
+ const after = readFileSync(p, 'utf-8');
109
+ expect(after.includes('\r\n')).toBe(false);
110
+ });
111
+ });
112
+
113
+ describe('unionArrayField', () => {
114
+ it('creates new array when field missing', () => {
115
+ expect(unionArrayField(undefined, 'x')).toEqual({ next: ['x'], added: true });
116
+ });
117
+
118
+ it('returns warning when existing value is not an array', () => {
119
+ const r = unionArrayField('not-an-array', 'x');
120
+ expect(r).toEqual({ warning: 'existing value is not an array, refusing to overwrite' });
121
+ });
122
+
123
+ it('returns added=false when entry already present', () => {
124
+ expect(unionArrayField(['a', 'b'], 'a')).toEqual({ next: ['a', 'b'], added: false });
125
+ });
126
+
127
+ it('appends entry when missing from array', () => {
128
+ expect(unionArrayField(['a'], 'b')).toEqual({ next: ['a', 'b'], added: true });
129
+ });
130
+ });
@@ -1,151 +1,151 @@
1
- /**
2
- * Generic JSON-config setup runner shared by `ccl setup <host>` subcommands.
3
- *
4
- * Each host adapter only supplies:
5
- * - resolveConfigPath(): where the host stores its global JSON config
6
- * - computePatch(current, opts): pure function returning the desired next config + change/warning notes
7
- *
8
- * The runner handles dry-run, diff, atomic write, and timestamped backup uniformly,
9
- * so adding a new host (gemini, claude-code, ...) is ~30 lines of glue.
10
- */
11
-
12
- import { existsSync, readFileSync, renameSync, copyFileSync, writeFileSync } from 'fs';
13
-
14
- export interface HostConfigPatcher<Opts extends object = Record<string, never>> {
15
- hostName: string;
16
- resolveConfigPath: () => string;
17
- computePatch: (current: unknown, opts: Opts) => HostPatchResult;
18
- }
19
-
20
- export interface HostPatchResult {
21
- next: unknown;
22
- changes: string[];
23
- warnings: string[];
24
- }
25
-
26
- export interface RunHostSetupFlags {
27
- yes?: boolean;
28
- print?: boolean;
29
- configPath?: string;
30
- backup?: boolean;
31
- }
32
-
33
- export interface RunHostSetupResult {
34
- exitCode: number;
35
- output: string[];
36
- }
37
-
38
- export function runHostConfigSetup<Opts extends object>(
39
- patcher: HostConfigPatcher<Opts>,
40
- hostOpts: Opts,
41
- flags: RunHostSetupFlags,
42
- ): RunHostSetupResult {
43
- const out: string[] = [];
44
- const configPath = flags.configPath ?? patcher.resolveConfigPath();
45
-
46
- if (flags.print) {
47
- const sample = patcher.computePatch({}, hostOpts);
48
- out.push(`# Recommended ${patcher.hostName} config patch:`);
49
- out.push(JSON.stringify(sample.next, null, 2));
50
- return { exitCode: 0, output: out };
51
- }
52
-
53
- if (!existsSync(configPath)) {
54
- out.push(`${patcher.hostName} config not found at: ${configPath}`);
55
- out.push(`Initialize it first (e.g. \`openclaw doctor\` for OpenClaw), then re-run.`);
56
- return { exitCode: 0, output: out };
57
- }
58
-
59
- let raw: string;
60
- try {
61
- raw = readFileSync(configPath, 'utf-8');
62
- } catch (err: any) {
63
- out.push(`Failed to read ${configPath}: ${err?.message ?? err}`);
64
- return { exitCode: 1, output: out };
65
- }
66
-
67
- let current: unknown;
68
- try {
69
- current = JSON.parse(raw);
70
- } catch (err: any) {
71
- out.push(`Failed to parse JSON at ${configPath}: ${err?.message ?? err}`);
72
- out.push(`Fix the JSON manually first; this tool does not edit malformed files.`);
73
- return { exitCode: 1, output: out };
74
- }
75
-
76
- const { next, changes, warnings } = patcher.computePatch(current, hostOpts);
77
-
78
- for (const w of warnings) out.push(`warning: ${w}`);
79
-
80
- if (changes.length === 0) {
81
- out.push(`${patcher.hostName} config already up to date at ${configPath}.`);
82
- return { exitCode: 0, output: out };
83
- }
84
-
85
- if (!flags.yes) {
86
- out.push(`Pending changes to ${configPath}:`);
87
- for (const c of changes) out.push(` - ${c}`);
88
- out.push(``);
89
- out.push(diffJson(current, next));
90
- out.push(``);
91
- out.push(`Dry-run only. Re-run with -y to apply.`);
92
- return { exitCode: 2, output: out };
93
- }
94
-
95
- let backupPath: string | undefined;
96
- if (flags.backup !== false) {
97
- const ts = new Date().toISOString().replace(/[:.]/g, '-');
98
- backupPath = `${configPath}.bak.${ts}`;
99
- try {
100
- copyFileSync(configPath, backupPath);
101
- } catch (err: any) {
102
- out.push(`Failed to back up ${configPath} → ${backupPath}: ${err?.message ?? err}`);
103
- return { exitCode: 1, output: out };
104
- }
105
- }
106
-
107
- const tmpPath = `${configPath}.tmp.${process.pid}`;
108
- try {
109
- const eol = raw.includes('\r\n') ? '\r\n' : '\n';
110
- const serialized = JSON.stringify(next, null, 2).replace(/\n/g, eol) + eol;
111
- writeFileSync(tmpPath, serialized, 'utf-8');
112
- renameSync(tmpPath, configPath);
113
- } catch (err: any) {
114
- out.push(`Failed to write ${configPath}: ${err?.message ?? err}`);
115
- return { exitCode: 1, output: out };
116
- }
117
-
118
- out.push(`Updated ${configPath}:`);
119
- for (const c of changes) out.push(` - ${c}`);
120
- if (backupPath) out.push(`Backup: ${backupPath}`);
121
- return { exitCode: 0, output: out };
122
- }
123
-
124
- /** Minimal line-level JSON diff for the dry-run preview. Self-contained, zero deps. */
125
- export function diffJson(before: unknown, after: unknown): string {
126
- const a = JSON.stringify(before, null, 2).split('\n');
127
- const b = JSON.stringify(after, null, 2).split('\n');
128
- const aSet = new Set(a);
129
- const bSet = new Set(b);
130
- const lines: string[] = [];
131
- const max = Math.max(a.length, b.length);
132
- for (let i = 0; i < max; i++) {
133
- const ax = a[i];
134
- const bx = b[i];
135
- if (ax === bx) {
136
- lines.push(` ${ax ?? ''}`);
137
- } else {
138
- if (ax !== undefined && !bSet.has(ax)) lines.push(`- ${ax}`);
139
- if (bx !== undefined && !aSet.has(bx)) lines.push(`+ ${bx}`);
140
- }
141
- }
142
- return lines.join('\n');
143
- }
144
-
145
- /** Shared helper for hosts: add an entry to an array field, returning a new array (Set union). */
146
- export function unionArrayField(arr: unknown, entry: string): { next: string[]; added: boolean } | { warning: string } {
147
- if (arr === undefined) return { next: [entry], added: true };
148
- if (!Array.isArray(arr)) return { warning: `existing value is not an array, refusing to overwrite` };
149
- if (arr.includes(entry)) return { next: arr.slice() as string[], added: false };
150
- return { next: [...(arr as string[]), entry], added: true };
151
- }
1
+ /**
2
+ * Generic JSON-config setup runner shared by `ccl setup <host>` subcommands.
3
+ *
4
+ * Each host adapter only supplies:
5
+ * - resolveConfigPath(): where the host stores its global JSON config
6
+ * - computePatch(current, opts): pure function returning the desired next config + change/warning notes
7
+ *
8
+ * The runner handles dry-run, diff, atomic write, and timestamped backup uniformly,
9
+ * so adding a new host (gemini, claude-code, ...) is ~30 lines of glue.
10
+ */
11
+
12
+ import { existsSync, readFileSync, renameSync, copyFileSync, writeFileSync } from 'fs';
13
+
14
+ export interface HostConfigPatcher<Opts extends object = Record<string, never>> {
15
+ hostName: string;
16
+ resolveConfigPath: () => string;
17
+ computePatch: (current: unknown, opts: Opts) => HostPatchResult;
18
+ }
19
+
20
+ export interface HostPatchResult {
21
+ next: unknown;
22
+ changes: string[];
23
+ warnings: string[];
24
+ }
25
+
26
+ export interface RunHostSetupFlags {
27
+ yes?: boolean;
28
+ print?: boolean;
29
+ configPath?: string;
30
+ backup?: boolean;
31
+ }
32
+
33
+ export interface RunHostSetupResult {
34
+ exitCode: number;
35
+ output: string[];
36
+ }
37
+
38
+ export function runHostConfigSetup<Opts extends object>(
39
+ patcher: HostConfigPatcher<Opts>,
40
+ hostOpts: Opts,
41
+ flags: RunHostSetupFlags,
42
+ ): RunHostSetupResult {
43
+ const out: string[] = [];
44
+ const configPath = flags.configPath ?? patcher.resolveConfigPath();
45
+
46
+ if (flags.print) {
47
+ const sample = patcher.computePatch({}, hostOpts);
48
+ out.push(`# Recommended ${patcher.hostName} config patch:`);
49
+ out.push(JSON.stringify(sample.next, null, 2));
50
+ return { exitCode: 0, output: out };
51
+ }
52
+
53
+ if (!existsSync(configPath)) {
54
+ out.push(`${patcher.hostName} config not found at: ${configPath}`);
55
+ out.push(`Initialize it first (e.g. \`openclaw doctor\` for OpenClaw), then re-run.`);
56
+ return { exitCode: 0, output: out };
57
+ }
58
+
59
+ let raw: string;
60
+ try {
61
+ raw = readFileSync(configPath, 'utf-8');
62
+ } catch (err: any) {
63
+ out.push(`Failed to read ${configPath}: ${err?.message ?? err}`);
64
+ return { exitCode: 1, output: out };
65
+ }
66
+
67
+ let current: unknown;
68
+ try {
69
+ current = JSON.parse(raw);
70
+ } catch (err: any) {
71
+ out.push(`Failed to parse JSON at ${configPath}: ${err?.message ?? err}`);
72
+ out.push(`Fix the JSON manually first; this tool does not edit malformed files.`);
73
+ return { exitCode: 1, output: out };
74
+ }
75
+
76
+ const { next, changes, warnings } = patcher.computePatch(current, hostOpts);
77
+
78
+ for (const w of warnings) out.push(`warning: ${w}`);
79
+
80
+ if (changes.length === 0) {
81
+ out.push(`${patcher.hostName} config already up to date at ${configPath}.`);
82
+ return { exitCode: 0, output: out };
83
+ }
84
+
85
+ if (!flags.yes) {
86
+ out.push(`Pending changes to ${configPath}:`);
87
+ for (const c of changes) out.push(` - ${c}`);
88
+ out.push(``);
89
+ out.push(diffJson(current, next));
90
+ out.push(``);
91
+ out.push(`Dry-run only. Re-run with -y to apply.`);
92
+ return { exitCode: 2, output: out };
93
+ }
94
+
95
+ let backupPath: string | undefined;
96
+ if (flags.backup !== false) {
97
+ const ts = new Date().toISOString().replace(/[:.]/g, '-');
98
+ backupPath = `${configPath}.bak.${ts}`;
99
+ try {
100
+ copyFileSync(configPath, backupPath);
101
+ } catch (err: any) {
102
+ out.push(`Failed to back up ${configPath} → ${backupPath}: ${err?.message ?? err}`);
103
+ return { exitCode: 1, output: out };
104
+ }
105
+ }
106
+
107
+ const tmpPath = `${configPath}.tmp.${process.pid}`;
108
+ try {
109
+ const eol = raw.includes('\r\n') ? '\r\n' : '\n';
110
+ const serialized = JSON.stringify(next, null, 2).replace(/\n/g, eol) + eol;
111
+ writeFileSync(tmpPath, serialized, 'utf-8');
112
+ renameSync(tmpPath, configPath);
113
+ } catch (err: any) {
114
+ out.push(`Failed to write ${configPath}: ${err?.message ?? err}`);
115
+ return { exitCode: 1, output: out };
116
+ }
117
+
118
+ out.push(`Updated ${configPath}:`);
119
+ for (const c of changes) out.push(` - ${c}`);
120
+ if (backupPath) out.push(`Backup: ${backupPath}`);
121
+ return { exitCode: 0, output: out };
122
+ }
123
+
124
+ /** Minimal line-level JSON diff for the dry-run preview. Self-contained, zero deps. */
125
+ export function diffJson(before: unknown, after: unknown): string {
126
+ const a = JSON.stringify(before, null, 2).split('\n');
127
+ const b = JSON.stringify(after, null, 2).split('\n');
128
+ const aSet = new Set(a);
129
+ const bSet = new Set(b);
130
+ const lines: string[] = [];
131
+ const max = Math.max(a.length, b.length);
132
+ for (let i = 0; i < max; i++) {
133
+ const ax = a[i];
134
+ const bx = b[i];
135
+ if (ax === bx) {
136
+ lines.push(` ${ax ?? ''}`);
137
+ } else {
138
+ if (ax !== undefined && !bSet.has(ax)) lines.push(`- ${ax}`);
139
+ if (bx !== undefined && !aSet.has(bx)) lines.push(`+ ${bx}`);
140
+ }
141
+ }
142
+ return lines.join('\n');
143
+ }
144
+
145
+ /** Shared helper for hosts: add an entry to an array field, returning a new array (Set union). */
146
+ export function unionArrayField(arr: unknown, entry: string): { next: string[]; added: boolean } | { warning: string } {
147
+ if (arr === undefined) return { next: [entry], added: true };
148
+ if (!Array.isArray(arr)) return { warning: `existing value is not an array, refusing to overwrite` };
149
+ if (arr.includes(entry)) return { next: arr.slice() as string[], added: false };
150
+ return { next: [...(arr as string[]), entry], added: true };
151
+ }
package/src/sdk/types.ts CHANGED
@@ -27,6 +27,8 @@ export enum ActionErrorCode {
27
27
  NO_SABOTAGE_COMPLETED = 'no_sabotage_completed',
28
28
  ROLE_CANNOT_KILL = 'role_cannot_kill',
29
29
  EMERGENCY_ALREADY_ACTIVE = 'emergency_already_active',
30
+ /** 动作撞上服务端冷却;具体冷却语义由 action 类型决定。 */
31
+ ON_COOLDOWN = 'on_cooldown',
30
32
  TARGET_UNREACHABLE = 'target_unreachable_or_too_far',
31
33
  PATH_NOT_FOUND = 'path_not_found',
32
34
  INVALID_POSITION = 'invalid_position_blocked',
@@ -18,6 +18,9 @@ import { emitLeaf, setBehavior, URGENT_GOAL_PRIORITY, WANDER_GOAL_PRIORITY } fro
18
18
  import { corpseReportWithNonTeammate, immediateLoneKillDecision } from './crab-octopus-reflexes.js';
19
19
 
20
20
  const SABOTAGE_ALARM_DEDUPE_MS = 90_000;
21
+ // 撞上 trigger_alarm 的 20s 阵营共享 CD 被服务端拒(on_cooldown)后,本地退避多久再补打。
22
+ // 退避期下沉去做任务/猎杀,避免原地空刷 trigger_alarm;远小于 CD,故 CD 一到很快补上。
23
+ const ALARM_RETRY_BACKOFF_MS = 4_000;
21
24
 
22
25
  /**
23
26
  * 蟹的「破坏 + 落单猎杀 + 任务伪装」编排 top。本身不产决策,每 tick 自上而下判定该走哪条分支、
@@ -38,6 +41,9 @@ export class CrabSabotageTop extends Goal {
38
41
  private readonly killCore = new LoneKillCore();
39
42
  private readonly patrol = new PatrolState();
40
43
  private readonly triggeredSabotageTasks = new Map<string, { at: number; tick: number | null }>();
44
+ // on_cooldown 反应式补打:上一发 trigger_alarm 打的任务 key,与退避到期时间戳。
45
+ private lastFiredAlarmKey: string | null = null;
46
+ private alarmRetryBlockedUntil = 0;
41
47
  private readonly loneKillGoal = new LoneKillGoal(this.killCore);
42
48
  private readonly emergencyHuntGoal = new EmergencyHuntGoal(this.killCore, this.patrol);
43
49
  private readonly wanderGoal = new WanderTaskGoal(
@@ -50,6 +56,15 @@ export class CrabSabotageTop extends Goal {
50
56
 
51
57
  onMeetingResume(): void {
52
58
  this.killCore.reset();
59
+ // 散会(meeting→wandering)时服务端把 trigger_alarm 阵营 CD 重置为 0,却**不清**已完成破坏
60
+ // (completed_sabotage_task_id 与 task_status 都留存)。本地这套去重是「同一游走阶段内防重复触发」,
61
+ // 跨会议后语义失效:那具破坏 CD 已清零可补打,却会被会前乐观写下的去重记录挡住——尤其撞 on_cooldown
62
+ // 后紧接开会时,回滚因会议跳过 decide 没跑,记录成了清不掉的孤儿(90s 后还得等新 task_sabotaged 才解封,
63
+ // 而已完成的破坏不会再发该事件 → 永久锁死)。整表清空与服务端 CD 重置对齐,下一阶段所有破坏均可重新触发
64
+ // (已成功触发过的至多多打一发被服务端以 no_sabotage_completed 拒,无害)。
65
+ this.triggeredSabotageTasks.clear();
66
+ this.lastFiredAlarmKey = null;
67
+ this.alarmRetryBlockedUntil = 0;
53
68
  }
54
69
 
55
70
  tick(state: GameState, ctx: StrategyContext): BehaviorDecision[] {
@@ -94,6 +109,19 @@ export class CrabSabotageTop extends Goal {
94
109
  if (ctx.emergency) return null;
95
110
 
96
111
  const now = Date.now();
112
+
113
+ // 上一发 trigger_alarm 撞了 20s 阵营共享 CD 被服务端拒(on_cooldown):那具破坏其实仍装填在
114
+ // 服务端、CD 一到就能打。撤掉刚才乐观打上的 90s 去重标记,并退避几秒再补打——退避期返回 null,
115
+ // 下沉去做任务/猎杀,不原地空刷 trigger_alarm。
116
+ if (ctx.alarmOnCooldown && this.lastFiredAlarmKey) {
117
+ this.triggeredSabotageTasks.delete(this.lastFiredAlarmKey);
118
+ this.lastFiredAlarmKey = null;
119
+ this.alarmRetryBlockedUntil = now + ALARM_RETRY_BACKOFF_MS;
120
+ // 一次性事件信号,消费即清:否则重试因破坏被解/开会/正做任务而没再提交下一发时,标记会滞留 true。
121
+ ctx.alarmOnCooldown = false;
122
+ }
123
+ if (now < this.alarmRetryBlockedUntil) return null;
124
+
97
125
  const completed = ctx.taskData.find(t =>
98
126
  t.faction === 'crab'
99
127
  && !t.is_fake_shrimp
@@ -102,8 +130,9 @@ export class CrabSabotageTop extends Goal {
102
130
  );
103
131
  if (completed && !state.you.doing_task) {
104
132
  this.markSabotageTriggered(completed, state, now);
133
+ this.lastFiredAlarmKey = this.sabotageTaskKey(completed);
105
134
  ctx.alarmDone = true;
106
- ctx.notifications.push('破坏任务完成,开启紧急警报!警报期照样会被举报,只清落单目标。');
135
+ ctx.notifications.push('破坏任务完成,触发紧急警报(撞阵营冷却会被拒、冷却好自动补打);警报期照样会被举报,只清落单目标。');
107
136
  return [{ action: Action.triggerAlarm() }];
108
137
  }
109
138
  return null;