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