@solidactions/cli 3.20.1 → 3.21.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.
package/README.md CHANGED
@@ -197,13 +197,15 @@ The CLI stores `host`, `apiKey`, and `workspaceId` in a JSON config file. Two lo
197
197
 
198
198
  ### Resolution order
199
199
 
200
- For each field (`host`, `apiKey`, `workspaceId`), the CLI resolves independently in this order:
200
+ Each field is looked up in this order, and the first layer that sets it wins:
201
201
 
202
202
  1. Environment variables: `SOLIDACTIONS_HOST`, `SOLIDACTIONS_API_KEY`, `SOLIDACTIONS_WORKSPACE_ID`
203
203
  2. Nearest local `./.solidactions/config.json` (walking up from cwd)
204
204
  3. Global `~/.solidactions/config.json`
205
205
 
206
- You can mix: e.g., set only `SOLIDACTIONS_WORKSPACE_ID` in the environment while letting `host` and `apiKey` come from a file.
206
+ **An API key is only ever sent to the host configured with it.** If a layer above the one that supplies the key sets a *different* `host` (for example a local file with only `"host"`, or `SOLIDACTIONS_HOST` on its own), the CLI refuses instead of sending that key to the other host, and says which file or variable to change. A key from `SOLIDACTIONS_API_KEY` without `SOLIDACTIONS_HOST` goes only to the host in the global config (`~/.solidactions/config.json`), or to `https://app.solidactions.com` when no file names a host. It is never sent to a host that a project folder's `.solidactions/config.json` names (unless that is the same host as the global one), so a cloned repository cannot redirect an exported key; set `SOLIDACTIONS_HOST` as well to use another host. A layer may still set only the workspace (`workspace set --local`, or `SOLIDACTIONS_WORKSPACE_ID`) and use the credentials from the layer below.
207
+
208
+ Hosts are compared exactly, ignoring only surrounding space, trailing slashes and letter case: `https://example.com` and `https://example.com:443` count as different hosts and are refused rather than guessed at. Write the host the same way in every file.
207
209
 
208
210
  ### Workspace safety
209
211
 
@@ -498,7 +500,7 @@ Manage docs in SA-Docs (the app's built-in documentation vault). `push` is drift
498
500
  | Command | Key Flags | Description |
499
501
  |---------|-----------|-------------|
500
502
  | `doc pull <folder> [dest]` | `-y`, `--overwrite`, `--json` | Download a Docs folder tree (markdown + media) to `dest` (defaults to `./<last-segment>/`); writes a `.solidactions-docs.json` revision manifest (including a `body_sha256` content hash per file) used by `push`'s drift guard. Falls back to fetching a single doc if `folder` is a doc path, not a folder |
501
- | `doc push <dir>` | `--on-conflict`, `--type`, `--folder`, `--dry-run`, `--force`, `--json` | Recursively upload a local markdown tree. Manifest-tracked files (from a prior `pull`) are written with a `base_revision` guard and reported separately as written/drifted/unchanged; files whose content hash still matches the last pull are skipped as unchanged (no write, no revision bump). Tracked media files whose bytes changed are replaced the same way, under the same guard; a tracked media file missing locally is left alone — `push` never deletes. An untracked binary in the tree is warned about, never uploaded (use `doc upload`). `--force` skips the drift guard (unchanged files are still skipped). `--dry-run` previews without writing. Untracked files are created under the manifest's `folder_path` when `<dir>` came from a `doc pull` (pass `--folder` to override); an untracked file whose title already exists in the target folder is skipped per `--on-conflict` (default `skip`, reported as `duplicate_title`) |
503
+ | `doc push <path>` | `--on-conflict`, `--type`, `--folder`, `--replace`, `--dry-run`, `--force`, `--json` | Upload a directory of docs (walked recursively) or one file: `<title>.md` becomes a markdown doc, `<title>.html` a visual doc, `<title>.canvas.json` or `<title>.canvas` a canvas. Each file must be at most 1 MiB. Manifest-tracked files (from a prior `pull`) are written with a `base_revision` guard and reported separately as written/drifted/unchanged; files whose content hash still matches the last pull are skipped as unchanged (no write, no revision bump). Tracked media files whose bytes changed are replaced the same way, under the same guard; a tracked media file missing locally is left alone — `push` never deletes. An untracked binary in the tree is warned about, never uploaded (use `doc upload`). `--force` skips the drift guard (unchanged files are still skipped). `--dry-run` previews without writing. Untracked files are created under the manifest's `folder_path` when `<dir>` came from a `doc pull` (pass `--folder` to override); an untracked file whose title already exists in the target folder is skipped per `--on-conflict` (default `skip`, reported as `duplicate_title`) |
502
504
  | `doc upload <files...>` | `--folder`, `--title`, `--replace <doc-id-or-path>` | Upload one or more media files to SA-Docs (requires a token with the "docs" ability); `--title` only valid for a single file. `--replace` swaps the bytes behind an existing media doc instead of creating a new one — see below |
503
505
 
504
506
  `doc upload <file> --replace <doc-id-or-path>` swaps the bytes behind an existing media doc, keeping its id, title, and folder, so embeds and references keep resolving — the old image stays in the doc's version history. Single file only; cannot be combined with `--title` or `--folder`. A purely numeric argument is a doc id; anything else is a docs path (`marketing/hero.png`), resolved against the doc's **title** — which `doc pull` may have sanitized, so for path-based work on a pulled folder prefer `doc push` instead:
@@ -508,7 +510,11 @@ solidactions doc upload logo-v2.png --replace 482
508
510
  solidactions doc upload logo-v2.png --replace marketing/logo.png
509
511
  ```
510
512
 
511
- **`doc pull` propagates deletions, within limits.** A file is removed locally only when its doc was deleted on the server *and* the file's bytes still match what the last pull gave it (the manifest's `body_sha256`) — anything you've edited locally is kept, with a warning that it's now untracked (re-create a markdown doc with `doc push`, a media doc with `doc upload`). Deletions only propagate when the destination's existing manifest `folder_path` matches the folder you're pulling (so pulling a different folder into a directory holding an old manifest deletes nothing), and never on the single-doc pull path; when propagation is skipped for either reason, `pull` says so. Nothing outside the destination directory is removed: every candidate path is resolved physically (so a symlinked subdirectory cannot lead the delete outside), and a file the same pull just wrote is never deleted, even if a case-only rename makes it look orphaned on a case-insensitive filesystem.
513
+ `doc push <file> --replace <doc-id>` replaces the body of an existing doc by its numeric id. It first reads the doc and refuses unless the kinds match: an `.html` file replaces only a visual doc, a `.canvas.json` / `.canvas` file only a canvas, and a `.md` file any doc that is not visual, canvas or media. There is no drift guard (you named the doc). It takes one file and cannot be combined with `--folder`, `--type` or `--on-conflict`. Like `doc upload --replace`, it does not update a pulled directory's manifest.
514
+
515
+ **Visual docs and canvases do not round-trip yet.** `doc pull` still writes every non-media doc as `<title>.md`, so a pulled visual doc arrives as `.md` holding HTML. And docs that `doc push` creates are not added to the manifest, so pushing the same directory again skips them (the push says how to update one: `--on-conflict overwrite`, or `--replace <id>`).
516
+
517
+ **`doc pull` propagates deletions, within limits.** A file is removed locally only when its doc was deleted on the server *and* the file's bytes still match what the last pull gave it (the manifest's `body_sha256`) — anything you've edited locally is kept, with a warning that it's now untracked (re-create a markdown doc with `doc push`, a media doc with `doc upload`). Deletions only propagate when the destination's existing manifest `folder_path` matches the folder you're pulling (so pulling a different folder into a directory holding an old manifest deletes nothing), and never on the single-doc pull path; a single-doc pull (`doc pull <folder>/<doc>`) records the doc's folder as the manifest's `folder_path` and, in a directory that already tracks that folder, adds or updates just that one entry; when propagation is skipped for either reason, `pull` says so. Nothing outside the destination directory is removed: every candidate path is resolved physically (so a symlinked subdirectory cannot lead the delete outside), and a file the same pull just wrote is never deleted, even if a case-only rename makes it look orphaned on a case-insensitive filesystem.
512
518
 
513
519
  **`doc pull --overwrite` is destructive.** If a manifest-tracked file still exists on the server *and* your local copy no longer matches the `body_sha256` recorded at the last pull (i.e. you've edited it and haven't pushed yet), a plain `doc pull` — even with `-y`/`--yes` — refuses with exit 1, naming every modified file, rather than silently discarding your edits. Nothing is written before that refusal. `-y`/`--yes` only bypasses the generic "destination is not empty" prompt; it does not cover locally-modified tracked files. Pass `--overwrite` to discard those local changes and re-pull server content anyway (it also implies `--yes`).
514
520
 
@@ -518,7 +524,7 @@ You do **not** need `--overwrite` to keep an edited file whose doc was deleted o
518
524
 
519
525
  **`doc push` and deleted docs.** If a tracked file's doc was deleted on the server, `push` names it per file (`doc <id> no longer exists (deleted remotely) — re-pull to untrack it, then push to re-create`) and carries on with the other files. Note the deleted doc still holds its title until it leaves the trash, so re-creating it needs the trashed copy restored or purged first — `push` says so if you hit it. `push` exits 1 on drift (a tracked doc moved on since your pull) and on any per-file server error; a deleted doc alone is not an error.
520
526
 
521
- **`doc pull` refuses to replace another folder's manifest.** If the destination already tracks a different folder, pulling into it would leave the previously tracked files untracked — and untracked files are not protected from being overwritten by a later pull. `pull` refuses (exit 1, before any network request) and names both folders. Pull into a different directory, or pass `--overwrite` to replace the manifest anyway. This also covers the single-doc pull path, whose one-entry manifest would otherwise clobber a folder's.
527
+ **`doc pull` refuses to replace another folder's manifest.** If the destination already tracks a different folder, pulling into it would leave the previously tracked files untracked — and untracked files are not protected from being overwritten by a later pull. `pull` refuses (exit 1, before anything is written) and names both folders. Pull into a different directory, or pass `--overwrite` to replace the manifest anyway. This also covers the single-doc pull path, whose one-entry manifest would otherwise clobber a folder's.
522
528
 
523
529
  ### workspace
524
530
 
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schema_version": 1,
3
3
  "cli_name": "solidactions",
4
- "cli_version": "3.20.1",
4
+ "cli_version": "3.21.0",
5
5
  "global_options": [
6
6
  {
7
7
  "flags": "-V, --version",
@@ -5678,14 +5678,14 @@
5678
5678
  ],
5679
5679
  "name": "push",
5680
5680
  "aliases": [],
5681
- "description": "Recursively upload a local markdown tree into SA-Docs",
5681
+ "description": "Upload docs from local files into SA-Docs: .md as markdown, .html as a visual doc, .canvas.json / .canvas as a canvas",
5682
5682
  "hidden": false,
5683
5683
  "arguments": [
5684
5684
  {
5685
- "name": "dir",
5685
+ "name": "path",
5686
5686
  "required": true,
5687
5687
  "variadic": false,
5688
- "description": "Path to the directory containing markdown files"
5688
+ "description": "A directory of .md / .html / .canvas.json / .canvas files (walked recursively), or one such file"
5689
5689
  }
5690
5690
  ],
5691
5691
  "options": [
@@ -5699,14 +5699,13 @@
5699
5699
  "value_optional": false,
5700
5700
  "variadic": false,
5701
5701
  "negated": false,
5702
- "hidden": false,
5703
- "default": "skip"
5702
+ "hidden": false
5704
5703
  },
5705
5704
  {
5706
5705
  "flags": "--type <slug>",
5707
5706
  "long": "--type",
5708
5707
  "short": null,
5709
- "description": "Doc-type slug to apply to all uploaded docs",
5708
+ "description": "Doc-type slug to apply to all uploaded docs (.html and canvas files keep visual / canvas)",
5710
5709
  "required": false,
5711
5710
  "value_required": true,
5712
5711
  "value_optional": false,
@@ -5726,6 +5725,18 @@
5726
5725
  "negated": false,
5727
5726
  "hidden": false
5728
5727
  },
5728
+ {
5729
+ "flags": "--replace <doc-id>",
5730
+ "long": "--replace",
5731
+ "short": null,
5732
+ "description": "Replace the body of an existing doc (numeric id) with a single file of the same kind",
5733
+ "required": false,
5734
+ "value_required": true,
5735
+ "value_optional": false,
5736
+ "variadic": false,
5737
+ "negated": false,
5738
+ "hidden": false
5739
+ },
5729
5740
  {
5730
5741
  "flags": "--dry-run",
5731
5742
  "long": "--dry-run",
@@ -48,10 +48,10 @@ async function connectionList() {
48
48
  }
49
49
  catch (error) {
50
50
  if (error.response?.status === 401) {
51
- console.error(chalk_1.default.red('Authentication failed. Run "solidactions login --global" to re-configure.'));
51
+ console.error(chalk_1.default.red(`Authentication failed against ${config.host}. Run "solidactions login --global" to re-configure.`));
52
52
  }
53
53
  else if (error.response) {
54
- console.error(chalk_1.default.red(`Failed: ${error.response.status}`), error.response.data);
54
+ console.error(chalk_1.default.red((0, api_1.formatApiFailure)(error.response.status, error.response.data)));
55
55
  }
56
56
  else {
57
57
  console.error(chalk_1.default.red('Connection failed:'), error.message);
@@ -281,7 +281,7 @@ async function databasePushWithConfig(name, file, options, config, dependencies
281
281
  return value;
282
282
  };
283
283
  const controlRemaining = () => Math.min(database_data_plane_1.DEFAULT_DATABASE_CONTROL_PLANE_TIMEOUT_MS, remaining());
284
- stdout(`WARNING: This destructively replaces database "${name}". Quiesce all writers; old URLs and credentials will become invalid. A private snapshot is normalized to WAL, 4096-byte pages, and auto-vacuum NONE; the source file is unchanged.`);
284
+ stdout(`WARNING: This destructively replaces database "${name}" in workspace ${config.workspaceId ?? '(none)'} on ${config.host}. Quiesce all writers; old URLs and credentials will become invalid. A private snapshot is normalized to WAL, 4096-byte pages, and auto-vacuum NONE; the source file is unchanged.`);
285
285
  stdout(`Hard deadline: ${Math.ceil(deadlineMs / 60_000)} minutes for ${normalized.inputBytes} bytes. Idempotency key: ${key}`);
286
286
  const prepareBody = {
287
287
  operation: 'bulk_load_prepare', name, bulk_mode: 'replace', input_bytes: normalized.inputBytes,
@@ -16,6 +16,7 @@ exports.pushYamlDeclarations = pushYamlDeclarations;
16
16
  exports.shouldPrintWorkspaceMismatch = shouldPrintWorkspaceMismatch;
17
17
  exports.isPlanLimitReachedError = isPlanLimitReachedError;
18
18
  exports.handlePlanLimitReached = handlePlanLimitReached;
19
+ exports.getProjectBySlugOrCanonical = getProjectBySlugOrCanonical;
19
20
  exports.deploy = deploy;
20
21
  exports.shouldPrintWebhookSecretNotice = shouldPrintWebhookSecretNotice;
21
22
  const fs_1 = __importDefault(require("fs"));
@@ -376,6 +377,23 @@ async function handlePlanLimitReached(config, projectName, error, productionExis
376
377
  process.exit(1);
377
378
  }
378
379
  }
380
+ /**
381
+ * GET a project by the name as typed, then — on a 404 only — by its canonical slug when
382
+ * that differs (cli#102). The server stores `Issue970-QX` as `issue970-qx`; without the
383
+ * retry a redeploy 404s, tries to create, and collides with the slug that already exists.
384
+ * The typed spelling goes first so a legacy slug the slugifier would rewrite still resolves.
385
+ */
386
+ async function getProjectBySlugOrCanonical(config, typed, canonical) {
387
+ try {
388
+ return await axios_1.default.get(`${config.host}/api/v1/projects/${typed}`, { headers: (0, api_1.getApiHeaders)(config) });
389
+ }
390
+ catch (error) {
391
+ if (error.response?.status !== 404 || canonical === '' || canonical === typed) {
392
+ throw error;
393
+ }
394
+ return axios_1.default.get(`${config.host}/api/v1/projects/${canonical}`, { headers: (0, api_1.getApiHeaders)(config) });
395
+ }
396
+ }
379
397
  async function deploy(projectName, sourcePath, options = {}) {
380
398
  const config = await (0, api_1.requireConfigWithWorkspace)();
381
399
  let workspaceMismatchPrinted = false;
@@ -413,9 +431,7 @@ async function deploy(projectName, sourcePath, options = {}) {
413
431
  let productionExists = null; // null = unknown (error path)
414
432
  let productionSlug = null;
415
433
  try {
416
- const prodResponse = await axios_1.default.get(`${config.host}/api/v1/projects/${projectName}`, {
417
- headers: (0, api_1.getApiHeaders)(config),
418
- });
434
+ const prodResponse = await getProjectBySlugOrCanonical(config, projectName, (0, slug_1.slugifyName)(projectName) === '' ? '' : (0, slug_1.buildProjectSlug)(projectName, 'production'));
419
435
  productionExists = true;
420
436
  productionSlug = prodResponse.data.slug || prodResponse.data.name;
421
437
  }
@@ -492,9 +508,7 @@ async function deploy(projectName, sourcePath, options = {}) {
492
508
  const lookupSlug = environment === 'production'
493
509
  ? projectName
494
510
  : `${projectName}-${environment}`;
495
- const checkResponse = await axios_1.default.get(`${config.host}/api/v1/projects/${lookupSlug}`, {
496
- headers: (0, api_1.getApiHeaders)(config),
497
- });
511
+ const checkResponse = await getProjectBySlugOrCanonical(config, lookupSlug, (0, slug_1.slugifyName)(projectName) === '' ? '' : (0, slug_1.buildProjectSlug)(projectName, environment));
498
512
  projectSlug = checkResponse.data.slug || checkResponse.data.name;
499
513
  }
500
514
  }
@@ -200,12 +200,12 @@ function assertLocalConfigParses(configPath) {
200
200
  * anchored to the entry's project and there is nothing to mismatch.
201
201
  *
202
202
  * `SOLIDACTIONS_HOST` / `SOLIDACTIONS_API_KEY` env overrides bypass the guard
203
- * ONLY when BOTH are set. `resolveConfig()` picks host and apiKey INDEPENDENTLY
204
- * (env > local > global), so with just one var set the OTHER field still falls
203
+ * ONLY when BOTH are set. With just one var set the OTHER field still falls
205
204
  * through to the global config — i.e. a partial override would send a run to
206
205
  * the production host, or to production credentials, exactly the way #30
207
- * describes. A partial override therefore refuses like any other unanchored
208
- * run, naming the field that would fall through.
206
+ * describes — and a partial env override now also meets the cli#124
207
+ * credential-pair refusal. A partial override therefore refuses like any other
208
+ * unanchored run, naming the field that would fall through.
209
209
  */
210
210
  function assertProjectLocalConfig(entryPath, env) {
211
211
  const envHost = !!process.env.SOLIDACTIONS_HOST;
@@ -224,16 +224,58 @@ async function fetchBodies(config, rows) {
224
224
  }
225
225
  return { fetched, warnings };
226
226
  }
227
+ /**
228
+ * Allocate the first free `<base>[ -N]<ext>` name not present in `used`,
229
+ * recording the winner in `used`.
230
+ */
231
+ function allocateName(used, base, ext) {
232
+ let candidate = base;
233
+ let suffix = 2;
234
+ while (used.has(`${candidate}${ext}`)) {
235
+ candidate = `${base}-${suffix}`;
236
+ suffix++;
237
+ }
238
+ const fileName = `${candidate}${ext}`;
239
+ used.add(fileName);
240
+ return fileName;
241
+ }
242
+ /**
243
+ * Whether `file` is the allocator's own output for `base` + `ext`: exactly
244
+ * `<base><ext>` or `<base>-N<ext>` with an integer N >= 2.
245
+ */
246
+ function isCollisionVariant(file, base, ext) {
247
+ if (file === `${base}${ext}`)
248
+ return true;
249
+ if (!file.startsWith(`${base}-`) || !file.endsWith(ext))
250
+ return false;
251
+ const middle = file.slice(base.length + 1, file.length - ext.length);
252
+ return middle !== '' && Number.isInteger(Number(middle)) && Number(middle) >= 2;
253
+ }
227
254
  /**
228
255
  * Resolve every fetched doc into a `PlannedDoc` — final relative path and
229
256
  * content hash — confirming/downloading media as needed. This is the only
230
257
  * place that talks to the media confirm/download endpoints; it performs no
231
258
  * filesystem writes.
259
+ *
260
+ * The optional `reserved` parameter serves the single-doc fallback pull
261
+ * (cli#153 C1): `usedNames` seeds the `-2`/`-3` allocator per directory
262
+ * with the file names the previous manifest assigns, and `pathById` frees
263
+ * each pulled doc's own tracked name back to it, so a stable title
264
+ * reallocates its own path (reuse in effect) while every other tracked
265
+ * name still forces a suffix. When the tracked title is unchanged and the
266
+ * tracked path is a collision variant of that title in the same folder,
267
+ * the doc keeps that exact path (R2-I2); a renamed/stale path still
268
+ * reallocates. Folder pulls pass nothing and behave exactly as before.
232
269
  */
233
- async function planDocs(docs, config) {
270
+ async function planDocs(docs, config, reserved) {
234
271
  const planned = [];
235
272
  const warnings = [];
236
273
  const usedNamesByDir = new Map();
274
+ if (reserved) {
275
+ for (const [dir, names] of reserved.usedNames) {
276
+ usedNamesByDir.set(dir, new Set(names));
277
+ }
278
+ }
237
279
  for (const doc of docs) {
238
280
  const dirRel = doc.relative;
239
281
  let used = usedNamesByDir.get(dirRel);
@@ -241,6 +283,17 @@ async function planDocs(docs, config) {
241
283
  used = new Set();
242
284
  usedNamesByDir.set(dirRel, used);
243
285
  }
286
+ // The pulled doc keeps its own tracked name: free it in its own
287
+ // directory so allocation below can hand it back. Names other ids
288
+ // own stay reserved.
289
+ const ownRelPath = reserved?.pathById.get(doc.id);
290
+ if (ownRelPath !== undefined) {
291
+ const slash = ownRelPath.lastIndexOf('/');
292
+ const ownDir = slash === -1 ? '' : ownRelPath.slice(0, slash);
293
+ if (ownDir === dirRel) {
294
+ used.delete(slash === -1 ? ownRelPath : ownRelPath.slice(slash + 1));
295
+ }
296
+ }
244
297
  const media = isMediaCandidate(doc) ? await resolveMedia(config, doc) : { isMedia: false };
245
298
  if (media.warning)
246
299
  warnings.push(media.warning);
@@ -258,15 +311,33 @@ async function planDocs(docs, config) {
258
311
  ext = (media.mime && MIME_EXTENSIONS[media.mime]) ?? '';
259
312
  }
260
313
  }
261
- let candidate = base;
262
- let suffix = 2;
263
- while (used.has(`${candidate}${ext}`)) {
264
- candidate = `${base}-${suffix}`;
265
- suffix++;
314
+ // Unchanged title keeps its existing collision-assigned path (R2-I2):
315
+ // the tracked path must be in this same folder and be the base name
316
+ // or a `-N` collision variant of it. A stale/renamed path (e.g. the
317
+ // `renamed.md` merge fixture) falls through to reallocation below.
318
+ const ownTitle = reserved?.titleById.get(doc.id);
319
+ let fileName;
320
+ let relPath;
321
+ if (ownRelPath !== undefined && ownTitle !== undefined && ownTitle === doc.title) {
322
+ const slash = ownRelPath.lastIndexOf('/');
323
+ const ownDir = slash === -1 ? '' : ownRelPath.slice(0, slash);
324
+ const ownFile = slash === -1 ? ownRelPath : ownRelPath.slice(slash + 1);
325
+ if (ownDir === dirRel && isCollisionVariant(ownFile, base, ext)) {
326
+ fileName = ownFile;
327
+ relPath = ownRelPath;
328
+ used.add(ownFile);
329
+ }
330
+ else {
331
+ const allocated = allocateName(used, base, ext);
332
+ fileName = allocated;
333
+ relPath = dirRel ? `${dirRel}/${fileName}` : fileName;
334
+ }
335
+ }
336
+ else {
337
+ const allocated = allocateName(used, base, ext);
338
+ fileName = allocated;
339
+ relPath = dirRel ? `${dirRel}/${fileName}` : fileName;
266
340
  }
267
- used.add(`${candidate}${ext}`);
268
- const fileName = `${candidate}${ext}`;
269
- const relPath = dirRel ? `${dirRel}/${fileName}` : fileName;
270
341
  let bodySha256;
271
342
  let mediaBytes = null;
272
343
  if (media.isMedia) {
@@ -331,6 +402,21 @@ function commitDocs(destination, planned) {
331
402
  }
332
403
  return { manifestDocs, files };
333
404
  }
405
+ /**
406
+ * Manifest-clobber protection, against the RESOLVED folder: the argument itself for a folder
407
+ * pull, the doc's own folder for a single-doc pull (cli#153). Runs once the server has said
408
+ * which one the argument is, and before anything is written. --overwrite bypasses it.
409
+ */
410
+ function refuseManifestClobber(previousManifest, resolvedFolder, argument, destination, options) {
411
+ if (previousManifest === null || previousManifest.folder_path === resolvedFolder || options.overwrite) {
412
+ return;
413
+ }
414
+ process.stderr.write(chalk_1.default.red(`error: "${destination}" already tracks "${previousManifest.folder_path}".\n`));
415
+ process.stderr.write(chalk_1.default.red(`Pulling "${argument}" here would replace its manifest, and local edits to the\n`));
416
+ process.stderr.write(chalk_1.default.red('previously tracked files would no longer be protected from being overwritten.\n'));
417
+ process.stderr.write(chalk_1.default.red('Pull into a different directory, or pass --overwrite to replace the manifest.\n'));
418
+ process.exit(1);
419
+ }
334
420
  /**
335
421
  * Core implementation — accepts an injected config so tests can point at a
336
422
  * stub server without touching the filesystem config.
@@ -368,23 +454,15 @@ async function docPullWithConfig(folderPath, dest, options, config) {
368
454
  }
369
455
  }
370
456
  }
371
- // Manifest-clobber protection: a manifest tracking a DIFFERENT folder than the one
372
- // being pulled must never be silently replaced — every file it tracks would become
373
- // untracked, and detectLocalModifications only protects tracked files. This must run
374
- // before any network I/O (listTree/planDocs) and before detectLocalModifications, since
375
- // a mismatched manifest can't meaningfully speak for the folder being pulled anyway.
376
- // --overwrite already means "discard local-edit protection", so it bypasses this too.
377
- if (previousManifest !== null && previousManifest.folder_path !== folderPath && !options.overwrite) {
378
- process.stderr.write(chalk_1.default.red(`error: "${destination}" already tracks "${previousManifest.folder_path}".\n`));
379
- process.stderr.write(chalk_1.default.red(`Pulling "${folderPath}" here would replace its manifest, and local edits to the\n`));
380
- process.stderr.write(chalk_1.default.red('previously tracked files would no longer be protected from being overwritten.\n'));
381
- process.stderr.write(chalk_1.default.red('Pull into a different directory, or pass --overwrite to replace the manifest.\n'));
382
- process.exit(1);
383
- }
457
+ // Manifest-clobber protection runs later, once the server has said whether the
458
+ // argument is a folder or a doc: refuseManifestClobber compares against the
459
+ // RESOLVED folder (the argument for a folder pull, the doc's own folder for a
460
+ // single-doc pull), still before anything is written.
384
461
  let rows;
385
462
  const listResult = await listTree(config, folderPath);
386
463
  if (listResult.ok) {
387
464
  rows = listResult.rows;
465
+ refuseManifestClobber(previousManifest, folderPath, folderPath, destination, options);
388
466
  }
389
467
  else if (listResult.isRoot && listResult.code === 'folder_path_not_found') {
390
468
  // Single-doc fallback: the target might be a doc path, not a folder.
@@ -409,7 +487,11 @@ async function docPullWithConfig(folderPath, dest, options, config) {
409
487
  current_revision_id: data.current_revision_id ?? null,
410
488
  properties: data.properties ?? {},
411
489
  }];
412
- await report(destination, folderPath, fetched, options, config, [], previousManifest, usedSingleDocFallback);
490
+ // The doc's real folder, not the argument (cli#153): a later `doc push` creates
491
+ // untracked files under the manifest's folder_path.
492
+ const docFolder = typeof data.folder_path === 'string' ? data.folder_path : (dir === '.' ? '' : dir);
493
+ refuseManifestClobber(previousManifest, docFolder, folderPath, destination, options);
494
+ await report(destination, docFolder, fetched, options, config, [], previousManifest, usedSingleDocFallback);
413
495
  return;
414
496
  }
415
497
  else {
@@ -422,7 +504,31 @@ async function docPullWithConfig(folderPath, dest, options, config) {
422
504
  }
423
505
  /** Write the docs + manifest to disk and print the result (chalk lines or --json). */
424
506
  async function report(destination, folderPath, fetched, options, config, extraWarnings, previousManifest, usedSingleDocFallback) {
425
- const { planned, warnings } = await planDocs(fetched, config);
507
+ // Single-doc fallback merging into a manifest that tracks the same folder
508
+ // must not steal a filename another tracked doc owns (cli#153 C1): the
509
+ // pulled doc reuses its own tracked path, and the allocator avoids every
510
+ // path the manifest assigns to other ids. Folder pulls pass nothing.
511
+ let reserved;
512
+ if (usedSingleDocFallback && previousManifest !== null && previousManifest.folder_path === folderPath) {
513
+ const usedNames = new Map();
514
+ const pathById = new Map();
515
+ const titleById = new Map();
516
+ for (const [relPath, entry] of Object.entries(previousManifest.docs)) {
517
+ pathById.set(entry.id, relPath);
518
+ titleById.set(entry.id, entry.title);
519
+ const slash = relPath.lastIndexOf('/');
520
+ const dir = slash === -1 ? '' : relPath.slice(0, slash);
521
+ const file = slash === -1 ? relPath : relPath.slice(slash + 1);
522
+ let names = usedNames.get(dir);
523
+ if (!names) {
524
+ names = new Set();
525
+ usedNames.set(dir, names);
526
+ }
527
+ names.add(file);
528
+ }
529
+ reserved = { usedNames, pathById, titleById };
530
+ }
531
+ const { planned, warnings } = await planDocs(fetched, config, reserved);
426
532
  // Unpushed-local-changes protection: now that the server walk is known, refuse only
427
533
  // for a file whose doc still exists remotely — i.e. its relative path is part of this
428
534
  // pull's plan and would be overwritten by commitDocs below. A modified file whose
@@ -460,7 +566,15 @@ async function report(destination, folderPath, fetched, options, config, extraWa
460
566
  continue;
461
567
  }
462
568
  }
463
- const manifest = { folder_path: folderPath, docs: manifestDocs };
569
+ let docs = manifestDocs;
570
+ if (usedSingleDocFallback && previousManifest !== null && previousManifest.folder_path === folderPath) {
571
+ // A single-doc pull speaks for one doc only: keep every other tracked entry (cli#153),
572
+ // dropping any stale key that pointed at this same doc id.
573
+ const pulledIds = new Set(Object.values(manifestDocs).map((entry) => entry.id));
574
+ docs = Object.fromEntries(Object.entries(previousManifest.docs).filter(([, entry]) => !pulledIds.has(entry.id)));
575
+ Object.assign(docs, manifestDocs);
576
+ }
577
+ const manifest = { folder_path: folderPath, docs };
464
578
  (0, docs_manifest_1.writeManifest)(destination, manifest);
465
579
  for (const warning of [...extraWarnings, ...warnings]) {
466
580
  process.stderr.write(chalk_1.default.yellow(`${warning}\n`));