@cueloop/daemon 0.1.0-alpha.8 → 0.1.0-alpha.81

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 (56) hide show
  1. package/package.json +37 -22
  2. package/src/api.test.ts +940 -65
  3. package/src/api.ts +1095 -88
  4. package/src/capabilities.test.ts +57 -0
  5. package/src/capabilities.ts +89 -0
  6. package/src/client.test.ts +24 -0
  7. package/src/client.ts +669 -86
  8. package/src/curate.ts +109 -0
  9. package/src/daemon-version.test.ts +93 -0
  10. package/src/diff-hot-reload.test.ts +272 -0
  11. package/src/diff-watcher.ts +274 -0
  12. package/src/gh.ts +37 -0
  13. package/src/ghostty-thread-surface-store.test.ts +49 -0
  14. package/src/ghostty-thread-surface-store.ts +101 -0
  15. package/src/ghostty-thread-surface.test.ts +398 -0
  16. package/src/ghostty-thread-surface.ts +267 -0
  17. package/src/harness-delivery.test.ts +208 -0
  18. package/src/harness-state-store.test.ts +65 -0
  19. package/src/harness-state-store.ts +181 -0
  20. package/src/herdr-split.test.ts +106 -0
  21. package/src/herdr-split.ts +92 -0
  22. package/src/herdr-thread-surface-store.test.ts +81 -0
  23. package/src/herdr-thread-surface-store.ts +64 -0
  24. package/src/herdr-thread-surface.test.ts +411 -0
  25. package/src/herdr-thread-surface.ts +355 -0
  26. package/src/index.ts +8 -9
  27. package/src/interruptible-wait.test.ts +127 -0
  28. package/src/interruptible-wait.ts +66 -0
  29. package/src/main.ts +4 -1
  30. package/src/paths.ts +49 -0
  31. package/src/pr-poller.test.ts +76 -0
  32. package/src/pr-poller.ts +74 -0
  33. package/src/project-files.test.ts +124 -0
  34. package/src/project-files.ts +56 -0
  35. package/src/protocol.ts +79 -7
  36. package/src/retention.test.ts +191 -0
  37. package/src/retention.ts +123 -0
  38. package/src/server.test.ts +432 -42
  39. package/src/server.ts +423 -89
  40. package/src/share-blob.test.ts +112 -0
  41. package/src/share-blob.ts +55 -0
  42. package/src/single-instance.test.ts +162 -13
  43. package/src/store.conformance.test.ts +41 -0
  44. package/src/store.jsonl.test.ts +159 -0
  45. package/src/store.ts +264 -34
  46. package/src/testing/store-conformance.ts +194 -0
  47. package/src/thread-review.test.ts +394 -0
  48. package/src/thread-review.ts +314 -0
  49. package/src/thread-surface-config.test.ts +63 -0
  50. package/src/thread-surface-config.ts +61 -0
  51. package/src/validate.test.ts +214 -35
  52. package/src/validate.ts +306 -25
  53. package/src/version.ts +6 -0
  54. package/src/working-tree.ts +149 -0
  55. package/src/review.test.ts +0 -167
  56. package/src/review.ts +0 -174
package/src/api.ts CHANGED
@@ -1,200 +1,1207 @@
1
1
  /**
2
- * The daemon's method surface (#14). Transport-independent: the socket
2
+ * The daemon's method surface. Transport-independent: the socket
3
3
  * server and the in-process test harness both call these handlers.
4
- * The wait contract: verdicts outlive waits - session.wait long-polls,
5
- * and a verdict resolved while nobody waited is delivered on next contact.
4
+ * The wait contract: messages outlive waits - session.wait long-polls,
5
+ * and a message resolved while nobody waited is delivered on next contact.
6
6
  */
7
7
 
8
8
  import {
9
9
  SCHEMA_VERSION,
10
+ appendEntry,
11
+ applyPathView,
12
+ createBranch,
13
+ cutBlock,
10
14
  feedbackForSession,
11
- verdictAllows,
15
+ forkHistory,
16
+ historyFromLinear,
17
+ HistoryError,
18
+ labelTip,
19
+ navigateTo,
20
+ recaptureMainHead,
21
+ viewOfPath,
22
+ isAddressed,
23
+ isAgentNote,
24
+ annotationTarget,
25
+ isMarkdownArtifact,
26
+ MAIN_BRANCH,
27
+ parseBlocks,
28
+ registerParticipant,
29
+ resolveAnchor,
30
+ newMessageId,
31
+ isBlockCut,
32
+ restoreBlock,
33
+ switchBranch,
34
+ messageAllows,
12
35
  type Annotation,
36
+ type DiffFileStatus,
37
+ type DiffFileContents,
38
+ type HunkRejection,
39
+ type NewEntry,
13
40
  type Artifact,
14
- type ReviewSession,
15
- type Verdict,
16
- type VerdictKind,
41
+ type ShareLink,
42
+ type Identity,
43
+ type HarnessBinding,
44
+ type Delivery,
45
+ type PendingDelivery,
46
+ type Thread,
47
+ type SessionHistory,
48
+ type Message,
49
+ type MessageOutcome,
17
50
  type WorkspaceKey,
18
51
  } from "@cueloop/schema";
19
- import { SessionStore } from "./store";
52
+ import { curateDiff } from "./curate";
53
+ import { ThreadStore, withHistory } from "./store";
54
+ import { pruneExpiredSessions, resolveCleanupPeriodDays } from "./retention";
55
+ import {
56
+ HerdrThreadSurfaceStore,
57
+ type HerdrThreadSurfaceHandle,
58
+ } from "./herdr-thread-surface-store";
59
+ import {
60
+ GhosttyThreadSurfaceStore,
61
+ type GhosttyThreadSurfaceHandle,
62
+ } from "./ghostty-thread-surface-store";
63
+ import { HarnessStateStore } from "./harness-state-store";
64
+ import { DiffWatcher } from "./diff-watcher";
65
+ import { PrReviewPoller } from "./pr-poller";
66
+ import { prDiff } from "./gh";
67
+ import { workingTreeDiff, workingChangeList, type WorkingTreeDiff } from "./working-tree";
68
+ import { listProjectFiles, readProjectFile } from "./project-files";
69
+ import { resolveWorkspace } from "./thread-review";
20
70
  import { DaemonError } from "./errors";
21
71
 
72
+ /** What a share hands back: the notes and names it collected, and the removals it recorded. */
73
+ export interface SharedMerge {
74
+ annotations: Annotation[];
75
+ participants?: Identity[];
76
+ /** Removal entries by id; a merge applies each once and never rewrites what it already holds. */
77
+ removals?: Array<{ id: string; annotationId: string; createdAt: string }>;
78
+ }
79
+
22
80
  export type EventName =
23
81
  | "session.created"
24
82
  | "session.updated"
25
- | "session.resolved"
83
+ | "message.sent"
26
84
  | "session.revised"
27
85
  | "inbox.changed";
28
86
 
29
87
  export interface DaemonEvent {
30
88
  event: EventName;
31
89
  sessionId: string;
90
+ /** The history entry the change appended, when it appended one. */
91
+ entryId?: string;
32
92
  }
33
93
 
34
- type EventListener = (e: DaemonEvent) => void;
94
+ type EventListener = (event: DaemonEvent) => void;
35
95
 
36
96
  export class DaemonCore {
37
- readonly store: SessionStore;
38
- private waiters = new Map<string, ((session: ReviewSession) => void)[]>();
97
+ readonly store: ThreadStore;
98
+ readonly herdrThreadSurfaces: HerdrThreadSurfaceStore;
99
+ readonly ghosttyThreadSurfaces: GhosttyThreadSurfaceStore;
100
+ readonly harnessState: HarnessStateStore;
101
+ private waiters = new Map<string, ((session: Thread) => void)[]>();
39
102
  private listeners = new Set<EventListener>();
40
103
  private seq = 0;
104
+ /** Drives diff hot-reload: watches each live diff session's repo for working-tree changes. */
105
+ private readonly diffWatcher: DiffWatcher;
106
+ /** Drives PR-review hot-reload: polls each open PR review for a moved head. */
107
+ private readonly prPoller: PrReviewPoller;
108
+ /**
109
+ * Per-diff-session capture generation. Bumped when a refresh begins; a
110
+ * capture whose generation is stale by the time it finishes discards its
111
+ * result, so overlapping captures never write an older patch over a newer one.
112
+ */
113
+ private readonly diffRefreshGenerations = new Map<string, number>();
114
+ /** In-flight workbench creations keyed by project, so concurrent bare launches share one thread. */
115
+ private readonly workbenchCreation = new Map<string, Promise<Thread>>();
41
116
 
42
117
  constructor(home: string) {
43
- this.store = new SessionStore(home);
118
+ this.store = new ThreadStore(home);
44
119
  this.store.recover();
120
+ this.harnessState = new HarnessStateStore(home);
121
+ for (const session of this.store.list()) this.reconcileDeliveries(session);
122
+ this.herdrThreadSurfaces = new HerdrThreadSurfaceStore(home);
123
+ this.ghosttyThreadSurfaces = new GhosttyThreadSurfaceStore(home);
124
+ const expiredThreadIds = pruneExpiredSessions(
125
+ this.store,
126
+ resolveCleanupPeriodDays(),
127
+ Date.now(),
128
+ this.harnessState.pendingThreadIds(),
129
+ );
130
+
131
+ for (const threadId of expiredThreadIds) {
132
+ this.herdrThreadSurfaces.delete(threadId);
133
+ this.ghosttyThreadSurfaces.delete(threadId);
134
+ }
135
+ this.diffWatcher = new DiffWatcher((repoRoot) => void this.refreshDiffsForRepo(repoRoot));
136
+ this.prPoller = new PrReviewPoller((sessionId) => void this.sessionRefreshPrDiff(sessionId));
137
+ // resume hot-reload for diff sessions that survived a daemon restart
138
+ for (const session of this.store.list()) {
139
+ this.trackLiveDiffSession(session);
140
+ }
141
+ }
142
+
143
+ /** Release the watchers and pollers behind diff hot-reload; call on daemon shutdown. */
144
+ dispose(): void {
145
+ this.diffWatcher.close();
146
+ this.prPoller.close();
147
+ }
148
+
149
+ /** The Herdr Thread surface handle, kept outside the canonical Thread. */
150
+ herdrGetThreadSurface(sessionId: string): HerdrThreadSurfaceHandle | null {
151
+ return this.herdrThreadSurfaces.get(sessionId);
152
+ }
153
+
154
+ herdrSetThreadSurface(sessionId: string, handle: HerdrThreadSurfaceHandle): void {
155
+ this.herdrThreadSurfaces.set(sessionId, handle);
156
+ }
157
+
158
+ ghosttyGetThreadSurface(sessionId: string): GhosttyThreadSurfaceHandle | null {
159
+ return this.ghosttyThreadSurfaces.get(sessionId);
160
+ }
161
+
162
+ ghosttySetThreadSurface(sessionId: string, handle: GhosttyThreadSurfaceHandle): void {
163
+ this.ghosttyThreadSurfaces.set(sessionId, handle);
164
+ }
165
+
166
+ ghosttyClaimThreadSurface(sessionId: string): boolean {
167
+ return this.ghosttyThreadSurfaces.claim(sessionId);
168
+ }
169
+
170
+ ghosttyReleaseThreadSurface(sessionId: string): void {
171
+ this.ghosttyThreadSurfaces.release(sessionId);
172
+ }
173
+
174
+ harnessBind(input: {
175
+ threadId: string;
176
+ harness: string;
177
+ harnessSessionId: string;
178
+ }): HarnessBinding {
179
+ this.sessionGet(input.threadId);
180
+ const binding = this.harnessState.bind(input);
181
+
182
+ this.reconcileDeliveries(this.sessionGet(input.threadId));
183
+
184
+ return binding;
185
+ }
186
+
187
+ harnessGetBinding(bindingId: string): HarnessBinding {
188
+ const binding = this.harnessState.binding(bindingId);
189
+
190
+ if (!binding) throw new DaemonError("not_found", `no harness binding ${bindingId}`);
191
+
192
+ return binding;
193
+ }
194
+
195
+ harnessBindingsForSession(harness: string, harnessSessionId: string): HarnessBinding[] {
196
+ return this.harnessState.bindingsForSession(harness, harnessSessionId);
197
+ }
198
+
199
+ harnessConsumeApprovedRetry(bindingId: string, messageId: string, content: string): boolean {
200
+ const binding = this.harnessState.binding(bindingId);
201
+
202
+ if (!binding) throw new DaemonError("not_found", `no harness binding ${bindingId}`);
203
+ const session = this.sessionGet(binding.threadId);
204
+
205
+ if (
206
+ session.artifact.type !== "plan" ||
207
+ session.status !== "resolved" ||
208
+ session.message?.id !== messageId ||
209
+ session.message.outcome !== "approved" ||
210
+ session.artifact.content !== content ||
211
+ this.harnessState.submittingBinding(session.id)?.id !== bindingId ||
212
+ !this.harnessState.acknowledged(bindingId, messageId)
213
+ ) {
214
+ throw new DaemonError("invalid_state", `no unchanged approved plan for ${bindingId}`);
215
+ }
216
+
217
+ return this.harnessState.consumeApprovedRetry(bindingId, messageId);
218
+ }
219
+
220
+ deliveryPending(bindingId: string): PendingDelivery[] {
221
+ const binding = this.harnessState.binding(bindingId);
222
+
223
+ if (!binding) throw new DaemonError("not_found", `no harness binding ${bindingId}`);
224
+ const session = this.sessionGet(binding.threadId);
225
+
226
+ return this.harnessState.pending(bindingId).map((delivery) => {
227
+ const historical = session.history?.entries.find(
228
+ (entry) => entry.type === "message" && entry.message.id === delivery.messageId,
229
+ );
230
+ const message =
231
+ session.message?.id === delivery.messageId
232
+ ? session.message
233
+ : historical?.type === "message"
234
+ ? historical.message
235
+ : null;
236
+
237
+ if (!message || message.id !== delivery.messageId) {
238
+ throw new DaemonError("not_found", `no message ${delivery.messageId}`);
239
+ }
240
+
241
+ return { delivery, message };
242
+ });
243
+ }
244
+
245
+ deliveryAcknowledge(deliveryId: string): Delivery {
246
+ if (!this.harnessState.delivery(deliveryId)) {
247
+ throw new DaemonError("not_found", `no delivery ${deliveryId}`);
248
+ }
249
+
250
+ return this.harnessState.acknowledge(deliveryId);
45
251
  }
46
252
 
47
253
  onEvent(listener: EventListener): () => void {
48
254
  this.listeners.add(listener);
255
+
49
256
  return () => this.listeners.delete(listener);
50
257
  }
51
258
 
52
- private emit(event: EventName, sessionId: string): void {
53
- for (const l of this.listeners) l({ event, sessionId });
259
+ private emit(event: EventName, sessionId: string, entryId?: string): void {
260
+ const frame: DaemonEvent =
261
+ entryId === undefined ? { event, sessionId } : { event, sessionId, entryId };
262
+
263
+ for (const listener of this.listeners) listener(frame);
54
264
  }
55
265
 
56
- /** True when nothing awaits a verdict - drives idle-exit. */
266
+ /** True when nothing awaits a message - drives idle-exit. */
57
267
  hasPendingSessions(): boolean {
58
- return this.store.list().some((s) => s.status === "pending");
268
+ return this.store.list().some((session) => session.status === "pending");
59
269
  }
60
270
 
61
- sessionCreate(params: { workspace: WorkspaceKey; artifact: Artifact }): ReviewSession {
271
+ sessionCreate(params: { workspace: WorkspaceKey; artifact: Artifact }): Thread {
62
272
  const now = new Date().toISOString();
63
- const session: ReviewSession = {
273
+ const session: Thread = {
64
274
  schemaVersion: SCHEMA_VERSION,
65
- id: `ses_${now.replace(/\D/g, "").slice(0, 14)}_${(++this.seq).toString(36)}${Math.random().toString(36).slice(2, 6)}`,
275
+ id: this.newSessionId(now),
66
276
  workspace: params.workspace,
67
277
  artifact: params.artifact,
68
278
  revisions: [{ revision: 1, content: params.artifact.content, submittedAt: now }],
69
279
  annotations: [],
70
- verdict: null,
280
+ message: null,
71
281
  status: "pending",
72
282
  createdAt: now,
73
283
  };
284
+
285
+ session.history = historyFromLinear(session);
74
286
  this.store.upsert(session);
287
+ this.reconcileDeliveries(session);
288
+ this.trackLiveDiffSession(session);
75
289
  this.emit("session.created", session.id);
76
290
  this.emit("inbox.changed", session.id);
291
+
77
292
  return session;
78
293
  }
79
294
 
80
- sessionGet(id: string): ReviewSession {
81
- const s = this.store.get(id);
82
- if (!s) throw new DaemonError("not_found", `no session ${id}`);
83
- return s;
295
+ private reconcileDeliveries(session: Thread): void {
296
+ if (!session.message) return;
297
+
298
+ const binding = this.harnessState.submittingBinding(session.id);
299
+
300
+ if (binding)
301
+ this.harnessState.enqueue({ bindingId: binding.id, messageId: session.message.id });
302
+ }
303
+
304
+ private newSessionId(now: string): string {
305
+ return `ses_${now.replace(/\D/g, "").slice(0, 14)}_${(++this.seq).toString(36)}${Math.random().toString(36).slice(2, 6)}`;
306
+ }
307
+
308
+ sessionGet(id: string): Thread {
309
+ const session = this.store.get(id);
310
+
311
+ if (!session) throw new DaemonError("not_found", `no session ${id}`);
312
+
313
+ return session;
84
314
  }
85
315
 
86
- sessionList(filter?: { status?: "pending" | "resolved"; workspace?: Partial<WorkspaceKey> }): ReviewSession[] {
87
- return this.store.list().filter((s) => {
88
- if (filter?.status && s.status !== filter.status) return false;
89
- if (filter?.workspace?.repoRoot && s.workspace.repoRoot !== filter.workspace.repoRoot) return false;
90
- if (filter?.workspace?.branch && s.workspace.branch !== filter.workspace.branch) return false;
316
+ sessionList(filter?: {
317
+ status?: "pending" | "resolved";
318
+ workspace?: Partial<WorkspaceKey>;
319
+ }): Thread[] {
320
+ return this.store.list().filter((session) => {
321
+ if (filter?.status && session.status !== filter.status) return false;
322
+ if (filter?.workspace?.repoRoot && session.workspace.repoRoot !== filter.workspace.repoRoot)
323
+ return false;
324
+ if (filter?.workspace?.branch && session.workspace.branch !== filter.workspace.branch)
325
+ return false;
326
+
91
327
  return true;
92
328
  });
93
329
  }
94
330
 
95
331
  /**
96
- * Long-poll for the verdict. Resolves immediately when already resolved;
97
- * otherwise parks until sessionResolve fires or timeoutMs elapses (null =
98
- * still pending - the caller re-polls later; the verdict is never lost).
332
+ * Long-poll for the message. Resolves immediately when already resolved;
333
+ * otherwise parks until sessionSendMessage fires or timeoutMs elapses (null =
334
+ * still pending - the caller re-polls later; the message is never lost).
99
335
  */
100
- sessionWait(id: string, timeoutMs: number): Promise<ReviewSession | null> {
101
- const s = this.sessionGet(id);
102
- if (s.status === "resolved") return Promise.resolve(s);
336
+ sessionWait(id: string, timeoutMs: number): Promise<Thread | null> {
337
+ const current = this.sessionGet(id);
338
+
339
+ if (current.status === "resolved") return Promise.resolve(current);
340
+
103
341
  return new Promise((resolve) => {
104
342
  const list = this.waiters.get(id) ?? [];
105
343
  let done = false;
106
344
  const timer = setTimeout(() => {
107
345
  if (done) return;
108
346
  done = true;
109
- const idx = list.indexOf(waiter);
110
- if (idx !== -1) list.splice(idx, 1);
347
+ const waiterIndex = list.indexOf(waiter);
348
+
349
+ if (waiterIndex !== -1) list.splice(waiterIndex, 1);
111
350
  resolve(null);
112
351
  }, timeoutMs);
113
- const waiter = (session: ReviewSession) => {
352
+ const waiter = (session: Thread) => {
114
353
  if (done) return;
115
354
  done = true;
116
355
  clearTimeout(timer);
117
356
  resolve(session);
118
357
  };
358
+
119
359
  list.push(waiter);
120
360
  this.waiters.set(id, list);
121
361
  });
122
362
  }
123
363
 
124
- sessionAnnotate(id: string, annotation: Omit<Annotation, "createdAt">): ReviewSession {
125
- const s = this.mutable(id);
126
- const existing = s.annotations.findIndex((a) => a.id === annotation.id);
364
+ /**
365
+ * `authorName` registers the annotation's author in the participant registry;
366
+ * a bare author id (no name) keeps its short-handle fallback instead.
367
+ */
368
+ sessionAnnotate(
369
+ id: string,
370
+ annotation: Omit<Annotation, "createdAt">,
371
+ authorName?: string,
372
+ ): Thread {
373
+ const session = this.mutable(id);
374
+ // a welcome-playground note is ephemeral by design: never persisted, so never fed back
375
+ if (annotationTarget(annotation).kind === "welcome") return session;
376
+ const existing = session.annotations.findIndex((candidate) => candidate.id === annotation.id);
127
377
  const full: Annotation = { ...annotation, createdAt: new Date().toISOString() };
128
- if (existing === -1) s.annotations.push(full);
129
- else s.annotations[existing] = { ...full, createdAt: s.annotations[existing]!.createdAt };
130
- this.store.upsert(s);
131
- this.emit("session.updated", id);
132
- return s;
378
+
379
+ let entryId: string | undefined;
380
+
381
+ if (existing === -1) {
382
+ session.annotations.push(full);
383
+ entryId = this.record(session, {
384
+ type: "comment",
385
+ annotationId: full.id,
386
+ createdAt: full.createdAt,
387
+ });
388
+ } else
389
+ session.annotations[existing] = {
390
+ ...full,
391
+ createdAt: session.annotations[existing]!.createdAt,
392
+ };
393
+ if (annotation.author && authorName)
394
+ session.participants = registerParticipant(
395
+ session,
396
+ annotation.author,
397
+ authorName,
398
+ ).participants;
399
+ this.store.upsert(session);
400
+ this.emit("session.updated", id, entryId);
401
+
402
+ return session;
403
+ }
404
+
405
+ /**
406
+ * Remove a comment. With `onBehalfOf`, the caller is a collaborator or an
407
+ * agent acting as that author and may remove only that author's comments;
408
+ * the owner (no `onBehalfOf`) may remove any.
409
+ */
410
+ sessionRemoveAnnotation(id: string, annotationId: string, onBehalfOf?: string): Thread {
411
+ const session = this.mutable(id);
412
+ const target = session.annotations.find((candidate) => candidate.id === annotationId);
413
+
414
+ if (onBehalfOf !== undefined && target !== undefined && target.author !== onBehalfOf) {
415
+ throw new DaemonError("forbidden", `${onBehalfOf} cannot remove another author's comment`);
416
+ }
417
+ session.annotations = session.annotations.filter((candidate) => candidate.id !== annotationId);
418
+ let entryId: string | undefined;
419
+
420
+ if (target !== undefined) {
421
+ // nothing is deleted: a navigate back before the removal shows it again
422
+ session.shelvedAnnotations = [...(session.shelvedAnnotations ?? []), target];
423
+ entryId = this.record(session, {
424
+ type: "comment-removed",
425
+ annotationId,
426
+ createdAt: new Date().toISOString(),
427
+ });
428
+ }
429
+
430
+ this.store.upsert(session);
431
+ this.emit("session.updated", id, entryId);
432
+
433
+ return session;
133
434
  }
134
435
 
135
- sessionRemoveAnnotation(id: string, annotationId: string): ReviewSession {
136
- const s = this.mutable(id);
137
- s.annotations = s.annotations.filter((a) => a.id !== annotationId);
138
- this.store.upsert(s);
436
+ /** Register a display name for a participant; how a collaborator or an agent names itself. */
437
+ sessionSetParticipantName(id: string, author: string, name: string): Thread {
438
+ const session = this.mutable(id);
439
+
440
+ session.participants = registerParticipant(session, author, name).participants;
441
+ this.store.upsert(session);
139
442
  this.emit("session.updated", id);
140
- return s;
443
+
444
+ return session;
141
445
  }
142
446
 
143
447
  /** The reviewer's working copy; undefined clears it (revert all edits). */
144
- sessionSetWorkingCopy(id: string, workingCopy: string | undefined): ReviewSession {
145
- const s = this.mutable(id);
146
- if (workingCopy === undefined || workingCopy === s.artifact.content) delete s.workingCopy;
147
- else s.workingCopy = workingCopy;
148
- this.store.upsert(s);
448
+ sessionSetWorkingCopy(id: string, workingCopy: string | undefined): Thread {
449
+ const session = this.mutable(id);
450
+ const entryId = this.applyWorkingCopy(session, workingCopy);
451
+
452
+ this.store.upsert(session);
453
+ this.emit("session.updated", id, entryId);
454
+
455
+ return session;
456
+ }
457
+
458
+ /**
459
+ * The guided walk's viewed marks. Merge-additive: walking only ever adds
460
+ * marks, so concurrent or stale clients converge instead of overwriting
461
+ * each other. An empty array is the explicit reset.
462
+ */
463
+ sessionSetViewed(id: string, viewedPaths: string[]): Thread {
464
+ const session = this.mutable(id);
465
+
466
+ if (viewedPaths.length === 0) delete session.viewedPaths;
467
+ else session.viewedPaths = [...new Set([...(session.viewedPaths ?? []), ...viewedPaths])];
468
+ this.store.upsert(session);
149
469
  this.emit("session.updated", id);
150
- return s;
470
+
471
+ return session;
151
472
  }
152
473
 
153
- sessionResolve(id: string, verdictKind: VerdictKind, summary: string): ReviewSession {
154
- const s = this.mutable(id);
155
- const verdict: Verdict = {
156
- kind: verdictKind,
474
+ /** Rename a session's display title; an empty title clears it back to the derived default. */
475
+ sessionSetTitle(id: string, title: string): Thread {
476
+ const session = this.mutable(id);
477
+ const trimmed = title.trim();
478
+
479
+ if (trimmed.length === 0) delete session.artifact.meta.title;
480
+ else session.artifact.meta.title = trimmed;
481
+ this.store.upsert(session);
482
+ // the title shows in the Threads sidebar, so a rename is an inbox change, not just a content edit
483
+ this.emit("inbox.changed", id);
484
+
485
+ return session;
486
+ }
487
+
488
+ /** Tracked, repo-relative file paths for the session's workspace; [] when it has no repo. */
489
+ projectFiles(id: string): Promise<string[]> {
490
+ return listProjectFiles(this.sessionGet(id).workspace.repoRoot);
491
+ }
492
+
493
+ /** UTF-8 contents of a repo-relative file in the session's workspace, or null when it cannot be read safely. */
494
+ fileContents(id: string, path: string): Promise<string | null> {
495
+ return readProjectFile(this.sessionGet(id).workspace.repoRoot, path);
496
+ }
497
+
498
+ /** Tracked, repo-relative file paths for the git repo containing `cwd`; [] when it is not a repo. Owner-only. */
499
+ async repoFiles(cwd: string): Promise<string[]> {
500
+ return listProjectFiles((await resolveWorkspace(cwd)).repoRoot);
501
+ }
502
+
503
+ /** UTF-8 contents of a repo-relative file in the repo containing `cwd`, or null when unreadable. Owner-only. */
504
+ async repoFileContents(cwd: string, path: string): Promise<string | null> {
505
+ return readProjectFile((await resolveWorkspace(cwd)).repoRoot, path);
506
+ }
507
+
508
+ /** Changed files (repo-relative path plus git status) in the working tree at `cwd`. Owner-only. */
509
+ repoChanges(cwd: string): Promise<{ path: string; status: DiffFileStatus }[]> {
510
+ return workingChangeList(cwd);
511
+ }
512
+
513
+ /**
514
+ * The live working-tree diff (HEAD vs working tree, untracked included) at `cwd`:
515
+ * the same unified patch plus full per-file contents a `cueloop diff` captures,
516
+ * so the Changes navigator renders a real diff for any thread. Owner-only.
517
+ */
518
+ repoDiff(cwd: string): Promise<WorkingTreeDiff> {
519
+ return workingTreeDiff(cwd);
520
+ }
521
+
522
+ /**
523
+ * The per-repo workbench thread for `cwd`: a self-initiated review of the current checkout, keyed by
524
+ * the repo's root-commit identity (a standalone bucket when there is none). Returns the existing one
525
+ * or lazily creates it with the working-tree diff as its artifact, so a bare launch persists its
526
+ * first comment without an agent submission. Owner-only.
527
+ */
528
+ async workbenchSession(cwd: string): Promise<Thread> {
529
+ const workspace = await resolveWorkspace(cwd);
530
+ const key = workspace.rootCommit ?? "_standalone";
531
+ // an open workbench is reused; a resolved one is immutable and would reject the note, so a fresh
532
+ // one is created past it
533
+ const open = this.store
534
+ .list()
535
+ .find(
536
+ (session) =>
537
+ session.artifact.meta.workbench === true &&
538
+ session.status !== "resolved" &&
539
+ (session.workspace.rootCommit ?? "_standalone") === key,
540
+ );
541
+
542
+ if (open) return open;
543
+ // serialize concurrent bare launches for the same repo onto one creation, so they share a thread
544
+ const inFlight = this.workbenchCreation.get(key);
545
+
546
+ if (inFlight) return inFlight;
547
+ const creation = workingTreeDiff(cwd).then((diff) =>
548
+ this.sessionCreate({
549
+ workspace,
550
+ artifact: {
551
+ type: "diff",
552
+ content: diff.patch,
553
+ files: diff.files,
554
+ meta: { workbench: true, title: "Workbench", cwd },
555
+ },
556
+ }),
557
+ );
558
+
559
+ this.workbenchCreation.set(key, creation);
560
+ try {
561
+ return await creation;
562
+ } finally {
563
+ this.workbenchCreation.delete(key);
564
+ }
565
+ }
566
+
567
+ sessionSetShareId(id: string, shareId: string): Thread {
568
+ const session = this.mutable(id);
569
+
570
+ session.shareId = shareId;
571
+ this.store.upsert(session);
572
+ this.emit("session.updated", id);
573
+
574
+ return session;
575
+ }
576
+
577
+ /** Replace the thread's share links; the legacy single-share fields are dropped once shares[] is authoritative. */
578
+ sessionSetShares(id: string, shares: ShareLink[]): Thread {
579
+ const session = this.mutable(id);
580
+
581
+ session.shares = shares;
582
+ delete session.shareId;
583
+ delete session.access;
584
+ delete session.owner;
585
+ delete session.shareBranch;
586
+ this.store.upsert(session);
587
+ this.emit("session.updated", id);
588
+
589
+ return session;
590
+ }
591
+
592
+ /** Set the private-share allowlist of GitHub logins; presence marks the share private. */
593
+ sessionSetAccess(id: string, githubLogins: string[]): Thread {
594
+ const session = this.mutable(id);
595
+
596
+ session.access = { githubLogins };
597
+ this.store.upsert(session);
598
+ this.emit("session.updated", id);
599
+
600
+ return session;
601
+ }
602
+
603
+ /** Remove a session for good (inbox delete); resolved or pending, both go. */
604
+ sessionDelete(id: string): void {
605
+ const session = this.store.get(id);
606
+
607
+ if (!this.store.delete(id)) throw new DaemonError("not_found", `no session ${id}`);
608
+ if (session) this.untrackLiveDiffSession(session);
609
+ this.diffRefreshGenerations.delete(id);
610
+ this.herdrThreadSurfaces.delete(id);
611
+ this.ghosttyThreadSurfaces.delete(id);
612
+ this.emit("inbox.changed", id);
613
+ }
614
+
615
+ /**
616
+ * Cut one block of the reviewer's working copy - the `blockIndex`-th block
617
+ * of the working text - so it serializes into the diff the agent receives.
618
+ */
619
+ sessionCutBlock(id: string, blockIndex: number): Thread {
620
+ const session = this.mutable(id);
621
+ const working = session.workingCopy ?? session.artifact.content;
622
+ const block = parseBlocks(working)[blockIndex];
623
+
624
+ if (!block)
625
+ throw new DaemonError("invalid_params", `no block ${blockIndex} in the working copy`);
626
+ const entryId = this.applyWorkingCopy(session, cutBlock(working, block));
627
+
628
+ this.store.upsert(session);
629
+ this.emit("session.updated", id, entryId);
630
+
631
+ return session;
632
+ }
633
+
634
+ /**
635
+ * Re-insert a cut block - the `baseBlockIndex`-th block of the submitted
636
+ * revision - into the working copy before `line` (default: the end). A copy
637
+ * that reads as the submitted revision again is dropped, not stored.
638
+ */
639
+ sessionRestoreBlock(id: string, baseBlockIndex: number, line?: number): Thread {
640
+ const session = this.mutable(id);
641
+ const base = session.artifact.content;
642
+ const block = parseBlocks(base)[baseBlockIndex];
643
+
644
+ if (!block) {
645
+ throw new DaemonError(
646
+ "invalid_params",
647
+ `no block ${baseBlockIndex} in the submitted revision`,
648
+ );
649
+ }
650
+ const working = session.workingCopy ?? base;
651
+
652
+ if (!isBlockCut(base, working, block)) {
653
+ throw new DaemonError(
654
+ "invalid_params",
655
+ `block ${baseBlockIndex} of the submitted revision is present in the working copy`,
656
+ );
657
+ }
658
+ const beforeLine = Math.min(line ?? working.split("\n").length, working.split("\n").length);
659
+ const entryId = this.applyWorkingCopy(session, restoreBlock(base, working, block, beforeLine));
660
+
661
+ this.store.upsert(session);
662
+ this.emit("session.updated", id, entryId);
663
+
664
+ return session;
665
+ }
666
+
667
+ /**
668
+ * Replace a diff review's reject decisions; the working copy becomes the
669
+ * patch they leave, or clears when nothing is rejected. Needs the full file
670
+ * contents a working-tree diff carries; a PR diff cannot be curated.
671
+ */
672
+ sessionCurate(id: string, rejections: HunkRejection[]): Thread {
673
+ const session = this.mutable(id);
674
+
675
+ if (session.artifact.type !== "diff") {
676
+ throw new DaemonError("invalid_params", "only a diff review is curated by hunk");
677
+ }
678
+ if (!session.artifact.files?.length) {
679
+ throw new DaemonError("invalid_params", "hunk curation needs full file contents");
680
+ }
681
+ if (rejections.length === 0) delete session.curation;
682
+ else session.curation = rejections;
683
+ const entryId = this.applyWorkingCopy(
684
+ session,
685
+ rejections.length === 0 ? undefined : curateDiff(session.artifact.files, rejections),
686
+ );
687
+
688
+ this.store.upsert(session);
689
+ this.emit("session.updated", id, entryId);
690
+
691
+ return session;
692
+ }
693
+
694
+ /**
695
+ * Merge a share's state back into the local session. Comments union by
696
+ * annotation id with existing ones (the planner's) winning; removals union by
697
+ * entry id, each shelving its comment once; the participant registry unions
698
+ * by id with the incoming identity winning (a collaborator is the authority
699
+ * on their own name). Everything lands on the branch the share follows, and
700
+ * the record then shows its current path again, wherever the owner stands.
701
+ */
702
+ sessionMergeShared(id: string, incoming: SharedMerge): Thread {
703
+ const session = this.mutable(id);
704
+ const branch = this.shareBranchOf(session);
705
+ const known = new Set(
706
+ [...session.annotations, ...(session.shelvedAnnotations ?? [])].map(
707
+ (annotation) => annotation.id,
708
+ ),
709
+ );
710
+ let changed = false;
711
+
712
+ for (const annotation of incoming.annotations) {
713
+ if (known.has(annotation.id)) continue;
714
+ known.add(annotation.id);
715
+ session.annotations.push(annotation);
716
+ this.recordOn(session, branch, {
717
+ type: "comment",
718
+ annotationId: annotation.id,
719
+ createdAt: annotation.createdAt,
720
+ });
721
+ changed = true;
722
+ }
723
+ const recorded = new Set((session.history?.entries ?? []).map((entry) => entry.id));
724
+
725
+ for (const removal of incoming.removals ?? []) {
726
+ if (recorded.has(removal.id) || !known.has(removal.annotationId)) continue;
727
+ this.recordOn(session, branch, {
728
+ id: removal.id,
729
+ type: "comment-removed",
730
+ annotationId: removal.annotationId,
731
+ createdAt: removal.createdAt,
732
+ });
733
+ changed = true;
734
+ }
735
+ if (incoming.participants?.length) {
736
+ const registry = new Map(
737
+ (session.participants ?? []).map((participant) => [participant.id, participant]),
738
+ );
739
+
740
+ for (const participant of incoming.participants) registry.set(participant.id, participant);
741
+ session.participants = [...registry.values()];
742
+ }
743
+ if (changed && session.history) this.refreshView(session, session.history);
744
+ else this.store.upsert(session);
745
+ this.emit("session.updated", id);
746
+
747
+ return session;
748
+ }
749
+
750
+ sessionSendMessage(
751
+ id: string,
752
+ outcome: MessageOutcome,
753
+ summary: string,
754
+ actionBodies?: Record<string, string>,
755
+ ): Thread {
756
+ const session = this.mutable(id);
757
+ const sentAt = new Date().toISOString();
758
+ const message: Message = {
759
+ id: newMessageId(),
760
+ outcome,
157
761
  summary,
158
- feedback: feedbackForSession(s, verdictKind, summary),
159
- resolvedAt: new Date().toISOString(),
762
+ body: feedbackForSession(session, outcome, summary, actionBodies),
763
+ sentAt,
160
764
  };
161
- s.verdict = verdict;
162
- s.status = "resolved";
163
- this.store.upsert(s);
765
+
766
+ session.message = message;
767
+ session.status = "resolved";
768
+ const entryId = this.record(session, {
769
+ type: "message",
770
+ message,
771
+ createdAt: message.sentAt,
772
+ });
773
+ this.store.upsert(session);
774
+ this.reconcileDeliveries(session);
775
+ // a resolved diff review is frozen; stop hot-reloading its working tree
776
+ this.untrackLiveDiffSession(session);
164
777
  const parked = this.waiters.get(id) ?? [];
778
+
165
779
  this.waiters.delete(id);
166
- for (const w of parked) w(s);
167
- this.emit("session.resolved", id);
780
+ for (const parkedWaiter of parked) parkedWaiter(session);
781
+ this.emit("message.sent", id, entryId);
168
782
  this.emit("inbox.changed", id);
169
- return s;
783
+
784
+ return session;
170
785
  }
171
786
 
172
- /** Agent resubmits: new revision becomes the artifact, session reopens. */
173
- sessionSubmitRevision(id: string, content: string): ReviewSession {
174
- const s = this.sessionGet(id);
787
+ /**
788
+ * Agent resubmits: new revision becomes the artifact, session reopens.
789
+ * Annotations the agent reports as acted on (by id) are marked addressed,
790
+ * and for plan revisions any still-open annotation whose quoted text no
791
+ * longer resolves is marked addressed too ("drift" - the line it pointed at
792
+ * was rewritten). Addressed is a marker, never a delete: the reviewer's
793
+ * rail hides them behind a count, and the next feedback document omits them.
794
+ * Unknown ids are ignored, so a stale id in the agent's list never fails
795
+ * the resubmit.
796
+ */
797
+ sessionSubmitRevision(
798
+ id: string,
799
+ content: string,
800
+ addressedAnnotationIds: string[] = [],
801
+ files?: DiffFileContents[],
802
+ ): Thread {
803
+ const session = this.sessionGet(id);
175
804
  const now = new Date().toISOString();
176
- s.revisions.push({ revision: s.revisions.length + 1, content, submittedAt: now });
177
- s.artifact = { ...s.artifact, content };
178
- delete s.workingCopy;
179
- s.verdict = null;
180
- s.status = "pending";
181
- this.store.upsert(s);
182
- this.emit("session.revised", id);
805
+ const revisionNumber = session.revisions.length + 1;
806
+
807
+ session.revisions.push({ revision: revisionNumber, content, submittedAt: now });
808
+ session.artifact = { ...session.artifact, content, files: files ?? session.artifact.files };
809
+ // the agent's revision lands on main wherever its tip sits; the artifact
810
+ // shows the head of the branch the reviewer is on
811
+ const entryId = this.recordOnMain(session, {
812
+ type: "revision",
813
+ by: "agent",
814
+ content,
815
+ createdAt: now,
816
+ });
817
+ delete session.workingCopy;
818
+ session.message = null;
819
+ session.status = "pending";
820
+
821
+ // a reported root comment addresses its whole discussion: replies are
822
+ // never listed on their own in the feedback document
823
+ const reportedIds = new Set(addressedAnnotationIds);
824
+
825
+ for (const annotation of session.annotations) {
826
+ if (annotation.replyTo !== undefined && reportedIds.has(annotation.replyTo)) {
827
+ reportedIds.add(annotation.id);
828
+ }
829
+ }
830
+ // drift assist applies to markdown artifacts (plan, reply) only: a diff
831
+ // revision is a whole new patch, where a vanished quote says nothing about
832
+ // the feedback
833
+ const revisedBlocks = isMarkdownArtifact(session.artifact.type) ? parseBlocks(content) : null;
834
+
835
+ for (const annotation of session.annotations) {
836
+ if (isAddressed(annotation) || isAgentNote(annotation)) continue;
837
+ if (reportedIds.has(annotation.id)) {
838
+ annotation.resolution = { revision: revisionNumber, source: "agent" };
839
+ } else if (
840
+ revisedBlocks !== null &&
841
+ // only a note on the artifact drifts against the artifact's revision; a selector-anchored
842
+ // pixel element or a file-targeted Changes-diff note anchors elsewhere
843
+ annotationTarget(annotation).kind === "artifact" &&
844
+ !annotation.anchor.selector &&
845
+ resolveAnchor(annotation.anchor, revisedBlocks) === null
846
+ ) {
847
+ annotation.resolution = { revision: revisionNumber, source: "drift" };
848
+ }
849
+ }
850
+
851
+ this.store.upsert(session);
852
+ this.emit("session.revised", id, entryId);
183
853
  this.emit("inbox.changed", id);
184
- return s;
854
+
855
+ return session;
856
+ }
857
+
858
+ /**
859
+ * Move a branch's tip back to an entry on its path - the current branch, or
860
+ * `branch` after switching to it. The entries after it stay in the tree; a
861
+ * summary records them as a branch-summary entry at the target. The view
862
+ * follows the path: on `main`, the agent's next revision lands there.
863
+ */
864
+ sessionNavigate(id: string, entryId: string, summary?: string, branch?: string): Thread {
865
+ const session = this.mutable(id);
866
+ const moved = this.tree(id, () => {
867
+ const history = this.historyOf(session);
868
+ const standing = branch === undefined ? history : switchBranch(history, branch);
869
+
870
+ return navigateTo(standing, entryId, summary === undefined ? {} : { summary });
871
+ });
872
+
873
+ this.refreshView(session, moved);
874
+ const tip = moved.tips[moved.branch];
875
+
876
+ this.emit("session.updated", id, tip === entryId ? undefined : tip);
877
+
878
+ return session;
879
+ }
880
+
881
+ /** Start a branch at the current tip and switch to it; `main` stays where it is. */
882
+ sessionBranch(id: string, name: string): Thread {
883
+ const session = this.mutable(id);
884
+
885
+ this.refreshView(
886
+ session,
887
+ this.tree(id, () => createBranch(this.historyOf(session), name)),
888
+ );
889
+ this.emit("session.updated", id);
890
+
891
+ return session;
892
+ }
893
+
894
+ sessionSwitch(id: string, branch: string): Thread {
895
+ const session = this.mutable(id);
896
+
897
+ this.refreshView(
898
+ session,
899
+ this.tree(id, () => switchBranch(this.historyOf(session), branch)),
900
+ );
901
+ this.emit("session.updated", id);
902
+
903
+ return session;
185
904
  }
186
905
 
187
- private mutable(id: string): ReviewSession {
188
- const s = this.sessionGet(id);
189
- if (s.status === "resolved") throw new DaemonError("resolved", `session ${id} is already resolved`);
190
- return s;
906
+ /** Name the current tip as a checkpoint to navigate back to. */
907
+ sessionLabel(id: string, label: string): Thread {
908
+ const session = this.mutable(id);
909
+
910
+ session.history = labelTip(this.historyOf(session), label);
911
+ this.store.upsert(session);
912
+ this.emit("session.updated", id);
913
+
914
+ return session;
915
+ }
916
+
917
+ /**
918
+ * Copy the current path into a new pending session: its revisions, open
919
+ * comments, labels, and participant names travel; messages, edits, and the
920
+ * share do not. A resolved session can be forked.
921
+ */
922
+ sessionFork(id: string): Thread {
923
+ const source = this.sessionGet(id);
924
+ const history = this.tree(id, () => forkHistory(this.historyOf(source)));
925
+ const now = new Date().toISOString();
926
+ const known = [...source.annotations, ...(source.shelvedAnnotations ?? [])];
927
+ const view = viewOfPath(history, known);
928
+ const fork: Thread = {
929
+ schemaVersion: SCHEMA_VERSION,
930
+ id: this.newSessionId(now),
931
+ workspace: source.workspace,
932
+ artifact: { ...source.artifact, content: view.content },
933
+ revisions: history.entries
934
+ .filter((entry) => entry.type === "revision")
935
+ .map((entry, index) => ({
936
+ revision: index + 1,
937
+ content: entry.content,
938
+ submittedAt: entry.createdAt,
939
+ })),
940
+ annotations: [],
941
+ history,
942
+ message: null,
943
+ status: "pending",
944
+ createdAt: now,
945
+ parentSessionId: id,
946
+ };
947
+
948
+ fork.annotations = view.annotations.map((annotation) =>
949
+ forkedAnnotation(annotation, source, fork),
950
+ );
951
+ if (source.participants)
952
+ fork.participants = source.participants.map((identity) => ({ ...identity }));
953
+ this.store.upsert(fork);
954
+ this.trackLiveDiffSession(fork);
955
+ this.emit("session.created", fork.id);
956
+ this.emit("inbox.changed", fork.id);
957
+
958
+ return fork;
959
+ }
960
+
961
+ /** Re-capture a diff session's working tree; broadcasts session.updated only when the patch moved. */
962
+ async sessionRefreshDiff(id: string): Promise<{ changed: boolean }> {
963
+ const session = this.mutable(id);
964
+
965
+ if (session.artifact.type !== "diff") return { changed: false };
966
+ // a PR review has no local working tree; re-pull it from the PR instead of clobbering it
967
+ if (session.artifact.meta.pr !== undefined) return this.sessionRefreshPrDiff(id);
968
+ const generation = (this.diffRefreshGenerations.get(id) ?? 0) + 1;
969
+
970
+ this.diffRefreshGenerations.set(id, generation);
971
+ const diff = await workingTreeDiff(session.workspace.repoRoot);
972
+
973
+ // The capture yields the event loop: a newer refresh may have started, or a
974
+ // concurrent resolve/delete may have closed the session. Discard a stale
975
+ // capture, and re-read so a resolved review is never mutated and a deleted
976
+ // one is never revived by this upsert.
977
+ if (this.diffRefreshGenerations.get(id) !== generation) return { changed: false };
978
+ const current = this.store.get(id);
979
+
980
+ if (!current || current.status !== "pending" || current.artifact.type !== "diff")
981
+ return { changed: false };
982
+ if (diff.patch === current.artifact.content) return { changed: false };
983
+ current.artifact = { ...current.artifact, content: diff.patch, files: diff.files };
984
+ // the history keeps showing the same revision, re-captured, so a later tree move derives this patch
985
+ const history = withHistory(current).history;
986
+
987
+ if (history) current.history = recaptureMainHead(history, diff.patch);
988
+ this.store.upsert(current);
989
+ this.emit("session.updated", id);
990
+
991
+ return { changed: true };
992
+ }
993
+
994
+ /**
995
+ * Re-pull a PR review's diff when its head moved; broadcasts session.updated
996
+ * only when the patch text changed. A PR review has no local working tree, so
997
+ * it never runs workingTreeDiff - the diff comes from gh.
998
+ */
999
+ async sessionRefreshPrDiff(id: string): Promise<{ changed: boolean }> {
1000
+ const session = this.store.get(id);
1001
+
1002
+ if (!session || session.status !== "pending" || session.artifact.type !== "diff")
1003
+ return { changed: false };
1004
+ const pr = session.artifact.meta.pr;
1005
+
1006
+ if (pr === undefined) return { changed: false };
1007
+ const generation = (this.diffRefreshGenerations.get(id) ?? 0) + 1;
1008
+
1009
+ this.diffRefreshGenerations.set(id, generation);
1010
+ const patch = await prDiff(pr);
1011
+
1012
+ // gh failed (offline, unauthenticated): keep the diff we have, try again next poll
1013
+ if (patch === null) return { changed: false };
1014
+ // the pull yields the event loop: discard a stale capture or a closed session
1015
+ if (this.diffRefreshGenerations.get(id) !== generation) return { changed: false };
1016
+ const current = this.store.get(id);
1017
+
1018
+ if (!current || current.status !== "pending" || current.artifact.type !== "diff")
1019
+ return { changed: false };
1020
+ if (patch === current.artifact.content) return { changed: false };
1021
+ current.artifact = { ...current.artifact, content: patch };
1022
+ const history = withHistory(current).history;
1023
+
1024
+ if (history) current.history = recaptureMainHead(history, patch);
1025
+ this.store.upsert(current);
1026
+ this.emit("session.updated", id);
1027
+
1028
+ return { changed: true };
1029
+ }
1030
+
1031
+ /** Re-capture every working-tree diff session sharing a repo root (one debounced fs change). */
1032
+ private async refreshDiffsForRepo(repoRoot: string): Promise<void> {
1033
+ const live = this.store
1034
+ .list()
1035
+ .filter(
1036
+ (session) => isWorkingTreeDiffSession(session) && session.workspace.repoRoot === repoRoot,
1037
+ );
1038
+
1039
+ for (const session of live) {
1040
+ // a session resolved or deleted between the change and this tick just skips
1041
+ try {
1042
+ await this.sessionRefreshDiff(session.id);
1043
+ } catch {
1044
+ // no-op: the session is gone or already resolved
1045
+ }
1046
+ }
1047
+ }
1048
+
1049
+ private trackLiveDiffSession(session: Thread): void {
1050
+ if (isWorkingTreeDiffSession(session))
1051
+ this.diffWatcher.trackDiffRepo(session.workspace.repoRoot, session.id);
1052
+ else if (isPrReviewSession(session))
1053
+ this.prPoller.trackPr(session.id, session.artifact.meta.pr!);
1054
+ }
1055
+
1056
+ private untrackLiveDiffSession(session: Thread): void {
1057
+ if (session.artifact.type !== "diff") return;
1058
+ this.diffWatcher.untrackDiffRepo(session.workspace.repoRoot, session.id);
1059
+ this.prPoller.untrackPr(session.id);
1060
+ }
1061
+
1062
+ /**
1063
+ * Set or clear the working copy and, when the reviewer's text changed, record
1064
+ * it as a reviewer revision on the current branch. Returns that entry's id.
1065
+ */
1066
+ private applyWorkingCopy(session: Thread, workingCopy: string | undefined): string | undefined {
1067
+ const before = session.workingCopy ?? session.artifact.content;
1068
+ const next =
1069
+ workingCopy === undefined || workingCopy === session.artifact.content
1070
+ ? undefined
1071
+ : workingCopy;
1072
+
1073
+ if (next === undefined) delete session.workingCopy;
1074
+ else session.workingCopy = next;
1075
+ const after = next ?? session.artifact.content;
1076
+
1077
+ if (after === before) return undefined;
1078
+
1079
+ return this.record(session, {
1080
+ type: "revision",
1081
+ by: "reviewer",
1082
+ content: after,
1083
+ createdAt: new Date().toISOString(),
1084
+ });
1085
+ }
1086
+
1087
+ /** The session's history; a record without a revision has none and cannot be moved through. */
1088
+ private historyOf(session: Thread): SessionHistory {
1089
+ const history = withHistory(session).history;
1090
+
1091
+ if (!history) throw new DaemonError("invalid_params", `session ${session.id} has no history`);
1092
+
1093
+ return history;
1094
+ }
1095
+
1096
+ /** Run a tree operation; a refused move is the caller's mistake, not the daemon's. */
1097
+ private tree(id: string, operation: () => SessionHistory): SessionHistory {
1098
+ try {
1099
+ return operation();
1100
+ } catch (error) {
1101
+ if (error instanceof HistoryError) throw new DaemonError("invalid_params", error.message);
1102
+ throw error;
1103
+ }
1104
+ }
1105
+
1106
+ /** Store a moved history and make the record show its active path. */
1107
+ private refreshView(session: Thread, history: SessionHistory): void {
1108
+ session.history = history;
1109
+ applyPathView(
1110
+ session,
1111
+ viewOfPath(history, [...session.annotations, ...(session.shelvedAnnotations ?? [])]),
1112
+ );
1113
+ this.store.upsert(session);
1114
+ }
1115
+
1116
+ /** Append an entry on the session's current branch; a session without a head has no history to extend. */
1117
+ private record(session: Thread, entry: NewEntry): string | undefined {
1118
+ const history = withHistory(session).history;
1119
+
1120
+ if (!history) return undefined;
1121
+ const appended = appendEntry(history, entry);
1122
+
1123
+ session.history = appended.history;
1124
+
1125
+ return appended.entry.id;
1126
+ }
1127
+
1128
+ /** Append an entry on main, leaving the reviewer's current branch where it is. */
1129
+ private recordOnMain(session: Thread, entry: NewEntry): string | undefined {
1130
+ return this.recordOn(session, MAIN_BRANCH, entry);
1131
+ }
1132
+
1133
+ /** Append an entry on a named branch, leaving the reviewer's current branch where it is. */
1134
+ private recordOn(session: Thread, branch: string, entry: NewEntry): string | undefined {
1135
+ const history = withHistory(session).history;
1136
+
1137
+ if (!history) return undefined;
1138
+ const appended = appendEntry(switchBranch(history, branch), entry);
1139
+
1140
+ session.history = { ...appended.history, branch: history.branch };
1141
+
1142
+ return appended.entry.id;
1143
+ }
1144
+
1145
+ /** The branch a share follows; a share made before branches existed follows main. */
1146
+ private shareBranchOf(session: Thread): string {
1147
+ const branch = session.shareBranch ?? MAIN_BRANCH;
1148
+
1149
+ return session.history?.tips[branch] === undefined ? MAIN_BRANCH : branch;
1150
+ }
1151
+
1152
+ private mutable(id: string): Thread {
1153
+ const session = this.sessionGet(id);
1154
+
1155
+ if (session.status === "resolved")
1156
+ throw new DaemonError("resolved", `session ${id} is already resolved`);
1157
+
1158
+ return session;
191
1159
  }
192
1160
  }
193
1161
 
194
1162
  export { DaemonError };
195
1163
 
1164
+ /**
1165
+ * A comment as the fork carries it. An addressed mark names a revision by the
1166
+ * source's numbering; the fork numbers its own, so the mark follows the
1167
+ * revision's text, and a comment addressed by a revision off the fork's path
1168
+ * is open again.
1169
+ */
1170
+ function forkedAnnotation(annotation: Annotation, source: Thread, fork: Thread): Annotation {
1171
+ const { resolution, ...open } = annotation;
1172
+
1173
+ if (resolution === undefined) return { ...annotation };
1174
+ const addressedBy = source.revisions.find(
1175
+ (revision) => revision.revision === resolution.revision,
1176
+ );
1177
+ const inFork = fork.revisions.find((revision) => revision.content === addressedBy?.content);
1178
+
1179
+ return inFork === undefined
1180
+ ? open
1181
+ : { ...annotation, resolution: { ...resolution, revision: inFork.revision } };
1182
+ }
1183
+
1184
+ /** A pending diff of the local working tree: hot-reloads by watching its repo. A PR review is excluded. */
1185
+ function isWorkingTreeDiffSession(session: Thread): boolean {
1186
+ return (
1187
+ session.status === "pending" &&
1188
+ session.artifact.type === "diff" &&
1189
+ session.artifact.meta.pr === undefined
1190
+ );
1191
+ }
1192
+
1193
+ /** A pending review of a remote PR: hot-reloads by polling the PR head, never by watching a working tree. */
1194
+ function isPrReviewSession(session: Thread): boolean {
1195
+ return (
1196
+ session.status === "pending" &&
1197
+ session.artifact.type === "diff" &&
1198
+ session.artifact.meta.pr !== undefined
1199
+ );
1200
+ }
1201
+
196
1202
  /** Convenience for adapters: map a resolved session to the agent contract. */
197
- export function verdictResponse(session: ReviewSession): { allow: boolean; feedback: string } {
198
- if (!session.verdict) throw new DaemonError("pending", "session has no verdict");
199
- return { allow: verdictAllows(session.verdict.kind), feedback: session.verdict.feedback };
1203
+ export function messageResponse(session: Thread) {
1204
+ if (!session.message) throw new DaemonError("pending", "session has no message");
1205
+
1206
+ return { allow: messageAllows(session.message.outcome), message: session.message };
200
1207
  }