@networkbase/cli 1.0.4 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,425 @@
1
+ // status, pull, push, sync and the offline queue (report §17.4, A1, A4.4, A12.4).
2
+ import crypto from "node:crypto";
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+
6
+ import { DIR_NAME, readUserConfig } from "../config.mjs";
7
+ import { CliError, EXIT, usage } from "../errors.mjs";
8
+ import { safe } from "../print/style.mjs";
9
+ import { scanLocal, toRelative, toRemote } from "../sync/local.mjs";
10
+ import { planSync, stateLabel } from "../sync/plan.mjs";
11
+ import { enqueue, QUEUE_TTL_MS, readQueue, writeQueue } from "../sync/queue.mjs";
12
+ import { acquireLock, pruneBaseCopies, readState, saveBaseCopy, writeState } from "../sync/state.mjs";
13
+ import { conflictCopyPath, downloadTo, fetchManifest, renameRetry, safeJoin, uploadFiles } from "../sync/transfer.mjs";
14
+ import { confirm } from "../tui/ask.mjs";
15
+ import { resolveTask } from "./tasks.mjs";
16
+
17
+ /** @typedef {import("../context.mjs").Context} Context */
18
+ /** @typedef {import("../sync/plan.mjs").PlanItem} PlanItem */
19
+
20
+ /** Paths given on the command line, as paths relative to the linked folder. @param {Context} ctx @param {string} root */
21
+ export function relativeArgs(ctx, root) {
22
+ return ctx.positionals.map((p) => {
23
+ const rel = path.relative(root, path.resolve(ctx.cwd, p));
24
+ if (rel.startsWith("..") || path.isAbsolute(rel)) throw usage(`${p} is outside the linked folder ${root}`);
25
+ return rel;
26
+ });
27
+ }
28
+
29
+ /**
30
+ * Server, base and local side by side. Offline: the server side is the base, and status says so (A12.4).
31
+ * @param {Context} ctx @param {{ only?: string[] }} [options]
32
+ */
33
+ export async function buildPlan(ctx, options = {}) {
34
+ const { root, project } = ctx.requireRoot();
35
+ const state = readState(root, project.workspaceId);
36
+ let offline = false;
37
+ /** @type {Awaited<ReturnType<typeof fetchManifest>>} */
38
+ let manifest;
39
+ try {
40
+ manifest = await fetchManifest(ctx.api, project.workspaceId);
41
+ } catch (error) {
42
+ if (!(error instanceof CliError) || error.code !== "OFFLINE") throw error;
43
+ offline = true;
44
+ manifest = { files: new Map(Object.entries(state.files).map(([p, b]) => [p, { path: p, nodeId: b.nodeId, version: b.baseVersion, hash: b.baseHash, size: b.size }])), canWrite: true, largestFileBytes: 0 };
45
+ }
46
+ // Only the part of the workspace this folder is linked to (A1.1 item 5).
47
+ const remote = new Map([...manifest.files].filter(([p]) => toRelative(project.remoteRoot, p) !== null));
48
+ const { files: local, skipped } = await scanLocal({ root, remoteRoot: project.remoteRoot, base: state.files, maxFileBytes: manifest.largestFileBytes || undefined, only: options.only });
49
+ let items = planSync({ base: state.files, local, remote });
50
+ if (options.only?.length) {
51
+ const prefixes = options.only.map((rel) => toRemote(project.remoteRoot, rel));
52
+ items = items.filter((i) => prefixes.some((pre) => i.path === pre || i.path.startsWith(pre.endsWith("/") ? pre : `${pre}/`)));
53
+ }
54
+ return { root, project, state, manifest, items, skipped, offline };
55
+ }
56
+
57
+ /** @param {string} root @param {string} remoteRoot @param {string} remotePath */
58
+ export const localPathOf = (root, remoteRoot, remotePath) => safeJoin(root, /** @type {string} */ (toRelative(remoteRoot, remotePath)));
59
+
60
+ /** Moves a local file into .networkbase/trash (kept 30 days) instead of deleting it (A1.6). @param {string} root @param {string} abs */
61
+ export function moveToLocalTrash(root, abs) {
62
+ const dest = path.join(root, DIR_NAME, "trash", new Date().toISOString().replace(/[:.]/g, "-"), path.relative(root, abs));
63
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
64
+ renameRetry(abs, dest);
65
+ return dest;
66
+ }
67
+
68
+ /** Records a synced file as the new base. @param {import("../sync/state.mjs").SyncState} state @param {string} p @param {{ nodeId: string, version: number, hash: string, abs: string }} f */
69
+ export function recordBase(state, p, f) {
70
+ const st = fs.statSync(f.abs);
71
+ state.files[p] = { nodeId: f.nodeId, baseVersion: f.version, baseHash: f.hash, size: st.size, mtimeMs: st.mtimeMs };
72
+ delete state.conflicts[p];
73
+ }
74
+
75
+ // ───────────────────────────────── status
76
+
77
+ /** @param {Context} ctx */
78
+ export async function status(ctx) {
79
+ const { root, project, items, skipped, offline, manifest } = await buildPlan(ctx);
80
+ const changed = items.filter((i) => i.state !== "unchanged");
81
+ const conflicts = changed.filter((i) => i.state === "conflict");
82
+ const data = {
83
+ workspace: { id: project.workspaceId, slug: project.slug, title: project.title },
84
+ startedTask: project.startedTask ?? null,
85
+ offline,
86
+ readOnly: !manifest.canWrite,
87
+ queued: readQueue(root).length,
88
+ files: changed.map((i) => ({ path: i.path, state: i.state, action: i.action, ...(i.note ? { note: i.note } : {}), ...(i.remote ? { remoteVersion: i.remote.version } : {}) })),
89
+ skipped,
90
+ };
91
+ const { c, sym } = ctx.out;
92
+ ctx.out.result("nb.status/1", data, (d) => {
93
+ const task = d.startedTask ? ` · #${d.startedTask.number ?? ""} ${safe(d.startedTask.title ?? "")}` : "";
94
+ const head = `${c.brand(sym.brand)} ${safe(project.slug ?? project.workspaceId)}${task}${d.readOnly ? ` · ${c.warning("read only")}` : ""}${d.offline ? ` · ${c.warning("offline: server side not checked")}` : ""}`;
95
+ const queued = d.queued ? [` ${c.warning(`${d.queued} push(es) queued while offline: nb sync`)}`] : [];
96
+ if (!d.files.length) return [head, ...queued, ` ${c.muted(`Up to date · ${root}`)}`, ...skippedLines(d.skipped)];
97
+ const color = (/** @type {string} */ s) => (s === "conflict" ? c.danger : s === "modified" || s === "added" ? c.accent : s.startsWith("remote") ? c.info : c.muted);
98
+ const counts = Object.entries(d.files.reduce((/** @type {Record<string, number>} */ acc, f) => ({ ...acc, [f.state]: (acc[f.state] ?? 0) + 1 }), {})).map(([s, n]) => `${n} ${s}`).join(" · ");
99
+ const rows = ctx.out.table([
100
+ { title: "State", value: (f) => color(f.state)(stateLabel(/** @type {any} */ (f))) },
101
+ { title: "Path", value: (f) => safe(f.path), flex: true, path: true },
102
+ { title: "", value: (f) => (f.note ? c.muted(f.note) : "") },
103
+ ], d.files);
104
+ const next = conflicts.length ? `nb resolve ${safe(conflicts[0]?.path.slice(1) ?? "")} --mine|--theirs|--both` : changed.some((f) => f.action === "push") ? "nb push <files>" : "nb pull";
105
+ return [head, ...queued, ` ${counts}`, "", ...rows, ...skippedLines(d.skipped), "", ` ${c.muted(next)}`];
106
+ });
107
+ if (conflicts.length) return EXIT.conflict;
108
+ return offline ? EXIT.offline : EXIT.ok;
109
+ }
110
+
111
+ /** @param {Array<{ path: string, reason: string }>} skipped */
112
+ const skippedLines = (skipped) => (skipped.length ? ["", ` skipped: ${skipped.slice(0, 5).map((s) => `${safe(s.path)} (${s.reason})`).join(", ")}${skipped.length > 5 ? ` and ${skipped.length - 5} more` : ""}`] : []);
113
+
114
+ // ───────────────────────────────── pull
115
+
116
+ /** @param {Context} ctx @param {{ quietResult?: boolean }} [options] */
117
+ export async function pull(ctx, options = {}) {
118
+ const { root } = ctx.requireRoot();
119
+ const only = relativeArgs(ctx, root);
120
+ const release = ctx.flags["dry-run"] ? () => {} : await acquireLock(root, "nb pull");
121
+ try {
122
+ const plan = await buildPlan(ctx, { only });
123
+ if (plan.offline) throw new CliError("OFFLINE", "Can't reach the server to pull", { hint: "Try again when you're online" });
124
+ const { project, state } = plan;
125
+ let todo = plan.items.filter((i) => ["pull", "restore", "adopt", "remove-local", "conflict"].includes(i.action));
126
+ // On disks that ignore letter case (macOS, Windows), Report.md and report.md would be one file: the first one
127
+ // wins and the other is skipped with a note, never overwritten (A1.16).
128
+ /** @type {Array<{ path: string, reason: string }>} */
129
+ const skipped = [];
130
+ if (process.platform === "darwin" || process.platform === "win32") {
131
+ const taken = new Map(Object.keys(state.files).concat(todo.map((i) => i.path)).sort().map((p) => [p.toLowerCase(), p]));
132
+ todo = todo.filter((i) => {
133
+ const owner = taken.get(i.path.toLowerCase());
134
+ if (owner === i.path || state.files[i.path]) return true;
135
+ skipped.push({ path: i.path, reason: `same name as ${owner} except for letter case` });
136
+ return false;
137
+ });
138
+ }
139
+ if (ctx.flags["dry-run"]) {
140
+ return ctx.out.result("nb.pull.plan/1", { files: todo.map((i) => ({ path: i.path, action: i.action })) }, (d) => (d.files.length ? d.files.map((f) => ` would ${f.action.replace("-", " ")} ${safe(f.path)}`) : "Nothing to pull"));
141
+ }
142
+ /** @type {Array<{ path: string, did: string, version?: number, by?: string, copy?: string }>} */
143
+ const results = [];
144
+ /** @param {PlanItem} item */
145
+ const apply = async (item) => {
146
+ const r = /** @type {import("../sync/plan.mjs").RemoteFile} */ (item.remote);
147
+ let abs;
148
+ try {
149
+ abs = localPathOf(root, project.remoteRoot, item.path);
150
+ } catch (error) {
151
+ if (!(error instanceof CliError) || error.code !== "RESERVED_NAME") throw error;
152
+ skipped.push({ path: item.path, reason: "Windows can't hold a file with this name" });
153
+ return;
154
+ }
155
+ if (item.action === "adopt") {
156
+ recordBase(state, item.path, { nodeId: r.nodeId, version: r.version, hash: r.hash ?? "", abs });
157
+ return;
158
+ }
159
+ if (item.action === "remove-local") {
160
+ const kept = moveToLocalTrash(root, abs);
161
+ delete state.files[item.path];
162
+ results.push({ path: item.path, did: "removed (deleted on the server)", copy: path.relative(root, kept) });
163
+ return;
164
+ }
165
+ if (item.action === "conflict") {
166
+ // Never overwrite: the server's version lands next to yours (A1.7, D18).
167
+ const copy = conflictCopyPath(abs, r.version);
168
+ await downloadTo(ctx.api, project.workspaceId, item.path, copy, r.hash);
169
+ state.conflicts[item.path] = { remoteVersion: r.version, copy: path.relative(root, copy) };
170
+ results.push({ path: item.path, did: "conflict", version: r.version, copy: path.relative(root, copy) });
171
+ return;
172
+ }
173
+ const got = await downloadTo(ctx.api, project.workspaceId, item.path, abs, r.hash);
174
+ if (got.content) saveBaseCopy(root, got.hash, got.content);
175
+ recordBase(state, item.path, { nodeId: r.nodeId, version: r.version, hash: got.hash, abs });
176
+ results.push({ path: item.path, did: item.action === "restore" ? "restored" : item.base ? "updated" : "new", version: r.version });
177
+ // State is saved every 100 files; after a crash, a downloaded file matching the server is adopted next run.
178
+ if (results.length % 100 === 0) writeState(root, state);
179
+ };
180
+ // 8 downloads at a time, 4 on Windows (A12.6).
181
+ let next = 0;
182
+ const worker = async () => { while (next < todo.length) await apply(/** @type {PlanItem} */ (todo[next++])); };
183
+ await Promise.all(Array.from({ length: Math.min(process.platform === "win32" ? 4 : 8, todo.length) }, worker));
184
+ results.sort((a, b) => a.path.localeCompare(b.path));
185
+ writeState(root, state);
186
+ pruneBaseCopies(root, state, Number(readUserConfig(ctx.env)["base-cache-mb"] ?? 200) * 1024 * 1024);
187
+ const conflicts = results.filter((r) => r.did === "conflict");
188
+ if (!options.quietResult) {
189
+ ctx.out.result("nb.pull/1", { files: results, skipped }, (d) => {
190
+ const skippedLines = d.skipped.map((x) => ctx.out.c.warning(` skipped ${safe(x.path)} (${x.reason})`));
191
+ if (!d.files.length) return skippedLines.length ? ["Up to date", ...skippedLines] : "Up to date";
192
+ const { c, sym } = ctx.out;
193
+ return [
194
+ `${c.success(sym.done)} Pulled ${d.files.length - conflicts.length} ${d.files.length - conflicts.length === 1 ? "file" : "files"}${conflicts.length ? ` · ${c.danger(`${conflicts.length} conflict${conflicts.length > 1 ? "s" : ""}`)}` : ""}`,
195
+ ...d.files.map((f) => ` ${f.did === "conflict" ? c.danger("conflict") : f.did.padEnd(8)} ${safe(f.path)}${f.version ? c.muted(` v${f.version}`) : ""}${f.copy ? c.muted(` → ${safe(f.copy)}`) : ""}`),
196
+ ...(conflicts.length ? [c.muted(` Server's version saved next to yours. Settle with nb resolve <path> --mine|--theirs|--both`)] : []),
197
+ ...skippedLines,
198
+ ];
199
+ });
200
+ }
201
+ return conflicts.length ? EXIT.conflict : EXIT.ok;
202
+ } finally {
203
+ release();
204
+ }
205
+ }
206
+
207
+ // ───────────────────────────────── push
208
+
209
+ /** 1.x `--done` / `--wip` changed task status as a side effect of uploading; 2.0 only uploads (finding 135). @param {Context} ctx */
210
+ function oldStatusFlags(ctx) {
211
+ if (ctx.flags.done) ctx.out.warn("--done no longer changes the task's status. After the push: nb task done");
212
+ if (ctx.flags.wip) ctx.out.warn("--wip no longer changes the task's status. Use: nb task move <task> in_progress");
213
+ }
214
+
215
+ /** @param {Context} ctx */
216
+ export async function push(ctx) {
217
+ oldStatusFlags(ctx);
218
+ const { root } = ctx.requireRoot();
219
+ // --from-git: what the last commit changed, its subject as the message, its NetworkBase-Task trailer as the task.
220
+ if (ctx.flags["from-git"]) {
221
+ const { filesFromLastCommit } = await import("./extras.mjs");
222
+ const last = await filesFromLastCommit(ctx.cwd);
223
+ if (!last.paths.length) throw usage("The last commit changed no files in this folder");
224
+ ctx.positionals = last.paths;
225
+ ctx.flags.message ??= last.subject || undefined;
226
+ if (last.task && !ctx.flags.task) ctx.flags.task = last.task;
227
+ }
228
+ const only = relativeArgs(ctx, root);
229
+ if (!only.length && !ctx.flags.all && !ctx.out.interactive) {
230
+ // Never upload a whole folder without being told which files (finding 21).
231
+ throw usage("Say which files to push", "nb push <paths…>, or nb push --all for every changed tracked file");
232
+ }
233
+ const as = ctx.flags.as ?? readUserConfig(ctx.env)["default-as"] ?? null;
234
+ if (as && !["reference", "draft", "final"].includes(as)) throw usage(`--as must be reference, draft or final (not ${as})`);
235
+ const keyBase = /** @type {any} */ (ctx).queueId ?? crypto.randomUUID();
236
+ const queueOffline = () => {
237
+ if (ctx.flags["dry-run"]) return new CliError("OFFLINE", "Can't reach the server", { hint: "Try again when you're online" });
238
+ const flags = Object.fromEntries(["task", "as", "message", "keep-both", "folder", "all"].filter((k) => ctx.flags[k] !== undefined).map((k) => [k, ctx.flags[k]]));
239
+ const n = enqueue(root, { id: keyBase, op: "push", paths: only, flags, queuedAt: new Date().toISOString() });
240
+ return new CliError("OFFLINE", `Offline: queued this push${n > 1 ? ` (${n} waiting)` : ""}`, { hint: "It sends with your next nb sync; your files are unchanged" });
241
+ };
242
+ const release = ctx.flags["dry-run"] ? () => {} : await acquireLock(root, "nb push");
243
+ try {
244
+ const plan = await buildPlan(ctx, { only });
245
+ if (plan.offline) throw queueOffline();
246
+ const { project, state } = plan;
247
+ if (!plan.manifest.canWrite) throw new CliError("READ_ONLY", "You can read this workspace but not change it", { hint: "Ask an owner for member access" });
248
+ // With no paths, only files NetworkBase already tracks; new files are pushed by naming them (A1.6, §17.4).
249
+ let items = plan.items.filter((i) => i.action === "push" && (only.length || i.base));
250
+ let moves = plan.items.filter((i) => i.action === "move");
251
+ // --recreate: files deleted on the server that you still have go back up as new files (§17.4.1).
252
+ if (ctx.flags.recreate) items = items.concat(plan.items.filter((i) => (i.action === "remove-local" || i.action === "keep-local") && i.local).map((i) => ({ ...i, base: undefined })));
253
+ const conflicts = plan.items.filter((i) => i.action === "conflict");
254
+ const deletions = only.length ? plan.items.filter((i) => i.action === "delete-remote") : [];
255
+ const behind = plan.items.filter((i) => i.action === "pull" || i.action === "restore");
256
+
257
+ if (conflicts.length && !ctx.flags.force) {
258
+ throw new CliError("LOCAL_CONFLICT", `${conflicts.length === 1 ? safe(conflicts[0]?.path) : `${conflicts.length} files`} changed here and on the server`, { hint: `Run nb resolve ${safe(conflicts[0]?.path.slice(1) ?? "<path>")}, or nb pull to get a copy of the server's version`, details: { conflicts: conflicts.map((i) => ({ path: i.path, remoteVersion: i.remote?.version })) } });
259
+ }
260
+ if (conflicts.length && ctx.flags.force) {
261
+ const ok = await confirm(ctx, { key: "force", question: `Replace the server's newer version of ${conflicts.length} file(s) with yours?`, yesLabel: "Replace", defaultYes: false });
262
+ if (!ok) return EXIT.cancelled;
263
+ items = items.concat(conflicts);
264
+ }
265
+ if (!only.length && !ctx.flags.all && items.length) {
266
+ const ok = await confirm(ctx, { key: "push", question: `Push ${items.length} changed file(s)?`, preview: items.slice(0, 10).map((i) => i.path).join("\n"), yesLabel: "Push", defaultYes: true });
267
+ if (!ok) return EXIT.cancelled;
268
+ }
269
+ if (ctx.flags["dry-run"]) {
270
+ return ctx.out.result("nb.push.plan/1", { files: items.map((i) => ({ path: i.path, state: i.state })), moves: moves.map((m) => ({ from: m.from, to: m.path })), deletions: deletions.map((i) => i.path) }, (d) => (d.files.length || d.deletions.length || d.moves.length ? [...d.files.map((f) => ` would push ${safe(f.path)}`), ...d.moves.map((m) => ` would move ${safe(m.from)} ${ctx.out.sym.arrow} ${safe(m.to)}`), ...d.deletions.map((p) => ` would delete ${safe(p)}`)] : "Nothing to push"));
271
+ }
272
+ // Moves and renames keep the file's history (A1.17). One the server can't do in place (a new folder, or both
273
+ // name and folder changed) goes up as a new file and the old one to Trash, like before.
274
+ let moved = 0;
275
+ for (const m of moves) {
276
+ const done = await moveOnServer(ctx, project.workspaceId, m).catch(() => false);
277
+ const local = /** @type {import("../sync/local.mjs").LocalFile} */ (m.local);
278
+ if (done) {
279
+ delete state.files[/** @type {string} */ (m.from)];
280
+ recordBase(state, m.path, { nodeId: /** @type {any} */ (m.remote).nodeId, version: /** @type {any} */ (m.remote).version, hash: local.hash, abs: local.abs });
281
+ moved++;
282
+ } else {
283
+ items.push({ ...m, action: "push", state: "added", base: undefined, remote: undefined });
284
+ deletions.push({ ...m, path: /** @type {string} */ (m.from), action: "delete-remote", state: "deleted" });
285
+ }
286
+ }
287
+ moves = moves.filter((m) => state.files[m.path]);
288
+ const task = ctx.flags.task ? await resolveTask(ctx, String(ctx.flags.task)) : null;
289
+ const uploaded = items.length
290
+ ? await uploadFiles(ctx.api, {
291
+ workspaceId: project.workspaceId,
292
+ items: items.map((i) => ({ path: i.path, abs: /** @type {any} */ (i.local).abs, size: /** @type {any} */ (i.local).size, hash: /** @type {any} */ (i.local).hash, baseVersion: ctx.flags.force && i.state === "conflict" ? null : i.base?.baseVersion ?? null })),
293
+ taskId: task?.id ?? null,
294
+ as,
295
+ message: ctx.flags.message ?? null,
296
+ keepBoth: Boolean(ctx.flags["keep-both"]),
297
+ folder: ctx.flags.folder ?? null,
298
+ confirmSecrets: Boolean(ctx.flags["confirm-secrets"]),
299
+ keyBase,
300
+ }, (done, total) => { if (total > 1) ctx.out.note(ctx.out.c.muted(`Uploading ${done} of ${total}`)); }).catch((error) => handlePushError(ctx, root, state, error instanceof CliError && error.code === "OFFLINE" ? queueOffline() : error))
301
+ : { files: [], transition: null };
302
+
303
+ for (const f of uploaded.files) {
304
+ const item = items.find((i) => i.path === f.path);
305
+ if (item?.local) recordBase(state, f.path, { nodeId: f.nodeId, version: f.version, hash: f.contentHash ?? item.local.hash, abs: item.local.abs });
306
+ if (item?.local && f.status !== "unchanged") saveBaseCopy(root, item.local.hash, fs.readFileSync(item.local.abs));
307
+ }
308
+ // Deleting on the server is a change other people see: it asks first (report §26.6).
309
+ let deleted = 0;
310
+ if (deletions.length && (await confirm(ctx, { key: "delete", question: `Move ${deletions.length} file(s) you deleted here to the workspace Trash?`, preview: deletions.map((d) => d.path).join("\n"), yesLabel: "Move to Trash", defaultYes: false }))) {
311
+ for (const d of deletions) {
312
+ await ctx.api.post("/api/v1/extension/file-operation", { kind: "trash", projectId: project.workspaceId, nodeId: d.remote?.nodeId, expectedUpdatedAt: d.remote?.updatedAt });
313
+ delete state.files[d.path];
314
+ deleted++;
315
+ }
316
+ }
317
+ writeState(root, state);
318
+
319
+ const changedFiles = uploaded.files.filter((/** @type {any} */ f) => f.status !== "unchanged");
320
+ const data = { files: uploaded.files.map((/** @type {any} */ f) => ({ path: f.path, status: f.status, version: f.version, versionTransition: f.versionTransition })), task: task ? { id: task.id, number: task.taskNumber, title: task.title } : null, as, transition: uploaded.transition, deleted, moved, moves: moves.map((m) => ({ from: m.from, to: m.path })), behind: behind.map((b) => b.path) };
321
+ ctx.out.result("nb.push/1", data, (d) => {
322
+ const { c, sym } = ctx.out;
323
+ if (!changedFiles.length && !d.deleted && !d.moved) return `Nothing changed${d.behind.length ? c.muted(` · ${d.behind.length} newer on the server: nb pull`) : ""}`;
324
+ const where = d.task ? ` to #${d.task.number ?? ""} ${safe(d.task.title ?? "")}${d.as ? ` as ${d.as}` : ""}` : d.as ? ` as ${d.as}` : "";
325
+ const lines = [`${c.success(sym.done)} Pushed ${changedFiles.length} ${changedFiles.length === 1 ? "file" : "files"}${where}${d.moved ? ` · ${d.moved} moved` : ""}${d.deleted ? ` · ${d.deleted} moved to Trash` : ""}`];
326
+ for (const m of d.moves.slice(0, 20)) lines.push(` ${safe(m.from)} ${c.muted(sym.arrow)} ${safe(m.to)}`);
327
+ for (const f of changedFiles.slice(0, 20)) lines.push(` ${safe(f.path)} ${c.muted(f.status === "new" ? "v1 (new)" : `v${f.version - 1} ${sym.arrow} v${f.version}`)}`);
328
+ if (d.transition) lines.push(d.transition.ok ? ` ${d.transition.outcome === "submitted" ? "Sent for review" : `Task moved to ${String(d.transition.status).replace("_", " ")}`}` : c.warning(` Task status didn't change: ${safe(d.transition.message)}`));
329
+ if (d.behind.length) lines.push(c.muted(` ${d.behind.length} newer on the server: nb pull`));
330
+ return lines;
331
+ });
332
+ return EXIT.ok;
333
+ } finally {
334
+ release();
335
+ }
336
+ }
337
+
338
+ /**
339
+ * Renames in place, or moves to a folder that exists on the server. False when it can't (then: upload + Trash).
340
+ * @param {Context} ctx @param {string} workspaceId @param {PlanItem} m
341
+ */
342
+ async function moveOnServer(ctx, workspaceId, m) {
343
+ const from = /** @type {string} */ (m.from);
344
+ const [fromDir, toDir] = [path.posix.dirname(from), path.posix.dirname(m.path)];
345
+ const [fromName, toName] = [path.posix.basename(from), path.posix.basename(m.path)];
346
+ if (fromDir !== toDir && fromName !== toName) return false;
347
+ const nodeId = /** @type {any} */ (m.remote).nodeId;
348
+ const meta = /** @type {any} */ (await ctx.api.get("/api/v1/extension/file", { query: { projectId: workspaceId, path: from, transfer: "metadata" } }));
349
+ const expectedUpdatedAt = new Date(meta.updatedAt).toISOString();
350
+ if (fromDir === toDir) {
351
+ await ctx.api.post("/api/v1/extension/file-operation", { kind: "rename", projectId: workspaceId, nodeId, name: toName, expectedUpdatedAt });
352
+ return true;
353
+ }
354
+ const parentId = toDir === "/" ? null : (/** @type {any} */ (await ctx.api.get("/api/v1/extension/file", { query: { projectId: workspaceId, path: toDir, transfer: "metadata" } }))).nodeId;
355
+ if (toDir !== "/" && !parentId) return false;
356
+ await ctx.api.post("/api/v1/extension/file-operation", { kind: "move", projectId: workspaceId, nodeId, parentId, expectedUpdatedAt });
357
+ return true;
358
+ }
359
+
360
+ /**
361
+ * Turns server refusals into the folder's state and a clear next step.
362
+ * @param {Context} ctx @param {string} root @param {import("../sync/state.mjs").SyncState} state @param {unknown} error
363
+ * @returns {never}
364
+ */
365
+ function handlePushError(ctx, root, state, error) {
366
+ if (error instanceof CliError && error.code === "VERSION_CONFLICT") {
367
+ const list = /** @type {any} */ (error.details)?.conflicts ?? [];
368
+ for (const conflict of list) state.conflicts[conflict.path] = { remoteVersion: conflict.currentVersion, copy: "" };
369
+ writeState(root, state);
370
+ throw new CliError("VERSION_CONFLICT", error.message, { hint: "Run nb pull (your files stay; the server's version is saved next to them), then nb resolve", details: error.details });
371
+ }
372
+ if (error instanceof CliError && error.code === "SECRET_DETECTED") {
373
+ const findings = /** @type {any} */ (error.details)?.findings ?? [];
374
+ throw new CliError("SECRET_DETECTED", `Not pushed: ${findings.map((/** @type {any} */ f) => `${f.path}${f.line ? `:${f.line}` : ""} (${f.rule})`).join(", ")}`, { hint: "Remove the secret, or add --confirm-secrets if it's safe to share", details: error.details });
375
+ }
376
+ throw error;
377
+ }
378
+
379
+ // ───────────────────────────────── sync
380
+
381
+ /** Pull, then push changed tracked files; new files are pushed by naming them (report §17.4). @param {Context} ctx */
382
+ export async function sync(ctx) {
383
+ oldStatusFlags(ctx);
384
+ await replayQueue(ctx);
385
+ const pulled = await pull(ctx, { quietResult: true });
386
+ if (pulled === EXIT.conflict) {
387
+ ctx.out.warn("Conflicts after pulling: settle them with nb resolve, then nb sync again");
388
+ return status(ctx);
389
+ }
390
+ const plan = await buildPlan(ctx);
391
+ const tracked = plan.items.filter((i) => i.action === "push" && i.base);
392
+ const fresh = plan.items.filter((i) => i.action === "push" && !i.base);
393
+ if (!tracked.length) {
394
+ ctx.out.result("nb.sync/1", { pushed: [], newFiles: fresh.map((i) => i.path) }, (d) => [`${ctx.out.c.success(ctx.out.sym.done)} In sync`, ...(d.newFiles.length ? [ctx.out.c.muted(` ${d.newFiles.length} new file(s) here aren't on NetworkBase yet: nb push <files>`)] : [])]);
395
+ return EXIT.ok;
396
+ }
397
+ const ctx2 = /** @type {Context} */ ({ ...ctx, positionals: [], flags: { ...ctx.flags, all: true } });
398
+ return push(ctx2);
399
+ }
400
+
401
+ /**
402
+ * Sends pushes queued while offline, oldest first. A conflict stops the queue there (later pushes may depend on
403
+ * it); still offline keeps it; expired entries are dropped with a note (A12.4).
404
+ * @param {Context} ctx
405
+ */
406
+ async function replayQueue(ctx) {
407
+ const { root } = ctx.requireRoot();
408
+ const entries = readQueue(root);
409
+ if (!entries.length) return;
410
+ const fresh = entries.filter((e) => Date.now() - Date.parse(e.queuedAt) < QUEUE_TTL_MS);
411
+ if (fresh.length < entries.length) ctx.out.warn(`Dropped ${entries.length - fresh.length} queued push(es) older than 7 days; your files are unchanged, push them again`);
412
+ writeQueue(root, fresh);
413
+ for (const entry of fresh) {
414
+ ctx.out.note(ctx.out.c.muted(`Sending a push queued ${entry.queuedAt.slice(0, 16).replace("T", " ")}`));
415
+ const ctx2 = /** @type {Context} */ ({ ...ctx, cwd: root, positionals: entry.paths, flags: { ...ctx.flags, ...entry.flags, done: false, wip: false }, queueId: entry.id });
416
+ try {
417
+ await push(ctx2);
418
+ } catch (error) {
419
+ if (error instanceof CliError && error.code === "OFFLINE") throw new CliError("OFFLINE", `Still offline: ${fresh.length} push(es) wait in the queue`, { hint: "Run nb sync when you're online" });
420
+ writeQueue(root, readQueue(root).filter((e) => e.id !== entry.id));
421
+ throw error;
422
+ }
423
+ writeQueue(root, readQueue(root).filter((e) => e.id !== entry.id));
424
+ }
425
+ }
@@ -0,0 +1,98 @@
1
+ // nb inbox (report A11.1–A11.3): the app's notification tray in the terminal, the same items and unread counts.
2
+ // --follow waits for new ones (long-poll, A11.2); --notify also shows them as desktop notifications (opt-in, D22).
3
+ import { execFile } from "node:child_process";
4
+
5
+ import { CliError, EXIT, usage } from "../errors.mjs";
6
+ import { safe } from "../print/style.mjs";
7
+ import { formatDate } from "./tasks.mjs";
8
+
9
+ /** @typedef {import("../context.mjs").Context} Context */
10
+
11
+ /** @param {Context} ctx */
12
+ async function page(ctx) {
13
+ return /** @type {any} */ (await ctx.api.get("/api/v1/inbox", { query: { limit: 50 } }));
14
+ }
15
+
16
+ /** @param {Context} ctx */
17
+ export async function inbox(ctx) {
18
+ if (ctx.flags.follow) return follow(ctx);
19
+ const p = await page(ctx);
20
+ const items = (/** @type {any[]} */ (p.items)).filter((i) => !ctx.flags.unread || !i.readAt);
21
+ const { c, sym } = ctx.out;
22
+ ctx.out.result("nb.inbox/1", { unread: p.unreadCount, items }, (d) => d.items.length ? [
23
+ `${d.unread} unread`,
24
+ ...d.items.map((i, n) => `${i.readAt ? " " : c.brand(sym.brand)} ${String(n + 1).padStart(2)} ${c.muted(formatDate(i.activityAt ?? i.createdAt))} ${safe(i.title)}${i.body ? c.muted(` · ${safe(String(i.body)).replace(/\n/g, " ").slice(0, 80)}`) : ""}`),
25
+ c.muted(" nb inbox read <n> · nb inbox open <n> · nb inbox --follow"),
26
+ ] : "Nothing in your inbox", { page: true });
27
+ }
28
+
29
+ /** Items by their number in `nb inbox` (newest first) or id. @param {Context} ctx */
30
+ async function pick(ctx) {
31
+ const refs = ctx.positionals;
32
+ if (!refs.length && !ctx.flags.all) throw usage("Which ones?", "nb inbox read 1 2, or nb inbox read --all");
33
+ const items = /** @type {any[]} */ ((await page(ctx)).items);
34
+ return refs.map((r) => {
35
+ const hit = /^\d+$/.test(r) ? items[Number(r) - 1] : items.find((i) => i.id.startsWith(r));
36
+ if (!hit) throw new CliError("NOT_FOUND", `No inbox item ${r}`, { hint: "nb inbox" });
37
+ return hit;
38
+ });
39
+ }
40
+
41
+ /** @param {Context} ctx */
42
+ export async function inboxRead(ctx) {
43
+ const items = ctx.flags.all ? [] : await pick(ctx);
44
+ const res = /** @type {any} */ (await ctx.api.post("/api/v1/inbox/read", ctx.flags.all ? { all: true } : { ids: items.map((i) => i.id) }));
45
+ ctx.out.result("nb.inbox.read/1", { read: res.read }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} Marked ${d.read} read`);
46
+ }
47
+
48
+ /** @param {Context} ctx */
49
+ export async function inboxOpen(ctx) {
50
+ const [item] = await pick(ctx);
51
+ if (!item?.href) throw new CliError("NOT_FOUND", "That item has no page to open");
52
+ const url = new URL(item.href, ctx.profile.origin).toString();
53
+ const { openInBrowser } = await import("./misc.mjs");
54
+ const opened = await openInBrowser(url);
55
+ await ctx.api.post("/api/v1/inbox/read", { ids: [item.id] });
56
+ ctx.out.result("nb.inbox.open/1", { url, opened }, (d) => (d.opened ? `Opened ${d.url}` : `Open ${d.url}`));
57
+ }
58
+
59
+ /**
60
+ * A desktop notification, without a shell: macOS osascript, Linux notify-send, Windows a PowerShell balloon. Text is
61
+ * passed as arguments, never pasted into a script. @param {string} title @param {string} body
62
+ */
63
+ export function desktopNotify(title, body) {
64
+ const clean = (/** @type {string} */ s) => s.replace(/[\u0000-\u001f\u007f"\\]/g, " ").slice(0, 200);
65
+ const [t, b] = [clean(title), clean(body)];
66
+ const run = (/** @type {string} */ cmd, /** @type {string[]} */ args) => new Promise((resolve) => execFile(cmd, args, { windowsHide: true, timeout: 5000 }, () => resolve(undefined)));
67
+ if (process.platform === "darwin") return run("osascript", ["-e", "on run argv", "-e", "display notification (item 2 of argv) with title (item 1 of argv)", "-e", "end run", t, b]);
68
+ if (process.platform === "linux") return run("notify-send", ["--app-name=NetworkBase", t, b]);
69
+ if (process.platform === "win32") return run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", "param($t,$b) Add-Type -AssemblyName System.Windows.Forms; $n=New-Object System.Windows.Forms.NotifyIcon; $n.Icon=[System.Drawing.SystemIcons]::Information; $n.Visible=$true; $n.ShowBalloonTip(5000,$t,$b,'Info'); Start-Sleep 6", t, b]);
70
+ return Promise.resolve(undefined);
71
+ }
72
+
73
+ /** Waits for new items until Ctrl+C: one line each (NDJSON with --json), and a desktop notification with --notify. @param {Context} ctx */
74
+ async function follow(ctx) {
75
+ let since = new Date().toISOString();
76
+ let stopping = false;
77
+ process.once("SIGINT", () => { stopping = true; });
78
+ if (!ctx.out.json) ctx.out.note(ctx.out.c.muted("Waiting for new notifications. Ctrl+C to stop."));
79
+ let backoff = 1000;
80
+ while (!stopping) {
81
+ try {
82
+ const res = /** @type {any} */ (await ctx.api.get("/api/v1/events", { query: { since, inbox: 1 }, timeoutMs: 40_000 }));
83
+ since = res.cursor;
84
+ backoff = 1000;
85
+ for (const n of res.notifications) {
86
+ if (ctx.out.json) ctx.out.raw(`${JSON.stringify({ schema: "nb.inbox.item/1", data: n })}\n`);
87
+ else ctx.out.raw(`${ctx.out.c.brand(ctx.out.sym.brand)} ${ctx.out.c.muted(n.at.slice(11, 16))} ${safe(n.title)}${n.body ? ctx.out.c.muted(` · ${safe(String(n.body)).replace(/\n/g, " ").slice(0, 80)}`) : ""}\n`);
88
+ if (ctx.flags.notify) await desktopNotify(n.title, n.body ?? "");
89
+ }
90
+ } catch (error) {
91
+ if (error instanceof CliError && (error.code === "UNAUTHORIZED" || error.status === 403)) throw error;
92
+ // Offline or the server is busy: wait longer each time, up to a minute.
93
+ await new Promise((r) => setTimeout(r, backoff));
94
+ backoff = Math.min(60_000, backoff * 2);
95
+ }
96
+ }
97
+ return EXIT.ok;
98
+ }
@@ -0,0 +1,85 @@
1
+ // Linking a folder to a workspace, and unlinking it (report A1.1, A1.20).
2
+ import { execFileSync } from "node:child_process";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+
7
+ import { DIR_NAME, findRoot, writeProjectConfig } from "../config.mjs";
8
+ import { CliError, EXIT, usage } from "../errors.mjs";
9
+ import { safe } from "../print/style.mjs";
10
+ import { ask, confirm } from "../tui/ask.mjs";
11
+
12
+ /** @typedef {import("../context.mjs").Context} Context */
13
+
14
+ /** @param {Context} ctx */
15
+ export async function init(ctx) {
16
+ const target = ctx.positionals[0] ?? ctx.flags.workspace;
17
+ const here = path.resolve(ctx.cwd);
18
+ if (here === path.resolve(os.homedir()) || here === path.parse(here).root) {
19
+ throw usage("Link a project folder, not your home folder or the disk root", "mkdir my-project && cd my-project && nb init <workspace>");
20
+ }
21
+ const outer = findRoot(path.dirname(here));
22
+ if (outer && !ctx.flags.nested && !fs.existsSync(path.join(here, DIR_NAME, "config.json"))) {
23
+ throw usage(`This folder is inside ${outer}, which is already linked`, "Work from there, or pass --nested to link this folder separately");
24
+ }
25
+ const { workspaces } = /** @type {any} */ (await ctx.api.get("/api/v1/extension/workspaces"));
26
+ let chosen = target ? workspaces.find((/** @type {any} */ w) => w.id === target || String(w.slug).toLowerCase() === String(target).toLowerCase()) : null;
27
+ if (target && !chosen) {
28
+ throw new CliError("WORKSPACE_NOT_FOUND", `No workspace ${target} in your list`, { hint: workspaces.length ? `Yours: ${workspaces.slice(0, 8).map((/** @type {any} */ w) => w.slug).join(", ")}` : "Create one at networkbase.in first", details: { workspaces: workspaces.map((/** @type {any} */ w) => ({ slug: w.slug, title: w.title })) } });
29
+ }
30
+ if (!chosen) {
31
+ if (!workspaces.length) throw new CliError("WORKSPACE_NOT_FOUND", "You have no workspaces yet", { hint: "Create one at networkbase.in first" });
32
+ const slug = await ask(ctx, { key: "workspace", header: "Workspace", question: "Which workspace should this folder link to?", options: workspaces.slice(0, 9).map((/** @type {any} */ w, /** @type {number} */ i) => ({ value: w.slug, label: safe(w.title), description: w.slug, recommended: i === 0 })) });
33
+ chosen = workspaces.find((/** @type {any} */ w) => w.slug === slug);
34
+ }
35
+ const remoteRoot = ctx.flags.path ? `/${String(ctx.flags.path).replace(/^\/+|\/+$/g, "")}` : "/";
36
+ writeProjectConfig(here, { workspaceId: chosen.id, slug: chosen.slug, title: chosen.title, remoteRoot: remoteRoot === "/" ? "/" : remoteRoot, startedTask: null, linkedAt: new Date().toISOString() });
37
+ const notes = migrateLegacy(here);
38
+ ctx.out.done(`Linked this folder to ${safe(chosen.title)} (${safe(chosen.slug)})${remoteRoot !== "/" ? ` · only ${remoteRoot}` : ""}`);
39
+ for (const note of notes) ctx.out.warn(note);
40
+ if (ctx.flags.task) {
41
+ const { start } = await import("./tasks.mjs");
42
+ const ctx2 = /** @type {Context} */ ({ ...ctx, root: here, project: { workspaceId: chosen.id, slug: chosen.slug, title: chosen.title, remoteRoot, startedTask: null }, positionals: [String(ctx.flags.task)] });
43
+ await start(ctx2);
44
+ }
45
+ ctx.out.result("nb.init/1", { workspace: { id: chosen.id, slug: chosen.slug, title: chosen.title }, root: here, remoteRoot, notes }, () =>
46
+ ctx.out.c.muted(`Next: nb pull to get the files, or edit and nb push <files>${ctx.flags.task ? "" : " (nb task start <n> to work on a task)"}`));
47
+ }
48
+
49
+ /**
50
+ * 1.x left a mirror folder and maybe a background process (A1.20). The mirror moves aside (never deleted);
51
+ * the old auto-push process is stopped.
52
+ * @param {string} root
53
+ */
54
+ function migrateLegacy(root) {
55
+ const notes = [];
56
+ const dir = path.join(root, DIR_NAME);
57
+ const pidFile = path.join(dir, "daemon.pid");
58
+ if (fs.existsSync(pidFile)) {
59
+ try {
60
+ const { pid } = JSON.parse(fs.readFileSync(pidFile, "utf8"));
61
+ const command = process.platform === "win32" ? "" : execFileSync("ps", ["-o", "command=", "-p", String(pid)], { encoding: "utf8" });
62
+ if (command.includes("--daemon-worker")) { process.kill(pid, "SIGTERM"); notes.push("Stopped the 1.x background auto-push process; nb watch replaces it (in the foreground)."); }
63
+ } catch {
64
+ // Already gone.
65
+ }
66
+ fs.rmSync(pidFile, { force: true });
67
+ }
68
+ const mirror = path.join(dir, "mirror");
69
+ if (fs.existsSync(mirror)) {
70
+ fs.renameSync(mirror, path.join(dir, "legacy-mirror"));
71
+ notes.push(`1.x kept a copy of the workspace in ${DIR_NAME}/mirror; it moved to ${DIR_NAME}/legacy-mirror. Edits made only there aren't pushed: copy them into this folder, then nb push.`);
72
+ }
73
+ for (const old of ["cache.json", "last-sync.json"]) fs.rmSync(path.join(dir, old), { force: true });
74
+ return notes;
75
+ }
76
+
77
+ /** @param {Context} ctx */
78
+ export async function unlink(ctx) {
79
+ const { root } = ctx.requireRoot();
80
+ const ok = await confirm(ctx, { key: "unlink", question: `Unlink ${root}? Your files stay; NetworkBase's sync records here are removed.`, yesLabel: "Unlink", defaultYes: false });
81
+ if (!ok) return EXIT.cancelled;
82
+ fs.rmSync(path.join(root, DIR_NAME), { recursive: true, force: true });
83
+ if (ctx.flags["purge-local"]) fs.rmSync(path.join(root, ".tasks"), { recursive: true, force: true });
84
+ ctx.out.result("nb.unlink/1", { root, purgedTasks: Boolean(ctx.flags["purge-local"]) }, () => `${ctx.out.c.success(ctx.out.sym.done)} Unlinked ${root}`);
85
+ }