@myclaw163/clawclaw-cli 0.6.96 → 0.6.101

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/bin/clawclaw-cli.mjs +3 -3
  2. package/package.json +1 -1
  3. package/skills/clawclaw/SKILL.md +26 -10
  4. package/skills/clawclaw/references/CLAUDE-CODE-MONITOR.md +1 -1
  5. package/skills/clawclaw/references/COMMANDS.md +17 -5
  6. package/skills/clawclaw/references/STREAM.md +15 -12
  7. package/src/commands/config.ts +30 -30
  8. package/src/commands/do.test.ts +27 -1
  9. package/src/commands/do.ts +61 -0
  10. package/src/commands/events.test.ts +21 -3
  11. package/src/commands/events.ts +8 -2
  12. package/src/commands/game-start-plan.test.ts +158 -0
  13. package/src/commands/game.ts +670 -64
  14. package/src/commands/history-player.test.ts +3 -0
  15. package/src/commands/setup/hermes.test.ts +96 -96
  16. package/src/commands/setup/hermes.ts +76 -76
  17. package/src/commands/setup/index.ts +13 -13
  18. package/src/commands/setup/openclaw.test.ts +124 -114
  19. package/src/commands/setup/openclaw.ts +162 -147
  20. package/src/commands/watch.test.ts +272 -0
  21. package/src/commands/watch.ts +185 -25
  22. package/src/lib/game-client.ts +34 -0
  23. package/src/lib/host-config-patcher.test.ts +130 -130
  24. package/src/lib/host-config-patcher.ts +151 -151
  25. package/src/lib/room.test.ts +74 -0
  26. package/src/lib/room.ts +129 -0
  27. package/src/lib/server-registry.test.ts +54 -0
  28. package/src/lib/server-registry.ts +35 -2
  29. package/src/perception/player-history-store.test.ts +92 -2
  30. package/src/perception/player-history-store.ts +68 -0
  31. package/src/pipeline/event-format.test.ts +61 -1
  32. package/src/pipeline/event-format.ts +88 -0
  33. package/src/pipeline/event-hints.ts +10 -1
  34. package/src/runtime/event-daemon.test.ts +43 -0
  35. package/src/runtime/event-daemon.ts +8 -4
  36. package/src/runtime/room-lobby-runtime.test.ts +95 -0
  37. package/src/runtime/room-lobby-runtime.ts +367 -0
@@ -12,7 +12,7 @@ import { hubReminder, readCachedGamesPlayed } from '../lib/hub-reminder.js';
12
12
  import { sendOwnerControlRequest } from '../runtime/owner-control.js';
13
13
 
14
14
  export const POLL_INTERVAL_MS = 220;
15
- const HEARTBEAT_INTERVAL_MS = 60_000;
15
+ const HEARTBEAT_INTERVAL_MS = 30_000;
16
16
  const RUNTIME_WAIT_MS = 30_000;
17
17
 
18
18
  export class WatchNotReadyError extends Error {
@@ -85,6 +85,24 @@ export const MONITOR_EVENT_CONFIG: Record<string, MonitorEventConfig> = {
85
85
  robot_speak_rule: { priority: 50 },
86
86
  // #endregion
87
87
 
88
+ // Room-mode lobby events
89
+ 'room.snapshot': { priority: 50 },
90
+ 'room.member_joined': { priority: 50 },
91
+ 'room.member_left': { priority: 50 },
92
+ 'room.owner_changed': { priority: 50 },
93
+ 'room.full': { priority: 60 },
94
+ 'room.chat': { priority: 50 },
95
+ 'room.game_starting': { priority: 80 },
96
+ 'room.game_started': { priority: 90 },
97
+ 'room.game_start_failed': { priority: 80 },
98
+ 'room.game_finished': { priority: 80 },
99
+ 'room.cooldown': { priority: 60 },
100
+ 'room.self_left': { priority: 80 },
101
+ room_self_left: { priority: 80 },
102
+ room_ready_to_start: { priority: 90 },
103
+ room_returning_to_lobby: { priority: 60 },
104
+ room_ping_timeout: { priority: 60 },
105
+
88
106
  // Strategy → agent real-time briefing (the automation explaining a decisive
89
107
  // autonomous move, e.g. self-reporting its own kill). Ranked above ambient
90
108
  // wander events so it leads the events[] list.
@@ -114,6 +132,19 @@ export interface GameEvent {
114
132
  export function eventKey(evt: GameEvent): string {
115
133
  const type = evt.type ?? '?';
116
134
  const tick = evt.tick ?? 0;
135
+ const roomDiscriminator = typeof type === 'string' && (type.startsWith('room.') || type.startsWith('room_'))
136
+ ? [
137
+ evt.room_code,
138
+ evt.status,
139
+ evt.agent_id,
140
+ evt.name,
141
+ evt.seat,
142
+ evt.content,
143
+ evt.reason,
144
+ Array.isArray(evt.members) ? evt.members.length : evt.member_count,
145
+ evt.ts,
146
+ ]
147
+ : [];
117
148
  const parts = [
118
149
  evt.actor_name,
119
150
  evt.spotted_name,
@@ -122,6 +153,7 @@ export function eventKey(evt: GameEvent): string {
122
153
  evt.target_name,
123
154
  evt.corpse_name,
124
155
  evt.task_name,
156
+ ...roomDiscriminator,
125
157
  ].filter(Boolean);
126
158
  const disc = parts.length > 0 ? parts.join('|') : '';
127
159
  return `${type}@${tick}#${disc}`;
@@ -146,6 +178,11 @@ interface RouteRule {
146
178
  nextStep: string;
147
179
  }
148
180
 
181
+ interface RouteContext {
182
+ summary?: any | null;
183
+ events?: Array<Record<string, any>>;
184
+ }
185
+
149
186
  const ROUTING_RULES: RouteRule[] = [
150
187
  { reason: 'speech_your_turn', match: (t) => t.includes('speech_your_turn'), nextStep: 'It is YOUR turn to speak. Submit `ccl do -s "<draft>"` immediately. Server skips you after 45s.' },
151
188
  { reason: 'role_assigned', match: (t) => t.includes('role_assigned'), nextStep: 'Tell user your role, faction, win condition, and first plan.' },
@@ -154,13 +191,30 @@ const ROUTING_RULES: RouteRule[] = [
154
191
  { reason: 'match_start', match: (t) => t.includes('match_start'), nextStep: 'Matchmaking queue entered. The game runtime is live and the stream is attached. Chat with the user while waiting for allocation.' },
155
192
  { reason: 'match_waiting', match: (t) => t.includes('match_waiting'), nextStep: 'Still in queue (see `events[].waited_secs`). Keep chatting with the user; no tactical action required.' },
156
193
  { reason: 'match_timeout', match: (t) => t.includes('match_timeout'), nextStep: `Cumulative wait reached ${Math.round(DEFAULT_MATCH_TIMEOUT_MS / 60_000)} min (see \`events[].waited_secs\`). The stream will exit — discuss with the user: launch a fresh \`ccl game start\` to retry, or call it a session.` },
194
+ { reason: 'room_ready_to_start', match: (t) => t.includes('room_ready_to_start') || t.includes('room.full'), nextStep: 'Room is full. Ask the user whether to start now before running `ccl game start-room`.' },
195
+ { reason: 'room_game_started', match: (t) => t.includes('room.game_started'), nextStep: 'Room match is starting. Stay attached; the runtime will switch to the GameServer stream.' },
196
+ { reason: 'room_game_finished', match: (t) => t.includes('room.game_finished'), nextStep: '上一轮房间对局已结束;如果你提前回房间等待,现在告知用户上局已结束,并继续留在房间。' },
197
+ { reason: 'room_self_left', match: (t) => t.includes('room.self_left') || t.includes('room_self_left'), nextStep: 'The user left the room from the web page, or the current CLI quit command has left the room. Stop the room flow and do not create or join another room unless the user asks.' },
157
198
  { reason: 'game_over', match: (t) => t.includes('game_over'), nextStep: 'Game ended. The current ccl game start process is exiting automatically. Review the result with the user; start another match only if the user asks.' },
158
199
  { reason: 'strategy_alert', match: (t) => t.includes('strategy_alert'), nextStep: 'Your automation just made a decisive autonomous move and is briefing you (read events[].message). Lock your story to it before you next speak or vote — e.g. if it reported a corpse that is likely your own kill, present yourself as the proactive reporter, steer suspicion onto the bystanders, and do NOT confess.' },
159
200
  ];
160
201
 
161
202
  const DEFAULT_NEXT_STEP = 'React to summary fields. No relaunch needed — the stream stays attached.';
203
+ const ROOM_GAME_OVER_NEXT_STEP = 'This room match round has ended. Wait for the room stream to resume; do not start normal matchmaking.';
204
+
205
+ function hasRoomGameContext(ctx?: RouteContext): boolean {
206
+ if (!ctx) return false;
207
+ if (ctx.summary?.game?.mode === 'room' || ctx.summary?.game_mode === 'room') return true;
208
+ return (ctx.events ?? []).some((event) => event.game_mode === 'room');
209
+ }
162
210
 
163
- function routeTriggers(triggers: string[]): { exitReason: string; nextStep: string } {
211
+ function routeTriggers(triggers: string[], ctx?: RouteContext): { exitReason: string; nextStep: string } {
212
+ if (triggers.includes('game_over') && hasRoomGameContext(ctx)) {
213
+ return {
214
+ exitReason: 'game_over',
215
+ nextStep: ROOM_GAME_OVER_NEXT_STEP,
216
+ };
217
+ }
164
218
  const rule = ROUTING_RULES.find((r) => r.match(triggers));
165
219
  return {
166
220
  exitReason: rule?.reason ?? triggers[0],
@@ -168,12 +222,12 @@ function routeTriggers(triggers: string[]): { exitReason: string; nextStep: stri
168
222
  };
169
223
  }
170
224
 
171
- export function nextStepFor(reason: string): string {
172
- return routeTriggers([reason]).nextStep;
225
+ export function nextStepFor(reason: string, ctx?: RouteContext): string {
226
+ return routeTriggers([reason], ctx).nextStep;
173
227
  }
174
228
 
175
- export function nextStepForTriggers(triggers: string[]): string {
176
- return routeTriggers(triggers).nextStep;
229
+ export function nextStepForTriggers(triggers: string[], ctx?: RouteContext): string {
230
+ return routeTriggers(triggers, ctx).nextStep;
177
231
  }
178
232
 
179
233
  export function sortEventsForMonitor(events: GameEvent[]): GameEvent[] {
@@ -230,6 +284,9 @@ export function summarizeFeed(feed: any): any | null {
230
284
  meeting: feed.meeting,
231
285
  };
232
286
  if (feed.automation) summary.automation = feed.automation;
287
+ if (typeof feed.phase === 'string' && feed.phase.startsWith('room_')) {
288
+ summary.room = feed.room;
289
+ }
233
290
  return summary;
234
291
  }
235
292
 
@@ -279,6 +336,30 @@ export function compactSummaryForMonitor(summary: any | null, triggers: string[]
279
336
  });
280
337
  }
281
338
 
339
+ function roomHeartbeatMessage(summary: any | null): string | null {
340
+ if (!summary || typeof summary.phase !== 'string' || !summary.phase.startsWith('room_')) return null;
341
+ const room = summary.room ?? {};
342
+ const label = typeof room.room_code === 'string' && room.room_code.length > 0
343
+ ? `房间 ${room.room_code}`
344
+ : '房间';
345
+ const count = typeof room.member_count === 'number'
346
+ ? room.member_count
347
+ : Array.isArray(room.members)
348
+ ? room.members.length
349
+ : undefined;
350
+ const countText = count === undefined ? '?/10' : `${count}/10`;
351
+ if (room.status === 'playing' || summary.phase === 'room_playing') {
352
+ return `${label} 上一轮对局仍在进行,正在等待其他玩家结束。`;
353
+ }
354
+ if (room.status === 'starting' || summary.phase === 'room_starting') {
355
+ return `${label} 对局正在开始,继续等待。`;
356
+ }
357
+ if (count !== undefined && count >= 10) {
358
+ return `${label} 当前 ${countText} 人,等待房主操作。`;
359
+ }
360
+ return `${label} 当前 ${countText} 人,正在等待更多玩家加入。`;
361
+ }
362
+
282
363
  export interface RunStreamingOptions {
283
364
  feedPath: string;
284
365
  sessionPath: string | null;
@@ -313,6 +394,13 @@ export interface RunStreamingOptions {
313
394
  * `initial_payload`.
314
395
  */
315
396
  emitGameStart?: boolean;
397
+ /**
398
+ * On intentional stream handoff, drain already-written events once more before
399
+ * returning so the next WS stage does not inherit them as backlog.
400
+ */
401
+ finalDrainOnAbort?: boolean | (() => boolean);
402
+ /** Max ms to wait for final written events during a handoff. Default 500ms. */
403
+ finalDrainTimeoutMs?: number;
316
404
  /**
317
405
  * When set, attached to the `game_over` emission (as a `hub_reminder` field
318
406
  * and appended to `next_step`) so the agent sees the nudge in the same beat it
@@ -423,7 +511,7 @@ export async function runStreaming(opts: RunStreamingOptions): Promise<void> {
423
511
 
424
512
  const buildOut = (
425
513
  triggers: string[],
426
- _nextStep: string,
514
+ nextStep: string,
427
515
  events: GameEvent[] = [],
428
516
  ): any => {
429
517
  const rawSummary = opts.readSummary?.() ?? readFeedSummary(opts.feedPath);
@@ -442,11 +530,16 @@ export async function runStreaming(opts: RunStreamingOptions): Promise<void> {
442
530
  if (sumCaller && e.caller && sumCaller !== e.caller) return e;
443
531
  return { ...e, speech_order: so };
444
532
  };
533
+ const heartbeatMessage = triggers.length === 1 && triggers[0] === 'heartbeat'
534
+ ? roomHeartbeatMessage(summary)
535
+ : null;
445
536
  const sourceEvents: GameEvent[] = events.length > 0
446
537
  ? sortEventsForMonitor(events).map(enrichMeetingBriefing)
447
- : triggers.map((type) => ({ type }));
538
+ : heartbeatMessage
539
+ ? [{ type: 'heartbeat', message: heartbeatMessage }]
540
+ : triggers.map((type) => ({ type }));
448
541
  const gameMode = sourceEvents.find(
449
- (event) => event.game_mode === 'match' || event.game_mode === 'competition',
542
+ (event) => event.game_mode === 'match' || event.game_mode === 'competition' || event.game_mode === 'room',
450
543
  )?.game_mode;
451
544
  const context = {
452
545
  summary,
@@ -458,6 +551,7 @@ export async function runStreaming(opts: RunStreamingOptions): Promise<void> {
458
551
  ...(gameMode ? { game_mode: gameMode } : {}),
459
552
  messages: sourceEvents.map((event) => formatEventMessage(event, context)),
460
553
  state: shortStateText(summary),
554
+ ...(nextStep === ROOM_GAME_OVER_NEXT_STEP ? { next_step: nextStep } : {}),
461
555
  };
462
556
  };
463
557
 
@@ -466,14 +560,90 @@ export async function runStreaming(opts: RunStreamingOptions): Promise<void> {
466
560
  triggeredEvents: GameEvent[],
467
561
  ): void => {
468
562
  if (triggers.length === 0) return;
469
- const { nextStep } = routeTriggers(triggers);
470
- const out = buildOut(triggers, nextStep, triggeredEvents.slice(-10));
563
+ const routeEvents = triggeredEvents.slice(-10);
564
+ const rawSummary = opts.readSummary?.() ?? readFeedSummary(opts.feedPath);
565
+ const { nextStep } = routeTriggers(triggers, { summary: rawSummary, events: routeEvents });
566
+ const out = buildOut(triggers, nextStep, routeEvents);
471
567
  if (opts.hubReminder && triggers.includes('game_over')) {
472
568
  out.hub_reminder = opts.hubReminder;
473
569
  }
474
570
  emit(out);
475
571
  };
476
572
 
573
+ const collectNotableEvents = (
574
+ events: GameEvent[],
575
+ triggers: string[],
576
+ triggeredEvents: GameEvent[],
577
+ ): void => {
578
+ for (const evt of events) {
579
+ const cls = classifyEvent(evt, youName);
580
+ if (!cls.notable) continue;
581
+ const key = eventKey(evt);
582
+ if (seenKeys.has(key)) continue;
583
+ seenKeys.add(key);
584
+ triggeredEvents.push(evt);
585
+ if (evt.type && !triggers.includes(evt.type)) {
586
+ triggers.push(evt.type);
587
+ }
588
+ }
589
+ };
590
+
591
+ const shouldFinalDrainOnAbort = (): boolean => {
592
+ if (typeof opts.finalDrainOnAbort === 'function') return opts.finalDrainOnAbort();
593
+ return opts.finalDrainOnAbort === true;
594
+ };
595
+
596
+ const waitForNextPoll = async (): Promise<void> => {
597
+ await new Promise<void>((resolve) => {
598
+ if (opts.signal?.aborted) {
599
+ resolve();
600
+ return;
601
+ }
602
+ let done = false;
603
+ let timer: ReturnType<typeof setTimeout> | null = null;
604
+ const finish = (): void => {
605
+ if (done) return;
606
+ done = true;
607
+ if (timer) clearTimeout(timer);
608
+ opts.signal?.removeEventListener('abort', finish);
609
+ resolve();
610
+ };
611
+ timer = setTimeout(finish, interval);
612
+ opts.signal?.addEventListener('abort', finish, { once: true });
613
+ });
614
+ };
615
+
616
+ const flushDelayBuffer = (triggers: string[], triggeredEvents: GameEvent[]): void => {
617
+ for (const t of delayBuffer.triggers) {
618
+ if (!triggers.includes(t)) triggers.push(t);
619
+ }
620
+ triggeredEvents.push(...delayBuffer.events);
621
+ delayBuffer.triggers.clear();
622
+ delayBuffer.events.length = 0;
623
+ delayActive = false;
624
+ };
625
+
626
+ const finalDrain = async (): Promise<void> => {
627
+ if (!shouldFinalDrainOnAbort()) return;
628
+ const deadline = Date.now() + (opts.finalDrainTimeoutMs ?? 500);
629
+ while (Date.now() <= deadline) {
630
+ refreshSessionPath();
631
+ const triggers: string[] = [];
632
+ const triggeredEvents: GameEvent[] = [];
633
+ if (delayBuffer.triggers.size > 0 || delayBuffer.events.length > 0) {
634
+ flushDelayBuffer(triggers, triggeredEvents);
635
+ }
636
+ collectNotableEvents(drainNewEvents(), triggers, triggeredEvents);
637
+ if (triggers.length > 0) {
638
+ fireTrigger(triggers, triggeredEvents);
639
+ return;
640
+ }
641
+ const remaining = deadline - Date.now();
642
+ if (remaining <= 0) break;
643
+ await new Promise((r) => setTimeout(r, Math.min(20, remaining)));
644
+ }
645
+ };
646
+
477
647
  // Always emit an attached first beat when there is a pre-attach backlog OR
478
648
  // the caller explicitly requests one.
479
649
  if (caughtUpEvents.length > 0 || opts.emitGameStart) {
@@ -503,18 +673,7 @@ export async function runStreaming(opts: RunStreamingOptions): Promise<void> {
503
673
  const triggers: string[] = [];
504
674
  const triggeredEvents: GameEvent[] = [];
505
675
 
506
- const newEvents = drainNewEvents();
507
- for (const evt of newEvents) {
508
- const cls = classifyEvent(evt, youName);
509
- if (!cls.notable) continue;
510
- const key = eventKey(evt);
511
- if (seenKeys.has(key)) continue;
512
- seenKeys.add(key);
513
- triggeredEvents.push(evt);
514
- if (evt.type && !triggers.includes(evt.type)) {
515
- triggers.push(evt.type);
516
- }
517
- }
676
+ collectNotableEvents(drainNewEvents(), triggers, triggeredEvents);
518
677
 
519
678
  // ── Delay buffer: merge rapid-fire wandering-phase events ──
520
679
  // Only active during wandering; meeting-phase events (my_turn, speech, etc.)
@@ -555,7 +714,7 @@ export async function runStreaming(opts: RunStreamingOptions): Promise<void> {
555
714
 
556
715
  if (triggers.length > 0) {
557
716
  fireTrigger(triggers, triggeredEvents);
558
- if (triggers.includes('game_over') || triggers.includes('user_left_game')) return;
717
+ if (triggers.includes('game_over') || triggers.includes('user_left_game') || triggers.includes('room.self_left') || triggers.includes('room_self_left')) return;
559
718
  } else if (!delayActive && heartbeatInterval > 0 && Date.now() - lastEmitMs >= heartbeatInterval) {
560
719
  // Idle keepalive — prevents downstream adapters from interpreting a quiet
561
720
  // wandering/transit period as a hung subprocess and killing it on their
@@ -567,8 +726,9 @@ export async function runStreaming(opts: RunStreamingOptions): Promise<void> {
567
726
  }
568
727
 
569
728
  if (opts.signal?.aborted) break;
570
- await new Promise((r) => setTimeout(r, interval));
729
+ await waitForNextPoll();
571
730
  }
731
+ if (opts.signal?.aborted) await finalDrain();
572
732
  }
573
733
 
574
734
  export interface SnapshotOnceOptions {
@@ -225,6 +225,40 @@ export class GameClient {
225
225
  return this.http.post('/api/v1/game/leave');
226
226
  }
227
227
 
228
+ // ─── Room API (→ lobby) ───
229
+
230
+ async createRoom(): Promise<any> {
231
+ return this.http.post('/api/v1/room/create');
232
+ }
233
+
234
+ async joinRoom(roomCode: string): Promise<any> {
235
+ return this.http.post('/api/v1/room/join', { room_code: roomCode });
236
+ }
237
+
238
+ async leaveRoom(): Promise<any> {
239
+ return this.http.post('/api/v1/room/leave');
240
+ }
241
+
242
+ async startRoom(): Promise<any> {
243
+ return this.http.post('/api/v1/room/start');
244
+ }
245
+
246
+ async chatRoom(content: string): Promise<any> {
247
+ return this.http.post('/api/v1/room/chat', { content });
248
+ }
249
+
250
+ get lobbyAgentWsUrl(): string {
251
+ return this.registry.lobbyAgentWsUrl;
252
+ }
253
+
254
+ setRoomGameServer(gameServerName: string): void {
255
+ this.registry.setGatewayGameServerName(gameServerName);
256
+ }
257
+
258
+ setGameServerUrl(url: string): void {
259
+ this.registry.setGameServerUrl(url);
260
+ }
261
+
228
262
  async getRoleInfo(): Promise<any> {
229
263
  return this.http.get('/api/v1/game/role_info');
230
264
  }
@@ -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
+ });