@cueloop/daemon 0.1.0-alpha.7 → 0.1.0-alpha.71

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 (42) hide show
  1. package/package.json +33 -22
  2. package/src/api.test.ts +891 -50
  3. package/src/api.ts +849 -72
  4. package/src/capabilities.test.ts +57 -0
  5. package/src/capabilities.ts +77 -0
  6. package/src/client.test.ts +24 -0
  7. package/src/client.ts +459 -69
  8. package/src/curate.ts +109 -0
  9. package/src/daemon-version.test.ts +93 -0
  10. package/src/diff-hot-reload.test.ts +186 -0
  11. package/src/diff-watcher.ts +102 -0
  12. package/src/herdr-pane.test.ts +240 -0
  13. package/src/herdr-pane.ts +167 -0
  14. package/src/herdr-split.test.ts +106 -0
  15. package/src/herdr-split.ts +92 -0
  16. package/src/herdr-tab-store.test.ts +96 -0
  17. package/src/herdr-tab-store.ts +66 -0
  18. package/src/index.ts +8 -9
  19. package/src/interruptible-wait.test.ts +127 -0
  20. package/src/interruptible-wait.ts +66 -0
  21. package/src/main.ts +4 -1
  22. package/src/paths.ts +39 -0
  23. package/src/project-files.test.ts +124 -0
  24. package/src/project-files.ts +56 -0
  25. package/src/protocol.ts +79 -7
  26. package/src/retention.test.ts +182 -0
  27. package/src/retention.ts +122 -0
  28. package/src/review.test.ts +255 -28
  29. package/src/review.ts +164 -62
  30. package/src/server.test.ts +381 -39
  31. package/src/server.ts +322 -84
  32. package/src/share-blob.test.ts +112 -0
  33. package/src/share-blob.ts +55 -0
  34. package/src/single-instance.test.ts +38 -11
  35. package/src/store.conformance.test.ts +41 -0
  36. package/src/store.jsonl.test.ts +159 -0
  37. package/src/store.ts +261 -34
  38. package/src/testing/store-conformance.ts +194 -0
  39. package/src/validate.test.ts +174 -28
  40. package/src/validate.ts +226 -16
  41. package/src/version.ts +6 -0
  42. package/src/working-tree.ts +149 -0
@@ -1,7 +1,8 @@
1
1
  import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2
- import { mkdtempSync, rmSync } from "node:fs";
2
+ import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
+ import * as v from "valibot";
5
6
  import { DaemonServer } from "./server";
6
7
  import { DaemonClient, DaemonClientError } from "./client";
7
8
  import type { Artifact, WorkspaceKey } from "@cueloop/schema";
@@ -27,38 +28,51 @@ afterEach(() => {
27
28
 
28
29
  describe("socket round-trip", () => {
29
30
  test("ping and full session flow over the wire", async () => {
31
+ // Assert
30
32
  expect((await client.ping()).pid).toBe(process.pid);
31
- const s = await client.sessionCreate(WS, PLAN);
32
- expect(s.status).toBe("pending");
33
- await client.sessionAnnotate(s.id, {
33
+
34
+ // Act
35
+ const session = await client.sessionCreate(WS, PLAN);
36
+
37
+ // Assert
38
+ expect(session.status).toBe("pending");
39
+
40
+ // Act
41
+ await client.sessionAnnotate(session.id, {
34
42
  id: "a1",
35
43
  kind: "comment",
36
44
  anchor: { quote: "Body text", prefix: "", suffix: "." },
37
45
  body: "More detail please.",
38
46
  });
39
- const wait = client.sessionWait(s.id, 5_000);
40
- await client.sessionResolve(s.id, "request_changes", "Expand it.");
47
+ const wait = client.sessionWait(session.id, 5_000);
48
+
49
+ await client.sessionResolve(session.id, "request_changes", "Expand it.");
41
50
  const resolved = (await wait)!;
51
+
52
+ // Assert
42
53
  expect(resolved.verdict!.kind).toBe("request_changes");
43
54
  expect(resolved.verdict!.feedback).toContain("More detail please.");
44
55
  });
45
56
 
46
57
  test("errors carry codes across the wire", async () => {
47
- expect(client.sessionGet("nope")).rejects.toBeInstanceOf(DaemonClientError);
48
- try {
49
- await client.sessionGet("nope");
50
- } catch (e) {
51
- expect((e as DaemonClientError).code).toBe("not_found");
52
- }
58
+ await expect(client.sessionGet("nope")).rejects.toBeInstanceOf(DaemonClientError);
59
+ await expect(client.sessionGet("nope")).rejects.toHaveProperty("code", "not_found");
53
60
  });
54
61
 
55
62
  test("events push to subscribed connections only", async () => {
63
+ // Arrange
56
64
  const observer = await DaemonClient.connect({ home });
57
65
  const seen: string[] = [];
58
- observer.onEvent((e) => seen.push(e.event));
66
+
67
+ observer.onEvent((event) => seen.push(event.event));
59
68
  await observer.subscribe();
60
- const s = await client.sessionCreate(WS, PLAN);
61
- await client.sessionResolve(s.id, "approve", "");
69
+
70
+ // Act
71
+ const session = await client.sessionCreate(WS, PLAN);
72
+
73
+ await client.sessionResolve(session.id, "approve", "");
74
+
75
+ // Assert
62
76
  // events are pushed async over the socket; give the loop a beat
63
77
  await Bun.sleep(50);
64
78
  expect(seen).toContain("session.created");
@@ -66,49 +80,377 @@ describe("socket round-trip", () => {
66
80
  observer.close();
67
81
  });
68
82
 
83
+ test("an event names the history entry its change appended", async () => {
84
+ // Arrange
85
+ const observer = await DaemonClient.connect({ home });
86
+ const frames: Array<{ event: string; entryId?: string }> = [];
87
+
88
+ observer.onEvent((event) => frames.push(event));
89
+ await observer.subscribe();
90
+ const session = await client.sessionCreate(WS, PLAN);
91
+
92
+ // Act
93
+ const annotated = await client.sessionAnnotate(session.id, {
94
+ id: "a_evt",
95
+ kind: "comment",
96
+ anchor: { quote: "Plan", prefix: "", suffix: "" },
97
+ body: "hello",
98
+ });
99
+
100
+ await Bun.sleep(50);
101
+
102
+ // Assert: the update frame carries the comment entry's id
103
+ const updated = frames.find((frame) => frame.event === "session.updated");
104
+
105
+ expect(updated?.entryId).toBe(annotated.history!.entries.at(-1)!.id);
106
+ observer.close();
107
+ });
108
+
109
+ test("a non-owner removes only the comments of the author it acts as, and names itself", async () => {
110
+ // Arrange: the owner's and Ana's comments; an agent connection acting as Ana
111
+ const session = await client.sessionCreate(WS, PLAN);
112
+
113
+ await client.sessionAnnotate(session.id, {
114
+ id: "own",
115
+ kind: "comment",
116
+ anchor: { quote: "Plan", prefix: "", suffix: "" },
117
+ body: "mine",
118
+ });
119
+ await client.sessionAnnotate(session.id, {
120
+ id: "anas",
121
+ kind: "comment",
122
+ anchor: { quote: "Plan", prefix: "", suffix: "" },
123
+ body: "hers",
124
+ author: "SHA256:ana",
125
+ });
126
+ const anonymous = await DaemonClient.connect({ home, role: "agent" });
127
+ const agent = await DaemonClient.connect({ home, role: "agent", author: "SHA256:ana" });
128
+
129
+ // Act + Assert: an unbound connection removes nothing; a bound one never another author's
130
+ await expect(anonymous.sessionRemoveAnnotation(session.id, "own")).rejects.toHaveProperty(
131
+ "code",
132
+ "forbidden",
133
+ );
134
+ await expect(agent.sessionRemoveAnnotation(session.id, "own")).rejects.toHaveProperty(
135
+ "code",
136
+ "forbidden",
137
+ );
138
+ await expect(
139
+ agent.sessionSetParticipantName(session.id, "SHA256:bob", "Not Bob"),
140
+ ).rejects.toHaveProperty("code", "forbidden");
141
+
142
+ // Act: her own comment goes, and she names herself
143
+ const removed = await agent.sessionRemoveAnnotation(session.id, "anas");
144
+ const named = await agent.sessionSetParticipantName(session.id, "SHA256:ana", "Ana");
145
+
146
+ // Assert
147
+ expect(removed.annotations.map((annotation) => annotation.id)).toEqual(["own"]);
148
+ expect(removed.history!.entries.at(-1)).toMatchObject({
149
+ type: "comment-removed",
150
+ annotationId: "anas",
151
+ });
152
+ expect(named.participants).toContainEqual({ id: "SHA256:ana", provider: "ssh", name: "Ana" });
153
+ anonymous.close();
154
+ agent.close();
155
+ });
156
+
69
157
  test("malformed requests get structured errors and never wedge the daemon", async () => {
70
158
  // missing required params
71
- try {
72
- await client.request("session.create", { artifact: { type: "plan", content: "x" } });
73
- throw new Error("should have thrown");
74
- } catch (e) {
75
- expect((e as DaemonClientError).code).toBe("invalid_params");
76
- }
159
+ await expect(
160
+ client.request("session.create", { artifact: { type: "plan", content: "x" } }, v.object({})),
161
+ ).rejects.toHaveProperty("code", "invalid_params");
77
162
  // wrong types
78
- try {
79
- await client.request("session.wait", { id: 42 });
80
- throw new Error("should have thrown");
81
- } catch (e) {
82
- expect((e as DaemonClientError).code).toBe("invalid_params");
83
- }
163
+ await expect(client.request("session.wait", { id: 42 }, v.object({}))).rejects.toHaveProperty(
164
+ "code",
165
+ "invalid_params",
166
+ );
84
167
  // unknown method
85
- try {
86
- await client.request("session.nuke", {});
87
- throw new Error("should have thrown");
88
- } catch (e) {
89
- expect((e as DaemonClientError).code).toBe("unknown_method");
90
- }
168
+ await expect(client.request("session.nuke", {}, v.object({}))).rejects.toHaveProperty(
169
+ "code",
170
+ "unknown_method",
171
+ );
172
+ await Promise.all(
173
+ ["__proto__", "toString", "constructor"].map((method) =>
174
+ expect(client.request(method, {}, v.object({}))).rejects.toHaveProperty(
175
+ "code",
176
+ "unknown_method",
177
+ ),
178
+ ),
179
+ );
91
180
  // the daemon is still fully alive afterwards
92
- const s = await client.sessionCreate(WS, PLAN);
93
- expect((await client.sessionGet(s.id)).id).toBe(s.id);
181
+ const session = await client.sessionCreate(WS, PLAN);
182
+
183
+ expect((await client.sessionGet(session.id)).id).toBe(session.id);
94
184
  });
95
185
 
96
186
  test("meta fields survive the wire: herdrPane set on create comes back from get", async () => {
97
- const s = await client.sessionCreate(WS, {
187
+ // Act
188
+ const session = await client.sessionCreate(WS, {
98
189
  type: "plan",
99
190
  content: "# P",
100
191
  meta: { agent: "claude-code", herdrPane: "%7" },
101
192
  });
102
- const got = await client.sessionGet(s.id);
193
+ const got = await client.sessionGet(session.id);
194
+
195
+ // Assert
103
196
  expect(got.artifact.meta.herdrPane).toBe("%7");
104
197
  expect(got.artifact.meta.agent).toBe("claude-code");
105
198
  });
106
199
 
200
+ test("share-sync primitives round-trip: setShareId persists, mergeShared unions notes and identities by id", async () => {
201
+ // Given a shared session with one local note
202
+ const session = await client.sessionCreate(WS, PLAN);
203
+ const anchor = { quote: "Body text", prefix: "", suffix: "." };
204
+
205
+ await client.sessionSetShareId(session.id, "p_abc123xy");
206
+ await client.sessionAnnotate(session.id, { id: "a1", kind: "comment", anchor, body: "mine" });
207
+ expect((await client.sessionGet(session.id)).shareId).toBe("p_abc123xy");
208
+
209
+ // When a pull merges an update to the known id, a new collaborator note, and the collaborator's identity
210
+ const merged = await client.sessionMergeShared(session.id, {
211
+ annotations: [
212
+ {
213
+ id: "a1",
214
+ kind: "comment",
215
+ anchor,
216
+ body: "should not overwrite",
217
+ createdAt: "2026-01-01T00:00:00.000Z",
218
+ },
219
+ {
220
+ id: "a2",
221
+ kind: "comment",
222
+ anchor,
223
+ body: "theirs",
224
+ author: "SHA256:mate",
225
+ createdAt: "2026-01-01T00:00:00.000Z",
226
+ },
227
+ ],
228
+ participants: [{ id: "SHA256:mate", provider: "ssh", name: "Sam" }],
229
+ });
230
+
231
+ // Then notes union by id (existing a1 kept), and the participant registry carries the collaborator's name
232
+ expect(merged.annotations.map((annotation) => annotation.id).sort()).toEqual(["a1", "a2"]);
233
+ expect(merged.annotations.find((annotation) => annotation.id === "a1")!.body).toBe("mine");
234
+ expect(merged.annotations.find((annotation) => annotation.id === "a2")!.author).toBe(
235
+ "SHA256:mate",
236
+ );
237
+ expect(merged.participants).toEqual([{ id: "SHA256:mate", provider: "ssh", name: "Sam" }]);
238
+ });
239
+
240
+ test("mergeShared validates each annotation at the socket boundary", async () => {
241
+ // Given a session
242
+ const session = await client.sessionCreate(WS, PLAN);
243
+
244
+ // When a malformed annotation is merged, it is rejected at the wire boundary
245
+ // @ts-expect-error intentionally malformed annotation (empty id, missing fields)
246
+ const merge = client.sessionMergeShared(session.id, { annotations: [{ id: "" }] });
247
+
248
+ await expect(merge).rejects.toHaveProperty("code", "invalid_params");
249
+ });
250
+
251
+ test("session.delete removes a session over the wire", async () => {
252
+ // Given a created session
253
+ const session = await client.sessionCreate(WS, PLAN);
254
+
255
+ // When it is deleted
256
+ await client.sessionDelete(session.id);
257
+
258
+ // Then it is gone, and deleting an unknown id is a not_found error
259
+ await expect(client.sessionGet(session.id)).rejects.toBeInstanceOf(DaemonClientError);
260
+ await expect(client.sessionDelete("ses_missing")).rejects.toHaveProperty("code", "not_found");
261
+ });
262
+
107
263
  test("two clients see the same state (thin-renderer model)", async () => {
264
+ // Arrange
108
265
  const second = await DaemonClient.connect({ home });
109
- const s = await client.sessionCreate(WS, PLAN);
110
- const fromSecond = await second.sessionGet(s.id);
266
+
267
+ // Act
268
+ const session = await client.sessionCreate(WS, PLAN);
269
+ const fromSecond = await second.sessionGet(session.id);
270
+
271
+ // Assert
111
272
  expect(fromSecond.artifact.content).toBe(PLAN.content);
112
273
  second.close();
113
274
  });
114
275
  });
276
+
277
+ describe("ownership is proven, never declared", () => {
278
+ /** A wire frame as the daemon answers it: a result or a coded error. */
279
+ interface WireReply {
280
+ result?: unknown;
281
+ error?: { code: string };
282
+ }
283
+
284
+ /** The request body a bare socket sends: the primitive's params as the wire carries them. */
285
+ type WireParams = Parameters<typeof JSON.stringify>[0];
286
+
287
+ interface RawConnection {
288
+ call: (method: string, params: WireParams) => Promise<WireReply>;
289
+ close: () => void;
290
+ }
291
+
292
+ /** A bare socket that speaks the wire protocol without the client's handshake. */
293
+ async function rawConnection(): Promise<RawConnection> {
294
+ const pending = new Map<number, (frame: WireReply) => void>();
295
+ let buffered = "";
296
+ let nextId = 1;
297
+ const socket = await Bun.connect({
298
+ unix: join(home, "cueloop.sock"),
299
+ socket: {
300
+ data: (_socket, data) => {
301
+ buffered += data.toString();
302
+ const lines = buffered.split("\n");
303
+
304
+ buffered = lines.pop() ?? "";
305
+ for (const line of lines) {
306
+ const frame = JSON.parse(line);
307
+
308
+ if ("id" in frame) pending.get(frame.id)?.(frame);
309
+ }
310
+ },
311
+ },
312
+ });
313
+
314
+ return {
315
+ call: (method, params) =>
316
+ new Promise((resolve) => {
317
+ const id = nextId++;
318
+
319
+ pending.set(id, resolve);
320
+ socket.write(JSON.stringify({ id, method, params }) + "\n");
321
+ }),
322
+ close: () => socket.end(),
323
+ };
324
+ }
325
+
326
+ test("a connection that never proves ownership is a collaborator: it reads and comments, nothing more", async () => {
327
+ // Arrange
328
+ const session = await client.sessionCreate(WS, PLAN);
329
+ const raw = await rawConnection();
330
+
331
+ // Act + Assert
332
+ expect((await raw.call("session.get", { id: session.id })).error).toBeUndefined();
333
+ expect(
334
+ (
335
+ await raw.call("session.annotate", {
336
+ id: session.id,
337
+ annotation: {
338
+ id: "a_raw",
339
+ kind: "comment",
340
+ anchor: { quote: "Plan", prefix: "", suffix: "" },
341
+ body: "from a bare socket",
342
+ },
343
+ })
344
+ ).error,
345
+ ).toBeUndefined();
346
+ expect(
347
+ (await raw.call("session.resolve", { id: session.id, verdictKind: "approve", summary: "" }))
348
+ .error?.code,
349
+ ).toBe("forbidden");
350
+ expect((await raw.call("session.delete", { id: session.id })).error?.code).toBe("forbidden");
351
+ raw.close();
352
+ });
353
+
354
+ test("claiming ownership without the token is refused; the token grants it", async () => {
355
+ // Arrange
356
+ const raw = await rawConnection();
357
+
358
+ // Act + Assert: a bare claim, then a wrong token, both refused
359
+ expect((await raw.call("daemon.hello", { role: "owner" })).error?.code).toBe("forbidden");
360
+ expect((await raw.call("daemon.hello", { role: "owner", token: "nope" })).error?.code).toBe(
361
+ "forbidden",
362
+ );
363
+ expect((await raw.call("daemon.shutdown", {})).error?.code).toBe("forbidden");
364
+
365
+ // Act: the token the daemon wrote into its home
366
+ const token = readFileSync(join(home, "owner.token"), "utf8").trim();
367
+
368
+ expect((await raw.call("daemon.hello", { role: "owner", token })).error).toBeUndefined();
369
+
370
+ // Assert: owner primitives open up
371
+ const created = await raw.call("session.create", { workspace: WS, artifact: PLAN });
372
+
373
+ expect(created.error).toBeUndefined();
374
+ raw.close();
375
+ });
376
+
377
+ test("a refused handshake reaches the caller and leaves the live daemon's socket alone", async () => {
378
+ // Arrange: a token file that is not what the daemon minted
379
+ const tokenPath = join(home, "owner.token");
380
+ const minted = readFileSync(tokenPath, "utf8");
381
+
382
+ writeFileSync(tokenPath, "0".repeat(64));
383
+
384
+ // Act + Assert: the client hears the refusal; autostart does not replace the daemon
385
+ await expect(DaemonClient.connect({ home, autostart: true })).rejects.toHaveProperty(
386
+ "code",
387
+ "forbidden",
388
+ );
389
+ expect(existsSync(join(home, "cueloop.sock"))).toBe(true);
390
+ expect((await client.sessionList()).length).toBe(0);
391
+
392
+ // Arrange: a token file that is not a token at all
393
+ writeFileSync(tokenPath, "not-a-token");
394
+
395
+ // Act + Assert
396
+ await expect(DaemonClient.connect({ home })).rejects.toHaveProperty(
397
+ "code",
398
+ "invalid_owner_token",
399
+ );
400
+ writeFileSync(tokenPath, minted);
401
+ });
402
+
403
+ test("the token exists before the socket does", () => {
404
+ // Arrange: a second daemon in another home
405
+ const other = mkdtempSync(join(tmpdir(), "cueloop-token-"));
406
+ const daemon = new DaemonServer({ home: other, idleExitMs: 0 });
407
+
408
+ try {
409
+ // Act
410
+ daemon.start();
411
+
412
+ // Assert: the token is on disk the moment the socket is
413
+ expect(existsSync(join(other, "owner.token"))).toBe(true);
414
+ expect(existsSync(join(other, "cueloop.sock"))).toBe(true);
415
+ } finally {
416
+ daemon.stop();
417
+ rmSync(other, { recursive: true, force: true });
418
+ }
419
+ });
420
+
421
+ test("the daemon client proves ownership on connect and the token is private to the home", async () => {
422
+ // Assert: the client in beforeEach connected as the owner through the token
423
+ const session = await client.sessionCreate(WS, PLAN);
424
+
425
+ expect((await client.sessionResolve(session.id, "approve", "")).status).toBe("resolved");
426
+ expect(statSync(join(home, "owner.token")).mode & 0o777).toBe(0o600);
427
+ });
428
+ });
429
+
430
+ describe("large payloads survive socket backpressure", () => {
431
+ test("a session bigger than the kernel socket buffer round-trips", async () => {
432
+ // Regression: responses larger than one socket write used to truncate
433
+ // mid-line because the write return value was ignored, so the client
434
+ // never saw the frame's newline and every later request wedged too.
435
+ // Arrange
436
+ const bigContent =
437
+ "# Big plan\n" + "lorem ipsum dolor sit amet, consectetur adipiscing elit\n".repeat(4000);
438
+
439
+ // Act
440
+ const created = await client.sessionCreate(
441
+ { repoRoot: "/repo", branch: "main" },
442
+ { type: "plan", content: bigContent, meta: { title: "big" } },
443
+ );
444
+ const fetched = await client.sessionGet(created.id);
445
+
446
+ // Assert
447
+ expect(fetched.artifact.content).toBe(bigContent);
448
+
449
+ // Act
450
+ // the connection must still be usable for the next frame
451
+ const listed = await client.sessionList();
452
+
453
+ // Assert
454
+ expect(listed.some((session) => session.id === created.id)).toBe(true);
455
+ }, 15_000);
456
+ });