@ramarivera/coding-buddy 0.4.0-alpha.9 → 0.6.0

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 (92) hide show
  1. package/{adapters/claude/plugin → .claude-plugin}/marketplace.json +11 -6
  2. package/{adapters/claude/plugin → .claude-plugin}/plugin.json +7 -3
  3. package/LICENSE +1 -1
  4. package/README.md +88 -37
  5. package/adapters/omp/commands.ts +201 -0
  6. package/adapters/omp/context.ts +22 -0
  7. package/adapters/omp/events.ts +551 -0
  8. package/adapters/omp/identity.ts +10 -0
  9. package/adapters/omp/index.ts +39 -0
  10. package/adapters/omp/logger.ts +52 -0
  11. package/adapters/omp/prompt.ts +60 -0
  12. package/adapters/omp/renderers.ts +73 -0
  13. package/adapters/omp/storage.ts +25 -0
  14. package/adapters/omp/ui.ts +85 -0
  15. package/adapters/pi/commands.ts +64 -37
  16. package/adapters/pi/events.ts +147 -72
  17. package/adapters/pi/index.ts +9 -4
  18. package/adapters/pi/storage.ts +14 -285
  19. package/adapters/pi/ui.ts +56 -5
  20. package/adapters/shared/file-storage.ts +526 -0
  21. package/{adapters/claude/install → cli}/backup.ts +130 -33
  22. package/cli/buddy-shell.ts +1 -1
  23. package/{adapters/claude/install → cli}/disable.ts +19 -32
  24. package/cli/doctor.ts +231 -0
  25. package/{adapters/claude/install → cli}/hunt.ts +7 -9
  26. package/cli/index.ts +30 -26
  27. package/{adapters/claude/install → cli}/install.ts +65 -83
  28. package/{adapters/claude/install → cli}/pick.ts +111 -50
  29. package/{adapters/claude/install → cli}/settings.ts +2 -2
  30. package/{adapters/claude/install → cli}/show.ts +4 -4
  31. package/{adapters/claude/install → cli}/test-statusline.sh +2 -2
  32. package/{adapters/claude/install → cli}/test-statusline.ts +21 -11
  33. package/cli/tui.tsx +106 -17
  34. package/{adapters/claude/install → cli}/uninstall.ts +40 -47
  35. package/cli/upgrade.ts +2 -2
  36. package/cli/validate-species.ts +209 -0
  37. package/cli/verify.ts +3 -3
  38. package/core/achievements.ts +12 -20
  39. package/core/art-data.ts +26 -0
  40. package/core/command-service.ts +99 -97
  41. package/core/engine.ts +83 -1
  42. package/core/ports.ts +10 -0
  43. package/core/reactions.ts +533 -95
  44. package/core/slot-slug.ts +22 -0
  45. package/{adapters/claude/hooks → hooks}/buddy-comment.sh +19 -1
  46. package/hooks/file-type-react.sh +401 -0
  47. package/hooks/hooks.json +52 -0
  48. package/hooks/mood-react.sh +208 -0
  49. package/{adapters/claude/hooks → hooks}/name-react.sh +1 -1
  50. package/hooks/react.sh +1368 -0
  51. package/hooks/suggest.sh +55 -0
  52. package/package.json +70 -31
  53. package/scripts/gen-emoji-widths.ts +34 -0
  54. package/scripts/paths.sh +17 -1
  55. package/scripts/postinstall.cjs +42 -0
  56. package/scripts/snapshot-statusline.sh +54 -0
  57. package/server/achievements.ts +1419 -15
  58. package/server/art.ts +450 -1
  59. package/server/award-xp.ts +48 -0
  60. package/server/check-suggestions.ts +102 -0
  61. package/server/consolidate.ts +33 -0
  62. package/{adapters/claude/server → server}/index.ts +556 -95
  63. package/server/mcp-launcher.sh +16 -6
  64. package/server/memory.ts +404 -0
  65. package/server/mood.ts +254 -0
  66. package/server/path.ts +70 -18
  67. package/server/shift-mood.ts +43 -0
  68. package/server/state.ts +540 -3
  69. package/server/suggestions.ts +335 -0
  70. package/server/theme.ts +53 -0
  71. package/server/xp.ts +435 -0
  72. package/{adapters/claude/skills → skills}/buddy/SKILL.md +36 -7
  73. package/statusline/buddy-status.sh +397 -0
  74. package/statusline/combined-status.sh +134 -0
  75. package/statusline/emoji-widths.data +4 -0
  76. package/adapters/claude/hooks/hooks.json +0 -35
  77. package/adapters/claude/hooks/react.sh +0 -207
  78. package/adapters/claude/install/doctor.ts +0 -172
  79. package/adapters/claude/rendering/art.ts +0 -264
  80. package/adapters/claude/server/instructions.ts +0 -24
  81. package/adapters/claude/server/path.ts +0 -12
  82. package/adapters/claude/server/resources.ts +0 -38
  83. package/adapters/claude/statusline/buddy-status.sh +0 -408
  84. package/adapters/claude/storage/achievements.ts +0 -253
  85. package/adapters/claude/storage/identity.ts +0 -13
  86. package/adapters/claude/storage/paths.ts +0 -33
  87. package/adapters/claude/storage/settings.ts +0 -91
  88. package/adapters/claude/storage/state.ts +0 -365
  89. package/adapters/pi/README.md +0 -83
  90. package/adapters/pi/tools.ts +0 -6
  91. package/server/engine.ts +0 -1
  92. package/server/reactions.ts +0 -1
package/server/path.ts CHANGED
@@ -1,30 +1,82 @@
1
- import {
2
- getBuddySkillDir,
3
- getBuddyStateDir,
4
- getClaudeConfigDir,
5
- getClaudeJsonPath,
6
- getClaudeSettingsPath,
7
- toUnixPath,
8
- } from "../adapters/claude/storage/paths.ts";
1
+ // Path utilities and helpers
2
+ //
3
+ // Two related concerns live here:
4
+ // 1. Path normalization (Windows compat) — toUnixPath().
5
+ // 2. Resolution of Claude Code config / state paths — claudeConfigDir,
6
+ // claudeSettingsPath, claudeSkillDir, claudeUserConfigPath, buddyStateDir.
7
+ // These honor CLAUDE_CONFIG_DIR so coding-buddy works with Claude Code's
8
+ // multi-account layout (one CLAUDE_CONFIG_DIR per profile).
9
+ //
10
+ // The shell counterpart of (2) lives in scripts/paths.sh and MUST stay in sync.
11
+
12
+ import { join } from "path";
13
+ import { homedir } from "os";
14
+
15
+ // ─── (1) Path normalization ─────────────────────────────────────────────────
16
+
17
+ // Node's path.join() produces backslash paths on Windows, which bash treats as
18
+ // escape sequences, stripping them entirely (e.g. C:\Users -> C:Users).
19
+ // Use forward slashes in all paths written to config files.
20
+
21
+ /**
22
+ * Converts all backslashes in a file path to forward slashes, producing a Unix-style path.
23
+ *
24
+ * @param p - The file path to convert.
25
+ * @returns The converted path with forward slashes.
26
+ */
27
+ export function toUnixPath(p: string): string {
28
+ return p.replace(/\\/g, "/");
29
+ }
30
+
31
+ // ─── (2) Claude config / state path resolvers ───────────────────────────────
32
+ //
33
+ // Resolution rules:
34
+ // - If CLAUDE_CONFIG_DIR is set: everything lives under
35
+ // $CLAUDE_CONFIG_DIR/. .claude.json is preferred inside the config dir
36
+ // when present, falling back to $HOME/.claude.json for setups that
37
+ // keep it at $HOME. Buddy state goes to $CLAUDE_CONFIG_DIR/buddy-state.
38
+ // - If CLAUDE_CONFIG_DIR is NOT set: the single-profile defaults —
39
+ // ~/.claude/, ~/.claude.json, ~/.claude-buddy/.
40
+
41
+ function envDir(name: string): string | undefined {
42
+ const v = process.env[name];
43
+ return v && v.length > 0 ? v : undefined;
44
+ }
9
45
 
10
46
  export function claudeConfigDir(): string {
11
- return getClaudeConfigDir();
47
+ return envDir("CLAUDE_CONFIG_DIR") ?? join(homedir(), ".claude");
12
48
  }
13
49
 
14
50
  export function claudeSettingsPath(): string {
15
- return getClaudeSettingsPath();
51
+ return join(claudeConfigDir(), "settings.json");
16
52
  }
17
53
 
18
- export function claudeUserConfigPath(): string {
19
- return getClaudeJsonPath();
54
+ export function claudeSkillDir(name: string): string {
55
+ return join(claudeConfigDir(), "skills", name);
20
56
  }
21
57
 
22
- export function buddyStateDir(): string {
23
- return getBuddyStateDir();
58
+ /**
59
+ * Resolve the path to Claude Code's user-config file (.claude.json).
60
+ *
61
+ * When CLAUDE_CONFIG_DIR is set the file lives inside it — we always
62
+ * resolve there so every read and write stays profile-scoped. Falling
63
+ * back to $HOME/.claude.json when the in-dir file is missing would
64
+ * break that isolation: installs in one profile could mutate the
65
+ * home-level file that a different profile reads. If the in-dir file
66
+ * doesn't exist yet, callers surface a clear "Start Claude Code once
67
+ * first" preflight error instead of silently writing to $HOME.
68
+ *
69
+ * When CLAUDE_CONFIG_DIR is unset we use $HOME/.claude.json — the
70
+ * single-profile default.
71
+ */
72
+ export function claudeUserConfigPath(): string {
73
+ const cfgDir = envDir("CLAUDE_CONFIG_DIR");
74
+ if (cfgDir) return join(cfgDir, ".claude.json");
75
+ return join(homedir(), ".claude.json");
24
76
  }
25
77
 
26
- export function claudeSkillDir(_name: string): string {
27
- return getBuddySkillDir();
78
+ export function buddyStateDir(): string {
79
+ const cfgDir = envDir("CLAUDE_CONFIG_DIR");
80
+ if (cfgDir) return join(cfgDir, "buddy-state");
81
+ return join(homedir(), ".claude-buddy");
28
82
  }
29
-
30
- export { toUnixPath };
@@ -0,0 +1,43 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * Lightweight mood shifting script — called from shell hooks.
4
+ * Shifts mood based on coding events.
5
+ *
6
+ * Usage:
7
+ * bun run server/shift-mood.ts <trigger> [slot]
8
+ *
9
+ * Triggers: tests_pass | tests_fail | error | large_diff | achievement | long_session | idle | rest
10
+ */
11
+
12
+ import { shiftMood, MOOD_NAMES, MOOD_COLORS } from "./mood";
13
+ import type { MoodTrigger } from "./mood";
14
+
15
+ const VALID_TRIGGERS = new Set([
16
+ "tests_pass",
17
+ "tests_fail",
18
+ "error",
19
+ "large_diff",
20
+ "achievement",
21
+ "long_session",
22
+ "idle",
23
+ "rest",
24
+ ]);
25
+
26
+ function main(): void {
27
+ const trigger = process.argv[2] as string;
28
+
29
+ if (!trigger || !VALID_TRIGGERS.has(trigger)) {
30
+ console.error(
31
+ `Usage: bun run server/shift-mood.ts <trigger>\nValid triggers: ${[...VALID_TRIGGERS].join(" | ")}`,
32
+ );
33
+ process.exit(1);
34
+ }
35
+
36
+ const state = shiftMood(trigger as MoodTrigger);
37
+ const mood = state.current;
38
+ const color = MOOD_COLORS[mood] ?? "💫";
39
+ const name = MOOD_NAMES[mood] ?? mood;
40
+ console.log(`Mood: ${color} ${name} (intensity ${state.intensity}/3)`);
41
+ }
42
+
43
+ main();
package/server/state.ts CHANGED
@@ -1,3 +1,540 @@
1
- export * from "../adapters/claude/storage/state.ts";
2
- export { resolveUserId } from "../adapters/claude/storage/identity.ts";
3
- export { setBuddyStatusLine, unsetBuddyStatusLine, cleanupPluginState } from "../adapters/claude/storage/settings.ts";
1
+ /**
2
+ * State management — reads/writes companion data to the buddy state dir.
3
+ *
4
+ * The state dir resolves via server/paths.ts (honors CLAUDE_CONFIG_DIR).
5
+ * Default: ~/.claude-buddy/. With CLAUDE_CONFIG_DIR set:
6
+ * $CLAUDE_CONFIG_DIR/buddy-state/.
7
+ *
8
+ * Storage layout (v3 — single manifest):
9
+ * <state-dir>/
10
+ * menagerie.json <- SSOT: { active, companions: { [slot]: Companion } }
11
+ * reaction.$SID.json <- transient reaction state (session-scoped)
12
+ * status.json <- compact state for the status-line shell script
13
+ * config.json <- user preferences (cooldown, bubble style, etc.)
14
+ *
15
+ * Rules:
16
+ * - saveCompanionSlot() APPENDS only — throws if the slot already exists
17
+ * - saveCompanion() UPDATES the currently-active slot (rename / personality)
18
+ * - All manifest writes are atomic (write tmp -> rename)
19
+ *
20
+ * Combined: PR #4 menagerie + PR #6 session isolation + config
21
+ */
22
+
23
+ import {
24
+ readFileSync,
25
+ writeFileSync,
26
+ mkdirSync,
27
+ existsSync,
28
+ readdirSync,
29
+ renameSync,
30
+ rmSync,
31
+ } from "fs";
32
+ import { join } from "path";
33
+ import type { Companion } from "../core/engine.ts"
34
+ import {
35
+ buddyStateDir,
36
+ claudeSettingsPath,
37
+ claudeUserConfigPath,
38
+ toUnixPath,
39
+ } from "./path.ts";
40
+
41
+ export const STATE_DIR = buddyStateDir();
42
+ const MANIFEST_FILE = join(STATE_DIR, "menagerie.json");
43
+ const CONFIG_FILE = join(STATE_DIR, "config.json");
44
+
45
+ // ─── Session ID (PR #6: tmux session isolation) ─────────────────────────────
46
+
47
+ function sessionId(): string {
48
+ const pane = process.env.TMUX_PANE;
49
+ if (!pane) return "default";
50
+ return pane.replace(/^%/, "");
51
+ }
52
+
53
+ function reactionFile(): string {
54
+ return join(STATE_DIR, `reaction.${sessionId()}.json`);
55
+ }
56
+
57
+ // ─── Manifest schema ─────────────────────────────────────────────────────────
58
+
59
+ interface Manifest {
60
+ active: string;
61
+ companions: Record<string, Companion>;
62
+ }
63
+
64
+ function emptyManifest(): Manifest {
65
+ return { active: "buddy", companions: {} };
66
+ }
67
+
68
+ // ─── Atomic manifest I/O ─────────────────────────────────────────────────────
69
+
70
+ function loadManifest(): Manifest {
71
+ try {
72
+ const raw = readFileSync(MANIFEST_FILE, "utf8");
73
+ const m = JSON.parse(raw) as Manifest;
74
+ if (!m.companions) m.companions = {};
75
+ return m;
76
+ } catch {
77
+ return emptyManifest();
78
+ }
79
+ }
80
+
81
+ function saveManifest(m: Manifest): void {
82
+ mkdirSync(STATE_DIR, { recursive: true });
83
+ const tmp = MANIFEST_FILE + ".tmp";
84
+ writeFileSync(tmp, JSON.stringify(m, null, 2));
85
+ renameSync(tmp, MANIFEST_FILE); // atomic on same filesystem
86
+ }
87
+
88
+ // ─── Slot helpers ────────────────────────────────────────────────────────────
89
+
90
+ /** Normalise a string to a safe slot key (a-z0-9-, max 14 chars). */
91
+ export function slugify(name: string): string {
92
+ return (
93
+ name
94
+ .toLowerCase()
95
+ .replace(/[^a-z0-9-]/g, "-")
96
+ .replace(/-+/g, "-")
97
+ .replace(/^-|-$/g, "")
98
+ .slice(0, 14) || "buddy"
99
+ );
100
+ }
101
+
102
+ /**
103
+ * Return a random fallback name whose slug is not already in the manifest.
104
+ * Falls back to "buddy-<random 3 digits>" if all names are taken.
105
+ */
106
+ export function unusedName(): string {
107
+ const { generateFallbackName } =
108
+ require("../core/reactions.ts") as typeof import("../core/reactions.ts");
109
+ const taken = new Set(Object.keys(loadManifest().companions));
110
+ for (let i = 0; i < 50; i++) {
111
+ const n = generateFallbackName();
112
+ if (!taken.has(slugify(n))) return n;
113
+ }
114
+ let suffix = 0;
115
+ while (taken.has(`buddy-${suffix}`)) suffix++;
116
+ return `buddy-${suffix}`;
117
+ }
118
+
119
+ // ─── Active slot ─────────────────────────────────────────────────────────────
120
+
121
+ export function loadActiveSlot(): string {
122
+ const m = loadManifest();
123
+ if (m.active && m.companions[m.active]) return m.active;
124
+ const first = Object.keys(m.companions)[0];
125
+ if (first) {
126
+ m.active = first;
127
+ saveManifest(m);
128
+ return first;
129
+ }
130
+ return "buddy";
131
+ }
132
+
133
+ export function saveActiveSlot(slot: string): void {
134
+ const m = loadManifest();
135
+ m.active = slot;
136
+ saveManifest(m);
137
+ }
138
+
139
+ // ─── Companion slot API ───────────────────────────────────────────────────────
140
+
141
+ export function loadCompanionSlot(slot: string): Companion | null {
142
+ return loadManifest().companions[slot] ?? null;
143
+ }
144
+
145
+ /**
146
+ * APPEND a new companion to the manifest.
147
+ * Throws if the slot already exists — use saveCompanion() to update an existing buddy.
148
+ */
149
+ export function saveCompanionSlot(companion: Companion, slot: string): void {
150
+ const m = loadManifest();
151
+ if (m.companions[slot]) {
152
+ throw new Error(`Slot "${slot}" already exists. Choose a different name.`);
153
+ }
154
+ m.companions[slot] = companion;
155
+ saveManifest(m);
156
+ }
157
+
158
+ /**
159
+ * UPDATE an existing (possibly non-active) companion slot.
160
+ * Throws if the slot does not exist.
161
+ */
162
+ export function updateCompanionSlot(slot: string, companion: Companion): void {
163
+ const m = loadManifest();
164
+ if (!m.companions[slot]) {
165
+ throw new Error(`Slot "${slot}" does not exist.`);
166
+ }
167
+ m.companions[slot] = companion;
168
+ saveManifest(m);
169
+ }
170
+
171
+ export function deleteCompanionSlot(slot: string): void {
172
+ const m = loadManifest();
173
+ delete m.companions[slot];
174
+ if (m.active === slot) {
175
+ m.active = Object.keys(m.companions)[0] ?? "buddy";
176
+ }
177
+ saveManifest(m);
178
+ }
179
+
180
+ export function listCompanionSlots(): Array<{
181
+ slot: string;
182
+ companion: Companion;
183
+ }> {
184
+ return Object.entries(loadManifest().companions).map(([slot, companion]) => ({
185
+ slot,
186
+ companion,
187
+ }));
188
+ }
189
+
190
+ // ─── Primary companion API ────────────────────────────────────────────────────
191
+
192
+ export function loadCompanion(): Companion | null {
193
+ migrateIfNeeded();
194
+ const m = loadManifest();
195
+ return m.companions[m.active] ?? null;
196
+ }
197
+
198
+ /**
199
+ * UPDATE the currently-active companion (rename, personality changes, etc.).
200
+ * This is the ONLY intentional in-place update path.
201
+ */
202
+ export function saveCompanion(companion: Companion): void {
203
+ const m = loadManifest();
204
+ m.companions[m.active] = companion;
205
+ saveManifest(m);
206
+ }
207
+
208
+ // ─── Migration: legacy companion.json -> single manifest ────────────────────
209
+
210
+ function migrateIfNeeded(): void {
211
+ if (existsSync(MANIFEST_FILE)) return;
212
+
213
+ const companions: Record<string, Companion> = {};
214
+ let active = "buddy";
215
+
216
+ // Absorb menagerie/<slot>.json files
217
+ const menagerieDir = join(STATE_DIR, "menagerie");
218
+ if (existsSync(menagerieDir)) {
219
+ try {
220
+ for (const f of readdirSync(menagerieDir).filter((f) =>
221
+ f.endsWith(".json"),
222
+ )) {
223
+ const slot = f.slice(0, -5);
224
+ try {
225
+ companions[slot] = JSON.parse(
226
+ readFileSync(join(menagerieDir, f), "utf8"),
227
+ );
228
+ } catch {
229
+ /* skip malformed */
230
+ }
231
+ }
232
+ } catch {
233
+ /* noop */
234
+ }
235
+ }
236
+
237
+ // Absorb legacy companion.json
238
+ const legacyFile = join(STATE_DIR, "companion.json");
239
+ if (existsSync(legacyFile) && Object.keys(companions).length === 0) {
240
+ try {
241
+ const c: Companion = JSON.parse(readFileSync(legacyFile, "utf8"));
242
+ const slot = slugify(c.name);
243
+ companions[slot] = c;
244
+ active = slot;
245
+ } catch {
246
+ /* noop */
247
+ }
248
+ }
249
+
250
+ // Read active pointer if it exists
251
+ const activeFile = join(STATE_DIR, "active");
252
+ if (existsSync(activeFile)) {
253
+ try {
254
+ const a = readFileSync(activeFile, "utf8").trim();
255
+ if (a && companions[a]) active = a;
256
+ } catch {
257
+ /* noop */
258
+ }
259
+ }
260
+
261
+ if (Object.keys(companions).length > 0) {
262
+ active = active && companions[active] ? active : Object.keys(companions)[0];
263
+ }
264
+
265
+ saveManifest({ active, companions });
266
+ }
267
+
268
+ // ─── Reaction state (session-scoped for tmux isolation) ──────────────────────
269
+
270
+ export interface ReactionState {
271
+ reaction: string;
272
+ timestamp: number;
273
+ reason: string;
274
+ }
275
+
276
+ export function loadReaction(): ReactionState | null {
277
+ try {
278
+ const data: ReactionState = JSON.parse(readFileSync(reactionFile(), "utf8"));
279
+ const { reactionTTL } = loadConfig();
280
+ if (reactionTTL > 0 && Date.now() - data.timestamp > reactionTTL * 1000) return null;
281
+ return data;
282
+ } catch {
283
+ return null;
284
+ }
285
+ }
286
+
287
+ export function saveReaction(reaction: string, reason: string): void {
288
+ mkdirSync(STATE_DIR, { recursive: true });
289
+ const state: ReactionState = { reaction, timestamp: Date.now(), reason };
290
+ writeFileSync(reactionFile(), JSON.stringify(state));
291
+ }
292
+
293
+ // ─── Identity resolution ─────────────────────────────────────────────────────
294
+
295
+ export function resolveUserId(): string {
296
+ try {
297
+ const claudeJson = JSON.parse(readFileSync(claudeUserConfigPath(), "utf8"));
298
+ return claudeJson.oauthAccount?.accountUuid ?? claudeJson.userID ?? "anon";
299
+ } catch {
300
+ return "anon";
301
+ }
302
+ }
303
+
304
+ // ─── Config persistence (PR #6: tmux popup settings) ─────────────────────────
305
+
306
+ export interface BuddyConfig {
307
+ commentCooldown: number;
308
+ reactionTTL: number;
309
+ bubbleStyle: "classic" | "round";
310
+ bubblePosition: "top" | "left";
311
+ showRarity: boolean;
312
+ statusLineEnabled: boolean;
313
+ bubbleWidth: number;
314
+ bubbleMargin: number;
315
+ useCombinedStatus: boolean;
316
+ rainbowColors?: string[];
317
+ theme: "dark" | "light" | "auto";
318
+ moodEnabled: boolean;
319
+ memoryEnabled: boolean;
320
+ suggestionsEnabled: boolean;
321
+ suggestionCooldown: number;
322
+ }
323
+
324
+ const DEFAULT_CONFIG: BuddyConfig = {
325
+ commentCooldown: 30,
326
+ reactionTTL: 0,
327
+ bubbleStyle: "classic",
328
+ bubblePosition: "top",
329
+ showRarity: true,
330
+ statusLineEnabled: false,
331
+ bubbleWidth: 28,
332
+ bubbleMargin: 8,
333
+ useCombinedStatus: false,
334
+ theme: "auto",
335
+ moodEnabled: true,
336
+ memoryEnabled: true,
337
+ suggestionsEnabled: true,
338
+ suggestionCooldown: 180,
339
+ };
340
+
341
+ export function loadConfig(): BuddyConfig {
342
+ try {
343
+ const data = JSON.parse(readFileSync(CONFIG_FILE, "utf8"));
344
+ return { ...DEFAULT_CONFIG, ...data };
345
+ } catch {
346
+ return { ...DEFAULT_CONFIG };
347
+ }
348
+ }
349
+
350
+ export function saveConfig(config: Partial<BuddyConfig>): BuddyConfig {
351
+ mkdirSync(STATE_DIR, { recursive: true });
352
+ const current = loadConfig();
353
+ const merged = { ...current, ...config };
354
+ writeFileSync(CONFIG_FILE, JSON.stringify(merged, null, 2));
355
+ return merged;
356
+ }
357
+
358
+ // ─── Status line state (compact JSON for the shell script) ───────────────────
359
+
360
+ export interface StatusState {
361
+ name: string;
362
+ species: string;
363
+ rarity: string;
364
+ stars: string;
365
+ face: string;
366
+ eye: string;
367
+ shiny: boolean;
368
+ hat: string;
369
+ reaction: string;
370
+ muted: boolean;
371
+ achievement: string;
372
+ frames: string[];
373
+ frameSequence: number[];
374
+ level: number;
375
+ xp: number;
376
+ mood: string;
377
+ }
378
+
379
+ export function writeStatusState(
380
+ companion: Companion,
381
+ reaction?: string,
382
+ muted?: boolean,
383
+ achievement?: string,
384
+ level?: number,
385
+ xp?: number,
386
+ ): void {
387
+ mkdirSync(STATE_DIR, { recursive: true });
388
+ const { renderFace, RARITY_STARS } =
389
+ require("../core/engine.ts") as typeof import("../core/engine.ts");
390
+ const { getStatusFrames } =
391
+ require("./art.ts") as typeof import("./art.ts");
392
+ const { frames, frameSequence } = getStatusFrames(companion.bones);
393
+ let xpLevel = level ?? 1;
394
+ let xpTotal = xp ?? 0;
395
+ let moodStr = "focused";
396
+ try {
397
+ const { getXpState } = require("./xp.ts") as typeof import("./xp.ts");
398
+ const xpState = getXpState();
399
+ xpLevel = xpState.level;
400
+ xpTotal = xpState.totalXp;
401
+ } catch {
402
+ // XP state is optional during first install / version skew.
403
+ }
404
+ try {
405
+ const { getMood } = require("./mood.ts") as typeof import("./mood.ts");
406
+ moodStr = getMood().current;
407
+ } catch {
408
+ // Mood state is optional during first install / version skew.
409
+ }
410
+ const state: StatusState = {
411
+ name: companion.name,
412
+ species: companion.bones.species,
413
+ rarity: companion.bones.rarity,
414
+ stars: RARITY_STARS[companion.bones.rarity],
415
+ face: renderFace(companion.bones.species, companion.bones.eye),
416
+ eye: companion.bones.eye,
417
+ shiny: companion.bones.shiny,
418
+ hat: companion.bones.hat,
419
+ reaction: reaction ?? "",
420
+ muted: muted ?? false,
421
+ achievement: achievement ?? "",
422
+ frames,
423
+ frameSequence,
424
+ level: xpLevel,
425
+ xp: xpTotal,
426
+ mood: moodStr,
427
+ };
428
+ writeFileSync(join(STATE_DIR, "status.json"), JSON.stringify(state));
429
+ }
430
+
431
+ // ─── Claude Code settings.json patching (for buddy_statusline tool) ──────────
432
+
433
+ export const CLAUDE_SETTINGS_PATH = claudeSettingsPath();
434
+
435
+ /**
436
+ * Write settings.statusLine pointing to the given buddy-status script.
437
+ * Atomic via tmp + rename. Returns false if settings.json is unreachable.
438
+ */
439
+ export function setBuddyStatusLine(
440
+ statusScript: string,
441
+ settingsPath: string = CLAUDE_SETTINGS_PATH,
442
+ ): boolean {
443
+ try {
444
+ const settings = JSON.parse(readFileSync(settingsPath, "utf8"));
445
+ settings.statusLine = {
446
+ type: "command",
447
+ command: toUnixPath(statusScript),
448
+ padding: 1,
449
+ refreshInterval: 1,
450
+ };
451
+ const tmp = settingsPath + ".tmp";
452
+ writeFileSync(tmp, JSON.stringify(settings, null, 2) + "\n");
453
+ renameSync(tmp, settingsPath);
454
+ return true;
455
+ } catch {
456
+ return false;
457
+ }
458
+ }
459
+
460
+ /**
461
+ * Remove settings.statusLine — but only if it points to buddy-status.sh.
462
+ * Leaves foreign statusLines untouched. Returns false if no buddy line was
463
+ * present or settings.json is unreachable.
464
+ */
465
+ export function unsetBuddyStatusLine(
466
+ settingsPath: string = CLAUDE_SETTINGS_PATH,
467
+ ): boolean {
468
+ try {
469
+ const settings = JSON.parse(readFileSync(settingsPath, "utf8"));
470
+ if (!settings.statusLine?.command?.includes("buddy-status.sh")) return false;
471
+ delete settings.statusLine;
472
+ const tmp = settingsPath + ".tmp";
473
+ writeFileSync(tmp, JSON.stringify(settings, null, 2) + "\n");
474
+ renameSync(tmp, settingsPath);
475
+ return true;
476
+ } catch {
477
+ return false;
478
+ }
479
+ }
480
+
481
+ // ─── Plugin uninstall cleanup ───────────────────────────────────────────────
482
+
483
+ export interface CleanupResult {
484
+ statusLineRemoved: boolean;
485
+ foreignStatusLineKept: boolean;
486
+ transientFilesRemoved: number;
487
+ }
488
+
489
+ const TRANSIENT_PREFIXES = [
490
+ "popup-stop.",
491
+ "popup-resize.",
492
+ "popup-env.",
493
+ "popup-scroll.",
494
+ "popup-reopen-pid.",
495
+ "reaction.",
496
+ ".last_reaction.",
497
+ ".last_comment.",
498
+ ];
499
+
500
+ /**
501
+ * Clean up plugin-owned writes to the user's global state so that
502
+ * `claude plugin uninstall` leaves no orphaned entries behind. Specifically:
503
+ * - remove settings.statusLine if it points to buddy-status.sh
504
+ * - delete session-scoped transient files under ~/.claude-buddy/
505
+ *
506
+ * Companion data (menagerie.json, status.json, config.json) is intentionally
507
+ * kept — users reinstalling get their buddy back. Call-sites that want a full
508
+ * wipe should delete STATE_DIR themselves after calling this.
509
+ */
510
+ export function cleanupPluginState(
511
+ settingsPath: string = CLAUDE_SETTINGS_PATH,
512
+ stateDir: string = STATE_DIR,
513
+ ): CleanupResult {
514
+ const statusLineRemoved = unsetBuddyStatusLine(settingsPath);
515
+
516
+ let foreignStatusLineKept = false;
517
+ try {
518
+ const settings = JSON.parse(readFileSync(settingsPath, "utf8"));
519
+ const cmd = settings.statusLine?.command;
520
+ if (cmd && !cmd.includes("buddy-status.sh")) foreignStatusLineKept = true;
521
+ } catch {
522
+ /* missing settings.json is fine */
523
+ }
524
+
525
+ let transientFilesRemoved = 0;
526
+ try {
527
+ if (existsSync(stateDir)) {
528
+ for (const f of readdirSync(stateDir)) {
529
+ if (TRANSIENT_PREFIXES.some(p => f.startsWith(p))) {
530
+ rmSync(join(stateDir, f), { force: true });
531
+ transientFilesRemoved++;
532
+ }
533
+ }
534
+ }
535
+ } catch {
536
+ /* state dir unreadable is fine */
537
+ }
538
+
539
+ return { statusLineRemoved, foreignStatusLineKept, transientFilesRemoved };
540
+ }