@networkbase/cli 2.1.1 → 2.1.3

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/bin/nb.mjs CHANGED
@@ -13,6 +13,20 @@ const { createOutput } = await import("../lib/print/out.mjs");
13
13
 
14
14
  const argv = process.argv.slice(2);
15
15
 
16
+ // A company proxy or certificates (C6, nb config set proxy|ca-file, or HTTPS_PROXY): start once more with them set.
17
+ {
18
+ const { readUserConfig } = await import("../lib/config.mjs");
19
+ const { networkEnv } = await import("../lib/network.mjs");
20
+ let userConfig = {};
21
+ try { userConfig = readUserConfig(process.env); } catch { /* unreadable config: carry on without */ }
22
+ const add = networkEnv(userConfig, process.env, process.versions.node);
23
+ if (add) {
24
+ const { spawnSync } = await import("node:child_process");
25
+ const again = spawnSync(process.execPath, process.argv.slice(1), { stdio: "inherit", env: { ...process.env, ...add } });
26
+ process.exit(again.status ?? 1);
27
+ }
28
+ }
29
+
16
30
  /** Errors before a command is known still honour --json. */
17
31
  const early = createOutput({ json: argv.includes("--json") || process.env.NB_JSON === "1", plain: argv.includes("--plain") });
18
32
 
@@ -45,7 +59,9 @@ try {
45
59
  }
46
60
  const { createContext } = await import("../lib/context.mjs");
47
61
  // nb prompt runs on every shell prompt: errors only, no notices.
48
- const ctx = createContext({ flags: spec.name === "prompt" ? { ...flags, quiet: true } : flags, positionals });
62
+ // push and pull plan their own dry run; for every other command the API client stops at the first write.
63
+ const ownDryRun = Boolean(spec.flags?.["dry-run"]);
64
+ const ctx = createContext({ flags: spec.name === "prompt" ? { ...flags, quiet: true } : { ...flags, ownDryRun }, positionals });
49
65
  if (alias) {
50
66
  const { remindOnce } = await import("../lib/print/remind.mjs");
51
67
  remindOnce(ctx, `alias:${alias.from}`, alias.shortcut ? `nb ${alias.from} is short for nb ${alias.to}` : `nb ${alias.from} is now nb ${alias.to} (the old name works until 3.0)`);
@@ -70,6 +86,13 @@ try {
70
86
  await (await import("../lib/print/notices.mjs")).afterCommand(ctx);
71
87
  } catch (error) {
72
88
  const cliError = toCliError(error);
89
+ // A dry run ends at the first change: that's its answer, not an error (C3).
90
+ if (cliError.code === "DRY_RUN") {
91
+ const d = /** @type {any} */ (cliError.details);
92
+ if (argv.includes("--json") || process.env.NB_JSON === "1") process.stdout.write(`${JSON.stringify({ ok: true, schema: "nb.dry-run/1", data: { wouldSend: d } })}\n`);
93
+ else process.stdout.write(`Dry run, nothing changed. Would ${d.method} ${d.path}${d.body ? `\n ${JSON.stringify(d.body).slice(0, 400)}` : ""}\n`);
94
+ process.exit(EXIT.ok);
95
+ }
73
96
  // A usage error's next step is the command's own help (C5).
74
97
  if (!cliError.hint && cliError.exitCode === EXIT.usage && commandName) cliError.hint = `See nb ${commandName} --help`;
75
98
  early.error(cliError);
package/lib/api.mjs CHANGED
@@ -26,11 +26,11 @@ const HINTS = /** @type {Record<string, string>} */ ({
26
26
  });
27
27
 
28
28
  /**
29
- * @param {{ origin: string, token: string | null, version: string, fetchImpl?: typeof fetch, onRetry?: (info: { attempt: number, waitMs: number, reason: string }) => void, confirmToken?: string | null, onUndo?: (u: { token: string, method: string, path: string, summary: string | null }) => void }} options
29
+ * @param {{ origin: string, token: string | null, version: string, fetchImpl?: typeof fetch, onRetry?: (info: { attempt: number, waitMs: number, reason: string }) => void, confirmToken?: string | null, onUndo?: (u: { token: string, method: string, path: string, summary: string | null }) => void, dryRun?: boolean }} options
30
30
  * confirmToken: the person's yes for a held agent change (sent as X-NB-Confirm); onUndo: called with every undo
31
31
  * token a write returns, so `nb undo` can use it (report A2.8, A2.9).
32
32
  */
33
- export function createApi({ origin, token, version, fetchImpl = fetch, onRetry, confirmToken = null, onUndo }) {
33
+ export function createApi({ origin, token, version, fetchImpl = fetch, onRetry, confirmToken = null, onUndo, dryRun = false }) {
34
34
  /**
35
35
  * @param {"GET" | "POST" | "PUT" | "PATCH" | "DELETE"} method
36
36
  * @param {string} path
@@ -40,6 +40,10 @@ export function createApi({ origin, token, version, fetchImpl = fetch, onRetry,
40
40
  if (options.auth !== false && !token) {
41
41
  throw new CliError("NOT_SIGNED_IN", `You're not signed in to ${new URL(origin).host}`, { hint: "Run nb login" });
42
42
  }
43
+ // --dry-run on every write command (C3): reads go ahead, the first change stops here and is shown instead.
44
+ if (dryRun && method !== "GET" && !path.startsWith("/api/v1/device/") && path !== "/api/v1/extension/auth-code") {
45
+ throw new CliError("DRY_RUN", `Dry run: would ${method} ${path}`, { details: { method, path, body: options.body ?? null } });
46
+ }
43
47
  const url = new URL(path, origin);
44
48
  for (const [k, v] of Object.entries(options.query ?? {})) if (v !== undefined && v !== null && v !== "") url.searchParams.set(k, String(v));
45
49
  const body = options.body === undefined ? undefined : JSON.stringify(options.body);
@@ -148,6 +152,8 @@ export function createApi({ origin, token, version, fetchImpl = fetch, onRetry,
148
152
  post: (path, body, o) => request("POST", path, { ...o, body }),
149
153
  /** @param {string} path @param {unknown} body @param {Parameters<typeof request>[2]} [o] */
150
154
  patch: (path, body, o) => request("PATCH", path, { ...o, body }),
155
+ /** @param {string} path @param {unknown} body @param {Parameters<typeof request>[2]} [o] */
156
+ put: (path, body, o) => request("PUT", path, { ...o, body }),
151
157
  };
152
158
  }
153
159
 
@@ -189,13 +189,48 @@ export async function reviewView(ctx) {
189
189
  ], { page: true });
190
190
  }
191
191
 
192
- /** @param {Context} ctx @param {"approve" | "return"} decision */
192
+ /**
193
+ * Approve or return one hand-in, or several at once (`nb review approve 3 5 8`, C4). Each is its own decision, so one
194
+ * that fails (changed meanwhile) is reported and the rest still go through.
195
+ * @param {Context} ctx @param {"approve" | "return"} decision
196
+ */
193
197
  async function decide(ctx, decision) {
194
- const row = await rowByRef(ctx, ctx.positionals[0]);
198
+ const refs = ctx.positionals.length ? ctx.positionals : [undefined];
195
199
  const reason = String(ctx.flags.message ?? "").trim();
196
200
  if (decision === "return" && !reason) throw usage('Say what to fix: nb review return <ref> -m "…"');
197
- await ctx.api.post(`/api/v1/reviews/${encodeURIComponent(row.copyId)}`, decision === "approve" ? { decision } : { decision, reason, ...(ctx.flags["fix-by"] ? { fixBy: new Date(String(ctx.flags["fix-by"])).toISOString() } : {}) });
198
- ctx.out.result(`nb.review.${decision}/1`, { copyId: row.copyId }, () => `${ctx.out.c.success(ctx.out.sym.done)} ${decision === "approve" ? "Approved" : "Returned"} ${safe(row.who)}’s ${safe(row.title)}`);
201
+ // Read the queue once: numbers refer to it as listed, before any decision moves rows.
202
+ const rows = await Promise.all(refs.map((ref) => rowByRef(ctx, /** @type {string} */ (ref))));
203
+ /** @type {Array<{ copyId: string, who: string, title: string, ok: boolean, error?: string }>} */
204
+ const done = [];
205
+ for (const row of rows) {
206
+ try {
207
+ await ctx.api.post(`/api/v1/reviews/${encodeURIComponent(row.copyId)}`, decision === "approve" ? { decision } : { decision, reason, ...(ctx.flags["fix-by"] ? { fixBy: new Date(String(ctx.flags["fix-by"])).toISOString() } : {}) });
208
+ done.push({ copyId: row.copyId, who: row.who, title: row.title, ok: true });
209
+ } catch (error) {
210
+ if (rows.length === 1) throw error;
211
+ done.push({ copyId: row.copyId, who: row.who, title: row.title, ok: false, error: error instanceof Error ? error.message : String(error) });
212
+ }
213
+ }
214
+ const verb = decision === "approve" ? "Approved" : "Returned";
215
+ ctx.out.result(`nb.review.${decision}/1`, rows.length === 1 ? { copyId: rows[0].copyId } : { results: done }, () => done.map((r) => (r.ok ? `${ctx.out.c.success(ctx.out.sym.done)} ${verb} ${safe(r.who)}’s ${safe(r.title)}` : ctx.out.c.warning(` ${safe(r.who)}’s ${safe(r.title)}: ${safe(r.error ?? "")}`))));
216
+ return done.some((r) => !r.ok) ? 1 : 0;
217
+ }
218
+
219
+ /** What changed since the last hand-in (C4): files added, removed and changed between the latest two. @param {Context} ctx */
220
+ export async function reviewDiff(ctx) {
221
+ const row = await rowByRef(ctx, ctx.positionals[0]);
222
+ const versions = [...(row.versions ?? [])].sort((a, b) => a.version - b.version);
223
+ const [before, after] = versions.slice(-2);
224
+ // ponytail: hand-ins record which files, not which version of each, so changes are by size; a line diff needs the
225
+ // hand-in to keep each file's version number.
226
+ const files = !before || !after ? [] : [
227
+ ...after.files.filter((/** @type {any} */ f) => !before.files.some((/** @type {any} */ b) => b.nodeId === f.nodeId)).map((/** @type {any} */ f) => ({ name: f.name, change: "added" })),
228
+ ...before.files.filter((/** @type {any} */ b) => !after.files.some((/** @type {any} */ f) => f.nodeId === b.nodeId)).map((/** @type {any} */ b) => ({ name: b.name, change: "removed" })),
229
+ ...after.files.filter((/** @type {any} */ f) => before.files.some((/** @type {any} */ b) => b.nodeId === f.nodeId && b.size !== f.size)).map((/** @type {any} */ f) => ({ name: f.name, change: "changed" })),
230
+ ];
231
+ ctx.out.result("nb.review.diff/1", { from: before?.version ?? null, to: after?.version ?? null, files }, (d) => (d.from === null
232
+ ? `${safe(row.who)}’s ${safe(row.title)} has one hand-in so far · nb review view ${ctx.positionals[0]}`
233
+ : [`${safe(row.who)}’s ${safe(row.title)}: v${d.from} → v${d.to}`, ...(d.files.length ? d.files.map((/** @type {any} */ f) => ` ${f.change === "added" ? ctx.out.c.success("+") : f.change === "removed" ? ctx.out.c.danger("-") : ctx.out.c.accent("~")} ${safe(f.name)} ${ctx.out.c.muted(f.change)}`) : [ctx.out.c.muted(" the same files, the same sizes")])]));
199
234
  }
200
235
  /** @param {Context} ctx */
201
236
  export const reviewApprove = (ctx) => decide(ctx, "approve");
@@ -1,9 +1,9 @@
1
1
  // workspace view, activity, sprint list|view, update post, file history|move|rename|delete|attach|detach
2
2
  // (report §17.4, A2.5, A8.7, D25).
3
3
  import { CliError, EXIT, usage } from "../errors.mjs";
4
- import { safe } from "../print/style.mjs";
4
+ import { commentText, safe } from "../print/style.mjs";
5
5
  import { confirm } from "../tui/ask.mjs";
6
- import { formatDate, resolveTask, taskRef } from "./tasks.mjs";
6
+ import { formatDate, formatWhen, resolveTask, taskRef } from "./tasks.mjs";
7
7
 
8
8
  /** @typedef {import("../context.mjs").Context} Context */
9
9
 
@@ -90,7 +90,7 @@ export async function updatePost(ctx) {
90
90
  const remote = (p) => `/${p.replace(/^\/+/, "")}`;
91
91
 
92
92
  /** @param {Context} ctx @param {string} p */
93
- async function nodeOf(ctx, p) {
93
+ export async function nodeOf(ctx, p) {
94
94
  return /** @type {any} */ (await ctx.api.get("/api/v1/extension/file", { query: { projectId: ctx.requireWorkspace(), path: remote(p), transfer: "metadata" } }).catch((error) => {
95
95
  if (error instanceof CliError && error.status === 404) throw new CliError("NOT_FOUND", `No file ${remote(p)} in this workspace`);
96
96
  throw error;
@@ -160,3 +160,139 @@ async function attach(ctx, detach) {
160
160
  export const fileAttach = (ctx) => attach(ctx, false);
161
161
  /** @param {Context} ctx */
162
162
  export const fileDetach = (ctx) => attach(ctx, true);
163
+
164
+ // ───────────────────────────────── trash, restore, folders, copies, locks (report C3, M4b)
165
+
166
+ /** What's in the workspace Trash, with the days left before it's gone. @param {Context} ctx */
167
+ export async function fileTrash(ctx) {
168
+ const { items } = /** @type {any} */ (await ctx.api.get(`/api/v1/workspaces/${encodeURIComponent(ctx.requireWorkspace())}/files/trash`, { query: { q: ctx.positionals[0] } }));
169
+ ctx.out.result("nb.file.trash/1", { items }, (d) => (d.items.length
170
+ ? [...ctx.out.table([
171
+ { title: "Path", value: (i) => safe(i.path), flex: true, path: true },
172
+ { title: "Deleted", value: (i) => `${String(i.deletedAt).slice(0, 10)}${i.deletedBy ? ` by @${safe(i.deletedBy)}` : ""}`, optional: true },
173
+ { title: "Days left", value: (i) => String(i.daysLeft), align: "right" },
174
+ ], d.items), ctx.out.c.muted(" nb file restore <path> brings one back")]
175
+ : "The Trash is empty"));
176
+ }
177
+
178
+ /** @param {Context} ctx */
179
+ export async function fileRestore(ctx) {
180
+ const p = ctx.positionals[0];
181
+ if (!p) throw usage("nb file restore <path>", "See what's there: nb file trash");
182
+ const want = p.startsWith("/") ? p : `/${p}`;
183
+ const { items } = /** @type {any} */ (await ctx.api.get(`/api/v1/workspaces/${encodeURIComponent(ctx.requireWorkspace())}/files/trash`, { query: { q: want.split("/").pop() } }));
184
+ const hit = items.find((/** @type {any} */ i) => i.path === want) ?? (items.length === 1 ? items[0] : null);
185
+ if (!hit) throw new CliError("NOT_FOUND", `${want} isn't in the Trash`, { hint: "nb file trash" });
186
+ await ctx.api.post("/api/v1/extension/file-operation", { kind: "restore", projectId: ctx.requireWorkspace(), nodeId: hit.nodeId });
187
+ ctx.out.result("nb.file.restore/1", { path: hit.path }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} Restored ${safe(d.path)} · nb pull gets it here`);
188
+ }
189
+
190
+ /** @param {Context} ctx */
191
+ export async function fileMkdir(ctx) {
192
+ const p = ctx.positionals[0];
193
+ if (!p) throw usage("nb file mkdir <folder>");
194
+ const clean = remote(p.replace(/\/+$/, ""));
195
+ const parentPath = clean.slice(0, clean.lastIndexOf("/")) || "/";
196
+ const parentId = parentPath === "/" ? null : (await nodeOf(ctx, parentPath)).nodeId ?? null;
197
+ const { folder } = /** @type {any} */ (await ctx.api.post("/api/v1/extension/file-operation", { kind: "mkdir", projectId: ctx.requireWorkspace(), parentId, name: clean.slice(clean.lastIndexOf("/") + 1) }));
198
+ ctx.out.result("nb.file.mkdir/1", { path: folder.path }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} Made ${safe(d.path)}/`);
199
+ }
200
+
201
+ /** A copy is a new file with the same content, placed like a push (every check applies). @param {Context} ctx */
202
+ export async function fileCopy(ctx) {
203
+ const [from, to] = ctx.positionals;
204
+ if (!from || !to) throw usage("nb file copy <file> <to>", "Like nb file copy report.md drafts/report-v2.md");
205
+ const projectId = ctx.requireWorkspace();
206
+ const source = remote(from);
207
+ const target = to.endsWith("/") ? `${remote(to).replace(/\/+$/, "")}/${source.split("/").pop()}` : remote(to);
208
+ const res = await ctx.api.download("/api/v1/extension/file", { projectId, path: source, transfer: "raw" });
209
+ const bytes = Buffer.from(await res.arrayBuffer());
210
+ const crypto = await import("node:crypto");
211
+ const { mimeFor } = await import("../sync/transfer.mjs");
212
+ const placed = /** @type {any} */ (await ctx.api.post("/api/v1/files/place", { projectId, onSameName: "keep-both", message: `Copy of ${source}`, files: [{ path: target, contentHash: crypto.createHash("sha256").update(bytes).digest("hex"), size: bytes.length, mimeType: mimeFor(target), contentBase64: bytes.toString("base64") }] }));
213
+ const out = placed.files?.[0];
214
+ ctx.out.result("nb.file.copy/1", { from: source, to: out?.path ?? target }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} Copied ${safe(d.from)} to ${safe(d.to)}`);
215
+ }
216
+
217
+ /**
218
+ * `nb file lock <file> [--for 30m]` (C3): the same lease as the app's editor, so teammates see you're editing. It
219
+ * holds until Ctrl+C (or --for), renewing every minute, and lets go when it ends.
220
+ * @param {Context} ctx
221
+ */
222
+ export async function fileLock(ctx) {
223
+ const p = ctx.positionals[0];
224
+ if (!p) throw usage("nb file lock <path> [--for 30m]");
225
+ const projectId = ctx.requireWorkspace();
226
+ const node = await nodeOf(ctx, p);
227
+ const nodeId = node.nodeId ?? node.id;
228
+ const crypto = await import("node:crypto");
229
+ const sessionId = crypto.randomUUID();
230
+ const forText = ctx.flags.for ? String(ctx.flags.for) : null;
231
+ const m = forText ? /^(\d+)\s*(s|m|h)$/.exec(forText) : null;
232
+ if (forText && !m) throw usage("--for takes 30s, 10m or 2h");
233
+ const holdMs = m ? Number(m[1]) * (m[2] === "h" ? 3_600_000 : m[2] === "m" ? 60_000 : 1000) : Infinity;
234
+ const lease = /** @type {any} */ (await ctx.api.post(`/api/v1/files/${nodeId}/lock`, { projectId, sessionId, ttlSeconds: 120 }));
235
+ const creds = () => ({ projectId, sessionId, leaseId: lease.leaseId ?? lease.id, fencingToken: lease.fencingToken });
236
+ ctx.out.note(`${ctx.out.c.success(ctx.out.sym.done)} Locked ${safe(node.path ?? p)}: teammates see you're editing it${Number.isFinite(holdMs) ? ` for ${forText}` : " · Ctrl+C to let go"}`);
237
+ const ends = Date.now() + holdMs;
238
+ let stop = false;
239
+ process.once("SIGINT", () => { stop = true; });
240
+ while (!stop && Date.now() < ends) {
241
+ await new Promise((r) => setTimeout(r, Math.min(1000, Math.max(0, ends - Date.now()))));
242
+ if (!stop && Date.now() - (lease.renewedAt ?? lease.acquiredAt ?? 0) > 60_000) {
243
+ const renewed = /** @type {any} */ (await ctx.api.post(`/api/v1/files/${nodeId}/lock-renew`, { ...creds(), ttlSeconds: 120 }).catch(() => null));
244
+ lease.renewedAt = Date.now();
245
+ if (renewed?.fencingToken) lease.fencingToken = renewed.fencingToken;
246
+ }
247
+ }
248
+ await ctx.api.request("DELETE", `/api/v1/files/${nodeId}/lock`, { body: creds() }).catch(() => undefined);
249
+ ctx.out.result("nb.file.lock/1", { path: node.path ?? p, released: true }, (d) => `Let go of ${safe(d.path)}`);
250
+ }
251
+
252
+ // ───────────────────────────────── updates (report C4, M4b)
253
+
254
+ /** The workspace's feed. @param {Context} ctx */
255
+ export async function updateList(ctx) {
256
+ const data = /** @type {any} */ (await ctx.api.get(`/api/v1/workspaces/${encodeURIComponent(ctx.requireWorkspace())}/updates`));
257
+ const updates = (data.updates ?? []).map((/** @type {any} */ u, /** @type {number} */ i) => ({ n: i + 1, id: u.id, by: u.authorUsername ?? u.author?.username ?? u.authorName ?? u.author?.name ?? null, at: u.createdAt, text: String(u.content ?? u.body ?? ""), likes: u.likeCount ?? u.likes ?? 0, comments: u.commentCount ?? u.comments ?? 0, liked: Boolean(u.likedByViewer ?? u.liked) }));
258
+ ctx.out.result("nb.update.list/1", { updates }, (d) => (d.updates.length
259
+ ? d.updates.flatMap((/** @type {any} */ u) => [`${String(u.n).padStart(2)} ${u.by ? `@${safe(u.by)}` : "someone"} ${ctx.out.c.muted(formatWhen(u.at))} ${ctx.out.c.muted(`♥ ${u.likes} · ${u.comments} comments`)}`, ` ${commentText(u.text).replace(/\s+/g, " ").slice(0, 160)}`])
260
+ .concat(ctx.out.c.muted(" nb update like <n> · nb update comment <n> -m text · nb update view <n>"))
261
+ : "No updates yet · nb update post -m \"…\""));
262
+ }
263
+
264
+ /** @param {Context} ctx */
265
+ async function updateByRef(ctx) {
266
+ const ref = ctx.positionals[0];
267
+ if (!ref) throw usage("Which update?", "The numbers are in nb update list");
268
+ const data = /** @type {any} */ (await ctx.api.get(`/api/v1/workspaces/${encodeURIComponent(ctx.requireWorkspace())}/updates`));
269
+ const list = data.updates ?? [];
270
+ const hit = /^\d+$/.test(ref) ? list[Number(ref) - 1] : list.find((/** @type {any} */ u) => String(u.id).startsWith(ref));
271
+ if (!hit) throw new CliError("NOT_FOUND", `No update ${ref}`, { hint: "nb update list" });
272
+ return hit;
273
+ }
274
+
275
+ /** One update and its comments. @param {Context} ctx */
276
+ export async function updateView(ctx) {
277
+ const u = await updateByRef(ctx);
278
+ const data = /** @type {any} */ (await ctx.api.get(`/api/v1/workspaces/${encodeURIComponent(ctx.requireWorkspace())}/updates/${u.id}`));
279
+ const comments = (data.comments ?? []).map((/** @type {any} */ c) => ({ by: c.authorUsername ?? c.author?.username ?? c.authorName ?? null, text: String(c.content ?? c.body ?? "") }));
280
+ ctx.out.result("nb.update.view/1", { id: u.id, text: String(u.content ?? u.body ?? ""), comments }, (d) => [commentText(d.text), "", ...(d.comments.length ? d.comments.map((/** @type {any} */ c) => ` ${c.by ? `@${safe(c.by)}` : "someone"}: ${commentText(c.text)}`) : [ctx.out.c.muted(" No comments yet")])]);
281
+ }
282
+
283
+ /** Like (or unlike) an update. @param {Context} ctx */
284
+ export async function updateLike(ctx) {
285
+ const u = await updateByRef(ctx);
286
+ const res = /** @type {any} */ (await ctx.api.post(`/api/v1/workspaces/${encodeURIComponent(ctx.requireWorkspace())}/updates/${u.id}`, { kind: "like" }));
287
+ const liked = res?.liked ?? res?.viewerHasLiked ?? !u.likedByViewer;
288
+ ctx.out.result("nb.update.like/1", { id: u.id, liked: Boolean(liked) }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} ${d.liked ? "Liked" : "Unliked"} the update`);
289
+ }
290
+
291
+ /** Comment on an update (everyone in the workspace sees it). @param {Context} ctx */
292
+ export async function updateComment(ctx) {
293
+ const u = await updateByRef(ctx);
294
+ const text = String(ctx.flags.message ?? ctx.positionals.slice(1).join(" ")).trim();
295
+ if (!text) throw usage('nb update comment <n> -m "text"');
296
+ await ctx.api.post(`/api/v1/workspaces/${encodeURIComponent(ctx.requireWorkspace())}/updates/${u.id}`, { kind: "comment", text });
297
+ ctx.out.result("nb.update.comment/1", { id: u.id }, () => `${ctx.out.c.success(ctx.out.sym.done)} Commented on the update`);
298
+ }
@@ -0,0 +1,72 @@
1
+ // Tab completion with real names (report C8): task numbers with their titles, member names and file paths, from a
2
+ // small cache per workspace that a background `nb complete --refresh` keeps no older than 10 minutes. Completing
3
+ // never waits on the network: it answers from the cache, even an old one, and refreshes behind.
4
+ import { spawn } from "node:child_process";
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+
8
+ import { globalDir, readJson, writeAtomic } from "../config.mjs";
9
+
10
+ /** @typedef {import("../context.mjs").Context} Context */
11
+ /** @typedef {{ at: number, tasks: Array<[number, string]>, members: string[], files: string[] }} CompleteCache */
12
+
13
+ export const FRESH_MS = 10 * 60_000;
14
+
15
+ /** Which kind of name each command's arguments take, for the shell scripts. */
16
+ export const ARG_KINDS = /** @type {Record<string, "tasks" | "members" | "files">} */ ({
17
+ "task start": "tasks", "task view": "tasks", "task done": "tasks", "task move": "tasks", "task edit": "tasks", "task assign": "tasks",
18
+ "task watch": "tasks", "task star": "tasks", "task remind": "tasks", "task review": "tasks", "task delete": "tasks", "task open": "tasks",
19
+ "member role": "members", "member remove": "members", "member invite": "members",
20
+ push: "files", pull: "files", diff: "files", edit: "files",
21
+ "file history": "files", "file use": "files", "file view": "files", "file star": "files", "file lock": "files",
22
+ "file copy": "files", "file move": "files", "file rename": "files", "file delete": "files",
23
+ });
24
+
25
+ /** @param {Context} ctx @param {string} workspaceId */
26
+ const cacheFile = (ctx, workspaceId) => path.join(globalDir(ctx.env), "complete", `${workspaceId.replace(/[^a-z0-9-]/gi, "")}.json`);
27
+
28
+ /** Fetches the names and writes the cache. @param {Context} ctx @param {string} workspaceId */
29
+ async function refresh(ctx, workspaceId) {
30
+ const [tasks, members, manifest] = await Promise.all([
31
+ ctx.api.get("/api/v1/extension/workspace-tasks", { query: { projectId: workspaceId, scope: "all", open: "1", limit: "100" } }).then((/** @type {any} */ r) => r.tasks, () => []),
32
+ ctx.api.get(`/api/v1/workspaces/${encodeURIComponent(workspaceId)}/members`).then((/** @type {any} */ r) => r.members, () => []),
33
+ ctx.api.get(`/api/v1/workspaces/${encodeURIComponent(workspaceId)}/manifest`).then((/** @type {any} */ r) => r.files, () => []),
34
+ ]);
35
+ /** @type {CompleteCache} */
36
+ const cache = {
37
+ at: Date.now(),
38
+ tasks: tasks.map((/** @type {any} */ t) => [t.taskNumber, String(t.title).slice(0, 60)]),
39
+ members: members.map((/** @type {any} */ m) => m.username).filter(Boolean).slice(0, 200),
40
+ files: manifest.map((/** @type {any} */ f) => String(f.path).replace(/^\//, "")).slice(0, 2000),
41
+ };
42
+ const file = cacheFile(ctx, workspaceId);
43
+ fs.mkdirSync(path.dirname(file), { recursive: true });
44
+ writeAtomic(file, JSON.stringify(cache));
45
+ return cache;
46
+ }
47
+
48
+ /**
49
+ * `nb complete tasks|members|files [prefix]`: one candidate per line, `value<TAB>description` for tasks. Hidden; the
50
+ * shell scripts call it. `--refresh` updates the cache now.
51
+ * @param {Context} ctx
52
+ */
53
+ export async function complete(ctx) {
54
+ const workspaceId = ctx.project?.workspaceId ?? (typeof ctx.flags.workspace === "string" ? ctx.flags.workspace : null);
55
+ if (!workspaceId || !ctx.profile.token) return 0;
56
+ if (ctx.flags.refresh) { await refresh(ctx, workspaceId); return 0; }
57
+ /** @type {CompleteCache | null} */
58
+ let cache = null;
59
+ try { cache = readJson(cacheFile(ctx, workspaceId)); } catch { cache = null; }
60
+ if (!cache || Date.now() - cache.at > FRESH_MS) {
61
+ // Behind the shell's back, so the Tab press doesn't wait.
62
+ spawn(process.execPath, [process.argv[1] ?? "", "complete", "--refresh"], { cwd: ctx.cwd, detached: true, stdio: "ignore", env: ctx.env }).unref();
63
+ }
64
+ if (!cache) return 0;
65
+ const [kind, prefix = ""] = ctx.positionals;
66
+ const lines = kind === "tasks" ? cache.tasks.map(([n, title]) => `${n}\t${title}`)
67
+ : kind === "members" ? cache.members.map((m) => `@${m}`)
68
+ : kind === "files" ? cache.files
69
+ : [];
70
+ ctx.out.raw(lines.filter((l) => l.startsWith(prefix)).join("\n"));
71
+ return 0;
72
+ }
@@ -7,11 +7,11 @@ import path from "node:path";
7
7
 
8
8
  import { readUserConfig } from "../config.mjs";
9
9
  import { CliError, EXIT, usage } from "../errors.mjs";
10
- import { safe } from "../print/style.mjs";
10
+ import { commentText, safe } from "../print/style.mjs";
11
11
  import { unifiedDiff } from "../sync/diff.mjs";
12
12
  import { fetchManifest } from "../sync/transfer.mjs";
13
13
  import { confirm } from "../tui/ask.mjs";
14
- import { resolveTask } from "./tasks.mjs";
14
+ import { formatWhen, resolveTask } from "./tasks.mjs";
15
15
 
16
16
  /** @typedef {import("../context.mjs").Context} Context */
17
17
 
@@ -127,9 +127,35 @@ export async function workspaceList(ctx) {
127
127
  /** @param {Context} ctx */
128
128
  export async function search(ctx) {
129
129
  const q = ctx.positionals.join(" ").trim();
130
- if (!q) throw usage('nb search "<text>"');
131
- const res = /** @type {any} */ (await ctx.api.get("/api/v1/extension/search", { query: { projectId: ctx.requireWorkspace(), q, kind: "file" } }));
132
- ctx.out.result("nb.search/1", { query: q, files: res.files.map((/** @type {any} */ f) => ({ path: f.path, version: f.currentVersion })) }, (/** @type {any} */ d) => (d.files.length ? d.files.map((/** @type {any} */ f) => ` ${safe(f.path)} ${ctx.out.c.muted(`v${f.version}`)}`) : `Nothing named like "${safe(q)}"`));
130
+ if (!q) throw usage('nb search "<text>" [--in tasks,files,comments,docs,people]');
131
+ // Beyond files (C2): tasks, comments, docs and people from the workspace search, files from the file search.
132
+ const kinds = String(ctx.flags.in ?? "files,tasks,comments,docs,people").split(",").map((k) => k.trim()).filter(Boolean);
133
+ const bad = kinds.find((k) => !["files", "tasks", "comments", "docs", "people"].includes(k));
134
+ if (bad) throw usage(`--in ${bad}: use tasks, files, comments, docs or people`);
135
+ const others = kinds.filter((k) => k !== "files");
136
+ const workspaceId = ctx.requireWorkspace();
137
+ const [files, rest] = await Promise.all([
138
+ kinds.includes("files") ? ctx.api.get("/api/v1/extension/search", { query: { projectId: workspaceId, q, kind: "file" } }).then((/** @type {any} */ r) => r.files) : [],
139
+ others.length && q.length >= 2 ? ctx.api.get(`/api/v1/workspaces/${encodeURIComponent(workspaceId)}/search`, { query: { q, in: others.join(",") } }) : {},
140
+ ]);
141
+ const r = /** @type {any} */ (rest);
142
+ const data = {
143
+ query: q,
144
+ files: /** @type {any[]} */ (files).map((f) => ({ path: f.path, version: f.currentVersion })),
145
+ tasks: r.tasks ?? [], comments: r.comments ?? [], docs: r.docs ?? [], people: r.people ?? [],
146
+ };
147
+ const { c } = ctx.out;
148
+ ctx.out.result("nb.search/1", data, (d) => {
149
+ const section = (/** @type {string} */ title, /** @type {any[]} */ items, /** @type {(x: any) => string} */ line) => (items.length ? [c.bold(title), ...items.map((x) => ` ${line(x)}`), ""] : []);
150
+ const lines = [
151
+ ...section("Tasks", d.tasks, (t) => `#${t.number} ${safe(t.title)} ${c.muted(t.status)}`),
152
+ ...section("Files", d.files, (f) => `${safe(f.path)} ${c.muted(`v${f.version}`)}`),
153
+ ...section("Comments", d.comments, (m) => `#${m.number} ${m.by ? `@${safe(m.by)}` : "someone"}: ${commentText(m.text).replace(/\s+/g, " ").slice(0, 100)}`),
154
+ ...section("Docs", d.docs, (x) => `${safe(x.title)} ${c.muted(`nb doc view ${x.slug}`)}`),
155
+ ...section("People", d.people, (p) => `@${safe(p.username ?? "")} ${safe(p.name ?? "")} ${c.muted(p.role)}`),
156
+ ];
157
+ return lines.length ? lines.slice(0, -1) : `Nothing matches "${safe(q)}"`;
158
+ });
133
159
  }
134
160
 
135
161
  // ───────────────────────────────── file list / view
@@ -137,6 +163,7 @@ export async function search(ctx) {
137
163
  /** @param {Context} ctx */
138
164
  export async function fileList(ctx) {
139
165
  const workspaceId = ctx.requireWorkspace();
166
+ if (ctx.flags.starred) return myFiles(ctx, "starred");
140
167
  if (ctx.flags.task) {
141
168
  const task = await resolveTask(ctx, String(ctx.flags.task));
142
169
  const files = /** @type {any[]} */ (task.files ?? []).map((f) => ({ path: f.path ?? f.name, as: f.role === "deliverable" ? "final" : f.role === "working" ? "draft" : f.role ?? "draft", version: f.currentVersion ?? null, size: f.size ?? null }));
@@ -149,6 +176,28 @@ export async function fileList(ctx) {
149
176
  d.files.length ? ctx.out.table([{ title: "Path", value: (f) => safe(f.path), flex: true, path: true }, { title: "Version", value: (f) => `v${f.version}`, align: "right" }, { title: "Size", value: (f) => formatBytes(f.size), align: "right" }], d.files) : "No files");
150
177
  }
151
178
 
179
+ /** Your starred files, or the ones you changed lately (C3, 0087). @param {Context} ctx @param {"starred" | "recent"} kind */
180
+ async function myFiles(ctx, kind) {
181
+ const { files } = /** @type {any} */ (await ctx.api.get(`/api/v1/workspaces/${encodeURIComponent(ctx.requireWorkspace())}/files/mine`, { query: { kind } }));
182
+ ctx.out.result(`nb.file.${kind}/1`, { files: files.map((/** @type {any} */ f) => ({ path: f.path, version: f.currentVersion, size: f.size, at: f.at })) }, (d) =>
183
+ d.files.length
184
+ ? ctx.out.table([{ title: "Path", value: (f) => safe(f.path), flex: true, path: true }, { title: kind === "recent" ? "Changed" : "Version", value: (f) => (kind === "recent" ? formatWhen(f.at) : f.version ? `v${f.version}` : ""), align: "right" }], d.files)
185
+ : kind === "starred" ? "No starred files · nb file star <path>" : "No files you changed in the last 30 days");
186
+ }
187
+ /** @param {Context} ctx */
188
+ export const fileRecent = (ctx) => myFiles(ctx, "recent");
189
+
190
+ /** @param {Context} ctx */
191
+ export async function fileStar(ctx) {
192
+ const p = ctx.positionals[0];
193
+ if (!p) throw usage("nb file star <path> [--off]");
194
+ const { nodeOf } = await import("./browse.mjs");
195
+ const node = await nodeOf(ctx, p);
196
+ const on = !ctx.flags.off;
197
+ await ctx.api.put(`/api/v1/workspaces/${encodeURIComponent(ctx.requireWorkspace())}/files/${node.nodeId ?? node.id}/star`, { starred: on });
198
+ ctx.out.result("nb.file.star/1", { path: node.path ?? p, starred: on }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} ${on ? "Starred" : "Unstarred"} ${safe(d.path)}${on ? " · the Files tab shows it too" : ""}`);
199
+ }
200
+
152
201
  /** @param {number} bytes */
153
202
  export const formatBytes = (bytes) => (bytes < 1024 ? `${bytes} B` : bytes < 1024 * 1024 ? `${(bytes / 1024).toFixed(1)} KB` : `${(bytes / 1024 / 1024).toFixed(1)} MB`);
154
203
 
@@ -182,3 +231,92 @@ export async function memberList(ctx) {
182
231
  ? [...ctx.out.table([{ title: "Member", value: (m) => (m.username ? `@${safe(m.username)}` : ""), flex: true }, { title: "Name", value: (m) => safe(m.name ?? "") }, { title: "Role", value: (m) => m.role }], d.members), ...(d.members.length >= 10 ? [ctx.out.c.muted(" First 10 shown: add a name to narrow it")] : [])]
183
232
  : `No members match "${safe(q)}"`);
184
233
  }
234
+
235
+ // ───────────────────────────────── members (report C4, M4b): owner and admins change them; your own sign-in only
236
+
237
+ /** @param {Context} ctx @param {"POST" | "PATCH" | "DELETE"} method @param {Record<string, unknown>} body */
238
+ const members = (ctx, method, body) => ctx.api.request(method, `/api/v1/workspaces/${encodeURIComponent(ctx.requireWorkspace())}/members`, { body });
239
+
240
+ /** `nb member invite @sam --role "Frontend developer"`: workspace invitations are for one of its open roles. @param {Context} ctx */
241
+ export async function memberInvite(ctx) {
242
+ const who = ctx.positionals[0];
243
+ if (!who || !ctx.flags.role) throw usage('nb member invite @username --role "<open role>"', "The open roles are on the workspace's Members page");
244
+ const res = /** @type {any} */ (await members(ctx, "POST", { username: who.replace(/^@/, ""), role: String(ctx.flags.role), ...(ctx.flags.message ? { note: String(ctx.flags.message) } : {}) }));
245
+ ctx.out.result("nb.member.invite/1", res, (d) => `${ctx.out.c.success(ctx.out.sym.done)} Invited ${safe(d.invited)} as ${safe(d.role)}; they accept in NetworkBase`);
246
+ }
247
+
248
+ /** `nb member role @sam admin` @param {Context} ctx */
249
+ export async function memberRole(ctx) {
250
+ const [who, role] = ctx.positionals;
251
+ if (!who || !["admin", "member", "viewer"].includes(String(role))) throw usage("nb member role @username admin|member|viewer");
252
+ await members(ctx, "PATCH", { username: who.replace(/^@/, ""), role });
253
+ ctx.out.result("nb.member.role/1", { username: who.replace(/^@/, ""), role }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} @${safe(d.username)} is now ${d.role}`);
254
+ }
255
+
256
+ /** `nb member remove @sam`: their open tasks become unassigned (asks first). @param {Context} ctx */
257
+ export async function memberRemove(ctx) {
258
+ const who = ctx.positionals[0];
259
+ if (!who) throw usage("nb member remove @username");
260
+ const { confirm } = await import("../tui/ask.mjs");
261
+ if (!(await confirm(ctx, { key: "remove", question: `Remove ${who.startsWith("@") ? who : `@${who}`} from this workspace? Their open tasks become unassigned.`, yesLabel: "Remove", defaultYes: false }))) return EXIT.cancelled;
262
+ await members(ctx, "DELETE", { username: who.replace(/^@/, "") });
263
+ ctx.out.result("nb.member.remove/1", { username: who.replace(/^@/, "") }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} Removed @${safe(d.username)}`);
264
+ }
265
+
266
+ /** `nb workspace leave` (the plain leave): your open tasks become unassigned; the owner can't leave. @param {Context} ctx */
267
+ export async function workspaceLeave(ctx) {
268
+ const { confirm } = await import("../tui/ask.mjs");
269
+ if (!(await confirm(ctx, { key: "leave", question: "Leave this workspace? Your open tasks become unassigned, and you'll need a new invitation to come back.", yesLabel: "Leave", defaultYes: false }))) return EXIT.cancelled;
270
+ await members(ctx, "DELETE", { leave: true });
271
+ ctx.out.result("nb.workspace.leave/1", { left: true }, () => `${ctx.out.c.success(ctx.out.sym.done)} You left the workspace${ctx.root ? " · nb unlink to unlink this folder" : ""}`);
272
+ }
273
+
274
+ /**
275
+ * `nb edit <file>` (C10): in a linked folder, opens your copy (pulled first if it isn't here) and pushes a new version
276
+ * when the editor closes, with push's conflict rules; elsewhere, edits a downloaded copy and saves it as a new
277
+ * version based on the one you opened.
278
+ * @param {Context} ctx
279
+ */
280
+ export async function fileEdit(ctx) {
281
+ const p = ctx.positionals[0];
282
+ if (!p) throw usage("nb edit <file> [-m note]");
283
+ if (!ctx.out.interactive && !ctx.env.NB_EDITOR) throw new CliError("NEEDS_INPUT", "nb edit opens your editor, so it needs a terminal", { hint: "Change the file, then nb push <file>" });
284
+ const [cmd, ...args] = editorCommand(ctx).split(" ");
285
+ const win = process.platform === "win32";
286
+ const openEditor = (/** @type {string} */ file) => {
287
+ const run = spawnSync(/** @type {string} */ (cmd), [...args, win ? `"${file}"` : file], { stdio: "inherit", shell: win });
288
+ if (run.status !== 0) throw new CliError("EDITOR_FAILED", `The editor exited with ${run.status ?? run.signal}`);
289
+ };
290
+ const message = ctx.flags.message ? String(ctx.flags.message) : `Edited with nb edit`;
291
+ if (ctx.root) {
292
+ const rel = path.relative(ctx.root, path.resolve(ctx.cwd, p));
293
+ if (rel.startsWith("..") || path.isAbsolute(rel)) throw usage(`${p} is outside the linked folder ${ctx.root}`);
294
+ const abs = path.join(ctx.root, rel);
295
+ const files = await import("./files.mjs");
296
+ if (!fs.existsSync(abs)) await files.pull(/** @type {Context} */ ({ ...ctx, cwd: ctx.root, positionals: [rel] }), { quietResult: true });
297
+ if (!fs.existsSync(abs)) throw new CliError("NOT_FOUND", `No file ${rel} here or in the workspace`, { hint: "nb file list" });
298
+ const before = fs.readFileSync(abs);
299
+ openEditor(abs);
300
+ if (fs.readFileSync(abs).equals(before)) return ctx.out.result("nb.edit/1", { path: rel, changed: false }, () => "No changes, nothing pushed");
301
+ return files.push(/** @type {Context} */ ({ ...ctx, cwd: ctx.root, positionals: [rel], flags: { ...ctx.flags, message } }));
302
+ }
303
+ // Not in a linked folder: a temporary copy, saved back as a new version based on the one opened.
304
+ const remotePath = p.startsWith("/") ? p : `/${p}`;
305
+ const projectId = ctx.requireWorkspace();
306
+ const meta = /** @type {any} */ (await ctx.api.get("/api/v1/extension/file", { query: { projectId, path: remotePath, transfer: "metadata" } }));
307
+ const res = await ctx.api.download("/api/v1/extension/file", { projectId, path: remotePath, transfer: "raw" });
308
+ const tmp = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "nb-edit-")), path.posix.basename(remotePath).replace(/[^A-Za-z0-9._-]/g, "_") || "file");
309
+ const before = Buffer.from(await res.arrayBuffer());
310
+ fs.writeFileSync(tmp, before);
311
+ try {
312
+ openEditor(tmp);
313
+ const after = fs.readFileSync(tmp);
314
+ if (after.equals(before)) return ctx.out.result("nb.edit/1", { path: remotePath, changed: false }, () => "No changes, nothing saved");
315
+ const { mimeFor } = await import("../sync/transfer.mjs");
316
+ const placed = /** @type {any} */ (await ctx.api.post("/api/v1/files/place", { projectId, message, files: [{ path: remotePath, contentHash: crypto.createHash("sha256").update(after).digest("hex"), size: after.length, mimeType: mimeFor(remotePath), contentBase64: after.toString("base64"), baseVersion: meta.currentVersion }] }));
317
+ const f = placed.files?.[0];
318
+ ctx.out.result("nb.edit/1", { path: remotePath, changed: true, version: f?.version ?? null }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} Saved ${safe(d.path)}${d.version ? ` as v${d.version}` : ""}`);
319
+ } finally {
320
+ fs.rmSync(path.dirname(tmp), { recursive: true, force: true });
321
+ }
322
+ }
@@ -49,7 +49,7 @@ export async function filesFromLastCommit(cwd) {
49
49
 
50
50
  // ───────────────────────────────── saved filters (finding 148)
51
51
 
52
- const FILTER_KEYS = ["mine", "all", "status", "limit", "due", "to", "sprint", "priority", "sort"];
52
+ const FILTER_KEYS = ["mine", "all", "status", "limit", "due", "to", "sprint", "priority", "sort", "label", "starred"];
53
53
 
54
54
  /** `--save <name>` stores the list flags; `@name` brings them back. @param {Context} ctx */
55
55
  export function applySavedFilter(ctx) {
@@ -112,3 +112,20 @@ export async function createFromMarkdown(ctx, file) {
112
112
  ctx.out.result("nb.task.create.many/1", { tasks: made }, (d) => [`${ctx.out.c.success(ctx.out.sym.done)} Created ${d.tasks.length} tasks`, ...d.tasks.map((t) => ` #${t.number} ${safe(t.title)}`)]);
113
113
  return EXIT.ok;
114
114
  }
115
+
116
+ /**
117
+ * `nb commit -m "…"` (C12): git commit with a `NetworkBase-Task: #4` trailer for the current task (nb task start, or
118
+ * the nb/<n>- branch), so the task links to it. Without a current task it's a plain git commit.
119
+ * @param {Context} ctx
120
+ */
121
+ export async function commit(ctx) {
122
+ const message = String(ctx.flags.message ?? "").trim();
123
+ if (!message) throw usage('nb commit -m "what changed" [-a]');
124
+ const cwd = ctx.root ?? ctx.cwd;
125
+ const { branchTask } = await import("./tasks.mjs");
126
+ const number = ctx.flags.task ? String(ctx.flags.task).replace(/^#/, "") : ctx.project?.startedTask?.number ? String(ctx.project.startedTask.number) : branchTask(cwd);
127
+ const args = ["commit", ...(ctx.flags.all ? ["-a"] : []), "-m", message, ...(number ? ["--trailer", `NetworkBase-Task: #${number}`] : [])];
128
+ const out = await git(cwd, args);
129
+ const hash = (/\[[^\]]* ([0-9a-f]{7,})\]/.exec(out) ?? [])[1] ?? null;
130
+ ctx.out.result("nb.commit/1", { commit: hash, task: number ? Number(number) : null }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} Committed${d.commit ? ` ${d.commit}` : ""}${d.task ? ` for #${d.task}` : ""}${d.task ? "" : ctx.out.c.muted(" (no current task: nb task start <n> links commits)")}`);
131
+ }