@wirecat/cli-core 0.665.0 → 0.666.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 (31) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/cli/documents/catalog.d.ts +87 -0
  3. package/dist/cli/documents/catalog.js +246 -0
  4. package/dist/cli/documents/documents.d.ts +32 -0
  5. package/dist/cli/documents/documents.js +76 -0
  6. package/dist/cli/documents/folders.d.ts +22 -0
  7. package/dist/cli/documents/folders.js +45 -0
  8. package/dist/cli/documents/index.d.ts +36 -0
  9. package/dist/cli/documents/index.js +32 -0
  10. package/dist/cli/documents/knowledge.d.ts +36 -0
  11. package/dist/cli/documents/knowledge.js +235 -0
  12. package/dist/cli/documents/mirrors.d.ts +46 -0
  13. package/dist/cli/documents/mirrors.js +198 -0
  14. package/dist/cli/documents/queries.d.ts +120 -0
  15. package/dist/cli/documents/queries.js +156 -0
  16. package/dist/cli/documents/search.d.ts +25 -0
  17. package/dist/cli/documents/search.js +34 -0
  18. package/dist/cli/documents/sync.d.ts +31 -0
  19. package/dist/cli/documents/sync.js +41 -0
  20. package/dist/cli/documents/testing/commands-contract.d.ts +35 -0
  21. package/dist/cli/documents/testing/commands-contract.js +205 -0
  22. package/dist/cli/documents/testing/index.d.ts +3 -0
  23. package/dist/cli/documents/testing/index.js +3 -0
  24. package/dist/cli/documents/testing/source-contract.d.ts +18 -0
  25. package/dist/cli/documents/testing/source-contract.js +112 -0
  26. package/dist/cli/documents/testing/source.d.ts +13 -0
  27. package/dist/cli/documents/testing/source.js +67 -0
  28. package/dist/cli/documents/words.d.ts +87 -0
  29. package/dist/cli/documents/words.js +79 -0
  30. package/dist/errors/reasons.js +15 -2
  31. package/package.json +9 -1
package/CHANGELOG.md CHANGED
@@ -5,6 +5,43 @@ 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.666.0 — 15.11.2026
9
+
10
+ ### Added
11
+
12
+ - **Shared documents commands, in `@wirecat/cli-core/documents/cli`.** `addDocumentCommands(program, options)` mounts
13
+ `folders add|list|remove`, `sync`, `status`, `documents list|show|export|context`, `search`, `catalog`, `tags`,
14
+ `relationships`, `notes`, `memories`, `facts`, `identities` and `mirrors` over the CLI's own ports, so every
15
+ documents and wiki CLI has the same commands, options and answers. One builder per group
16
+ (`addDocumentFolderCommands`, `addDocumentSyncCommands`, `addLocalDocumentCommands`, `addDocumentSearchCommand`,
17
+ `addDocumentCatalogCommands`, `addDocumentKnowledgeCommands`, `addDocumentMirrorCommands`) lets a CLI put its own
18
+ groups between them, and each honours a global `--dry-run`. `words` names the CLI and its provider: the remote
19
+ side's word (`mirrors sync --keep local|<remote>|both`, `identities link <remote>-id`), and the store provider an
20
+ issue names. The answers use the same entities and fields in every CLI: `document` in the `imported` and `catalog`
21
+ views, `document_tag`, `document_relationship`, `document_identity` (`remote_id`, `provider`, `role`, `person`),
22
+ `selected_folder` and `mirror`. The `documents` group the builders return takes the CLI's live subcommands (`get`,
23
+ `create`, …), and `folders` takes its own `browse` outside the shared contract. drive-cli's commands, moved here
24
+ ([DOCUMENTS.md](docs/dev/DOCUMENTS.md#shared-commands)).
25
+ - **`catalog tree` reads only what it shows.** Each shown entry's children come from the store by parent, 1 000 a
26
+ page, and the branches cut at `--depth` are checked 200 at a time. Any entry with children can be a root or a
27
+ branch, so a page with sub-pages works. An entry in two folders is shown in full once and marked `repeated` at its
28
+ other place. Over 10 000 entries the answer is `catalog.tree-limit`, which says to name a smaller folder or lower
29
+ `--depth`.
30
+ - **A documents contract kit, in `@wirecat/cli-core/documents/testing`.** `documentSourceContract` checks a
31
+ `DocumentSource` adapter: identity, the folder walk, content and bytes, the change feed with a change in it
32
+ (`change`), `not_found`, and pages that are folders and documents at once (`isDocument`).
33
+ `documentCommandsContract` checks a CLI's shared commands over its fakes: every shared path mounted, still
34
+ cli-core's and not overridden, its effects, the remote word, and sync → list → show → search, tags and notes by id.
35
+ `fakeDocumentSource` is a provider in memory.
36
+
37
+ ### Changed — may break callers
38
+
39
+ - **The shared documents commands' error reasons are cli-core's.** `catalog.unavailable`, `catalog.not-found`,
40
+ `catalog.depth-invalid`, `catalog.cycle`, `catalog.tree-limit`, `mirror.none`, `mirror.not-found`,
41
+ `mirror.not-folder`, `export.exists` and `listing.too-large`. An app that lists one of them under the same code
42
+ still starts, as a CLI released before the move does. An app that lists one under another code fails at start.
43
+ - **`sync.partial` names no provider:** "some sources did not sync; the next sync retries them".
44
+
8
45
  ## 0.665.0 — 14.11.2026
9
46
 
10
47
  ### Added
@@ -0,0 +1,87 @@
1
+ import type { Command } from "commander";
2
+ import { type CatalogEntry, type CatalogQuery } from "../../store/index.js";
3
+ import { type Body } from "../envelope.js";
4
+ import type { DocumentKnowledgePort } from "./knowledge.js";
5
+ import { type DocumentWords } from "./words.js";
6
+ /** The selected profile's catalog in the shared store, as the CLI binds it to its account. */
7
+ export interface DocumentCatalog {
8
+ import(principal: string): Promise<{
9
+ entries: number;
10
+ retired: number;
11
+ }>;
12
+ get(principal: string, id: string): Promise<CatalogEntry | undefined>;
13
+ list(principal: string, query?: CatalogQuery): Promise<{
14
+ items: CatalogEntry[];
15
+ hasMore: boolean;
16
+ }>;
17
+ }
18
+ export interface DocumentCatalogStores {
19
+ catalog?: DocumentCatalog;
20
+ knowledge?: Pick<DocumentKnowledgePort, "tags">;
21
+ }
22
+ export interface DocumentCatalogCommands {
23
+ words: DocumentWords;
24
+ output(body: Body): void;
25
+ /**
26
+ * Opens the selected profile's store for one command. `write` is true for `catalog import` and tag changes: the CLI
27
+ * then holds the lock its sync takes, and checks it is still held before and after `fn`.
28
+ */
29
+ run<T>(fn: (stores: DocumentCatalogStores, principal: string) => Promise<T>, write: boolean): Promise<T>;
30
+ /** The provider's id of a file or folder the user names by id or URL. */
31
+ id(input: string): string;
32
+ /** The chosen folders: what `catalog tree` shows without a folder. */
33
+ roots(): string[];
34
+ }
35
+ export interface CatalogTree {
36
+ item: Pick<CatalogEntry, "ref" | "name" | "kind" | "url" | "content"> & {
37
+ id: string;
38
+ };
39
+ children: CatalogTree[];
40
+ truncated: boolean;
41
+ /** The entry is already in this answer (a file in two folders): its children are shown at its first place. */
42
+ repeated?: true;
43
+ }
44
+ /** How many entries one `catalog tree` answer holds before it asks for a smaller folder or depth. */
45
+ export declare const CATALOG_TREE_LIMIT = 10000;
46
+ /** Reads one profile's catalog for `catalog tree`: an entry by its external id, and one page of its children. */
47
+ export interface CatalogTreeSource {
48
+ get(externalId: string): Promise<CatalogEntry | undefined>;
49
+ children(externalId: string, page: {
50
+ limit: number;
51
+ offset: number;
52
+ }): Promise<{
53
+ items: CatalogEntry[];
54
+ hasMore: boolean;
55
+ }>;
56
+ /** Which of these entries have children, in one read; the tree asks each one when absent. */
57
+ withChildren?(externalIds: string[]): Promise<Set<string>>;
58
+ }
59
+ /** The tree's reads through the CLI's catalog, which takes ids without the `.md` the store's entries carry. */
60
+ export declare const catalogSource: (catalog: Pick<DocumentCatalog, "get" | "list">, principal: string) => CatalogTreeSource;
61
+ /**
62
+ * Builds the tree by reading each shown entry's children from the store, page by page, so what it holds is what it
63
+ * answers. Any entry can have children: a page with sub-pages is a `file`.
64
+ */
65
+ export declare const catalogTree: (source: CatalogTreeSource, roots: string[], depth: number, limit?: number) => Promise<CatalogTree[]>;
66
+ export declare const catalogId: (entry: Pick<CatalogEntry, "externalId">) => string;
67
+ export declare const catalogOutput: (entry: CatalogEntry) => {
68
+ id: string;
69
+ ref: string;
70
+ kind: "file" | "folder";
71
+ name: string;
72
+ parents: string[];
73
+ url: string | undefined;
74
+ mime: string | undefined;
75
+ size: number | undefined;
76
+ created_at: string | undefined;
77
+ modified_at: string | undefined;
78
+ observed_at: string;
79
+ description: string | undefined;
80
+ actors: import("../../store/index.js").CatalogActor[] | undefined;
81
+ provider_metadata: unknown;
82
+ active: boolean;
83
+ content: "indexed" | "metadata" | "unreadable";
84
+ };
85
+ export declare const CATALOG_FIELDS: string[];
86
+ /** `catalog import|show|list|search|tree|tags` over the selected profile's files and folders in the shared store. */
87
+ export declare const addDocumentCatalogCommands: (program: Command, helpers: DocumentCatalogCommands) => void;
@@ -0,0 +1,246 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { annotate, sharedCommand } from "@wirecat/cli-base/commands";
3
+ import { parseLucene, validateQuery } from "@wirecat/cli-base/query";
4
+ import { CATALOG_QUERY } from "../../store/index.js";
5
+ import { honoursDryRun } from "../dry-run-guard.js";
6
+ import { LOCAL_READ, LOCAL_WRITE } from "../effects.js";
7
+ import { itemOf, listOf } from "../envelope.js";
8
+ import { bindQuery, documentQueries, tagRow, termsOf } from "./queries.js";
9
+ import { allOf, examples, nonnegative, positive, wordsOf } from "./words.js";
10
+ /** How many entries one `catalog tree` answer holds before it asks for a smaller folder or depth. */
11
+ export const CATALOG_TREE_LIMIT = 10_000;
12
+ const CATALOG_PAGE = 1000;
13
+ const PARENT_BATCH = 200;
14
+ /** `parent:a OR parent:b …` over ids as they are: the values go into a parsed template, so none needs escaping. */
15
+ const anyParent = (ids) => {
16
+ const ast = parseLucene(Array.from({ length: Math.max(2, ids.length) }, () => "parent:x").join(" OR "), {
17
+ defaultField: "none",
18
+ });
19
+ const clauses = ast.root.clauses;
20
+ clauses.forEach((clause, i) => {
21
+ clause.node.value = ids[Math.min(i, ids.length - 1)];
22
+ });
23
+ return validateQuery(ast, CATALOG_QUERY);
24
+ };
25
+ /** The tree's reads through the CLI's catalog, which takes ids without the `.md` the store's entries carry. */
26
+ export const catalogSource = (catalog, principal) => ({
27
+ get: (externalId) => catalog.get(principal, catalogId({ externalId })),
28
+ children: (externalId, page) => catalog.list(principal, { parent: catalogId({ externalId }), ...page }),
29
+ // Each read scans the account's catalog, so the branches cut at the depth are asked about 200 at a time.
30
+ withChildren: async (externalIds) => {
31
+ const found = new Set();
32
+ for (let start = 0; start < externalIds.length; start += PARENT_BATCH) {
33
+ const batch = new Set(externalIds.slice(start, start + PARENT_BATCH));
34
+ const ast = anyParent([...batch].map((externalId) => catalogId({ externalId })));
35
+ for (let offset = 0;; offset += CATALOG_PAGE) {
36
+ const page = await catalog.list(principal, { ast, limit: CATALOG_PAGE, offset });
37
+ for (const item of page.items)
38
+ for (const parent of item.parents)
39
+ if (batch.delete(parent))
40
+ found.add(parent);
41
+ if (!page.hasMore || batch.size === 0)
42
+ break;
43
+ }
44
+ }
45
+ return found;
46
+ },
47
+ });
48
+ const tooLarge = (limit) => new CliError("validation_error", `the tree is over ${limit} entries; name a smaller FOLDER or lower --depth`, {
49
+ reason: "catalog.tree-limit",
50
+ });
51
+ /**
52
+ * Builds the tree by reading each shown entry's children from the store, page by page, so what it holds is what it
53
+ * answers. Any entry can have children: a page with sub-pages is a `file`.
54
+ */
55
+ export const catalogTree = async (source, roots, depth, limit = CATALOG_TREE_LIMIT) => {
56
+ if (!Number.isSafeInteger(depth) || depth < 0 || depth > 50)
57
+ throw new CliError("validation_error", "tree depth must be between 0 and 50", { reason: "catalog.depth-invalid" });
58
+ let nodes = 0;
59
+ const seen = new Set();
60
+ const cut = [];
61
+ const cutIds = [];
62
+ const hasChildren = async (externalId) => (await source.children(externalId, { limit: 1, offset: 0 })).items.length > 0;
63
+ const childrenOf = async (externalId) => {
64
+ const items = [];
65
+ for (let offset = 0;; offset += CATALOG_PAGE) {
66
+ const page = await source.children(externalId, { limit: CATALOG_PAGE, offset });
67
+ for (const item of page.items)
68
+ items.push(item);
69
+ if (nodes + items.length > limit)
70
+ throw tooLarge(limit);
71
+ if (!page.hasMore)
72
+ return items;
73
+ }
74
+ };
75
+ const node = async (entry, level, ancestors) => {
76
+ if (ancestors.has(entry.externalId))
77
+ throw new CliError("invalid_response", "local folder ancestry contains a cycle", { reason: "catalog.cycle" });
78
+ if (++nodes > limit)
79
+ throw tooLarge(limit);
80
+ const tree = {
81
+ item: {
82
+ id: catalogId(entry),
83
+ ref: entry.ref,
84
+ name: entry.name,
85
+ kind: entry.kind,
86
+ url: entry.url,
87
+ content: entry.content,
88
+ },
89
+ children: [],
90
+ truncated: false,
91
+ };
92
+ if (seen.has(entry.externalId))
93
+ return { ...tree, repeated: true };
94
+ seen.add(entry.externalId);
95
+ if (level >= depth) {
96
+ cut.push(tree);
97
+ cutIds.push(entry.externalId);
98
+ return tree;
99
+ }
100
+ const next = new Set(ancestors).add(entry.externalId);
101
+ for (const child of await childrenOf(entry.externalId))
102
+ tree.children.push(await node(child, level + 1, next));
103
+ return tree;
104
+ };
105
+ const trees = [];
106
+ for (const id of roots) {
107
+ const entry = await source.get(id);
108
+ if (!entry || (entry.kind !== "folder" && !(await hasChildren(entry.externalId))))
109
+ throw new CliError("not_found", "no folder or page with sub-pages by that id in the active local catalog", {
110
+ reason: "catalog.not-found",
111
+ });
112
+ trees.push(await node(entry, 0, new Set()));
113
+ }
114
+ const parents = source.withChildren
115
+ ? await source.withChildren(cutIds)
116
+ : new Set((await Promise.all(cutIds.map(async (id) => ((await hasChildren(id)) ? id : "")))).filter(Boolean));
117
+ cut.forEach((tree, i) => {
118
+ tree.truncated = parents.has(cutIds[i]);
119
+ });
120
+ return trees;
121
+ };
122
+ export const catalogId = (entry) => entry.externalId.replace(/\.md$/, "");
123
+ export const catalogOutput = (entry) => ({
124
+ id: catalogId(entry),
125
+ ref: entry.ref,
126
+ kind: entry.kind,
127
+ name: entry.name,
128
+ parents: entry.parents.map((id) => id.replace(/\.md$/, "")),
129
+ url: entry.url,
130
+ mime: entry.mime,
131
+ size: entry.size,
132
+ created_at: entry.createdAt,
133
+ modified_at: entry.modifiedAt,
134
+ observed_at: entry.observedAt,
135
+ description: entry.description,
136
+ actors: entry.actors,
137
+ provider_metadata: entry.metadata,
138
+ active: entry.active,
139
+ content: entry.content,
140
+ });
141
+ // Keep field selection tied to the provider view, including future additions to that view.
142
+ export const CATALOG_FIELDS = Object.keys({
143
+ id: true,
144
+ ref: true,
145
+ kind: true,
146
+ name: true,
147
+ parents: true,
148
+ url: true,
149
+ mime: true,
150
+ size: true,
151
+ created_at: true,
152
+ modified_at: true,
153
+ observed_at: true,
154
+ description: true,
155
+ actors: true,
156
+ provider_metadata: true,
157
+ active: true,
158
+ content: true,
159
+ });
160
+ const local = (command, mutates = false) => annotate(command, { effects: mutates ? LOCAL_WRITE : LOCAL_READ });
161
+ const addDocumentCatalogCommandsDefinition = (program, helpers) => {
162
+ const { output } = helpers;
163
+ const wording = wordsOf(helpers.words);
164
+ const { prefix, text } = wording;
165
+ const queries = documentQueries();
166
+ const view = "catalog";
167
+ const catalog = local(program.command("catalog")).description(text.catalog);
168
+ const run = (fn, write = false) => helpers.run(async (index, principal) => {
169
+ if (!index.catalog)
170
+ throw new CliError("configuration_error", "index has no shared catalog adapter", {
171
+ reason: "catalog.unavailable",
172
+ });
173
+ return fn({ ...index, catalog: index.catalog }, principal);
174
+ }, write);
175
+ const entry = async (index, principal, id) => {
176
+ const found = await index.catalog?.get(principal, helpers.id(id));
177
+ if (!found)
178
+ throw new CliError("not_found", "file or folder is not in the active local catalog; run catalog import or sync", {
179
+ reason: "catalog.not-found",
180
+ });
181
+ return found;
182
+ };
183
+ examples(local(catalog.command("import").description("put cached file and folder metadata into the shared database"), true), [`${prefix} catalog import --offline`]).action(async () => output(itemOf(await run((index, principal) => index.catalog.import(principal), true))));
184
+ examples(annotate(local(catalog.command("show").description("show stored metadata and the stable file or folder reference")), {
185
+ output: { entity: "document", view },
186
+ }), [`${prefix} catalog show FILE_ID --offline`])
187
+ .argument("<file>", text.catalogArgument)
188
+ .action(async (id) => output(itemOf(await run(async (index, principal) => catalogOutput(await entry(index, principal, id))))));
189
+ const list = async (terms, args, search) => {
190
+ const ast = terms.length
191
+ ? validateQuery(parseLucene(terms.join(" "), { defaultField: search ? "text" : "none" }), CATALOG_QUERY)
192
+ : undefined;
193
+ const result = await run((index, principal) => index.catalog.list(principal, { ast, limit: args.limit, offset: (args.page - 1) * args.limit }));
194
+ output(listOf(`catalog ${search ? "search" : "list"}`, {
195
+ items: result.items.map(catalogOutput),
196
+ limit: args.limit,
197
+ has_more: result.hasMore,
198
+ page: args.page,
199
+ args: { query: terms.length ? terms.join(" ") : undefined },
200
+ }));
201
+ };
202
+ for (const action of ["list", "search"]) {
203
+ const command = examples(local(catalog
204
+ .command(action)
205
+ .description(action === "list"
206
+ ? "list cached files and folders using metadata queries"
207
+ : "search cached names, descriptions, types and observed people")), [
208
+ action === "list"
209
+ ? `${prefix} catalog list "parent:FOLDER_ID AND kind:file" --offline`
210
+ : `${prefix} catalog search "budget AND person:Rin*" --offline`,
211
+ ])
212
+ .argument(action === "list" ? "[query...]" : "<query...>", "metadata query: kind, mime, name, parent, person, tag; AND, OR, NOT")
213
+ .option("--limit <n>", "how many entries to return (at most 1000)", positive, 50)
214
+ .option("--page <n>", "which page to return", positive, 1)
215
+ .action(async (terms, args) => list(terms, args, action === "search"));
216
+ annotate(command, { query: CATALOG_QUERY, output: { entity: "document", view } });
217
+ }
218
+ examples(local(catalog.command("tree").description("show the cached hierarchy below a folder or all selected roots")), [`${prefix} catalog tree --offline`, `${prefix} catalog tree FOLDER_ID --depth 3 --offline`])
219
+ .argument("[folder]", text.treeArgument)
220
+ .option("--depth <n>", "maximum descendant depth, from 0 to 50", nonnegative, 5)
221
+ .action(async (id, args) => output(await run(async (index, principal) => {
222
+ const roots = id ? [helpers.id(id)] : helpers.roots();
223
+ const tree = await catalogTree(catalogSource(index.catalog, principal), roots.map((root) => `${root}.md`), args.depth);
224
+ return allOf(tree);
225
+ })));
226
+ const tags = local(catalog.command("tags")).description("add owner tags to cached files or folders");
227
+ for (const action of ["list", "add", "remove"]) {
228
+ const command = examples(local(tags.command(action).description(`${action} local tags on a cached file or folder`), action !== "list"), [`${prefix} catalog tags ${action} FOLDER_ID${action === "list" ? "" : " project"} --offline`]).argument("<file>", text.catalogArgument);
229
+ if (action === "list")
230
+ bindQuery(command, queries.tags, tagRow);
231
+ else
232
+ command.argument("<tags...>", "local tag names");
233
+ command.action(async (id, values = []) => {
234
+ const filter = action === "list" ? termsOf(values, queries.tags, "catalog tags list") : undefined;
235
+ return output(allOf(await run(async (index, principal) => {
236
+ const found = await entry(index, principal, id);
237
+ if (!index.knowledge)
238
+ throw new CliError("configuration_error", "index has no shared knowledge adapter");
239
+ const tags = await index.knowledge.tags(principal, found.ref, action, action === "list" ? undefined : values, filter);
240
+ return action === "list" ? tags.map((tag) => ({ tag })) : tags;
241
+ }, action !== "list")));
242
+ });
243
+ }
244
+ };
245
+ /** `catalog import|show|list|search|tree|tags` over the selected profile's files and folders in the shared store. */
246
+ export const addDocumentCatalogCommands = honoursDryRun(sharedCommand(addDocumentCatalogCommandsDefinition));
@@ -0,0 +1,32 @@
1
+ import type { QueryAst } from "@wirecat/cli-base/query";
2
+ import type { Command } from "commander";
3
+ import type { SourceContent } from "../../documents.js";
4
+ import { type Body } from "../envelope.js";
5
+ import { type DocumentWords } from "./words.js";
6
+ /** An imported document of the selected profile, with its metadata as the CLI prints it. */
7
+ export interface ImportedDocument {
8
+ id: string;
9
+ metadata: unknown;
10
+ snapshot: SourceContent;
11
+ }
12
+ export interface LocalDocumentCommands {
13
+ words: DocumentWords;
14
+ output(body: Body): void;
15
+ /** The selected profile's imported documents the query matches, one page, as the CLI prints each. */
16
+ list(query: QueryAst | undefined, page: {
17
+ limit: number;
18
+ offset: number;
19
+ }): Promise<{
20
+ items: object[];
21
+ hasMore: boolean;
22
+ }>;
23
+ /** Resolves an id, URL or `document:<n>` ref; one the profile has not imported is the CLI's `not_found`. */
24
+ document(input: string): ImportedDocument;
25
+ /** When the selected profile last synced: every answer says how old its copy is. */
26
+ lastSync(): string | undefined;
27
+ }
28
+ /**
29
+ * `documents list|show|export` over the selected profile's local copy, in the `documents` group it returns: the CLI
30
+ * adds its live subcommands (`get`, `create`, …) to that group after these.
31
+ */
32
+ export declare const addLocalDocumentCommands: (program: Command, helpers: LocalDocumentCommands) => Command;
@@ -0,0 +1,76 @@
1
+ import { writeFileSync } from "node:fs";
2
+ import { CliError } from "@wirecat/cli-base";
3
+ import { annotate, sharedCommand } from "@wirecat/cli-base/commands";
4
+ import { IMPORTED_DOCUMENT_QUERY } from "../../store/index.js";
5
+ import { honoursDryRun } from "../dry-run-guard.js";
6
+ import { LOCAL_READ, LOCAL_WRITE } from "../effects.js";
7
+ import { itemOf, listOf } from "../envelope.js";
8
+ import { listQuery, typedQuery, withQuery } from "../list-query.js";
9
+ import { ageOf, documentsGroup, examples, positive, staleCopy, wordsOf } from "./words.js";
10
+ const addLocalDocumentCommandsDefinition = (program, helpers) => {
11
+ const { output, lastSync } = helpers;
12
+ const wording = wordsOf(helpers.words);
13
+ const { prefix, provider, text } = wording;
14
+ const documents = documentsGroup(program, wording);
15
+ annotate(withQuery(examples(annotate(documents.command("list"), { effects: LOCAL_READ }).description(text.documentsList), [
16
+ `${prefix} documents list`,
17
+ `${prefix} documents list tag:budget`,
18
+ `${prefix} documents list person:PERSON_UID --limit 10`,
19
+ ]), IMPORTED_DOCUMENT_QUERY), { output: { entity: "document", view: "imported" }, partial: true })
20
+ .option("--limit <n>", "how many documents to return", positive, 50)
21
+ .option("--page <n>", "which page to return", positive, 1)
22
+ .action(async (words, { limit, page }) => {
23
+ const query = typedQuery(words);
24
+ const ast = listQuery(query, IMPORTED_DOCUMENT_QUERY, "documents list");
25
+ const found = await helpers.list(ast, { limit, offset: (page - 1) * limit });
26
+ const synced = lastSync();
27
+ const age = ageOf(synced);
28
+ output(listOf("documents list", {
29
+ ...staleCopy(provider, synced),
30
+ items: found.items.map((item) => ({ ...item, ...age })),
31
+ limit,
32
+ has_more: found.hasMore,
33
+ page,
34
+ args: { query: query || undefined },
35
+ }));
36
+ });
37
+ examples(annotate(documents.command("show"), { effects: LOCAL_READ, partial: true })
38
+ .argument("<document>", text.documentArgument)
39
+ .description("show an imported document's text, tabs and metadata"), [`${prefix} documents show DOC_ID`, `${prefix} documents show document:42 --offline`]).action((input) => {
40
+ const { metadata, snapshot } = helpers.document(input);
41
+ const synced = lastSync();
42
+ output(itemOf({
43
+ metadata,
44
+ ...ageOf(synced),
45
+ text: snapshot.text,
46
+ tabs: snapshot.tabs,
47
+ ...(snapshot.notRead ? { not_read: snapshot.notRead } : {}),
48
+ }, staleCopy(provider, synced)));
49
+ });
50
+ examples(annotate(documents.command("export"), { effects: LOCAL_WRITE, partial: true })
51
+ .argument("<document>", text.documentArgument)
52
+ .description("write an imported document to a new Markdown file"), [`${prefix} documents export DOC_ID --output notes.md`])
53
+ .requiredOption("--output <file>", "path of the Markdown file to write; an existing file is refused")
54
+ .action((input, args) => {
55
+ const { id, snapshot } = helpers.document(input);
56
+ try {
57
+ writeFileSync(args.output, snapshot.markdown, { flag: "wx", mode: 0o600 });
58
+ }
59
+ catch (error) {
60
+ if (error.code === "EEXIST")
61
+ throw new CliError("validation_error", "the output file already exists; choose another --output", {
62
+ reason: "export.exists",
63
+ param: "--output",
64
+ });
65
+ throw error;
66
+ }
67
+ const synced = lastSync();
68
+ output(itemOf({ id, path: args.output, format: "markdown", ...ageOf(synced) }, staleCopy(provider, synced)));
69
+ });
70
+ return documents;
71
+ };
72
+ /**
73
+ * `documents list|show|export` over the selected profile's local copy, in the `documents` group it returns: the CLI
74
+ * adds its live subcommands (`get`, `create`, …) to that group after these.
75
+ */
76
+ export const addLocalDocumentCommands = honoursDryRun(sharedCommand(addLocalDocumentCommandsDefinition));
@@ -0,0 +1,22 @@
1
+ import type { Command } from "commander";
2
+ import { type Body } from "../envelope.js";
3
+ import { type DocumentWords } from "./words.js";
4
+ export interface DocumentFolderCommands {
5
+ words: DocumentWords;
6
+ output(body: Body): void;
7
+ /** Checks the folder with the provider and keeps it in the selected profile; refuses one that is not a folder. */
8
+ add(input: string): Promise<{
9
+ id: string;
10
+ name: string;
11
+ }>;
12
+ /** The selected profile's chosen folders, narrowed by `id:`. */
13
+ list(filter: Record<string, string>): {
14
+ id: string;
15
+ }[];
16
+ /** Forgets the folder; answers its id. */
17
+ remove(input: string): string;
18
+ /** Adds the CLI's own `folders browse`, which help then lists between `list` and `remove`. */
19
+ browse?(folders: Command): void;
20
+ }
21
+ /** `folders add|list|remove`: the folders the selected profile's sync imports. */
22
+ export declare const addDocumentFolderCommands: (program: Command, helpers: DocumentFolderCommands) => Command;
@@ -0,0 +1,45 @@
1
+ import { annotate, sharedCommand } from "@wirecat/cli-base/commands";
2
+ import { honoursDryRun } from "../dry-run-guard.js";
3
+ import { FETCH, LOCAL_READ, LOCAL_WRITE } from "../effects.js";
4
+ import { itemOf } from "../envelope.js";
5
+ import { bindQuery, documentQueries, folderRow, termsOf } from "./queries.js";
6
+ import { allOf, examples, wordsOf } from "./words.js";
7
+ const addDocumentFolderCommandsDefinition = (program, helpers) => {
8
+ const { output } = helpers;
9
+ const wording = wordsOf(helpers.words);
10
+ const { prefix, text } = wording;
11
+ const queries = documentQueries();
12
+ const folders = annotate(program.command("folders"), { effects: LOCAL_READ }).description(text.folders);
13
+ examples(annotate(folders.command("add"), { effects: FETCH })
14
+ .argument("<folder>", text.folderArgument)
15
+ .description("import a folder and everything under it on the next sync"), [`${prefix} folders add FOLDER_ID`]).action(async (input) => {
16
+ const { id, name } = await helpers.add(input);
17
+ output(itemOf({ id, name, added: true }));
18
+ });
19
+ bindQuery(examples(annotate(folders.command("list"), { effects: LOCAL_READ }).description("list the folder ids sync imports"), [`${prefix} folders list`]), queries.folders, folderRow).action((words) => {
20
+ const filter = termsOf(words, queries.folders, "folders list");
21
+ output(allOf(helpers.list(filter)));
22
+ });
23
+ examples(annotate(folders.command("remove"), { effects: LOCAL_WRITE })
24
+ .argument("<folder>", text.folderArgument)
25
+ .description("stop importing a folder; the next sync drops its documents"), [`${prefix} folders remove FOLDER_ID`]).action((input) => {
26
+ output(itemOf({ id: helpers.remove(input), removed: true }));
27
+ });
28
+ return folders;
29
+ };
30
+ const sharedFolderCommands = honoursDryRun(sharedCommand(addDocumentFolderCommandsDefinition));
31
+ /** `folders add|list|remove`: the folders the selected profile's sync imports. */
32
+ export const addDocumentFolderCommands = (program, helpers) => {
33
+ const folders = sharedFolderCommands(program, helpers);
34
+ if (!helpers.browse)
35
+ return folders;
36
+ const before = new Set(folders.commands);
37
+ helpers.browse(folders);
38
+ // The CLI's own command stays outside the shared contract, so it is added after it is taken, then put in its place.
39
+ const added = folders.commands.filter((command) => !before.has(command));
40
+ const children = folders.commands;
41
+ const rest = children.filter((command) => before.has(command));
42
+ const at = rest.findIndex((command) => command.name() === "remove");
43
+ children.splice(0, children.length, ...rest.slice(0, at), ...added, ...rest.slice(at));
44
+ return folders;
45
+ };
@@ -0,0 +1,36 @@
1
+ import type { Command } from "commander";
2
+ import { type DocumentCatalogCommands } from "./catalog.js";
3
+ import { type LocalDocumentCommands } from "./documents.js";
4
+ import { type DocumentFolderCommands } from "./folders.js";
5
+ import { type DocumentKnowledgeCommands } from "./knowledge.js";
6
+ import { type DocumentMirrorCommands } from "./mirrors.js";
7
+ import { type DocumentSearchCommands } from "./search.js";
8
+ import { type DocumentSyncCommands } from "./sync.js";
9
+ import type { DocumentWords } from "./words.js";
10
+ export { addDocumentCatalogCommands, CATALOG_FIELDS, type CatalogTree, type CatalogTreeSource, catalogId, catalogOutput, catalogSource, catalogTree, type DocumentCatalog, type DocumentCatalogCommands, type DocumentCatalogStores, } from "./catalog.js";
11
+ export { addLocalDocumentCommands, type ImportedDocument, type LocalDocumentCommands } from "./documents.js";
12
+ export { addDocumentFolderCommands, type DocumentFolderCommands } from "./folders.js";
13
+ export { addDocumentKnowledgeCommands, type DocumentKnowledgeCommands, type DocumentKnowledgePort, } from "./knowledge.js";
14
+ export { addDocumentMirrorCommands, type DocumentMirrorCommands, type DocumentMirrorConnection } from "./mirrors.js";
15
+ export { documentQueries, FACT_QUERY, factItem, folderRow, IDENTITY_ROLES, identityRow, linkRow, MEMORY_QUERY, MEMORY_SEARCH_QUERY, memoryItem, memorySearch, mirrorRow, tagRow, } from "./queries.js";
16
+ export { addDocumentSearchCommand, type DocumentSearchCommands, type DocumentSearchOptions } from "./search.js";
17
+ export { addDocumentSyncCommands, type DocumentSyncArgs, type DocumentSyncCommands } from "./sync.js";
18
+ export { ageOf, type CopyAge, type DocumentTexts, type DocumentWords, staleCopy } from "./words.js";
19
+ type Group<T> = Omit<T, "words" | "output">;
20
+ /** Every shared group at once, for a CLI with nothing of its own between them. */
21
+ export interface DocumentCommands<S> {
22
+ words: DocumentWords;
23
+ output: DocumentKnowledgeCommands["output"];
24
+ folders: Group<DocumentFolderCommands>;
25
+ sync: Group<DocumentSyncCommands>;
26
+ documents: Group<LocalDocumentCommands>;
27
+ search: Group<DocumentSearchCommands>;
28
+ catalog: Group<DocumentCatalogCommands>;
29
+ knowledge: Group<DocumentKnowledgeCommands>;
30
+ mirrors?: Group<DocumentMirrorCommands<S>>;
31
+ }
32
+ /**
33
+ * `folders`, `sync`, `status`, `documents list|show|export|context`, `search`, `catalog`, the knowledge groups and,
34
+ * when given, `mirrors`, in that order. Answers the `documents` group, for the CLI's live subcommands.
35
+ */
36
+ export declare const addDocumentCommands: <S>(program: Command, options: DocumentCommands<S>) => Command;
@@ -0,0 +1,32 @@
1
+ import { addDocumentCatalogCommands } from "./catalog.js";
2
+ import { addLocalDocumentCommands } from "./documents.js";
3
+ import { addDocumentFolderCommands } from "./folders.js";
4
+ import { addDocumentKnowledgeCommands } from "./knowledge.js";
5
+ import { addDocumentMirrorCommands } from "./mirrors.js";
6
+ import { addDocumentSearchCommand } from "./search.js";
7
+ import { addDocumentSyncCommands } from "./sync.js";
8
+ export { addDocumentCatalogCommands, CATALOG_FIELDS, catalogId, catalogOutput, catalogSource, catalogTree, } from "./catalog.js";
9
+ export { addLocalDocumentCommands } from "./documents.js";
10
+ export { addDocumentFolderCommands } from "./folders.js";
11
+ export { addDocumentKnowledgeCommands, } from "./knowledge.js";
12
+ export { addDocumentMirrorCommands } from "./mirrors.js";
13
+ export { documentQueries, FACT_QUERY, factItem, folderRow, IDENTITY_ROLES, identityRow, linkRow, MEMORY_QUERY, MEMORY_SEARCH_QUERY, memoryItem, memorySearch, mirrorRow, tagRow, } from "./queries.js";
14
+ export { addDocumentSearchCommand } from "./search.js";
15
+ export { addDocumentSyncCommands } from "./sync.js";
16
+ export { ageOf, staleCopy } from "./words.js";
17
+ /**
18
+ * `folders`, `sync`, `status`, `documents list|show|export|context`, `search`, `catalog`, the knowledge groups and,
19
+ * when given, `mirrors`, in that order. Answers the `documents` group, for the CLI's live subcommands.
20
+ */
21
+ export const addDocumentCommands = (program, options) => {
22
+ const shared = { words: options.words, output: options.output };
23
+ addDocumentFolderCommands(program, { ...shared, ...options.folders });
24
+ addDocumentSyncCommands(program, { ...shared, ...options.sync });
25
+ const documents = addLocalDocumentCommands(program, { ...shared, ...options.documents });
26
+ addDocumentSearchCommand(program, { ...shared, ...options.search });
27
+ addDocumentCatalogCommands(program, { ...shared, ...options.catalog });
28
+ addDocumentKnowledgeCommands(program, { ...shared, ...options.knowledge });
29
+ if (options.mirrors)
30
+ addDocumentMirrorCommands(program, { ...shared, ...options.mirrors });
31
+ return documents;
32
+ };