@aragon-agent/cli 0.6.76 → 0.6.78

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 (64) hide show
  1. package/dist/account/config.d.ts +4 -1
  2. package/dist/account/config.js +14 -1
  3. package/dist/account/device-client.d.ts +2 -0
  4. package/dist/account/device-client.js +11 -5
  5. package/dist/account/login-flow.d.ts +1 -0
  6. package/dist/account/login-flow.js +11 -5
  7. package/dist/account/store.d.ts +5 -0
  8. package/dist/account/store.js +38 -0
  9. package/dist/agent/controller.js +4 -1
  10. package/dist/app/App.d.ts +0 -6
  11. package/dist/app/App.js +21 -2
  12. package/dist/cli.js +6 -0
  13. package/dist/cloud-sync/coordinator.d.ts +64 -0
  14. package/dist/cloud-sync/coordinator.js +294 -0
  15. package/dist/cloud-sync/gene-adapter.d.ts +2 -0
  16. package/dist/cloud-sync/gene-adapter.js +234 -0
  17. package/dist/cloud-sync/identity.d.ts +19 -0
  18. package/dist/cloud-sync/identity.js +311 -0
  19. package/dist/cloud-sync/lease.d.ts +9 -0
  20. package/dist/cloud-sync/lease.js +173 -0
  21. package/dist/cloud-sync/memory-adapter.d.ts +4 -0
  22. package/dist/cloud-sync/memory-adapter.js +107 -0
  23. package/dist/cloud-sync/project-bindings.d.ts +7 -0
  24. package/dist/cloud-sync/project-bindings.js +68 -0
  25. package/dist/cloud-sync/protocol.d.ts +65 -0
  26. package/dist/cloud-sync/protocol.js +193 -0
  27. package/dist/cloud-sync/reconcile.d.ts +14 -0
  28. package/dist/cloud-sync/reconcile.js +539 -0
  29. package/dist/cloud-sync/state.d.ts +117 -0
  30. package/dist/cloud-sync/state.js +208 -0
  31. package/dist/cloud-sync/transport.d.ts +28 -0
  32. package/dist/cloud-sync/transport.js +134 -0
  33. package/dist/commands/account-command.d.ts +2 -1
  34. package/dist/commands/account-command.js +54 -7
  35. package/dist/config/app-paths.d.ts +2 -2
  36. package/dist/config/app-paths.js +4 -4
  37. package/dist/config/env.d.ts +2 -0
  38. package/dist/config/env.js +17 -0
  39. package/dist/gene/commit-exec.js +5 -1
  40. package/dist/gene/commit-prepare.js +3 -1
  41. package/dist/gene/commit-types.d.ts +2 -0
  42. package/dist/gene/manager-actions.js +29 -1
  43. package/dist/gene/manager-library.js +5 -4
  44. package/dist/gene/paths.d.ts +4 -3
  45. package/dist/gene/paths.js +9 -2
  46. package/dist/gene/store.d.ts +2 -0
  47. package/dist/gene/store.js +2 -1
  48. package/dist/gene/transfer.d.ts +2 -0
  49. package/dist/gene/transfer.js +2 -1
  50. package/dist/gene/version-service.d.ts +4 -0
  51. package/dist/gene/version-service.js +72 -8
  52. package/dist/gene/wiring.d.ts +9 -0
  53. package/dist/gene/wiring.js +1 -1
  54. package/dist/host/cloud-sync.d.ts +21 -0
  55. package/dist/host/cloud-sync.js +49 -0
  56. package/dist/memory/format.d.ts +2 -0
  57. package/dist/memory/format.js +11 -2
  58. package/dist/memory/paths.d.ts +5 -3
  59. package/dist/memory/paths.js +15 -6
  60. package/dist/memory/service.d.ts +2 -0
  61. package/dist/memory/service.js +43 -6
  62. package/dist/memory/store.d.ts +11 -1
  63. package/dist/memory/store.js +74 -9
  64. package/package.json +3 -3
@@ -0,0 +1,539 @@
1
+ import { existsSync, lstatSync, readFileSync } from 'node:fs';
2
+ import { isAbsolute, relative } from 'node:path';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+ import { checkContent, conflictRef, contentHash } from './protocol.js';
5
+ import { adapterScope, bindingGeneration } from './project-bindings.js';
6
+ import { applyingRemote, wakeLibrarySync } from './state.js';
7
+ import { assertLibraryIdentity, withLibraryWrite } from './identity.js';
8
+ import { SyncHttpError } from './transport.js';
9
+ export const digest = (content) => content ? contentHash(content) : null;
10
+ function confirm(row, epoch, rev, hash, localHash = hash) {
11
+ row.baseline = { epoch, rev, hash, localHash };
12
+ delete row.applying;
13
+ delete row.firstLocal;
14
+ delete row.incoming;
15
+ delete row.conflict;
16
+ delete row.out;
17
+ delete row.rejected;
18
+ delete row.blocked;
19
+ }
20
+ function conflict(row, local, remote) {
21
+ row.conflict = { local: local?.content ?? null, remote };
22
+ delete row.applying;
23
+ delete row.out;
24
+ }
25
+ function queue(row, epoch, content, binding) {
26
+ const baseRev = row.baseline?.rev ?? 0;
27
+ row.out = {
28
+ binding,
29
+ op: {
30
+ schema: 1,
31
+ opId: randomUUID(),
32
+ epoch,
33
+ baseRev,
34
+ op: baseRev ? 'update' : 'create',
35
+ space: row.space,
36
+ kind: row.kind,
37
+ itemId: row.itemId,
38
+ content
39
+ }
40
+ };
41
+ }
42
+ async function readOne(adapter, scope, id) {
43
+ if (adapter.read)
44
+ return (await adapter.read(scope, id)) ?? undefined;
45
+ return (await adapter.scan(scope)).find(v => v.itemId === id);
46
+ }
47
+ async function apply(ctx, row, remote, scope, local) {
48
+ const expected = digest(local?.content);
49
+ const target = digest(remote.content);
50
+ row.applying = { expected, target, rev: remote.rev };
51
+ ctx.store.put(row);
52
+ const adapter = ctx.adapters[row.kind];
53
+ await applyingRemote(() => adapter.apply(scope, remote, expected));
54
+ const actual = await readOne(adapter, scope, row.itemId);
55
+ confirm(row, ctx.store.cursor().epoch, remote.rev, target, digest(actual?.content));
56
+ }
57
+ async function incoming(ctx, scope, row, local) {
58
+ const remote = row.incoming;
59
+ const base = row.baseline;
60
+ const epoch = ctx.store.cursor().epoch;
61
+ const localHash = digest(local?.content);
62
+ const remoteHash = digest(remote.content);
63
+ const issue = remote.content && checkContent(row, remote.content);
64
+ if (issue) {
65
+ row.blocked = 'Received item requires review: ' + issue;
66
+ return;
67
+ }
68
+ if (remoteHash === localHash || (row.out && digest(row.out.op.content) === remoteHash
69
+ && row.out.op.epoch === epoch && row.out.op.baseRev + 1 === remote.rev)) {
70
+ confirm(row, epoch, remote.rev, remoteHash);
71
+ return;
72
+ }
73
+ if (base?.epoch === epoch && base.rev === remote.rev && base.hash === remoteHash) {
74
+ delete row.incoming;
75
+ return;
76
+ }
77
+ if (row.conflict || (base && base.epoch !== epoch)) {
78
+ conflict(row, local, remote);
79
+ return;
80
+ }
81
+ if (row.applying && row.applying.expected !== localHash) {
82
+ conflict(row, local, remote);
83
+ return;
84
+ }
85
+ if (!local && base?.localHash && !remote.deleted) {
86
+ conflict(row, local, remote);
87
+ return;
88
+ }
89
+ if ((local && !base) || (base && localHash !== base.localHash && !local?.localOnly)) {
90
+ conflict(row, local, remote);
91
+ return;
92
+ }
93
+ await apply(ctx, row, remote, scope, local);
94
+ }
95
+ async function processRow(ctx, scope, row, local) {
96
+ const cursor = ctx.store.cursor();
97
+ const generation = bindingGeneration(ctx.store, row.space);
98
+ if (!cursor.epoch || !generation)
99
+ return;
100
+ if (row.binding && row.binding !== generation) {
101
+ // A new project directory must compare independently of the former directory's baseline.
102
+ if (!row.incoming && row.baseline) {
103
+ conflict(row, local, null);
104
+ return;
105
+ }
106
+ delete row.baseline;
107
+ delete row.out;
108
+ delete row.applying;
109
+ delete row.conflict;
110
+ }
111
+ row.binding = generation;
112
+ delete row.blocked;
113
+ if (local?.blocked) {
114
+ row.blocked = local.blocked;
115
+ return;
116
+ }
117
+ if (row.firstLocal && !local && !row.conflict) {
118
+ conflict(row, { itemId: row.itemId, content: row.firstLocal }, row.incoming ?? null);
119
+ return;
120
+ }
121
+ delete row.firstLocal;
122
+ if (row.incoming) {
123
+ await incoming(ctx, scope, row, local);
124
+ return;
125
+ }
126
+ if (row.baseline && row.baseline.epoch !== cursor.epoch) {
127
+ conflict(row, local, null);
128
+ return;
129
+ }
130
+ if (row.conflict)
131
+ return;
132
+ if (row.out && (row.out.op.epoch !== cursor.epoch || row.out.binding !== generation)) {
133
+ delete row.out;
134
+ }
135
+ if (!local) {
136
+ if (row.baseline?.hash && row.out?.op.op !== 'delete')
137
+ row.blocked = 'Missing on this device.';
138
+ return;
139
+ }
140
+ if (row.rejected && row.out) {
141
+ if (row.out.op.op === 'delete' || digest(row.out.op.content) === digest(local.content)) {
142
+ if (Date.now() < row.rejected.retryAt)
143
+ row.blocked = row.rejected.code;
144
+ return;
145
+ }
146
+ // A definitive rejection did not commit. A corrected draft starts a fresh intention.
147
+ delete row.out;
148
+ delete row.rejected;
149
+ }
150
+ if (local.localOnly || row.out)
151
+ return;
152
+ const hash = contentHash(local.content);
153
+ if (row.baseline?.localHash === hash)
154
+ return;
155
+ if (row.baseline?.hash === null) {
156
+ conflict(row, local, null);
157
+ return;
158
+ }
159
+ const problem = checkContent(row, local.content);
160
+ if (problem) {
161
+ row.blocked = 'Check ' + problem + ' before syncing.';
162
+ return;
163
+ }
164
+ queue(row, cursor.epoch, local.content, generation);
165
+ }
166
+ function localIssue(row, error) {
167
+ const code = error instanceof Error ? error.message : '';
168
+ if (row.kind === 'gene' && row.incoming?.deleted) {
169
+ return 'Open /gene and confirm ' + row.incoming.deleteReason + ' for this gene.';
170
+ }
171
+ if (code === 'Gene requires review.' || code === 'GENE_OVERSIGHT_HUMAN_ONLY') {
172
+ return 'Review this oversight gene in the local gene manager.';
173
+ }
174
+ if (/^(GENE|MEMORY)_[A-Z_]+$/.test(code))
175
+ return code;
176
+ return 'Check this item in the local library before retrying.';
177
+ }
178
+ async function scanWindow(adapter, scope, store, rows, kind) {
179
+ if (!adapter.list || !adapter.read)
180
+ return { locals: await adapter.scan(scope), rows };
181
+ const ids = await adapter.list(scope);
182
+ // Include a vanished, tracked id to classify it as locally missing. Never infer a deletion.
183
+ const byId = new Map(rows.map(row => [row.itemId, row]));
184
+ const sorted = [...new Set([...ids, ...byId.keys()])].sort();
185
+ const slot = scope.space + '/' + kind;
186
+ const after = store.scans()[slot] ?? '';
187
+ let start = sorted.findIndex(id => id > after);
188
+ if (start < 0)
189
+ start = 0;
190
+ const rotated = sorted.slice(start, start + 64);
191
+ const selected = new Set(rotated);
192
+ for (const id of ids)
193
+ if (!byId.has(id))
194
+ selected.add(id);
195
+ const epoch = store.cursor().epoch;
196
+ for (const row of rows)
197
+ if (row.dirty || row.out || row.incoming || row.firstLocal ||
198
+ row.applying || row.baseline?.epoch !== epoch)
199
+ selected.add(row.itemId);
200
+ const locals = [];
201
+ for (const id of selected) {
202
+ try {
203
+ const local = await adapter.read(scope, id);
204
+ if (local)
205
+ locals.push(local);
206
+ }
207
+ catch {
208
+ locals.push({ itemId: id, content: {}, blocked: 'Cannot read this local item.' });
209
+ }
210
+ }
211
+ if (rotated.length)
212
+ await withLibraryWrite(store.identity, async () => {
213
+ store.saveScans({ ...store.scans(), [slot]: rotated[rotated.length - 1] });
214
+ });
215
+ return { locals, rows: rows.filter(row => selected.has(row.itemId)) };
216
+ }
217
+ export async function reconcileLocals(ctx) {
218
+ const { store } = ctx;
219
+ const byScope = new Map();
220
+ for (const row of store.entries()) {
221
+ const group = row.space + '/' + row.kind;
222
+ const rows = byScope.get(group) ?? [];
223
+ rows.push(row);
224
+ byScope.set(group, rows);
225
+ }
226
+ const spaces = ['personal', ...Object.keys(store.bindings())];
227
+ for (const space of spaces) {
228
+ for (const kind of ['memory', 'gene']) {
229
+ const capture = await withLibraryWrite(store.identity, async () => ({
230
+ scope: await adapterScope(store, space),
231
+ generation: bindingGeneration(store, space),
232
+ }));
233
+ const scope = capture.scope;
234
+ if (!scope || !capture.generation)
235
+ continue;
236
+ const adapter = ctx.adapters[kind];
237
+ assertLibraryIdentity(store.identity);
238
+ const page = await scanWindow(adapter, scope, store, byScope.get(space + '/' + kind) ?? [], kind);
239
+ const locals = page.locals;
240
+ assertLibraryIdentity(store.identity);
241
+ const entries = new Map(page.rows.map(row => [row.itemId, row]));
242
+ for (const local of locals) {
243
+ if (!entries.has(local.itemId))
244
+ entries.set(local.itemId, { space, kind, itemId: local.itemId });
245
+ }
246
+ const index = new Map(locals.map(local => [local.itemId, local]));
247
+ for (const key of entries.values()) {
248
+ await withLibraryWrite(store.identity, async () => {
249
+ const current = await adapterScope(store, space);
250
+ if (!current || current.projectKey !== scope.projectKey ||
251
+ capture.generation !== bindingGeneration(store, space)) {
252
+ wakeLibrarySync();
253
+ return;
254
+ }
255
+ let row;
256
+ try {
257
+ row = store.get(key);
258
+ }
259
+ catch {
260
+ store.damaged.add(key.itemId);
261
+ return;
262
+ }
263
+ // A conflict may have been resolved or a local edit committed since the scan.
264
+ if (JSON.stringify(key) !== JSON.stringify(row)) {
265
+ wakeLibrarySync();
266
+ return;
267
+ }
268
+ const before = JSON.stringify(row);
269
+ delete row.dirty;
270
+ try {
271
+ await processRow(ctx, scope, row, index.get(row.itemId));
272
+ }
273
+ catch (error) {
274
+ row.blocked = localIssue(row, error);
275
+ }
276
+ if (JSON.stringify(row) !== before)
277
+ store.put(row);
278
+ });
279
+ }
280
+ }
281
+ }
282
+ }
283
+ async function captureFirstLocals(ctx) {
284
+ const { store } = ctx;
285
+ for (const space of ['personal', ...Object.keys(store.bindings())]) {
286
+ const capture = await withLibraryWrite(store.identity, async () => ({
287
+ scope: await adapterScope(store, space),
288
+ generation: bindingGeneration(store, space),
289
+ }));
290
+ const scope = capture.scope;
291
+ if (!scope || !capture.generation)
292
+ continue;
293
+ for (const kind of ['memory', 'gene']) {
294
+ const locals = await ctx.adapters[kind].scan(scope);
295
+ await withLibraryWrite(store.identity, async () => {
296
+ if (bindingGeneration(store, space) !== capture.generation ||
297
+ (await adapterScope(store, space))?.projectKey !== scope.projectKey)
298
+ throw Error('Project binding changed.');
299
+ for (const local of locals) {
300
+ let row;
301
+ try {
302
+ row = store.get({ space, kind, itemId: local.itemId });
303
+ }
304
+ catch {
305
+ store.damaged.add(local.itemId);
306
+ continue;
307
+ }
308
+ if (!row.firstLocal && !local.blocked && !checkContent(row, local.content)) {
309
+ row.firstLocal = local.content;
310
+ store.put(row);
311
+ }
312
+ }
313
+ });
314
+ }
315
+ }
316
+ }
317
+ export async function receive(ctx) {
318
+ const { store, transport } = ctx;
319
+ let cursor = store.cursor();
320
+ if (!cursor.epoch)
321
+ await captureFirstLocals(ctx);
322
+ for (;;) {
323
+ const page = await transport.changes(cursor.after, cursor.epoch, cursor.fence);
324
+ await withLibraryWrite(store.identity, async () => {
325
+ const current = store.cursor();
326
+ if (JSON.stringify(current) !== JSON.stringify(cursor))
327
+ throw Error('Library bindings changed.');
328
+ store.replayQuarantine(page.epoch);
329
+ for (const item of page.items) {
330
+ let row;
331
+ try {
332
+ row = store.get(item);
333
+ }
334
+ catch {
335
+ store.preserveIncoming(item, page.epoch);
336
+ continue;
337
+ }
338
+ if (row.applying && row.incoming?.rev !== item.rev)
339
+ delete row.applying;
340
+ row.incoming = item;
341
+ store.put(row);
342
+ }
343
+ cursor = {
344
+ epoch: page.epoch,
345
+ after: page.nextAfter,
346
+ fence: page.hasMore ? page.fence : undefined,
347
+ receivedAt: Date.now(),
348
+ reset: page.hasMore ? cursor.reset : undefined
349
+ };
350
+ store.saveCursor(cursor);
351
+ });
352
+ if (!page.hasMore)
353
+ return;
354
+ }
355
+ }
356
+ function verified(store, fact) {
357
+ if (!fact.verify || (fact.sourcePath && existsSync(fact.sourcePath)))
358
+ return false;
359
+ const candidates = fact.sourcePath ? [fact.sourcePath, fact.verify.path] : [fact.verify.path];
360
+ const paths = candidates.map(p => relative(store.identity.dataRoot, p));
361
+ if (paths.some(p => p.startsWith('..') || isAbsolute(p) || !p))
362
+ return false;
363
+ const stat = lstatSync(fact.verify.path, { throwIfNoEntry: false });
364
+ if (!stat?.isFile() || stat.size > 2 * 1024 * 1024)
365
+ return false;
366
+ return createHash('sha256').update(readFileSync(fact.verify.path)).digest('hex') === fact.verify.sha256;
367
+ }
368
+ export async function prepareDeletions(ctx) {
369
+ const { store } = ctx;
370
+ for (const fact of store.facts()) {
371
+ if (!fact.complete && verified(store, fact)) {
372
+ fact.complete = true;
373
+ store.saveFact(fact);
374
+ }
375
+ if (!fact.complete || bindingGeneration(store, fact.key.space) !== fact.binding)
376
+ continue;
377
+ if (!await adapterScope(store, fact.key.space))
378
+ continue;
379
+ const row = store.get(fact.key);
380
+ if (row.baseline?.hash === null) {
381
+ store.clearFact(fact.id);
382
+ continue;
383
+ }
384
+ if (fact.baseline.epoch !== store.cursor().epoch || row.conflict || row.incoming)
385
+ continue;
386
+ if (row.out) {
387
+ if (row.out.op.opId !== fact.predecessor?.opId)
388
+ continue;
389
+ if (!row.rejected) {
390
+ // A lost reply may already have committed this edit. Replay exactly that operation first.
391
+ if (row.blocked === 'Missing on this device.') {
392
+ delete row.blocked;
393
+ store.put(row);
394
+ }
395
+ continue;
396
+ }
397
+ if (!row.baseline) {
398
+ // The create was definitively rejected, so there is no cloud item to remove.
399
+ delete row.out;
400
+ delete row.rejected;
401
+ delete row.blocked;
402
+ store.put(row);
403
+ store.clearFact(fact.id);
404
+ continue;
405
+ }
406
+ }
407
+ const base = row.baseline;
408
+ if (!base || base.epoch !== fact.baseline.epoch)
409
+ continue;
410
+ const original = base.rev === fact.baseline.rev && base.hash === fact.baseline.hash;
411
+ const acknowledged = base.rev === fact.predecessor?.rev && base.hash === fact.predecessor.hash;
412
+ if (!original && !acknowledged)
413
+ continue;
414
+ if (fact.target) {
415
+ if (!fact.targetHash || bindingGeneration(store, fact.target.space) !== fact.targetBinding)
416
+ continue;
417
+ const target = store.get(fact.target);
418
+ if (target.conflict || target.out || target.baseline?.epoch !== fact.baseline.epoch ||
419
+ target.baseline.hash !== fact.targetHash || !await adapterScope(store, fact.target.space))
420
+ continue;
421
+ }
422
+ row.out = {
423
+ binding: fact.binding,
424
+ op: {
425
+ schema: 1,
426
+ epoch: fact.baseline.epoch,
427
+ opId: randomUUID(),
428
+ baseRev: base.rev,
429
+ op: 'delete',
430
+ ...fact.key,
431
+ reason: fact.reason
432
+ }
433
+ };
434
+ delete row.blocked;
435
+ delete row.rejected;
436
+ store.put(row);
437
+ }
438
+ }
439
+ export async function sendQueued(ctx) {
440
+ const { store, transport } = ctx;
441
+ for (const candidate of store.entries().filter(row => row.out)) {
442
+ const row = store.get(candidate);
443
+ const out = row.out;
444
+ if (!out || row.blocked || row.conflict || row.incoming)
445
+ continue;
446
+ if (!await withLibraryWrite(store.identity, async () => !!await adapterScope(store, row.space) && bindingGeneration(store, row.space) === out.binding &&
447
+ store.get(row).out?.op.opId === out.op.opId))
448
+ continue;
449
+ try {
450
+ const receipt = await transport.mutate(out.op);
451
+ await withLibraryWrite(store.identity, async () => {
452
+ const latest = store.get(row);
453
+ if (latest.out?.op.opId !== out.op.opId)
454
+ return;
455
+ confirm(latest, out.op.epoch, receipt.rev, digest(out.op.content));
456
+ store.put(latest);
457
+ });
458
+ }
459
+ catch (error) {
460
+ if (!(error instanceof SyncHttpError))
461
+ throw error;
462
+ if (error.code === 'E_LIBRARY_CONFLICT' && !error.reusedOpId) {
463
+ const remote = await transport.detail(row, out.op.epoch);
464
+ await withLibraryWrite(store.identity, async () => {
465
+ const latest = store.get(row);
466
+ latest.incoming = remote;
467
+ store.put(latest);
468
+ });
469
+ }
470
+ else if (error.code === 'E_LIBRARY_QUOTA' || error.status === 400 || error.status === 413 || error.reusedOpId) {
471
+ await withLibraryWrite(store.identity, async () => {
472
+ const latest = store.get(row);
473
+ if (latest.out?.op.opId !== out.op.opId)
474
+ return;
475
+ const reason = error.reusedOpId ? 'Operation identifier was already used. Edit this draft to retry.' : error.code;
476
+ latest.blocked = reason;
477
+ latest.rejected = {
478
+ code: reason,
479
+ retryAt: error.code === 'E_LIBRARY_QUOTA' ? Date.now() + 60_000 : Number.MAX_SAFE_INTEGER,
480
+ };
481
+ store.put(latest);
482
+ });
483
+ }
484
+ else
485
+ throw error;
486
+ }
487
+ }
488
+ }
489
+ export async function resolveConflict(ctx, key, choice) {
490
+ const { store, transport } = ctx;
491
+ const matches = store.entries().filter(r => conflictRef(r) === key && r.conflict);
492
+ const row = matches.length === 1 ? matches[0] : undefined;
493
+ if (!row)
494
+ throw Error('Conflict no longer exists.');
495
+ const epoch = store.cursor().epoch;
496
+ let remote;
497
+ try {
498
+ remote = await transport.detail(row, epoch);
499
+ }
500
+ catch (error) {
501
+ if (!(error instanceof SyncHttpError) || error.status !== 404)
502
+ throw error;
503
+ remote = null;
504
+ }
505
+ await withLibraryWrite(store.identity, async () => {
506
+ if (JSON.stringify(row.conflict) !== JSON.stringify(store.get(row).conflict) ||
507
+ remote?.rev !== row.conflict?.remote?.rev || store.cursor().epoch !== epoch) {
508
+ throw Error('Cloud version changed. Refresh the conflict.');
509
+ }
510
+ const scope = await adapterScope(store, row.space);
511
+ if (!scope)
512
+ throw Error('Bind and enable this project first.');
513
+ const adapter = ctx.adapters[row.kind];
514
+ const local = await readOne(adapter, scope, row.itemId);
515
+ if (local && digest(local.content) !== digest(row.conflict?.local))
516
+ throw Error('Local draft changed.');
517
+ const retained = local?.content ?? row.conflict?.local;
518
+ if (choice === 'local') {
519
+ if (!local || remote?.deleted)
520
+ throw Error('Use Save a copy for a deleted item.');
521
+ confirm(row, epoch, remote?.rev ?? 0, digest(remote?.content));
522
+ queue(row, epoch, local.content, bindingGeneration(store, row.space));
523
+ }
524
+ else {
525
+ if (choice === 'copy' && retained)
526
+ await applyingRemote(() => adapter.copy(scope, retained));
527
+ if (remote)
528
+ await apply(ctx, row, remote, scope, local);
529
+ else if (local) {
530
+ const tombstone = { ...row, rev: 0, seq: 0, updatedAt: Date.now(), deleted: true, deleteReason: 'delete' };
531
+ await applyingRemote(() => adapter.apply(scope, tombstone, digest(local.content)));
532
+ confirm(row, epoch, 0, null);
533
+ }
534
+ else
535
+ confirm(row, epoch, 0, null);
536
+ }
537
+ store.put(row);
538
+ });
539
+ }
@@ -0,0 +1,117 @@
1
+ import { type LibraryIdentity } from './identity.js';
2
+ import type { Content, LibraryItem, LibraryKey, LibraryKind, Mutation } from './protocol.js';
3
+ export interface Baseline {
4
+ rev: number;
5
+ epoch: string;
6
+ hash: string | null;
7
+ localHash: string | null;
8
+ }
9
+ export interface Entry extends LibraryKey {
10
+ baseline?: Baseline;
11
+ binding?: string;
12
+ incoming?: LibraryItem;
13
+ out?: {
14
+ op: Mutation;
15
+ binding: string;
16
+ };
17
+ firstLocal?: Content;
18
+ dirty?: boolean;
19
+ applying?: {
20
+ expected: string | null;
21
+ target: string | null;
22
+ rev: number;
23
+ };
24
+ conflict?: {
25
+ local: Content | null;
26
+ remote: LibraryItem | null;
27
+ };
28
+ blocked?: string;
29
+ rejected?: {
30
+ code: string;
31
+ retryAt: number;
32
+ };
33
+ }
34
+ export interface Binding {
35
+ key: string;
36
+ root: string;
37
+ generation: string;
38
+ }
39
+ export interface Cursor {
40
+ epoch?: string;
41
+ after: number;
42
+ fence?: number;
43
+ receivedAt: number | null;
44
+ reset?: boolean;
45
+ }
46
+ interface DeleteInput {
47
+ kind: LibraryKind;
48
+ itemId: string;
49
+ projectKey?: string;
50
+ reason: string;
51
+ target?: {
52
+ itemId: string;
53
+ projectKey?: string;
54
+ contentHash?: string;
55
+ };
56
+ verify?: {
57
+ path: string;
58
+ sha256: string;
59
+ };
60
+ sourcePath?: string;
61
+ }
62
+ export interface DeleteFact {
63
+ id: string;
64
+ key: LibraryKey;
65
+ baseline: Baseline;
66
+ predecessor?: {
67
+ opId: string;
68
+ rev: number;
69
+ hash: string;
70
+ };
71
+ binding: string;
72
+ complete: boolean;
73
+ reason: string;
74
+ target?: LibraryKey;
75
+ targetHash?: string;
76
+ targetBinding?: string;
77
+ verify?: {
78
+ path: string;
79
+ sha256: string;
80
+ };
81
+ sourcePath?: string;
82
+ }
83
+ export declare function wakeLibrarySync(changed?: {
84
+ kind: LibraryKind;
85
+ itemId: string;
86
+ projectKey?: string;
87
+ }): void;
88
+ export declare function observeLibraryWake(fn: () => void): () => void;
89
+ export declare const applyingRemote: <T>(fn: () => T) => T;
90
+ export declare function readPrivate<T>(file: string, fallback: T): T;
91
+ /** All calls that mutate this store execute inside the captured identity's home lock. */
92
+ export declare class AccountState {
93
+ readonly identity: LibraryIdentity;
94
+ readonly root: string;
95
+ readonly damaged: Set<string>;
96
+ private cached;
97
+ constructor(identity: LibraryIdentity);
98
+ cursor(): Cursor;
99
+ saveCursor(v: Cursor): void;
100
+ scans(): Record<string, string>;
101
+ saveScans(scans: Record<string, string>): void;
102
+ bindings(): Record<string, Binding>;
103
+ saveBindings(v: Record<string, Binding>): void;
104
+ entryPath(key: LibraryKey): string;
105
+ get(key: LibraryKey): Entry;
106
+ put(entry: Entry): void;
107
+ entries(): Entry[];
108
+ preserveIncoming(item: LibraryItem, epoch: string): void;
109
+ replayQuarantine(epoch: string): void;
110
+ facts(): DeleteFact[];
111
+ saveFact(fact: DeleteFact): void;
112
+ clearFact(id: string): void;
113
+ }
114
+ /** Only an explicit, completed domain action may create an outbound tombstone. */
115
+ export declare function beginLibraryDeletion(input: DeleteInput): () => void;
116
+ export declare function isCloudDeleted(input: Pick<DeleteInput, 'kind' | 'itemId' | 'projectKey'>): boolean;
117
+ export {};