@needmoretruth/nmts-cli 0.36.3 → 0.38.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/AGENTS.md +22 -0
  2. package/CHANGELOG.md +25 -0
  3. package/README.ko.md +1 -1
  4. package/README.md +1 -1
  5. package/dist/artifact-about.d.ts +1 -1
  6. package/dist/commands/erase.js +1 -1
  7. package/dist/commands/organise.d.ts +5 -27
  8. package/dist/commands/organise.js +33 -193
  9. package/dist/commands/push.js +1 -1
  10. package/dist/commands/s3.d.ts +0 -10
  11. package/dist/commands/s3.js +46 -121
  12. package/dist/commands/trash.d.ts +0 -9
  13. package/dist/commands/trash.js +23 -223
  14. package/dist/drive-edit/errors.d.ts +44 -0
  15. package/dist/drive-edit/errors.js +65 -0
  16. package/dist/drive-edit/folders.d.ts +29 -0
  17. package/dist/drive-edit/folders.js +98 -0
  18. package/dist/drive-edit/move.d.ts +66 -0
  19. package/dist/drive-edit/move.js +119 -0
  20. package/dist/drive-edit/trash.d.ts +53 -0
  21. package/dist/drive-edit/trash.js +190 -0
  22. package/dist/drive-edit/tree.d.ts +15 -0
  23. package/dist/drive-edit/tree.js +77 -0
  24. package/dist/drive-edit.d.ts +9 -0
  25. package/dist/drive-edit.js +23 -0
  26. package/dist/product.d.ts +1 -1
  27. package/dist/product.js +1 -1
  28. package/dist/s3/contract.d.ts +80 -0
  29. package/dist/s3/contract.js +3 -0
  30. package/dist/s3/drive.d.ts +108 -0
  31. package/dist/s3/drive.js +136 -0
  32. package/dist/s3/listing.d.ts +8 -1
  33. package/dist/s3/listing.js +8 -1
  34. package/dist/s3/routes.d.ts +4 -0
  35. package/dist/s3/routes.js +249 -0
  36. package/dist/s3/server.d.ts +15 -53
  37. package/dist/s3/server.js +18 -222
  38. package/dist/s3/sigv4.d.ts +26 -0
  39. package/dist/s3/sigv4.js +37 -0
  40. package/dist/s3/xml.d.ts +8 -1
  41. package/dist/s3/xml.js +13 -4
  42. package/dist/s3-gateway.d.ts +8 -0
  43. package/dist/s3-gateway.js +13 -0
  44. package/docs/commands/create.md +2 -2
  45. package/docs/commands/env.md +1 -1
  46. package/docs/commands/extend.md +0 -3
  47. package/docs/commands/login.md +1 -1
  48. package/docs/commands/logout.md +1 -1
  49. package/docs/commands/marks.md +1 -1
  50. package/docs/commands/mcp.md +1 -1
  51. package/docs/commands/put.md +2 -2
  52. package/docs/commands/wallet.md +7 -9
  53. package/docs/commands/whoami.md +2 -2
  54. package/package.json +9 -1
@@ -0,0 +1,98 @@
1
+ // Making a folder, and every folder above it that is missing.
2
+ import { KIND_FOLDER, normaliseName, normalisePath } from "../drive-paths.js";
3
+ import { NmtsError } from "../errors.js";
4
+ import { applyToList } from "../manifest-write.js";
5
+ import { DriveEditError } from "./errors.js";
6
+ /**
7
+ * Make a folder path, and every folder above it that is missing, for an account already opened.
8
+ *
9
+ * ⛔ THE RULES BELOW ARE THE ONES A SECOND COPY WOULD GET SUBTLY WRONG: a folder that is already
10
+ * there IS the folder asked for (never a numbered one), the decision is taken inside each
11
+ * attempt so a lost race cannot make two, and what was made before a failure is named rather
12
+ * than silently kept.
13
+ *
14
+ * ⚠ MISSING PARENTS ARE CREATED, and that is a decision rather than a convenience. A folder costs
15
+ * nothing, holds nothing and can be moved to the trash, so the failure mode of creating one too
16
+ * many is a tidy-up; the failure mode of refusing is a caller that has to discover the tree one
17
+ * call at a time. Every folder made is named in the result, so it is never a surprise.
18
+ */
19
+ export async function ensureFolderPath(input, wanted) {
20
+ const made = [];
21
+ let parentId = null;
22
+ let walked = "";
23
+ for (const name of wanted.split("/")) {
24
+ // ⚠ A name that is only spaces is refused too. `mkdir` used to accept it, and then `rm` and
25
+ // `restore` rejected the very path `ls` printed for it as "no path given" — a code-2 message
26
+ // blaming the caller for an argument they had supplied (2026-08-23).
27
+ if (name.trim() === "" || name === "." || name === "..") {
28
+ throw new DriveEditError("BAD_NAME", `"${wanted}" is not a folder path this tool will make.`, {
29
+ exitCode: 2,
30
+ nextStep: `Empty names, "." and ".." are not folder names in a drive. Nothing was made.`,
31
+ });
32
+ }
33
+ walked = walked === "" ? name : `${walked}/${name}`;
34
+ const under = parentId;
35
+ const here = walked;
36
+ // The global one, not `node:crypto`: the SDK's browser entry bundles this file.
37
+ const fresh = globalThis.crypto.randomUUID();
38
+ let landedOn = fresh;
39
+ // ⛔ ONE WRITE PER FOLDER, and the check that decides whether to write happens INSIDE the
40
+ // attempt. Two things went wrong when it sat outside (2026-08-23):
41
+ // · running `mkdir` twice at the same moment made `shared` AND `shared (2)`, because the
42
+ // loser of the compare-and-swap re-applied a decision taken against the older list;
43
+ // · a trashed folder of the same name made the second `mkdir` produce `photos (2)` while
44
+ // printing `Made "photos"`, because it went through the upload helper — and picking a
45
+ // free name is the right rule for BYTES and the wrong rule for a folder. A folder with
46
+ // that name in that parent IS the folder that was asked for.
47
+ // Building the whole chain in memory and writing once would be fewer round trips and would
48
+ // also mean a lost compare-and-swap threw away folders the ones below already point at.
49
+ const result = await applyToList(input, (entries) => {
50
+ const there = entries.find((e) => e.parentId === under &&
51
+ normaliseName(e.name) === normaliseName(name) &&
52
+ e.deletedAt === undefined);
53
+ if (there !== undefined) {
54
+ if (there.kind !== KIND_FOLDER) {
55
+ throw new DriveEditError("NAME_TAKEN", `"${here}" is a file, so nothing can be made inside it.`, {
56
+ exitCode: 4,
57
+ nextStep: made.length > 0 ? `The folders made so far are kept: ${made.join(", ")}.` : "Nothing was made.",
58
+ });
59
+ }
60
+ landedOn = there.id;
61
+ return null;
62
+ }
63
+ landedOn = fresh;
64
+ const at = Date.now();
65
+ return {
66
+ op: "add",
67
+ entry: { id: fresh, parentId: under, kind: KIND_FOLDER, name, size: 0, createdAt: at, updatedAt: at },
68
+ };
69
+ }).catch((error) => {
70
+ // ⛔ WHAT SURVIVED IS NAMED. A run that stops half way leaves real folders behind, and the
71
+ // message that says so was attached only to the "that is a file" refusal.
72
+ if (error instanceof NmtsError || made.length === 0)
73
+ throw error;
74
+ const because = error instanceof Error ? error.message : "the server refused";
75
+ throw new NmtsError(because, {
76
+ exitCode: 1,
77
+ nextStep: `The folders made so far are kept: ${made.join(", ")}. Running the same command again ` +
78
+ `makes the rest — nothing is lost.`,
79
+ });
80
+ });
81
+ if (result.changed)
82
+ made.push(here);
83
+ parentId = landedOn;
84
+ }
85
+ return { parentId, made };
86
+ }
87
+ /** Make one folder path. A path that is already there is a success with nothing made. */
88
+ export async function makeFolder(input, path) {
89
+ const wanted = normalisePath(path);
90
+ if (wanted === "") {
91
+ throw new DriveEditError("BAD_NAME", `"${path}" names the whole drive, not a folder in it.`, {
92
+ exitCode: 2,
93
+ nextStep: "Nothing was made.",
94
+ });
95
+ }
96
+ const { parentId, made } = await ensureFolderPath(input, wanted);
97
+ return { path: wanted, parentId, made };
98
+ }
@@ -0,0 +1,66 @@
1
+ import { type ListEditInput } from "../manifest-write.ts";
2
+ /** One thing a move carried, with where it came from and where it landed. */
3
+ export interface MovedThing {
4
+ id: string;
5
+ /** Its name, which a move never changes. */
6
+ name: string;
7
+ /** Its full path before the move. */
8
+ from: string;
9
+ /** Its full path after, or null if another device took it out of the list meanwhile. */
10
+ path: string | null;
11
+ }
12
+ /** What one run of moving did. */
13
+ export interface MoveOutcome {
14
+ /** The things this run moved, in the order they were named. */
15
+ moved: MovedThing[];
16
+ /** The names that were already in the destination, so nothing was written for them. */
17
+ already: string[];
18
+ /** The destination folder id, or null for the top of the drive. */
19
+ parentId: string | null;
20
+ /** False when everything named was already there, so no list was written. */
21
+ changed: boolean;
22
+ /** True when the list was rebuilt because another device wrote first. */
23
+ reappliedAfterConflict: boolean;
24
+ /** The list version now current. */
25
+ seq: number;
26
+ }
27
+ /**
28
+ * Move things into a folder. An empty destination is the top of the drive.
29
+ *
30
+ * ⛔ ONE WRITE FOR THE WHOLE RUN, however many things are named. The list is rewritten whole on
31
+ * every save, so a second thing costs nothing extra — while a second WRITE is a second chance
32
+ * to lose the compare-and-swap, and losing it half way through a run leaves some things moved
33
+ * and some not, which is a state the caller cannot tell apart from the one it asked for.
34
+ *
35
+ * ⛔ AND THE NAME CHECK RUNS AGAINST WHAT THIS RUN HAS ALREADY MOVED, not against the list as it
36
+ * was read. Two files called `notes.txt` in two folders, moved into one folder by one call,
37
+ * would otherwise both be written — two entries at one path, which nothing can address
38
+ * afterwards: every lookup answers "names 2 things in this account". So the loop folds each
39
+ * move onto a working copy and asks the working copy the next question.
40
+ */
41
+ export declare function moveEntries(input: ListEditInput, paths: readonly string[], destination: string): Promise<MoveOutcome>;
42
+ /** What renaming one thing did. */
43
+ export interface RenameOutcome {
44
+ id: string;
45
+ /** The name it had. */
46
+ from: string;
47
+ /** The full path it had, which is what a person recognises it by. */
48
+ fromPath: string;
49
+ /** The name it has now. */
50
+ to: string;
51
+ /** False when it was already called that, so no list was written. */
52
+ changed: boolean;
53
+ reappliedAfterConflict: boolean;
54
+ seq: number;
55
+ }
56
+ /**
57
+ * Give one thing a new name. The path stays the same otherwise.
58
+ *
59
+ * ⛔ REFUSED RATHER THAN NUMBERED, AND THE REFUSAL IS RE-DECIDED ON EVERY ATTEMPT. An upload picks
60
+ * `report (2).pdf` because nobody was watching; a rename is somebody choosing a name on purpose,
61
+ * and silently giving them a different one is how two files end up looking like a mistake nobody
62
+ * made. Checking once, before the write, was not enough: when another device took the name in
63
+ * between, the retry re-applied the old decision and produced two entries at one path, which
64
+ * nothing can address afterwards (2026-08-23).
65
+ */
66
+ export declare function renameEntry(input: ListEditInput, path: string, name: string): Promise<RenameOutcome>;
@@ -0,0 +1,119 @@
1
+ // Moving things into a folder, and giving one thing a new name where it is.
2
+ import { buildIndex, entryAt, folderIdFor, fullPathOf, namesIn, normaliseName, } from "../drive-paths.js";
3
+ import { readFileList } from "../manifest.js";
4
+ import { applyManyToList, applyToList, batchTargets } from "../manifest-write.js";
5
+ import { applyIntent } from "../shared/lib/drive/manifest-ops.js";
6
+ import { DriveEditError, requireNewName, resolving } from "./errors.js";
7
+ import { isUnder } from "./tree.js";
8
+ /**
9
+ * Move things into a folder. An empty destination is the top of the drive.
10
+ *
11
+ * ⛔ ONE WRITE FOR THE WHOLE RUN, however many things are named. The list is rewritten whole on
12
+ * every save, so a second thing costs nothing extra — while a second WRITE is a second chance
13
+ * to lose the compare-and-swap, and losing it half way through a run leaves some things moved
14
+ * and some not, which is a state the caller cannot tell apart from the one it asked for.
15
+ *
16
+ * ⛔ AND THE NAME CHECK RUNS AGAINST WHAT THIS RUN HAS ALREADY MOVED, not against the list as it
17
+ * was read. Two files called `notes.txt` in two folders, moved into one folder by one call,
18
+ * would otherwise both be written — two entries at one path, which nothing can address
19
+ * afterwards: every lookup answers "names 2 things in this account". So the loop folds each
20
+ * move onto a working copy and asks the working copy the next question.
21
+ */
22
+ export async function moveEntries(input, paths, destination) {
23
+ const at = Date.now();
24
+ let moved = [];
25
+ let already = [];
26
+ let parentId = null;
27
+ // ⛔ EVERY GUARD RUNS INSIDE THE ATTEMPT, INCLUDING WHICH ENTRY EACH PATH NAMES. A lost
28
+ // compare-and-swap re-applies the intent to a list that changed underneath — and when the
29
+ // winner had just taken this name, the loser landed on top of it and produced two entries at
30
+ // one path. Meanwhile the caller was told the move had been made.
31
+ const result = await applyManyToList(input, (now) => {
32
+ const targets = resolving(() => batchTargets(now, paths, { nothingHappened: "Nothing was moved." }));
33
+ const into = resolving(() => folderIdFor(destination, now, "Nothing was moved."));
34
+ const index = buildIndex(now);
35
+ const intents = [];
36
+ const carried = [];
37
+ const there = [];
38
+ let working = now;
39
+ for (const target of targets) {
40
+ if (into !== null && (into === target.id || isUnder(working, into, target.id))) {
41
+ throw new DriveEditError("INTO_ITSELF", `A folder cannot be moved inside itself.`, {
42
+ exitCode: 4,
43
+ nextStep: "Nothing was moved.",
44
+ });
45
+ }
46
+ if (into === target.parentId) {
47
+ there.push(target.name);
48
+ continue;
49
+ }
50
+ if (namesIn(working, into).has(normaliseName(target.name))) {
51
+ throw new DriveEditError("NAME_TAKEN", `Something called "${target.name}" is already in that folder.`, {
52
+ exitCode: 4,
53
+ nextStep: `Nothing was moved. Rename it first: nmts rename "${target.name}" <new name>`,
54
+ });
55
+ }
56
+ const intent = { op: "move", id: target.id, parentId: into, at };
57
+ intents.push(intent);
58
+ working = applyIntent(working, intent);
59
+ carried.push({ id: target.id, name: target.name, from: fullPathOf(index, target) });
60
+ }
61
+ moved = carried;
62
+ already = there;
63
+ parentId = into;
64
+ return intents;
65
+ });
66
+ // ⚠ Read off the list AS WRITTEN, not off the intents: an id another device took out of the list
67
+ // meanwhile has no path any more, and claiming one would name a place nothing is at.
68
+ const after = buildIndex(result.entries);
69
+ return {
70
+ moved: moved.map((m) => {
71
+ const live = result.entries.find((e) => e.id === m.id);
72
+ return { id: m.id, name: m.name, from: m.from, path: live === undefined ? null : fullPathOf(after, live) };
73
+ }),
74
+ already,
75
+ parentId,
76
+ changed: result.changed,
77
+ reappliedAfterConflict: result.reappliedAfterConflict,
78
+ seq: result.seq,
79
+ };
80
+ }
81
+ /**
82
+ * Give one thing a new name. The path stays the same otherwise.
83
+ *
84
+ * ⛔ REFUSED RATHER THAN NUMBERED, AND THE REFUSAL IS RE-DECIDED ON EVERY ATTEMPT. An upload picks
85
+ * `report (2).pdf` because nobody was watching; a rename is somebody choosing a name on purpose,
86
+ * and silently giving them a different one is how two files end up looking like a mistake nobody
87
+ * made. Checking once, before the write, was not enough: when another device took the name in
88
+ * between, the retry re-applied the old decision and produced two entries at one path, which
89
+ * nothing can address afterwards (2026-08-23).
90
+ */
91
+ export async function renameEntry(input, path, name) {
92
+ requireNewName(name);
93
+ const list = await readFileList(input.server, input.apiKey, input.code, input.accountId);
94
+ const entries = list.manifest?.entries ?? [];
95
+ const target = resolving(() => entryAt(entries, path, { nothingHappened: "Nothing was renamed." }));
96
+ const at = Date.now();
97
+ const fromPath = fullPathOf(buildIndex(entries), target);
98
+ const result = await applyToList(input, (now) => {
99
+ const live = now.find((e) => e.id === target.id);
100
+ if (live === undefined)
101
+ return null;
102
+ if (normaliseName(name) !== normaliseName(live.name) && namesIn(now, live.parentId).has(normaliseName(name))) {
103
+ throw new DriveEditError("NAME_TAKEN", `Something called "${name}" is already in that folder.`, {
104
+ exitCode: 4,
105
+ nextStep: "Nothing was renamed.",
106
+ });
107
+ }
108
+ return { op: "rename", id: target.id, name, at };
109
+ });
110
+ return {
111
+ id: target.id,
112
+ from: target.name,
113
+ fromPath,
114
+ to: name,
115
+ changed: result.changed,
116
+ reappliedAfterConflict: result.reappliedAfterConflict,
117
+ seq: result.seq,
118
+ };
119
+ }
@@ -0,0 +1,53 @@
1
+ import { type ListEditInput } from "../manifest-write.ts";
2
+ /**
3
+ * What one run of the trash did — and, in this order, exactly what `nmts rm --json` prints.
4
+ *
5
+ * ⛔ THE ORDER OF THESE FIELDS IS THE COMMAND'S JSON. The command hands this object straight to
6
+ * `JSON.stringify`, so a field added in the middle changes what an agent reading that output
7
+ * sees. Add at the end, or not at all.
8
+ */
9
+ export interface TrashOutcome {
10
+ /** The paths acted on. Empty when everything named was already where it was asked to be. */
11
+ paths: string[];
12
+ /** Their ids, in the same order. */
13
+ ids: string[];
14
+ /** How many server rows were moved. A folder has none of its own; its files have one each. */
15
+ files: number;
16
+ /** Named, and nothing written for them: already out of the trash, or covered by a named folder. */
17
+ skipped: string[];
18
+ changed: boolean;
19
+ reappliedAfterConflict: boolean;
20
+ seq: number;
21
+ }
22
+ export interface TrashEditOptions {
23
+ /**
24
+ * Refuse what the command-line tool names and carries on with.
25
+ *
26
+ * ⛔ OFF FOR THE COMMANDS AND ON FOR A LIBRARY, and the difference is who is reading. A person
27
+ * who typed `nmts restore a.txt b.txt` and had already restored `a.txt` wants `b.txt` back and
28
+ * a line saying the first was not in the trash; a program calling `restore` wants to know that
29
+ * what it asked for was not what it got, and the only way it learns that is a refusal.
30
+ *
31
+ * It adds two: a path that is not in the trash (`NOT_IN_TRASH`) and a restore whose old name has
32
+ * been taken since (`NAME_TAKEN`).
33
+ */
34
+ strict?: boolean;
35
+ }
36
+ /**
37
+ * Move things to the trash, or bring them back.
38
+ *
39
+ * ⛔ NEITHER HALF DESTROYS ANYTHING. `rm` moves everything it is given to the trash, where it stays
40
+ * restorable for thirty days; the endpoint that erases a stored row for good is closed to an API
41
+ * key and stays closed, so nothing here can reach it.
42
+ *
43
+ * ⛔ THE SERVER ROW GOES FIRST, AND "ALREADY DONE" COUNTS AS DONE. A trashed item's bytes cannot be
44
+ * fetched, so the state to avoid above all others is a list that shows a file as live when the
45
+ * server has already trashed it: the person sees it, asks for it, and is told it does not exist.
46
+ * Writing the list only after the server agreed means a failed server call leaves the drive
47
+ * exactly as it was — the state a caller can act on.
48
+ *
49
+ * ⛔ AND ONE PATH THAT WILL NOT RESOLVE REFUSES THE WHOLE RUN, before a single server row is
50
+ * touched. Trashing four of the five things somebody named and answering success is worse than
51
+ * trashing none: the run reads as done, and finding the odd one out means diffing the drive.
52
+ */
53
+ export declare function trashPaths(input: ListEditInput, verb: "rm" | "restore", paths: readonly string[], options?: TrashEditOptions): Promise<TrashOutcome>;
@@ -0,0 +1,190 @@
1
+ // The two halves of the trash: moving things into it, and bringing them back.
2
+ import { buildIndex, fullPathOf, isLive, normaliseName } from "../drive-paths.js";
3
+ import { NmtsError } from "../errors.js";
4
+ import { setTrashed } from "../item-trash.js";
5
+ import { readFileList } from "../manifest.js";
6
+ import { applyManyToList, batchTargets } from "../manifest-write.js";
7
+ import { applyIntent } from "../shared/lib/drive/manifest-ops.js";
8
+ import { DriveEditError, resolving } from "./errors.js";
9
+ import { filesUnder, hasNamedAncestor, uniqueById } from "./tree.js";
10
+ /**
11
+ * Move things to the trash, or bring them back.
12
+ *
13
+ * ⛔ NEITHER HALF DESTROYS ANYTHING. `rm` moves everything it is given to the trash, where it stays
14
+ * restorable for thirty days; the endpoint that erases a stored row for good is closed to an API
15
+ * key and stays closed, so nothing here can reach it.
16
+ *
17
+ * ⛔ THE SERVER ROW GOES FIRST, AND "ALREADY DONE" COUNTS AS DONE. A trashed item's bytes cannot be
18
+ * fetched, so the state to avoid above all others is a list that shows a file as live when the
19
+ * server has already trashed it: the person sees it, asks for it, and is told it does not exist.
20
+ * Writing the list only after the server agreed means a failed server call leaves the drive
21
+ * exactly as it was — the state a caller can act on.
22
+ *
23
+ * ⛔ AND ONE PATH THAT WILL NOT RESOLVE REFUSES THE WHOLE RUN, before a single server row is
24
+ * touched. Trashing four of the five things somebody named and answering success is worse than
25
+ * trashing none: the run reads as done, and finding the odd one out means diffing the drive.
26
+ */
27
+ export async function trashPaths(input, verb, paths, options = {}) {
28
+ const list = await readFileList(input.server, input.apiKey, input.code, input.accountId);
29
+ const entries = list.manifest?.entries ?? [];
30
+ // ⛔ `rm` REFUSES what is already in the trash rather than quietly doing nothing, so the caller
31
+ // learns nothing was needed; `restore` has to be able to SEE the trash to act on it. That is
32
+ // why the two lookups differ.
33
+ const index = buildIndex(entries);
34
+ const found = resolving(() => batchTargets(entries, paths, {
35
+ ...(verb === "restore" ? { includeTrashed: true } : {}),
36
+ nothingHappened: "Nothing changed.",
37
+ }));
38
+ const acting = [];
39
+ const skipped = [];
40
+ for (const entry of found) {
41
+ const at = fullPathOf(index, entry);
42
+ if (verb === "restore" && isLive(index, entry)) {
43
+ // Already in the state being asked for. Named, and left alone — unless the caller is a
44
+ // program, which cannot read a line about it.
45
+ if (options.strict === true) {
46
+ throw new DriveEditError("NOT_IN_TRASH", `"${at}" is not in the trash.`, {
47
+ exitCode: 4,
48
+ nextStep: "Nothing changed. Only something in the trash can be restored.",
49
+ });
50
+ }
51
+ skipped.push(at);
52
+ continue;
53
+ }
54
+ if (verb === "restore" && entry.deletedAt === undefined) {
55
+ // In the trash, but only because something above it is. Restoring this row would clear a
56
+ // `deletedAt` it does not have and leave the person exactly where they were.
57
+ throw new DriveEditError("NOT_IN_TRASH", `"${at}" is in the trash because a folder above it is.`, {
58
+ exitCode: 4,
59
+ nextStep: `Nothing changed. Restore that folder instead — \`nmts ls --all\` shows which one carries the trash.`,
60
+ });
61
+ }
62
+ acting.push({ entry, path: at });
63
+ }
64
+ // ⛔ NAMING A FOLDER AND SOMETHING INSIDE IT IS NAMING ONE TRASHING TWICE, and only for `rm` is
65
+ // that a problem worth solving here: stamping the child as well would give it a thirty-day
66
+ // clock of its own, and then restoring the folder would leave it behind — the person would
67
+ // have to remember they had also named it to ever find it again. Its bytes are covered either
68
+ // way, because the rows are read from the folder. `restore` is the opposite case: a child with
69
+ // its own instant needs its own clearing, so nothing is dropped there.
70
+ const named = new Set(acting.map((t) => t.entry.id));
71
+ const covered = verb === "rm" ? acting.filter((t) => hasNamedAncestor(entries, t.entry, named)) : [];
72
+ const targets = acting.filter((t) => !covered.includes(t));
73
+ for (const t of covered)
74
+ skipped.push(t.path);
75
+ if (targets.length === 0) {
76
+ // Everything named was already where it was asked to be. A no-op is a success: writing the
77
+ // list would cost every other device a download for nothing.
78
+ return { paths: [], ids: [], files: 0, skipped, changed: false, reappliedAfterConflict: false, seq: list.seq ?? 0 };
79
+ }
80
+ // Every FILE at or under the targets — a folder holds no bytes and has no server row, so the
81
+ // rows to move are its file descendants.
82
+ //
83
+ // ⛔ THE ROWS TO MOVE ARE THE ONES THE EDIT WILL MAKE REACHABLE, so the set is read off a PREVIEW
84
+ // of the list rather than guessed (2026-08-23). `rm` is easy — everything under the target
85
+ // loses its bytes. `restore` is not: a file the person deleted separately last week keeps its
86
+ // own `deletedAt`, stays in the trash after the folder comes back, and its row must stay
87
+ // deleted with it. Restoring that row would cancel its own thirty-day sweep, go on costing
88
+ // storage, and leave the list saying "trashed" while the server says "live" — after which
89
+ // `rm` refuses to put it back and there is no way out.
90
+ const at = Date.now();
91
+ const ids = targets.map((t) => t.entry.id);
92
+ const preview = buildIndex(applyIntent(entries, intentFor(verb, ids, at)));
93
+ const under = uniqueById(targets.flatMap((t) => filesUnder(entries, t.entry.id)));
94
+ // ⚠ Judged on the PREVIEW's own row, not on the one in hand: `applyIntent` returns new objects,
95
+ // so asking the preview about the old object reads the old `deletedAt` and answers "still
96
+ // trashed" for the very thing being restored.
97
+ const files = verb === "rm"
98
+ ? under
99
+ : under.filter((f) => {
100
+ const after = preview.byId.get(f.id);
101
+ return after !== undefined && isLive(preview, after);
102
+ });
103
+ let done = 0;
104
+ try {
105
+ for (const file of files) {
106
+ await setTrashed(input.server, input.apiKey, file.id, verb === "rm");
107
+ done += 1;
108
+ }
109
+ }
110
+ catch (error) {
111
+ // ⛔ A HALF-FINISHED RUN MUST NAME ITSELF. Without this an agent sees six words of stderr and
112
+ // the tool's own guidance ("a refusal is not a transient error, do not retry in a loop")
113
+ // steers it away from the one thing that fixes this — running the same command again.
114
+ const because = error instanceof Error ? error.message : "the server refused";
115
+ throw new NmtsError(because, {
116
+ exitCode: 1,
117
+ nextStep: `${done} of ${files.length} file rows were moved before this stopped, and the file list was ` +
118
+ `not written. Running \`nmts ${verb}\` on the same paths again finishes the job — nothing is lost.`,
119
+ });
120
+ }
121
+ // ⛔ THE IDS ARE DECIDED AGAIN ON EVERY ATTEMPT, and this is not ceremony. Between the read above
122
+ // and the write below another device can put one of these targets in the trash — by trashing
123
+ // it, or by moving it under a folder that already is. Re-applying the intent we built earlier
124
+ // would then stamp `deletedAt` on something that is ALREADY in the trash by inheritance,
125
+ // giving it a clock of its own and quietly detaching it from the folder it came with:
126
+ // restoring that folder afterwards would leave it behind. An id that has left the list
127
+ // entirely is dropped for the reason `manifest-ops.ts` gives — the other device removing it is
128
+ // newer information than our edit, and putting it back would undo a deletion somebody made on
129
+ // purpose.
130
+ const writing = applyManyToList(input, (now) => {
131
+ const nowIndex = buildIndex(now);
132
+ const still = ids.filter((id) => {
133
+ const live = nowIndex.byId.get(id);
134
+ if (live === undefined)
135
+ return false;
136
+ return verb === "rm" ? isLive(nowIndex, live) : live.deletedAt !== undefined;
137
+ });
138
+ if (verb === "restore" && options.strict === true)
139
+ refuseTakenNames(now, nowIndex.byId, still);
140
+ return still.length === 0 ? [] : [intentFor(verb, still, at)];
141
+ });
142
+ // ⛔ A STRICT RESTORE REFUSED HERE HAS ALREADY MOVED ITS ROWS. The name was free when the trash
143
+ // was read and taken by the time the list was written, so the rows above are live while the
144
+ // list still says trashed — the state the note on `files` calls no way out. Put the rows back
145
+ // before the refusal leaves. If putting them back fails too, the refusal still leaves as it
146
+ // is: restoring again after the rename moves the same rows and writes the list.
147
+ const result = await writing.catch(async (error) => {
148
+ if (verb === "restore" && error instanceof DriveEditError && error.code === "NAME_TAKEN") {
149
+ for (const file of files) {
150
+ await setTrashed(input.server, input.apiKey, file.id, true).catch(() => undefined);
151
+ }
152
+ }
153
+ throw error;
154
+ });
155
+ return {
156
+ paths: targets.map((t) => t.path),
157
+ ids,
158
+ files: files.length,
159
+ skipped,
160
+ changed: result.changed,
161
+ reappliedAfterConflict: result.reappliedAfterConflict,
162
+ seq: result.seq,
163
+ };
164
+ }
165
+ /**
166
+ * Refuse a restore that would land beside a live thing of the same name.
167
+ *
168
+ * ⛔ DECIDED INSIDE THE ATTEMPT like every other guard here: the name that was free when the trash
169
+ * was read can be taken by the time the list is written, and two entries at one path is a state
170
+ * no lookup can get out of.
171
+ */
172
+ function refuseTakenNames(entries, byId, ids) {
173
+ const index = buildIndex(entries);
174
+ for (const id of ids) {
175
+ const entry = byId.get(id);
176
+ if (entry === undefined)
177
+ continue;
178
+ const holder = entries.find((e) => e.id !== id && e.parentId === entry.parentId && normaliseName(e.name) === normaliseName(entry.name) && isLive(index, e));
179
+ if (holder === undefined)
180
+ continue;
181
+ throw new DriveEditError("NAME_TAKEN", `Something called "${entry.name}" is already in that folder.`, {
182
+ exitCode: 4,
183
+ nextStep: "The file list was not changed. Rename the one that is there, then restore again.",
184
+ });
185
+ }
186
+ }
187
+ /** The one intent either half of the trash writes. Built in two places, so it is spelled in one. */
188
+ function intentFor(verb, ids, at) {
189
+ return verb === "rm" ? { op: "trash", ids, at } : { op: "restore", ids, at };
190
+ }
@@ -0,0 +1,15 @@
1
+ import type { ManifestEntry } from "../shared/lib/drive/manifest-codec.ts";
2
+ /** Is `id` at or under `rootId`? Used to refuse moving a folder into its own subtree. */
3
+ export declare function isUnder(entries: readonly ManifestEntry[], id: string | null, rootId: string): boolean;
4
+ /** Is any ancestor of this entry in the set? Used to drop a target a named folder already covers. */
5
+ export declare function hasNamedAncestor(entries: readonly ManifestEntry[], entry: ManifestEntry, named: ReadonlySet<string>): boolean;
6
+ /** One entry per id, keeping the first. Two named folders can hold the same file only once. */
7
+ export declare function uniqueById(files: readonly ManifestEntry[]): ManifestEntry[];
8
+ /**
9
+ * Every file at or under one entry.
10
+ *
11
+ * ⚠ Trashed descendants are INCLUDED HERE, and the CALLER filters. Somebody who trashed one file
12
+ * last week and then trashes its folder expects the folder to be gone from the server too — so
13
+ * `rm` takes this set whole. `restore` cannot: see the note at the call site.
14
+ */
15
+ export declare function filesUnder(entries: readonly ManifestEntry[], rootId: string): ManifestEntry[];
@@ -0,0 +1,77 @@
1
+ // Walking the list: the three questions the edits below ask about where an entry sits, and the one
2
+ // that gathers the files a folder carries.
3
+ import { buildIndex, KIND_FILE } from "../drive-paths.js";
4
+ /** Is `id` at or under `rootId`? Used to refuse moving a folder into its own subtree. */
5
+ export function isUnder(entries, id, rootId) {
6
+ const byId = buildIndex(entries).byId;
7
+ const seen = new Set();
8
+ let at = id;
9
+ while (at !== null && !seen.has(at)) {
10
+ if (at === rootId)
11
+ return true;
12
+ seen.add(at);
13
+ at = byId.get(at)?.parentId ?? null;
14
+ }
15
+ return false;
16
+ }
17
+ /** Is any ancestor of this entry in the set? Used to drop a target a named folder already covers. */
18
+ export function hasNamedAncestor(entries, entry, named) {
19
+ const byId = buildIndex(entries).byId;
20
+ const seen = new Set([entry.id]);
21
+ let at = entry.parentId;
22
+ while (at !== null && !seen.has(at)) {
23
+ if (named.has(at))
24
+ return true;
25
+ seen.add(at);
26
+ at = byId.get(at)?.parentId ?? null;
27
+ }
28
+ return false;
29
+ }
30
+ /** One entry per id, keeping the first. Two named folders can hold the same file only once. */
31
+ export function uniqueById(files) {
32
+ const byId = new Map();
33
+ for (const file of files)
34
+ if (!byId.has(file.id))
35
+ byId.set(file.id, file);
36
+ return [...byId.values()];
37
+ }
38
+ /**
39
+ * Every file at or under one entry.
40
+ *
41
+ * ⚠ Trashed descendants are INCLUDED HERE, and the CALLER filters. Somebody who trashed one file
42
+ * last week and then trashes its folder expects the folder to be gone from the server too — so
43
+ * `rm` takes this set whole. `restore` cannot: see the note at the call site.
44
+ */
45
+ export function filesUnder(entries, rootId) {
46
+ const root = entries.find((e) => e.id === rootId);
47
+ if (root === undefined)
48
+ return [];
49
+ if (root.kind === KIND_FILE)
50
+ return [root];
51
+ const childrenOf = new Map();
52
+ for (const e of entries) {
53
+ const list = childrenOf.get(e.parentId);
54
+ if (list === undefined)
55
+ childrenOf.set(e.parentId, [e]);
56
+ else
57
+ list.push(e);
58
+ }
59
+ const out = [];
60
+ const seen = new Set([rootId]);
61
+ const queue = [rootId];
62
+ while (queue.length > 0) {
63
+ const id = queue.pop();
64
+ if (id === undefined)
65
+ break;
66
+ for (const child of childrenOf.get(id) ?? []) {
67
+ if (seen.has(child.id))
68
+ continue;
69
+ seen.add(child.id);
70
+ if (child.kind === KIND_FILE)
71
+ out.push(child);
72
+ else
73
+ queue.push(child.id);
74
+ }
75
+ }
76
+ return out;
77
+ }
@@ -0,0 +1,9 @@
1
+ export { DriveEditError, requireNewName } from "./drive-edit/errors.ts";
2
+ export type { DriveEditCode } from "./drive-edit/errors.ts";
3
+ export { ensureFolderPath, makeFolder } from "./drive-edit/folders.ts";
4
+ export type { MadeFolder } from "./drive-edit/folders.ts";
5
+ export { moveEntries, renameEntry } from "./drive-edit/move.ts";
6
+ export type { MoveOutcome, MovedThing, RenameOutcome } from "./drive-edit/move.ts";
7
+ export { trashPaths } from "./drive-edit/trash.ts";
8
+ export type { TrashEditOptions, TrashOutcome } from "./drive-edit/trash.ts";
9
+ export { filesUnder } from "./drive-edit/tree.ts";
@@ -0,0 +1,23 @@
1
+ // The drive's own edits without a terminal: making a folder, moving, renaming, and the two halves
2
+ // of the trash — decided, written, and handed back rather than printed.
3
+ //
4
+ // ⛔ ONE IMPLEMENTATION, TWO CALLERS, WHICH IS THE WHOLE REASON THIS FILE EXISTS. The commands in
5
+ // `commands/organise.ts` and `commands/trash.ts` are a terminal's shape: they print sentences
6
+ // and answer an exit code. The SDK is somebody else's program and needs the same five verbs
7
+ // with neither. A second implementation of "what does moving onto a taken name do" would be a
8
+ // second place for the compare-and-swap rules to be got right, and the copy nobody re-reads is
9
+ // the one that quietly disagrees — which is the failure this package has already had once, in
10
+ // the two `mkdir` paths that produced `photos (2)` while printing `Made "photos"`.
11
+ //
12
+ // ⛔ NOTHING HERE WRITES TO A STREAM OR PICKS AN EXIT CODE. Every refusal is thrown and every
13
+ // outcome is returned; the words a person reads are the caller's.
14
+ //
15
+ // ⚠ THE VERBS LIVE IN `drive-edit/`, ONE FILE EACH, AND THIS IS THE DOOR TO THEM. What a caller
16
+ // imports is this name — `@needmoretruth/nmts-cli/drive-edit` — so the pieces can be split and
17
+ // joined without a single caller changing. Nothing in the folder reaches for `node:`: the SDK's
18
+ // browser entry bundles what this exports.
19
+ export { DriveEditError, requireNewName } from "./drive-edit/errors.js";
20
+ export { ensureFolderPath, makeFolder } from "./drive-edit/folders.js";
21
+ export { moveEntries, renameEntry } from "./drive-edit/move.js";
22
+ export { trashPaths } from "./drive-edit/trash.js";
23
+ export { filesUnder } from "./drive-edit/tree.js";