@anhlp/alp-daemon 0.0.0-stage → 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 (66) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +7 -0
  3. package/README.md +14 -2
  4. package/dist/THIRD-PARTY-NOTICES.txt +431 -0
  5. package/dist/alp-templates.d.ts +5 -0
  6. package/dist/alpd.js +49562 -0
  7. package/dist/attachments.d.ts +211 -0
  8. package/dist/attachments.js +819 -0
  9. package/dist/build-manifest.json +131 -0
  10. package/dist/conversation.d.ts +119 -0
  11. package/dist/conversation.js +672 -0
  12. package/dist/files.d.ts +123 -0
  13. package/dist/files.js +365 -0
  14. package/dist/git.d.ts +87 -0
  15. package/dist/git.js +1093 -0
  16. package/dist/gitignore.d.ts +62 -0
  17. package/dist/gitignore.js +254 -0
  18. package/dist/history.d.ts +24 -0
  19. package/dist/history.js +149 -0
  20. package/dist/index.d.ts +10 -0
  21. package/dist/index.js +25 -0
  22. package/dist/lifecycle.d.ts +101 -0
  23. package/dist/lifecycle.js +239 -0
  24. package/dist/lock.d.ts +21 -0
  25. package/dist/lock.js +42 -0
  26. package/dist/main.d.ts +1 -0
  27. package/dist/main.js +277 -0
  28. package/dist/operations.d.ts +23 -0
  29. package/dist/operations.js +275 -0
  30. package/dist/registry.d.ts +89 -0
  31. package/dist/registry.js +343 -0
  32. package/dist/rpc-error.d.ts +6 -0
  33. package/dist/rpc-error.js +11 -0
  34. package/dist/scheduler.d.ts +96 -0
  35. package/dist/scheduler.js +290 -0
  36. package/dist/schedules.d.ts +69 -0
  37. package/dist/schedules.js +244 -0
  38. package/dist/server.d.ts +58 -0
  39. package/dist/server.js +1780 -0
  40. package/dist/store.d.ts +176 -0
  41. package/dist/store.js +385 -0
  42. package/dist/terminals.d.ts +157 -0
  43. package/dist/terminals.js +487 -0
  44. package/dist/worktrees.d.ts +41 -0
  45. package/dist/worktrees.js +246 -0
  46. package/package.json +159 -4
  47. package/src/alp-templates.d.ts +5 -0
  48. package/src/attachments.ts +870 -0
  49. package/src/conversation.ts +837 -0
  50. package/src/files.ts +459 -0
  51. package/src/git.ts +1045 -0
  52. package/src/gitignore.ts +277 -0
  53. package/src/history.ts +118 -0
  54. package/src/index.ts +11 -0
  55. package/src/lifecycle.ts +283 -0
  56. package/src/lock.ts +53 -0
  57. package/src/main.ts +292 -0
  58. package/src/operations.ts +300 -0
  59. package/src/registry.ts +238 -0
  60. package/src/rpc-error.ts +4 -0
  61. package/src/scheduler.ts +422 -0
  62. package/src/schedules.ts +294 -0
  63. package/src/server.ts +2056 -0
  64. package/src/store.ts +448 -0
  65. package/src/terminals.ts +591 -0
  66. package/src/worktrees.ts +287 -0
@@ -0,0 +1,300 @@
1
+ import { createHash, createHmac, randomBytes } from 'node:crypto';
2
+ import { lstat, stat } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { CAPABILITY, ERROR, RPC_ERROR } from '@anhlp/alp-protocol';
5
+ import { closeTask, createTask, epicReport, loadTasks, reopenTask, resolveGate } from '@anhlp/alp-core/tasks';
6
+ import { taskRows } from '@anhlp/alp-core/task-rows';
7
+ import { deleteEntry, duplicateEntry, getEntry, listEntries, renameEntry, saveEntry, setGivenSkills } from '@anhlp/alp-core/library-edit';
8
+ import { listTeams } from '@anhlp/alp-core/teams';
9
+ import { MODELS } from '@anhlp/alp-core/models';
10
+ import { listProviders } from '@anhlp/alp-core/providers';
11
+ import { languageSetting, setLanguage, LANGUAGE_CHARS } from '@anhlp/alp-core/user-settings';
12
+ import { syncProjectSettings } from '@anhlp/alp-core/init';
13
+ import { RpcError } from './rpc-error.js';
14
+
15
+ /**
16
+ * The project, task, library and settings methods (docs/protocol/alp-json-rpc-v1.md §12, §15):
17
+ * what a client needs besides sessions, answered from the daemon host's own files so a remote
18
+ * client never reads ALP_HOME or a project. The business logic is core's; alpd resolves the
19
+ * project, serializes its own writes, maps core's refusals to protocol errors and keeps
20
+ * secrets out of what it answers. The schema has checked every param before a handler runs.
21
+ */
22
+
23
+ export type OperationsOptions = {
24
+ /** The daemon user's ALP_HOME: their library and settings.json. Without it only task.* is served. */
25
+ home?: string;
26
+ /** ALP's built-in agents and teams. */
27
+ templates?: Record<string, string>;
28
+ /** Project roots the daemon knows from its session records, for a team save's sync. */
29
+ knownProjects?: () => Iterable<string>;
30
+ };
31
+
32
+ type Handler = (params: any) => Promise<unknown>;
33
+
34
+ /** How long task.create remembers a requestId (§10): within one alpd process only. */
35
+ const REQUEST_TTL_MS = 10 * 60 * 1000;
36
+ /** At most this many remembered requestIds; the oldest go first. */
37
+ const MAX_REQUESTS = 10_000;
38
+ const MARKER = '$secret';
39
+ const KEEP = 'keep';
40
+
41
+ /** Secret-bearing maps of each kind's content: their values never leave alpd. */
42
+ const SECRET_MAPS: Record<string, string[][]> = {
43
+ mcp: [['server', 'env'], ['server', 'headers']],
44
+ providers: [['provider', 'env']],
45
+ };
46
+
47
+ const failure = (code: number, reason: string, message: string, extra: object = {}) => new RpcError(code, message, { reason, ...extra });
48
+
49
+ /** Core refusals (AlpError codes) as protocol errors; `context` decides what an ambiguous one means. */
50
+ function fromCore(error: any, context: { notFound?: 'not_found' | 'invalid_entry' } = {}): unknown {
51
+ if (error instanceof RpcError || typeof error?.code !== 'string' || error?.name !== 'AlpError') return error;
52
+ const message = error.message as string;
53
+ switch (error.code) {
54
+ case 'UNSAFE_LIBRARY_WRITE': return failure(ERROR.forbidden, 'library_policy', message);
55
+ case 'UNSAFE_PATH': return failure(ERROR.forbidden, 'unsafe_path', message);
56
+ case 'TASK_NOT_FOUND': return failure(ERROR.notFound, 'unknown_task', message);
57
+ case 'TASK_CHANGED': case 'REVISION_CONFLICT': return failure(ERROR.conflict, 'revision_conflict', message);
58
+ case 'INVALID_TASK': case 'TASK_CYCLE': case 'TASK_TAKEN': case 'TASK_UNVERIFIED': return failure(ERROR.conflict, 'task_state', message);
59
+ case 'TASKS_LOCKED': return failure(ERROR.unavailable, 'busy', message);
60
+ case 'IN_USE': return failure(ERROR.conflict, 'in_use', message);
61
+ case 'INVALID_SCOPE': return failure(RPC_ERROR.invalidParams, 'invalid_scope', message);
62
+ case 'INVALID_LIBRARY': case 'INVALID_SETTINGS': return failure(ERROR.failed, 'unreadable', message);
63
+ }
64
+ if (error.code === 'NOT_FOUND' || error.code.endsWith('_NOT_FOUND')) {
65
+ return context.notFound === 'invalid_entry' ? failure(RPC_ERROR.invalidParams, 'invalid_entry', message) : failure(ERROR.notFound, 'not_found', message);
66
+ }
67
+ if (error.code.startsWith('INVALID_')) return failure(RPC_ERROR.invalidParams, 'invalid_entry', message);
68
+ return error;
69
+ }
70
+
71
+ const object = (value: unknown): value is Record<string, any> => value !== null && typeof value === 'object' && !Array.isArray(value);
72
+ const pointer = (parts: string[]) => parts.map(part => `/${part.replaceAll('~', '~0').replaceAll('/', '~1')}`).join('');
73
+ const isMarker = (value: unknown) => object(value) && Object.keys(value).length === 1 && value[MARKER] === KEEP;
74
+ const at = (content: unknown, parts: string[]) => parts.reduce<any>((value, part) => object(value) ? value[part] : undefined, content);
75
+
76
+ /** A copy of an entry's content with each stored secret replaced by the marker, and where they were. */
77
+ function redact(kind: string, content: Record<string, unknown>) {
78
+ const copy = structuredClone(content);
79
+ const secrets: string[] = [];
80
+ for (const parts of SECRET_MAPS[kind] ?? []) {
81
+ const map = at(copy, parts);
82
+ if (!object(map)) continue;
83
+ for (const key of Object.keys(map)) {
84
+ if (typeof map[key] !== 'string') continue;
85
+ map[key] = { [MARKER]: KEEP };
86
+ secrets.push(pointer([...parts, key]));
87
+ }
88
+ }
89
+ return { content: copy, secrets };
90
+ }
91
+
92
+ /**
93
+ * The content a save writes: a marker keeps the value stored at its place in `previous` (the entry
94
+ * the save replaces, or the one that applies when the scope has none yet), a string replaces it, a
95
+ * missing key removes it. A marker anywhere else, or with nothing stored to keep, refuses the save,
96
+ * so a placeholder never reaches storage.
97
+ */
98
+ function unredact(kind: string, content: Record<string, unknown>, previous: Record<string, unknown> | undefined) {
99
+ const next = structuredClone(content);
100
+ for (const parts of SECRET_MAPS[kind] ?? []) {
101
+ const map = at(next, parts);
102
+ if (!object(map)) continue;
103
+ const stored = at(previous, parts);
104
+ for (const key of Object.keys(map)) {
105
+ if (!isMarker(map[key])) continue;
106
+ const value = object(stored) ? stored[key] : undefined;
107
+ if (typeof value !== 'string') throw failure(RPC_ERROR.invalidParams, 'secret_marker', `There is no stored value of ${pointer([...parts, key])} to keep; send the value instead`);
108
+ map[key] = value;
109
+ }
110
+ }
111
+ const stray = (value: unknown, parts: string[]): string | undefined => {
112
+ if (isMarker(value) || (object(value) && Object.hasOwn(value, MARKER))) return pointer(parts);
113
+ if (Array.isArray(value)) for (const [index, item] of value.entries()) { const found = stray(item, [...parts, String(index)]); if (found) return found; }
114
+ if (object(value)) for (const [key, item] of Object.entries(value)) { const found = stray(item, [...parts, key]); if (found) return found; }
115
+ return undefined;
116
+ };
117
+ const found = stray(next, []);
118
+ if (found !== undefined) throw failure(RPC_ERROR.invalidParams, 'secret_marker', `${found || 'content'} holds a secret marker where no secret is kept`);
119
+ return next;
120
+ }
121
+
122
+ export function createOperations({ home, templates, knownProjects = () => [] }: OperationsOptions = {}) {
123
+ /** Revisions on the wire are keyed per alpd process, so they never carry a hash of secret content. */
124
+ const revisionKey = randomBytes(32);
125
+ const toWire = (revision: string | null | undefined) => revision == null ? null : `r${createHmac('sha256', revisionKey).update(revision).digest('base64url').slice(0, 22)}`;
126
+ /** alpd's own writes to the library, settings and projects' .alp happen one at a time. */
127
+ let writes: Promise<unknown> = Promise.resolve();
128
+ const serial = <T>(work: () => Promise<T>): Promise<T> => {
129
+ const run = writes.catch(() => {}).then(work);
130
+ writes = run;
131
+ return run;
132
+ };
133
+ const requests = new Map<string, { fingerprint: string; at: number; result: Promise<{ id: string }> }>();
134
+
135
+ /**
136
+ * A project as params name it: an absolute, normalized path to a directory holding a real .alp
137
+ * directory. alpd never walks up to a parent, so the path a caller authorizes is the one used.
138
+ */
139
+ async function project(value: string) {
140
+ if (!path.isAbsolute(value) || path.resolve(value) !== value) throw failure(RPC_ERROR.invalidParams, 'invalid_path', 'projectRoot must be an absolute, normalized path');
141
+ if (!(await stat(value).catch(() => undefined))?.isDirectory()) throw failure(ERROR.notFound, 'not_alp_project', `${value} is not a directory`);
142
+ const alp = await lstat(path.join(value, '.alp')).catch(() => undefined);
143
+ if (alp?.isSymbolicLink()) throw failure(ERROR.forbidden, 'unsafe_path', `${path.join(value, '.alp')} is a symlink`);
144
+ if (!alp?.isDirectory()) throw failure(ERROR.notFound, 'not_alp_project', `${value} is not an ALP project; run alp init there`);
145
+ return value;
146
+ }
147
+
148
+ async function where(projectRoot: string | undefined, scope?: string) {
149
+ if (scope === 'project' && projectRoot === undefined) throw failure(RPC_ERROR.invalidParams, 'invalid_scope', 'scope project needs projectRoot');
150
+ return { root: projectRoot === undefined ? undefined : await project(projectRoot), library: home, templates };
151
+ }
152
+
153
+ /** One layer's version of an entry, or undefined. */
154
+ async function layer(kind: string, name: string, options: object, scope?: string) {
155
+ try { return await getEntry(kind as any, name, { ...options, ...(scope ? { scope } : {}) } as any); }
156
+ catch (error: any) { if (error?.code === 'NOT_FOUND') return undefined; throw error; }
157
+ }
158
+
159
+ const guard = (handler: Handler, context?: Parameters<typeof fromCore>[1]): Handler => async params => {
160
+ try { return await handler(params); }
161
+ catch (error) { throw fromCore(error, context); }
162
+ };
163
+
164
+ const taskHandlers: Record<string, Handler> = {
165
+ 'task.list': guard(async ({ projectRoot }) => {
166
+ const root = await project(projectRoot);
167
+ const { tasks, unreadable } = await taskRows(root);
168
+ return { projectRoot: root, tasks, unreadable, revision: createHash('sha256').update(JSON.stringify([tasks, unreadable])).digest('hex').slice(0, 16) };
169
+ }),
170
+
171
+ 'task.create': guard(async ({ projectRoot, title, priority, requestId }) => {
172
+ const root = await project(projectRoot);
173
+ const create = () => createTask(root, { title: title.trim(), ...(priority !== undefined ? { priority } : {}) }, 'user').then(task => ({ id: task.id }));
174
+ if (requestId === undefined) return create();
175
+ const now = Date.now();
176
+ for (const [key, entry] of requests) if (now - entry.at > REQUEST_TTL_MS) requests.delete(key);
177
+ const key = JSON.stringify([root, requestId]);
178
+ const fingerprint = JSON.stringify([title.trim(), priority ?? null]);
179
+ const existing = requests.get(key);
180
+ if (existing) {
181
+ if (existing.fingerprint !== fingerprint) throw failure(ERROR.conflict, 'key_conflict', `Request ${requestId} was already used for another task`);
182
+ return { ...await existing.result, duplicate: true as const };
183
+ }
184
+ const result = create();
185
+ if (requests.size >= MAX_REQUESTS) requests.delete(requests.keys().next().value!);
186
+ requests.set(key, { fingerprint, at: now, result });
187
+ // A create that failed made nothing: the same requestId may try again.
188
+ result.catch(() => { if (requests.get(key)?.result === result) requests.delete(key); });
189
+ return result;
190
+ }),
191
+
192
+ 'task.update': guard(async ({ projectRoot, id, action, note, ifRev }) => {
193
+ const root = await project(projectRoot);
194
+ const options = ifRev !== undefined ? { ifRev } : undefined;
195
+ if (action === 'reopen') {
196
+ const task = await reopenTask(root, id, { ...(note ? { note } : {}) }, 'user', options);
197
+ return { id: task.id, status: task.status, rev: task.rev };
198
+ }
199
+ const task = await closeTask(root, id, { reason: 'done', ...(note ? { summary: note } : {}) }, 'user', options);
200
+ const { tasks } = await loadTasks(root);
201
+ const landed = tasks.some(entry => entry.parent === task.id) ? epicReport(task.id, tasks).text.split('\n')[0] : undefined;
202
+ return { id: task.id, status: task.status, rev: task.rev, ...(landed ? { landed } : {}) };
203
+ }),
204
+
205
+ 'task.gate.resolve': guard(async ({ projectRoot, id, gate, note, ifRev }) => {
206
+ const root = await project(projectRoot);
207
+ const task = await resolveGate(root, id, gate, { by: 'user', ...(note ? { note } : {}), ...(ifRev !== undefined ? { ifRev } : {}) });
208
+ return { id: task.id, status: task.status, rev: task.rev };
209
+ }),
210
+ };
211
+
212
+ const libraryHandlers: Record<string, Handler> = {
213
+ 'team.list': guard(async ({ projectRoot }) => {
214
+ const { root } = await where(projectRoot);
215
+ const teams = await listTeams(root, { library: home, templates });
216
+ return { projectRoot: root ?? null, teams: teams.map(({ path: _path, ...team }) => team) };
217
+ }),
218
+
219
+ 'library.list': guard(async ({ kind, projectRoot }) => {
220
+ const options = await where(projectRoot);
221
+ const entries = await listEntries(kind, options);
222
+ return { projectRoot: options.root ?? null, entries: entries.map(({ path: _path, ...entry }: any) => entry) };
223
+ }),
224
+
225
+ 'library.get': guard(async ({ kind, name, projectRoot, scope }) => {
226
+ const options = await where(projectRoot, scope);
227
+ const entry = await getEntry(kind, name, { ...options, ...(scope ? { scope } : {}) });
228
+ const { content, secrets } = redact(kind, entry.content);
229
+ return { ...entry, content, revision: toWire(entry.revision), ...(secrets.length ? { secrets } : {}) };
230
+ }),
231
+
232
+ 'library.save': guard(({ kind, name, scope, projectRoot, content, revision, policy, sync = 'none' }) => serial(async () => {
233
+ if (policy === 'project-data' && sync !== 'none') throw failure(ERROR.forbidden, 'library_policy', 'Project-data writes cannot synchronize projects');
234
+ const options = await where(projectRoot, scope);
235
+ const current = await layer(kind, name, options, scope);
236
+ if (revision !== undefined && revision !== toWire(current?.revision ?? null)) {
237
+ throw failure(ERROR.conflict, 'revision_conflict', current === undefined ? `${kind} '${name}' is not in the ${scope}` : revision === null ? `${kind} '${name}' already exists in the ${scope}` : `${kind} '${name}' changed in the ${scope} since you opened it; reload it and apply your change again`);
238
+ }
239
+ const previous = current?.content ?? (await layer(kind, name, options))?.content;
240
+ const next = unredact(kind, content, previous);
241
+ // Core checks the revision again as it writes, against writers outside alpd.
242
+ const saved = await saveEntry(kind, name, next, { ...options, scope, policy, ...(revision !== undefined ? { revision: current?.revision ?? null } : {}) });
243
+ if (kind !== 'teams' || sync !== 'known-projects') return { revision: toWire(saved.revision) };
244
+ const roots = new Set<string>(options.root ? [options.root] : []);
245
+ if (scope === 'library') for (const root of knownProjects()) if (typeof root === 'string' && path.isAbsolute(root)) roots.add(path.resolve(root));
246
+ let syncedProjects = 0;
247
+ const syncErrors: string[] = [];
248
+ for (const root of roots) {
249
+ try { if (await syncProjectSettings(root, { library: home, templates, teamIds: [name], replaceModels: true })) syncedProjects += 1; }
250
+ catch (error) { syncErrors.push(`${root}: ${error instanceof Error ? error.message : String(error)}`); }
251
+ }
252
+ return { revision: toWire(saved.revision), syncedProjects, syncErrors };
253
+ }), { notFound: 'invalid_entry' }),
254
+
255
+ 'library.delete': guard(({ kind, name, scope, projectRoot, revision, policy }) => serial(async () => {
256
+ const options = await where(projectRoot, scope);
257
+ const current = await layer(kind, name, options, scope);
258
+ if (!current) throw failure(ERROR.notFound, 'not_found', `No ${kind} entry '${name}' in the ${scope}`);
259
+ if (revision !== undefined && revision !== toWire(current.revision)) throw failure(ERROR.conflict, 'revision_conflict', `${kind} '${name}' changed in the ${scope} since you opened it`);
260
+ return deleteEntry(kind, name, { ...options, scope, policy, ...(revision !== undefined ? { revision: current.revision } : {}) });
261
+ })),
262
+
263
+ 'library.duplicate': guard(({ kind, from, to, scope, projectRoot, policy }) => serial(async () => {
264
+ const options = await where(projectRoot, scope);
265
+ try { await getEntry(kind, from, options); }
266
+ catch (error) { throw fromCore(error, { notFound: 'not_found' }); }
267
+ return { revision: toWire((await duplicateEntry(kind, from, to, { ...options, scope, policy })).revision) };
268
+ }), { notFound: 'invalid_entry' }),
269
+
270
+ 'library.rename': guard(({ kind, from, to, scope, projectRoot, policy }) => serial(async () => {
271
+ const options = await where(projectRoot, scope);
272
+ return { revision: toWire((await renameEntry(kind, from, to, { ...options, scope, policy })).revision) };
273
+ })),
274
+
275
+ 'library.skills.set': guard(({ agent, skills }) => serial(() => setGivenSkills(agent, skills, { library: home })), { notFound: 'invalid_entry' }),
276
+
277
+ 'library.models': guard(async () => {
278
+ const models: Array<{ id: string; label: string; efforts: string[]; effort?: string }> = MODELS.map(model => ({ id: `${model.runtime}:${model.id}`, label: `${model.runtime} · ${model.label}`, efforts: model.efforts, ...(model.effort ? { effort: model.effort } : {}) }));
279
+ for (const provider of await listProviders(home)) {
280
+ if (provider.enabled === false || provider.kind === 'antigravity') continue;
281
+ models.push({ id: `acp:${provider.id}`, label: `${provider.label} · Provider default`, efforts: [] });
282
+ for (const model of [...(provider.models ?? []), ...(provider.additionalModels ?? [])]) models.push({ id: `acp:${provider.id}/${model.id}`, label: `${provider.label} · ${model.label ?? model.id}`, efforts: [] });
283
+ }
284
+ return { models: [...new Map(models.map(model => [model.id, model])).values()] };
285
+ }),
286
+
287
+ 'settings.language.get': guard(async () => languageSetting(home!)),
288
+
289
+ 'settings.language.set': guard(async ({ language }) => {
290
+ if (language !== null && language.trim().length > LANGUAGE_CHARS) throw failure(RPC_ERROR.invalidParams, 'invalid_params', `A language is a name of at most ${LANGUAGE_CHARS} characters`);
291
+ return serial(() => setLanguage(home!, language));
292
+ }),
293
+ };
294
+
295
+ const library = home !== undefined;
296
+ return {
297
+ handlers: { ...taskHandlers, ...(library ? libraryHandlers : {}) },
298
+ capabilities: [CAPABILITY.task, ...(library ? [CAPABILITY.team, CAPABILITY.library, CAPABILITY.libraryProjectWrite, CAPABILITY.settingsLanguage] : [])],
299
+ };
300
+ }
@@ -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>;
@@ -0,0 +1,4 @@
1
+ /** An error alpd answers with as is: its code, message and `data` (docs/protocol/alp-json-rpc-v1.md §5). */
2
+ export class RpcError extends Error {
3
+ constructor(public code: number, message: string, public data?: unknown) { super(message); }
4
+ }