@wirecat/cli-core 0.720.0 → 0.721.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 (63) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/cli/config-command.js +8 -2
  4. package/dist/cli/config-issues.d.ts +3 -1
  5. package/dist/cli/config-issues.js +9 -2
  6. package/dist/cli/documents/file-conflicts.d.ts +25 -0
  7. package/dist/cli/documents/file-conflicts.js +102 -0
  8. package/dist/cli/documents/file-edit.d.ts +29 -0
  9. package/dist/cli/documents/file-edit.js +352 -0
  10. package/dist/cli/documents/file-update.d.ts +43 -0
  11. package/dist/cli/documents/file-update.js +95 -0
  12. package/dist/cli/documents/history.d.ts +34 -0
  13. package/dist/cli/documents/history.js +89 -0
  14. package/dist/cli/documents/index.d.ts +9 -2
  15. package/dist/cli/documents/index.js +9 -2
  16. package/dist/cli/documents/library.js +10 -0
  17. package/dist/cli/permission-keys.d.ts +6 -0
  18. package/dist/cli/permission-keys.js +15 -3
  19. package/dist/cli/service-api.d.ts +1 -1
  20. package/dist/cli/service-api.js +16 -34
  21. package/dist/documents/file-mirror-model.d.ts +18 -1
  22. package/dist/documents/index.d.ts +7 -4
  23. package/dist/documents/index.js +4 -1
  24. package/dist/documents/model.d.ts +16 -1
  25. package/dist/errors/reasons.js +4 -0
  26. package/dist/services/documents/block-diff.d.ts +13 -3
  27. package/dist/services/documents/block-diff.js +13 -7
  28. package/dist/services/documents/ingestion.d.ts +21 -2
  29. package/dist/services/documents/ingestion.js +29 -2
  30. package/dist/services/documents/plan.js +16 -7
  31. package/dist/services/documents/ports.d.ts +2 -0
  32. package/dist/services/documents/sync.d.ts +1 -0
  33. package/dist/services/documents/sync.js +9 -4
  34. package/dist/services/files/conflicts.d.ts +78 -0
  35. package/dist/services/files/conflicts.js +183 -0
  36. package/dist/services/files/guarded-write.d.ts +34 -0
  37. package/dist/services/files/guarded-write.js +42 -0
  38. package/dist/services/files/listing.d.ts +8 -0
  39. package/dist/services/files/listing.js +1 -1
  40. package/dist/services/files/local-files.d.ts +54 -0
  41. package/dist/services/files/local-files.js +143 -0
  42. package/dist/services/files/mirror-state.d.ts +14 -0
  43. package/dist/services/files/mirror-state.js +65 -0
  44. package/dist/services/files/mirror.d.ts +3 -13
  45. package/dist/services/files/mirror.js +163 -204
  46. package/dist/services/files/text-merge.d.ts +27 -0
  47. package/dist/services/files/text-merge.js +134 -0
  48. package/dist/services/files/versions.d.ts +36 -9
  49. package/dist/services/files/versions.js +40 -12
  50. package/dist/services/metadata.d.ts +1 -1
  51. package/dist/store/index.d.ts +1 -0
  52. package/dist/store/index.js +1 -0
  53. package/dist/store/sqlite/document-history.d.ts +84 -0
  54. package/dist/store/sqlite/document-history.js +158 -0
  55. package/dist/store/sqlite/manifest.js +2 -0
  56. package/dist/store/sqlite/migrations.generated.js +17 -0
  57. package/dist/store/sqlite/notes.d.ts +9 -10
  58. package/dist/store/sqlite/notes.js +33 -21
  59. package/dist/store/sqlite/schema/document-changes.d.ts +136 -0
  60. package/dist/store/sqlite/schema/document-changes.js +11 -0
  61. package/dist/store/sqlite/schema.d.ts +65 -0
  62. package/dist/store/sqlite/schema.js +5 -0
  63. package/package.json +2 -2
@@ -0,0 +1,43 @@
1
+ import type { Command } from "commander";
2
+ import type { FileTarget } from "../../documents/file-mirror-model.js";
3
+ import { type GuardedFileWriteResult } from "../../services/files/guarded-write.js";
4
+ import type { FileVersions } from "../../services/files/versions.js";
5
+ import { type Body } from "../envelope.js";
6
+ import { type DocumentWords } from "./words.js";
7
+ /** What `files update` writes through, signed in for one run. */
8
+ export interface FileUpdatePort {
9
+ target: FileTarget;
10
+ /** The profile's version store, under its state folder. */
11
+ versions: FileVersions;
12
+ signal?: AbortSignal;
13
+ }
14
+ export interface FileUpdateCommands {
15
+ words: DocumentWords;
16
+ /** `command` is the one running, in this and the helpers below: one set of helpers serves several commands. */
17
+ output(body: Body, command: Command): void;
18
+ /** What the user typed, as the target's path. */
19
+ path(input: string): string;
20
+ /** The command that reads the file and its sha256 again, for a conflict's message (`ydisk personal files show …`). */
21
+ reread(input: string): string;
22
+ /** Read for the text when --text is absent. */
23
+ stdin(): NodeJS.ReadableStream | undefined;
24
+ /**
25
+ * The CLI's own write path: its permission key for the command and `extra` (the delete key when a file is
26
+ * replaced), its run and send journal. Answers what `act` answered, with whatever the CLI adds (`operation_id`).
27
+ */
28
+ write(extra: readonly string[], act: (port: FileUpdatePort) => Promise<object>, command: Command): Promise<object>;
29
+ /** The key an overwrite also asks; `files.delete` when absent. */
30
+ deleteKey?: string;
31
+ }
32
+ /** A sha256 the user typed, in lower case; `flag` names it in the refusal. */
33
+ export declare const sha256Of: (input: string | undefined, flag?: string) => string | undefined;
34
+ /** The answer's `replaced`: the old sha256 and where its copy is kept, or null when nothing was there. */
35
+ export declare const replacedOf: (done: GuardedFileWriteResult, versions: FileVersions) => {
36
+ sha256: string;
37
+ kept_at?: string | undefined;
38
+ } | null;
39
+ /**
40
+ * `<files> update <path> (--text | stdin) [--expected-fingerprint <sha256>]`: a text written over a file only at the
41
+ * content it was read at, the replaced content kept in the profile's version store (`guardedFileWrite`).
42
+ */
43
+ export declare const addFileUpdateCommand: (files: Command, helpers: FileUpdateCommands) => Command;
@@ -0,0 +1,95 @@
1
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { CliError } from "@wirecat/cli-base";
5
+ import { annotate, sharedCommand } from "@wirecat/cli-base/commands";
6
+ import { guardedFileWrite } from "../../services/files/guarded-write.js";
7
+ import { honoursDryRun } from "../dry-run-guard.js";
8
+ import { REMOTE_WRITE } from "../effects.js";
9
+ import { itemOf } from "../envelope.js";
10
+ import { bufferedInput, MAX_BUFFERED_INPUT } from "../input-policy.js";
11
+ import { examples, wordsOf } from "./words.js";
12
+ const SHA256 = /^[0-9a-f]{64}$/u;
13
+ // A read gives the text extracted from these, never the file itself: written back, it would replace the whole file.
14
+ const EXTRACTED = /\.(pdf|docx|xlsx)$/iu;
15
+ /** A sha256 the user typed, in lower case; `flag` names it in the refusal. */
16
+ export const sha256Of = (input, flag = "--expected-fingerprint") => {
17
+ const hash = input?.toLowerCase();
18
+ if (hash !== undefined && !SHA256.test(hash))
19
+ throw new CliError("validation_error", `${flag} takes a 64-character sha256`, { param: flag });
20
+ return hash;
21
+ };
22
+ /** The answer's `replaced`: the old sha256 and where its copy is kept, or null when nothing was there. */
23
+ export const replacedOf = (done, versions) => done.replaced
24
+ ? {
25
+ sha256: done.replaced.sha256,
26
+ ...(versions.dir ? { kept_at: join(versions.dir, "objects", done.replaced.sha256) } : {}),
27
+ }
28
+ : null;
29
+ const newText = async (input, text) => {
30
+ if (text !== undefined)
31
+ return text;
32
+ if (!input || input.isTTY)
33
+ throw new CliError("validation_error", "give the new text with --text or on stdin", { param: "--text" });
34
+ const read = await bufferedInput(input, { maxBytes: MAX_BUFFERED_INPUT });
35
+ // An agent over MCP has no stdin: an empty one is a missing --text, not a wish to empty the file.
36
+ if (read.length === 0)
37
+ throw new CliError("validation_error", "stdin gave no text; give the new text with --text or on stdin", {
38
+ param: "--text",
39
+ });
40
+ return read.toString("utf8");
41
+ };
42
+ const addFileUpdateCommandDefinition = (files, helpers) => {
43
+ const { prefix, place } = wordsOf(helpers.words);
44
+ const group = files.name();
45
+ const deleteKey = helpers.deleteKey ?? "files.delete";
46
+ return examples(annotate(files.command("update"), { effects: REMOTE_WRITE, offline: false })
47
+ .summary(`replace a ${place} file's text, or create a text file`)
48
+ .description(`replace a ${place} file's text, or create a text file. A file already there is replaced only with ` +
49
+ `--expected-fingerprint, the sha256 read from it; it asks as ${deleteKey} does. The file is checked just ` +
50
+ "before the write, and what it replaced is kept on this computer. Write back only a whole plain-text file: " +
51
+ "a text cut with truncated: true would replace the whole file, and a .pdf, .docx or .xlsx is refused")
52
+ .argument("<path>", `the file on ${place}`)
53
+ .option("--text <text>", "the file's new text; without it, the text is read from stdin")
54
+ .option("--expected-fingerprint <hash>", "the sha256 the file had when it was read; required when it exists"), [
55
+ `${prefix} ${group} update /notes.md --text "# Notes"`,
56
+ `${prefix} ${group} update /notes.md --text "# Notes" --expected-fingerprint 9f86d081…`,
57
+ ]).action(async function (input, args) {
58
+ const expected = sha256Of(args.expectedFingerprint);
59
+ const path = helpers.path(input);
60
+ if (EXTRACTED.test(path))
61
+ throw new CliError("validation_error", `${path} is not a plain-text file; change a .docx with ${group} documents update and a .xlsx with ${group} ` +
62
+ "sheets update, where a CLI has them", { reason: "file.not-plain-text" });
63
+ const text = await newText(helpers.stdin(), args.text);
64
+ const answer = await helpers.write(expected ? [deleteKey] : [], async ({ target, versions, signal }) => {
65
+ const folder = await mkdtemp(join(tmpdir(), "wirecat-update-"));
66
+ try {
67
+ const from = join(folder, "text");
68
+ await writeFile(from, text, { mode: 0o600 });
69
+ const done = await guardedFileWrite({
70
+ target,
71
+ versions,
72
+ path,
73
+ from,
74
+ reread: helpers.reread(input),
75
+ ...(expected ? { expected } : {}),
76
+ ...(signal ? { signal } : {}),
77
+ });
78
+ return {
79
+ path,
80
+ sha256: done.file.sha256 ?? null,
81
+ replaced: replacedOf(done, versions),
82
+ };
83
+ }
84
+ finally {
85
+ await rm(folder, { recursive: true, force: true });
86
+ }
87
+ }, this);
88
+ helpers.output(itemOf(answer), this);
89
+ });
90
+ };
91
+ /**
92
+ * `<files> update <path> (--text | stdin) [--expected-fingerprint <sha256>]`: a text written over a file only at the
93
+ * content it was read at, the replaced content kept in the profile's version store (`guardedFileWrite`).
94
+ */
95
+ export const addFileUpdateCommand = honoursDryRun(sharedCommand(addFileUpdateCommandDefinition));
@@ -0,0 +1,34 @@
1
+ import { type Command } from "commander";
2
+ import * as v from "valibot";
3
+ import { type documentIngestion } from "../../documents.js";
4
+ import { type Body } from "../envelope.js";
5
+ import { type Settings } from "../settings.js";
6
+ import { type DocumentWords } from "./words.js";
7
+ /** The local history `documentIngestion` gives: what a CLI hands these commands. */
8
+ export type DocumentHistoryPort = ReturnType<typeof documentIngestion>["history"];
9
+ export interface DocumentHistoryCommands {
10
+ words: DocumentWords;
11
+ output(body: Body): void;
12
+ /** Opens the store read-only for the selected profile, with the source account its documents belong to. */
13
+ run<T>(fn: (history: DocumentHistoryPort, principal: string) => Promise<T>): Promise<T>;
14
+ /** The source's id from what was typed: an id or a link. A `document:<n>` ref may pass as it is. */
15
+ id(input: string): string;
16
+ }
17
+ /** `keep_versions_for_days`: a documents CLI adds it to `settingsFor` and passes `keepVersionsForDays` to its sync. */
18
+ export declare const DOCUMENT_HISTORY_SETTINGS: {
19
+ profile: {
20
+ keep_versions_for_days: v.OptionalSchema<v.SchemaWithPipe<readonly [v.NumberSchema<(issue: v.BaseIssue<unknown>) => string>, v.IntegerAction<number, (issue: v.BaseIssue<unknown>) => string>, v.MinValueAction<number, 1, (issue: v.BaseIssue<unknown>) => string>]>, undefined>;
21
+ };
22
+ settings: {
23
+ key: string;
24
+ default: number;
25
+ description: string;
26
+ }[];
27
+ };
28
+ /** The profile's `keep_versions_for_days`, or 365. */
29
+ export declare const keepVersionsForDays: (settings: Pick<Settings, "configured" | "shared">) => number;
30
+ /**
31
+ * `documents history <document>` and `changes`, over the selected profile's local history: every version a sync
32
+ * replaced or removed, and what changed since a time. A CLI whose `documents` group is its own gets them there too.
33
+ */
34
+ export declare const addDocumentHistoryCommands: (program: Command, helpers: DocumentHistoryCommands) => Command;
@@ -0,0 +1,89 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { annotate, sharedCommand } from "@wirecat/cli-base/commands";
3
+ import { InvalidArgumentError } from "commander";
4
+ import * as v from "valibot";
5
+ import { KEEP_VERSIONS_FOR_DAYS } from "../../documents.js";
6
+ import { momentOf } from "../../services/moment.js";
7
+ import { DOCUMENT_EVENTS } from "../../store/index.js";
8
+ import { honoursDryRun } from "../dry-run-guard.js";
9
+ import { LOCAL_READ } from "../effects.js";
10
+ import { itemOf, listOf } from "../envelope.js";
11
+ import { count, fromFile } from "../settings.js";
12
+ import { documentsGroup, examples, positive, wordsOf } from "./words.js";
13
+ /** `keep_versions_for_days`: a documents CLI adds it to `settingsFor` and passes `keepVersionsForDays` to its sync. */
14
+ export const DOCUMENT_HISTORY_SETTINGS = {
15
+ profile: { keep_versions_for_days: v.optional(count) },
16
+ settings: [
17
+ {
18
+ key: "keep_versions_for_days",
19
+ default: KEEP_VERSIONS_FOR_DAYS,
20
+ description: "days earlier versions of synced documents, and the change log, are kept",
21
+ },
22
+ ],
23
+ };
24
+ /** The profile's `keep_versions_for_days`, or 365. */
25
+ export const keepVersionsForDays = (settings) => fromFile(settings, "keep_versions_for_days", KEEP_VERSIONS_FOR_DAYS).value;
26
+ const eventList = (input, before = []) => {
27
+ const events = input.split(",").map((one) => one.trim());
28
+ for (const event of events)
29
+ if (!DOCUMENT_EVENTS.includes(event))
30
+ throw new InvalidArgumentError(`use ${DOCUMENT_EVENTS.join(", ")}`);
31
+ return [...before, ...events];
32
+ };
33
+ const addDocumentHistoryCommandsDefinition = (program, helpers) => {
34
+ const wording = wordsOf(helpers.words);
35
+ const { prefix, text } = wording;
36
+ const documents = documentsGroup(program, wording);
37
+ const reference = async (history, principal, input) => {
38
+ const found = await history.reference(principal, /^document:\d+$/.test(input) ? input : helpers.id(input));
39
+ if (!found)
40
+ throw new CliError("not_found", "this document is not in the selected profile's local copy", {
41
+ reason: "document.not-imported",
42
+ });
43
+ return found;
44
+ };
45
+ examples(annotate(documents.command("history"), { effects: LOCAL_READ })
46
+ .argument("<document>", text.documentArgument)
47
+ .description("list the versions of a document kept in the local copy, or show one with --revision"), [`${prefix} documents history DOC_ID`, `${prefix} documents history DOC_ID --revision 3`])
48
+ .option("--revision <n>", "show the text of this version", positive)
49
+ .action((input, args) => helpers.run(async (history, principal) => {
50
+ const ref = await reference(history, principal, input);
51
+ if (args.revision !== undefined) {
52
+ helpers.output(itemOf({ document: ref, ...(await history.version(ref, args.revision)) }));
53
+ return;
54
+ }
55
+ helpers.output(itemOf(await history.versions(ref)));
56
+ }));
57
+ return examples(annotate(program.command("changes"), { effects: LOCAL_READ }).description("list the documents the sync added, changed, removed or brought back, newest first"), [`${prefix} changes`, `${prefix} changes --since 7d --event deleted,unavailable`])
58
+ .option("--since <when>", "from this time: an ISO 8601 time, today, yesterday, or 30m, 2h, 1d ago", "1d")
59
+ .option("--until <when>", "up to this time, in the same forms")
60
+ .option(`--event <events>`, `only these, comma separated: ${DOCUMENT_EVENTS.join(", ")}`, eventList)
61
+ .option("--limit <n>", "how many changes to return", positive, 50)
62
+ .option("--page <n>", "which page to return", positive, 1)
63
+ .action((args) => helpers.run(async (history, principal) => {
64
+ const now = Date.now();
65
+ const since = new Date(momentOf(args.since, "--since", now)).toISOString();
66
+ const until = args.until === undefined
67
+ ? undefined
68
+ : new Date(momentOf(args.until, "--until", now, { end: true })).toISOString();
69
+ const found = await history.changes(principal, {
70
+ since,
71
+ ...(until ? { until } : {}),
72
+ ...(args.event ? { events: args.event } : {}),
73
+ limit: args.limit,
74
+ offset: (args.page - 1) * args.limit,
75
+ });
76
+ helpers.output(listOf("changes", {
77
+ items: found.items,
78
+ limit: args.limit,
79
+ has_more: found.hasMore,
80
+ page: args.page,
81
+ args: { since, ...(until ? { until } : {}), ...(args.event ? { event: args.event } : {}) },
82
+ }));
83
+ }));
84
+ };
85
+ /**
86
+ * `documents history <document>` and `changes`, over the selected profile's local history: every version a sync
87
+ * replaced or removed, and what changed since a time. A CLI whose `documents` group is its own gets them there too.
88
+ */
89
+ export const addDocumentHistoryCommands = honoursDryRun(sharedCommand(addDocumentHistoryCommandsDefinition));
@@ -2,6 +2,7 @@ import type { Command } from "commander";
2
2
  import { type DocumentCatalogCommands } from "./catalog.js";
3
3
  import { type LocalDocumentCommands } from "./documents.js";
4
4
  import { type DocumentFolderCommands } from "./folders.js";
5
+ import { type DocumentHistoryCommands } from "./history.js";
5
6
  import { type DocumentKnowledgeCommands } from "./knowledge.js";
6
7
  import { type DocumentMirrorCommands } from "./mirrors.js";
7
8
  import { type DocumentSearchCommands } from "./search.js";
@@ -9,7 +10,11 @@ import { type DocumentSyncCommands } from "./sync.js";
9
10
  import type { DocumentWords } from "./words.js";
10
11
  export { addDocumentCatalogCommands, CATALOG_FIELDS, type CatalogTree, type CatalogTreeSource, catalogId, catalogOutput, catalogSource, catalogTree, type DocumentCatalog, type DocumentCatalogCommands, type DocumentCatalogStores, } from "./catalog.js";
11
12
  export { addLocalDocumentCommands, type ImportedDocument, type LocalDocumentCommands } from "./documents.js";
13
+ export { type FileConflictCommands, fileConflictsCommand } from "./file-conflicts.js";
14
+ export { addFileEditCommands, type FileEditCommands } from "./file-edit.js";
15
+ export { addFileUpdateCommand, type FileUpdateCommands, type FileUpdatePort } from "./file-update.js";
12
16
  export { addDocumentFolderCommands, type DocumentFolderCommands } from "./folders.js";
17
+ export { addDocumentHistoryCommands, DOCUMENT_HISTORY_SETTINGS, type DocumentHistoryCommands, type DocumentHistoryPort, keepVersionsForDays, } from "./history.js";
13
18
  export { addDocumentKnowledgeCommands, type DocumentKnowledgeCommands, type DocumentKnowledgePort, } from "./knowledge.js";
14
19
  export { addDocumentMirrorCommands, type DocumentMirrorCommands, type DocumentMirrorConnection } from "./mirrors.js";
15
20
  export { documentQueries, FACT_QUERY, factItem, folderRow, IDENTITY_ROLES, identityRow, linkRow, MEMORY_QUERY, MEMORY_SEARCH_QUERY, memoryItem, memorySearch, mirrorRow, tagRow, } from "./queries.js";
@@ -28,10 +33,12 @@ export interface DocumentCommands<S> {
28
33
  catalog: Group<DocumentCatalogCommands>;
29
34
  knowledge: Group<DocumentKnowledgeCommands>;
30
35
  mirrors?: Group<DocumentMirrorCommands<S>>;
36
+ /** `documents history` and `changes`, over the local history; left out, a CLI has neither. */
37
+ history?: Group<DocumentHistoryCommands>;
31
38
  }
32
39
  /**
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.
40
+ * `folders`, `sync`, `status`, `documents list|show|export|context`, when given `documents history` and `changes`,
41
+ * `search`, `catalog`, the knowledge groups and, when given, `mirrors`, in that order. Answers the `documents` group, for the CLI's live subcommands.
35
42
  */
36
43
  export declare const addDocumentCommands: <S>(program: Command, options: DocumentCommands<S>) => Command;
37
44
  export { claimDocumentAccount, type DocumentLibraryOptions, type DocumentLibraryTools, type DocumentSourceRun, type DocumentWarning, documentLibraryCommands, documentProfile, } from "./library.js";
@@ -1,13 +1,18 @@
1
1
  import { addDocumentCatalogCommands } from "./catalog.js";
2
2
  import { addLocalDocumentCommands } from "./documents.js";
3
3
  import { addDocumentFolderCommands } from "./folders.js";
4
+ import { addDocumentHistoryCommands } from "./history.js";
4
5
  import { addDocumentKnowledgeCommands } from "./knowledge.js";
5
6
  import { addDocumentMirrorCommands } from "./mirrors.js";
6
7
  import { addDocumentSearchCommand } from "./search.js";
7
8
  import { addDocumentSyncCommands } from "./sync.js";
8
9
  export { addDocumentCatalogCommands, CATALOG_FIELDS, catalogId, catalogOutput, catalogSource, catalogTree, } from "./catalog.js";
9
10
  export { addLocalDocumentCommands } from "./documents.js";
11
+ export { fileConflictsCommand } from "./file-conflicts.js";
12
+ export { addFileEditCommands } from "./file-edit.js";
13
+ export { addFileUpdateCommand } from "./file-update.js";
10
14
  export { addDocumentFolderCommands } from "./folders.js";
15
+ export { addDocumentHistoryCommands, DOCUMENT_HISTORY_SETTINGS, keepVersionsForDays, } from "./history.js";
11
16
  export { addDocumentKnowledgeCommands, } from "./knowledge.js";
12
17
  export { addDocumentMirrorCommands } from "./mirrors.js";
13
18
  export { documentQueries, FACT_QUERY, factItem, folderRow, IDENTITY_ROLES, identityRow, linkRow, MEMORY_QUERY, MEMORY_SEARCH_QUERY, memoryItem, memorySearch, mirrorRow, tagRow, } from "./queries.js";
@@ -15,14 +20,16 @@ export { addDocumentSearchCommand } from "./search.js";
15
20
  export { addDocumentSyncCommands } from "./sync.js";
16
21
  export { ageOf, staleCopy } from "./words.js";
17
22
  /**
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.
23
+ * `folders`, `sync`, `status`, `documents list|show|export|context`, when given `documents history` and `changes`,
24
+ * `search`, `catalog`, the knowledge groups and, when given, `mirrors`, in that order. Answers the `documents` group, for the CLI's live subcommands.
20
25
  */
21
26
  export const addDocumentCommands = (program, options) => {
22
27
  const shared = { words: options.words, output: options.output };
23
28
  addDocumentFolderCommands(program, { ...shared, ...options.folders });
24
29
  addDocumentSyncCommands(program, { ...shared, ...options.sync });
25
30
  const documents = addLocalDocumentCommands(program, { ...shared, ...options.documents });
31
+ if (options.history)
32
+ addDocumentHistoryCommands(program, { ...shared, ...options.history });
26
33
  addDocumentSearchCommand(program, { ...shared, ...options.search });
27
34
  addDocumentCatalogCommands(program, { ...shared, ...options.catalog });
28
35
  addDocumentKnowledgeCommands(program, { ...shared, ...options.knowledge });
@@ -22,6 +22,7 @@ import { ProfileTokenStore } from "../profile-token.js";
22
22
  import { addDocumentCatalogCommands } from "./catalog.js";
23
23
  import { addLocalDocumentCommands } from "./documents.js";
24
24
  import { addDocumentFolderCommands } from "./folders.js";
25
+ import { addDocumentHistoryCommands, keepVersionsForDays } from "./history.js";
25
26
  import { addDocumentKnowledgeCommands } from "./knowledge.js";
26
27
  import { factItem, memoryItem } from "./queries.js";
27
28
  import { addDocumentSearchCommand } from "./search.js";
@@ -351,6 +352,7 @@ export const documentLibraryCommands = (options) => {
351
352
  errorOf,
352
353
  assertHeld,
353
354
  storeVersion: app.version,
355
+ keepVersionsForDays: keepVersionsForDays(context().settings),
354
356
  ...(environmentOf(command()).signal ? { signal: environmentOf(command()).signal } : {}),
355
357
  ...(rescan ? { rescan } : {}),
356
358
  ...(budget ? { budget } : {}),
@@ -421,6 +423,13 @@ export const documentLibraryCommands = (options) => {
421
423
  },
422
424
  lastSync: () => files().state("").read().lastSync,
423
425
  },
426
+ history: {
427
+ run: (fn) => {
428
+ const account = principal();
429
+ return withStore(false, (store) => fn(options.ingestion(store).history, account));
430
+ },
431
+ id: (input) => options.idOf(input),
432
+ },
424
433
  search: {
425
434
  search: (query, searchOptions) => {
426
435
  const account = principal();
@@ -509,6 +518,7 @@ export const documentLibraryCommands = (options) => {
509
518
  addDocumentFolderCommands(holder, { ...shared, ...groups.folders });
510
519
  addDocumentSyncCommands(holder, { ...shared, ...groups.sync });
511
520
  addLocalDocumentCommands(holder, { ...shared, ...groups.documents });
521
+ addDocumentHistoryCommands(holder, { ...shared, ...groups.history });
512
522
  addDocumentSearchCommand(holder, { ...shared, ...groups.search });
513
523
  addDocumentCatalogCommands(holder, { ...shared, ...groups.catalog });
514
524
  addDocumentKnowledgeCommands(holder, { ...shared, ...groups.knowledge });
@@ -35,6 +35,12 @@ export declare const commandPermissions: ({ keyOf, extra, defaults, alsoChecks,
35
35
  * parents. A key outside it is a typo that would otherwise do nothing (BUG-137).
36
36
  */
37
37
  export declare const knownPermissionKeys: (command: Command, keyOf?: PermissionKeySource, extra?: readonly PermissionKey[]) => Set<PermissionKey>;
38
+ /**
39
+ * Old keys of commands that moved, on the group that moved them (the generated `api` group, `api.contacts-list` →
40
+ * `api.contacts.list`): such a key is still refused like any unknown one (WC-CMD-8), and the refusal names the new key.
41
+ */
42
+ export declare const markRenamedPermissionKeys: (command: Command, renamed: ReadonlyMap<PermissionKey, PermissionKey>) => void;
43
+ export declare const renamedPermissionKeys: (command: Command) => Map<PermissionKey, PermissionKey>;
38
44
  /** The known keys one level under the unknown key's parent, to name in the refusal. */
39
45
  export declare const knownBeside: (key: PermissionKey, known: ReadonlySet<PermissionKey>) => PermissionKey[];
40
46
  export declare const unknownPermissionKeys: (levels: Readonly<Record<PermissionKey, unknown>>, known: ReadonlySet<PermissionKey>) => PermissionKey[];
@@ -67,6 +67,16 @@ export const knownPermissionKeys = (command, keyOf = (one) => keyForCommand(path
67
67
  add(key);
68
68
  return known;
69
69
  };
70
+ const RENAMED = new WeakMap();
71
+ /**
72
+ * Old keys of commands that moved, on the group that moved them (the generated `api` group, `api.contacts-list` →
73
+ * `api.contacts.list`): such a key is still refused like any unknown one (WC-CMD-8), and the refusal names the new key.
74
+ */
75
+ export const markRenamedPermissionKeys = (command, renamed) => {
76
+ if (renamed.size > 0)
77
+ RENAMED.set(command, renamed);
78
+ };
79
+ export const renamedPermissionKeys = (command) => new Map(everyCommand(rootOf(command)).flatMap((one) => [...(RENAMED.get(one) ?? [])]));
70
80
  /** The known keys one level under the unknown key's parent, to name in the refusal. */
71
81
  export const knownBeside = (key, known) => {
72
82
  const parent = key.split(".").slice(0, -1).join(".");
@@ -82,7 +92,7 @@ export const unknownPermissionIssues = (command, settings, tool, keyOf) => {
82
92
  Object.keys(settings.permissions)
83
93
  .filter((key) => key !== CEILING_KEY && settings.permissionSources[key] !== "flag")
84
94
  .map((key) => ({ key, at: ["profiles", settings.profile, "permissions", key] }));
85
- return permissionIssues(saved, knownPermissionKeys(command, keyOf), { file: settings.configPath, tool }).map(publicIssue);
95
+ return permissionIssues(saved, knownPermissionKeys(command, keyOf), { file: settings.configPath, tool }, renamedPermissionKeys(command)).map(publicIssue);
86
96
  };
87
97
  /**
88
98
  * A saved key no command checks would do nothing, so the command refuses to run and names the unset that removes
@@ -94,6 +104,8 @@ export const refuseUnknownPermissionKeys = (command, settings, tool, keyOf) => {
94
104
  throw new CliError("configuration_error", issueMessage(issues), { permission: issues[0]?.key });
95
105
  const flagged = Object.keys(settings.permissions).filter((key) => settings.permissionSources[key] === "flag");
96
106
  const [key] = unknownPermissionKeys(Object.fromEntries(flagged.map((one) => [one, true])), knownPermissionKeys(command, keyOf));
97
- if (key !== undefined)
98
- throw new CliError("validation_error", `--permission ${key} names no command`, { permission: key });
107
+ if (key === undefined)
108
+ return;
109
+ const now = renamedPermissionKeys(command).get(key);
110
+ throw new CliError("validation_error", `--permission ${key} names no command${now === undefined ? "" : `: its command moved, so use ${now}`}`, { permission: key });
99
111
  };
@@ -6,7 +6,7 @@ import type * as v from "valibot";
6
6
  import type { AppIdentity } from "../ports/app.js";
7
7
  import type { Level, PermissionKey } from "../sends/permissions.js";
8
8
  import { type ApiCommandInput } from "./bot/api.js";
9
- import type { ConditionalKey } from "./permission-keys.js";
9
+ import { type ConditionalKey } from "./permission-keys.js";
10
10
  import { type ServiceApiManifest } from "./service-api-manifest.js";
11
11
  import type { Configuration } from "./settings.js";
12
12
  /** A key a call's body implies in a way no flag names, as notion's `agent-batch` with an action `delete`. */
@@ -15,6 +15,7 @@ import { NO_EFFECTS } from "./effects.js";
15
15
  import { itemOf, listOf, renderAnswer } from "./envelope.js";
16
16
  import { queryTerms, termField, withQuery } from "./list-query.js";
17
17
  import { terminalAsker } from "./messenger/ask.js";
18
+ import { markRenamedPermissionKeys } from "./permission-keys.js";
18
19
  import { manifestBaseUrl, nextPage, parameterValue, signRequest, underBase, } from "./service-api-manifest.js";
19
20
  /**
20
21
  * The operations the `api` group offers, and why it leaves out the rest: one that answers with a credential needs a
@@ -38,9 +39,8 @@ const keyOf = (operation) => ["api", ...apiPathOf(operation)].join(".");
38
39
  /** `contacts list`: what follows `api` on the command line. */
39
40
  const pathOf = (operation) => apiPathOf(operation).join(" ");
40
41
  /**
41
- * The key a grouped operation had while `api` was flat, `api.contacts-list`. A profile that still names it keeps its
42
- * hold on that one command: checked beside the new key, it only ever tightens. A group never takes an old command's
43
- * name (the generator refuses it), so the old key never reaches past its command.
42
+ * The key a grouped operation had while `api` was flat, `api.contacts-list`. It checks nothing now: a config that still
43
+ * names it is refused as an unknown key, and the refusal names the new key (WC-CMD-8).
44
44
  */
45
45
  const formerKeyOf = (operation) => {
46
46
  const former = `api.${operation.command}`;
@@ -100,27 +100,18 @@ export const serviceApiKeys = (input, operation, call) => {
100
100
  */
101
101
  export const serviceApiPermissions = (input) => {
102
102
  const checks = new Map();
103
- const former = [];
104
103
  for (const operation of input.manifest.operations) {
105
- const old = formerKeyOf(operation);
106
- if (old)
107
- former.push(old);
108
104
  checks.set(pathOf(operation), [
109
105
  ...permissionsOf(operation).map((permission) => {
110
106
  const when = whenOf(permission);
111
107
  return when === undefined ? permission.key : { key: permission.key, when };
112
108
  }),
113
109
  ...(input.bodyPermissions?.[operation.command] ?? []).map(({ key, when }) => ({ key, when })),
114
- ...(old ? [{ key: old, when: "while a profile still names this old key" }] : []),
115
110
  ]);
116
111
  }
117
- const keys = [
118
- ...new Set([...checks.values()]
119
- .flat()
120
- .flatMap((one) => (typeof one === "string" ? [one] : former.includes(one.key) ? [] : [one.key]))),
121
- ];
112
+ const keys = [...new Set([...checks.values()].flat().map((one) => (typeof one === "string" ? one : one.key)))];
122
113
  return {
123
- extra: [...keys, ...former],
114
+ extra: keys,
124
115
  alsoChecks: (path) => (path[0] === "api" ? (checks.get(path.slice(1).join(" ")) ?? []) : []),
125
116
  defaults: {
126
117
  ...Object.fromEntries(keys.map((key) => [key, "ask"])),
@@ -252,22 +243,10 @@ const serviceApiCore = (options) => {
252
243
  throw error;
253
244
  }
254
245
  };
255
- /** The old flat key, when the profile names it: on a read only its refusal or its question applies. */
256
- const formerKeys = (command, operation) => {
257
- const former = formerKeyOf(operation);
258
- if (!former)
259
- return [];
260
- const { settings, renderer } = baseContext(command, configuration.resolveSettings);
261
- const level = settings.permissions[former];
262
- if (level === undefined)
263
- return [];
264
- renderer.warn(`permissions name ${former}, the old key of api ${pathOf(operation)}: rename it to ${keyOf(operation)}`);
265
- return operation.effect === "read" && level !== "deny" && level !== "ask" ? [] : [former];
266
- };
267
246
  /**
268
247
  * The refusal `execute` would give, before the body is read: a `deny` stops a call whatever its input, and a missing
269
- * body must not answer `validation_error` in its place. Only the keys known without the body; the rest, and an old
270
- * flat key (which warns), wait for `execute`.
248
+ * body must not answer `validation_error` in its place. Only the keys known without the body; the rest wait for
249
+ * `execute`.
271
250
  */
272
251
  const refuseBeforeBody = (command, operation) => {
273
252
  const extra = permissionsOf(operation)
@@ -283,7 +262,6 @@ const serviceApiCore = (options) => {
283
262
  baseUrlOf,
284
263
  defaults,
285
264
  exchange,
286
- formerKeys,
287
265
  operationOf,
288
266
  readsFreely,
289
267
  refuseBeforeBody,
@@ -292,8 +270,8 @@ const serviceApiCore = (options) => {
292
270
  };
293
271
  };
294
272
  export const serviceApiCommand = (options) => {
295
- const { app, configuration } = options;
296
- const { operations, baseUrlOf, exchange, formerKeys, operationOf, readsFreely, refuseBeforeBody, signed, write } = serviceApiCore(options);
273
+ const { app, configuration, manifest } = options;
274
+ const { operations, baseUrlOf, exchange, operationOf, readsFreely, refuseBeforeBody, signed, write } = serviceApiCore(options);
297
275
  const send = async (command, operation, request) => (await exchange(command, operation, request)).answer;
298
276
  let schemas;
299
277
  const loaded = () => {
@@ -374,7 +352,7 @@ export const serviceApiCommand = (options) => {
374
352
  command.hook("preAction", load);
375
353
  },
376
354
  execute: async (command, operation, input) => {
377
- const extra = [...serviceApiKeys(options, operation, input), ...formerKeys(command, operation)];
355
+ const extra = serviceApiKeys(options, operation, input);
378
356
  const read = readsFreely(command, operation, extra);
379
357
  if (operation.pagination && command.opts().all === true) {
380
358
  if (!read)
@@ -422,6 +400,10 @@ export const serviceApiCommand = (options) => {
422
400
  group.addCommand(list).addCommand(show);
423
401
  for (const child of [...generated.commands])
424
402
  group.addCommand(child);
403
+ markRenamedPermissionKeys(group, new Map(manifest.operations.flatMap((operation) => {
404
+ const former = formerKeyOf(operation);
405
+ return former ? [[former, keyOf(operation)]] : [];
406
+ })));
425
407
  return group;
426
408
  };
427
409
  // Code may pass a number, a boolean or a list where a person types text; the check reads the text it stands for.
@@ -442,7 +424,7 @@ const writerBody = (operation, input, schemas) => {
442
424
  * can be asked. A read that no key guards goes through `serviceApiCall`.
443
425
  */
444
426
  export const serviceApiWriter = (options) => {
445
- const { baseUrlOf, formerKeys, operationOf, signed, write } = serviceApiCore(options);
427
+ const { baseUrlOf, operationOf, signed, write } = serviceApiCore(options);
446
428
  return async (command, name, input, { confirmed } = {}) => {
447
429
  const operation = operationOf(name);
448
430
  // The api group offers only declared parameters; code must not reach further, as WordPress's `_method` turns a
@@ -468,6 +450,6 @@ export const serviceApiWriter = (options) => {
468
450
  throw new CliError("validation_error", problem);
469
451
  }
470
452
  const request = await signed(command, operation, httpApiRequest(operation, writerBody(operation, input, schemas), baseUrlOf(command)));
471
- return write(command, operation, [...extra, ...formerKeys(command, operation)], request, confirmed);
453
+ return write(command, operation, extra, request, confirmed);
472
454
  };
473
455
  };
@@ -71,6 +71,21 @@ export interface FileEntry {
71
71
  localSize: number;
72
72
  syncedAt: string;
73
73
  }
74
+ /**
75
+ * A conflict the last sync left: why, when, and the contents it found. A side that deleted the file has no hash. The
76
+ * store keeps all three (`kept`) for a text file the merge could not settle; for other files only the hashes are
77
+ * known, and a resolution reads the sides again.
78
+ */
79
+ export interface FileConflict {
80
+ reason: string;
81
+ at: string;
82
+ base?: string;
83
+ local?: string;
84
+ remote?: string;
85
+ /** The remote file as the listing saw it. */
86
+ remoteFile?: RemoteFile;
87
+ kept?: boolean;
88
+ }
74
89
  export interface FileMirrorState {
75
90
  version: 1;
76
91
  principal: string;
@@ -104,9 +119,11 @@ export interface FileMirrorState {
104
119
  next: string;
105
120
  files: RemoteFile[];
106
121
  };
122
+ /** The conflicts the last sync left, by path; each sync replaces them, and a resolution removes its own. */
123
+ conflicts?: Record<string, FileConflict>;
107
124
  }
108
125
  export interface FileMirrorStatePort {
109
126
  read(): FileMirrorState;
110
127
  save(state: FileMirrorState): void;
111
128
  }
112
- export type FileStepKind = "upload" | "download" | "adopt" | "trash-remote" | "trash-local" | "rename-local" | "keep-both" | "forget" | "conflict" | "unknown";
129
+ export type FileStepKind = "upload" | "download" | "adopt" | "trash-remote" | "trash-local" | "rename-local" | "keep-both" | "merge" | "forget" | "conflict" | "unknown";
@@ -9,16 +9,19 @@ export { conflictReport, fileMirrorState, type HeldLock, type Mirror, type Mirro
9
9
  export type { SyncOptions } from "../services/documents/ports.js";
10
10
  export { extractDocumentMemories, type ImportedSource, type ProposalOptions } from "../services/documents/proposals.js";
11
11
  export { type MirrorAction, type PushConflict, type PushOptions, type PushResult, planPush, pushDocuments, scanLocal, skippedName, } from "../services/documents/push.js";
12
- export { type SyncResult, syncDocuments } from "../services/documents/sync.js";
12
+ export { KEEP_VERSIONS_FOR_DAYS, type SyncResult, syncDocuments } from "../services/documents/sync.js";
13
+ export { type FileConflictResolution, type FileConflictResolveOptions, type FileConflictVersion, type FileConflictView, listFileConflicts, resolveFileConflict, showFileConflict, } from "../services/files/conflicts.js";
13
14
  export { excludedBy, exclusionPattern } from "../services/files/exclusions.js";
15
+ export { type GuardedFileWrite, type GuardedFileWriteResult, guardedFileWrite, } from "../services/files/guarded-write.js";
14
16
  export { type FileMirrorOptions, type FileMirrorResult, type FileMirrorSyncOptions, type FileStep, fileMirrorStatus, fileRemoteChanges, fileSyncState, MAX_DELETIONS, MAX_REPLACEMENTS, type MirrorHints, syncFileMirror, syncFileMirrors, } from "../services/files/mirror.js";
15
- export { type FileVersion, type FileVersions, fileVersions, restoreFileVersion, type VersionDirection, type VersionEvent, } from "../services/files/versions.js";
17
+ export { MAX_MERGE_BYTES, mergeable, mergeText, type TextMerge, type TextSegment, } from "../services/files/text-merge.js";
18
+ export { type FileVersion, type FileVersions, fileVersions, restoreFileVersion, type VersionDirection, type VersionEvent, type VersionParts, type VersionRole, } from "../services/files/versions.js";
16
19
  export { type Block, blockKey, blockShape, type Inline, type ListKind, normalizeInlines } from "./blocks.js";
17
20
  export { catalogFiles } from "./catalog.js";
18
- export type { Expect, FileEntry, FileMirrorState, FileMirrorStatePort, FileStepKind, FileTarget, RemoteFile, } from "./file-mirror-model.js";
21
+ export type { Expect, FileConflict, FileEntry, FileMirrorState, FileMirrorStatePort, FileStepKind, FileTarget, RemoteFile, } from "./file-mirror-model.js";
19
22
  export { htmlToMarkdown, markdownToHtml } from "./html-markdown.js";
20
23
  export { markdownBlocks, type PlacedBlock, placedMarkdownBlocks } from "./markdown-blocks.js";
21
- export type { DocumentSource, FeedlessDocumentSource, IndexedSource, PictureWriter, SourceChange, SourceContent, SourceFile, SourceIndex, SourceSkip, SourceState, SourceStatePort, SourceWalk, SourceWork, TabText, } from "./model.js";
24
+ export type { DocumentSource, FeedlessDocumentSource, IndexedSource, PictureWriter, SourceChange, SourceContent, SourceFile, SourceIndex, SourceRemoval, SourceSkip, SourceState, SourceStatePort, SourceWalk, SourceWork, TabText, } from "./model.js";
22
25
  export { feedOf } from "./model.js";
23
26
  export type { ConflictPart, DocumentTarget, Keep, LocalDocument, Prepared, PushEntry, Pushed, PushPlan, PushState, PushStatePort, RemoteChange, } from "./push-model.js";
24
27
  export { inScope, type SourceQuery, within } from "./scope.js";