@anhlp/alp-daemon 0.0.0-beta.2 → 0.0.1-beta.10

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 (104) hide show
  1. package/README.md +4 -0
  2. package/dist/THIRD-PARTY-NOTICES.txt +27 -2
  3. package/dist/alpd.js +39374 -17503
  4. package/dist/attachments.d.ts +187 -0
  5. package/dist/attachments.js +856 -0
  6. package/dist/build-manifest.json +41 -2
  7. package/dist/conversation.d.ts +119 -0
  8. package/dist/conversation.js +688 -0
  9. package/dist/disk.d.ts +67 -0
  10. package/dist/disk.js +152 -0
  11. package/dist/files.d.ts +156 -3
  12. package/dist/files.js +402 -59
  13. package/dist/git.d.ts +98 -0
  14. package/dist/git.js +1246 -0
  15. package/dist/gitignore.d.ts +5 -0
  16. package/dist/gitignore.js +26 -7
  17. package/dist/history.d.ts +24 -0
  18. package/dist/history.js +149 -0
  19. package/dist/index.d.ts +7 -0
  20. package/dist/index.js +21 -1
  21. package/dist/lifecycle.d.ts +101 -0
  22. package/dist/lifecycle.js +239 -0
  23. package/dist/main.js +146 -21
  24. package/dist/model-catalog.d.ts +2 -0
  25. package/dist/model-catalog.js +44 -0
  26. package/dist/native-entry.d.ts +2 -0
  27. package/dist/native-entry.js +3 -0
  28. package/dist/native-register.d.ts +1 -0
  29. package/dist/native-register.js +13 -0
  30. package/dist/native-terminal.d.ts +45 -0
  31. package/dist/native-terminal.js +201 -0
  32. package/dist/operations.d.ts +20 -3
  33. package/dist/operations.js +62 -21
  34. package/dist/registry.d.ts +89 -0
  35. package/dist/registry.js +343 -0
  36. package/dist/scheduler.d.ts +96 -0
  37. package/dist/scheduler.js +298 -0
  38. package/dist/schedules.d.ts +70 -0
  39. package/dist/schedules.js +246 -0
  40. package/dist/server.d.ts +14 -2
  41. package/dist/server.js +903 -97
  42. package/dist/store.d.ts +72 -2
  43. package/dist/store.js +111 -4
  44. package/dist/terminal-native/README.md +201 -0
  45. package/dist/terminal-native/prebuilt/darwin-arm64/manifest.json +11 -0
  46. package/dist/terminal-native/prebuilt/darwin-arm64/terminal-owner +0 -0
  47. package/dist/terminal-native/prebuilt/darwin-x64/manifest.json +11 -0
  48. package/dist/terminal-native/prebuilt/darwin-x64/terminal-owner +0 -0
  49. package/dist/terminal-native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
  50. package/dist/terminal-native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
  51. package/dist/terminal-native/prebuilt/linux-arm64-musl/manifest.json +10 -0
  52. package/dist/terminal-native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
  53. package/dist/terminal-native/prebuilt/linux-x64-glibc/manifest.json +10 -0
  54. package/dist/terminal-native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
  55. package/dist/terminal-native/prebuilt/linux-x64-musl/manifest.json +10 -0
  56. package/dist/terminal-native/prebuilt/linux-x64-musl/terminal-owner +0 -0
  57. package/dist/terminal-native/terminal-owner.c +389 -0
  58. package/dist/terminal-screen.d.ts +24 -0
  59. package/dist/terminal-screen.js +99 -0
  60. package/dist/terminals.d.ts +203 -0
  61. package/dist/terminals.js +570 -0
  62. package/dist/windows-terminal.d.ts +32 -0
  63. package/dist/windows-terminal.js +79 -0
  64. package/dist/worktrees.d.ts +65 -0
  65. package/dist/worktrees.js +318 -0
  66. package/native/README.md +201 -0
  67. package/native/prebuilt/darwin-arm64/manifest.json +11 -0
  68. package/native/prebuilt/darwin-arm64/terminal-owner +0 -0
  69. package/native/prebuilt/darwin-x64/manifest.json +11 -0
  70. package/native/prebuilt/darwin-x64/terminal-owner +0 -0
  71. package/native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
  72. package/native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
  73. package/native/prebuilt/linux-arm64-musl/manifest.json +10 -0
  74. package/native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
  75. package/native/prebuilt/linux-x64-glibc/manifest.json +10 -0
  76. package/native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
  77. package/native/prebuilt/linux-x64-musl/manifest.json +10 -0
  78. package/native/prebuilt/linux-x64-musl/terminal-owner +0 -0
  79. package/native/terminal-owner.c +389 -0
  80. package/package.json +71 -8
  81. package/src/attachments.ts +908 -0
  82. package/src/conversation.ts +857 -0
  83. package/src/disk.ts +175 -0
  84. package/src/files.ts +535 -71
  85. package/src/git.ts +1220 -0
  86. package/src/gitignore.ts +25 -8
  87. package/src/history.ts +118 -0
  88. package/src/index.ts +7 -0
  89. package/src/lifecycle.ts +283 -0
  90. package/src/main.ts +154 -23
  91. package/src/model-catalog.ts +36 -0
  92. package/src/native-entry.ts +5 -0
  93. package/src/native-register.ts +21 -0
  94. package/src/native-terminal.ts +127 -0
  95. package/src/operations.ts +53 -22
  96. package/src/registry.ts +238 -0
  97. package/src/scheduler.ts +438 -0
  98. package/src/schedules.ts +297 -0
  99. package/src/server.ts +1019 -109
  100. package/src/store.ts +117 -4
  101. package/src/terminal-screen.ts +74 -0
  102. package/src/terminals.ts +653 -0
  103. package/src/windows-terminal.ts +74 -0
  104. package/src/worktrees.ts +382 -0
package/src/operations.ts CHANGED
@@ -2,11 +2,11 @@ import { createHash, createHmac, randomBytes } from 'node:crypto';
2
2
  import { lstat, stat } from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import { CAPABILITY, ERROR, RPC_ERROR } from '@anhlp/alp-protocol';
5
- import { closeTask, createTask, epicReport, loadTasks, reopenTask, resolveGate } from '@anhlp/alp-core/tasks';
5
+ import { closeTask, createTask, epicReport, loadTasks, rejectGate, reopenTask, resolveGate } from '@anhlp/alp-core/tasks';
6
6
  import { taskRows } from '@anhlp/alp-core/task-rows';
7
7
  import { deleteEntry, duplicateEntry, getEntry, listEntries, renameEntry, saveEntry, setGivenSkills } from '@anhlp/alp-core/library-edit';
8
8
  import { listTeams } from '@anhlp/alp-core/teams';
9
- import { MODELS } from '@anhlp/alp-core/models';
9
+ import { catalogEntries } from '@anhlp/alp-runtime/index';
10
10
  import { listProviders } from '@anhlp/alp-core/providers';
11
11
  import { languageSetting, setLanguage, LANGUAGE_CHARS } from '@anhlp/alp-core/user-settings';
12
12
  import { syncProjectSettings } from '@anhlp/alp-core/init';
@@ -27,9 +27,17 @@ export type OperationsOptions = {
27
27
  templates?: Record<string, string>;
28
28
  /** Project roots the daemon knows from its session records, for a team save's sync. */
29
29
  knownProjects?: () => Iterable<string>;
30
+ /** A gate changed through task.gate.resolve: the runtime syncs the project's gate cards and mail. */
31
+ onGateChange?: (projectRoot: string) => Promise<void> | void;
32
+ /** A provider file was written or removed; `enabled` when this save turned it from off to on (t-d0b0). */
33
+ onProviderSaved?: (id: string, enabled: boolean) => void;
34
+ /** The models alpd's catalog learned or probed for an ACP provider (t-d0b0). */
35
+ learnedModels?: (id: string) => Array<{ id: string; label?: string }>;
30
36
  };
31
37
 
32
- type Handler = (params: any) => Promise<unknown>;
38
+ /** `caller.agent`: the connection said in daemon.hello that an ALP agent started it (t-ca1f). */
39
+ export type Caller = { agent?: boolean };
40
+ type Handler = (params: any, caller?: Caller) => Promise<unknown>;
33
41
 
34
42
  /** How long task.create remembers a requestId (§10): within one alpd process only. */
35
43
  const REQUEST_TTL_MS = 10 * 60 * 1000;
@@ -47,14 +55,16 @@ const SECRET_MAPS: Record<string, string[][]> = {
47
55
  const failure = (code: number, reason: string, message: string, extra: object = {}) => new RpcError(code, message, { reason, ...extra });
48
56
 
49
57
  /** 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 {
58
+ export function fromCore(error: any, context: { notFound?: 'not_found' | 'invalid_entry' } = {}): unknown {
51
59
  if (error instanceof RpcError || typeof error?.code !== 'string' || error?.name !== 'AlpError') return error;
52
60
  const message = error.message as string;
53
61
  switch (error.code) {
62
+ case 'UNSAFE_LIBRARY_WRITE': return failure(ERROR.forbidden, 'library_policy', message);
54
63
  case 'UNSAFE_PATH': return failure(ERROR.forbidden, 'unsafe_path', message);
55
64
  case 'TASK_NOT_FOUND': return failure(ERROR.notFound, 'unknown_task', message);
56
65
  case 'TASK_CHANGED': case 'REVISION_CONFLICT': return failure(ERROR.conflict, 'revision_conflict', message);
57
66
  case 'INVALID_TASK': case 'TASK_CYCLE': case 'TASK_TAKEN': case 'TASK_UNVERIFIED': return failure(ERROR.conflict, 'task_state', message);
67
+ case 'GATE_USER_ONLY': return failure(ERROR.forbidden, 'user_only', message);
58
68
  case 'TASKS_LOCKED': return failure(ERROR.unavailable, 'busy', message);
59
69
  case 'IN_USE': return failure(ERROR.conflict, 'in_use', message);
60
70
  case 'INVALID_SCOPE': return failure(RPC_ERROR.invalidParams, 'invalid_scope', message);
@@ -118,7 +128,7 @@ function unredact(kind: string, content: Record<string, unknown>, previous: Reco
118
128
  return next;
119
129
  }
120
130
 
121
- export function createOperations({ home, templates, knownProjects = () => [] }: OperationsOptions = {}) {
131
+ export function createOperations({ home, templates, knownProjects = () => [], onGateChange, onProviderSaved, learnedModels }: OperationsOptions = {}) {
122
132
  /** Revisions on the wire are keyed per alpd process, so they never carry a hash of secret content. */
123
133
  const revisionKey = randomBytes(32);
124
134
  const toWire = (revision: string | null | undefined) => revision == null ? null : `r${createHmac('sha256', revisionKey).update(revision).digest('base64url').slice(0, 22)}`;
@@ -155,8 +165,8 @@ export function createOperations({ home, templates, knownProjects = () => [] }:
155
165
  catch (error: any) { if (error?.code === 'NOT_FOUND') return undefined; throw error; }
156
166
  }
157
167
 
158
- const guard = (handler: Handler, context?: Parameters<typeof fromCore>[1]): Handler => async params => {
159
- try { return await handler(params); }
168
+ const guard = (handler: Handler, context?: Parameters<typeof fromCore>[1]): Handler => async (params, caller) => {
169
+ try { return await handler(params, caller); }
160
170
  catch (error) { throw fromCore(error, context); }
161
171
  };
162
172
 
@@ -188,22 +198,33 @@ export function createOperations({ home, templates, knownProjects = () => [] }:
188
198
  return result;
189
199
  }),
190
200
 
191
- 'task.update': guard(async ({ projectRoot, id, action, note, ifRev }) => {
201
+ 'task.update': guard(async ({ projectRoot, id, action, note, ifRev }, caller) => {
192
202
  const root = await project(projectRoot);
193
203
  const options = ifRev !== undefined ? { ifRev } : undefined;
194
204
  if (action === 'reopen') {
195
205
  const task = await reopenTask(root, id, { ...(note ? { note } : {}) }, 'user', options);
196
206
  return { id: task.id, status: task.status, rev: task.rev };
197
207
  }
198
- const task = await closeTask(root, id, { reason: 'done', ...(note ? { summary: note } : {}) }, 'user', options);
208
+ const task = await closeTask(root, id, { reason: 'done', ...(note ? { summary: note } : {}), agent: caller?.agent === true, channel: 'web' }, 'user', options);
199
209
  const { tasks } = await loadTasks(root);
200
210
  const landed = tasks.some(entry => entry.parent === task.id) ? epicReport(task.id, tasks).text.split('\n')[0] : undefined;
201
211
  return { id: task.id, status: task.status, rev: task.rev, ...(landed ? { landed } : {}) };
202
212
  }),
203
213
 
204
- 'task.gate.resolve': guard(async ({ projectRoot, id, gate, note, ifRev }) => {
214
+ // Approves a gate, or with reject records the user's rejection and leaves it open. Either way
215
+ // the runtime is told, so main gets the decision by mail (at least once) and the gate's card settles.
216
+ 'task.gate.resolve': guard(async ({ projectRoot, id, gate, note, ifRev, choice, reject, channel = 'web' }, caller) => {
205
217
  const root = await project(projectRoot);
206
- const task = await resolveGate(root, id, gate, { by: 'user', ...(note ? { note } : {}), ...(ifRev !== undefined ? { ifRev } : {}) });
218
+ // Only the user decides a human gate: never a connection an ALP agent opened (t-ca1f).
219
+ if (caller?.agent) {
220
+ const { tasks } = await loadTasks(root);
221
+ if (tasks.find(task => task.id === id)?.gates.find(entry => entry.id === gate)?.kind === 'human') throw failure(ERROR.forbidden, 'user_only', 'Only the user decides a human gate; this connection was opened by an ALP agent');
222
+ }
223
+ const guarded = ifRev !== undefined ? { ifRev } : {};
224
+ const task = reject === true
225
+ ? await rejectGate(root, id, gate, { by: 'user', channel, ...(note ? { reason: note } : {}), ...guarded })
226
+ : await resolveGate(root, id, gate, { by: 'user', channel, ...(note ? { note } : {}), ...(choice !== undefined ? { choice } : {}), ...guarded });
227
+ await onGateChange?.(root);
207
228
  return { id: task.id, status: task.status, rev: task.rev };
208
229
  }),
209
230
  };
@@ -228,7 +249,8 @@ export function createOperations({ home, templates, knownProjects = () => [] }:
228
249
  return { ...entry, content, revision: toWire(entry.revision), ...(secrets.length ? { secrets } : {}) };
229
250
  }),
230
251
 
231
- 'library.save': guard(({ kind, name, scope, projectRoot, content, revision, sync = 'none' }) => serial(async () => {
252
+ 'library.save': guard(({ kind, name, scope, projectRoot, content, revision, policy, sync = 'none' }) => serial(async () => {
253
+ if (policy === 'project-data' && sync !== 'none') throw failure(ERROR.forbidden, 'library_policy', 'Project-data writes cannot synchronize projects');
232
254
  const options = await where(projectRoot, scope);
233
255
  const current = await layer(kind, name, options, scope);
234
256
  if (revision !== undefined && revision !== toWire(current?.revision ?? null)) {
@@ -237,7 +259,9 @@ export function createOperations({ home, templates, knownProjects = () => [] }:
237
259
  const previous = current?.content ?? (await layer(kind, name, options))?.content;
238
260
  const next = unredact(kind, content, previous);
239
261
  // Core checks the revision again as it writes, against writers outside alpd.
240
- const saved = await saveEntry(kind, name, next, { ...options, scope, ...(revision !== undefined ? { revision: current?.revision ?? null } : {}) });
262
+ const saved = await saveEntry(kind, name, next, { ...options, scope, policy, ...(revision !== undefined ? { revision: current?.revision ?? null } : {}) });
263
+ // Enabled is the change from off to on, never a save of a provider that was on already (t-d0b0).
264
+ if (kind === 'providers') { try { onProviderSaved?.(name, (previous as any)?.provider?.enabled === false && (next as any)?.provider?.enabled !== false); } catch { /* the catalog is best effort */ } }
241
265
  if (kind !== 'teams' || sync !== 'known-projects') return { revision: toWire(saved.revision) };
242
266
  const roots = new Set<string>(options.root ? [options.root] : []);
243
267
  if (scope === 'library') for (const root of knownProjects()) if (typeof root === 'string' && path.isAbsolute(root)) roots.add(path.resolve(root));
@@ -250,34 +274,41 @@ export function createOperations({ home, templates, knownProjects = () => [] }:
250
274
  return { revision: toWire(saved.revision), syncedProjects, syncErrors };
251
275
  }), { notFound: 'invalid_entry' }),
252
276
 
253
- 'library.delete': guard(({ kind, name, scope, projectRoot, revision }) => serial(async () => {
277
+ 'library.delete': guard(({ kind, name, scope, projectRoot, revision, policy }) => serial(async () => {
254
278
  const options = await where(projectRoot, scope);
255
279
  const current = await layer(kind, name, options, scope);
256
280
  if (!current) throw failure(ERROR.notFound, 'not_found', `No ${kind} entry '${name}' in the ${scope}`);
257
281
  if (revision !== undefined && revision !== toWire(current.revision)) throw failure(ERROR.conflict, 'revision_conflict', `${kind} '${name}' changed in the ${scope} since you opened it`);
258
- return deleteEntry(kind, name, { ...options, scope, ...(revision !== undefined ? { revision: current.revision } : {}) });
282
+ const deleted = await deleteEntry(kind, name, { ...options, scope, policy, ...(revision !== undefined ? { revision: current.revision } : {}) });
283
+ if (kind === 'providers') { try { onProviderSaved?.(name, false); } catch { /* best effort */ } }
284
+ return deleted;
259
285
  })),
260
286
 
261
- 'library.duplicate': guard(({ kind, from, to, scope, projectRoot }) => serial(async () => {
287
+ 'library.duplicate': guard(({ kind, from, to, scope, projectRoot, policy }) => serial(async () => {
262
288
  const options = await where(projectRoot, scope);
263
289
  try { await getEntry(kind, from, options); }
264
290
  catch (error) { throw fromCore(error, { notFound: 'not_found' }); }
265
- return { revision: toWire((await duplicateEntry(kind, from, to, { ...options, scope })).revision) };
291
+ const result = { revision: toWire((await duplicateEntry(kind, from, to, { ...options, scope, policy })).revision) };
292
+ if (kind === 'providers') { try { onProviderSaved?.(to, false); } catch { /* best effort */ } }
293
+ return result;
266
294
  }), { notFound: 'invalid_entry' }),
267
295
 
268
- 'library.rename': guard(({ kind, from, to, scope, projectRoot }) => serial(async () => {
296
+ 'library.rename': guard(({ kind, from, to, scope, projectRoot, policy }) => serial(async () => {
269
297
  const options = await where(projectRoot, scope);
270
- return { revision: toWire((await renameEntry(kind, from, to, { ...options, scope })).revision) };
298
+ const renamed = await renameEntry(kind, from, to, { ...options, scope, policy });
299
+ if (kind === 'providers') { try { onProviderSaved?.(to, false); } catch { /* best effort */ } }
300
+ return { revision: toWire(renamed.revision) };
271
301
  })),
272
302
 
273
303
  'library.skills.set': guard(({ agent, skills }) => serial(() => setGivenSkills(agent, skills, { library: home })), { notFound: 'invalid_entry' }),
274
304
 
275
305
  'library.models': guard(async () => {
276
- 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 } : {}) }));
306
+ const models: Array<{ id: string; label: string; efforts: string[]; effort?: string }> = catalogEntries.map(model => ({ id: `${model.runtime}:${model.id}`, label: `${model.runtime} · ${model.label}`, efforts: model.efforts, ...(model.effort ? { effort: model.effort } : {}) }));
277
307
  for (const provider of await listProviders(home)) {
278
308
  if (provider.enabled === false || provider.kind === 'antigravity') continue;
279
309
  models.push({ id: `acp:${provider.id}`, label: `${provider.label} · Provider default`, efforts: [] });
280
- for (const model of [...(provider.models ?? []), ...(provider.additionalModels ?? [])]) models.push({ id: `acp:${provider.id}/${model.id}`, label: `${provider.label} · ${model.label ?? model.id}`, efforts: [] });
310
+ // The file's models replace what a session or probe taught alpd's catalog (t-d0b0); additionalModels add.
311
+ for (const model of [...(provider.models ?? learnedModels?.(provider.id) ?? []), ...(provider.additionalModels ?? [])]) models.push({ id: `acp:${provider.id}/${model.id}`, label: `${provider.label} · ${model.label ?? model.id}`, efforts: [] });
281
312
  }
282
313
  return { models: [...new Map(models.map(model => [model.id, model])).values()] };
283
314
  }),
@@ -293,6 +324,6 @@ export function createOperations({ home, templates, knownProjects = () => [] }:
293
324
  const library = home !== undefined;
294
325
  return {
295
326
  handlers: { ...taskHandlers, ...(library ? libraryHandlers : {}) },
296
- capabilities: [CAPABILITY.task, ...(library ? [CAPABILITY.team, CAPABILITY.library, CAPABILITY.settingsLanguage] : [])],
327
+ capabilities: [CAPABILITY.task, ...(library ? [CAPABILITY.team, CAPABILITY.library, CAPABILITY.libraryProjectWrite, CAPABILITY.settingsLanguage] : [])],
297
328
  };
298
329
  }
@@ -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 (canonical !== (w.canonical ?? w.directory)) 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>;