@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,241 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { CliError } from "@wirecat/cli-base";
3
+ import { annotate } from "@wirecat/cli-base/commands";
4
+ import { contextEvidenceFingerprint, LOCAL_READ, LOCAL_WRITE, queryTerms, termField, withQuery, } from "@wirecat/cli-core";
5
+ import { InvalidArgumentError } from "commander";
6
+ import { answers, itemAnswer, listAnswer, withStore } from "../answer.js";
7
+ import { isMcpRun } from "../author.js";
8
+ import { loadConfig } from "../config.js";
9
+ import { collect, positive } from "../options.js";
10
+ import { importNotesMap } from "../people/notes-map.js";
11
+ import { subjectOf } from "../people/subject.js";
12
+ import { refuseBareNumber } from "../refs.js";
13
+ import { SAVE_HELP } from "../save-help.js";
14
+ import { meetingReference } from "../store/scope.js";
15
+ import { MEETING_WRITE_HELP, oneAccountOf, writeAccountOf, writeOptions } from "../store/source-list.js";
16
+ import { isNoteReference } from "./about.js";
17
+ import { boundFolders, folderOfFile } from "./bound.js";
18
+ import { DIALECTS } from "./dialects/index.js";
19
+ import { folderNotes } from "./import.js";
20
+ import { exportInternal, exportTarget, internalNotes } from "./internal.js";
21
+ import { listNotes } from "./list.js";
22
+ const formatOf = (value) => {
23
+ if (!DIALECTS.includes(value))
24
+ throw new InvalidArgumentError(`choose ${DIALECTS.join(", ")}`);
25
+ return value;
26
+ };
27
+ const NOTES_LIST_QUERY = {
28
+ entity: "note",
29
+ backend: "native",
30
+ fields: [
31
+ termField("about", "ref", 'about:"telegram:Kai Sample"', {
32
+ relation: "notes about it or linking it: <messenger>:<name or id> or a typed reference; stands alone",
33
+ }),
34
+ termField("source", "enum", "source:internal", { values: ["file", "internal"] }),
35
+ termField("text", "txt", "text:budget"),
36
+ ],
37
+ };
38
+ /** Over MCP `-` would read the server's own stdin, a path a file of this computer, and `--export` write anywhere. */
39
+ const refuseOverMcp = (options, mcp) => {
40
+ if (!mcp)
41
+ return;
42
+ if (options.textFile !== undefined)
43
+ throw new CliError("permission_error", "over MCP a note's text is given as text, never read from a file", {
44
+ param: "text_file",
45
+ });
46
+ if (options.export !== undefined)
47
+ throw new CliError("permission_error", "over MCP a note is not written as a file; the owner exports it", {
48
+ param: "export",
49
+ });
50
+ };
51
+ const textOf = (options, given) => {
52
+ const sources = [given, options.text, options.textFile].filter((value) => value !== undefined);
53
+ if (sources.length !== 1)
54
+ throw new CliError("validation_error", "give the text once: as an argument, --text or --text-file");
55
+ if (options.textFile !== undefined)
56
+ return readFileSync(options.textFile === "-" ? 0 : options.textFile, "utf8");
57
+ return sources[0];
58
+ };
59
+ /** `note:<id>`, `document:<id>`, or a file inside a configured folder. */
60
+ const noteOf = async (store, env, reference) => {
61
+ if (isNoteReference(reference))
62
+ return store.notes.note(reference);
63
+ await refuseBareNumber(store, reference, ["note", "document"], { path: true });
64
+ const { folder, path } = folderOfFile(await boundFolders(store, env, { strict: false }), reference);
65
+ const found = (await folderNotes(store, folder.id)).find((note) => note.path === path);
66
+ if (!found)
67
+ throw new CliError("not_found", `${reference} is not imported — files sync`, {
68
+ reason: "note.not-imported",
69
+ });
70
+ return found;
71
+ };
72
+ const notesCommandDefinition = (program, streams, env) => {
73
+ const { print } = answers(program, streams, env);
74
+ // The note's own export_path says where it was written; a file edited since is left as it is, and said so.
75
+ const exportedPath = ({ written, unchanged, edited }) => {
76
+ for (const { path } of edited)
77
+ streams.diagnostic(`Edited since export, left as it is: ${path}\n`);
78
+ return written[0] ?? unchanged[0] ?? edited[0]?.path ?? null;
79
+ };
80
+ const withNotes = (work) => withStore(env, async (store) => {
81
+ await importNotesMap(store, env, await boundFolders(store, env, { strict: false }));
82
+ return work(store);
83
+ });
84
+ const notes = program.command("notes").description("notes from your folders, and notes you write here");
85
+ annotate(notes.command("show"), { effects: LOCAL_READ, output: { entity: "note" } })
86
+ .description("one note: its text, tags, what it links and what links it")
87
+ .addHelpText("after", SAVE_HELP)
88
+ .argument("<note>", "note:<id>, document:<id>, or a file in a configured folder")
89
+ .action(async (reference, options) => {
90
+ const answer = await withNotes(async (store) => {
91
+ const note = await noteOf(store, env, reference);
92
+ const ref = note.ref;
93
+ return {
94
+ ...note,
95
+ ref,
96
+ tags: (await store.notes.noteTags(ref)).map(({ tag }) => tag),
97
+ links: (await store.notes.links({ from: ref })).map(({ to, targetText, kind, anchor }) => ({
98
+ to,
99
+ targetText,
100
+ kind,
101
+ anchor,
102
+ })),
103
+ backlinks: (await store.notes.links({ to: ref })).map(({ from, targetText, kind, anchor }) => ({
104
+ from,
105
+ targetText,
106
+ kind,
107
+ anchor,
108
+ })),
109
+ fingerprint: await citedFingerprint(store, ref),
110
+ };
111
+ });
112
+ print(options.json, itemAnswer(answer), [
113
+ `${answer.ref} ${answer.path ?? answer.title ?? ""}`.trimEnd(),
114
+ ` updated ${new Date(answer.updatedAt).toISOString().slice(0, 16).replace("T", " ")}${answer.tags.length ? ` tags: ${answer.tags.join(", ")}` : ""}`,
115
+ "",
116
+ answer.text,
117
+ ...(answer.links.length
118
+ ? ["", `links: ${answer.links.map(({ to, targetText }) => to ?? `${targetText} (not found)`).join(", ")}`]
119
+ : []),
120
+ ...(answer.backlinks.length ? [`linked from: ${answer.backlinks.map(({ from }) => from).join(", ")}`] : []),
121
+ ].join("\n"));
122
+ });
123
+ withQuery(annotate(notes.command("list"), { effects: LOCAL_READ }).description("notes, newest first"), NOTES_LIST_QUERY)
124
+ .option("--limit <n>", "most notes, at most 500", positive, 20)
125
+ .option("--page <n>", "which page, from 1", positive, 1)
126
+ .action(async (words, { json, ...paging }) => {
127
+ const terms = queryTerms(words, NOTES_LIST_QUERY, "notes list");
128
+ const about = terms.get("about");
129
+ const source = terms.get("source");
130
+ const search = terms.get("text");
131
+ if (about !== undefined && terms.size > 1)
132
+ throw new CliError("validation_error", "about: stands alone in notes list: its notes are found through links");
133
+ const options = { ...paging, json };
134
+ const page = await withNotes(async (store) => {
135
+ const found = await listNotes(store, {
136
+ limit: options.limit,
137
+ offset: (options.page - 1) * options.limit,
138
+ ...(about === undefined
139
+ ? { ...(source === undefined ? {} : { source }), ...(search === undefined ? {} : { search }) }
140
+ : { about: await subjectOf(store, about) }),
141
+ });
142
+ return found;
143
+ });
144
+ print(options.json, listAnswer("notes list", {
145
+ items: page.items,
146
+ limit: options.limit,
147
+ has_more: page.hasMore,
148
+ page: options.page,
149
+ ...(words.length === 0 ? {} : { args: { query: words.join(" ") } }),
150
+ }), page.items
151
+ .map((note) => `${note.ref} ${note.source}${note.via ? ` ${note.via}` : ""} ${note.path ?? note.title ?? note.text.split("\n")[0]}${note.anchors?.length ? ` ${note.anchors.join(" ")}` : ""}${note.linkText ? ` as "${note.linkText}"` : ""}`)
152
+ .join("\n") || "No notes.");
153
+ });
154
+ const noteAdd = annotate(notes.command("add"), {
155
+ effects: LOCAL_WRITE,
156
+ output: { entity: "note" },
157
+ literal_after_dashes: true,
158
+ })
159
+ .description("write a note of your own about messages, people, projects or other notes")
160
+ .argument("[text]", "the note; or --text, or --text-file")
161
+ .option("--text <text>", "the note")
162
+ .option("--text-file <path>", "read the note from a file; - reads stdin")
163
+ .option("--title <title>", "a title")
164
+ .option("--subject <ref>", "what it is about: <messenger>:<name or id>, msg:, chat:, person:, organization:, project:, task:, note:, document:, meeting:; repeat for more", collect)
165
+ .option("--meeting <id>", "also about this meeting, by its store id, with --account");
166
+ writeOptions(noteAdd, `the account of --meeting: ${MEETING_WRITE_HELP}`)
167
+ .option("--export [dir]", "also write it as a file — to this folder, or notes.export.dir")
168
+ .option("--format <format>", `the file's format: ${DIALECTS.join(", ")}`, formatOf)
169
+ .action(async (given, options, command) => {
170
+ refuseOverMcp(options, isMcpRun(command, env));
171
+ const body = textOf(options, given);
172
+ const value = writeAccountOf(options, (text) => streams.diagnostic(text));
173
+ if (options.meeting === undefined && value !== undefined)
174
+ throw new CliError("validation_error", "--account selects the account of --meeting");
175
+ const answer = await withNotes(async (store) => {
176
+ const about = await Promise.all((options.subject ?? []).map(async (subject) => (await subjectOf(store, subject)).ref));
177
+ if (options.meeting !== undefined)
178
+ about.push(await meetingReference(store, env, options.meeting, value === undefined ? {} : await oneAccountOf(store, env, value, "--account")));
179
+ const note = await store.notes.addNote({
180
+ text: body,
181
+ about,
182
+ ...(options.title === undefined ? {} : { title: options.title }),
183
+ });
184
+ if (options.export === undefined)
185
+ return note;
186
+ const target = exportTarget(loadConfig(env), options.export, options.format);
187
+ const exported = await exportInternal(store, { ...target, notes: [note] });
188
+ return { ...note, exportPath: exportedPath(exported) };
189
+ });
190
+ print(options.json, itemAnswer(answer), answer.ref);
191
+ });
192
+ annotate(notes.command("edit"), { effects: LOCAL_WRITE, output: { entity: "note" }, literal_after_dashes: true })
193
+ .description("change a note you wrote here; a file's note is edited in its file")
194
+ .argument("<id>", "note:<id>")
195
+ .requiredOption("--revision <n>", "its current revision, so an edit made meanwhile is not lost", positive)
196
+ .option("--text <text>", "the new text")
197
+ .option("--text-file <path>", "read the new text from a file; - reads stdin")
198
+ .option("--export [dir]", "also rewrite its file — in this folder, or notes.export.dir")
199
+ .option("--format <format>", `the file's format: ${DIALECTS.join(", ")}`, formatOf)
200
+ .action(async (id, options, command) => {
201
+ refuseOverMcp(options, isMcpRun(command, env));
202
+ const body = textOf(options);
203
+ const answer = await withNotes(async (store) => {
204
+ await refuseBareNumber(store, id, ["note"]);
205
+ const note = await store.notes.editNote(id.replace(/^note:/, ""), body, options.revision);
206
+ if (options.export === undefined)
207
+ return note;
208
+ const target = exportTarget(loadConfig(env), options.export, options.format);
209
+ return { ...note, exportPath: exportedPath(await exportInternal(store, { ...target, notes: [note] })) };
210
+ });
211
+ print(options.json, itemAnswer(answer), `${answer.ref} revision ${answer.revision}`);
212
+ });
213
+ annotate(notes.command("remove"), { effects: LOCAL_WRITE })
214
+ .description("delete a note you wrote here; a file it was exported to stays")
215
+ .argument("<id>", "note:<id>")
216
+ .action(async (id, options) => {
217
+ const answer = await withNotes(async (store) => {
218
+ await refuseBareNumber(store, id, ["note"]);
219
+ return store.notes.removeNote(id.replace(/^note:/, ""));
220
+ });
221
+ print(options.json, itemAnswer(answer), `note:${answer.id} removed`);
222
+ });
223
+ annotate(notes.command("export"), { effects: LOCAL_WRITE })
224
+ .description("write the notes you wrote here as files, never overwriting one you edited")
225
+ .option("--output-dir <dir>", "the folder to write to (default: notes.export.dir)")
226
+ .option("--format <format>", `the files' format: ${DIALECTS.join(", ")}`, formatOf)
227
+ .action(async (options) => {
228
+ const target = exportTarget(loadConfig(env), options.outputDir, options.format);
229
+ const result = await withNotes(async (store) => exportInternal(store, { ...target, notes: await internalNotes(store) }));
230
+ print(options.json, itemAnswer(result), [
231
+ `${result.dir}: ${result.written.length} written, ${result.unchanged.length} unchanged`,
232
+ ...result.edited.map(({ path }) => `Edited since export, left as it is: ${path}`),
233
+ ].join("\n"));
234
+ });
235
+ };
236
+ const citedFingerprint = async (store, ref) => {
237
+ const record = await store.contextRecords?.read(ref);
238
+ return record ? contextEvidenceFingerprint(record) : null;
239
+ };
240
+ export const notesCommand = notesCommandDefinition;
241
+ //# sourceMappingURL=command.js.map
@@ -0,0 +1,15 @@
1
+ /** A bare day in front matter is that day's midnight where the owner is, as a calendar app reads it. */
2
+ const BARE_DAY = /^(\d{4})-(\d{2})-(\d{2})$/;
3
+ const frontMatterTime = (frontMatter) => {
4
+ const value = frontMatter?.date;
5
+ if (value instanceof Date)
6
+ return value.getTime();
7
+ if (typeof value !== "string")
8
+ return undefined;
9
+ const day = BARE_DAY.exec(value.trim());
10
+ const time = day ? new Date(Number(day[1]), Number(day[2]) - 1, Number(day[3])).getTime() : Date.parse(value);
11
+ return Number.isFinite(time) ? time : undefined;
12
+ };
13
+ /** When a note file is dated: its front matter `date`, else the file's modification time — never the import. */
14
+ export const noteFileTime = (frontMatter, mtimeMs) => new Date(frontMatterTime(frontMatter) ?? mtimeMs).toISOString();
15
+ //# sourceMappingURL=dates.js.map
@@ -0,0 +1,79 @@
1
+ import { posix } from "node:path";
2
+ import { parse, stringify } from "yaml";
3
+ const FRONT_MATTER = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;
4
+ const REFERENCE = /^(msg|note|document|person|organization|project|task|chat|contact):\S+$/;
5
+ const BARE_REFERENCE = /(?<![\w/:])((?:msg|note|document|person|organization|project|task|chat|contact):[^\s<>()[\]"'`]+)/g;
6
+ const MAX_LINKS = 200;
7
+ export const isReference = (target) => REFERENCE.test(target);
8
+ export const splitFrontMatter = (text) => {
9
+ const match = FRONT_MATTER.exec(text);
10
+ if (!match)
11
+ return { frontMatter: {}, body: text };
12
+ let data;
13
+ try {
14
+ data = parse(match[1] ?? "");
15
+ }
16
+ catch {
17
+ data = null;
18
+ }
19
+ const frontMatter = data !== null && typeof data === "object" && !Array.isArray(data) ? data : {};
20
+ return { frontMatter: frontMatter, body: text.slice(match[0].length) };
21
+ };
22
+ const strings = (value) => typeof value === "string"
23
+ ? value
24
+ .split(/[,\s]+/)
25
+ .map((item) => item.trim())
26
+ .filter(Boolean)
27
+ : Array.isArray(value)
28
+ ? value.filter((item) => typeof item === "string").map((item) => item.trim())
29
+ : [];
30
+ export const frontMatterAliases = (frontMatter) => {
31
+ const value = frontMatter.aliases ?? frontMatter.alias;
32
+ return typeof value === "string" ? [value.trim()] : strings(value);
33
+ };
34
+ export const frontMatterTags = (frontMatter) => strings(frontMatter.tags ?? frontMatter.tag).map((tag) => tag.replace(/^#/, ""));
35
+ /** Code says what a reader typed into a fence, not what the note links to or is tagged with. */
36
+ export const withoutCode = (body) => body.replace(/^(```|~~~)[^\n]*\n[\s\S]*?^\1[^\n]*$/gm, "").replace(/`[^`\n]*`/g, "");
37
+ export const titleOf = (frontMatter, body, path) => {
38
+ if (typeof frontMatter.title === "string" && frontMatter.title.trim())
39
+ return frontMatter.title.trim();
40
+ const heading = /^#\s+(.+?)\s*#*\s*$/m.exec(withoutCode(body))?.[1];
41
+ return heading ?? posix.basename(path.replace(/\\/g, "/")).replace(/\.[^./]+$/, "");
42
+ };
43
+ export const dropNoteExtension = (target) => target.replace(/\.(md|markdown)$/i, "");
44
+ /** `msg:…` written in the text with no link syntax around it. */
45
+ export const bareReferences = (body) => [...body.matchAll(BARE_REFERENCE)].map((match) => ({
46
+ target: (match[1] ?? "").replace(/[.,;:!?]+$/, ""),
47
+ anchor: null,
48
+ label: null,
49
+ }));
50
+ export const dedupe = (links) => {
51
+ const seen = new Set();
52
+ return links
53
+ .filter((link) => {
54
+ const key = `${link.target}\u0000${link.anchor ?? ""}\u0000${link.label ?? ""}`;
55
+ if (seen.has(key))
56
+ return false;
57
+ seen.add(key);
58
+ return true;
59
+ })
60
+ .slice(0, MAX_LINKS);
61
+ };
62
+ export const parsedNote = (frontMatter, body, path, links, inlineTags = []) => ({
63
+ title: titleOf(frontMatter, body, path),
64
+ aliases: frontMatterAliases(frontMatter),
65
+ tags: [...new Set([...frontMatterTags(frontMatter), ...inlineTags])],
66
+ links: dedupe(links),
67
+ frontMatter,
68
+ });
69
+ export const renderNote = (note, link) => {
70
+ const frontMatter = {
71
+ ...note.frontMatter,
72
+ ...(note.aliases.length ? { aliases: note.aliases } : {}),
73
+ ...(note.tags.length ? { tags: note.tags } : {}),
74
+ };
75
+ const head = Object.keys(frontMatter).length ? `---\n${stringify(frontMatter).trimEnd()}\n---\n` : "";
76
+ const links = note.links.length ? `\n\n${note.links.map((item) => `- ${link(item)}`).join("\n")}` : "";
77
+ return `${head}# ${note.title}\n\n${note.text.trimEnd()}${links}\n`;
78
+ };
79
+ //# sourceMappingURL=common.js.map
@@ -0,0 +1,6 @@
1
+ import { markdown } from "./markdown.js";
2
+ import { obsidian } from "./obsidian.js";
3
+ const BY_NAME = { obsidian, markdown };
4
+ export const dialectOf = (name = "obsidian") => BY_NAME[name];
5
+ export { DIALECTS } from "./types.js";
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,51 @@
1
+ import { NOTE_EXTENSIONS } from "../files.js";
2
+ import { bareReferences, dropNoteExtension, isReference, parsedNote, renderNote, splitFrontMatter, withoutCode, } from "./common.js";
3
+ const LINK = /(?<!!)\[([^\]\n]*)\]\(\s*(<[^>\n]+>|[^)\s]+)(?:\s+"[^"\n]*")?\s*\)/g;
4
+ const SCHEME = /^[a-z][a-z0-9+.-]*:/i;
5
+ const decode = (value) => {
6
+ try {
7
+ return decodeURIComponent(value);
8
+ }
9
+ catch {
10
+ return value;
11
+ }
12
+ };
13
+ const linkOf = (label, destination) => {
14
+ const angled = destination.startsWith("<") && destination.endsWith(">");
15
+ const raw = angled ? destination.slice(1, -1) : destination;
16
+ if (isReference(raw))
17
+ return { target: raw, anchor: null, label: label.trim() || null };
18
+ if (SCHEME.test(raw))
19
+ return null;
20
+ const hash = raw.indexOf("#");
21
+ const path = hash < 0 ? raw : raw.slice(0, hash);
22
+ const fragment = hash < 0 ? null : raw.slice(hash + 1);
23
+ return {
24
+ target: dropNoteExtension(angled ? path : decode(path)).trim(),
25
+ anchor: fragment === null ? null : `#${angled ? fragment : decode(fragment)}`,
26
+ label: label.trim() || null,
27
+ };
28
+ };
29
+ /** `[label](path.md#Heading)` and `[label](person:…)`; web links are not notes and are left out. */
30
+ export const markdownLinks = (body) => [...withoutCode(body).matchAll(LINK)]
31
+ .map((match) => linkOf(match[1] ?? "", match[2] ?? ""))
32
+ .filter((link) => link !== null);
33
+ export const stripMarkdownLinks = (body) => body.replace(LINK, " ");
34
+ const hasOwnExtension = (target) => NOTE_EXTENSIONS.some((extension) => target.toLowerCase().endsWith(extension));
35
+ export const markdownLink = (link) => {
36
+ if (isReference(link.target))
37
+ return `[${link.label ?? link.target}](${link.target})`;
38
+ const file = hasOwnExtension(link.target) ? link.target : `${link.target}.md`;
39
+ const label = link.label ?? link.target.split("/").pop() ?? link.target;
40
+ return `[${label}](<${file}${link.anchor ?? ""}>)`;
41
+ };
42
+ export const markdown = {
43
+ name: "markdown",
44
+ parse(text, path) {
45
+ const { frontMatter, body } = splitFrontMatter(text);
46
+ const links = markdownLinks(body);
47
+ return parsedNote(frontMatter, body, path, [...links, ...bareReferences(withoutCode(stripMarkdownLinks(body)))]);
48
+ },
49
+ render: (note) => renderNote(note, markdownLink),
50
+ };
51
+ //# sourceMappingURL=markdown.js.map
@@ -0,0 +1,33 @@
1
+ import { bareReferences, dropNoteExtension, isReference, parsedNote, renderNote, splitFrontMatter, withoutCode, } from "./common.js";
2
+ import { markdownLink, markdownLinks, stripMarkdownLinks } from "./markdown.js";
3
+ const WIKI = /!?\[\[([^\]|\n]+)(?:\|([^\]\n]*))?\]\]/g;
4
+ const TAG = /(?<![\p{L}\p{N}_#&/])#([\p{L}_][\p{L}\p{N}_/-]*)/gu;
5
+ export const wikiLinks = (body) => [...withoutCode(body).matchAll(WIKI)].map((match) => {
6
+ const raw = (match[1] ?? "").trim();
7
+ const label = match[2]?.trim() || null;
8
+ if (isReference(raw))
9
+ return { target: raw, anchor: null, label };
10
+ const split = raw.search(/[#^]/);
11
+ return {
12
+ target: dropNoteExtension(split < 0 ? raw : raw.slice(0, split)).trim(),
13
+ anchor: split < 0 ? null : raw.slice(split),
14
+ label,
15
+ };
16
+ });
17
+ /** Obsidian reads `#tag` anywhere in the text except code, links and headings. */
18
+ export const inlineTags = (body) => [
19
+ ...new Set([...stripMarkdownLinks(withoutCode(body).replace(WIKI, " ")).matchAll(TAG)].map((match) => match[1] ?? "")),
20
+ ];
21
+ const wikiLink = (link) => isReference(link.target)
22
+ ? markdownLink(link)
23
+ : `[[${link.target}${link.anchor ?? ""}${link.label ? `|${link.label}` : ""}]]`;
24
+ export const obsidian = {
25
+ name: "obsidian",
26
+ parse(text, path) {
27
+ const { frontMatter, body } = splitFrontMatter(text);
28
+ const rest = stripMarkdownLinks(withoutCode(body).replace(WIKI, " "));
29
+ return parsedNote(frontMatter, body, path, [...wikiLinks(body), ...markdownLinks(body), ...bareReferences(rest)], inlineTags(body));
30
+ },
31
+ render: (note) => renderNote(note, wikiLink),
32
+ };
33
+ //# sourceMappingURL=obsidian.js.map
@@ -0,0 +1,2 @@
1
+ export const DIALECTS = ["obsidian", "markdown"];
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1,97 @@
1
+ import { existsSync, readdirSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { isCliError } from "@wirecat/cli-base";
4
+ import { chosenTextModel, embedNotes as embedNoteChunksOf, sharedModelsDirectory, textModels, } from "@wirecat/cli-core";
5
+ import { APP } from "../app.js";
6
+ /** About three chunks a second with e5-small on this laptop (2026-10-06): a run stays near three minutes, under a five-minute timer, and the next resumes. */
7
+ const EMBED_PER_RUN = 600;
8
+ /** The model EMBED_PER_RUN was measured with; no longer the default, so it is named here. */
9
+ const MEASURED_WITH = "e5-small";
10
+ /** A model of unknown speed is taken to be as slow as EmbeddingGemma, so a timer run still ends in time. */
11
+ const SLOWEST_KNOWN = 2;
12
+ /** The run's bound for the chosen model: a slower model embeds fewer chunks in the same three minutes. */
13
+ const embedPerRun = (env = process.env) => {
14
+ const models = textModels(env);
15
+ const speed = (id) => models.find((model) => model.id === id)?.chunksPerSecond ?? SLOWEST_KNOWN;
16
+ const ratio = speed(chosenTextModel(env).id) / speed(MEASURED_WITH);
17
+ return Math.max(8, Math.min(EMBED_PER_RUN, Math.round(EMBED_PER_RUN * ratio)));
18
+ };
19
+ /** The model the error names, and the exact command that downloads it. */
20
+ const missingModel = (error, env) => {
21
+ const named = isCliError(error) ? error.details.model : undefined;
22
+ const id = typeof named === "string" ? named : chosenTextModel(env).id;
23
+ return `the ${id} model is not downloaded — wcat models download ${id}`;
24
+ };
25
+ /** Whether the chosen text model is downloaded; an unreadable model choice counts as missing, and doctor names it. */
26
+ export const searchModelPresent = (env) => {
27
+ try {
28
+ const path = join(sharedModelsDirectory("text", env), chosenTextModel(env).id);
29
+ return existsSync(path) && readdirSync(path).length > 0;
30
+ }
31
+ catch {
32
+ return false;
33
+ }
34
+ };
35
+ const isMissingModel = (error) => isCliError(error) && error.details.reason === "model.not-downloaded";
36
+ const reportOf = (run) => {
37
+ if (run === undefined)
38
+ return undefined;
39
+ if (!("provider" in run))
40
+ return {
41
+ status: "failed",
42
+ sent: 0,
43
+ enriched: 0,
44
+ failed: 0,
45
+ left: 0,
46
+ inputTokens: 0,
47
+ outputTokens: 0,
48
+ costUsd: 0,
49
+ reason: run.reason,
50
+ reasonId: run.reason_id,
51
+ };
52
+ return {
53
+ status: run.status,
54
+ provider: run.provider,
55
+ model: run.model,
56
+ sent: run.enriched + run.failed,
57
+ enriched: run.enriched,
58
+ failed: run.failed,
59
+ left: run.left,
60
+ inputTokens: run.usage.input,
61
+ outputTokens: run.usage.output,
62
+ costUsd: run.cost_usd,
63
+ ...(run.reason === undefined ? {} : { reason: run.reason }),
64
+ ...(run.reason_id === undefined ? {} : { reasonId: run.reason_id }),
65
+ };
66
+ };
67
+ /**
68
+ * Embeds the notes' chunks that have no vector yet, for search by meaning. Bounded like mail, so a
69
+ * timer run stays short and the next continues. A missing model is reported, never downloaded.
70
+ */
71
+ export const embedNoteChunks = async (store, { embed = true, env, maxChunks = embedPerRun(env), keyring, } = {}) => {
72
+ if (!embed)
73
+ return { chunks: 0, left: true, notEmbedded: "embedding is off" };
74
+ try {
75
+ const done = await embedNoteChunksOf(store, {
76
+ maxChunks,
77
+ command: APP.command,
78
+ app: APP,
79
+ ...(env === undefined ? {} : { env }),
80
+ ...(keyring ? { keyring } : {}),
81
+ });
82
+ const enrichment = reportOf(done.enrichment);
83
+ return { chunks: done.embedded, left: done.left, ...(enrichment ? { enrichment } : {}) };
84
+ }
85
+ catch (error) {
86
+ if (!isMissingModel(error))
87
+ throw error;
88
+ const enrichment = isCliError(error) ? reportOf(error.details.enrichment) : undefined;
89
+ return {
90
+ chunks: 0,
91
+ left: true,
92
+ notEmbedded: missingModel(error, env),
93
+ ...(enrichment ? { enrichment } : {}),
94
+ };
95
+ }
96
+ };
97
+ //# sourceMappingURL=embed.js.map
@@ -0,0 +1,76 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { readMemoId } from "./files.js";
5
+ const HASH_LINE = /^memo-hash: .*\r?\n/m;
6
+ const PLACEHOLDER = "f".repeat(64);
7
+ const UNSAFE = /[\\/:*?"<>|#^[\]\p{Cc}]/gu;
8
+ const MAX_NAME = 120;
9
+ const sha256 = (text) => createHash("sha256").update(text).digest("hex");
10
+ /**
11
+ * The hash covers the file minus its own `memo-hash` line, so a file can prove it is still what files
12
+ * wrote without files keeping any record of its own.
13
+ */
14
+ const withHash = (content) => {
15
+ const hash = sha256(content.replace(HASH_LINE, ""));
16
+ return content.replace(`memo-hash: ${PLACEHOLDER}`, `memo-hash: ${hash}`);
17
+ };
18
+ export const editedSinceExport = (content) => {
19
+ const stored = /^memo-hash: ([0-9a-f]{64})$/m.exec(content)?.[1];
20
+ return stored === undefined || sha256(content.replace(HASH_LINE, "")) !== stored;
21
+ };
22
+ const fileName = (title, id, taken) => {
23
+ const base = title.replace(UNSAFE, " ").replace(/\s+/g, " ").trim().slice(0, MAX_NAME) || id;
24
+ const plain = `${base}.md`;
25
+ return taken(plain) ? `${base} (${id.slice(-8)}).md` : plain;
26
+ };
27
+ const exportedIn = (dir) => {
28
+ const found = new Map();
29
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
30
+ if (!entry.isFile() || !/\.(md|markdown)$/i.test(entry.name))
31
+ continue;
32
+ const id = readMemoId(join(dir, entry.name));
33
+ if (id !== null)
34
+ found.set(id, entry.name);
35
+ }
36
+ return found;
37
+ };
38
+ /**
39
+ * Writes each note to `dir` in `dialect`'s format. A file keeps its name across exports (found by its
40
+ * `memo-id`), is rewritten only while it is still what files wrote, and a file files did not write is never
41
+ * touched. Nothing is deleted.
42
+ */
43
+ export const exportNotes = ({ dir, dialect, notes, }) => {
44
+ mkdirSync(dir, { recursive: true });
45
+ const existing = exportedIn(dir);
46
+ const claimed = new Set(existing.values());
47
+ const result = { dir, written: [], unchanged: [], edited: [] };
48
+ for (const { id, ...note } of notes) {
49
+ const frontMatter = { "memo-id": id, "memo-hash": PLACEHOLDER, ...note.frontMatter };
50
+ frontMatter["memo-id"] = id;
51
+ frontMatter["memo-hash"] = PLACEHOLDER;
52
+ const content = withHash(dialect.render({ ...note, frontMatter }));
53
+ const known = existing.get(id);
54
+ const name = known ?? fileName(note.title, id, (candidate) => claimed.has(candidate) || existsSync(join(dir, candidate)));
55
+ claimed.add(name);
56
+ const path = join(dir, name);
57
+ if (known !== undefined) {
58
+ const current = readFileSync(path, "utf8");
59
+ if (editedSinceExport(current)) {
60
+ result.edited.push({ path, id });
61
+ continue;
62
+ }
63
+ if (current === content) {
64
+ result.unchanged.push(path);
65
+ continue;
66
+ }
67
+ }
68
+ // Hidden, so an import running meanwhile never lists a half-written file.
69
+ const partial = join(dir, `.${name}.files-tmp`);
70
+ writeFileSync(partial, content);
71
+ renameSync(partial, path);
72
+ result.written.push(path);
73
+ }
74
+ return result;
75
+ };
76
+ //# sourceMappingURL=export.js.map