@anhlp/alp-daemon 0.0.1-beta.3 → 0.0.1-beta.4

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 (51) hide show
  1. package/README.md +4 -0
  2. package/dist/alpd.js +10350 -3346
  3. package/dist/attachments.d.ts +211 -0
  4. package/dist/attachments.js +819 -0
  5. package/dist/build-manifest.json +21 -1
  6. package/dist/conversation.d.ts +119 -0
  7. package/dist/conversation.js +672 -0
  8. package/dist/files.d.ts +13 -0
  9. package/dist/files.js +15 -0
  10. package/dist/git.d.ts +87 -0
  11. package/dist/git.js +1093 -0
  12. package/dist/gitignore.d.ts +5 -0
  13. package/dist/gitignore.js +7 -1
  14. package/dist/history.d.ts +24 -0
  15. package/dist/history.js +149 -0
  16. package/dist/index.d.ts +6 -0
  17. package/dist/index.js +18 -1
  18. package/dist/lifecycle.d.ts +101 -0
  19. package/dist/lifecycle.js +239 -0
  20. package/dist/main.js +9 -3
  21. package/dist/registry.d.ts +89 -0
  22. package/dist/registry.js +343 -0
  23. package/dist/scheduler.d.ts +96 -0
  24. package/dist/scheduler.js +290 -0
  25. package/dist/schedules.d.ts +69 -0
  26. package/dist/schedules.js +244 -0
  27. package/dist/server.d.ts +11 -1
  28. package/dist/server.js +698 -76
  29. package/dist/store.d.ts +69 -1
  30. package/dist/store.js +109 -3
  31. package/dist/terminals.d.ts +157 -0
  32. package/dist/terminals.js +487 -0
  33. package/dist/worktrees.d.ts +41 -0
  34. package/dist/worktrees.js +246 -0
  35. package/package.json +64 -5
  36. package/src/attachments.ts +870 -0
  37. package/src/conversation.ts +837 -0
  38. package/src/files.ts +23 -2
  39. package/src/git.ts +1045 -0
  40. package/src/gitignore.ts +10 -0
  41. package/src/history.ts +118 -0
  42. package/src/index.ts +6 -0
  43. package/src/lifecycle.ts +283 -0
  44. package/src/main.ts +9 -3
  45. package/src/registry.ts +238 -0
  46. package/src/scheduler.ts +422 -0
  47. package/src/schedules.ts +294 -0
  48. package/src/server.ts +810 -86
  49. package/src/store.ts +115 -3
  50. package/src/terminals.ts +591 -0
  51. package/src/worktrees.ts +287 -0
@@ -0,0 +1,238 @@
1
+ import { randomBytes, createHash } from 'node:crypto';
2
+ import { mkdir, readFile, writeFile, rename, realpath, stat, chmod, unlink } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+
5
+ export type ProjectRecord = { id: string; root: string; canonical?: string; customName?: string | null; addedAt: string; removedAt?: string | null };
6
+ export type WorkspaceRecord = { id: string; projectId: string; directory: string; canonical?: string; title?: string | null; pinnedAt?: string | null; labels: string[]; createdAt: string; archivedAt?: string | null; idempotencyKey?: string; worktree?: ManagedWorktree };
7
+ export type ManagedWorktree = { kind: 'user'; sourceWorkspaceId: string; source: string; commonDir: string; gitDir: string; mappingId: string; principalId: string; grantEpoch: string; requestId?: string; ifRevision?: number; branch: string; head: string; removedAt?: string };
8
+ export type Registry = { version: 1; revision: number; projects: ProjectRecord[]; workspaces: WorkspaceRecord[]; sessions: Record<string, string>; labels: { generation: string; seq: number; catalog: { name: string; color: string }[] }; worktreeJournal?: Record<string, { fingerprint: string; intent: any }>; receipts: Record<string, { fingerprint: string; result: unknown }> };
9
+ export class RegistryError extends Error {
10
+ constructor(readonly code: number, message: string, readonly data: { reason: string }) { super(message); }
11
+ }
12
+ function fail(reason: string, message: string, code = 1004): never { throw new RegistryError(code, message, { reason }); }
13
+ const hex = () => randomBytes(8).toString('hex');
14
+ const now = () => new Date().toISOString();
15
+ const object = (v: any) => v && typeof v === 'object' && !Array.isArray(v);
16
+ const nullable = (v: any) => v === undefined || v === null || typeof v === 'string';
17
+ // Legacy bridge wire palette; domain code does not depend on the Paseo SDK.
18
+ const labelColors = new Set(['violet', 'sky', 'emerald', 'orange', 'pink', 'indigo', 'teal', 'red', 'amber', 'blue']);
19
+ const strings = (v: any) => Array.isArray(v) && v.every((s: any) => typeof s === 'string');
20
+ function validate(value: any): asserts value is Registry {
21
+ if (!object(value) || !Array.isArray(value.projects) || !Array.isArray(value.workspaces) || !object(value.sessions) || !object(value.labels)
22
+ || typeof value.labels.generation !== 'string' || !Number.isSafeInteger(value.labels.seq) || value.labels.seq < 0 || !Array.isArray(value.labels.catalog)
23
+ || value.labels.catalog.some((l: any) => !object(l) || typeof l.name !== 'string' || !labelColors.has(l.color))
24
+ || (value.version !== undefined && value.version !== 1) || (value.revision !== undefined && (!Number.isSafeInteger(value.revision) || value.revision < 0))) fail('corrupt_registry', 'Invalid workspace registry', 1005);
25
+ if (value.version === 1 && (!Number.isSafeInteger(value.revision) || !object(value.receipts))) fail('corrupt_registry', 'Missing versioned registry metadata', 1005);
26
+ if (value.worktreeJournal !== undefined && (!object(value.worktreeJournal) || Object.values(value.worktreeJournal).some((j: any) => !object(j) || typeof j.fingerprint !== 'string' || !object(j.intent)))) fail('corrupt_registry', 'Invalid worktree journal', 1005);
27
+ for (const j of Object.values(value.worktreeJournal ?? {}) as any[]) { const i=j.intent; if (!['create','remove'].includes(i.method) || !/^wks_[0-9a-f]{16}$/.test(i.id) || i.branch !== `alp/workspace/${i.id}` || !['directory','source','commonDir'].every(k=>typeof i[k]==='string' && path.isAbsolute(i[k])) || !/^[0-9a-f]{40,64}$/.test(i.head)) fail('corrupt_registry','Invalid native intent',1005); }
28
+ const projects = new Set<string>(); const workspaces = new Set<string>();
29
+ for (const p of value.projects) {
30
+ if (!object(p) || typeof p.id !== 'string' || !p.id || projects.has(p.id) || typeof p.root !== 'string' || !path.isAbsolute(p.root) || typeof p.addedAt !== 'string' || !nullable(p.customName) || !nullable(p.removedAt) || (p.canonical !== undefined && (typeof p.canonical !== 'string' || !path.isAbsolute(p.canonical)))) fail('corrupt_registry', 'Invalid project record', 1005);
31
+ projects.add(p.id);
32
+ }
33
+ for (const w of value.workspaces) {
34
+ if (!object(w) || typeof w.id !== 'string' || !w.id || workspaces.has(w.id) || !projects.has(w.projectId) || typeof w.directory !== 'string' || !path.isAbsolute(w.directory) || typeof w.createdAt !== 'string' || ((value.version === 1 || w.labels !== undefined) && !strings(w.labels)) || !nullable(w.title) || !nullable(w.pinnedAt) || !nullable(w.archivedAt) || (w.canonical !== undefined && (typeof w.canonical !== 'string' || !path.isAbsolute(w.canonical))) || (w.idempotencyKey !== undefined && typeof w.idempotencyKey !== 'string')) fail('corrupt_registry', 'Invalid workspace record', 1005);
35
+ if (w.worktree !== undefined && (!object(w.worktree) || w.worktree.kind !== 'user' || ['sourceWorkspaceId','source','commonDir','gitDir','mappingId','principalId','grantEpoch','branch','head'].some(k => typeof w.worktree[k] !== 'string'))) fail('corrupt_registry', 'Invalid managed worktree', 1005);
36
+ workspaces.add(w.id);
37
+ }
38
+ if (Object.values(value.sessions).some(id => typeof id !== 'string' || !workspaces.has(id))) fail('corrupt_registry', 'Invalid session placement', 1005);
39
+ if (value.receipts !== undefined && (!object(value.receipts) || Object.values(value.receipts).some((r: any) => !object(r) || typeof r.fingerprint !== 'string' || !Object.hasOwn(r, 'result')))) fail('corrupt_registry', 'Invalid operation receipts', 1005);
40
+ }
41
+ const placementOf = (r: Registry, id: string) => Object.hasOwn(r.sessions, id) ? r.sessions[id] : undefined;
42
+ const place = (r: Registry, id: string, workspaceId: string) => Object.defineProperty(r.sessions, id, { value: workspaceId, writable: true, enumerable: true, configurable: true });
43
+ async function identity(directory: string) {
44
+ if (typeof directory !== 'string' || !path.isAbsolute(directory)) fail('directory_not_found', 'An absolute existing directory is required', -32602);
45
+ const canonical = await realpath(directory);
46
+ if (!(await stat(canonical)).isDirectory()) fail('directory_not_found', 'An existing directory is required', -32602);
47
+ return canonical;
48
+ }
49
+ /** Sole mutable owner. Failed writes never publish the draft or consume a requestId. */
50
+ export function createRegistry(home: string, options: { write?: typeof writeFile } = {}) {
51
+ const file = path.join(home, 'state', 'web-workspaces.json');
52
+ let committed: Registry | undefined;
53
+ let tail: Promise<unknown> = Promise.resolve();
54
+ const serial = <T>(fn: () => Promise<T>): Promise<T> => { const result = tail.then(fn); tail = result.catch(() => {}); return result; };
55
+ const write = options.write ?? writeFile;
56
+ async function persist(value: Registry) {
57
+ await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
58
+ await chmod(path.dirname(file), 0o700);
59
+ const temporary = `${file}.${hex()}.tmp`;
60
+ try { await write(temporary, JSON.stringify(value, null, 2) + '\n', { mode: 0o600, flag: 'wx' }); await rename(temporary, file); }
61
+ finally { await unlink(temporary).catch(() => {}); }
62
+ }
63
+ async function load() {
64
+ if (committed) return;
65
+ let text: string;
66
+ try { text = await readFile(file, 'utf8'); }
67
+ catch (error: any) {
68
+ if (error.code !== 'ENOENT') throw error;
69
+ committed = { version: 1, revision: 0, projects: [], workspaces: [], sessions: {}, labels: { generation: hex(), seq: 0, catalog: [] }, receipts: {} }; return;
70
+ }
71
+ let parsed: any;
72
+ try { parsed = JSON.parse(text); } catch { fail('corrupt_registry', 'Workspace registry is unreadable; original retained', 1005); }
73
+ validate(parsed);
74
+ if (parsed.version === undefined) {
75
+ // Keep the exact original for recovery. Never replace it with a synthesized format.
76
+ await writeFile(`${file}.legacy-v0.json`, text, { mode: 0o600, flag: 'wx' }).catch((e: any) => { if (e.code !== 'EEXIST') throw e; });
77
+ await chmod(`${file}.legacy-v0.json`, 0o600);
78
+ const migrated = { ...parsed, version: 1 as const, revision: 0, receipts: {}, workspaces: parsed.workspaces.map((w: WorkspaceRecord) => ({ ...w, labels: w.labels ?? [] })) };
79
+ for (const p of migrated.projects) p.canonical = await realpath(p.root).catch(() => undefined);
80
+ for (const w of migrated.workspaces) w.canonical = await realpath(w.directory).catch(() => undefined);
81
+ await persist(migrated); committed = migrated;
82
+ } else { await chmod(path.dirname(file), 0o700); await chmod(file, 0o600); committed = parsed; }
83
+ }
84
+ const project = (r: Registry, id: string) => r.projects.find(p => p.id === id) ?? fail('not_found', 'No project', 1001);
85
+ const workspace = (r: Registry, id: string) => r.workspaces.find(w => w.id === id) ?? fail('not_found', 'No workspace', 1001);
86
+ const live = (r: Registry, w: WorkspaceRecord) => !w.archivedAt && !project(r, w.projectId).removedAt;
87
+ function register(r: Registry, directory: string, canonical?: string) {
88
+ let p = r.projects.find(p => !p.removedAt && (p.canonical ?? path.resolve(p.root)) === (canonical ?? path.resolve(directory)));
89
+ if (!p) { p = { id: `prj_${hex()}`, root: directory, ...(canonical === undefined ? {} : { canonical }), addedAt: now() }; r.projects.push(p); }
90
+ return p;
91
+ }
92
+ function makeWorkspace(r: Registry, p: ProjectRecord, directory: string, canonical: string | undefined, fields: Partial<WorkspaceRecord> = {}) {
93
+ const w: WorkspaceRecord = { id: `wks_${hex()}`, projectId: p.id, directory, ...(canonical === undefined ? {} : { canonical }), labels: [], createdAt: now(), ...fields }; r.workspaces.push(w); return w;
94
+ }
95
+ async function action(r: Registry, method: string, a: any): Promise<any> {
96
+ switch (method) {
97
+ case 'project.add': { const canonical = await identity(a.directory); return { project: register(r, a.directory, canonical) }; }
98
+ case 'project.register': {
99
+ const canonical = await identity(a.directory); const p = register(r, a.directory, canonical);
100
+ if (!r.workspaces.some(w => w.projectId === p.id && live(r, w) && (w.canonical ?? w.directory) === canonical)) makeWorkspace(r, p, a.directory, canonical);
101
+ return { project: p };
102
+ }
103
+ case 'project.remove': { const p = project(r, a.projectId); p.removedAt = now(); for (const w of r.workspaces.filter(w => w.projectId === p.id)) { w.archivedAt = now(); w.pinnedAt = null; } return { project: p }; }
104
+ case 'project.rename': { const p = project(r, a.projectId); p.customName = a.customName?.trim() || null; return { project: p }; }
105
+ case 'workspace.create': {
106
+ const canonical = await identity(a.directory);
107
+ const previous = a.idempotencyKey ? r.workspaces.find(w => w.idempotencyKey === a.idempotencyKey) : undefined;
108
+ if (previous) { if ((previous.canonical ?? previous.directory) !== canonical) fail('request_conflict', 'Idempotency key names another directory'); return { workspace: previous }; }
109
+ const p = a.projectId ? project(r, a.projectId) : register(r, a.directory, canonical);
110
+ if (p.removedAt) fail('not_found', 'Project was removed', 1001);
111
+ return { workspace: makeWorkspace(r, p, a.directory, canonical, { ...(a.workspaceId ? { id: a.workspaceId } : {}), title: a.title?.trim() || null, ...(a.idempotencyKey ? { idempotencyKey: a.idempotencyKey } : {}) }) };
112
+ }
113
+ case 'workspace.update': {
114
+ const w = workspace(r, a.workspaceId);
115
+ if (a.title !== undefined) w.title = a.title?.trim() || null;
116
+ if (a.pinned !== undefined) w.pinnedAt = a.pinned ? w.pinnedAt ?? now() : null;
117
+ if (a.archived !== undefined) { w.archivedAt = a.archived ? now() : null; if (a.archived) w.pinnedAt = null; }
118
+ return { workspace: w };
119
+ }
120
+ case 'placement.prepare': {
121
+ for (const s of a.sessions) {
122
+ const mapped = placementOf(r, s.id);
123
+ let w = mapped ? workspace(r, mapped) : undefined;
124
+ const historical = s.archived || s.status === 'closed' || s.status === 'error';
125
+ // Preparation projects saved roots, including history and processes whose cwd
126
+ // was deleted. It does not authorize execution: resolve still checks live identity.
127
+ // A saved mapping must never be rebound through a retargeted directory alias.
128
+ if (w) {
129
+ if (!historical && w.archivedAt) w.archivedAt = null;
130
+ continue;
131
+ }
132
+ if (typeof s.projectRoot !== 'string' || !path.isAbsolute(s.projectRoot)) fail('directory_not_found', 'An absolute directory is required', -32602);
133
+ const lexical = path.resolve(s.projectRoot);
134
+ // A lexical fallback is placement metadata, never proof of canonical identity.
135
+ const canonical = await identity(s.projectRoot).catch((error: any) => {
136
+ if (historical || error.code === 'ENOENT' || error.code === 'ENOTDIR') return undefined;
137
+ throw error;
138
+ });
139
+ const here = r.workspaces.filter(w => canonical === undefined ? path.resolve(w.directory) === lexical : (w.canonical ?? w.directory) === canonical).sort((a, b) => a.createdAt.localeCompare(b.createdAt));
140
+ w = here.find(w => live(r, w)) ?? (s.archived ? here.at(-1) : undefined) ?? makeWorkspace(r, register(r, s.projectRoot, canonical), s.projectRoot, canonical, s.archived ? { archivedAt: s.updatedAt ?? now() } : {});
141
+ place(r, s.id, w.id);
142
+ }
143
+ return {};
144
+ }
145
+ case 'placement.assign': { workspace(r, a.workspaceId); if (placementOf(r, a.sessionId) && placementOf(r, a.sessionId) !== a.workspaceId) fail('workspace_mismatch', 'Session already has another workspace'); place(r, a.sessionId, a.workspaceId); return {}; }
146
+ case 'placement.remove': { if (placementOf(r, a.sessionId) === a.workspaceId) delete r.sessions[a.sessionId]; return {}; }
147
+ case 'label.assign': {
148
+ const w = workspace(r, a.workspaceId); const name = a.label.name.trim().replace(/\s+/g, ' '); if (!name) fail('invalid_label', 'A label needs a name', -32602);
149
+ let l = r.labels.catalog.find(l => l.name.toLowerCase() === name.toLowerCase());
150
+ if (!l && a.assigned) { l = { name, color: a.label.color }; r.labels.catalog.push(l); r.labels.seq++; }
151
+ w.labels = w.labels.filter(n => n.toLowerCase() !== name.toLowerCase()); if (a.assigned && l) w.labels.push(l.name); return { label: l ?? a.label, workspaceLabels: w.labels };
152
+ }
153
+ case 'label.update': {
154
+ const l = r.labels.catalog.find(l => l.name.toLowerCase() === a.name.toLowerCase()); if (!l) fail('not_found', 'No label', 1001);
155
+ const previousName = l.name; const name = a.newName === undefined ? l.name : a.newName.trim().replace(/\s+/g, ' ');
156
+ if (!name || r.labels.catalog.some(other => other !== l && other.name.toLowerCase() === name.toLowerCase())) fail('label_name_taken', 'Invalid or duplicate label', -32602);
157
+ l.name = name; if (a.color) l.color = a.color;
158
+ let affectedWorkspaceCount = 0;
159
+ for (const w of r.workspaces) { const i = w.labels.findIndex(n => n.toLowerCase() === previousName.toLowerCase()); if (i >= 0) { w.labels[i] = name; affectedWorkspaceCount++; } }
160
+ r.labels.seq++; return { label: l, previousName, affectedWorkspaceCount };
161
+ }
162
+ case 'label.delete': {
163
+ const l = r.labels.catalog.find(l => l.name.toLowerCase() === a.name.toLowerCase()); if (!l) fail('not_found', 'No label', 1001);
164
+ r.labels.catalog = r.labels.catalog.filter(other => other !== l); let affectedWorkspaceCount = 0;
165
+ for (const w of r.workspaces) { const before = w.labels.length; w.labels = w.labels.filter(n => n.toLowerCase() !== l.name.toLowerCase()); if (before !== w.labels.length) affectedWorkspaceCount++; }
166
+ r.labels.seq++; return { affectedWorkspaceCount };
167
+ }
168
+ default: return fail('unknown_operation', 'Unknown registry operation', -32602);
169
+ }
170
+ }
171
+ const fingerprintOf = (args: any, revision: number | undefined) => createHash('sha256').update(JSON.stringify({ args, ifRevision: revision }, (_key, value) => object(value) ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b))) : value)).digest('hex');
172
+ return {
173
+ /** Native intent and receipt share the sole registry writer and atomic persistence boundary. */
174
+ nativeMutation: (method: string, args: any, context: { actor: string; requestId: string; ifRevision: number }, prepare: (r: Registry) => Promise<any>, apply: (intent: any, draft: Registry) => Promise<any>) => serial(async () => {
175
+ await load();
176
+ if (!context.requestId || typeof context.requestId !== 'string' || context.requestId.length > 200 || !Number.isSafeInteger(context.ifRevision) || context.ifRevision < 0) fail('invalid_request_id', 'requestId and ifRevision are required', -32602);
177
+ const key = createHash('sha256').update(JSON.stringify([context.actor, method, context.requestId])).digest('hex');
178
+ const fingerprint = fingerprintOf(args, context.ifRevision);
179
+ const receipt = committed!.receipts[key];
180
+ if (receipt) { if (receipt.fingerprint !== fingerprint) fail('request_conflict', 'requestId reused'); return structuredClone(receipt.result); }
181
+ const pending = committed!.worktreeJournal?.[key];
182
+ if (pending && pending.fingerprint !== fingerprint) fail('request_conflict', 'requestId reused');
183
+ if (!pending && Object.keys(committed!.worktreeJournal ?? {}).length) fail('reconciliation_required', 'Retry the pending worktree request before another mutation');
184
+ if (!pending && context.ifRevision !== committed!.revision) fail('stale_revision', 'Registry changed; refresh');
185
+ if (!pending) {
186
+ const intent = await prepare(structuredClone(committed!));
187
+ const draft = structuredClone(committed!); (draft.worktreeJournal ??= {})[key] = { fingerprint, intent };
188
+ await persist(draft); committed = draft;
189
+ }
190
+ const draft = structuredClone(committed!);
191
+ const result = await apply(structuredClone(draft.worktreeJournal![key].intent), draft);
192
+ draft.revision++;
193
+ const response = { ...result, revision: draft.revision };
194
+ draft.receipts[key] = { fingerprint, result: structuredClone(response) }; delete draft.worktreeJournal![key];
195
+ validate(draft); await persist(draft); committed = draft; return structuredClone(response);
196
+ }),
197
+ snapshot: () => serial(async () => { await load(); return structuredClone(committed!); }),
198
+ mutate: (method: string, args: any, context: { actor?: string; allowedRoots?: string[]; ifRevision?: number; requestId: string }) => serial(async () => {
199
+ await load();
200
+ if (Object.keys(committed!.worktreeJournal ?? {}).length) fail('reconciliation_required', 'Retry the pending worktree request before changing metadata');
201
+ if (context.allowedRoots) {
202
+ const checked = async (directory: string, canonical?: string) => {
203
+ const actual = await identity(directory);
204
+ if (!context.allowedRoots!.includes(actual) || (canonical !== undefined && canonical !== actual)) fail('outside_workspace', 'Resource is outside the credential grant', 1003);
205
+ };
206
+ if (method === 'project.register') await checked(args.directory);
207
+ else if (method === 'workspace.update') { const w = workspace(committed!, args.workspaceId); await checked(w.directory, w.canonical); }
208
+ else if (method === 'project.remove') {
209
+ const p = project(committed!, args.projectId); await checked(p.root, p.canonical);
210
+ for (const w of committed!.workspaces.filter(w => w.projectId === p.id)) await checked(w.directory, w.canonical);
211
+ }
212
+ }
213
+ if (!context.requestId || typeof context.requestId !== 'string' || context.requestId.length > 200) fail('invalid_request_id', 'requestId is required', -32602);
214
+ const key = createHash('sha256').update(JSON.stringify([context.actor ?? 'owner', method, context.requestId])).digest('hex');
215
+ const fingerprint = createHash('sha256').update(JSON.stringify({ args, ifRevision: context.ifRevision }, (_key, value) => object(value) ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b))) : value)).digest('hex');
216
+ const receipt = committed!.receipts[key];
217
+ if (receipt) { if (receipt.fingerprint !== fingerprint) fail('request_conflict', 'requestId reused with different payload'); return structuredClone(receipt.result); }
218
+ if (context.ifRevision !== undefined && context.ifRevision !== committed!.revision) fail('stale_revision', 'Registry changed; refresh and retry');
219
+ const draft = structuredClone(committed!); const result = await action(draft, method, args);
220
+ if (method === 'placement.prepare' && JSON.stringify(draft) === JSON.stringify(committed)) return { ...result, revision: draft.revision };
221
+ draft.revision++;
222
+ const response = { ...result, revision: draft.revision };
223
+ draft.receipts[key] = { fingerprint, result: structuredClone(response) };
224
+ validate(draft); await persist(draft); committed = draft;
225
+ return structuredClone(response);
226
+ }),
227
+ async resolve(workspaceId: string, cwd?: string, includeArchived = false) {
228
+ const r = await this.snapshot(); const w = workspace(r, workspaceId);
229
+ if (!includeArchived && !live(r, w)) fail('not_found', 'Workspace is archived', 1001);
230
+ if (Object.values(r.worktreeJournal ?? {}).some(j => j.intent.id === workspaceId)) fail('reconciliation_required', 'Workspace mutation requires reconciliation');
231
+ const canonical = await identity(w.directory);
232
+ if (w.canonical && canonical !== w.canonical) fail('identity_changed', 'Workspace directory identity changed', 1003);
233
+ if (cwd !== undefined && await identity(cwd) !== canonical) fail('cwd_mismatch', 'cwd and workspaceId must agree', -32602);
234
+ return canonical;
235
+ },
236
+ };
237
+ }
238
+ export type RegistryService = ReturnType<typeof createRegistry>;