@wirecat/cli-core 0.710.0 → 0.711.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/CHANGELOG.md CHANGED
@@ -5,6 +5,53 @@ Notable changes to `@wirecat/cli-core` (`@wirecat/cli-messaging` up to 0.261.0,
5
5
  minor version may break callers, and says how under "Changed — may break callers". `pnpm docs:check` checks the
6
6
  shape of this file.
7
7
 
8
+ ## 0.711.0 — 19.11.2026
9
+
10
+ ### Added
11
+
12
+ - **Mirror exclusions.** `Mirror.exclude` (and `FileMirrorOptions.exclude`) takes globs, read by `excludedBy` and
13
+ checked by `exclusionPattern`. An excluded path is skipped on both sides and is never deleted: adding an exclusion
14
+ trashes nothing, and removing one syncs the path as a new folder. `fileMirrorStatus` leaves excluded paths out.
15
+ - **A file mirror checks free space before it writes.** A run that would leave less free than a tenth of what it
16
+ writes (at least 100 MB, at most 1 GB) on the drive it downloads into, or on the version store's drive, stops with
17
+ `mirror.no-space` and the bytes it needs. The local
18
+ scan takes up to 100,000 files, and a big state is saved less often.
19
+ - **linear joins `WIRECAT_TOOLS`.** Linear (`linear`, `@wirecat/linear-cli`) is on npm since 0.1.0, so every CLI's
20
+ first screen ("Works with") and first-run list of other WireCat tools now name it, and an upload refuses a file from
21
+ its folders (`linear-cli`, `WCLINEAR_`) as it does for the other tools.
22
+ - **A read-only scheduled agent may stage project and meeting findings.** `projects actions add` and
23
+ `meetings actions add` join `messages acknowledge` and `mail findings add` in the propose tier, when the host marks
24
+ them `proposesOnly`. Like mail findings, each stages a cited batch the owner confirms or rejects; nothing becomes a
25
+ fact or a task until he does. memo's task agent needs it to propose tasks from messengers and meetings.
26
+ - **`@wirecat/cli-core/mount`: show a service's folder as a read-only folder on this computer.** `serveMount` serves a
27
+ `MountSource` (`stat`, `list`, `read` of a byte range; it has no write) over WebDAV on 127.0.0.1, which the system's
28
+ own client mounts: `gio mount` on Linux, Finder on macOS, `net use` on Windows. Every request must carry a random
29
+ per-run secret in its path and this machine's `Host`, so another site's page cannot reach it. Only OPTIONS,
30
+ PROPFIND, GET and HEAD are answered; every write method is refused (405, MKCOL 403), and a file is served sandboxed
31
+ so an HTML file on the mount cannot script it. Listings are kept 10 seconds, so a file manager's
32
+ probes do not spend the service's rate limit ([mount](docs/mount.md)).
33
+
34
+ ### Changed — may break callers
35
+
36
+ - **A file mirror asks before more than 10 deletions or 50 replacements, whatever its size.** The deletion guard no
37
+ longer lets a share of a big mirror through (40 deletions out of 1,000 files used to pass): more than 10 deletions
38
+ stop the run. More than 50 replacements of existing files, on either side, stop it too, as an editor rewriting
39
+ every file or ransomware encrypting the folder would. `allowReplacements` allows them like `allowDeletions`. The
40
+ stop is no longer thrown: the mirror's result carries one `confirmation_required` error at path `.`
41
+ (`mirror.too-many-deletions` or `mirror.too-many-replacements`), so the other mirrors still sync and a watch reports
42
+ it at every cycle that syncs the mirror. Its message names the counts and the one command that allows them;
43
+ `MirrorHints` gains `sync`, `allowReplacements` and `exclude`, and fills `<id>` and `<count>`. See
44
+ [DOCUMENTS.md](docs/dev/DOCUMENTS.md#plain-files-both-ways).
45
+ - **`FileTarget` needs `exists(path)`.** A file missing from a complete listing is deleted locally only once a
46
+ direct read after the listing finds nothing there, so a page that shifted while it was read, or a lagging flat
47
+ listing, never deletes a file. A remote that changes all the time still has its deletions proven: no listing has to
48
+ stand still.
49
+
50
+ ### Fixed
51
+
52
+ - **A local server's answer ends when its body fails part-way.** `listen` left the connection open, and the client
53
+ waited for bytes that never came.
54
+
8
55
  ## 0.710.0 — 19.11.2026
9
56
 
10
57
  ### Added
@@ -45,7 +45,7 @@ export declare const destroysNothing: <T extends Command>(command: T) => T;
45
45
  * be marked `proposesOnly` **and** end with one of these paths; adding a path widens what a read-only agent can
46
46
  * write, so it needs its own review.
47
47
  */
48
- export declare const PROPOSE_COMMANDS: readonly ["messages acknowledge", "mail findings add"];
48
+ export declare const PROPOSE_COMMANDS: readonly ["messages acknowledge", "mail findings add", "projects actions add", "meetings actions add"];
49
49
  /** Marks a command of the `propose` tier; the lock lets it through only when its path is in `PROPOSE_COMMANDS`. */
50
50
  export declare const proposesOnly: <T extends Command>(command: T) => T;
51
51
  export declare const isProposal: (command: Command) => boolean;
@@ -66,7 +66,12 @@ export const destroysNothing = (command) => {
66
66
  * be marked `proposesOnly` **and** end with one of these paths; adding a path widens what a read-only agent can
67
67
  * write, so it needs its own review.
68
68
  */
69
- export const PROPOSE_COMMANDS = ["messages acknowledge", "mail findings add"];
69
+ export const PROPOSE_COMMANDS = [
70
+ "messages acknowledge",
71
+ "mail findings add",
72
+ "projects actions add",
73
+ "meetings actions add",
74
+ ];
70
75
  const PROPOSES = new WeakSet();
71
76
  /** Marks a command of the `propose` tier; the lock lets it through only when its path is in `PROPOSE_COMMANDS`. */
72
77
  export const proposesOnly = (command) => {
@@ -29,12 +29,20 @@ export interface FileTarget {
29
29
  /**
30
30
  * Every file under `root`, with the root folder's own id; undefined when the folder does not exist. `complete` is
31
31
  * false when any page was skipped or a cap was hit: a file missing from such a listing is not taken as deleted.
32
+ * Files at paths `excluded` names are listed too, so a file moved there is found by its id, but count toward no cap.
32
33
  */
33
- list(root: string, signal?: AbortSignal): Promise<{
34
+ list(root: string, signal?: AbortSignal, options?: {
35
+ excluded?(path: string): boolean;
36
+ }): Promise<{
34
37
  rootId: string;
35
38
  files: RemoteFile[];
36
39
  complete: boolean;
37
40
  } | undefined>;
41
+ /**
42
+ * Whether anything is at `path` now, read directly rather than from a listing; false only when the provider says
43
+ * nothing is there. A file missing from a listing is deleted only once this says so.
44
+ */
45
+ exists(path: string, signal?: AbortSignal): Promise<boolean>;
38
46
  /** Streams the file into `into`, a new local file. */
39
47
  download(path: string, into: string, signal?: AbortSignal): Promise<void>;
40
48
  /** Streams the local file `from` to `path` and returns the file as the remote now has it. */
@@ -10,7 +10,8 @@ export type { SyncOptions } from "../services/documents/ports.js";
10
10
  export { extractDocumentMemories, type ImportedSource, type ProposalOptions } from "../services/documents/proposals.js";
11
11
  export { type MirrorAction, type PushConflict, type PushOptions, type PushResult, planPush, pushDocuments, scanLocal, skippedName, } from "../services/documents/push.js";
12
12
  export { type SyncResult, syncDocuments } from "../services/documents/sync.js";
13
- export { type FileMirrorOptions, type FileMirrorResult, type FileMirrorSyncOptions, type FileStep, fileMirrorStatus, fileRemoteChanges, fileSyncState, type MirrorHints, syncFileMirror, syncFileMirrors, } from "../services/files/mirror.js";
13
+ export { excludedBy, exclusionPattern } from "../services/files/exclusions.js";
14
+ export { type FileMirrorOptions, type FileMirrorResult, type FileMirrorSyncOptions, type FileStep, fileMirrorStatus, fileRemoteChanges, fileSyncState, MAX_DELETIONS, MAX_REPLACEMENTS, type MirrorHints, syncFileMirror, syncFileMirrors, } from "../services/files/mirror.js";
14
15
  export { type FileVersion, type FileVersions, fileVersions, restoreFileVersion, type VersionDirection, type VersionEvent, } from "../services/files/versions.js";
15
16
  export { type Block, blockKey, blockShape, type Inline, type ListKind, normalizeInlines } from "./blocks.js";
16
17
  export { catalogFiles } from "./catalog.js";
@@ -9,7 +9,8 @@ export { conflictReport, fileMirrorState, mirrorId, mirrorStatus, syncMirrors, }
9
9
  export { extractDocumentMemories } from "../services/documents/proposals.js";
10
10
  export { planPush, pushDocuments, scanLocal, skippedName, } from "../services/documents/push.js";
11
11
  export { syncDocuments } from "../services/documents/sync.js";
12
- export { fileMirrorStatus, fileRemoteChanges, fileSyncState, syncFileMirror, syncFileMirrors, } from "../services/files/mirror.js";
12
+ export { excludedBy, exclusionPattern } from "../services/files/exclusions.js";
13
+ export { fileMirrorStatus, fileRemoteChanges, fileSyncState, MAX_DELETIONS, MAX_REPLACEMENTS, syncFileMirror, syncFileMirrors, } from "../services/files/mirror.js";
13
14
  export { fileVersions, restoreFileVersion, } from "../services/files/versions.js";
14
15
  export { blockKey, blockShape, normalizeInlines } from "./blocks.js";
15
16
  export { catalogFiles } from "./catalog.js";
@@ -228,6 +228,13 @@ const OTHERS = [
228
228
  "confirmation_required",
229
229
  "the sync would delete more files than the guard allows; check them with --dry-run and allow them explicitly",
230
230
  ],
231
+ [
232
+ "mirror.too-many-replacements",
233
+ "confirmation_required",
234
+ "the sync would replace more files than the guard allows; check them with --dry-run and allow them explicitly",
235
+ ],
236
+ validation("mirror.no-space", "the sync needs more free space than the local drive has"),
237
+ validation("mirror.bad-exclusion", "the exclusion is not a path pattern inside the mirror"),
231
238
  [
232
239
  "mirror.version-not-kept",
233
240
  "provider_error",
@@ -1,5 +1,5 @@
1
1
  import { createServer } from "node:http";
2
- import { Readable } from "node:stream";
2
+ import { pipeline, Readable } from "node:stream";
3
3
  /** Larger bodies are refused unread: the port faces the internet. MCP requests are small JSON. */
4
4
  export const MAX_BODY = 4 * 1024 * 1024;
5
5
  class TooLarge extends Error {
@@ -41,8 +41,8 @@ const send = async (response, outgoing) => {
41
41
  if (!response.body)
42
42
  return void outgoing.end();
43
43
  const body = Readable.fromWeb(response.body);
44
- outgoing.once("close", () => body.destroy());
45
- body.pipe(outgoing);
44
+ // pipe() leaves the answer open when the body fails mid-way, and the client waits for bytes that never come.
45
+ pipeline(body, outgoing, () => undefined);
46
46
  };
47
47
  /**
48
48
  * Binds `host` only — never every interface: the public address is the owner's tunnel.
@@ -0,0 +1,3 @@
1
+ export { type Mounted, type MountOptions, mountSteps, serveMount } from "./serve.js";
2
+ export type { ByteRange, MountEntry, MountRead, MountSource } from "./source.js";
3
+ export { type WebdavOptions, webdavHandler } from "./webdav.js";
@@ -0,0 +1,2 @@
1
+ export { mountSteps, serveMount } from "./serve.js";
2
+ export { webdavHandler } from "./webdav.js";
@@ -0,0 +1,28 @@
1
+ import type { MountSource } from "./source.js";
2
+ export interface MountOptions {
3
+ /** 0 picks a free port. */
4
+ port?: number;
5
+ /** A new random one each run when left out. */
6
+ secret?: string;
7
+ cacheMs?: number;
8
+ now?: () => number;
9
+ onError?: (error: unknown) => void;
10
+ }
11
+ export interface Mounted {
12
+ /** Holds the per-run secret and nothing else: no token, no account. */
13
+ url: string;
14
+ /** The command or the steps that mount `url` on each system. */
15
+ how: {
16
+ linux: string;
17
+ macos: string;
18
+ windows: string;
19
+ };
20
+ close(): Promise<void>;
21
+ }
22
+ /** The ways to mount a URL the system's own WebDAV client understands, so no driver is installed. */
23
+ export declare const mountSteps: (url: string) => Mounted["how"];
24
+ /**
25
+ * Serves `source` read-only over WebDAV on 127.0.0.1, behind a random secret in the path. Only this machine can
26
+ * reach it, and only a client that was given the URL.
27
+ */
28
+ export declare const serveMount: (source: MountSource, options?: MountOptions) => Promise<Mounted>;
@@ -0,0 +1,31 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { listen } from "../http/listen.js";
3
+ import { webdavHandler } from "./webdav.js";
4
+ const HOST = "127.0.0.1";
5
+ /** A PROPFIND body is a few hundred bytes; a larger body, such as a file a client tries to upload, is refused unread. */
6
+ const MOST_BODY = 64 * 1024;
7
+ /** The ways to mount a URL the system's own WebDAV client understands, so no driver is installed. */
8
+ export const mountSteps = (url) => ({
9
+ linux: `gio mount ${url.replace(/^http:/u, "dav:")}`,
10
+ macos: `Finder > Go > Connect to Server (Cmd+K), then ${url}`,
11
+ windows: `net use * ${url}`,
12
+ });
13
+ /**
14
+ * Serves `source` read-only over WebDAV on 127.0.0.1, behind a random secret in the path. Only this machine can
15
+ * reach it, and only a client that was given the URL.
16
+ */
17
+ export const serveMount = async (source, options = {}) => {
18
+ const secret = options.secret ?? randomBytes(24).toString("base64url");
19
+ let port = options.port ?? 0;
20
+ const handle = webdavHandler(source, {
21
+ secret,
22
+ hosts: () => [`${HOST}:${port}`, `localhost:${port}`],
23
+ ...(options.cacheMs === undefined ? {} : { cacheMs: options.cacheMs }),
24
+ ...(options.now ? { now: options.now } : {}),
25
+ ...(options.onError ? { onError: options.onError } : {}),
26
+ });
27
+ const listening = await listen(handle, { host: HOST, port, maxBody: MOST_BODY });
28
+ port = Number(listening.url.port);
29
+ const url = `http://${HOST}:${port}/${secret}/`;
30
+ return { url, how: mountSteps(url), close: listening.close };
31
+ };
@@ -0,0 +1,31 @@
1
+ /** One file or folder as a mount shows it. */
2
+ export interface MountEntry {
3
+ name: string;
4
+ folder: boolean;
5
+ size?: number;
6
+ /** ISO 8601. */
7
+ modifiedAt?: string;
8
+ createdAt?: string;
9
+ mime?: string;
10
+ /** Changes when the content does, such as an md5; it becomes the ETag. */
11
+ version?: string;
12
+ }
13
+ /** Inclusive, as HTTP's `Range: bytes=start-end`. */
14
+ export interface ByteRange {
15
+ start: number;
16
+ end: number;
17
+ }
18
+ export interface MountRead {
19
+ body: ReadableStream<Uint8Array>;
20
+ /** True when `body` holds only the range asked for; false when the service sent the whole file. */
21
+ ranged: boolean;
22
+ }
23
+ /**
24
+ * What a service hands a mount. It has no method that changes anything, so a mount cannot write, whatever a client
25
+ * asks. Paths are `/` or `/a/b`, under the folder the owner mounted; a missing item throws `not_found`.
26
+ */
27
+ export interface MountSource {
28
+ stat(path: string): Promise<MountEntry>;
29
+ list(path: string): Promise<MountEntry[]>;
30
+ read(path: string, entry: MountEntry, range?: ByteRange): Promise<MountRead>;
31
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,18 @@
1
+ import type { MountSource } from "./source.js";
2
+ export interface WebdavOptions {
3
+ /** The first path segment every request must carry; the URL the owner mounts holds it. */
4
+ secret: string;
5
+ /** The `Host` values a request may carry, such as `127.0.0.1:8080`; any other is a page on another site. */
6
+ hosts: () => readonly string[];
7
+ /** How long a listing or a stat answers from memory. */
8
+ cacheMs?: number;
9
+ now?: () => number;
10
+ /** A failure other than `not_found`, for the command to report; never the request, whose path holds the secret. */
11
+ onError?: (error: unknown) => void;
12
+ }
13
+ /**
14
+ * A read-only WebDAV server over a `MountSource`, as a web-standard handler. Every request must name an allowed
15
+ * `Host` (a page on another site that rebinds its name to 127.0.0.1 cannot), carry no foreign `Origin`, and start
16
+ * with the secret; it may only read. Answers carry no CORS header, so no page can read them.
17
+ */
18
+ export declare const webdavHandler: (source: MountSource, options: WebdavOptions) => (request: Request) => Promise<Response>;
@@ -0,0 +1,241 @@
1
+ import { timingSafeEqual } from "node:crypto";
2
+ import { CliError, isCliError } from "@wirecat/cli-base";
3
+ /** WebDAV class 1 only: without class 2 (LOCK) a client has nothing to lock a file it would write with. */
4
+ const ALLOW = "OPTIONS, PROPFIND, GET, HEAD";
5
+ const MOST_CACHED = 2000;
6
+ class BadPath extends Error {
7
+ }
8
+ const sameSecret = (given, secret) => {
9
+ const a = Buffer.from(given);
10
+ const b = Buffer.from(secret);
11
+ return a.length === b.length && timingSafeEqual(a, b);
12
+ };
13
+ /**
14
+ * The path under the mount, decoded one segment at a time. A segment that decodes to a separator or a dot step is
15
+ * refused: `a%2F..%2F..` survives URL parsing and would climb out of the mounted folder once the service joins it.
16
+ */
17
+ const innerPath = (segments) => {
18
+ const names = segments
19
+ .filter((segment) => segment !== "")
20
+ .map((segment) => {
21
+ let name;
22
+ try {
23
+ name = decodeURIComponent(segment);
24
+ }
25
+ catch {
26
+ throw new BadPath();
27
+ }
28
+ if (name === "." || name === ".." || /[/\\\0]/u.test(name))
29
+ throw new BadPath();
30
+ return name;
31
+ });
32
+ return `/${names.join("/")}`;
33
+ };
34
+ const parentOf = (path) => path.slice(0, path.lastIndexOf("/")) || "/";
35
+ const baseOf = (path) => path.slice(path.lastIndexOf("/") + 1);
36
+ const childOf = (path, name) => (path === "/" ? `/${name}` : `${path}/${name}`);
37
+ const xml = (text) => text.replace(/[<>&"']/gu, (c) => ({ "<": "&lt;", ">": "&gt;", "&": "&amp;", '"': "&quot;", "'": "&apos;" })[c] ?? c);
38
+ const etagOf = (entry) => {
39
+ const tag = entry.version ?? (entry.modifiedAt ? `${entry.modifiedAt}-${entry.size ?? 0}` : undefined);
40
+ return tag === undefined ? undefined : `"${tag.replace(/["\\]/gu, "")}"`;
41
+ };
42
+ const httpDate = (iso) => {
43
+ const ms = iso === undefined ? Number.NaN : Date.parse(iso);
44
+ return Number.isNaN(ms) ? undefined : new Date(ms).toUTCString();
45
+ };
46
+ const hrefOf = (secret, path, folder) => {
47
+ const encoded = path === "/" ? "" : path.split("/").map(encodeURIComponent).join("/");
48
+ return `/${secret}${encoded}${folder ? "/" : ""}`;
49
+ };
50
+ const responseXml = (href, entry) => {
51
+ const props = [
52
+ `<D:displayname>${xml(entry.name)}</D:displayname>`,
53
+ entry.folder ? "<D:resourcetype><D:collection/></D:resourcetype>" : "<D:resourcetype/>",
54
+ ...(entry.folder || entry.size === undefined ? [] : [`<D:getcontentlength>${entry.size}</D:getcontentlength>`]),
55
+ ...(entry.folder ? [] : [`<D:getcontenttype>${xml(entry.mime ?? "application/octet-stream")}</D:getcontenttype>`]),
56
+ ...[httpDate(entry.modifiedAt)].filter(Boolean).map((date) => `<D:getlastmodified>${date}</D:getlastmodified>`),
57
+ ...(entry.createdAt ? [`<D:creationdate>${xml(entry.createdAt)}</D:creationdate>`] : []),
58
+ ...[etagOf(entry)].filter(Boolean).map((tag) => `<D:getetag>${xml(tag ?? "")}</D:getetag>`),
59
+ // Windows reads this flag and opens the file read-only, so an editor says so before a save fails.
60
+ `<Z:Win32FileAttributes>${entry.folder ? "00000011" : "00000001"}</Z:Win32FileAttributes>`,
61
+ ];
62
+ return (`<D:response><D:href>${xml(href)}</D:href><D:propstat><D:prop>${props.join("")}</D:prop>` +
63
+ "<D:status>HTTP/1.1 200 OK</D:status></D:propstat></D:response>");
64
+ };
65
+ const multistatus = (responses) => new Response(`<?xml version="1.0" encoding="utf-8"?>\n<D:multistatus xmlns:D="DAV:" xmlns:Z="urn:schemas-microsoft-com:">${responses.join("")}</D:multistatus>`, {
66
+ status: 207,
67
+ headers: { "content-type": "application/xml; charset=utf-8" },
68
+ });
69
+ const plain = (status, text, headers = {}) => new Response(text, {
70
+ status,
71
+ headers: { "content-type": "text/plain; charset=utf-8", "x-content-type-options": "nosniff", ...headers },
72
+ });
73
+ /** One `bytes=` range; anything else (several ranges, another unit) is ignored and the whole file is sent. */
74
+ const rangeOf = (header, size) => {
75
+ if (header === null || size === undefined)
76
+ return undefined;
77
+ const match = /^bytes=(\d*)-(\d*)$/u.exec(header.trim());
78
+ if (!match)
79
+ return undefined;
80
+ const [, from = "", to = ""] = match;
81
+ if (from === "" && to === "")
82
+ return undefined;
83
+ if (from === "") {
84
+ const suffix = Number(to);
85
+ if (suffix === 0)
86
+ return "unsatisfiable";
87
+ return { start: Math.max(0, size - suffix), end: size - 1 };
88
+ }
89
+ const start = Number(from);
90
+ if (start >= size)
91
+ return "unsatisfiable";
92
+ const end = to === "" ? size - 1 : Math.min(Number(to), size - 1);
93
+ return end < start ? undefined : { start, end };
94
+ };
95
+ /**
96
+ * Listings and stats answer from memory for `ms`, and a stat is answered from its parent's listing when that is
97
+ * fresh: a file manager asks for `.DS_Store`, `desktop.ini` and thumbnails in every folder, and each would otherwise be
98
+ * a request that counts against the service's rate limit.
99
+ */
100
+ const cachedSource = (source, ms, now) => {
101
+ const lists = new Map();
102
+ const stats = new Map();
103
+ const fresh = (map, key) => {
104
+ const hit = map.get(key);
105
+ if (hit && now() - hit.at < ms)
106
+ return hit.value;
107
+ map.delete(key);
108
+ return undefined;
109
+ };
110
+ const keep = (map, key, value) => {
111
+ if (map.size >= MOST_CACHED)
112
+ map.delete(map.keys().next().value);
113
+ map.set(key, { at: now(), value });
114
+ value.catch(() => map.delete(key));
115
+ return value;
116
+ };
117
+ const list = (path) => fresh(lists, path) ??
118
+ keep(lists, path, source.list(path).then((entries) => {
119
+ for (const entry of entries)
120
+ keep(stats, childOf(path, entry.name), Promise.resolve(entry));
121
+ return entries;
122
+ }));
123
+ const stat = async (path) => {
124
+ const hit = fresh(stats, path);
125
+ if (hit)
126
+ return hit;
127
+ const siblings = path === "/" ? undefined : fresh(lists, parentOf(path));
128
+ if (siblings) {
129
+ const found = (await siblings).find((entry) => entry.name === baseOf(path));
130
+ if (found)
131
+ return found;
132
+ throw notFound();
133
+ }
134
+ return keep(stats, path, source.stat(path));
135
+ };
136
+ return { list, stat };
137
+ };
138
+ const notFound = () => new CliError("not_found", "no such item");
139
+ const isNotFound = (error) => isCliError(error) && error.code === "not_found";
140
+ const failure = (error, onError) => {
141
+ if (isNotFound(error))
142
+ return plain(404, "not found");
143
+ onError?.(error);
144
+ if (isCliError(error) && error.code === "rate_limited") {
145
+ const wait = Number(error.details?.retry_after_ms ?? 60_000);
146
+ return plain(503, "the service asked to slow down", { "retry-after": String(Math.ceil(wait / 1000)) });
147
+ }
148
+ return plain(502, "the service did not answer");
149
+ };
150
+ /**
151
+ * A read-only WebDAV server over a `MountSource`, as a web-standard handler. Every request must name an allowed
152
+ * `Host` (a page on another site that rebinds its name to 127.0.0.1 cannot), carry no foreign `Origin`, and start
153
+ * with the secret; it may only read. Answers carry no CORS header, so no page can read them.
154
+ */
155
+ export const webdavHandler = (source, options) => {
156
+ const { secret, onError } = options;
157
+ const cache = cachedSource(source, options.cacheMs ?? 10_000, options.now ?? Date.now);
158
+ const propfind = async (request, path) => {
159
+ const depth = request.headers.get("depth")?.trim().toLowerCase() ?? "1";
160
+ if (depth !== "0" && depth !== "1")
161
+ return new Response('<?xml version="1.0" encoding="utf-8"?>\n<D:error xmlns:D="DAV:"><D:propfind-finite-depth/></D:error>', { status: 403, headers: { "content-type": "application/xml; charset=utf-8" } });
162
+ const entry = await cache.stat(path);
163
+ const own = responseXml(hrefOf(secret, path, entry.folder), entry);
164
+ if (depth === "0" || !entry.folder)
165
+ return multistatus([own]);
166
+ const children = await cache.list(path);
167
+ return multistatus([
168
+ own,
169
+ ...children.map((child) => responseXml(hrefOf(secret, childOf(path, child.name), child.folder), child)),
170
+ ]);
171
+ };
172
+ const get = async (request, path) => {
173
+ const entry = await cache.stat(path);
174
+ if (entry.folder) {
175
+ const names = (await cache.list(path)).map((child) => `${child.name}${child.folder ? "/" : ""}`);
176
+ return plain(200, request.method === "HEAD" ? "" : `${names.join("\n")}\n`);
177
+ }
178
+ const etag = etagOf(entry);
179
+ const lastModified = httpDate(entry.modifiedAt);
180
+ const headers = {
181
+ "content-type": entry.mime ?? "application/octet-stream",
182
+ // A file is anyone's content: an HTML or SVG file opened from the mount would run on its origin, read the secret
183
+ // from its own address and fetch the rest of the folder.
184
+ "content-security-policy": "sandbox",
185
+ "x-content-type-options": "nosniff",
186
+ "accept-ranges": "bytes",
187
+ ...(etag ? { etag } : {}),
188
+ ...(lastModified ? { "last-modified": lastModified } : {}),
189
+ };
190
+ const ifRange = request.headers.get("if-range");
191
+ const asked = ifRange !== null && ifRange !== etag && ifRange !== lastModified ? null : request.headers.get("range");
192
+ const range = rangeOf(asked, entry.size);
193
+ if (range === "unsatisfiable")
194
+ return new Response(null, { status: 416, headers: { ...headers, "content-range": `bytes */${entry.size}` } });
195
+ const whole = entry.size === undefined ? {} : { "content-length": String(entry.size) };
196
+ if (request.method === "HEAD")
197
+ return new Response(null, { status: 200, headers: { ...headers, ...whole } });
198
+ const read = await source.read(path, entry, range);
199
+ if (!range || !read.ranged)
200
+ return new Response(read.body, { status: 200, headers: { ...headers, ...whole } });
201
+ return new Response(read.body, {
202
+ status: 206,
203
+ headers: {
204
+ ...headers,
205
+ "content-length": String(range.end - range.start + 1),
206
+ "content-range": `bytes ${range.start}-${range.end}/${entry.size}`,
207
+ },
208
+ });
209
+ };
210
+ return async (request) => {
211
+ if (!options.hosts().includes(request.headers.get("host") ?? ""))
212
+ return plain(403, "this host is not served");
213
+ const origin = request.headers.get("origin");
214
+ if (origin !== null && !options.hosts().some((host) => origin === `http://${host}`))
215
+ return plain(403, "this origin is not served");
216
+ const segments = new URL(request.url).pathname.split("/").slice(1);
217
+ if (request.method === "OPTIONS")
218
+ return new Response(null, { status: 200, headers: { dav: "1", allow: ALLOW, "ms-author-via": "DAV" } });
219
+ // Windows asks about the server's top before the folder it mounts; an empty folder answers it and shows nothing.
220
+ if (request.method === "PROPFIND" && segments.every((segment) => segment === ""))
221
+ return multistatus([responseXml("/", { name: "", folder: true })]);
222
+ if (!sameSecret(segments[0] ?? "", secret))
223
+ return plain(404, "not found");
224
+ if (!["PROPFIND", "GET", "HEAD"].includes(request.method))
225
+ // A 405 to MKCOL means "it already exists" (RFC 4918, 9.3.1); 403 says creating is refused.
226
+ return plain(request.method === "MKCOL" ? 403 : 405, "this mount is read-only", { allow: ALLOW });
227
+ let path;
228
+ try {
229
+ path = innerPath(segments.slice(1));
230
+ }
231
+ catch {
232
+ return plain(400, "this path is refused");
233
+ }
234
+ try {
235
+ return await (request.method === "PROPFIND" ? propfind(request, path) : get(request, path));
236
+ }
237
+ catch (error) {
238
+ return failure(error, onError);
239
+ }
240
+ };
241
+ };
@@ -99,4 +99,11 @@ export const WIRECAT_TOOLS = [
99
99
  package: "@wirecat/wordpress-cli",
100
100
  does: "WordPress posts and pages, searchable with your other WireCat data",
101
101
  },
102
+ {
103
+ command: "linear",
104
+ appName: "linear-cli",
105
+ envPrefix: "WCLINEAR",
106
+ package: "@wirecat/linear-cli",
107
+ does: "Linear issues and projects, searchable with your other WireCat data",
108
+ },
102
109
  ];
@@ -6,6 +6,8 @@ export interface Mirror {
6
6
  id: string;
7
7
  path: string;
8
8
  folder: string;
9
+ /** Globs of paths the mirror leaves alone on both sides, as `excludedBy` reads them. */
10
+ exclude?: string[];
9
11
  }
10
12
  export declare const mirrorId: (root: string, folder: string) => string;
11
13
  /**
@@ -114,7 +114,7 @@ export declare const scanLocal: (root: string, kindOf: (path: string) => string
114
114
  size: number;
115
115
  mtimeMs: number;
116
116
  hash: string;
117
- } | undefined) => Promise<{
117
+ } | undefined, skip?: (path: string) => boolean) => Promise<{
118
118
  files: LocalDocument[];
119
119
  unsupported: number;
120
120
  links: string[];
@@ -133,7 +133,7 @@ export const replaceLocal = async (absolute, hash, content, { tag = randomUUID()
133
133
  * links' paths are returned in `links`, so a mirror does not take the files behind one as deleted. A file whose size
134
134
  * and mtime match what `known` returns keeps that hash instead of being read again.
135
135
  */
136
- export const scanLocal = async (root, kindOf, maxFiles = 10_000, known) => {
136
+ export const scanLocal = async (root, kindOf, maxFiles = 10_000, known, skip) => {
137
137
  const files = [];
138
138
  const links = [];
139
139
  let unsupported = 0;
@@ -143,6 +143,8 @@ export const scanLocal = async (root, kindOf, maxFiles = 10_000, known) => {
143
143
  if (SKIPPED.test(entry.name))
144
144
  continue;
145
145
  const path = relative ? posix.join(relative, entry.name) : entry.name;
146
+ if (skip?.(path))
147
+ continue;
146
148
  if (entry.isSymbolicLink()) {
147
149
  links.push(path);
148
150
  continue;
@@ -0,0 +1,8 @@
1
+ /** An exclusion as the mirror keeps it: trimmed, without a trailing `/`; refused when it names nothing or leaves. */
2
+ export declare const exclusionPattern: (input: string) => string;
3
+ /**
4
+ * Whether a mirror's exclusions cover `path`, or a folder on the way to it. A pattern without `/` is a name at any
5
+ * depth (`node_modules`, `*.iso`); one with `/` is a path from the mirror's root (`Photos/2019`, `/Camera`). `*` and `?`
6
+ * stay within a name; `**` crosses folders.
7
+ */
8
+ export declare const excludedBy: (patterns?: readonly string[]) => (path: string) => boolean;
@@ -0,0 +1,39 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ /** An exclusion as the mirror keeps it: trimmed, without a trailing `/`; refused when it names nothing or leaves. */
3
+ export const exclusionPattern = (input) => {
4
+ const pattern = input.trim().replace(/\/+$/u, "");
5
+ const parts = pattern.replace(/^\//u, "").split("/");
6
+ if (!pattern || pattern === "/" || parts.some((part) => !part || part === "." || part === ".."))
7
+ throw new CliError("validation_error", `${JSON.stringify(input)} is not a path pattern like Photos or /Work/*.iso`, {
8
+ reason: "mirror.bad-exclusion",
9
+ });
10
+ return pattern;
11
+ };
12
+ const globSource = (glob) => glob
13
+ .split(/(\*\*\/|\*\*|\*|\?)/u)
14
+ .map((part) => part === "**/"
15
+ ? "(?:.*/)?"
16
+ : part === "**"
17
+ ? ".*"
18
+ : part === "*"
19
+ ? "[^/]*"
20
+ : part === "?"
21
+ ? "[^/]"
22
+ : part.replace(/[.+^${}()|[\]\\]/gu, "\\$&"))
23
+ .join("");
24
+ /**
25
+ * Whether a mirror's exclusions cover `path`, or a folder on the way to it. A pattern without `/` is a name at any
26
+ * depth (`node_modules`, `*.iso`); one with `/` is a path from the mirror's root (`Photos/2019`, `/Camera`). `*` and `?`
27
+ * stay within a name; `**` crosses folders.
28
+ */
29
+ export const excludedBy = (patterns = []) => {
30
+ const test = (glob) => new RegExp(`^${globSource(glob)}$`, "u");
31
+ const names = patterns.filter((pattern) => !pattern.includes("/")).map(test);
32
+ const paths = patterns.filter((pattern) => pattern.includes("/")).map((pattern) => test(pattern.replace(/^\//u, "")));
33
+ return (path) => {
34
+ if (!names.length && !paths.length)
35
+ return false;
36
+ const parts = path.split("/");
37
+ return parts.some((name, index) => names.some((glob) => glob.test(name)) || paths.some((way) => way.test(parts.slice(0, index + 1).join("/"))));
38
+ };
39
+ };
@@ -21,8 +21,14 @@ export interface FileMirrorOptions {
21
21
  /** Settles conflicts; without it they are reported and left. */
22
22
  keep?: Keep;
23
23
  dryRun?: boolean;
24
- /** Lets a run delete this many files although the deletion guard would stop it. */
24
+ /** Lets a run delete this many files although the guard would stop it. */
25
25
  allowDeletions?: number;
26
+ /** Lets a run replace this many existing files, on either side, although the guard would stop it. */
27
+ allowReplacements?: number;
28
+ /** Globs of paths the mirror leaves alone on both sides, as `excludedBy` reads them. */
29
+ exclude?: string[];
30
+ /** The mirror's id, put for `<id>` in the hints. */
31
+ id?: string;
26
32
  /**
27
33
  * The owner confirmed that a root reported as replaced is the right folder now: its identity is recorded again and
28
34
  * the run is a first sync (identical files adopted, different ones conflicts), deleting nothing.
@@ -30,7 +36,7 @@ export interface FileMirrorOptions {
30
36
  repin?: boolean;
31
37
  /** How the app names the remote side; it ends a conflict copy's name. */
32
38
  remote: string;
33
- /** How the app's commands are named in the deletion guard's and the repin message; the defaults are flags. */
39
+ /** How the app's commands are named in the guard's, the free space and the repin message. */
34
40
  hints?: Partial<MirrorHints>;
35
41
  /** Runs one write behind the app's permission checks; `side` says which side it changes. */
36
42
  guard<T>(attempt: {
@@ -44,16 +50,29 @@ export interface FileMirrorOptions {
44
50
  /** Throws once the sync lock is lost; checked before every write. */
45
51
  assertHeld(): void | Promise<void>;
46
52
  signal?: AbortSignal;
53
+ /** Local files the mirror takes at most; more fail the run. */
47
54
  maxFiles?: number;
55
+ /** Bytes free for this process on the file system holding `path`, and its device. */
56
+ space?(path: string): Promise<{
57
+ free: number;
58
+ dev: number;
59
+ }>;
48
60
  now?(): number;
49
61
  }
62
+ /** The app's commands, as the engine's messages name them; `<id>` is the mirror's id and `<count>` a number. */
50
63
  export interface MirrorHints {
51
- /** How to preview a run: `--dry-run`. */
64
+ /** How to preview a run: `ydisk work mirrors preview <id>`. */
52
65
  preview: string;
53
- /** How to record a replaced root again: `--repin`. */
66
+ /** How to record a replaced root again: `ydisk work mirrors sync <id> --repin`. */
54
67
  repin: string;
55
- /** How to allow a run's deletions: `explicitly`, as in "allow them explicitly". */
68
+ /** The sync an approval is added to: `ydisk work mirrors sync <id>`. */
69
+ sync: string;
70
+ /** How a sync allows deletions: `--allow-deletions <count>`. */
56
71
  allowDeletions: string;
72
+ /** How a sync allows replacements: `--allow-replacements <count>`. */
73
+ allowReplacements: string;
74
+ /** How to exclude a folder: `ydisk work mirrors exclude <id> <glob>`. */
75
+ exclude: string;
57
76
  }
58
77
  export interface FileStep {
59
78
  kind: FileStepKind;
@@ -75,10 +94,12 @@ export interface FileMirrorResult {
75
94
  adopted: string[];
76
95
  unchanged: number;
77
96
  conflicts: PushConflict[];
97
+ /** A whole-run refusal (the guard, too little space) is one error at path `.` with its `reason`. */
78
98
  errors: {
79
99
  path: string;
80
100
  code: string;
81
101
  message: string;
102
+ reason?: string;
82
103
  }[];
83
104
  /**
84
105
  * Files of the last sync missing from a side that cannot prove a deletion: its listing was incomplete, or its root
@@ -91,10 +112,25 @@ export interface FileMirrorResult {
91
112
  }[];
92
113
  /** Every step but the unchanged files, on a dry run. */
93
114
  plan?: FileStep[];
94
- /** On a dry run, the deletions that would stop the real run without `allowDeletions`. */
115
+ /** The deletions that stop the run without `allowDeletions`; a dry run reports them without stopping. */
95
116
  tooManyDeletions?: number;
117
+ /** The replacements of existing files that stop the run without `allowReplacements`. */
118
+ tooManyReplacements?: number;
119
+ /** The run needs more free space than the file system at `path` has. */
120
+ noSpace?: {
121
+ path: string;
122
+ needed: number;
123
+ free: number;
124
+ };
96
125
  stopped?: true;
97
126
  }
127
+ /**
128
+ * A run that would delete more than `MAX_DELETIONS` files, or replace more than `MAX_REPLACEMENTS` existing files on
129
+ * either side, stops before writing until the owner allows the count. Replacements get the higher bar: every content
130
+ * one replaces is kept in the version store first, and bulk edits (a find-and-replace, a branch switch) are common.
131
+ */
132
+ export declare const MAX_DELETIONS = 10;
133
+ export declare const MAX_REPLACEMENTS = 50;
98
134
  /**
99
135
  * Syncs a local folder and a remote folder of plain files both ways, whole files at a time. Each path is compared
100
136
  * three ways (local now, remote now, last sync): a change on one side is copied to the other, the same content on
@@ -120,7 +156,7 @@ export declare const fileMirrorStatus: (mirrors: Mirror[], stateOf: (mirror: Mir
120
156
  * at the first poll), none when it did not, and every mirror at each poll when the target has no revision.
121
157
  */
122
158
  export declare const fileRemoteChanges: (target: FileTarget) => (signal: AbortSignal) => Promise<string[] | "all">;
123
- export interface FileMirrorSyncOptions extends Pick<FileMirrorOptions, "target" | "principal" | "keep" | "dryRun" | "allowDeletions" | "repin" | "hints" | "guard" | "operationId" | "errorOf" | "signal"> {
159
+ export interface FileMirrorSyncOptions extends Pick<FileMirrorOptions, "target" | "principal" | "keep" | "dryRun" | "allowDeletions" | "allowReplacements" | "repin" | "hints" | "guard" | "operationId" | "errorOf" | "signal" | "space"> {
124
160
  mirrors: Mirror[];
125
161
  stateOf(mirror: Mirror): FileMirrorStatePort;
126
162
  versionsOf(mirror: Mirror): FileVersions;
@@ -1,18 +1,30 @@
1
1
  import { createHash } from "node:crypto";
2
- import { mkdir, rm, stat, unlink } from "node:fs/promises";
2
+ import { mkdir, rm, stat, statfs, unlink } from "node:fs/promises";
3
3
  import { dirname, join, posix } from "node:path";
4
4
  import { CliError, isCliError } from "@wirecat/cli-base";
5
5
  import * as v from "valibot";
6
6
  import { eachMirror, heldCheck, jsonState } from "../documents/mirrors.js";
7
7
  import { assertNoLink, hashFile, localTemp, placeNew, replaceLocal, safePath, scanLocal, skippedName, } from "../documents/push.js";
8
- const HINTS = { preview: "--dry-run", repin: "--repin", allowDeletions: "explicitly" };
8
+ import { excludedBy } from "./exclusions.js";
9
+ const HINTS = {
10
+ preview: "--dry-run",
11
+ repin: "--repin",
12
+ sync: "sync",
13
+ allowDeletions: "--allow-deletions <count>",
14
+ allowReplacements: "--allow-replacements <count>",
15
+ exclude: "--exclude <glob>",
16
+ };
9
17
  /**
10
- * A run that would delete more than `ALWAYS_DELETED` files and more than `MAX_DELETIONS` files or `MAX_DELETED_SHARE`
11
- * of the mirror stops before writing.
18
+ * A run that would delete more than `MAX_DELETIONS` files, or replace more than `MAX_REPLACEMENTS` existing files on
19
+ * either side, stops before writing until the owner allows the count. Replacements get the higher bar: every content
20
+ * one replaces is kept in the version store first, and bulk edits (a find-and-replace, a branch switch) are common.
12
21
  */
13
- const ALWAYS_DELETED = 2;
14
- const MAX_DELETIONS = 50;
15
- const MAX_DELETED_SHARE = 0.25;
22
+ export const MAX_DELETIONS = 10;
23
+ export const MAX_REPLACEMENTS = 50;
24
+ /** What a run leaves free on a drive it writes to: a tenth of what it writes, from 100 MB up to 1 GB. */
25
+ const spareFor = (needed) => Math.min(1024 ** 3, Math.max(100 * 1024 ** 2, needed / 10));
26
+ const MAX_FILES = 100_000;
27
+ const CHECKS = 8;
16
28
  const TRASH = ".wirecat-trash";
17
29
  const SAVE_EVERY_MS = 1_000;
18
30
  /** A temporary file's tag from any operation id, safe in a file name. */
@@ -119,12 +131,12 @@ const renameLocal = async (root, from, to, hash) => {
119
131
  await unlink(source);
120
132
  return true;
121
133
  };
122
- /** Every local file, hashed only when its size or mtime moved since the last sync. */
123
- const scan = async (root, entries, maxFiles) => {
134
+ /** Every local file but excluded ones, hashed only when its size or mtime moved since the last sync. */
135
+ const scan = async (root, entries, excluded, maxFiles = MAX_FILES) => {
124
136
  const { files, links } = await scanLocal(root, () => "file", maxFiles, (path) => {
125
137
  const entry = entries[path];
126
138
  return entry && { size: entry.localSize, mtimeMs: entry.localMtimeMs, hash: entry.sha256 };
127
- });
139
+ }, excluded);
128
140
  return { files: files, links };
129
141
  };
130
142
  /** Remote files the mirror covers: hidden files and editor leftovers are skipped, as they are locally. */
@@ -146,6 +158,20 @@ const whole = async (absolute, hashes) => {
146
158
  };
147
159
  /** True when `path` is `link` or lies under it. */
148
160
  const under = (path, link) => path === link || path.startsWith(`${link}/`);
161
+ /** Free bytes and the device of the file system holding `path`, or of its nearest folder that exists. */
162
+ const freeSpace = async (path) => {
163
+ for (let at = path;; at = dirname(at)) {
164
+ try {
165
+ const [{ bavail, bsize }, { dev }] = await Promise.all([statfs(at), stat(at)]);
166
+ return { free: bavail * bsize, dev };
167
+ }
168
+ catch (error) {
169
+ if (error.code !== "ENOENT" || dirname(at) === at)
170
+ throw error;
171
+ }
172
+ }
173
+ };
174
+ const gigabytes = (bytes) => `${(bytes / 1024 ** 3).toFixed(1)} GB`;
149
175
  /**
150
176
  * Syncs a local folder and a remote folder of plain files both ways, whole files at a time. Each path is compared
151
177
  * three ways (local now, remote now, last sync): a change on one side is copied to the other, the same content on
@@ -156,6 +182,8 @@ const under = (path, link) => path === link || path.startsWith(`${link}/`);
156
182
  export const syncFileMirror = async (options) => {
157
183
  const { root, folder, target, principal, keep, signal, versions } = options;
158
184
  const hints = { ...HINTS, ...options.hints };
185
+ const fill = (hint, count) => hint.replaceAll("<id>", options.id ?? "<id>").replaceAll("<count>", count === undefined ? "<count>" : `${count}`);
186
+ const excluded = excludedBy(options.exclude);
159
187
  const now = options.now ?? Date.now;
160
188
  if (signal?.aborted)
161
189
  throw new CliError("cancelled", "sync was cancelled");
@@ -166,7 +194,7 @@ export const syncFileMirror = async (options) => {
166
194
  const state = options.state.read();
167
195
  if (state.principal !== principal || state.root !== root || state.target !== folder)
168
196
  throw new CliError("configuration_error", "mirror state belongs to another account or mirror");
169
- const listed = await target.list(folder, signal);
197
+ const listed = await target.list(folder, signal, { excluded });
170
198
  const localRoot = await stat(root).catch(() => undefined);
171
199
  const remoteReplaced = listed !== undefined && state.rootId !== undefined && listed.rootId !== state.rootId;
172
200
  const localReplaced = localRoot?.isDirectory() === true &&
@@ -174,9 +202,13 @@ export const syncFileMirror = async (options) => {
174
202
  (state.localRoot.dev !== localRoot.dev || state.localRoot.ino !== localRoot.ino);
175
203
  // Only a mirror whose root really was replaced is re-pinned; `repin` on a sync of every mirror leaves the others be.
176
204
  const repin = options.repin === true && (remoteReplaced || localReplaced);
205
+ // An excluded path is absent by filter, never deleted: the last sync's entries under it are left out.
206
+ const synced = Object.fromEntries(Object.entries(state.entries).filter(([path]) => !excluded(path)));
177
207
  // A re-pinned mirror starts over: the last sync's entries describe the folder it replaced.
178
- const entries = repin ? {} : state.entries;
179
- const scanned = localRoot?.isDirectory() ? await scan(root, entries, options.maxFiles) : { files: [], links: [] };
208
+ const entries = repin ? {} : synced;
209
+ const scanned = localRoot?.isDirectory()
210
+ ? await scan(root, entries, excluded, options.maxFiles)
211
+ : { files: [], links: [] };
180
212
  const local = new Map(scanned.files.map((file) => [file.path, file]));
181
213
  const problem = (side, code, reason, repinnable = false) => ({ side, code, reason, repinnable });
182
214
  // A folder that is gone, replaced, or empty where the state had files (an unmounted drive) is not this mirror.
@@ -188,22 +220,23 @@ export const syncFileMirror = async (options) => {
188
220
  ? problem("local", "not_found", "the local folder is gone")
189
221
  : localReplaced && !repin
190
222
  ? problem("local", "confirmation_required", "the local folder was replaced by another one", true)
191
- : Object.keys(state.entries).length > 0 && !local.size
223
+ : Object.keys(synced).length > 0 && !local.size
192
224
  ? problem("local", "validation_error", "the local folder is empty; it may be an unmounted drive. Mount it, or if the files were really " +
193
225
  "deleted, add a file to the folder or remove the mirror's state to start over")
194
226
  : undefined;
195
227
  const refused = rootProblem ? [] : (listed?.files ?? []).filter((file) => !safePath(file.path));
196
228
  const refusedIds = new Set(refused.map((file) => file.id));
197
- const remote = new Map(rootProblem
198
- ? []
199
- : mirrored((listed?.files ?? []).filter((file) => safePath(file.path))).map((file) => [file.path, file]));
229
+ const visible = rootProblem ? [] : mirrored((listed?.files ?? []).filter((file) => safePath(file.path)));
230
+ const remote = new Map(visible.filter((file) => !excluded(file.path)).map((file) => [file.path, file]));
231
+ // Where a synced file went when it moved into an excluded folder on the remote.
232
+ const excludedIds = new Set(visible.filter((file) => excluded(file.path)).map((file) => file.id));
200
233
  const sure = {
201
234
  local: rootProblem?.side !== "local",
202
235
  remote: rootProblem?.side !== "remote" && listed?.complete === true,
203
236
  };
204
237
  const base = { ...entries };
205
238
  const steps = [];
206
- const byId = new Map([...remote.values()].map((file) => [file.id, file]));
239
+ const byId = new Map(visible.map((file) => [file.id, file]));
207
240
  for (const [path, entry] of Object.entries(entries)) {
208
241
  const moved = remote.has(path) ? undefined : byId.get(entry.id);
209
242
  const file = local.get(path);
@@ -231,12 +264,12 @@ export const syncFileMirror = async (options) => {
231
264
  };
232
265
  if (rootProblem) {
233
266
  const { side, code, reason, repinnable } = rootProblem;
234
- result.unknown = Object.keys(state.entries).map((path) => ({ path, side, reason }));
267
+ result.unknown = Object.keys(synced).map((path) => ({ path, side, reason }));
235
268
  result.errors.push({
236
269
  path: ".",
237
270
  code,
238
271
  message: repinnable
239
- ? `${reason}; if it is the right folder now, sync again with ${hints.repin} to record it ` +
272
+ ? `${reason}; if it is the right folder now, sync again with ${fill(hints.repin)} to record it ` +
240
273
  "(that run deletes nothing)"
241
274
  : reason,
242
275
  });
@@ -250,6 +283,9 @@ export const syncFileMirror = async (options) => {
250
283
  });
251
284
  const cutOff = new Set();
252
285
  for (const path of paths) {
286
+ // A synced file moved into an excluded folder is renamed there above, and then left alone.
287
+ if (excluded(path))
288
+ continue;
253
289
  const entry = base[path];
254
290
  if (entry && !local.has(path) && scanned.links.some((link) => under(path, link))) {
255
291
  steps.push({
@@ -264,6 +300,15 @@ export const syncFileMirror = async (options) => {
264
300
  steps.push({ kind: "unknown", path, reason: "remote", why: `moved on the ${options.remote} to a refused path` });
265
301
  continue;
266
302
  }
303
+ if (entry && !remote.has(path) && excludedIds.has(entry.id)) {
304
+ steps.push({
305
+ kind: "unknown",
306
+ path,
307
+ reason: "remote",
308
+ why: `moved on the ${options.remote} into an excluded folder`,
309
+ });
310
+ continue;
311
+ }
267
312
  const file = remote.get(path);
268
313
  if (file && file.sha256 === undefined) {
269
314
  result.errors.push({ path, code: "provider_error", message: `the ${options.remote} has no hash for it yet` });
@@ -297,6 +342,20 @@ export const syncFileMirror = async (options) => {
297
342
  touched.push(path);
298
343
  }
299
344
  result.unchanged = unchanged;
345
+ const remotePath = (path) => posix.join(folder, path);
346
+ // A listing read in pages can miss a file that moved while it was read, and a provider's flat listing may lag: a
347
+ // file missing from it is deleted locally only once a direct read, made after the listing, finds nothing there.
348
+ const absent = steps.filter((step) => step.kind === "trash-local");
349
+ for (let at = 0; at < absent.length; at += CHECKS)
350
+ await Promise.all(absent.slice(at, at + CHECKS).map(async (step) => {
351
+ const why = await target.exists(remotePath(step.path), signal).then((there) => (there ? `missing from the ${options.remote} listing, but still there` : undefined), (error) => {
352
+ if (signal?.aborted)
353
+ throw error;
354
+ return `the ${options.remote} could not say whether it was deleted: ${options.errorOf(error).message}`;
355
+ });
356
+ if (why)
357
+ Object.assign(step, { kind: "unknown", reason: "remote", why });
358
+ }));
300
359
  const conflict = (step, reason) => result.conflicts.push({
301
360
  path: step.path,
302
361
  reason,
@@ -314,17 +373,60 @@ export const syncFileMirror = async (options) => {
314
373
  });
315
374
  }
316
375
  const deletions = steps.filter((step) => step.kind === "trash-local" || step.kind === "trash-remote").length;
317
- const tooMany = deletions > ALWAYS_DELETED &&
318
- (deletions > MAX_DELETIONS || deletions > Object.keys(state.entries).length * MAX_DELETED_SHARE);
376
+ const replacements = steps.filter((step) => (step.kind === "upload" && step.remote) || (step.kind === "download" && step.local) || step.kind === "keep-both").length;
377
+ const over = [
378
+ ...(deletions > MAX_DELETIONS
379
+ ? [
380
+ {
381
+ reason: "mirror.too-many-deletions",
382
+ what: `delete ${deletions} files (more than ${MAX_DELETIONS})`,
383
+ flag: fill(hints.allowDeletions, deletions),
384
+ allowed: (options.allowDeletions ?? 0) >= deletions,
385
+ },
386
+ ]
387
+ : []),
388
+ ...(replacements > MAX_REPLACEMENTS
389
+ ? [
390
+ {
391
+ reason: "mirror.too-many-replacements",
392
+ what: `replace ${replacements} existing files (more than ${MAX_REPLACEMENTS})`,
393
+ flag: fill(hints.allowReplacements, replacements),
394
+ allowed: (options.allowReplacements ?? 0) >= replacements,
395
+ },
396
+ ]
397
+ : []),
398
+ ];
399
+ if (deletions > MAX_DELETIONS)
400
+ result.tooManyDeletions = deletions;
401
+ if (replacements > MAX_REPLACEMENTS)
402
+ result.tooManyReplacements = replacements;
403
+ const noSpace = await shortOfSpace(steps, root, versions, options.space ?? freeSpace);
404
+ if (noSpace)
405
+ result.noSpace = noSpace;
319
406
  if (options.dryRun) {
320
407
  result.plan = steps.map(({ kind, path, to }) => ({ kind, path, ...(to ? { to } : {}) }));
321
- if (tooMany)
322
- result.tooManyDeletions = deletions;
323
408
  return result;
324
409
  }
325
- if (tooMany && (options.allowDeletions ?? 0) < deletions)
326
- throw new CliError("confirmation_required", `this sync would delete ${deletions} files; ` +
327
- `check them with ${hints.preview} and allow them ${hints.allowDeletions}`, { reason: "mirror.too-many-deletions", deletions });
410
+ const unapproved = over.find((one) => !one.allowed);
411
+ if (unapproved)
412
+ result.errors.push({
413
+ path: ".",
414
+ code: "confirmation_required",
415
+ reason: unapproved.reason,
416
+ message: `this sync would ${over.map((one) => one.what).join(" and ")}; check them with \`${fill(hints.preview)}\`, ` +
417
+ `then allow them with \`${fill(hints.sync)} ${over.map((one) => one.flag).join(" ")}\``,
418
+ });
419
+ if (noSpace)
420
+ result.errors.push({
421
+ path: ".",
422
+ code: "validation_error",
423
+ reason: "mirror.no-space",
424
+ message: `this sync needs ${gigabytes(noSpace.needed)} on the drive of ${noSpace.path}, which has ` +
425
+ `${gigabytes(noSpace.free)} free, and leaves ${gigabytes(spareFor(noSpace.needed))} of it free; free some space, or ` +
426
+ `leave big folders out with \`${fill(hints.exclude)}\``,
427
+ });
428
+ if (unapproved || noSpace)
429
+ return result;
328
430
  if (repin) {
329
431
  state.entries = {};
330
432
  state.rootId = listed?.rootId;
@@ -344,8 +446,10 @@ export const syncFileMirror = async (options) => {
344
446
  delete state.pending[path];
345
447
  }
346
448
  let savedAt = now();
449
+ // A big mirror's state is megabytes of JSON: saved less often, it costs no more than a small one's.
450
+ const saveEvery = SAVE_EVERY_MS * Math.max(1, Object.keys(state.entries).length / 10_000);
347
451
  const save = (force = false) => {
348
- if (!force && now() - savedAt < SAVE_EVERY_MS)
452
+ if (!force && now() - savedAt < saveEvery)
349
453
  return;
350
454
  options.state.save(state);
351
455
  savedAt = now();
@@ -358,7 +462,6 @@ export const syncFileMirror = async (options) => {
358
462
  }
359
463
  save(true);
360
464
  const date = new Date(now()).toISOString().slice(0, 10);
361
- const remotePath = (path) => posix.join(folder, path);
362
465
  const folders = new Set([...remote.keys()].map((path) => posix.dirname(path)));
363
466
  for (const path of [...folders])
364
467
  for (let up = path; up !== "."; up = posix.dirname(up))
@@ -574,12 +677,51 @@ export const syncFileMirror = async (options) => {
574
677
  }
575
678
  }
576
679
  finally {
680
+ // Forgotten, so a file whose exclusion is removed later is a new file, never a deletion.
681
+ for (const path of Object.keys(state.entries))
682
+ if (excluded(path))
683
+ delete state.entries[path];
577
684
  save(true);
578
685
  }
579
686
  await options.assertHeld();
580
687
  await versions.prune();
581
688
  return result;
582
689
  };
690
+ /**
691
+ * The free space a run needs that a file system lacks: downloads land under `root`, and the store keeps every
692
+ * content they replace or a deletion removes, plus each remote content an upload replaces that it lacks.
693
+ */
694
+ const shortOfSpace = async (steps, root, versions, space) => {
695
+ let incoming = 0;
696
+ let kept = 0;
697
+ for (const step of steps) {
698
+ const local = step.local?.size ?? 0;
699
+ const remote = step.remote?.size ?? 0;
700
+ if (step.kind === "download") {
701
+ incoming += remote;
702
+ kept += local;
703
+ }
704
+ if (step.kind === "keep-both") {
705
+ incoming += remote;
706
+ kept += remote;
707
+ }
708
+ if (step.kind === "trash-local")
709
+ kept += local;
710
+ if (step.kind === "upload" && step.remote && !versions.has(step.remote.sha256))
711
+ kept += remote;
712
+ }
713
+ if (!incoming && !kept)
714
+ return undefined;
715
+ const here = await space(root);
716
+ const store = versions.dir === undefined ? here : await space(versions.dir);
717
+ const needs = store.dev === here.dev
718
+ ? [{ path: root, needed: incoming + kept, free: here.free }]
719
+ : [
720
+ { path: root, needed: incoming, free: here.free },
721
+ { path: versions.dir, needed: kept, free: store.free },
722
+ ];
723
+ return needs.find((need) => need.needed > 0 && need.free < need.needed + spareFor(need.needed));
724
+ };
583
725
  const ancestors = (path) => {
584
726
  const found = [];
585
727
  for (let up = posix.dirname(path); up !== "."; up = posix.dirname(up))
@@ -619,8 +761,9 @@ export const fileSyncState = (dir, mirror, principal) => jsonState(join(dir, `${
619
761
  export const fileMirrorStatus = async (mirrors, stateOf) => {
620
762
  const items = [];
621
763
  for (const mirror of mirrors) {
622
- const { entries } = stateOf(mirror).read();
623
- const { files, links } = await scan(mirror.path, entries);
764
+ const excluded = excludedBy(mirror.exclude);
765
+ const entries = Object.fromEntries(Object.entries(stateOf(mirror).read().entries).filter(([path]) => !excluded(path)));
766
+ const { files, links } = await scan(mirror.path, entries, excluded);
624
767
  const seen = new Set(files.map((file) => file.path));
625
768
  items.push({
626
769
  id: mirror.id,
@@ -654,6 +797,8 @@ export const syncFileMirrors = (options) => eachMirror(options.mirrors, options.
654
797
  ...options,
655
798
  root: mirror.path,
656
799
  folder: mirror.folder,
800
+ id: mirror.id,
801
+ ...(mirror.exclude ? { exclude: mirror.exclude } : {}),
657
802
  state: options.stateOf(mirror),
658
803
  versions: options.versionsOf(mirror),
659
804
  assertHeld: heldCheck(held),
@@ -23,6 +23,8 @@ export interface FileVersion extends VersionEvent {
23
23
  available: boolean;
24
24
  }
25
25
  export interface FileVersions {
26
+ /** The folder the store keeps its copies in, when it is on disk: a sync checks its free space first. */
27
+ readonly dir?: string;
26
28
  /**
27
29
  * Copies a content into the store before the sync overwrites or deletes it; returns the hash of what it copied. The
28
30
  * source is a local file, or a writer that creates the temporary file it is given, such as a target's `download`.
@@ -61,6 +61,7 @@ export const fileVersions = (dir, now = Date.now) => {
61
61
  };
62
62
  const has = (sha256) => existsSync(join(objects, sha256));
63
63
  return {
64
+ dir,
64
65
  keep: async (source) => {
65
66
  await stored(() => mkdir(objects, { recursive: true, mode: 0o700 }));
66
67
  const temp = join(objects, `.${randomUUID()}.tmp`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.710.0",
3
+ "version": "0.711.0",
4
4
  "description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Viacheslav Ptsarev",
@@ -215,6 +215,10 @@
215
215
  "types": "./dist/sftp/index.d.ts",
216
216
  "default": "./dist/sftp/index.js"
217
217
  },
218
+ "./mount": {
219
+ "types": "./dist/mount/index.d.ts",
220
+ "default": "./dist/mount/index.js"
221
+ },
218
222
  "./sql": {
219
223
  "types": "./dist/sql/index.d.ts",
220
224
  "default": "./dist/sql/index.js"