@solidactions/cli 3.22.0 → 3.24.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.
@@ -32,6 +32,7 @@ const chalk_1 = __importDefault(require("chalk"));
32
32
  const prompts_1 = __importDefault(require("prompts"));
33
33
  const api_1 = require("../utils/api");
34
34
  const mcp_1 = require("../utils/mcp");
35
+ const source_provenance_1 = require("../utils/source-provenance");
35
36
  const docs_manifest_1 = require("../utils/docs-manifest");
36
37
  Object.defineProperty(exports, "DOCS_MANIFEST", { enumerable: true, get: function () { return docs_manifest_1.DOCS_MANIFEST; } });
37
38
  Object.defineProperty(exports, "sha256Hex", { enumerable: true, get: function () { return docs_manifest_1.sha256Hex; } });
@@ -69,6 +70,21 @@ function sanitizeSegment(name) {
69
70
  function sanitizeTitle(title) {
70
71
  return sanitizeSegment(title);
71
72
  }
73
+ /** Server-derived text (a title, code, message, or a path built from titles and folder names) as printed (cli#189). Display only. */
74
+ function shown(value) {
75
+ return (0, source_provenance_1.sanitizeDisplayText)(value, 1024) ?? '(untitled)';
76
+ }
77
+ /**
78
+ * Command error boundary (cli#189): an escaping error — a filesystem throw
79
+ * embedding a server-derived path, or a server-bearing exception like
80
+ * `McpRpcError` — prints through shown() like every other server-derived
81
+ * message. Keeps the diagnostic meaning; exits 1, as the top-level handler
82
+ * would.
83
+ */
84
+ function reportWriteError(error) {
85
+ process.stderr.write(chalk_1.default.red(`error: ${shown(error instanceof Error ? error.message : String(error))}\n`));
86
+ process.exit(1);
87
+ }
72
88
  /**
73
89
  * A doc is a media *candidate* when the bulk_read row carries blob metadata
74
90
  * and an empty body. This is a cheap pre-filter, not authoritative — the
@@ -94,16 +110,20 @@ async function resolveMedia(config, doc) {
94
110
  if (confirm.status === 404 && confirm.data?.code === 'media_not_found') {
95
111
  return { isMedia: false };
96
112
  }
113
+ if (confirm.status === 401) {
114
+ process.stderr.write(chalk_1.default.red((0, api_1.authFailedLine)(config.host)) + '\n');
115
+ process.exit(1);
116
+ }
97
117
  if (confirm.status !== 200) {
98
118
  const code = confirm.data?.code ?? 'unknown_error';
99
119
  const message = confirm.data?.message ?? 'media confirm request failed';
100
- process.stderr.write(chalk_1.default.red(`error: ${code}: ${message}\n`));
120
+ process.stderr.write(chalk_1.default.red(`error: ${shown(code)}: ${shown(message)}\n`));
101
121
  process.exit(1);
102
122
  }
103
123
  const { url, mime } = confirm.data;
104
124
  const download = await axios_1.default.get(url, { responseType: 'arraybuffer', validateStatus: () => true });
105
125
  if (download.status !== 200) {
106
- return { isMedia: true, mime, bytes: null, warning: `warn: failed to download media for doc ${doc.id} (${doc.title}): HTTP ${download.status}` };
126
+ return { isMedia: true, mime, bytes: null, warning: `warn: failed to download media for doc ${doc.id} (${shown(doc.title)}): HTTP ${download.status}` };
107
127
  }
108
128
  return { isMedia: true, mime, bytes: Buffer.from(download.data) };
109
129
  }
@@ -202,7 +222,7 @@ async function fetchBodies(config, rows) {
202
222
  if (!result.ok) {
203
223
  const code = result.data?.code ?? 'unknown_error';
204
224
  const message = result.data?.message ?? 'MCP returned an error with no message';
205
- process.stderr.write(chalk_1.default.red(`error: ${code}: ${message}\n`));
225
+ process.stderr.write(chalk_1.default.red(`error: ${shown(code)}: ${shown(message)}\n`));
206
226
  process.exit(1);
207
227
  }
208
228
  const resultRows = result.data?.results ?? [];
@@ -213,7 +233,7 @@ async function fetchBodies(config, rows) {
213
233
  continue;
214
234
  seenIds.add(row.id);
215
235
  if (row.status !== BULK_READ_OK_STATUS) {
216
- warnings.push(`warn: skipping doc ${row.id} (${original.title}): bulk_read returned status "${row.status ?? 'unknown'}"`);
236
+ warnings.push(`warn: skipping doc ${row.id} (${shown(original.title)}): bulk_read returned status "${shown(row.status ?? 'unknown')}"`);
217
237
  continue;
218
238
  }
219
239
  fetched.push({
@@ -225,7 +245,7 @@ async function fetchBodies(config, rows) {
225
245
  }
226
246
  for (const requested of chunk) {
227
247
  if (!seenIds.has(requested.id)) {
228
- warnings.push(`warn: skipping doc ${requested.id} (${requested.title}): missing from bulk_read results`);
248
+ warnings.push(`warn: skipping doc ${requested.id} (${shown(requested.title)}): missing from bulk_read results`);
229
249
  }
230
250
  }
231
251
  }
@@ -257,7 +277,7 @@ async function backfillDocTypes(config, fetched) {
257
277
  // valid untyped doc, not a failure — warn only when the type could
258
278
  // not be read at all.
259
279
  if (!readOk) {
260
- warnings.push(`warn: could not read the type of doc ${doc.id} (${doc.title}); writing it as .md`);
280
+ warnings.push(`warn: could not read the type of doc ${doc.id} (${shown(doc.title)}); writing it as .md`);
261
281
  }
262
282
  doc.docType = slug;
263
283
  doc.docTypeKnown = true;
@@ -456,8 +476,8 @@ function refuseManifestClobber(previousManifest, resolvedFolder, argument, desti
456
476
  if (previousManifest === null || previousManifest.folder_path === resolvedFolder || options.overwrite) {
457
477
  return;
458
478
  }
459
- process.stderr.write(chalk_1.default.red(`error: "${destination}" already tracks "${previousManifest.folder_path}".\n`));
460
- process.stderr.write(chalk_1.default.red(`Pulling "${argument}" here would replace its manifest, and local edits to the\n`));
479
+ process.stderr.write(chalk_1.default.red(`error: "${shown(destination)}" already tracks "${shown(previousManifest.folder_path)}".\n`));
480
+ process.stderr.write(chalk_1.default.red(`Pulling "${shown(argument)}" here would replace its manifest, and local edits to the\n`));
461
481
  process.stderr.write(chalk_1.default.red('previously tracked files would no longer be protected from being overwritten.\n'));
462
482
  process.stderr.write(chalk_1.default.red('Pull into a different directory, or pass --overwrite to replace the manifest.\n'));
463
483
  process.exit(1);
@@ -480,13 +500,13 @@ async function docPullWithConfig(folderPath, dest, options, config) {
480
500
  // doc still exists remotely) from an edited orphan (kept + warned, no flag needed).
481
501
  if (fs_1.default.existsSync(destination)) {
482
502
  if (!fs_1.default.statSync(destination).isDirectory()) {
483
- process.stderr.write(chalk_1.default.red(`error: destination "${destination}" exists and is not a directory.\n`));
503
+ process.stderr.write(chalk_1.default.red(`error: destination "${shown(destination)}" exists and is not a directory.\n`));
484
504
  process.exit(1);
485
505
  }
486
506
  const entries = fs_1.default.readdirSync(destination);
487
507
  if (entries.length > 0 && !options.yes && !options.overwrite) {
488
- console.log(chalk_1.default.yellow(`Destination "${destination}" is not empty (${entries.length} items).`));
489
- console.log(chalk_1.default.yellow('Pulling will overwrite existing files.'));
508
+ console.log(chalk_1.default.yellow(`Destination "${shown(destination)}" is not empty (${entries.length} items).`));
509
+ console.log(chalk_1.default.yellow("Pulling overwrites tracked files; local files the folder doesn't track are refused unless --overwrite."));
490
510
  const response = await (0, prompts_1.default)({
491
511
  type: 'confirm',
492
512
  name: 'proceed',
@@ -519,8 +539,8 @@ async function docPullWithConfig(folderPath, dest, options, config) {
519
539
  if (!readResult.ok) {
520
540
  const readCode = readResult.data?.code ?? 'unknown_error';
521
541
  const readMessage = readResult.data?.message ?? 'MCP returned an error with no message';
522
- process.stderr.write(chalk_1.default.red(`error: ${listResult.code}: ${listResult.message}\n`));
523
- process.stderr.write(chalk_1.default.red(`error: ${readCode}: ${readMessage}\n`));
542
+ process.stderr.write(chalk_1.default.red(`error: ${shown(listResult.code)}: ${shown(listResult.message)}\n`));
543
+ process.stderr.write(chalk_1.default.red(`error: ${shown(readCode)}: ${shown(readMessage)}\n`));
524
544
  process.exit(1);
525
545
  }
526
546
  const data = readResult.data;
@@ -542,7 +562,7 @@ async function docPullWithConfig(folderPath, dest, options, config) {
542
562
  return;
543
563
  }
544
564
  else {
545
- process.stderr.write(chalk_1.default.red(`error: ${listResult.code}: ${listResult.message}\n`));
565
+ process.stderr.write(chalk_1.default.red(`error: ${shown(listResult.code)}: ${shown(listResult.message)}\n`));
546
566
  process.exit(1);
547
567
  return;
548
568
  }
@@ -619,6 +639,133 @@ function physicalTargetPath(absPath) {
619
639
  }
620
640
  }
621
641
  }
642
+ /** The first symbolic link on `rel`'s way (inside `destination`, the destination itself excluded), as a relative path; null when there is none. */
643
+ function linkOnTheWay(destination, rel) {
644
+ const parts = rel.split('/');
645
+ for (let i = 1; i <= parts.length; i++) {
646
+ const abs = path_1.default.join(destination, ...parts.slice(0, i));
647
+ try {
648
+ if (fs_1.default.lstatSync(abs).isSymbolicLink())
649
+ return parts.slice(0, i).join('/');
650
+ }
651
+ catch {
652
+ return null; // the rest does not exist yet
653
+ }
654
+ }
655
+ return null;
656
+ }
657
+ function refuseLink(rel, link, doc) {
658
+ const where = link === rel ? '' : ` (or sits under one: ${shown(link)})`;
659
+ process.stderr.write(chalk_1.default.red(`error: ${shown(rel)} is a symbolic link${where}; this pull would write doc ${doc.id} ("${shown(doc.title)}") through it.\n`));
660
+ process.stderr.write(chalk_1.default.red('Replace it with a regular file or folder and pull again.\n'));
661
+ process.exit(1);
662
+ }
663
+ /** One line for a path that cannot be resolved (spec §2.3): the ELOOP wording, or the error code and message. Never returns. */
664
+ function explainUnresolvable(label, error) {
665
+ const code = error.code ?? 'ERROR';
666
+ const reason = code === 'ELOOP' ? 'too many symbolic links (ELOOP). Fix or remove the link and pull again.' : `${code} ${error.message}.`;
667
+ process.stderr.write(chalk_1.default.red(`error: cannot resolve ${shown(label)}: ${shown(reason)}\n`));
668
+ process.exit(1);
669
+ }
670
+ /** physicalTargetPath, but a resolution error becomes one line (spec §2.3). A planned target with a link on the way gets the symbolic-link refusal. */
671
+ function resolveOrExplain(destination, rel, target) {
672
+ const abs = path_1.default.resolve(destination, ...rel.split('/'));
673
+ try {
674
+ return physicalTargetPath(abs);
675
+ }
676
+ catch (error) {
677
+ if (target) {
678
+ const link = linkOnTheWay(destination, rel);
679
+ if (link !== null)
680
+ refuseLink(rel, link, target);
681
+ }
682
+ explainUnresolvable(rel, error);
683
+ }
684
+ }
685
+ /**
686
+ * Refuse, before any write, a pull that would write a planned doc through a
687
+ * symbolic link or to a place that resolves outside the destination. Covers
688
+ * every planned doc, including a failed media download: commitDocs still
689
+ * creates its directory. Also refuse, unless `--overwrite`, a planned write
690
+ * over a regular file the pull does not own (cli#167): one the previous
691
+ * manifest does not track with a hash and whose bytes differ from the
692
+ * pulled ones. A file already holding the pulled bytes is adopted, and a
693
+ * rename's own source file (a case-only retitle on a case-insensitive
694
+ * filesystem) is never "untracked".
695
+ */
696
+ function checkPlannedWrites(destination, planned, previousManifest, options, renameMoves) {
697
+ // First, so a destination that is itself a looping link gets one line, not a raw ELOOP from the sidecar check below.
698
+ let realDest;
699
+ try {
700
+ realDest = physicalTargetPath(path_1.default.resolve(destination));
701
+ }
702
+ catch (error) {
703
+ explainUnresolvable(destination, error);
704
+ }
705
+ // The manifest sidecar is written at the end of every pull: never through a link.
706
+ try {
707
+ if (fs_1.default.lstatSync(path_1.default.join(destination, docs_manifest_1.DOCS_MANIFEST)).isSymbolicLink()) {
708
+ process.stderr.write(chalk_1.default.red(`error: ${docs_manifest_1.DOCS_MANIFEST} is a symbolic link; this pull would write the docs manifest through it.\n`));
709
+ process.stderr.write(chalk_1.default.red('Replace it with a regular file or folder and pull again.\n'));
710
+ process.exit(1);
711
+ }
712
+ }
713
+ catch (error) {
714
+ if (error.code !== 'ENOENT')
715
+ explainUnresolvable(docs_manifest_1.DOCS_MANIFEST, error);
716
+ }
717
+ for (const p of planned) {
718
+ const link = linkOnTheWay(destination, p.relPath);
719
+ if (link !== null)
720
+ refuseLink(p.relPath, link, p.doc);
721
+ const physical = resolveOrExplain(destination, p.relPath, p.doc);
722
+ // Belt and braces behind linkOnTheWay, which refuses every link first; kept in case the physical path ever diverges without one.
723
+ if (physical !== realDest && !physical.startsWith(realDest + path_1.default.sep)) {
724
+ process.stderr.write(chalk_1.default.red(`error: ${shown(p.relPath)} resolves outside the destination (${shown(physical)}); this pull would write doc ${p.doc.id} ("${shown(p.doc.title)}") there.\n`));
725
+ process.exit(1);
726
+ }
727
+ }
728
+ if (options.overwrite)
729
+ return;
730
+ const untracked = [];
731
+ for (const p of planned) {
732
+ if (p.isMedia && p.mediaBytes === null)
733
+ continue; // a failed download writes nothing
734
+ const tracked = previousManifest?.docs[p.relPath];
735
+ if (tracked !== undefined && tracked.body_sha256 != null)
736
+ continue; // checked as unpushed local changes
737
+ const targetAbs = path_1.default.join(destination, ...p.relPath.split('/'));
738
+ let targetStat;
739
+ let current;
740
+ try {
741
+ targetStat = fs_1.default.statSync(targetAbs);
742
+ if (!targetStat.isFile())
743
+ continue;
744
+ current = fs_1.default.readFileSync(targetAbs);
745
+ }
746
+ catch (error) {
747
+ const code = error.code ?? 'ERROR';
748
+ if (code === 'ENOENT')
749
+ continue; // absent: nothing to overwrite here
750
+ untracked.push(`${p.relPath} (cannot be read: ${code})`); // present but unverifiable: not owned
751
+ continue;
752
+ }
753
+ if ((0, docs_manifest_1.sha256Hex)(current) === p.bodySha256)
754
+ continue;
755
+ const ownSource = renameMoves.find((m) => m.id === p.doc.id)?.sourceIdentity;
756
+ if (ownSource === `${targetStat.dev}:${targetStat.ino}`)
757
+ continue;
758
+ untracked.push(p.relPath);
759
+ }
760
+ if (untracked.length > 0) {
761
+ const one = untracked.length === 1;
762
+ process.stderr.write(chalk_1.default.red(`${untracked.length} ${one ? 'file exists' : 'files exist'} locally but ${one ? 'is' : 'are'} not tracked:\n`));
763
+ for (const rel of untracked)
764
+ process.stderr.write(chalk_1.default.red(` ${shown(rel)}\n`));
765
+ process.stderr.write(chalk_1.default.red('Move them aside and pull again, or pass --overwrite to replace them.\n'));
766
+ process.exit(1);
767
+ }
768
+ }
622
769
  /** Write the docs + manifest to disk and print the result (chalk lines or --json). */
623
770
  async function report(destination, folderPath, fetched, options, config, extraWarnings, previousManifest, usedSingleDocFallback) {
624
771
  // Single-doc fallback merging into a manifest that tracks the same folder
@@ -646,6 +793,18 @@ async function report(destination, folderPath, fetched, options, config, extraWa
646
793
  reserved = { usedNames, pathById, titleById };
647
794
  }
648
795
  const { planned, warnings } = await planDocs(fetched, config, reserved, previousManifest);
796
+ // Same doc id under a different path is a rename (PM ruling 2, cli#157):
797
+ // the previous manifest tracks a planned doc under a DIFFERENT path `old`,
798
+ // whatever is on disk at `old` (cli#157 FR4-C1). What is at `old` decides
799
+ // only what happens to `old`; the target checks below apply to every
800
+ // rename. Every rename ends one of three ways:
801
+ // (a) `old` is removed only after its replacement is written (nothing to
802
+ // remove when `old` holds no regular file);
803
+ // (b) `old`'s tracking (and file, if any) is kept, the replacement is
804
+ // not written;
805
+ // (c) the pull refuses here, before any write.
806
+ // Never: bytes lost, an untracked file overwritten without --overwrite,
807
+ // or one doc's tracking attached to another doc's bytes.
649
808
  const renameMoves = [];
650
809
  if (previousManifest) {
651
810
  const pathById = new Map();
@@ -704,7 +863,7 @@ async function report(destination, folderPath, fetched, options, config, extraWa
704
863
  const plannedByIdentity = new Map();
705
864
  const plannedByPhysicalPath = new Map();
706
865
  for (const p of planned) {
707
- const physicalPath = physicalTargetPath(path_1.default.resolve(destination, ...p.relPath.split('/')));
866
+ const physicalPath = resolveOrExplain(destination, p.relPath, p.doc);
708
867
  const physicalTargets = plannedByPhysicalPath.get(physicalPath) ?? [];
709
868
  physicalTargets.push(p);
710
869
  plannedByPhysicalPath.set(physicalPath, physicalTargets);
@@ -726,7 +885,7 @@ async function report(destination, folderPath, fetched, options, config, extraWa
726
885
  // its old tracking). Present sources also need protection from writes
727
886
  // through another name, hard link, symlink or directory component alias.
728
887
  const plannedTargetForSource = (m) => plannedPaths.get(m.oldRel)
729
- ?? plannedByPhysicalPath.get(physicalTargetPath(path_1.default.resolve(destination, ...m.oldRel.split('/'))))?.find((p) => p.doc.id !== m.id)
888
+ ?? plannedByPhysicalPath.get(resolveOrExplain(destination, m.oldRel))?.find((p) => p.doc.id !== m.id)
730
889
  ?? (m.sourceIdentity === null
731
890
  ? undefined
732
891
  : plannedByIdentity.get(m.sourceIdentity)?.find((p) => p.doc.id !== m.id));
@@ -739,8 +898,8 @@ async function report(destination, folderPath, fetched, options, config, extraWa
739
898
  if (!taker)
740
899
  continue;
741
900
  const oldTitle = previousManifest.docs[m.oldRel]?.title ?? `#${m.id}`;
742
- process.stderr.write(chalk_1.default.red(`error: ${m.oldRel} holds unpublished edits for doc ${m.id} ("${oldTitle}", now written as ${m.newRel}), but this pull would write doc ${taker.doc.id} ("${taker.doc.title}") to ${taker.relPath}, the same file.\n`));
743
- process.stderr.write(chalk_1.default.red(`Move or rename the edited ${m.oldRel} (or push it first) and pull again.\n`));
901
+ process.stderr.write(chalk_1.default.red(`error: ${shown(m.oldRel)} holds unpublished edits for doc ${m.id} ("${shown(oldTitle)}", now written as ${shown(m.newRel)}), but this pull would write doc ${taker.doc.id} ("${shown(taker.doc.title)}") to ${shown(taker.relPath)}, the same file.\n`));
902
+ process.stderr.write(chalk_1.default.red(`Move or rename the edited ${shown(m.oldRel)} (or push it first) and pull again.\n`));
744
903
  process.exit(1);
745
904
  }
746
905
  // A rename whose replacement will not be written keeps its old file and
@@ -753,7 +912,7 @@ async function report(destination, folderPath, fetched, options, config, extraWa
753
912
  const taker = plannedTargetForSource(m);
754
913
  if (!taker)
755
914
  continue;
756
- process.stderr.write(chalk_1.default.red(`error: doc ${m.id} ("${m.title}") failed to download to ${m.newRel}, so ${m.oldRel} must keep its previous file and tracking, but this pull would put doc ${taker.doc.id} ("${taker.doc.title}") at ${taker.relPath}, the same file.\n`));
915
+ process.stderr.write(chalk_1.default.red(`error: doc ${m.id} ("${shown(m.title)}") failed to download to ${shown(m.newRel)}, so ${shown(m.oldRel)} must keep its previous file and tracking, but this pull would put doc ${taker.doc.id} ("${shown(taker.doc.title)}") at ${shown(taker.relPath)}, the same file.\n`));
757
916
  process.stderr.write(chalk_1.default.red('Nothing was written. Pull again once the download succeeds.\n'));
758
917
  process.exit(1);
759
918
  }
@@ -762,15 +921,15 @@ async function report(destination, folderPath, fetched, options, config, extraWa
762
921
  for (const m of renameMoves) {
763
922
  if (m.replacementWritten || !m.modified)
764
923
  continue;
765
- process.stderr.write(chalk_1.default.red(`error: ${m.oldRel} holds unpublished edits for doc ${m.id}, which is now ${m.newRel}, but its download failed.\n`));
766
- process.stderr.write(chalk_1.default.red(`Nothing was written. Push ${m.oldRel} first (or move it aside), then pull again once the download succeeds.\n`));
924
+ process.stderr.write(chalk_1.default.red(`error: ${shown(m.oldRel)} holds unpublished edits for doc ${m.id}, which is now ${shown(m.newRel)}, but its download failed.\n`));
925
+ process.stderr.write(chalk_1.default.red(`Nothing was written. Push ${shown(m.oldRel)} first (or move it aside), then pull again once the download succeeds.\n`));
767
926
  process.exit(1);
768
927
  }
769
928
  const blocked = renameMoves.filter((m) => m.modified);
770
929
  if (blocked.length > 0) {
771
930
  for (const m of blocked) {
772
- process.stderr.write(chalk_1.default.red(`error: ${m.oldRel} holds unpublished edits for doc ${m.id} ("${m.title}"), which is now written as ${m.newRel}.\n`));
773
- process.stderr.write(chalk_1.default.red(`Nothing was written. Push ${m.oldRel} first (or move it aside) and pull again.\n`));
931
+ process.stderr.write(chalk_1.default.red(`error: ${shown(m.oldRel)} holds unpublished edits for doc ${m.id} ("${shown(m.title)}"), which is now written as ${shown(m.newRel)}.\n`));
932
+ process.stderr.write(chalk_1.default.red(`Nothing was written. Push ${shown(m.oldRel)} first (or move it aside) and pull again.\n`));
774
933
  }
775
934
  process.exit(1);
776
935
  }
@@ -789,7 +948,7 @@ async function report(destination, folderPath, fetched, options, config, extraWa
789
948
  if (!writes.some((p) => renamedIds.has(p.doc.id)) && foldedPaths.size === writes.length)
790
949
  continue;
791
950
  const [first, second] = writes;
792
- process.stderr.write(chalk_1.default.red(`error: ${first.relPath} (doc ${first.doc.id}) and ${second.relPath} (doc ${second.doc.id}) are the same file on this filesystem; this pull would write different docs through those names.\n`));
951
+ process.stderr.write(chalk_1.default.red(`error: ${shown(first.relPath)} (doc ${first.doc.id}) and ${shown(second.relPath)} (doc ${second.doc.id}) are the same file on this filesystem; this pull would write different docs through those names.\n`));
793
952
  process.stderr.write(chalk_1.default.red('Nothing was written. Move the aliased files apart and pull again.\n'));
794
953
  process.exit(1);
795
954
  }
@@ -808,8 +967,8 @@ async function report(destination, folderPath, fetched, options, config, extraWa
808
967
  }
809
968
  if (!isLink)
810
969
  continue;
811
- process.stderr.write(chalk_1.default.red(`error: ${m.newRel} is a symbolic link; this pull would write doc ${m.id} ("${m.title}", renamed from ${m.oldRel}) through it.\n`));
812
- process.stderr.write(chalk_1.default.red(`Replace ${m.newRel} with a regular file (or remove it) and pull again.\n`));
970
+ process.stderr.write(chalk_1.default.red(`error: ${shown(m.newRel)} is a symbolic link; this pull would write doc ${m.id} ("${shown(m.title)}", renamed from ${shown(m.oldRel)}) through it.\n`));
971
+ process.stderr.write(chalk_1.default.red(`Replace ${shown(m.newRel)} with a regular file (or remove it) and pull again.\n`));
813
972
  process.exit(1);
814
973
  }
815
974
  // A rename target holding an untracked local file (not in the previous
@@ -828,25 +987,32 @@ async function report(destination, folderPath, fetched, options, config, extraWa
828
987
  if (targetEntry !== undefined && targetEntry.body_sha256 != null)
829
988
  continue;
830
989
  const absNew = path_1.default.join(destination, ...m.newRel.split('/'));
831
- let existing;
990
+ let existing = null;
991
+ let unreadable = '';
832
992
  try {
833
993
  if (!fs_1.default.statSync(absNew).isFile())
834
994
  continue;
835
995
  existing = fs_1.default.readFileSync(absNew);
836
996
  }
837
- catch {
838
- continue;
997
+ catch (error) {
998
+ const code = error.code ?? 'ERROR';
999
+ if (code === 'ENOENT')
1000
+ continue;
1001
+ unreadable = ` (cannot be read: ${code})`; // present but unverifiable: not owned
839
1002
  }
840
- if ((0, docs_manifest_1.sha256Hex)(existing) === plannedPaths.get(m.newRel)?.bodySha256)
1003
+ if (existing !== null && (0, docs_manifest_1.sha256Hex)(existing) === plannedPaths.get(m.newRel)?.bodySha256)
841
1004
  continue;
842
- const state = targetEntry === undefined ? 'exists locally but is not tracked' : `holds local bytes with no recorded hash (tracked for doc ${targetEntry.id})`;
843
- process.stderr.write(chalk_1.default.red(`error: ${m.newRel} ${state}; this pull would overwrite it with doc ${m.id} ("${m.title}", renamed from ${m.oldRel}).\n`));
844
- process.stderr.write(chalk_1.default.red(`Move ${m.newRel} aside and pull again, or pass --overwrite to replace it.\n`));
1005
+ const state = (targetEntry === undefined ? 'exists locally but is not tracked' : `holds local bytes with no recorded hash (tracked for doc ${targetEntry.id})`) + unreadable;
1006
+ process.stderr.write(chalk_1.default.red(`error: ${shown(m.newRel)} ${state}; this pull would overwrite it with doc ${m.id} ("${shown(m.title)}", renamed from ${shown(m.oldRel)}).\n`));
1007
+ process.stderr.write(chalk_1.default.red(`Move ${shown(m.newRel)} aside and pull again, or pass --overwrite to replace it.\n`));
845
1008
  process.exit(1);
846
1009
  }
847
1010
  }
848
1011
  }
849
1012
  const handledOldPaths = new Set(renameMoves.map((m) => m.oldRel));
1013
+ // After the rename block (which keeps its own messages for rename cases) and before anything
1014
+ // else that reads or writes the plan: no planned write may go through a link or outside.
1015
+ checkPlannedWrites(destination, planned, previousManifest, options, renameMoves);
850
1016
  // Unpushed-local-changes protection: now that the server walk is known, refuse only
851
1017
  // for a file whose doc still exists remotely — i.e. its relative path is part of this
852
1018
  // pull's plan and would be overwritten by commitDocs below. A modified file whose
@@ -862,7 +1028,7 @@ async function report(destination, folderPath, fetched, options, config, extraWa
862
1028
  const noun = conflicts.length === 1 ? 'file has' : 'files have';
863
1029
  process.stderr.write(chalk_1.default.red(`${conflicts.length} ${noun} unpushed local changes:\n`));
864
1030
  for (const file of conflicts) {
865
- process.stderr.write(chalk_1.default.red(` ${file}\n`));
1031
+ process.stderr.write(chalk_1.default.red(` ${shown(file)}\n`));
866
1032
  }
867
1033
  process.stderr.write(chalk_1.default.red('push your changes first, or pass --overwrite to discard them.\n'));
868
1034
  process.exit(1);
@@ -874,23 +1040,55 @@ async function report(destination, folderPath, fetched, options, config, extraWa
874
1040
  for (const p of planned) {
875
1041
  const targetAbs = path_1.default.join(destination, ...p.relPath.split('/'));
876
1042
  if (fs_1.default.existsSync(targetAbs) && !fs_1.default.statSync(targetAbs).isFile()) {
877
- process.stderr.write(chalk_1.default.red(`error: "${p.relPath}" exists and is not a regular file — cannot write doc ${p.doc.id} (${p.doc.title}).\n`));
1043
+ process.stderr.write(chalk_1.default.red(`error: "${shown(p.relPath)}" exists and is not a regular file — cannot write doc ${p.doc.id} (${shown(p.doc.title)}).\n`));
878
1044
  process.exit(1);
879
1045
  }
880
1046
  }
1047
+ // Every throw below can carry a server-derived path (commitDocs writes
1048
+ // title-named files): the command boundary in `docPull` prints it
1049
+ // sanitised.
881
1050
  fs_1.default.mkdirSync(destination, { recursive: true });
882
1051
  const destPrefix = path_1.default.resolve(destination) + path_1.default.sep;
883
1052
  const realDest = fs_1.default.realpathSync(destination);
884
1053
  const { manifestDocs, files } = commitDocs(destination, planned);
1054
+ // cli#167: a media doc whose download failed must not be tracked over a
1055
+ // local file the previous manifest does not track, with a hash, for that
1056
+ // same doc: nothing was written, so the manifest would claim bytes the
1057
+ // pull never gave it. A rename keeps its restore-old-entry handling below.
1058
+ const renamedIds = new Set(renameMoves.map((m) => m.id));
1059
+ for (const p of planned) {
1060
+ if (!p.isMedia || p.mediaBytes !== null || renamedIds.has(p.doc.id))
1061
+ continue;
1062
+ const tracked = previousManifest?.docs[p.relPath];
1063
+ if (tracked !== undefined && tracked.id === p.doc.id && tracked.body_sha256 != null)
1064
+ continue;
1065
+ let holdsLocalFile = false;
1066
+ try {
1067
+ holdsLocalFile = fs_1.default.statSync(path_1.default.join(destination, ...p.relPath.split('/'))).isFile();
1068
+ }
1069
+ catch {
1070
+ holdsLocalFile = false;
1071
+ }
1072
+ if (!holdsLocalFile)
1073
+ continue;
1074
+ delete manifestDocs[p.relPath];
1075
+ process.stderr.write(chalk_1.default.yellow(`! doc ${p.doc.id} ("${shown(p.doc.title)}") failed to download and ${shown(p.relPath)} holds a local file; not tracking it — pull again later\n`));
1076
+ }
885
1077
  // Identity of every file this pull actually wrote, keyed by dev:ino. Used by the
886
1078
  // deletion-propagation loop below to recognize an "orphan" that is really just the
887
1079
  // same file this pull wrote under a different manifest key (e.g. a case-only title
888
1080
  // rename on a case-insensitive filesystem) — that file must never be deleted.
1081
+ // writtenPathByIdentity names the path this pull wrote for each identity, so
1082
+ // rename cleanup can warn instead of silently keeping an old path that
1083
+ // aliases a written file (cli#167 M2).
889
1084
  const writtenIdentities = new Set();
1085
+ const writtenPathByIdentity = new Map();
890
1086
  for (const file of files) {
891
1087
  try {
892
1088
  const stat = fs_1.default.statSync(path_1.default.join(destination, ...file.path.split('/')));
893
- writtenIdentities.add(`${stat.dev}:${stat.ino}`);
1089
+ const identity = `${stat.dev}:${stat.ino}`;
1090
+ writtenIdentities.add(identity);
1091
+ writtenPathByIdentity.set(identity, file.path);
894
1092
  }
895
1093
  catch {
896
1094
  continue;
@@ -914,16 +1112,35 @@ async function report(destination, folderPath, fetched, options, config, extraWa
914
1112
  manifestDocs[m.oldRel] = oldEntry;
915
1113
  }
916
1114
  if (m.sourcePresent) {
917
- process.stderr.write(chalk_1.default.yellow(`! kept ${m.oldRel} — doc ${m.id} download failed; still tracked as ${m.oldRel}\n`));
1115
+ process.stderr.write(chalk_1.default.yellow(`! kept ${shown(m.oldRel)} — doc ${m.id} download failed; still tracked as ${shown(m.oldRel)}\n`));
918
1116
  }
919
1117
  else {
920
- process.stderr.write(chalk_1.default.yellow(`! doc ${m.id} download failed; still tracked as ${m.oldRel}, which is not present locally\n`));
1118
+ process.stderr.write(chalk_1.default.yellow(`! doc ${m.id} download failed; still tracked as ${shown(m.oldRel)}, which is not present locally\n`));
921
1119
  }
922
1120
  continue;
923
1121
  }
924
1122
  if (!m.sourcePresent)
925
1123
  continue;
926
1124
  const absOld = path_1.default.resolve(destination, ...m.oldRel.split('/'));
1125
+ // cli#167 M2: the old path is the same file as one this pull just
1126
+ // wrote under another name (a link) — it is kept, loudly, so the
1127
+ // extra name is not mistaken for an orphan. The same-file case
1128
+ // (targetIsSource) stays silent: there is no extra name.
1129
+ if (!m.targetIsSource) {
1130
+ let oldIdentity = null;
1131
+ try {
1132
+ const oldStat = fs_1.default.statSync(absOld);
1133
+ if (oldStat.isFile())
1134
+ oldIdentity = `${oldStat.dev}:${oldStat.ino}`;
1135
+ }
1136
+ catch {
1137
+ oldIdentity = null;
1138
+ }
1139
+ const writtenPath = oldIdentity === null ? undefined : writtenPathByIdentity.get(oldIdentity);
1140
+ if (writtenPath !== undefined) {
1141
+ process.stderr.write(chalk_1.default.yellow(`! kept ${shown(m.oldRel)}: it is the same file as ${shown(writtenPath)} (a link); the extra name is not tracked — remove it yourself if you don't need it\n`));
1142
+ }
1143
+ }
927
1144
  if (!isSafeToRemoveTrackedFile(absOld, destPrefix, realDest, writtenIdentities))
928
1145
  continue;
929
1146
  try {
@@ -960,7 +1177,7 @@ async function report(destination, folderPath, fetched, options, config, extraWa
960
1177
  process.stderr.write(chalk_1.default.yellow("deletions not propagated: single-doc pull cannot speak for a folder's contents\n"));
961
1178
  }
962
1179
  else if (previousManifest.folder_path !== folderPath) {
963
- process.stderr.write(chalk_1.default.yellow(`deletions not propagated: this directory tracks "${previousManifest.folder_path}", not "${folderPath}"\n`));
1180
+ process.stderr.write(chalk_1.default.yellow(`deletions not propagated: this directory tracks "${shown(previousManifest.folder_path)}", not "${shown(folderPath)}"\n`));
964
1181
  }
965
1182
  }
966
1183
  const keptModifiedMedia = new Set();
@@ -998,18 +1215,18 @@ async function report(destination, folderPath, fetched, options, config, extraWa
998
1215
  }
999
1216
  }
1000
1217
  if (options.json) {
1001
- console.log(JSON.stringify({ manifest, files, removed, kept_modified: keptModified }));
1218
+ console.log((0, source_provenance_1.escapeJsonDisplayText)(JSON.stringify({ manifest, files, removed, kept_modified: keptModified })));
1002
1219
  process.exit(0);
1003
1220
  }
1004
- console.log(chalk_1.default.green(`pulled ${files.length} doc${files.length === 1 ? '' : 's'} → ${destination}`));
1221
+ console.log(chalk_1.default.green(`pulled ${files.length} doc${files.length === 1 ? '' : 's'} → ${shown(destination)}`));
1005
1222
  for (const file of files) {
1006
- console.log(chalk_1.default.gray(` ${file.path}`));
1223
+ console.log(chalk_1.default.gray(` ${shown(file.path)}`));
1007
1224
  }
1008
1225
  for (const file of removed) {
1009
- console.log(chalk_1.default.gray(`- removed (deleted remotely): ${file}`));
1226
+ console.log(chalk_1.default.gray(`- removed (deleted remotely): ${shown(file)}`));
1010
1227
  }
1011
1228
  for (const file of keptModified) {
1012
- process.stderr.write(chalk_1.default.yellow(`! kept ${file} — deleted remotely but modified locally\n`));
1229
+ process.stderr.write(chalk_1.default.yellow(`! kept ${shown(file)} — deleted remotely but modified locally\n`));
1013
1230
  if (keptModifiedMedia.has(file)) {
1014
1231
  process.stderr.write(chalk_1.default.yellow(' (it is now untracked; use `solidactions doc upload` to re-create it)\n'));
1015
1232
  }
@@ -1021,8 +1238,19 @@ async function report(destination, folderPath, fetched, options, config, extraWa
1021
1238
  }
1022
1239
  /**
1023
1240
  * Entry point called from index.ts.
1241
+ *
1242
+ * Command-level error boundary (cli#189): any error escaping the command's
1243
+ * work — a server-bearing exception like `McpRpcError` as well as a
1244
+ * filesystem throw — prints one sanitised red `error: ` line and exits 1.
1245
+ * The command's own `process.exit` calls terminate the process and never
1246
+ * reach this catch.
1024
1247
  */
1025
1248
  async function docPull(folder, dest, options) {
1026
- const config = await (0, api_1.requireConfigWithWorkspace)();
1027
- await docPullWithConfig(folder, dest, options, config);
1249
+ try {
1250
+ const config = await (0, api_1.requireConfigWithWorkspace)();
1251
+ await docPullWithConfig(folder, dest, options, config);
1252
+ }
1253
+ catch (error) {
1254
+ reportWriteError(error);
1255
+ }
1028
1256
  }
@@ -499,6 +499,10 @@ async function docPushWithConfig(dir, options, config) {
499
499
  trackedMissing.push({ file: relPath, id: entry.id });
500
500
  continue;
501
501
  }
502
+ if (status === 401) {
503
+ process.stderr.write(chalk_1.default.red((0, api_1.authFailedLine)(config.host)) + '\n');
504
+ process.exit(1);
505
+ }
502
506
  process.stderr.write(chalk_1.default.red(`error: ${relPath}: ${data?.message ?? error.message}\n`));
503
507
  process.exit(1);
504
508
  }