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