vault-cortex 0.7.0 → 0.9.0-beta.43

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -15,14 +15,20 @@ and data files — see the
15
15
  The server runs as a Docker container; this CLI scaffolds the config and
16
16
  manages the container so you don't have to.
17
17
 
18
- ![npx vault-cortex init — the interactive setup wizard picks a mode, finds your vault, generates the config, and starts the server](https://raw.githubusercontent.com/aliasunder/vault-cortex/main/assets/demo-cli-init.gif)
18
+ ![npx vault-cortex init — the interactive setup wizard picks a mode, finds your vault, offers the optional settings, generates the config, and starts the server](https://raw.githubusercontent.com/aliasunder/vault-cortex/main/assets/demo-cli-init.gif)
19
19
 
20
20
  ## Commands
21
21
 
22
22
  - [`init`](#init) — interactive setup: scaffold the config, generate the auth
23
23
  token, start the server
24
+ - [`configure`](#configure) — change optional settings interactively and
25
+ restart to apply them
24
26
  - [`upgrade`](#upgrade) — pull the latest image and re-create the container;
25
27
  your data stays
28
+ - [`restart`](#restart) — re-create the container so your `.env` edits take
29
+ effect; no image pull
30
+ - [`logs`](#logs) — show the server's logs, live or after the fact
31
+ - [`down`](#down) — stop and remove the container; your data stays
26
32
  - [`get-sync-token`](#get-sync-token) — generate an Obsidian Sync auth token
27
33
  for remote setups
28
34
 
@@ -40,9 +46,14 @@ What it does:
40
46
  - **Local** — Docker on this machine, your vault folder bind-mounted
41
47
  - **Remote** — a VPS with [Obsidian Sync](https://obsidian.md/sync),
42
48
  reachable from any device
43
- 2. Generates a `.env` file with a securely generated `MCP_AUTH_TOKEN`
44
- 3. Optionally starts the container and waits for the health check
45
- 4. Prints your connection details the MCP URL, your auth token, and how to
49
+ 2. Offers the most common optional settings memory layer and folder,
50
+ file tools, semantic search, port, timezone (plus sync direction for
51
+ remote) press enter to keep the defaults, or pick the ones you want to
52
+ change. Skipped when the target directory already has a `.env` (use
53
+ [`configure`](#configure) instead)
54
+ 3. Generates a `.env` file with a securely generated `MCP_AUTH_TOKEN`
55
+ 4. Optionally starts the container and waits for the health check
56
+ 5. Prints your connection details — the MCP URL, your auth token, and how to
46
57
  connect your client
47
58
 
48
59
  Existing files are never overwritten without asking. During a remote setup,
@@ -63,6 +74,22 @@ Non-interactive example:
63
74
  npx vault-cortex@latest init --yes --vault-path /path/to/YourVault
64
75
  ```
65
76
 
77
+ ## configure
78
+
79
+ Change optional settings on an existing setup:
80
+
81
+ ```bash
82
+ npx vault-cortex@latest configure
83
+ ```
84
+
85
+ Shows the same settings chooser as [`init`](#init) — memory layer and
86
+ folder, file tools, semantic search, port, timezone (plus sync direction
87
+ for remote) — pre-filled with your current values, saves your picks to
88
+ `.env`, and offers to restart the container so they take effect. Settings not in the chooser
89
+ live in `.env` too: edit the value there, then run [`restart`](#restart).
90
+
91
+ Use `--dir <path>` if your config isn't in `./vault-cortex`.
92
+
66
93
  ## upgrade
67
94
 
68
95
  Pull the latest image, re-create the container, and verify health:
@@ -88,6 +115,55 @@ include Compose files you can use directly. If you set up with Compose, stick
88
115
  with Compose for updates too (`docker compose pull && docker compose up -d`)
89
116
  — the CLI and Compose manage the container independently.
90
117
 
118
+ ## restart
119
+
120
+ Re-create the container from your `.env` and verify health:
121
+
122
+ ```bash
123
+ npx vault-cortex@latest restart
124
+ ```
125
+
126
+ Use it after editing `.env` — settings are only read when the container is
127
+ created, so a plain `docker restart` won't pick them up, but this will. Unlike
128
+ [`upgrade`](#upgrade), it never pulls a new image: you get the same server
129
+ version back, with your current settings applied.
130
+
131
+ Use `--dir <path>` if your config isn't in `./vault-cortex`.
132
+
133
+ ## logs
134
+
135
+ Show the server's logs:
136
+
137
+ ```bash
138
+ npx vault-cortex@latest logs
139
+ ```
140
+
141
+ Flags:
142
+
143
+ - `--follow` — keep streaming new output until you press ctrl-C
144
+ - `--since <time>` — only logs newer than this (e.g. `10m`, `2h`, or a
145
+ timestamp)
146
+ - `--dir <path>` — directory containing `.env` (default `./vault-cortex`)
147
+
148
+ ```bash
149
+ npx vault-cortex@latest logs --follow --since 10m
150
+ ```
151
+
152
+ ## down
153
+
154
+ Stop and remove the container:
155
+
156
+ ```bash
157
+ npx vault-cortex@latest down
158
+ ```
159
+
160
+ Safe by design: your vault, search index, and `.env` settings all live
161
+ outside the container, so nothing is lost. Start again any time with
162
+ [`restart`](#restart). Running `down` when nothing is running is fine — it
163
+ just tells you there's nothing to stop.
164
+
165
+ Use `--dir <path>` if your config isn't in `./vault-cortex`.
166
+
91
167
  ## get-sync-token
92
168
 
93
169
  Generate an [Obsidian Sync](https://obsidian.md/sync) auth token — needed for
@@ -114,7 +190,8 @@ is available.
114
190
  - Node.js >= 20.12 (only for this CLI — the server itself runs in Docker)
115
191
  - [Docker](https://docs.docker.com/get-docker/) or a Docker-compatible
116
192
  runtime (e.g. OrbStack, Colima, Podman) to run the server — the CLI
117
- manages the container through the `docker` command
193
+ manages the container through the `docker` command (on Linux, see
194
+ [Docker Engine](https://docs.docker.com/engine/install/))
118
195
 
119
196
  ## Docs
120
197
 
@@ -0,0 +1,70 @@
1
+ import { readFileSync, writeFileSync } from "node:fs";
2
+ import { recreateContainer, requireInitializedDir, resolveDeployment, } from "./lifecycle.js";
3
+ import { applyOptionalSettings, askOptionalSettings, derivePublicUrlOverride, readOptionalValue, } from "./optional-settings.js";
4
+ /**
5
+ * Interactively changes optional settings in an existing deployment's .env,
6
+ * then offers to re-create the container so the new values take effect (the
7
+ * env-file is only read at container creation). The edit succeeds on its own:
8
+ * a stopped daemon or a declined restart still exits 0 with the settings
9
+ * saved and a restart hint printed.
10
+ */
11
+ export const runConfigure = async (flags, deps) => {
12
+ const { prompts, docker, fetchFn } = deps;
13
+ prompts.intro("vault-cortex configure");
14
+ // Editing settings only needs an init'd .env — the full start validation
15
+ // (VAULT_PATH, PUBLIC_URL) runs later, only when a restart is requested.
16
+ const initialized = requireInitializedDir(flags.dir, prompts);
17
+ if (!initialized)
18
+ return 1;
19
+ const { targetDir, envFilePath, mode } = initialized;
20
+ const envContent = readFileSync(envFilePath, "utf8");
21
+ const pickedOverrides = await askOptionalSettings({ mode, envContent }, prompts);
22
+ if (Object.keys(pickedOverrides).length === 0) {
23
+ prompts.log("No settings selected — nothing changed.");
24
+ prompts.outro("Done.");
25
+ return 0;
26
+ }
27
+ const overrides = derivePublicUrlOverride(envContent, pickedOverrides);
28
+ const changedNames = Object.keys(overrides);
29
+ writeFileSync(envFilePath, applyOptionalSettings(envContent, overrides));
30
+ prompts.log(`Updated ${changedNames.join(", ")} in ${targetDir}/.env.`);
31
+ // A custom PUBLIC_URL is never rewritten (see derivePublicUrlOverride), but
32
+ // a port change can still strand it — surface the consequence non-blocking.
33
+ const currentPublicUrl = readOptionalValue(envContent, "PUBLIC_URL");
34
+ if (pickedOverrides.PORT && !overrides.PUBLIC_URL && currentPublicUrl) {
35
+ prompts.warn(`PORT changed — make sure PUBLIC_URL (${currentPublicUrl}) still reaches the server.`);
36
+ }
37
+ const restartHint = `Apply the new settings with: npx vault-cortex@latest restart --dir "${targetDir}"`;
38
+ const daemonStatus = docker.daemonStatus();
39
+ if (daemonStatus !== "running") {
40
+ // Settings are already saved — the runtime state only affects the restart
41
+ // offer, so both non-running states degrade to the hint; restart itself
42
+ // prints the full install/start guidance when run.
43
+ prompts.warn(daemonStatus === "not-installed"
44
+ ? `No container runtime found — settings saved.\n${restartHint}`
45
+ : `Container runtime not running — settings saved.\n${restartHint}`);
46
+ prompts.outro("Done.");
47
+ return 0;
48
+ }
49
+ const restartNow = await prompts.confirm("Restart the container now to apply the new settings?", true);
50
+ if (!restartNow) {
51
+ prompts.log(restartHint);
52
+ prompts.outro("Done.");
53
+ return 0;
54
+ }
55
+ // Resolve from disk after the write so the restart honors the new values
56
+ // (a changed PORT must drive the port mapping and health URL).
57
+ const deployment = resolveDeployment(flags.dir, prompts);
58
+ if (!deployment) {
59
+ // The edit already succeeded — don't let the failed restart read as a
60
+ // failed configure.
61
+ prompts.warn(`The restart did not run — your settings are saved. Fix the issue above, then apply them with: npx vault-cortex@latest restart --dir "${targetDir}"`);
62
+ return 1;
63
+ }
64
+ const exitCode = await recreateContainer({ deployment, healthTimeoutMs: deps.healthTimeoutMs }, { prompts, docker, fetchFn });
65
+ if (exitCode !== 0)
66
+ return exitCode;
67
+ prompts.log("Applied the current .env settings.");
68
+ prompts.outro("Configure complete.");
69
+ return 0;
70
+ };
package/dist/docker.js CHANGED
@@ -1,4 +1,4 @@
1
- import { spawnSync } from "node:child_process";
1
+ import { spawn, spawnSync } from "node:child_process";
2
2
  export const LOCAL_IMAGE = "ghcr.io/aliasunder/vault-cortex:latest";
3
3
  export const REMOTE_IMAGE = "ghcr.io/aliasunder/vault-cortex:remote";
4
4
  export const CONTAINER_NAME = "vault-cortex";
@@ -94,8 +94,36 @@ export const buildDockerRunArgs = (params) => {
94
94
  args.push(image);
95
95
  return args;
96
96
  };
97
+ /**
98
+ * Builds the `docker logs` args array. Pure function — no I/O — so it's
99
+ * testable without spawning processes.
100
+ */
101
+ export const buildDockerLogsArgs = (params) => {
102
+ const { follow, since } = params;
103
+ return [
104
+ "logs",
105
+ ...(follow ? ["--follow"] : []),
106
+ ...(since ? ["--since", since] : []),
107
+ CONTAINER_NAME,
108
+ ];
109
+ };
110
+ /**
111
+ * Classifies a `docker info` spawnSync result. ENOENT on the spawn itself
112
+ * means the `docker` binary is absent (not installed); any other failure —
113
+ * non-zero exit, timeout, signal kill — means the binary exists but the
114
+ * daemon isn't answering. `status` alone can't make that call: it is null
115
+ * for ENOENT *and* for timeouts, so the split keys on the error code.
116
+ */
117
+ export const classifyDaemonStatus = (spawnResult) => {
118
+ if (spawnResult.status === 0)
119
+ return "running";
120
+ const spawnErrorCode = spawnResult.error && "code" in spawnResult.error
121
+ ? spawnResult.error.code
122
+ : undefined;
123
+ return spawnErrorCode === "ENOENT" ? "not-installed" : "not-running";
124
+ };
97
125
  export const createDockerRunner = () => ({
98
- isDaemonRunning: () => spawnSync("docker", ["info"], { timeout: 5_000 }).status === 0,
126
+ daemonStatus: () => classifyDaemonStatus(spawnSync("docker", ["info"], { timeout: 5_000 })),
99
127
  // stdout is discarded: `docker run -d` prints only the container ID there,
100
128
  // which lands as a raw hex line between the wizard's prompts. stderr stays
101
129
  // inherited — image-pull progress and error output print live, which the
@@ -108,12 +136,61 @@ export const createDockerRunner = () => ({
108
136
  }).status === 0,
109
137
  pullImage: (image) => spawnSync("docker", ["pull", image], { stdio: "inherit" }).status === 0,
110
138
  stopAndRemoveContainer: () => spawnSync("docker", ["rm", "-f", CONTAINER_NAME]).status === 0,
139
+ // `docker rm -f` on a missing container exits 1 on engines < 23 and 0 on
140
+ // >= 23, so stopAndRemoveContainer's status can't distinguish "already
141
+ // gone" from "failed" — callers needing idempotent messaging probe
142
+ // existence first. Output stays piped (discarded): this is a boolean probe.
143
+ containerExists: () => spawnSync("docker", ["container", "inspect", CONTAINER_NAME]).status === 0,
144
+ // Async spawn, not spawnSync: --follow streams until interrupted, and the
145
+ // exit code must be observable after the stream closes.
146
+ streamLogs: (params) => new Promise((resolveExitCode) => {
147
+ const child = spawn("docker", buildDockerLogsArgs(params), {
148
+ stdio: ["ignore", "inherit", "inherit"],
149
+ });
150
+ // ctrl-C delivers SIGINT to the whole foreground process group. Node's
151
+ // default disposition would kill this process before the child's
152
+ // "close" event fires; this no-op keep-alive lets the docker child
153
+ // exit on its own SIGINT, the streams flush, and the exit code
154
+ // propagate. `once` self-removes, so later ctrl-Cs behave normally.
155
+ process.once("SIGINT", () => { });
156
+ child.once("error", (spawnError) => {
157
+ // Event handler, not a catch — but the same "never swallow" rule
158
+ // applies: without this line a spawn failure is a bare exit 1.
159
+ process.stderr.write(`vault-cortex: could not run docker logs — ${spawnError.message}\n`);
160
+ resolveExitCode(1);
161
+ });
162
+ // A null code means the child died to a signal — report the shell
163
+ // convention for ctrl-C (128 + SIGINT = 130).
164
+ child.once("close", (code) => resolveExitCode(code ?? 130));
165
+ }),
111
166
  runObsidianLogin: (configMountPath) => spawnSync("docker", buildObsidianLoginArgs({
112
167
  configMountPath,
113
168
  uid: process.getuid?.(),
114
169
  gid: process.getgid?.(),
115
170
  }), { stdio: "inherit" }).status === 0,
116
171
  });
172
+ /** Default bound on a single health request (shared by probe and poll). */
173
+ const PROBE_TIMEOUT_MS = 10_000;
174
+ /**
175
+ * One-shot health probe: true on an HTTP 2xx, false on any error, non-2xx,
176
+ * or timeout — false IS the handled outcome for a boolean probe, so the
177
+ * catch maps rather than logs. Unlike the localhost poll target (which fails
178
+ * fast with ECONNREFUSED), a public URL behind a dropped firewall rule can
179
+ * black-hole the TCP handshake for minutes — the abort timeout bounds every
180
+ * caller.
181
+ */
182
+ export const probeHealth = async (params, fetchFn) => {
183
+ const { url, timeoutMs = PROBE_TIMEOUT_MS } = params;
184
+ try {
185
+ const response = await fetchFn(url, {
186
+ signal: AbortSignal.timeout(timeoutMs),
187
+ });
188
+ return response.ok;
189
+ }
190
+ catch {
191
+ return false;
192
+ }
193
+ };
117
194
  /**
118
195
  * Polls the health endpoint until it responds OK or the timeout elapses.
119
196
  * The first `docker run` pulls the image, so the default window is generous.
@@ -125,19 +202,20 @@ export const createDockerRunner = () => ({
125
202
  export const pollHealth = async (params, fetchFn) => {
126
203
  const { url, timeoutMs = 120_000, intervalMs = 2_000 } = params;
127
204
  const deadline = Date.now() + timeoutMs;
128
- const isHealthy = async () => {
129
- try {
130
- const response = await fetchFn(url);
131
- return response.ok;
132
- }
133
- catch {
134
- return false;
135
- }
136
- };
205
+ // Each attempt is bounded by the per-request cap AND the remaining budget
206
+ // (a bare remaining-budget bound would let one black-holed request consume
207
+ // the whole window with no retries), and the pause never sleeps past the
208
+ // deadline — so the loop can't overshoot timeoutMs and the caller's
209
+ // "did not respond within N minutes" message stays accurate.
137
210
  while (Date.now() < deadline) {
138
- if (await isHealthy())
211
+ const attemptTimeoutMs = Math.min(PROBE_TIMEOUT_MS, deadline - Date.now());
212
+ if (await probeHealth({ url, timeoutMs: attemptTimeoutMs }, fetchFn)) {
139
213
  return true;
140
- await new Promise((resolvePause) => setTimeout(resolvePause, intervalMs));
214
+ }
215
+ const pauseMs = Math.min(intervalMs, deadline - Date.now());
216
+ if (pauseMs > 0) {
217
+ await new Promise((resolvePause) => setTimeout(resolvePause, pauseMs));
218
+ }
141
219
  }
142
220
  return false;
143
221
  };
package/dist/env.js CHANGED
@@ -10,8 +10,9 @@
10
10
  // └─────────────────────────────────────────────────────────────────────────┘
11
11
  // sync:local-optional:begin
12
12
  const LOCAL_OPTIONAL_BLOCK = `# Optional ──────────────────────────────────────────────────
13
- # To change a setting: edit its value (uncommenting it first if needed),
14
- # then apply with "npx vault-cortex upgrade" (restart alone does not
13
+ # To change a setting: run "npx vault-cortex@latest configure", or edit
14
+ # its value here (uncommenting it first if needed) and apply with
15
+ # "npx vault-cortex@latest restart" (plain docker restart does not
15
16
  # re-read this file).
16
17
 
17
18
  # Public URL for OAuth issuer URL in discovery metadata (default: http://localhost:8000).
@@ -100,8 +101,9 @@ WINDOWS_MODE=false
100
101
  // └─────────────────────────────────────────────────────────────────────────┘
101
102
  // sync:remote-optional:begin
102
103
  const REMOTE_OPTIONAL_BLOCK = `# Optional ──────────────────────────────────────────────────
103
- # To change a setting: edit its value (uncommenting it first if needed),
104
- # then apply with "npx vault-cortex upgrade" (restart alone does not
104
+ # To change a setting: run "npx vault-cortex@latest configure", or edit
105
+ # its value here (uncommenting it first if needed) and apply with
106
+ # "npx vault-cortex@latest restart" (plain docker restart does not
105
107
  # re-read this file).
106
108
 
107
109
  # Your IANA timezone — affects daily note resolution and memory timestamps.
@@ -193,7 +195,7 @@ SYNC_MODE=bidirectional
193
195
  `;
194
196
  // sync:remote-optional:end
195
197
  export const buildLocalEnv = (answers) => `# vault-cortex — local quickstart
196
- # Generated by \`npx vault-cortex init\`. Full option reference:
198
+ # Generated by \`npx vault-cortex@latest init\`. Full option reference:
197
199
  # https://github.com/aliasunder/vault-cortex/blob/main/deploy/local/.env.example
198
200
 
199
201
  # Required ──────────────────────────────────────────────────
@@ -204,10 +206,6 @@ MCP_AUTH_TOKEN=${answers.mcpAuthToken}
204
206
  # Absolute path to your Obsidian vault on this machine.
205
207
  VAULT_PATH=${answers.vaultPath}
206
208
 
207
- # Public URL for OAuth issuer URL in discovery metadata.
208
- # Override if you expose the server on a different URL (e.g. via a reverse proxy).
209
- PUBLIC_URL=http://localhost:8000
210
-
211
209
  ${LOCAL_OPTIONAL_BLOCK}`;
212
210
  export const buildRemoteEnv = (answers) => {
213
211
  const vaultPasswordLines = answers.vaultPassword === undefined
@@ -218,10 +216,10 @@ VAULT_PASSWORD=${answers.vaultPassword}`;
218
216
  const obsidianTokenComment = answers.obsidianAuthToken === ""
219
217
  ? `# Obsidian Sync auth token — FILL THIS IN before starting the server.
220
218
  # Generate once with:
221
- # npx vault-cortex get-sync-token`
219
+ # npx vault-cortex@latest get-sync-token`
222
220
  : `# Obsidian Sync auth token.`;
223
221
  return `# vault-cortex — remote quickstart (Obsidian Sync)
224
- # Generated by \`npx vault-cortex init\`. Full option reference:
222
+ # Generated by \`npx vault-cortex@latest init\`. Full option reference:
225
223
  # https://github.com/aliasunder/vault-cortex/blob/main/deploy/remote/.env.example
226
224
 
227
225
  # Required ──────────────────────────────────────────────────
@@ -1,6 +1,7 @@
1
1
  import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
2
2
  import { tmpdir } from "node:os";
3
3
  import { join, resolve } from "node:path";
4
+ import { buildDaemonNotRunningMessage, buildDockerNotInstalledMessage, } from "./messages.js";
4
5
  import { patchEnvObsidianToken } from "./scaffold.js";
5
6
  import { expandTilde } from "./vault.js";
6
7
  /** Message from an unknown throw — Error instances keep their message. */
@@ -90,14 +91,14 @@ export const captureObsidianToken = (deps, tokenDestinationMessage) => {
90
91
  const loginSucceeded = runLoginContainer(configMountPath, deps);
91
92
  if (!loginSucceeded) {
92
93
  prompts.warn("The Obsidian login did not complete — you can run it later with:\n" +
93
- " npx vault-cortex get-sync-token");
94
+ " npx vault-cortex@latest get-sync-token");
94
95
  return undefined;
95
96
  }
96
97
  const token = readCapturedTokenFile(configMountPath);
97
98
  if (!token) {
98
99
  prompts.warn("The Obsidian login finished, but no token was captured — the " +
99
100
  "token file was missing, empty, or unreadable. You can retry with:\n" +
100
- " npx vault-cortex get-sync-token");
101
+ " npx vault-cortex@latest get-sync-token");
101
102
  return undefined;
102
103
  }
103
104
  return token;
@@ -113,9 +114,11 @@ export const captureObsidianToken = (deps, tokenDestinationMessage) => {
113
114
  */
114
115
  export const runGetSyncToken = async (flags, deps) => {
115
116
  const { prompts, docker } = deps;
116
- if (!docker.isDaemonRunning()) {
117
- prompts.error("Container runtime not running — start Docker Desktop, Colima,\n" +
118
- "OrbStack, or another Docker-compatible runtime and try again.");
117
+ const daemonStatus = docker.daemonStatus();
118
+ if (daemonStatus !== "running") {
119
+ prompts.error(daemonStatus === "not-installed"
120
+ ? buildDockerNotInstalledMessage({ nextStep: "\nThen try again." })
121
+ : buildDaemonNotRunningMessage(" and try again."));
119
122
  return 1;
120
123
  }
121
124
  prompts.intro("vault-cortex get-sync-token");
package/dist/init.js CHANGED
@@ -1,9 +1,12 @@
1
+ import { existsSync } from "node:fs";
1
2
  import { join, resolve } from "node:path";
2
3
  import { buildLocalEnv, buildRemoteEnv } from "./env.js";
3
4
  import { captureObsidianToken } from "./get-sync-token.js";
4
- import { buildLocalConnectMessage, buildRemoteConnectMessage, } from "./messages.js";
5
+ import { buildDaemonNotRunningMessage, buildDockerNotInstalledMessage, buildLocalConnectMessage, buildRemoteConnectMessage, } from "./messages.js";
5
6
  import { pollHealth } from "./docker.js";
6
- import { buildFilesToWrite, readEnvPort, writeFiles, } from "./scaffold.js";
7
+ import { reportPublicUrlProbe } from "./lifecycle.js";
8
+ import { applyOptionalSettings, askOptionalSettings, derivePublicUrlOverride, } from "./optional-settings.js";
9
+ import { buildFilesToWrite, readEnvPort, readEnvPublicUrl, writeFiles, } from "./scaffold.js";
7
10
  import { generateToken } from "./token.js";
8
11
  import { expandTilde, validateVaultPath } from "./vault.js";
9
12
  const DEFAULT_TARGET_DIR = "./vault-cortex";
@@ -137,10 +140,14 @@ const reportWrites = (params, prompts) => {
137
140
  const offerDockerRun = async (params, deps) => {
138
141
  const { targetDir, port, mode, vaultPath } = params;
139
142
  const { prompts, docker, fetchFn } = deps;
140
- if (!docker.isDaemonRunning()) {
141
- prompts.warn("Container runtime not running — start Docker Desktop, Colima,\n" +
142
- "OrbStack, or another Docker-compatible runtime, then run:\n" +
143
- ` npx vault-cortex upgrade --dir "${targetDir}"`);
143
+ const daemonStatus = docker.daemonStatus();
144
+ if (daemonStatus !== "running") {
145
+ const upgradeHint = `npx vault-cortex@latest upgrade --dir "${targetDir}"`;
146
+ prompts.warn(daemonStatus === "not-installed"
147
+ ? buildDockerNotInstalledMessage({
148
+ nextStep: `\nThen start the server with:\n ${upgradeHint}`,
149
+ })
150
+ : buildDaemonNotRunningMessage(`, then run:\n ${upgradeHint}`));
144
151
  return false;
145
152
  }
146
153
  const startNow = await prompts.confirm("Start the server now?", true);
@@ -203,10 +210,25 @@ const runLocalInit = async (flags, deps) => {
203
210
  placeholder: DEFAULT_TARGET_DIR,
204
211
  }))));
205
212
  const token = generateToken();
213
+ // Guided optional settings: the chooser reads current values from the
214
+ // generated defaults; enter with nothing picked keeps them all. --yes
215
+ // skips the chooser (non-interactive by contract), and so does an existing
216
+ // .env — the conflict prompt defaults to keeping it, which would discard
217
+ // the answers; settings on an existing deployment are configure's job.
218
+ const defaultEnvContent = buildLocalEnv({ mcpAuthToken: token, vaultPath });
219
+ const envAlreadyExists = existsSync(join(targetDir, ".env"));
220
+ const offerSettingsChooser = !flags.yes && !envAlreadyExists;
221
+ if (!flags.yes && envAlreadyExists) {
222
+ prompts.log('Found an existing .env — settings prompts skipped. Adjust settings with "npx vault-cortex@latest configure".');
223
+ }
224
+ const optionalOverrides = offerSettingsChooser
225
+ ? await askOptionalSettings({ mode: "local", envContent: defaultEnvContent }, prompts)
226
+ : {};
227
+ const envContent = applyOptionalSettings(defaultEnvContent, derivePublicUrlOverride(defaultEnvContent, optionalOverrides));
206
228
  // Conflict policy: identical existing files are skipped silently;
207
229
  // differing ones prompt per file (default keep). --yes never overwrites —
208
230
  // any differing file becomes an exit-1 below, leaving it untouched.
209
- const files = buildFilesToWrite(buildLocalEnv({ mcpAuthToken: token, vaultPath }));
231
+ const files = buildFilesToWrite(envContent);
210
232
  const resolveConflict = flags.yes ? keepExisting : confirmOverwrite(prompts);
211
233
  const results = await writeFiles({ targetDir, files }, resolveConflict);
212
234
  reportWrites({ targetDir, results }, prompts);
@@ -248,8 +270,10 @@ const runRemoteInit = async (flags, deps) => {
248
270
  const vaultName = await askVaultName(prompts);
249
271
  // Auto-capture the Obsidian Sync token via a Docker volume mount when
250
272
  // the daemon is reachable. Falls back to a paste prompt when capture
251
- // fails or the user declines.
252
- const capturedToken = docker.isDaemonRunning()
273
+ // fails or the user declines. Both non-running states stay silent here —
274
+ // the paste fallback is fully functional without Docker, and the start
275
+ // offer surfaces the differentiated runtime guidance later in the flow.
276
+ const capturedToken = docker.daemonStatus() === "running"
253
277
  ? await offerSyncTokenCapture(prompts, docker)
254
278
  : undefined;
255
279
  // Masked prompt: the sync token is a credential and must not echo into
@@ -262,13 +286,24 @@ const runRemoteInit = async (flags, deps) => {
262
286
  ? await prompts.password("Vault encryption password:")
263
287
  : undefined;
264
288
  const token = generateToken();
265
- const envContent = buildRemoteEnv({
289
+ // Guided optional settings, mirroring the local flow — remote also offers
290
+ // SYNC_MODE. Remote init is always interactive (no --yes), so only an
291
+ // existing .env skips the chooser here.
292
+ const defaultEnvContent = buildRemoteEnv({
266
293
  mcpAuthToken: token,
267
294
  publicUrl,
268
295
  obsidianAuthToken,
269
296
  vaultName,
270
297
  vaultPassword,
271
298
  });
299
+ const envAlreadyExists = existsSync(join(targetDir, ".env"));
300
+ if (envAlreadyExists) {
301
+ prompts.log('Found an existing .env — settings prompts skipped. Adjust settings with "npx vault-cortex@latest configure".');
302
+ }
303
+ const optionalOverrides = envAlreadyExists
304
+ ? {}
305
+ : await askOptionalSettings({ mode: "remote", envContent: defaultEnvContent }, prompts);
306
+ const envContent = applyOptionalSettings(defaultEnvContent, derivePublicUrlOverride(defaultEnvContent, optionalOverrides));
272
307
  const files = buildFilesToWrite(envContent);
273
308
  const results = await writeFiles({ targetDir, files }, confirmOverwrite(prompts));
274
309
  reportWrites({ targetDir, results }, prompts);
@@ -281,15 +316,28 @@ const runRemoteInit = async (flags, deps) => {
281
316
  if (tokenWritten)
282
317
  prompts.log("Generated MCP auth token (saved to .env).");
283
318
  const port = readEnvPort(join(targetDir, ".env"));
319
+ // Like PORT above, PUBLIC_URL comes from the .env actually on disk — a kept
320
+ // existing file may hold a different URL than this run's prompt, and the
321
+ // server only reads the file. The prompted value is the fallback for a kept
322
+ // legacy .env that predates PUBLIC_URL.
323
+ const effectivePublicUrl = readEnvPublicUrl(join(targetDir, ".env")) ?? publicUrl;
284
324
  // Without the sync token the container can't start (init-check-auth fails
285
325
  // and s6 stops it), so only offer docker run when it was provided.
286
326
  const started = obsidianAuthToken === ""
287
327
  ? false
288
328
  : await offerDockerRun({ targetDir, port, mode: "remote" }, deps);
329
+ // The container check above hit localhost on this machine; the public URL
330
+ // is the ingress path clients actually use — probe it too, informationally.
331
+ if (started) {
332
+ await reportPublicUrlProbe(effectivePublicUrl, {
333
+ prompts,
334
+ fetchFn: deps.fetchFn,
335
+ });
336
+ }
289
337
  prompts.print(buildRemoteConnectMessage({
290
338
  targetDir,
291
339
  token,
292
- publicUrl,
340
+ publicUrl: effectivePublicUrl,
293
341
  started,
294
342
  obsidianTokenMissing: obsidianAuthToken === "",
295
343
  tokenWritten,