@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.
Files changed (66) hide show
  1. package/CHANGELOG.md +7 -1
  2. package/README.md +3 -3
  3. package/dist/account/config.d.ts +4 -1
  4. package/dist/account/config.js +14 -1
  5. package/dist/account/device-client.d.ts +2 -0
  6. package/dist/account/device-client.js +11 -5
  7. package/dist/account/login-flow.d.ts +1 -0
  8. package/dist/account/login-flow.js +11 -5
  9. package/dist/account/store.d.ts +5 -0
  10. package/dist/account/store.js +38 -0
  11. package/dist/agent/controller.js +4 -1
  12. package/dist/app/App.d.ts +0 -6
  13. package/dist/app/App.js +36 -5
  14. package/dist/cli.js +6 -0
  15. package/dist/cloud-sync/coordinator.d.ts +64 -0
  16. package/dist/cloud-sync/coordinator.js +294 -0
  17. package/dist/cloud-sync/gene-adapter.d.ts +2 -0
  18. package/dist/cloud-sync/gene-adapter.js +234 -0
  19. package/dist/cloud-sync/identity.d.ts +19 -0
  20. package/dist/cloud-sync/identity.js +311 -0
  21. package/dist/cloud-sync/lease.d.ts +9 -0
  22. package/dist/cloud-sync/lease.js +173 -0
  23. package/dist/cloud-sync/memory-adapter.d.ts +4 -0
  24. package/dist/cloud-sync/memory-adapter.js +107 -0
  25. package/dist/cloud-sync/project-bindings.d.ts +7 -0
  26. package/dist/cloud-sync/project-bindings.js +68 -0
  27. package/dist/cloud-sync/protocol.d.ts +65 -0
  28. package/dist/cloud-sync/protocol.js +193 -0
  29. package/dist/cloud-sync/reconcile.d.ts +14 -0
  30. package/dist/cloud-sync/reconcile.js +539 -0
  31. package/dist/cloud-sync/state.d.ts +117 -0
  32. package/dist/cloud-sync/state.js +208 -0
  33. package/dist/cloud-sync/transport.d.ts +28 -0
  34. package/dist/cloud-sync/transport.js +134 -0
  35. package/dist/commands/account-command.d.ts +2 -1
  36. package/dist/commands/account-command.js +54 -7
  37. package/dist/config/app-paths.d.ts +2 -2
  38. package/dist/config/app-paths.js +4 -4
  39. package/dist/config/env.d.ts +2 -0
  40. package/dist/config/env.js +17 -0
  41. package/dist/gene/commit-exec.js +5 -1
  42. package/dist/gene/commit-prepare.js +3 -1
  43. package/dist/gene/commit-types.d.ts +2 -0
  44. package/dist/gene/manager-actions.js +29 -1
  45. package/dist/gene/manager-library.js +5 -4
  46. package/dist/gene/paths.d.ts +4 -3
  47. package/dist/gene/paths.js +9 -2
  48. package/dist/gene/store.d.ts +2 -0
  49. package/dist/gene/store.js +2 -1
  50. package/dist/gene/transfer.d.ts +2 -0
  51. package/dist/gene/transfer.js +2 -1
  52. package/dist/gene/version-service.d.ts +4 -0
  53. package/dist/gene/version-service.js +72 -8
  54. package/dist/gene/wiring.d.ts +9 -0
  55. package/dist/gene/wiring.js +1 -1
  56. package/dist/host/cloud-sync.d.ts +21 -0
  57. package/dist/host/cloud-sync.js +49 -0
  58. package/dist/memory/format.d.ts +2 -0
  59. package/dist/memory/format.js +11 -2
  60. package/dist/memory/paths.d.ts +5 -3
  61. package/dist/memory/paths.js +15 -6
  62. package/dist/memory/service.d.ts +2 -0
  63. package/dist/memory/service.js +43 -6
  64. package/dist/memory/store.d.ts +11 -1
  65. package/dist/memory/store.js +74 -9
  66. package/package.json +3 -3
@@ -0,0 +1,311 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { chmodSync, closeSync, constants, fsyncSync, openSync, copyFileSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmdirSync, rmSync, writeFileSync, } from 'node:fs';
3
+ import { dirname, join } from 'node:path';
4
+ import { normaliseBaseUrl } from '../account/config.js';
5
+ import { getHomeRoot } from '../config/app-paths.js';
6
+ import { withHomeLock, withHomeLockSync } from './lease.js';
7
+ const HASH = /^[0-9a-f]{64}$/;
8
+ export function privateJson(path, value) {
9
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
10
+ const tmp = path + '.tmp-' + randomUUID();
11
+ try {
12
+ const fd = openSync(tmp, 'wx', 0o600);
13
+ try {
14
+ writeFileSync(fd, JSON.stringify(value));
15
+ fsyncSync(fd);
16
+ }
17
+ finally {
18
+ closeSync(fd);
19
+ }
20
+ renameSync(tmp, path);
21
+ if (process.platform !== 'win32') {
22
+ const directory = openSync(dirname(path), 'r');
23
+ try {
24
+ fsyncSync(directory);
25
+ }
26
+ finally {
27
+ closeSync(directory);
28
+ }
29
+ }
30
+ }
31
+ finally {
32
+ rmSync(tmp, { force: true });
33
+ }
34
+ }
35
+ export function libraryKey(account) {
36
+ const url = normaliseBaseUrl(account.baseUrl);
37
+ if (!url)
38
+ throw Error('Invalid issuing site');
39
+ return createHash('sha256').update(JSON.stringify([url, account.user.id])).digest('hex');
40
+ }
41
+ export function hasLibraryGrant(account) {
42
+ return account.scopes.includes('library:read') && account.scopes.includes('library:write');
43
+ }
44
+ const ownerFile = (home) => join(home, 'library-sync', 'owner.json');
45
+ function readOwner(home) {
46
+ const path = ownerFile(home);
47
+ if (!existsSync(path)) {
48
+ if (existsSync(join(home, 'library-sync', 'accounts')))
49
+ throw Error('Library ownership record is missing.');
50
+ return null;
51
+ }
52
+ const value = JSON.parse(readFileSync(path, 'utf8'));
53
+ if (!HASH.test(value.claimed) || (value.active !== null && !HASH.test(value.active))
54
+ || !value.generation || !['ready', 'claiming', 'switching'].includes(value.phase)) {
55
+ throw Error('Library ownership record is damaged.');
56
+ }
57
+ return value;
58
+ }
59
+ function credentialKey(home) {
60
+ const path = join(home, 'account.json');
61
+ if (!existsSync(path))
62
+ return null;
63
+ const value = JSON.parse(readFileSync(path, 'utf8'));
64
+ if (value.version !== 1 || !value.user?.id || !value.token || !Array.isArray(value.scopes)) {
65
+ throw Error('Library credential is damaged.');
66
+ }
67
+ return libraryKey(value);
68
+ }
69
+ export function captureLibraryIdentity(home = getHomeRoot()) {
70
+ let owner = readOwner(home);
71
+ if (owner?.phase === 'switching') {
72
+ owner = withHomeLockSync(home, () => recoverSwitch(home));
73
+ }
74
+ if (!owner || owner.phase === 'claiming') {
75
+ return { home, dataRoot: home, generation: 'legacy', accountRoot: null, accountKey: null };
76
+ }
77
+ const key = credentialKey(home);
78
+ if (owner.phase !== 'ready' || (owner.active !== null && owner.active !== key)) {
79
+ throw Error('Library account changed. Reopen the session or sign in again.');
80
+ }
81
+ const root = owner.active && join(home, 'library-sync', 'accounts', owner.active);
82
+ return {
83
+ home,
84
+ generation: owner.generation,
85
+ accountRoot: root,
86
+ accountKey: owner.active,
87
+ dataRoot: root ? join(root, 'data') : join(home, 'library-sync', 'guest')
88
+ };
89
+ }
90
+ export function assertLibraryIdentity(identity) {
91
+ if (captureLibraryIdentity(identity.home).generation !== identity.generation) {
92
+ throw Error('Account changed. Reopen this session.');
93
+ }
94
+ }
95
+ export function withLibraryWriteSync(identity, run) {
96
+ return withHomeLockSync(identity.home, () => {
97
+ assertLibraryIdentity(identity);
98
+ return run();
99
+ });
100
+ }
101
+ export function withLibraryWrite(identity, run) {
102
+ return withHomeLock(identity.home, async () => {
103
+ assertLibraryIdentity(identity);
104
+ return run();
105
+ });
106
+ }
107
+ function recoverSwitch(home) {
108
+ const record = readOwner(home);
109
+ if (!record || record.phase !== 'switching')
110
+ return record;
111
+ const key = credentialKey(home);
112
+ let next;
113
+ if (key === record.pendingCredential) {
114
+ next = { claimed: record.claimed, active: record.active, generation: record.generation, phase: 'ready' };
115
+ }
116
+ else if (record.prior && key === record.prior.credential) {
117
+ next = {
118
+ claimed: record.claimed,
119
+ active: record.prior.active,
120
+ generation: record.prior.generation,
121
+ phase: record.prior.phase ?? 'ready'
122
+ };
123
+ }
124
+ else
125
+ throw Error('Library credential changed during recovery. Sign in again.');
126
+ privateJson(ownerFile(home), next);
127
+ return next;
128
+ }
129
+ function skip(name) {
130
+ return name === 'lock' || /(?:\.lock|\.lease)$|\.tmp(?:[-.]|$)/i.test(name);
131
+ }
132
+ /** Digest the source independently before, during and after copying. */
133
+ function manifest(dir, output, skipped) {
134
+ const hash = createHash('sha256');
135
+ if (output)
136
+ mkdirSync(output, { recursive: true, mode: 0o700 });
137
+ const visit = (path, rel) => {
138
+ const stat = lstatSync(path);
139
+ if (stat.isSymbolicLink()) {
140
+ skipped?.push(rel);
141
+ hash.update(JSON.stringify(['link', rel]));
142
+ return;
143
+ }
144
+ if (stat.isDirectory()) {
145
+ hash.update(JSON.stringify(['dir', rel]));
146
+ if (output)
147
+ mkdirSync(join(output, rel), { recursive: true, mode: 0o700 });
148
+ for (const name of readdirSync(path).sort()) {
149
+ if (!skip(name))
150
+ visit(join(path, name), join(rel, name));
151
+ }
152
+ }
153
+ else if (stat.isFile()) {
154
+ if (output) {
155
+ copyFileSync(path, join(output, rel), constants.COPYFILE_EXCL);
156
+ chmodSync(join(output, rel), 0o600);
157
+ }
158
+ const digest = createHash('sha256').update(readFileSync(output ? join(output, rel) : path)).digest('hex');
159
+ hash.update(JSON.stringify([rel, stat.size, digest]));
160
+ }
161
+ else
162
+ throw Error('Unsupported entry in legacy library');
163
+ };
164
+ for (const name of ['genes', 'memory'])
165
+ if (existsSync(join(dir, name)))
166
+ visit(join(dir, name), name);
167
+ return hash.digest('hex');
168
+ }
169
+ function snapshot(home, account, destination = 'data') {
170
+ const root = join(home, 'library-sync', 'accounts', account);
171
+ const data = join(root, destination);
172
+ if (existsSync(data))
173
+ return;
174
+ const staging = join(root, 'snapshot.pending');
175
+ // Only this account can resume a first claim. A partial copy never becomes the active root.
176
+ rmSync(staging, { recursive: true, force: true });
177
+ const skipped = [];
178
+ const before = manifest(home);
179
+ try {
180
+ if (manifest(home, staging, skipped) !== before || manifest(home) !== before) {
181
+ throw Error('Legacy library changed during snapshot. Retry sign-in.');
182
+ }
183
+ privateJson(join(root, 'snapshot-report.json'), { skippedLinks: skipped });
184
+ renameSync(staging, data);
185
+ }
186
+ finally {
187
+ rmSync(staging, { recursive: true, force: true });
188
+ }
189
+ }
190
+ /** Publish ownership and credentials under the same cross-process lock. */
191
+ export function switchLibraryAccount(home, account, changeCredential) {
192
+ return withHomeLockSync(home, () => {
193
+ const prior = recoverSwitch(home);
194
+ if (!prior && (!account || !hasLibraryGrant(account)))
195
+ return changeCredential();
196
+ const key = account ? libraryKey(account) : null;
197
+ if (prior?.phase === 'claiming' && prior.claimed !== key) {
198
+ throw Error('The initial library snapshot belongs to another account.');
199
+ }
200
+ const owner = prior ?? {
201
+ claimed: key,
202
+ active: null,
203
+ generation: randomUUID(),
204
+ phase: 'claiming',
205
+ };
206
+ if (!prior || prior.phase === 'claiming') {
207
+ privateJson(ownerFile(home), owner);
208
+ snapshot(home, owner.claimed);
209
+ }
210
+ const active = key;
211
+ if (prior?.phase === 'ready' && active === prior.active)
212
+ return changeCredential();
213
+ const next = {
214
+ claimed: owner.claimed,
215
+ active,
216
+ phase: 'switching',
217
+ generation: randomUUID(),
218
+ pendingCredential: key,
219
+ prior: { active: owner.active, generation: owner.generation, credential: credentialKey(home),
220
+ phase: owner.phase === 'ready' ? 'ready' : 'claiming' }
221
+ };
222
+ privateJson(ownerFile(home), next);
223
+ if (!changeCredential()) {
224
+ privateJson(ownerFile(home), prior ?? { ...owner, phase: 'claiming' });
225
+ return false;
226
+ }
227
+ privateJson(ownerFile(home), { claimed: next.claimed, active, generation: next.generation, phase: 'ready' });
228
+ return true;
229
+ });
230
+ }
231
+ /** Validate the snapshot and publish credentials only while the login attempt is still current. */
232
+ export function commitLibraryLogin(home, account, current, publish) {
233
+ return withHomeLock(home, async () => {
234
+ if (!current())
235
+ return false;
236
+ const firstClaim = hasLibraryGrant(account) && !recoverSwitch(home);
237
+ try {
238
+ await prepareLibraryLogin(home, account);
239
+ return current() && publish();
240
+ }
241
+ finally {
242
+ if (firstClaim && !current()) {
243
+ const owner = readOwner(home);
244
+ const key = libraryKey(account);
245
+ if (owner?.phase === 'claiming' && owner.claimed === key) {
246
+ // Only this unpublished copy was created by the cancelled attempt under this lock.
247
+ const accounts = join(home, 'library-sync', 'accounts');
248
+ rmSync(join(accounts, key), { recursive: true, force: true });
249
+ if (existsSync(accounts))
250
+ rmdirSync(accounts);
251
+ rmSync(ownerFile(home));
252
+ }
253
+ }
254
+ }
255
+ });
256
+ }
257
+ /** Check a first-claim snapshot with the same index and head recovery logic as the domain. */
258
+ async function prepareLibraryLogin(home, account) {
259
+ if (!hasLibraryGrant(account))
260
+ return;
261
+ const owner = readOwner(home);
262
+ if (owner && owner.phase !== 'claiming')
263
+ return;
264
+ const key = libraryKey(account);
265
+ if (owner && owner.claimed !== key)
266
+ throw Error('First claim belongs to another account.');
267
+ if (!owner)
268
+ privateJson(ownerFile(home), {
269
+ claimed: key,
270
+ active: null,
271
+ generation: randomUUID(),
272
+ phase: 'claiming',
273
+ });
274
+ const root = join(home, 'library-sync', 'accounts', key);
275
+ const staging = join(root, 'checking');
276
+ rmSync(staging, { recursive: true, force: true });
277
+ const original = manifest(home);
278
+ snapshot(home, key, 'checking');
279
+ try {
280
+ if (existsSync(join(staging, 'genes')))
281
+ await validateSnapshotGenes(staging);
282
+ if (manifest(home) !== original)
283
+ throw Error('Legacy library changed while checking the snapshot.');
284
+ // Until ownership is published, local edits still land in the legacy directories. A retry
285
+ // must publish this fresh copy even if a previous attempt finished copying its old draft.
286
+ rmSync(join(root, 'data'), { recursive: true, force: true });
287
+ renameSync(staging, join(root, 'data'));
288
+ }
289
+ finally {
290
+ rmSync(staging, { recursive: true, force: true });
291
+ }
292
+ }
293
+ async function validateSnapshotGenes(staging) {
294
+ const { GeneStore } = await import('../gene/store.js');
295
+ const { ScopeRowsView } = await import('../gene/store-rows.js');
296
+ const { verifyScope, repairScope } = await import('../gene/scope-verify.js');
297
+ const store = new GeneStore({ ctx: { root: join(staging, 'genes'), teamPath: '' } });
298
+ const rows = new ScopeRowsView(store);
299
+ for (const scope of await store.listScopes()) {
300
+ if (scope.kind === 'team')
301
+ continue;
302
+ const report = await verifyScope(store, rows, scope, Date.now());
303
+ if (report.missingVersions.length)
304
+ throw Error('Legacy gene references a missing version.');
305
+ const index = report.index;
306
+ if (!report.counts.matches || index.missing.length || index.stale.length || index.extra.length ||
307
+ report.duplicateArchived.length || report.strayFiles.length) {
308
+ await repairScope(store, rows, scope, Date.now());
309
+ }
310
+ }
311
+ }
@@ -0,0 +1,9 @@
1
+ export declare const outsideHomeLock: <T>(run: () => T) => T;
2
+ export interface Lease {
3
+ refresh(): void;
4
+ release(): void;
5
+ }
6
+ /** Publish complete owner metadata atomically. Never evict a sleeping live owner. */
7
+ export declare function acquireLease(dir: string, name: string): Lease | null;
8
+ export declare function withHomeLockSync<T>(dir: string, run: () => T): T;
9
+ export declare function withHomeLock<T>(dir: string, run: () => Promise<T>): Promise<T>;
@@ -0,0 +1,173 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { linkSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, utimesSync, writeFileSync, } from 'node:fs';
4
+ import { basename, dirname, join } from 'node:path';
5
+ const held = new AsyncLocalStorage();
6
+ const STALE_MS = 30_000;
7
+ export const outsideHomeLock = (run) => held.exit(run);
8
+ function gone(pid) {
9
+ try {
10
+ process.kill(pid, 0);
11
+ return false;
12
+ }
13
+ catch (error) {
14
+ return error.code === 'ESRCH';
15
+ }
16
+ }
17
+ /** Publish complete owner metadata atomically. Never evict a sleeping live owner. */
18
+ export function acquireLease(dir, name) {
19
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
20
+ const file = join(dir, name);
21
+ const unique = file + '.' + randomUUID();
22
+ const owner = JSON.stringify({ pid: process.pid, nonce: randomUUID() });
23
+ writeFileSync(unique, owner, { flag: 'wx', mode: 0o600 });
24
+ try {
25
+ try {
26
+ linkSync(unique, file);
27
+ }
28
+ catch (error) {
29
+ if (error.code !== 'EEXIST')
30
+ throw error;
31
+ if (!reap(file))
32
+ return null;
33
+ try {
34
+ linkSync(unique, file);
35
+ }
36
+ catch (retry) {
37
+ if (retry.code === 'EEXIST')
38
+ return null;
39
+ throw retry;
40
+ }
41
+ }
42
+ }
43
+ finally {
44
+ rmSync(unique, { force: true });
45
+ }
46
+ let active = true;
47
+ return {
48
+ refresh() {
49
+ if (!active || readFileSync(file, 'utf8') !== owner)
50
+ throw Error('Library lease expired');
51
+ utimesSync(file, new Date(), new Date());
52
+ },
53
+ release() {
54
+ if (active && readFileSync(file, 'utf8') === owner)
55
+ rmSync(file);
56
+ active = false;
57
+ },
58
+ };
59
+ }
60
+ function reap(file) {
61
+ // Only one reaper may compare and unlink a dead owner at a time.
62
+ const observed = statSync(file, { throwIfNoEntry: false });
63
+ if (!observed)
64
+ return true;
65
+ if (Date.now() - observed.mtimeMs < STALE_MS)
66
+ return false;
67
+ const release = acquireReaper(file);
68
+ if (!release)
69
+ return false;
70
+ try {
71
+ const stat = statSync(file, { throwIfNoEntry: false });
72
+ if (!stat)
73
+ return true;
74
+ const owner = JSON.parse(readFileSync(file, 'utf8'));
75
+ if (!Number.isSafeInteger(owner.pid) || owner.pid <= 0)
76
+ return false;
77
+ if (Date.now() - stat.mtimeMs < STALE_MS || !gone(owner.pid))
78
+ return false;
79
+ rmSync(file);
80
+ return true;
81
+ }
82
+ finally {
83
+ release();
84
+ }
85
+ }
86
+ export function withHomeLockSync(dir, run) {
87
+ const context = held.getStore();
88
+ if (context?.path === dir && context.active)
89
+ return run();
90
+ const lock = acquireLease(dir, '.library-identity.lock');
91
+ if (!lock)
92
+ throw Error('Library busy. Retry after the current edit.');
93
+ const owner = { path: dir, active: true };
94
+ try {
95
+ return held.run(owner, run);
96
+ }
97
+ finally {
98
+ owner.active = false;
99
+ lock.release();
100
+ }
101
+ }
102
+ export async function withHomeLock(dir, run) {
103
+ const context = held.getStore();
104
+ if (context?.path === dir && context.active)
105
+ return run();
106
+ for (let attempt = 0; attempt < 100; attempt++) {
107
+ const lock = acquireLease(dir, '.library-identity.lock');
108
+ if (!lock) {
109
+ await new Promise(resolve => setTimeout(resolve, 25));
110
+ continue;
111
+ }
112
+ const owner = { path: dir, active: true };
113
+ try {
114
+ return await held.run(owner, run);
115
+ }
116
+ finally {
117
+ owner.active = false;
118
+ lock.release();
119
+ }
120
+ }
121
+ throw Error('Library busy. Retry after the current edit.');
122
+ }
123
+ /** Unique bakery tickets make an interrupted reaper recoverable without unlinking a successor. */
124
+ function acquireReaper(file) {
125
+ const dir = dirname(file);
126
+ const prefix = basename(file) + '.reap-';
127
+ const name = prefix + randomUUID();
128
+ const claim = join(dir, name);
129
+ const staging = join(dir, '.lease-' + randomUUID());
130
+ const entry = { name, ticket: 0, pid: process.pid };
131
+ const publish = () => {
132
+ writeFileSync(staging, JSON.stringify(entry), { flag: 'wx', mode: 0o600 });
133
+ renameSync(staging, claim);
134
+ };
135
+ const peers = () => {
136
+ const active = [];
137
+ for (const candidate of readdirSync(dir).filter(n => n !== name && n.startsWith(prefix))) {
138
+ const path = join(dir, candidate);
139
+ try {
140
+ const owner = JSON.parse(readFileSync(path, 'utf8'));
141
+ if (gone(owner.pid) && Date.now() - statSync(path).mtimeMs >= STALE_MS) {
142
+ rmSync(path, { force: true });
143
+ continue;
144
+ }
145
+ active.push(owner);
146
+ }
147
+ catch (error) {
148
+ if (error.code !== 'ENOENT')
149
+ throw error;
150
+ }
151
+ }
152
+ return active;
153
+ };
154
+ const release = () => rmSync(claim, { force: true });
155
+ try {
156
+ publish();
157
+ entry.ticket = 1 + Math.max(0, ...peers().map(p => p.ticket));
158
+ publish();
159
+ const earlier = peers().some(p => p.ticket === 0 || p.ticket < entry.ticket ||
160
+ (p.ticket === entry.ticket && p.name < name));
161
+ if (!earlier)
162
+ return release;
163
+ release();
164
+ return null;
165
+ }
166
+ catch (error) {
167
+ release();
168
+ throw error;
169
+ }
170
+ finally {
171
+ rmSync(staging, { force: true });
172
+ }
173
+ }
@@ -0,0 +1,4 @@
1
+ import { type LibraryAdapter } from './protocol.js';
2
+ /** Locate a secret without including any original text in a diagnostic. */
3
+ export declare function sensitiveField(value: unknown, secrets: readonly string[], path?: string): string | null;
4
+ export declare const memoryAdapter: LibraryAdapter;
@@ -0,0 +1,107 @@
1
+ import { join, resolve } from 'node:path';
2
+ import { isCompleteMemoryProjection } from '../memory/format.js';
3
+ import { looksLikeSecret } from '../memory/secrets.js';
4
+ import { getMemoryDir, mintNoteId, isValidProjectKey } from '../memory/paths.js';
5
+ import { importNote, readNote, scanScope, trashNote, updateNote } from '../memory/store.js';
6
+ import { contentHash } from './protocol.js';
7
+ function targetFor(scope) {
8
+ if (resolve(getMemoryDir()) !== resolve(join(scope.dataRoot, 'memory'))) {
9
+ throw new Error('Library changed. Reopen the account.');
10
+ }
11
+ if (scope.space === 'personal')
12
+ return { scope: 'global' };
13
+ if (!isValidProjectKey(scope.projectKey))
14
+ throw new Error('Project binding required.');
15
+ return { scope: 'project', projectKey: scope.projectKey };
16
+ }
17
+ function project(note) {
18
+ return {
19
+ title: note.title, summary: note.summaryDerived ? '' : note.summary, body: note.body,
20
+ tags: note.tags, enabled: note.enabled, load: note.load, source: note.source,
21
+ };
22
+ }
23
+ /** Locate a secret without including any original text in a diagnostic. */
24
+ export function sensitiveField(value, secrets, path = 'content') {
25
+ if (typeof value === 'string')
26
+ return looksLikeSecret(value, secrets).hit ? path : null;
27
+ if (!value || typeof value !== 'object')
28
+ return null;
29
+ for (const [key, child] of Object.entries(value)) {
30
+ if (looksLikeSecret(key, secrets).hit)
31
+ return path;
32
+ const result = sensitiveField(child, secrets, path + '.' + key);
33
+ if (result)
34
+ return result;
35
+ }
36
+ return null;
37
+ }
38
+ function localEntry(note, scope) {
39
+ const content = project(note);
40
+ const blocked = sensitiveField(content, scope.knownSecrets ?? []) ??
41
+ (!isCompleteMemoryProjection(note) ? 'Inspect the original note before syncing.' : null);
42
+ return { itemId: note.id, content, ...(blocked ? { blocked } : {}) };
43
+ }
44
+ function draftFor(target, record) {
45
+ if (typeof record.title !== 'string' || typeof record.summary !== 'string'
46
+ || typeof record.body !== 'string' || typeof record.enabled !== 'boolean'
47
+ || !Array.isArray(record.tags) || !record.tags.every(tag => typeof tag === 'string')
48
+ || !['user', 'agent', 'hand', 'imported'].includes(String(record.source))
49
+ || !['auto', 'manual', 'pinned'].includes(String(record.load)))
50
+ throw new Error('Invalid memory.');
51
+ return {
52
+ scope: target.scope, title: record.title, summary: record.summary, body: record.body,
53
+ enabled: record.enabled, tags: record.tags, load: record.load,
54
+ };
55
+ }
56
+ export const memoryAdapter = {
57
+ async read(scope, itemId) {
58
+ const result = readNote(targetFor(scope), itemId);
59
+ if (!result.ok)
60
+ return null;
61
+ return localEntry(result.value, scope);
62
+ },
63
+ async scan(scope) {
64
+ return scanScope(targetFor(scope)).notes.map(note => localEntry(note, scope));
65
+ },
66
+ async apply(scope, item, expectedHash) {
67
+ const target = targetFor(scope);
68
+ const current = readNote(target, item.itemId);
69
+ if (current.ok && localEntry(current.value, scope).blocked)
70
+ throw new Error('Inspect the local memory.');
71
+ const hash = current.ok ? contentHash(project(current.value)) : null;
72
+ if (hash !== expectedHash)
73
+ throw new Error('Local memory changed.');
74
+ if (item.deleted) {
75
+ if (!current.ok)
76
+ return;
77
+ const removed = trashNote(target, item.itemId, current.value.rev);
78
+ if (!removed.ok)
79
+ throw new Error(removed.code);
80
+ return;
81
+ }
82
+ const content = item.content;
83
+ if (!content)
84
+ throw new Error('Missing memory.');
85
+ if (sensitiveField(content, scope.knownSecrets ?? []))
86
+ throw new Error('Sensitive memory.');
87
+ const draft = draftFor(target, content);
88
+ if (current.ok && current.value.source !== content.source)
89
+ throw new Error('Creator changed.');
90
+ const knownSecrets = scope.knownSecrets ?? [];
91
+ const result = current.ok
92
+ ? updateNote(target, item.itemId, draft, current.value.rev, { source: 'imported', knownSecrets })
93
+ : importNote(target, draft, { id: item.itemId, creator: content.source, knownSecrets });
94
+ if (!result.ok)
95
+ throw new Error(result.code);
96
+ },
97
+ async copy(scope, content) {
98
+ const target = targetFor(scope);
99
+ const id = mintNoteId();
100
+ const result = importNote(target, draftFor(target, content), {
101
+ id, creator: content.source, knownSecrets: scope.knownSecrets ?? [],
102
+ });
103
+ if (!result.ok)
104
+ throw new Error(result.code);
105
+ return id;
106
+ },
107
+ };
@@ -0,0 +1,7 @@
1
+ import { type AdapterScope } from './protocol.js';
2
+ import { AccountState } from './state.js';
3
+ /** Desktop main can run sync before a model session has registered its provider keys. */
4
+ export declare function refreshKnownSecrets(): readonly string[];
5
+ export declare function adapterScope(store: AccountState, space: string): Promise<AdapterScope | null>;
6
+ export declare function changeBinding(store: AccountState, cwd: string, space: string | null): Promise<void>;
7
+ export declare function bindingGeneration(store: AccountState, space: string): string | undefined;
@@ -0,0 +1,68 @@
1
+ import { existsSync, statSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { getSecrets, registerProfileSecrets, registerSecret, registerSecretsFrom } from '@aragon-agent/tui/model/logging/secret-registry';
5
+ import { getConfigPath } from '../config/app-paths.js';
6
+ import { readConfigFile } from '../config/store.js';
7
+ import { PROVIDER_ENV_KEYS } from '../config/env.js';
8
+ import { ProjectLearningPolicy } from '../gene/policy.js';
9
+ import { resolveProjectKey } from '../memory/paths.js';
10
+ import { UUID } from './protocol.js';
11
+ let configStamp = null;
12
+ /** Desktop main can run sync before a model session has registered its provider keys. */
13
+ export function refreshKnownSecrets() {
14
+ const path = getConfigPath();
15
+ const stat = statSync(path, { throwIfNoEntry: false });
16
+ const stamp = path + '/' + stat?.mtimeMs + '/' + stat?.size;
17
+ if (stamp !== configStamp) {
18
+ const disk = readConfigFile();
19
+ if (disk.parseError)
20
+ throw Error('Check the model settings file before syncing.');
21
+ registerSecretsFrom(disk.config?.apiKeys);
22
+ registerProfileSecrets(disk.config);
23
+ configStamp = stamp;
24
+ }
25
+ for (const names of Object.values(PROVIDER_ENV_KEYS))
26
+ for (const name of names)
27
+ registerSecret(process.env[name]);
28
+ return getSecrets();
29
+ }
30
+ export async function adapterScope(store, space) {
31
+ const dataRoot = store.identity.dataRoot;
32
+ const basic = { space, dataRoot, knownSecrets: refreshKnownSecrets() };
33
+ if (space === 'personal')
34
+ return basic;
35
+ const binding = store.bindings()[space];
36
+ if (!binding || !existsSync(binding.root) || resolveProjectKey(binding.root).key !== binding.key)
37
+ return null;
38
+ const policy = new ProjectLearningPolicy({ ctx: { root: join(dataRoot, 'genes') } });
39
+ const verdict = await policy.refresh(binding.key, binding.root);
40
+ return verdict.learn ? { ...basic, projectKey: binding.key, projectRoot: binding.root } : null;
41
+ }
42
+ export async function changeBinding(store, cwd, space) {
43
+ const project = resolveProjectKey(cwd);
44
+ const bindings = store.bindings();
45
+ const old = Object.entries(bindings).find(([, v]) => v.key === project.key)?.[0];
46
+ if (space) {
47
+ if (!UUID.test(space))
48
+ throw Error('Enter a valid project space identifier.');
49
+ if (bindings[space] && bindings[space].key !== project.key)
50
+ throw Error('Space is bound to another project.');
51
+ const policy = new ProjectLearningPolicy({ ctx: { root: join(store.identity.dataRoot, 'genes') } });
52
+ if (!(await policy.refresh(project.key, project.root)).learn)
53
+ throw Error('Project is excluded.');
54
+ }
55
+ if (old === space)
56
+ return;
57
+ if (old)
58
+ delete bindings[old];
59
+ if (space)
60
+ bindings[space] = { key: project.key, root: project.root, generation: randomUUID() };
61
+ store.saveBindings(bindings);
62
+ // Re-read remote before resuming queued work, including when rebinding to the same project.
63
+ const cursor = store.cursor();
64
+ store.saveCursor({ ...cursor, after: 0, fence: undefined });
65
+ }
66
+ export function bindingGeneration(store, space) {
67
+ return space === 'personal' ? 'personal' : store.bindings()[space]?.generation;
68
+ }