@leitwerk-dev/coding 0.2.0 → 0.3.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 (105) hide show
  1. package/README.md +28 -10
  2. package/dist/actions.d.ts +12 -3
  3. package/dist/actions.d.ts.map +1 -1
  4. package/dist/auto-work-branch-internal.d.ts +4 -0
  5. package/dist/auto-work-branch-internal.d.ts.map +1 -0
  6. package/dist/auto-work-branch.d.ts +1 -12
  7. package/dist/auto-work-branch.d.ts.map +1 -1
  8. package/dist/auto-work-branch.js +18 -97
  9. package/dist/auto-work-branch.js.map +1 -1
  10. package/dist/{chunk-EP3ZC37F.js → chunk-34B3Q75M.js} +1 -1
  11. package/dist/chunk-34B3Q75M.js.map +1 -0
  12. package/dist/{chunk-OFDNIT5X.js → chunk-F6CEEAFE.js} +1 -1
  13. package/dist/chunk-F6CEEAFE.js.map +1 -0
  14. package/dist/chunk-GO44KCUS.js +154 -0
  15. package/dist/chunk-GO44KCUS.js.map +1 -0
  16. package/dist/{chunk-WQEPA35Z.js → chunk-R3UCUGY6.js} +1 -1
  17. package/dist/chunk-R3UCUGY6.js.map +1 -0
  18. package/dist/{chunk-67YKGZLM.js → chunk-W7VJT6AN.js} +1 -1
  19. package/dist/chunk-W7VJT6AN.js.map +1 -0
  20. package/dist/{chunk-NIJCT4VK.js → chunk-WKHVLLKE.js} +1 -1
  21. package/dist/chunk-WKHVLLKE.js.map +1 -0
  22. package/dist/{chunk-UBVLJV3V.js → chunk-YSC5GEQJ.js} +1 -1
  23. package/dist/chunk-YSC5GEQJ.js.map +1 -0
  24. package/dist/finalization-git-internal.d.ts +33 -0
  25. package/dist/finalization-git-internal.d.ts.map +1 -0
  26. package/dist/finalization-git.d.ts +2 -47
  27. package/dist/finalization-git.d.ts.map +1 -1
  28. package/dist/finalization-git.js +3 -9
  29. package/dist/index.d.ts +3 -7
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +73 -112
  32. package/dist/index.js.map +1 -1
  33. package/dist/repository-change-launch-internal.d.ts +35 -0
  34. package/dist/repository-change-launch-internal.d.ts.map +1 -0
  35. package/dist/repository-change-launch.d.ts +2 -64
  36. package/dist/repository-change-launch.d.ts.map +1 -1
  37. package/dist/repository-change-launch.js +22 -11
  38. package/dist/repository-change-launch.js.map +1 -1
  39. package/dist/repository-change-process.d.ts +31 -13
  40. package/dist/repository-change-process.d.ts.map +1 -1
  41. package/dist/repository-change-publication.d.ts +229 -0
  42. package/dist/repository-change-publication.d.ts.map +1 -0
  43. package/dist/repository-change-publication.js +368 -0
  44. package/dist/repository-change-publication.js.map +1 -0
  45. package/dist/repository-change-state-internal.d.ts +21 -0
  46. package/dist/repository-change-state-internal.d.ts.map +1 -0
  47. package/dist/repository-change-state.d.ts +1 -17
  48. package/dist/repository-change-state.d.ts.map +1 -1
  49. package/dist/repository-change-state.js +0 -13
  50. package/dist/turns/generate-commit-message.d.ts +2 -0
  51. package/dist/turns/generate-commit-message.d.ts.map +1 -1
  52. package/dist/turns/generate-commit-message.js +1 -1
  53. package/dist/turns/generate-plan.d.ts +1 -0
  54. package/dist/turns/generate-plan.d.ts.map +1 -1
  55. package/dist/turns/generate-plan.js +1 -1
  56. package/dist/turns/implement.d.ts +1 -0
  57. package/dist/turns/implement.d.ts.map +1 -1
  58. package/dist/turns/implement.js +1 -1
  59. package/dist/turns/review-implementation.d.ts +1 -0
  60. package/dist/turns/review-implementation.d.ts.map +1 -1
  61. package/dist/turns/review-implementation.js +1 -1
  62. package/dist/turns/review-plan.d.ts +1 -0
  63. package/dist/turns/review-plan.d.ts.map +1 -1
  64. package/dist/turns/review-plan.js +1 -1
  65. package/dist/turns/simplify-implementation.d.ts +1 -0
  66. package/dist/turns/simplify-implementation.d.ts.map +1 -1
  67. package/dist/turns/simplify-implementation.js +1 -1
  68. package/package.json +24 -8
  69. package/src/actions.ts +12 -9
  70. package/src/auto-work-branch-internal.ts +41 -0
  71. package/src/auto-work-branch.ts +1 -140
  72. package/src/finalization-git-internal.ts +218 -0
  73. package/src/finalization-git.ts +2 -828
  74. package/src/index.ts +15 -4
  75. package/src/repository-change-launch-internal.ts +64 -0
  76. package/src/repository-change-launch.ts +10 -264
  77. package/src/repository-change-process.ts +33 -123
  78. package/src/repository-change-publication.ts +689 -0
  79. package/src/repository-change-state-internal.ts +60 -0
  80. package/src/repository-change-state.ts +1 -78
  81. package/src/turns/generate-commit-message.ts +2 -0
  82. package/src/turns/generate-plan.ts +1 -0
  83. package/src/turns/implement.ts +1 -0
  84. package/src/turns/review-implementation.ts +1 -0
  85. package/src/turns/review-plan.ts +1 -0
  86. package/src/turns/simplify-implementation.ts +1 -0
  87. package/dist/chunk-5LVPKVI2.js +0 -27
  88. package/dist/chunk-5LVPKVI2.js.map +0 -1
  89. package/dist/chunk-67YKGZLM.js.map +0 -1
  90. package/dist/chunk-73LKROYK.js +0 -616
  91. package/dist/chunk-73LKROYK.js.map +0 -1
  92. package/dist/chunk-EP3ZC37F.js.map +0 -1
  93. package/dist/chunk-NIJCT4VK.js.map +0 -1
  94. package/dist/chunk-OFDNIT5X.js.map +0 -1
  95. package/dist/chunk-UBVLJV3V.js.map +0 -1
  96. package/dist/chunk-WQEPA35Z.js.map +0 -1
  97. package/dist/chunk-Y2S6JFVO.js +0 -185
  98. package/dist/chunk-Y2S6JFVO.js.map +0 -1
  99. package/dist/chunk-YIP4MP64.js +0 -61
  100. package/dist/chunk-YIP4MP64.js.map +0 -1
  101. package/dist/turns/resolve-merge-conflict.d.ts +0 -3
  102. package/dist/turns/resolve-merge-conflict.d.ts.map +0 -1
  103. package/dist/turns/resolve-merge-conflict.js +0 -8
  104. package/dist/turns/resolve-merge-conflict.js.map +0 -1
  105. package/src/turns/resolve-merge-conflict.ts +0 -25
@@ -0,0 +1,689 @@
1
+ import { asUnknownRecord } from "@leitwerk-dev/domain";
2
+ import {
3
+ type ExternalActionSource,
4
+ type FlowAutomaticRunContext,
5
+ flow,
6
+ } from "@leitwerk-dev/process-sdk";
7
+ import {
8
+ type ConflictEvidence,
9
+ conflictKey,
10
+ validateConflict,
11
+ } from "@leitwerk-dev/repository-rebase";
12
+ import { publishRebase, startRebase } from "@leitwerk-dev/repository-rebase/git";
13
+ import { rebasePrompt } from "@leitwerk-dev/repository-rebase/prompt";
14
+ import { commitAndPushWorkBranch, type GitIdentity } from "./finalization-git.js";
15
+ import type { RepositoryChangeState } from "./repository-change-state.js";
16
+
17
+ /** @public */
18
+ export interface PublicationRequest {
19
+ /** @public */
20
+ number: number;
21
+ /** @public */
22
+ html_url: string;
23
+ /** @public */
24
+ merged: boolean;
25
+ /** @public */
26
+ merge_commit_sha?: string | null;
27
+ }
28
+ /** @public */
29
+ export interface PublicationPipeline {
30
+ /** @public */
31
+ number: number;
32
+ /** @public */
33
+ status: string;
34
+ /** @public */
35
+ [key: string]: unknown;
36
+ }
37
+ /** @public */
38
+ export interface PublicationParams {
39
+ /** @public */
40
+ owner: string;
41
+ /** @public */
42
+ repo: string;
43
+ /** @public */
44
+ workBranch: string;
45
+ /** @public */
46
+ baseBranch: string;
47
+ }
48
+ /** @public */
49
+ export type PublicationContext<P> = FlowAutomaticRunContext<P, RepositoryChangeState>;
50
+ /** @public */
51
+ export type PublicationEvidence = (
52
+ | {
53
+ /** @public */
54
+ kind: "feedback";
55
+ /** @public */
56
+ feedbackIds: PublicationFeedbackId[];
57
+ /** @public */
58
+ conversationCursor: number;
59
+ /** @public */
60
+ reviewCursor: number;
61
+ /** @public */
62
+ inlineCursor: number;
63
+ }
64
+ | {
65
+ /** @public */
66
+ kind: "failure";
67
+ /** @public */
68
+ pipeline: PublicationPipeline;
69
+ }
70
+ | {
71
+ /** @public */
72
+ kind: "conflict";
73
+ /** @public */
74
+ conflict: ConflictEvidence;
75
+ }
76
+ | {
77
+ /** @public */
78
+ kind: "terminal";
79
+ /** @public */
80
+ request: PublicationRequest;
81
+ }
82
+ | {
83
+ /** @public */
84
+ kind: "cancelled";
85
+ }
86
+ | {
87
+ /** @public */
88
+ kind: "observed";
89
+ }
90
+ ) & {
91
+ /** @public */
92
+ observationKey?: string;
93
+ };
94
+ /** @public */
95
+ export interface PublicationSource<P> {
96
+ /** @public */
97
+ id: string;
98
+ /** @public */
99
+ kind: "feedback" | "failure" | "conflict" | "terminal" | "cancelled" | "observation";
100
+ /** @public */
101
+ operatorId?: string;
102
+ /** @public */
103
+ label: string;
104
+ /** @public */
105
+ source: ExternalActionSource<P, RepositoryChangeState, unknown>;
106
+ /** @public */
107
+ enabled?(params: P): boolean;
108
+ /** @public */
109
+ read(input: {
110
+ /** @public */
111
+ params: P;
112
+ /** @public */
113
+ state: RepositoryChangeState;
114
+ /** @public */
115
+ event: unknown;
116
+ }): PublicationEvidence;
117
+ }
118
+ /** @public */
119
+ export interface RepositoryChangePublicationAdapter<P extends PublicationParams> {
120
+ /** @public */
121
+ namespace: string;
122
+ /** @public */
123
+ label: string;
124
+ /** @public */
125
+ ids: {
126
+ /** @public */
127
+ deliver: string;
128
+ /** @public */
129
+ feedback: string;
130
+ /** @public */
131
+ ciRepair: string;
132
+ /** @public */
133
+ operator: string;
134
+ };
135
+ /** @public */
136
+ tools: {
137
+ /** @public */
138
+ delivery: readonly string[];
139
+ /** @public */
140
+ feedback: readonly string[];
141
+ /** @public */
142
+ ci: readonly string[];
143
+ };
144
+ /** @public */
145
+ sources: readonly PublicationSource<P>[];
146
+ /** @public */
147
+ identity(ctx: PublicationContext<P>): Promise<GitIdentity>;
148
+ /** @public */
149
+ ensureRequest(ctx: PublicationContext<P>): Promise<PublicationRequest>;
150
+ /** @public */
151
+ reconcileTerminal(
152
+ ctx: PublicationContext<P>,
153
+ current: PublicationState,
154
+ request: PublicationRequest,
155
+ ): Promise<void>;
156
+ /** @public */
157
+ linkIssue(ctx: PublicationContext<P>, current: PublicationState): Promise<void>;
158
+ /** @public */
159
+ acknowledge(ctx: PublicationContext<P>, current: PublicationState): Promise<void>;
160
+ /** @public */
161
+ reply(ctx: PublicationContext<P>, current: PublicationState): Promise<void>;
162
+ /** @public */
163
+ afterRebase(ctx: PublicationContext<P>, current: PublicationState): Promise<void>;
164
+ /** @public */
165
+ head(ctx: PublicationContext<P>, current: PublicationState): Promise<string>;
166
+ /** @public */
167
+ prompt(kind: "feedback" | "ci", current: PublicationState): string;
168
+ /** @public */
169
+ commitMessage(kind: "feedback" | "ci"): string;
170
+ }
171
+ /** @public */
172
+ export type PublicationFeedbackId = {
173
+ /** @public */
174
+ kind: "conversation" | "review" | "inline";
175
+ /** @public */
176
+ id: number;
177
+ /** @public */
178
+ discussionId?: string;
179
+ };
180
+ /** @public */
181
+ type AdjustmentInvocation = {
182
+ /** @public */
183
+ origin: "feedback" | "ci" | "rebase";
184
+ /** @public */
185
+ publishRequired: boolean;
186
+ };
187
+
188
+ /** @public */
189
+ export interface DeliveryState {
190
+ /** @public */
191
+ stage: "not_started" | "branch_published" | "pull_request_ready" | "awaiting";
192
+ /** @public */
193
+ issueLinked: boolean;
194
+ /** @public */
195
+ adjustment: AdjustmentInvocation | null;
196
+ /** @public */
197
+ terminalPullRequest: PublicationRequest | null;
198
+ }
199
+
200
+ /** @public */
201
+ export interface PublicationState {
202
+ /** @public */
203
+ lastConflictKey?: string | null;
204
+ /** @public */
205
+ conflict?: ConflictEvidence | null;
206
+ /** @public */
207
+ repairReason?: "feedback" | "ci" | "rebase";
208
+ /** @public */
209
+ headSha: string | null;
210
+ /** @public */
211
+ prNumber: number | null;
212
+ /** @public */
213
+ prUrl: string | null;
214
+ /** @public */
215
+ conversationCursor: number;
216
+ /** @public */
217
+ reviewCursor: number;
218
+ /** @public */
219
+ inlineCursor: number;
220
+ /** @public */
221
+ feedbackIds: PublicationFeedbackId[];
222
+ /** @public */
223
+ pipeline: PublicationPipeline | null;
224
+ /** @public */
225
+ ciRecoveryCycles: number;
226
+ /** @public */
227
+ delivery: DeliveryState;
228
+ /** @public */
229
+ observationKey?: string;
230
+ /** @public */
231
+ pendingEvidence?: PublicationEvidence | null;
232
+ }
233
+
234
+ const initialDeliveryState: DeliveryState = {
235
+ stage: "not_started",
236
+ issueLinked: false,
237
+ adjustment: null,
238
+ terminalPullRequest: null,
239
+ };
240
+
241
+ const initialPublicationState: PublicationState = {
242
+ headSha: null,
243
+ prNumber: null,
244
+ prUrl: null,
245
+ conversationCursor: 0,
246
+ reviewCursor: 0,
247
+ inlineCursor: 0,
248
+ feedbackIds: [],
249
+ pipeline: null,
250
+ ciRecoveryCycles: 0,
251
+ delivery: initialDeliveryState,
252
+ };
253
+
254
+ /** @public */
255
+ export const publicationObject = (value: unknown) => asUnknownRecord(value) ?? {};
256
+
257
+ /** @public */
258
+ export function readPublicationState(
259
+ state: RepositoryChangeState,
260
+ namespace: string,
261
+ ): PublicationState {
262
+ const stored = publicationObject(publicationObject(state.extensionState)[namespace]);
263
+ return {
264
+ ...initialPublicationState,
265
+ ...stored,
266
+ delivery: {
267
+ ...initialDeliveryState,
268
+ ...publicationObject(stored.delivery),
269
+ },
270
+ } as PublicationState;
271
+ }
272
+
273
+ /** @public */
274
+ export function patchPublicationState(
275
+ state: RepositoryChangeState,
276
+ namespace: string,
277
+ patch: Partial<Omit<PublicationState, "delivery">> & {
278
+ /** @public */
279
+ delivery?: Partial<DeliveryState>;
280
+ },
281
+ ): RepositoryChangeState {
282
+ const current = readPublicationState(state, namespace);
283
+ return {
284
+ ...state,
285
+ extensionState: {
286
+ ...state.extensionState,
287
+ [namespace]: {
288
+ ...current,
289
+ ...patch,
290
+ delivery: { ...current.delivery, ...patch.delivery },
291
+ },
292
+ },
293
+ };
294
+ }
295
+
296
+ /** @public */
297
+ export function applyPublicationEvidence(
298
+ params: PublicationParams,
299
+ current: PublicationState,
300
+ evidence: PublicationEvidence,
301
+ countFailure = true,
302
+ ): PublicationState {
303
+ if (evidence.observationKey !== undefined)
304
+ current = { ...current, observationKey: evidence.observationKey };
305
+ switch (evidence.kind) {
306
+ case "feedback": {
307
+ const { kind: _, ...batch } = evidence;
308
+ return { ...current, ...batch, repairReason: "feedback" };
309
+ }
310
+ case "failure":
311
+ return {
312
+ ...current,
313
+ repairReason: "ci",
314
+ pipeline: evidence.pipeline,
315
+ ciRecoveryCycles: current.ciRecoveryCycles + (countFailure ? 1 : 0),
316
+ };
317
+ case "conflict": {
318
+ const conflict = validateConflict(
319
+ evidence.conflict,
320
+ {
321
+ owner: params.owner,
322
+ repo: params.repo,
323
+ prNumber: current.prNumber ?? 0,
324
+ headSha: current.headSha ?? "",
325
+ headBranch: params.workBranch,
326
+ baseBranch: params.baseBranch,
327
+ },
328
+ current.lastConflictKey,
329
+ );
330
+ return {
331
+ ...current,
332
+ conflict,
333
+ lastConflictKey: conflictKey(conflict),
334
+ repairReason: "rebase",
335
+ };
336
+ }
337
+ case "terminal":
338
+ return {
339
+ ...current,
340
+ delivery: { ...current.delivery, terminalPullRequest: evidence.request },
341
+ };
342
+ default:
343
+ return current;
344
+ }
345
+ }
346
+ function deliveryProgress(value: PublicationState, label: string, activeStepId?: string) {
347
+ const delivery = value.delivery;
348
+ const step = (id: string, label: string, done: boolean) => ({
349
+ id,
350
+ label,
351
+ status: (activeStepId === id ? "in_progress" : done ? "completed" : "incomplete") as
352
+ | "in_progress"
353
+ | "completed"
354
+ | "incomplete",
355
+ });
356
+ const adjustmentHandled =
357
+ delivery.adjustment === null && delivery.stage === "awaiting" && value.headSha !== null;
358
+ return {
359
+ title: "Delivery progress",
360
+ steps: [
361
+ step("publish_branch", "Publish work branch", value.headSha !== null),
362
+ step("open_pr", "Create or find pull request", value.prNumber !== null),
363
+ step("link_issue", "Link source issue when applicable", delivery.issueLinked),
364
+ step("publish_adjustment", "Publish an adjustment when applicable", adjustmentHandled),
365
+ step(
366
+ "reply_feedback",
367
+ "Acknowledge or reply to feedback when applicable",
368
+ value.feedbackIds.length === 0,
369
+ ),
370
+ step("await_evidence", "Await external evidence", delivery.stage === "awaiting"),
371
+ step(
372
+ "reconcile_terminal",
373
+ "Reconcile terminal pull request",
374
+ delivery.terminalPullRequest !== null,
375
+ ),
376
+ ],
377
+ ...(value.prNumber && value.prUrl
378
+ ? {
379
+ links: [
380
+ {
381
+ id: `${label}-pr-${value.prNumber}`,
382
+ label: `${label} #${value.prNumber}`,
383
+ url: value.prUrl,
384
+ kind: "pull_request" as const,
385
+ },
386
+ ],
387
+ }
388
+ : {}),
389
+ };
390
+ }
391
+
392
+ /** @public */
393
+ export function createRepositoryChangePublication<P extends PublicationParams>(
394
+ adapter: RepositoryChangePublicationAdapter<P>,
395
+ ) {
396
+ const applyEvidence = applyPublicationEvidence;
397
+ const ids = adapter.ids;
398
+ const publication = flow.fragment<P, RepositoryChangeState>(`${adapter.namespace}-publication`);
399
+ const remote = (state: RepositoryChangeState) => readPublicationState(state, adapter.namespace);
400
+ const patchRemote = (
401
+ state: RepositoryChangeState,
402
+ patch: Partial<Omit<PublicationState, "delivery">> & { delivery?: Partial<DeliveryState> },
403
+ ) => patchPublicationState(state, adapter.namespace, patch);
404
+ async function commitWorkBranch(ctx: PublicationContext<P>, commitMessage: string) {
405
+ const repo = ctx.repo.get("repo");
406
+ return commitAndPushWorkBranch({
407
+ repoPath: repo.fsPath,
408
+ workBranch: repo.workBranch,
409
+ commitMessage,
410
+ gitIdentity: await adapter.identity(ctx),
411
+ });
412
+ }
413
+ const delivery = flow
414
+ .automatic<P, RepositoryChangeState>(ids.deliver)
415
+ .description("Deliver")
416
+ .integrationTools(...adapter.tools.delivery)
417
+ .run(async (ctx) => {
418
+ let current = remote(ctx.state);
419
+ const update = (patch: Parameters<typeof patchRemote>[1]) => {
420
+ current = { ...current, ...patch, delivery: { ...current.delivery, ...patch.delivery } };
421
+ };
422
+ const result = (
423
+ outcome:
424
+ | "awaiting"
425
+ | "feedback_ready"
426
+ | "completed"
427
+ | "aborted"
428
+ | "ci_ready"
429
+ | "conflict_ready"
430
+ | "operator_action",
431
+ ) => ({
432
+ outcome,
433
+ params: { nextState: patchRemote(ctx.state, current) },
434
+ });
435
+ if (current.pendingEvidence) {
436
+ const evidence = current.pendingEvidence;
437
+ const needsOperator = evidence.kind === "failure" && current.ciRecoveryCycles >= 3;
438
+ current = applyEvidence(ctx.params, current, evidence, !needsOperator);
439
+ current.pendingEvidence = null;
440
+ if (evidence.kind === "cancelled") return result("aborted");
441
+ if (evidence.kind === "failure")
442
+ return result(needsOperator ? "operator_action" : "ci_ready");
443
+ if (evidence.kind === "conflict") return result("conflict_ready");
444
+ }
445
+ ctx.reportProgress(deliveryProgress(current, adapter.label));
446
+
447
+ if (current.delivery.terminalPullRequest) {
448
+ ctx.reportProgress(deliveryProgress(current, adapter.label, "reconcile_terminal"));
449
+ const pr = current.delivery.terminalPullRequest;
450
+ await adapter.reconcileTerminal(ctx, current, pr);
451
+ ctx.reportProgress(deliveryProgress(current, adapter.label));
452
+ return result(pr.merged ? "completed" : "aborted");
453
+ }
454
+
455
+ if (!current.headSha) {
456
+ ctx.reportProgress(deliveryProgress(current, adapter.label, "publish_branch"));
457
+ const published = await commitWorkBranch(
458
+ ctx,
459
+ ctx.state.finalization.generatedCommitMessage ?? "",
460
+ );
461
+ update({ headSha: published.headSha, pipeline: null });
462
+ }
463
+
464
+ if (!current.prNumber || !current.prUrl) {
465
+ ctx.reportProgress(deliveryProgress(current, adapter.label, "open_pr"));
466
+ const pr = await adapter.ensureRequest(ctx);
467
+ update({ prNumber: pr.number, prUrl: pr.html_url });
468
+ }
469
+
470
+ if (!current.delivery.issueLinked) {
471
+ ctx.reportProgress(deliveryProgress(current, adapter.label, "link_issue"));
472
+ await adapter.linkIssue(ctx, current);
473
+ update({ delivery: { issueLinked: true } });
474
+ }
475
+
476
+ if (current.delivery.adjustment) {
477
+ const adjustment = current.delivery.adjustment;
478
+ if (adjustment.publishRequired || adjustment.origin === "rebase") {
479
+ ctx.reportProgress(deliveryProgress(current, adapter.label, "publish_adjustment"));
480
+ const published =
481
+ adjustment.origin === "rebase"
482
+ ? publishRebase(rebaseInput(ctx))
483
+ : await commitWorkBranch(ctx, adapter.commitMessage(adjustment.origin));
484
+ if (adjustment.origin === "rebase") {
485
+ const head = await adapter.head(ctx, current);
486
+ if (head !== published.headSha)
487
+ throw new Error("Pull request head has not caught up with rebase publication");
488
+ }
489
+ update({ headSha: published.headSha, pipeline: null });
490
+ }
491
+ if (adjustment.origin === "rebase") await adapter.afterRebase(ctx, current);
492
+ if (adjustment.origin === "feedback") {
493
+ ctx.reportProgress(deliveryProgress(current, adapter.label, "reply_feedback"));
494
+ await adapter.reply(ctx, current);
495
+ }
496
+ update({
497
+ ...(adjustment.origin === "feedback" ? { feedbackIds: [] } : {}),
498
+ delivery: { adjustment: null },
499
+ });
500
+ }
501
+
502
+ if (current.feedbackIds.length > 0) {
503
+ ctx.reportProgress(deliveryProgress(current, adapter.label, "reply_feedback"));
504
+ await adapter.acknowledge(ctx, current);
505
+ return result("feedback_ready");
506
+ }
507
+
508
+ update({ delivery: { stage: "awaiting" } });
509
+ ctx.reportProgress(deliveryProgress(current, adapter.label, "await_evidence"));
510
+ return result("awaiting");
511
+ })
512
+ .outcome("awaiting", (outcome) =>
513
+ outcome
514
+ .description("Delivery is waiting for external evidence")
515
+ .object("nextState")
516
+ .wait()
517
+ .state(({ event }) => event.params.nextState as RepositoryChangeState),
518
+ )
519
+ .outcome("feedback_ready", (outcome) =>
520
+ outcome
521
+ .description("Pull request feedback is acknowledged and ready for revision")
522
+ .object("nextState")
523
+ .to(ids.feedback)
524
+ .state(({ event }) => event.params.nextState as RepositoryChangeState),
525
+ )
526
+ .outcome("completed", (outcome) =>
527
+ outcome
528
+ .description("Merged pull request was reconciled")
529
+ .object("nextState")
530
+ .complete()
531
+ .state(({ event }) => event.params.nextState as RepositoryChangeState),
532
+ )
533
+ .outcome("aborted", (outcome) =>
534
+ outcome
535
+ .description("Closed pull request was reconciled")
536
+ .object("nextState")
537
+ .lifecycleStatus("aborted")
538
+ .state(({ event }) => event.params.nextState as RepositoryChangeState),
539
+ );
540
+ for (const [outcome, target] of [
541
+ ["ci_ready", ids.ciRepair],
542
+ ["conflict_ready", ids.feedback],
543
+ ["operator_action", ids.operator],
544
+ ] as const) {
545
+ delivery.outcome(outcome, (o) =>
546
+ o
547
+ .description("Route observed delivery evidence")
548
+ .object("nextState")
549
+ .to(target)
550
+ .state(({ event }) => event.params.nextState as RepositoryChangeState),
551
+ );
552
+ }
553
+ for (const source of adapter.sources) {
554
+ const attach = (id: string, operator: boolean) =>
555
+ delivery.externalAction(id, source.source, (external) => {
556
+ external
557
+ .label(source.label)
558
+ .when(
559
+ ({ params, state }) =>
560
+ (!source.enabled || source.enabled(params)) &&
561
+ (source.kind !== "failure" || remote(state).ciRecoveryCycles >= 3 === operator),
562
+ );
563
+ if (source.kind === "cancelled") return external.lifecycleStatus("aborted");
564
+ external.to(
565
+ source.kind === "conflict"
566
+ ? ids.feedback
567
+ : source.kind === "failure"
568
+ ? operator
569
+ ? ids.operator
570
+ : ids.ciRepair
571
+ : ids.deliver,
572
+ );
573
+ return external.effect((input) => {
574
+ const evidence = source.read(input);
575
+ const current = remote(input.state);
576
+ return {
577
+ state: patchRemote(
578
+ input.state,
579
+ source.kind === "observation"
580
+ ? { pendingEvidence: evidence }
581
+ : applyEvidence(input.params, current, evidence, !operator),
582
+ ),
583
+ };
584
+ });
585
+ });
586
+ attach(source.id, false);
587
+ if (source.kind === "failure") attach(source.operatorId ?? `${source.id}_operator`, true);
588
+ }
589
+ publication.turn(delivery);
590
+ function rebaseInput(ctx: {
591
+ state: RepositoryChangeState;
592
+ repo: { get(key: string): { fsPath: string; workBranch: string } };
593
+ }) {
594
+ const project = ctx.repo.get("repo");
595
+ const conflict = remote(ctx.state).conflict;
596
+ if (!conflict) throw new Error("Missing conflict evidence");
597
+ return { projectKey: "repo", path: project.fsPath, workBranch: project.workBranch, conflict };
598
+ }
599
+ function repairReason(state: RepositoryChangeState, kind: "feedback" | "ci") {
600
+ return kind === "feedback" && remote(state).repairReason === "rebase" ? "rebase" : kind;
601
+ }
602
+
603
+ function revisionPrompt(kind: "feedback" | "ci") {
604
+ return (ctx: { state: RepositoryChangeState }) => {
605
+ const current = remote(ctx.state);
606
+ if (repairReason(ctx.state, kind) === "rebase")
607
+ return `${rebasePrompt} Evidence: ${JSON.stringify(current.conflict)}. Call changes_ready or no_changes when verified complete, cannot_repair when blocked.`;
608
+ return adapter.prompt(kind, current);
609
+ };
610
+ }
611
+
612
+ function revisionTurn(id: string, kind: "feedback" | "ci") {
613
+ const turn = flow
614
+ .llm<P, RepositoryChangeState>(id)
615
+ .description(kind === "feedback" ? "Address Feedback" : "Fix CI")
616
+ .tools("read", "bash", "edit", "write")
617
+ .resolveIntegrationTools((_params, state) =>
618
+ repairReason(state, kind) === "rebase" ? [] : adapter.tools[kind],
619
+ )
620
+ .prepare((ctx) =>
621
+ repairReason(ctx.state, kind) === "rebase" ? startRebase(rebaseInput(ctx)) : {},
622
+ )
623
+ .freshPrimary()
624
+ .prompt(revisionPrompt(kind));
625
+ for (const [name, description, publishRequired] of [
626
+ ["changes_ready", "Repository changes are ready to publish", true],
627
+ ["no_changes", "No repository change is required", false],
628
+ ] as const) {
629
+ turn.outcomeTool(name, (tool) =>
630
+ tool
631
+ .resultSummary()
632
+ .description(description)
633
+ .to(ids.deliver)
634
+ .state(({ ctx }) =>
635
+ patchRemote(ctx.state, {
636
+ delivery: { adjustment: { origin: repairReason(ctx.state, kind), publishRequired } },
637
+ }),
638
+ ),
639
+ );
640
+ }
641
+ return turn.outcomeTool("cannot_repair", (tool) =>
642
+ tool.description("The adjustment requires operator action").to(ids.operator),
643
+ );
644
+ }
645
+
646
+ publication.turn(revisionTurn(ids.feedback, "feedback"));
647
+ publication.turn(revisionTurn(ids.ciRepair, "ci"));
648
+ publication.turn({
649
+ id: ids.operator,
650
+ definition: {
651
+ kind: "human",
652
+ description: "Repository repair needs operator action",
653
+ operatorAttention: "required",
654
+ actions: {
655
+ retry_repair: {
656
+ label: "Retry repair",
657
+ acceptanceState: "accepted",
658
+ branches: { feedback: { to: ids.feedback }, ci: { to: ids.ciRepair } },
659
+ choose: ({ ctx }) =>
660
+ remote(ctx.state).repairReason === "rebase" ||
661
+ remote(ctx.state).repairReason === "feedback"
662
+ ? "feedback"
663
+ : "ci",
664
+ },
665
+ resume_waiting: {
666
+ label: "Resume waiting",
667
+ acceptanceState: "accepted",
668
+ to: ids.deliver,
669
+ effect: ({ ctx }) => ({
670
+ state: patchRemote(ctx.state, {
671
+ feedbackIds: [],
672
+ delivery: { adjustment: null },
673
+ }),
674
+ }),
675
+ },
676
+ abort: { label: "Abort process", acceptanceState: "neutral", lifecycleStatus: "aborted" },
677
+ },
678
+ },
679
+ });
680
+
681
+ return {
682
+ /** @public */
683
+ entryTurnId: ids.deliver,
684
+ /** @public */
685
+ fragment: publication,
686
+ /** @public */
687
+ happyPath: [ids.deliver],
688
+ };
689
+ }