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

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