@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,208 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import { EventEmitter } from 'node:events';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+ import { existsSync, readFileSync, readdirSync, rmSync } from 'node:fs';
5
+ import { join } from 'node:path';
6
+ import { captureLibraryIdentity, privateJson, withLibraryWriteSync, } from './identity.js';
7
+ import { contentHash, isKey, isRecord, itemKey, parseItem, UUID } from './protocol.js';
8
+ const signal = new EventEmitter();
9
+ const inbound = new AsyncLocalStorage();
10
+ export function wakeLibrarySync(changed) {
11
+ if (changed && !inbound.getStore()) {
12
+ const id = captureLibraryIdentity();
13
+ if (id.accountRoot)
14
+ withLibraryWriteSync(id, () => {
15
+ const store = new AccountState(id);
16
+ const loc = mapping(store.bindings(), changed.projectKey);
17
+ if (loc) {
18
+ const row = store.get({ space: loc[0], kind: changed.kind, itemId: changed.itemId });
19
+ if (!row.dirty) {
20
+ row.dirty = true;
21
+ store.put(row);
22
+ }
23
+ }
24
+ });
25
+ }
26
+ if (!inbound.getStore())
27
+ signal.emit('wake');
28
+ }
29
+ export function observeLibraryWake(fn) {
30
+ signal.on('wake', fn);
31
+ return () => { signal.off('wake', fn); };
32
+ }
33
+ export const applyingRemote = (fn) => inbound.run(true, fn);
34
+ export function readPrivate(file, fallback) {
35
+ if (!existsSync(file))
36
+ return fallback;
37
+ return JSON.parse(readFileSync(file, 'utf8'));
38
+ }
39
+ function names(dir) {
40
+ return existsSync(dir) ? readdirSync(dir).filter(n => n.endsWith('.json')) : [];
41
+ }
42
+ /** All calls that mutate this store execute inside the captured identity's home lock. */
43
+ export class AccountState {
44
+ identity;
45
+ root;
46
+ damaged = new Set();
47
+ cached = null;
48
+ constructor(identity) {
49
+ this.identity = identity;
50
+ if (!identity.accountRoot)
51
+ throw Error('Sign in with library access.');
52
+ this.root = identity.accountRoot;
53
+ }
54
+ cursor() { return readPrivate(join(this.root, 'cursor.json'), { after: 0, receivedAt: null }); }
55
+ saveCursor(v) { privateJson(join(this.root, 'cursor.json'), v); }
56
+ scans() { return readPrivate(join(this.root, 'scans.json'), {}); }
57
+ saveScans(scans) { privateJson(join(this.root, 'scans.json'), scans); }
58
+ bindings() { return readPrivate(join(this.root, 'bindings.json'), {}); }
59
+ saveBindings(v) { privateJson(join(this.root, 'bindings.json'), v); }
60
+ entryPath(key) {
61
+ const file = createHash('sha256').update(itemKey(key)).digest('hex');
62
+ return join(this.root, 'records', file + '.json');
63
+ }
64
+ get(key) {
65
+ const row = readPrivate(this.entryPath(key), { space: key.space, kind: key.kind, itemId: key.itemId });
66
+ if (!isRecord(row) || !isKey(row) || itemKey(row) !== itemKey(key))
67
+ throw Error('Damaged library record.');
68
+ return row;
69
+ }
70
+ put(entry) {
71
+ privateJson(this.entryPath(entry), entry);
72
+ this.cached?.set(itemKey(entry), structuredClone(entry));
73
+ }
74
+ entries() {
75
+ const dir = join(this.root, 'records');
76
+ if (!this.cached) {
77
+ this.cached = new Map();
78
+ for (const name of names(dir)) {
79
+ const path = join(dir, name);
80
+ try {
81
+ const row = readPrivate(path, null);
82
+ if (!isRecord(row) || !isKey(row) || this.entryPath(row) !== path)
83
+ throw Error('Damaged record.');
84
+ this.cached.set(itemKey(row), row);
85
+ }
86
+ catch {
87
+ this.damaged.add(name);
88
+ }
89
+ }
90
+ }
91
+ return [...this.cached.values()];
92
+ }
93
+ preserveIncoming(item, epoch) {
94
+ const key = createHash('sha256').update(itemKey(item)).digest('hex');
95
+ privateJson(join(this.root, 'quarantine', key + '.json'), { epoch, item });
96
+ this.damaged.add(key);
97
+ }
98
+ replayQuarantine(epoch) {
99
+ const dir = join(this.root, 'quarantine');
100
+ for (const name of names(dir)) {
101
+ const path = join(dir, name);
102
+ try {
103
+ const held = readPrivate(path, null);
104
+ if (held.epoch !== epoch)
105
+ continue;
106
+ const remote = parseItem(held.item);
107
+ const row = this.get(remote);
108
+ if ((row.incoming?.seq ?? 0) < remote.seq &&
109
+ (row.baseline?.epoch !== epoch || row.baseline.rev < remote.rev)) {
110
+ row.incoming = remote;
111
+ this.put(row);
112
+ }
113
+ rmSync(path);
114
+ }
115
+ catch {
116
+ this.damaged.add(name);
117
+ }
118
+ }
119
+ }
120
+ facts() {
121
+ const dir = join(this.root, 'deletions');
122
+ const facts = [];
123
+ for (const name of names(dir)) {
124
+ try {
125
+ const fact = readPrivate(join(dir, name), null);
126
+ if (!fact || !UUID.test(fact.id) || fact.id + '.json' !== name || !isRecord(fact.key)
127
+ || !isKey(fact.key) || typeof fact.complete !== 'boolean')
128
+ throw Error('Damaged deletion record.');
129
+ facts.push(fact);
130
+ }
131
+ catch {
132
+ this.damaged.add(name);
133
+ }
134
+ }
135
+ return facts;
136
+ }
137
+ saveFact(fact) { privateJson(join(this.root, 'deletions', fact.id + '.json'), fact); }
138
+ clearFact(id) { rmSync(join(this.root, 'deletions', id + '.json'), { force: true }); }
139
+ }
140
+ function mapping(bindings, key) {
141
+ if (!key)
142
+ return ['personal', 'personal'];
143
+ const match = Object.entries(bindings).find(([, b]) => b.key === key);
144
+ return match && [match[0], match[1].generation];
145
+ }
146
+ /** Only an explicit, completed domain action may create an outbound tombstone. */
147
+ export function beginLibraryDeletion(input) {
148
+ if (inbound.getStore())
149
+ return () => { };
150
+ const identity = captureLibraryIdentity();
151
+ if (!identity.accountRoot)
152
+ return () => { };
153
+ return withLibraryWriteSync(identity, () => {
154
+ const store = new AccountState(identity);
155
+ const bindings = store.bindings();
156
+ const source = mapping(bindings, input.projectKey);
157
+ const dest = input.target && mapping(bindings, input.target.projectKey);
158
+ if (!source || (input.target && !dest))
159
+ return () => { };
160
+ const key = { space: source[0], kind: input.kind, itemId: input.itemId };
161
+ const row = store.get(key);
162
+ const op = row.out?.op;
163
+ const base = row.baseline ?? (op?.op === 'create' && op.content ? {
164
+ epoch: op.epoch,
165
+ rev: 1,
166
+ hash: contentHash(op.content),
167
+ localHash: contentHash(op.content),
168
+ } : undefined);
169
+ if (!base || !base.hash)
170
+ return () => { };
171
+ const fact = {
172
+ id: randomUUID(),
173
+ key,
174
+ baseline: base,
175
+ ...(op && op.content && op.op !== 'delete' ? {
176
+ predecessor: { opId: op.opId, rev: op.baseRev + 1, hash: contentHash(op.content) },
177
+ } : {}),
178
+ binding: source[1],
179
+ complete: false,
180
+ reason: input.reason,
181
+ verify: input.verify,
182
+ sourcePath: input.sourcePath
183
+ };
184
+ if (input.target && dest) {
185
+ fact.target = { ...key, space: dest[0], itemId: input.target.itemId };
186
+ fact.targetHash = input.target.contentHash;
187
+ fact.targetBinding = dest[1];
188
+ }
189
+ store.saveFact(fact);
190
+ return () => withLibraryWriteSync(identity, () => {
191
+ store.saveFact({ ...fact, complete: true });
192
+ wakeLibrarySync();
193
+ });
194
+ });
195
+ }
196
+ export function isCloudDeleted(input) {
197
+ const identity = captureLibraryIdentity();
198
+ if (!identity.accountRoot)
199
+ return false;
200
+ const store = new AccountState(identity);
201
+ const location = mapping(store.bindings(), input.projectKey);
202
+ if (!location)
203
+ return false;
204
+ const key = { space: location[0], kind: input.kind, itemId: input.itemId };
205
+ const row = store.get(key);
206
+ return row.baseline?.hash === null || row.incoming?.deleted === true ||
207
+ store.facts().some(fact => fact.complete && itemKey(fact.key) === itemKey(key));
208
+ }
@@ -0,0 +1,28 @@
1
+ import type { AccountRecord } from '../account/store.js';
2
+ import type { LibraryKey, Mutation } from './protocol.js';
3
+ export declare class SyncHttpError extends Error {
4
+ readonly status: number;
5
+ readonly code: string;
6
+ readonly retryMs: number;
7
+ readonly reusedOpId: boolean;
8
+ constructor(status: number, code: string, retryMs?: number, reusedOpId?: boolean);
9
+ }
10
+ export declare class LibraryTransport {
11
+ readonly credential: AccountRecord;
12
+ readonly current: () => boolean;
13
+ readonly signal: AbortSignal;
14
+ readonly http: typeof fetch;
15
+ constructor(credential: AccountRecord, current: () => boolean, signal: AbortSignal, http?: typeof fetch);
16
+ private request;
17
+ spaces(): Promise<{
18
+ space: string;
19
+ label: string;
20
+ }[]>;
21
+ changes(after: number, epoch?: string, fence?: number): Promise<import("./protocol.js").ChangePage>;
22
+ detail(key: LibraryKey, epoch: string): Promise<import("./protocol.js").LibraryItem>;
23
+ mutate(op: Mutation): Promise<{
24
+ rev: number;
25
+ seq: number;
26
+ }>;
27
+ receipt(epoch: string, receivedSeq: number, pendingCount: number): Promise<void>;
28
+ }
@@ -0,0 +1,134 @@
1
+ import { apiUrl, isCredentialSite, normaliseBaseUrl } from '../account/config.js';
2
+ import { counter, isRecord, isSpace, parseItem, parsePage, UUID, validateMutation } from './protocol.js';
3
+ export class SyncHttpError extends Error {
4
+ status;
5
+ code;
6
+ retryMs;
7
+ reusedOpId;
8
+ constructor(status, code, retryMs = 0, reusedOpId = false) {
9
+ super('Library request failed (' + status + ', ' + code + ').');
10
+ this.status = status;
11
+ this.code = code;
12
+ this.retryMs = retryMs;
13
+ this.reusedOpId = reusedOpId;
14
+ }
15
+ }
16
+ async function readBounded(reply) {
17
+ if (!reply.body)
18
+ throw Error('Empty library response.');
19
+ const reader = reply.body.getReader();
20
+ const parts = [];
21
+ let size = 0;
22
+ try {
23
+ for (;;) {
24
+ const packet = await reader.read();
25
+ if (packet.done)
26
+ break;
27
+ size += packet.value.byteLength;
28
+ if (size > 1024 * 1024) {
29
+ await reader.cancel();
30
+ throw Error('Oversize library response.');
31
+ }
32
+ parts.push(packet.value);
33
+ }
34
+ }
35
+ finally {
36
+ reader.releaseLock();
37
+ }
38
+ return JSON.parse(Buffer.concat(parts).toString('utf8'));
39
+ }
40
+ export class LibraryTransport {
41
+ credential;
42
+ current;
43
+ signal;
44
+ http;
45
+ constructor(credential, current, signal, http = fetch) {
46
+ this.credential = credential;
47
+ this.current = current;
48
+ this.signal = signal;
49
+ this.http = http;
50
+ }
51
+ async request(path, body) {
52
+ const base = normaliseBaseUrl(this.credential.baseUrl);
53
+ if (!base || base !== this.credential.baseUrl || !isCredentialSite(base))
54
+ throw Error('Invalid issuing site.');
55
+ if (!this.current() || this.signal.aborted)
56
+ throw Error('Account changed.');
57
+ const controller = new AbortController();
58
+ const abort = () => controller.abort();
59
+ const timeout = setTimeout(abort, 10_000);
60
+ this.signal.addEventListener('abort', abort, { once: true });
61
+ try {
62
+ const headers = { authorization: 'Bearer ' + this.credential.token, 'content-type': 'application/json' };
63
+ const reply = await this.http(apiUrl(base, '/api/v1/library/' + path), {
64
+ method: body === undefined ? 'GET' : 'POST',
65
+ headers,
66
+ redirect: 'error',
67
+ body: JSON.stringify(body),
68
+ signal: controller.signal,
69
+ });
70
+ if (!this.current())
71
+ throw Error('Account changed.');
72
+ if (!reply.ok) {
73
+ const message = await readBounded(reply).catch(() => null);
74
+ const error = isRecord(message) && isRecord(message.error) ? message.error : null;
75
+ const raw = error?.code;
76
+ const code = typeof raw === 'string' && /^E_[A-Z_]+$/.test(raw) ? raw : 'HTTP_ERROR';
77
+ const seconds = Number(reply.headers.get('retry-after')) || 0;
78
+ const reusedOpId = code === 'E_LIBRARY_CONFLICT' && isRecord(error?.details) && error.details.reason === 'op_id';
79
+ throw new SyncHttpError(reply.status, code, Math.min(seconds, 3600) * 1000, reusedOpId);
80
+ }
81
+ return await readBounded(reply);
82
+ }
83
+ finally {
84
+ clearTimeout(timeout);
85
+ this.signal.removeEventListener('abort', abort);
86
+ }
87
+ }
88
+ async spaces() {
89
+ const reply = await this.request('spaces');
90
+ if (!isRecord(reply) || !Array.isArray(reply.spaces) || typeof reply.epoch !== 'string'
91
+ || !UUID.test(reply.epoch))
92
+ throw Error('Invalid space list.');
93
+ return reply.spaces.map(s => {
94
+ if (!isRecord(s) || !isSpace(s.space) || typeof s.label !== 'string')
95
+ throw Error('Invalid space.');
96
+ return { space: s.space, label: s.label };
97
+ });
98
+ }
99
+ async changes(after, epoch, fence) {
100
+ const query = new URLSearchParams({ after: String(after) });
101
+ if (epoch)
102
+ query.set('epoch', epoch);
103
+ if (fence !== undefined)
104
+ query.set('fence', String(fence));
105
+ const page = parsePage(await this.request('changes?' + query), after);
106
+ if ((epoch && epoch !== page.epoch) || (fence !== undefined && fence !== page.fence)) {
107
+ throw new SyncHttpError(409, 'E_LIBRARY_RESET');
108
+ }
109
+ return page;
110
+ }
111
+ async detail(key, epoch) {
112
+ const path = [key.space, key.kind, key.itemId].map(encodeURIComponent).join('/');
113
+ const reply = await this.request('items/' + path);
114
+ if (!isRecord(reply) || reply.epoch !== epoch)
115
+ throw new SyncHttpError(409, 'E_LIBRARY_RESET');
116
+ const item = parseItem(reply.item);
117
+ if (item.space !== key.space || item.kind !== key.kind || item.itemId !== key.itemId) {
118
+ throw Error('Wrong item in library response.');
119
+ }
120
+ return item;
121
+ }
122
+ async mutate(op) {
123
+ if (!validateMutation(op))
124
+ throw new SyncHttpError(400, 'E_VALIDATION');
125
+ const reply = await this.request('mutations', op);
126
+ if (!isRecord(reply) || reply.epoch !== op.epoch || reply.opId !== op.opId
127
+ || !counter(reply.rev) || !reply.rev || !counter(reply.seq) || !reply.seq)
128
+ throw Error('Invalid acknowledgment.');
129
+ return { rev: reply.rev, seq: reply.seq };
130
+ }
131
+ async receipt(epoch, receivedSeq, pendingCount) {
132
+ await this.request('receipt', { epoch, receivedSeq, pendingCount, label: 'Aragon client' });
133
+ }
134
+ }
@@ -53,7 +53,8 @@ export interface AccountCommandPort {
53
53
  /** Absolute path of `<home>/account.json`, for the reports below. */
54
54
  accountPath(): string;
55
55
  /** Open the four-phase panel and run `startLogin` in the background (C6). */
56
- openLogin(): void;
56
+ openLogin(accountOnly?: boolean): void;
57
+ cloudSync?(): import('../host/cloud-sync.js').CloudSyncHost | null;
57
58
  /** Open the account panel - the same overlay `Ctrl+X` / `Alt+X` opens. */
58
59
  openAccount(): void;
59
60
  signOut(): AccountSignOutResult;
@@ -111,17 +111,16 @@ function resolvePort(ctx) {
111
111
  return port;
112
112
  }
113
113
  /**
114
- * `/login [status]`.
114
+ * `/login [status|local]`.
115
115
  *
116
116
  * NO ARGS MEANS "SHOW ME WHERE I STAND, THEN LET ME SIGN IN": the report is printed and the
117
117
  * panel opens in its `prompt` phase, where Enter starts the device flow. `status` prints the
118
- * report and stops. Anything else is refused with the usage line rather than ignored, so a typo
119
- * cannot be mistaken for a start.
118
+ * report and stops. `local` opens the same sign-in panel with account-only access.
120
119
  */
121
120
  function runLogin(ctx) {
122
121
  const arg = ctx.args.trim().toLowerCase();
123
- if (arg !== '' && arg !== 'status') {
124
- ctx.notify('warn', `Unknown argument "${arg}" - use /login [status].`);
122
+ if (arg !== '' && arg !== 'status' && arg !== 'local') {
123
+ ctx.notify('warn', `Unknown argument "${arg}" - use /login [status|local].`);
125
124
  return;
126
125
  }
127
126
  const port = resolvePort(ctx);
@@ -132,7 +131,10 @@ function runLogin(ctx) {
132
131
  }
133
132
  if (arg === 'status')
134
133
  return;
135
- port.openLogin();
134
+ if (arg === 'local')
135
+ port.openLogin(true);
136
+ else
137
+ port.openLogin();
136
138
  }
137
139
  /**
138
140
  * `/logout`.
@@ -167,10 +169,55 @@ function runLogout(ctx) {
167
169
  * the facts and the two actions live, and printing every field twice would give the same
168
170
  * numbers two places to be wrong.
169
171
  */
170
- function runAccount(ctx) {
172
+ async function runAccount(ctx) {
171
173
  const port = resolvePort(ctx);
172
174
  if (port === null)
173
175
  return;
176
+ if (ctx.args.trim().split(/\s+/)[0] === 'sync') {
177
+ const host = port.cloudSync?.();
178
+ if (!host) {
179
+ ctx.notify('warn', 'Library sync is unavailable in this session.');
180
+ return;
181
+ }
182
+ const [, action, arg, choice, ...extra] = ctx.args.trim().split(/\s+/);
183
+ const cwd = ctx.controller.getCwd();
184
+ try {
185
+ if (!action) {
186
+ const v = host.status();
187
+ ctx.notify('info', [
188
+ v.baseUrl ?? 'No issuing site', v.state,
189
+ 'Last received: ' + (v.lastReceivedAt ? new Date(v.lastReceivedAt).toISOString() : 'never'),
190
+ 'Pending send: ' + v.pendingSend, 'pending apply: ' + v.pendingApply,
191
+ 'conflicts: ' + v.conflicts.length, 'project space: ' + (host.bindingFor(cwd) ?? 'unbound'), v.message,
192
+ ].filter(Boolean).join(' | '));
193
+ for (const issue of v.issues)
194
+ ctx.notify('warn', issue.itemId + ' (' + issue.space + '): ' + issue.reason);
195
+ }
196
+ else if (action === 'bind' && arg && !choice) {
197
+ await host.bind(arg, cwd);
198
+ ctx.notify('info', 'Project bound.');
199
+ }
200
+ else if (action === 'unbind' && !arg) {
201
+ await host.unbind(cwd);
202
+ ctx.notify('info', 'Project unbound.');
203
+ }
204
+ else if (action === 'conflicts' && !arg) {
205
+ const conflicts = host.status().conflicts.map(c => `${c.key} ${c.space}/${c.kind}/${c.itemId}`);
206
+ ctx.notify('info', conflicts.join('\n') || 'No conflicts.');
207
+ }
208
+ else if (action === 'resolve' && arg && !extra.length
209
+ && (choice === 'remote' || choice === 'local' || choice === 'copy')) {
210
+ await host.resolve(arg, choice);
211
+ ctx.notify('info', 'Conflict resolved.');
212
+ }
213
+ else
214
+ ctx.notify('warn', 'Use /account sync [bind <space>|unbind|conflicts|resolve <key> remote|copy|local].');
215
+ }
216
+ catch (error) {
217
+ ctx.notify('warn', error instanceof Error ? error.message : 'Library action failed.');
218
+ }
219
+ return;
220
+ }
174
221
  ctx.notify('info', describeExpiry(port.status()));
175
222
  port.openAccount();
176
223
  }
@@ -188,7 +188,7 @@ export declare function getGovernanceDir(): string;
188
188
  * real user's notes, so tests delete single files or directories they built themselves.
189
189
  * The caller creates it (0700 on POSIX); this function only names it.
190
190
  */
191
- export declare function getMemoryDir(): string;
191
+ export declare function getMemoryDir(dataRoot?: string): string;
192
192
  /**
193
193
  * `<home>/genes` - the Gene Bank (gene-bank spec 6.8).
194
194
  *
@@ -198,7 +198,7 @@ export declare function getMemoryDir(): string;
198
198
  * user's library, so tests delete directories they built themselves. The caller creates it
199
199
  * (0700 on POSIX); this function only names it.
200
200
  */
201
- export declare function getGeneDir(): string;
201
+ export declare function getGeneDir(dataRoot?: string): string;
202
202
  /**
203
203
  * `<home>/redteam` - red team prompt profiles (redteam-prompt-profile 8.1).
204
204
  *
@@ -283,8 +283,8 @@ export function getGovernanceDir() {
283
283
  * real user's notes, so tests delete single files or directories they built themselves.
284
284
  * The caller creates it (0700 on POSIX); this function only names it.
285
285
  */
286
- export function getMemoryDir() {
287
- return join(resolution.root, 'memory');
286
+ export function getMemoryDir(dataRoot = resolution.root) {
287
+ return join(dataRoot, 'memory');
288
288
  }
289
289
  /**
290
290
  * `<home>/genes` - the Gene Bank (gene-bank spec 6.8).
@@ -295,8 +295,8 @@ export function getMemoryDir() {
295
295
  * user's library, so tests delete directories they built themselves. The caller creates it
296
296
  * (0700 on POSIX); this function only names it.
297
297
  */
298
- export function getGeneDir() {
299
- return join(resolution.root, 'genes');
298
+ export function getGeneDir(dataRoot = resolution.root) {
299
+ return join(dataRoot, 'genes');
300
300
  }
301
301
  /**
302
302
  * `<home>/redteam` - red team prompt profiles (redteam-prompt-profile 8.1).
@@ -50,6 +50,8 @@ import { type PersistedConfig } from '@aragon-agent/tui/model/config/schema';
50
50
  export declare function loadDotenv(cwd: string): void;
51
51
  /** Provider -> the env vars that may carry its key (first non-empty wins). */
52
52
  export declare const PROVIDER_ENV_KEYS: Record<string, string[]>;
53
+ export declare let managedConfig: boolean;
54
+ export declare function enableManagedConfig(): void;
53
55
  export interface EnvConfig {
54
56
  /** Non-secret overrides sourced from ARAGON_* env vars. */
55
57
  partial: Partial<PersistedConfig>;
@@ -54,6 +54,8 @@ import { clampContextWindow, clampMaxTokens, clampTheme, clampThinkingLevel, isA
54
54
  * process env wins — dotenv never overrides already-set variables).
55
55
  */
56
56
  export function loadDotenv(cwd) {
57
+ if (managedConfig)
58
+ return;
57
59
  dotenv.config({ path: join(cwd, '.env') });
58
60
  }
59
61
  /** Provider -> the env vars that may carry its key (first non-empty wins). */
@@ -62,6 +64,21 @@ export const PROVIDER_ENV_KEYS = {
62
64
  openai: ['OPENAI_API_KEY'],
63
65
  google: ['GOOGLE_API_KEY', 'GEMINI_API_KEY'],
64
66
  };
67
+ // Set by the root command before the first config load. A profile reload only
68
+ // passes cwd, so the configuration source must live for the whole CLI session.
69
+ export let managedConfig = false;
70
+ export function enableManagedConfig() {
71
+ managedConfig = true;
72
+ // This is the CLI child's environment. Keep its home, terminal and task
73
+ // settings, including ARAGON_PLAN for unattended sessions.
74
+ for (const name of [
75
+ 'ARAGON_PROVIDER', 'ARAGON_MODEL', 'ARAGON_BASE_URL', 'ARAGON_FAST',
76
+ 'ARAGON_FAST_PROVIDER', 'ARAGON_FAST_MODEL', 'ARAGON_FAST_BASE_URL',
77
+ ...Object.values(PROVIDER_ENV_KEYS).flat(),
78
+ ]) {
79
+ delete process.env[name];
80
+ }
81
+ }
65
82
  function firstEnv(names) {
66
83
  for (const name of names) {
67
84
  const v = process.env[name];
@@ -3,8 +3,12 @@ import { GeneStoreError } from './gene-errors.js';
3
3
  import { applyDelta, contribution } from './commit-counts.js';
4
4
  /** Step 6: everything the new head will point at, written before the head. */
5
5
  async function writeBeforeHead(env, plan) {
6
- for (const evidence of plan.evidence)
6
+ for (const evidence of plan.evidence) {
7
+ if (await env.store.readEvidence(plan.scope, plan.id, evidence.ref)) {
8
+ throw new GeneStoreError('GENE_STALE_BASIS', 'The evidence reference is occupied.');
9
+ }
7
10
  await env.store.writeEvidence(plan.scope, evidence);
11
+ }
8
12
  for (const item of plan.versionsBefore) {
9
13
  if (item.mode === 'create' && item.version.n <= plan.knownLatest) {
10
14
  const message = 'A version number may not be reused.';
@@ -165,7 +165,9 @@ export function prepareContent(input) {
165
165
  const evidence = buildEvidence(input);
166
166
  if (!evidence.ok)
167
167
  return evidence;
168
- const refs = [...new Set([...input.content.evidence, ...evidence.value.map((e) => e.ref)])];
168
+ // Wire evidence may be referenced only by a claim or a script. Preserve the author's list.
169
+ const refs = input.actor.kind === 'import' && input.actor.cloudSync ? input.content.evidence
170
+ : [...new Set([...input.content.evidence, ...evidence.value.map((e) => e.ref)])];
169
171
  let content = { ...stripClass(input.content), evidence: refs };
170
172
  if (input.type === 'tool') {
171
173
  const script = scriptTextOf(content, evidence.value, input.storedScriptText);
@@ -21,6 +21,8 @@ export interface GeneActor {
21
21
  kind: GeneActorKind;
22
22
  /** Free-form, short, English; recorded on the version (`author.label`). */
23
23
  label?: string;
24
+ /** Device imports always produce candidates, including metadata-only edits. */
25
+ cloudSync?: true;
24
26
  }
25
27
  export declare function isUserActor(actor: GeneActor): boolean;
26
28
  /**
@@ -17,6 +17,7 @@
17
17
  * A STALE ANSWER CARRIES THE FRESH HEAD'S VERSION in its `detail` (`version latest=4`), so an
18
18
  * editor can offer "keep mine / take theirs / merge" without a second round trip.
19
19
  */
20
+ import { isCloudDeleted } from '../cloud-sync/state.js';
20
21
  import { dedupeKeyOf } from '@aragon-agent/tui/model/gene/proposal';
21
22
  import { mintProposalId } from '@aragon-agent/tui/model/gene/ids';
22
23
  import { validateGeneContent, } from '@aragon-agent/tui/model/gene/validate';
@@ -218,12 +219,38 @@ async function enqueueRecheck(core, found) {
218
219
  }
219
220
  return geneOk({ id: found.read.head.id });
220
221
  }
222
+ /** A permanent cloud tombstone is never revived with its old ID. */
223
+ async function restoreCopy(core, found) {
224
+ const { scope, read: { head } } = found;
225
+ const n = head.candidateVersion ?? head.currentVersion ?? head.latestVersion;
226
+ const version = await core.lib.store.readVersion(scope, head.id, n);
227
+ if (!version)
228
+ return geneFail('GENE_NOT_FOUND', 'The archived version could not be read.');
229
+ const pieces = await core.lib.store.listEvidence(scope, head.id);
230
+ const evidence = pieces.filter(piece => version.content.evidence.includes(piece.ref));
231
+ if (evidence.length !== version.content.evidence.length) {
232
+ return geneFail('GENE_INVALID_CONTENT', 'The archived evidence is incomplete.');
233
+ }
234
+ const restored = await core.lib.versions.commit({
235
+ op: 'create', type: head.type, class: head.class, scope,
236
+ content: version.content, evidence, reason: 'Restored from the account archive.',
237
+ }, MANAGER_ACTOR);
238
+ return restored.ok ? geneOk({ ...outcomeOf(restored.value), also: [head.id] }) : restored;
239
+ }
221
240
  /** `action`: one of the twelve human operations of 7.6 on one gene. */
222
241
  export async function runGeneAction(core, req) {
223
242
  const found = await findGene(core, req.target, req.id);
224
243
  if (!found.ok)
225
244
  return found;
226
245
  const where = { scope: found.value.scope, id: req.id };
246
+ if (req.action === 'restore' && found.value.archived && isCloudDeleted({
247
+ kind: 'gene', itemId: req.id, ...(where.scope.key ? { projectKey: where.scope.key } : {}),
248
+ })) {
249
+ if (req.expectedVersion && req.expectedVersion !== found.value.read.head.latestVersion) {
250
+ return geneFail('GENE_STALE_BASIS', 'The archived version changed.');
251
+ }
252
+ return restoreCopy(core, found.value);
253
+ }
227
254
  if (req.action === 'recheck')
228
255
  return enqueueRecheck(core, found.value);
229
256
  const expect = expectOf(req.expectedVersion);
@@ -233,7 +260,8 @@ export async function runGeneAction(core, req) {
233
260
  const change = await changeFor(req.action, { core, found: found.value, args: req.args ?? {} });
234
261
  if (!change.ok)
235
262
  return change;
236
- const done = await core.lib.versions.commit(change.value, MANAGER_ACTOR, expect);
263
+ const basis = expect ?? { version: found.value.read.head.latestVersion, rev: found.value.read.rev };
264
+ const done = await core.lib.versions.commit(change.value, MANAGER_ACTOR, basis);
237
265
  if (!done.ok)
238
266
  return withFreshness(core, where, done);
239
267
  return geneOk(outcomeOf(done.value));