@networkbase/cli 2.2.0 → 2.2.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.
@@ -16,7 +16,7 @@ const ITEMS_PER_CALL = 200;
16
16
  const PARALLEL = process.platform === "win32" ? 4 : 8;
17
17
 
18
18
  /**
19
- * @typedef {{ op: "add" | "change" | "delete" | "rename", path: string, fromPath?: string, abs?: string, contentHash?: string, size?: number, mimeType?: string, baseVersion?: number, baseHash?: string }} DraftItem
19
+ * @typedef {{ op: "add" | "change" | "delete" | "rename", path: string, fromPath?: string, abs?: string, contentHash?: string, size?: number, mimeType?: string, baseVersion?: number, baseHash?: string, executable?: boolean }} DraftItem
20
20
  * @typedef {{ id: string, title: string, sent: Record<string, string>, missing: string[], held?: Record<string, string> }} Journal
21
21
  * held: content the server didn't store because it looks like it holds a key, by hash → path
22
22
  */
@@ -83,13 +83,16 @@ export async function draftItems(root, project) {
83
83
  drop.add(/** @type {DraftItem} */ (from));
84
84
  Object.assign(/** @type {DraftItem} */ (to), { op: "rename", fromPath: from?.path, baseVersion: from?.baseVersion, baseHash: from?.baseHash });
85
85
  }
86
- return { items: items.filter((i) => !drop.has(i)).sort((a, b) => a.path.localeCompare(b.path)), skipped };
86
+ const kept = items.filter((i) => !drop.has(i)).sort((a, b) => a.path.localeCompare(b.path));
87
+ // The executable bit travels with the file (G16); Windows has none, so it's left as it is there.
88
+ if (process.platform !== "win32") for (const i of kept) if (i.abs) { try { i.executable = (fs.statSync(i.abs).mode & 0o100) !== 0; } catch { /* gone since the scan */ } }
89
+ return { items: kept, skipped };
87
90
  }
88
91
 
89
92
  /** What the server has for an item; a different key means it needs sending again. @param {DraftItem} i */
90
- const keyOf = (i) => `${i.op}:${i.fromPath ?? ""}:${i.contentHash ?? ""}:${i.baseVersion ?? ""}`;
93
+ const keyOf = (i) => `${i.op}:${i.fromPath ?? ""}:${i.contentHash ?? ""}:${i.baseVersion ?? ""}:${i.executable ? "x" : ""}`;
91
94
  /** @param {DraftItem} i */
92
- const wire = (i) => ({ op: i.op, path: i.path, ...(i.fromPath ? { fromPath: i.fromPath } : {}), ...(i.contentHash ? { contentHash: i.contentHash, size: i.size, mimeType: i.mimeType } : {}), ...(i.baseVersion != null ? { baseVersion: i.baseVersion, baseHash: i.baseHash } : {}) });
95
+ const wire = (i) => ({ op: i.op, path: i.path, ...(i.fromPath ? { fromPath: i.fromPath } : {}), ...(i.contentHash ? { contentHash: i.contentHash, size: i.size, mimeType: i.mimeType } : {}), ...(typeof i.executable === "boolean" ? { executable: i.executable } : {}), ...(i.baseVersion != null ? { baseVersion: i.baseVersion, baseHash: i.baseHash } : {}) });
93
96
 
94
97
  /**
95
98
  * Sends the draft's changes since the last sync, then the content the server doesn't have.
@@ -69,13 +69,15 @@ export async function changeStatus(ctx) {
69
69
  const conflicts = view.items.filter((/** @type {any} */ i) => i.state === "conflict");
70
70
  const pending = readJournal(root, id).missing.length;
71
71
  const held = Object.values(readJournal(root, id).held ?? {});
72
- ctx.out.result("nb.change.status/1", { changeSet: set, items: view.items, uploadsPending: pending, held, conflicts, skipped: capture?.skipped ?? [] }, (d) => [
72
+ const comments = (view.comments ?? []).filter((/** @type {any} */ c) => !c.resolvedAt);
73
+ ctx.out.result("nb.change.status/1", { changeSet: set, items: view.items, uploadsPending: pending, held, conflicts, comments, skipped: capture?.skipped ?? [] }, (d) => [
73
74
  `${ctx.out.c.bold(safe(d.changeSet.title))} ${ctx.out.c.muted(`${d.changeSet.id.slice(0, 8)} · ${d.changeSet.status}`)}`,
74
75
  ` ${counts(d.changeSet)}${d.changeSet.linesAdded || d.changeSet.linesRemoved ? ctx.out.c.muted(`, +${d.changeSet.linesAdded} −${d.changeSet.linesRemoved}`) : ""}`,
75
76
  ...(d.held.length ? [ctx.out.c.warning(` Not sent, ${d.held.length === 1 ? "it looks" : "they look"} like ${d.held.length === 1 ? "it holds" : "they hold"} a key: ${d.held.map((/** @type {string} */ p) => safe(p)).join(", ")}`), ctx.out.c.muted(" Remove the key, or nb change finish --confirm-secrets if it's safe to share")] : []),
76
77
  ...(d.uploadsPending > d.held.length ? [ctx.out.c.warning(` ${plural(d.uploadsPending - d.held.length, "file")} still to upload: run nb change status again`)] : []),
77
78
  ...d.conflicts.map((/** @type {any} */ c) => ctx.out.c.warning(` ${ctx.out.sym.warn} ${safe(c.path)} changed since you started (${c.conflict?.kind ?? "edit"})`)),
78
79
  ...d.skipped.map((/** @type {any} */ s) => ctx.out.c.muted(` skipped ${safe(s.path)}: ${s.reason}`)),
80
+ ...d.comments.map((/** @type {any} */ c) => ` ${ctx.out.c.brand("»")} ${safe(c.path)}${c.line ? `:${c.line}` : ""} ${ctx.out.c.muted(`${safe(c.author || c.username || "someone")}:`)} ${safe(c.body).replace(/\s+/g, " ").slice(0, 160)}`),
79
81
  ctx.out.c.muted(d.changeSet.status === "ready" ? " Ready: nb change apply" : " nb change finish when you're done"),
80
82
  ]);
81
83
  return EXIT.ok;
@@ -101,6 +103,7 @@ export async function changeView(ctx) {
101
103
  ctx.out.result("nb.change.view/1", res, (d) => [
102
104
  `${ctx.out.c.bold(safe(d.changeSet.title))} ${ctx.out.c.muted(`${d.changeSet.id.slice(0, 8)} · ${d.changeSet.status} · ${counts(d.changeSet)}`)}`,
103
105
  ...(d.changeSet.message ? [` ${safe(d.changeSet.message)}`] : []),
106
+ ...(d.comments ?? []).filter((/** @type {any} */ c) => !c.resolvedAt).map((/** @type {any} */ c) => ` ${ctx.out.c.brand("»")} ${safe(c.path)}${c.line ? `:${c.line}` : ""} ${ctx.out.c.muted(`${safe(c.author || c.username || "someone")}:`)} ${safe(c.body).replace(/\s+/g, " ").slice(0, 160)}`),
104
107
  ...d.items.map((/** @type {any} */ i) => ` ${sym[i.op] ?? "?"} ${safe(i.fromPath ? `${i.fromPath} → ${i.path}` : i.path)}${i.linesAdded != null ? ctx.out.c.muted(` +${i.linesAdded} −${i.linesRemoved}`) : ""}${i.state === "conflict" ? ctx.out.c.warning(` (changed since: ${i.conflict?.kind ?? "edit"})`) : i.state === "pending" ? ctx.out.c.muted(" (uploading)") : ""}`),
105
108
  ]);
106
109
  return EXIT.ok;
@@ -350,3 +353,64 @@ export async function pushAsChangeSet(ctx, root, project, items) {
350
353
  const res = /** @type {any} */ (await ctx.api.post(`/api/v1/change-sets/${enc(id)}/apply`, {}));
351
354
  return { changeSet: res.changeSet, applied: res.applied ?? [] };
352
355
  }
356
+
357
+ /**
358
+ * nb change split (report G16): a change set over the limits (2,000 files, 500 MB) becomes one per top-level folder,
359
+ * each sent and finished, ready to apply one at a time. The original is discarded; your files stay as they are.
360
+ * @param {Context} ctx
361
+ */
362
+ export async function changeSplit(ctx) {
363
+ const { root, project } = ctx.requireRoot();
364
+ const id = currentChange(root);
365
+ if (!id) throw new CliError("NOT_FOUND", "No open change set in this folder to split", { hint: "nb change status" });
366
+ const { items } = await draftItems(root, project);
367
+ if (!items.length) throw new CliError("USAGE", "Nothing to split: no saved changes here");
368
+ const title = readJournal(root, id).title || "Changes";
369
+ const MAX_FILES = 1900;
370
+ const MAX_BYTES = 450 * 1024 * 1024;
371
+ /** @type {Map<string, typeof items>} */
372
+ const byFolder = new Map();
373
+ for (const item of items) {
374
+ const top = item.path.split("/").filter(Boolean).length > 1 ? item.path.split("/")[1] ?? "/" : "/";
375
+ byFolder.set(top, [...(byFolder.get(top) ?? []), item]);
376
+ }
377
+ // A folder bigger than one change set allows goes in parts, in path order.
378
+ /** @type {Array<{ name: string, items: typeof items }>} */
379
+ const groups = [];
380
+ for (const [folder, list] of [...byFolder].sort(([a], [b]) => a.localeCompare(b))) {
381
+ let part = /** @type {typeof items} */ ([]);
382
+ let bytes = 0;
383
+ const name = folder === "/" ? "top level" : folder;
384
+ for (const item of list) {
385
+ if (part.length && (part.length >= MAX_FILES || bytes + (item.size ?? 0) > MAX_BYTES)) { groups.push({ name, items: part }); part = []; bytes = 0; }
386
+ part.push(item);
387
+ bytes += item.size ?? 0;
388
+ }
389
+ if (part.length) groups.push({ name, items: part });
390
+ }
391
+ const counts = new Map();
392
+ for (const g of groups) counts.set(g.name, (counts.get(g.name) ?? 0) + 1);
393
+ const seen = new Map();
394
+ /** @type {Array<{ id: string, title: string, files: number, decision: string }>} */
395
+ const made = [];
396
+ for (const g of groups) {
397
+ const n = (seen.get(g.name) ?? 0) + 1;
398
+ seen.set(g.name, n);
399
+ const partTitle = `${title} (${g.name}${counts.get(g.name) > 1 ? ` ${n}` : ""})`.slice(0, 120);
400
+ const started = /** @type {any} */ (await ctx.api.post(`/api/v1/workspaces/${enc(project.workspaceId)}/change-sets`, { title: partTitle }));
401
+ const partId = started.changeSet.id;
402
+ writeJournal(root, { id: partId, title: partTitle, sent: {}, missing: [] });
403
+ const sync = await syncDraft(ctx.api, root, partId, g.items, { confirmSecrets: Boolean(ctx.flags["confirm-secrets"]) });
404
+ if (sync.pending || sync.held.length) throw new CliError("CONTENT_MISSING", `${partTitle}: ${plural(sync.pending, "file")} not uploaded yet`, { hint: `nb change status ${partId.slice(0, 8)}, then nb change finish there` });
405
+ const finished = /** @type {any} */ (await ctx.api.post(`/api/v1/change-sets/${enc(partId)}/finish`, {}));
406
+ made.push({ id: partId, title: partTitle, files: g.items.length, decision: finished.decision });
407
+ }
408
+ await ctx.api.post(`/api/v1/change-sets/${enc(id)}/discard`, {});
409
+ setCurrentChange(root, null);
410
+ ctx.out.result("nb.change.split/1", { from: id, changeSets: made }, (d) => [
411
+ `${ctx.out.c.success(ctx.out.sym.done)} Split into ${plural(d.changeSets.length, "change set")}, each finished:`,
412
+ ...d.changeSets.map((/** @type {any} */ s) => ` ${ctx.out.c.muted(s.id.slice(0, 8))} ${safe(s.title)} ${ctx.out.c.muted(`· ${plural(s.files, "file")}`)}`),
413
+ ctx.out.c.muted(` Apply each: nb change apply <id>`),
414
+ ]);
415
+ return EXIT.ok;
416
+ }
@@ -178,6 +178,10 @@ export async function pull(ctx, options = {}) {
178
178
  try {
179
179
  abs = localPathOf(root, project.remoteRoot, item.path);
180
180
  } catch (error) {
181
+ if (error instanceof CliError && error.code === "UNSAFE_PATH" && /** @type {any} */ (error.details)?.protected) {
182
+ skipped.push({ path: item.path, reason: "it's inside a .git or .networkbase folder, which nb never writes" });
183
+ return;
184
+ }
181
185
  if (!(error instanceof CliError) || error.code !== "RESERVED_NAME") throw error;
182
186
  skipped.push({ path: item.path, reason: "Windows can't hold a file with this name" });
183
187
  return;
@@ -206,6 +210,8 @@ export async function pull(ctx, options = {}) {
206
210
  throw error;
207
211
  });
208
212
  if (!got) return;
213
+ // Executable files (scripts, bin/) come back executable (report G16). Windows has no such bit.
214
+ if (/** @type {any} */ (r).executable && process.platform !== "win32") fs.chmodSync(abs, fs.statSync(abs).mode | 0o111);
209
215
  if (got.content) saveBaseCopy(root, got.hash, got.content);
210
216
  recordBase(state, item.path, { nodeId: r.nodeId, version: r.version, hash: got.hash, abs });
211
217
  results.push({ path: item.path, did: item.action === "restore" ? "restored" : item.base ? "updated" : "new", version: r.version });
@@ -133,6 +133,7 @@ export const COMMANDS = [
133
133
  { group: "Files", name: "change update", summary: "Merge teammates' newer versions into your change set's files", usage: "nb change update", module: "change", fn: "changeUpdate", exit: [0, 4] },
134
134
  { group: "Files", name: "change resolve", summary: "Keep yours or theirs for a file that changed on both sides", usage: "nb change resolve <path> --mine|--theirs", module: "change", fn: "changeResolve",
135
135
  flags: { mine: { type: "boolean", describe: "Your file goes over theirs" }, theirs: { type: "boolean", describe: "Take the workspace's file; drop yours from the change set" } } },
136
+ { group: "Files", name: "change split", summary: "Split a change set that's too big into one per folder", usage: "nb change split", module: "change", fn: "changeSplit" },
136
137
  { group: "Files", name: "change copy", summary: "Copy an undone or discarded change set as a new draft", usage: "nb change copy <id>", module: "change", fn: "changeCopy" },
137
138
  { group: "Files", name: "watch", summary: "Push your saves as drafts; pull teammates' changes (foreground)", usage: "nb watch [--no-pull] [--change]", module: "watch", fn: "watch",
138
139
  flags: { "no-pull": { type: "boolean", describe: "Only push; don't pull other people's changes" }, inbox: { type: "boolean", describe: "Also show your notifications as they come" },
@@ -26,7 +26,7 @@ export const FIXES = /** @type {Record<string, string>} */ ({
26
26
  "CHANGE_SETS_OFF": "Push with nb push for now",
27
27
  "CHANGE_SET_LIMIT": "nb change list, then finish or discard one",
28
28
  "CHANGE_SET_CLOSED": "nb change start for a new one, or nb change copy <id>",
29
- "CHANGE_SET_TOO_LARGE": "Split it into smaller change sets, for example by folder",
29
+ "CHANGE_SET_TOO_LARGE": "nb change split makes one change set per folder",
30
30
  "CHANGE_SET_NOT_READY": "nb change finish, then apply",
31
31
  "CHANGE_SET_CONFLICT": "nb change view <id> to see them, then nb change resolve <path>",
32
32
  "CONTENT_MISSING": "Wait for nb change status to show all uploaded, then finish again",
package/lib/mcp/tools.mjs CHANGED
@@ -207,7 +207,7 @@ export const TOOLS = [
207
207
 
208
208
  // Change sets (report G7, G8): where they're on, the agent's saved files go into one change set as it works.
209
209
  { name: "networkbase_change_status", title: "The change set", tier: "read", pack: "changes", props: {},
210
- description: "Where change sets are on, your saved files go into one change set as you work (no push needed). Shows its files, uploads and anything a teammate changed since.",
210
+ description: "Where change sets are on, your saved files go into one change set as you work (no push needed). Shows its files, uploads, review comments to address, and anything a teammate changed since.",
211
211
  run: (nb) => nb("change status") },
212
212
  { name: "networkbase_change_start", title: "Start a change set", tier: "small", pack: "changes", props: { title: { type: "string", description: "The job, like \"Redesign the sign-in page\"" }, task: { type: "string" } }, required: ["title"],
213
213
  description: "Name the work before you start; otherwise your first save opens one named after the task. If it answers CHANGE_SETS_OFF, push with networkbase_file_push instead.",
@@ -23,7 +23,7 @@ export async function fetchManifest(api, workspaceId) {
23
23
  let page;
24
24
  do {
25
25
  page = await api.get(`/api/v1/workspaces/${encodeURIComponent(workspaceId)}/manifest`, { query: { cursor } });
26
- for (const f of page.files) files.set(f.path, { path: f.path, nodeId: f.nodeId, version: f.version, hash: f.contentHash ? String(f.contentHash).toLowerCase() : null, size: f.size ?? 0, updatedAt: f.updatedAt ?? null });
26
+ for (const f of page.files) files.set(f.path, { path: f.path, nodeId: f.nodeId, version: f.version, hash: f.contentHash ? String(f.contentHash).toLowerCase() : null, size: f.size ?? 0, updatedAt: f.updatedAt ?? null, ...(f.executable ? { executable: true } : {}) });
27
27
  cursor = page.nextCursor;
28
28
  } while (cursor);
29
29
  return { files, canWrite: Boolean(page.canWrite), largestFileBytes: page.limits?.largestFileBytes ?? 25 * 1024 * 1024 };
@@ -35,6 +35,14 @@ export function safeJoin(root, rel) {
35
35
  const target = path.resolve(root, ...rel.split("/"));
36
36
  const inside = path.relative(root, target);
37
37
  if (!inside || inside.startsWith("..") || path.isAbsolute(inside)) throw new CliError("UNSAFE_PATH", `Refusing a path outside this folder: ${JSON.stringify(rel)}`);
38
+ // Never inside a .git or .networkbase folder, at any depth or letter case: a file there (a hook, a config) would run
39
+ // commands or replace nb's own state (M5 security review). Checked on the resolved path, so Windows' own rules apply:
40
+ // "\" separators, trailing dots and spaces, 8.3 short names (GIT~1) and stream suffixes (":").
41
+ const parts = inside.split(path.sep).map((part) => part.replace(/[. ]+$/, ""));
42
+ const win = process.platform === "win32";
43
+ if (parts.some((part) => /^\.(git|networkbase)$/i.test(part) || (win && (/^(git|networ)~\d+$/i.test(part) || part.includes(":"))))) {
44
+ throw new CliError("UNSAFE_PATH", `Refusing a file inside a .git or .networkbase folder: ${JSON.stringify(rel)}`, { details: { protected: true } });
45
+ }
38
46
  if (process.platform === "win32" && inside.split(path.sep).some((part) => /^(con|prn|aux|nul|com\d|lpt\d)(\.|$)/i.test(part))) {
39
47
  throw new CliError("RESERVED_NAME", `Windows can't hold a file named ${JSON.stringify(rel)}`);
40
48
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@networkbase/cli",
3
- "version": "2.2.0",
3
+ "version": "2.2.1",
4
4
  "description": "NetworkBase in your terminal: sync files, work on tasks, edit docs",
5
5
  "type": "module",
6
6
  "homepage": "https://networkbase.in",