@networkbase/cli 0.0.0-stage → 1.0.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 (3) hide show
  1. package/README.md +54 -2
  2. package/bin/nb.mjs +4869 -0
  3. package/package.json +34 -4
package/bin/nb.mjs ADDED
@@ -0,0 +1,4869 @@
1
+ #!/usr/bin/env node
2
+
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import os from "node:os";
6
+ import http from "node:http";
7
+ import crypto from "node:crypto";
8
+ import readline from "node:readline";
9
+ import { execFileSync, spawn } from "node:child_process";
10
+ import { fileURLToPath } from "node:url";
11
+
12
+ const CLI_SCRIPT_PATH = fileURLToPath(import.meta.url);
13
+
14
+ const CLI_VERSION = "1.0.0";
15
+ const DEFAULT_API_URL = process.env.NETWORKBASE_API_URL || "https://networkbase.in";
16
+ const GLOBAL_CONFIG_DIR = path.join(os.homedir(), ".networkbase");
17
+ const GLOBAL_CREDENTIALS_PATH = path.join(GLOBAL_CONFIG_DIR, "credentials.json");
18
+
19
+ const MIME_MAP = {
20
+ ".ts": "text/typescript",
21
+ ".tsx": "text/typescript",
22
+ ".js": "application/javascript",
23
+ ".mjs": "application/javascript",
24
+ ".cjs": "application/javascript",
25
+ ".jsx": "text/javascript",
26
+ ".json": "application/json",
27
+ ".md": "text/markdown",
28
+ ".mdx": "text/markdown",
29
+ ".css": "text/css",
30
+ ".html": "text/html",
31
+ ".py": "text/x-python",
32
+ ".sql": "application/sql",
33
+ ".svg": "image/svg+xml",
34
+ ".png": "image/png",
35
+ ".jpg": "image/jpeg",
36
+ ".jpeg": "image/jpeg",
37
+ ".webp": "image/webp",
38
+ ".gif": "image/gif",
39
+ ".pdf": "application/pdf",
40
+ ".txt": "text/plain",
41
+ ".yml": "text/yaml",
42
+ ".yaml": "text/yaml",
43
+ };
44
+
45
+ const SECRET_PATTERNS = [
46
+ { name: "AWS Access Key ID", regex: /\bAKIA[0-9A-Z]{16}\b/ },
47
+ { name: "Private Key Block", regex: /-----BEGIN (?:RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----/ },
48
+ { name: "GitHub Personal Access Token", regex: /\bgh[pousr]_[A-Za-z0-9_]{36,}\b/ },
49
+ { name: "OpenAI API Key", regex: /\bsk-[A-Za-z0-9]{20}T3BlbkFJ[A-Za-z0-9]{20}\b/ },
50
+ ];
51
+
52
+ const IGNORED_DIRS = new Set([
53
+ ".git",
54
+ ".next",
55
+ "node_modules",
56
+ ".networkbase",
57
+ "dist",
58
+ "build",
59
+ ".turbo",
60
+ "coverage",
61
+ "Library",
62
+ "Applications",
63
+ "Movies",
64
+ "Music",
65
+ "Pictures",
66
+ ".Trash",
67
+ ".npm",
68
+ ".cache",
69
+ ".gemini",
70
+ "venv",
71
+ ".venv",
72
+ "__pycache__",
73
+ ]);
74
+
75
+ function ensureDir(dirPath) {
76
+ if (!fs.existsSync(dirPath)) {
77
+ fs.mkdirSync(dirPath, { recursive: true, mode: 0o700 });
78
+ }
79
+ }
80
+
81
+ function readJsonSafe(filePath, fallback = null) {
82
+ try {
83
+ if (!fs.existsSync(filePath)) return fallback;
84
+ return JSON.parse(fs.readFileSync(filePath, "utf8"));
85
+ } catch {
86
+ return fallback;
87
+ }
88
+ }
89
+
90
+ function writeJsonSafe(filePath, data, mode = 0o600) {
91
+ ensureDir(path.dirname(filePath));
92
+ fs.writeFileSync(filePath, JSON.stringify(data, null, 2) + "\n", { encoding: "utf8", mode });
93
+ }
94
+
95
+ function getLocalNbDir(cwd = process.cwd()) {
96
+ return path.join(cwd, ".networkbase");
97
+ }
98
+
99
+ function getLocalConfig(cwd = process.cwd()) {
100
+ return readJsonSafe(path.join(getLocalNbDir(cwd), "config.json"), {});
101
+ }
102
+
103
+ function saveLocalConfig(config, cwd = process.cwd()) {
104
+ writeJsonSafe(path.join(getLocalNbDir(cwd), "config.json"), config, 0o644);
105
+ }
106
+
107
+ function getLocalState(cwd = process.cwd()) {
108
+ return readJsonSafe(path.join(getLocalNbDir(cwd), "state.json"), {});
109
+ }
110
+
111
+ function saveLocalState(state, cwd = process.cwd()) {
112
+ writeJsonSafe(path.join(getLocalNbDir(cwd), "state.json"), state, 0o600);
113
+ }
114
+
115
+ function getLocalCache(cwd = process.cwd()) {
116
+ return readJsonSafe(path.join(getLocalNbDir(cwd), "cache.json"), { tasks: [], updatedAt: null });
117
+ }
118
+
119
+ function saveLocalCache(cache, cwd = process.cwd()) {
120
+ writeJsonSafe(path.join(getLocalNbDir(cwd), "cache.json"), cache, 0o644);
121
+ }
122
+
123
+ function getLocalManifest(cwd = process.cwd()) {
124
+ return readJsonSafe(path.join(getLocalNbDir(cwd), "manifest.json"), {
125
+ projectId: null,
126
+ files: {},
127
+ updatedAt: null,
128
+ });
129
+ }
130
+
131
+ function saveLocalManifest(manifest, cwd = process.cwd()) {
132
+ writeJsonSafe(path.join(getLocalNbDir(cwd), "manifest.json"), manifest, 0o644);
133
+ }
134
+
135
+ function updateManifestFiles(projectId, fileRecords, cwd = process.cwd()) {
136
+ const current = getLocalManifest(cwd);
137
+ const filesMap = current.projectId === projectId && current.files ? { ...current.files } : {};
138
+ for (const item of fileRecords) {
139
+ if (!item || !item.path) continue;
140
+ const normPath = item.path.startsWith("/") ? item.path : `/${item.path}`;
141
+ filesMap[normPath] = {
142
+ nodeId: item.nodeId || filesMap[normPath]?.nodeId || null,
143
+ version: item.version || item.currentVersion || filesMap[normPath]?.version || 1,
144
+ contentHash: (item.contentHash || filesMap[normPath]?.contentHash || "").toLowerCase(),
145
+ size: item.size ?? filesMap[normPath]?.size ?? 0,
146
+ syncedAt: new Date().toISOString(),
147
+ };
148
+ }
149
+ saveLocalManifest(
150
+ {
151
+ projectId,
152
+ files: filesMap,
153
+ updatedAt: new Date().toISOString(),
154
+ },
155
+ cwd,
156
+ );
157
+ }
158
+
159
+ function getLocalMirrorDir(cwd = process.cwd()) {
160
+ return path.join(getLocalNbDir(cwd), "mirror");
161
+ }
162
+
163
+ function getLocalTasksDir(cwd = process.cwd()) {
164
+ return path.join(getLocalNbDir(cwd), "tasks");
165
+ }
166
+
167
+ function formatRoleLabel(role) {
168
+ if (role === "deliverable") return "Final Deliverable (#deliverable)";
169
+ if (role === "reference") return "Reference Spec (#reference)";
170
+ return "Working Draft (#editor_working)";
171
+ }
172
+
173
+ function writeLocalTaskIntelligence(projectId, workspaceTitle, tasksList, cwd = process.cwd()) {
174
+ const tasksDir = getLocalTasksDir(cwd);
175
+ ensureDir(tasksDir);
176
+ const state = getLocalState(cwd);
177
+ const activeTaskId = state?.activeTaskId || null;
178
+
179
+ const snapshot = {
180
+ projectId,
181
+ workspaceTitle: workspaceTitle || projectId,
182
+ activeTaskId,
183
+ updatedAt: new Date().toISOString(),
184
+ totalTasks: tasksList.length,
185
+ openTasksCount: tasksList.filter((t) => t.status !== "done").length,
186
+ doneTasksCount: tasksList.filter((t) => t.status === "done").length,
187
+ tasks: tasksList.map((t) => ({
188
+ ...t,
189
+ isActive: t.id === activeTaskId,
190
+ files: (t.files || []).map((f) => ({
191
+ ...f,
192
+ localMirrorPath: `.networkbase/mirror/${(f.path || f.name || "").replace(/^\/+/, "")}`,
193
+ })),
194
+ })),
195
+ };
196
+
197
+ writeJsonSafe(path.join(tasksDir, "tasks.json"), snapshot, 0o644);
198
+ saveLocalCache({ tasks: snapshot.tasks, updatedAt: snapshot.updatedAt }, cwd);
199
+
200
+ const lines = [
201
+ `# NetworkBase Workspace Tasks · ${workspaceTitle || projectId}`,
202
+ ``,
203
+ `- **Workspace ID:** \`${projectId}\``,
204
+ `- **Updated At:** \`${snapshot.updatedAt}\``,
205
+ `- **Total Tasks:** ${snapshot.totalTasks} (${snapshot.openTasksCount} open, ${snapshot.doneTasksCount} done)`,
206
+ activeTaskId
207
+ ? `- **Active Bound Task:** \`${state.activeTaskTitle || activeTaskId}\` (\`${activeTaskId}\`)`
208
+ : `- **Active Bound Task:** None bound (run \`nb task work <#number>\` to bind)`,
209
+ ``,
210
+ `> **AI & Developer Note:** All attached task files below are automatically mirrored inside \`.networkbase/mirror/\`. You can read and edit them directly on disk with zero permission prompts, and push updates via \`nb sync\` or \`nb push --deliverable\`.`,
211
+ ``,
212
+ `---`,
213
+ ``,
214
+ ];
215
+
216
+ if (snapshot.tasks.length === 0) {
217
+ lines.push(`_No tasks found in this workspace._`, ``);
218
+ } else {
219
+ for (const t of snapshot.tasks) {
220
+ const numLabel = t.taskNumber ? `#${t.taskNumber}` : t.id.slice(0, 8);
221
+ const activeTag = t.isActive ? " ⭐ [ACTIVE TASK]" : "";
222
+ const statusUpper = String(t.status || "todo").toUpperCase();
223
+ const prioUpper = String(t.priority || "medium").toUpperCase();
224
+ lines.push(`## ${numLabel}: ${t.title}${activeTag}`);
225
+ lines.push(`- **Task ID:** \`${t.id}\``);
226
+ lines.push(`- **Status:** \`${statusUpper}\` | **Priority:** \`${prioUpper}\`${t.storyPoints ? ` | **Points:** \`${t.storyPoints}\`` : ""}${t.sprintName ? ` | **Sprint:** ${t.sprintName}` : ""}`);
227
+ if (t.assigneeName || t.assigneeUsername) {
228
+ lines.push(`- **Assignee:** ${t.assigneeName || `@${t.assigneeUsername}`}`);
229
+ }
230
+ if (t.dueDate) {
231
+ lines.push(`- **Due Date:** \`${t.dueDate}\``);
232
+ }
233
+ lines.push(``);
234
+ lines.push(`### Description`);
235
+ lines.push(t.description && t.description.trim() ? t.description.trim() : `_No description provided._`);
236
+ lines.push(``);
237
+
238
+ const subtasks = t.subtasks || [];
239
+ const stCompleted = subtasks.filter((s) => s.completed).length;
240
+ lines.push(`### Subtasks (${stCompleted}/${subtasks.length} Completed)`);
241
+ if (subtasks.length === 0) {
242
+ lines.push(`_No subtasks defined for this task._`);
243
+ } else {
244
+ for (let i = 0; i < subtasks.length; i++) {
245
+ const st = subtasks[i];
246
+ const idx = st.index || i + 1;
247
+ lines.push(`- [${st.completed ? "x" : " "}] **${idx}.** ${st.title} _(id: \`${st.id}\`)_`);
248
+ }
249
+ }
250
+ lines.push(``);
251
+
252
+ const files = t.files || [];
253
+ lines.push(`### Attached & Linked Files (${files.length})`);
254
+ if (files.length === 0) {
255
+ lines.push(`_No files attached to this task yet._`);
256
+ } else {
257
+ for (const f of files) {
258
+ const roleText = formatRoleLabel(f.role);
259
+ lines.push(
260
+ `- **\`${f.path || f.name}\`** · \`v${f.currentVersion || 1}\` · **${roleText}** · Local Mirror: \`${f.localMirrorPath}\`${f.annotation ? ` · Note: _${f.annotation}_` : ""}`,
261
+ );
262
+ }
263
+ }
264
+ lines.push(``, `---`, ``);
265
+ }
266
+ }
267
+
268
+ fs.writeFileSync(path.join(tasksDir, "TASKS.md"), lines.join("\n"), { mode: 0o644 });
269
+ return {
270
+ tasksMdPath: path.join(tasksDir, "TASKS.md"),
271
+ tasksJsonPath: path.join(tasksDir, "tasks.json"),
272
+ snapshot,
273
+ };
274
+ }
275
+
276
+ function resolveTaskIdentifier(rawInput, cwd = process.cwd()) {
277
+ if (!rawInput) return null;
278
+ const trimmed = String(rawInput).trim();
279
+ const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
280
+ if (UUID_REGEX.test(trimmed)) return trimmed;
281
+
282
+ const numCleaned = trimmed.replace(/^(?:[a-zA-Z]+-)?#?/, "");
283
+ if (/^\d+$/.test(numCleaned)) {
284
+ const targetNum = Number(numCleaned);
285
+ const localSnapshot = readJsonSafe(path.join(getLocalTasksDir(cwd), "tasks.json"), null);
286
+ const candidateList = localSnapshot?.tasks || getLocalCache(cwd)?.tasks || [];
287
+ const matched = candidateList.find((t) => Number(t.taskNumber) === targetNum);
288
+ if (matched?.id) return matched.id;
289
+ return String(targetNum);
290
+ }
291
+ return trimmed;
292
+ }
293
+
294
+ function getLastSyncReceipt(cwd = process.cwd()) {
295
+ return readJsonSafe(path.join(getLocalNbDir(cwd), "last-sync.json"), null);
296
+ }
297
+
298
+ function saveLastSyncReceipt(receipt, cwd = process.cwd()) {
299
+ writeJsonSafe(
300
+ path.join(getLocalNbDir(cwd), "last-sync.json"),
301
+ {
302
+ ...receipt,
303
+ timestamp: new Date().toISOString(),
304
+ },
305
+ 0o644,
306
+ );
307
+ }
308
+
309
+ function getDaemonStatus(cwd = process.cwd()) {
310
+ const pidPath = path.join(getLocalNbDir(cwd), "daemon.pid");
311
+ const info = readJsonSafe(pidPath, null);
312
+ if (!info || !info.pid) return { running: false, pid: null, projectId: null };
313
+ try {
314
+ process.kill(info.pid, 0);
315
+ return { running: true, pid: info.pid, projectId: info.projectId || null, startedAt: info.startedAt };
316
+ } catch {
317
+ return { running: false, pid: null, projectId: null };
318
+ }
319
+ }
320
+
321
+ function stopBackgroundDaemon(cwd = process.cwd()) {
322
+ const pidPath = path.join(getLocalNbDir(cwd), "daemon.pid");
323
+ const info = readJsonSafe(pidPath, null);
324
+ if (info && info.pid) {
325
+ try {
326
+ process.kill(info.pid, "SIGTERM");
327
+ } catch {
328
+ // Ignore already-stopped process
329
+ }
330
+ }
331
+ try {
332
+ if (fs.existsSync(pidPath)) fs.unlinkSync(pidPath);
333
+ } catch {
334
+ // Ignore
335
+ }
336
+ }
337
+
338
+ function ensureBackgroundDaemon(projectId, cwd = process.cwd()) {
339
+ const status = getDaemonStatus(cwd);
340
+ if (status.running && status.projectId === projectId) {
341
+ return status;
342
+ }
343
+ if (status.running) {
344
+ stopBackgroundDaemon(cwd);
345
+ }
346
+ try {
347
+ const nbDir = getLocalNbDir(cwd);
348
+ ensureDir(nbDir);
349
+ const child = spawn(
350
+ process.execPath,
351
+ [CLI_SCRIPT_PATH, "watch", "--daemon-worker", "--workspace", projectId],
352
+ {
353
+ cwd,
354
+ detached: true,
355
+ stdio: "ignore",
356
+ },
357
+ );
358
+ child.unref();
359
+ if (child.pid) {
360
+ const pidInfo = {
361
+ pid: child.pid,
362
+ projectId,
363
+ startedAt: new Date().toISOString(),
364
+ };
365
+ writeJsonSafe(path.join(nbDir, "daemon.pid"), pidInfo, 0o644);
366
+ return { running: true, ...pidInfo };
367
+ }
368
+ } catch {
369
+ // Non-fatal if background spawn is disallowed in constrained environments
370
+ }
371
+ return { running: false, pid: null, projectId };
372
+ }
373
+
374
+ function getCredentials() {
375
+ const creds = readJsonSafe(GLOBAL_CREDENTIALS_PATH, null);
376
+ if (process.env.NETWORKBASE_TOKEN) {
377
+ return {
378
+ token: process.env.NETWORKBASE_TOKEN,
379
+ apiUrl: process.env.NETWORKBASE_API_URL || creds?.apiUrl || DEFAULT_API_URL,
380
+ clientSessionId: creds?.clientSessionId || crypto.randomUUID(),
381
+ };
382
+ }
383
+ return creds;
384
+ }
385
+
386
+ function saveCredentials(creds) {
387
+ writeJsonSafe(GLOBAL_CREDENTIALS_PATH, {
388
+ ...creds,
389
+ clientSessionId: creds.clientSessionId || crypto.randomUUID(),
390
+ savedAt: new Date().toISOString(),
391
+ });
392
+ }
393
+
394
+ function parseFlags(argv) {
395
+ const positional = [];
396
+ const flags = {};
397
+ for (let i = 0; i < argv.length; i++) {
398
+ const arg = argv[i];
399
+ if (arg.startsWith("--")) {
400
+ const eqIdx = arg.indexOf("=");
401
+ if (eqIdx !== -1) {
402
+ flags[arg.slice(2, eqIdx)] = arg.slice(eqIdx + 1);
403
+ } else {
404
+ const key = arg.slice(2);
405
+ const next = argv[i + 1];
406
+ if (next && !next.startsWith("-")) {
407
+ flags[key] = next;
408
+ i++;
409
+ } else {
410
+ flags[key] = true;
411
+ }
412
+ }
413
+ } else if (arg === "-m" && argv[i + 1]) {
414
+ flags.message = argv[++i];
415
+ } else if (arg === "-j") {
416
+ flags.json = true;
417
+ } else {
418
+ positional.push(arg);
419
+ }
420
+ }
421
+ return { positional, flags };
422
+ }
423
+
424
+ function outputResult(data, flags, humanFormatter) {
425
+ if (flags.json) {
426
+ process.stdout.write(JSON.stringify(data, null, 2) + "\n");
427
+ } else if (humanFormatter) {
428
+ humanFormatter(data);
429
+ } else {
430
+ console.log(data);
431
+ }
432
+ }
433
+
434
+ async function apiRequest(endpoint, options = {}) {
435
+ const creds = getCredentials();
436
+ const localCfg = getLocalConfig();
437
+ const baseUrl = (options.apiUrl || localCfg.apiUrl || creds?.apiUrl || DEFAULT_API_URL).replace(/\/+$/, "");
438
+ const token = options.token || creds?.token;
439
+
440
+ if (!token && !options.allowUnauthenticated) {
441
+ throw new Error("Not signed in. Run `nb auth login --token <token>` or `nb auth login` first.");
442
+ }
443
+
444
+ const headers = {
445
+ "Content-Type": "application/json",
446
+ "User-Agent": `networkbase-cli/${CLI_VERSION} (${process.platform}-${process.arch})`,
447
+ "x-extension-version": CLI_VERSION,
448
+ "x-editor-host": "cli",
449
+ "x-editor-name": "NetworkBase CLI",
450
+ "x-editor-platform": `${process.platform}-${process.arch}`,
451
+ "x-editor-version": process.version,
452
+ ...(options.headers || {}),
453
+ };
454
+
455
+ if (token) {
456
+ headers.Authorization = `Bearer ${token}`;
457
+ }
458
+
459
+ const timeoutMs = options.timeoutMs || 10000;
460
+ let response;
461
+ try {
462
+ response = await fetch(`${baseUrl}${endpoint}`, {
463
+ method: options.method || "GET",
464
+ headers,
465
+ body: options.body ? JSON.stringify(options.body) : undefined,
466
+ signal: AbortSignal.timeout(timeoutMs),
467
+ });
468
+ } catch (fetchErr) {
469
+ if (baseUrl !== "http://localhost:3000" && !options.apiUrl) {
470
+ response = await fetch(`http://localhost:3000${endpoint}`, {
471
+ method: options.method || "GET",
472
+ headers,
473
+ body: options.body ? JSON.stringify(options.body) : undefined,
474
+ signal: AbortSignal.timeout(timeoutMs),
475
+ });
476
+ } else {
477
+ throw fetchErr;
478
+ }
479
+ }
480
+
481
+ if (response.status === 304) {
482
+ return { notModified: true, etag: response.headers.get("etag") };
483
+ }
484
+
485
+ const payload = await response.json().catch(() => null);
486
+ if (!response.ok || (payload && payload.success === false)) {
487
+ const errMsg = payload?.message || payload?.error || `HTTP ${response.status} from ${endpoint}`;
488
+ const err = new Error(errMsg);
489
+ err.status = response.status;
490
+ err.errorCode = payload?.errorCode;
491
+ err.details = payload;
492
+ throw err;
493
+ }
494
+
495
+ return payload?.data !== undefined ? payload.data : payload;
496
+ }
497
+
498
+ function detectMimeType(filePath) {
499
+ const ext = path.extname(filePath).toLowerCase();
500
+ return MIME_MAP[ext] || "application/octet-stream";
501
+ }
502
+
503
+ function computeFileSha256(filePath) {
504
+ const buf = fs.readFileSync(filePath);
505
+ const hash = crypto.createHash("sha256").update(buf).digest("hex");
506
+ return { hash, size: buf.length, buffer: buf };
507
+ }
508
+
509
+ function scanFileForSecrets(relativePath, buffer) {
510
+ const baseName = path.basename(relativePath);
511
+ if (baseName === ".env" || (baseName.startsWith(".env.") && !baseName.endsWith(".example"))) {
512
+ return `Environment secret file (${baseName}) should not be pushed directly`;
513
+ }
514
+ if (buffer.length > 2 * 1024 * 1024) return null;
515
+ const text = buffer.toString("utf8");
516
+ for (const rule of SECRET_PATTERNS) {
517
+ if (rule.regex.test(text)) {
518
+ return `Detected potential ${rule.name}`;
519
+ }
520
+ }
521
+ return null;
522
+ }
523
+
524
+ function collectLocalFiles(targetPaths, cwd = process.cwd(), scopeDir = null, { maxFiles = 2000, maxDepth = 8 } = {}) {
525
+ const files = [];
526
+ const mirrorDir = getLocalMirrorDir(cwd);
527
+ const rootDir = scopeDir ? path.resolve(cwd, scopeDir) : cwd;
528
+
529
+ // Never recursively walk the entire OS home directory when no explicit path/scope is given
530
+ if (targetPaths.length === 0 && !scopeDir && path.resolve(cwd) === path.resolve(os.homedir())) {
531
+ if (fs.existsSync(mirrorDir)) {
532
+ return collectLocalFiles([], cwd, mirrorDir, { maxFiles, maxDepth });
533
+ }
534
+ return files;
535
+ }
536
+
537
+ function walk(currentPath, depth = 0) {
538
+ if (files.length >= maxFiles || depth > maxDepth) return;
539
+ let stat;
540
+ try {
541
+ stat = fs.statSync(currentPath);
542
+ } catch {
543
+ return;
544
+ }
545
+ if (stat.isDirectory()) {
546
+ const base = path.basename(currentPath);
547
+ const isInsideMirror = currentPath === mirrorDir || currentPath.startsWith(mirrorDir + path.sep);
548
+ if (depth > 0 && !isInsideMirror && (IGNORED_DIRS.has(base) || base.startsWith("."))) return;
549
+ let entries;
550
+ try {
551
+ entries = fs.readdirSync(currentPath);
552
+ } catch {
553
+ return;
554
+ }
555
+ for (const entry of entries) {
556
+ if (files.length >= maxFiles) break;
557
+ walk(path.join(currentPath, entry), depth + 1);
558
+ }
559
+ } else if (stat.isFile()) {
560
+ const baseName = path.basename(currentPath);
561
+ if (targetPaths.length === 0 && baseName.startsWith(".") && baseName !== ".env.example") {
562
+ return;
563
+ }
564
+ if (currentPath.startsWith(mirrorDir + path.sep)) {
565
+ const mirrorRel = path.relative(mirrorDir, currentPath).replace(/\\/g, "/");
566
+ files.push({ absPath: currentPath, relativePath: mirrorRel, fromMirror: true });
567
+ return;
568
+ }
569
+ const rel = path.relative(cwd, currentPath).replace(/\\/g, "/");
570
+ if (rel.startsWith(".networkbase/") || rel.startsWith(".git/")) return;
571
+ files.push({ absPath: currentPath, relativePath: rel });
572
+ }
573
+ }
574
+
575
+ if (targetPaths.length > 0) {
576
+ const manifest = getLocalManifest(cwd);
577
+ const manifestFiles = manifest?.files || {};
578
+ for (const p of targetPaths) {
579
+ const cleanRel = p.replace(/^\/+/, "");
580
+ const mirrorCandidate = path.join(mirrorDir, cleanRel);
581
+ const cwdCandidate = path.resolve(cwd, p);
582
+
583
+ // Prefer .networkbase/mirror/<p> if it exists and has uncommitted edits relative to manifest, or if cwdCandidate doesn't exist
584
+ if (fs.existsSync(mirrorCandidate) && fs.statSync(mirrorCandidate).isFile()) {
585
+ const normKey = `/${cleanRel}`;
586
+ const mirrorHash = computeFileSha256(mirrorCandidate).hash.toLowerCase();
587
+ const manifestHash = (manifestFiles[normKey]?.contentHash || "").toLowerCase();
588
+ if (!fs.existsSync(cwdCandidate) || (manifestHash && mirrorHash !== manifestHash)) {
589
+ walk(mirrorCandidate, 0);
590
+ continue;
591
+ }
592
+ }
593
+ if (fs.existsSync(cwdCandidate)) {
594
+ walk(cwdCandidate, 0);
595
+ } else if (fs.existsSync(mirrorCandidate)) {
596
+ walk(mirrorCandidate, 0);
597
+ }
598
+ }
599
+ } else if (fs.existsSync(rootDir)) {
600
+ // If .networkbase/mirror/ has mirrored workspace files, scope default push/sync to the mirror
601
+ if (rootDir === cwd && fs.existsSync(mirrorDir)) {
602
+ walk(mirrorDir, 0);
603
+ if (files.length > 0) {
604
+ return files;
605
+ }
606
+ }
607
+ walk(rootDir, 0);
608
+ }
609
+ return files;
610
+ }
611
+
612
+ function inferActiveTaskId(flags, cwd = process.cwd()) {
613
+ if ((typeof flags.task === "string" || typeof flags.task === "number") && String(flags.task).trim()) {
614
+ return resolveTaskIdentifier(flags.task, cwd);
615
+ }
616
+ const state = getLocalState(cwd);
617
+ if (state.activeTaskId) return state.activeTaskId;
618
+
619
+ try {
620
+ const branch = execFileSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
621
+ cwd,
622
+ stdio: ["ignore", "pipe", "ignore"],
623
+ })
624
+ .toString("utf8")
625
+ .trim();
626
+ const uuidMatch = branch.match(
627
+ /[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/i,
628
+ );
629
+ if (uuidMatch) return uuidMatch[0];
630
+ } catch {}
631
+ return null;
632
+ }
633
+
634
+ function resolveRoleFromFlags(flags) {
635
+ if (flags.deliverable) return "deliverable";
636
+ if (flags.draft || flags.working) return "working";
637
+ if (flags.reference || flags.spec) return "reference";
638
+ if (typeof flags.role === "string" && ["deliverable", "working", "reference"].includes(flags.role)) {
639
+ return flags.role;
640
+ }
641
+ return null;
642
+ }
643
+
644
+ // ============================================================================
645
+ // NETWORKBASE TUI DESIGN SYSTEM (Claude Code / Clack Grade Interactive Engine)
646
+ // ============================================================================
647
+
648
+ const USE_COLOR = Boolean(
649
+ process.stdout.isTTY &&
650
+ !process.env.NO_COLOR &&
651
+ process.env.FORCE_COLOR !== "0" &&
652
+ process.env.TERM !== "dumb",
653
+ );
654
+
655
+ const c = {
656
+ reset: USE_COLOR ? "\x1b[0m" : "",
657
+ bold: USE_COLOR ? "\x1b[1m" : "",
658
+ dim: USE_COLOR ? "\x1b[38;2;82;82;91m" : "",
659
+ muted: USE_COLOR ? "\x1b[38;2;161;161;170m" : "",
660
+ ink: USE_COLOR ? "\x1b[38;2;250;250;250m" : "",
661
+ accent: USE_COLOR ? "\x1b[38;2;56;189;248m" : "",
662
+ emerald: USE_COLOR ? "\x1b[38;2;52;211;153m" : "",
663
+ amber: USE_COLOR ? "\x1b[38;2;251;191;36m" : "",
664
+ red: USE_COLOR ? "\x1b[38;2;248;113;113m" : "",
665
+ };
666
+
667
+ const RAIL = `${c.dim}│${c.reset}`;
668
+ const RAIL_END = `${c.dim}└${c.reset}`;
669
+ const STEP_ACTIVE = `${c.accent}◆${c.reset}`;
670
+ const STEP_DONE = `${c.emerald}◇${c.reset}`;
671
+ const STEP_WARN = `${c.amber}▲${c.reset}`;
672
+ const STEP_ERR = `${c.red}✖${c.reset}`;
673
+ const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
674
+
675
+ // Always restore cursor visibility on exit
676
+ process.on("exit", () => {
677
+ if (process.stdout.isTTY) {
678
+ process.stdout.write("\x1b[?25h");
679
+ }
680
+ });
681
+
682
+ function stripAnsi(str) {
683
+ return String(str).replace(/\x1b\[[0-9;]*m/g, "");
684
+ }
685
+
686
+ function fitTerminalLine(str) {
687
+ const cols = Math.max(50, (process.stdout.columns || 80) - 2);
688
+ const plain = stripAnsi(str);
689
+ if (plain.length <= cols) return str;
690
+ // Truncate visible characters while preserving ANSI resets
691
+ let visible = 0;
692
+ let out = "";
693
+ let i = 0;
694
+ while (i < str.length && visible < cols - 1) {
695
+ if (str[i] === "\x1b") {
696
+ const m = str.slice(i).match(/^\x1b\[[0-9;]*m/);
697
+ if (m) {
698
+ out += m[0];
699
+ i += m[0].length;
700
+ continue;
701
+ }
702
+ }
703
+ out += str[i];
704
+ visible++;
705
+ i++;
706
+ }
707
+ return `${out}…${c.reset}`;
708
+ }
709
+
710
+ function formatBytes(bytes) {
711
+ if (!bytes || bytes < 1024) return `${bytes || 0} B`;
712
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
713
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
714
+ }
715
+
716
+ function formatStatusBadge(status) {
717
+ const s = String(status || "").toLowerCase();
718
+ if (s === "in_progress") return `${c.accent}[IN PROGRESS]${c.reset}`;
719
+ if (s === "done" || s === "completed") return `${c.emerald}[DONE]${c.reset}`;
720
+ if (s === "todo") return `${c.muted}[TODO]${c.reset}`;
721
+ if (s === "blocked") return `${c.red}[BLOCKED]${c.reset}`;
722
+ if (s === "deliverable") return `${c.emerald}[Final file]${c.reset}`;
723
+ if (s === "working") return `${c.amber}[Draft file]${c.reset}`;
724
+ if (s === "reference") return `${c.accent}[Reference]${c.reset}`;
725
+ return `${c.muted}[${String(status).toUpperCase()}]${c.reset}`;
726
+ }
727
+
728
+ function formatPriorityBadge(priority) {
729
+ const p = String(priority || "medium").toLowerCase();
730
+ if (p === "urgent") return `${c.red}[URGENT]${c.reset}`;
731
+ if (p === "high") return `${c.amber}[HIGH]${c.reset}`;
732
+ if (p === "low") return `${c.dim}[LOW]${c.reset}`;
733
+ return `${c.muted}[MEDIUM]${c.reset}`;
734
+ }
735
+
736
+ function renderBrandHeader({ subtitle = "High-EQ Workspace, Task & File Sync", contextRows = [] } = {}) {
737
+ const width = Math.min(68, Math.max(54, (process.stdout.columns || 80) - 6));
738
+ const inner = width - 2;
739
+ const top = `${c.dim}╭${"─".repeat(inner)}╮${c.reset}`;
740
+ const divider = `${c.dim}├${"─".repeat(inner)}┤${c.reset}`;
741
+ const bottom = `${c.dim}╰${"─".repeat(inner)}╯${c.reset}`;
742
+
743
+ const leftBrand = ` ${c.ink}●${c.reset} ${c.bold}${c.ink}NetworkBase${c.reset}`;
744
+ const rightVer = `${c.muted}CLI v${CLI_VERSION}${c.reset} `;
745
+ const padLen = Math.max(1, inner - stripAnsi(leftBrand).length - stripAnsi(rightVer).length);
746
+ const titleRow = `${c.dim}│${c.reset}${leftBrand}${" ".repeat(padLen)}${rightVer}${c.dim}│${c.reset}`;
747
+
748
+ const subText = ` ${c.muted}${subtitle}${c.reset}`;
749
+ const subPad = Math.max(1, inner - stripAnsi(subText).length);
750
+ const subRow = `${c.dim}│${c.reset}${subText}${" ".repeat(subPad)}${c.dim}│${c.reset}`;
751
+
752
+ const lines = ["", top, titleRow, subRow];
753
+
754
+ if (contextRows.length > 0) {
755
+ lines.push(divider);
756
+ for (const row of contextRows) {
757
+ const label = row.label.padEnd(13);
758
+ const content = ` ${c.muted}${label}${c.reset}${row.value}`;
759
+ const visLen = stripAnsi(content).length;
760
+ const clipped =
761
+ visLen > inner - 1
762
+ ? content.slice(0, content.length - (visLen - (inner - 2))) + "…" + c.reset
763
+ : content;
764
+ const rowPad = Math.max(0, inner - stripAnsi(clipped).length);
765
+ lines.push(`${c.dim}│${c.reset}${clipped}${" ".repeat(rowPad)}${c.dim}│${c.reset}`);
766
+ }
767
+ }
768
+
769
+ lines.push(bottom);
770
+ process.stdout.write(lines.join("\n") + "\n");
771
+ }
772
+
773
+ function createLiveRenderer() {
774
+ let renderedLineCount = 0;
775
+
776
+ return {
777
+ render(lines) {
778
+ if (renderedLineCount > 0) {
779
+ process.stdout.write(`\x1b[${renderedLineCount}A`);
780
+ for (let i = 0; i < renderedLineCount; i++) {
781
+ process.stdout.write("\x1b[2K\x1b[1B");
782
+ }
783
+ process.stdout.write(`\x1b[${renderedLineCount}A`);
784
+ }
785
+ const safeLines = lines.map((l) => fitTerminalLine(l));
786
+ process.stdout.write(safeLines.join("\n") + "\n");
787
+ renderedLineCount = safeLines.length;
788
+ },
789
+ clear() {
790
+ if (renderedLineCount > 0) {
791
+ process.stdout.write(`\x1b[${renderedLineCount}A`);
792
+ for (let i = 0; i < renderedLineCount; i++) {
793
+ process.stdout.write("\x1b[2K\x1b[1B");
794
+ }
795
+ process.stdout.write(`\x1b[${renderedLineCount}A`);
796
+ renderedLineCount = 0;
797
+ }
798
+ },
799
+ };
800
+ }
801
+
802
+ async function withSpinner(label, asyncFn, { silent = false } = {}) {
803
+ if (silent || !process.stdout.isTTY) {
804
+ return asyncFn();
805
+ }
806
+ const live = createLiveRenderer();
807
+ let frameIdx = 0;
808
+ const startedAt = Date.now();
809
+ process.stdout.write("\x1b[?25l");
810
+
811
+ const renderFrame = () => {
812
+ const elapsed = Math.floor((Date.now() - startedAt) / 1000);
813
+ const timeSuffix = elapsed >= 2 ? ` ${c.dim}(${elapsed}s)${c.reset}` : "";
814
+ const spinner = `${c.accent}${SPINNER_FRAMES[frameIdx % SPINNER_FRAMES.length]}${c.reset}`;
815
+ live.render([RAIL, `${ spinner } ${c.ink}${label}${c.reset}${timeSuffix}`]);
816
+ frameIdx++;
817
+ };
818
+
819
+ renderFrame();
820
+ const interval = setInterval(renderFrame, 80);
821
+
822
+ try {
823
+ const res = await asyncFn();
824
+ clearInterval(interval);
825
+ live.clear();
826
+ process.stdout.write("\x1b[?25h");
827
+ return res;
828
+ } catch (err) {
829
+ clearInterval(interval);
830
+ live.clear();
831
+ process.stdout.write("\x1b[?25h");
832
+ throw err;
833
+ }
834
+ }
835
+
836
+ function printStepDone(label, value) {
837
+ console.log(`${RAIL}`);
838
+ console.log(`${STEP_DONE} ${c.muted}${label}${c.reset} ${c.dim}·${c.reset} ${c.bold}${c.ink}${value}${c.reset}`);
839
+ }
840
+
841
+ /**
842
+ * Arrow-Key Interactive Single-Select Menu with Live Search Filter & In-Place Collapse
843
+ */
844
+ async function tuiSelect({
845
+ title,
846
+ stepLabel = title,
847
+ items,
848
+ initialIndex = 0,
849
+ searchable = false,
850
+ allowCancel = false,
851
+ }) {
852
+ if (!items || items.length === 0) return null;
853
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
854
+ return items[Math.min(initialIndex, items.length - 1)].value;
855
+ }
856
+
857
+ const live = createLiveRenderer();
858
+ let cursor = Math.max(0, Math.min(initialIndex, items.length - 1));
859
+ let filterQuery = "";
860
+ const maxVisible = 7;
861
+
862
+ function getFilteredItems() {
863
+ if (!filterQuery) return items;
864
+ const q = filterQuery.toLowerCase();
865
+ return items.filter(
866
+ (item) =>
867
+ String(item.label || "").toLowerCase().includes(q) ||
868
+ String(item.hint || "").toLowerCase().includes(q) ||
869
+ String(item.badge || "").toLowerCase().includes(q),
870
+ );
871
+ }
872
+
873
+ function renderMenu() {
874
+ const filtered = getFilteredItems();
875
+ if (cursor >= filtered.length) {
876
+ cursor = Math.max(0, filtered.length - 1);
877
+ }
878
+
879
+ const lines = [RAIL, `${STEP_ACTIVE} ${c.bold}${c.ink}${title}${c.reset}`];
880
+
881
+ if (searchable || filterQuery.length > 0) {
882
+ const filterDisplay = filterQuery
883
+ ? `${c.accent}${filterQuery}${c.reset}`
884
+ : `${c.dim}type to filter (${items.length} items)${c.reset}`;
885
+ lines.push(`${RAIL} ${c.muted}Filter:${c.reset} ${filterDisplay}`);
886
+ }
887
+
888
+ if (filtered.length === 0) {
889
+ lines.push(`${RAIL} ${c.amber}No matches for "${filterQuery}" (press Backspace)${c.reset}`);
890
+ } else {
891
+ let start = 0;
892
+ if (filtered.length > maxVisible) {
893
+ start = Math.max(
894
+ 0,
895
+ Math.min(cursor - Math.floor(maxVisible / 2), filtered.length - maxVisible),
896
+ );
897
+ }
898
+ const end = Math.min(filtered.length, start + maxVisible);
899
+
900
+ if (start > 0) {
901
+ lines.push(`${RAIL} ${c.dim}↑ ${start} more above${c.reset}`);
902
+ }
903
+
904
+ for (let i = start; i < end; i++) {
905
+ const item = filtered[i];
906
+ const isSelected = i === cursor;
907
+ const pointer = isSelected ? `${c.accent}❯ ●${c.reset}` : ` ${c.dim}○${c.reset}`;
908
+ const labelText = isSelected
909
+ ? `${c.bold}${c.ink}${item.label}${c.reset}`
910
+ : `${c.muted}${item.label}${c.reset}`;
911
+ const hintText = item.hint ? ` ${c.dim}${item.hint}${c.reset}` : "";
912
+ const badgeText = item.badge ? ` ${item.badge}` : "";
913
+ lines.push(`${RAIL} ${pointer} ${labelText}${hintText}${badgeText}`);
914
+ if (isSelected && item.description) {
915
+ lines.push(`${RAIL} ${c.dim}${item.description}${c.reset}`);
916
+ }
917
+ }
918
+
919
+ if (end < filtered.length) {
920
+ lines.push(`${RAIL} ${c.dim}↓ ${filtered.length - end} more below${c.reset}`);
921
+ }
922
+ }
923
+
924
+ const helpHint = searchable
925
+ ? `↑/↓ move · Enter select · type to filter${allowCancel ? " · Esc skip" : " · Ctrl+C cancel"}`
926
+ : `↑/↓ move · Enter select${allowCancel ? " · Esc skip" : " · Ctrl+C cancel"}`;
927
+ lines.push(`${RAIL_END} ${c.dim}${helpHint}${c.reset}`);
928
+ live.render(lines);
929
+ }
930
+
931
+ return new Promise((resolve) => {
932
+ readline.emitKeypressEvents(process.stdin);
933
+ const wasRaw = process.stdin.isRaw;
934
+ process.stdin.setRawMode(true);
935
+ process.stdin.resume();
936
+ process.stdout.write("\x1b[?25l");
937
+
938
+ renderMenu();
939
+
940
+ function cleanup() {
941
+ process.stdin.removeListener("keypress", onKeypress);
942
+ if (process.stdin.isTTY) {
943
+ process.stdin.setRawMode(Boolean(wasRaw));
944
+ }
945
+ process.stdin.pause();
946
+ process.stdout.write("\x1b[?25h");
947
+ }
948
+
949
+ function onKeypress(str, key = {}) {
950
+ if (key.ctrl && key.name === "c") {
951
+ live.clear();
952
+ cleanup();
953
+ console.log(`${RAIL_END} ${STEP_ERR} ${c.muted}Cancelled.${c.reset}\n`);
954
+ process.exit(130);
955
+ }
956
+
957
+ if (key.name === "escape") {
958
+ if (filterQuery.length > 0) {
959
+ filterQuery = "";
960
+ cursor = 0;
961
+ renderMenu();
962
+ return;
963
+ }
964
+ if (allowCancel) {
965
+ live.clear();
966
+ cleanup();
967
+ printStepDone(stepLabel, "Skipped");
968
+ resolve(null);
969
+ return;
970
+ }
971
+ }
972
+
973
+ const filtered = getFilteredItems();
974
+
975
+ if (key.name === "up" || (!searchable && !filterQuery && key.name === "k")) {
976
+ if (filtered.length > 0) {
977
+ cursor = (cursor - 1 + filtered.length) % filtered.length;
978
+ }
979
+ renderMenu();
980
+ return;
981
+ }
982
+
983
+ if (key.name === "down" || (!searchable && !filterQuery && key.name === "j")) {
984
+ if (filtered.length > 0) {
985
+ cursor = (cursor + 1) % filtered.length;
986
+ }
987
+ renderMenu();
988
+ return;
989
+ }
990
+
991
+ if (key.name === "return" || key.name === "enter") {
992
+ const chosen = filtered[cursor];
993
+ if (!chosen) return;
994
+ live.clear();
995
+ cleanup();
996
+ printStepDone(stepLabel, chosen.summaryLabel || chosen.label);
997
+ resolve(chosen.value);
998
+ return;
999
+ }
1000
+
1001
+ if (key.name === "backspace") {
1002
+ if (filterQuery.length > 0) {
1003
+ filterQuery = filterQuery.slice(0, -1);
1004
+ cursor = 0;
1005
+ renderMenu();
1006
+ }
1007
+ return;
1008
+ }
1009
+
1010
+ // Number shortcut 1..9 when not filtering
1011
+ if (!searchable && !filterQuery && str && /^[1-9]$/.test(str)) {
1012
+ const idx = parseInt(str, 10) - 1;
1013
+ if (idx >= 0 && idx < filtered.length) {
1014
+ cursor = idx;
1015
+ renderMenu();
1016
+ }
1017
+ return;
1018
+ }
1019
+
1020
+ // Live search typing
1021
+ if (str && !key.ctrl && !key.meta && str.length === 1 && str >= " " && str <= "~") {
1022
+ if (searchable || items.length > 4) {
1023
+ filterQuery += str;
1024
+ cursor = 0;
1025
+ renderMenu();
1026
+ }
1027
+ }
1028
+ }
1029
+
1030
+ process.stdin.on("keypress", onKeypress);
1031
+ });
1032
+ }
1033
+
1034
+ /**
1035
+ * Arrow-Key Interactive Multi-Select Checkbox Menu (Space to toggle, Enter to confirm)
1036
+ */
1037
+ async function tuiMultiSelect({ title, stepLabel = title, items }) {
1038
+ if (!items || items.length === 0) return [];
1039
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
1040
+ return items.map((i) => i.value);
1041
+ }
1042
+
1043
+ const live = createLiveRenderer();
1044
+ let cursor = 0;
1045
+ const checked = new Set(items.map((_, idx) => idx));
1046
+ const maxVisible = 8;
1047
+
1048
+ function renderMenu(validationError = "") {
1049
+ const lines = [
1050
+ RAIL,
1051
+ `${STEP_ACTIVE} ${c.bold}${c.ink}${title}${c.reset} ${c.muted}(${checked.size}/${items.length} selected)${c.reset}`,
1052
+ ];
1053
+
1054
+ let start = 0;
1055
+ if (items.length > maxVisible) {
1056
+ start = Math.max(0, Math.min(cursor - Math.floor(maxVisible / 2), items.length - maxVisible));
1057
+ }
1058
+ const end = Math.min(items.length, start + maxVisible);
1059
+
1060
+ if (start > 0) {
1061
+ lines.push(`${RAIL} ${c.dim}↑ ${start} more above${c.reset}`);
1062
+ }
1063
+
1064
+ for (let i = start; i < end; i++) {
1065
+ const item = items[i];
1066
+ const isCur = i === cursor;
1067
+ const isChecked = checked.has(i);
1068
+ const pointer = isCur ? `${c.accent}❯${c.reset}` : " ";
1069
+ const box = isChecked ? `${c.emerald}◼${c.reset}` : `${c.dim}◻${c.reset}`;
1070
+ const labelText = isCur
1071
+ ? `${c.bold}${c.ink}${item.label}${c.reset}`
1072
+ : isChecked
1073
+ ? `${c.ink}${item.label}${c.reset}`
1074
+ : `${c.muted}${item.label}${c.reset}`;
1075
+ const badgeText = item.badge ? ` ${item.badge}` : "";
1076
+ const hintText = item.hint ? ` ${c.dim}${item.hint}${c.reset}` : "";
1077
+ lines.push(`${RAIL} ${pointer} ${box} ${labelText}${badgeText}${hintText}`);
1078
+ }
1079
+
1080
+ if (end < items.length) {
1081
+ lines.push(`${RAIL} ${c.dim}↓ ${items.length - end} more below${c.reset}`);
1082
+ }
1083
+
1084
+ if (validationError) {
1085
+ lines.push(`${RAIL} ${STEP_WARN} ${c.amber}${validationError}${c.reset}`);
1086
+ }
1087
+
1088
+ lines.push(
1089
+ `${RAIL_END} ${c.dim}↑/↓ move · Space toggle · a toggle all · Enter confirm${c.reset}`,
1090
+ );
1091
+ live.render(lines);
1092
+ }
1093
+
1094
+ return new Promise((resolve) => {
1095
+ readline.emitKeypressEvents(process.stdin);
1096
+ const wasRaw = process.stdin.isRaw;
1097
+ process.stdin.setRawMode(true);
1098
+ process.stdin.resume();
1099
+ process.stdout.write("\x1b[?25l");
1100
+
1101
+ renderMenu();
1102
+
1103
+ function cleanup() {
1104
+ process.stdin.removeListener("keypress", onKeypress);
1105
+ if (process.stdin.isTTY) {
1106
+ process.stdin.setRawMode(Boolean(wasRaw));
1107
+ }
1108
+ process.stdin.pause();
1109
+ process.stdout.write("\x1b[?25h");
1110
+ }
1111
+
1112
+ function onKeypress(str, key = {}) {
1113
+ if (key.ctrl && key.name === "c") {
1114
+ live.clear();
1115
+ cleanup();
1116
+ console.log(`${RAIL_END} ${STEP_ERR} ${c.muted}Cancelled.${c.reset}\n`);
1117
+ process.exit(130);
1118
+ }
1119
+
1120
+ if (key.name === "up" || key.name === "k") {
1121
+ cursor = (cursor - 1 + items.length) % items.length;
1122
+ renderMenu();
1123
+ return;
1124
+ }
1125
+
1126
+ if (key.name === "down" || key.name === "j") {
1127
+ cursor = (cursor + 1) % items.length;
1128
+ renderMenu();
1129
+ return;
1130
+ }
1131
+
1132
+ if (key.name === "space") {
1133
+ if (checked.has(cursor)) checked.delete(cursor);
1134
+ else checked.add(cursor);
1135
+ renderMenu();
1136
+ return;
1137
+ }
1138
+
1139
+ if (str === "a" || str === "A") {
1140
+ if (checked.size === items.length) {
1141
+ checked.clear();
1142
+ } else {
1143
+ items.forEach((_, idx) => checked.add(idx));
1144
+ }
1145
+ renderMenu();
1146
+ return;
1147
+ }
1148
+
1149
+ if (key.name === "return" || key.name === "enter") {
1150
+ if (checked.size === 0) {
1151
+ renderMenu("Select at least 1 file with Spacebar before pressing Enter.");
1152
+ return;
1153
+ }
1154
+ const selectedValues = items.filter((_, idx) => checked.has(idx)).map((i) => i.value);
1155
+ live.clear();
1156
+ cleanup();
1157
+ printStepDone(stepLabel, `${selectedValues.length} file(s) selected`);
1158
+ resolve(selectedValues);
1159
+ }
1160
+ }
1161
+
1162
+ process.stdin.on("keypress", onKeypress);
1163
+ });
1164
+ }
1165
+
1166
+ /**
1167
+ * Arrow-Key Horizontal Yes/No Toggle
1168
+ */
1169
+ async function tuiConfirm({
1170
+ title,
1171
+ stepLabel = title,
1172
+ yesLabel = "Yes",
1173
+ noLabel = "No",
1174
+ initialValue = true,
1175
+ }) {
1176
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
1177
+ return initialValue;
1178
+ }
1179
+
1180
+ const live = createLiveRenderer();
1181
+ let value = Boolean(initialValue);
1182
+
1183
+ function renderToggle() {
1184
+ const yesBtn = value
1185
+ ? `${c.accent}[ ● ${c.bold}${c.ink}${yesLabel}${c.reset}${c.accent} ]${c.reset}`
1186
+ : ` ${c.dim}○ ${noLabel ? c.muted : ""}${yesLabel}${c.reset} `;
1187
+ const noBtn = !value
1188
+ ? `${c.accent}[ ● ${c.bold}${c.ink}${noLabel}${c.reset}${c.accent} ]${c.reset}`
1189
+ : ` ${c.dim}○ ${c.muted}${noLabel}${c.reset} `;
1190
+
1191
+ live.render([
1192
+ RAIL,
1193
+ `${STEP_ACTIVE} ${c.bold}${c.ink}${title}${c.reset}`,
1194
+ `${RAIL} ${yesBtn} ${noBtn}`,
1195
+ `${RAIL_END} ${c.dim}←/→ or y/n to toggle · Enter to confirm${c.reset}`,
1196
+ ]);
1197
+ }
1198
+
1199
+ return new Promise((resolve) => {
1200
+ readline.emitKeypressEvents(process.stdin);
1201
+ const wasRaw = process.stdin.isRaw;
1202
+ process.stdin.setRawMode(true);
1203
+ process.stdin.resume();
1204
+ process.stdout.write("\x1b[?25l");
1205
+
1206
+ renderToggle();
1207
+
1208
+ function cleanup() {
1209
+ process.stdin.removeListener("keypress", onKeypress);
1210
+ if (process.stdin.isTTY) {
1211
+ process.stdin.setRawMode(Boolean(wasRaw));
1212
+ }
1213
+ process.stdin.pause();
1214
+ process.stdout.write("\x1b[?25h");
1215
+ }
1216
+
1217
+ function onKeypress(str, key = {}) {
1218
+ if (key.ctrl && key.name === "c") {
1219
+ live.clear();
1220
+ cleanup();
1221
+ console.log(`${RAIL_END} ${STEP_ERR} ${c.muted}Cancelled.${c.reset}\n`);
1222
+ process.exit(130);
1223
+ }
1224
+
1225
+ if (key.name === "left" || key.name === "right" || key.name === "tab" || key.name === "h" || key.name === "l") {
1226
+ value = !value;
1227
+ renderToggle();
1228
+ return;
1229
+ }
1230
+
1231
+ if (str === "y" || str === "Y") {
1232
+ value = true;
1233
+ renderToggle();
1234
+ return;
1235
+ }
1236
+
1237
+ if (str === "n" || str === "N") {
1238
+ value = false;
1239
+ renderToggle();
1240
+ return;
1241
+ }
1242
+
1243
+ if (key.name === "return" || key.name === "enter") {
1244
+ live.clear();
1245
+ cleanup();
1246
+ printStepDone(stepLabel, value ? yesLabel : noLabel);
1247
+ resolve(value);
1248
+ }
1249
+ }
1250
+
1251
+ process.stdin.on("keypress", onKeypress);
1252
+ });
1253
+ }
1254
+
1255
+ /**
1256
+ * Styled Inline Text / Token Input Along the Vertical Rail
1257
+ */
1258
+ async function tuiTextInput({ title, stepLabel = title, hint = "", placeholder = "", mask = false }) {
1259
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
1260
+ return promptLine(`${title}: `);
1261
+ }
1262
+
1263
+ const live = createLiveRenderer();
1264
+ let val = "";
1265
+
1266
+ function renderInput(errText = "") {
1267
+ const displayVal = val.length > 0
1268
+ ? mask
1269
+ ? `${val.slice(0, 10)}${"•".repeat(Math.min(24, Math.max(0, val.length - 10)))}`
1270
+ : val
1271
+ : `${c.dim}${placeholder}${c.reset}`;
1272
+
1273
+ const lines = [RAIL, `${STEP_ACTIVE} ${c.bold}${c.ink}${title}${c.reset}`];
1274
+ if (hint) {
1275
+ lines.push(`${RAIL} ${c.muted}${hint}${c.reset}`);
1276
+ }
1277
+ lines.push(`${RAIL} ${c.accent}❯${c.reset} ${displayVal}${c.accent}█${c.reset}`);
1278
+ if (errText) {
1279
+ lines.push(`${RAIL} ${STEP_WARN} ${c.amber}${errText}${c.reset}`);
1280
+ }
1281
+ lines.push(`${RAIL_END} ${c.dim}Paste or type value · Enter to submit · Ctrl+C to cancel${c.reset}`);
1282
+ live.render(lines);
1283
+ }
1284
+
1285
+ return new Promise((resolve) => {
1286
+ readline.emitKeypressEvents(process.stdin);
1287
+ const wasRaw = process.stdin.isRaw;
1288
+ process.stdin.setRawMode(true);
1289
+ process.stdin.resume();
1290
+ process.stdout.write("\x1b[?25l");
1291
+
1292
+ renderInput();
1293
+
1294
+ function cleanup() {
1295
+ process.stdin.removeListener("keypress", onKeypress);
1296
+ if (process.stdin.isTTY) {
1297
+ process.stdin.setRawMode(Boolean(wasRaw));
1298
+ }
1299
+ process.stdin.pause();
1300
+ process.stdout.write("\x1b[?25h");
1301
+ }
1302
+
1303
+ function onKeypress(str, key = {}) {
1304
+ if (key.ctrl && key.name === "c") {
1305
+ live.clear();
1306
+ cleanup();
1307
+ console.log(`${RAIL_END} ${STEP_ERR} ${c.muted}Cancelled.${c.reset}\n`);
1308
+ process.exit(130);
1309
+ }
1310
+
1311
+ if (key.name === "return" || key.name === "enter") {
1312
+ const trimmed = val.trim();
1313
+ if (!trimmed) {
1314
+ renderInput("Please enter a value before pressing Enter.");
1315
+ return;
1316
+ }
1317
+ live.clear();
1318
+ cleanup();
1319
+ const summary = mask && trimmed.length > 12 ? `${trimmed.slice(0, 11)}…` : trimmed;
1320
+ printStepDone(stepLabel, summary);
1321
+ resolve(trimmed);
1322
+ return;
1323
+ }
1324
+
1325
+ if (key.name === "backspace") {
1326
+ val = val.slice(0, -1);
1327
+ renderInput();
1328
+ return;
1329
+ }
1330
+
1331
+ if (str && !key.ctrl && !key.meta) {
1332
+ // Support multi-character paste bursts cleanly
1333
+ const clean = str.replace(/[\r\n]+/g, "");
1334
+ if (clean) {
1335
+ val += clean;
1336
+ renderInput();
1337
+ }
1338
+ }
1339
+ }
1340
+
1341
+ process.stdin.on("keypress", onKeypress);
1342
+ });
1343
+ }
1344
+
1345
+ async function resolveBestApiUrl(explicitUrl) {
1346
+ if (explicitUrl) return explicitUrl.replace(/\/+$/, "");
1347
+ if (process.env.NETWORKBASE_API_URL) return process.env.NETWORKBASE_API_URL.replace(/\/+$/, "");
1348
+ const localCfg = getLocalConfig();
1349
+ if (localCfg?.apiUrl) return localCfg.apiUrl.replace(/\/+$/, "");
1350
+ const creds = getCredentials();
1351
+ if (creds?.apiUrl) return creds.apiUrl.replace(/\/+$/, "");
1352
+
1353
+ // Probe local development server (http://localhost:3000) before defaulting to production
1354
+ try {
1355
+ const controller = new AbortController();
1356
+ const timer = setTimeout(() => controller.abort(), 600);
1357
+ const res = await fetch("http://localhost:3000/api/v1/extension/session", {
1358
+ signal: controller.signal,
1359
+ });
1360
+ clearTimeout(timer);
1361
+ if (res.status === 200 || res.status === 401) {
1362
+ return "http://localhost:3000";
1363
+ }
1364
+ } catch {
1365
+ // Local dev server not running; fall back to production URL
1366
+ }
1367
+ return DEFAULT_API_URL.replace(/\/+$/, "");
1368
+ }
1369
+
1370
+ function openBrowserUrl(url) {
1371
+ try {
1372
+ if (process.platform === "darwin") {
1373
+ execFileSync("open", [url], { stdio: "ignore" });
1374
+ return true;
1375
+ }
1376
+ if (process.platform === "win32") {
1377
+ execFileSync("cmd", ["/c", "start", "", url], { stdio: "ignore" });
1378
+ return true;
1379
+ }
1380
+ execFileSync("xdg-open", [url], { stdio: "ignore" });
1381
+ return true;
1382
+ } catch {
1383
+ return false;
1384
+ }
1385
+ }
1386
+
1387
+ async function loginWithBrowser(apiUrl, flags = {}) {
1388
+ const state = crypto.randomBytes(24).toString("hex");
1389
+
1390
+ return new Promise((resolve, reject) => {
1391
+ let timeoutHandle;
1392
+ const server = http.createServer(async (req, res) => {
1393
+ try {
1394
+ const reqUrl = new URL(req.url || "/", "http://127.0.0.1");
1395
+ if (reqUrl.pathname !== "/auth-callback") {
1396
+ res.writeHead(404, { "Content-Type": "text/plain" });
1397
+ res.end("Not found");
1398
+ return;
1399
+ }
1400
+
1401
+ const error = reqUrl.searchParams.get("error");
1402
+ const message = reqUrl.searchParams.get("message");
1403
+ const code = reqUrl.searchParams.get("code");
1404
+ const returnedState = reqUrl.searchParams.get("state");
1405
+
1406
+ if (error) {
1407
+ res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
1408
+ res.end(`<!doctype html><html><body style="font-family:system-ui,sans-serif;padding:40px;text-align:center;">
1409
+ <h2>Authorization Cancelled</h2>
1410
+ <p>${message || error}</p>
1411
+ <p>You can close this window and return to your terminal.</p>
1412
+ </body></html>`);
1413
+ clearTimeout(timeoutHandle);
1414
+ server.close();
1415
+ reject(new Error(message || `Browser authorization failed: ${error}`));
1416
+ return;
1417
+ }
1418
+
1419
+ if (!code || returnedState !== state) {
1420
+ res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
1421
+ res.end(`<!doctype html><html><body style="font-family:system-ui,sans-serif;padding:40px;text-align:center;">
1422
+ <h2>Invalid Callback State</h2>
1423
+ <p>Please restart sign-in from your terminal.</p>
1424
+ </body></html>`);
1425
+ clearTimeout(timeoutHandle);
1426
+ server.close();
1427
+ reject(new Error("Invalid state or missing authorization code from browser callback."));
1428
+ return;
1429
+ }
1430
+
1431
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
1432
+ res.end(`<!doctype html><html><body style="font-family:system-ui,-apple-system,sans-serif;background:#0a0a0a;color:#fafafa;padding:64px 24px;text-align:center;">
1433
+ <div style="max-width:420px;margin:0 auto;border:1px solid #262626;border-radius:12px;padding:32px;background:#121212;">
1434
+ <div style="font-size:28px;margin-bottom:12px;">✔</div>
1435
+ <h2 style="margin:0 0 8px;font-size:18px;font-weight:600;">NetworkBase CLI Connected</h2>
1436
+ <p style="margin:0;color:#a1a1aa;font-size:14px;line-height:1.5;">Your terminal is now authenticated. You can close this tab and return to your terminal.</p>
1437
+ </div>
1438
+ </body></html>`);
1439
+
1440
+ clearTimeout(timeoutHandle);
1441
+ server.close();
1442
+
1443
+ const exchanged = await apiRequest("/api/v1/extension/auth-code", {
1444
+ method: "POST",
1445
+ apiUrl,
1446
+ body: { code, state },
1447
+ });
1448
+
1449
+ const token = exchanged.token;
1450
+ const sessionInfo = await apiRequest("/api/v1/extension/session", {
1451
+ apiUrl,
1452
+ token,
1453
+ });
1454
+
1455
+ saveCredentials({
1456
+ token,
1457
+ apiUrl,
1458
+ sessionId: sessionInfo.sessionId,
1459
+ tokenType: sessionInfo.tokenType || "device",
1460
+ user: sessionInfo.user || null,
1461
+ });
1462
+
1463
+ resolve({
1464
+ authenticated: true,
1465
+ method: "browser",
1466
+ apiUrl,
1467
+ sessionId: sessionInfo.sessionId,
1468
+ tokenType: sessionInfo.tokenType || "device",
1469
+ user: sessionInfo.user,
1470
+ });
1471
+ } catch (err) {
1472
+ clearTimeout(timeoutHandle);
1473
+ server.close();
1474
+ reject(err);
1475
+ }
1476
+ });
1477
+
1478
+ server.listen(0, "127.0.0.1", () => {
1479
+ const addr = server.address();
1480
+ const port = typeof addr === "object" && addr ? addr.port : 0;
1481
+ const callbackUrl = `http://127.0.0.1:${port}/auth-callback`;
1482
+ const authorizeUrl = `${apiUrl}/authorize?callback=${encodeURIComponent(callbackUrl)}&state=${encodeURIComponent(state)}`;
1483
+
1484
+ const opened = openBrowserUrl(authorizeUrl);
1485
+ if (!flags.json) {
1486
+ console.log(`\n→ ${opened ? "Opened" : "Open"} your browser to approve NetworkBase CLI access:`);
1487
+ console.log(` ${authorizeUrl}`);
1488
+ console.log(`→ Waiting for approval in browser... (Press Ctrl+C to cancel)\n`);
1489
+ }
1490
+
1491
+ timeoutHandle = setTimeout(() => {
1492
+ server.close();
1493
+ reject(
1494
+ new Error(
1495
+ `Browser login timed out after 120s. Run \`nb auth login --token <nb_pat_...>\` or open: ${authorizeUrl}`,
1496
+ ),
1497
+ );
1498
+ }, 120000);
1499
+ });
1500
+ });
1501
+ }
1502
+
1503
+ async function loginWithToken(rawToken, apiUrl, explicitUrl = null) {
1504
+ const token = rawToken ? rawToken.trim() : "";
1505
+ if (!token || (!token.startsWith("nb_dev_") && !token.startsWith("nb_pat_"))) {
1506
+ throw new Error("A valid `nb_dev_...` or `nb_pat_...` token is required.");
1507
+ }
1508
+
1509
+ let resolvedUrl = apiUrl;
1510
+ let sessionInfo;
1511
+ try {
1512
+ sessionInfo = await apiRequest("/api/v1/extension/session", {
1513
+ apiUrl: resolvedUrl,
1514
+ token,
1515
+ });
1516
+ } catch (err) {
1517
+ if (!explicitUrl && resolvedUrl !== "http://localhost:3000") {
1518
+ resolvedUrl = "http://localhost:3000";
1519
+ sessionInfo = await apiRequest("/api/v1/extension/session", {
1520
+ apiUrl: resolvedUrl,
1521
+ token,
1522
+ });
1523
+ } else {
1524
+ throw err;
1525
+ }
1526
+ }
1527
+
1528
+ if (!sessionInfo.active && !explicitUrl && resolvedUrl !== "http://localhost:3000") {
1529
+ try {
1530
+ const localInfo = await apiRequest("/api/v1/extension/session", {
1531
+ apiUrl: "http://localhost:3000",
1532
+ token,
1533
+ });
1534
+ if (localInfo?.active) {
1535
+ resolvedUrl = "http://localhost:3000";
1536
+ sessionInfo = localInfo;
1537
+ }
1538
+ } catch {
1539
+ // Ignore fallback failure
1540
+ }
1541
+ }
1542
+
1543
+ if (!sessionInfo.active) {
1544
+ throw new Error("This token is expired or has been revoked.");
1545
+ }
1546
+
1547
+ saveCredentials({
1548
+ token,
1549
+ apiUrl: resolvedUrl,
1550
+ sessionId: sessionInfo.sessionId,
1551
+ tokenType: sessionInfo.tokenType || (token.startsWith("nb_pat_") ? "pat" : "device"),
1552
+ user: sessionInfo.user || null,
1553
+ });
1554
+
1555
+ return {
1556
+ authenticated: true,
1557
+ method: "token",
1558
+ apiUrl: resolvedUrl,
1559
+ sessionId: sessionInfo.sessionId,
1560
+ tokenType: sessionInfo.tokenType || (token.startsWith("nb_pat_") ? "pat" : "device"),
1561
+ user: sessionInfo.user,
1562
+ };
1563
+ }
1564
+
1565
+ async function promptLine(question) {
1566
+ const rl = readline.createInterface({
1567
+ input: process.stdin,
1568
+ output: process.stdout,
1569
+ });
1570
+ return new Promise((resolve) => {
1571
+ rl.question(question, (answer) => {
1572
+ rl.close();
1573
+ resolve(answer.trim());
1574
+ });
1575
+ });
1576
+ }
1577
+
1578
+ async function performInteractiveOrFlagLogin(flags, positionalToken = null) {
1579
+ const explicitUrl =
1580
+ typeof flags["api-url"] === "string"
1581
+ ? flags["api-url"]
1582
+ : typeof flags.url === "string"
1583
+ ? flags.url
1584
+ : null;
1585
+ const apiUrl = await resolveBestApiUrl(explicitUrl);
1586
+ const directToken = typeof flags.token === "string" ? flags.token.trim() : positionalToken?.trim();
1587
+
1588
+ if (directToken) {
1589
+ return withSpinner(
1590
+ `Verifying token against ${apiUrl}…`,
1591
+ () => loginWithToken(directToken, apiUrl, explicitUrl),
1592
+ { silent: Boolean(flags.json) },
1593
+ );
1594
+ }
1595
+
1596
+ if (flags.web || flags.browser || !process.stdin.isTTY) {
1597
+ return loginWithBrowser(apiUrl, flags);
1598
+ }
1599
+
1600
+ const method = await tuiSelect({
1601
+ title: `Step 1 of 3 · Authenticate with NetworkBase (${apiUrl})`,
1602
+ stepLabel: "Authentication Method",
1603
+ items: [
1604
+ {
1605
+ label: "Login with Web Browser",
1606
+ value: "browser",
1607
+ badge: `${c.emerald}[Recommended]${c.reset}`,
1608
+ description: "Opens /authorize in your browser for 1-click Approve (zero copy-pasting)",
1609
+ },
1610
+ {
1611
+ label: "Paste Personal Access Token",
1612
+ value: "token",
1613
+ badge: `${c.muted}[nb_pat_ / nb_dev_]${c.reset}`,
1614
+ description: `Paste a token generated in ${apiUrl}/settings?tab=integrations`,
1615
+ },
1616
+ ],
1617
+ });
1618
+
1619
+ if (method === "token") {
1620
+ const entered = await tuiTextInput({
1621
+ title: "Paste your NetworkBase Access Token",
1622
+ stepLabel: "Token",
1623
+ hint: `Generate at ${apiUrl}/settings?tab=integrations#settings-integrations-pat`,
1624
+ placeholder: "nb_pat_... or nb_dev_...",
1625
+ mask: true,
1626
+ });
1627
+ return withSpinner(
1628
+ `Verifying token with ${apiUrl}…`,
1629
+ () => loginWithToken(entered, apiUrl, explicitUrl),
1630
+ { silent: Boolean(flags.json) },
1631
+ );
1632
+ }
1633
+
1634
+ return loginWithBrowser(apiUrl, flags);
1635
+ }
1636
+
1637
+ // ============================================================================
1638
+ // COMMAND HANDLERS
1639
+ // ============================================================================
1640
+
1641
+ async function handleAuth(sub, positional, flags) {
1642
+ if (!sub || sub === "login") {
1643
+ if (!flags.json && process.stdout.isTTY) {
1644
+ renderBrandHeader({ subtitle: "Account Authentication & Device Session" });
1645
+ }
1646
+ const res = await performInteractiveOrFlagLogin(flags, positional[0]);
1647
+ outputResult(res, flags, (out) => {
1648
+ const identity = out.user?.username
1649
+ ? `@${out.user.username}`
1650
+ : out.user?.email || out.sessionId;
1651
+ console.log(`${RAIL}`);
1652
+ console.log(
1653
+ `${c.dim}╰─${c.reset} ${c.emerald}✔${c.reset} Signed in as ${c.bold}${c.ink}${identity}${c.reset} ${c.muted}(${out.tokenType || "device"} session · ${out.apiUrl})${c.reset}\n`,
1654
+ );
1655
+ });
1656
+ return;
1657
+ }
1658
+
1659
+ if (sub === "logout") {
1660
+ const creds = getCredentials();
1661
+ if (creds?.token) {
1662
+ await apiRequest("/api/v1/extension/session", { method: "POST" }).catch(() => {});
1663
+ }
1664
+ if (fs.existsSync(GLOBAL_CREDENTIALS_PATH)) {
1665
+ fs.unlinkSync(GLOBAL_CREDENTIALS_PATH);
1666
+ }
1667
+ outputResult({ loggedOut: true }, flags, () => {
1668
+ console.log(`\n${c.emerald}✔${c.reset} Signed out and revoked local NetworkBase credentials.\n`);
1669
+ });
1670
+ return;
1671
+ }
1672
+
1673
+ if (sub === "whoami" || sub === "status") {
1674
+ await handleStatus(flags);
1675
+ return;
1676
+ }
1677
+
1678
+ if (sub === "setup-git") {
1679
+ const creds = getCredentials();
1680
+ const apiUrl = creds?.apiUrl || DEFAULT_API_URL;
1681
+ execFileSync("git", [
1682
+ "config",
1683
+ "--global",
1684
+ `credential.${apiUrl}.helper`,
1685
+ "!nb auth git-credential",
1686
+ ]);
1687
+ outputResult({ configured: true, apiUrl }, flags, () => {
1688
+ console.log(`\n${c.emerald}✔${c.reset} Configured Git HTTPS credential helper for ${apiUrl}\n`);
1689
+ });
1690
+ return;
1691
+ }
1692
+
1693
+ if (sub === "git-credential") {
1694
+ const creds = getCredentials();
1695
+ if (creds?.token) {
1696
+ process.stdout.write(`username=token\npassword=${creds.token}\n\n`);
1697
+ }
1698
+ return;
1699
+ }
1700
+
1701
+ throw new Error(`Unknown auth subcommand: ${sub}. Available: login, logout, whoami, setup-git`);
1702
+ }
1703
+
1704
+ async function handleInit(positional, flags, { skipHeader = false } = {}) {
1705
+ const requestedId = typeof flags.workspace === "string" ? flags.workspace : positional[0];
1706
+ const requestedTaskId = typeof flags.task === "string" ? flags.task : null;
1707
+ const explicitUrl =
1708
+ typeof flags["api-url"] === "string"
1709
+ ? flags["api-url"]
1710
+ : typeof flags.url === "string"
1711
+ ? flags.url
1712
+ : null;
1713
+
1714
+ if (!flags.json && !skipHeader) {
1715
+ renderBrandHeader({ subtitle: "Interactive Workspace & Sprint Task Setup" });
1716
+ }
1717
+
1718
+ // Step 1: Check or Perform Authentication
1719
+ let creds = getCredentials();
1720
+ let apiUrl = await resolveBestApiUrl(explicitUrl);
1721
+ let activeSession = null;
1722
+
1723
+ if (creds?.token && !flags.reauth) {
1724
+ try {
1725
+ const check = await withSpinner(
1726
+ "Verifying active session…",
1727
+ () =>
1728
+ apiRequest("/api/v1/extension/session", {
1729
+ apiUrl: explicitUrl ? apiUrl : creds.apiUrl || apiUrl,
1730
+ token: creds.token,
1731
+ }),
1732
+ { silent: Boolean(flags.json) },
1733
+ );
1734
+ if (check?.active) {
1735
+ activeSession = check;
1736
+ apiUrl = (explicitUrl ? apiUrl : creds.apiUrl || apiUrl).replace(/\/+$/, "");
1737
+ }
1738
+ } catch {
1739
+ activeSession = null;
1740
+ }
1741
+ }
1742
+
1743
+ if (!activeSession) {
1744
+ const loginRes = await performInteractiveOrFlagLogin(flags);
1745
+ apiUrl = loginRes.apiUrl;
1746
+ creds = getCredentials();
1747
+ if (!flags.json) {
1748
+ const identity = loginRes.user?.username
1749
+ ? `@${loginRes.user.username}`
1750
+ : loginRes.user?.email || loginRes.sessionId;
1751
+ printStepDone("Authenticated", `${identity} (${apiUrl})`);
1752
+ }
1753
+ } else if (!flags.json) {
1754
+ const identity = activeSession.user?.username
1755
+ ? `@${activeSession.user.username}`
1756
+ : activeSession.user?.email || activeSession.sessionId;
1757
+ printStepDone("Authenticated", `${identity} (${apiUrl})`);
1758
+ }
1759
+
1760
+ // Step 2: Workspace Selection & Binding
1761
+ const { workspaces } = await withSpinner(
1762
+ "Loading accessible workspaces…",
1763
+ () => apiRequest("/api/v1/extension/workspaces", { apiUrl }),
1764
+ { silent: Boolean(flags.json) },
1765
+ );
1766
+
1767
+ if (!workspaces || workspaces.length === 0) {
1768
+ throw new Error("No accessible workspaces found for your account.");
1769
+ }
1770
+
1771
+ const currentLinkedId = getLocalConfig()?.projectId;
1772
+ let chosen = null;
1773
+
1774
+ if (requestedId) {
1775
+ chosen =
1776
+ workspaces.find((w) => w.id === requestedId || w.slug === requestedId) || {
1777
+ id: requestedId,
1778
+ title: requestedId,
1779
+ slug: requestedId,
1780
+ };
1781
+ if (!flags.json) {
1782
+ printStepDone("Workspace", `${chosen.title} (${chosen.slug || chosen.id})`);
1783
+ }
1784
+ } else if (!process.stdin.isTTY || flags.json) {
1785
+ chosen = workspaces[0];
1786
+ } else {
1787
+ const defaultIdx = Math.max(
1788
+ 0,
1789
+ workspaces.findIndex((w) => w.id === currentLinkedId),
1790
+ );
1791
+ chosen = await tuiSelect({
1792
+ title: "Step 2 of 3 · Select a Workspace to link to this folder",
1793
+ stepLabel: "Workspace",
1794
+ searchable: workspaces.length > 4,
1795
+ initialIndex: defaultIdx,
1796
+ items: workspaces.map((ws) => ({
1797
+ label: ws.title,
1798
+ summaryLabel: `${ws.title} (${ws.slug || ws.id})`,
1799
+ hint: ws.slug || ws.id.slice(0, 8),
1800
+ badge: `${c.muted}[${ws.role || "member"}]${c.reset}${ws.id === currentLinkedId ? ` ${c.emerald}● current${c.reset}` : ""}`,
1801
+ value: ws,
1802
+ })),
1803
+ });
1804
+ }
1805
+
1806
+ const config = {
1807
+ projectId: chosen.id,
1808
+ title: chosen.title,
1809
+ slug: chosen.slug,
1810
+ apiUrl,
1811
+ linkedAt: new Date().toISOString(),
1812
+ };
1813
+ saveLocalConfig(config);
1814
+
1815
+ // Step 3: Optional Active Task Binding
1816
+ let boundTask = null;
1817
+ let loadedTasks = null;
1818
+ if (requestedTaskId) {
1819
+ try {
1820
+ const detail = await withSpinner(
1821
+ "Loading task details…",
1822
+ () =>
1823
+ apiRequest(
1824
+ `/api/v1/extension/task-detail?projectId=${chosen.id}&taskId=${encodeURIComponent(requestedTaskId)}`,
1825
+ { apiUrl },
1826
+ ),
1827
+ { silent: Boolean(flags.json) },
1828
+ );
1829
+ if (detail?.task) {
1830
+ boundTask = detail.task;
1831
+ }
1832
+ } catch {
1833
+ boundTask = { id: requestedTaskId, title: requestedTaskId, status: "in_progress" };
1834
+ }
1835
+ if (!flags.json && boundTask) {
1836
+ printStepDone("Active Task", `${boundTask.title}`);
1837
+ }
1838
+ } else if (process.stdin.isTTY && !flags.json && !flags["no-task"]) {
1839
+ try {
1840
+ const taskData = await withSpinner(
1841
+ `Loading sprint tasks for ${chosen.title}…`,
1842
+ () =>
1843
+ apiRequest(
1844
+ `/api/v1/extension/workspace-tasks?projectId=${chosen.id}&scope=all`,
1845
+ { apiUrl },
1846
+ ),
1847
+ { silent: Boolean(flags.json) },
1848
+ );
1849
+ loadedTasks = taskData?.tasks || [];
1850
+ const openTasks = loadedTasks.filter((t) => t.status !== "done");
1851
+ if (openTasks.length > 0) {
1852
+ const currentTaskId = getLocalState()?.activeTaskId;
1853
+ const taskItems = [
1854
+ ...openTasks.map((t) => {
1855
+ const num = t.taskNumber ? `#${t.taskNumber} ` : "";
1856
+ const stSum = t.subtaskSummary || { completed: 0, total: (t.subtasks || []).length };
1857
+ const stText = stSum.total > 0 ? ` · ☑ ${stSum.completed}/${stSum.total} subtasks` : "";
1858
+ const fCount = t.filesCount ?? (t.files || []).length;
1859
+ const fText = fCount > 0 ? ` · 📎 ${fCount} file(s)` : "";
1860
+ return {
1861
+ label: `${num}${t.title}`,
1862
+ summaryLabel: `${num}${t.title}`,
1863
+ badge: `${formatStatusBadge(t.status)} ${formatPriorityBadge(t.priority)}`,
1864
+ description: `${t.id === currentTaskId ? "Currently bound · " : ""}${
1865
+ (t.descriptionPreview || t.description || "No description").replace(/\s+/g, " ").slice(0, 68)
1866
+ }${stText}${fText}`,
1867
+ value: t,
1868
+ };
1869
+ }),
1870
+ {
1871
+ label: "Skip for now (push to workspace without a specific task)",
1872
+ summaryLabel: "None (workspace level)",
1873
+ badge: `${c.dim}[Workspace Root]${c.reset}`,
1874
+ value: null,
1875
+ },
1876
+ ];
1877
+
1878
+ const initialTaskIdx = Math.max(
1879
+ 0,
1880
+ openTasks.findIndex((t) => t.id === currentTaskId),
1881
+ );
1882
+
1883
+ boundTask = await tuiSelect({
1884
+ title: "Step 3 of 3 · Bind an Active Sprint Task (Optional)",
1885
+ stepLabel: "Active Task",
1886
+ searchable: openTasks.length > 5,
1887
+ allowCancel: true,
1888
+ initialIndex: initialTaskIdx,
1889
+ items: taskItems,
1890
+ });
1891
+ } else {
1892
+ printStepDone("Active Task", "No open tasks in workspace");
1893
+ }
1894
+ } catch {
1895
+ // Non-fatal if workspace has no tasks
1896
+ }
1897
+ }
1898
+
1899
+ if (boundTask) {
1900
+ saveLocalState({
1901
+ ...getLocalState(),
1902
+ activeTaskId: boundTask.id,
1903
+ activeTaskTitle: boundTask.title,
1904
+ startedAt: new Date().toISOString(),
1905
+ });
1906
+ if (boundTask.status === "todo" && boundTask.updatedAt) {
1907
+ await apiRequest("/api/v1/extension/task-update", {
1908
+ method: "PATCH",
1909
+ apiUrl,
1910
+ body: {
1911
+ kind: "status",
1912
+ projectId: chosen.id,
1913
+ taskId: boundTask.id,
1914
+ status: "in_progress",
1915
+ expectedUpdatedAt: new Date(boundTask.updatedAt).toISOString(),
1916
+ },
1917
+ }).catch(() => {});
1918
+ boundTask.status = "in_progress";
1919
+ }
1920
+ } else if (!requestedTaskId) {
1921
+ const prev = getLocalState();
1922
+ delete prev.activeTaskId;
1923
+ delete prev.activeTaskTitle;
1924
+ saveLocalState(prev);
1925
+ }
1926
+
1927
+ let mirrorSummary = null;
1928
+ if (!flags["no-mirror"]) {
1929
+ try {
1930
+ const [mSum, fetchedTaskData] = await withSpinner(
1931
+ `Syncing ${chosen.title} files & tasks to local mirror (.networkbase/)…`,
1932
+ () =>
1933
+ Promise.all([
1934
+ hydrateWorkspaceMirror(chosen.id),
1935
+ loadedTasks
1936
+ ? Promise.resolve({ tasks: loadedTasks })
1937
+ : apiRequest(`/api/v1/extension/workspace-tasks?projectId=${chosen.id}&scope=all`, { apiUrl }).catch(
1938
+ () => ({ tasks: [] }),
1939
+ ),
1940
+ ]),
1941
+ { silent: Boolean(flags.json || flags.silent) },
1942
+ );
1943
+ mirrorSummary = mSum;
1944
+ loadedTasks = fetchedTaskData?.tasks || [];
1945
+ writeLocalTaskIntelligence(chosen.id, chosen.title, loadedTasks);
1946
+ } catch {
1947
+ // Non-fatal if workspace is empty
1948
+ }
1949
+ } else if (loadedTasks) {
1950
+ writeLocalTaskIntelligence(chosen.id, chosen.title, loadedTasks);
1951
+ }
1952
+
1953
+ const daemon = flags["no-daemon"] ? { running: false } : ensureBackgroundDaemon(chosen.id);
1954
+
1955
+ if (flags.silent) {
1956
+ return;
1957
+ }
1958
+
1959
+ outputResult(
1960
+ {
1961
+ ...config,
1962
+ activeTask: boundTask ? { id: boundTask.id, title: boundTask.title } : null,
1963
+ mirrorDir: mirrorSummary?.mirrorDir || getLocalMirrorDir(),
1964
+ tasksBriefingPath: path.join(getLocalTasksDir(), "TASKS.md"),
1965
+ mirroredFilesCount: (mirrorSummary?.downloadedCount || 0) + (mirrorSummary?.upToDateCount || 0),
1966
+ tasksCount: (loadedTasks || []).length,
1967
+ daemonRunning: daemon.running,
1968
+ daemonPid: daemon.pid || null,
1969
+ },
1970
+ flags,
1971
+ (res) => {
1972
+ if (mirrorSummary) {
1973
+ printStepDone(
1974
+ "Local Mirror",
1975
+ `.networkbase/mirror/ (${res.mirroredFilesCount} file(s)) & .networkbase/tasks/TASKS.md (${res.tasksCount} task(s))`,
1976
+ );
1977
+ }
1978
+ if (res.daemonRunning) {
1979
+ printStepDone(
1980
+ "Auto-Sync",
1981
+ `Background watcher active (PID ${res.daemonPid} · saves push automatically in <400ms)`,
1982
+ );
1983
+ }
1984
+ console.log(`${RAIL}`);
1985
+ console.log(
1986
+ `${c.dim}╰─${c.reset} ${c.emerald}✔${c.reset} ${c.bold}${c.ink}Workspace ready!${c.reset} Edit files in ${c.accent}.networkbase/mirror/${c.reset} or run ${c.accent}nb task${c.reset}.\n`,
1987
+ );
1988
+ },
1989
+ );
1990
+ }
1991
+
1992
+ async function handleStatus(flags) {
1993
+ const creds = getCredentials();
1994
+ const localCfg = getLocalConfig();
1995
+ const localState = getLocalState();
1996
+ const apiUrl = await resolveBestApiUrl(localCfg?.apiUrl || creds?.apiUrl);
1997
+
1998
+ let sessionInfo = { active: false, user: null, sessionId: null, tokenType: null };
1999
+ if (creds?.token) {
2000
+ try {
2001
+ sessionInfo = await apiRequest("/api/v1/extension/session", { apiUrl, token: creds.token });
2002
+ } catch {
2003
+ sessionInfo = { active: false, user: creds.user || null, sessionId: creds.sessionId, tokenType: creds.tokenType };
2004
+ }
2005
+ }
2006
+
2007
+ const localFilesCount = localCfg?.projectId ? collectLocalFiles([], process.cwd()).length : 0;
2008
+
2009
+ const statusPayload = {
2010
+ authenticated: Boolean(sessionInfo.active),
2011
+ apiUrl,
2012
+ sessionId: sessionInfo.sessionId || null,
2013
+ tokenType: sessionInfo.tokenType || creds?.tokenType || null,
2014
+ user: sessionInfo.user || creds?.user || null,
2015
+ workspace: localCfg?.projectId ? localCfg : null,
2016
+ activeTask: localState?.activeTaskId
2017
+ ? { id: localState.activeTaskId, title: localState.activeTaskTitle }
2018
+ : null,
2019
+ localFilesCount,
2020
+ };
2021
+
2022
+ outputResult(statusPayload, flags, (res) => {
2023
+ const identity = res.authenticated
2024
+ ? `${c.emerald}●${c.reset} ${c.bold}${c.ink}${res.user?.username ? `@${res.user.username}` : res.user?.email || res.sessionId}${c.reset} ${c.muted}(${res.tokenType || "device"})${c.reset}`
2025
+ : `${c.amber}○ Not signed in${c.reset}`;
2026
+
2027
+ const wsDisplay = res.workspace?.projectId
2028
+ ? `${c.bold}${c.ink}${res.workspace.title || res.workspace.projectId}${c.reset} ${c.muted}(${res.workspace.slug || res.workspace.projectId.slice(0, 8)})${c.reset}`
2029
+ : `${c.muted}Not linked (run \`nb init\`)${c.reset}`;
2030
+
2031
+ const taskDisplay = res.activeTask
2032
+ ? `${c.ink}${res.activeTask.title || res.activeTask.id}${c.reset}`
2033
+ : `${c.muted}None bound${c.reset}`;
2034
+
2035
+ renderBrandHeader({
2036
+ subtitle: `Server: ${res.apiUrl}`,
2037
+ contextRows: [
2038
+ { label: "Account", value: identity },
2039
+ { label: "Workspace", value: wsDisplay },
2040
+ { label: "Active Task", value: taskDisplay },
2041
+ { label: "Local Tree", value: `${c.ink}${res.localFilesCount} tracked file(s)${c.reset}` },
2042
+ ],
2043
+ });
2044
+ console.log("");
2045
+ });
2046
+
2047
+ return statusPayload;
2048
+ }
2049
+
2050
+ async function handleWorkspace(sub, positional, flags) {
2051
+ if (sub === "switch" || (!sub && process.stdin.isTTY && !flags.json)) {
2052
+ const target = positional[0] || flags.workspace;
2053
+ if (target) {
2054
+ await handleInit([target], { ...flags, "no-task": true });
2055
+ return;
2056
+ }
2057
+ await handleInit([], flags);
2058
+ return;
2059
+ }
2060
+
2061
+ if (!sub || sub === "list" || sub === "ls") {
2062
+ const data = await apiRequest("/api/v1/extension/workspaces");
2063
+ const currentId = getLocalConfig().projectId;
2064
+ outputResult(data, flags, (res) => {
2065
+ renderBrandHeader({ subtitle: `Accessible Workspaces (${res.workspaces.length})` });
2066
+ console.log(RAIL);
2067
+ for (const ws of res.workspaces) {
2068
+ const marker = ws.id === currentId ? `${c.emerald}●${c.reset}` : `${c.dim}○${c.reset}`;
2069
+ console.log(
2070
+ `${RAIL} ${marker} ${c.bold}${c.ink}${ws.title}${c.reset} ${c.muted}(${ws.slug || ws.id})${c.reset} ${formatStatusBadge(ws.role)}`,
2071
+ );
2072
+ }
2073
+ console.log(`${c.dim}╰─${c.reset} Run ${c.accent}nb workspace switch${c.reset} to switch interactively.\n`);
2074
+ });
2075
+ return;
2076
+ }
2077
+
2078
+ if (sub === "info") {
2079
+ const cfg = getLocalConfig();
2080
+ if (!cfg.projectId) throw new Error("No workspace linked. Run `nb init` first.");
2081
+ const summary = await apiRequest(`/api/v1/extension/workspace-summary?projectId=${cfg.projectId}`);
2082
+ outputResult({ workspace: cfg, summary }, flags, (res) => {
2083
+ renderBrandHeader({
2084
+ subtitle: "Workspace Summary",
2085
+ contextRows: [
2086
+ { label: "Workspace", value: `${c.bold}${c.ink}${res.workspace.title}${c.reset}` },
2087
+ { label: "Project ID", value: `${c.muted}${res.workspace.projectId}${c.reset}` },
2088
+ { label: "Total Tasks", value: `${c.ink}${res.summary.taskCount}${c.reset}` },
2089
+ ],
2090
+ });
2091
+ console.log("");
2092
+ });
2093
+ return;
2094
+ }
2095
+
2096
+ throw new Error(`Unknown workspace subcommand: ${sub}`);
2097
+ }
2098
+
2099
+ async function hydrateTaskAttachedFiles(projectId, attachedFiles, cwd = process.cwd()) {
2100
+ if (!attachedFiles || attachedFiles.length === 0) return 0;
2101
+ const mirrorDir = getLocalMirrorDir(cwd);
2102
+ ensureDir(mirrorDir);
2103
+ const manifest = getLocalManifest(cwd);
2104
+ const manifestFiles = manifest.projectId === projectId && manifest.files ? manifest.files : {};
2105
+ const manifestUpdates = [];
2106
+ let hydratedCount = 0;
2107
+
2108
+ const candidates = attachedFiles.filter(
2109
+ (f) => f.type !== "folder" && (f.size ?? 0) <= 512 * 1024 && (f.path || f.name),
2110
+ );
2111
+
2112
+ for (let offset = 0; offset < candidates.length; offset += 8) {
2113
+ const chunk = candidates.slice(offset, offset + 8);
2114
+ await Promise.all(
2115
+ chunk.map(async (f) => {
2116
+ const rawPath = f.path || `/${f.name}`;
2117
+ const normPath = rawPath.startsWith("/") ? rawPath : `/${rawPath}`;
2118
+ const cleanRel = normPath.replace(/^\/+/, "");
2119
+ const mirrorDest = path.join(mirrorDir, cleanRel);
2120
+ const expectedHash = (f.contentHash || manifestFiles[normPath]?.contentHash || "").toLowerCase();
2121
+
2122
+ if (expectedHash && fs.existsSync(mirrorDest)) {
2123
+ try {
2124
+ const localHash = computeFileSha256(mirrorDest).hash.toLowerCase();
2125
+ if (localHash === expectedHash) {
2126
+ hydratedCount++;
2127
+ return;
2128
+ }
2129
+ } catch {
2130
+ // Re-download if unreadable
2131
+ }
2132
+ }
2133
+
2134
+ try {
2135
+ const { buffer, meta } = await downloadRemoteFileBuffer(projectId, normPath);
2136
+ if (buffer) {
2137
+ ensureDir(path.dirname(mirrorDest));
2138
+ fs.writeFileSync(mirrorDest, buffer);
2139
+ hydratedCount++;
2140
+ manifestUpdates.push({
2141
+ path: normPath,
2142
+ nodeId: meta?.nodeId || f.nodeId || f.id,
2143
+ version: meta?.currentVersion || f.currentVersion || 1,
2144
+ contentHash:
2145
+ meta?.contentHash || f.contentHash || crypto.createHash("sha256").update(buffer).digest("hex"),
2146
+ size: buffer.length,
2147
+ });
2148
+ }
2149
+ } catch {
2150
+ // Ignore unavailable file
2151
+ }
2152
+ }),
2153
+ );
2154
+ }
2155
+
2156
+ if (manifestUpdates.length > 0) {
2157
+ updateManifestFiles(projectId, manifestUpdates, cwd);
2158
+ }
2159
+ return hydratedCount;
2160
+ }
2161
+
2162
+ function renderTaskDetailCard(res, cfg, hydratedCount = 0) {
2163
+ const t = res.task;
2164
+ const numStr = t.taskNumber ? `#${t.taskNumber}` : t.id.slice(0, 8);
2165
+ const subtasks = res.subtasks || [];
2166
+ const stSummary = res.subtaskSummary || {
2167
+ completed: subtasks.filter((s) => s.completed).length,
2168
+ total: subtasks.length,
2169
+ };
2170
+ const files = res.files || [];
2171
+ const comments = res.comments || [];
2172
+ const pushes = res.pushes || [];
2173
+
2174
+ const contextRows = [
2175
+ { label: "Title", value: `${c.bold}${c.ink}${t.title}${c.reset}` },
2176
+ {
2177
+ label: "Status",
2178
+ value: `${formatStatusBadge(t.status)} · Priority: ${formatPriorityBadge(t.priority)}${
2179
+ t.storyPoints ? ` · Points: ${c.ink}${t.storyPoints}${c.reset}` : ""
2180
+ }`,
2181
+ },
2182
+ ];
2183
+
2184
+ if (t.sprint?.name || t.assignee?.name || t.assignee?.username) {
2185
+ const sprintPart = t.sprint?.name ? `Sprint: ${c.ink}${t.sprint.name}${c.reset}` : "";
2186
+ const assigneePart =
2187
+ t.assignee?.name || t.assignee?.username
2188
+ ? `Assignee: ${c.ink}${t.assignee.username ? `@${t.assignee.username}` : t.assignee.name}${c.reset}`
2189
+ : "";
2190
+ contextRows.push({
2191
+ label: "Assignment",
2192
+ value: [sprintPart, assigneePart].filter(Boolean).join(" · "),
2193
+ });
2194
+ }
2195
+ if (t.reviewStatus && t.reviewStatus !== "none") {
2196
+ contextRows.push({
2197
+ label: "Review",
2198
+ value: `${c.amber}${t.reviewStatus.toUpperCase()}${c.reset}${
2199
+ t.reviewReason ? ` · "${t.reviewReason}"` : ""
2200
+ }`,
2201
+ });
2202
+ }
2203
+ contextRows.push({ label: "Task ID", value: `${c.muted}${t.id}${c.reset}` });
2204
+
2205
+ renderBrandHeader({
2206
+ subtitle: `Task ${numStr} · ${cfg?.title || t.projectId}`,
2207
+ contextRows,
2208
+ });
2209
+
2210
+ console.log(RAIL);
2211
+ console.log(`${STEP_ACTIVE} ${c.bold}${c.ink}Description${c.reset}`);
2212
+ if (t.description && t.description.trim()) {
2213
+ for (const line of t.description.trim().split("\n")) {
2214
+ console.log(`${RAIL} ${c.ink}${line}${c.reset}`);
2215
+ }
2216
+ } else {
2217
+ console.log(`${RAIL} ${c.muted}No description provided.${c.reset}`);
2218
+ }
2219
+
2220
+ console.log(RAIL);
2221
+ console.log(
2222
+ `${stSummary.total > 0 && stSummary.completed === stSummary.total ? STEP_DONE : STEP_ACTIVE} ${c.bold}${c.ink}Subtasks (${stSummary.completed}/${stSummary.total} Completed)${c.reset}`,
2223
+ );
2224
+ if (subtasks.length === 0) {
2225
+ console.log(`${RAIL} ${c.muted}No subtasks defined for this task.${c.reset}`);
2226
+ } else {
2227
+ for (let i = 0; i < subtasks.length; i++) {
2228
+ const st = subtasks[i];
2229
+ const idx = st.index || i + 1;
2230
+ const box = st.completed ? `${c.emerald}[x]${c.reset}` : `${c.muted}[ ]${c.reset}`;
2231
+ const textStyle = st.completed ? c.muted : c.ink;
2232
+ console.log(`${RAIL} ${box} ${c.bold}${idx}.${c.reset} ${textStyle}${st.title}${c.reset}`);
2233
+ }
2234
+ }
2235
+
2236
+ console.log(RAIL);
2237
+ console.log(
2238
+ `${files.length > 0 ? STEP_DONE : STEP_ACTIVE} ${c.bold}${c.ink}Attached & Linked Files (${files.length})${c.reset}${
2239
+ hydratedCount > 0 ? ` ${c.muted}— Synced to .networkbase/mirror/${c.reset}` : ""
2240
+ }`,
2241
+ );
2242
+ if (files.length === 0) {
2243
+ console.log(`${RAIL} ${c.muted}No files attached yet. Push with \`nb push <file> --deliverable\` to attach.${c.reset}`);
2244
+ } else {
2245
+ for (const f of files) {
2246
+ const cleanRel = (f.path || f.name || "").replace(/^\/+/, "");
2247
+ const mirrorPath = `.networkbase/mirror/${cleanRel}`;
2248
+ const roleBadge = formatStatusBadge(f.role || "working");
2249
+ console.log(
2250
+ `${RAIL} • ${c.bold}${c.ink}${f.path || f.name}${c.reset} ${c.accent}[v${f.currentVersion || 1}]${c.reset} ${c.muted}(${formatBytes(f.size || 0)})${c.reset} ${roleBadge} ${c.dim}-> ${mirrorPath}${c.reset}`,
2251
+ );
2252
+ if (f.annotation && !f.annotation.startsWith("#")) {
2253
+ console.log(`${RAIL} ${c.muted}Note: "${f.annotation}"${c.reset}`);
2254
+ }
2255
+ }
2256
+ }
2257
+
2258
+ if (comments.length > 0) {
2259
+ console.log(RAIL);
2260
+ console.log(`${STEP_ACTIVE} ${c.bold}${c.ink}Discussion Comments (${comments.length})${c.reset}`);
2261
+ for (const cm of comments.slice(0, 5)) {
2262
+ console.log(
2263
+ `${RAIL} • ${c.bold}${c.ink}${cm.authorUsername ? `@${cm.authorUsername}` : cm.authorName}:${c.reset} ${c.muted}${cm.content.replace(/\s+/g, " ")}${c.reset}`,
2264
+ );
2265
+ }
2266
+ }
2267
+
2268
+ if (pushes.length > 0) {
2269
+ console.log(RAIL);
2270
+ console.log(`${STEP_DONE} ${c.bold}${c.ink}Recent Pushes (${pushes.length})${c.reset}`);
2271
+ for (const p of pushes.slice(0, 4)) {
2272
+ console.log(
2273
+ `${RAIL} • ${c.ink}${p.message || "Update"}${c.reset} ${c.muted}by ${p.pushedByName} (${p.filesCount} file(s))${c.reset}`,
2274
+ );
2275
+ }
2276
+ }
2277
+
2278
+ console.log(
2279
+ `${c.dim}╰─${c.reset} ${c.emerald}✔${c.reset} Run ${c.accent}nb task check${c.reset} to toggle subtasks or edit ${c.accent}.networkbase/mirror/${c.reset} directly.\n`,
2280
+ );
2281
+ }
2282
+
2283
+ async function handleTask(sub, positional, flags) {
2284
+ const cwd = process.cwd();
2285
+ const cfg = getLocalConfig(cwd);
2286
+ const projectId = typeof flags.workspace === "string" ? flags.workspace : cfg.projectId;
2287
+
2288
+ // Support `nb task list --all` / `nb task --all-workspaces` across all accessible workspaces
2289
+ if ((!sub || sub === "list" || sub === "ls") && (flags.all || flags["all-workspaces"])) {
2290
+ const wsData = await withSpinner(
2291
+ "Loading all accessible workspaces & tasks…",
2292
+ () => apiRequest("/api/v1/extension/workspaces"),
2293
+ { silent: Boolean(flags.json) },
2294
+ );
2295
+ const workspaces = wsData?.workspaces || [];
2296
+ const results = await Promise.all(
2297
+ workspaces.map(async (ws) => {
2298
+ try {
2299
+ const td = await apiRequest(
2300
+ `/api/v1/extension/workspace-tasks?projectId=${ws.id}&scope=${flags.mine ? "mine" : "all"}`,
2301
+ );
2302
+ return { workspace: ws, tasks: td?.tasks || [] };
2303
+ } catch {
2304
+ return { workspace: ws, tasks: [] };
2305
+ }
2306
+ }),
2307
+ );
2308
+
2309
+ const totalTasks = results.reduce((acc, r) => acc + r.tasks.length, 0);
2310
+ outputResult({ workspaces: results, totalTasks }, flags, (res) => {
2311
+ renderBrandHeader({
2312
+ subtitle: `All Workspaces Task Overview (${res.totalTasks} total task(s) across ${res.workspaces.length} workspace(s))`,
2313
+ });
2314
+ for (const group of res.workspaces) {
2315
+ if (group.tasks.length === 0) continue;
2316
+ console.log(RAIL);
2317
+ console.log(
2318
+ `${STEP_ACTIVE} ${c.bold}${c.ink}${group.workspace.title}${c.reset} ${c.muted}(${group.workspace.slug || group.workspace.id} · ${group.tasks.length} task(s))${c.reset}`,
2319
+ );
2320
+ for (const t of group.tasks) {
2321
+ const num = t.taskNumber ? `#${t.taskNumber}` : t.id.slice(0, 8);
2322
+ const stSum = t.subtaskSummary || { completed: 0, total: (t.subtasks || []).length };
2323
+ const stBadge = stSum.total > 0 ? ` · ${c.muted}☑ ${stSum.completed}/${stSum.total} subtasks${c.reset}` : "";
2324
+ const fBadge = t.filesCount > 0 ? ` · ${c.muted}📎 ${t.filesCount} file(s)${c.reset}` : "";
2325
+ console.log(
2326
+ `${RAIL} • ${formatStatusBadge(t.status)} ${formatPriorityBadge(t.priority)} ${c.bold}${c.ink}${num}${c.reset} ${c.ink}${t.title}${c.reset}${stBadge}${fBadge}`,
2327
+ );
2328
+ }
2329
+ }
2330
+ console.log(`${c.dim}╰─${c.reset}\n`);
2331
+ });
2332
+ return;
2333
+ }
2334
+
2335
+ if (!projectId) throw new Error("No workspace linked. Run `nb init` first.");
2336
+
2337
+ // Allow shorthand `nb task #4` or `nb task 4` to directly open `nb task view #4`
2338
+ if (sub && (/^#?\d+$/.test(sub) || /^[0-9a-f]{8}-[0-9a-f]{4}-/i.test(sub))) {
2339
+ positional = [sub, ...positional];
2340
+ sub = "view";
2341
+ }
2342
+
2343
+ if (sub === "work") {
2344
+ let rawTarget = positional[0];
2345
+ if (!rawTarget && process.stdin.isTTY && !flags.json) {
2346
+ renderBrandHeader({ subtitle: `Select Active Sprint Task · ${cfg.title || projectId}` });
2347
+ const data = await withSpinner("Loading workspace tasks…", () =>
2348
+ apiRequest(`/api/v1/extension/workspace-tasks?projectId=${projectId}&scope=all`),
2349
+ );
2350
+ const allTasks = data?.tasks || [];
2351
+ writeLocalTaskIntelligence(projectId, cfg.title || projectId, allTasks, cwd);
2352
+ const openTasks = allTasks.filter((t) => t.status !== "done");
2353
+ if (openTasks.length === 0) {
2354
+ console.log(`${RAIL}\n${c.dim}╰─${c.reset} No open tasks found in this workspace.\n`);
2355
+ return;
2356
+ }
2357
+ const chosenTask = await tuiSelect({
2358
+ title: "Choose a task to work on",
2359
+ stepLabel: "Active Task",
2360
+ searchable: openTasks.length > 5,
2361
+ items: openTasks.map((t) => {
2362
+ const num = t.taskNumber ? `#${t.taskNumber} ` : "";
2363
+ const stSum = t.subtaskSummary || { completed: 0, total: (t.subtasks || []).length };
2364
+ const stPart = stSum.total > 0 ? ` · ☑ ${stSum.completed}/${stSum.total} subtasks` : "";
2365
+ const fPart = (t.filesCount || 0) > 0 ? ` · 📎 ${t.filesCount} file(s)` : "";
2366
+ return {
2367
+ label: `${num}${t.title}`,
2368
+ badge: `${formatStatusBadge(t.status)} ${formatPriorityBadge(t.priority)}`,
2369
+ description: `${(t.descriptionPreview || t.description || "No description").replace(/\s+/g, " ").slice(0, 68)}${stPart}${fPart}`,
2370
+ value: t,
2371
+ };
2372
+ }),
2373
+ });
2374
+ if (!chosenTask) return;
2375
+ rawTarget = chosenTask.id;
2376
+ }
2377
+
2378
+ if (!rawTarget) throw new Error("Usage: nb task work <#number-or-task-id>");
2379
+ const resolvedId = resolveTaskIdentifier(rawTarget, cwd);
2380
+ const detail = await withSpinner(
2381
+ "Loading task intelligence & attached files…",
2382
+ () =>
2383
+ apiRequest(
2384
+ `/api/v1/extension/task-detail?projectId=${projectId}&taskId=${encodeURIComponent(resolvedId)}`,
2385
+ ),
2386
+ { silent: Boolean(flags.json) },
2387
+ );
2388
+ const task = detail.task;
2389
+ saveLocalState(
2390
+ {
2391
+ ...getLocalState(cwd),
2392
+ activeTaskId: task.id,
2393
+ activeTaskTitle: task.title,
2394
+ startedAt: new Date().toISOString(),
2395
+ },
2396
+ cwd,
2397
+ );
2398
+ if (task.status === "todo") {
2399
+ await apiRequest("/api/v1/extension/task-update", {
2400
+ method: "PATCH",
2401
+ body: {
2402
+ kind: "status",
2403
+ projectId,
2404
+ taskId: task.id,
2405
+ status: "in_progress",
2406
+ expectedUpdatedAt: new Date(task.updatedAt).toISOString(),
2407
+ },
2408
+ }).catch(() => {});
2409
+ detail.task.status = "in_progress";
2410
+ }
2411
+
2412
+ const hydratedCount = await hydrateTaskAttachedFiles(projectId, detail.files || [], cwd);
2413
+
2414
+ // Refresh local TASKS.md with newly bound activeTaskId
2415
+ const cachedTasks = getLocalCache(cwd)?.tasks || [];
2416
+ if (cachedTasks.length > 0) {
2417
+ writeLocalTaskIntelligence(projectId, cfg.title || projectId, cachedTasks, cwd);
2418
+ }
2419
+
2420
+ outputResult(
2421
+ {
2422
+ activeTaskId: task.id,
2423
+ taskNumber: task.taskNumber,
2424
+ title: task.title,
2425
+ description: task.description,
2426
+ status: detail.task.status,
2427
+ subtasks: detail.subtasks || [],
2428
+ files: detail.files || [],
2429
+ hydratedFilesCount: hydratedCount,
2430
+ },
2431
+ flags,
2432
+ () => {
2433
+ renderTaskDetailCard(detail, cfg, hydratedCount);
2434
+ },
2435
+ );
2436
+ return;
2437
+ }
2438
+
2439
+ if (!sub || sub === "list" || sub === "ls") {
2440
+ const scope = flags.mine ? "mine" : flags.scope || "all";
2441
+ const renderTaskListCard = (tasks, isOffline = false) => {
2442
+ const activeId = getLocalState(cwd)?.activeTaskId;
2443
+ const openCount = tasks.filter((t) => t.status !== "done").length;
2444
+ const doneCount = tasks.filter((t) => t.status === "done").length;
2445
+ const activeTaskObj = tasks.find((t) => t.id === activeId);
2446
+
2447
+ renderBrandHeader({
2448
+ subtitle: `Workspace Tasks · ${cfg.title || projectId} (${openCount} open, ${doneCount} done)${isOffline ? " [Local Mirror]" : ""}`,
2449
+ contextRows: activeTaskObj
2450
+ ? [
2451
+ {
2452
+ label: "Active Task",
2453
+ value: `${c.emerald}●${c.reset} ${c.bold}${c.ink}${
2454
+ activeTaskObj.taskNumber ? `#${activeTaskObj.taskNumber} ` : ""
2455
+ }${activeTaskObj.title}${c.reset}`,
2456
+ },
2457
+ {
2458
+ label: "Local Brief",
2459
+ value: `${c.muted}.networkbase/tasks/TASKS.md (synced)${c.reset}`,
2460
+ },
2461
+ ]
2462
+ : [
2463
+ {
2464
+ label: "Local Brief",
2465
+ value: `${c.muted}.networkbase/tasks/TASKS.md (synced)${c.reset}`,
2466
+ },
2467
+ ],
2468
+ });
2469
+ console.log(RAIL);
2470
+ if (tasks.length === 0) {
2471
+ console.log(`${RAIL} ${c.muted}No tasks found in this workspace.${c.reset}`);
2472
+ }
2473
+ for (const t of tasks) {
2474
+ const num = t.taskNumber ? `#${t.taskNumber}` : t.id.slice(0, 8);
2475
+ const marker = t.id === activeId ? `${c.emerald}●${c.reset}` : `${c.dim}○${c.reset}`;
2476
+ const stSum = t.subtaskSummary || { completed: 0, total: (t.subtasks || []).length };
2477
+ const stInfo =
2478
+ stSum.total > 0
2479
+ ? ` · ${stSum.completed === stSum.total ? c.emerald : c.ink}☑ ${stSum.completed}/${stSum.total} subtasks${c.reset}`
2480
+ : "";
2481
+ const fCount = t.filesCount ?? (t.files || []).length;
2482
+ const fInfo = fCount > 0 ? ` · ${c.accent}📎 ${fCount} attached file(s)${c.reset}` : "";
2483
+ console.log(
2484
+ `${RAIL} ${marker} ${c.bold}${c.ink}${num.padEnd(4)}${c.reset} ${c.bold}${c.ink}${t.title}${c.reset}`,
2485
+ );
2486
+ console.log(
2487
+ `${RAIL} ${formatStatusBadge(t.status)} · ${formatPriorityBadge(t.priority)}${stInfo}${fInfo}`,
2488
+ );
2489
+ if (t.description && t.description.trim()) {
2490
+ const snippet = t.description.trim().replace(/\s+/g, " ").slice(0, 78);
2491
+ console.log(
2492
+ `${RAIL} ${c.muted}"${snippet}${t.description.trim().length > 78 ? "…" : ""}"${c.reset}`,
2493
+ );
2494
+ }
2495
+ if ((t.subtasks || []).length > 0) {
2496
+ for (const st of (t.subtasks || []).slice(0, 4)) {
2497
+ const box = st.completed ? `${c.emerald}[x]${c.reset}` : `${c.muted}[ ]${c.reset}`;
2498
+ console.log(`${RAIL} ${box} ${c.muted}${st.index}. ${st.title}${c.reset}`);
2499
+ }
2500
+ }
2501
+ if ((t.files || []).length > 0) {
2502
+ for (const f of (t.files || []).slice(0, 3)) {
2503
+ const cleanRel = (f.path || f.name || "").replace(/^\/+/, "");
2504
+ console.log(
2505
+ `${RAIL} ${c.accent}📎 ${f.path || f.name}${c.reset} ${c.muted}[v${f.currentVersion || 1}]${c.reset} ${formatStatusBadge(f.role)} ${c.dim}(.networkbase/mirror/${cleanRel})${c.reset}`,
2506
+ );
2507
+ }
2508
+ }
2509
+ console.log(RAIL);
2510
+ }
2511
+ console.log(
2512
+ `${c.dim}╰─${c.reset} Run ${c.accent}nb task <number>${c.reset} (e.g. ${c.accent}nb task 4${c.reset}) to inspect or ${c.accent}nb task work <number>${c.reset} to bind.\n`,
2513
+ );
2514
+ };
2515
+
2516
+ try {
2517
+ const data = await withSpinner(
2518
+ `Loading tasks for ${cfg.title || projectId}…`,
2519
+ () => apiRequest(`/api/v1/extension/workspace-tasks?projectId=${projectId}&scope=${scope}`),
2520
+ { silent: Boolean(flags.json) },
2521
+ );
2522
+ const list = data.tasks || [];
2523
+ writeLocalTaskIntelligence(projectId, cfg.title || projectId, list, cwd);
2524
+
2525
+ const allAttachedFiles = list
2526
+ .filter((t) => t.status !== "done")
2527
+ .flatMap((t) => t.files || []);
2528
+ if (allAttachedFiles.length > 0) {
2529
+ await hydrateTaskAttachedFiles(projectId, allAttachedFiles, cwd);
2530
+ }
2531
+
2532
+ outputResult(data, flags, (res) => renderTaskListCard(res.tasks || [], false));
2533
+ } catch (err) {
2534
+ const snapshot = readJsonSafe(path.join(getLocalTasksDir(cwd), "tasks.json"), null);
2535
+ const cachedTasks = snapshot?.tasks || getLocalCache(cwd)?.tasks || [];
2536
+ if (cachedTasks.length) {
2537
+ outputResult({ tasks: cachedTasks, offlineCache: true }, flags, (res) =>
2538
+ renderTaskListCard(res.tasks || [], true),
2539
+ );
2540
+ return;
2541
+ }
2542
+ throw err;
2543
+ }
2544
+ return;
2545
+ }
2546
+
2547
+ if (sub === "view" || sub === "inspect" || sub === "show") {
2548
+ const rawTarget = positional[0] || inferActiveTaskId(flags, cwd);
2549
+ if (!rawTarget) {
2550
+ throw new Error("Usage: nb task view <#number-or-task-id> (or bind an active task with `nb task work`)");
2551
+ }
2552
+ const resolvedId = resolveTaskIdentifier(rawTarget, cwd);
2553
+ let detail;
2554
+ let hydratedCount = 0;
2555
+ try {
2556
+ detail = await withSpinner(
2557
+ "Loading complete task briefing, subtasks & attached files…",
2558
+ () =>
2559
+ apiRequest(
2560
+ `/api/v1/extension/task-detail?projectId=${projectId}&taskId=${encodeURIComponent(resolvedId)}`,
2561
+ ),
2562
+ { silent: Boolean(flags.json) },
2563
+ );
2564
+ hydratedCount = await hydrateTaskAttachedFiles(projectId, detail.files || [], cwd);
2565
+ } catch (err) {
2566
+ const snapshot = readJsonSafe(path.join(getLocalTasksDir(cwd), "tasks.json"), null);
2567
+ const cachedTasks = snapshot?.tasks || getLocalCache(cwd)?.tasks || [];
2568
+ const matched = cachedTasks.find(
2569
+ (t) => t.id === resolvedId || String(t.taskNumber) === String(resolvedId).replace(/^#/, ""),
2570
+ );
2571
+ if (!matched) throw err;
2572
+ detail = {
2573
+ task: matched,
2574
+ subtasks: matched.subtasks || [],
2575
+ subtaskSummary: matched.subtaskSummary || {
2576
+ completed: (matched.subtasks || []).filter((s) => s.completed).length,
2577
+ total: (matched.subtasks || []).length,
2578
+ },
2579
+ files: matched.files || [],
2580
+ comments: matched.comments || [],
2581
+ pushes: matched.pushes || [],
2582
+ offlineCache: true,
2583
+ };
2584
+ }
2585
+
2586
+ const enrichedDetail = {
2587
+ ...detail,
2588
+ files: (detail.files || []).map((f) => ({
2589
+ ...f,
2590
+ localMirrorPath: `.networkbase/mirror/${(f.path || f.name || "").replace(/^\/+/, "")}`,
2591
+ })),
2592
+ };
2593
+
2594
+ outputResult(enrichedDetail, flags, (res) => {
2595
+ renderTaskDetailCard(res, cfg, hydratedCount);
2596
+ });
2597
+ return;
2598
+ }
2599
+
2600
+ if (sub === "check" || sub === "subtask" || sub === "subtasks") {
2601
+ const rawTaskTarget = flags.task ? String(flags.task) : inferActiveTaskId(flags, cwd);
2602
+ let targetTaskId = rawTaskTarget ? resolveTaskIdentifier(rawTaskTarget, cwd) : null;
2603
+ let targetArgs = [...positional];
2604
+
2605
+ // If first positional arg looks like `#4` and there are more args (e.g., `nb task check #4 1 2`)
2606
+ if (!targetTaskId && targetArgs.length > 0) {
2607
+ targetTaskId = resolveTaskIdentifier(targetArgs.shift(), cwd);
2608
+ } else if (targetArgs.length > 1 && /^#\d+$/.test(targetArgs[0])) {
2609
+ targetTaskId = resolveTaskIdentifier(targetArgs.shift(), cwd);
2610
+ }
2611
+
2612
+ if (!targetTaskId) {
2613
+ throw new Error("No active task bound. Run `nb task work <#number>` or pass `--task <#number>`.");
2614
+ }
2615
+
2616
+ const detail = await apiRequest(
2617
+ `/api/v1/extension/task-detail?projectId=${projectId}&taskId=${encodeURIComponent(targetTaskId)}`,
2618
+ );
2619
+ const task = detail.task;
2620
+ const subtasks = detail.subtasks || [];
2621
+
2622
+ if (subtasks.length === 0) {
2623
+ outputResult({ taskId: task.id, subtasks: [], updatedCount: 0 }, flags, () => {
2624
+ console.log(`${RAIL}\n${c.dim}╰─${c.reset} Task "${task.title}" has no subtasks.\n`);
2625
+ });
2626
+ return;
2627
+ }
2628
+
2629
+ const desiredCompletionById = new Map();
2630
+
2631
+ if (flags.all) {
2632
+ const targetVal = !flags.uncheck;
2633
+ for (const st of subtasks) {
2634
+ if (st.completed !== targetVal) {
2635
+ desiredCompletionById.set(st.id, targetVal);
2636
+ }
2637
+ }
2638
+ } else if (targetArgs.length > 0) {
2639
+ const targetVal = !flags.uncheck;
2640
+ for (const arg of targetArgs) {
2641
+ const cleaned = String(arg).replace(/^#/, "");
2642
+ const matched = subtasks.find(
2643
+ (st, idx) =>
2644
+ st.id === cleaned ||
2645
+ String(st.index || idx + 1) === cleaned ||
2646
+ st.title.toLowerCase().includes(cleaned.toLowerCase()),
2647
+ );
2648
+ if (matched && matched.completed !== targetVal) {
2649
+ desiredCompletionById.set(matched.id, targetVal);
2650
+ }
2651
+ }
2652
+ } else if (process.stdin.isTTY && !flags.json) {
2653
+ renderBrandHeader({
2654
+ subtitle: `Subtasks Checklist · ${task.taskNumber ? `#${task.taskNumber} ` : ""}${task.title}`,
2655
+ });
2656
+ const selectedIds = await tuiMultiSelect({
2657
+ title: "Toggle completed subtasks (Space to toggle, A for all, Enter to save)",
2658
+ stepLabel: "Subtasks",
2659
+ items: subtasks.map((st, idx) => ({
2660
+ label: `${st.index || idx + 1}. ${st.title}`,
2661
+ badge: st.completed ? `${c.emerald}[Completed]${c.reset}` : `${c.muted}[Pending]${c.reset}`,
2662
+ value: st.id,
2663
+ checked: Boolean(st.completed),
2664
+ })),
2665
+ });
2666
+ const selectedSet = new Set(selectedIds);
2667
+ for (const st of subtasks) {
2668
+ const nextVal = selectedSet.has(st.id);
2669
+ if (Boolean(st.completed) !== nextVal) {
2670
+ desiredCompletionById.set(st.id, nextVal);
2671
+ }
2672
+ }
2673
+ } else {
2674
+ throw new Error("Usage: nb task check <subtask-number...> or `nb task check --all`");
2675
+ }
2676
+
2677
+ let updatedCount = 0;
2678
+ for (const st of subtasks) {
2679
+ if (!desiredCompletionById.has(st.id)) continue;
2680
+ const nextCompleted = desiredCompletionById.get(st.id);
2681
+ await apiRequest("/api/v1/extension/task-update", {
2682
+ method: "PATCH",
2683
+ body: {
2684
+ kind: "subtask",
2685
+ projectId,
2686
+ taskId: task.id,
2687
+ subtaskId: st.id,
2688
+ completed: nextCompleted,
2689
+ expectedUpdatedAt: new Date(st.updatedAt).toISOString(),
2690
+ },
2691
+ });
2692
+ st.completed = nextCompleted;
2693
+ updatedCount++;
2694
+ }
2695
+
2696
+ // Refresh local TASKS.md
2697
+ try {
2698
+ const refreshed = await apiRequest(`/api/v1/extension/workspace-tasks?projectId=${projectId}&scope=all`);
2699
+ writeLocalTaskIntelligence(projectId, cfg.title || projectId, refreshed.tasks || [], cwd);
2700
+ } catch {
2701
+ // Non-fatal
2702
+ }
2703
+
2704
+ const completedTotal = subtasks.filter((s) => s.completed).length;
2705
+ outputResult(
2706
+ {
2707
+ taskId: task.id,
2708
+ title: task.title,
2709
+ updatedCount,
2710
+ subtaskSummary: { completed: completedTotal, total: subtasks.length },
2711
+ subtasks,
2712
+ },
2713
+ flags,
2714
+ (res) => {
2715
+ console.log(RAIL);
2716
+ console.log(
2717
+ `${STEP_DONE} ${c.bold}${c.ink}Updated ${res.updatedCount} subtask(s)${c.reset} ${c.muted}(${res.subtaskSummary.completed}/${res.subtaskSummary.total} completed on "${res.title}")${c.reset}`,
2718
+ );
2719
+ for (const st of res.subtasks) {
2720
+ const box = st.completed ? `${c.emerald}[x]${c.reset}` : `${c.muted}[ ]${c.reset}`;
2721
+ console.log(`${RAIL} ${box} ${c.bold}${st.index}.${c.reset} ${c.ink}${st.title}${c.reset}`);
2722
+ }
2723
+ console.log(`${c.dim}╰─${c.reset}\n`);
2724
+ },
2725
+ );
2726
+ return;
2727
+ }
2728
+
2729
+ if (sub === "done") {
2730
+ const rawTarget = positional[0] || inferActiveTaskId(flags, cwd);
2731
+ if (!rawTarget) throw new Error("Usage: nb task done <#number-or-task-id>");
2732
+ const resolvedId = resolveTaskIdentifier(rawTarget, cwd);
2733
+ const detail = await apiRequest(
2734
+ `/api/v1/extension/task-detail?projectId=${projectId}&taskId=${encodeURIComponent(resolvedId)}`,
2735
+ );
2736
+ const task = detail.task;
2737
+ const updated = await apiRequest("/api/v1/extension/task-update", {
2738
+ method: "PATCH",
2739
+ body: {
2740
+ kind: "status",
2741
+ projectId,
2742
+ taskId: task.id,
2743
+ status: "done",
2744
+ expectedUpdatedAt: new Date(task.updatedAt).toISOString(),
2745
+ },
2746
+ });
2747
+ outputResult(updated, flags, () => {
2748
+ console.log(
2749
+ `\n${c.emerald}✔${c.reset} Task ${c.bold}${c.ink}"${task.title}"${c.reset} marked as ${formatStatusBadge("done")}\n`,
2750
+ );
2751
+ });
2752
+ return;
2753
+ }
2754
+
2755
+ if (sub === "status") {
2756
+ let tasks = [];
2757
+ let offlineCache = false;
2758
+ try {
2759
+ const data = await apiRequest(`/api/v1/extension/workspace-tasks?projectId=${projectId}&scope=all`);
2760
+ tasks = data.tasks || [];
2761
+ writeLocalTaskIntelligence(projectId, cfg.title || projectId, tasks, cwd);
2762
+ } catch {
2763
+ const cached = getLocalCache(cwd);
2764
+ tasks = cached.tasks || [];
2765
+ offlineCache = true;
2766
+ }
2767
+ const todoCount = tasks.filter((t) => t.status === "todo").length;
2768
+ const inProgressCount = tasks.filter((t) => t.status === "in_progress").length;
2769
+ const doneCount = tasks.filter((t) => t.status === "done").length;
2770
+ const completionPct = tasks.length > 0 ? Math.round((doneCount / tasks.length) * 100) : 0;
2771
+ outputResult(
2772
+ {
2773
+ projectId,
2774
+ totalTasks: tasks.length,
2775
+ todoCount,
2776
+ inProgressCount,
2777
+ doneCount,
2778
+ completionPct,
2779
+ offlineCache,
2780
+ },
2781
+ flags,
2782
+ (res) => {
2783
+ renderBrandHeader({
2784
+ subtitle: `Sprint & Task Health${res.offlineCache ? " (Offline Cache)" : ""}`,
2785
+ contextRows: [
2786
+ {
2787
+ label: "Completion",
2788
+ value: `${c.bold}${c.emerald}${res.completionPct}%${c.reset} ${c.muted}(${res.totalTasks} total tasks)${c.reset}`,
2789
+ },
2790
+ { label: "In Progress", value: `${c.accent}${res.inProgressCount}${c.reset}` },
2791
+ { label: "Todo", value: `${c.muted}${res.todoCount}${c.reset}` },
2792
+ { label: "Done", value: `${c.emerald}${res.doneCount}${c.reset}` },
2793
+ ],
2794
+ });
2795
+ console.log("");
2796
+ },
2797
+ );
2798
+ return;
2799
+ }
2800
+
2801
+ if (sub === "comment") {
2802
+ const rawTarget = positional[0] || inferActiveTaskId(flags, cwd);
2803
+ const content = flags.message || positional.slice(1).join(" ").trim();
2804
+ if (!rawTarget || !content) {
2805
+ throw new Error("Usage: nb task comment <#number-or-task-id> <message>");
2806
+ }
2807
+ const resolvedId = resolveTaskIdentifier(rawTarget, cwd);
2808
+ const detail = await apiRequest(
2809
+ `/api/v1/extension/task-detail?projectId=${projectId}&taskId=${encodeURIComponent(resolvedId)}`,
2810
+ );
2811
+ const created = await apiRequest("/api/v1/extension/comments", {
2812
+ method: "POST",
2813
+ body: { taskId: detail.task.id, content },
2814
+ });
2815
+ outputResult(created, flags, () => {
2816
+ console.log(`\n${c.emerald}✔${c.reset} Posted comment to task "${detail.task.title}"\n`);
2817
+ });
2818
+ return;
2819
+ }
2820
+
2821
+ throw new Error(`Unknown task subcommand: ${sub}`);
2822
+ }
2823
+
2824
+ async function fetchWorkspaceFiles(projectId, query = "") {
2825
+ const allFiles = [];
2826
+ let cursor = null;
2827
+ for (let page = 0; page < 5; page++) {
2828
+ const qs = new URLSearchParams({
2829
+ projectId,
2830
+ q: query,
2831
+ kind: "file",
2832
+ });
2833
+ if (cursor) qs.set("after", cursor);
2834
+ const res = await apiRequest(`/api/v1/extension/search?${qs.toString()}`);
2835
+ const pageFiles = res?.files || [];
2836
+ allFiles.push(...pageFiles);
2837
+ if (!res?.nextCursor || pageFiles.length === 0) break;
2838
+ cursor = res.nextCursor;
2839
+ }
2840
+ return allFiles;
2841
+ }
2842
+
2843
+ async function downloadRemoteFileBuffer(projectId, remotePath, options = {}) {
2844
+ const normPath = remotePath.startsWith("/") ? remotePath : `/${remotePath}`;
2845
+ const headers = {};
2846
+ if (options.ifNoneMatch) {
2847
+ headers["If-None-Match"] = `"${options.ifNoneMatch}"`;
2848
+ }
2849
+ const fileRes = await apiRequest(
2850
+ `/api/v1/extension/file?projectId=${projectId}&path=${encodeURIComponent(normPath)}&transfer=inline`,
2851
+ { headers },
2852
+ );
2853
+ if (fileRes?.notModified) {
2854
+ return { notModified: true, buffer: null, meta: fileRes };
2855
+ }
2856
+ if (fileRes?.content !== undefined) {
2857
+ const buf =
2858
+ fileRes.encoding === "base64"
2859
+ ? Buffer.from(fileRes.content || "", "base64")
2860
+ : Buffer.from(fileRes.content || "", "utf8");
2861
+ return { buffer: buf, meta: fileRes };
2862
+ }
2863
+ if (fileRes?.signedUrl) {
2864
+ const creds = getCredentials();
2865
+ const rawRes = await fetch(fileRes.signedUrl, {
2866
+ headers: creds?.token ? { Authorization: `Bearer ${creds.token}` } : {},
2867
+ });
2868
+ if (!rawRes.ok) throw new Error(`Failed to download ${normPath}: HTTP ${rawRes.status}`);
2869
+ const arr = await rawRes.arrayBuffer();
2870
+ return { buffer: Buffer.from(arr), meta: fileRes };
2871
+ }
2872
+ throw new Error(`Unable to read remote file content for ${normPath}`);
2873
+ }
2874
+
2875
+ async function handleFile(sub, positional, flags) {
2876
+ const cfg = getLocalConfig();
2877
+ const projectId = flags.workspace || cfg.projectId;
2878
+ if (!projectId) throw new Error("No workspace linked. Run `nb init` first.");
2879
+
2880
+ if (sub === "ls" || !sub) {
2881
+ const filterQuery = positional[0] || "";
2882
+ const nodes = await withSpinner(
2883
+ "Loading remote workspace file tree…",
2884
+ () => fetchWorkspaceFiles(projectId, filterQuery),
2885
+ { silent: Boolean(flags.json) },
2886
+ );
2887
+ outputResult({ files: nodes }, flags, (res) => {
2888
+ renderBrandHeader({ subtitle: `Workspace Files · ${cfg.title || projectId} (${res.files.length})` });
2889
+ console.log(RAIL);
2890
+ for (const f of res.files) {
2891
+ console.log(
2892
+ `${RAIL} ${c.ink}${f.path}${c.reset} ${c.accent}[v${f.currentVersion || 1}]${c.reset} ${c.muted}(${formatBytes(f.size || 0)})${c.reset}`,
2893
+ );
2894
+ }
2895
+ console.log(`${c.dim}╰─${c.reset}\n`);
2896
+ });
2897
+ return;
2898
+ }
2899
+
2900
+ if (sub === "cat" || sub === "view" || sub === "read") {
2901
+ const targetPath = positional[0];
2902
+ if (!targetPath) throw new Error("Usage: nb file cat <path>");
2903
+ const normPath = targetPath.startsWith("/") ? targetPath : `/${targetPath}`;
2904
+ const { buffer, meta } = await withSpinner(
2905
+ `Reading ${normPath} from NetworkBase…`,
2906
+ () => downloadRemoteFileBuffer(projectId, normPath),
2907
+ { silent: Boolean(flags.json) },
2908
+ );
2909
+ const text = buffer.toString("utf8");
2910
+ outputResult(
2911
+ {
2912
+ path: normPath,
2913
+ nodeId: meta.nodeId,
2914
+ currentVersion: meta.currentVersion,
2915
+ contentHash: meta.contentHash,
2916
+ size: meta.size,
2917
+ content: text,
2918
+ },
2919
+ flags,
2920
+ () => {
2921
+ renderBrandHeader({
2922
+ subtitle: `${normPath} · v${meta.currentVersion || 1} (${formatBytes(meta.size || buffer.length)})`,
2923
+ });
2924
+ console.log(text);
2925
+ },
2926
+ );
2927
+ return;
2928
+ }
2929
+
2930
+ if (sub === "log") {
2931
+ const targetPath = positional[0];
2932
+ if (!targetPath) throw new Error("Usage: nb file log <path>");
2933
+ const normPath = targetPath.startsWith("/") ? targetPath : `/${targetPath}`;
2934
+ const meta = await apiRequest(
2935
+ `/api/v1/extension/file?projectId=${projectId}&path=${encodeURIComponent(normPath)}&transfer=metadata`,
2936
+ );
2937
+ if (!meta?.nodeId) throw new Error(`File not found in workspace: ${targetPath}`);
2938
+ const history = await apiRequest(
2939
+ `/api/v1/extension/file-history?projectId=${projectId}&nodeId=${meta.nodeId}`,
2940
+ );
2941
+ outputResult({ path: meta.path, nodeId: meta.nodeId, versions: history.versions || [] }, flags, (res) => {
2942
+ renderBrandHeader({ subtitle: `Version History · ${res.path}` });
2943
+ console.log(RAIL);
2944
+ for (const v of res.versions) {
2945
+ console.log(
2946
+ `${RAIL} ${c.accent}v${v.version}${c.reset} · ${c.muted}${v.contentHash?.slice(0, 8) || "no-hash"}${c.reset} · ${c.dim}${v.createdAt}${c.reset} · ${c.ink}${v.comment || "Update"}${c.reset}`,
2947
+ );
2948
+ }
2949
+ console.log(`${c.dim}╰─${c.reset}\n`);
2950
+ });
2951
+ return;
2952
+ }
2953
+
2954
+ if (sub === "diff") {
2955
+ const { analysis } = await withSpinner(
2956
+ "Comparing local files with remote workspace…",
2957
+ () => executePrePushAnalysis(positional, flags),
2958
+ { silent: Boolean(flags.json) },
2959
+ );
2960
+ outputResult(analysis, flags, (res) => {
2961
+ renderBrandHeader({
2962
+ subtitle: `Diff vs Remote (${res.summary.newCount} new, ${res.summary.modifiedCount} modified, ${res.summary.unchangedCount} unchanged)`,
2963
+ });
2964
+ console.log(RAIL);
2965
+ for (const f of res.files) {
2966
+ const badge =
2967
+ f.status === "new"
2968
+ ? `${c.emerald}NEW ${c.reset}`
2969
+ : f.status === "modified"
2970
+ ? `${c.amber}MODIFIED ${c.reset}`
2971
+ : `${c.dim}UNCHANGED${c.reset}`;
2972
+ console.log(`${RAIL} ${badge} ${c.ink}${f.path}${c.reset} ${c.accent}(${f.versionTransition})${c.reset}`);
2973
+ }
2974
+ console.log(`${c.dim}╰─${c.reset}\n`);
2975
+ });
2976
+ return;
2977
+ }
2978
+
2979
+ if (sub === "lock" || sub === "unlock") {
2980
+ const targetPath = positional[0];
2981
+ if (!targetPath) throw new Error(`Usage: nb file ${sub} <path>`);
2982
+ const creds = getCredentials();
2983
+ const state = getLocalState();
2984
+ const locks = state.locks || {};
2985
+ const normPath = targetPath.startsWith("/") ? targetPath : `/${targetPath}`;
2986
+
2987
+ if (sub === "lock") {
2988
+ const lease = await apiRequest("/api/v1/extension/file-lock", {
2989
+ method: "POST",
2990
+ body: {
2991
+ action: "acquire",
2992
+ projectId,
2993
+ path: normPath,
2994
+ clientSessionId: creds.clientSessionId,
2995
+ clientKind: "cli",
2996
+ createIfMissing: true,
2997
+ },
2998
+ });
2999
+ locks[normPath] = lease;
3000
+ saveLocalState({ ...state, locks });
3001
+ outputResult(lease, flags, (res) => {
3002
+ console.log(`🔒 Locked ${normPath} (lease: ${res.leaseId}, fencingToken: ${res.fencingToken})`);
3003
+ });
3004
+ } else {
3005
+ const existingLease = locks[normPath];
3006
+ if (!existingLease) throw new Error(`No active local lock recorded for ${normPath}`);
3007
+ await apiRequest("/api/v1/extension/file-lock", {
3008
+ method: "POST",
3009
+ body: {
3010
+ action: "release",
3011
+ projectId,
3012
+ path: normPath,
3013
+ clientSessionId: creds.clientSessionId,
3014
+ leaseId: existingLease.leaseId,
3015
+ fencingToken: existingLease.fencingToken,
3016
+ },
3017
+ });
3018
+ delete locks[normPath];
3019
+ saveLocalState({ ...state, locks });
3020
+ outputResult({ released: true, path: normPath }, flags, () => {
3021
+ console.log(`🔓 Released lock on ${normPath}`);
3022
+ });
3023
+ }
3024
+ return;
3025
+ }
3026
+
3027
+ throw new Error(`Unknown file subcommand: ${sub}`);
3028
+ }
3029
+
3030
+ function prepareLocalFilesForPush(targetPaths, flags, cwd = process.cwd()) {
3031
+ const cfg = getLocalConfig(cwd);
3032
+ const projectId = flags.workspace || cfg.projectId;
3033
+ if (!projectId) {
3034
+ throw new Error("No workspace linked in this directory. Run `nb init` first.");
3035
+ }
3036
+
3037
+ const localFiles = collectLocalFiles(targetPaths, cwd, flags.scope);
3038
+ if (localFiles.length === 0) {
3039
+ throw new Error("No local files found to analyze or push.");
3040
+ }
3041
+
3042
+ const secretViolations = [];
3043
+ const explicitRemotePath =
3044
+ typeof flags["remote-path"] === "string" && localFiles.length === 1
3045
+ ? flags["remote-path"].startsWith("/")
3046
+ ? flags["remote-path"]
3047
+ : `/${flags["remote-path"]}`
3048
+ : null;
3049
+
3050
+ const manifest = getLocalManifest(cwd);
3051
+ const manifestMap = manifest.projectId === projectId && manifest.files ? manifest.files : {};
3052
+
3053
+ const allPrepared = localFiles.map((item) => {
3054
+ const { hash, size, buffer } = computeFileSha256(item.absPath);
3055
+ const violation = scanFileForSecrets(item.relativePath, buffer);
3056
+ if (violation) {
3057
+ secretViolations.push({ path: item.relativePath, reason: violation });
3058
+ }
3059
+ const targetRemotePath =
3060
+ explicitRemotePath ||
3061
+ (item.relativePath.startsWith("/") ? item.relativePath : `/${item.relativePath}`);
3062
+ const manifestEntry = manifestMap[targetRemotePath] || null;
3063
+ const matchesLocalManifest =
3064
+ manifestEntry &&
3065
+ manifestEntry.contentHash &&
3066
+ manifestEntry.contentHash.toLowerCase() === hash.toLowerCase();
3067
+
3068
+ return {
3069
+ absPath: item.absPath,
3070
+ path: targetRemotePath,
3071
+ relativePath: item.relativePath,
3072
+ contentHash: hash,
3073
+ size,
3074
+ mimeType: detectMimeType(targetRemotePath),
3075
+ buffer,
3076
+ manifestEntry,
3077
+ matchesLocalManifest: Boolean(matchesLocalManifest),
3078
+ fromMirror: Boolean(item.fromMirror),
3079
+ };
3080
+ });
3081
+
3082
+ // Deduplicate by path (preferring .networkbase/mirror/ entries when present)
3083
+ const dedupedByPath = new Map();
3084
+ for (const item of allPrepared) {
3085
+ const prev = dedupedByPath.get(item.path);
3086
+ if (!prev || (item.fromMirror && !prev.fromMirror)) {
3087
+ dedupedByPath.set(item.path, item);
3088
+ }
3089
+ }
3090
+ const uniquePrepared = Array.from(dedupedByPath.values());
3091
+
3092
+ // When scanning without explicit paths, if .networkbase/mirror/ has tracked files, scope default push to mirror/manifest files
3093
+ let preparedFiles = uniquePrepared;
3094
+ let skippedByLocalManifestCount = 0;
3095
+ if (targetPaths.length === 0 && !flags.all && Object.keys(manifestMap).length > 0) {
3096
+ const mirrorOrTracked = uniquePrepared.filter((f) => f.fromMirror || Boolean(f.manifestEntry));
3097
+ const candidatePool = mirrorOrTracked.length > 0 ? mirrorOrTracked : uniquePrepared;
3098
+ const locallyChanged = candidatePool.filter((f) => !f.matchesLocalManifest);
3099
+ if (locallyChanged.length > 0) {
3100
+ skippedByLocalManifestCount = candidatePool.length - locallyChanged.length;
3101
+ preparedFiles = locallyChanged;
3102
+ } else {
3103
+ preparedFiles = candidatePool;
3104
+ }
3105
+ }
3106
+
3107
+ const taskId = inferActiveTaskId(flags, cwd);
3108
+ return {
3109
+ projectId,
3110
+ taskId,
3111
+ preparedFiles,
3112
+ allPreparedCount: preparedFiles.length + skippedByLocalManifestCount,
3113
+ skippedByLocalManifestCount,
3114
+ secretViolations,
3115
+ };
3116
+ }
3117
+
3118
+ async function executePrePushAnalysis(targetPaths, flags, cwd = process.cwd()) {
3119
+ const {
3120
+ projectId,
3121
+ taskId,
3122
+ preparedFiles,
3123
+ allPreparedCount,
3124
+ skippedByLocalManifestCount,
3125
+ secretViolations,
3126
+ } = prepareLocalFilesForPush(targetPaths, flags, cwd);
3127
+
3128
+ const analysis = await apiRequest("/api/v1/extension/pre-push", {
3129
+ method: "POST",
3130
+ body: {
3131
+ projectId,
3132
+ taskId,
3133
+ files: preparedFiles.slice(0, 200).map((f) => ({
3134
+ path: f.path,
3135
+ contentHash: f.contentHash,
3136
+ size: f.size,
3137
+ })),
3138
+ },
3139
+ });
3140
+
3141
+ // Sync unchanged remote versions into local manifest cache
3142
+ if (analysis?.files?.length) {
3143
+ const unchangedRemote = analysis.files
3144
+ .filter((f) => f.status === "unchanged" && f.nodeId)
3145
+ .map((f) => {
3146
+ const local = preparedFiles.find((p) => p.path === f.path);
3147
+ return {
3148
+ path: f.path,
3149
+ nodeId: f.nodeId,
3150
+ version: f.currentVersion,
3151
+ contentHash: local?.contentHash,
3152
+ size: local?.size,
3153
+ };
3154
+ });
3155
+ if (unchangedRemote.length > 0) {
3156
+ updateManifestFiles(projectId, unchangedRemote, cwd);
3157
+ }
3158
+ }
3159
+
3160
+ return {
3161
+ projectId,
3162
+ taskId,
3163
+ preparedFiles,
3164
+ allPreparedCount,
3165
+ skippedByLocalManifestCount,
3166
+ secretViolations,
3167
+ analysis,
3168
+ };
3169
+ }
3170
+
3171
+ const FAST_PUSH_INLINE_LIMIT_BYTES = 4 * 1024 * 1024; // 4 MiB
3172
+
3173
+ async function executeFastPushRequest({
3174
+ projectId,
3175
+ taskId,
3176
+ selectedRole,
3177
+ transitionStatus,
3178
+ commitMessage,
3179
+ filesToPush,
3180
+ cwd = process.cwd(),
3181
+ }) {
3182
+ const fastRes = await apiRequest("/api/v1/extension/fast-push", {
3183
+ method: "POST",
3184
+ headers: {
3185
+ "Idempotency-Key": crypto.randomUUID(),
3186
+ },
3187
+ body: {
3188
+ projectId,
3189
+ taskId: taskId || null,
3190
+ role: selectedRole || "working",
3191
+ transitionStatus: transitionStatus || null,
3192
+ message: commitMessage,
3193
+ files: filesToPush.map((f) => ({
3194
+ path: f.path,
3195
+ contentHash: f.contentHash,
3196
+ size: f.size,
3197
+ mimeType: f.mimeType,
3198
+ contentBase64: f.buffer.toString("base64"),
3199
+ comment: commitMessage,
3200
+ })),
3201
+ },
3202
+ });
3203
+
3204
+ if (fastRes?.files?.length) {
3205
+ updateManifestFiles(projectId, fastRes.files, cwd);
3206
+ }
3207
+ return fastRes;
3208
+ }
3209
+
3210
+ async function handlePush(positional, flags, { skipHeader = false } = {}) {
3211
+ const cfg = getLocalConfig();
3212
+ if (!flags.json && !skipHeader && !flags["dry-run"]) {
3213
+ renderBrandHeader({
3214
+ subtitle: `High-EQ Smart Push · ${cfg.title || flags.workspace || "Workspace"}`,
3215
+ });
3216
+ }
3217
+
3218
+ const explicitRole = resolveRoleFromFlags(flags);
3219
+ const transitionFromFlags = flags.done ? "done" : flags.wip ? "in_progress" : undefined;
3220
+
3221
+ // ULTRA-FAST 1-ROUND-TRIP PATH:
3222
+ // When role is already specified (e.g. --deliverable / --draft / --reference / --json) and not dry-run,
3223
+ // skip /pre-push completely and execute atomic /fast-push in 1 single HTTP round-trip!
3224
+ if (!flags["dry-run"] && (explicitRole || flags.json || !process.stdin.isTTY)) {
3225
+ const {
3226
+ projectId,
3227
+ taskId,
3228
+ preparedFiles,
3229
+ allPreparedCount,
3230
+ skippedByLocalManifestCount,
3231
+ secretViolations,
3232
+ } = prepareLocalFilesForPush(positional, flags);
3233
+
3234
+ if (secretViolations.length > 0 && !flags["allow-secrets"]) {
3235
+ const errPayload = {
3236
+ blockedBySecretGuard: true,
3237
+ violations: secretViolations,
3238
+ hint: "Remove the secrets or add them to .gitignore before pushing.",
3239
+ };
3240
+ outputResult(errPayload, flags, () => {
3241
+ console.error(`\n${STEP_ERR} ${c.red}Pre-Push Secret Guard blocked this push:${c.reset}`);
3242
+ for (const v of secretViolations) {
3243
+ console.error(` - ${v.path}: ${v.reason}`);
3244
+ }
3245
+ });
3246
+ process.exitCode = 1;
3247
+ return;
3248
+ }
3249
+
3250
+ if (
3251
+ preparedFiles.length > 0 &&
3252
+ preparedFiles.every((f) => f.matchesLocalManifest) &&
3253
+ !flags.force &&
3254
+ !taskId &&
3255
+ !transitionFromFlags
3256
+ ) {
3257
+ const cachedPayload = {
3258
+ pushed: false,
3259
+ fastPath: true,
3260
+ cachedByManifest: true,
3261
+ uploadedCount: 0,
3262
+ unchangedCount: allPreparedCount,
3263
+ files: preparedFiles.map((f) => ({
3264
+ path: f.path,
3265
+ nodeId: f.manifestEntry?.nodeId || null,
3266
+ status: "unchanged",
3267
+ previousVersion: f.manifestEntry?.version || 1,
3268
+ version: f.manifestEntry?.version || 1,
3269
+ versionTransition: `v${f.manifestEntry?.version || 1} (unchanged · 0ms local cache)`,
3270
+ contentHash: f.contentHash,
3271
+ size: f.size,
3272
+ })),
3273
+ };
3274
+ outputResult(cachedPayload, flags, (res) => {
3275
+ console.log(RAIL);
3276
+ console.log(
3277
+ `${STEP_DONE} ${c.bold}${c.ink}All ${res.unchangedCount} file(s) already up to date${c.reset} ${c.muted}(0ms local SHA-256 manifest cache)${c.reset}`,
3278
+ );
3279
+ for (const f of res.files) {
3280
+ console.log(`${RAIL} ${c.dim}•${c.reset} ${c.ink}${f.path}${c.reset} -> ${c.accent}${f.versionTransition}${c.reset}`);
3281
+ }
3282
+ console.log(`${c.dim}╰─${c.reset} ${STEP_DONE} Sync complete.\n`);
3283
+ });
3284
+ return cachedPayload;
3285
+ }
3286
+
3287
+ const totalBytes = preparedFiles.reduce((acc, f) => acc + f.size, 0);
3288
+ const selectedRole = explicitRole || "working";
3289
+ const commitMessage =
3290
+ typeof flags.message === "string"
3291
+ ? flags.message
3292
+ : `Pushed via NetworkBase CLI (${selectedRole} update)`;
3293
+
3294
+ if (preparedFiles.length <= 50 && totalBytes <= FAST_PUSH_INLINE_LIMIT_BYTES) {
3295
+ const fastPayload = await withSpinner(
3296
+ `Fast-pushing ${preparedFiles.length} file(s) to NetworkBase…`,
3297
+ () =>
3298
+ executeFastPushRequest({
3299
+ projectId,
3300
+ taskId,
3301
+ selectedRole,
3302
+ transitionStatus: transitionFromFlags,
3303
+ commitMessage,
3304
+ filesToPush: preparedFiles,
3305
+ }),
3306
+ { silent: Boolean(flags.json) },
3307
+ );
3308
+
3309
+ const finalFast = {
3310
+ ...fastPayload,
3311
+ unchangedCount: (fastPayload.unchangedCount || 0) + skippedByLocalManifestCount,
3312
+ };
3313
+
3314
+ outputResult(finalFast, flags, (res) => {
3315
+ console.log(RAIL);
3316
+ console.log(
3317
+ `${STEP_DONE} ${c.bold}${c.ink}Pushed ${res.uploadedCount} changed file(s)${c.reset} ${c.muted}(${res.unchangedCount} unchanged · 1-RTT fast-path)${c.reset} ${
3318
+ res.role ? formatStatusBadge(res.role) : ""
3319
+ }`,
3320
+ );
3321
+ for (const f of res.files || []) {
3322
+ if (f.status !== "unchanged" || res.files.length <= 8) {
3323
+ console.log(`${RAIL} • ${c.ink}${f.path}${c.reset} ${c.accent}-> ${f.versionTransition}${c.reset}`);
3324
+ }
3325
+ }
3326
+ if (res.taskPushReceipt) {
3327
+ console.log(
3328
+ `${c.dim}╰─${c.reset} ${c.emerald}✔${c.reset} Linked to Task ${c.muted}(${res.taskId})${c.reset} · Commit ${c.accent}${res.taskPushReceipt.commitSha?.slice(0, 10) || res.taskPushReceipt.pushId}${c.reset}\n`,
3329
+ );
3330
+ } else {
3331
+ console.log(`${c.dim}╰─${c.reset} ${c.emerald}✔${c.reset} Sync complete.\n`);
3332
+ }
3333
+ });
3334
+ return finalFast;
3335
+ }
3336
+ }
3337
+
3338
+ const {
3339
+ projectId,
3340
+ taskId,
3341
+ preparedFiles,
3342
+ skippedByLocalManifestCount,
3343
+ secretViolations,
3344
+ analysis,
3345
+ } = await withSpinner(
3346
+ "Analyzing local files & SHA-256 manifest…",
3347
+ () => executePrePushAnalysis(positional, flags),
3348
+ { silent: Boolean(flags.json) },
3349
+ );
3350
+
3351
+ if (secretViolations.length > 0 && !flags["allow-secrets"]) {
3352
+ const errPayload = {
3353
+ blockedBySecretGuard: true,
3354
+ violations: secretViolations,
3355
+ hint: "Remove the secrets or add them to .gitignore before pushing.",
3356
+ };
3357
+ outputResult(errPayload, flags, () => {
3358
+ console.error(`\n${STEP_ERR} ${c.red}Pre-Push Secret Guard blocked this push:${c.reset}`);
3359
+ for (const v of secretViolations) {
3360
+ console.error(` - ${v.path}: ${v.reason}`);
3361
+ }
3362
+ });
3363
+ process.exitCode = 1;
3364
+ return;
3365
+ }
3366
+
3367
+ if (flags["dry-run"]) {
3368
+ outputResult(
3369
+ {
3370
+ dryRun: true,
3371
+ ...analysis,
3372
+ },
3373
+ flags,
3374
+ (res) => {
3375
+ renderBrandHeader({ subtitle: `Pre-Push Analysis (${res.summary.totalFiles} file(s))` });
3376
+ console.log(RAIL);
3377
+ if (res.task) {
3378
+ console.log(
3379
+ `${RAIL} Linked Task: ${c.bold}${c.ink}${res.task.taskNumber ? `#${res.task.taskNumber} ` : ""}${res.task.title}${c.reset} ${formatStatusBadge(res.task.status)}`,
3380
+ );
3381
+ }
3382
+ for (const f of res.files) {
3383
+ const lockNote = f.lockedByTeammate ? ` ${c.red}⚠ LOCKED by ${f.lockedByTeammate.name}${c.reset}` : "";
3384
+ console.log(
3385
+ `${RAIL} ${f.status.toUpperCase().padEnd(9)} ${c.ink}${f.path}${c.reset} ${c.accent}(${f.versionTransition})${c.reset}${lockNote}`,
3386
+ );
3387
+ }
3388
+ console.log(`${RAIL}\n${RAIL} ${c.muted}Delivery Intent Options:${c.reset}`);
3389
+ console.log(`${RAIL} --deliverable ${formatStatusBadge("deliverable")}`);
3390
+ console.log(`${RAIL} --draft ${formatStatusBadge("working")}`);
3391
+ console.log(`${RAIL} --reference ${formatStatusBadge("reference")}`);
3392
+ console.log(`${c.dim}╰─${c.reset}\n`);
3393
+ },
3394
+ );
3395
+ return;
3396
+ }
3397
+
3398
+ if (!analysis.summary.canPushCleanly) {
3399
+ const locked = analysis.files.filter((f) => f.lockedByTeammate);
3400
+ throw new Error(
3401
+ `Cannot push: ${locked.map((l) => `${l.path} is locked by ${l.lockedByTeammate.name}`).join(", ")}`,
3402
+ );
3403
+ }
3404
+
3405
+ const changedAnalysisFiles = analysis.files.filter((f) => f.status !== "unchanged");
3406
+ let selectedPathsSet = new Set(changedAnalysisFiles.map((f) => f.path));
3407
+
3408
+ let selectedRole = explicitRole;
3409
+
3410
+ // Interactive Multi-File Selection & Role Classification when running in a terminal without flags
3411
+ if (process.stdin.isTTY && !flags.json && !selectedRole) {
3412
+ if (changedAnalysisFiles.length > 1) {
3413
+ const chosenPaths = await tuiMultiSelect({
3414
+ title: "Select changed files to include in this push",
3415
+ stepLabel: "Files Selected",
3416
+ items: changedAnalysisFiles.map((f) => {
3417
+ const prep = preparedFiles.find((p) => p.path === f.path);
3418
+ const statusTag =
3419
+ f.status === "new"
3420
+ ? `${c.emerald}NEW${c.reset}`
3421
+ : `${c.amber}MODIFIED${c.reset}`;
3422
+ return {
3423
+ label: f.path,
3424
+ badge: `${statusTag} ${c.accent}(${f.versionTransition})${c.reset}`,
3425
+ hint: prep ? formatBytes(prep.size) : "",
3426
+ value: f.path,
3427
+ };
3428
+ }),
3429
+ });
3430
+ selectedPathsSet = new Set(chosenPaths);
3431
+ } else if (changedAnalysisFiles.length === 1) {
3432
+ const single = changedAnalysisFiles[0];
3433
+ printStepDone("File to Push", `${single.path} (${single.versionTransition})`);
3434
+ } else {
3435
+ printStepDone("Files", `All ${analysis.files.length} file(s) already match remote SHA-256`);
3436
+ }
3437
+
3438
+ const taskContextLabel = analysis.task
3439
+ ? `for Task ${analysis.task.taskNumber ? `#${analysis.task.taskNumber}` : analysis.task.title}`
3440
+ : "for this Workspace push";
3441
+
3442
+ selectedRole = await tuiSelect({
3443
+ title: `How should NetworkBase classify this delivery ${taskContextLabel}?`,
3444
+ stepLabel: "Delivery Role",
3445
+ items: [
3446
+ {
3447
+ label: "Final Deliverable",
3448
+ summaryLabel: "Final Deliverable [Final file]",
3449
+ badge: formatStatusBadge("deliverable"),
3450
+ description: "Production-ready output · promotes file badge to Final file (#deliverable)",
3451
+ value: "deliverable",
3452
+ },
3453
+ {
3454
+ label: "Working Draft",
3455
+ summaryLabel: "Working Draft [Draft file]",
3456
+ badge: formatStatusBadge("working"),
3457
+ description: "Work-in-progress checkpoint · keeps task In Progress (#editor_working)",
3458
+ value: "working",
3459
+ },
3460
+ {
3461
+ label: "Reference Material",
3462
+ summaryLabel: "Reference Material [Reference]",
3463
+ badge: formatStatusBadge("reference"),
3464
+ description: "Architecture specification, benchmark, or reference doc (#reference)",
3465
+ value: "reference",
3466
+ },
3467
+ ],
3468
+ });
3469
+ } else if (!selectedRole) {
3470
+ selectedRole = "working";
3471
+ }
3472
+
3473
+ const filesToUpload = preparedFiles.filter((f) => selectedPathsSet.has(f.path));
3474
+
3475
+ let transitionStatus = transitionFromFlags;
3476
+ if (
3477
+ taskId &&
3478
+ selectedRole === "deliverable" &&
3479
+ !transitionStatus &&
3480
+ process.stdin.isTTY &&
3481
+ !flags.json
3482
+ ) {
3483
+ const taskTitle = analysis.task?.title || taskId;
3484
+ const markDone = await tuiConfirm({
3485
+ title: `Mark linked task ("${taskTitle}") as Done?`,
3486
+ stepLabel: "Task Status",
3487
+ yesLabel: "Yes, mark Done",
3488
+ noLabel: "No, keep In Progress",
3489
+ initialValue: false,
3490
+ });
3491
+ if (markDone) {
3492
+ transitionStatus = "done";
3493
+ }
3494
+ }
3495
+
3496
+ const commitMessage =
3497
+ typeof flags.message === "string"
3498
+ ? flags.message
3499
+ : `Pushed via NetworkBase CLI (${selectedRole || "workspace"} update)`;
3500
+
3501
+ const totalUploadBytes = filesToUpload.reduce((acc, f) => acc + f.size, 0);
3502
+
3503
+ // Use atomic 1-call /fast-push after interactive selection when payload <= 4 MiB
3504
+ if (filesToUpload.length <= 50 && totalUploadBytes <= FAST_PUSH_INLINE_LIMIT_BYTES) {
3505
+ const filesForFastPush = filesToUpload.length > 0 ? filesToUpload : preparedFiles.slice(0, 50);
3506
+ const fastPayload = await withSpinner(
3507
+ `Committing ${filesToUpload.length} file(s) to NetworkBase…`,
3508
+ () =>
3509
+ executeFastPushRequest({
3510
+ projectId,
3511
+ taskId,
3512
+ selectedRole,
3513
+ transitionStatus,
3514
+ commitMessage,
3515
+ filesToPush: filesForFastPush,
3516
+ }),
3517
+ { silent: Boolean(flags.json) },
3518
+ );
3519
+
3520
+ const finalFast = {
3521
+ ...fastPayload,
3522
+ unchangedCount:
3523
+ (fastPayload.unchangedCount || 0) +
3524
+ skippedByLocalManifestCount +
3525
+ Math.max(0, preparedFiles.length - filesForFastPush.length),
3526
+ };
3527
+
3528
+ outputResult(finalFast, flags, (res) => {
3529
+ console.log(RAIL);
3530
+ console.log(
3531
+ `${STEP_DONE} ${c.bold}${c.ink}Pushed ${res.uploadedCount} changed file(s)${c.reset} ${c.muted}(${res.unchangedCount} unchanged)${c.reset} ${
3532
+ res.role ? formatStatusBadge(res.role) : ""
3533
+ }`,
3534
+ );
3535
+ for (const f of res.files || []) {
3536
+ if (f.status !== "unchanged" || res.files.length <= 8) {
3537
+ console.log(`${RAIL} • ${c.ink}${f.path}${c.reset} ${c.accent}-> ${f.versionTransition}${c.reset}`);
3538
+ }
3539
+ }
3540
+ if (res.taskPushReceipt) {
3541
+ console.log(
3542
+ `${c.dim}╰─${c.reset} ${c.emerald}✔${c.reset} Linked to Task ${c.muted}(${res.taskId})${c.reset} · Commit ${c.accent}${res.taskPushReceipt.commitSha?.slice(0, 10) || res.taskPushReceipt.pushId}${c.reset}\n`,
3543
+ );
3544
+ } else {
3545
+ console.log(`${c.dim}╰─${c.reset} ${c.emerald}✔${c.reset} Sync complete.\n`);
3546
+ }
3547
+ });
3548
+ return finalFast;
3549
+ }
3550
+
3551
+ // Fallback for large binary batches (> 4 MiB): parallel signed upload + parallel finalize
3552
+ const creds = getCredentials();
3553
+ const finalizedMap = new Map();
3554
+
3555
+ if (filesToUpload.length > 0) {
3556
+ await withSpinner(
3557
+ `Uploading & finalizing ${filesToUpload.length} large file(s) to NetworkBase…`,
3558
+ async () => {
3559
+ for (let i = 0; i < filesToUpload.length; i += 50) {
3560
+ const batch = filesToUpload.slice(i, i + 50);
3561
+ const intentRes = await apiRequest("/api/v1/extension/bulk-intent", {
3562
+ method: "POST",
3563
+ body: {
3564
+ projectId,
3565
+ clientSessionId: creds.clientSessionId,
3566
+ files: batch.map((f) => ({
3567
+ path: f.path,
3568
+ size: f.size,
3569
+ mimeType: f.mimeType,
3570
+ contentHash: f.contentHash,
3571
+ comment: commitMessage,
3572
+ })),
3573
+ },
3574
+ });
3575
+
3576
+ await Promise.all(
3577
+ intentRes.files.map(async (slot) => {
3578
+ const localFile = batch.find((b) => b.path === slot.path);
3579
+ const putRes = await fetch(slot.uploadUrl, {
3580
+ method: "PUT",
3581
+ headers: {
3582
+ "Content-Type": localFile.mimeType,
3583
+ },
3584
+ body: localFile.buffer,
3585
+ });
3586
+ if (!putRes.ok) {
3587
+ throw new Error(`Failed uploading ${slot.path} to storage (HTTP ${putRes.status})`);
3588
+ }
3589
+ }),
3590
+ );
3591
+
3592
+ const finalizeRes = await apiRequest("/api/v1/extension/bulk-finalize", {
3593
+ method: "POST",
3594
+ body: {
3595
+ projectId,
3596
+ uploadSessionId: intentRes.uploadSessionId,
3597
+ files: intentRes.files.map((slot) => {
3598
+ const localFile = batch.find((b) => b.path === slot.path);
3599
+ return {
3600
+ path: slot.path,
3601
+ uploadIntentId: slot.uploadIntentId,
3602
+ checksum: localFile.contentHash,
3603
+ comment: commitMessage,
3604
+ };
3605
+ }),
3606
+ },
3607
+ });
3608
+
3609
+ for (const fin of finalizeRes.files || []) {
3610
+ finalizedMap.set(fin.path, fin);
3611
+ }
3612
+ }
3613
+ },
3614
+ { silent: Boolean(flags.json) },
3615
+ );
3616
+ }
3617
+
3618
+ if (finalizedMap.size > 0) {
3619
+ updateManifestFiles(projectId, Array.from(finalizedMap.values()));
3620
+ }
3621
+
3622
+ // Also include unchanged files when linking to a task if the user explicitly pushed them
3623
+ const allTaskFiles = analysis.files
3624
+ .map((f) => {
3625
+ const fin = finalizedMap.get(f.path);
3626
+ if (fin) {
3627
+ return {
3628
+ nodeId: fin.nodeId,
3629
+ version: fin.version,
3630
+ contentHash: fin.contentHash,
3631
+ role: selectedRole || "working",
3632
+ };
3633
+ }
3634
+ const local = preparedFiles.find((p) => p.path === f.path);
3635
+ if (f.nodeId && local) {
3636
+ return {
3637
+ nodeId: f.nodeId,
3638
+ version: f.currentVersion || 1,
3639
+ contentHash: local.contentHash,
3640
+ role: selectedRole || "working",
3641
+ };
3642
+ }
3643
+ return null;
3644
+ })
3645
+ .filter(Boolean);
3646
+
3647
+ let taskPushReceipt = null;
3648
+ if (taskId && allTaskFiles.length > 0) {
3649
+ taskPushReceipt = await withSpinner(
3650
+ "Linking delivery to Sprint Task…",
3651
+ () =>
3652
+ apiRequest("/api/v1/extension/task-push", {
3653
+ method: "POST",
3654
+ headers: {
3655
+ "Idempotency-Key": crypto.randomUUID(),
3656
+ },
3657
+ body: {
3658
+ taskId,
3659
+ projectId,
3660
+ taskAction: selectedRole === "deliverable" ? "replace_task_version" : "upload_to_task",
3661
+ role: selectedRole || "working",
3662
+ transitionStatus,
3663
+ message: commitMessage,
3664
+ files: allTaskFiles,
3665
+ },
3666
+ }),
3667
+ { silent: Boolean(flags.json) },
3668
+ );
3669
+ }
3670
+
3671
+ const finalPayload = {
3672
+ success: true,
3673
+ projectId,
3674
+ taskId: taskId || null,
3675
+ role: selectedRole || null,
3676
+ transitionStatus: transitionStatus || null,
3677
+ uploadedCount: filesToUpload.length,
3678
+ unchangedCount: preparedFiles.length - filesToUpload.length + skippedByLocalManifestCount,
3679
+ taskPushReceipt,
3680
+ files: analysis.files.map((f) => {
3681
+ const fin = finalizedMap.get(f.path);
3682
+ return {
3683
+ path: f.path,
3684
+ status: f.status,
3685
+ version: fin ? fin.version : f.currentVersion,
3686
+ versionTransition: fin
3687
+ ? f.status === "new"
3688
+ ? "v1 (new)"
3689
+ : `v${f.currentVersion} -> v${fin.version}`
3690
+ : f.versionTransition,
3691
+ };
3692
+ }),
3693
+ };
3694
+
3695
+ outputResult(finalPayload, flags, (res) => {
3696
+ console.log(RAIL);
3697
+ console.log(
3698
+ `${STEP_DONE} ${c.bold}${c.ink}Pushed ${res.uploadedCount} changed file(s)${c.reset} ${c.muted}(${res.unchangedCount} unchanged)${c.reset} ${
3699
+ res.role ? formatStatusBadge(res.role) : ""
3700
+ }`,
3701
+ );
3702
+ for (const f of res.files) {
3703
+ if (f.status !== "unchanged" || res.files.length <= 8) {
3704
+ console.log(`${RAIL} • ${c.ink}${f.path}${c.reset} ${c.accent}-> ${f.versionTransition}${c.reset}`);
3705
+ }
3706
+ }
3707
+ if (res.taskPushReceipt) {
3708
+ console.log(
3709
+ `${c.dim}╰─${c.reset} ${c.emerald}✔${c.reset} Linked to Task ${c.muted}(${res.taskId})${c.reset} · Commit ${c.accent}${res.taskPushReceipt.commitSha?.slice(0, 10) || res.taskPushReceipt.pushId}${c.reset}\n`,
3710
+ );
3711
+ } else {
3712
+ console.log(`${c.dim}╰─${c.reset} ${c.emerald}✔${c.reset} Sync complete.\n`);
3713
+ }
3714
+ });
3715
+
3716
+ return finalPayload;
3717
+ }
3718
+
3719
+ async function handlePull(positional, flags, { skipHeader = false } = {}) {
3720
+ const cfg = getLocalConfig();
3721
+ const projectId = flags.workspace || cfg.projectId;
3722
+ if (!projectId) throw new Error("No workspace linked. Run `nb init` first.");
3723
+
3724
+ if (!flags.json && !skipHeader) {
3725
+ renderBrandHeader({ subtitle: `Pull Workspace Files · ${cfg.title || projectId}` });
3726
+ }
3727
+
3728
+ const filterPaths = positional.map((p) => (p.startsWith("/") ? p : `/${p}`));
3729
+ const outOverride = typeof flags.out === "string" && filterPaths.length === 1 ? flags.out : null;
3730
+
3731
+ // DIRECT-PATH FAST-PATH:
3732
+ // When explicit file path(s) (not directory prefixes ending in "/") are provided,
3733
+ // download them directly in 1 round-trip without calling /api/v1/extension/search first!
3734
+ const allExplicitFilePaths =
3735
+ filterPaths.length > 0 && filterPaths.every((fp) => !fp.endsWith("/") && path.extname(fp).length > 0);
3736
+
3737
+ if (allExplicitFilePaths) {
3738
+ let downloadedCount = 0;
3739
+ let skippedUnchangedCount = 0;
3740
+ const manifestUpdates = [];
3741
+
3742
+ await withSpinner(
3743
+ `Fast-pulling ${filterPaths.length} file(s) from NetworkBase…`,
3744
+ async () => {
3745
+ await Promise.all(
3746
+ filterPaths.map(async (normPath) => {
3747
+ const localDest = outOverride
3748
+ ? path.resolve(process.cwd(), outOverride)
3749
+ : path.join(process.cwd(), normPath.replace(/^\/+/, ""));
3750
+ let localHash = null;
3751
+ if (!flags.force && fs.existsSync(localDest)) {
3752
+ try {
3753
+ localHash = computeFileSha256(localDest).hash;
3754
+ } catch {
3755
+ localHash = null;
3756
+ }
3757
+ }
3758
+ const { notModified, buffer, meta } = await downloadRemoteFileBuffer(projectId, normPath, {
3759
+ ifNoneMatch: localHash,
3760
+ });
3761
+ if (notModified || !buffer) {
3762
+ skippedUnchangedCount++;
3763
+ return;
3764
+ }
3765
+ ensureDir(path.dirname(localDest));
3766
+ fs.writeFileSync(localDest, buffer);
3767
+ downloadedCount++;
3768
+ manifestUpdates.push({
3769
+ path: normPath,
3770
+ nodeId: meta?.nodeId,
3771
+ version: meta?.currentVersion || 1,
3772
+ contentHash: meta?.contentHash || crypto.createHash("sha256").update(buffer).digest("hex"),
3773
+ size: buffer.length,
3774
+ });
3775
+ }),
3776
+ );
3777
+ },
3778
+ { silent: Boolean(flags.json) },
3779
+ );
3780
+
3781
+ if (manifestUpdates.length > 0) {
3782
+ updateManifestFiles(projectId, manifestUpdates);
3783
+ }
3784
+
3785
+ outputResult(
3786
+ {
3787
+ projectId,
3788
+ downloadedCount,
3789
+ skippedUnchangedCount,
3790
+ totalRemoteFiles: filterPaths.length,
3791
+ fastPath: true,
3792
+ },
3793
+ flags,
3794
+ (res) => {
3795
+ console.log(
3796
+ `${RAIL}\n${c.dim}╰─${c.reset} ${c.emerald}✔${c.reset} Pulled ${c.bold}${c.ink}${res.downloadedCount} file(s)${c.reset}${
3797
+ res.skippedUnchangedCount > 0 ? ` ${c.muted}(${res.skippedUnchangedCount} already up to date · HTTP 304)${c.reset}` : ""
3798
+ } from workspace ${c.muted}(${cfg.title || res.projectId} · 1-RTT fast-path)${c.reset}\n`,
3799
+ );
3800
+ },
3801
+ );
3802
+ return;
3803
+ }
3804
+
3805
+ const searchQuery = positional.length === 1 ? path.basename(positional[0]) : "";
3806
+ const remoteFiles = await withSpinner(
3807
+ "Fetching remote workspace manifest…",
3808
+ () => fetchWorkspaceFiles(projectId, searchQuery),
3809
+ { silent: Boolean(flags.json) },
3810
+ );
3811
+
3812
+ const targets =
3813
+ filterPaths.length > 0
3814
+ ? remoteFiles.filter((f) => filterPaths.some((fp) => f.path === fp || f.path.startsWith(`${fp.replace(/\/+$/, "")}/`)))
3815
+ : remoteFiles;
3816
+
3817
+ if (targets.length === 0) {
3818
+ throw new Error(
3819
+ filterPaths.length > 0
3820
+ ? `No matching remote file(s) found for: ${filterPaths.join(", ")}`
3821
+ : "No remote files found in workspace.",
3822
+ );
3823
+ }
3824
+
3825
+ // Deduplicate against local files / manifest unless --force is passed
3826
+ const filesToDownload = [];
3827
+ let skippedUnchangedCount = 0;
3828
+
3829
+ for (const node of targets) {
3830
+ const localDest = outOverride
3831
+ ? path.resolve(process.cwd(), outOverride)
3832
+ : path.join(process.cwd(), node.path.replace(/^\/+/, ""));
3833
+ if (!flags.force && node.contentHash && fs.existsSync(localDest)) {
3834
+ try {
3835
+ const { hash } = computeFileSha256(localDest);
3836
+ if (hash.toLowerCase() === node.contentHash.toLowerCase()) {
3837
+ skippedUnchangedCount++;
3838
+ continue;
3839
+ }
3840
+ } catch {
3841
+ // Proceed to download if local read fails
3842
+ }
3843
+ }
3844
+ filesToDownload.push({ node, localDest });
3845
+ }
3846
+
3847
+ let downloadedCount = 0;
3848
+ const manifestUpdates = [...targets];
3849
+
3850
+ if (filesToDownload.length > 0) {
3851
+ await withSpinner(
3852
+ `Downloading ${filesToDownload.length} changed file(s) in parallel (${skippedUnchangedCount} unchanged)…`,
3853
+ async () => {
3854
+ for (let offset = 0; offset < filesToDownload.length; offset += 8) {
3855
+ const chunk = filesToDownload.slice(offset, offset + 8);
3856
+ await Promise.all(
3857
+ chunk.map(async ({ node, localDest }) => {
3858
+ const { buffer } = await downloadRemoteFileBuffer(projectId, node.path);
3859
+ ensureDir(path.dirname(localDest));
3860
+ fs.writeFileSync(localDest, buffer);
3861
+ downloadedCount++;
3862
+ }),
3863
+ );
3864
+ }
3865
+ },
3866
+ { silent: Boolean(flags.json) },
3867
+ );
3868
+ }
3869
+
3870
+ updateManifestFiles(projectId, manifestUpdates);
3871
+
3872
+ outputResult(
3873
+ { projectId, downloadedCount, skippedUnchangedCount, totalRemoteFiles: remoteFiles.length },
3874
+ flags,
3875
+ (res) => {
3876
+ console.log(
3877
+ `${RAIL}\n${c.dim}╰─${c.reset} ${c.emerald}✔${c.reset} Pulled ${c.bold}${c.ink}${res.downloadedCount} changed file(s)${c.reset} ${c.muted}(${res.skippedUnchangedCount} already up to date)${c.reset} from ${c.bold}${c.ink}${cfg.title || res.projectId}${c.reset}\n`,
3878
+ );
3879
+ },
3880
+ );
3881
+ }
3882
+
3883
+ async function hydrateWorkspaceMirror(projectId, { cwd = process.cwd(), force = false } = {}) {
3884
+ const mirrorDir = getLocalMirrorDir(cwd);
3885
+ ensureDir(mirrorDir);
3886
+ const remoteFiles = await fetchWorkspaceFiles(projectId, "");
3887
+ const manifest = getLocalManifest(cwd);
3888
+ const manifestFiles = manifest.projectId === projectId && manifest.files ? manifest.files : {};
3889
+
3890
+ const inlineCandidates = remoteFiles.filter((node) => (node.size ?? 0) <= 512 * 1024);
3891
+ const toDownload = [];
3892
+ let upToDateCount = 0;
3893
+
3894
+ for (const node of inlineCandidates) {
3895
+ const cleanRel = node.path.replace(/^\/+/, "");
3896
+ const mirrorDest = path.join(mirrorDir, cleanRel);
3897
+ const expectedHash = (node.contentHash || manifestFiles[node.path]?.contentHash || "").toLowerCase();
3898
+ if (!force && expectedHash && fs.existsSync(mirrorDest)) {
3899
+ try {
3900
+ const localHash = computeFileSha256(mirrorDest).hash.toLowerCase();
3901
+ if (localHash === expectedHash) {
3902
+ upToDateCount++;
3903
+ continue;
3904
+ }
3905
+ } catch {
3906
+ // Re-download if unreadable
3907
+ }
3908
+ }
3909
+ toDownload.push({ node, mirrorDest });
3910
+ }
3911
+
3912
+ let downloadedCount = 0;
3913
+ const manifestUpdates = [...remoteFiles];
3914
+
3915
+ for (let offset = 0; offset < toDownload.length; offset += 8) {
3916
+ const chunk = toDownload.slice(offset, offset + 8);
3917
+ await Promise.all(
3918
+ chunk.map(async ({ node, mirrorDest }) => {
3919
+ try {
3920
+ const { buffer, meta } = await downloadRemoteFileBuffer(projectId, node.path);
3921
+ if (buffer) {
3922
+ ensureDir(path.dirname(mirrorDest));
3923
+ fs.writeFileSync(mirrorDest, buffer);
3924
+ downloadedCount++;
3925
+ manifestUpdates.push({
3926
+ path: node.path,
3927
+ nodeId: meta?.nodeId || node.id,
3928
+ version: meta?.currentVersion || node.currentVersion || 1,
3929
+ contentHash:
3930
+ meta?.contentHash || node.contentHash || crypto.createHash("sha256").update(buffer).digest("hex"),
3931
+ size: buffer.length,
3932
+ });
3933
+ }
3934
+ } catch {
3935
+ // Skip unavailable binary/oversized file in mirror hydration
3936
+ }
3937
+ }),
3938
+ );
3939
+ }
3940
+
3941
+ updateManifestFiles(projectId, manifestUpdates, cwd);
3942
+ return {
3943
+ mirrorDir,
3944
+ downloadedCount,
3945
+ upToDateCount,
3946
+ totalRemoteFiles: remoteFiles.length,
3947
+ };
3948
+ }
3949
+
3950
+ async function handleSync(positional, flags) {
3951
+ const cwd = process.cwd();
3952
+ let cfg = getLocalConfig(cwd);
3953
+
3954
+ // Allow switching workspace in the same single `nb sync --workspace <slug-or-id>` call
3955
+ if (typeof flags.workspace === "string" && flags.workspace.trim() && flags.workspace !== cfg.projectId) {
3956
+ await handleInit([flags.workspace.trim()], { ...flags, "no-task": true, silent: true }, { skipHeader: true });
3957
+ cfg = getLocalConfig(cwd);
3958
+ }
3959
+
3960
+ const projectId = cfg.projectId;
3961
+ if (!projectId) {
3962
+ throw new Error("No workspace linked. Run `nb init` first.");
3963
+ }
3964
+
3965
+ if (!flags.json) {
3966
+ renderBrandHeader({ subtitle: `Unified One-Permission Sync · ${cfg.title || projectId}` });
3967
+ }
3968
+
3969
+ const selectedRole = resolveRoleFromFlags(flags) || "deliverable";
3970
+ const transitionStatus = flags.done ? "done" : flags.wip ? "in_progress" : undefined;
3971
+ const taskId = inferActiveTaskId(flags, cwd);
3972
+ const commitMessage =
3973
+ typeof flags.message === "string"
3974
+ ? flags.message
3975
+ : `Synced via NetworkBase CLI (${selectedRole})`;
3976
+
3977
+ // 1. Check for locally modified files in .networkbase/mirror/ or explicit positional paths
3978
+ let pushResult = null;
3979
+ const mirrorDir = getLocalMirrorDir(cwd);
3980
+ const hasMirrorOrTargets = positional.length > 0 || fs.existsSync(mirrorDir);
3981
+
3982
+ if (hasMirrorOrTargets && !flags["pull-only"]) {
3983
+ try {
3984
+ const { preparedFiles, secretViolations } = prepareLocalFilesForPush(
3985
+ positional,
3986
+ { ...flags, scope: positional.length === 0 && fs.existsSync(mirrorDir) ? mirrorDir : flags.scope },
3987
+ cwd,
3988
+ );
3989
+ const changedLocal = preparedFiles.filter((f) => !f.matchesLocalManifest);
3990
+ if (secretViolations.length === 0 && changedLocal.length > 0) {
3991
+ const totalBytes = changedLocal.reduce((acc, f) => acc + f.size, 0);
3992
+ if (changedLocal.length <= 50 && totalBytes <= FAST_PUSH_INLINE_LIMIT_BYTES) {
3993
+ pushResult = await withSpinner(
3994
+ `Fast-pushing ${changedLocal.length} modified file(s) to ${cfg.title || projectId}…`,
3995
+ () =>
3996
+ executeFastPushRequest({
3997
+ projectId,
3998
+ taskId,
3999
+ selectedRole,
4000
+ transitionStatus,
4001
+ commitMessage,
4002
+ filesToPush: changedLocal,
4003
+ cwd,
4004
+ }),
4005
+ { silent: Boolean(flags.json) },
4006
+ );
4007
+ saveLastSyncReceipt(
4008
+ {
4009
+ status: "pushed",
4010
+ projectId,
4011
+ uploadedCount: pushResult.uploadedCount,
4012
+ files: pushResult.files,
4013
+ },
4014
+ cwd,
4015
+ );
4016
+ }
4017
+ }
4018
+ } catch {
4019
+ // No local files yet; proceed to mirror hydration
4020
+ }
4021
+ }
4022
+
4023
+ // 2. Hydrate .networkbase/mirror/ and .networkbase/tasks/TASKS.md in parallel
4024
+ const [mirrorResult, taskData] = await withSpinner(
4025
+ `Syncing workspace mirror (.networkbase/mirror/) & task briefing (.networkbase/tasks/TASKS.md)…`,
4026
+ () =>
4027
+ Promise.all([
4028
+ hydrateWorkspaceMirror(projectId, { cwd, force: Boolean(flags.force) }),
4029
+ apiRequest(`/api/v1/extension/workspace-tasks?projectId=${projectId}&scope=all`).catch(() => ({
4030
+ tasks: [],
4031
+ })),
4032
+ ]),
4033
+ { silent: Boolean(flags.json) },
4034
+ );
4035
+
4036
+ const tasksList = taskData?.tasks || [];
4037
+ writeLocalTaskIntelligence(projectId, cfg.title || projectId, tasksList, cwd);
4038
+
4039
+ // 3. Ensure background auto-sync daemon is running for 0-permission auto-push on save
4040
+ const daemon = flags["no-daemon"] ? { running: false } : ensureBackgroundDaemon(projectId, cwd);
4041
+
4042
+ const payload = {
4043
+ synced: true,
4044
+ projectId,
4045
+ workspaceTitle: cfg.title || projectId,
4046
+ mirrorDir: mirrorResult.mirrorDir,
4047
+ tasksBriefingPath: path.join(getLocalTasksDir(cwd), "TASKS.md"),
4048
+ tasksCount: tasksList.length,
4049
+ pushedCount: pushResult?.uploadedCount || 0,
4050
+ pushedFiles: pushResult?.files || [],
4051
+ pulledCount: mirrorResult.downloadedCount,
4052
+ upToDateCount: mirrorResult.upToDateCount,
4053
+ totalRemoteFiles: mirrorResult.totalRemoteFiles,
4054
+ daemonRunning: daemon.running,
4055
+ daemonPid: daemon.pid || null,
4056
+ };
4057
+
4058
+ outputResult(payload, flags, (res) => {
4059
+ console.log(RAIL);
4060
+ if (res.pushedCount > 0) {
4061
+ console.log(
4062
+ `${STEP_DONE} ${c.bold}${c.ink}Pushed ${res.pushedCount} modified file(s)${c.reset} ${formatStatusBadge(selectedRole)}`,
4063
+ );
4064
+ for (const f of res.pushedFiles) {
4065
+ if (f.status !== "unchanged") {
4066
+ console.log(`${RAIL} • ${c.ink}${f.path}${c.reset} ${c.accent}-> ${f.versionTransition}${c.reset}`);
4067
+ }
4068
+ }
4069
+ }
4070
+ console.log(
4071
+ `${STEP_DONE} ${c.bold}${c.ink}Local Mirror Ready${c.reset} ${c.muted}(.networkbase/mirror/ · ${res.pulledCount} pulled, ${res.upToDateCount} up to date)${c.reset}`,
4072
+ );
4073
+ console.log(
4074
+ `${STEP_DONE} ${c.bold}${c.ink}Task Briefing Synced${c.reset} ${c.muted}(.networkbase/tasks/TASKS.md · ${res.tasksCount} task(s) with subtasks & attached files)${c.reset}`,
4075
+ );
4076
+ if (res.daemonRunning) {
4077
+ console.log(
4078
+ `${STEP_DONE} ${c.bold}${c.ink}Auto-Sync Daemon Active${c.reset} ${c.muted}(PID ${res.daemonPid} · edits in .networkbase/mirror/ auto-push in <400ms with 0 prompts)${c.reset}`,
4079
+ );
4080
+ }
4081
+ console.log(`${c.dim}╰─${c.reset} ${c.emerald}✔${c.reset} Sync complete.\n`);
4082
+ });
4083
+
4084
+ return payload;
4085
+ }
4086
+
4087
+ async function handleWatch(positional, flags) {
4088
+ const cwd = process.cwd();
4089
+ const cfg = getLocalConfig(cwd);
4090
+ const projectId = flags.workspace || cfg.projectId;
4091
+ if (!projectId) throw new Error("No workspace linked. Run `nb init` first.");
4092
+
4093
+ const isDaemonWorker = Boolean(flags["daemon-worker"]);
4094
+ const role = resolveRoleFromFlags(flags) || "deliverable";
4095
+ const taskId = inferActiveTaskId(flags, cwd);
4096
+ const mirrorDir = getLocalMirrorDir(cwd);
4097
+ ensureDir(mirrorDir);
4098
+ const watchTarget = positional[0] ? path.resolve(cwd, positional[0]) : mirrorDir;
4099
+
4100
+ if (!isDaemonWorker) {
4101
+ renderBrandHeader({
4102
+ subtitle: `Live Auto-Sync Watch · ${cfg.title || projectId}`,
4103
+ contextRows: [
4104
+ { label: "Watching", value: `${c.ink}${watchTarget}${c.reset}` },
4105
+ { label: "Default Role", value: formatStatusBadge(role) },
4106
+ { label: "Press", value: `${c.muted}Ctrl+C to stop watching${c.reset}` },
4107
+ ],
4108
+ });
4109
+ }
4110
+
4111
+ const pendingPaths = new Set();
4112
+ let debounceTimer = null;
4113
+
4114
+ const flushChanges = async () => {
4115
+ const changed = Array.from(pendingPaths);
4116
+ pendingPaths.clear();
4117
+ if (changed.length === 0) return;
4118
+
4119
+ try {
4120
+ const prepared = [];
4121
+ for (const absPath of changed) {
4122
+ if (!fs.existsSync(absPath) || !fs.statSync(absPath).isFile()) continue;
4123
+ const { hash, size, buffer } = computeFileSha256(absPath);
4124
+ if (size > FAST_PUSH_INLINE_LIMIT_BYTES) continue;
4125
+
4126
+ const isMirrorFile = absPath.startsWith(mirrorDir + path.sep);
4127
+ const rel = isMirrorFile
4128
+ ? path.relative(mirrorDir, absPath).replace(/\\/g, "/")
4129
+ : path.relative(cwd, absPath).replace(/\\/g, "/");
4130
+ if (!isMirrorFile && (rel.startsWith(".networkbase/") || rel.startsWith(".git/"))) continue;
4131
+ if (scanFileForSecrets(rel, buffer)) continue;
4132
+
4133
+ const normPath = rel.startsWith("/") ? rel : `/${rel}`;
4134
+ const existingHash = getLocalManifest(cwd)?.files?.[normPath]?.contentHash;
4135
+ if (existingHash && existingHash.toLowerCase() === hash.toLowerCase()) continue;
4136
+
4137
+ prepared.push({
4138
+ path: normPath,
4139
+ contentHash: hash,
4140
+ size,
4141
+ mimeType: detectMimeType(normPath),
4142
+ buffer,
4143
+ });
4144
+ }
4145
+
4146
+ if (prepared.length === 0) return;
4147
+
4148
+ const res = await executeFastPushRequest({
4149
+ projectId,
4150
+ taskId: inferActiveTaskId(flags, cwd),
4151
+ selectedRole: role,
4152
+ transitionStatus: undefined,
4153
+ commitMessage: `Auto-synced via NetworkBase CLI (${role})`,
4154
+ filesToPush: prepared,
4155
+ cwd,
4156
+ });
4157
+
4158
+ saveLastSyncReceipt(
4159
+ {
4160
+ status: "synced",
4161
+ projectId,
4162
+ uploadedCount: res.uploadedCount,
4163
+ files: res.files,
4164
+ },
4165
+ cwd,
4166
+ );
4167
+
4168
+ if (!isDaemonWorker) {
4169
+ for (const f of res.files || []) {
4170
+ if (f.status !== "unchanged") {
4171
+ printStepDone("Auto-Synced", `${f.path} (${f.versionTransition})`);
4172
+ }
4173
+ }
4174
+ }
4175
+ } catch (err) {
4176
+ saveLastSyncReceipt(
4177
+ {
4178
+ status: "error",
4179
+ projectId,
4180
+ error: err instanceof Error ? err.message : String(err),
4181
+ },
4182
+ cwd,
4183
+ );
4184
+ if (!isDaemonWorker) {
4185
+ console.error(
4186
+ `${RAIL} ${STEP_ERR} ${c.red}Auto-sync error: ${err instanceof Error ? err.message : String(err)}${c.reset}`,
4187
+ );
4188
+ }
4189
+ }
4190
+ };
4191
+
4192
+ fs.watch(watchTarget, { recursive: true }, (_eventType, filename) => {
4193
+ if (!filename) return;
4194
+ const rel = String(filename).replace(/\\/g, "/");
4195
+ const parts = rel.split("/");
4196
+ if (parts.some((p) => IGNORED_DIRS.has(p) || p.startsWith("."))) return;
4197
+ const absPath = path.resolve(watchTarget, rel);
4198
+ pendingPaths.add(absPath);
4199
+ if (debounceTimer) clearTimeout(debounceTimer);
4200
+ debounceTimer = setTimeout(flushChanges, 180);
4201
+ });
4202
+
4203
+ await new Promise(() => {});
4204
+ }
4205
+
4206
+ async function handleInteractiveHub(flags) {
4207
+ const creds = getCredentials();
4208
+ const localCfg = getLocalConfig();
4209
+ const localState = getLocalState();
4210
+ const apiUrl = await resolveBestApiUrl(localCfg?.apiUrl || creds?.apiUrl);
4211
+
4212
+ let sessionInfo = { active: false, user: null, sessionId: null, tokenType: null };
4213
+ if (creds?.token) {
4214
+ try {
4215
+ sessionInfo = await apiRequest("/api/v1/extension/session", { apiUrl, token: creds.token });
4216
+ } catch {
4217
+ sessionInfo = { active: false };
4218
+ }
4219
+ }
4220
+
4221
+ if (!sessionInfo.active || !localCfg?.projectId) {
4222
+ renderBrandHeader({
4223
+ subtitle: "Welcome · Let's connect this folder to NetworkBase",
4224
+ });
4225
+ const shouldSetup = await tuiConfirm({
4226
+ title: !sessionInfo.active
4227
+ ? "Sign in and link this folder to a NetworkBase workspace now?"
4228
+ : "Link this folder to a NetworkBase workspace now?",
4229
+ stepLabel: "Quick Setup",
4230
+ yesLabel: "Yes, start setup",
4231
+ noLabel: "No, exit",
4232
+ initialValue: true,
4233
+ });
4234
+ if (shouldSetup) {
4235
+ await handleInit([], flags, { skipHeader: true });
4236
+ } else {
4237
+ console.log(`${c.dim}╰─${c.reset} Run ${c.accent}nb init${c.reset} whenever you're ready.\n`);
4238
+ }
4239
+ return;
4240
+ }
4241
+
4242
+ const localFilesCount = collectLocalFiles([], process.cwd()).length;
4243
+ const identity = `${c.emerald}●${c.reset} ${c.bold}${c.ink}${sessionInfo.user?.username ? `@${sessionInfo.user.username}` : sessionInfo.user?.email || sessionInfo.sessionId}${c.reset} ${c.muted}(${sessionInfo.tokenType || creds?.tokenType || "device"})${c.reset}`;
4244
+ const wsDisplay = `${c.bold}${c.ink}${localCfg.title || localCfg.projectId}${c.reset} ${c.muted}(${localCfg.slug || localCfg.projectId.slice(0, 8)})${c.reset}`;
4245
+ const taskDisplay = localState?.activeTaskId
4246
+ ? `${c.ink}${localState.activeTaskTitle || localState.activeTaskId}${c.reset} ${formatStatusBadge("in_progress")}`
4247
+ : `${c.muted}None bound${c.reset}`;
4248
+
4249
+ renderBrandHeader({
4250
+ subtitle: `Connected to ${apiUrl}`,
4251
+ contextRows: [
4252
+ { label: "Account", value: identity },
4253
+ { label: "Workspace", value: wsDisplay },
4254
+ { label: "Active Task", value: taskDisplay },
4255
+ { label: "Local Tree", value: `${c.ink}${localFilesCount} tracked file(s)${c.reset}` },
4256
+ ],
4257
+ });
4258
+
4259
+ const action = await tuiSelect({
4260
+ title: "What would you like to do?",
4261
+ stepLabel: "Action",
4262
+ allowCancel: true,
4263
+ items: [
4264
+ {
4265
+ label: "Push local files to NetworkBase",
4266
+ badge: `${c.emerald}[Smart Push]${c.reset}`,
4267
+ description: "Compare SHA-256, select files, and classify as Final Deliverable / Draft / Reference",
4268
+ value: "push",
4269
+ },
4270
+ {
4271
+ label: "Switch or bind an Active Sprint Task",
4272
+ badge: `${c.accent}[Tasks]${c.reset}`,
4273
+ description: `Pick an open task from ${localCfg.title || "this workspace"}`,
4274
+ value: "task",
4275
+ },
4276
+ {
4277
+ label: "Pull latest files from Workspace",
4278
+ badge: `${c.muted}[Sync Down]${c.reset}`,
4279
+ description: "Download remote workspace files into this directory",
4280
+ value: "pull",
4281
+ },
4282
+ {
4283
+ label: "Live Auto-Sync Watch Mode",
4284
+ badge: `${c.emerald}[nb watch]${c.reset}`,
4285
+ description: "Automatically push saved file edits in milliseconds (0ms local SHA-256 diff)",
4286
+ value: "watch",
4287
+ },
4288
+ {
4289
+ label: "Inspect remote files & version diffs",
4290
+ badge: `${c.muted}[Diff & Tree]${c.reset}`,
4291
+ description: "Compare local files against remote v1/v2 versions",
4292
+ value: "diff",
4293
+ },
4294
+ {
4295
+ label: "Switch linked Workspace",
4296
+ badge: `${c.muted}[Workspace]${c.reset}`,
4297
+ description: "Connect this folder to a different NetworkBase workspace",
4298
+ value: "workspace",
4299
+ },
4300
+ {
4301
+ label: "Re-authenticate or switch Account",
4302
+ badge: `${c.muted}[Auth]${c.reset}`,
4303
+ description: "Sign in via Web Browser (/authorize) or Personal Access Token",
4304
+ value: "reauth",
4305
+ },
4306
+ {
4307
+ label: "Exit",
4308
+ value: "exit",
4309
+ },
4310
+ ],
4311
+ });
4312
+
4313
+ if (!action || action === "exit") {
4314
+ console.log(`${c.dim}╰─${c.reset} Bye!\n`);
4315
+ return;
4316
+ }
4317
+
4318
+ if (action === "push") {
4319
+ await handlePush([], flags, { skipHeader: true });
4320
+ return;
4321
+ }
4322
+ if (action === "task") {
4323
+ await handleTask("work", [], flags);
4324
+ return;
4325
+ }
4326
+ if (action === "pull") {
4327
+ await handlePull([], flags, { skipHeader: true });
4328
+ return;
4329
+ }
4330
+ if (action === "watch") {
4331
+ await handleWatch([], flags);
4332
+ return;
4333
+ }
4334
+ if (action === "diff") {
4335
+ await handleFile("diff", [], flags);
4336
+ return;
4337
+ }
4338
+ if (action === "workspace") {
4339
+ await handleInit([], flags, { skipHeader: true });
4340
+ return;
4341
+ }
4342
+ if (action === "reauth") {
4343
+ await handleAuth("login", [], flags);
4344
+ }
4345
+ }
4346
+
4347
+ async function handleHookInstall(flags) {
4348
+ const gitHooksDir = path.join(process.cwd(), ".git", "hooks");
4349
+ if (!fs.existsSync(gitHooksDir)) {
4350
+ throw new Error("No .git/hooks directory found in current working directory.");
4351
+ }
4352
+ const hookPath = path.join(gitHooksDir, "pre-push");
4353
+ const script = `#!/bin/sh
4354
+ # NetworkBase Pre-Push Secret & Version Guard
4355
+ nb push --dry-run
4356
+ `;
4357
+ fs.writeFileSync(hookPath, script, { mode: 0o755 });
4358
+ outputResult({ installed: true, hookPath }, flags, () => {
4359
+ console.log(`✔ Installed NetworkBase pre-push guard at ${hookPath}`);
4360
+ });
4361
+ }
4362
+
4363
+ // ============================================================================
4364
+ // BUILT-IN MCP SERVER (`nb mcp`) FOR AI PAIR PROGRAMMERS (Antigravity, Codex, Claude)
4365
+ // ============================================================================
4366
+
4367
+ async function startMcpServer() {
4368
+ const rl = readline.createInterface({
4369
+ input: process.stdin,
4370
+ terminal: false,
4371
+ });
4372
+
4373
+ function sendJsonRpc(id, result, error = null) {
4374
+ const response = error
4375
+ ? { jsonrpc: "2.0", id, error }
4376
+ : { jsonrpc: "2.0", id, result };
4377
+ process.stdout.write(JSON.stringify(response) + "\n");
4378
+ }
4379
+
4380
+ rl.on("line", async (line) => {
4381
+ if (!line.trim()) return;
4382
+ let msg;
4383
+ try {
4384
+ msg = JSON.parse(line);
4385
+ } catch {
4386
+ return;
4387
+ }
4388
+
4389
+ const { id, method, params } = msg;
4390
+
4391
+ try {
4392
+ if (method === "initialize") {
4393
+ sendJsonRpc(id, {
4394
+ protocolVersion: "2024-11-05",
4395
+ serverInfo: { name: "networkbase-cli-mcp", version: CLI_VERSION },
4396
+ capabilities: { tools: {} },
4397
+ });
4398
+ return;
4399
+ }
4400
+
4401
+ if (method === "tools/list") {
4402
+ sendJsonRpc(id, {
4403
+ tools: [
4404
+ {
4405
+ name: "nb_auth_status",
4406
+ description:
4407
+ "Check current NetworkBase CLI authentication status, signed-in user, linked workspace, and active task.",
4408
+ inputSchema: { type: "object", properties: {} },
4409
+ },
4410
+ {
4411
+ name: "nb_auth_login",
4412
+ description:
4413
+ "Authenticate the NetworkBase CLI. If no token is provided, opens the user's browser to `/authorize` for 1-click approval.",
4414
+ inputSchema: {
4415
+ type: "object",
4416
+ properties: {
4417
+ method: {
4418
+ type: "string",
4419
+ enum: ["browser", "token"],
4420
+ description: "Use `browser` to open `/authorize` for 1-click sign-in, or `token` with `nb_pat_...`.",
4421
+ },
4422
+ token: { type: "string" },
4423
+ apiUrl: { type: "string" },
4424
+ },
4425
+ },
4426
+ },
4427
+ {
4428
+ name: "nb_workspace_list",
4429
+ description: "List all NetworkBase workspaces accessible to the authenticated user.",
4430
+ inputSchema: { type: "object", properties: {} },
4431
+ },
4432
+ {
4433
+ name: "nb_init",
4434
+ description:
4435
+ "Initialize and link the current directory to a NetworkBase workspace (and optional sprint task). Automatically triggers browser login if not signed in.",
4436
+ inputSchema: {
4437
+ type: "object",
4438
+ properties: {
4439
+ workspaceId: { type: "string" },
4440
+ taskId: { type: "string" },
4441
+ apiUrl: { type: "string" },
4442
+ },
4443
+ },
4444
+ },
4445
+ {
4446
+ name: "nb_pre_push_analyze",
4447
+ description:
4448
+ "Run High-EQ Pre-Push Analysis on local files before pushing to NetworkBase. Returns version transitions (new v1 vs v1 -> v2 bumps), lock status, and task role options (`deliverable`, `working`, `reference`). Always call this first and ask the user which role they want before calling `nb_push`.",
4449
+ inputSchema: {
4450
+ type: "object",
4451
+ properties: {
4452
+ paths: { type: "array", items: { type: "string" } },
4453
+ taskId: { type: "string" },
4454
+ },
4455
+ },
4456
+ },
4457
+ {
4458
+ name: "nb_push",
4459
+ description:
4460
+ "Push local files to NetworkBase with SHA-256 verification, version bumping (v1 -> v2), and task role classification (`deliverable`, `working`, or `reference`).",
4461
+ inputSchema: {
4462
+ type: "object",
4463
+ properties: {
4464
+ paths: { type: "array", items: { type: "string" } },
4465
+ taskId: { type: "string" },
4466
+ role: {
4467
+ type: "string",
4468
+ enum: ["deliverable", "working", "reference"],
4469
+ },
4470
+ transitionStatus: {
4471
+ type: "string",
4472
+ enum: ["in_progress", "done"],
4473
+ },
4474
+ message: { type: "string" },
4475
+ },
4476
+ required: ["role"],
4477
+ },
4478
+ },
4479
+ {
4480
+ name: "nb_task_list",
4481
+ description:
4482
+ "List tasks in the active NetworkBase workspace with full descriptions, subtasks, and role-classified attached files, and sync .networkbase/tasks/TASKS.md.",
4483
+ inputSchema: {
4484
+ type: "object",
4485
+ properties: {
4486
+ allWorkspaces: { type: "boolean" },
4487
+ scope: { type: "string", enum: ["all", "mine"] },
4488
+ },
4489
+ },
4490
+ },
4491
+ {
4492
+ name: "nb_task_view",
4493
+ description:
4494
+ "View full task details, description, subtasks checklist, and attached files categorized by role (`reference`, `working`, `deliverable`), and mirror attached files to .networkbase/mirror/.",
4495
+ inputSchema: {
4496
+ type: "object",
4497
+ properties: { taskId: { type: "string", description: "Task UUID or task number (e.g. #4 or 4)" } },
4498
+ required: ["taskId"],
4499
+ },
4500
+ },
4501
+ {
4502
+ name: "nb_task_work",
4503
+ description:
4504
+ "Bind the active task in .networkbase/state.json, transition it to in_progress, and download its attached files into .networkbase/mirror/.",
4505
+ inputSchema: {
4506
+ type: "object",
4507
+ properties: { taskId: { type: "string", description: "Task UUID or task number (e.g. #4 or 4)" } },
4508
+ required: ["taskId"],
4509
+ },
4510
+ },
4511
+ {
4512
+ name: "nb_task_check",
4513
+ description: "Check or uncheck subtasks on the active or specified task.",
4514
+ inputSchema: {
4515
+ type: "object",
4516
+ properties: {
4517
+ taskId: { type: "string" },
4518
+ subtaskNumbers: { type: "array", items: { type: "number" } },
4519
+ all: { type: "boolean" },
4520
+ uncheck: { type: "boolean" },
4521
+ },
4522
+ },
4523
+ },
4524
+ {
4525
+ name: "nb_file_diff",
4526
+ description: "Compare local files against the remote NetworkBase workspace SHA-256 manifest.",
4527
+ inputSchema: {
4528
+ type: "object",
4529
+ properties: { paths: { type: "array", items: { type: "string" } } },
4530
+ },
4531
+ },
4532
+ ],
4533
+ });
4534
+ return;
4535
+ }
4536
+
4537
+ if (method === "tools/call") {
4538
+ const toolName = params?.name;
4539
+ const args = params?.arguments || {};
4540
+
4541
+ if (toolName === "nb_auth_status") {
4542
+ const status = await handleStatus({ json: true });
4543
+ sendJsonRpc(id, {
4544
+ content: [{ type: "text", text: JSON.stringify(status, null, 2) }],
4545
+ });
4546
+ return;
4547
+ }
4548
+
4549
+ if (toolName === "nb_auth_login") {
4550
+ const loginFlags = {
4551
+ json: true,
4552
+ web: args.method !== "token",
4553
+ token: args.token,
4554
+ url: args.apiUrl,
4555
+ };
4556
+ const loginRes = await performInteractiveOrFlagLogin(loginFlags, args.token);
4557
+ sendJsonRpc(id, {
4558
+ content: [{ type: "text", text: JSON.stringify(loginRes, null, 2) }],
4559
+ });
4560
+ return;
4561
+ }
4562
+
4563
+ if (toolName === "nb_workspace_list") {
4564
+ const apiUrl = await resolveBestApiUrl();
4565
+ const data = await apiRequest("/api/v1/extension/workspaces", { apiUrl });
4566
+ sendJsonRpc(id, {
4567
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
4568
+ });
4569
+ return;
4570
+ }
4571
+
4572
+ if (toolName === "nb_init") {
4573
+ await handleInit(args.workspaceId ? [args.workspaceId] : [], {
4574
+ json: true,
4575
+ workspace: args.workspaceId,
4576
+ task: args.taskId,
4577
+ url: args.apiUrl,
4578
+ });
4579
+ const status = await handleStatus({ json: true });
4580
+ sendJsonRpc(id, {
4581
+ content: [{ type: "text", text: JSON.stringify(status, null, 2) }],
4582
+ });
4583
+ return;
4584
+ }
4585
+
4586
+ if (toolName === "nb_pre_push_analyze" || toolName === "nb_file_diff") {
4587
+ const res = await executePrePushAnalysis(args.paths || [], {
4588
+ task: args.taskId,
4589
+ });
4590
+ sendJsonRpc(id, {
4591
+ content: [
4592
+ {
4593
+ type: "text",
4594
+ text: JSON.stringify(res.analysis, null, 2),
4595
+ },
4596
+ ],
4597
+ });
4598
+ return;
4599
+ }
4600
+
4601
+ if (toolName === "nb_push") {
4602
+ const flags = {
4603
+ json: true,
4604
+ task: args.taskId,
4605
+ role: args.role || "working",
4606
+ done: args.transitionStatus === "done",
4607
+ wip: args.transitionStatus === "in_progress",
4608
+ message: args.message,
4609
+ };
4610
+ const pushResult = await handlePush(args.paths || [], flags);
4611
+ sendJsonRpc(id, {
4612
+ content: [
4613
+ {
4614
+ type: "text",
4615
+ text: JSON.stringify(pushResult, null, 2),
4616
+ },
4617
+ ],
4618
+ });
4619
+ return;
4620
+ }
4621
+
4622
+ if (toolName === "nb_task_list") {
4623
+ const cfg = getLocalConfig();
4624
+ const data = await apiRequest(
4625
+ `/api/v1/extension/workspace-tasks?projectId=${cfg.projectId}&scope=${args.scope || "all"}`,
4626
+ );
4627
+ writeLocalTaskIntelligence(cfg.projectId, cfg.title || cfg.projectId, data.tasks || []);
4628
+ sendJsonRpc(id, {
4629
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
4630
+ });
4631
+ return;
4632
+ }
4633
+
4634
+ if (toolName === "nb_task_view") {
4635
+ const cfg = getLocalConfig();
4636
+ const resolvedId = resolveTaskIdentifier(args.taskId);
4637
+ const detail = await apiRequest(
4638
+ `/api/v1/extension/task-detail?projectId=${cfg.projectId}&taskId=${encodeURIComponent(resolvedId)}`,
4639
+ );
4640
+ await hydrateTaskAttachedFiles(cfg.projectId, detail.files || []);
4641
+ sendJsonRpc(id, {
4642
+ content: [{ type: "text", text: JSON.stringify(detail, null, 2) }],
4643
+ });
4644
+ return;
4645
+ }
4646
+
4647
+ if (toolName === "nb_task_work") {
4648
+ const cfg = getLocalConfig();
4649
+ const resolvedId = resolveTaskIdentifier(args.taskId);
4650
+ const detail = await apiRequest(
4651
+ `/api/v1/extension/task-detail?projectId=${cfg.projectId}&taskId=${encodeURIComponent(resolvedId)}`,
4652
+ );
4653
+ const task = detail.task;
4654
+ saveLocalState({
4655
+ ...getLocalState(),
4656
+ activeTaskId: task.id,
4657
+ activeTaskTitle: task.title,
4658
+ startedAt: new Date().toISOString(),
4659
+ });
4660
+ await hydrateTaskAttachedFiles(cfg.projectId, detail.files || []);
4661
+ sendJsonRpc(id, {
4662
+ content: [
4663
+ {
4664
+ type: "text",
4665
+ text: JSON.stringify(
4666
+ {
4667
+ activeTaskId: task.id,
4668
+ taskNumber: task.taskNumber,
4669
+ title: task.title,
4670
+ description: task.description,
4671
+ status: "in_progress",
4672
+ subtasks: detail.subtasks || [],
4673
+ files: detail.files || [],
4674
+ },
4675
+ null,
4676
+ 2,
4677
+ ),
4678
+ },
4679
+ ],
4680
+ });
4681
+ return;
4682
+ }
4683
+
4684
+ if (toolName === "nb_task_check") {
4685
+ const cfg = getLocalConfig();
4686
+ const targetId = resolveTaskIdentifier(args.taskId || getLocalState()?.activeTaskId);
4687
+ const detail = await apiRequest(
4688
+ `/api/v1/extension/task-detail?projectId=${cfg.projectId}&taskId=${encodeURIComponent(targetId)}`,
4689
+ );
4690
+ const subtasks = detail.subtasks || [];
4691
+ const nums = new Set((args.subtaskNumbers || []).map(Number));
4692
+ const targetCompleted = !args.uncheck;
4693
+ for (const st of subtasks) {
4694
+ if (args.all || nums.has(st.index)) {
4695
+ if (Boolean(st.completed) !== targetCompleted) {
4696
+ await apiRequest("/api/v1/extension/task-update", {
4697
+ method: "PATCH",
4698
+ body: {
4699
+ kind: "subtask",
4700
+ projectId: cfg.projectId,
4701
+ taskId: detail.task.id,
4702
+ subtaskId: st.id,
4703
+ completed: targetCompleted,
4704
+ expectedUpdatedAt: new Date(st.updatedAt).toISOString(),
4705
+ },
4706
+ });
4707
+ st.completed = targetCompleted;
4708
+ }
4709
+ }
4710
+ }
4711
+ sendJsonRpc(id, {
4712
+ content: [{ type: "text", text: JSON.stringify({ taskId: detail.task.id, subtasks }, null, 2) }],
4713
+ });
4714
+ return;
4715
+ }
4716
+
4717
+ sendJsonRpc(id, null, { code: -32601, message: `Unknown tool: ${toolName}` });
4718
+ }
4719
+ } catch (err) {
4720
+ sendJsonRpc(id, null, {
4721
+ code: -32000,
4722
+ message: err instanceof Error ? err.message : String(err),
4723
+ });
4724
+ }
4725
+ });
4726
+ }
4727
+
4728
+ function printHelp() {
4729
+ console.log(`
4730
+ NetworkBase High-EQ CLI (v${CLI_VERSION})
4731
+
4732
+ Quick Start (One-Command Setup):
4733
+ npx @networkbase/cli init Authenticate (Browser or Token), link Workspace & Task
4734
+
4735
+ Usage:
4736
+ nb <command> [subcommand] [flags]
4737
+
4738
+ Core Commands:
4739
+ nb init [--workspace <id>] 3-step setup wizard + local mirror + auto-sync daemon
4740
+ nb sync [paths...] Single-permission universal sync (push edits + pull mirror + start daemon)
4741
+ nb status Show active account, server, workspace, and task context
4742
+ nb auth login [--web | --token] Sign in via Web Browser (/authorize) or Token (nb_pat_...)
4743
+ nb auth whoami Display active user, session, and workspace
4744
+ nb auth logout Revoke active session and clear credentials
4745
+ nb auth setup-git Configure Git HTTPS credential helper
4746
+ nb workspace list | switch List or switch active NetworkBase workspaces
4747
+ nb task [list] [--all | --mine] View project tasks, descriptions, subtasks & attached files
4748
+ nb task view <#number|id> Inspect task description, subtasks & mirror attached files
4749
+ nb task work <#number|id> Bind active task, transition to in_progress & mirror files
4750
+ nb task check [1 2 | --all] Toggle subtasks interactively (Space) or via CLI numbers
4751
+ nb task done [#number|id] Mark active or specified task as Done
4752
+ nb file ls | log | diff | lock Inspect workspace files, history, diffs, or CLI locks
4753
+ nb hook install Install local .git/hooks/pre-push secret scanner
4754
+ nb pull [paths...] Download remote workspace files to local directory
4755
+ nb watch [paths...] Live debounced auto-sync watcher (1-RTT fast-push on save)
4756
+ nb push [paths...] High-EQ Smart Push (SHA-256 diff + v1->v2 bump + task link)
4757
+ --deliverable Classify pushed files as Final Deliverable (#deliverable)
4758
+ --draft Classify pushed files as Working Draft (#editor_working)
4759
+ --reference Classify pushed files as Reference Material (#reference)
4760
+ --done Transition linked task to Done upon push
4761
+ --task <uuid> Link push to a specific task (or auto-infer from branch)
4762
+ -m, --message <msg> Commit / revision summary message
4763
+ --dry-run Run Pre-Push Analysis without uploading
4764
+ --json Output structured JSON for AI assistants
4765
+ nb mcp Start Model Context Protocol (MCP) server over stdio
4766
+ `);
4767
+ }
4768
+
4769
+ async function main() {
4770
+ const { positional, flags } = parseFlags(process.argv.slice(2));
4771
+ const [cmd, sub, ...rest] = positional;
4772
+
4773
+ if (cmd === "version" || flags.version || flags.v) {
4774
+ console.log(CLI_VERSION);
4775
+ return;
4776
+ }
4777
+
4778
+ if (cmd === "help" || flags.help || flags.h) {
4779
+ printHelp();
4780
+ return;
4781
+ }
4782
+
4783
+ if (!cmd) {
4784
+ if (process.stdin.isTTY && !flags.json) {
4785
+ try {
4786
+ await handleInteractiveHub(flags);
4787
+ } catch (err) {
4788
+ console.error(` ${STEP_ERR} ${c.red}${err instanceof Error ? err.message : String(err)}${c.reset}`);
4789
+ process.exitCode = 1;
4790
+ }
4791
+ return;
4792
+ }
4793
+ printHelp();
4794
+ return;
4795
+ }
4796
+
4797
+ try {
4798
+ switch (cmd) {
4799
+ case "auth":
4800
+ await handleAuth(sub, rest, flags);
4801
+ break;
4802
+ case "login":
4803
+ await handleAuth("login", [sub, ...rest].filter(Boolean), flags);
4804
+ break;
4805
+ case "logout":
4806
+ await handleAuth("logout", [], flags);
4807
+ break;
4808
+ case "whoami":
4809
+ case "status":
4810
+ await handleStatus(flags);
4811
+ break;
4812
+ case "init":
4813
+ case "setup":
4814
+ await handleInit([sub, ...rest].filter(Boolean), flags);
4815
+ break;
4816
+ case "sync":
4817
+ await handleSync([sub, ...rest].filter(Boolean), flags);
4818
+ break;
4819
+ case "workspace":
4820
+ case "ws":
4821
+ await handleWorkspace(sub, rest, flags);
4822
+ break;
4823
+ case "task":
4824
+ case "sprint":
4825
+ await handleTask(sub, rest, flags);
4826
+ break;
4827
+ case "file":
4828
+ await handleFile(sub, rest, flags);
4829
+ break;
4830
+ case "pull":
4831
+ await handlePull([sub, ...rest].filter(Boolean), flags);
4832
+ break;
4833
+ case "watch":
4834
+ await handleWatch([sub, ...rest].filter(Boolean), flags);
4835
+ break;
4836
+ case "push":
4837
+ await handlePush([sub, ...rest].filter(Boolean), flags);
4838
+ break;
4839
+ case "hook":
4840
+ if (sub === "install") await handleHookInstall(flags);
4841
+ else throw new Error("Usage: nb hook install");
4842
+ break;
4843
+ case "mcp":
4844
+ await startMcpServer();
4845
+ break;
4846
+ default:
4847
+ throw new Error(`Unknown command: ${cmd}. Run \`nb --help\` for available commands.`);
4848
+ }
4849
+ } catch (err) {
4850
+ if (flags.json) {
4851
+ process.stdout.write(
4852
+ JSON.stringify(
4853
+ {
4854
+ success: false,
4855
+ error: err instanceof Error ? err.message : String(err),
4856
+ errorCode: err.errorCode || "CLI_ERROR",
4857
+ },
4858
+ null,
4859
+ 2,
4860
+ ) + "\n",
4861
+ );
4862
+ } else {
4863
+ console.error(` ${STEP_ERR} ${c.red}${err instanceof Error ? err.message : String(err)}${c.reset}`);
4864
+ }
4865
+ process.exitCode = 1;
4866
+ }
4867
+ }
4868
+
4869
+ void main();