@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
@@ -16,6 +16,7 @@
16
16
  * calls its `limits()` at COMMIT time, so a settings change applies to the next write without
17
17
  * rebuilding the service.
18
18
  */
19
+ import { captureLibraryIdentity } from '../cloud-sync/identity.js';
19
20
  import process from 'node:process';
20
21
  import { GeneEvalRecorder } from './eval-recorder.js';
21
22
  import { geneRoot } from './paths.js';
@@ -26,7 +27,7 @@ import { GeneStore } from './store.js';
26
27
  import { GeneVersionService } from './version-service.js';
27
28
  const libraries = new Map();
28
29
  function keyOf(ctx, teamWritable) {
29
- return [geneRoot(ctx), ctx.teamPath, teamWritable ? 'w' : 'r'].join('\u0000');
30
+ return [geneRoot(ctx), ctx.libraryIdentity?.generation ?? '', ctx.teamPath, teamWritable ? 'w' : 'r'].join('\u0000');
30
31
  }
31
32
  function buildLibrary(request, ctx) {
32
33
  const now = request.now ?? Date.now;
@@ -34,7 +35,7 @@ function buildLibrary(request, ctx) {
34
35
  const tuning = { limits: () => ({}), knownSecrets: () => [] };
35
36
  const store = new GeneStore({ ctx, ...(request.teamWritable ? { teamWritable: true } : {}) });
36
37
  const locks = new ScopeLockManager(ctx);
37
- const rootOnly = { ...(ctx.root === undefined ? {} : { root: ctx.root }) };
38
+ const rootOnly = { ...ctx };
38
39
  const queue = new GeneQueue({ ctx: rootOnly, now, pid });
39
40
  // No session id: a record written by the manager is the PERSON managing, not a session's work.
40
41
  const runLog = new GeneRunLog({
@@ -60,7 +61,7 @@ function buildLibrary(request, ctx) {
60
61
  export function getGeneLibrary(request) {
61
62
  const ctx = {
62
63
  teamPath: request.teamPath,
63
- ...(request.root === undefined ? {} : { root: request.root }),
64
+ ...(request.root === undefined ? { libraryIdentity: captureLibraryIdentity() } : { root: request.root }),
64
65
  };
65
66
  const key = keyOf(ctx, request.teamWritable === true);
66
67
  const existing = libraries.get(key);
@@ -74,7 +75,7 @@ export function getGeneLibrary(request) {
74
75
  export function forgetGeneLibrary(request) {
75
76
  const ctx = {
76
77
  teamPath: request.teamPath,
77
- ...(request.root === undefined ? {} : { root: request.root }),
78
+ ...(request.root === undefined ? { libraryIdentity: captureLibraryIdentity() } : { root: request.root }),
78
79
  };
79
80
  libraries.delete(keyOf(ctx, request.teamWritable === true));
80
81
  }
@@ -1,15 +1,16 @@
1
- import { getGeneDir } from '../config/app-paths.js';
1
+ import { type LibraryIdentity } from '../cloud-sync/identity.js';
2
2
  import type { GeneScope } from '@aragon-agent/tui/model/gene/types';
3
3
  import { isValidProposalId } from '@aragon-agent/tui/model/gene/ids';
4
- export { getGeneDir };
4
+ export declare function getGeneDir(): string;
5
5
  /** `team` scopes live in an external, user-chosen directory; everything else under `genes/`. */
6
6
  export interface GenePathContext {
7
7
  /** Absolute external team directory, or '' when unset. */
8
8
  teamPath: string;
9
9
  /** Library root override for tests; defaults to `getGeneDir()`. */
10
10
  root?: string;
11
+ libraryIdentity?: LibraryIdentity;
11
12
  }
12
- export declare function geneRoot(ctx?: Pick<GenePathContext, 'root'>): string;
13
+ export declare function geneRoot(ctx?: Pick<GenePathContext, 'root' | 'libraryIdentity'>): string;
13
14
  /** `candidate` is inside `root` (or is `root`). Compares path SEGMENTS, never string prefixes. */
14
15
  export declare function isInsideRoot(root: string, candidate: string): boolean;
15
16
  /** The scope's own directory. `team` resolves to the configured external directory. */
@@ -15,10 +15,17 @@
15
15
  * same-volume `rename`, never a cross-device copy that Windows reports as EXDEV / EPERM.
16
16
  */
17
17
  import { join, relative, sep, isAbsolute } from 'node:path';
18
- import { getGeneDir } from '../config/app-paths.js';
18
+ import { assertLibraryIdentity, captureLibraryIdentity } from '../cloud-sync/identity.js';
19
+ import { getGeneDir as resolveDirectory } from '../config/app-paths.js';
19
20
  import { geneShard, isValidEvidenceRef, isValidGeneId, isValidProposalId, isValidScope, scopeId, } from '@aragon-agent/tui/model/gene/ids';
20
- export { getGeneDir };
21
+ export function getGeneDir() {
22
+ return resolveDirectory(captureLibraryIdentity().dataRoot);
23
+ }
21
24
  export function geneRoot(ctx) {
25
+ if (ctx?.libraryIdentity) {
26
+ assertLibraryIdentity(ctx.libraryIdentity);
27
+ return join(ctx.libraryIdentity.dataRoot, 'genes');
28
+ }
22
29
  return ctx?.root ?? getGeneDir();
23
30
  }
24
31
  /** `candidate` is inside `root` (or is `root`). Compares path SEGMENTS, never string prefixes. */
@@ -22,6 +22,8 @@ export interface WrittenHead {
22
22
  size: number;
23
23
  }
24
24
  export type VersionWriteMode = 'create' | 'mutate';
25
+ /** Stable head representation used for publication and recovery checks. */
26
+ export declare function orderHead(head: GeneHead): Record<string, unknown>;
25
27
  export declare class GeneStore implements GeneStoreReader {
26
28
  readonly ctx: P.GenePathContext;
27
29
  private readonly hooks;
@@ -75,7 +75,8 @@ function orderKeys(value, order) {
75
75
  }
76
76
  return out;
77
77
  }
78
- function orderHead(head) {
78
+ /** Stable head representation used for publication and recovery checks. */
79
+ export function orderHead(head) {
79
80
  return orderKeys(head, HEAD_ORDER);
80
81
  }
81
82
  function orderVersion(version) {
@@ -64,6 +64,8 @@ export interface ImportReport {
64
64
  /** Ids of the candidates created. */
65
65
  ids: string[];
66
66
  }
67
+ /** Keep only the transferable fields of a version source. */
68
+ export declare function portableContent(content: GeneContent): GeneContent;
67
69
  /** The pack of the published genes in `scopes`. A scope that cannot be read contributes nothing. */
68
70
  export declare function buildPack(core: ManagerCore, scopes: readonly GeneScope[]): Promise<GenePack>;
69
71
  /** The bytes of a pack file: JSON, gzipped when `gzip`. */
@@ -66,7 +66,8 @@ function packVersion() {
66
66
  // ---------------------------------------------------------------------------
67
67
  // export
68
68
  // ---------------------------------------------------------------------------
69
- function portableContent(content) {
69
+ /** Keep only the transferable fields of a version source. */
70
+ export function portableContent(content) {
70
71
  return {
71
72
  ...content,
72
73
  source: { origin: content.source.origin, capturedAt: content.source.capturedAt },
@@ -56,6 +56,7 @@ export interface GeneVersionServiceOptions {
56
56
  onInvalidate?: InvalidateHook;
57
57
  }
58
58
  export declare class GeneVersionService {
59
+ private readonly identity;
59
60
  readonly store: GeneStore;
60
61
  private readonly locks;
61
62
  private readonly rows;
@@ -79,6 +80,7 @@ export declare class GeneVersionService {
79
80
  private compound;
80
81
  /** Run an action and turn anything it throws into a failure result. */
81
82
  private guarded;
83
+ private withActiveLibrary;
82
84
  commit(change: GeneChange, actor: GeneActor, expect?: GeneExpect): Promise<GeneResult<CommitOutcome>>;
83
85
  private ensureLibrary;
84
86
  private expand;
@@ -90,6 +92,8 @@ export declare class GeneVersionService {
90
92
  private apply;
91
93
  /** Steps 3-8, inside the lock. */
92
94
  private locked;
95
+ private deletionEvidence;
96
+ private outboundDeletion;
93
97
  private plan;
94
98
  private planSimple;
95
99
  private outcomeOf;
@@ -1,3 +1,11 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { headFile, archiveHeadFile, trashEntryDir } from './paths.js';
5
+ import { serializeJson } from './fs.js';
6
+ import { orderHead } from './store.js';
7
+ import { captureLibraryIdentity, withLibraryWrite } from '../cloud-sync/identity.js';
8
+ import { beginLibraryDeletion, wakeLibrarySync } from '../cloud-sync/state.js';
1
9
  import { DEFAULT_GENE_CONFIG } from '@aragon-agent/tui/model/config/schema';
2
10
  import { geneFail, geneOk, toGeneFailure } from './gene-errors.js';
3
11
  import { isValidGeneId } from '@aragon-agent/tui/model/gene/ids';
@@ -16,6 +24,7 @@ import { TombstoneStore } from './tombstones.js';
16
24
  /** Who writes when the system itself acts: capacity eviction, dependency health marks. */
17
25
  const MAINTENANCE_ACTOR = { kind: 'curator', label: 'maintenance' };
18
26
  export class GeneVersionService {
27
+ identity;
19
28
  store;
20
29
  locks;
21
30
  rows;
@@ -32,6 +41,8 @@ export class GeneVersionService {
32
41
  schemaReady = false;
33
42
  constructor(options) {
34
43
  this.store = options.store;
44
+ const ctx = this.store.ctx;
45
+ this.identity = ctx.libraryIdentity ?? (ctx.root === undefined ? captureLibraryIdentity() : undefined);
35
46
  this.now = options.now ?? Date.now;
36
47
  this.random = options.random ?? defaultRandom;
37
48
  this.knownSecrets = options.knownSecrets ?? (() => []);
@@ -110,8 +121,12 @@ export class GeneVersionService {
110
121
  return toGeneFailure(error);
111
122
  }
112
123
  }
124
+ withActiveLibrary(work) {
125
+ // Explicit roots (backups, imported libraries, tests) have no account and emit no cloud intent.
126
+ return this.identity ? withLibraryWrite(this.identity, work) : work();
127
+ }
113
128
  async commit(change, actor, expect) {
114
- return this.guarded(async () => {
129
+ return this.guarded(() => this.withActiveLibrary(async () => {
115
130
  await this.ensureLibrary();
116
131
  if (change.op === 'merge')
117
132
  return runMerge(this.compound(), change, actor, expect);
@@ -123,7 +138,7 @@ export class GeneVersionService {
123
138
  if (expanded.value.kind === 'done')
124
139
  return geneOk(expanded.value.outcome);
125
140
  return this.apply(expanded.value.change, actor, expect);
126
- });
141
+ }));
127
142
  }
128
143
  async ensureLibrary() {
129
144
  if (this.schemaReady)
@@ -134,7 +149,9 @@ export class GeneVersionService {
134
149
  // ---- rewriting operations that are edits in disguise -------------------------
135
150
  async expand(change, actor) {
136
151
  if (change.op === 'edit' || change.op === 'revise') {
137
- return geneOk({ kind: 'apply', change: { ...change, op: 'edit' } });
152
+ return geneOk({ kind: 'apply', change: { ...change, op: 'edit',
153
+ ...(actor.kind === 'import' && actor.cloudSync ? { forceVersion: true } : {}),
154
+ } });
138
155
  }
139
156
  if (change.op === 'confirmPreference') {
140
157
  return this.expandConfirm(change.scope, change.id, actor);
@@ -252,9 +269,56 @@ export class GeneVersionService {
252
269
  const planned = await this.plan(change, { ...request, counts, now });
253
270
  if (!planned.ok)
254
271
  return planned;
255
- const executed = await executePlan(this.execEnv(now), planned.value, counts);
272
+ const plan = planned.value;
273
+ const reason = this.identity && await this.outboundDeletion(plan, request.actor);
274
+ const confirm = reason && beginLibraryDeletion({
275
+ kind: 'gene', itemId: plan.id, reason,
276
+ ...(await this.deletionEvidence(plan, now)),
277
+ ...(plan.scope.key ? { projectKey: plan.scope.key } : {}),
278
+ });
279
+ const executed = await executePlan(this.execEnv(now), plan, counts);
280
+ if (confirm)
281
+ confirm();
282
+ if (this.identity && !plan.noop && (plan.scope.kind === 'user' || plan.scope.kind === 'project')) {
283
+ wakeLibrarySync({ kind: 'gene', itemId: plan.id, ...(plan.scope.key ? { projectKey: plan.scope.key } : {}) });
284
+ }
256
285
  return geneOk({ plan: planned.value, executed });
257
286
  }
287
+ async deletionEvidence(plan, now) {
288
+ const { scope, id } = plan;
289
+ const ctx = this.store.ctx;
290
+ const live = headFile(scope, id, ctx);
291
+ const archive = archiveHeadFile(scope, id, ctx);
292
+ if (plan.move === 'trash') {
293
+ const sourcePath = plan.trashFrom === 'archive' ? archive : live;
294
+ const sha256 = createHash('sha256').update(await readFile(sourcePath)).digest('hex');
295
+ return { sourcePath, verify: { path: join(trashEntryDir(scope, id, now, ctx), 'head.json'), sha256 } };
296
+ }
297
+ if (!plan.head)
298
+ return {};
299
+ const sha256 = createHash('sha256').update(serializeJson(orderHead(plan.head))).digest('hex');
300
+ return plan.move === 'archive' ? { sourcePath: live, verify: { path: archive, sha256 } }
301
+ : { verify: { path: live, sha256 } };
302
+ }
303
+ async outboundDeletion(plan, actor) {
304
+ if (plan.noop || actor.kind !== 'user')
305
+ return null;
306
+ if (plan.scope.kind !== 'user' && plan.scope.kind !== 'project')
307
+ return null;
308
+ if (plan.op === 'rejectCandidate' && plan.before?.head.currentVersion === null) {
309
+ const candidate = plan.before.head.candidateVersion;
310
+ const version = candidate && await this.store.readVersion(plan.scope, plan.id, candidate);
311
+ if (version && version.author.label !== 'account-sync')
312
+ return 'delete';
313
+ }
314
+ switch (plan.op) {
315
+ case 'delete':
316
+ case 'archive':
317
+ case 'revoke':
318
+ case 'forget': return plan.op;
319
+ default: return null;
320
+ }
321
+ }
258
322
  async plan(change, ctx) {
259
323
  const base = {
260
324
  env: this.planEnv(ctx.now),
@@ -426,7 +490,7 @@ export class GeneVersionService {
426
490
  }
427
491
  /** Recount a scope from its heads and rewrite `counts.json` under the scope lock. */
428
492
  async rebuildScopeCounts(scope) {
429
- return this.guarded(async () => {
493
+ return this.guarded(() => this.withActiveLibrary(async () => {
430
494
  const allowed = checkScopeFor(this.prepareEnv(), scope, MAINTENANCE_ACTOR);
431
495
  if (!allowed.ok)
432
496
  return allowed;
@@ -437,17 +501,17 @@ export class GeneVersionService {
437
501
  });
438
502
  this.counter.invalidate();
439
503
  return geneOk(counts);
440
- });
504
+ }));
441
505
  }
442
506
  /** Bring the derived parts of a scope back in line with its heads (index, counts, moves). */
443
507
  async reconcileScope(scope) {
444
- return this.guarded(async () => {
508
+ return this.guarded(() => this.withActiveLibrary(async () => {
445
509
  const allowed = checkScopeFor(this.prepareEnv(), scope, MAINTENANCE_ACTOR);
446
510
  if (!allowed.ok)
447
511
  return allowed;
448
512
  const summary = await this.locks.withLock(scope, () => repairScope(this.store, this.rows, scope, this.now()));
449
513
  this.counter.invalidate();
450
514
  return geneOk(summary);
451
- });
515
+ }));
452
516
  }
453
517
  }
@@ -67,6 +67,15 @@ export interface GeneWiringDeps extends ModelPorts {
67
67
  skills?(): SkillSourcePort | null;
68
68
  /** Library root override (tests). */
69
69
  root?: string;
70
+ /**
71
+ * How long a turn waits for its `<gene_context>` zone. Default `PLAN_WAIT_MS`.
72
+ *
73
+ * THE SAME SHAPE AS `syncWaitMs` IN `GeneServiceDeps`, for the same reason: the bound is a
74
+ * product decision (a cold index must never cost the user's turn more than a frame), so it
75
+ * stays small in production. Whoever needs the plan to actually LAND - a test asserting the
76
+ * block it produced - widens it here instead of raising the shipped bound for everybody.
77
+ */
78
+ planWaitMs?: number;
70
79
  }
71
80
  export declare class GeneWiring {
72
81
  private readonly deps;
@@ -524,7 +524,7 @@ export class GeneWiring {
524
524
  taskText: text,
525
525
  reason,
526
526
  });
527
- await settleWithin(job, PLAN_WAIT_MS);
527
+ await settleWithin(job, this.deps.planWaitMs ?? PLAN_WAIT_MS);
528
528
  }
529
529
  catch {
530
530
  // The block stays as it was; the prompt falls back to the previous zone or none.
@@ -0,0 +1,21 @@
1
+ import { type LoginCode } from '../account/login-flow.js';
2
+ export type { CloudSyncStatus } from '../cloud-sync/coordinator.js';
3
+ /** Start one host participant. Only the elected writer performs background synchronization. */
4
+ export declare function startCloudSync(options?: {
5
+ cwd?: string;
6
+ }): {
7
+ status: () => import("../cloud-sync/coordinator.js").CloudSyncStatus;
8
+ wake: () => void;
9
+ dispose: () => Promise<void>;
10
+ subscribe: (fn: (v: import("../cloud-sync/coordinator.js").CloudSyncStatus) => void) => () => void;
11
+ bind: (space: string, cwd?: string) => Promise<void>;
12
+ unbind: (cwd?: string) => Promise<void>;
13
+ resolve: (key: string, choice: "remote" | "copy" | "local") => Promise<void>;
14
+ bindingFor(cwd: string): string | null;
15
+ login(onCode: (code: LoginCode) => void, signal?: AbortSignal): Promise<void>;
16
+ logout(): void;
17
+ };
18
+ export type CloudSyncHost = ReturnType<typeof startCloudSync>;
19
+ export declare function libraryGeneration(): string;
20
+ /** Scope one desktop operation to the account generation that opened the editor. */
21
+ export declare function withCloudLibraryAccess<T>(generation: string, run: () => Promise<T>): Promise<T>;
@@ -0,0 +1,49 @@
1
+ import { startLogin } from '../account/login-flow.js';
2
+ import { captureLibraryIdentity, withLibraryWrite } from '../cloud-sync/identity.js';
3
+ import { clearAccount } from '../account/store.js';
4
+ import { LibraryCoordinator } from '../cloud-sync/coordinator.js';
5
+ import { memoryAdapter } from '../cloud-sync/memory-adapter.js';
6
+ import { geneAdapter } from '../cloud-sync/gene-adapter.js';
7
+ import { resolveProjectKey } from '../memory/paths.js';
8
+ import { AccountState, wakeLibrarySync } from '../cloud-sync/state.js';
9
+ /** Start one host participant. Only the elected writer performs background synchronization. */
10
+ export function startCloudSync(options = {}) {
11
+ const sync = new LibraryCoordinator(options.cwd ?? process.cwd(), { memory: memoryAdapter, gene: geneAdapter });
12
+ return {
13
+ status: sync.status.bind(sync),
14
+ wake: sync.wake.bind(sync),
15
+ dispose: sync.dispose.bind(sync),
16
+ subscribe: sync.subscribe.bind(sync),
17
+ bind: sync.bind.bind(sync),
18
+ unbind: sync.unbind.bind(sync),
19
+ resolve: sync.resolve.bind(sync),
20
+ bindingFor(cwd) {
21
+ const id = captureLibraryIdentity();
22
+ if (!id.accountRoot)
23
+ return null;
24
+ const key = resolveProjectKey(cwd).key;
25
+ return Object.entries(new AccountState(id).bindings()).find(([, binding]) => binding.key === key)?.[0] ?? null;
26
+ },
27
+ async login(onCode, signal) {
28
+ const result = await startLogin({ onCode, signal });
29
+ if (!result.ok)
30
+ throw Error(result.message);
31
+ wakeLibrarySync();
32
+ },
33
+ logout() {
34
+ if (!clearAccount())
35
+ throw Error('Could not remove the account credential.');
36
+ wakeLibrarySync();
37
+ },
38
+ };
39
+ }
40
+ export function libraryGeneration() {
41
+ return captureLibraryIdentity().generation;
42
+ }
43
+ /** Scope one desktop operation to the account generation that opened the editor. */
44
+ export function withCloudLibraryAccess(generation, run) {
45
+ const identity = captureLibraryIdentity();
46
+ if (identity.generation !== generation)
47
+ return Promise.reject(Error('Account changed. Reopen the editor.'));
48
+ return withLibraryWrite(identity, run);
49
+ }
@@ -33,6 +33,8 @@ interface ParseContext {
33
33
  * caller counts that as skipped); every other oddity becomes a repaired note.
34
34
  */
35
35
  export declare function parseNoteBytes(bytes: Uint8Array, ctx: ParseContext): MemoryNote | null;
36
+ /** Headerless notes are marked repaired for the editor even when all their text was read. */
37
+ export declare function isCompleteMemoryProjection(note: MemoryNote): boolean;
36
38
  /** The fields a file carries (everything but the derived `rev` / `bytes` / counts). */
37
39
  export interface SerializableNote {
38
40
  title: string;
@@ -207,14 +207,20 @@ function finishNote(partial, rev, bytes, repairedBefore) {
207
207
  bodyChars: codePointCount(body),
208
208
  };
209
209
  }
210
+ const completeHandwrittenNotes = new WeakSet();
211
+ /** Headerless notes are marked repaired for the editor even when all their text was read. */
212
+ export function isCompleteMemoryProjection(note) {
213
+ return !note.repaired || completeHandwrittenNotes.has(note);
214
+ }
210
215
  function parseHeaderless(text, ctx, rev, bytes) {
211
216
  const heading = firstHeading(text);
212
- return finishNote({
217
+ const body = text.replace(/\n+$/, '');
218
+ const note = finishNote({
213
219
  id: ctx.id,
214
220
  scope: ctx.scope,
215
221
  title: heading ?? ctx.id,
216
222
  rawSummary: '',
217
- body: text.replace(/\n+$/, ''),
223
+ body,
218
224
  tags: [],
219
225
  load: 'auto',
220
226
  enabled: true,
@@ -224,6 +230,9 @@ function parseHeaderless(text, ctx, rev, bytes) {
224
230
  schema: MEMORY_FILE_SCHEMA,
225
231
  repaired: true,
226
232
  }, rev, bytes, true);
233
+ if (note.body === body && note.title === (heading ?? ctx.id))
234
+ completeHandwrittenNotes.add(note);
235
+ return note;
227
236
  }
228
237
  function parseWithFrontmatter(front, ctx, rev, bytes) {
229
238
  let repaired = front.repaired;
@@ -10,15 +10,17 @@
10
10
  * the directory. `noteFile()` checks the id FIRST, builds the path SECOND, and then
11
11
  * proves the result is still inside the scope directory.
12
12
  */
13
- import { getMemoryDir } from '../config/app-paths.js';
13
+ import { type LibraryIdentity } from '../cloud-sync/identity.js';
14
14
  import type { MemoryNoteScope } from '@aragon-agent/tui/model/memory/types';
15
- export { getMemoryDir };
15
+ export declare function getMemoryDir(): string;
16
16
  /** Which directory a store call is about. `projectKey` is required for `project`. */
17
- export type MemoryTarget = {
17
+ export type MemoryTarget = ({
18
18
  scope: 'global';
19
19
  } | {
20
20
  scope: 'project';
21
21
  projectKey: string;
22
+ }) & {
23
+ libraryIdentity?: LibraryIdentity;
22
24
  };
23
25
  /** Whether `id` may name a note file. Pure; no filesystem access. */
24
26
  export declare function isValidNoteId(id: unknown): id is string;
@@ -14,9 +14,18 @@ import { createHash, randomBytes } from 'node:crypto';
14
14
  import { existsSync, realpathSync } from 'node:fs';
15
15
  import { basename, dirname, join, parse, relative, resolve, sep } from 'node:path';
16
16
  import process from 'node:process';
17
- import { getMemoryDir } from '../config/app-paths.js';
17
+ import { assertLibraryIdentity, captureLibraryIdentity } from '../cloud-sync/identity.js';
18
+ import { getMemoryDir as resolveDirectory } from '../config/app-paths.js';
18
19
  import { MEMORY_LIMITS } from '@aragon-agent/tui/model/memory/limits';
19
- export { getMemoryDir };
20
+ export function getMemoryDir() {
21
+ return resolveDirectory(captureLibraryIdentity().dataRoot);
22
+ }
23
+ function targetRoot(target) {
24
+ if (!target.libraryIdentity)
25
+ return getMemoryDir();
26
+ assertLibraryIdentity(target.libraryIdentity);
27
+ return join(target.libraryIdentity.dataRoot, 'memory');
28
+ }
20
29
  const ID_PATTERN = /^[a-z0-9][a-z0-9_-]*$/;
21
30
  /**
22
31
  * Names Win32 resolves to a DEVICE no matter the extension or directory. `con.md` is the
@@ -115,7 +124,7 @@ export function scopeSegment(target) {
115
124
  export function scopeDir(target) {
116
125
  if (target.scope === 'project' && !isValidProjectKey(target.projectKey))
117
126
  return null;
118
- const root = getMemoryDir();
127
+ const root = targetRoot(target);
119
128
  const dir = join(root, scopeSegment(target));
120
129
  return isInside(root, dir) ? dir : null;
121
130
  }
@@ -123,7 +132,7 @@ export function scopeDir(target) {
123
132
  export function trashDir(target) {
124
133
  if (target.scope === 'project' && !isValidProjectKey(target.projectKey))
125
134
  return null;
126
- const root = join(getMemoryDir(), '.trash');
135
+ const root = join(targetRoot(target), '.trash');
127
136
  const dir = join(root, scopeSegment(target));
128
137
  return isInside(root, dir) ? dir : null;
129
138
  }
@@ -133,7 +142,7 @@ export function versionsDir(target, id) {
133
142
  return null;
134
143
  if (target.scope === 'project' && !isValidProjectKey(target.projectKey))
135
144
  return null;
136
- const root = join(getMemoryDir(), '.trash', 'versions');
145
+ const root = join(targetRoot(target), '.trash', 'versions');
137
146
  const dir = join(root, scopeSegment(target), id);
138
147
  return isInside(root, dir) ? dir : null;
139
148
  }
@@ -147,7 +156,7 @@ export function versionsDir(target, id) {
147
156
  export function journalDir(target) {
148
157
  if (target.scope === 'project' && !isValidProjectKey(target.projectKey))
149
158
  return null;
150
- const root = join(getMemoryDir(), '.journal');
159
+ const root = join(targetRoot(target), '.journal');
151
160
  const dir = join(root, scopeSegment(target));
152
161
  return isInside(root, dir) ? dir : null;
153
162
  }
@@ -44,6 +44,7 @@ export interface MemoryServiceDeps {
44
44
  }
45
45
  export declare class MemoryService {
46
46
  private readonly deps;
47
+ private readonly libraryIdentity;
47
48
  private session;
48
49
  private notes;
49
50
  private project;
@@ -222,6 +223,7 @@ export declare class MemoryService {
222
223
  subscribe(listener: () => void): () => void;
223
224
  /** Tell subscribers if the view differs from the last one they were told. */
224
225
  emitIfChanged(): void;
226
+ private isCurrentLibrary;
225
227
  private now;
226
228
  }
227
229
  /** What a surface sees when the controller has no memory service, or memory is off. */