@flyingrobots/graft 0.4.0 → 0.5.0

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 (111) hide show
  1. package/ARCHITECTURE.md +386 -0
  2. package/CHANGELOG.md +47 -0
  3. package/CODE_OF_CONDUCT.md +65 -0
  4. package/README.md +153 -17
  5. package/bin/graft.js +4 -14
  6. package/docs/ADVANCED_GUIDE.md +49 -0
  7. package/docs/CLI.md +43 -0
  8. package/docs/GUIDE.md +321 -32
  9. package/docs/MCP.md +44 -0
  10. package/package.json +15 -4
  11. package/src/adapters/node-fs.ts +4 -0
  12. package/src/adapters/node-git.ts +47 -0
  13. package/src/adapters/node-process-runner.ts +27 -0
  14. package/src/cli/index-cmd.ts +75 -11
  15. package/src/cli/init.ts +808 -57
  16. package/src/cli/main.ts +437 -0
  17. package/src/contracts/capabilities.ts +341 -0
  18. package/src/contracts/causal-ontology.ts +622 -0
  19. package/src/contracts/causal-surface-next-action.ts +18 -0
  20. package/src/contracts/output-schemas.ts +1169 -0
  21. package/src/git/diff.ts +25 -21
  22. package/src/git/target-git-hook-bootstrap.ts +56 -0
  23. package/src/hooks/posttooluse-read.ts +21 -74
  24. package/src/hooks/pretooluse-read.ts +20 -56
  25. package/src/hooks/read-governor.ts +95 -0
  26. package/src/hooks/read-messages.ts +53 -0
  27. package/src/mcp/burden.ts +123 -0
  28. package/src/mcp/cache.ts +51 -0
  29. package/src/mcp/cached-file.ts +10 -8
  30. package/src/mcp/context.ts +65 -2
  31. package/src/mcp/daemon-control-plane.ts +554 -0
  32. package/src/mcp/daemon-job-scheduler.ts +279 -0
  33. package/src/mcp/daemon-repos.ts +216 -0
  34. package/src/mcp/daemon-server.ts +396 -0
  35. package/src/mcp/daemon-worker-pool.ts +310 -0
  36. package/src/mcp/daemon-worker-process.ts +52 -0
  37. package/src/mcp/metrics.ts +108 -1
  38. package/src/mcp/monitor-tick-job.ts +99 -0
  39. package/src/mcp/persisted-local-history.ts +1246 -0
  40. package/src/mcp/persistent-monitor-runtime.ts +549 -0
  41. package/src/mcp/policy.ts +84 -0
  42. package/src/mcp/receipt.ts +82 -12
  43. package/src/mcp/repo-concurrency.ts +318 -0
  44. package/src/mcp/repo-state.ts +777 -0
  45. package/src/mcp/repo-tool-job.ts +302 -0
  46. package/src/mcp/run-capture-config.ts +33 -0
  47. package/src/mcp/runtime-causal-context.ts +72 -0
  48. package/src/mcp/runtime-observability.ts +219 -0
  49. package/src/mcp/runtime-staged-target.ts +161 -0
  50. package/src/mcp/runtime-workspace-overlay.ts +255 -0
  51. package/src/mcp/semantic-transition-guidance.ts +60 -0
  52. package/src/mcp/semantic-transition-summary.ts +130 -0
  53. package/src/mcp/server.ts +696 -55
  54. package/src/mcp/stdio-server.ts +12 -0
  55. package/src/mcp/stdio.ts +2 -5
  56. package/src/mcp/tools/activity-view.ts +325 -0
  57. package/src/mcp/tools/causal-attach.ts +67 -0
  58. package/src/mcp/tools/causal-status.ts +58 -0
  59. package/src/mcp/tools/changed-since.ts +13 -11
  60. package/src/mcp/tools/code-find.ts +164 -0
  61. package/src/mcp/tools/code-refs.ts +466 -0
  62. package/src/mcp/tools/code-show.ts +252 -0
  63. package/src/mcp/tools/daemon-monitors.ts +14 -0
  64. package/src/mcp/tools/daemon-repos.ts +22 -0
  65. package/src/mcp/tools/daemon-sessions.ts +14 -0
  66. package/src/mcp/tools/daemon-status.ts +12 -0
  67. package/src/mcp/tools/doctor.ts +45 -2
  68. package/src/mcp/tools/explain.ts +4 -0
  69. package/src/mcp/tools/file-outline.ts +7 -3
  70. package/src/mcp/tools/git-files.ts +73 -0
  71. package/src/mcp/tools/graft-diff.ts +12 -4
  72. package/src/mcp/tools/map.ts +92 -38
  73. package/src/mcp/tools/monitor-pause.ts +18 -0
  74. package/src/mcp/tools/monitor-resume.ts +18 -0
  75. package/src/mcp/tools/monitor-start.ts +20 -0
  76. package/src/mcp/tools/monitor-stop.ts +18 -0
  77. package/src/mcp/tools/precision-match.ts +51 -0
  78. package/src/mcp/tools/precision-query.ts +127 -0
  79. package/src/mcp/tools/precision.ts +312 -0
  80. package/src/mcp/tools/run-capture.ts +126 -44
  81. package/src/mcp/tools/safe-read.ts +14 -12
  82. package/src/mcp/tools/since.ts +7 -2
  83. package/src/mcp/tools/state.ts +11 -3
  84. package/src/mcp/tools/stats.ts +5 -1
  85. package/src/mcp/tools/workspace-authorizations.ts +14 -0
  86. package/src/mcp/tools/workspace-authorize.ts +20 -0
  87. package/src/mcp/tools/workspace-bind.ts +25 -0
  88. package/src/mcp/tools/workspace-rebind.ts +25 -0
  89. package/src/mcp/tools/workspace-revoke.ts +18 -0
  90. package/src/mcp/tools/workspace-status.ts +12 -0
  91. package/src/mcp/warp-pool.ts +36 -0
  92. package/src/mcp/workspace-router.ts +984 -0
  93. package/src/operations/file-outline.ts +12 -2
  94. package/src/operations/graft-diff.ts +56 -10
  95. package/src/operations/safe-read.ts +27 -4
  96. package/src/operations/state.ts +6 -9
  97. package/src/parser/lang.ts +19 -3
  98. package/src/parser/outline.ts +191 -2
  99. package/src/parser/types.ts +9 -1
  100. package/src/policy/types.ts +4 -3
  101. package/src/ports/filesystem.ts +1 -0
  102. package/src/ports/git.ts +16 -0
  103. package/src/ports/process-runner.ts +22 -0
  104. package/src/release/security-gate.ts +102 -0
  105. package/src/session/tracker.ts +31 -0
  106. package/src/version.ts +3 -0
  107. package/src/warp/indexer.ts +171 -56
  108. package/src/warp/observers.ts +1 -1
  109. package/src/warp/open.ts +4 -3
  110. package/src/warp/plumbing.d.ts +5 -1
  111. package/src/warp/writer-id.ts +30 -0
@@ -0,0 +1,622 @@
1
+ import { z } from "zod";
2
+
3
+ export const ACTOR_KINDS = [
4
+ "human",
5
+ "agent",
6
+ "git",
7
+ "daemon",
8
+ "unknown",
9
+ ] as const;
10
+
11
+ export const actorKindSchema = z.enum(ACTOR_KINDS);
12
+ export type ActorKind = z.infer<typeof actorKindSchema>;
13
+
14
+ export const AUTHORITY_SCOPES = [
15
+ "authoritative",
16
+ "declared",
17
+ "inferred",
18
+ "mixed",
19
+ ] as const;
20
+
21
+ export const authorityScopeSchema = z.enum(AUTHORITY_SCOPES);
22
+ export type AuthorityScope = z.infer<typeof authorityScopeSchema>;
23
+
24
+ export const actorSchema = z.object({
25
+ actorId: z.string().min(1),
26
+ actorKind: actorKindSchema,
27
+ displayName: z.string().min(1).optional(),
28
+ source: z.string().min(1),
29
+ authorityScope: authorityScopeSchema,
30
+ }).strict();
31
+
32
+ export type Actor = z.infer<typeof actorSchema>;
33
+
34
+ export const EVIDENCE_KINDS = [
35
+ "mcp_transport_binding",
36
+ "workspace_authorization",
37
+ "daemon_session_observation",
38
+ "explicit_handoff",
39
+ "git_transition_observation",
40
+ "git_hook_transition",
41
+ "git_index_observation",
42
+ "worktree_fs_observation",
43
+ "writer_lane_identity",
44
+ "explicit_user_declaration",
45
+ "explicit_agent_declaration",
46
+ "conflicting_actor_signal",
47
+ ] as const;
48
+
49
+ export const evidenceKindSchema = z.enum(EVIDENCE_KINDS);
50
+ export type EvidenceKind = z.infer<typeof evidenceKindSchema>;
51
+
52
+ export const EVIDENCE_STRENGTHS = [
53
+ "direct",
54
+ "strong",
55
+ "weak",
56
+ "conflicted",
57
+ ] as const;
58
+
59
+ export const evidenceStrengthSchema = z.enum(EVIDENCE_STRENGTHS);
60
+ export type EvidenceStrength = z.infer<typeof evidenceStrengthSchema>;
61
+
62
+ export const evidenceSchema = z.object({
63
+ evidenceId: z.string().min(1),
64
+ evidenceKind: evidenceKindSchema,
65
+ source: z.string().min(1),
66
+ capturedAt: z.string().min(1),
67
+ strength: evidenceStrengthSchema,
68
+ details: z.record(z.string(), z.unknown()),
69
+ }).strict();
70
+
71
+ export type Evidence = z.infer<typeof evidenceSchema>;
72
+
73
+ export const ATTRIBUTION_CONFIDENCES = [
74
+ "high",
75
+ "medium",
76
+ "low",
77
+ "unknown",
78
+ ] as const;
79
+
80
+ export const attributionConfidenceSchema = z.enum(ATTRIBUTION_CONFIDENCES);
81
+ export type AttributionConfidence = z.infer<typeof attributionConfidenceSchema>;
82
+
83
+ export const ATTRIBUTION_BASES = [
84
+ "explicit_declaration",
85
+ "git_transition",
86
+ "unknown_fallback",
87
+ "conflicting_signals",
88
+ ] as const;
89
+
90
+ export const attributionBasisSchema = z.enum(ATTRIBUTION_BASES);
91
+ export type AttributionBasis = z.infer<typeof attributionBasisSchema>;
92
+
93
+ const confidenceRank = Object.freeze({
94
+ unknown: 0,
95
+ low: 1,
96
+ medium: 2,
97
+ high: 3,
98
+ } as const satisfies Record<AttributionConfidence, number>);
99
+
100
+ export function getMaximumConfidenceForEvidence(
101
+ strengths: readonly EvidenceStrength[],
102
+ ): AttributionConfidence {
103
+ if (strengths.length === 0) {
104
+ return "unknown";
105
+ }
106
+ if (strengths.includes("conflicted")) {
107
+ return "unknown";
108
+ }
109
+ if (strengths.includes("direct")) {
110
+ return "high";
111
+ }
112
+ if (strengths.includes("strong")) {
113
+ return "medium";
114
+ }
115
+ if (strengths.includes("weak")) {
116
+ return "low";
117
+ }
118
+ return "unknown";
119
+ }
120
+
121
+ export function isConfidenceBoundedByEvidence(
122
+ confidence: AttributionConfidence,
123
+ strengths: readonly EvidenceStrength[],
124
+ ): boolean {
125
+ return confidenceRank[confidence] <= confidenceRank[getMaximumConfidenceForEvidence(strengths)];
126
+ }
127
+
128
+ export const attributionSummarySchema = z.object({
129
+ actor: actorSchema,
130
+ confidence: attributionConfidenceSchema,
131
+ basis: attributionBasisSchema,
132
+ evidence: z.array(evidenceSchema),
133
+ }).strict().superRefine((summary, ctx) => {
134
+ if (!isConfidenceBoundedByEvidence(
135
+ summary.confidence,
136
+ summary.evidence.map((evidence) => evidence.strength),
137
+ )) {
138
+ ctx.addIssue({
139
+ code: "custom",
140
+ message: "Attribution confidence must be bounded by supporting evidence strength",
141
+ path: ["confidence"],
142
+ });
143
+ }
144
+ });
145
+
146
+ export type AttributionSummary = z.infer<typeof attributionSummarySchema>;
147
+
148
+ export const causalRegionSchema = z.object({
149
+ path: z.string().min(1),
150
+ startLine: z.number().int().positive(),
151
+ endLine: z.number().int().positive(),
152
+ startColumn: z.number().int().positive().optional(),
153
+ endColumn: z.number().int().positive().optional(),
154
+ }).strict();
155
+
156
+ export type CausalRegion = z.infer<typeof causalRegionSchema>;
157
+
158
+ function hasUniqueItems(values: readonly string[]): boolean {
159
+ return new Set(values).size === values.length;
160
+ }
161
+
162
+ export const causalFootprintSchema = z.object({
163
+ paths: z.array(z.string().min(1)),
164
+ symbols: z.array(z.string().min(1)),
165
+ regions: z.array(causalRegionSchema),
166
+ }).strict().superRefine((footprint, ctx) => {
167
+ if (!hasUniqueItems(footprint.paths)) {
168
+ ctx.addIssue({
169
+ code: "custom",
170
+ message: "Footprint paths must be unique",
171
+ path: ["paths"],
172
+ });
173
+ }
174
+ if (!hasUniqueItems(footprint.symbols)) {
175
+ ctx.addIssue({
176
+ code: "custom",
177
+ message: "Footprint symbols must be unique",
178
+ path: ["symbols"],
179
+ });
180
+ }
181
+ });
182
+
183
+ export type CausalFootprint = z.infer<typeof causalFootprintSchema>;
184
+
185
+ export const SOURCE_LAYERS = [
186
+ "canonical_structural_truth",
187
+ "workspace_overlay",
188
+ "strand_local_speculation",
189
+ ] as const;
190
+
191
+ export const sourceLayerSchema = z.enum(SOURCE_LAYERS);
192
+ export type SourceLayer = z.infer<typeof sourceLayerSchema>;
193
+
194
+ export const SELECTION_KINDS = [
195
+ "full_file",
196
+ "partial_file",
197
+ "symbol_subset",
198
+ ] as const;
199
+
200
+ export const selectionKindSchema = z.enum(SELECTION_KINDS);
201
+ export type SelectionKind = z.infer<typeof selectionKindSchema>;
202
+
203
+ export const stagedTargetSelectionEntrySchema = z.object({
204
+ path: z.string().min(1),
205
+ symbols: z.array(z.string().min(1)),
206
+ regions: z.array(causalRegionSchema),
207
+ }).strict().superRefine((entry, ctx) => {
208
+ if (!hasUniqueItems(entry.symbols)) {
209
+ ctx.addIssue({
210
+ code: "custom",
211
+ message: "Selection entry symbols must be unique",
212
+ path: ["symbols"],
213
+ });
214
+ }
215
+ });
216
+
217
+ export type StagedTargetSelectionEntry = z.infer<typeof stagedTargetSelectionEntrySchema>;
218
+
219
+ const stagedTargetBaseSchema = z.object({
220
+ headCommitSha: z.string().min(1),
221
+ indexTreeSha: z.string().min(1).nullable(),
222
+ }).strict();
223
+
224
+ export const stagedTargetSchema = z.object({
225
+ targetId: z.string().min(1),
226
+ targetKind: z.literal("staged_target"),
227
+ repoId: z.string().min(1),
228
+ worktreeId: z.string().min(1),
229
+ checkoutEpochId: z.string().min(1),
230
+ workspaceOverlayId: z.string().min(1),
231
+ selectedAt: z.string().min(1),
232
+ selectionKind: selectionKindSchema,
233
+ selectionEntries: z.array(stagedTargetSelectionEntrySchema).min(1),
234
+ base: stagedTargetBaseSchema,
235
+ }).strict().superRefine((target, ctx) => {
236
+ const seenPaths = new Set<string>();
237
+ for (const [index, entry] of target.selectionEntries.entries()) {
238
+ if (seenPaths.has(entry.path)) {
239
+ ctx.addIssue({
240
+ code: "custom",
241
+ message: "Selection entry paths must be unique within a staged target",
242
+ path: ["selectionEntries", index, "path"],
243
+ });
244
+ }
245
+ seenPaths.add(entry.path);
246
+
247
+ if (target.selectionKind === "full_file" && entry.regions.length > 0) {
248
+ ctx.addIssue({
249
+ code: "custom",
250
+ message: "Full-file staged targets must not carry regions",
251
+ path: ["selectionEntries", index, "regions"],
252
+ });
253
+ }
254
+ if (target.selectionKind === "partial_file" && entry.regions.length === 0) {
255
+ ctx.addIssue({
256
+ code: "custom",
257
+ message: "Partial-file staged targets require at least one region",
258
+ path: ["selectionEntries", index, "regions"],
259
+ });
260
+ }
261
+ if (target.selectionKind === "symbol_subset" && entry.symbols.length === 0) {
262
+ ctx.addIssue({
263
+ code: "custom",
264
+ message: "Symbol-subset staged targets require at least one symbol",
265
+ path: ["selectionEntries", index, "symbols"],
266
+ });
267
+ }
268
+ }
269
+ });
270
+
271
+ export type StagedTarget = z.infer<typeof stagedTargetSchema>;
272
+
273
+ export const DECISION_KINDS = [
274
+ "task_intent",
275
+ "hypothesis_shift",
276
+ "accepted_alternative",
277
+ "rejected_alternative",
278
+ "checkpoint",
279
+ ] as const;
280
+
281
+ export const decisionKindSchema = z.enum(DECISION_KINDS);
282
+ export type DecisionKind = z.infer<typeof decisionKindSchema>;
283
+
284
+ export const WRITE_KINDS = [
285
+ "human_edit",
286
+ "agent_edit",
287
+ "git_generated",
288
+ "stage_projection",
289
+ ] as const;
290
+
291
+ export const writeKindSchema = z.enum(WRITE_KINDS);
292
+ export type WriteKind = z.infer<typeof writeKindSchema>;
293
+
294
+ export const TRANSITION_KINDS = [
295
+ "checkout",
296
+ "merge",
297
+ "rebase",
298
+ "reset",
299
+ "rewrite",
300
+ "detached_head",
301
+ ] as const;
302
+
303
+ export const transitionKindSchema = z.enum(TRANSITION_KINDS);
304
+ export type TransitionKind = z.infer<typeof transitionKindSchema>;
305
+
306
+ export const SEMANTIC_TRANSITION_KINDS = [
307
+ "index_update",
308
+ "conflict_resolution",
309
+ "merge_phase",
310
+ "rebase_phase",
311
+ "bulk_transition",
312
+ "unknown",
313
+ ] as const;
314
+
315
+ export const semanticTransitionKindSchema = z.enum(SEMANTIC_TRANSITION_KINDS);
316
+ export type SemanticTransitionKind = z.infer<typeof semanticTransitionKindSchema>;
317
+
318
+ export const SEMANTIC_TRANSITION_AUTHORITIES = [
319
+ "authoritative_git_state",
320
+ "repo_snapshot",
321
+ ] as const;
322
+
323
+ export const semanticTransitionAuthoritySchema = z.enum(SEMANTIC_TRANSITION_AUTHORITIES);
324
+ export type SemanticTransitionAuthority = z.infer<typeof semanticTransitionAuthoritySchema>;
325
+
326
+ export const REPO_CONCURRENCY_POSTURES = [
327
+ "exclusive",
328
+ "shared_repo_only",
329
+ "shared_worktree",
330
+ "overlapping_actors",
331
+ "divergent_checkout",
332
+ "unknown",
333
+ ] as const;
334
+
335
+ export const repoConcurrencyPostureSchema = z.enum(REPO_CONCURRENCY_POSTURES);
336
+ export type RepoConcurrencyPosture = z.infer<typeof repoConcurrencyPostureSchema>;
337
+
338
+ export const REPO_CONCURRENCY_AUTHORITIES = [
339
+ "repo_identity_only",
340
+ "active_history_scan",
341
+ "daemon_live_sessions",
342
+ "footprint_overlap",
343
+ "explicit_handoff",
344
+ "unknown",
345
+ ] as const;
346
+
347
+ export const repoConcurrencyAuthoritySchema = z.enum(REPO_CONCURRENCY_AUTHORITIES);
348
+ export type RepoConcurrencyAuthority = z.infer<typeof repoConcurrencyAuthoritySchema>;
349
+
350
+ export const SEMANTIC_TRANSITION_PHASES = [
351
+ "started",
352
+ "conflicted",
353
+ "resolved_waiting_commit",
354
+ "continued",
355
+ "completed_or_cleared",
356
+ ] as const;
357
+
358
+ export const semanticTransitionPhaseSchema = z.enum(SEMANTIC_TRANSITION_PHASES);
359
+ export type SemanticTransitionPhase = z.infer<typeof semanticTransitionPhaseSchema>;
360
+
361
+ export const HANDOFF_KINDS = [
362
+ "attach",
363
+ "resume",
364
+ "fork",
365
+ "park",
366
+ ] as const;
367
+
368
+ export const handoffKindSchema = z.enum(HANDOFF_KINDS);
369
+ export type HandoffKind = z.infer<typeof handoffKindSchema>;
370
+
371
+ export const LOCAL_HISTORY_CONTINUITY_OPERATIONS = [
372
+ "start",
373
+ "attach",
374
+ "resume",
375
+ "fork",
376
+ "park",
377
+ ] as const;
378
+
379
+ export const localHistoryContinuityOperationSchema = z.enum(LOCAL_HISTORY_CONTINUITY_OPERATIONS);
380
+ export type LocalHistoryContinuityOperation = z.infer<typeof localHistoryContinuityOperationSchema>;
381
+
382
+ const causalEventCommonSchema = z.object({
383
+ eventId: z.string().min(1),
384
+ repoId: z.string().min(1),
385
+ worktreeId: z.string().min(1).nullable(),
386
+ checkoutEpochId: z.string().min(1).nullable(),
387
+ workspaceOverlayId: z.string().min(1).nullable(),
388
+ transportSessionId: z.string().min(1).nullable(),
389
+ workspaceSliceId: z.string().min(1).nullable(),
390
+ causalSessionId: z.string().min(1).nullable(),
391
+ strandId: z.string().min(1).nullable(),
392
+ actorId: z.string().min(1).nullable(),
393
+ confidence: attributionConfidenceSchema,
394
+ evidenceIds: z.array(z.string().min(1)),
395
+ attribution: attributionSummarySchema,
396
+ footprint: causalFootprintSchema,
397
+ occurredAt: z.string().min(1),
398
+ }).strict().superRefine((event, ctx) => {
399
+ if (!hasUniqueItems(event.evidenceIds)) {
400
+ ctx.addIssue({
401
+ code: "custom",
402
+ message: "Evidence ids must be unique",
403
+ path: ["evidenceIds"],
404
+ });
405
+ }
406
+ const attributionEvidenceIds = event.attribution.evidence.map((evidence) => evidence.evidenceId);
407
+ if (event.actorId !== event.attribution.actor.actorId) {
408
+ ctx.addIssue({
409
+ code: "custom",
410
+ message: "Causal event actorId must match attribution.actor.actorId",
411
+ path: ["actorId"],
412
+ });
413
+ }
414
+ if (event.confidence !== event.attribution.confidence) {
415
+ ctx.addIssue({
416
+ code: "custom",
417
+ message: "Causal event confidence must match attribution.confidence",
418
+ path: ["confidence"],
419
+ });
420
+ }
421
+ if (
422
+ attributionEvidenceIds.length !== event.evidenceIds.length ||
423
+ attributionEvidenceIds.some((evidenceId, index) => evidenceId !== event.evidenceIds[index])
424
+ ) {
425
+ ctx.addIssue({
426
+ code: "custom",
427
+ message: "Causal event evidenceIds must match attribution evidence ids in order",
428
+ path: ["evidenceIds"],
429
+ });
430
+ }
431
+ });
432
+
433
+ const readEventPayloadSchema = z.object({
434
+ surface: z.string().min(1),
435
+ projection: z.string().min(1),
436
+ sourceLayer: sourceLayerSchema,
437
+ reason: z.string().min(1),
438
+ }).strict();
439
+
440
+ const writeEventPayloadSchema = z.object({
441
+ surface: z.string().min(1),
442
+ writeKind: writeKindSchema,
443
+ beforeRef: z.string().min(1).optional(),
444
+ afterRef: z.string().min(1).optional(),
445
+ }).strict();
446
+
447
+ const decisionEventPayloadSchema = z.object({
448
+ decisionKind: decisionKindSchema,
449
+ summary: z.string().min(1),
450
+ }).strict();
451
+
452
+ const stageEventPayloadSchema = z.object({
453
+ targetId: z.string().min(1),
454
+ footprint: causalFootprintSchema,
455
+ selectionKind: selectionKindSchema,
456
+ }).strict();
457
+
458
+ const commitEventPayloadSchema = z.object({
459
+ commitSha: z.string().min(1),
460
+ parentShas: z.array(z.string().min(1)),
461
+ message: z.string(),
462
+ }).strict();
463
+
464
+ const transitionEventPayloadSchema = z.object({
465
+ semanticKind: semanticTransitionKindSchema,
466
+ authority: semanticTransitionAuthoritySchema,
467
+ phase: semanticTransitionPhaseSchema.nullable(),
468
+ summary: z.string().min(1),
469
+ transitionKind: transitionKindSchema.nullable(),
470
+ fromRef: z.string().min(1).nullable(),
471
+ toRef: z.string().min(1).nullable(),
472
+ createdCheckoutEpochId: z.string().min(1).nullable(),
473
+ }).strict();
474
+
475
+ const handoffEventPayloadSchema = z.object({
476
+ handoffKind: handoffKindSchema,
477
+ fromActorId: z.string().min(1).optional(),
478
+ toActorId: z.string().min(1).optional(),
479
+ notes: z.string().min(1).optional(),
480
+ }).strict();
481
+
482
+ export const readEventSchema = causalEventCommonSchema.extend({
483
+ eventKind: z.literal("read"),
484
+ payload: readEventPayloadSchema,
485
+ }).strict();
486
+
487
+ export const writeEventSchema = causalEventCommonSchema.extend({
488
+ eventKind: z.literal("write"),
489
+ payload: writeEventPayloadSchema,
490
+ }).strict();
491
+
492
+ export const decisionEventSchema = causalEventCommonSchema.extend({
493
+ eventKind: z.literal("decision"),
494
+ payload: decisionEventPayloadSchema,
495
+ }).strict();
496
+
497
+ export const stageEventSchema = causalEventCommonSchema.extend({
498
+ eventKind: z.literal("stage"),
499
+ payload: stageEventPayloadSchema,
500
+ }).strict();
501
+
502
+ export const commitEventSchema = causalEventCommonSchema.extend({
503
+ eventKind: z.literal("commit"),
504
+ payload: commitEventPayloadSchema,
505
+ }).strict();
506
+
507
+ export const transitionEventSchema = causalEventCommonSchema.extend({
508
+ eventKind: z.literal("transition"),
509
+ payload: transitionEventPayloadSchema,
510
+ }).strict();
511
+
512
+ export const handoffEventSchema = causalEventCommonSchema.extend({
513
+ eventKind: z.literal("handoff"),
514
+ payload: handoffEventPayloadSchema,
515
+ }).strict();
516
+
517
+ export const causalEventSchema = z.discriminatedUnion("eventKind", [
518
+ readEventSchema,
519
+ writeEventSchema,
520
+ decisionEventSchema,
521
+ stageEventSchema,
522
+ commitEventSchema,
523
+ transitionEventSchema,
524
+ handoffEventSchema,
525
+ ]);
526
+
527
+ export type CausalEvent = z.infer<typeof causalEventSchema>;
528
+
529
+ export const CAUSAL_PERSISTENCE_CLASSES = [
530
+ "canonical_structural_truth",
531
+ "canonical_provenance",
532
+ "strand_local",
533
+ "discardable",
534
+ ] as const;
535
+
536
+ export const causalPersistenceClassSchema = z.enum(CAUSAL_PERSISTENCE_CLASSES);
537
+ export type CausalPersistenceClass = z.infer<typeof causalPersistenceClassSchema>;
538
+
539
+ export const COLLAPSE_TARGET_KINDS = [
540
+ "staged_target",
541
+ "commit",
542
+ ] as const;
543
+
544
+ export const collapseTargetKindSchema = z.enum(COLLAPSE_TARGET_KINDS);
545
+ export type CollapseTargetKind = z.infer<typeof collapseTargetKindSchema>;
546
+
547
+ export const EXCLUSION_REASONS = [
548
+ "outside_target_footprint",
549
+ "different_checkout_epoch",
550
+ "different_causal_session",
551
+ "insufficient_evidence",
552
+ "precedes_selection_boundary",
553
+ ] as const;
554
+
555
+ export const exclusionReasonSchema = z.enum(EXCLUSION_REASONS);
556
+ export type ExclusionReason = z.infer<typeof exclusionReasonSchema>;
557
+
558
+ const collapseBoundarySchema = z.object({
559
+ afterEventId: z.string().min(1),
560
+ reason: exclusionReasonSchema,
561
+ note: z.string().min(1).optional(),
562
+ }).strict();
563
+
564
+ export const collapseWitnessSchema = z.object({
565
+ collapseRecordId: z.string().min(1),
566
+ targetKind: collapseTargetKindSchema,
567
+ targetId: z.string().min(1),
568
+ targetFootprint: causalFootprintSchema,
569
+ base: z.object({
570
+ repoId: z.string().min(1),
571
+ checkoutEpochId: z.string().min(1),
572
+ commitSha: z.string().min(1),
573
+ }).strict(),
574
+ causalSessionId: z.string().min(1),
575
+ strandIds: z.array(z.string().min(1)).min(1),
576
+ includedEventIds: z.array(z.string().min(1)).min(1),
577
+ sharedEventIds: z.array(z.string().min(1)),
578
+ excludedBoundaries: z.array(collapseBoundarySchema),
579
+ evidenceIds: z.array(z.string().min(1)).min(1),
580
+ confidence: attributionConfidenceSchema,
581
+ createdAt: z.string().min(1),
582
+ }).strict().superRefine((witness, ctx) => {
583
+ if (!hasUniqueItems(witness.strandIds)) {
584
+ ctx.addIssue({
585
+ code: "custom",
586
+ message: "Strand ids must be unique",
587
+ path: ["strandIds"],
588
+ });
589
+ }
590
+ if (!hasUniqueItems(witness.includedEventIds)) {
591
+ ctx.addIssue({
592
+ code: "custom",
593
+ message: "Included event ids must be unique",
594
+ path: ["includedEventIds"],
595
+ });
596
+ }
597
+ if (!hasUniqueItems(witness.sharedEventIds)) {
598
+ ctx.addIssue({
599
+ code: "custom",
600
+ message: "Shared event ids must be unique",
601
+ path: ["sharedEventIds"],
602
+ });
603
+ }
604
+ for (const [index, sharedEventId] of witness.sharedEventIds.entries()) {
605
+ if (!witness.includedEventIds.includes(sharedEventId)) {
606
+ ctx.addIssue({
607
+ code: "custom",
608
+ message: "Shared events must also appear in includedEventIds",
609
+ path: ["sharedEventIds", index],
610
+ });
611
+ }
612
+ }
613
+ if (!hasUniqueItems(witness.evidenceIds)) {
614
+ ctx.addIssue({
615
+ code: "custom",
616
+ message: "Witness evidence ids must be unique",
617
+ path: ["evidenceIds"],
618
+ });
619
+ }
620
+ });
621
+
622
+ export type CollapseWitness = z.infer<typeof collapseWitnessSchema>;
@@ -0,0 +1,18 @@
1
+ import { z } from "zod";
2
+
3
+ export const CAUSAL_SURFACE_NEXT_ACTIONS = [
4
+ "bind_workspace_to_begin_local_history",
5
+ "continue_active_causal_workspace",
6
+ "review_transition_boundary_before_continuing",
7
+ "inspect_or_resume_local_history",
8
+ "coordinate_shared_worktree_before_continuing",
9
+ "inspect_overlapping_actor_activity_before_continuing",
10
+ "review_divergent_checkout_before_continuing",
11
+ "resolve_conflicts_before_continuing",
12
+ "complete_merge_phase_before_continuing",
13
+ "continue_rebase_phase_before_continuing",
14
+ "inspect_bulk_transition_scope_before_continuing",
15
+ ] as const;
16
+
17
+ export const causalSurfaceNextActionSchema = z.enum(CAUSAL_SURFACE_NEXT_ACTIONS);
18
+ export type CausalSurfaceNextAction = z.infer<typeof causalSurfaceNextActionSchema>;