@cueloop/daemon 0.1.0-alpha.9 → 0.1.0-alpha.90

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/package.json +39 -22
  2. package/src/api.test.ts +1060 -65
  3. package/src/api.ts +1398 -89
  4. package/src/capabilities.test.ts +57 -0
  5. package/src/capabilities.ts +89 -0
  6. package/src/client.test.ts +24 -0
  7. package/src/client.ts +669 -86
  8. package/src/curate.ts +109 -0
  9. package/src/daemon-version.test.ts +142 -0
  10. package/src/diff-hot-reload.test.ts +419 -0
  11. package/src/diff-watcher.ts +293 -0
  12. package/src/gh.test.ts +59 -0
  13. package/src/gh.ts +74 -0
  14. package/src/ghostty-thread-surface-store.test.ts +49 -0
  15. package/src/ghostty-thread-surface-store.ts +101 -0
  16. package/src/ghostty-thread-surface.test.ts +398 -0
  17. package/src/ghostty-thread-surface.ts +267 -0
  18. package/src/harness-delivery.test.ts +268 -0
  19. package/src/harness-state-store.test.ts +93 -0
  20. package/src/harness-state-store.ts +213 -0
  21. package/src/herdr-split.test.ts +106 -0
  22. package/src/herdr-split.ts +92 -0
  23. package/src/herdr-thread-surface-store.test.ts +81 -0
  24. package/src/herdr-thread-surface-store.ts +64 -0
  25. package/src/herdr-thread-surface.test.ts +411 -0
  26. package/src/herdr-thread-surface.ts +355 -0
  27. package/src/index.ts +8 -9
  28. package/src/interruptible-wait.test.ts +127 -0
  29. package/src/interruptible-wait.ts +66 -0
  30. package/src/jj-working-tree.ts +131 -0
  31. package/src/main.ts +4 -1
  32. package/src/paths.ts +49 -0
  33. package/src/pr-poller.test.ts +102 -0
  34. package/src/pr-poller.ts +73 -0
  35. package/src/project-files.test.ts +124 -0
  36. package/src/project-files.ts +56 -0
  37. package/src/protocol.ts +79 -7
  38. package/src/retention.test.ts +191 -0
  39. package/src/retention.ts +123 -0
  40. package/src/server.test.ts +453 -42
  41. package/src/server.ts +433 -88
  42. package/src/share-blob.test.ts +112 -0
  43. package/src/share-blob.ts +55 -0
  44. package/src/single-instance.test.ts +162 -13
  45. package/src/store.conformance.test.ts +41 -0
  46. package/src/store.jsonl.test.ts +159 -0
  47. package/src/store.ts +264 -34
  48. package/src/testing/store-conformance.ts +194 -0
  49. package/src/thread-review.test.ts +483 -0
  50. package/src/thread-review.ts +398 -0
  51. package/src/thread-surface-config.test.ts +63 -0
  52. package/src/thread-surface-config.ts +61 -0
  53. package/src/validate.test.ts +282 -37
  54. package/src/validate.ts +398 -33
  55. package/src/vcs-source.test.ts +180 -0
  56. package/src/vcs-source.ts +228 -0
  57. package/src/version.ts +6 -0
  58. package/src/working-tree.ts +149 -0
  59. package/src/review.test.ts +0 -167
  60. package/src/review.ts +0 -174
package/src/validate.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Runtime validation of the wire boundary (#14). Everything arriving over the
2
+ * Runtime validation of the wire boundary. Everything arriving over the
3
3
  * socket is untrusted JSON: adapters, the CLI, extensions, and any script a
4
4
  * user writes all speak this protocol. Validating here means DaemonCore only
5
5
  * ever sees well-formed input, and a malformed request gets a precise error
@@ -11,17 +11,36 @@
11
11
 
12
12
  import * as v from "valibot";
13
13
  import {
14
+ ARTIFACT_TYPES,
15
+ MESSAGE_OUTCOMES,
16
+ WORKFLOW_KINDS,
14
17
  SCHEMA_VERSION,
15
18
  type Anchor,
16
19
  type Annotation,
20
+ type AnnotationTarget,
17
21
  type Artifact,
18
22
  type ArtifactMeta,
19
- type ReviewSession,
23
+ type DiffFileContents,
24
+ type Identity,
25
+ type Thread,
26
+ type TextCut,
27
+ type HunkRejection,
28
+ type HarnessBinding,
29
+ type Delivery,
30
+ type PendingDelivery,
20
31
  type Revision,
21
- type Verdict,
32
+ REVIEW_SEVERITIES,
33
+ type ReviewComment,
34
+ type SessionHistory,
35
+ type ShareAccess,
36
+ type ShareLink,
37
+ validateHistory,
38
+ type Message,
22
39
  type WorkspaceKey,
40
+ applyTextCuts,
23
41
  } from "@cueloop/schema";
24
42
  import { DaemonError } from "./errors";
43
+ import type { Request } from "./protocol";
25
44
 
26
45
  /**
27
46
  * Drift guard for every hand-mirrored shape below. v.object strips keys it
@@ -34,25 +53,69 @@ type EntriesOf<T> = { [K in keyof T]-?: v.GenericSchema<any, any> };
34
53
 
35
54
  const NonEmpty = v.pipe(v.string(), v.minLength(1));
36
55
 
56
+ const TextCutSchema = v.object({
57
+ start: v.pipe(v.number(), v.integer(), v.minValue(0)),
58
+ end: v.pipe(v.number(), v.integer(), v.minValue(1)),
59
+ quote: NonEmpty,
60
+ } satisfies EntriesOf<TextCut>);
61
+
62
+ const TextCutsSchema = v.pipe(
63
+ v.array(TextCutSchema),
64
+ v.check(
65
+ (cuts) =>
66
+ cuts.every(
67
+ (cut, index) =>
68
+ cut.end - cut.start === cut.quote.length &&
69
+ (index === 0 || cuts[index - 1]!.end <= cut.start),
70
+ ),
71
+ "text Cuts must be ordered, non-overlapping, and match their quote lengths",
72
+ ),
73
+ );
74
+
37
75
  export const WorkspaceSchema = v.object({
38
76
  repoRoot: NonEmpty,
39
77
  branch: NonEmpty,
78
+ rootCommit: v.optional(NonEmpty),
79
+ remote: v.optional(NonEmpty),
40
80
  } satisfies EntriesOf<WorkspaceKey>);
41
81
 
42
82
  export const ArtifactMetaSchema = v.object({
83
+ workflow: v.optional(v.picklist(WORKFLOW_KINDS)),
43
84
  cwd: v.optional(v.string()),
85
+ vcs: v.optional(NonEmpty),
86
+ vcsChangeId: v.optional(NonEmpty),
87
+ vcsRevisionId: v.optional(NonEmpty),
44
88
  agent: v.optional(v.string()),
45
89
  agentSessionId: v.optional(v.string()),
46
90
  planPath: v.optional(v.string()),
91
+ prototypePath: v.optional(v.string()),
47
92
  pr: v.optional(v.string()),
93
+ prBrief: v.optional(v.string()),
94
+ prBaseSha: v.optional(NonEmpty),
95
+ prHeadSha: v.optional(NonEmpty),
96
+ prRefreshBaseSha: v.optional(NonEmpty),
97
+ prRefreshHeadSha: v.optional(NonEmpty),
98
+ prUrl: v.optional(NonEmpty),
48
99
  herdrPane: v.optional(v.string()),
49
100
  title: v.optional(v.string()),
101
+ workbench: v.optional(v.boolean()),
102
+ snapshot: v.optional(v.boolean()),
50
103
  } satisfies EntriesOf<ArtifactMeta>);
51
104
 
105
+ export const DiffFileContentsSchema = v.object({
106
+ path: NonEmpty,
107
+ oldContents: v.string(),
108
+ newContents: v.string(),
109
+ status: v.picklist(["added", "modified", "deleted"]),
110
+ } satisfies EntriesOf<DiffFileContents>);
111
+
52
112
  export const ArtifactSchema = v.object({
53
- type: v.picklist(["plan", "diff"]),
113
+ // Derived from the schema's runtime union: a new primitive extends the wire
114
+ // contract without touching this file.
115
+ type: v.picklist(ARTIFACT_TYPES),
54
116
  content: v.string(),
55
117
  meta: v.optional(ArtifactMetaSchema, {}),
118
+ files: v.optional(v.array(DiffFileContentsSchema)),
56
119
  } satisfies EntriesOf<Artifact>);
57
120
 
58
121
  export const AnchorSchema = v.object({
@@ -60,22 +123,93 @@ export const AnchorSchema = v.object({
60
123
  prefix: v.optional(v.string(), ""),
61
124
  suffix: v.optional(v.string(), ""),
62
125
  blockIndex: v.optional(v.number()),
126
+ endBlockIndex: v.optional(v.number()),
63
127
  start: v.optional(v.number()),
64
128
  end: v.optional(v.number()),
129
+ selector: v.optional(v.string()),
65
130
  } satisfies EntriesOf<Anchor>);
66
131
 
132
+ /** The surface a note was made on; absent means the reviewed artifact. */
133
+ export const AnnotationTargetSchema: v.GenericSchema<AnnotationTarget> = v.variant("kind", [
134
+ v.object({ kind: v.literal("artifact") }),
135
+ v.object({ kind: v.literal("file"), path: NonEmpty, rev: v.picklist(["worktree", "head"]) }),
136
+ v.object({ kind: v.literal("welcome") }),
137
+ ]);
138
+
67
139
  /** Wire annotations arrive without createdAt - the daemon stamps it. */
68
140
  export const AnnotationSchema = v.object({
69
141
  id: NonEmpty,
70
- /** Open kind set (#2): built-ins are comment and suggestion. */
142
+ /** Open kind set: the built-in is comment. */
71
143
  kind: NonEmpty,
72
144
  anchor: AnchorSchema,
145
+ target: v.optional(AnnotationTargetSchema),
73
146
  body: v.string(),
74
147
  orphan: v.optional(v.boolean()),
148
+ author: v.optional(v.string()),
149
+ reviewComment: v.optional(
150
+ v.object({
151
+ severity: v.picklist(REVIEW_SEVERITIES),
152
+ title: NonEmpty,
153
+ path: NonEmpty,
154
+ line: v.pipe(v.number(), v.integer(), v.minValue(1)),
155
+ startLine: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1))),
156
+ startAnchor: v.optional(AnchorSchema),
157
+ side: v.picklist(["LEFT", "RIGHT"]),
158
+ suggestion: v.optional(v.string()),
159
+ prompt: v.optional(v.string()),
160
+ } satisfies EntriesOf<ReviewComment>),
161
+ ),
162
+ replyTo: v.optional(NonEmpty),
163
+ resolution: v.optional(
164
+ v.object({
165
+ revision: v.number(),
166
+ source: v.picklist(["agent", "drift"]),
167
+ }),
168
+ ),
75
169
  } satisfies EntriesOf<Omit<Annotation, "createdAt">>);
76
170
 
77
171
  const SessionId = NonEmpty;
78
172
 
173
+ /** A stored annotation: the wire shape plus the daemon-stamped createdAt. */
174
+ export const FullAnnotationSchema = v.object({
175
+ ...AnnotationSchema.entries,
176
+ createdAt: v.string(),
177
+ } satisfies EntriesOf<Annotation>);
178
+
179
+ export const IdentitySchema = v.object({
180
+ id: NonEmpty,
181
+ provider: v.picklist(["ssh", "github"]),
182
+ name: v.optional(v.string()),
183
+ handle: v.optional(v.string()),
184
+ } satisfies EntriesOf<Identity>);
185
+
186
+ export const ShareLinkSchema = v.object({
187
+ id: NonEmpty,
188
+ name: v.optional(v.string()),
189
+ requireAuth: v.boolean(),
190
+ allowlist: v.array(NonEmpty),
191
+ owner: v.optional(v.string()),
192
+ shareBranch: v.optional(v.string()),
193
+ } satisfies EntriesOf<ShareLink>);
194
+
195
+ export const HarnessBindingSchema = v.object({
196
+ id: NonEmpty,
197
+ threadId: NonEmpty,
198
+ harness: NonEmpty,
199
+ harnessSessionId: NonEmpty,
200
+ createdAt: NonEmpty,
201
+ approvedRetryMessageId: v.optional(NonEmpty),
202
+ } satisfies EntriesOf<HarnessBinding>);
203
+
204
+ export const DeliverySchema = v.object({
205
+ id: NonEmpty,
206
+ messageId: NonEmpty,
207
+ bindingId: NonEmpty,
208
+ status: v.picklist(["pending", "acknowledged"]),
209
+ createdAt: NonEmpty,
210
+ acknowledgedAt: v.optional(NonEmpty),
211
+ } satisfies EntriesOf<Delivery>);
212
+
79
213
  export const Params = {
80
214
  "session.create": v.object({ workspace: WorkspaceSchema, artifact: ArtifactSchema }),
81
215
  "session.get": v.object({ id: SessionId }),
@@ -90,20 +224,140 @@ export const Params = {
90
224
  "session.wait": v.object({
91
225
  id: SessionId,
92
226
  // clamped: a negative or absurd timeout is a client bug, not a daemon one
93
- timeoutMs: v.optional(v.pipe(v.number(), v.minValue(0), v.maxValue(24 * 60 * 60 * 1000)), 60_000),
227
+ timeoutMs: v.optional(
228
+ v.pipe(v.number(), v.minValue(0), v.maxValue(24 * 60 * 60 * 1000)),
229
+ 60_000,
230
+ ),
231
+ }),
232
+ "session.annotate": v.object({
233
+ id: SessionId,
234
+ annotation: AnnotationSchema,
235
+ authorName: v.optional(v.string()),
236
+ }),
237
+ // "session.comment" is the primary annotate method; "session.annotate" stays an accepted alias
238
+ "session.comment": v.object({
239
+ id: SessionId,
240
+ annotation: AnnotationSchema,
241
+ authorName: v.optional(v.string()),
94
242
  }),
95
- "session.annotate": v.object({ id: SessionId, annotation: AnnotationSchema }),
96
243
  "session.removeAnnotation": v.object({ id: SessionId, annotationId: NonEmpty }),
97
- "session.setWorkingCopy": v.object({ id: SessionId, workingCopy: v.optional(v.string()) }),
98
- "session.resolve": v.object({
244
+ "session.setParticipantName": v.object({ id: SessionId, author: NonEmpty, name: NonEmpty }),
245
+ "session.setWorkingCopy": v.object({
246
+ id: SessionId,
247
+ workingCopy: v.optional(v.string()),
248
+ textCuts: v.optional(TextCutsSchema),
249
+ }),
250
+ "session.cutBlock": v.object({
251
+ id: SessionId,
252
+ blockIndex: v.pipe(v.number(), v.integer(), v.minValue(0)),
253
+ }),
254
+ "session.restoreBlock": v.object({
255
+ id: SessionId,
256
+ baseBlockIndex: v.pipe(v.number(), v.integer(), v.minValue(0)),
257
+ line: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0))),
258
+ }),
259
+ "session.curate": v.object({
260
+ id: SessionId,
261
+ rejections: v.array(
262
+ v.object({
263
+ path: NonEmpty,
264
+ hunkIndex: v.pipe(v.number(), v.integer(), v.minValue(0)),
265
+ changeIndex: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0))),
266
+ } satisfies EntriesOf<HunkRejection>),
267
+ ),
268
+ }),
269
+ "session.setViewed": v.object({ id: SessionId, viewedPaths: v.array(v.string()) }),
270
+ "session.setTitle": v.object({ id: SessionId, title: v.string() }),
271
+ "session.projectFiles": v.object({ id: SessionId }),
272
+ "session.fileContents": v.object({ id: SessionId, path: NonEmpty }),
273
+ "repo.files": v.object({ cwd: NonEmpty }),
274
+ "repo.fileContents": v.object({ cwd: NonEmpty, path: NonEmpty }),
275
+ "repo.changes": v.object({ cwd: NonEmpty }),
276
+ "repo.diff": v.object({ cwd: NonEmpty, vcs: v.optional(NonEmpty) }),
277
+ "session.workbench": v.object({ cwd: NonEmpty }),
278
+ "session.navigate": v.object({
279
+ id: SessionId,
280
+ entryId: NonEmpty,
281
+ summary: v.optional(v.string()),
282
+ // stand on this branch first, so a move on another branch is one request
283
+ branch: v.optional(NonEmpty),
284
+ }),
285
+ "session.branch": v.object({ id: SessionId, name: NonEmpty }),
286
+ "session.switch": v.object({ id: SessionId, branch: NonEmpty }),
287
+ "session.label": v.object({ id: SessionId, label: NonEmpty }),
288
+ "session.fork": v.object({ id: SessionId }),
289
+ "session.refreshDiff": v.object({ id: SessionId }),
290
+ "session.setShareId": v.object({ id: SessionId, shareId: NonEmpty }),
291
+ "session.setShares": v.object({ id: SessionId, shares: v.array(ShareLinkSchema) }),
292
+ "session.setAccess": v.object({ id: SessionId, githubLogins: v.array(NonEmpty) }),
293
+ "session.delete": v.object({ id: SessionId }),
294
+ "session.mergeShared": v.object({
295
+ id: SessionId,
296
+ annotations: v.array(FullAnnotationSchema),
297
+ participants: v.optional(v.array(IdentitySchema)),
298
+ // the removal entries a share recorded, carried by id so a merge applies each once
299
+ removals: v.optional(
300
+ v.array(v.object({ id: NonEmpty, annotationId: NonEmpty, createdAt: v.string() })),
301
+ ),
302
+ }),
303
+ "session.sendMessage": v.object({
99
304
  id: SessionId,
100
- verdictKind: v.picklist(["comment", "approve", "request_changes"]),
305
+ outcome: v.picklist(MESSAGE_OUTCOMES),
101
306
  summary: v.optional(v.string(), ""),
307
+ actionBodies: v.optional(v.record(v.string(), v.string())),
308
+ }),
309
+ "harness.bind": v.object({
310
+ threadId: SessionId,
311
+ harness: NonEmpty,
312
+ harnessSessionId: NonEmpty,
313
+ }),
314
+ "harness.getBinding": v.object({ bindingId: NonEmpty }),
315
+ "harness.bindingsForSession": v.object({ harness: NonEmpty, harnessSessionId: NonEmpty }),
316
+ "harness.consumeApprovedRetry": v.object({
317
+ bindingId: NonEmpty,
318
+ messageId: NonEmpty,
319
+ content: v.string(),
320
+ }),
321
+ "delivery.pending": v.object({ bindingId: NonEmpty }),
322
+ "delivery.acknowledge": v.object({ deliveryId: NonEmpty }),
323
+ "session.submitRevision": v.object({
324
+ id: SessionId,
325
+ content: v.string(),
326
+ files: v.optional(v.array(DiffFileContentsSchema)),
327
+ source: v.optional(
328
+ v.object({
329
+ vcs: NonEmpty,
330
+ changeId: v.optional(NonEmpty),
331
+ revisionId: v.optional(NonEmpty),
332
+ baseRevisionId: v.optional(NonEmpty),
333
+ }),
334
+ ),
335
+ /** Annotation ids the agent acted on; each is marked addressed. */
336
+ addressedAnnotationIds: v.optional(v.array(NonEmpty), []),
102
337
  }),
103
- "session.submitRevision": v.object({ id: SessionId, content: v.string() }),
104
338
  "events.subscribe": v.object({}),
105
339
  "daemon.ping": v.object({}),
340
+ // the owner token proves ownership; without it a request for owner stays a collaborator
341
+ "daemon.hello": v.object({
342
+ role: v.picklist(["owner", "collaborator", "agent"]),
343
+ clientVersion: v.optional(v.string()),
344
+ token: v.optional(v.string()),
345
+ // the author a non-owner acts as, bound once for the connection
346
+ author: v.optional(NonEmpty),
347
+ }),
106
348
  "daemon.shutdown": v.object({}),
349
+ // Herdr terminal handles stay outside canonical Thread records.
350
+ "herdr.getThreadSurface": v.object({ id: SessionId }),
351
+ "herdr.setThreadSurface": v.object({
352
+ id: SessionId,
353
+ tabId: NonEmpty,
354
+ paneId: NonEmpty,
355
+ mode: v.optional(v.picklist(["tab", "pane"])),
356
+ }),
357
+ "ghostty.getThreadSurface": v.object({ id: SessionId }),
358
+ "ghostty.setThreadSurface": v.object({ id: SessionId, terminalId: NonEmpty }),
359
+ "ghostty.claimThreadSurface": v.object({ id: SessionId }),
360
+ "ghostty.releaseThreadSurface": v.object({ id: SessionId }),
107
361
  } as const;
108
362
 
109
363
  export type MethodName = keyof typeof Params;
@@ -113,13 +367,22 @@ export function isKnownMethod(method: string): method is MethodName {
113
367
  }
114
368
 
115
369
  /** Validate params for a method, or throw a DaemonError the client can read. */
116
- export function parseParams<M extends MethodName>(method: M, params: unknown): v.InferOutput<(typeof Params)[M]> {
370
+ export function parseParams<M extends MethodName>(
371
+ method: M,
372
+ params: Request["params"],
373
+ ): v.InferOutput<(typeof Params)[M]> {
117
374
  const result = v.safeParse(Params[method], params ?? {});
375
+
118
376
  if (!result.success) {
119
377
  const issue = result.issues[0]!;
120
- const path = issue.path?.map((p) => String(p.key)).join(".") ?? "";
121
- throw new DaemonError("invalid_params", `${method}: ${path ? path + " - " : ""}${issue.message}`);
378
+ const path = issue.path?.map((pathSegment) => String(pathSegment.key)).join(".") ?? "";
379
+
380
+ throw new DaemonError(
381
+ "invalid_params",
382
+ `${method}: ${path ? path + " - " : ""}${issue.message}`,
383
+ );
122
384
  }
385
+
123
386
  return result.output;
124
387
  }
125
388
 
@@ -127,33 +390,135 @@ export const RevisionSchema = v.object({
127
390
  revision: v.number(),
128
391
  content: v.string(),
129
392
  submittedAt: v.string(),
393
+ files: v.optional(v.array(DiffFileContentsSchema)),
394
+ source: v.optional(
395
+ v.object({
396
+ vcs: NonEmpty,
397
+ changeId: v.optional(NonEmpty),
398
+ revisionId: v.optional(NonEmpty),
399
+ baseRevisionId: v.optional(NonEmpty),
400
+ }),
401
+ ),
130
402
  } satisfies EntriesOf<Revision>);
131
403
 
132
- export const VerdictSchema = v.object({
133
- kind: v.picklist(["comment", "approve", "request_changes"]),
404
+ export const MessageSchema = v.object({
405
+ id: NonEmpty,
406
+ outcome: v.picklist(MESSAGE_OUTCOMES),
134
407
  summary: v.string(),
135
- feedback: v.string(),
136
- resolvedAt: v.string(),
137
- } satisfies EntriesOf<Verdict>);
408
+ body: v.string(),
409
+ annotations: v.optional(v.array(FullAnnotationSchema)),
410
+ sentAt: v.string(),
411
+ } satisfies EntriesOf<Message>);
138
412
 
139
- /** Persisted records are validated on recovery: a bad file is skipped, not fatal. */
140
- export const SessionRecordSchema = v.object({
141
- schemaVersion: v.literal(SCHEMA_VERSION),
413
+ export const PendingDeliverySchema = v.object({
414
+ delivery: DeliverySchema,
415
+ message: MessageSchema,
416
+ } satisfies EntriesOf<PendingDelivery>);
417
+
418
+ const EntryBaseEntries = {
142
419
  id: NonEmpty,
143
- workspace: WorkspaceSchema,
144
- artifact: ArtifactSchema,
145
- revisions: v.array(RevisionSchema),
146
- annotations: v.array(v.object({ ...AnnotationSchema.entries, createdAt: v.string() } satisfies EntriesOf<Annotation>)),
147
- workingCopy: v.optional(v.string()),
148
- verdict: v.nullable(VerdictSchema),
149
- status: v.picklist(["pending", "resolved"]),
420
+ parentId: v.nullable(NonEmpty),
150
421
  createdAt: v.string(),
151
- } satisfies EntriesOf<ReviewSession>);
422
+ };
423
+
424
+ /** One record of a session's history; the tree pointers plus the entry's own fields. */
425
+ export const SessionEntrySchema = v.variant("type", [
426
+ v.object({
427
+ ...EntryBaseEntries,
428
+ type: v.literal("revision"),
429
+ by: v.picklist(["agent", "reviewer"]),
430
+ content: v.string(),
431
+ textCuts: v.optional(TextCutsSchema),
432
+ }),
433
+ v.object({ ...EntryBaseEntries, type: v.literal("comment"), annotationId: NonEmpty }),
434
+ v.object({ ...EntryBaseEntries, type: v.literal("comment-removed"), annotationId: NonEmpty }),
435
+ v.object({ ...EntryBaseEntries, type: v.literal("message"), message: MessageSchema }),
436
+ v.object({
437
+ ...EntryBaseEntries,
438
+ type: v.literal("branch-summary"),
439
+ text: v.string(),
440
+ abandoned: v.array(NonEmpty),
441
+ }),
442
+ ]);
443
+
444
+ export const SessionHistorySchema = v.pipe(
445
+ v.object({
446
+ entries: v.array(SessionEntrySchema),
447
+ tips: v.record(v.string(), NonEmpty),
448
+ branch: NonEmpty,
449
+ labels: v.record(v.string(), v.string()),
450
+ } satisfies EntriesOf<SessionHistory>),
451
+ // the shape is not enough: the tree itself must hold, or a walk hangs or rewires the path
452
+ v.rawCheck(({ dataset, addIssue }) => {
453
+ if (!dataset.typed) return;
454
+ const problem = validateHistory(dataset.value);
455
+
456
+ if (problem !== null) addIssue({ message: `history: ${problem}` });
457
+ }),
458
+ );
459
+
460
+ /** Persisted records are validated on recovery: a bad file is skipped, not fatal. */
461
+ export const ThreadRecordSchema = v.pipe(
462
+ v.object({
463
+ schemaVersion: v.literal(SCHEMA_VERSION),
464
+ id: NonEmpty,
465
+ workspace: WorkspaceSchema,
466
+ artifact: ArtifactSchema,
467
+ revisions: v.array(RevisionSchema),
468
+ annotations: v.array(FullAnnotationSchema),
469
+ history: v.optional(SessionHistorySchema),
470
+ curation: v.optional(
471
+ v.array(
472
+ v.object({
473
+ path: NonEmpty,
474
+ hunkIndex: v.number(),
475
+ changeIndex: v.optional(v.number()),
476
+ } satisfies EntriesOf<HunkRejection>),
477
+ ),
478
+ ),
479
+ workingCopy: v.optional(v.string()),
480
+ textCuts: v.optional(TextCutsSchema),
481
+ viewedPaths: v.optional(v.array(v.string())),
482
+ message: v.nullable(MessageSchema),
483
+ status: v.picklist(["pending", "resolved"]),
484
+ createdAt: v.string(),
485
+ shelvedAnnotations: v.optional(v.array(FullAnnotationSchema)),
486
+ parentSessionId: v.optional(v.string()),
487
+ shares: v.optional(v.array(ShareLinkSchema)),
488
+ shareId: v.optional(v.string()),
489
+ shareBranch: v.optional(v.string()),
490
+ owner: v.optional(v.string()),
491
+ access: v.optional(
492
+ v.object({ githubLogins: v.array(NonEmpty) } satisfies EntriesOf<ShareAccess>),
493
+ ),
494
+ participants: v.optional(v.array(IdentitySchema)),
495
+ } satisfies EntriesOf<Thread>),
496
+ v.rawCheck(({ dataset, addIssue }) => {
497
+ if (!dataset.typed || !dataset.value.textCuts?.length) return;
498
+ const { artifact, textCuts, workingCopy } = dataset.value;
499
+ const matchesSource = textCuts.every(
500
+ (cut) => artifact.content.slice(cut.start, cut.end) === cut.quote,
501
+ );
502
+
503
+ if (!matchesSource || workingCopy !== applyTextCuts(artifact.content, textCuts)) {
504
+ addIssue({ message: "text Cuts do not match the submitted artifact and working copy" });
505
+ }
506
+ }),
507
+ );
508
+
509
+ export function validateThreadRecord(
510
+ raw: Parameters<typeof v.safeParse>[1],
511
+ ): { ok: true; value: v.InferOutput<typeof ThreadRecordSchema> } | { ok: false; error: string } {
512
+ const result = v.safeParse(ThreadRecordSchema, raw);
152
513
 
153
- export function validateSessionRecord(raw: unknown): { ok: true; value: v.InferOutput<typeof SessionRecordSchema> } | { ok: false; error: string } {
154
- const result = v.safeParse(SessionRecordSchema, raw);
155
514
  if (result.success) return { ok: true, value: result.output };
156
515
  const issue = result.issues[0]!;
157
- const path = issue.path?.map((p) => String(p.key)).join(".") ?? "";
516
+ const path = issue.path?.map((pathSegment) => String(pathSegment.key)).join(".") ?? "";
517
+
158
518
  return { ok: false, error: `${path ? path + ": " : ""}${issue.message}` };
159
519
  }
520
+
521
+ /** @deprecated use ThreadRecordSchema */
522
+ export const SessionRecordSchema = ThreadRecordSchema;
523
+ /** @deprecated use validateThreadRecord */
524
+ export const validateSessionRecord = validateThreadRecord;