@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
package/src/store.ts CHANGED
@@ -1,10 +1,23 @@
1
- import { appendFile, mkdir, open, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
1
+ import { createHistoryIndex } from './history.js';
2
+ import { appendFile, mkdir, open, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
2
3
  import { replaceFile } from './lock.js';
3
4
  import { randomBytes } from 'node:crypto';
4
5
  import path from 'node:path';
5
6
  import { createLogger } from '@anhlp/alp-core/log';
6
7
  import type { Envelope, SessionSnapshot, SessionSpec } from '@anhlp/alp-runtime/index';
7
8
  import type { SessionError, SessionStatus } from '@anhlp/alp-protocol/session';
9
+ import type { TurnAttention } from '@anhlp/alp-protocol/events';
10
+ import type { ConversationBranch, ForkProvenance, NativeBase } from '@anhlp/alp-protocol/session';
11
+
12
+ /** A branch a rewind set aside (§12.7): its public description, the native conversation and where its timeline lies. */
13
+ export type StoredBranch = ConversationBranch & {
14
+ /** The native conversation the root continued before the rewind: never deleted, so the branch stays recoverable. */
15
+ threadId: string;
16
+ base?: NativeBase;
17
+ /** The first discarded cursor, and the rewind's marker cursor (the branch holds what lay between). */
18
+ cut: number;
19
+ marker: number;
20
+ };
8
21
 
9
22
  /**
10
23
  * alpd's durable state (plans/reference/ALPD.md §5, §66): one JSON record per session,
@@ -30,6 +43,18 @@ export type SessionRecord = {
30
43
  title?: string;
31
44
  /** Set aside by the user: closed, and listed only when asked (ALPD §61). */
32
45
  archived?: boolean;
46
+ /** A root's last turn that ended unseen, until a client acknowledges it or another turn starts (Paseo's requiresAttention). */
47
+ attention?: TurnAttention;
48
+ /** Claude: the conversation `session.threadId` is made from on its first prompt, after a fork or rewind (§12.7). */
49
+ base?: NativeBase;
50
+ /** Where this root was forked from (§12.7). */
51
+ forkedFrom?: ForkProvenance;
52
+ /** Stable creation ownership; current native binding/title may change after a fork. */
53
+ forkAttempt?: { key: string; attemptId?: string; createdAt: string; fingerprint: string };
54
+ /** Branches rewinds set aside, oldest first (§12.7). */
55
+ branches?: StoredBranch[];
56
+ /** Atomic proof of completed conversation commits whose journal marker may be missing. */
57
+ lifecycleCommits?: Record<string, { operation: string; requestId: string; createdAt: string; fingerprint: string; attemptId?: string; result: any }>;
33
58
  createdAt: string;
34
59
  updatedAt: string;
35
60
  };
@@ -69,6 +94,7 @@ export type Store = ReturnType<typeof createStore>;
69
94
  export function createStore(root: string) {
70
95
  const sessionsDir = path.join(root, 'sessions');
71
96
  const timelineDir = path.join(root, 'timeline');
97
+ const historyIndexes = new Map<string, ReturnType<typeof createHistoryIndex>>();
72
98
  const receiptsDir = path.join(root, 'receipts');
73
99
  const writes = new Map<string, Promise<void>>();
74
100
  const appends = new Map<string, Promise<void>>();
@@ -167,8 +193,12 @@ export function createStore(root: string) {
167
193
  }
168
194
 
169
195
  const receiptFile = (key: string) => path.join(receiptsDir, `${fileName(key)}.json`);
196
+ const branchFile = (rootId: string, branchId: string) => path.join(timelineDir, `${fileName(rootId)}.branch-${fileName(branchId)}.jsonl`);
170
197
 
171
198
  return {
199
+ /** The state directory this store keeps its files in. */
200
+ root,
201
+
172
202
  put(record: SessionRecord) {
173
203
  const file = path.join(sessionsDir, `${fileName(record.id)}.json`);
174
204
  const body = JSON.stringify(record);
@@ -241,6 +271,13 @@ export function createStore(root: string) {
241
271
  }
242
272
  },
243
273
 
274
+ /** Authoritative record after queued writes, including failed writes (which do not prove completion). */
275
+ async get(id: string): Promise<SessionRecord | undefined> {
276
+ await writes.get(id)?.catch(() => {});
277
+ try { return JSON.parse(await readFile(path.join(sessionsDir, `${fileName(id)}.json`), 'utf8')); }
278
+ catch (error: any) { if (error?.code === 'ENOENT') return undefined; throw error; }
279
+ },
280
+
244
281
  async list(): Promise<SessionRecord[]> {
245
282
  await prepare();
246
283
  const records: SessionRecord[] = [];
@@ -267,6 +304,78 @@ export function createStore(root: string) {
267
304
  }, true, { rootId });
268
305
  },
269
306
 
307
+ async history(rootId: string, sessionId: string, options: { before?: string; limit?: number; maxBytes?: number } = {}) {
308
+ await prepare();
309
+ await appends.get(rootId);
310
+ let index = historyIndexes.get(rootId);
311
+ if (!index) { index = createHistoryIndex(path.join(timelineDir, `${fileName(rootId)}.jsonl`)); historyIndexes.set(rootId, index); }
312
+ return index.page(sessionId, options);
313
+ },
314
+
315
+ /**
316
+ * Rewinds a tree's timeline (§12.7), idempotently: the whole timeline moves to the branch file
317
+ * `<root>.branch-<id>.jsonl`, and the root's timeline becomes its lines before `cut`, the root's own
318
+ * session lifecycle lines after it (opened, updated, closed: not conversation), `marker`, and any line
319
+ * whose cursor follows the marker's, in cursor order. Runs in
320
+ * the tree's append queue, so no append lands in between. A crash leaves the old timeline, or the
321
+ * branch and the new one beside it (finished by the next call); the history index is rebuilt with a
322
+ * new generation, so every older history cursor is stale.
323
+ */
324
+ rewind(rootId: string, { cut, branchId, marker }: { cut: number; branchId: string; marker: Envelope }) {
325
+ const file = path.join(timelineDir, `${fileName(rootId)}.jsonl`);
326
+ const branch = branchFile(rootId, branchId);
327
+ const temporary = `${file}.rewind-${fileName(branchId)}.tmp`;
328
+ return queue(appends, rootId, `timeline rewind ${rootId}`, async () => {
329
+ const exists = (target: string) => stat(target).then(() => true, (error: any) => { if (error?.code === 'ENOENT') return false; throw error; });
330
+ if (!await exists(branch)) {
331
+ if (!repaired.has(rootId)) { await repairTail(file); repaired.add(rootId); }
332
+ const text = await readFile(file, 'utf8').catch((error: any) => { if (error?.code === 'ENOENT') return ''; throw error; });
333
+ const kept: Array<{ cursor: number; line: string }> = [];
334
+ const markerCursor = marker.cursor ?? Number.MAX_SAFE_INTEGER;
335
+ let cursor = 0;
336
+ for (const line of text.split('\n')) {
337
+ if (!line) continue;
338
+ let envelope: Envelope;
339
+ try { envelope = JSON.parse(line); } catch { continue; }
340
+ cursor = typeof envelope.cursor === 'number' && envelope.cursor > cursor ? envelope.cursor : cursor + 1;
341
+ const lifecycle = envelope.sessionId === rootId && ['session.opened', 'session.ready', 'session.updated', 'session.closed', 'session.failed'].includes(envelope.event?.type);
342
+ // Before the cut: the kept conversation. Between the cut and the marker: only the root's own
343
+ // lifecycle. After the marker (an event kept while the rewind waited for this queue): the new
344
+ // conversation's. A line kept past the cut carries its cursor, so cursors stay what clients saw.
345
+ if (cursor < cut) kept.push({ cursor, line });
346
+ else if (lifecycle || cursor > markerCursor) kept.push({ cursor, line: JSON.stringify({ ...envelope, cursor }) });
347
+ }
348
+ kept.push({ cursor: markerCursor, line: JSON.stringify(marker) });
349
+ kept.sort((a, b) => a.cursor - b.cursor);
350
+ await writeFile(temporary, `${kept.map(entry => entry.line).join('\n')}\n`, { mode: 0o600 });
351
+ if (await exists(file)) await rename(file, branch);
352
+ else await writeFile(branch, '', { mode: 0o600 });
353
+ }
354
+ if (await exists(temporary)) await rename(temporary, file);
355
+ await Promise.all(['.jsonl.idx', '.jsonl.history.json'].map(suffix => rm(path.join(timelineDir, `${fileName(rootId)}${suffix}`), { force: true })));
356
+ historyIndexes.delete(rootId);
357
+ repaired.add(rootId);
358
+ }, false, { rootId });
359
+ },
360
+
361
+ /** Writes a new tree's whole timeline at once (a fork's, §12.7); written again whole by a repeat. */
362
+ createTimeline(rootId: string, envelopes: Envelope[]) {
363
+ const file = path.join(timelineDir, `${fileName(rootId)}.jsonl`);
364
+ return queue(appends, rootId, `timeline ${rootId}`, async () => {
365
+ await writeAtomic(file, envelopes.map(envelope => `${JSON.stringify(envelope)}\n`).join(''));
366
+ await Promise.all(['.jsonl.idx', '.jsonl.history.json'].map(suffix => rm(path.join(timelineDir, `${fileName(rootId)}${suffix}`), { force: true })));
367
+ historyIndexes.delete(rootId);
368
+ repaired.add(rootId);
369
+ }, false, { rootId });
370
+ },
371
+
372
+ /** The timeline of a branch a rewind set aside; empty when it is not there. */
373
+ async branchTimeline(rootId: string, branchId: string): Promise<Envelope[]> {
374
+ await appends.get(rootId);
375
+ try { return parseTimeline(await readFile(branchFile(rootId, branchId), 'utf8'), path.basename(branchFile(rootId, branchId))); }
376
+ catch (error: any) { if (error?.code === 'ENOENT') return []; throw error; }
377
+ },
378
+
270
379
  async timeline(rootId: string): Promise<Envelope[]> {
271
380
  await appends.get(rootId);
272
381
  const name = `${fileName(rootId)}.jsonl`;
@@ -317,15 +426,18 @@ export function createStore(root: string) {
317
426
  return { ...health, ...(health.lastError ? { lastError: { ...health.lastError } } : {}) };
318
427
  },
319
428
 
320
- /** Removes a whole tree: its records and its timeline. */
429
+ /** Removes a whole tree: its records, its timeline and the branches rewinds set aside. */
321
430
  async remove(rootId: string, ids: string[]) {
322
431
  await Promise.all([...ids.map(id => writes.get(id)), appends.get(rootId)]);
432
+ const branches = (await readdir(timelineDir).catch(() => [] as string[])).filter(name => name.startsWith(`${fileName(rootId)}.branch-`));
323
433
  await Promise.all([
324
434
  ...ids.map(id => rm(path.join(sessionsDir, `${fileName(id)}.json`), { force: true })),
325
- rm(path.join(timelineDir, `${fileName(rootId)}.jsonl`), { force: true }),
435
+ ...['.jsonl', '.jsonl.idx', '.jsonl.history.json'].map(suffix => rm(path.join(timelineDir, `${fileName(rootId)}${suffix}`), { force: true })),
436
+ ...branches.map(name => rm(path.join(timelineDir, name), { force: true })),
326
437
  ]);
327
438
  for (const id of ids) failed.delete(id);
328
439
  failed.delete(`timeline:${rootId}`);
440
+ historyIndexes.delete(rootId);
329
441
  repaired.delete(rootId);
330
442
  },
331
443