@aragon-agent/cli 0.6.75 → 0.6.77
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.
- package/CHANGELOG.md +7 -1
- package/README.md +3 -3
- package/dist/account/config.d.ts +4 -1
- package/dist/account/config.js +14 -1
- package/dist/account/device-client.d.ts +2 -0
- package/dist/account/device-client.js +11 -5
- package/dist/account/login-flow.d.ts +1 -0
- package/dist/account/login-flow.js +11 -5
- package/dist/account/store.d.ts +5 -0
- package/dist/account/store.js +38 -0
- package/dist/agent/controller.js +4 -1
- package/dist/app/App.d.ts +0 -6
- package/dist/app/App.js +36 -5
- package/dist/cli.js +6 -0
- package/dist/cloud-sync/coordinator.d.ts +64 -0
- package/dist/cloud-sync/coordinator.js +294 -0
- package/dist/cloud-sync/gene-adapter.d.ts +2 -0
- package/dist/cloud-sync/gene-adapter.js +234 -0
- package/dist/cloud-sync/identity.d.ts +19 -0
- package/dist/cloud-sync/identity.js +311 -0
- package/dist/cloud-sync/lease.d.ts +9 -0
- package/dist/cloud-sync/lease.js +173 -0
- package/dist/cloud-sync/memory-adapter.d.ts +4 -0
- package/dist/cloud-sync/memory-adapter.js +107 -0
- package/dist/cloud-sync/project-bindings.d.ts +7 -0
- package/dist/cloud-sync/project-bindings.js +68 -0
- package/dist/cloud-sync/protocol.d.ts +65 -0
- package/dist/cloud-sync/protocol.js +193 -0
- package/dist/cloud-sync/reconcile.d.ts +14 -0
- package/dist/cloud-sync/reconcile.js +539 -0
- package/dist/cloud-sync/state.d.ts +117 -0
- package/dist/cloud-sync/state.js +208 -0
- package/dist/cloud-sync/transport.d.ts +28 -0
- package/dist/cloud-sync/transport.js +134 -0
- package/dist/commands/account-command.d.ts +2 -1
- package/dist/commands/account-command.js +54 -7
- package/dist/config/app-paths.d.ts +2 -2
- package/dist/config/app-paths.js +4 -4
- package/dist/config/env.d.ts +2 -0
- package/dist/config/env.js +17 -0
- package/dist/gene/commit-exec.js +5 -1
- package/dist/gene/commit-prepare.js +3 -1
- package/dist/gene/commit-types.d.ts +2 -0
- package/dist/gene/manager-actions.js +29 -1
- package/dist/gene/manager-library.js +5 -4
- package/dist/gene/paths.d.ts +4 -3
- package/dist/gene/paths.js +9 -2
- package/dist/gene/store.d.ts +2 -0
- package/dist/gene/store.js +2 -1
- package/dist/gene/transfer.d.ts +2 -0
- package/dist/gene/transfer.js +2 -1
- package/dist/gene/version-service.d.ts +4 -0
- package/dist/gene/version-service.js +72 -8
- package/dist/gene/wiring.d.ts +9 -0
- package/dist/gene/wiring.js +1 -1
- package/dist/host/cloud-sync.d.ts +21 -0
- package/dist/host/cloud-sync.js +49 -0
- package/dist/memory/format.d.ts +2 -0
- package/dist/memory/format.js +11 -2
- package/dist/memory/paths.d.ts +5 -3
- package/dist/memory/paths.js +15 -6
- package/dist/memory/service.d.ts +2 -0
- package/dist/memory/service.js +43 -6
- package/dist/memory/store.d.ts +11 -1
- package/dist/memory/store.js +74 -9
- package/package.json +3 -3
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
import { readAccount, saveLoginAccount } from '../account/store.js';
|
|
3
|
+
import { resolveProjectKey } from '../memory/paths.js';
|
|
4
|
+
import { captureLibraryIdentity, hasLibraryGrant, libraryKey, withLibraryWrite } from './identity.js';
|
|
5
|
+
import { acquireLease, outsideHomeLock } from './lease.js';
|
|
6
|
+
import { changeBinding } from './project-bindings.js';
|
|
7
|
+
import { conflictRef } from './protocol.js';
|
|
8
|
+
import { prepareDeletions, receive, reconcileLocals, resolveConflict, sendQueued } from './reconcile.js';
|
|
9
|
+
import { AccountState, observeLibraryWake, readPrivate } from './state.js';
|
|
10
|
+
import { LibraryTransport, SyncHttpError } from './transport.js';
|
|
11
|
+
const empty = () => ({
|
|
12
|
+
state: 'signed-out',
|
|
13
|
+
username: null,
|
|
14
|
+
baseUrl: null,
|
|
15
|
+
generation: 'legacy',
|
|
16
|
+
lastReceivedAt: null,
|
|
17
|
+
pendingSend: 0,
|
|
18
|
+
pendingApply: 0,
|
|
19
|
+
conflicts: [],
|
|
20
|
+
issues: [],
|
|
21
|
+
boundSpace: null,
|
|
22
|
+
message: null
|
|
23
|
+
});
|
|
24
|
+
export class LibraryCoordinator {
|
|
25
|
+
cwd;
|
|
26
|
+
adapters;
|
|
27
|
+
view = empty();
|
|
28
|
+
lease = null;
|
|
29
|
+
active = null;
|
|
30
|
+
queued = false;
|
|
31
|
+
stopped = false;
|
|
32
|
+
abort = new AbortController();
|
|
33
|
+
nextTry = 0;
|
|
34
|
+
retryToken = null;
|
|
35
|
+
retryTimer;
|
|
36
|
+
editTimer;
|
|
37
|
+
failures = 0;
|
|
38
|
+
deadToken = null;
|
|
39
|
+
receiptAt = 0;
|
|
40
|
+
receiptToken = '';
|
|
41
|
+
receiptMark = '';
|
|
42
|
+
listeners = new Set();
|
|
43
|
+
timer;
|
|
44
|
+
detach;
|
|
45
|
+
constructor(cwd, adapters) {
|
|
46
|
+
this.cwd = cwd;
|
|
47
|
+
this.adapters = adapters;
|
|
48
|
+
this.detach = observeLibraryWake(() => {
|
|
49
|
+
if (this.editTimer)
|
|
50
|
+
return;
|
|
51
|
+
this.editTimer = setTimeout(() => {
|
|
52
|
+
this.editTimer = undefined;
|
|
53
|
+
this.wake();
|
|
54
|
+
}, 500);
|
|
55
|
+
this.editTimer.unref();
|
|
56
|
+
});
|
|
57
|
+
this.timer = setInterval(() => this.wake(), 15_000);
|
|
58
|
+
this.timer.unref();
|
|
59
|
+
this.wake();
|
|
60
|
+
}
|
|
61
|
+
status() {
|
|
62
|
+
try {
|
|
63
|
+
const id = captureLibraryIdentity();
|
|
64
|
+
const account = readAccount();
|
|
65
|
+
if (this.view.generation !== id.generation || this.view.username !== (account?.user.username ?? null)) {
|
|
66
|
+
return {
|
|
67
|
+
...empty(),
|
|
68
|
+
state: account ? 'waiting' : 'signed-out',
|
|
69
|
+
generation: id.generation,
|
|
70
|
+
username: account?.user.username ?? null,
|
|
71
|
+
baseUrl: account?.baseUrl ?? null
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
return structuredClone(this.view);
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
return { ...empty(), state: 'paused', message: 'Check local account ownership.' };
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
subscribe(fn) {
|
|
81
|
+
this.listeners.add(fn);
|
|
82
|
+
return () => { this.listeners.delete(fn); };
|
|
83
|
+
}
|
|
84
|
+
emit(view) {
|
|
85
|
+
this.view = view;
|
|
86
|
+
for (const fn of this.listeners)
|
|
87
|
+
fn(this.status());
|
|
88
|
+
}
|
|
89
|
+
wake() {
|
|
90
|
+
if (this.stopped)
|
|
91
|
+
return;
|
|
92
|
+
if (this.active) {
|
|
93
|
+
this.queued = true;
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
this.active = outsideHomeLock(() => Promise.resolve().then(() => this.cycle())).catch(error => {
|
|
97
|
+
if (this.stopped)
|
|
98
|
+
return;
|
|
99
|
+
const retry = error instanceof SyncHttpError ? error.retryMs : 0;
|
|
100
|
+
const delay = Math.max(retry, Math.min(300_000, 1000 * 2 ** this.failures + Math.random() * 250));
|
|
101
|
+
this.failures = Math.min(this.failures + 1, 9);
|
|
102
|
+
this.nextTry = Date.now() + delay;
|
|
103
|
+
clearTimeout(this.retryTimer);
|
|
104
|
+
this.retryTimer = setTimeout(() => this.wake(), Math.ceil(delay));
|
|
105
|
+
this.retryTimer.unref();
|
|
106
|
+
const code = error?.code;
|
|
107
|
+
const storage = {
|
|
108
|
+
ENOSPC: 'The library disk is full.',
|
|
109
|
+
EROFS: 'The library disk is read-only.',
|
|
110
|
+
EACCES: 'Permission denied while reading the library.',
|
|
111
|
+
EPERM: 'Permission denied while writing the library.'
|
|
112
|
+
};
|
|
113
|
+
const message = error instanceof SyncHttpError ? error.message
|
|
114
|
+
: storage[String(code)] ?? 'Connection unavailable or local library unreadable. Changes remain on this device.';
|
|
115
|
+
this.emit({ ...this.status(), state: 'paused', message });
|
|
116
|
+
}).finally(() => {
|
|
117
|
+
this.active = null;
|
|
118
|
+
if (this.queued) {
|
|
119
|
+
this.queued = false;
|
|
120
|
+
this.wake();
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
context(account) {
|
|
125
|
+
const id = captureLibraryIdentity();
|
|
126
|
+
if (!hasLibraryGrant(account) || libraryKey(account) !== id.accountKey)
|
|
127
|
+
throw Error('Library access required.');
|
|
128
|
+
const current = () => !this.stopped && captureLibraryIdentity().generation === id.generation
|
|
129
|
+
&& readAccount()?.token === account.token && account.expiresAt > Date.now();
|
|
130
|
+
return {
|
|
131
|
+
store: new AccountState(id),
|
|
132
|
+
adapters: this.adapters,
|
|
133
|
+
transport: new LibraryTransport(account, current, this.abort.signal)
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
requireContext() {
|
|
137
|
+
const account = readAccount();
|
|
138
|
+
if (!account)
|
|
139
|
+
throw Error('Sign in to manage the library.');
|
|
140
|
+
return this.context(account);
|
|
141
|
+
}
|
|
142
|
+
summary(ctx, account) {
|
|
143
|
+
const { store } = ctx;
|
|
144
|
+
const rows = store.entries();
|
|
145
|
+
const cursor = store.cursor();
|
|
146
|
+
const key = resolveProjectKey(this.cwd).key;
|
|
147
|
+
const report = readPrivate(join(store.root, 'snapshot-report.json'), { skippedLinks: [] });
|
|
148
|
+
const skipped = report.skippedLinks.length ? 'External links skipped in legacy snapshot: ' + report.skippedLinks.length : null;
|
|
149
|
+
const conflicts = rows.filter(row => row.conflict).map(row => ({
|
|
150
|
+
key: conflictRef(row),
|
|
151
|
+
space: row.space,
|
|
152
|
+
kind: row.kind,
|
|
153
|
+
itemId: row.itemId,
|
|
154
|
+
local: row.conflict.local,
|
|
155
|
+
remote: row.conflict.remote?.content ?? null,
|
|
156
|
+
remoteDeleted: Boolean(row.conflict.remote?.deleted),
|
|
157
|
+
}));
|
|
158
|
+
const bindings = store.bindings();
|
|
159
|
+
const issues = rows.flatMap(row => {
|
|
160
|
+
const reason = row.blocked ?? (row.incoming && row.space !== 'personal' && !bindings[row.space]
|
|
161
|
+
? 'Bind a local project to apply this space.' : null);
|
|
162
|
+
return reason ? [{ space: row.space, kind: row.kind, itemId: row.itemId, reason }] : [];
|
|
163
|
+
});
|
|
164
|
+
return {
|
|
165
|
+
...empty(),
|
|
166
|
+
state: 'ready',
|
|
167
|
+
username: account.user.username,
|
|
168
|
+
baseUrl: account.baseUrl,
|
|
169
|
+
generation: store.identity.generation,
|
|
170
|
+
lastReceivedAt: cursor.receivedAt,
|
|
171
|
+
pendingSend: rows.filter(r => r.out).length,
|
|
172
|
+
pendingApply: rows.filter(r => r.incoming || r.blocked || r.conflict).length + store.damaged.size,
|
|
173
|
+
conflicts,
|
|
174
|
+
boundSpace: Object.entries(store.bindings()).find(([, b]) => b.key === key)?.[0] ?? null,
|
|
175
|
+
issues,
|
|
176
|
+
message: issues.length ? issues[0].itemId + ': ' + issues[0].reason : store.damaged.size ? 'Damaged sync records: ' + store.damaged.size : skipped
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
async cycle() {
|
|
180
|
+
const account = readAccount();
|
|
181
|
+
if (this.retryToken !== (account?.token ?? null)) {
|
|
182
|
+
clearTimeout(this.retryTimer);
|
|
183
|
+
this.retryToken = account?.token ?? null;
|
|
184
|
+
this.failures = 0;
|
|
185
|
+
this.nextTry = 0;
|
|
186
|
+
}
|
|
187
|
+
let id = captureLibraryIdentity();
|
|
188
|
+
const base = {
|
|
189
|
+
...empty(),
|
|
190
|
+
generation: id.generation,
|
|
191
|
+
username: account?.user.username ?? null,
|
|
192
|
+
baseUrl: account?.baseUrl ?? null
|
|
193
|
+
};
|
|
194
|
+
if (!account || !hasLibraryGrant(account) || account.expiresAt <= Date.now() || account.token === this.deadToken) {
|
|
195
|
+
this.lease?.release();
|
|
196
|
+
this.lease = null;
|
|
197
|
+
const message = !account ? (id.generation === 'legacy' ? null : 'Guest library. Sign in to reopen your library.')
|
|
198
|
+
: 'Sign in with library access to resume sync.';
|
|
199
|
+
this.emit({ ...base, state: account ? 'authorization-required' : 'signed-out', message });
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
if (!id.accountRoot && id.generation === 'legacy') {
|
|
203
|
+
if (!await saveLoginAccount(account, { signal: this.abort.signal, expectedToken: account.token })) {
|
|
204
|
+
throw Error('Could not claim the local library.');
|
|
205
|
+
}
|
|
206
|
+
id = captureLibraryIdentity();
|
|
207
|
+
}
|
|
208
|
+
if (Date.now() < this.nextTry || this.stopped)
|
|
209
|
+
return;
|
|
210
|
+
const ctx = this.context(account);
|
|
211
|
+
this.lease ??= acquireLease(join(id.home, 'library-sync'), 'writer.lease');
|
|
212
|
+
if (!this.lease) {
|
|
213
|
+
this.emit({ ...this.summary(ctx, account), state: 'another-host' });
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
this.lease.refresh();
|
|
217
|
+
try {
|
|
218
|
+
await receive(ctx);
|
|
219
|
+
if (this.stopped)
|
|
220
|
+
return;
|
|
221
|
+
await reconcileLocals(ctx);
|
|
222
|
+
await withLibraryWrite(id, () => prepareDeletions(ctx));
|
|
223
|
+
await sendQueued(ctx);
|
|
224
|
+
const status = this.summary(ctx, account);
|
|
225
|
+
const cursor = ctx.store.cursor();
|
|
226
|
+
const mark = [cursor.epoch, cursor.after, status.pendingApply].join('/');
|
|
227
|
+
if (mark !== this.receiptMark || this.receiptToken !== account.token || Date.now() - this.receiptAt >= 60_000) {
|
|
228
|
+
await ctx.transport.receipt(cursor.epoch, cursor.after, status.pendingApply);
|
|
229
|
+
this.receiptAt = Date.now();
|
|
230
|
+
this.receiptMark = mark;
|
|
231
|
+
this.receiptToken = account.token;
|
|
232
|
+
}
|
|
233
|
+
this.nextTry = 0;
|
|
234
|
+
this.failures = 0;
|
|
235
|
+
this.emit(status);
|
|
236
|
+
}
|
|
237
|
+
catch (error) {
|
|
238
|
+
if (error instanceof SyncHttpError && error.code === 'E_LIBRARY_RESET') {
|
|
239
|
+
await this.reset(ctx);
|
|
240
|
+
this.queued = true;
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
if (error instanceof SyncHttpError && [401, 403].includes(error.status)) {
|
|
244
|
+
this.deadToken = account.token;
|
|
245
|
+
this.queued = true;
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
throw error;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
async reset(ctx) {
|
|
252
|
+
await withLibraryWrite(ctx.store.identity, async () => {
|
|
253
|
+
for (const row of ctx.store.entries()) {
|
|
254
|
+
// A pre-restore cursor and its in-flight acknowledgments never belong to the new epoch.
|
|
255
|
+
if (row.out && !row.baseline)
|
|
256
|
+
row.conflict = { local: row.out.op.content ?? null, remote: null };
|
|
257
|
+
delete row.out;
|
|
258
|
+
delete row.incoming;
|
|
259
|
+
delete row.applying;
|
|
260
|
+
ctx.store.put(row);
|
|
261
|
+
}
|
|
262
|
+
ctx.store.saveCursor({ after: 0, receivedAt: null, reset: true });
|
|
263
|
+
});
|
|
264
|
+
this.receiptMark = '';
|
|
265
|
+
}
|
|
266
|
+
async bind(space, cwd = this.cwd) {
|
|
267
|
+
const ctx = this.requireContext();
|
|
268
|
+
if (!(await ctx.transport.spaces()).some(s => s.space === space))
|
|
269
|
+
throw Error('Unknown project space.');
|
|
270
|
+
await withLibraryWrite(ctx.store.identity, () => changeBinding(ctx.store, cwd, space));
|
|
271
|
+
this.wake();
|
|
272
|
+
}
|
|
273
|
+
async unbind(cwd = this.cwd) {
|
|
274
|
+
const ctx = this.requireContext();
|
|
275
|
+
await withLibraryWrite(ctx.store.identity, () => changeBinding(ctx.store, cwd, null));
|
|
276
|
+
this.wake();
|
|
277
|
+
}
|
|
278
|
+
async resolve(key, choice) {
|
|
279
|
+
await resolveConflict(this.requireContext(), key, choice);
|
|
280
|
+
this.wake();
|
|
281
|
+
}
|
|
282
|
+
async dispose() {
|
|
283
|
+
this.stopped = true;
|
|
284
|
+
this.abort.abort();
|
|
285
|
+
this.detach();
|
|
286
|
+
clearInterval(this.timer);
|
|
287
|
+
clearTimeout(this.retryTimer);
|
|
288
|
+
clearTimeout(this.editTimer);
|
|
289
|
+
await this.active;
|
|
290
|
+
this.lease?.release();
|
|
291
|
+
this.lease = null;
|
|
292
|
+
this.listeners.clear();
|
|
293
|
+
}
|
|
294
|
+
}
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { captureLibraryIdentity, privateJson } from './identity.js';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
|
+
import { geneTypeOfId, isValidEvidenceRef, mintEvidenceRef, mintGeneId } from '@aragon-agent/tui/model/gene/ids';
|
|
5
|
+
import { portableContent } from '../gene/transfer.js';
|
|
6
|
+
import { GeneStore } from '../gene/store.js';
|
|
7
|
+
import { redactSecrets } from '../gene/secrets.js';
|
|
8
|
+
import { defaultRandom } from '../gene/service-prepare.js';
|
|
9
|
+
import { GeneVersionService } from '../gene/version-service.js';
|
|
10
|
+
import { sensitiveField } from './memory-adapter.js';
|
|
11
|
+
import { contentHash } from './protocol.js';
|
|
12
|
+
const actor = { kind: 'import', label: 'account-sync', cloudSync: true };
|
|
13
|
+
function context(space) {
|
|
14
|
+
const scope = space.space === 'personal'
|
|
15
|
+
? { kind: 'user' } : { kind: 'project', key: space.projectKey };
|
|
16
|
+
const libraryIdentity = captureLibraryIdentity();
|
|
17
|
+
if (libraryIdentity.dataRoot !== space.dataRoot)
|
|
18
|
+
throw new Error('Account library changed.');
|
|
19
|
+
const store = new GeneStore({ ctx: { teamPath: '', libraryIdentity } });
|
|
20
|
+
const versions = new GeneVersionService({ store, knownSecrets: () => space.knownSecrets ?? [] });
|
|
21
|
+
return { scope, store, versions };
|
|
22
|
+
}
|
|
23
|
+
// The pre-commit mapping also recovers a crash after head publication. Each version has its own
|
|
24
|
+
// mapping, so an unsuccessful import can never reinterpret evidence served by an older version.
|
|
25
|
+
function mapFile(space, id, version) {
|
|
26
|
+
if (!geneTypeOfId(id) || !Number.isSafeInteger(version) || version < 1)
|
|
27
|
+
throw new Error('Invalid gene.');
|
|
28
|
+
if (space.space !== 'personal' && !/^[a-f0-9-]{36}$/i.test(space.space))
|
|
29
|
+
throw new Error('Invalid space.');
|
|
30
|
+
return join(dirname(space.dataRoot), 'gene-projections', space.space, id, String(version) + '.json');
|
|
31
|
+
}
|
|
32
|
+
async function loadMap(space, id, version) {
|
|
33
|
+
try {
|
|
34
|
+
return JSON.parse(await readFile(mapFile(space, id, version), 'utf8'));
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
if (error.code === 'ENOENT')
|
|
38
|
+
return null;
|
|
39
|
+
throw error;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
function provenanceFile(space, id) {
|
|
43
|
+
return join(dirname(mapFile(space, id, 1)), 'origin.json');
|
|
44
|
+
}
|
|
45
|
+
async function provenance(space, id) {
|
|
46
|
+
try {
|
|
47
|
+
return JSON.parse(await readFile(provenanceFile(space, id), 'utf8'));
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
if (error.code === 'ENOENT')
|
|
51
|
+
return null;
|
|
52
|
+
throw error;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
function referenced(content) {
|
|
56
|
+
const names = new Set(content.evidence);
|
|
57
|
+
for (const claim of content.payload.claims ?? []) {
|
|
58
|
+
if (claim.evidence)
|
|
59
|
+
names.add(claim.evidence);
|
|
60
|
+
}
|
|
61
|
+
const exec = content.payload.exec;
|
|
62
|
+
if (exec?.kind === 'script')
|
|
63
|
+
names.add(exec.evidence);
|
|
64
|
+
return [...names];
|
|
65
|
+
}
|
|
66
|
+
function remap(content, refs) {
|
|
67
|
+
const refOf = (ref) => refs[ref] ?? ref;
|
|
68
|
+
content.evidence = content.evidence.map(refOf);
|
|
69
|
+
const knowledge = content.payload;
|
|
70
|
+
for (const claim of knowledge.claims ?? [])
|
|
71
|
+
claim.evidence = refOf(claim.evidence);
|
|
72
|
+
const exec = content.payload.exec;
|
|
73
|
+
if (exec?.kind === 'script')
|
|
74
|
+
exec.evidence = refOf(exec.evidence);
|
|
75
|
+
}
|
|
76
|
+
async function readLocal(space, id, ctx) {
|
|
77
|
+
const { store, scope } = ctx;
|
|
78
|
+
const read = await store.readHead(scope, id);
|
|
79
|
+
if (!read || !['candidate', 'published'].includes(read.head.status))
|
|
80
|
+
return null;
|
|
81
|
+
const { head } = read;
|
|
82
|
+
const n = head.candidateVersion ?? head.currentVersion;
|
|
83
|
+
if (!n)
|
|
84
|
+
return null;
|
|
85
|
+
const version = await store.readVersion(scope, id, n);
|
|
86
|
+
if (!version)
|
|
87
|
+
throw new Error('Missing gene version.');
|
|
88
|
+
const content = structuredClone(portableContent(version.content));
|
|
89
|
+
if (head.candidateVersion === null) {
|
|
90
|
+
content.name = head.brief.name;
|
|
91
|
+
content.tags = head.tags;
|
|
92
|
+
content.localeHints = head.indexData?.localeHints ?? content.localeHints;
|
|
93
|
+
content.roles = head.indexData?.roles ?? content.roles;
|
|
94
|
+
}
|
|
95
|
+
const mapping = version.author.label === actor.label
|
|
96
|
+
? await loadMap(space, id, n) : await provenance(space, id);
|
|
97
|
+
const evidence = [];
|
|
98
|
+
for (const ref of referenced(content)) {
|
|
99
|
+
const piece = await store.readEvidence(scope, id, ref);
|
|
100
|
+
if (!piece)
|
|
101
|
+
throw new Error('Missing gene evidence.');
|
|
102
|
+
evidence.push({ ref: mapping?.refs[ref] ?? ref, kind: piece.kind, text: piece.text });
|
|
103
|
+
}
|
|
104
|
+
if (mapping) {
|
|
105
|
+
content.source = mapping.source;
|
|
106
|
+
remap(content, mapping.refs);
|
|
107
|
+
}
|
|
108
|
+
if (mapping?.order) {
|
|
109
|
+
const order = new Map(mapping.order.map((ref, index) => [ref, index]));
|
|
110
|
+
evidence.sort((a, b) => (order.get(a.ref) ?? Infinity) - (order.get(b.ref) ?? Infinity));
|
|
111
|
+
}
|
|
112
|
+
if (head.type === 'tool')
|
|
113
|
+
delete content.payload.risk;
|
|
114
|
+
const pref = content.payload.preference;
|
|
115
|
+
if (pref?.statedBy === 'inferred')
|
|
116
|
+
pref.confirmed = false;
|
|
117
|
+
const record = { type: head.type, class: head.class, content, evidence, reason: version.reason };
|
|
118
|
+
const last = head.latestVersion > n ? await store.readVersion(scope, id, head.latestVersion) : null;
|
|
119
|
+
return { read, record, localOnly: last?.author.label === actor.label && last.state === 'rejected' };
|
|
120
|
+
}
|
|
121
|
+
function prepareImport(record, existing, secrets, prior) {
|
|
122
|
+
const content = structuredClone(record.content);
|
|
123
|
+
const source = portableContent(content).source;
|
|
124
|
+
const wireRefs = {};
|
|
125
|
+
const newRefs = {};
|
|
126
|
+
const inputs = [];
|
|
127
|
+
const taken = new Set(existing.map(e => e.ref));
|
|
128
|
+
for (const piece of record.evidence) {
|
|
129
|
+
if (redactSecrets(piece.text, secrets).redacted)
|
|
130
|
+
throw new Error('Review the evidence before importing.');
|
|
131
|
+
if (!isValidEvidenceRef(piece.ref) || piece.ref in newRefs)
|
|
132
|
+
throw new Error('Invalid evidence.');
|
|
133
|
+
const same = existing.find(e => (e.ref === piece.ref || prior?.refs[e.ref] === piece.ref)
|
|
134
|
+
&& e.trust === 'untrusted' && e.text === piece.text && e.kind === piece.kind
|
|
135
|
+
&& !Object.hasOwn(wireRefs, e.ref));
|
|
136
|
+
let ref = same?.ref ?? piece.ref;
|
|
137
|
+
if (!same) {
|
|
138
|
+
while (taken.has(ref))
|
|
139
|
+
ref = mintEvidenceRef(defaultRandom);
|
|
140
|
+
taken.add(ref);
|
|
141
|
+
inputs.push({ ref, kind: piece.kind, text: piece.text, trust: 'untrusted' });
|
|
142
|
+
}
|
|
143
|
+
newRefs[piece.ref] = ref;
|
|
144
|
+
wireRefs[ref] = piece.ref;
|
|
145
|
+
}
|
|
146
|
+
if (referenced(content).some(ref => !Object.hasOwn(newRefs, ref)))
|
|
147
|
+
throw new Error('Missing evidence.');
|
|
148
|
+
remap(content, newRefs);
|
|
149
|
+
content.source = { origin: 'import', capturedAt: source.capturedAt };
|
|
150
|
+
if (record.type === 'tool')
|
|
151
|
+
content.payload.risk = 'read_only';
|
|
152
|
+
const preference = content.payload.preference;
|
|
153
|
+
if (preference?.statedBy === 'inferred')
|
|
154
|
+
preference.confirmed = false;
|
|
155
|
+
return { content, inputs, projection: { source, refs: wireRefs, order: Object.keys(newRefs) } };
|
|
156
|
+
}
|
|
157
|
+
export const geneAdapter = {
|
|
158
|
+
async list(space) {
|
|
159
|
+
const ctx = context(space);
|
|
160
|
+
return ctx.store.listHeadIds(ctx.scope);
|
|
161
|
+
},
|
|
162
|
+
async read(space, itemId) {
|
|
163
|
+
const local = await readLocal(space, itemId, context(space));
|
|
164
|
+
if (!local)
|
|
165
|
+
return null;
|
|
166
|
+
const blocked = sensitiveField(local.record, space.knownSecrets ?? []);
|
|
167
|
+
return { itemId, content: local.record, localOnly: local.localOnly, ...(blocked ? { blocked } : {}) };
|
|
168
|
+
},
|
|
169
|
+
async scan(space) {
|
|
170
|
+
const ctx = context(space);
|
|
171
|
+
const rows = [];
|
|
172
|
+
for (const itemId of await ctx.store.listHeadIds(ctx.scope)) {
|
|
173
|
+
try {
|
|
174
|
+
const local = await readLocal(space, itemId, ctx);
|
|
175
|
+
if (!local)
|
|
176
|
+
continue;
|
|
177
|
+
const blocked = sensitiveField(local.record, space.knownSecrets ?? []);
|
|
178
|
+
rows.push({ itemId, content: local.record, localOnly: local.localOnly, ...(blocked ? { blocked } : {}) });
|
|
179
|
+
}
|
|
180
|
+
catch {
|
|
181
|
+
rows.push({ itemId, content: {}, blocked: 'The local gene could not be read.' });
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return rows;
|
|
185
|
+
},
|
|
186
|
+
async apply(space, item, expectedHash) {
|
|
187
|
+
const id = item.itemId;
|
|
188
|
+
const type = geneTypeOfId(id);
|
|
189
|
+
if (!type)
|
|
190
|
+
throw new Error('Invalid gene ID.');
|
|
191
|
+
const ctx = context(space);
|
|
192
|
+
const { scope, store, versions } = ctx;
|
|
193
|
+
const local = await readLocal(space, id, ctx);
|
|
194
|
+
if ((local ? contentHash(local.record) : null) !== expectedHash)
|
|
195
|
+
throw new Error('Local gene changed.');
|
|
196
|
+
const basis = local && { rev: local.read.rev, version: local.read.head.latestVersion };
|
|
197
|
+
if (item.deleted) {
|
|
198
|
+
if (!local)
|
|
199
|
+
return;
|
|
200
|
+
const op = item.deleteReason ?? 'delete';
|
|
201
|
+
if (op !== 'delete' && op !== 'forget' && op !== 'revoke' && op !== 'archive')
|
|
202
|
+
throw new Error('Invalid deletion.');
|
|
203
|
+
const result = await versions.commit({ op, scope, id, reason: 'Removed from account library.' }, actor, basis);
|
|
204
|
+
if (!result.ok)
|
|
205
|
+
throw new Error(result.code);
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
const record = item.content;
|
|
209
|
+
if (!record || record.type !== type || record.class !== 'standard')
|
|
210
|
+
throw new Error('Gene requires review.');
|
|
211
|
+
if (sensitiveField(record, space.knownSecrets ?? []))
|
|
212
|
+
throw new Error('Sensitive gene field.');
|
|
213
|
+
const prior = await provenance(space, id);
|
|
214
|
+
const incoming = prepareImport(record, await store.listEvidence(scope, id), space.knownSecrets ?? [], prior);
|
|
215
|
+
privateJson(mapFile(space, id, (basis?.version ?? 0) + 1), incoming.projection);
|
|
216
|
+
const change = { scope, id, content: incoming.content, evidence: incoming.inputs, reason: String(record.reason) };
|
|
217
|
+
const result = basis
|
|
218
|
+
? await versions.commit({ ...change, op: 'edit' }, actor, basis)
|
|
219
|
+
: await versions.commit({ ...change, op: 'create', type }, actor);
|
|
220
|
+
if (!result.ok)
|
|
221
|
+
throw new Error(result.code);
|
|
222
|
+
privateJson(provenanceFile(space, id), {
|
|
223
|
+
...incoming.projection, refs: { ...prior?.refs, ...incoming.projection.refs },
|
|
224
|
+
});
|
|
225
|
+
},
|
|
226
|
+
async copy(space, record) {
|
|
227
|
+
const id = mintGeneId(record.type, defaultRandom);
|
|
228
|
+
await geneAdapter.apply(space, {
|
|
229
|
+
itemId: id, kind: 'gene', space: space.space, deleted: false,
|
|
230
|
+
rev: 1, seq: 1, updatedAt: Date.now(), content: record,
|
|
231
|
+
}, null);
|
|
232
|
+
return id;
|
|
233
|
+
},
|
|
234
|
+
};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { AccountRecord } from '../account/store.js';
|
|
2
|
+
export interface LibraryIdentity {
|
|
3
|
+
home: string;
|
|
4
|
+
dataRoot: string;
|
|
5
|
+
accountRoot: string | null;
|
|
6
|
+
generation: string;
|
|
7
|
+
accountKey: string | null;
|
|
8
|
+
}
|
|
9
|
+
export declare function privateJson(path: string, value: unknown): void;
|
|
10
|
+
export declare function libraryKey(account: Pick<AccountRecord, 'user' | 'baseUrl'>): string;
|
|
11
|
+
export declare function hasLibraryGrant(account: Pick<AccountRecord, 'scopes'>): boolean;
|
|
12
|
+
export declare function captureLibraryIdentity(home?: string): LibraryIdentity;
|
|
13
|
+
export declare function assertLibraryIdentity(identity: LibraryIdentity): void;
|
|
14
|
+
export declare function withLibraryWriteSync<T>(identity: LibraryIdentity, run: () => T): T;
|
|
15
|
+
export declare function withLibraryWrite<T>(identity: LibraryIdentity, run: () => Promise<T>): Promise<T>;
|
|
16
|
+
/** Publish ownership and credentials under the same cross-process lock. */
|
|
17
|
+
export declare function switchLibraryAccount(home: string, account: AccountRecord | null, changeCredential: () => boolean): boolean;
|
|
18
|
+
/** Validate the snapshot and publish credentials only while the login attempt is still current. */
|
|
19
|
+
export declare function commitLibraryLogin(home: string, account: AccountRecord, current: () => boolean, publish: () => boolean): Promise<boolean>;
|