@wirecat/files-cli 0.0.0-stage → 0.2.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.
Files changed (87) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/LICENSE +204 -0
  3. package/README.md +68 -2
  4. package/contracts/wirecat.json +793 -0
  5. package/dist/answer.js +60 -0
  6. package/dist/app.js +6 -0
  7. package/dist/author.js +87 -0
  8. package/dist/bin/files.js +40 -0
  9. package/dist/bundle/chunk-3GCXH3WT.js +263 -0
  10. package/dist/bundle/files.js +21 -0
  11. package/dist/bundle/program-OBKXQ4VY.js +12479 -0
  12. package/dist/config.js +74 -0
  13. package/dist/doctor.js +33 -0
  14. package/dist/entities.js +104 -0
  15. package/dist/failure.js +21 -0
  16. package/dist/identity.js +27 -0
  17. package/dist/import/audio.js +96 -0
  18. package/dist/import/command.js +156 -0
  19. package/dist/import/external-id.js +44 -0
  20. package/dist/import/files.js +206 -0
  21. package/dist/import/readers.js +87 -0
  22. package/dist/index.js +3 -0
  23. package/dist/migrate.js +192 -0
  24. package/dist/notes/about.js +55 -0
  25. package/dist/notes/bound.js +41 -0
  26. package/dist/notes/command.js +241 -0
  27. package/dist/notes/dates.js +15 -0
  28. package/dist/notes/dialects/common.js +79 -0
  29. package/dist/notes/dialects/index.js +6 -0
  30. package/dist/notes/dialects/markdown.js +51 -0
  31. package/dist/notes/dialects/obsidian.js +33 -0
  32. package/dist/notes/dialects/types.js +2 -0
  33. package/dist/notes/embed.js +97 -0
  34. package/dist/notes/export.js +76 -0
  35. package/dist/notes/files.js +87 -0
  36. package/dist/notes/folders-command.js +172 -0
  37. package/dist/notes/folders.js +90 -0
  38. package/dist/notes/import.js +289 -0
  39. package/dist/notes/internal.js +51 -0
  40. package/dist/notes/links.js +46 -0
  41. package/dist/notes/list.js +23 -0
  42. package/dist/notes/renames.js +24 -0
  43. package/dist/notes/search.js +16 -0
  44. package/dist/notes/state.js +33 -0
  45. package/dist/options.js +9 -0
  46. package/dist/output.js +4 -0
  47. package/dist/paths.js +5 -0
  48. package/dist/people/command.js +92 -0
  49. package/dist/people/identity.js +19 -0
  50. package/dist/people/notes-map.js +58 -0
  51. package/dist/people/owner.js +14 -0
  52. package/dist/people/subject.js +19 -0
  53. package/dist/program.js +101 -0
  54. package/dist/progress.js +19 -0
  55. package/dist/reasons.js +187 -0
  56. package/dist/records/input.js +114 -0
  57. package/dist/records/receipt.js +25 -0
  58. package/dist/records/source.js +12 -0
  59. package/dist/refs.js +28 -0
  60. package/dist/run/lock.js +21 -0
  61. package/dist/save-help.js +3 -0
  62. package/dist/search.js +63 -0
  63. package/dist/sources/command.js +295 -0
  64. package/dist/sources/copy.js +32 -0
  65. package/dist/sources/mentions.js +78 -0
  66. package/dist/sources/read.js +262 -0
  67. package/dist/sources/readers/ai-model.js +74 -0
  68. package/dist/sources/readers/api.js +48 -0
  69. package/dist/sources/readers/claude-code.js +74 -0
  70. package/dist/sources/readers/codex.js +72 -0
  71. package/dist/sources/readers/index.js +10 -0
  72. package/dist/sources/readers/keys.js +31 -0
  73. package/dist/sources/readers/ollama.js +84 -0
  74. package/dist/sources/readers/process.js +49 -0
  75. package/dist/sources/readers/types.js +2 -0
  76. package/dist/sources/suggest-command.js +253 -0
  77. package/dist/sources/suggest.js +142 -0
  78. package/dist/sources/transcript.js +52 -0
  79. package/dist/store/group.js +8 -0
  80. package/dist/store/scope.js +25 -0
  81. package/dist/store/source-list.js +22 -0
  82. package/dist/sync.js +182 -0
  83. package/dist/terminal.js +16 -0
  84. package/dist/version.js +2 -0
  85. package/dist/wcat.js +4 -0
  86. package/package.json +89 -4
  87. package/skills/files-cli/SKILL.md +41 -0
@@ -0,0 +1,206 @@
1
+ import { createHash } from "node:crypto";
2
+ import { constants } from "node:fs";
3
+ import { lstat, open, readdir, realpath } from "node:fs/promises";
4
+ import { basename, extname, join, relative, sep } from "node:path";
5
+ import { pathToFileURL } from "node:url";
6
+ import { attachmentMaxBytes, readWhole, sizeText } from "@wirecat/cli-core/documents";
7
+ import { idOfPath } from "./external-id.js";
8
+ /** A whole tree is walked before anything is written; past these the folder is refused rather than read in part. */
9
+ export const MOST_FILES = 10_000;
10
+ const DEEPEST = 32;
11
+ /**
12
+ * The envelope refuses a document whose fields pass 1 MiB as JSON, or whose text passes a million characters; the
13
+ * title, the address and the metadata get the rest. A longer text is cut and the receipt says so.
14
+ */
15
+ const FIELDS_BYTES = 1024 * 1024 - 4096;
16
+ export const TEXT_CHARS = 1_000_000;
17
+ export const TEXT_EXTENSIONS = {
18
+ ".txt": "text",
19
+ ".text": "text",
20
+ ".md": "markdown",
21
+ ".markdown": "markdown",
22
+ };
23
+ const refusedLink = "a symbolic link is not followed: give the folder it points at";
24
+ /** Opened without following a link, so a file swapped for one after the walk is refused too. */
25
+ export const readBytes = async (path) => {
26
+ const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
27
+ try {
28
+ const bytes = await readWhole(handle);
29
+ // A view, not a copy: the buffer is the file's own, and a large file is held once.
30
+ return new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
31
+ }
32
+ finally {
33
+ await handle.close();
34
+ }
35
+ };
36
+ /** Why a file or folder could not be read, in words, never an errno alone. */
37
+ export const unreadable = (error) => {
38
+ const code = typeof error === "object" && error !== null && "code" in error ? String(error.code) : undefined;
39
+ if (code === "EACCES" || code === "EPERM")
40
+ return "no permission to read it";
41
+ if (code === "ELOOP")
42
+ return "it became a symbolic link while the import ran";
43
+ if (code === "ENOENT")
44
+ return "it disappeared while the import ran";
45
+ return `could not be read${error instanceof Error ? `: ${error.message}` : ""}`;
46
+ };
47
+ const isInside = (root, path) => path === root || path.startsWith(root + sep);
48
+ /**
49
+ * Every regular file under `root`, or `root` itself when it is a file. Links are refused, not followed, and every
50
+ * file's real path must stay under the folder's. Names starting with `.` (`.git`, `.obsidian`) are left out.
51
+ */
52
+ export const walk = async (root) => {
53
+ // The folder the owner names may itself be a link; only what is inside it may not.
54
+ const real = await realpath(root);
55
+ const files = [];
56
+ const skipped = [];
57
+ const stat = await lstat(real);
58
+ if (!stat.isDirectory()) {
59
+ if (!stat.isFile())
60
+ return { files, skipped: [{ path: root, reason: "not a file or a folder" }], base: real };
61
+ const name = basename(real);
62
+ return {
63
+ files: [{ path: real, relative: name, extension: extname(name).toLowerCase(), stat }],
64
+ skipped,
65
+ base: real,
66
+ };
67
+ }
68
+ const visit = async (folder, depth) => {
69
+ if (depth > DEEPEST) {
70
+ skipped.push({ path: relative(real, folder), reason: `deeper than ${DEEPEST} folders` });
71
+ return;
72
+ }
73
+ let entries;
74
+ try {
75
+ entries = await readdir(folder, { withFileTypes: true });
76
+ }
77
+ catch (error) {
78
+ skipped.push({ path: relative(real, folder).split(sep).join("/") || ".", reason: unreadable(error) });
79
+ return;
80
+ }
81
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
82
+ for (const entry of entries) {
83
+ if (entry.name.startsWith("."))
84
+ continue;
85
+ const path = join(folder, entry.name);
86
+ const shown = relative(real, path).split(sep).join("/");
87
+ if (entry.isSymbolicLink()) {
88
+ skipped.push({ path: shown, reason: refusedLink });
89
+ continue;
90
+ }
91
+ const resolved = await realpath(path).catch(() => undefined);
92
+ if (resolved === undefined) {
93
+ skipped.push({ path: shown, reason: "could not be read" });
94
+ continue;
95
+ }
96
+ if (!isInside(real, resolved)) {
97
+ skipped.push({ path: shown, reason: "outside the folder" });
98
+ continue;
99
+ }
100
+ if (entry.isDirectory()) {
101
+ await visit(path, depth + 1);
102
+ continue;
103
+ }
104
+ if (!entry.isFile()) {
105
+ skipped.push({ path: shown, reason: "not a file" });
106
+ continue;
107
+ }
108
+ if (files.length >= MOST_FILES)
109
+ throw new TooMany();
110
+ files.push({ path, relative: shown, extension: extname(entry.name).toLowerCase(), stat: await lstat(path) });
111
+ }
112
+ };
113
+ await visit(real, 0);
114
+ return { files, skipped, base: real };
115
+ };
116
+ export class TooMany extends Error {
117
+ constructor() {
118
+ super(`more than ${MOST_FILES} files`);
119
+ }
120
+ }
121
+ const UTF8 = new TextDecoder("utf-8", { fatal: true });
122
+ /** Plain UTF-8 text with its line ends as `\n`; `undefined` for bytes that are not, such as cp1251 or a binary. */
123
+ export const utf8Text = (bytes) => {
124
+ if (bytes.includes(0))
125
+ return undefined;
126
+ try {
127
+ return UTF8.decode(bytes).replace(/^/, "").replace(/\r\n?/g, "\n");
128
+ }
129
+ catch {
130
+ return undefined;
131
+ }
132
+ };
133
+ const FRONT_MATTER = /^---\n[\s\S]*?\n(?:---|\.\.\.)\n/;
134
+ /** The first Markdown heading, past any front matter; a plain text file has none. */
135
+ export const headingOf = (text) => {
136
+ const body = text.replace(FRONT_MATTER, "");
137
+ for (const line of body.split("\n")) {
138
+ const heading = /^#{1,6}[ \t]+(.+?)[ \t#]*$/.exec(line)?.[1]?.trim();
139
+ if (heading)
140
+ return heading.slice(0, 200);
141
+ }
142
+ return undefined;
143
+ };
144
+ export const titleOfName = (name) => (basename(name).replace(/\.[^.]+$/, "") || basename(name)).slice(0, 200);
145
+ export const sha256Of = (bytes) => createHash("sha256").update(bytes).digest("hex");
146
+ const bytesOf = (value) => Buffer.byteLength(JSON.stringify(value));
147
+ /**
148
+ * A `document` record's fields: the text cut by code point so the fields fit the envelope's limit, and `metadata`
149
+ * saying where the file was. `revision` is left out on purpose: a restored file goes back in time, and a lower
150
+ * revision would be refused; the fingerprint says whether it changed.
151
+ */
152
+ export const documentFields = (file, { title, text, metadata }) => {
153
+ const born = file.stat.birthtimeMs > 0 && file.stat.birthtimeMs <= file.stat.mtimeMs ? file.stat.birthtime : null;
154
+ const base = {
155
+ title,
156
+ text: "",
157
+ created_at: (born ?? file.stat.mtime).toISOString(),
158
+ updated_at: file.stat.mtime.toISOString(),
159
+ url: pathToFileURL(file.path).href,
160
+ metadata: { path: file.relative.normalize("NFC"), size: file.stat.size, ...metadata },
161
+ };
162
+ const room = FIELDS_BYTES - bytesOf(base);
163
+ if (text.length <= TEXT_CHARS && bytesOf(text) <= room)
164
+ return { fields: { ...base, text }, cut: false };
165
+ // Each UTF-16 unit is at least one byte, so nothing past `room` units can fit; a large file is never split whole.
166
+ const head = text.slice(0, Math.max(0, Math.min(room, TEXT_CHARS))).replace(/[\uD800-\uDBFF]$/, "");
167
+ const points = Array.from(head);
168
+ let low = 0;
169
+ let high = points.length;
170
+ while (low < high) {
171
+ const middle = Math.ceil((low + high) / 2);
172
+ if (bytesOf(points.slice(0, middle).join("")) <= room - 64)
173
+ low = middle;
174
+ else
175
+ high = middle - 1;
176
+ }
177
+ return {
178
+ fields: { ...base, text: points.slice(0, low).join(""), metadata: { ...base.metadata, truncated: true } },
179
+ cut: true,
180
+ };
181
+ };
182
+ /** A `.txt` or `.md` file's text and title; a refusal names why it was skipped. */
183
+ export const readTextFile = async (file) => {
184
+ const max = attachmentMaxBytes();
185
+ if (file.stat.size > max)
186
+ return { refused: `larger than ${sizeText(max)}; configure MESSAGING_ATTACHMENT_MAX_MIB` };
187
+ const bytes = await readBytes(file.path);
188
+ const text = utf8Text(bytes);
189
+ if (text === undefined)
190
+ return { refused: "not UTF-8 text" };
191
+ if (!text.trim())
192
+ return { refused: "holds no text" };
193
+ const format = TEXT_EXTENSIONS[file.extension] ?? "text";
194
+ return {
195
+ title: (format === "markdown" ? headingOf(text) : undefined) ?? titleOfName(file.relative),
196
+ text: text.trim(),
197
+ metadata: { format, sha256: sha256Of(bytes) },
198
+ };
199
+ };
200
+ /** The envelope's record type for a file's text. */
201
+ export const DOCUMENT_TYPE = "document";
202
+ export const documentRecord = (file, fields, type) => {
203
+ const id = idOfPath(file.relative);
204
+ return { key: id, type, external_id: id, operation: "upsert", fields };
205
+ };
206
+ //# sourceMappingURL=files.js.map
@@ -0,0 +1,87 @@
1
+ import { isCliError } from "@wirecat/cli-base";
2
+ import { NOTE_EXTENSIONS } from "../notes/files.js";
3
+ import { readFile } from "../sources/read.js";
4
+ import { readBytes, readTextFile, sha256Of, TEXT_CHARS, TEXT_EXTENSIONS, titleOfName, } from "./files.js";
5
+ export const RECORDS_FILES = new Set([".json", ".jsonl"]);
6
+ /**
7
+ * Read on this computer by the readers of a notes folder, less what `TEXT_EXTENSIONS` reads and `.xls`, which no
8
+ * reader takes; an image is never among them, so nothing is sent to a model.
9
+ */
10
+ const DOCUMENT_EXTENSIONS = Object.fromEntries(NOTE_EXTENSIONS.filter((extension) => !TEXT_EXTENSIONS[extension] && extension !== ".xls").map((extension) => [
11
+ extension,
12
+ extension.slice(1),
13
+ ]));
14
+ const TRANSCRIPT_EXTENSIONS = { ".vtt": "vtt", ".srt": "srt" };
15
+ /** A document, sheet or web page through files' document readers, which run on this computer. */
16
+ const readDocument = async (file) => {
17
+ try {
18
+ const read = await readFile(file.path, { maxChars: TEXT_CHARS });
19
+ if (read.read !== "extracted" || !read.text.trim())
20
+ return { refused: "holds no text files can read, such as a scanned PDF" };
21
+ return {
22
+ title: read.title ?? titleOfName(file.relative),
23
+ text: read.text.trim(),
24
+ metadata: {
25
+ format: DOCUMENT_EXTENSIONS[file.extension],
26
+ sha256: sha256Of(read.bytes ?? new Uint8Array()),
27
+ extractor: read.extractor,
28
+ },
29
+ };
30
+ }
31
+ catch (error) {
32
+ return { refused: isCliError(error) ? error.message : "its reader could not read it" };
33
+ }
34
+ };
35
+ const CUE = /((?:\d+:)?\d{1,2}:\d{2}[.,]\d{1,3})\s*-->\s*((?:\d+:)?\d{1,2}:\d{2}[.,]\d{1,3})/;
36
+ const secondsOf = (stamp) => stamp
37
+ .replace(",", ".")
38
+ .split(":")
39
+ .reduce((total, part) => total * 60 + Number(part), 0);
40
+ /** Where the talk starts and ends, in seconds, and who speaks: what `transcriptText` leaves out of the text. */
41
+ export const transcriptTimings = (raw, text) => {
42
+ let cues = 0;
43
+ let start;
44
+ let end = 0;
45
+ for (const line of raw.split(/\r?\n/)) {
46
+ const cue = CUE.exec(line);
47
+ if (!cue?.[1] || !cue[2])
48
+ continue;
49
+ cues++;
50
+ start ??= secondsOf(cue[1]);
51
+ end = Math.max(end, secondsOf(cue[2]));
52
+ }
53
+ const speakers = [...new Set(text.split("\n").flatMap((line) => /^([^:\n]{1,60}):\s/.exec(line)?.[1] ?? []))];
54
+ return { cues, start_seconds: start ?? 0, end_seconds: end, speakers: speakers.slice(0, 50) };
55
+ };
56
+ /** A WebVTT or SubRip file as `sources add` keeps it, one `Name: text` line per turn, with its timings beside it. */
57
+ const readTranscript = async (file) => {
58
+ const read = await readDocument(file);
59
+ if ("refused" in read)
60
+ return read;
61
+ const raw = new TextDecoder().decode(await readBytes(file.path));
62
+ return {
63
+ ...read,
64
+ title: titleOfName(file.relative),
65
+ metadata: {
66
+ ...read.metadata,
67
+ format: TRANSCRIPT_EXTENSIONS[file.extension],
68
+ transcript: transcriptTimings(raw, read.text),
69
+ },
70
+ };
71
+ };
72
+ /** The reader of a file found in a folder, or why it is skipped; recordings were heard before, in `heard`. */
73
+ export const readerOf = (file, heard) => {
74
+ const recording = heard.get(file.path);
75
+ if (recording)
76
+ return async () => recording;
77
+ if (TEXT_EXTENSIONS[file.extension])
78
+ return readTextFile;
79
+ if (DOCUMENT_EXTENSIONS[file.extension])
80
+ return readDocument;
81
+ if (TRANSCRIPT_EXTENSIONS[file.extension])
82
+ return readTranscript;
83
+ if (RECORDS_FILES.has(file.extension))
84
+ return "a records file is imported on its own: files import <file> --account …";
85
+ return `no reader for ${file.extension || "a file without an extension"}`;
86
+ };
87
+ //# sourceMappingURL=readers.js.map
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { IDENTITY } from "./identity.js";
2
+ export { createProgram, definition, run } from "./program.js";
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,192 @@
1
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { Credentials, configFilePath, pathsAreOverridden, resolvePaths, saveConfigFile, } from "@wirecat/cli-base";
4
+ import { installerOf } from "@wirecat/cli-base/update";
5
+ import { configPath } from "./config.js";
6
+ import { IDENTITY } from "./identity.js";
7
+ import { filesPaths } from "./paths.js";
8
+ /** memo's folders before and after it became wcat; wcat's first start moves `cli-memo` to `wcat`, so `wcat` is read first. */
9
+ const MEMO_HOMES = [
10
+ { appName: "wcat", prefix: "WCAT" },
11
+ { appName: "cli-memo", prefix: "MEMO" },
12
+ ];
13
+ const MARKER = "migrated-from-memo.json";
14
+ /** The settings that moved with the notes: the folders, and the reader `sources suggest` sends text to. */
15
+ const MOVED = ["notes", "sources"];
16
+ const OLD_MARK = "memo:";
17
+ const NEW_MARK = "files:";
18
+ /** The providers whose key memo's sync enriched notes with, kept as `embeddings:<provider>` under memo's own service. */
19
+ const KEY_PROVIDERS = ["openai", "anthropic"];
20
+ const readJson = (path) => {
21
+ try {
22
+ return JSON.parse(readFileSync(path, "utf8"));
23
+ }
24
+ catch {
25
+ return undefined;
26
+ }
27
+ };
28
+ const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
29
+ const homeOf = (env) => MEMO_HOMES.map((home) => resolvePaths({ ...home, env })).find(({ config, state }) => existsSync(configFilePath(config)) || existsSync(join(state, "folders")));
30
+ /** A folder's state with memo's mark on the files it exported turned into files' mark; every other entry as it was. */
31
+ export const renamedMarks = (state) => {
32
+ if (!isRecord(state) || !isRecord(state.files))
33
+ return state;
34
+ const files = Object.fromEntries(Object.entries(state.files).map(([path, value]) => [
35
+ path,
36
+ typeof value === "string" && value.startsWith(OLD_MARK) ? `${NEW_MARK}${value.slice(OLD_MARK.length)}` : value,
37
+ ]));
38
+ return { ...state, files };
39
+ };
40
+ const copyConfig = (from, env) => {
41
+ const old = readJson(configFilePath(from));
42
+ if (!isRecord(old))
43
+ return [];
44
+ const target = configPath(env);
45
+ const current = readJson(target);
46
+ const raw = isRecord(current) ? current : {};
47
+ const defaults = isRecord(raw.defaults) ? { ...raw.defaults } : {};
48
+ // A section files already has is the owner's newer choice; memo's copy never replaces it.
49
+ const copied = MOVED.filter((key) => old[key] !== undefined && defaults[key] === undefined);
50
+ if (copied.length === 0)
51
+ return [];
52
+ for (const key of copied)
53
+ defaults[key] = old[key];
54
+ saveConfigFile(target, { ...raw, defaults });
55
+ return copied.map((key) => `defaults.${key}`);
56
+ };
57
+ const copyFolderStates = (from, to) => {
58
+ const source = join(from, "folders");
59
+ if (!existsSync(source))
60
+ return 0;
61
+ const target = join(to, "folders");
62
+ mkdirSync(target, { recursive: true });
63
+ let copied = 0;
64
+ for (const name of readdirSync(source)) {
65
+ if (!name.endsWith(".json") || existsSync(join(target, name)))
66
+ continue;
67
+ const state = readJson(join(source, name));
68
+ if (state === undefined)
69
+ continue;
70
+ writeFileSync(join(target, name), JSON.stringify(renamedMarks(state)));
71
+ copied++;
72
+ }
73
+ return copied;
74
+ };
75
+ const copyMaps = (from, to) => {
76
+ const copied = [];
77
+ for (const [dir, name, into] of [
78
+ [from.config, "people-notes.json", to.config],
79
+ [from.state, "people-notes-imported.json", to.state],
80
+ ]) {
81
+ if (!existsSync(join(dir, name)) || existsSync(join(into, name)))
82
+ continue;
83
+ mkdirSync(into, { recursive: true });
84
+ copyFileSync(join(dir, name), join(into, name));
85
+ copied.push(name);
86
+ }
87
+ return copied;
88
+ };
89
+ /**
90
+ * The `embeddings:<provider>` entries under one tool's own service, where cli-core's enrichment reads that tool's key.
91
+ * Named as cli-core's embeddingKeys names them; cli-core 2.0.0 does not export it. No environment variable is read: a
92
+ * key in the environment is no stored entry to copy.
93
+ */
94
+ const enrichmentKeys = (appName, prefix, env, keyring) => {
95
+ const where = { appName, prefix, env };
96
+ const credentials = new Credentials({
97
+ configDir: resolvePaths(where).config,
98
+ service: appName,
99
+ isolated: pathsAreOverridden(where),
100
+ env,
101
+ ...(keyring ? { keyring } : {}),
102
+ warn: (message) => process.stderr.write(`${message}\n`),
103
+ });
104
+ return {
105
+ read: (provider) => credentials.read(`embeddings:${provider}`)?.secret,
106
+ write: (provider, key) => credentials.write(`embeddings:${provider}`, key, { signIn: true }),
107
+ };
108
+ };
109
+ /**
110
+ * memo's enrichment key for each provider, copied into files' own entry, which cli-core's enrichment reads for files.
111
+ * wcat's entry is read first, then cli-memo's. memo's entry stays, and files' own is never replaced.
112
+ */
113
+ const copyKeys = (env, keyring) => {
114
+ const own = enrichmentKeys(IDENTITY.appName, IDENTITY.envPrefix, env, keyring);
115
+ const homes = MEMO_HOMES.map(({ appName, prefix }) => enrichmentKeys(appName, prefix, env, keyring));
116
+ const copied = [];
117
+ for (const provider of KEY_PROVIDERS) {
118
+ if (own.read(provider) !== undefined)
119
+ continue;
120
+ const found = homes.map((home) => home.read(provider)).find((key) => key !== undefined);
121
+ if (found === undefined)
122
+ continue;
123
+ own.write(provider, found);
124
+ copied.push(provider);
125
+ }
126
+ return copied;
127
+ };
128
+ /** The keys, or none when the keyring does not answer: that must not stop the command, and a later start tries again. */
129
+ const keysIfAnswered = (env, keyring) => {
130
+ try {
131
+ return copyKeys(env, keyring);
132
+ }
133
+ catch {
134
+ return undefined;
135
+ }
136
+ };
137
+ const writeMarker = (path, done, keysPending) => {
138
+ mkdirSync(join(path, ".."), { recursive: true });
139
+ writeFileSync(path, JSON.stringify({ ...done, keys_pending: keysPending, at: new Date().toISOString() }));
140
+ };
141
+ /**
142
+ * On files' first start: the notes and sources settings from memo's config, its notes folders' state (memo's mark on
143
+ * exported files becomes files'), the old people-notes map and memo's enrichment keys. Only files' own folders and
144
+ * keyring entries are written: memo's stay as they are, and the owner's notes are never touched. Once: a marker in
145
+ * files' state folder records it, also when there was nothing to copy. Only the keys are tried again, on a later start,
146
+ * when the keyring did not answer.
147
+ */
148
+ export const migrateFromMemo = (env, keyring) => {
149
+ const own = filesPaths(env);
150
+ const marker = join(own.state, MARKER);
151
+ if (existsSync(marker)) {
152
+ const saved = readJson(marker);
153
+ if (!isRecord(saved) || saved.keys_pending !== true)
154
+ return undefined;
155
+ const keys = keysIfAnswered(env, keyring);
156
+ if (keys === undefined)
157
+ return undefined;
158
+ const done = { ...saved, keys };
159
+ writeMarker(marker, done, false);
160
+ return done;
161
+ }
162
+ const home = homeOf(env);
163
+ // Without memo's folders there is no memo to take keys from, so a new owner's first start never asks the keyring.
164
+ const keys = home ? keysIfAnswered(env, keyring) : [];
165
+ const done = home
166
+ ? {
167
+ from: home.config,
168
+ config: copyConfig(home.config, env),
169
+ folders: copyFolderStates(home.state, own.state),
170
+ maps: copyMaps(home, own),
171
+ keys: keys ?? [],
172
+ }
173
+ : { from: null, config: [], folders: 0, maps: [], keys: keys ?? [] };
174
+ writeMarker(marker, done, keys === undefined);
175
+ return done;
176
+ };
177
+ /**
178
+ * Only an installed files moves memo's data. A build in a checkout runs under dev scripts and agents, often with the
179
+ * owner's real home, and must never copy or rewrite the owner's live memo data.
180
+ */
181
+ export const isInstalledCopy = (script) => {
182
+ if (!script)
183
+ return false;
184
+ try {
185
+ const installer = installerOf(realpathSync(script));
186
+ return installer !== "checkout" && installer !== "unknown";
187
+ }
188
+ catch {
189
+ return false;
190
+ }
191
+ };
192
+ //# sourceMappingURL=migrate.js.map
@@ -0,0 +1,55 @@
1
+ import { formatReference } from "@wirecat/cli-core";
2
+ /** A file in a notes folder is a `document:`, a written note a `note:`. */
3
+ export const isNoteReference = (reference) => /^(note|document):/.test(reference);
4
+ const fold = (value) => value.normalize("NFC").toLocaleLowerCase("en").trim().replace(/^@/, "");
5
+ const PAGE = 500;
6
+ /** cli-core's list reader names a notes folder or a documents account as `notes:<id>`, never by its own provider. */
7
+ const holdsFolder = (scope) => (id) => scope === undefined || scope.some((one) => one.provider === "notes" && one.account === id);
8
+ /**
9
+ * Every live note that reaches a subject through the links the store holds — never a name found in plain text — in a
10
+ * folder of `scope`. The owner's own notes belong to no folder, so every scope reads them.
11
+ */
12
+ export const notesReaching = async (store, subject, scope) => {
13
+ const inScope = holdsFolder(scope);
14
+ const kept = (note) => note.deletedAt === null && (note.folderId === null || inScope(note.folderId));
15
+ const refs = [
16
+ subject.ref,
17
+ ...(subject.person?.identities.map((identity) => formatReference({ type: "contact", provider: identity.provider, id: identity.id })) ?? []),
18
+ ];
19
+ const live = async (links, via) => {
20
+ const found = [];
21
+ for (const link of links) {
22
+ if (!isNoteReference(link.from))
23
+ continue;
24
+ const note = await store.notes.resolveNote(link.from);
25
+ if (note && kept(note))
26
+ found.push({ note, anchor: link.anchor, text: link.targetText, via });
27
+ }
28
+ return found;
29
+ };
30
+ const aboutOne = async (ref) => {
31
+ const notes = [];
32
+ for (let offset = 0;; offset += PAGE) {
33
+ const page = await store.notes.notes({ about: ref, limit: PAGE, offset });
34
+ notes.push(...page.items.filter(kept));
35
+ if (!page.hasMore)
36
+ return notes;
37
+ }
38
+ };
39
+ // A written note's first subject is the note's own, not a link, so only `notes({ about })` sees all of them.
40
+ const about = (await Promise.all(refs.map(aboutOne)))
41
+ .flat()
42
+ .map((note) => ({ note, anchor: null, text: null, via: "about" }));
43
+ const linking = await live((await Promise.all(refs.map((to) => store.notes.links({ to })))).flat().filter((link) => link.kind === "links-to"), "link");
44
+ const through = await live((await Promise.all(about.map(({ note }) => store.notes.links({ to: note.ref }))))
45
+ .flat()
46
+ .filter((link) => link.kind === "links-to"), "through");
47
+ const names = new Set([subject.person?.name, ...(subject.person?.identities.map(({ name }) => name) ?? [])]
48
+ .filter((name) => !!name?.trim())
49
+ .map(fold));
50
+ const waiting = names.size === 0
51
+ ? []
52
+ : await live((await store.notes.links({ unresolved: true })).filter((link) => names.has(fold(link.targetText ?? ""))), "name");
53
+ return [...about, ...linking, ...through, ...waiting];
54
+ };
55
+ //# sourceMappingURL=about.js.map
@@ -0,0 +1,41 @@
1
+ import { isAbsolute, relative, resolve, sep } from "node:path";
2
+ import { CliError } from "@wirecat/cli-base";
3
+ import { loadConfig } from "../config.js";
4
+ import { noteFolders } from "./folders.js";
5
+ export const UNBOUND = "folder.unbound";
6
+ export const unboundReason = (path) => `${path} has no folder id — files folders add ${path}, or files folders update <id> ${path} if another computer made one`;
7
+ const unbound = (path) => new CliError("configuration_error", unboundReason(path), { reason: UNBOUND, path });
8
+ /**
9
+ * The configured folders the store knows; `only` narrows them by path or id.
10
+ * `strict` refuses a folder with no id — an import must not invent one — while a read just leaves it out.
11
+ */
12
+ export const boundFolders = async (store, env, { only, strict = true } = {}) => {
13
+ const known = new Set((await store.notes.folders()).map(({ id }) => id));
14
+ const configured = noteFolders(loadConfig(env).notes);
15
+ const wanted = only === undefined
16
+ ? configured
17
+ : only.map((name) => {
18
+ const found = configured.find((folder) => folder.id === name || folder.path === resolve(name));
19
+ if (!found)
20
+ throw unbound(resolve(name));
21
+ return found;
22
+ });
23
+ return wanted.flatMap((folder) => {
24
+ if (folder.id !== null && known.has(folder.id))
25
+ return [folder];
26
+ if (strict)
27
+ throw unbound(folder.path);
28
+ return [];
29
+ });
30
+ };
31
+ /** The folder a file lies in, and its path inside it. */
32
+ export const folderOfFile = (folders, file) => {
33
+ const at = resolve(file);
34
+ for (const folder of folders) {
35
+ const path = relative(folder.path, at);
36
+ if (path && path !== ".." && !path.startsWith(`..${sep}`) && !isAbsolute(path))
37
+ return { folder, path: path.split(sep).join("/") };
38
+ }
39
+ throw new CliError("not_found", `${at} is in no configured folder of notes`, { reason: "folder.not-found" });
40
+ };
41
+ //# sourceMappingURL=bound.js.map