@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
@@ -0,0 +1,36 @@
1
+ import { type Command } from "commander";
2
+ import { type Complete, type DocumentKnowledge, type ImportedSource } from "../../documents.js";
3
+ import type { Author, Decider } from "../../store/index.js";
4
+ import { type Body } from "../envelope.js";
5
+ import { type DocumentWords } from "./words.js";
6
+ /** The shared knowledge port, and what only the provider knows: a document's context and the accounts seen on it. */
7
+ export interface DocumentKnowledgePort extends DocumentKnowledge {
8
+ context(principal: string, ref: string): Promise<unknown>;
9
+ /**
10
+ * The accounts seen on the document, as `identity` rows (`remote_id`, `provider`, `role`, `person`), filtered by
11
+ * `role` and `remote_id` as `identities list` names them.
12
+ */
13
+ people(principal: string, ref: string, filter?: Record<string, string>): Promise<unknown>;
14
+ linkPerson(principal: string, ref: string, remoteId: string, personRef: string): Promise<unknown>;
15
+ }
16
+ export interface DocumentKnowledgeCommands {
17
+ words: DocumentWords;
18
+ /** Prints one answer: the CLI's own envelope, keys and `--fields`. */
19
+ output(body: Body): void;
20
+ /**
21
+ * Resolves the command's document to its ref and runs `fn` with the selected profile's knowledge. The CLI opens the
22
+ * store and holds the lock its sync takes, so a write never races a sync.
23
+ */
24
+ run<T>(input: string, fn: (knowledge: DocumentKnowledgePort, principal: string, ref: string) => Promise<T>): Promise<T>;
25
+ /** The imported document `memories extract` reads, with the hash it checks before saving. */
26
+ document(input: string): ImportedSource;
27
+ complete(): Complete;
28
+ /** Who writes or decides in this run: the owner at a terminal, an agent over MCP. */
29
+ author(): Author;
30
+ decider(): Decider;
31
+ }
32
+ /**
33
+ * `documents context`, `tags`, `relationships`, `notes`, `memories`, `facts` and `identities` over one imported
34
+ * document of the selected profile: the same commands, options and answers in every documents CLI.
35
+ */
36
+ export declare const addDocumentKnowledgeCommands: (program: Command, helpers: DocumentKnowledgeCommands) => void;
@@ -0,0 +1,235 @@
1
+ import { annotate, sharedCommand } from "@wirecat/cli-base/commands";
2
+ import { defineQuery } from "@wirecat/cli-base/query";
3
+ import { Option } from "commander";
4
+ import { extractDocumentMemories } from "../../documents.js";
5
+ import { FACT_TYPES, MEMORY_KINDS } from "../../domain/knowledge.js";
6
+ import { honoursDryRun } from "../dry-run-guard.js";
7
+ import { LOCAL_READ, LOCAL_WRITE, REMOTE_WRITE } from "../effects.js";
8
+ import { itemOf, listOf } from "../envelope.js";
9
+ import { queryHelp, queryTerms, withQuery } from "../list-query.js";
10
+ import { bindQuery, documentQueries, FACT_QUERY, factItem, identityRow, linkRow, MEMORY_QUERY, MEMORY_SEARCH_QUERY, memoryItem, memorySearch, tagRow, termsOf, } from "./queries.js";
11
+ import { allOf, documentsGroup, examples, positive, wordsOf } from "./words.js";
12
+ const addDocumentKnowledgeCommandsDefinition = (program, helpers) => {
13
+ const { run, output, author, decider } = helpers;
14
+ const wording = wordsOf(helpers.words);
15
+ const { prefix, text } = wording;
16
+ const queries = documentQueries();
17
+ const documentArgument = text.knowledgeArgument;
18
+ const scopes = ["personal", "work"];
19
+ const documents = documentsGroup(program, wording);
20
+ examples(annotate(documents.command("context"), { effects: LOCAL_READ })
21
+ .argument("<document>", documentArgument)
22
+ .description("show a document with its tags, relationships, notes, memories and editors"), [`${prefix} documents context DOC_ID`]).action(async (doc) => output(itemOf(await run(doc, (k, p, ref) => k.context(p, ref)))));
23
+ const tags = annotate(program.command("tags"), { effects: LOCAL_READ }).description("label imported documents; labels survive a sync");
24
+ for (const action of ["list", "add", "remove"]) {
25
+ const command = examples(annotate(tags.command(action), { effects: action === "list" ? LOCAL_READ : LOCAL_WRITE })
26
+ .description(action === "list" ? "list a document's tags" : action === "add" ? "tag a document" : "untag a document")
27
+ .argument("<document>", documentArgument), [`${prefix} tags ${action} DOC_ID${action === "list" ? "" : " budget q3"}`]);
28
+ if (action === "list") {
29
+ bindQuery(command, queries.tags, tagRow).action(async (doc, words) => {
30
+ const filter = termsOf(words, queries.tags, "tags list");
31
+ output(allOf((await run(doc, (k, p, ref) => k.tags(p, ref, "list", [], filter))).map((tag) => ({ tag }))));
32
+ });
33
+ }
34
+ else
35
+ command
36
+ .argument("<tags...>", "one or more tags")
37
+ .action(async (doc, values) => output(itemOf({ tags: await run(doc, (k, p, ref) => k.tags(p, ref, action, values)) })));
38
+ }
39
+ const relationships = annotate(program.command("relationships"), { effects: LOCAL_READ }).description("connect a document to people, projects, notes and other references");
40
+ bindQuery(examples(annotate(relationships.command("list"), { effects: LOCAL_READ }).description("list a document's relationships"), [`${prefix} relationships list DOC_ID`]).argument("<document>", documentArgument), queries.links, linkRow).action(async (doc, words) => {
41
+ const { confirmed, ...filter } = termsOf(words, queries.links, "relationships list");
42
+ output(allOf(await run(doc, (k, p, ref) => k.links(p, ref, { ...filter, ...(confirmed === undefined ? {} : { confirmed: confirmed === "true" }) }))));
43
+ });
44
+ examples(annotate(relationships.command("add"), { effects: LOCAL_WRITE }).description("connect a document to another reference"), [
45
+ `${prefix} relationships add DOC_ID project:PROJECT_ID --kind about`,
46
+ `${prefix} relationships add DOC_ID person:PERSON_UID --kind assigned-to --role reviewer`,
47
+ ])
48
+ .argument("<document>", documentArgument)
49
+ .argument("<reference>", "what it connects to, such as person:<uid>, project:<id> or note:<id>")
50
+ .addOption(new Option("--kind <kind>", "how the two relate")
51
+ .choices(["links-to", "about", "evidence", "created-from", "related-to", "assigned-to"])
52
+ .default("related-to"))
53
+ .option("--role <role>", "the part the reference plays, in a word or two")
54
+ .option("--reason <text>", "why the two are connected")
55
+ .action(async (doc, to, { reason, ...args }) => output(itemOf(await run(doc, (k, p, ref) => k.addLink(p, ref, { to, ...args, by: decider(), ...(reason ? { evidence: reason } : {}) })))));
56
+ examples(annotate(relationships.command("remove"), { effects: LOCAL_WRITE }).description("remove one of a document's relationships"), [`${prefix} relationships remove DOC_ID LINK_ID`])
57
+ .argument("<document>", documentArgument)
58
+ .argument("<relationship-id>", "id, as relationships list prints it")
59
+ .action(async (doc, id) => output(itemOf(await run(doc, (k, p, ref) => k.removeLink(p, ref, id, decider())))));
60
+ const notes = annotate(program.command("notes"), { effects: LOCAL_READ }).description("write notes about an imported document");
61
+ const noteArgument = "note:<id> reference, as notes list prints it";
62
+ examples(annotate(notes.command("add"), {
63
+ effects: LOCAL_WRITE,
64
+ output: { entity: "note" },
65
+ literal_after_dashes: true,
66
+ }).description("write a note about a document"), [`${prefix} notes add DOC_ID "Check the numbers" --title Review`])
67
+ .argument("<document>", documentArgument)
68
+ .argument("<text>", "the note's text")
69
+ .option("--title <title>", "a title for the note")
70
+ .action(async (doc, text, args) => output(itemOf(await run(doc, (k, p, ref) => k.addNote(p, ref, text, args.title)))));
71
+ withQuery(examples(annotate(notes.command("list"), { effects: LOCAL_READ }).description("list a document's notes"), [
72
+ `${prefix} notes list DOC_ID`,
73
+ `${prefix} notes list DOC_ID text:review --limit 10`,
74
+ ]).argument("<document>", documentArgument), queries.notes)
75
+ .option("--limit <n>", "how many notes to return", positive, 50)
76
+ .option("--page <n>", "which page to return", positive, 1)
77
+ .action(async (doc, words, { page, limit }) => {
78
+ const query = termsOf(words, queries.notes, "notes list").text;
79
+ const found = await run(doc, (k, p, ref) => k.notes(p, ref, { ...(query ? { search: query } : {}), limit, offset: (page - 1) * limit }));
80
+ output(listOf("notes list", {
81
+ items: found.items,
82
+ limit,
83
+ has_more: found.hasMore,
84
+ page,
85
+ args: { document: doc, query: words.join(" ") },
86
+ }));
87
+ });
88
+ examples(annotate(notes.command("show"), { effects: LOCAL_READ, output: { entity: "note" } }).description("show one note"), [`${prefix} notes show DOC_ID note:NOTE_ID`])
89
+ .argument("<document>", documentArgument)
90
+ .argument("<note>", noteArgument)
91
+ .action(async (doc, noteRef) => output(itemOf(await run(doc, (k, p, ref) => k.note(p, ref, noteRef)))));
92
+ examples(annotate(notes.command("edit"), {
93
+ effects: LOCAL_WRITE,
94
+ output: { entity: "note" },
95
+ literal_after_dashes: true,
96
+ }).description("replace a note's text"), [`${prefix} notes edit DOC_ID note:NOTE_ID "Numbers checked" --revision 2`])
97
+ .argument("<document>", documentArgument)
98
+ .argument("<note>", noteArgument)
99
+ .argument("<text>", "the note's new text")
100
+ .requiredOption("--revision <n>", "revision from notes show; a newer note is not overwritten", positive)
101
+ .action(async (doc, noteRef, text, args) => output(itemOf(await run(doc, (k, p, ref) => k.editNote(p, ref, noteRef, text, args.revision)))));
102
+ examples(annotate(notes.command("remove"), { effects: LOCAL_WRITE }).description("delete one note"), [
103
+ `${prefix} notes remove DOC_ID note:NOTE_ID`,
104
+ ])
105
+ .argument("<document>", documentArgument)
106
+ .argument("<note>", noteArgument)
107
+ .action(async (doc, noteRef) => output(itemOf(await run(doc, (k, p, ref) => k.removeNote(p, ref, noteRef)))));
108
+ const memories = annotate(program.command("memories"), { effects: LOCAL_READ }).description("keep what was learned from a document, with evidence; an agent's stay proposed");
109
+ const memoryArgument = "memory:<id> reference, as memories list prints it";
110
+ const scope = (description) => new Option("--scope <scope>", description).choices(scopes);
111
+ examples(annotate(memories.command("add"), { effects: LOCAL_WRITE }).description("record a memory about a document"), [`${prefix} memories add DOC_ID "The team prefers async reviews" --scope work --kind preference`])
112
+ .argument("<document>", documentArgument)
113
+ .argument("<text>", "what to remember")
114
+ .addOption(scope("whose memory it is: personal or work").makeOptionMandatory())
115
+ .addOption(new Option("--kind <kind>", "what kind of memory it is").choices(MEMORY_KINDS).default("summary"))
116
+ .option("--supersedes <ref>", "a memory:<id> about the same document that this one replaces")
117
+ .action(async (doc, body, args) => output(itemOf(memoryItem(await run(doc, (k, p, ref) => k.addMemory(p, ref, { body, ...args, status: "proposed", author: author() }))))));
118
+ withQuery(examples(annotate(memories.command("list"), { effects: LOCAL_READ }).description("list a document's memories"), [
119
+ `${prefix} memories list DOC_ID scope:work`,
120
+ `${prefix} memories list DOC_ID kind:preference status:confirmed`,
121
+ ]).argument("<document>", documentArgument), MEMORY_QUERY)
122
+ .option("--limit <n>", "how many memories to return", positive, 50)
123
+ .action(async (doc, words, { limit }) => {
124
+ const terms = queryTerms(words, MEMORY_QUERY, "memories list");
125
+ const filters = {
126
+ ...(terms.has("kind") ? { kind: terms.get("kind") } : {}),
127
+ ...(terms.has("status") ? { status: terms.get("status") } : {}),
128
+ ...(terms.has("scope") ? { scope: terms.get("scope") } : {}),
129
+ };
130
+ output(allOf((await run(doc, (k, p, ref) => k.memories(p, ref, { ...filters, limit }))).items.map(memoryItem)));
131
+ });
132
+ const memoryActions = {
133
+ show: "show one memory",
134
+ confirm: "confirm a proposed memory as true",
135
+ stale: "mark a memory as out of date",
136
+ };
137
+ for (const [action, description] of Object.entries(memoryActions))
138
+ examples(annotate(memories.command(action), { effects: action === "show" ? LOCAL_READ : LOCAL_WRITE }).description(description), [`${prefix} memories ${action} DOC_ID memory:MEMORY_ID`])
139
+ .argument("<document>", documentArgument)
140
+ .argument("<memory>", memoryArgument)
141
+ .action(async (doc, memoryRef) => output(itemOf(memoryItem(await run(doc, (k, p, ref) => action === "show" ? k.memory(p, ref, memoryRef) : k.memory(p, ref, memoryRef, action, decider()))))));
142
+ const search = examples(annotate(memories.command("search"), { effects: LOCAL_READ }).description("search a document's memories by words"), [`${prefix} memories search DOC_ID reviews scope:work`, `${prefix} memories search DOC_ID "async reviews"`])
143
+ .argument("<document>", documentArgument)
144
+ .argument("<query...>", "words to look for, and scope:personal or scope:work — the fields are below")
145
+ .allowUnknownOption()
146
+ .addHelpText("after", queryHelp(MEMORY_SEARCH_QUERY))
147
+ .action(async (doc, words) => {
148
+ const { text, scope } = memorySearch(words);
149
+ const found = await run(doc, (k, p, ref) => k.searchMemories(p, ref, text, scope));
150
+ output({
151
+ ...allOf(found.items.map(memoryItem)),
152
+ ...(found.hasMore ? { meta: { truncated: true } } : {}),
153
+ });
154
+ });
155
+ annotate(search, { query: defineQuery(MEMORY_SEARCH_QUERY), output: { entity: "memory" } });
156
+ examples(annotate(memories.command("extract"), { effects: REMOTE_WRITE })
157
+ .argument("<document>", documentArgument)
158
+ .description("send a document's text to the model and show the memories it proposes"), [`${prefix} memories extract DOC_ID --scope work`, `${prefix} memories extract DOC_ID --scope work --yes`])
159
+ .addOption(scope("whose memories they become: personal or work").makeOptionMandatory())
160
+ .option("--tab <id>", "send only this tab of the document")
161
+ .option("--yes", "save the proposals, each with its quote and the document's version")
162
+ .action(async function (doc) {
163
+ const args = this.opts();
164
+ await run(doc, async () => undefined);
165
+ const result = await extractDocumentMemories({
166
+ read: () => helpers.document(doc),
167
+ complete: helpers.complete(),
168
+ scope: args.scope,
169
+ author: `${wording.app}-memory`,
170
+ tab: args.tab,
171
+ save: args.yes,
172
+ withWrite: (write) => run(doc, write),
173
+ });
174
+ output(itemOf({ ...result, saved: result.saved.map((item) => ("type" in item ? factItem(item) : memoryItem(item))) }));
175
+ });
176
+ const facts = annotate(program.command("facts"), { effects: LOCAL_READ }).description("what happened, as a document shows it; an agent's stay proposed until confirmed");
177
+ const factArgument = "fact:<id> reference, as facts list prints it";
178
+ examples(annotate(facts.command("add"), { effects: LOCAL_WRITE }).description("record a fact a document shows"), [
179
+ `${prefix} facts add DOC_ID "Budget approved" --type decision --scope work`,
180
+ ])
181
+ .argument("<document>", documentArgument)
182
+ .argument("<statement>", "the fact, in one sentence")
183
+ .addOption(new Option("--type <type>", "what kind of fact it is").choices(FACT_TYPES).default("fact"))
184
+ .addOption(scope("whose fact it is: personal or work"))
185
+ .option("--supersedes <ref>", "a decision only: the decision this one replaces")
186
+ .option("--occurred-time <time>", "when it happened, as the evidence shows, ISO 8601; a time without a zone is read in this computer's zone, a date alone as its midnight")
187
+ .action(async (doc, statement, { occurredTime, ...args }) => output(itemOf(factItem(await run(doc, (k, p, ref) => k.addFact(p, ref, {
188
+ statement,
189
+ ...args,
190
+ by: author(),
191
+ ...(occurredTime === undefined ? {} : { occurredAt: occurredTime }),
192
+ }))))));
193
+ withQuery(examples(annotate(facts.command("list"), { effects: LOCAL_READ }).description("list a document's facts"), [
194
+ `${prefix} facts list DOC_ID status:proposed`,
195
+ `${prefix} facts list DOC_ID kind:decision`,
196
+ ]).argument("<document>", documentArgument), FACT_QUERY)
197
+ .option("--limit <n>", "how many facts to return", positive, 50)
198
+ .action(async (doc, words, { limit }) => {
199
+ const terms = queryTerms(words, FACT_QUERY, "facts list");
200
+ const filters = {
201
+ ...(terms.has("kind") ? { type: terms.get("kind") } : {}),
202
+ ...(terms.has("status") ? { status: terms.get("status") } : {}),
203
+ };
204
+ output(allOf((await run(doc, (k, p, ref) => k.facts(p, ref, { ...filters, limit }))).items.map(factItem)));
205
+ });
206
+ const factActions = {
207
+ show: "show one fact",
208
+ confirm: "confirm a proposed fact; a decision it supersedes stops holding",
209
+ reverse: "an accepted decision no longer holds, and nothing replaced it",
210
+ };
211
+ for (const [action, description] of Object.entries(factActions))
212
+ examples(annotate(facts.command(action), { effects: action === "show" ? LOCAL_READ : LOCAL_WRITE }).description(description), [`${prefix} facts ${action} DOC_ID fact:FACT_ID`])
213
+ .argument("<document>", documentArgument)
214
+ .argument("<fact>", factArgument)
215
+ .action(async (doc, factRef) => output(itemOf(factItem(await run(doc, (k, p, ref) => action === "show" ? k.fact(p, ref, factRef) : k.fact(p, ref, factRef, action, decider()))))));
216
+ const identities = annotate(program.command("identities"), { effects: LOCAL_READ }).description(text.identities);
217
+ bindQuery(examples(annotate(identities.command("list"), { effects: LOCAL_READ }).description(text.identitiesList), [
218
+ `${prefix} identities list DOC_ID`,
219
+ ]).argument("<document>", documentArgument), queries.identities, identityRow).action(async (doc, words) => {
220
+ const filter = termsOf(words, queries.identities, "identities list");
221
+ output(itemOf(await run(doc, (k, p, ref) => k.people(p, ref, filter))));
222
+ });
223
+ examples(annotate(identities.command("link"), { effects: LOCAL_WRITE }).description(text.identitiesLink), [
224
+ `${prefix} identities link DOC_ID ${wording.remote.toUpperCase()}_ID person:PERSON_UID`,
225
+ ])
226
+ .argument("<document>", documentArgument)
227
+ .argument(`<${wording.remote}-id>`, text.identityArgument)
228
+ .argument("<person>", "person:<uid> reference of someone already known")
229
+ .action(async (doc, remoteId, personRef) => output(itemOf(await run(doc, (k, p, ref) => k.linkPerson(p, ref, remoteId, personRef)))));
230
+ };
231
+ /**
232
+ * `documents context`, `tags`, `relationships`, `notes`, `memories`, `facts` and `identities` over one imported
233
+ * document of the selected profile: the same commands, options and answers in every documents CLI.
234
+ */
235
+ export const addDocumentKnowledgeCommands = honoursDryRun(sharedCommand(addDocumentKnowledgeCommandsDefinition));
@@ -0,0 +1,46 @@
1
+ import { type RenderFormat } from "@wirecat/cli-base";
2
+ import { type Command } from "commander";
3
+ import { type Mirror, type MirrorSyncOptions, type PushStatePort } from "../../documents.js";
4
+ import { type Body } from "../envelope.js";
5
+ import { type DocumentWords } from "./words.js";
6
+ /** The provider, signed in for one `mirrors sync` or `mirrors watch`. */
7
+ export interface DocumentMirrorConnection<S> {
8
+ /** What `syncMirrors` takes beside the mirrors, the state and the user's choices. */
9
+ sync: Omit<MirrorSyncOptions<S>, "mirrors" | "keep" | "recreate" | "remote" | "stateOf">;
10
+ /** The provider's change feed, which `mirrors watch` polls. */
11
+ startToken(): Promise<string>;
12
+ /**
13
+ * The changes since `token`. Throws a `listing.too-large` CliError when the feed cannot go on from it (expired, or
14
+ * over its bound): `mirrors watch` then starts a new feed and checks every mirror once.
15
+ */
16
+ changes(token: string): Promise<{
17
+ cursor: string;
18
+ items: {
19
+ id: string;
20
+ }[];
21
+ }>;
22
+ }
23
+ export interface DocumentMirrorCommands<S> {
24
+ words: DocumentWords;
25
+ output(body: Body): void;
26
+ /** Prints one `mirrors watch` record in the run's format. */
27
+ print(render: (format: RenderFormat, data: (text: string) => void) => void): void;
28
+ /** The selected profile, as messages name it. */
29
+ profile(): string;
30
+ /** The selected profile's mirrors. */
31
+ mirrors(): Mirror[];
32
+ /** Replaces the selected profile's mirrors. */
33
+ save(mirrors: Mirror[]): void;
34
+ /** Resolves `--parent` and checks it is a folder the account can write into; refuses anything else. */
35
+ parent(input: string): Promise<{
36
+ id: string;
37
+ name: string;
38
+ }>;
39
+ kindOf(path: string): string | undefined;
40
+ stateOf(mirror: Mirror): PushStatePort<S>;
41
+ connect(): Promise<DocumentMirrorConnection<S>>;
42
+ /** Ctrl-C or `--timeout` ends `mirrors watch` normally; its signal says when. */
43
+ endsOnStop(): AbortSignal | undefined;
44
+ }
45
+ /** `mirrors add|list|remove|status|sync|watch`: local folders kept in step with the provider both ways. */
46
+ export declare const addDocumentMirrorCommands: <S>(program: Command, helpers: DocumentMirrorCommands<S>) => void;
@@ -0,0 +1,198 @@
1
+ import { statSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { CliError, isCliError } from "@wirecat/cli-base";
4
+ import { annotate, sharedCommand } from "@wirecat/cli-base/commands";
5
+ import { Option } from "commander";
6
+ import { mirrorId, mirrorStatus, syncMirrors, watchMirrors, } from "../../documents.js";
7
+ import { parseDuration } from "../../domain/duration.js";
8
+ import { honoursDryRun } from "../dry-run-guard.js";
9
+ import { FETCH, LOCAL_READ, LOCAL_WRITE, REMOTE_WRITE } from "../effects.js";
10
+ import { itemOf, jsonlRecords, listOf } from "../envelope.js";
11
+ import { bindQuery, documentQueries, mirrorRow, termsOf } from "./queries.js";
12
+ import { allOf, examples, wordsOf } from "./words.js";
13
+ const addDocumentMirrorCommandsDefinition = (program, helpers) => {
14
+ const { output } = helpers;
15
+ const wording = wordsOf(helpers.words);
16
+ const { app, prefix, provider, remote, text } = wording;
17
+ const queries = documentQueries();
18
+ const mirrors = annotate(program.command("mirrors"), { effects: LOCAL_READ }).description(text.mirrors);
19
+ const find = (id) => {
20
+ const mirror = helpers.mirrors().find((item) => item.id === id);
21
+ if (!mirror)
22
+ throw new CliError("not_found", `no mirror ${id} in profile ${helpers.profile()}; see ${app} ${helpers.profile()} mirrors list`, {
23
+ reason: "mirror.not-found",
24
+ });
25
+ return mirror;
26
+ };
27
+ const syncing = (connection) => ({
28
+ ...connection.sync,
29
+ stateOf: (mirror) => helpers.stateOf(mirror),
30
+ remote,
31
+ });
32
+ const chosenOf = (id) => {
33
+ const name = helpers.profile();
34
+ const chosen = id ? [find(id)] : helpers.mirrors();
35
+ if (!chosen.length)
36
+ throw new CliError("not_found", `profile ${name} has no mirrors; add one with ${app} ${name} mirrors add`, {
37
+ reason: "mirror.none",
38
+ });
39
+ return chosen;
40
+ };
41
+ examples(annotate(mirrors.command("add"), { effects: FETCH })
42
+ .argument("<path>", "local folder to mirror")
43
+ .requiredOption("--parent <id>", text.mirrorParent)
44
+ .description(text.mirrorsAdd), [`${prefix} mirrors add ./notes --parent FOLDER_ID`]).action(async (path, args) => {
45
+ const root = resolve(path);
46
+ let directory = false;
47
+ try {
48
+ directory = statSync(root).isDirectory();
49
+ }
50
+ catch { }
51
+ if (!directory)
52
+ throw new CliError("validation_error", "the path to mirror is not a folder", { reason: "mirror.not-folder" });
53
+ const parent = await helpers.parent(args.parent);
54
+ const folder = parent.id;
55
+ const id = mirrorId(root, folder);
56
+ const list = helpers.mirrors();
57
+ if (!list.some((mirror) => mirror.id === id))
58
+ list.push({ id, path: root, folder });
59
+ helpers.save(list);
60
+ output(itemOf({ id, path: root, folder, folder_name: parent.name, added: true }));
61
+ });
62
+ bindQuery(examples(annotate(mirrors.command("list"), { effects: LOCAL_READ }).description("list this profile's mirrors"), [
63
+ `${prefix} mirrors list`,
64
+ ]), queries.mirrors, mirrorRow).action((words) => {
65
+ const filter = termsOf(words, queries.mirrors, "mirrors list");
66
+ output(allOf(helpers
67
+ .mirrors()
68
+ .filter((row) => Object.entries(filter).every(([key, value]) => row[key] === value))));
69
+ });
70
+ examples(annotate(mirrors.command("remove"), { effects: LOCAL_WRITE })
71
+ .argument("<id>", "mirror id from mirrors list")
72
+ .description(`stop mirroring a folder; nothing in ${wording.place} is changed or deleted`), [`${prefix} mirrors remove 1a2b3c4d`]).action((id) => {
73
+ find(id);
74
+ helpers.save(helpers.mirrors().filter((mirror) => mirror.id !== id));
75
+ output(itemOf({ id, removed: true }));
76
+ });
77
+ examples(annotate(mirrors.command("status"), { effects: LOCAL_READ })
78
+ .argument("[id]", "mirror id; every mirror of the profile when omitted")
79
+ .description(`show which local files the next sync would create or send; ${provider} is not asked`), [`${prefix} mirrors status`]).action(async (id) => {
80
+ const items = await mirrorStatus(id ? [find(id)] : helpers.mirrors(), helpers.kindOf, (mirror) => helpers.stateOf(mirror));
81
+ output(allOf(items.map(({ id, folder, create, update, unchanged, orphans, unsupported, remote_checked }) => ({
82
+ id,
83
+ folder,
84
+ create: create.length,
85
+ update: update.length,
86
+ unchanged,
87
+ orphans: orphans.length,
88
+ unsupported,
89
+ remote_checked,
90
+ }))));
91
+ });
92
+ examples(annotate(mirrors.command("sync"), { effects: REMOTE_WRITE })
93
+ .argument("[id]", "mirror id; every mirror of the profile when omitted")
94
+ .addOption(new Option("--keep <side>", "where a part changed on both sides, keep this side").choices([
95
+ "local",
96
+ remote,
97
+ "both",
98
+ ]))
99
+ .option("--replace", `same as --keep local, and create again files deleted in ${provider}`)
100
+ .description(text.mirrorsSync), [
101
+ `${prefix} mirrors sync`,
102
+ `${prefix} mirrors sync 1a2b3c4d --keep ${remote}`,
103
+ `${prefix} mirrors sync 1a2b3c4d --replace`,
104
+ ]).action(async (id, args) => {
105
+ const chosen = chosenOf(id);
106
+ if (args.replace && args.keep && args.keep !== "local")
107
+ throw new CliError("validation_error", `--replace keeps the local side; it cannot be combined with --keep ${remote} or both`);
108
+ const keep = (args.replace ? "local" : args.keep === remote ? "remote" : args.keep);
109
+ const connection = await helpers.connect();
110
+ const { items, issues } = await syncMirrors({
111
+ ...syncing(connection),
112
+ mirrors: chosen,
113
+ ...(keep ? { keep } : {}),
114
+ recreate: args.replace === true,
115
+ });
116
+ const body = allOf(items);
117
+ if (issues.length)
118
+ body.meta = { complete: false, issues };
119
+ output(body);
120
+ if (issues.length)
121
+ throw new CliError("provider_error", `some files were not synced; see conflicts, missing and errors, then rerun with --keep local, ${remote} or both`, { reason: "mirror.partial" });
122
+ });
123
+ examples(annotate(mirrors.command("watch"), { effects: REMOTE_WRITE, lifetime: "persistent" })
124
+ .argument("[id]", "mirror id; every mirror of the profile when omitted")
125
+ .option("--every <duration>", `how often to ask ${provider} for changes`, "60s")
126
+ .summary("keep syncing both ways until Ctrl-C or --timeout")
127
+ .description(`keep syncing both ways until Ctrl-C or --timeout: on each local save and each ${provider} change; ` +
128
+ "a part changed on both sides is reported and left for mirrors sync --keep"), [`${prefix} mirrors watch`, `${prefix} mirrors watch 1a2b3c4d --every 2m --jsonl`]).action(async (id, args) => {
129
+ const pollMs = parseDuration(args.every, "--every");
130
+ if (pollMs < 10_000)
131
+ throw new CliError("validation_error", "--every must be at least 10s");
132
+ const chosen = chosenOf(id);
133
+ const signal = helpers.endsOnStop() ?? new AbortController().signal;
134
+ const connection = await helpers.connect();
135
+ const states = (mirror) => helpers.stateOf(mirror);
136
+ let token = await connection.startToken();
137
+ const remoteChanges = async () => {
138
+ let changed;
139
+ try {
140
+ const feed = await connection.changes(token);
141
+ token = feed.cursor;
142
+ changed = new Set(feed.items.map((item) => item.id));
143
+ }
144
+ catch (error) {
145
+ if (!isCliError(error) || error.details?.reason !== "listing.too-large")
146
+ throw error;
147
+ token = await connection.startToken();
148
+ return "all";
149
+ }
150
+ return chosen
151
+ .filter((mirror) => Object.values(states(mirror).read().entries).some((entry) => changed.has(entry.id)))
152
+ .map((mirror) => mirror.id);
153
+ };
154
+ let cycles = 0;
155
+ for await (const event of watchMirrors((mirrors) => syncMirrors({ ...syncing(connection), mirrors }), {
156
+ mirrors: chosen,
157
+ signal,
158
+ kindOf: helpers.kindOf,
159
+ stateOf: states,
160
+ remoteChanges,
161
+ pollMs,
162
+ })) {
163
+ cycles++;
164
+ const data = {
165
+ at: new Date().toISOString(),
166
+ triggers: event.triggers,
167
+ mirrors: event.mirrors,
168
+ ...("error" in event
169
+ ? { error: { code: event.error.code, message: event.error.message } }
170
+ : { results: event.result.items, ...(event.result.issues.length ? { issues: event.result.issues } : {}) }),
171
+ };
172
+ helpers.print((format, write) => write(format === "pretty" ? describeCycle(data) : JSON.stringify({ type: "item", data })));
173
+ }
174
+ helpers.print((format, write) => {
175
+ if (format === "pretty")
176
+ return;
177
+ const end = listOf("mirrors watch", {
178
+ items: [],
179
+ limit: Math.max(1, cycles),
180
+ has_more: false,
181
+ paging: "cursor",
182
+ meta: { complete: true },
183
+ });
184
+ for (const record of jsonlRecords(end))
185
+ write(JSON.stringify(record));
186
+ });
187
+ });
188
+ };
189
+ const describeCycle = (cycle) => {
190
+ const time = cycle.at.slice(11, 19);
191
+ if (cycle.error)
192
+ return `${time} ${cycle.triggers.join("+")}: ${cycle.error.message}; trying again`;
193
+ const parts = (cycle.results ?? []).map((result) => `${result.id} ${result.created.length} created, ${result.updated.length} sent, ${result.pulled.length} pulled` +
194
+ (result.conflicts.length ? `, ${result.conflicts.length} conflicts (mirrors sync ${result.id} --keep …)` : ""));
195
+ return `${time} ${cycle.triggers.join("+")}: ${parts.join("; ") || "nothing to do"}`;
196
+ };
197
+ /** `mirrors add|list|remove|status|sync|watch`: local folders kept in step with the provider both ways. */
198
+ export const addDocumentMirrorCommands = honoursDryRun(sharedCommand(addDocumentMirrorCommandsDefinition));
@@ -0,0 +1,120 @@
1
+ import { type QueryRegistry } from "@wirecat/cli-base/query";
2
+ import type { Command } from "commander";
3
+ import * as v from "valibot";
4
+ import type { Fact, Memory } from "../../store/index.js";
5
+ import { type QueryWords } from "../list-query.js";
6
+ export declare const folderRow: v.StrictObjectSchema<{
7
+ readonly id: v.StringSchema<undefined>;
8
+ }, undefined>;
9
+ export declare const mirrorRow: v.StrictObjectSchema<{
10
+ readonly id: v.StringSchema<undefined>;
11
+ readonly path: v.StringSchema<undefined>;
12
+ readonly folder: v.StringSchema<undefined>;
13
+ }, undefined>;
14
+ export declare const tagRow: v.StrictObjectSchema<{
15
+ readonly tag: v.StringSchema<undefined>;
16
+ }, undefined>;
17
+ export declare const linkRow: v.LooseObjectSchema<{
18
+ readonly id: v.StringSchema<undefined>;
19
+ readonly from: v.StringSchema<undefined>;
20
+ readonly to: v.NullableSchema<v.StringSchema<undefined>, undefined>;
21
+ readonly kind: v.StringSchema<undefined>;
22
+ readonly role: v.NullableSchema<v.StringSchema<undefined>, undefined>;
23
+ readonly confirmed: v.BooleanSchema<undefined>;
24
+ readonly origin: v.PicklistSchema<["file", "owner", "suggested", "message"], undefined>;
25
+ }, undefined>;
26
+ /** Who a document names, in every documents CLI: the provider's id of the account, the provider, and the person. */
27
+ export declare const IDENTITY_ROLES: readonly ["owner", "last-editor"];
28
+ export declare const identityRow: v.LooseObjectSchema<{
29
+ readonly remote_id: v.NullableSchema<v.StringSchema<undefined>, undefined>;
30
+ readonly provider: v.StringSchema<undefined>;
31
+ readonly role: v.PicklistSchema<readonly ["owner", "last-editor"], undefined>;
32
+ readonly person: v.NullableSchema<v.RecordSchema<v.StringSchema<undefined>, v.UnknownSchema, undefined>, undefined>;
33
+ }, undefined>;
34
+ /** The list queries of the shared documents commands: the same entities in every documents CLI. */
35
+ export declare const documentQueries: () => {
36
+ folders: QueryRegistry;
37
+ mirrors: QueryRegistry;
38
+ tags: QueryRegistry;
39
+ notes: QueryRegistry;
40
+ links: QueryRegistry;
41
+ identities: QueryRegistry;
42
+ };
43
+ export declare const bindQuery: (command: Command, query: QueryRegistry, schema: v.GenericSchema) => Command;
44
+ export declare const termsOf: (words: string[], query: QueryRegistry, command: string) => {
45
+ [k: string]: string;
46
+ };
47
+ export declare const FACT_QUERY: {
48
+ readonly entity: "fact";
49
+ readonly backend: "native";
50
+ readonly fields: readonly [import("@wirecat/cli-base/query").FieldSpec, import("@wirecat/cli-base/query").FieldSpec];
51
+ };
52
+ export declare const MEMORY_QUERY: {
53
+ readonly entity: "memory";
54
+ readonly backend: "native";
55
+ readonly fields: readonly [import("@wirecat/cli-base/query").FieldSpec, import("@wirecat/cli-base/query").FieldSpec, import("@wirecat/cli-base/query").FieldSpec];
56
+ };
57
+ export declare const MEMORY_SEARCH_QUERY: {
58
+ readonly entity: "memory";
59
+ readonly backend: "native";
60
+ readonly fields: readonly [import("@wirecat/cli-base/query").FieldSpec, import("@wirecat/cli-base/query").FieldSpec];
61
+ };
62
+ /** A fact as cli-core's `fact` entity. */
63
+ export declare const factItem: ({ type, statement, source, confirmedBy, ...fact }: Fact) => {
64
+ ref: string;
65
+ id: string;
66
+ kind: "decision" | "fact" | "promise" | "question" | "statement";
67
+ text: string;
68
+ status: "accepted" | "proposed" | "rejected" | "reversed" | "superseded";
69
+ project: string | null;
70
+ subject: string | null;
71
+ occurred_at: string | null;
72
+ supersedes: string | null;
73
+ author: {
74
+ type: import("../../store/sqlite/actors.js").Actor["type"];
75
+ id: string;
76
+ name: string | null;
77
+ kind: "agent" | "rule" | null;
78
+ };
79
+ model: string | null;
80
+ confirmed_by: {
81
+ type: import("../../store/sqlite/actors.js").Actor["type"];
82
+ id: string;
83
+ } | null;
84
+ scope: "personal" | "work" | null;
85
+ origin: string;
86
+ evidence: string[];
87
+ created_at: string;
88
+ updated_at: string;
89
+ };
90
+ /** A memory as cli-core's `memory` entity. */
91
+ export declare const memoryItem: ({ body, ...memory }: Memory) => {
92
+ ref: string;
93
+ id: string;
94
+ kind: "digest" | "preference" | "summary";
95
+ text: string;
96
+ subject: string | null;
97
+ author: {
98
+ type: import("../../store/sqlite/actors.js").Actor["type"];
99
+ id: string;
100
+ name: string | null;
101
+ kind: "agent" | "rule" | null;
102
+ };
103
+ model: string | null;
104
+ confidence: number | null;
105
+ status: "confirmed" | "proposed" | "stale" | "superseded";
106
+ scope: "personal" | "work";
107
+ supersedes: string | null;
108
+ evidence: string[];
109
+ last_verified_at: string | null;
110
+ created_at: string;
111
+ updated_at: string;
112
+ };
113
+ /**
114
+ * `memories search`'s words and its `scope:` term: the store searches the words and filters the scope in one
115
+ * query. Bare words are text, so they may repeat; everything is joined by AND.
116
+ */
117
+ export declare const memorySearch: (words: QueryWords) => {
118
+ text: string;
119
+ scope?: Memory["scope"];
120
+ };