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