@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,287 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { lstat, readFile, realpath, stat } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { user_worktree } from '@anhlp/alp-core';
5
+ import { RegistryError, type RegistryService, type Registry, type WorkspaceRecord } from './registry.js';
6
+
7
+ type Mapping = { id: string; source: string; commonDir: string; parent: string };
8
+ type Context = { principalId?: string; principalEpoch?: string; mappingIds?: string[]; authorizedRoots?: string[] };
9
+ const fail = (reason: string, message: string, code = 1004): never => {
10
+ throw new RegistryError(code, message, { reason });
11
+ };
12
+ const git = user_worktree.userWorktreeGit;
13
+ /** Owner-only file; neither an RPC parameter nor repository configuration can approve a destination. */
14
+ export async function worktreeMappings(home: string): Promise<Mapping[]> {
15
+ const file = path.join(home, 'worktree-destinations.json');
16
+ const info = await lstat(file).catch((e: any) => {
17
+ if (e.code === 'ENOENT') return undefined;
18
+ throw e;
19
+ });
20
+ if (!info) return [];
21
+ if (!info.isFile() || (process.platform !== 'win32' && (info.uid !== process.getuid?.() || info.mode & 0o077)))
22
+ fail('mapping_invalid', 'Worktree destination configuration must be private', 1005);
23
+ const value = JSON.parse(await readFile(file, 'utf8'));
24
+ if (value?.version !== 1 || !Array.isArray(value.mappings))
25
+ fail('mapping_invalid', 'Invalid worktree destination configuration', 1005);
26
+ const ids = new Set<string>();
27
+ for (const m of value.mappings) {
28
+ if (!m || typeof m.id !== 'string' || !/^[a-zA-Z0-9_-]{1,64}$/.test(m.id) || ids.has(m.id))
29
+ fail('mapping_invalid', 'Invalid mapping identity', 1005);
30
+ ids.add(m.id);
31
+ for (const k of ['source', 'commonDir', 'parent']) {
32
+ if (
33
+ typeof m[k] !== 'string' ||
34
+ !path.isAbsolute(m[k]) ||
35
+ (await realpath(m[k])) !== m[k] ||
36
+ !(await stat(m[k])).isDirectory()
37
+ )
38
+ fail('mapping_invalid', 'Mapping paths must be existing canonical directories', 1005);
39
+ }
40
+ const parentInfo = await stat(m.parent);
41
+ if (process.platform !== 'win32' && (parentInfo.uid !== process.getuid?.() || parentInfo.mode & 0o077))
42
+ fail('mapping_invalid', 'Destination parent must be owner-private', 1005);
43
+ for (const reserved of [path.join(home, 'worktrees'), path.join(home, 'copies'), m.commonDir])
44
+ if (m.parent === reserved || m.parent.startsWith(reserved + path.sep) || reserved.startsWith(m.parent + path.sep))
45
+ fail('mapping_invalid', 'Destination overlaps protected assignment or Git storage', 1005);
46
+ if (m.parent === m.source || m.parent.startsWith(m.source + path.sep) || m.source.startsWith(m.parent + path.sep))
47
+ fail('mapping_invalid', 'Destination parent must be separate from source', 1005);
48
+ }
49
+ return value.mappings;
50
+ }
51
+ export function createWorkspaceWorktrees(
52
+ home: string,
53
+ registry: RegistryService,
54
+ guard: <T>(directory: string, run: () => Promise<T>) => Promise<T>,
55
+ register: (directory: string) => Promise<void>
56
+ ) {
57
+ const adapter = git();
58
+ async function approved(context: Context, source: string, mappingId: string, native = true) {
59
+ const m = (await worktreeMappings(home)).find((m) => m.id === mappingId && m.source === source);
60
+ if (!m) return fail('outside_workspace', 'Mapping unavailable', 1003);
61
+ if (
62
+ (context.mappingIds && !context.mappingIds.includes(m.id)) ||
63
+ (context.authorizedRoots && !context.authorizedRoots.includes(source))
64
+ )
65
+ fail('outside_workspace', 'Worktree mapping is not approved for this credential', 1003);
66
+ if ((await (native ? adapter.facts(source) : user_worktree.repositoryIdentity(source))).commonDir !== m.commonDir)
67
+ fail('identity_changed', 'Source repository identity changed', 1003);
68
+ return m;
69
+ }
70
+ const workspace = (r: Registry, id: string) =>
71
+ r.workspaces.find((w) => w.id === id) ?? fail('not_found', 'No workspace', 1001);
72
+ async function sourceOf(r: Registry, id: string) {
73
+ const w = workspace(r, id);
74
+ if (w.archivedAt || w.worktree?.removedAt || r.projects.find((p) => p.id === w.projectId)?.removedAt)
75
+ fail('not_found', 'Workspace unavailable', 1001);
76
+ if ((await realpath(w.directory)) !== (w.canonical ?? w.directory))
77
+ fail('identity_changed', 'Source identity changed', 1003);
78
+ return w;
79
+ }
80
+ async function clean(source: string, target: string, branch: string, head: string) {
81
+ if (!(await adapter.inspect(source, target, branch)))
82
+ fail('outcome_unknown', 'Worktree creation needs owner reconciliation', 1005);
83
+ // Reconciliation never resets files: a partially materialized or subsequently edited checkout is retained.
84
+ if ((await adapter.facts(target)).head !== head) fail('outcome_unknown', 'Prepared worktree HEAD changed', 1005);
85
+ await adapter.assertClean(target);
86
+ }
87
+ return {
88
+ async describe(w: WorkspaceRecord) {
89
+ const { worktree, ...row } = w;
90
+ let branch: string | null = null;
91
+ try {
92
+ // The registry keeps the directory as given (it may pass through a symlink, e.g. /var on
93
+ // macOS) and its realpath as canonical; read the checkout only where that identity still
94
+ // holds. A record with no canonical identity is read only at its own, already canonical, path.
95
+ const canonical = await realpath(w.directory);
96
+ if (canonical === (w.canonical ?? w.directory))
97
+ branch = (await user_worktree.repositoryIdentity(canonical)).branch;
98
+ } catch {}
99
+ return { ...row, branch, ...(worktree ? { managedWorktree: true } : {}) };
100
+ },
101
+ async assertAvailable(directory: string) {
102
+ const r = await registry.snapshot();
103
+ const canonical = await realpath(directory).catch(() => path.resolve(directory));
104
+ if (
105
+ Object.values(r.worktreeJournal ?? {}).some(
106
+ (j) => canonical === j.intent.directory || canonical.startsWith(j.intent.directory + path.sep)
107
+ )
108
+ )
109
+ fail('reconciliation_required', 'Workspace is pending reconciliation');
110
+ },
111
+ async grants(context: Context = {}) {
112
+ const r = await registry.snapshot();
113
+ const mappings: Mapping[] = [];
114
+ for (const m of await worktreeMappings(home)) {
115
+ try {
116
+ await approved(context, m.source, m.id, false);
117
+ mappings.push(m);
118
+ } catch {}
119
+ }
120
+ const workspaces: WorkspaceRecord[] = [];
121
+ for (const w of r.workspaces) {
122
+ const m = w.worktree;
123
+ if (
124
+ !m ||
125
+ m.principalId !== (context.principalId ?? 'owner') ||
126
+ m.grantEpoch !== (context.principalEpoch ?? 'owner') ||
127
+ !mappings.some((a) => a.id === m.mappingId && a.source === m.source && a.commonDir === m.commonDir)
128
+ )
129
+ continue;
130
+ const expected = path.join(mappings.find((a) => a.id === m.mappingId)!.parent, w.id);
131
+ if (w.directory !== expected || w.canonical !== expected) continue;
132
+ const pending = Object.values(r.worktreeJournal ?? {}).find((j) => j.intent.id === w.id);
133
+ if (!m.removedAt && !pending) {
134
+ try {
135
+ const identity = await user_worktree.repositoryIdentity(w.directory);
136
+ if (
137
+ identity.gitDir !== m.gitDir ||
138
+ identity.commonDir !== m.commonDir ||
139
+ identity.branch !== m.branch ||
140
+ (await lstat(path.join(identity.gitDir, 'locked')).catch((e: any) => {
141
+ if (e.code === 'ENOENT') return undefined;
142
+ throw e;
143
+ }))
144
+ )
145
+ continue;
146
+ } catch {
147
+ continue;
148
+ }
149
+ }
150
+ workspaces.push(
151
+ Object.values(r.worktreeJournal ?? {}).some((j) => j.intent.id === w.id)
152
+ ? { ...w, archivedAt: w.archivedAt ?? 'pending' }
153
+ : w
154
+ );
155
+ }
156
+ return { mappings: mappings.map((m) => ({ id: m.id, source: m.source })), workspaces };
157
+ },
158
+ async mutate(method: 'create' | 'remove', p: any, context: Context = {}) {
159
+ const actor = context.principalId ?? 'owner';
160
+ const r = await registry.snapshot();
161
+ const w = workspace(r, p.workspaceId);
162
+ const origin = method === 'create' ? await sourceOf(r, w.id) : w;
163
+ const meta = w.worktree;
164
+ if (
165
+ method === 'remove' &&
166
+ (!meta ||
167
+ meta.kind !== 'user' ||
168
+ meta.principalId !== actor ||
169
+ meta.grantEpoch !== (context.principalEpoch ?? 'owner'))
170
+ )
171
+ fail('not_managed', 'Only your managed user worktrees can be removed', 1003);
172
+ const source = method === 'create' ? await realpath(origin.directory) : meta!.source;
173
+ const mappingId = method === 'create' ? p.mappingId : meta!.mappingId;
174
+ const mapping = await approved(context, source, mappingId);
175
+ return registry.nativeMutation(
176
+ 'workspace.worktree.' + method,
177
+ { workspaceId: p.workspaceId, ...(method === 'create' ? { mappingId: p.mappingId } : {}) },
178
+ { actor: actor + ':' + (context.principalEpoch ?? 'owner'), requestId: p.requestId, ifRevision: p.ifRevision },
179
+ async (draft) => {
180
+ if (method === 'create') {
181
+ const id = 'wks_' + randomBytes(8).toString('hex');
182
+ const facts = await adapter.facts(source);
183
+ return {
184
+ method,
185
+ id,
186
+ requestId: p.requestId,
187
+ ifRevision: p.ifRevision,
188
+ directory: path.join(mapping.parent, id),
189
+ projectId: origin.projectId,
190
+ sourceWorkspaceId: origin.id,
191
+ source,
192
+ commonDir: mapping.commonDir,
193
+ mappingId,
194
+ principalId: actor,
195
+ grantEpoch: context.principalEpoch ?? 'owner',
196
+ branch: `alp/workspace/${id}`,
197
+ head: facts.head
198
+ };
199
+ }
200
+ if (w.directory !== path.join(mapping.parent, w.id) || w.canonical !== w.directory)
201
+ fail('identity_changed', 'Managed worktree path changed', 1003);
202
+ // Guard before journaling so ordinary safety refusals do not strand a prepared intent.
203
+ await guard(w.directory, async () => {
204
+ if (Object.values(draft.sessions).includes(w.id))
205
+ fail(
206
+ 'workspace_history',
207
+ 'Saved sessions reference this checkout; retain its files. This operation does not delete history.'
208
+ );
209
+ try {
210
+ await adapter.assertClean(w.directory);
211
+ } catch {
212
+ fail(
213
+ 'workspace_dirty',
214
+ 'Worktree has dirty, ignored, hidden-index or submodule data; preserve it before removal'
215
+ );
216
+ }
217
+ });
218
+ return { method, id: w.id, directory: w.directory, ...meta };
219
+ },
220
+ async (intent, draft) => {
221
+ await approved(context, intent.source, intent.mappingId);
222
+ if (
223
+ intent.principalId !== actor ||
224
+ intent.grantEpoch !== (context.principalEpoch ?? 'owner') ||
225
+ intent.directory !== path.join(mapping.parent, intent.id) ||
226
+ intent.commonDir !== mapping.commonDir
227
+ )
228
+ fail('identity_changed', 'Worktree journal identity changed', 1003);
229
+ if (method === 'create') {
230
+ const row = await adapter.inspect(intent.source, intent.directory, intent.branch);
231
+ if (!row) await adapter.create(intent.source, mapping.parent, intent.id, intent.branch, intent.head);
232
+ await clean(intent.source, intent.directory, intent.branch, intent.head);
233
+ await register(intent.directory);
234
+ const created: WorkspaceRecord = {
235
+ id: intent.id,
236
+ projectId: intent.projectId,
237
+ directory: intent.directory,
238
+ canonical: intent.directory,
239
+ labels: [],
240
+ createdAt: new Date().toISOString(),
241
+ worktree: {
242
+ kind: 'user',
243
+ sourceWorkspaceId: intent.sourceWorkspaceId,
244
+ source: intent.source,
245
+ commonDir: intent.commonDir,
246
+ gitDir: (await user_worktree.repositoryIdentity(intent.directory)).gitDir,
247
+ requestId: intent.requestId,
248
+ ifRevision: intent.ifRevision,
249
+ mappingId: intent.mappingId,
250
+ principalId: actor,
251
+ grantEpoch: context.principalEpoch ?? 'owner',
252
+ branch: intent.branch,
253
+ head: intent.head
254
+ }
255
+ };
256
+ draft.workspaces.push(created);
257
+ return { workspace: created };
258
+ }
259
+ const finish = async () => {
260
+ if (Object.values(draft.sessions).includes(intent.id))
261
+ fail(
262
+ 'workspace_history',
263
+ 'Saved sessions reference this checkout; retain its files. This operation does not delete history.'
264
+ );
265
+ const present = await lstat(intent.directory).catch((e: any) => {
266
+ if (e.code === 'ENOENT') return undefined;
267
+ throw e;
268
+ });
269
+ if (present) await adapter.remove(intent.source, intent.directory, intent.branch);
270
+ else if (await adapter.inspect(intent.source, intent.directory, intent.branch))
271
+ fail('outcome_unknown', 'Worktree removal needs reconciliation', 1005);
272
+ const removed = workspace(draft, intent.id);
273
+ removed.archivedAt = new Date().toISOString();
274
+ removed.pinnedAt = null;
275
+ removed.worktree!.removedAt = removed.archivedAt;
276
+ return { workspace: removed, filesRemoved: true, branchRetained: true };
277
+ };
278
+ const present = await lstat(intent.directory).catch((e: any) => {
279
+ if (e.code === 'ENOENT') return undefined;
280
+ throw e;
281
+ });
282
+ return present ? guard(intent.directory, finish) : finish();
283
+ }
284
+ );
285
+ }
286
+ };
287
+ }