@leitwerk-dev/coding 0.1.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 (99) hide show
  1. package/README.md +9 -0
  2. package/dist/LICENSE +13 -0
  3. package/dist/actions.d.ts +18 -0
  4. package/dist/actions.d.ts.map +1 -0
  5. package/dist/actions.js +45 -0
  6. package/dist/actions.js.map +1 -0
  7. package/dist/auto-work-branch.d.ts +17 -0
  8. package/dist/auto-work-branch.d.ts.map +1 -0
  9. package/dist/auto-work-branch.js +112 -0
  10. package/dist/auto-work-branch.js.map +1 -0
  11. package/dist/chunk-5LVPKVI2.js +27 -0
  12. package/dist/chunk-5LVPKVI2.js.map +1 -0
  13. package/dist/chunk-67YKGZLM.js +25 -0
  14. package/dist/chunk-67YKGZLM.js.map +1 -0
  15. package/dist/chunk-DSQX3ZHJ.js +60 -0
  16. package/dist/chunk-DSQX3ZHJ.js.map +1 -0
  17. package/dist/chunk-JZU3UVR6.js +573 -0
  18. package/dist/chunk-JZU3UVR6.js.map +1 -0
  19. package/dist/chunk-NIJCT4VK.js +45 -0
  20. package/dist/chunk-NIJCT4VK.js.map +1 -0
  21. package/dist/chunk-OFDNIT5X.js +13 -0
  22. package/dist/chunk-OFDNIT5X.js.map +1 -0
  23. package/dist/chunk-PX6F3LHL.js +40 -0
  24. package/dist/chunk-PX6F3LHL.js.map +1 -0
  25. package/dist/chunk-RWCLBBB2.js +34 -0
  26. package/dist/chunk-RWCLBBB2.js.map +1 -0
  27. package/dist/chunk-RZ54IVY5.js +28 -0
  28. package/dist/chunk-RZ54IVY5.js.map +1 -0
  29. package/dist/chunk-UBVLJV3V.js +23 -0
  30. package/dist/chunk-UBVLJV3V.js.map +1 -0
  31. package/dist/chunk-Y2S6JFVO.js +185 -0
  32. package/dist/chunk-Y2S6JFVO.js.map +1 -0
  33. package/dist/dist-CFKPEMX5.js +546 -0
  34. package/dist/dist-CFKPEMX5.js.map +1 -0
  35. package/dist/finalization-git.d.ts +34 -0
  36. package/dist/finalization-git.d.ts.map +1 -0
  37. package/dist/finalization-git.js +533 -0
  38. package/dist/finalization-git.js.map +1 -0
  39. package/dist/index.d.ts +11 -0
  40. package/dist/index.d.ts.map +1 -0
  41. package/dist/index.js +7 -0
  42. package/dist/index.js.map +1 -0
  43. package/dist/magic-string.es-4IX5OHLL.js +1309 -0
  44. package/dist/magic-string.es-4IX5OHLL.js.map +1 -0
  45. package/dist/repository-change-launch.d.ts +65 -0
  46. package/dist/repository-change-launch.d.ts.map +1 -0
  47. package/dist/repository-change-launch.js +183 -0
  48. package/dist/repository-change-launch.js.map +1 -0
  49. package/dist/repository-change-process.d.ts +38 -0
  50. package/dist/repository-change-process.d.ts.map +1 -0
  51. package/dist/repository-change-process.js +751 -0
  52. package/dist/repository-change-process.js.map +1 -0
  53. package/dist/repository-change-state.d.ts +16 -0
  54. package/dist/repository-change-state.d.ts.map +1 -0
  55. package/dist/repository-change-state.js +52 -0
  56. package/dist/repository-change-state.js.map +1 -0
  57. package/dist/turns/generate-commit-message.d.ts +4 -0
  58. package/dist/turns/generate-commit-message.d.ts.map +1 -0
  59. package/dist/turns/generate-commit-message.js +39 -0
  60. package/dist/turns/generate-commit-message.js.map +1 -0
  61. package/dist/turns/generate-plan.d.ts +3 -0
  62. package/dist/turns/generate-plan.d.ts.map +1 -0
  63. package/dist/turns/generate-plan.js +20 -0
  64. package/dist/turns/generate-plan.js.map +1 -0
  65. package/dist/turns/implement.d.ts +3 -0
  66. package/dist/turns/implement.d.ts.map +1 -0
  67. package/dist/turns/implement.js +18 -0
  68. package/dist/turns/implement.js.map +1 -0
  69. package/dist/turns/resolve-merge-conflict.d.ts +3 -0
  70. package/dist/turns/resolve-merge-conflict.d.ts.map +1 -0
  71. package/dist/turns/resolve-merge-conflict.js +22 -0
  72. package/dist/turns/resolve-merge-conflict.js.map +1 -0
  73. package/dist/turns/review-implementation.d.ts +4 -0
  74. package/dist/turns/review-implementation.d.ts.map +1 -0
  75. package/dist/turns/review-implementation.js +28 -0
  76. package/dist/turns/review-implementation.js.map +1 -0
  77. package/dist/turns/review-plan.d.ts +4 -0
  78. package/dist/turns/review-plan.d.ts.map +1 -0
  79. package/dist/turns/review-plan.js +22 -0
  80. package/dist/turns/review-plan.js.map +1 -0
  81. package/dist/turns/simplify-implementation.d.ts +3 -0
  82. package/dist/turns/simplify-implementation.d.ts.map +1 -0
  83. package/dist/turns/simplify-implementation.js +8 -0
  84. package/dist/turns/simplify-implementation.js.map +1 -0
  85. package/package.json +72 -0
  86. package/src/actions.ts +60 -0
  87. package/src/auto-work-branch.ts +145 -0
  88. package/src/finalization-git.ts +741 -0
  89. package/src/index.ts +9 -0
  90. package/src/repository-change-launch.ts +264 -0
  91. package/src/repository-change-process.ts +933 -0
  92. package/src/repository-change-state.ts +75 -0
  93. package/src/turns/generate-commit-message.ts +49 -0
  94. package/src/turns/generate-plan.ts +23 -0
  95. package/src/turns/implement.ts +21 -0
  96. package/src/turns/resolve-merge-conflict.ts +25 -0
  97. package/src/turns/review-implementation.ts +32 -0
  98. package/src/turns/review-plan.ts +26 -0
  99. package/src/turns/simplify-implementation.ts +11 -0
@@ -0,0 +1,933 @@
1
+ import { createReviewSubject, normalizeOptionalMarkdown } from "@leitwerk-dev/domain";
2
+ import {
3
+ acceptedReviewHandoffAction,
4
+ type Codec,
5
+ createEmptyStructuralProcessState,
6
+ type FormDefinition,
7
+ flow,
8
+ type HumanTurnDefinition,
9
+ humanTurn,
10
+ type ProcessLauncherDefinition,
11
+ type RepositoryCredentialProject,
12
+ type RepositoryCredentialRequirement,
13
+ revisionAction,
14
+ } from "@leitwerk-dev/process-sdk";
15
+ import {
16
+ acceptReviewForm,
17
+ codingActionIds,
18
+ requestReviewChangesForm,
19
+ requestRevisionForm,
20
+ } from "./actions.js";
21
+ import { runDeterministicFinalization } from "./finalization-git.js";
22
+ import {
23
+ clearReviewRefs,
24
+ createEmptyRepositoryChangeFinalizationState,
25
+ type RepositoryChangeState,
26
+ repositoryChangeStateCodec,
27
+ resetRepositoryChangeFinalizationState,
28
+ } from "./repository-change-state.js";
29
+ import {
30
+ buildGenerateCommitMessagePrompt,
31
+ normalizeGeneratedCommitMessage,
32
+ } from "./turns/generate-commit-message.js";
33
+ import { buildGeneratePlanPrompt } from "./turns/generate-plan.js";
34
+ import { buildImplementPrompt } from "./turns/implement.js";
35
+ import { buildResolveMergeConflictPrompt } from "./turns/resolve-merge-conflict.js";
36
+ import { buildReviewImplementationPrompt } from "./turns/review-implementation.js";
37
+ import { buildReviewPlanPrompt } from "./turns/review-plan.js";
38
+ import { buildSimplifyImplementationPrompt } from "./turns/simplify-implementation.js";
39
+
40
+ export type RepositoryChangeParams = {
41
+ launchKind: "requested_change" | "imported_plan";
42
+ importedPlanMarkdown?: string;
43
+ };
44
+
45
+ export interface RepositoryChangeProcessConfig<TParams extends RepositoryChangeParams> {
46
+ processId: string;
47
+ displayName: string;
48
+ paramsCodec: Codec<TParams>;
49
+ launcher: ProcessLauncherDefinition<TParams>;
50
+ finalizeLabel: string;
51
+ finalizeForm: FormDefinition;
52
+ finalizationDescription: string;
53
+ repositoryCredentials?(input: {
54
+ params: TParams;
55
+ projects: readonly RepositoryCredentialProject[];
56
+ }): readonly RepositoryCredentialRequirement[];
57
+ }
58
+
59
+ export function createRepositoryChangeProcess<TParams extends RepositoryChangeParams>(
60
+ config: RepositoryChangeProcessConfig<TParams>,
61
+ ) {
62
+ const planReviewSubject = createReviewSubject("plan");
63
+ const implementationReviewSubject = createReviewSubject("implementation");
64
+
65
+ const turnIds = {
66
+ importPlan: "import_plan",
67
+ generatePlan: "generate_plan",
68
+ planDecision: "plan_decision",
69
+ reviewPlan: "review_plan",
70
+ planReviewFeedback: "plan_review_feedback",
71
+ implement: "implement",
72
+ implementationDecision: "implementation_decision",
73
+ reviewImplementation: "review_implementation",
74
+ implementationReviewFeedback: "implementation_review_feedback",
75
+ simplifyImplementation: "simplify_implementation",
76
+ simplificationDecision: "simplification_decision",
77
+ generateCommitMessage: "generate_commit_message",
78
+ commitAndMerge: "commit_and_merge",
79
+ resolveMergeConflict: "resolve_merge_conflict",
80
+ } as const;
81
+
82
+ const products = {
83
+ plan: "plan",
84
+ review: "review",
85
+ simplificationPlan: "simplification-plan",
86
+ implementationSummary: "implementation-summary",
87
+ mergeResolutionSummary: "merge-resolution-summary",
88
+ commitMessage: "commit-message",
89
+ } as const;
90
+
91
+ const implementationTurnAvailableTools = ["read", "bash", "edit", "write"] as const;
92
+
93
+ function normalizeMessage(value: unknown): string {
94
+ return typeof value === "string" ? value.trim() : "";
95
+ }
96
+
97
+ function resetFinalizationAfterMessage(
98
+ state: RepositoryChangeState,
99
+ overrides: Partial<RepositoryChangeState["finalization"]> = {},
100
+ ) {
101
+ return resetRepositoryChangeFinalizationState({
102
+ generatedCommitMessage: state.finalization.generatedCommitMessage,
103
+ ...overrides,
104
+ });
105
+ }
106
+
107
+ function hasResolvedTurnRecordRef(
108
+ ref: RepositoryChangeState["semanticEntryRefs"][keyof RepositoryChangeState["semanticEntryRefs"]],
109
+ ): ref is { entryId: string; turnRecordId: string } {
110
+ return typeof ref?.turnRecordId === "string" && ref.turnRecordId.trim() !== "";
111
+ }
112
+
113
+ function requireResolvedPlanRef(
114
+ plan: RepositoryChangeState["semanticEntryRefs"][keyof RepositoryChangeState["semanticEntryRefs"]],
115
+ usage: "simplification review" | "implementation review",
116
+ ): asserts plan is { entryId: string; turnRecordId: string } {
117
+ if (!hasResolvedTurnRecordRef(plan)) {
118
+ throw new Error(`No plan is available for ${usage}`);
119
+ }
120
+ }
121
+
122
+ function buildImplementationReviewTurnState(ctx: {
123
+ state: RepositoryChangeState;
124
+ }): RepositoryChangeState {
125
+ return patchRepositoryChangeState(ctx.state, {
126
+ reviewSubject: implementationReviewSubject,
127
+ clearReviewRefs: true,
128
+ clearProductRefs: [products.simplificationPlan],
129
+ });
130
+ }
131
+
132
+ function buildAcceptedReviewFollowUpMessage(input: {
133
+ reviewSubject: { kind: "plan" | "implementation" };
134
+ reviewMarkdown: string;
135
+ adjustment?: string | null;
136
+ }): string {
137
+ const adjustment = normalizeMessage(input.adjustment);
138
+ if (input.reviewSubject.kind === "plan") {
139
+ return [
140
+ "Revise the plan according to this review:",
141
+ input.reviewMarkdown,
142
+ adjustment
143
+ ? ["Also follow this adjustment where it conflicts with the review:", adjustment].join(
144
+ "\n\n",
145
+ )
146
+ : null,
147
+ ]
148
+ .filter((section): section is string => typeof section === "string" && section !== "")
149
+ .join("\n\n");
150
+ }
151
+ return buildAcceptedImplementationFollowUpMessage({
152
+ kind: "review",
153
+ implementationMarkdown: input.reviewMarkdown,
154
+ adjustment,
155
+ });
156
+ }
157
+
158
+ function buildAcceptedImplementationFollowUpMessage(input: {
159
+ kind: "review" | "simplification";
160
+ implementationMarkdown: string;
161
+ adjustment?: string | null;
162
+ }): string {
163
+ const adjustment = normalizeMessage(input.adjustment);
164
+ const isSimplification = input.kind === "simplification";
165
+ const subject = isSimplification ? "simplification plan" : "review";
166
+
167
+ return [
168
+ `Implement according to this ${subject}:`,
169
+ input.implementationMarkdown,
170
+ adjustment
171
+ ? [`Also follow this adjustment where it conflicts with the ${subject}:`, adjustment].join(
172
+ "\n\n",
173
+ )
174
+ : null,
175
+ [
176
+ "This is now an implementation turn. Ignore earlier review-only or read-only instructions.",
177
+ "You may change files in the repository workspace.",
178
+ `Use the available tools (${implementationTurnAvailableTools.join(", ")}) to inspect, edit, build, and test the change.`,
179
+ "When finished, return an implementation summary.",
180
+ ].join("\n"),
181
+ ]
182
+ .filter((section): section is string => typeof section === "string" && section !== "")
183
+ .join("\n\n");
184
+ }
185
+
186
+ function buildAcceptedSimplificationFollowUpMessage(input: {
187
+ simplificationMarkdown: string;
188
+ adjustment?: string | null;
189
+ }): string {
190
+ return buildAcceptedImplementationFollowUpMessage({
191
+ kind: "simplification",
192
+ implementationMarkdown: input.simplificationMarkdown,
193
+ adjustment: input.adjustment,
194
+ });
195
+ }
196
+
197
+ function patchRepositoryChangeState(
198
+ state: RepositoryChangeState,
199
+ input: {
200
+ reviewSubject?: RepositoryChangeState["reviewSubject"];
201
+ finalization?: RepositoryChangeState["finalization"];
202
+ semanticEntryRefs?: RepositoryChangeState["semanticEntryRefs"];
203
+ clearReviewRefs?: boolean;
204
+ clearProductRefs?: readonly string[];
205
+ },
206
+ ): RepositoryChangeState {
207
+ const nextState: RepositoryChangeState = {
208
+ ...state,
209
+ ...("reviewSubject" in input ? { reviewSubject: input.reviewSubject ?? null } : {}),
210
+ ...("finalization" in input ? { finalization: input.finalization } : {}),
211
+ ...("semanticEntryRefs" in input ? { semanticEntryRefs: input.semanticEntryRefs } : {}),
212
+ };
213
+ const productRefsToClear = new Set(input.clearProductRefs ?? []);
214
+ if (input.clearReviewRefs) {
215
+ productRefsToClear.add(products.review);
216
+ }
217
+ if (!input.clearReviewRefs && productRefsToClear.size === 0) {
218
+ return nextState;
219
+ }
220
+ const productRefs = { ...nextState.productRefs };
221
+ for (const productName of productRefsToClear) {
222
+ delete productRefs[productName];
223
+ }
224
+ return {
225
+ ...nextState,
226
+ semanticEntryRefs: input.clearReviewRefs
227
+ ? clearReviewRefs(nextState.semanticEntryRefs)
228
+ : nextState.semanticEntryRefs,
229
+ productRefs,
230
+ };
231
+ }
232
+
233
+ const planDecisionSpec = humanTurn<TParams, RepositoryChangeState>({
234
+ description: "Review plan",
235
+ reviewSubject: planReviewSubject,
236
+ reviewSemanticRef: "plan",
237
+ notesFields: [
238
+ {
239
+ id: "message",
240
+ label: "Revision notes",
241
+ placeholder: "Describe what the next plan revision should improve",
242
+ required: true,
243
+ },
244
+ ],
245
+ commentary: "Approve this plan, request a revision, or run an automated review.",
246
+ actions: {
247
+ [codingActionIds.approvePlan]: {
248
+ label: "Approve plan",
249
+ description: "Accept the current plan and continue into implementation.",
250
+ acceptanceState: "accepted",
251
+ to: turnIds.implement,
252
+ effect: ({ ctx }) => {
253
+ const plan = ctx.state.semanticEntryRefs.plan;
254
+ if (!hasResolvedTurnRecordRef(plan)) {
255
+ throw new Error("No plan is available for approval");
256
+ }
257
+ return {
258
+ state: patchRepositoryChangeState(ctx.state, {
259
+ reviewSubject: null,
260
+ clearReviewRefs: true,
261
+ clearProductRefs: [products.simplificationPlan],
262
+ }),
263
+ emit: [
264
+ {
265
+ type: "plan_approved",
266
+ data: {
267
+ externalId: ctx.process.externalId,
268
+ planRevision: ctx.process.planRevision,
269
+ },
270
+ },
271
+ ],
272
+ };
273
+ },
274
+ },
275
+ [codingActionIds.requestRevision]: revisionAction({
276
+ label: "Request revision",
277
+ description: "Send the plan back for another draft revision.",
278
+ acceptanceState: "requires_changes",
279
+ form: requestRevisionForm,
280
+ schedulable: true,
281
+ to: turnIds.generatePlan,
282
+ queueTarget: { semanticRef: "currentPrimaryPathLeaf" },
283
+ effect: ({ ctx, input }) => {
284
+ const message = normalizeMessage(input.message);
285
+ return {
286
+ state: patchRepositoryChangeState(ctx.state, {
287
+ reviewSubject: null,
288
+ clearReviewRefs: true,
289
+ clearProductRefs: [products.simplificationPlan],
290
+ }),
291
+ emit: [{ type: "plan_revision_requested", data: { message } }],
292
+ };
293
+ },
294
+ }),
295
+ [codingActionIds.runReview]: {
296
+ label: "Run automated review",
297
+ description: "Send the current plan to the LLM reviewer.",
298
+ acceptanceState: "neutral",
299
+ schedulable: true,
300
+ to: turnIds.reviewPlan,
301
+ effect: ({ ctx }) => {
302
+ const plan = ctx.state.semanticEntryRefs.plan;
303
+ if (!hasResolvedTurnRecordRef(plan)) {
304
+ throw new Error("No plan is available for review");
305
+ }
306
+ return {
307
+ state: patchRepositoryChangeState(ctx.state, {
308
+ reviewSubject: planReviewSubject,
309
+ clearReviewRefs: true,
310
+ clearProductRefs: [products.simplificationPlan],
311
+ }),
312
+ };
313
+ },
314
+ },
315
+ },
316
+ });
317
+
318
+ const planReviewFeedbackSpec = humanTurn<TParams, RepositoryChangeState>({
319
+ description: "Review plan feedback",
320
+ reviewSubject: planReviewSubject,
321
+ reviewSemanticRef: "review",
322
+ notesFields: [
323
+ {
324
+ id: "message",
325
+ label: "Review notes",
326
+ placeholder: "Describe how the next review pass should change",
327
+ required: true,
328
+ },
329
+ ],
330
+ commentary:
331
+ "Apply this feedback to the next plan revision, request a revised review, or dismiss it.",
332
+ actions: {
333
+ [codingActionIds.acceptReview]: acceptedReviewHandoffAction({
334
+ label: "Accept review",
335
+ description: "Apply the current review outcome and continue with the plan flow.",
336
+ acceptanceState: "accepted",
337
+ form: acceptReviewForm,
338
+ to: turnIds.generatePlan,
339
+ resolveBodyMarkdown: ({ ctx, input }) => {
340
+ const reviewMarkdown = normalizeOptionalMarkdown(
341
+ ctx.readSemanticTurnResultMarkdown("review"),
342
+ );
343
+ if (!reviewMarkdown) {
344
+ throw new Error("No review output markdown is available to accept");
345
+ }
346
+ return buildAcceptedReviewFollowUpMessage({
347
+ reviewSubject: planReviewSubject,
348
+ reviewMarkdown,
349
+ adjustment: normalizeMessage(input.message),
350
+ });
351
+ },
352
+ effect: ({ ctx }) => ({
353
+ state: patchRepositoryChangeState(ctx.state, {
354
+ reviewSubject: null,
355
+ }),
356
+ }),
357
+ }),
358
+ [codingActionIds.requestReviewChanges]: revisionAction({
359
+ label: "Request review changes",
360
+ description: "Ask the LLM reviewer to revise its plan review.",
361
+ acceptanceState: "requires_changes",
362
+ form: requestReviewChangesForm,
363
+ to: turnIds.reviewPlan,
364
+ queueTarget: { semanticRef: "review" },
365
+ effect: ({ ctx }) => ({
366
+ state: patchRepositoryChangeState(ctx.state, {
367
+ reviewSubject: planReviewSubject,
368
+ }),
369
+ }),
370
+ }),
371
+ [codingActionIds.dismissReview]: {
372
+ label: "Dismiss review",
373
+ description: "Return to the plan decision without applying the review.",
374
+ acceptanceState: "neutral",
375
+ to: turnIds.planDecision,
376
+ effect: ({ ctx }) => ({
377
+ state: patchRepositoryChangeState(ctx.state, {
378
+ reviewSubject: planReviewSubject,
379
+ }),
380
+ }),
381
+ },
382
+ },
383
+ });
384
+
385
+ const implementationDecisionSpec = humanTurn<TParams, RepositoryChangeState>({
386
+ description: "Review implementation",
387
+ reviewSubject: implementationReviewSubject,
388
+ reviewSemanticRef: "currentPrimaryPathLeaf",
389
+ notesFields: [
390
+ {
391
+ id: "message",
392
+ label: "Revision notes",
393
+ placeholder: "Describe what the next implementation turn should improve",
394
+ required: true,
395
+ },
396
+ ],
397
+ commentary:
398
+ "Merge this implementation, request another pass, simplify it, or run an automated review.",
399
+ actions: {
400
+ [codingActionIds.finalizeChange]: {
401
+ label: config.finalizeLabel,
402
+ acceptanceState: "accepted",
403
+ form: config.finalizeForm,
404
+ schedulable: true,
405
+ to: turnIds.generateCommitMessage,
406
+ effect: ({ ctx }) => ({
407
+ state: patchRepositoryChangeState(ctx.state, {
408
+ reviewSubject: null,
409
+ finalization: createEmptyRepositoryChangeFinalizationState(),
410
+ clearReviewRefs: true,
411
+ clearProductRefs: [products.simplificationPlan],
412
+ }),
413
+ }),
414
+ },
415
+ [codingActionIds.requestRevision]: revisionAction({
416
+ label: "Request revision",
417
+ acceptanceState: "requires_changes",
418
+ form: requestRevisionForm,
419
+ schedulable: true,
420
+ to: turnIds.implement,
421
+ queueTarget: { semanticRef: "currentPrimaryPathLeaf" },
422
+ effect: ({ ctx }) => ({
423
+ state: patchRepositoryChangeState(ctx.state, {
424
+ reviewSubject: null,
425
+ clearReviewRefs: true,
426
+ clearProductRefs: [products.simplificationPlan],
427
+ }),
428
+ }),
429
+ }),
430
+ [codingActionIds.simplify]: {
431
+ label: "Simplify",
432
+ description: "Ask for a focused simplification review before another implementation pass.",
433
+ acceptanceState: "neutral",
434
+ schedulable: true,
435
+ to: turnIds.simplifyImplementation,
436
+ effect: ({ ctx }) => {
437
+ requireResolvedPlanRef(ctx.state.semanticEntryRefs.plan, "simplification review");
438
+ return { state: buildImplementationReviewTurnState(ctx) };
439
+ },
440
+ },
441
+ [codingActionIds.runReview]: {
442
+ label: "Run automated review",
443
+ acceptanceState: "neutral",
444
+ schedulable: true,
445
+ to: turnIds.reviewImplementation,
446
+ effect: ({ ctx }) => {
447
+ requireResolvedPlanRef(ctx.state.semanticEntryRefs.plan, "implementation review");
448
+ return { state: buildImplementationReviewTurnState(ctx) };
449
+ },
450
+ },
451
+ },
452
+ });
453
+
454
+ const implementationReviewFeedbackSpec = humanTurn<TParams, RepositoryChangeState>({
455
+ description: "Review implementation feedback",
456
+ reviewSubject: implementationReviewSubject,
457
+ reviewSemanticRef: "review",
458
+ notesFields: [
459
+ {
460
+ id: "message",
461
+ label: "Review notes",
462
+ placeholder: "Describe how the next implementation review pass should change",
463
+ required: true,
464
+ },
465
+ ],
466
+ commentary:
467
+ "Apply this feedback to the next implementation pass, request a revised review, or dismiss it.",
468
+ actions: {
469
+ [codingActionIds.acceptReview]: acceptedReviewHandoffAction({
470
+ label: "Accept review",
471
+ acceptanceState: "accepted",
472
+ form: acceptReviewForm,
473
+ schedulable: true,
474
+ to: turnIds.implement,
475
+ queueTarget: { semanticRef: "review" },
476
+ resolveBodyMarkdown: ({ ctx, input }) => {
477
+ const reviewMarkdown = normalizeOptionalMarkdown(
478
+ ctx.readSemanticTurnResultMarkdown("review"),
479
+ );
480
+ if (!reviewMarkdown) {
481
+ throw new Error("No review output markdown is available to accept");
482
+ }
483
+ return buildAcceptedReviewFollowUpMessage({
484
+ reviewSubject: implementationReviewSubject,
485
+ reviewMarkdown,
486
+ adjustment: normalizeMessage(input.message),
487
+ });
488
+ },
489
+ effect: ({ ctx }) => ({
490
+ state: patchRepositoryChangeState(ctx.state, {
491
+ reviewSubject: null,
492
+ clearProductRefs: [products.simplificationPlan],
493
+ }),
494
+ }),
495
+ }),
496
+ [codingActionIds.requestReviewChanges]: revisionAction({
497
+ label: "Request review changes",
498
+ acceptanceState: "requires_changes",
499
+ form: requestReviewChangesForm,
500
+ schedulable: true,
501
+ to: turnIds.reviewImplementation,
502
+ queueTarget: { semanticRef: "review" },
503
+ effect: ({ ctx }) => ({
504
+ state: patchRepositoryChangeState(ctx.state, {
505
+ reviewSubject: implementationReviewSubject,
506
+ }),
507
+ }),
508
+ }),
509
+ [codingActionIds.dismissReview]: {
510
+ label: "Dismiss review",
511
+ acceptanceState: "neutral",
512
+ to: turnIds.implementationDecision,
513
+ effect: ({ ctx }) => ({
514
+ state: patchRepositoryChangeState(ctx.state, {
515
+ reviewSubject: implementationReviewSubject,
516
+ }),
517
+ }),
518
+ },
519
+ },
520
+ });
521
+
522
+ const simplificationDecisionSpec = humanTurn<TParams, RepositoryChangeState>({
523
+ description: "Review simplification plan",
524
+ reviewSubject: implementationReviewSubject,
525
+ reviewProduct: products.simplificationPlan,
526
+ notesFields: [
527
+ {
528
+ id: "message",
529
+ label: "Simplification notes",
530
+ placeholder: "Describe how the simplification plan should change",
531
+ required: true,
532
+ },
533
+ ],
534
+ commentary: "Apply this simplification plan, request changes to it, or reject it.",
535
+ actions: {
536
+ [codingActionIds.acceptReview]: acceptedReviewHandoffAction({
537
+ label: "Accept simplification plan",
538
+ acceptanceState: "accepted",
539
+ form: acceptReviewForm,
540
+ schedulable: true,
541
+ to: turnIds.implement,
542
+ queueTarget: { productName: products.simplificationPlan },
543
+ resolveBodyMarkdown: ({ ctx, input }) => {
544
+ const simplificationMarkdown = normalizeOptionalMarkdown(
545
+ ctx.readProductTurnResultMarkdown(products.simplificationPlan),
546
+ );
547
+ if (!simplificationMarkdown) {
548
+ throw new Error("No simplification plan markdown is available to accept");
549
+ }
550
+ return buildAcceptedSimplificationFollowUpMessage({
551
+ simplificationMarkdown,
552
+ adjustment: normalizeMessage(input.message),
553
+ });
554
+ },
555
+ effect: ({ ctx }) => ({
556
+ state: patchRepositoryChangeState(ctx.state, {
557
+ reviewSubject: null,
558
+ clearReviewRefs: true,
559
+ }),
560
+ }),
561
+ }),
562
+ [codingActionIds.requestReviewChanges]: revisionAction({
563
+ label: "Request simplification changes",
564
+ acceptanceState: "requires_changes",
565
+ form: requestReviewChangesForm,
566
+ to: turnIds.simplifyImplementation,
567
+ queueTarget: { productName: products.simplificationPlan },
568
+ effect: ({ ctx }) => ({
569
+ state: patchRepositoryChangeState(ctx.state, {
570
+ reviewSubject: implementationReviewSubject,
571
+ }),
572
+ }),
573
+ }),
574
+ [codingActionIds.dismissReview]: {
575
+ label: "Reject simplification plan",
576
+ description:
577
+ "Return to the implementation decision without applying the simplification plan.",
578
+ acceptanceState: "neutral",
579
+ to: turnIds.implementationDecision,
580
+ effect: ({ ctx }) => ({
581
+ state: patchRepositoryChangeState(ctx.state, {
582
+ reviewSubject: implementationReviewSubject,
583
+ clearReviewRefs: true,
584
+ clearProductRefs: [products.simplificationPlan],
585
+ }),
586
+ }),
587
+ },
588
+ },
589
+ });
590
+
591
+ const importPlanTurn = flow
592
+ .serverAutomatic<TParams, RepositoryChangeState>(turnIds.importPlan)
593
+ .description("Import handoff plan")
594
+ .run((ctx) => {
595
+ const planMarkdown =
596
+ ctx.params.launchKind === "imported_plan"
597
+ ? normalizeOptionalMarkdown(ctx.params.importedPlanMarkdown)
598
+ : null;
599
+ if (!planMarkdown) {
600
+ throw new Error("No importedPlanMarkdown is available to import");
601
+ }
602
+ return {
603
+ outcome: "imported",
604
+ params: { plan: planMarkdown },
605
+ markdown: planMarkdown,
606
+ state: patchRepositoryChangeState(ctx.state, {
607
+ reviewSubject: null,
608
+ clearReviewRefs: true,
609
+ clearProductRefs: [products.simplificationPlan],
610
+ }),
611
+ };
612
+ })
613
+ .outcome("imported", (outcome) =>
614
+ outcome
615
+ .description("Imported a handoff plan and skipped replanning")
616
+ .markdown("plan", { description: "Imported handoff plan", publish: true })
617
+ .to(turnIds.implement)
618
+ .effect(({ ctx }) => ({ processPatch: { planRevision: ctx.process.planRevision + 1 } })),
619
+ );
620
+
621
+ const generatePlanTurn = flow
622
+ .llm<TParams, RepositoryChangeState>(turnIds.generatePlan)
623
+ .description("Draft plan")
624
+ .tools("read", "bash")
625
+ .askQuestions()
626
+ .freshPrimary()
627
+ .buildPrompt(buildGeneratePlanPrompt)
628
+ .outcomeTool("plan_saved", (tool) =>
629
+ tool
630
+ .description(
631
+ "Save the finished plan for review. Its Markdown may include Mermaid diagrams or uploaded images.",
632
+ )
633
+ .requiredString("summary", "Short summary of the proposed plan")
634
+ .requiredStringArray(
635
+ "acceptanceCriteria",
636
+ "Acceptance criteria for the requested repository change",
637
+ )
638
+ .to(turnIds.planDecision)
639
+ .effect(({ ctx, event }) => {
640
+ const planRevision = ctx.process.planRevision + 1;
641
+ const summary = normalizeMessage(event.params.summary);
642
+ const acceptanceCriteria = Array.isArray(event.params.acceptanceCriteria)
643
+ ? event.params.acceptanceCriteria.filter(
644
+ (entry): entry is string => typeof entry === "string" && entry.trim() !== "",
645
+ )
646
+ : [];
647
+ const planMarkdown = ctx.output?.content ?? "";
648
+ return {
649
+ state: patchRepositoryChangeState(ctx.state, {
650
+ reviewSubject: planReviewSubject,
651
+ clearReviewRefs: true,
652
+ clearProductRefs: [products.simplificationPlan],
653
+ }),
654
+ processPatch: { planRevision },
655
+ broadcasts: [
656
+ {
657
+ type: "plan.updated",
658
+ payload: {
659
+ planRevision,
660
+ reviewState: "awaiting_approval",
661
+ approved: false,
662
+ summary,
663
+ },
664
+ },
665
+ ],
666
+ emit: [
667
+ {
668
+ type: "plan_saved",
669
+ data: {
670
+ planRevision,
671
+ summary,
672
+ planMarkdown,
673
+ acceptanceCriteria,
674
+ },
675
+ },
676
+ ],
677
+ };
678
+ }),
679
+ )
680
+ .publish(products.plan);
681
+
682
+ const reviewPlanTurn = flow
683
+ .llm<TParams, RepositoryChangeState>(turnIds.reviewPlan)
684
+ .description("Review plan")
685
+ .tools("read", "bash")
686
+ .rootBranchReview()
687
+ .startFromReviewBranch()
688
+ .reviews(planReviewSubject)
689
+ .consume(products.plan)
690
+ .buildPrompt(buildReviewPlanPrompt)
691
+ .outcomeTool("no_issues", (tool) =>
692
+ tool
693
+ .description(
694
+ "Approve the plan and publish the review. Its Markdown may include Mermaid diagrams or uploaded images.",
695
+ )
696
+ .to(turnIds.planDecision)
697
+ .state(({ ctx }) =>
698
+ patchRepositoryChangeState(ctx.state, {
699
+ reviewSubject: planReviewSubject,
700
+ }),
701
+ ),
702
+ )
703
+ .outcomeTool("request_changes", (tool) =>
704
+ tool
705
+ .description(
706
+ "Request plan changes and publish actionable feedback. Its Markdown may include Mermaid diagrams or uploaded images.",
707
+ )
708
+ .to(turnIds.planReviewFeedback)
709
+ .state(({ ctx }) =>
710
+ patchRepositoryChangeState(ctx.state, {
711
+ reviewSubject: planReviewSubject,
712
+ }),
713
+ ),
714
+ )
715
+ .publish(products.review);
716
+
717
+ const implementTurn = flow
718
+ .llm<TParams, RepositoryChangeState>(turnIds.implement)
719
+ .description("Implement change")
720
+ .tools(...implementationTurnAvailableTools)
721
+ .freshSeededPrimary()
722
+ .continueFromProductBranch(products.simplificationPlan, {
723
+ kind: "semantic_ref",
724
+ ref: "review",
725
+ fallback: { kind: "session_root" },
726
+ })
727
+ .consume(products.plan)
728
+ .buildPrompt(buildImplementPrompt)
729
+ .publish(products.implementationSummary)
730
+ .to(turnIds.implementationDecision)
731
+ .state(({ ctx }) =>
732
+ patchRepositoryChangeState(ctx.state, {
733
+ reviewSubject: implementationReviewSubject,
734
+ clearReviewRefs: true,
735
+ clearProductRefs: [products.simplificationPlan],
736
+ }),
737
+ );
738
+
739
+ const reviewImplementationTurn = flow
740
+ .llm<TParams, RepositoryChangeState>(turnIds.reviewImplementation)
741
+ .description("Review implementation")
742
+ .tools("read", "bash")
743
+ .rootBranchReview()
744
+ .startFromReviewBranch()
745
+ .reviews(implementationReviewSubject)
746
+ .buildPrompt(buildReviewImplementationPrompt)
747
+ .outcomeTool("no_issues", (tool) =>
748
+ tool
749
+ .description(
750
+ "Approve the implementation and publish the review. Its Markdown may include Mermaid diagrams or uploaded images.",
751
+ )
752
+ .to(turnIds.implementationDecision)
753
+ .state(({ ctx }) =>
754
+ patchRepositoryChangeState(ctx.state, {
755
+ reviewSubject: implementationReviewSubject,
756
+ }),
757
+ ),
758
+ )
759
+ .outcomeTool("request_changes", (tool) =>
760
+ tool
761
+ .description(
762
+ "Request implementation changes and publish actionable feedback. Its Markdown may include Mermaid diagrams or uploaded images.",
763
+ )
764
+ .to(turnIds.implementationReviewFeedback)
765
+ .state(({ ctx }) =>
766
+ patchRepositoryChangeState(ctx.state, {
767
+ reviewSubject: implementationReviewSubject,
768
+ }),
769
+ ),
770
+ )
771
+ .publish(products.review);
772
+
773
+ const simplifyImplementationTurn = flow
774
+ .llm<TParams, RepositoryChangeState>(turnIds.simplifyImplementation)
775
+ .description("Simplify implementation")
776
+ .tools("read", "bash")
777
+ .rootBranchReview()
778
+ .startFromProductBranch(products.simplificationPlan)
779
+ .buildPrompt(buildSimplifyImplementationPrompt)
780
+ .publish(products.simplificationPlan)
781
+ .to(turnIds.simplificationDecision)
782
+ .state(({ ctx }) =>
783
+ patchRepositoryChangeState(ctx.state, {
784
+ reviewSubject: implementationReviewSubject,
785
+ }),
786
+ );
787
+
788
+ const generateCommitMessageTurn = flow
789
+ .llm<TParams, RepositoryChangeState>(turnIds.generateCommitMessage)
790
+ .description("Generate commit message")
791
+ .modelPurpose("process_title_generation")
792
+ .rootBranchReview()
793
+ .startFromRoot()
794
+ .consume(products.plan)
795
+ .buildPrompt(buildGenerateCommitMessagePrompt)
796
+ .publish(products.commitMessage)
797
+ .to(turnIds.commitAndMerge)
798
+ .state(({ ctx }) =>
799
+ patchRepositoryChangeState(ctx.state, {
800
+ finalization: {
801
+ ...ctx.state.finalization,
802
+ generatedCommitMessage: normalizeGeneratedCommitMessage(ctx.output?.content),
803
+ },
804
+ }),
805
+ );
806
+
807
+ const commitAndMergeTurn = flow
808
+ .automatic<TParams, RepositoryChangeState>(turnIds.commitAndMerge)
809
+ .description(config.finalizationDescription)
810
+ .run(runDeterministicFinalization)
811
+ .outcome("merge_conflict", (outcome) =>
812
+ outcome
813
+ .description("Deterministic merge hit conflicts and needs conflict resolution")
814
+ .requiredString("headSha", "The current HEAD sha while the merge conflict is active")
815
+ .stringArray("conflictedFiles", "Conflicted files that need resolution")
816
+ .string("fetchedBaseSha", "The fetched origin/<baseBranch> sha when available")
817
+ .to(turnIds.resolveMergeConflict)
818
+ .state(({ ctx }) =>
819
+ patchRepositoryChangeState(ctx.state, {
820
+ finalization: resetFinalizationAfterMessage(ctx.state),
821
+ }),
822
+ ),
823
+ )
824
+ .outcome("finalized", (outcome) =>
825
+ outcome
826
+ .description("Deterministic finalization succeeded")
827
+ .requiredString("headSha", "The final HEAD sha")
828
+ .requiredString("mergeMode", "How origin/<baseBranch> was integrated")
829
+ .requiredString("pushTarget", "The final base-branch publish target")
830
+ .requiredBoolean("usedConflictResolution", "Whether the merge required conflict resolution")
831
+ .complete()
832
+ .state(({ ctx, event }) =>
833
+ patchRepositoryChangeState(ctx.state, {
834
+ reviewSubject: null,
835
+ finalization: resetFinalizationAfterMessage(ctx.state, {
836
+ usedConflictResolution:
837
+ event.params.usedConflictResolution === true ||
838
+ ctx.state.finalization.usedConflictResolution,
839
+ finalizationSummaryMarkdown: normalizeOptionalMarkdown(ctx.output?.content),
840
+ finalizedHeadSha: normalizeMessage(event.params.headSha),
841
+ }),
842
+ }),
843
+ ),
844
+ );
845
+
846
+ const resolveMergeConflictTurn = flow
847
+ .llm<TParams, RepositoryChangeState>(turnIds.resolveMergeConflict)
848
+ .description("Resolve merge conflict")
849
+ .tools("read", "bash", "edit", "write")
850
+ .fullPrimary()
851
+ .startFromRoot()
852
+ .buildPrompt(buildResolveMergeConflictPrompt)
853
+ .outcomeTool("clean", (tool) =>
854
+ tool
855
+ .description("The merge conflict was resolved and the repository is clean")
856
+ .requiredString("headSha", "The post-resolution HEAD sha")
857
+ .to(turnIds.commitAndMerge)
858
+ .state(({ ctx, event }) =>
859
+ patchRepositoryChangeState(ctx.state, {
860
+ finalization: resetFinalizationAfterMessage(ctx.state, {
861
+ expectedPostConflictHeadSha: normalizeMessage(event.params.headSha),
862
+ usedConflictResolution: true,
863
+ }),
864
+ }),
865
+ ),
866
+ )
867
+ .publish(products.mergeResolutionSummary);
868
+
869
+ const planFlow = flow
870
+ .fragment<TParams, RepositoryChangeState>("plan")
871
+ .turn(importPlanTurn)
872
+ .turn(generatePlanTurn)
873
+ .turn({ id: turnIds.planDecision, definition: planDecisionSpec })
874
+ .turn(reviewPlanTurn)
875
+ .turn({ id: turnIds.planReviewFeedback, definition: planReviewFeedbackSpec });
876
+
877
+ const implementationFlow = flow
878
+ .fragment<TParams, RepositoryChangeState>("implementation")
879
+ .turn(implementTurn)
880
+ .turn({ id: turnIds.implementationDecision, definition: implementationDecisionSpec })
881
+ .turn(reviewImplementationTurn)
882
+ .turn({
883
+ id: turnIds.implementationReviewFeedback,
884
+ definition: implementationReviewFeedbackSpec,
885
+ })
886
+ .turn(simplifyImplementationTurn)
887
+ .turn({ id: turnIds.simplificationDecision, definition: simplificationDecisionSpec });
888
+
889
+ const finalizationFlow = flow
890
+ .fragment<TParams, RepositoryChangeState>("finalization")
891
+ .turn(generateCommitMessageTurn)
892
+ .turn(commitAndMergeTurn)
893
+ .turn(resolveMergeConflictTurn);
894
+
895
+ const builder = flow
896
+ .process<TParams, RepositoryChangeState>(config.processId)
897
+ .displayName(config.displayName)
898
+ .entry(turnIds.generatePlan)
899
+ .alternateEntry(turnIds.importPlan)
900
+ .happyPath(
901
+ turnIds.generatePlan,
902
+ turnIds.implement,
903
+ turnIds.generateCommitMessage,
904
+ turnIds.commitAndMerge,
905
+ )
906
+ .piConfig({ sessionCwdTemplate: "{{{projectKey}}}" })
907
+ .codecs({
908
+ params: config.paramsCodec,
909
+ state: repositoryChangeStateCodec,
910
+ })
911
+ .initialState(() => ({
912
+ ...createEmptyStructuralProcessState(),
913
+ finalization: createEmptyRepositoryChangeFinalizationState(),
914
+ }))
915
+ .use(planFlow)
916
+ .use(implementationFlow)
917
+ .use(finalizationFlow);
918
+ if (config.repositoryCredentials) builder.repositoryCredentials(config.repositoryCredentials);
919
+ const process = builder.launcher(config.launcher).define();
920
+ const decision = (id: string) =>
921
+ ({
922
+ id,
923
+ ...(process.turns.get(id)?.definition as HumanTurnDefinition),
924
+ }) as HumanTurnDefinition & { id: string };
925
+ return {
926
+ process,
927
+ planDecision: decision(turnIds.planDecision),
928
+ planReviewFeedback: decision(turnIds.planReviewFeedback),
929
+ implementationDecision: decision(turnIds.implementationDecision),
930
+ implementationReviewFeedback: decision(turnIds.implementationReviewFeedback),
931
+ simplificationDecision: decision(turnIds.simplificationDecision),
932
+ };
933
+ }