nemu-cli 1.4.0 → 1.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,59 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.6.1
4
+
5
+ When `nemu sync` merges a note automatically, it now records the merge in the vault's merge log,
6
+ with this computer's text from before the merge, so the console can restore either side with one
7
+ click. A merge log that cannot be reached never fails the sync; the run reports it as a notice.
8
+
9
+ `-w <workspace>` works. It was read as a switch, so the workspace after it was dropped and the
10
+ command ran in your first workspace; `--workspace` was not affected. `-o` and `-d` had the same
11
+ problem and are fixed too.
12
+
13
+ `nemu vault link` on a folder that is no longer linked, such as a drive folder that was emptied and
14
+ linked again, now starts fresh and downloads the vault, instead of treating every missing file as
15
+ deleted and stopping at the mass-delete guard.
16
+
17
+ Sync never writes `.claude/`, `.codex/`, `.cursor/`, `.vscode/`, `.idea/`, `.husky/`,
18
+ `.github/workflows/` or `.git/hooks/`, in either direction, because files there can run code when
19
+ you open the folder in an editor or an agent. A folder inside the vault that is a symbolic link to
20
+ somewhere else is never written through.
21
+
22
+ ## 1.6.0
23
+
24
+ `nemu sync` keeps a folder, such as an Obsidian vault, in step with a Context vault.
25
+ `nemu vault link <folder>` links it once (`--vault <name|id>` picks the vault, `--create` makes
26
+ one) and writes `.nemu/vault.json`, without which sync refuses to run, so an unmounted drive never
27
+ looks like a folder whose notes were deleted. `nemu sync --watch` keeps syncing until stopped.
28
+ `nemu vault list`, `status` and `unlink` round it off.
29
+
30
+ Each run reads the vault's changes since the last run, or lists every file when the device has been
31
+ away longer than the change history, and compares files by content, never by modification time.
32
+ Markdown changed on both sides is merged line by line when the edits do not overlap, treating CRLF
33
+ and LF as equal and keeping your file's line endings. Otherwise the vault's version keeps the name
34
+ and yours is saved beside it as `Note (conflict, <device>, <date> <time>).md`; no note ever gets
35
+ conflict markers. `--conflicts=file` always writes the conflict file instead. An edit wins over a
36
+ delete, a rename is sent as a move so the note keeps its history, and two renames onto one name
37
+ give the second ` (2)`.
38
+
39
+ A run that would delete more than 10 files, every file, or at least 3 files and more than 10% of
40
+ the vault stops and deletes nothing until you pass `--allow-deletes`. `.nemu/lock` keeps two syncs
41
+ off one folder and is taken over when its process is gone. Downloads are written to a temporary file
42
+ and renamed; uploads wait until a file has been unchanged for 2 seconds and reads the same twice.
43
+ Symbolic links, files above the plan's size, case clashes and names Windows cannot hold are skipped
44
+ and listed. Out of storage stops uploads and keeps downloading; a revoked device or key stops sync
45
+ and never deletes a local file. `.git/`, `node_modules/`, `.trash/`, `.DS_Store`, `._*` and
46
+ `.obsidian/workspace*.json` are never synced, the rest of `.obsidian/` is opt in per device, and
47
+ `.nemuignore` adds patterns.
48
+
49
+ ## 1.5.0
50
+
51
+ `nemu login key` signs in with a workspace API key, the same `sk_` key that calls the gateway. It
52
+ asks for the key, or reads `NEMU_API_KEY`, and shows the workspace and access the key has. Context
53
+ and vault commands use the unified routes under `/api/v1`, and work in the workspace you choose, so
54
+ members share the workspace's Context. Earlier versions call routes that no longer exist and need
55
+ this update.
56
+
3
57
  ## 1.4.0
4
58
 
5
59
  `nemu setup opencode` adds the Nemu MCP server to OpenCode's global config,
package/LICENSE CHANGED
File without changes
package/README.md CHANGED
@@ -181,6 +181,44 @@ and again on the server, and saved notes are always given to agents as data, nev
181
181
  Each computer you sign in from is registered as a device. Revoke one in the console under Context to
182
182
  stop it reading or writing; what it already saved stays.
183
183
 
184
+ ## Syncing a folder with a vault
185
+
186
+ A vault is an Obsidian compatible folder of Markdown notes kept in your workspace's Context.
187
+ `nemu sync` keeps a folder on this computer in step with one.
188
+
189
+ ```bash
190
+ nemu vault link ~/Notes --vault "Notes" # or --create for a new vault named after the folder
191
+ nemu sync ~/Notes # one run
192
+ nemu sync ~/Notes --watch # keep syncing until Ctrl C
193
+ ```
194
+
195
+ | Command | Does |
196
+ | --- | --- |
197
+ | `nemu vault list` | Vaults in the workspace |
198
+ | `nemu vault link <folder> [--vault <name\|id>] [--create] [--obsidian]` | Link a folder; writes `<folder>/.nemu/vault.json` |
199
+ | `nemu sync [folder] [--watch] [--dry-run] [--conflicts=merge\|file] [--allow-deletes]` | Sync a linked folder (the current one, or the nearest parent that is linked) |
200
+ | `nemu vault status [folder]` | Last sync, device settings and open conflict copies |
201
+ | `nemu vault unlink [folder]` | Stop syncing; the files stay |
202
+
203
+ Files are compared by content, never by modification time. A note changed on both sides is merged
204
+ line by line when the edits do not overlap; otherwise the vault's version keeps the name and yours
205
+ is saved beside it as `Note (conflict, <device>, <date> <time>).md`. Conflict markers are never
206
+ written into a note. `--conflicts=file` always writes the conflict file instead of merging, and is
207
+ remembered for this device. An edit wins over a delete, and a rename keeps the note's history.
208
+
209
+ Sync refuses to run without `.nemu/vault.json`, so an unmounted drive never reads as "everything was
210
+ deleted". A run that would delete more than 10 files, every file, or at least 3 files and more than
211
+ 10% of the vault stops and deletes nothing; pass `--allow-deletes` if you meant it. Symbolic links,
212
+ files above the plan's size, case clashes and names Windows cannot hold are skipped and listed.
213
+ `.git/`, `node_modules/`, `.trash/`, `.DS_Store`, `._*` and `.obsidian/workspace*.json` are never
214
+ synced, the rest of `.obsidian/` only with `--obsidian`, and a `.nemuignore` file adds patterns.
215
+ What each folder last agreed with its vault is kept in `~/.nemu/vaults/<vault id>.json`.
216
+
217
+ `tests/sim/simulate.ts` runs several fake devices with random edits, moves, deletes, crashes and
218
+ duplicated requests against a development platform and checks that they converge without losing a
219
+ byte. It does nothing unless `NEMU_SIM_API_URL`, `NEMU_SIM_API_KEY` and `NEMU_SIM_ROOT` are set, so
220
+ `bun test` stays offline.
221
+
184
222
  ## Error references
185
223
 
186
224
  After you sign in, a command that fails sends a small report and prints a reference like
package/dist/args.js CHANGED
@@ -1,3 +1,4 @@
1
+ const SHORT_WITH_VALUE = new Set(["w", "o", "d"]);
1
2
  export function parse_args(argv) {
2
3
  const positional = [];
3
4
  const flags = {};
@@ -24,7 +25,14 @@ export function parse_args(argv) {
24
25
  continue;
25
26
  }
26
27
  if (token.startsWith("-") && token.length > 1) {
27
- flags[token.slice(1)] = true;
28
+ const name = token.slice(1);
29
+ const next = argv[i + 1];
30
+ if (SHORT_WITH_VALUE.has(name) && next !== undefined && !next.startsWith("-")) {
31
+ flags[name] = next;
32
+ i += 1;
33
+ continue;
34
+ }
35
+ flags[name] = true;
28
36
  continue;
29
37
  }
30
38
  positional.push(token);
@@ -97,7 +97,7 @@ export async function fresh_credentials() {
97
97
  if (current === null) {
98
98
  throw new CliError("Not signed in. Run nemu login.", "not_signed_in");
99
99
  }
100
- if (is_fresh(current))
100
+ if (current.kind === "key" || is_fresh(current))
101
101
  return current;
102
102
  const release = await acquire_lock();
103
103
  try {
@@ -0,0 +1,95 @@
1
+ import { z } from "zod";
2
+ import { API_VERSION, api_url, write_credentials } from "../config.js";
3
+ import { CliError } from "../errors.js";
4
+ import { VERSION } from "../version.js";
5
+ import { done, is_json_mode } from "../output.js";
6
+ import { ask_secret, bold, dim, is_interactive, out, success } from "../ui.js";
7
+ const KEY_PATTERN = /^sk_[a-z]{5}-[a-z]{5}\.[A-Za-z0-9]{40}$/;
8
+ const description_schema = z.object({
9
+ data: z.object({
10
+ kind: z.literal("key"),
11
+ name: z.string(),
12
+ workspace: z.object({ id: z.string(), name: z.string() }),
13
+ expires_at: z.string().nullable(),
14
+ scopes: z.array(z.string()),
15
+ access: z.array(z.object({ scope: z.string(), label: z.string(), granted: z.boolean() })),
16
+ }),
17
+ });
18
+ async function read_stdin() {
19
+ const chunks = [];
20
+ for await (const chunk of process.stdin) {
21
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));
22
+ }
23
+ return Buffer.concat(chunks).toString("utf8");
24
+ }
25
+ async function read_key() {
26
+ const from_env = process.env.NEMU_API_KEY;
27
+ if (from_env !== undefined && from_env.trim().length > 0)
28
+ return from_env.trim();
29
+ if (is_interactive())
30
+ return (await ask_secret("API key:")).trim();
31
+ return (await read_stdin()).trim();
32
+ }
33
+ export async function describe_key(url, key) {
34
+ let response;
35
+ try {
36
+ response = await fetch(`${url}/api/v1/key`, {
37
+ headers: {
38
+ authorization: `Bearer ${key}`,
39
+ "nemu-api-version": API_VERSION,
40
+ "user-agent": `nemu-cli/${VERSION}`,
41
+ },
42
+ signal: AbortSignal.timeout(20_000),
43
+ });
44
+ }
45
+ catch {
46
+ throw new CliError(`Could not reach ${url}.`, "network_failed");
47
+ }
48
+ if (response.status === 401 || response.status === 403) {
49
+ throw new CliError("This key is invalid, disabled, expired or not allowed from this address.", "key_rejected");
50
+ }
51
+ const parsed = description_schema.safeParse(await response.json().catch(() => null));
52
+ if (!response.ok || !parsed.success) {
53
+ throw new CliError("Nemu could not describe this key.", "key_describe_failed", {
54
+ status: response.status,
55
+ });
56
+ }
57
+ return parsed.data.data;
58
+ }
59
+ export async function login_key() {
60
+ const url = api_url();
61
+ const key = await read_key();
62
+ if (!KEY_PATTERN.test(key)) {
63
+ throw new CliError("That is not a Nemu API key. Keys look like sk_xxxxx-xxxxx. followed by 40 letters and digits.", "invalid_key_format");
64
+ }
65
+ const description = await describe_key(url, key);
66
+ await write_credentials({
67
+ kind: "key",
68
+ access_token: key,
69
+ expires_at: Number.MAX_SAFE_INTEGER,
70
+ scope: description.scopes.join(" "),
71
+ api_url: url,
72
+ account: `key ${description.name}`,
73
+ workspace: description.workspace,
74
+ });
75
+ if (is_json_mode()) {
76
+ done("Signed in with an API key", {
77
+ key: description.name,
78
+ workspace: description.workspace,
79
+ scopes: description.scopes,
80
+ expires_at: description.expires_at,
81
+ });
82
+ return 0;
83
+ }
84
+ success(`Signed in with the key ${bold(description.name)} for the workspace ${bold(description.workspace.name)}`);
85
+ out();
86
+ for (const row of description.access) {
87
+ out(` ${row.granted ? "yes" : " no"} ${row.label}`);
88
+ }
89
+ out();
90
+ if (description.expires_at !== null) {
91
+ out(dim(` The key expires on ${description.expires_at.slice(0, 10)}.`));
92
+ }
93
+ out(dim(" The key is stored only on this machine. nemu logout removes it."));
94
+ return 0;
95
+ }
@@ -1,6 +1,7 @@
1
1
  import { NemuDeviceError } from "@nemu-ai/sdk";
2
2
  import { api_url, is_expired, read_credentials, write_credentials, } from "../config.js";
3
3
  import { device_client } from "../session.js";
4
+ import { login_key } from "./key.js";
4
5
  import { verify_device } from "../device.js";
5
6
  import { bool_flag } from "../args.js";
6
7
  import { done, is_json_mode } from "../output.js";
@@ -15,6 +16,8 @@ async function account_name(nemu) {
15
16
  }
16
17
  }
17
18
  export async function login(args) {
19
+ if (args.positional[0] === "key")
20
+ return login_key();
18
21
  const url = api_url();
19
22
  const force = bool_flag(args, "force", "f");
20
23
  const no_browser = bool_flag(args, "no-browser");
@@ -196,8 +196,8 @@ const SNIPPETS = {
196
196
  text: JSON.stringify({ mcp: { nemu: { type: "local", command: ["nemu", "mcp", "--client", "opencode"], enabled: true } } }, null, 2),
197
197
  },
198
198
  remote: {
199
- where: "Any client that supports remote MCP over HTTP (create a Context key in the dashboard first)",
200
- text: JSON.stringify({ url: "https://app.nemu.cc/api/mcp", headers: { Authorization: "Bearer <your Context key>" } }, null, 2),
199
+ where: "Any client that supports remote MCP over HTTP (create an API key with Context access on the Keys page first)",
200
+ text: JSON.stringify({ url: "https://app.nemu.cc/api/mcp", headers: { Authorization: "Bearer <your API key>" } }, null, 2),
201
201
  },
202
202
  };
203
203
  function mcp_config(args) {
@@ -0,0 +1,197 @@
1
+ import { resolve } from "node:path";
2
+ import { bool_flag, flag } from "../args.js";
3
+ import { device_name } from "../device.js";
4
+ import { CliError } from "../errors.js";
5
+ import { emit, is_json_mode } from "../output.js";
6
+ import { bold, cyan, dim, fail, green, out, red } from "../ui.js";
7
+ import { open_linked } from "../vault/connect.js";
8
+ import { run_sync } from "../vault/engine.js";
9
+ import { find_root, read_marker } from "../vault/state.js";
10
+ import { watch_folder } from "../vault/watch.js";
11
+ function settings_from(args) {
12
+ const settings = {};
13
+ const conflicts = flag(args, "conflicts");
14
+ if (conflicts !== undefined) {
15
+ if (conflicts !== "merge" && conflicts !== "file") {
16
+ throw new CliError("--conflicts is merge or file.", "invalid_arguments");
17
+ }
18
+ settings.conflicts = conflicts;
19
+ }
20
+ const obsidian = flag(args, "obsidian");
21
+ if (obsidian !== undefined || bool_flag(args, "obsidian")) {
22
+ if (obsidian !== undefined && obsidian !== "on" && obsidian !== "off") {
23
+ throw new CliError("--obsidian is on or off.", "invalid_arguments");
24
+ }
25
+ settings.obsidian = obsidian !== "off";
26
+ }
27
+ return settings;
28
+ }
29
+ async function root_of(args) {
30
+ const raw = args.positional[0];
31
+ if (raw !== undefined) {
32
+ const folder = resolve(raw);
33
+ if ((await read_marker(folder)) === null) {
34
+ throw new CliError(`${folder} has no .nemu/vault.json, so it is not a linked vault folder. Nothing was synced. If it lives on a drive, check that the drive is mounted.`, "not_linked");
35
+ }
36
+ return folder;
37
+ }
38
+ const found = await find_root(process.cwd());
39
+ if (found === null) {
40
+ throw new CliError("This folder is not linked to a vault. Run nemu vault link <folder> first, or pass the folder to nemu sync.", "not_linked");
41
+ }
42
+ return found;
43
+ }
44
+ function print_event(event) {
45
+ switch (event.kind) {
46
+ case "pulled":
47
+ out(` ${cyan("↓")} ${event.path}`);
48
+ return;
49
+ case "pushed":
50
+ out(` ${green("↑")} ${event.path}`);
51
+ return;
52
+ case "restored":
53
+ out(` ${green("↑")} ${event.path} ${dim("(restored, edited here after it was deleted elsewhere)")}`);
54
+ return;
55
+ case "merged":
56
+ out(` ${green("⇄")} ${event.path} ${dim("(merged edits from both sides)")}`);
57
+ return;
58
+ case "deleted_local":
59
+ out(` ${red("−")} ${event.path} ${dim("(deleted elsewhere)")}`);
60
+ return;
61
+ case "deleted_remote":
62
+ out(` ${red("−")} ${event.path} ${dim("(deleted here, removed from the vault; history keeps it)")}`);
63
+ return;
64
+ case "moved":
65
+ out(` ${cyan("→")} ${event.from} ${dim("to")} ${event.to}`);
66
+ return;
67
+ case "conflict":
68
+ out(` ${red("!")} ${event.path} ${dim("conflict: your version is kept as")} ${event.copy}`);
69
+ return;
70
+ case "skipped":
71
+ out(dim(` · ${event.path}: ${event.reason}`));
72
+ return;
73
+ case "notice":
74
+ out(dim(` ${event.message}`));
75
+ return;
76
+ }
77
+ }
78
+ function describe(action) {
79
+ switch (action.kind) {
80
+ case "pull":
81
+ return `download ${action.path}`;
82
+ case "push":
83
+ return `upload ${action.local.path}${action.reason === "new" ? " (new)" : ""}`;
84
+ case "merge":
85
+ return `merge ${action.remote.path}`;
86
+ case "keep_both":
87
+ return `keep both versions of ${action.remote.path}; yours becomes ${action.copy_path}`;
88
+ case "delete_local":
89
+ return `delete ${action.disk} here (deleted elsewhere)`;
90
+ case "delete_remote":
91
+ return action.counted ? `delete ${action.path} from the vault` : null;
92
+ case "move_remote":
93
+ return `move ${action.from} to ${action.to} in the vault`;
94
+ case "rename_local":
95
+ return `move ${action.from} to ${action.to} here`;
96
+ case "adopt":
97
+ case "forget":
98
+ return null;
99
+ }
100
+ }
101
+ function plural(count, word) {
102
+ return `${count} ${word}${count === 1 ? "" : "s"}`;
103
+ }
104
+ function summary(report) {
105
+ const parts = [
106
+ report.pulled.length > 0 ? `${report.pulled.length} down` : "",
107
+ report.pushed.length > 0 ? `${report.pushed.length} up` : "",
108
+ report.merged.length > 0 ? `${report.merged.length} merged` : "",
109
+ report.moved.length > 0 ? `${report.moved.length} moved` : "",
110
+ report.deleted_local.length + report.deleted_remote.length > 0
111
+ ? `${report.deleted_local.length + report.deleted_remote.length} deleted`
112
+ : "",
113
+ report.conflicts.length > 0 ? plural(report.conflicts.length, "conflict") : "",
114
+ ].filter((part) => part.length > 0);
115
+ return parts.length === 0 ? "Already in sync" : parts.join(", ");
116
+ }
117
+ function print_report(name, report) {
118
+ if (report.dry_run) {
119
+ const lines = report.planned.map(describe).filter((line) => line !== null);
120
+ out(` ${bold(name)} ${dim("dry run, nothing was changed")}`);
121
+ if (lines.length === 0)
122
+ out(dim(" Already in sync."));
123
+ for (const line of lines)
124
+ out(` ${line}`);
125
+ return;
126
+ }
127
+ if (report.waiting.length > 0) {
128
+ out(dim(` Still being written, synced on the next run: ${report.waiting.join(", ")}`));
129
+ }
130
+ if (report.blocked !== null)
131
+ fail(`Uploads stopped: ${report.blocked.message} Downloads continued.`);
132
+ out(`${green("✓")} ${bold(name)} ${summary(report)}`);
133
+ }
134
+ function json_report(report) {
135
+ const { planned, ...rest } = report;
136
+ return {
137
+ ok: true,
138
+ ...rest,
139
+ ...(report.dry_run ? { planned: planned.map(describe).filter((line) => line !== null) } : {}),
140
+ };
141
+ }
142
+ export async function sync(args) {
143
+ const root = await root_of(args);
144
+ const marker = (await read_marker(root));
145
+ const linked = await open_linked(marker);
146
+ const settings = settings_from(args);
147
+ const json = is_json_mode();
148
+ const once = (lock) => run_sync({
149
+ root,
150
+ api: linked.api,
151
+ state_path: linked.state_path,
152
+ device: device_name(),
153
+ dry_run: bool_flag(args, "dry-run"),
154
+ allow_deletes: bool_flag(args, "allow-deletes"),
155
+ settings,
156
+ lock,
157
+ on_event: json ? undefined : print_event,
158
+ });
159
+ if (!bool_flag(args, "watch") || bool_flag(args, "dry-run")) {
160
+ const report = await once(true);
161
+ if (json)
162
+ emit(json_report(report));
163
+ else
164
+ print_report(marker.vault_name, report);
165
+ return report.blocked === null ? 0 : 2;
166
+ }
167
+ if (!json)
168
+ out(dim(` Watching ${root}. Press Ctrl+C to stop.`));
169
+ let exit = 0;
170
+ await watch_folder({
171
+ root,
172
+ run: async () => {
173
+ const report = await once(false);
174
+ const quiet = report.pulled.length + report.pushed.length + report.merged.length + report.moved.length +
175
+ report.deleted_local.length + report.deleted_remote.length + report.conflicts.length ===
176
+ 0;
177
+ if (json)
178
+ emit(json_report(report));
179
+ else if (!quiet)
180
+ print_report(marker.vault_name, report);
181
+ },
182
+ on_error: (error) => {
183
+ const code = error instanceof CliError ? error.code : "unexpected";
184
+ const message = error instanceof Error ? error.message : String(error);
185
+ if (json)
186
+ emit({ ok: false, error: message, code });
187
+ else
188
+ fail(message);
189
+ if (code === "sync_stopped" || code === "not_linked" || code === "server_mismatch") {
190
+ exit = 1;
191
+ return "stop";
192
+ }
193
+ return "continue";
194
+ },
195
+ });
196
+ return exit;
197
+ }
@@ -0,0 +1,189 @@
1
+ import { mkdir, readdir } from "node:fs/promises";
2
+ import { basename, dirname, resolve } from "node:path";
3
+ import { bool_flag, flag } from "../args.js";
4
+ import { CliError } from "../errors.js";
5
+ import { emit, is_json_mode, table } from "../output.js";
6
+ import { bold, dim, out, success } from "../ui.js";
7
+ import { create_vault, list_vaults, VaultApi } from "../vault/api.js";
8
+ import { cli_transport, client_label, signed_in } from "../vault/connect.js";
9
+ import { is_conflict_copy } from "../vault/paths.js";
10
+ import { empty_state, find_root, marker_path, read_marker, read_state, remove_marker, remove_state, state_path_for, write_marker, write_state, } from "../vault/state.js";
11
+ import { is_default_ignored } from "../vault/ignore.js";
12
+ const USAGE = "Use: nemu vault list | link <folder> [--vault <name|id>] [--create] [--obsidian] | unlink [folder] | status [folder]";
13
+ function size_of(bytes) {
14
+ if (bytes === undefined)
15
+ return "";
16
+ if (bytes < 1024 * 1024)
17
+ return `${Math.ceil(bytes / 1024)} KB`;
18
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
19
+ }
20
+ async function list(args) {
21
+ await signed_in();
22
+ const vaults = await list_vaults(cli_transport(flag(args, "workspace", "w")));
23
+ table(vaults.map((vault) => ({
24
+ id: vault.id,
25
+ name: vault.name,
26
+ notes: vault.notes ?? "",
27
+ size: size_of(vault.stored_bytes),
28
+ })), ["id", "name", "notes", "size"], "No vaults yet. Create one with nemu vault link <folder> --create.");
29
+ return 0;
30
+ }
31
+ function pick_vault(vaults, wanted) {
32
+ if (wanted === undefined)
33
+ return vaults.length === 1 ? vaults[0] : null;
34
+ return (vaults.find((vault) => vault.id === wanted) ??
35
+ vaults.find((vault) => vault.name.toLowerCase() === wanted.toLowerCase()) ??
36
+ null);
37
+ }
38
+ async function link(args) {
39
+ const raw = args.positional[1];
40
+ if (raw === undefined)
41
+ throw new CliError(USAGE, "invalid_arguments");
42
+ const folder = resolve(raw);
43
+ const credentials = await signed_in();
44
+ const workspace = flag(args, "workspace", "w");
45
+ const wanted = flag(args, "vault");
46
+ const create = bool_flag(args, "create");
47
+ const enclosing = await find_root(dirname(folder));
48
+ if (enclosing !== null && enclosing !== folder) {
49
+ throw new CliError(`${folder} is inside ${enclosing}, which is already linked to a vault.`, "already_linked");
50
+ }
51
+ await mkdir(folder, { recursive: true });
52
+ const existing = await read_marker(folder);
53
+ const transport = cli_transport(workspace);
54
+ const vaults = await list_vaults(transport);
55
+ let vault = pick_vault(vaults, wanted);
56
+ if (vault === null && create) {
57
+ vault = await create_vault(transport, wanted ?? basename(folder));
58
+ }
59
+ if (vault === null) {
60
+ const names = vaults.map((entry) => `"${entry.name}"`).join(", ");
61
+ throw new CliError(vaults.length === 0
62
+ ? "This workspace has no vaults yet. Add --create to make one named after the folder."
63
+ : wanted === undefined
64
+ ? `Choose a vault with --vault <name|id>: ${names}. Or add --create for a new one.`
65
+ : `No vault is called "${wanted}". Have: ${names}. Add --create to make it.`, "vault_not_found");
66
+ }
67
+ if (existing !== null && existing.vault_id !== vault.id) {
68
+ throw new CliError(`${folder} is already linked to the vault "${existing.vault_name}". Run nemu vault unlink ${folder} first.`, "already_linked");
69
+ }
70
+ const state_path = state_path_for(vault.id);
71
+ const previous = await read_state(state_path);
72
+ if (previous !== null && previous.root !== folder && (await read_marker(previous.root))?.vault_id === vault.id) {
73
+ throw new CliError(`The vault "${vault.name}" is already synced into ${previous.root} on this computer. Run nemu vault unlink ${previous.root} first.`, "already_linked");
74
+ }
75
+ const info = await new VaultApi(transport, vault.id, client_label()).info();
76
+ const workspace_id = info.workspace_id ?? credentials.workspace?.id ?? workspace ?? null;
77
+ await write_marker(folder, {
78
+ version: 1,
79
+ vault_id: vault.id,
80
+ vault_name: vault.name,
81
+ workspace_id,
82
+ server: credentials.api_url,
83
+ linked_at: new Date().toISOString(),
84
+ });
85
+ if (previous === null || previous.root !== folder || existing === null) {
86
+ await write_state(state_path, empty_state(vault.id, folder, {
87
+ conflicts: previous?.settings.conflicts,
88
+ obsidian: bool_flag(args, "obsidian") || (previous?.settings.obsidian ?? false),
89
+ }));
90
+ }
91
+ else if (bool_flag(args, "obsidian")) {
92
+ await write_state(state_path, { ...previous, settings: { ...previous.settings, obsidian: true }, full_next: true });
93
+ }
94
+ if (is_json_mode()) {
95
+ emit({ ok: true, folder, vault: { id: vault.id, name: vault.name }, workspace_id, marker: marker_path(folder) });
96
+ return 0;
97
+ }
98
+ success(`Linked ${folder} to the vault ${bold(vault.name)}`);
99
+ out(dim(` Run nemu sync ${raw} to sync it, or nemu sync ${raw} --watch to keep it in sync.`));
100
+ return 0;
101
+ }
102
+ async function locate(args) {
103
+ const raw = args.positional[1];
104
+ if (raw !== undefined)
105
+ return resolve(raw);
106
+ const found = await find_root(process.cwd());
107
+ if (found === null)
108
+ throw new CliError("This folder is not linked to a vault.", "not_linked");
109
+ return found;
110
+ }
111
+ async function unlink(args) {
112
+ const folder = await locate(args);
113
+ const marker = await read_marker(folder);
114
+ if (marker === null)
115
+ throw new CliError(`${folder} is not linked to a vault.`, "not_linked");
116
+ const state_path = state_path_for(marker.vault_id);
117
+ const state = await read_state(state_path);
118
+ if (state === null || state.root === folder)
119
+ await remove_state(state_path);
120
+ await remove_marker(folder);
121
+ if (is_json_mode()) {
122
+ emit({ ok: true, folder, vault_id: marker.vault_id });
123
+ return 0;
124
+ }
125
+ success(`Unlinked ${folder} from "${marker.vault_name}". Your files are still there.`);
126
+ return 0;
127
+ }
128
+ async function conflict_copies(root, relative = "") {
129
+ const found = [];
130
+ const entries = await readdir(relative === "" ? root : `${root}/${relative}`, { withFileTypes: true }).catch(() => []);
131
+ for (const entry of entries) {
132
+ const path = relative === "" ? entry.name : `${relative}/${entry.name}`;
133
+ if (is_default_ignored(path, false))
134
+ continue;
135
+ if (entry.isDirectory())
136
+ found.push(...(await conflict_copies(root, path)));
137
+ else if (entry.isFile() && is_conflict_copy(path.normalize("NFC")))
138
+ found.push(path);
139
+ }
140
+ return found;
141
+ }
142
+ async function status(args) {
143
+ const folder = await locate(args);
144
+ const marker = await read_marker(folder);
145
+ if (marker === null)
146
+ throw new CliError(`${folder} is not linked to a vault.`, "not_linked");
147
+ const state = await read_state(state_path_for(marker.vault_id));
148
+ const conflicts = await conflict_copies(folder);
149
+ const summary = {
150
+ folder,
151
+ vault: { id: marker.vault_id, name: marker.vault_name },
152
+ server: marker.server,
153
+ workspace_id: marker.workspace_id,
154
+ tracked: state === null ? 0 : Object.keys(state.files).length,
155
+ last_sync: state?.synced_at ?? null,
156
+ conflicts_mode: state?.settings.conflicts ?? "merge",
157
+ obsidian_settings: state?.settings.obsidian ?? false,
158
+ conflicts,
159
+ };
160
+ if (is_json_mode()) {
161
+ emit(summary);
162
+ return 0;
163
+ }
164
+ out(` ${bold(marker.vault_name)} ${dim(marker.vault_id)}`);
165
+ out(` ${dim("folder ")} ${folder}`);
166
+ out(` ${dim("files ")} ${summary.tracked}`);
167
+ out(` ${dim("last sync")} ${summary.last_sync ?? "never"}`);
168
+ out(` ${dim("conflicts")} ${summary.conflicts_mode === "merge" ? "merge when possible" : "always write a conflict file"}`);
169
+ out(` ${dim(".obsidian")} ${summary.obsidian_settings ? "synced" : "not synced on this device"}`);
170
+ if (conflicts.length > 0) {
171
+ out();
172
+ out(` ${bold(`${conflicts.length} open conflict${conflicts.length === 1 ? "" : "s"}`)} ${dim("(delete the copy you do not want)")}`);
173
+ for (const path of conflicts)
174
+ out(` ${path}`);
175
+ }
176
+ return 0;
177
+ }
178
+ export async function vault(args) {
179
+ const action = args.positional[0] ?? "list";
180
+ if (action === "list")
181
+ return list(args);
182
+ if (action === "link")
183
+ return link(args);
184
+ if (action === "unlink")
185
+ return unlink(args);
186
+ if (action === "status" || action === "conflicts")
187
+ return status(args);
188
+ throw new CliError(USAGE, "invalid_arguments");
189
+ }