@bobsworkshop/cli 0.1.4 → 0.2.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.
@@ -1,939 +0,0 @@
1
- // src/commands/analyse-results.ts
2
- import chalk3 from "chalk";
3
- import inquirer from "inquirer";
4
- import * as fs4 from "fs";
5
- import * as path4 from "path";
6
-
7
- // src/core/api-client.ts
8
- import axios2 from "axios";
9
-
10
- // src/core/config-store.ts
11
- import Conf from "conf";
12
-
13
- // src/types/config.ts
14
- var DEFAULT_CONFIG = {
15
- tier: "local",
16
- loggedIn: false,
17
- email: null,
18
- uid: null,
19
- authToken: null,
20
- refreshToken: null,
21
- provider: null,
22
- providerKey: null,
23
- localEndpoint: null,
24
- personalizationMode: false,
25
- consultantMode: false,
26
- autoMode: false,
27
- idrp: false,
28
- idrpFilter: "free",
29
- activeProject: null,
30
- conversationId: null,
31
- activePersona: null,
32
- hasSeenWelcome: false
33
- };
34
-
35
- // src/core/config-store.ts
36
- var store = new Conf({
37
- projectName: "bob-cli",
38
- defaults: DEFAULT_CONFIG
39
- });
40
- function getConfig() {
41
- return {
42
- tier: store.get("tier"),
43
- loggedIn: store.get("loggedIn"),
44
- email: store.get("email"),
45
- uid: store.get("uid"),
46
- authToken: store.get("authToken"),
47
- refreshToken: store.get("refreshToken"),
48
- provider: store.get("provider"),
49
- providerKey: store.get("providerKey"),
50
- localEndpoint: store.get("localEndpoint"),
51
- personalizationMode: store.get("personalizationMode"),
52
- consultantMode: store.get("consultantMode"),
53
- idrp: store.get("idrp"),
54
- idrpFilter: store.get("idrpFilter"),
55
- activeProject: store.get("activeProject"),
56
- conversationId: store.get("conversationId"),
57
- activePersona: store.get("activePersona"),
58
- hasSeenWelcome: store.get("hasSeenWelcome"),
59
- autoMode: store.get("autoMode")
60
- };
61
- }
62
- function setConfigValue(key, value) {
63
- store.set(key, value);
64
- }
65
- function getConfigPath() {
66
- return store.path;
67
- }
68
-
69
- // src/commands/login.ts
70
- import chalk from "chalk";
71
- import http from "http";
72
- import open from "open";
73
- import axios from "axios";
74
- import { URL } from "url";
75
- import * as readline from "readline";
76
- var CLI_AUTH_URL = "https://bobs-workshop.web.app/cli-auth";
77
- var CALLBACK_PORT = 9876;
78
- var FIREBASE_API_KEY = "AIzaSyB-hUZEonRIzbExVDwuneJaDjJZBvHdIps";
79
- function registerLoginCommand(program) {
80
- program.command("login").description("Authenticate with Bob's Workshop via browser").action(async () => {
81
- console.log("");
82
- console.log(chalk.bold.cyan(" \u{1F510} Bob CLI \u2014 Login"));
83
- console.log(chalk.gray(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"));
84
- console.log("");
85
- console.log(chalk.yellow(" \u26A0\uFE0F Important:"));
86
- console.log(chalk.gray(" \u2022 Local conversations (Tier 1) will NOT sync to the platform."));
87
- console.log(chalk.gray(" \u2022 Only NEW conversations created after login will save to Firebase."));
88
- console.log(chalk.gray(" \u2022 Your local history stays in ~/.bob/projects/ (backup via `bob backup`)."));
89
- console.log(chalk.gray(" \u2022 Logging in upgrades you to Tier 3 (Platform) with full features."));
90
- console.log("");
91
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
92
- const answer = await new Promise((resolve3) => {
93
- rl.question(chalk.cyan(" Continue with login? (y/n): "), resolve3);
94
- });
95
- rl.close();
96
- if (answer.toLowerCase() !== "y" && answer.toLowerCase() !== "yes") {
97
- console.log("");
98
- console.log(chalk.gray(" Login cancelled."));
99
- console.log("");
100
- return;
101
- }
102
- console.log("");
103
- console.log(chalk.gray(" Opening browser for authentication..."));
104
- console.log("");
105
- try {
106
- const result = await startAuthFlow();
107
- if (result) {
108
- const exchangeResult = await exchangeCustomToken(result.token);
109
- setConfigValue("authToken", exchangeResult.idToken);
110
- setConfigValue("refreshToken", exchangeResult.refreshToken);
111
- setConfigValue("email", result.email);
112
- setConfigValue("uid", result.uid);
113
- setConfigValue("loggedIn", true);
114
- setConfigValue("tier", "platform");
115
- console.log("");
116
- console.log(chalk.green(` \u2705 Logged in as ${result.email}`));
117
- console.log(chalk.gray(" Tier: Platform (Tier 3)"));
118
- console.log(chalk.gray(" All platform features are now available."));
119
- console.log("");
120
- }
121
- } catch (error) {
122
- console.log(chalk.red(` \u274C Login failed: ${error.message}`));
123
- console.log("");
124
- }
125
- });
126
- program.command("logout").description("Sign out and clear stored credentials").action(() => {
127
- setConfigValue("authToken", null);
128
- setConfigValue("refreshToken", null);
129
- setConfigValue("email", null);
130
- setConfigValue("uid", null);
131
- setConfigValue("loggedIn", false);
132
- setConfigValue("tier", "local");
133
- console.log("");
134
- console.log(chalk.gray(" \u{1F44B} Logged out. Switched to Tier 1 (local-first)."));
135
- console.log("");
136
- });
137
- }
138
- async function exchangeCustomToken(customToken) {
139
- const url = `https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${FIREBASE_API_KEY}`;
140
- const response = await axios.post(url, {
141
- token: customToken,
142
- returnSecureToken: true
143
- });
144
- if (!response.data?.idToken || !response.data?.refreshToken) {
145
- throw new Error("Token exchange failed \u2014 no ID token returned.");
146
- }
147
- return {
148
- idToken: response.data.idToken,
149
- refreshToken: response.data.refreshToken
150
- };
151
- }
152
- async function refreshAuthToken(refreshToken) {
153
- const url = `https://securetoken.googleapis.com/v1/token?key=${FIREBASE_API_KEY}`;
154
- const response = await axios.post(url, {
155
- grant_type: "refresh_token",
156
- refresh_token: refreshToken
157
- });
158
- if (!response.data?.id_token) {
159
- throw new Error("Token refresh failed.");
160
- }
161
- setConfigValue("authToken", response.data.id_token);
162
- return response.data.id_token;
163
- }
164
- function startAuthFlow() {
165
- return new Promise((resolve3, reject) => {
166
- const timeout = setTimeout(() => {
167
- server.close();
168
- reject(new Error("Login timed out after 120 seconds. Please try again."));
169
- }, 12e4);
170
- const server = http.createServer((req, res) => {
171
- if (!req.url?.startsWith("/callback")) {
172
- res.writeHead(404);
173
- res.end("Not found");
174
- return;
175
- }
176
- try {
177
- const url = new URL(req.url, `http://localhost:${CALLBACK_PORT}`);
178
- const token = url.searchParams.get("token");
179
- const email = url.searchParams.get("email");
180
- const uid = url.searchParams.get("uid");
181
- if (!token || !email || !uid) {
182
- res.writeHead(400);
183
- res.end("Missing parameters");
184
- reject(new Error("Invalid callback \u2014 missing token, email, or uid."));
185
- return;
186
- }
187
- res.writeHead(200, { "Content-Type": "text/html" });
188
- res.end(`
189
- <html>
190
- <body style="background: #0a0a0a; color: white; font-family: system-ui; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0;">
191
- <div style="text-align: center;">
192
- <h1>\u2705 Authenticated!</h1>
193
- <p style="color: #888;">You can close this tab and return to your terminal.</p>
194
- </div>
195
- </body>
196
- </html>
197
- `);
198
- clearTimeout(timeout);
199
- server.close();
200
- resolve3({ token, email, uid });
201
- } catch (e) {
202
- res.writeHead(500);
203
- res.end("Error");
204
- reject(e);
205
- }
206
- });
207
- server.listen(CALLBACK_PORT, () => {
208
- console.log(chalk.gray(` \u{1F310} Waiting for authentication (port ${CALLBACK_PORT})...`));
209
- console.log(chalk.gray(" If your browser doesn't open, visit:"));
210
- console.log(chalk.cyan(` ${CLI_AUTH_URL}`));
211
- console.log("");
212
- open(CLI_AUTH_URL).catch(() => {
213
- });
214
- });
215
- server.on("error", (err) => {
216
- clearTimeout(timeout);
217
- if (err.code === "EADDRINUSE") {
218
- reject(new Error("Port 9876 is already in use. Close other instances and try again."));
219
- } else {
220
- reject(err);
221
- }
222
- });
223
- });
224
- }
225
-
226
- // src/core/api-client.ts
227
- var FUNCTIONS_BASE = "https://us-central1-seedlingapp.cloudfunctions.net";
228
- async function callCloudFunction(functionName, data) {
229
- const config = getConfig();
230
- if (!config.authToken) {
231
- throw new Error("Not authenticated. Run `bob login` first.");
232
- }
233
- try {
234
- const response = await axios2.post(
235
- `${FUNCTIONS_BASE}/${functionName}`,
236
- { data },
237
- {
238
- headers: {
239
- "Content-Type": "application/json",
240
- "Authorization": `Bearer ${config.authToken}`
241
- },
242
- timeout: 18e4
243
- }
244
- );
245
- return response.data?.result || response.data;
246
- } catch (error) {
247
- const status = error.response?.status;
248
- if (status === 401 && config.refreshToken) {
249
- try {
250
- const newToken = await refreshAuthToken(config.refreshToken);
251
- const retryResponse = await axios2.post(
252
- `${FUNCTIONS_BASE}/${functionName}`,
253
- { data },
254
- {
255
- headers: {
256
- "Content-Type": "application/json",
257
- "Authorization": `Bearer ${newToken}`
258
- },
259
- timeout: 18e4
260
- }
261
- );
262
- return retryResponse.data?.result || retryResponse.data;
263
- } catch (refreshError) {
264
- setConfigValue("loggedIn", false);
265
- throw new Error("Session expired. Run `bob login` again.");
266
- }
267
- }
268
- if (status === 404) {
269
- throw new Error(`Function "${functionName}" not found. Is it deployed?`);
270
- }
271
- if (status === 403) {
272
- throw new Error("Permission denied. You may not have access to this feature.");
273
- }
274
- if (status === 500) {
275
- const serverMsg = error.response?.data?.error?.message || error.response?.data?.error || "Internal server error";
276
- throw new Error(`Server error: ${serverMsg}`);
277
- }
278
- if (status === 429) {
279
- throw new Error("Rate limited. Please wait a moment and try again.");
280
- }
281
- const errorMsg = error.response?.data?.error?.message || error.message || `Request failed with status ${status}`;
282
- throw new Error(errorMsg);
283
- }
284
- }
285
- function isAuthenticated() {
286
- const config = getConfig();
287
- return !!(config.loggedIn && config.authToken);
288
- }
289
-
290
- // src/ai/providers/local.ts
291
- import axios3 from "axios";
292
- async function callLocalModel(endpoint, messages) {
293
- try {
294
- const response = await axios3.post(
295
- endpoint,
296
- {
297
- model: "bob-local-dna:latest",
298
- messages,
299
- stream: false
300
- },
301
- {
302
- headers: { "Content-Type": "application/json" },
303
- timeout: 18e4
304
- }
305
- );
306
- if (response.data?.message?.content) {
307
- return response.data.message.content;
308
- }
309
- const choice = response.data?.choices?.[0];
310
- if (choice?.message?.content) {
311
- return choice.message.content;
312
- }
313
- if (typeof response.data?.response === "string") {
314
- return response.data.response;
315
- }
316
- return "No response received from local model.";
317
- } catch (error) {
318
- if (error.code === "ECONNREFUSED") {
319
- throw new Error("Cannot connect to local model. Is Ollama running? Check your endpoint: " + endpoint);
320
- }
321
- throw new Error("Local model error: " + (error.response?.status ? `Status ${error.response.status}` : error.message));
322
- }
323
- }
324
-
325
- // src/core/context-builder.ts
326
- import * as fs from "fs";
327
- import * as path from "path";
328
- var IGNORE_DIRS = ["node_modules", ".git", "dist", "build", ".dart_tool", ".idea", ".gradle", ".pub-cache", ".bob"];
329
- var MAX_DEPTH = 3;
330
- function buildLocalContext(rootDir) {
331
- const tree = getDirectoryTree(rootDir, 0);
332
- return `Working Directory: ${rootDir}
333
-
334
- File Tree:
335
- ${tree}`;
336
- }
337
- function getDirectoryTree(dir, depth) {
338
- if (depth >= MAX_DEPTH) return "";
339
- let result = "";
340
- try {
341
- const entries = fs.readdirSync(dir, { withFileTypes: true });
342
- for (const entry of entries) {
343
- if (IGNORE_DIRS.includes(entry.name)) continue;
344
- if (entry.name.startsWith(".") && depth === 0) continue;
345
- const indent = " ".repeat(depth);
346
- if (entry.isDirectory()) {
347
- result += `${indent}${entry.name}/
348
- `;
349
- result += getDirectoryTree(path.join(dir, entry.name), depth + 1);
350
- } else {
351
- result += `${indent}${entry.name}
352
- `;
353
- }
354
- }
355
- } catch (e) {
356
- }
357
- return result;
358
- }
359
- function readFileContent(filePath) {
360
- try {
361
- return fs.readFileSync(path.resolve(filePath), "utf-8");
362
- } catch (e) {
363
- return null;
364
- }
365
- }
366
-
367
- // src/core/file-writer.ts
368
- import * as fs2 from "fs";
369
- import * as path2 from "path";
370
- import * as readline2 from "readline";
371
- import chalk2 from "chalk";
372
- function extractAllProposedFiles(response) {
373
- const proposals = [];
374
- const codeBlockRegex = /```[\w]*\n([\s\S]*?)```/g;
375
- let match;
376
- while ((match = codeBlockRegex.exec(response)) !== null) {
377
- const codeContent = match[1].trim();
378
- const lines = codeContent.split("\n");
379
- if (lines.length === 0) continue;
380
- const firstLine = lines[0].trim();
381
- let filePathMatch = firstLine.match(/^\/\/\s*File:\s*(.+)$/);
382
- if (!filePathMatch) filePathMatch = firstLine.match(/^\/\/\s*([\w\-\.\/\\]+\.\w+)\s*$/);
383
- if (!filePathMatch) filePathMatch = firstLine.match(/^#\s*File:\s*(.+)$/);
384
- if (!filePathMatch) filePathMatch = firstLine.match(/^#\s*([\w\-\.\/\\]+\.\w+)\s*$/);
385
- if (!filePathMatch) filePathMatch = firstLine.match(/^\*\s*\[FILE:\s*(.+?)\]/);
386
- if (!filePathMatch) continue;
387
- const filePath = filePathMatch[1].trim();
388
- if (!filePath.includes("/") && !filePath.includes("\\")) continue;
389
- if (!filePath.includes(".")) continue;
390
- const fileContent = lines.slice(1).join("\n").trim();
391
- const isLocal = isLocalProjectFile(filePath);
392
- const absolutePath = path2.join(process.cwd(), filePath);
393
- const isNew = !fs2.existsSync(absolutePath);
394
- proposals.push({ filePath, content: fileContent, isNew, isLocal });
395
- }
396
- return proposals;
397
- }
398
- function extractProposedFile(response) {
399
- const all = extractAllProposedFiles(response);
400
- return all.length > 0 ? all[0] : null;
401
- }
402
- function stripCodeBlockFromResponse(response) {
403
- return response.replace(/```[\w]*\n\s*(?:\/\/\s*(?:File:)?\s*[\w\-\.\/\\]+\.\w+|#\s*(?:File:)?\s*[\w\-\.\/\\]+\.\w+|\*\s*\[FILE:)[^\n]*\n[\s\S]*?```/g, "").trim();
404
- }
405
- function isLocalProjectFile(filePath) {
406
- const cwd = process.cwd();
407
- const externalPatterns = ["functions/", "lib/", "android/", "ios/", "macos/", "windows/", "web/"];
408
- for (const pattern of externalPatterns) {
409
- if (filePath.startsWith(pattern)) {
410
- const localPath = path2.join(cwd, pattern.replace("/", ""));
411
- if (!fs2.existsSync(localPath)) return false;
412
- }
413
- }
414
- const resolved = path2.resolve(cwd, filePath);
415
- if (!resolved.startsWith(cwd)) return false;
416
- return true;
417
- }
418
- async function processAllProposedFiles(response, autoApprove = false, existingRl) {
419
- const proposals = extractAllProposedFiles(response);
420
- if (proposals.length === 0) return;
421
- for (const proposed of proposals) {
422
- if (proposed.isLocal) {
423
- await proposeAndWriteFile(proposed, autoApprove, existingRl);
424
- } else {
425
- displayExternalFile(proposed);
426
- }
427
- }
428
- }
429
- function displayExternalFile(proposed) {
430
- const totalLines = proposed.content.split("\n").length;
431
- console.log("");
432
- console.log(chalk2.yellow(` \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510`));
433
- console.log(chalk2.yellow(` \u2502 \u{1F4CB} EXTERNAL: ${proposed.filePath}`));
434
- console.log(chalk2.yellow(` \u2502 This file belongs to another project.`));
435
- console.log(chalk2.yellow(` \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524`));
436
- const previewLines = proposed.content.split("\n").slice(0, 6);
437
- for (const line of previewLines) {
438
- console.log(chalk2.gray(` \u2502 ${line}`));
439
- }
440
- if (totalLines > 6) {
441
- console.log(chalk2.gray(` \u2502 ... (${totalLines - 6} more lines)`));
442
- }
443
- console.log(chalk2.yellow(` \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518`));
444
- console.log(chalk2.gray(` Copy this file manually to your project at: ${proposed.filePath}`));
445
- console.log("");
446
- }
447
- async function proposeAndWriteFile(proposed, autoApprove = false, existingRl) {
448
- if (!proposed.isLocal) {
449
- displayExternalFile(proposed);
450
- return false;
451
- }
452
- const absolutePath = path2.join(process.cwd(), proposed.filePath);
453
- const action = proposed.isNew ? "CREATE" : "UPDATE";
454
- const icon = proposed.isNew ? "\u{1F4C4}" : "\u270F\uFE0F";
455
- const color = proposed.isNew ? chalk2.green : chalk2.yellow;
456
- const totalLines = proposed.content.split("\n").length;
457
- if (!autoApprove) {
458
- console.log("");
459
- console.log(color(` \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510`));
460
- console.log(color(` \u2502 ${icon} ${action}: ${proposed.filePath} (${totalLines} lines)`));
461
- console.log(color(` \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524`));
462
- const previewLines = proposed.content.split("\n").slice(0, 6);
463
- for (const line of previewLines) {
464
- console.log(chalk2.gray(` \u2502 ${line}`));
465
- }
466
- if (totalLines > 6) {
467
- console.log(chalk2.gray(` \u2502 ... (${totalLines - 6} more lines)`));
468
- }
469
- console.log(color(` \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518`));
470
- console.log("");
471
- let answer;
472
- if (existingRl) {
473
- answer = await new Promise((resolve3) => {
474
- existingRl.question(chalk2.cyan(` \u{1F4BE} ${action === "CREATE" ? "Write this file" : "Apply changes"}? (y/n/path): `), resolve3);
475
- });
476
- } else {
477
- const rl = readline2.createInterface({ input: process.stdin, output: process.stdout });
478
- answer = await new Promise((resolve3) => {
479
- rl.question(chalk2.cyan(` \u{1F4BE} ${action === "CREATE" ? "Write this file" : "Apply changes"}? (y/n/path): `), resolve3);
480
- });
481
- rl.close();
482
- }
483
- const trimmed = answer.trim().toLowerCase();
484
- if (trimmed === "n" || trimmed === "no") {
485
- console.log(chalk2.gray(" \u23ED\uFE0F Skipped."));
486
- return false;
487
- }
488
- if (trimmed !== "y" && trimmed !== "yes" && trimmed.length > 0) {
489
- const customPath = path2.join(process.cwd(), trimmed);
490
- return writeFile(customPath, proposed.content, proposed.filePath, proposed.isNew);
491
- }
492
- }
493
- return writeFile(absolutePath, proposed.content, proposed.filePath, proposed.isNew);
494
- }
495
- function writeFile(targetPath, content, originalFilePath, isNew) {
496
- try {
497
- const dir = path2.dirname(targetPath);
498
- if (!fs2.existsSync(dir)) fs2.mkdirSync(dir, { recursive: true });
499
- if (!isNew && fs2.existsSync(targetPath)) {
500
- const backupDir = path2.join(process.cwd(), ".bob-backups");
501
- if (!fs2.existsSync(backupDir)) fs2.mkdirSync(backupDir, { recursive: true });
502
- const timestamp = Date.now();
503
- const backupName = originalFilePath.replace(/[\/\\]/g, "_") + `.${timestamp}.bak`;
504
- fs2.copyFileSync(targetPath, path2.join(backupDir, backupName));
505
- }
506
- fs2.writeFileSync(targetPath, content, "utf-8");
507
- const relativePath = path2.relative(process.cwd(), targetPath);
508
- console.log(chalk2.green(` \u2705 Written: ${relativePath}`));
509
- if (!isNew) {
510
- console.log(chalk2.gray(` \u{1F4E6} Backup saved to .bob-backups/`));
511
- }
512
- console.log("");
513
- return true;
514
- } catch (error) {
515
- console.log(chalk2.red(` \u274C Write failed: ${error.message}`));
516
- return false;
517
- }
518
- }
519
-
520
- // src/core/analysis-tracker.ts
521
- import * as fs3 from "fs";
522
- import * as path3 from "path";
523
- var BOB_DIR = path3.join(process.env.HOME || process.env.USERPROFILE || "", ".bob");
524
- function getResultsDir() {
525
- const projectName = path3.basename(process.cwd());
526
- return path3.join(BOB_DIR, "projects", projectName, "analysis", "results");
527
- }
528
- function getAnalysisPath() {
529
- return path3.join(getResultsDir(), "analysis.json");
530
- }
531
- function getStatusLogPath() {
532
- return path3.join(getResultsDir(), "status-log.json");
533
- }
534
- function markSuggestionStatus(filePath, suggestionIndex, category, status, metadata) {
535
- const analysisPath = getAnalysisPath();
536
- const logPath = getStatusLogPath();
537
- if (!fs3.existsSync(analysisPath)) return;
538
- const allResults = JSON.parse(fs3.readFileSync(analysisPath, "utf-8"));
539
- if (allResults[filePath] && allResults[filePath][category]) {
540
- const items = allResults[filePath][category];
541
- if (items[suggestionIndex]) {
542
- items[suggestionIndex].status = status;
543
- items[suggestionIndex].statusUpdatedAt = (/* @__PURE__ */ new Date()).toISOString();
544
- }
545
- }
546
- fs3.writeFileSync(analysisPath, JSON.stringify(allResults, null, 2));
547
- let log = [];
548
- if (fs3.existsSync(logPath)) {
549
- try {
550
- log = JSON.parse(fs3.readFileSync(logPath, "utf-8"));
551
- } catch {
552
- log = [];
553
- }
554
- }
555
- log.push({
556
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
557
- filePath,
558
- category,
559
- suggestionIndex,
560
- action: status,
561
- confidence: metadata?.confidence || null,
562
- reason: metadata?.reason || null,
563
- implementedBy: metadata?.implementedBy || "minibob",
564
- previousStatus: "pending"
565
- });
566
- fs3.writeFileSync(logPath, JSON.stringify(log, null, 2));
567
- }
568
- function markSuggestionById(id, category, status, metadata) {
569
- const analysisPath = getAnalysisPath();
570
- if (!fs3.existsSync(analysisPath)) return;
571
- const allResults = JSON.parse(fs3.readFileSync(analysisPath, "utf-8"));
572
- for (const [filePath, fileResults] of Object.entries(allResults)) {
573
- const items = fileResults[category];
574
- if (!items) continue;
575
- for (let i = 0; i < items.length; i++) {
576
- const itemId = `${filePath.replace(/[\/\\]/g, "_")}_${i}`;
577
- if (itemId === id) {
578
- markSuggestionStatus(filePath, i, category, status, metadata);
579
- return;
580
- }
581
- }
582
- }
583
- }
584
-
585
- // src/commands/analyse-results.ts
586
- var RED = chalk3.hex("#EF5350");
587
- var PURPLE = chalk3.hex("#AB47BC");
588
- var BLUE = chalk3.hex("#42A5F5");
589
- var TEAL = chalk3.hex("#26A69A");
590
- var AMBER = chalk3.hex("#FFAB00");
591
- var GRAY = chalk3.gray;
592
- var BORDER = chalk3.hex("#455A64");
593
- var PRIORITY_COLORS = {
594
- "critical": chalk3.bgHex("#B71C1C").white,
595
- "high": chalk3.hex("#FF6D00"),
596
- "medium": chalk3.hex("#FFA726"),
597
- "low": chalk3.hex("#66BB6A")
598
- };
599
- var CATEGORY_COLORS = {
600
- "bugs": RED,
601
- "features": PURPLE,
602
- "improvements": BLUE,
603
- "upgrades": TEAL
604
- };
605
- async function showInteractiveResults(config, category, sort, search) {
606
- let allSuggestions = [];
607
- if (config.tier === "platform" && config.provider !== "local" && config.loggedIn && config.conversationId) {
608
- try {
609
- const result = await callCloudFunction("getCLIAnalysisResults", {
610
- conversationId: config.conversationId,
611
- category,
612
- sort: sort || "priority",
613
- search: search || null
614
- });
615
- allSuggestions = result?.suggestions || [];
616
- } catch (error) {
617
- console.log(chalk3.red(` \u274C ${error.message}`));
618
- return;
619
- }
620
- } else {
621
- allSuggestions = loadLocalSuggestions(category);
622
- }
623
- if (search) {
624
- const query = search.toLowerCase();
625
- allSuggestions = allSuggestions.filter(
626
- (s) => (s.description || "").toLowerCase().includes(query) || (s.title || "").toLowerCase().includes(query) || (s.filePath || "").toLowerCase().includes(query)
627
- );
628
- }
629
- sortSuggestions(allSuggestions, sort || "priority");
630
- if (allSuggestions.length === 0) {
631
- console.log("");
632
- console.log(chalk3.green(" \u2705 No items found. Clean!"));
633
- console.log("");
634
- return;
635
- }
636
- const color = CATEGORY_COLORS[category] || GRAY;
637
- let running = true;
638
- let displaySuggestions = [...allSuggestions];
639
- let currentSort = sort || "priority";
640
- while (running) {
641
- console.log("");
642
- console.log(color(` \u25C6 ${category.toUpperCase()} (${displaySuggestions.length} items) | Sort: ${currentSort}`));
643
- console.log(GRAY(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"));
644
- console.log("");
645
- const choices = [];
646
- choices.push({
647
- name: chalk3.cyan(" \u{1F500} Toggle sort"),
648
- value: "__sort__",
649
- short: "Sort"
650
- });
651
- choices.push(new inquirer.Separator(GRAY(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")));
652
- for (let idx = 0; idx < displaySuggestions.length; idx++) {
653
- const item = displaySuggestions[idx];
654
- const pColor = PRIORITY_COLORS[item.priority?.toLowerCase()] || GRAY;
655
- const priorityLabel = (item.priority || "MEDIUM").toUpperCase().padEnd(9);
656
- const filePath = (item.filePath || "unknown").split("/").pop() || "unknown";
657
- const desc = (item.description || item.title || "No description").slice(0, 42);
658
- const displayName = `${pColor(priorityLabel)} ${chalk3.cyan(filePath.padEnd(18))} ${chalk3.white(desc)}`;
659
- choices.push({
660
- name: displayName,
661
- value: idx,
662
- short: item.title || item.description?.slice(0, 30) || "Item",
663
- description: `${item.priority} ${item.filePath} ${item.title} ${item.description}`
664
- });
665
- }
666
- choices.push(new inquirer.Separator(GRAY(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")));
667
- choices.push({
668
- name: chalk3.gray(" \u2190 Quit"),
669
- value: "__quit__",
670
- short: "Quit"
671
- });
672
- const { selected } = await inquirer.prompt([
673
- {
674
- type: "search",
675
- name: "selected",
676
- message: color(`Search ${category} (type to filter):`),
677
- source: (input) => {
678
- if (!input) return choices;
679
- const query = input.toLowerCase();
680
- const filtered = choices.filter((c) => {
681
- if (c.type === "separator") return true;
682
- if (c.value === "__sort__" || c.value === "__quit__") return true;
683
- const searchable = c.description?.toLowerCase() || "";
684
- return searchable.includes(query);
685
- });
686
- return filtered;
687
- },
688
- pageSize: 12
689
- }
690
- ]);
691
- if (selected === "__quit__") {
692
- running = false;
693
- break;
694
- }
695
- if (selected === "__sort__") {
696
- currentSort = currentSort === "priority" ? "file" : "priority";
697
- sortSuggestions(displaySuggestions, currentSort);
698
- console.log(chalk3.cyan(` Sort changed to: ${currentSort}`));
699
- continue;
700
- }
701
- if (typeof selected === "number") {
702
- const item = displaySuggestions[selected];
703
- const action = await showExpandedView(item, category);
704
- if (action === "implement") {
705
- await handleImplement(item, config, category);
706
- displaySuggestions.splice(selected, 1);
707
- const originalIdx = allSuggestions.findIndex((s) => s.id === item.id);
708
- if (originalIdx !== -1) allSuggestions.splice(originalIdx, 1);
709
- } else if (action === "dismiss") {
710
- if (item.id) {
711
- markSuggestionById(item.id, category, "dismissed", {
712
- reason: "User dismissed from CLI",
713
- implementedBy: "user"
714
- });
715
- }
716
- displaySuggestions.splice(selected, 1);
717
- const originalIdx = allSuggestions.findIndex((s) => s.id === item.id);
718
- if (originalIdx !== -1) allSuggestions.splice(originalIdx, 1);
719
- console.log(chalk3.gray(" \u23ED\uFE0F Dismissed and logged."));
720
- }
721
- }
722
- }
723
- }
724
- async function showExpandedView(item, category) {
725
- const color = CATEGORY_COLORS[category] || GRAY;
726
- const pColor = PRIORITY_COLORS[item.priority?.toLowerCase()] || GRAY;
727
- console.log("");
728
- console.log(color(" \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557"));
729
- console.log(color(" \u2551 ") + pColor(`${(item.priority || "MEDIUM").toUpperCase()} ${category.toUpperCase().slice(0, -1)}`));
730
- console.log(color(" \u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"));
731
- console.log(color(" \u2551") + chalk3.gray(" File: ") + chalk3.cyan(item.filePath || "unknown"));
732
- console.log(color(" \u2551") + chalk3.gray(" Priority: ") + pColor((item.priority || "medium").toUpperCase()));
733
- console.log(color(" \u2551"));
734
- console.log(color(" \u2551") + chalk3.gray(" Title:"));
735
- console.log(color(" \u2551") + chalk3.white.bold(` ${item.title || "No title"}`));
736
- console.log(color(" \u2551"));
737
- console.log(color(" \u2551") + chalk3.gray(" Description:"));
738
- const descLines = wrapText(item.description || "No description", 54);
739
- for (const line of descLines) {
740
- console.log(color(" \u2551") + chalk3.white(` ${line}`));
741
- }
742
- if (item.implementation) {
743
- console.log(color(" \u2551"));
744
- console.log(color(" \u2551") + chalk3.gray(" Implementation:"));
745
- const implLines = wrapText(item.implementation, 54);
746
- for (const line of implLines) {
747
- console.log(color(" \u2551") + chalk3.white(` ${line}`));
748
- }
749
- }
750
- console.log(color(" \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"));
751
- console.log("");
752
- const { action } = await inquirer.prompt([
753
- {
754
- type: "select",
755
- name: "action",
756
- message: "What do you want to do?",
757
- choices: [
758
- { name: chalk3.green(" \u{1F527} Implement this fix"), value: "implement" },
759
- { name: chalk3.red(" \u{1F5D1}\uFE0F Dismiss"), value: "dismiss" },
760
- { name: chalk3.gray(" \u2190 Back to list"), value: "back" }
761
- ]
762
- }
763
- ]);
764
- return action;
765
- }
766
- async function handleImplement(item, config, category) {
767
- console.log("");
768
- console.log(chalk3.cyan(" \u{1F527} Implementing fix..."));
769
- console.log("");
770
- if (config.provider === "local" && config.localEndpoint) {
771
- const fileContent = readFileContent(item.filePath);
772
- if (!fileContent) {
773
- console.log(chalk3.red(` \u274C Could not read file: ${item.filePath}`));
774
- return;
775
- }
776
- const prompt = `You are MiniBob \u2014 a junior engineer making SURGICAL code fixes under strict supervision.
777
-
778
- CURRENT FILE: ${item.filePath}
779
- ${fileContent}
780
-
781
- CHANGE TO IMPLEMENT:
782
- Title: ${item.title}
783
- Description: ${item.description}
784
- Implementation Instructions: ${item.implementation || "Apply the fix described above."}
785
-
786
- RULES (CRITICAL \u2014 VIOLATION = REJECTED):
787
- - Return ONLY valid source code. No markdown, no code fences, no \`\`\`, no explanation text.
788
- - Start the FIRST line with: // File: ${item.filePath}
789
- - PRESERVE ALL existing imports exactly as they are. Do NOT add, remove, or reorder imports.
790
- - PRESERVE ALL existing exports exactly as they are. Do NOT rename exported functions or classes.
791
- - PRESERVE the existing code structure, indentation, patterns, and naming conventions.
792
- - Make the MINIMUM change necessary to implement the fix. Touch NOTHING else.
793
- - Do NOT refactor, reorganize, or "improve" unrelated code.
794
- - Do NOT add comments explaining what you changed.
795
- - Do NOT wrap the response in markdown code blocks.
796
- - The output must be valid TypeScript/JavaScript that compiles without errors.
797
- - If you are unsure about a change, return the file UNCHANGED rather than risk breaking it.
798
-
799
- Return the complete file content now:`;
800
- try {
801
- const messages = [
802
- { role: "system", content: "You are MiniBob, a junior engineer making SURGICAL fixes. Return ONLY valid source code. NO markdown. NO code fences. NO explanation. Start with // File: comment. Make the ABSOLUTE MINIMUM change needed. Do NOT restructure, refactor, or touch ANYTHING beyond the specific fix. If unsure, return the file unchanged." },
803
- { role: "user", content: prompt }
804
- ];
805
- const response = await callLocalModel(config.localEndpoint, messages);
806
- const lines = response.split("\n");
807
- const firstLine = lines[0].trim();
808
- let newContent;
809
- if (firstLine.match(/^\/\/\s*(File:)?\s*/)) {
810
- newContent = lines.slice(1).join("\n").trim();
811
- } else {
812
- newContent = response.trim();
813
- }
814
- if (newContent.includes("```") || newContent.includes("## ") || newContent.startsWith("Here") || newContent.startsWith("I have") || newContent.startsWith("Sure")) {
815
- console.log(chalk3.yellow(" \u26A0\uFE0F MiniBob returned explanation instead of code. Fix rejected."));
816
- return;
817
- }
818
- if (newContent.length < fileContent.length * 0.5) {
819
- console.log(chalk3.yellow(` \u26A0\uFE0F MiniBob's output is ${Math.round(newContent.length / fileContent.length * 100)}% of original size. Rejecting.`));
820
- return;
821
- }
822
- const originalExports = fileContent.match(/export\s+(function|class|const|interface|type|async\s+function)\s+\w+/g) || [];
823
- for (const exp of originalExports) {
824
- const exportName = exp.split(/\s+/).pop();
825
- if (!newContent.includes(exportName)) {
826
- console.log(chalk3.yellow(` \u26A0\uFE0F MiniBob removed export "${exportName}". Rejecting.`));
827
- return;
828
- }
829
- }
830
- await proposeAndWriteFile({
831
- filePath: item.filePath,
832
- content: newContent,
833
- isNew: false
834
- });
835
- if (item.id) {
836
- markSuggestionById(item.id, category, "implemented", {
837
- reason: "User approved implementation from CLI",
838
- implementedBy: "minibob"
839
- });
840
- }
841
- } catch (error) {
842
- console.log(chalk3.red(` \u274C Implementation failed: ${error.message}`));
843
- }
844
- } else if (config.loggedIn && config.conversationId) {
845
- try {
846
- const result = await callCloudFunction("implementSuggestion", {
847
- conversationId: config.conversationId,
848
- filePath: item.filePath,
849
- suggestionId: item.id || "unknown",
850
- category,
851
- jobId: `cli_impl_${Date.now()}`
852
- });
853
- if (result?.success) {
854
- console.log(chalk3.green(` \u2705 ${result.message}`));
855
- if (item.id) {
856
- markSuggestionById(item.id, category, "implemented", {
857
- reason: "Platform implementation",
858
- implementedBy: "platform"
859
- });
860
- }
861
- } else {
862
- console.log(chalk3.red(" \u274C Implementation failed on platform."));
863
- }
864
- } catch (error) {
865
- console.log(chalk3.red(` \u274C ${error.message}`));
866
- }
867
- } else {
868
- console.log(chalk3.red(" \u274C No provider configured for implementation."));
869
- }
870
- console.log("");
871
- }
872
- function sortSuggestions(suggestions, method) {
873
- if (method === "file") {
874
- suggestions.sort((a, b) => (a.filePath || "").localeCompare(b.filePath || ""));
875
- } else {
876
- const priorityMap = { "critical": 0, "high": 1, "medium": 2, "low": 3 };
877
- suggestions.sort((a, b) => {
878
- const pA = priorityMap[a.priority?.toLowerCase()] ?? 99;
879
- const pB = priorityMap[b.priority?.toLowerCase()] ?? 99;
880
- return pA - pB;
881
- });
882
- }
883
- }
884
- function loadLocalSuggestions(category) {
885
- const cwd = process.cwd();
886
- const projectName = path4.basename(cwd);
887
- const homeDir = process.env.HOME || process.env.USERPROFILE || "";
888
- const analysisPath = path4.join(homeDir, ".bob", "projects", projectName, "analysis", "results", "analysis.json");
889
- if (!fs4.existsSync(analysisPath)) return [];
890
- const allResults = JSON.parse(fs4.readFileSync(analysisPath, "utf-8"));
891
- const suggestions = [];
892
- for (const [filePath, fileResults] of Object.entries(allResults)) {
893
- const items = fileResults[category] || [];
894
- items.forEach((item, idx) => {
895
- if (!item.status || item.status === "pending") {
896
- suggestions.push({
897
- ...item,
898
- filePath,
899
- id: `${filePath.replace(/[\/\\]/g, "_")}_${idx}`
900
- });
901
- }
902
- });
903
- }
904
- return suggestions;
905
- }
906
- function wrapText(text, maxWidth) {
907
- const words = text.split(" ");
908
- const lines = [];
909
- let currentLine = "";
910
- for (const word of words) {
911
- if (currentLine.length + word.length + 1 > maxWidth) {
912
- lines.push(currentLine);
913
- currentLine = word;
914
- } else {
915
- currentLine += (currentLine ? " " : "") + word;
916
- }
917
- }
918
- if (currentLine) lines.push(currentLine);
919
- return lines;
920
- }
921
-
922
- export {
923
- getConfig,
924
- setConfigValue,
925
- getConfigPath,
926
- registerLoginCommand,
927
- callCloudFunction,
928
- isAuthenticated,
929
- callLocalModel,
930
- buildLocalContext,
931
- readFileContent,
932
- extractProposedFile,
933
- stripCodeBlockFromResponse,
934
- processAllProposedFiles,
935
- proposeAndWriteFile,
936
- markSuggestionStatus,
937
- showInteractiveResults,
938
- loadLocalSuggestions
939
- };