@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
@@ -1,11 +1,21 @@
1
1
  import { type HeldLock } from "../documents/mirrors.js";
2
- /** Which way a sync moved a change. */
3
- export type VersionDirection = "local-to-remote" | "remote-to-local" | "restored";
2
+ /** Which way a sync moved a change; `both` is a merge or a conflict's resolution, written to both sides. */
3
+ export type VersionDirection = "local-to-remote" | "remote-to-local" | "restored" | "both";
4
+ /** The contents a merge, a conflict or its resolution worked from: the last sync's, and each side's. */
5
+ export interface VersionParts {
6
+ base?: string;
7
+ local?: string;
8
+ remote?: string;
9
+ }
4
10
  /** One line of a mirror's version log: what a sync did to a path, with the content's hash before and after. */
5
11
  export interface VersionEvent {
6
12
  at: string;
7
13
  path: string;
8
- event: "created" | "changed" | "deleted" | "renamed";
14
+ /**
15
+ * `merged`: both sides' changes merged into `new`. `conflict`: they could not be, and `parts` were kept. `resolved`:
16
+ * the owner settled the conflict with `new`, as `resolution` says.
17
+ */
18
+ event: "created" | "changed" | "deleted" | "renamed" | "merged" | "conflict" | "resolved";
9
19
  direction: VersionDirection;
10
20
  /** The content the change replaced: the local file kept before a pull or deletion, the remote version an upload replaced. */
11
21
  old?: string;
@@ -17,10 +27,22 @@ export interface VersionEvent {
17
27
  size?: number;
18
28
  /** A rename's new path. */
19
29
  to?: string;
30
+ /** A merge's, a conflict's or a resolution's contents; with `new`, kept for good. */
31
+ parts?: VersionParts;
32
+ /** How the owner resolved a conflict: kept one side, both, or gave the final file. */
33
+ resolution?: "local" | "remote" | "both" | "file";
20
34
  }
35
+ /** Which content of a merge or a conflict a kept version is; `result` is the merge's or the resolution's. */
36
+ export type VersionRole = "base" | "local" | "remote" | "result";
21
37
  /** A version of a path, and whether its bytes are still in the store. */
22
38
  export interface FileVersion extends VersionEvent {
23
39
  available: boolean;
40
+ /** Each content of a merge, a conflict or a resolution, and whether the store still has it. */
41
+ versions?: {
42
+ role: VersionRole;
43
+ sha256: string;
44
+ available: boolean;
45
+ }[];
24
46
  }
25
47
  export interface FileVersions {
26
48
  /** The folder the store keeps its copies in, when it is on disk: a sync checks its free space first. */
@@ -34,6 +56,8 @@ export interface FileVersions {
34
56
  keep(source: string | ((temp: string) => Promise<void>)): Promise<string>;
35
57
  /** Whether the store holds this content. */
36
58
  has(sha256: string): boolean;
59
+ /** A kept content's bytes, or undefined when the store does not hold it. Meant for text a merge reads whole. */
60
+ read(sha256: string): Promise<Buffer | undefined>;
37
61
  log(event: Omit<VersionEvent, "at">): void;
38
62
  /** Every event of `path`, oldest first, including renames to or from it. */
39
63
  list(path: string): FileVersion[];
@@ -42,15 +66,18 @@ export interface FileVersions {
42
66
  * undefined. False when the store no longer has the version or the file was not as `over` said.
43
67
  */
44
68
  write(sha256: string, into: string, over?: string): Promise<boolean>;
45
- /** Applies the retention rule; see `fileVersions`. A sync runs it under its lock; call it only under that lock. */
46
- prune(): Promise<void>;
69
+ /**
70
+ * Applies the retention rule; see `fileVersions`. `pinned` stay too: a mirror's last synced contents, the base of
71
+ * its next merge. A sync runs it under its lock; call it only under that lock.
72
+ */
73
+ prune(pinned?: Iterable<string>): Promise<void>;
47
74
  }
48
75
  /**
49
76
  * A mirror's local version store: `<dir>/objects/<sha256>` holds each kept content once, `<dir>/log.jsonl` is
50
- * append-only. The store lives under the profile's state folder, never inside the mirrored folder. Retention, one
51
- * rule: a content stays while an event newer than 30 days names it, and the last content of a path whose newest
52
- * event is a deletion stays for good. A content no event names stays 30 days after it was last kept, so a crash
53
- * between keeping a file and logging the change loses nothing.
77
+ * append-only. The store lives under the profile's state folder, never inside the mirrored folder. Retention: a
78
+ * content stays while an event newer than 30 days names it; the last content of a path whose newest event is a
79
+ * deletion, and every content a merge, a conflict or a resolution names, stay for good. A content no event names stays
80
+ * 30 days after it was last kept, so a crash between keeping a file and logging the change loses nothing.
54
81
  */
55
82
  export declare const fileVersions: (dir: string, now?: () => number) => FileVersions;
56
83
  /**
@@ -1,6 +1,6 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import { appendFileSync, createReadStream, createWriteStream, existsSync, mkdirSync, readFileSync } from "node:fs";
3
- import { mkdir, readdir, rename, rm, stat, utimes } from "node:fs/promises";
3
+ import { mkdir, readdir, readFile, rename, rm, stat, utimes } from "node:fs/promises";
4
4
  import { join } from "node:path";
5
5
  import { Transform } from "node:stream";
6
6
  import { pipeline } from "node:stream/promises";
@@ -36,12 +36,23 @@ const copyHashed = async (from, into) => {
36
36
  }), createWriteStream(into, { flags: "wx", mode: 0o600 }));
37
37
  return hash.digest("hex");
38
38
  };
39
+ const rolesOf = (event) => {
40
+ if (!event.parts)
41
+ return [];
42
+ const { base, local, remote } = event.parts;
43
+ return [
44
+ ...(base ? [{ role: "base", sha256: base }] : []),
45
+ ...(local ? [{ role: "local", sha256: local }] : []),
46
+ ...(remote ? [{ role: "remote", sha256: remote }] : []),
47
+ ...(event.new ? [{ role: "result", sha256: event.new }] : []),
48
+ ];
49
+ };
39
50
  /**
40
51
  * A mirror's local version store: `<dir>/objects/<sha256>` holds each kept content once, `<dir>/log.jsonl` is
41
- * append-only. The store lives under the profile's state folder, never inside the mirrored folder. Retention, one
42
- * rule: a content stays while an event newer than 30 days names it, and the last content of a path whose newest
43
- * event is a deletion stays for good. A content no event names stays 30 days after it was last kept, so a crash
44
- * between keeping a file and logging the change loses nothing.
52
+ * append-only. The store lives under the profile's state folder, never inside the mirrored folder. Retention: a
53
+ * content stays while an event newer than 30 days names it; the last content of a path whose newest event is a
54
+ * deletion, and every content a merge, a conflict or a resolution names, stay for good. A content no event names stays
55
+ * 30 days after it was last kept, so a crash between keeping a file and logging the change loses nothing.
45
56
  */
46
57
  export const fileVersions = (dir, now = Date.now) => {
47
58
  const objects = join(dir, "objects");
@@ -59,7 +70,7 @@ export const fileVersions = (dir, now = Date.now) => {
59
70
  throw error;
60
71
  }
61
72
  };
62
- const has = (sha256) => existsSync(join(objects, sha256));
73
+ const has = (sha256) => /^[0-9a-f]{64}$/.test(sha256) && existsSync(join(objects, sha256));
63
74
  return {
64
75
  dir,
65
76
  keep: async (source) => {
@@ -91,16 +102,31 @@ export const fileVersions = (dir, now = Date.now) => {
91
102
  }
92
103
  },
93
104
  has,
105
+ read: async (sha256) => {
106
+ if (!has(sha256))
107
+ return undefined;
108
+ return readFile(join(objects, sha256)).catch((error) => {
109
+ if (error.code === "ENOENT")
110
+ return undefined;
111
+ throw error;
112
+ });
113
+ },
94
114
  log: (event) => {
95
115
  mkdirSync(dir, { recursive: true, mode: 0o700 });
96
116
  appendFileSync(logPath, `${JSON.stringify({ at: new Date(now()).toISOString(), ...event })}\n`, { mode: 0o600 });
97
117
  },
98
118
  list: (path) => {
99
119
  const found = events().filter((event) => event.path === path || event.to === path);
100
- return found.map((event) => ({
101
- ...event,
102
- available: event.old !== undefined && existsSync(join(objects, event.old)),
103
- }));
120
+ return found.map((event) => {
121
+ const roles = rolesOf(event);
122
+ return {
123
+ ...event,
124
+ available: roles.length
125
+ ? roles.every(({ sha256 }) => has(sha256))
126
+ : event.old !== undefined && has(event.old),
127
+ ...(roles.length ? { versions: roles.map((role) => ({ ...role, available: has(role.sha256) })) } : {}),
128
+ };
129
+ });
104
130
  },
105
131
  write: async (sha256, into, over) => {
106
132
  if (!has(sha256))
@@ -108,9 +134,9 @@ export const fileVersions = (dir, now = Date.now) => {
108
134
  const copy = (temp) => pipeline(createReadStream(join(objects, sha256)), createWriteStream(temp, { flags: "wx" }));
109
135
  return (await replaceLocal(into, over, copy, { sha256 })) !== undefined;
110
136
  },
111
- prune: async () => {
137
+ prune: async (pinned = []) => {
112
138
  const all = events();
113
- const keep = new Set();
139
+ const keep = new Set(pinned);
114
140
  const last = new Map();
115
141
  for (const event of all) {
116
142
  last.set(event.path, event);
@@ -118,6 +144,8 @@ export const fileVersions = (dir, now = Date.now) => {
118
144
  for (const hash of [event.old, event.new])
119
145
  if (hash)
120
146
  keep.add(hash);
147
+ for (const { sha256 } of rolesOf(event))
148
+ keep.add(sha256);
121
149
  }
122
150
  for (const event of last.values())
123
151
  if (event.event === "deleted" && event.old)
@@ -14,12 +14,12 @@ export declare const metadataService: (deps: ServiceDeps) => {
14
14
  dryRun?: boolean;
15
15
  }) => Promise<{
16
16
  items: ({
17
- error?: undefined;
18
17
  chatId: string;
19
18
  tags: import("../domain/channel-tags.js").ChannelTagMatch[];
20
19
  algorithm: string;
21
20
  fetchedAt: string | null;
22
21
  source: string;
22
+ error?: undefined;
23
23
  } | {
24
24
  tags?: undefined;
25
25
  algorithm?: undefined;
@@ -56,6 +56,7 @@ export { type ChangeFilter, CRM_CHANGES, type CrmChange, type CrmChangeKind } fr
56
56
  export { COMPANY_TYPE_MEANINGS, type CompanyTypeMeaning, CRM_LINK_MODES, type CrmLinkMode, type CrmStageMove, type CrmStageTasks, crmSettingKey, type StageTaskRule, } from "./sqlite/crm-settings.js";
57
57
  export type { Deal, DealFilter, DealInput, DealPerson, DealScope, DealsStore, FunnelStage, Pipeline, PipelineInput, PipelineReport, PipelineStage, StageChange, } from "./sqlite/deals.js";
58
58
  export type { DecisionMessage, DecisionPress, DecisionRefusal, DecisionRequest, DecisionRequestInput, DecisionRequestStore, TakeResult, } from "./sqlite/decision-requests.js";
59
+ export { DOCUMENT_EVENTS, DOCUMENT_REMOVALS, type DocumentChange, type DocumentEvent, type DocumentHistoryAnswer, type DocumentHistoryStore, type DocumentRemoval, type DocumentVersion, type DocumentVersionText, type VersionReason, } from "./sqlite/document-history.js";
59
60
  export { DOCUMENT_KINDS, type DocumentDetail, type DocumentFolderNode, type DocumentKind, type DocumentLink, type DocumentListFilter, type DocumentListing, type DocumentListRow, type DocumentSourceNode, } from "./sqlite/document-listing.js";
60
61
  export type { Email, EmailAddress, EmailAttachment, EmailFacts, EmailFilter, EmailInput, EmailInThread, EmailLocationInput, EmailRecipient, EmailRef, EmailThread, EmailVectorHit, FolderEmail, Mailbox, MailboxInput, MailFilter, MailStore, PartialEmail, SenderScore, ThreadDetails, ThreadSave, } from "./sqlite/emails.js";
61
62
  export { EVENT_FIELDS, type EventChunkToEmbed, type EventHit, type EventQuery, type EventSearch, type NearestEvent, } from "./sqlite/event-search.js";
@@ -36,6 +36,7 @@ export { CATALOG_QUERY } from "./sqlite/catalog.js";
36
36
  export { crmIdentityId, } from "./sqlite/crm.js";
37
37
  export { CRM_CHANGES } from "./sqlite/crm-changes.js";
38
38
  export { COMPANY_TYPE_MEANINGS, CRM_LINK_MODES, crmSettingKey, } from "./sqlite/crm-settings.js";
39
+ export { DOCUMENT_EVENTS, DOCUMENT_REMOVALS, } from "./sqlite/document-history.js";
39
40
  export { DOCUMENT_KINDS, } from "./sqlite/document-listing.js";
40
41
  export { EVENT_FIELDS, } from "./sqlite/event-search.js";
41
42
  export { QUOTE_LIMIT, quoteKept } from "./sqlite/evidence-signature.js";
@@ -0,0 +1,84 @@
1
+ import type { CacheDatabase } from "../driver.js";
2
+ import type { StoreContext } from "./open.js";
3
+ type Row = Record<string, unknown>;
4
+ /** Why a sync took a document out of its copy. Only `deleted` is a deletion the source reported. */
5
+ export declare const DOCUMENT_REMOVALS: readonly ["deleted", "unavailable", "unsynced"];
6
+ export type DocumentRemoval = (typeof DOCUMENT_REMOVALS)[number];
7
+ /** What replaced a kept version: an edit, or one of the removals. */
8
+ export type VersionReason = "edited" | DocumentRemoval;
9
+ export declare const DOCUMENT_EVENTS: readonly ["added", "changed", "restored", "deleted", "unavailable", "unsynced"];
10
+ export type DocumentEvent = (typeof DOCUMENT_EVENTS)[number];
11
+ /** One earlier version of a document, as the store kept it before something replaced it. */
12
+ export interface DocumentVersion {
13
+ revision: number;
14
+ title: string | null;
15
+ reason: VersionReason;
16
+ /** When this version was replaced or removed; the current version's is when it was written. */
17
+ replacedAt: string | null;
18
+ current: boolean;
19
+ characters: number;
20
+ }
21
+ export interface DocumentVersionText extends DocumentVersion {
22
+ text: string;
23
+ frontMatter: unknown;
24
+ }
25
+ export interface DocumentHistoryAnswer {
26
+ ref: string;
27
+ title: string | null;
28
+ path: string;
29
+ revision: number;
30
+ deletedAt: string | null;
31
+ removal: DocumentRemoval | null;
32
+ /** Newest first, the current version at the top. */
33
+ versions: DocumentVersion[];
34
+ }
35
+ export interface DocumentChange {
36
+ ref: string;
37
+ path: string;
38
+ title: string | null;
39
+ event: DocumentEvent;
40
+ revision: number;
41
+ at: string;
42
+ }
43
+ export interface DocumentHistoryStore {
44
+ /** The document at this path of a documents account, a removed one too, as `document:<n>`. */
45
+ documentAt(folderId: string, path: string): Promise<string | undefined>;
46
+ documentHistory(reference: string): Promise<DocumentHistoryAnswer>;
47
+ documentVersion(reference: string, revision: number): Promise<DocumentVersionText>;
48
+ /** What changed in the account at or after `since` (ISO 8601), newest first. */
49
+ documentChanges(folderId: string, options: {
50
+ since: string;
51
+ until?: string;
52
+ events?: readonly DocumentEvent[];
53
+ limit: number;
54
+ offset: number;
55
+ }): Promise<{
56
+ items: DocumentChange[];
57
+ hasMore: boolean;
58
+ }>;
59
+ /**
60
+ * Drops the versions and the change log of the account older than `before` (ISO 8601), and the text of a document
61
+ * that has been unavailable since before then. Answers what it dropped.
62
+ */
63
+ pruneDocumentHistory(folderId: string, before: string): Promise<{
64
+ versions: number;
65
+ changes: number;
66
+ texts: number;
67
+ }>;
68
+ }
69
+ /**
70
+ * Keeps a document's text, title and front matter under its current revision before the caller replaces or removes
71
+ * them with `revision + 1`, so a citation reads back the words it cited and the history shows what was there.
72
+ */
73
+ export declare const keepRevision: (database: CacheDatabase, row: Row, at: number, reason?: VersionReason) => {
74
+ changes: number;
75
+ };
76
+ /** One line of the change log, from the document row as it is after the change. */
77
+ export declare const logDocumentChange: (database: CacheDatabase, id: number, event: DocumentEvent, at: number) => void;
78
+ /**
79
+ * Takes a document out of the live copy for `reason`. An unavailable one keeps its text, since the source may show it
80
+ * again; a deleted or unsynced one keeps its last text as a version and its body is blanked.
81
+ */
82
+ export declare const removeDocument: (database: CacheDatabase, id: number, at: number, reason: DocumentRemoval) => boolean;
83
+ export declare const documentHistoryOver: ({ database }: StoreContext) => DocumentHistoryStore;
84
+ export {};
@@ -0,0 +1,158 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { thingOf } from "./things.js";
3
+ import { write } from "./transaction.js";
4
+ /** Why a sync took a document out of its copy. Only `deleted` is a deletion the source reported. */
5
+ export const DOCUMENT_REMOVALS = ["deleted", "unavailable", "unsynced"];
6
+ export const DOCUMENT_EVENTS = ["added", "changed", "restored", ...DOCUMENT_REMOVALS];
7
+ const iso = (value) => (value == null ? null : new Date(Number(value)).toISOString());
8
+ const json = (value) => (value == null ? null : JSON.parse(String(value)));
9
+ /**
10
+ * Keeps a document's text, title and front matter under its current revision before the caller replaces or removes
11
+ * them with `revision + 1`, so a citation reads back the words it cited and the history shows what was there.
12
+ */
13
+ export const keepRevision = (database, row, at, reason = "edited") => database
14
+ .prepare("INSERT INTO document_revisions (document_id, body, revision, created_at, title, front_matter, reason) " +
15
+ "VALUES (?, ?, ?, ?, ?, ?, ?)")
16
+ .run(Number(row.id), String(row.body ?? ""), Number(row.revision), at, row.title == null ? null : String(row.title), row.front_matter == null ? null : String(row.front_matter), reason);
17
+ /** One line of the change log, from the document row as it is after the change. */
18
+ export const logDocumentChange = (database, id, event, at) => {
19
+ const row = database.prepare("SELECT account_id, external_id, title, revision FROM documents WHERE id = ?").get(id);
20
+ if (!row)
21
+ return;
22
+ database
23
+ .prepare("INSERT INTO document_changes (account_id, document_id, path, title, event, revision, at) " +
24
+ "VALUES (?, ?, ?, ?, ?, ?, ?)")
25
+ .run(Number(row.account_id), id, String(row.external_id), row.title == null ? null : String(row.title), event, Number(row.revision), at);
26
+ };
27
+ /**
28
+ * Takes a document out of the live copy for `reason`. An unavailable one keeps its text, since the source may show it
29
+ * again; a deleted or unsynced one keeps its last text as a version and its body is blanked.
30
+ */
31
+ export const removeDocument = (database, id, at, reason) => {
32
+ const row = database.prepare("SELECT * FROM documents WHERE id = ? AND deleted_at IS NULL").get(id);
33
+ if (!row)
34
+ return false;
35
+ if (reason === "unavailable")
36
+ database.prepare("UPDATE documents SET deleted_at = ?, removal = ? WHERE id = ?").run(at, reason, id);
37
+ else {
38
+ if (row.body != null)
39
+ keepRevision(database, row, at, reason);
40
+ database
41
+ .prepare("UPDATE documents SET deleted_at = ?, removal = ?, body = '', revision = revision + 1 WHERE id = ?")
42
+ .run(at, reason, id);
43
+ }
44
+ logDocumentChange(database, id, reason, at);
45
+ return true;
46
+ };
47
+ const removalOf = (value) => DOCUMENT_REMOVALS.includes(value) ? value : null;
48
+ export const documentHistoryOver = ({ database }) => {
49
+ const account = (folderId) => {
50
+ const row = /^\d+$/.test(folderId)
51
+ ? database.prepare("SELECT id FROM accounts WHERE id = ?").get(Number(folderId))
52
+ : undefined;
53
+ if (!row)
54
+ throw new CliError("not_found", `no documents account ${folderId} in the local store`);
55
+ return Number(row.id);
56
+ };
57
+ const documentRow = (reference) => {
58
+ const thing = thingOf(database, reference);
59
+ const row = thing?.type === "document" ? database.prepare("SELECT * FROM documents WHERE id = ?").get(thing.id) : undefined;
60
+ if (!row)
61
+ throw new CliError("not_found", `document ${reference} is not in the local store`);
62
+ return row;
63
+ };
64
+ const kept = (id) => database
65
+ .prepare("SELECT revision, title, front_matter, reason, body, created_at FROM document_revisions " +
66
+ "WHERE document_id = ? ORDER BY revision DESC, id DESC")
67
+ .all(id);
68
+ const keptVersion = (row, current = false) => ({
69
+ revision: Number(row.revision),
70
+ title: row.title == null ? null : String(row.title),
71
+ reason: current ? "edited" : (row.reason ?? "edited"),
72
+ replacedAt: current ? null : iso(row.created_at),
73
+ current,
74
+ characters: String(row.body ?? "").length,
75
+ });
76
+ // A removed document's row holds no text of its own once its last version was kept: it is not a version then.
77
+ const currentShown = (row) => row.deleted_at == null || String(row.body ?? "") !== "";
78
+ return {
79
+ documentAt: async (folderId, path) => {
80
+ const row = database
81
+ .prepare("SELECT id FROM documents WHERE account_id = ? AND external_id = ?")
82
+ .get(account(folderId), path);
83
+ return row ? `document:${row.id}` : undefined;
84
+ },
85
+ documentHistory: async (reference) => {
86
+ const row = documentRow(reference);
87
+ const id = Number(row.id);
88
+ return {
89
+ ref: `document:${id}`,
90
+ title: row.title == null ? null : String(row.title),
91
+ path: String(row.external_id),
92
+ revision: Number(row.revision),
93
+ deletedAt: iso(row.deleted_at),
94
+ removal: row.deleted_at == null ? null : removalOf(row.removal),
95
+ versions: [
96
+ ...(currentShown(row) ? [{ ...keptVersion(row, true), replacedAt: iso(row.updated_at) }] : []),
97
+ ...kept(id).map((one) => keptVersion(one)),
98
+ ],
99
+ };
100
+ },
101
+ documentVersion: async (reference, revision) => {
102
+ const row = documentRow(reference);
103
+ if (Number(row.revision) === revision && currentShown(row))
104
+ return {
105
+ ...keptVersion(row, true),
106
+ replacedAt: iso(row.updated_at),
107
+ text: String(row.body ?? ""),
108
+ frontMatter: json(row.front_matter),
109
+ };
110
+ const found = kept(Number(row.id)).find((one) => Number(one.revision) === revision);
111
+ if (!found)
112
+ throw new CliError("not_found", `document ${reference} has no version ${revision} in the local store`, {
113
+ reason: "document.version-missing",
114
+ });
115
+ return { ...keptVersion(found), text: String(found.body ?? ""), frontMatter: json(found.front_matter) };
116
+ },
117
+ documentChanges: async (folderId, { since, until, events, limit, offset }) => {
118
+ const from = Date.parse(since);
119
+ const to = until === undefined ? Number.MAX_SAFE_INTEGER : Date.parse(until);
120
+ if (Number.isNaN(from) || Number.isNaN(to))
121
+ throw new CliError("validation_error", "since and until take an ISO 8601 time");
122
+ const kinds = events?.length ? events : DOCUMENT_EVENTS;
123
+ const rows = database
124
+ .prepare("SELECT * FROM document_changes WHERE account_id = ? AND at >= ? AND at <= ? " +
125
+ `AND event IN (${kinds.map(() => "?").join(", ")}) ORDER BY at DESC, id DESC LIMIT ? OFFSET ?`)
126
+ .all(account(folderId), from, to, ...kinds, limit + 1, offset);
127
+ return {
128
+ items: rows.slice(0, limit).map((row) => ({
129
+ ref: `document:${row.document_id}`,
130
+ path: String(row.path),
131
+ title: row.title == null ? null : String(row.title),
132
+ event: row.event,
133
+ revision: Number(row.revision),
134
+ at: iso(row.at),
135
+ })),
136
+ hasMore: rows.length > limit,
137
+ };
138
+ },
139
+ pruneDocumentHistory: async (folderId, before) => write(database, () => {
140
+ const id = account(folderId);
141
+ const cut = Date.parse(before);
142
+ if (Number.isNaN(cut))
143
+ throw new CliError("validation_error", "before takes an ISO 8601 time");
144
+ const versions = database
145
+ .prepare("DELETE FROM document_revisions WHERE created_at < ? " +
146
+ "AND document_id IN (SELECT id FROM documents WHERE account_id = ?)")
147
+ .run(cut, id).changes;
148
+ const changes = database
149
+ .prepare("DELETE FROM document_changes WHERE account_id = ? AND at < ?")
150
+ .run(id, cut).changes;
151
+ const texts = database
152
+ .prepare("UPDATE documents SET body = '', revision = revision + 1 WHERE account_id = ? AND removal = 'unavailable' " +
153
+ "AND deleted_at IS NOT NULL AND deleted_at < ? AND body <> ''")
154
+ .run(id, cut).changes;
155
+ return { versions, changes, texts };
156
+ }),
157
+ };
158
+ };
@@ -140,6 +140,8 @@ export const MANIFEST = [
140
140
  { name: "20261117211414_version-70-tracker-item-words", version: 70, minCompatible: 56 },
141
141
  { name: "20261118230213_version-71-content", version: 71, minCompatible: 56 },
142
142
  { name: "20261118230214_version-71-content-words", version: 71, minCompatible: 56 },
143
+ { name: "20261123022342_version-72-document-history", version: 72, minCompatible: 56 },
144
+ { name: "20261123022347_version-72-document-changes-trigger", version: 72, minCompatible: 56 },
143
145
  ];
144
146
  export const generatedMigrations = (manifest = MANIFEST, generated = GENERATED) => {
145
147
  const migrations = [];
@@ -1424,5 +1424,22 @@ export const GENERATED = [
1424
1424
  "CREATE TRIGGER content_post_words_au AFTER UPDATE OF normalized_text ON content_posts\n WHEN old.normalized_text IS NOT new.normalized_text BEGIN\n DELETE FROM content_post_words WHERE rowid = old.id;\n INSERT INTO content_post_words (rowid, normalized_text)\n SELECT new.id, new.normalized_text WHERE new.normalized_text <> '';\nEND;",
1425
1425
  "-- Taggings are polymorphic, with no foreign key: a post row that goes takes its tags along.\nCREATE TRIGGER content_post_words_ad AFTER DELETE ON content_posts BEGIN\n DELETE FROM content_post_words WHERE rowid = old.id;\n DELETE FROM taggings WHERE taggable_type = 'post' AND taggable_id = old.id;\nEND;"
1426
1426
  ]
1427
+ },
1428
+ {
1429
+ "name": "20261123022342_version-72-document-history",
1430
+ "statements": [
1431
+ "CREATE TABLE `document_changes` (\n\t`id` integer PRIMARY KEY,\n\t`account_id` integer NOT NULL,\n\t`document_id` integer NOT NULL,\n\t`path` text NOT NULL,\n\t`title` text,\n\t`event` text NOT NULL,\n\t`revision` integer NOT NULL,\n\t`at` integer NOT NULL\n);",
1432
+ "ALTER TABLE `document_revisions` ADD `title` text;",
1433
+ "ALTER TABLE `document_revisions` ADD `front_matter` text;",
1434
+ "ALTER TABLE `document_revisions` ADD `reason` text;",
1435
+ "ALTER TABLE `documents` ADD `removal` text;",
1436
+ "CREATE INDEX `document_changes_by_account_id_at` ON `document_changes` (`account_id`,`at`);"
1437
+ ]
1438
+ },
1439
+ {
1440
+ "name": "20261123022347_version-72-document-changes-trigger",
1441
+ "statements": [
1442
+ "-- No foreign key on the change log, so an older build that purges an account still can; this drops its rows with it.\nCREATE TRIGGER document_changes_account_bd BEFORE DELETE ON accounts BEGIN\n DELETE FROM document_changes WHERE account_id = old.id;\nEND;"
1443
+ ]
1427
1444
  }
1428
1445
  ];
@@ -3,6 +3,8 @@ import type { Section } from "../../readers/types.js";
3
3
  import { type Decider } from "../decisions.js";
4
4
  import type { CacheDatabase } from "../driver.js";
5
5
  import type { AddedSources } from "./added-sources.js";
6
+ import type { DocumentHistoryStore, DocumentRemoval } from "./document-history.js";
7
+ import { keepRevision } from "./document-history.js";
6
8
  import { type DocumentMetadata } from "./document-metadata.js";
7
9
  import { type ImportedDocuments } from "./imported-documents.js";
8
10
  import { LINK_KINDS, LINK_ORIGINS, type LINK_SOURCES } from "./link-kinds.js";
@@ -117,7 +119,7 @@ export interface MessageDocument {
117
119
  reference: string;
118
120
  fileId: string;
119
121
  }
120
- export interface NotesStore extends NoteSearch, ImportedDocuments, AddedSources {
122
+ export interface NotesStore extends NoteSearch, ImportedDocuments, AddedSources, DocumentHistoryStore {
121
123
  addFolder(input: {
122
124
  name: string;
123
125
  format?: NoteFolder["format"];
@@ -145,8 +147,11 @@ export interface NotesStore extends NoteSearch, ImportedDocuments, AddedSources
145
147
  path: string;
146
148
  modifiedAt: string;
147
149
  }[]): Promise<number>;
148
- /** Marks the folder's notes at these paths deleted; answers how many were live. */
149
- deleteFileNotes(folderId: string, paths: string[]): Promise<number>;
150
+ /**
151
+ * Takes the folder's notes at these paths out of the live copy; answers how many were live. `deleted` (the default)
152
+ * and `unsynced` keep the last text as a version and blank it; `unavailable` keeps the text on the document.
153
+ */
154
+ deleteFileNotes(folderId: string, paths: string[], reason?: DocumentRemoval): Promise<number>;
150
155
  /** A note about the things named, the first of them its subject; about nothing, a note to self. */
151
156
  addNote(input: {
152
157
  text: string;
@@ -205,13 +210,7 @@ export interface NotesStore extends NoteSearch, ImportedDocuments, AddedSources
205
210
  type Row = Record<string, unknown>;
206
211
  /** What a link's written target is matched by: case, accents and a leading `@` do not count. */
207
212
  export declare const targetKey: (text: string) => string;
208
- /**
209
- * Keeps a document's text under its current revision before the caller writes the new text with `revision + 1`, so
210
- * a citation reads back the words it cited and the source check sees the change.
211
- */
212
- export declare const keepRevision: (database: CacheDatabase, row: Row, at: number) => {
213
- changes: number;
214
- };
213
+ export { keepRevision };
215
214
  export declare const documentOf: (row: Row) => Note;
216
215
  export declare const noteOf: (row: Row, database: CacheDatabase) => Note;
217
216
  /** A document or note row by its typed reference, or `undefined`. */