@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
@@ -8,9 +8,12 @@ export { watchMirrors, } from "../services/documents/mirror-watch.js";
8
8
  export { conflictReport, fileMirrorState, mirrorId, mirrorStatus, syncMirrors, } from "../services/documents/mirrors.js";
9
9
  export { extractDocumentMemories } from "../services/documents/proposals.js";
10
10
  export { planPush, pushDocuments, scanLocal, skippedName, } from "../services/documents/push.js";
11
- export { syncDocuments } from "../services/documents/sync.js";
11
+ export { KEEP_VERSIONS_FOR_DAYS, syncDocuments } from "../services/documents/sync.js";
12
+ export { listFileConflicts, resolveFileConflict, showFileConflict, } from "../services/files/conflicts.js";
12
13
  export { excludedBy, exclusionPattern } from "../services/files/exclusions.js";
14
+ export { guardedFileWrite, } from "../services/files/guarded-write.js";
13
15
  export { fileMirrorStatus, fileRemoteChanges, fileSyncState, MAX_DELETIONS, MAX_REPLACEMENTS, syncFileMirror, syncFileMirrors, } from "../services/files/mirror.js";
16
+ export { MAX_MERGE_BYTES, mergeable, mergeText, } from "../services/files/text-merge.js";
14
17
  export { fileVersions, restoreFileVersion, } from "../services/files/versions.js";
15
18
  export { blockKey, blockShape, normalizeInlines } from "./blocks.js";
16
19
  export { catalogFiles } from "./catalog.js";
@@ -26,9 +26,20 @@ export interface SourceContent<M extends SourceFile = SourceFile> {
26
26
  notRead?: string;
27
27
  raw?: unknown;
28
28
  }
29
+ /**
30
+ * Why a document left the sync's copy. `deleted` only on a direct signal from the source (its trash, a delete event);
31
+ * `unavailable` when the source no longer shows it but may still hold it (a 404 that can mean unshared, lost access);
32
+ * `unsynced` when it left the synced folders.
33
+ */
34
+ export type SourceRemoval = "deleted" | "unavailable" | "unsynced";
29
35
  export interface SourceChange<M extends SourceFile = SourceFile> {
30
36
  id: string;
31
37
  removed: boolean;
38
+ /**
39
+ * What a removal means. Left out, a removal counts as `unavailable` and the document keeps its text: a removal
40
+ * from a feed can be a lost share as well as a deletion. A source sets `deleted` only when it knows.
41
+ */
42
+ gone?: "deleted" | "unavailable";
32
43
  file?: M;
33
44
  }
34
45
  /**
@@ -85,6 +96,8 @@ export interface SourceWork<M extends SourceFile = SourceFile> {
85
96
  id: string;
86
97
  kind: "save" | "remove";
87
98
  file?: M;
99
+ /** A removal's reason; a job saved before reasons existed counts as `unavailable`. */
100
+ reason?: SourceRemoval;
88
101
  }
89
102
  export interface SourceSkip<M extends SourceFile = SourceFile> {
90
103
  id: string;
@@ -137,7 +150,9 @@ export interface SourceIndex<M extends SourceFile = SourceFile> {
137
150
  import(principal: string, files: M[]): Promise<unknown>;
138
151
  };
139
152
  save(principal: string, content: SourceContent<M>, hash: string): Promise<string>;
140
- remove(principal: string, id: string): Promise<void>;
153
+ remove(principal: string, id: string, reason?: SourceRemoval): Promise<void>;
154
+ /** Drops the history older than `before` (ISO 8601); a sync calls it when a pass completes. */
155
+ prune?(principal: string, before: string): Promise<unknown>;
141
156
  openPictures(): Promise<PictureWriter>;
142
157
  /** Indexes what the sync saved for word search, until `until` says stop; the rest waits for the next search. */
143
158
  settle?(options: {
@@ -87,6 +87,7 @@ const PROVIDER_API = [
87
87
  validation("file.not-a-file", "the path names a folder or another thing that is not a file"),
88
88
  ["file.denied", "permission_error", "the file cannot be opened: permission denied"],
89
89
  validation("file.too-large", "the file is larger than the limit set for this read"),
90
+ validation("file.not-plain-text", "the file's text is extracted on a read; writing it back would replace the file"),
90
91
  ];
91
92
  /** The read-only SFTP client (`./sftp`). */
92
93
  const SFTP = [
@@ -204,6 +205,7 @@ const OTHERS = [
204
205
  validation("agent.cost-unknown", "the agent reports no cost, so a cost cap cannot stop it"),
205
206
  validation("document.changed", "the document changed while it was read; nothing was saved"),
206
207
  ["document.not-imported", "not_found", "the document is not imported in this source account"],
208
+ ["document.version-missing", "not_found", "the local copy holds no such version of the document"],
207
209
  ["document.not-found", "not_found", "no listed document has that reference"],
208
210
  ["state.unreadable", "configuration_error", "a sync state file cannot be read; move it away and sync again"],
209
211
  ["profile.busy", "provider_unavailable", "another sync or write holds this profile's local copy"],
@@ -257,6 +259,8 @@ const OTHERS = [
257
259
  "the earlier content could not be kept in the version store, so the sync did not replace it",
258
260
  ],
259
261
  ["mirror.remote-changed", "conflict", "the remote file changed since the listing; the next sync settles it"],
262
+ ["mirror.local-changed", "conflict", "the local file changed since the conflict was found; nothing was written"],
263
+ ["mirror.no-conflict", "not_found", "the path has no recorded conflict; the last sync settled it or never saw one"],
260
264
  ["upload.mismatch", "conflict", "the uploaded file reads back with other content; the local file changed meanwhile"],
261
265
  ["download.mismatch", "invalid_response", "the downloaded file has other content than the listing said"],
262
266
  ["catalog.unavailable", "configuration_error", "the store has no shared catalog for this account"],
@@ -1,11 +1,14 @@
1
1
  import { type Block } from "../../documents/blocks.js";
2
2
  import type { Keep } from "../../documents/push-model.js";
3
3
  /** `base[from, to)` is replaced by `blocks`; an empty range is an insert, an empty `blocks` a delete. */
4
- export interface BlockHunk {
4
+ export interface Hunk<T> {
5
5
  from: number;
6
6
  to: number;
7
- blocks: Block[];
7
+ blocks: T[];
8
8
  }
9
+ export type BlockHunk = Hunk<Block>;
10
+ /** The edits that turn `base` into `next`, leaving every unchanged item in place: blocks, or a text's lines. */
11
+ export declare const diffSequence: <T>(base: T[], next: T[], keyOf: (item: T) => string) => Hunk<T>[];
9
12
  /** The edits that turn `base` into `next`, leaving every unchanged block in place. */
10
13
  export declare const diffBlocks: (base: Block[], next: Block[], keyOf?: (block: Block) => string) => BlockHunk[];
11
14
  /** A stretch both sides changed differently: the blocks it held at the last sync and on each side now. */
@@ -24,10 +27,17 @@ export type Merged = {
24
27
  } | {
25
28
  status: "unaligned";
26
29
  };
30
+ /** Two hunks touch the same stretch: their ranges overlap, both insert at one point, or one inserts inside the other. */
31
+ export declare const touches: (a: Hunk<unknown>, b: Hunk<unknown>) => boolean;
32
+ /** Two hunks touch or sit side by side with no unchanged item between them: Git's diff3 conflicts on both. */
33
+ export declare const adjoins: (a: Hunk<unknown>, b: Hunk<unknown>) => boolean;
34
+ /** `base[from, to)` with `hunks`, which lie inside it in order, applied. */
35
+ export declare const applied: <T>(base: T[], from: number, to: number, hunks: Hunk<T>[]) => T[];
27
36
  /**
28
37
  * Three-way merge of a document changed on both sides since the last sync. `baseLocal` and `baseRemote` are each
29
38
  * side as the last sync left it; they hold the same blocks, though a tick may differ. Blocks line up by their
30
39
  * shape, so a checklist tick never collides with a text edit: each tick follows the side that changed it, the
31
40
  * remote when neither did. A stretch both sides changed differently is a conflict, settled by `keep` when given.
41
+ * `overlap` decides which hunks share a stretch; `adjoins` also joins neighbours, as a file merge needs.
32
42
  */
33
- export declare const mergeBlocks: (baseLocal: Block[], baseRemote: Block[], local: Block[], remote: Block[], keep?: Keep) => Merged;
43
+ export declare const mergeBlocks: (baseLocal: Block[], baseRemote: Block[], local: Block[], remote: Block[], keep?: Keep, overlap?: (a: Hunk<unknown>, b: Hunk<unknown>) => boolean) => Merged;
@@ -1,6 +1,6 @@
1
1
  import { blockKey, blockShape } from "../../documents/blocks.js";
2
2
  const MAX_CELLS = 4_000_000;
3
- /** Longest common subsequence: index pairs [inA, inB] of blocks with equal keys, in order. */
3
+ /** Longest common subsequence: index pairs [inA, inB] of items with equal keys, in order. */
4
4
  const matches = (a, b, keyOf) => {
5
5
  const ka = a.map(keyOf);
6
6
  const kb = b.map(keyOf);
@@ -47,8 +47,8 @@ const matches = (a, b, keyOf) => {
47
47
  pairs.push([endA + offset, endB + offset]);
48
48
  return pairs;
49
49
  };
50
- /** The edits that turn `base` into `next`, leaving every unchanged block in place. */
51
- export const diffBlocks = (base, next, keyOf = blockKey) => {
50
+ /** The edits that turn `base` into `next`, leaving every unchanged item in place: blocks, or a text's lines. */
51
+ export const diffSequence = (base, next, keyOf) => {
52
52
  const hunks = [];
53
53
  let a = 0;
54
54
  let b = 0;
@@ -60,14 +60,19 @@ export const diffBlocks = (base, next, keyOf = blockKey) => {
60
60
  }
61
61
  return hunks;
62
62
  };
63
+ /** The edits that turn `base` into `next`, leaving every unchanged block in place. */
64
+ export const diffBlocks = (base, next, keyOf = blockKey) => diffSequence(base, next, keyOf);
63
65
  const isCheck = (block) => block?.kind === "item" && block.list === "check";
64
66
  const sameKeys = (a, b) => a.length === b.length && a.every((block, index) => blockKey(block) === blockKey(b[index]));
65
67
  /** Two hunks touch the same stretch: their ranges overlap, both insert at one point, or one inserts inside the other. */
66
- const touches = (a, b) => Math.max(a.from, b.from) < Math.min(a.to, b.to) ||
68
+ export const touches = (a, b) => Math.max(a.from, b.from) < Math.min(a.to, b.to) ||
67
69
  a.from === b.from ||
68
70
  (a.from === a.to && b.from < a.from && a.from < b.to) ||
69
71
  (b.from === b.to && a.from < b.from && b.from < a.to);
70
- const applied = (base, from, to, hunks) => {
72
+ /** Two hunks touch or sit side by side with no unchanged item between them: Git's diff3 conflicts on both. */
73
+ export const adjoins = (a, b) => touches(a, b) || a.to === b.from || b.to === a.from;
74
+ /** `base[from, to)` with `hunks`, which lie inside it in order, applied. */
75
+ export const applied = (base, from, to, hunks) => {
71
76
  let out = [];
72
77
  let at = from;
73
78
  for (const hunk of hunks) {
@@ -81,8 +86,9 @@ const applied = (base, from, to, hunks) => {
81
86
  * side as the last sync left it; they hold the same blocks, though a tick may differ. Blocks line up by their
82
87
  * shape, so a checklist tick never collides with a text edit: each tick follows the side that changed it, the
83
88
  * remote when neither did. A stretch both sides changed differently is a conflict, settled by `keep` when given.
89
+ * `overlap` decides which hunks share a stretch; `adjoins` also joins neighbours, as a file merge needs.
84
90
  */
85
- export const mergeBlocks = (baseLocal, baseRemote, local, remote, keep) => {
91
+ export const mergeBlocks = (baseLocal, baseRemote, local, remote, keep, overlap = touches) => {
86
92
  if (baseLocal.length !== baseRemote.length ||
87
93
  baseLocal.some((block, index) => blockShape(block) !== blockShape(baseRemote[index])))
88
94
  return { status: "unaligned" };
@@ -93,7 +99,7 @@ export const mergeBlocks = (baseLocal, baseRemote, local, remote, keep) => {
93
99
  const clusters = [];
94
100
  for (const hunk of tagged) {
95
101
  const last = clusters.at(-1);
96
- if (last?.some((other) => touches(other, hunk)))
102
+ if (last?.some((other) => overlap(other, hunk)))
97
103
  last.push(hunk);
98
104
  else
99
105
  clusters.push([hunk]);
@@ -1,4 +1,4 @@
1
- import type { SourceContent, SourceFile } from "../../documents/model.js";
1
+ import type { SourceContent, SourceFile, SourceRemoval } from "../../documents/model.js";
2
2
  import type { CatalogInput, CatalogQuery, MessageStore } from "../../store/index.js";
3
3
  export interface IngestionOptions<M extends SourceFile> {
4
4
  /**
@@ -35,5 +35,24 @@ export declare const documentIngestion: <M extends SourceFile>(store: Pick<Messa
35
35
  until: () => boolean;
36
36
  }) => Promise<number>;
37
37
  save: (principal: string, content: SourceContent<M>, hash: string) => Promise<string>;
38
- remove: (principal: string, id: string) => Promise<void>;
38
+ remove: (principal: string, id: string, reason?: SourceRemoval) => Promise<void>;
39
+ prune: (principal: string, before: string) => Promise<{
40
+ versions: number;
41
+ changes: number;
42
+ texts: number;
43
+ } | undefined>;
44
+ /** The profile's local history: earlier versions of a document and what changed when. */
45
+ history: {
46
+ /** `id` is the source's id, or a `document:<n>` ref; a removed document is found too. */
47
+ reference: (principal: string, id: string) => Promise<string | undefined>;
48
+ versions: (reference: string) => Promise<import("../../store/index.js").DocumentHistoryAnswer>;
49
+ version: (reference: string, revision: number) => Promise<import("../../store/index.js").DocumentVersionText>;
50
+ changes: (principal: string, query: Parameters<MessageStore["notes"]["documentChanges"]>[1]) => Promise<{
51
+ items: import("../../store/index.js").DocumentChange[];
52
+ hasMore: boolean;
53
+ } | {
54
+ items: never[];
55
+ hasMore: boolean;
56
+ }>;
57
+ };
39
58
  };
@@ -101,7 +101,7 @@ export const documentIngestion = (store, options) => {
101
101
  await options.observed?.(principal, content.metadata, note.id);
102
102
  return note.ref;
103
103
  },
104
- remove: async (principal, id) => {
104
+ remove: async (principal, id, reason) => {
105
105
  const selected = await folder(principal, false);
106
106
  if (selected) {
107
107
  const path = options.externalId(id);
@@ -110,8 +110,35 @@ export const documentIngestion = (store, options) => {
110
110
  const ref = note?.ref ?? retired?.ref;
111
111
  if (ref)
112
112
  await stale(ref);
113
- await store.notes.deleteFileNotes(selected.id, [path]);
113
+ await store.notes.deleteFileNotes(selected.id, [path], reason);
114
114
  }
115
115
  },
116
+ prune: async (principal, before) => {
117
+ const selected = await folder(principal, false);
118
+ return selected ? store.notes.pruneDocumentHistory?.(selected.id, before) : undefined;
119
+ },
120
+ /** The profile's local history: earlier versions of a document and what changed when. */
121
+ history: {
122
+ /** `id` is the source's id, or a `document:<n>` ref; a removed document is found too. */
123
+ reference: async (principal, id) => {
124
+ if (/^document:\d+$/.test(id))
125
+ return id;
126
+ const selected = await folder(principal, false);
127
+ if (!selected)
128
+ return undefined;
129
+ for (const path of both(id)) {
130
+ const found = await store.notes.documentAt(selected.id, path);
131
+ if (found)
132
+ return found;
133
+ }
134
+ return undefined;
135
+ },
136
+ versions: (reference) => store.notes.documentHistory(reference),
137
+ version: (reference, revision) => store.notes.documentVersion(reference, revision),
138
+ changes: async (principal, query) => {
139
+ const selected = await folder(principal, false);
140
+ return selected ? store.notes.documentChanges(selected.id, query) : { items: [], hasMore: false };
141
+ },
142
+ },
116
143
  };
117
144
  };
@@ -45,7 +45,7 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
45
45
  cursor: state.cursor ?? "",
46
46
  folders: {},
47
47
  skipped: [],
48
- jobs: Object.keys(state.documents).map((id) => ({ id, kind: "remove" })),
48
+ jobs: Object.keys(state.documents).map((id) => ({ id, kind: "remove", reason: "unsynced" })),
49
49
  },
50
50
  };
51
51
  if (!source)
@@ -78,11 +78,13 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
78
78
  changed.add(file.id);
79
79
  delta.set(file.id, file);
80
80
  };
81
- const drop = (id) => {
81
+ const removals = new Map();
82
+ const drop = (id, reason) => {
82
83
  const known = files.get(id);
83
84
  if (known)
84
85
  delta.set(id, { ...known, trashed: true });
85
86
  files.delete(id);
87
+ removals.set(id, reason);
86
88
  };
87
89
  const container = (file) => {
88
90
  if (options.isDocument?.(file))
@@ -126,7 +128,7 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
126
128
  // Apply all ancestry changes before classifying document scope.
127
129
  for (const change of latest.values()) {
128
130
  if (change.removed || change.file?.trashed) {
129
- drop(change.id);
131
+ drop(change.id, change.file?.trashed ? "deleted" : (change.gone ?? "unavailable"));
130
132
  if (folders[change.id])
131
133
  folders[change.id] = { ...folders[change.id], trashed: true };
132
134
  }
@@ -188,8 +190,9 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
188
190
  const visited = new Set(walk.visited);
189
191
  Object.assign(folders, walk.folders);
190
192
  for (const file of walk.files) {
193
+ // A walk saved part way keeps no reason; one it cannot prove is a deletion keeps the text.
191
194
  if (file.trashed)
192
- drop(file.id);
195
+ drop(file.id, "unavailable");
193
196
  else
194
197
  keep(file);
195
198
  }
@@ -280,7 +283,7 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
280
283
  walk.stack.pop();
281
284
  visited.add(folder.id);
282
285
  folders[folder.id] = { ...folder, trashed: true };
283
- drop(folder.id);
286
+ drop(folder.id, "unavailable");
284
287
  spent++;
285
288
  listed++;
286
289
  continue;
@@ -386,10 +389,16 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
386
389
  // After every real edit, so a run that stops on its deadline spends it on those first.
387
390
  for (const job of again)
388
391
  jobs.push(job);
392
+ // Absent from the listing is not a deletion: only the source's own signal is (`drop`). Out of scope is `unsynced`
393
+ // only when the owner changed the scope; a folder above that was unshared or vanished leaves its files unavailable.
394
+ const narrowed = state.scope !== scope;
389
395
  for (const id of Object.keys(state.documents)) {
390
396
  const file = files.get(id);
391
- if (!file || !inScope(file, roots, folders, matched, scoped))
392
- jobs.push({ id, kind: "remove" });
397
+ const known = file ?? state.documents[id]?.metadata;
398
+ if (file && inScope(file, roots, folders, matched, scoped))
399
+ continue;
400
+ const outside = narrowed && known !== undefined && !inScope(known, roots, folders, matched, scoped);
401
+ jobs.push({ id, kind: "remove", reason: removals.get(id) ?? (outside ? "unsynced" : "unavailable") });
393
402
  }
394
403
  // Only retain metadata for selected ancestry; the account-wide feed includes unrelated folders.
395
404
  const scopedFolders = Object.fromEntries(Object.entries(folders).filter(([, file]) => roots.includes(file.id) || (!excluded(file) && within(file, roots, folders, new Set(), cut))));
@@ -43,5 +43,7 @@ export interface SyncOptions<M extends SourceFile> {
43
43
  signal?: AbortSignal;
44
44
  rescan?: boolean;
45
45
  pictures?: boolean;
46
+ /** How long earlier versions and the change log are kept, in days (`keep_versions_for_days`); 365 unless given. */
47
+ keepVersionsForDays?: number;
46
48
  now?(): number;
47
49
  }
@@ -1,6 +1,7 @@
1
1
  import type { SourceFile } from "../../documents/model.js";
2
2
  import { type WalkStop } from "./plan.js";
3
3
  import type { SyncOptions } from "./ports.js";
4
+ export declare const KEEP_VERSIONS_FOR_DAYS = 365;
4
5
  export interface SyncResult {
5
6
  saved: number;
6
7
  names_only: number;
@@ -8,6 +8,8 @@ const MAX_PICTURE_BYTES = 25 * 1024 * 1024;
8
8
  const SAVE_EVERY_MS = 2000;
9
9
  const SAVE_EVERY_ITEMS = 25;
10
10
  const SETTLE_MS = 10_000;
11
+ const DAY_MS = 24 * 60 * 60 * 1000;
12
+ export const KEEP_VERSIONS_FOR_DAYS = 365;
11
13
  const isPicture = (file) => file.mime.startsWith("image/") && file.canDownload;
12
14
  const hashText = (text) => createHash("sha256").update(text).digest("hex");
13
15
  export const syncDocuments = async (options) => {
@@ -53,7 +55,7 @@ export const syncDocuments = async (options) => {
53
55
  // Work the new plan cannot see: a file saved to the index before its state was.
54
56
  for (const job of state.pending.jobs)
55
57
  if (!state.documents[job.id]) {
56
- await index.remove(profile.principal, job.id);
58
+ await index.remove(profile.principal, job.id, "unsynced");
57
59
  statePort.removeSnapshot(job.id);
58
60
  }
59
61
  delete state.pending;
@@ -166,7 +168,7 @@ export const syncDocuments = async (options) => {
166
168
  lock.assertHeld();
167
169
  try {
168
170
  if (job.kind === "remove") {
169
- await index.remove(profile.principal, job.id);
171
+ await index.remove(profile.principal, job.id, job.reason ?? "unavailable");
170
172
  statePort.removeSnapshot(job.id);
171
173
  delete state.documents[job.id];
172
174
  result.removed++;
@@ -190,7 +192,7 @@ export const syncDocuments = async (options) => {
190
192
  const content = await source.content(job.id, limit, job.file);
191
193
  const listed = query?.mode === "include" && (pending.matched?.includes(job.id) ?? query.matches(content.metadata));
192
194
  if (!listed && !inScope(content.metadata, profile.roots, pending.folders, new Set(), query)) {
193
- await index.remove(profile.principal, job.id);
195
+ await index.remove(profile.principal, job.id, "unsynced");
194
196
  statePort.removeSnapshot(job.id);
195
197
  delete state.documents[job.id];
196
198
  result.removed++;
@@ -235,7 +237,8 @@ export const syncDocuments = async (options) => {
235
237
  if (job.file && safe.code === "validation_error")
236
238
  await saveNamesOnly(job.file, skipped.reason);
237
239
  else {
238
- await index.remove(profile.principal, job.id);
240
+ // A 404 or a refusal says the sign-in cannot read it now, not that it is gone: its text stays.
241
+ await index.remove(profile.principal, job.id, "unavailable");
239
242
  statePort.removeSnapshot(job.id);
240
243
  delete state.documents[job.id];
241
244
  }
@@ -263,6 +266,8 @@ export const syncDocuments = async (options) => {
263
266
  delete state.pending;
264
267
  state.lastSync = new Date(now()).toISOString();
265
268
  statePort.save(state);
269
+ const days = options.keepVersionsForDays ?? KEEP_VERSIONS_FOR_DAYS;
270
+ await index.prune?.(profile.principal, new Date(now() - days * DAY_MS).toISOString());
266
271
  }
267
272
  // A reader that cannot write finds the text by its words only once it is indexed; a search that can write does it
268
273
  // itself, so what this bound leaves, or a failure here, is indexed by the next one. Skipped after a stop, and kept
@@ -0,0 +1,78 @@
1
+ import type { FileMirrorStatePort } from "../../documents/file-mirror-model.js";
2
+ import type { Keep } from "../../documents/push-model.js";
3
+ import { type HeldLock, type Mirror } from "../documents/mirrors.js";
4
+ import type { FileMirrorOptions } from "./mirror.js";
5
+ import { type TextSegment } from "./text-merge.js";
6
+ import type { FileVersions } from "./versions.js";
7
+ /** The conflicts each mirror's last sync left, by mirror and path. */
8
+ export declare const listFileConflicts: (mirrors: Mirror[], stateOf: (mirror: Mirror) => FileMirrorStatePort) => {
9
+ id: string;
10
+ path: string;
11
+ reason: string;
12
+ at: string;
13
+ kept: boolean;
14
+ local: string | null;
15
+ remote: string | null;
16
+ }[];
17
+ export interface FileConflictVersion {
18
+ sha256: string | null;
19
+ available: boolean;
20
+ /** The content as text, when the store has it and the file is text a merge reads. */
21
+ text?: string;
22
+ }
23
+ export interface FileConflictView {
24
+ path: string;
25
+ reason: string;
26
+ at: string;
27
+ base: FileConflictVersion;
28
+ local: FileConflictVersion;
29
+ remote: FileConflictVersion;
30
+ /** The local file was changed since the conflict was found: a resolution is refused until a sync sees it. */
31
+ localChanged: boolean;
32
+ /** Each changed stretch of the line merge, conflicts included; empty when the versions are not all kept text. */
33
+ hunks: TextSegment[];
34
+ /** The whole file as the merge would write it, with Git's markers around each conflict: a start for `--file`. */
35
+ merged?: string;
36
+ }
37
+ /** A recorded conflict with its three versions and, for kept text, the line merge that failed. */
38
+ export declare const showFileConflict: (options: {
39
+ root: string;
40
+ path: string;
41
+ state: FileMirrorStatePort;
42
+ versions: FileVersions;
43
+ /** How the app names the remote side in the conflict markers. */
44
+ remote: string;
45
+ }) => Promise<FileConflictView>;
46
+ export interface FileConflictResolveOptions extends Pick<FileMirrorOptions, "target" | "principal" | "guard" | "operationId" | "signal" | "now"> {
47
+ root: string;
48
+ folder: string;
49
+ path: string;
50
+ state: FileMirrorStatePort;
51
+ versions: FileVersions;
52
+ /** How the app names the remote side; it ends a kept copy's name. */
53
+ remote: string;
54
+ /** The mirrors' sync lock, as `acquireLock` returns it. */
55
+ lock(): Promise<HeldLock>;
56
+ /** Keep one side or both whole, or `file`: the absolute path of the final content, written to both sides. */
57
+ choice: {
58
+ keep: Keep;
59
+ } | {
60
+ file: string;
61
+ };
62
+ }
63
+ export interface FileConflictResolution {
64
+ path: string;
65
+ resolution: "local" | "remote" | "both" | "file";
66
+ /** The content both sides now have; null when the resolution deleted the file. */
67
+ sha256: string | null;
68
+ /** The remote version's copy beside the local file, for `keep: "both"`. */
69
+ copy?: string;
70
+ }
71
+ /**
72
+ * Settles a recorded conflict with the owner's choice, on both sides at once. Both sides are checked against what the
73
+ * conflict recorded: the local file by its hash, the remote by an upload or trash that expects its hash, made before
74
+ * the local file is touched, so a remote changed meanwhile refuses the resolution with nothing written. Every content
75
+ * replaced was kept by the conflict or is kept first, and the resolution is logged with all of them, kept for good.
76
+ * Runs under the mirrors' sync lock.
77
+ */
78
+ export declare const resolveFileConflict: (options: FileConflictResolveOptions) => Promise<FileConflictResolution>;