@leitwerk-dev/coding 0.3.1 → 0.4.1

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 (123) hide show
  1. package/README.md +154 -13
  2. package/dist/chunk-3WJRJ3Q7.js +220 -0
  3. package/dist/chunk-3WJRJ3Q7.js.map +1 -0
  4. package/dist/chunk-ABQH2WZT.js +36 -0
  5. package/dist/chunk-ABQH2WZT.js.map +1 -0
  6. package/dist/chunk-B3PE6DPF.js +820 -0
  7. package/dist/chunk-B3PE6DPF.js.map +1 -0
  8. package/dist/chunk-DNG7D77K.js +65 -0
  9. package/dist/chunk-DNG7D77K.js.map +1 -0
  10. package/dist/chunk-E3DB4TIZ.js +49 -0
  11. package/dist/chunk-E3DB4TIZ.js.map +1 -0
  12. package/dist/chunk-L2TFD72B.js +16320 -0
  13. package/dist/chunk-L2TFD72B.js.map +1 -0
  14. package/dist/chunk-M2VTUPFO.js +265 -0
  15. package/dist/chunk-M2VTUPFO.js.map +1 -0
  16. package/dist/{chunk-YSC5GEQJ.js → chunk-QD6FI4HR.js} +7 -3
  17. package/dist/chunk-QD6FI4HR.js.map +1 -0
  18. package/dist/chunk-SKGB4CZS.js +14 -0
  19. package/dist/chunk-SKGB4CZS.js.map +1 -0
  20. package/dist/chunk-SZ4WOGV2.js +120 -0
  21. package/dist/chunk-SZ4WOGV2.js.map +1 -0
  22. package/dist/finalization-git-internal.d.ts +9 -0
  23. package/dist/finalization-git-internal.d.ts.map +1 -1
  24. package/dist/finalization-git.d.ts +1 -1
  25. package/dist/finalization-git.d.ts.map +1 -1
  26. package/dist/finalization-git.js +6 -3
  27. package/dist/index.d.ts +1 -0
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +18 -591
  30. package/dist/index.js.map +1 -1
  31. package/dist/pull-request-publication-internal.d.ts +34 -24
  32. package/dist/pull-request-publication-internal.d.ts.map +1 -1
  33. package/dist/repository-change-launch-internal-BudnAfL7.d.ts +88 -0
  34. package/dist/repository-change-launch-internal.d.ts +32 -11
  35. package/dist/repository-change-launch-internal.d.ts.map +1 -1
  36. package/dist/repository-change-launch.d.ts +4 -3
  37. package/dist/repository-change-launch.d.ts.map +1 -1
  38. package/dist/repository-change-launch.js +162 -34
  39. package/dist/repository-change-launch.js.map +1 -1
  40. package/dist/repository-change-process-DlgF04fU.d.ts +69 -0
  41. package/dist/repository-change-process.d.ts +30 -25
  42. package/dist/repository-change-process.d.ts.map +1 -1
  43. package/dist/repository-change-publication.d.ts +76 -7
  44. package/dist/repository-change-publication.d.ts.map +1 -1
  45. package/dist/repository-change-publication.js +624 -136
  46. package/dist/repository-change-publication.js.map +1 -1
  47. package/dist/repository-change-state-internal.d.ts +18 -4
  48. package/dist/repository-change-state-internal.d.ts.map +1 -1
  49. package/dist/repository-change-ui-launcher-internal.d.ts +34 -22
  50. package/dist/repository-change-ui-launcher-internal.d.ts.map +1 -1
  51. package/dist/repository-publication-receipt.d.ts +23 -0
  52. package/dist/repository-publication-receipt.d.ts.map +1 -0
  53. package/dist/repository-rebase/git.d.ts +8 -0
  54. package/dist/repository-rebase/git.d.ts.map +1 -1
  55. package/dist/repository-reconciliation.d.ts +47 -0
  56. package/dist/repository-reconciliation.d.ts.map +1 -0
  57. package/dist/repository-record.d.ts +6 -0
  58. package/dist/repository-record.d.ts.map +1 -0
  59. package/dist/settings.d.ts +15 -0
  60. package/dist/settings.d.ts.map +1 -0
  61. package/dist/turns/commit-message-evidence.d.ts +35 -0
  62. package/dist/turns/commit-message-evidence.d.ts.map +1 -0
  63. package/dist/turns/commit-message-evidence.js +9 -0
  64. package/dist/turns/generate-commit-message.d.ts +4 -1
  65. package/dist/turns/generate-commit-message.d.ts.map +1 -1
  66. package/dist/turns/generate-commit-message.js +7 -5
  67. package/dist/turns/generate-plan.d.ts.map +1 -1
  68. package/dist/turns/generate-plan.js +1 -1
  69. package/dist/turns/git-inspection-profile.d.ts +25 -0
  70. package/dist/turns/git-inspection-profile.d.ts.map +1 -0
  71. package/dist/turns/git-inspection-profile.js +8 -0
  72. package/dist/turns/implement.d.ts +1 -1
  73. package/dist/turns/implement.d.ts.map +1 -1
  74. package/dist/turns/implement.js +1 -1
  75. package/dist/turns/simplify-implementation.d.ts +1 -1
  76. package/dist/turns/simplify-implementation.d.ts.map +1 -1
  77. package/dist/turns/simplify-implementation.js +3 -3
  78. package/package.json +5 -9
  79. package/src/finalization-git-internal.ts +186 -114
  80. package/src/finalization-git.ts +1 -1
  81. package/src/index.ts +4 -1
  82. package/src/pull-request-publication-internal.ts +158 -79
  83. package/src/repository-change-launch-internal.ts +119 -12
  84. package/src/repository-change-launch.ts +8 -4
  85. package/src/repository-change-process.ts +252 -524
  86. package/src/repository-change-publication.ts +702 -121
  87. package/src/repository-change-state-internal.ts +34 -20
  88. package/src/repository-change-ui-launcher-internal.ts +139 -56
  89. package/src/repository-publication-receipt.ts +71 -0
  90. package/src/repository-rebase/git.ts +108 -29
  91. package/src/repository-reconciliation.ts +600 -0
  92. package/src/repository-record.ts +14 -0
  93. package/src/settings.ts +79 -0
  94. package/src/turns/commit-message-evidence.ts +241 -0
  95. package/src/turns/generate-commit-message.ts +53 -23
  96. package/src/turns/generate-plan.ts +26 -12
  97. package/src/turns/git-inspection-profile.ts +134 -0
  98. package/src/turns/implement.ts +13 -3
  99. package/src/turns/simplify-implementation.ts +10 -6
  100. package/dist/chunk-34B3Q75M.js +0 -25
  101. package/dist/chunk-34B3Q75M.js.map +0 -1
  102. package/dist/chunk-F6CEEAFE.js +0 -13
  103. package/dist/chunk-F6CEEAFE.js.map +0 -1
  104. package/dist/chunk-GO44KCUS.js +0 -154
  105. package/dist/chunk-GO44KCUS.js.map +0 -1
  106. package/dist/chunk-R3UCUGY6.js +0 -31
  107. package/dist/chunk-R3UCUGY6.js.map +0 -1
  108. package/dist/chunk-W7VJT6AN.js +0 -25
  109. package/dist/chunk-W7VJT6AN.js.map +0 -1
  110. package/dist/chunk-WKHVLLKE.js +0 -45
  111. package/dist/chunk-WKHVLLKE.js.map +0 -1
  112. package/dist/chunk-YSC5GEQJ.js.map +0 -1
  113. package/dist/repository-change-launch-internal-Dd-AONUs.d.ts +0 -67
  114. package/dist/turns/review-implementation.d.ts +0 -4
  115. package/dist/turns/review-implementation.d.ts.map +0 -1
  116. package/dist/turns/review-implementation.js +0 -8
  117. package/dist/turns/review-plan.d.ts +0 -4
  118. package/dist/turns/review-plan.d.ts.map +0 -1
  119. package/dist/turns/review-plan.js +0 -8
  120. package/src/turns/review-implementation.ts +0 -30
  121. package/src/turns/review-plan.ts +0 -24
  122. /package/dist/turns/{review-implementation.js.map → commit-message-evidence.js.map} +0 -0
  123. /package/dist/turns/{review-plan.js.map → git-inspection-profile.js.map} +0 -0
@@ -1,21 +1,39 @@
1
1
  import { asUnknownRecord } from "@leitwerk-dev/domain";
2
2
  import {
3
3
  type AutomaticOutcomeBuilder,
4
+ type ExtensionProcessDefinition,
4
5
  type ExternalActionSource,
5
6
  type FlowAutomaticRunContext,
6
7
  flow,
8
+ type ServerExtensionAPI,
7
9
  } from "@leitwerk-dev/process-sdk";
8
- import { commitAndPushWorkBranch, type GitIdentity } from "./finalization-git.js";
10
+ import {
11
+ commitAndPushWorkBranch,
12
+ type GitIdentity,
13
+ repositoryHasChanges,
14
+ } from "./finalization-git.js";
15
+ import { RemoteBranchChangedError } from "./finalization-git-internal.js";
9
16
  import type { RepositoryChangeState } from "./repository-change-state.js";
10
- import { publishRebase, startRebase } from "./repository-rebase/git.js";
17
+ import {
18
+ ConcurrentRebaseSourceError,
19
+ hasPreparedRebase,
20
+ publishRebase,
21
+ startRebase,
22
+ } from "./repository-rebase/git.js";
11
23
  import { type ConflictEvidence, conflictKey, validateConflict } from "./repository-rebase/index.js";
12
24
  import { rebasePrompt } from "./repository-rebase/prompt.js";
25
+ import {
26
+ reconcilePublicationRepository,
27
+ reconciliationPrompt,
28
+ recordRepositoryPublication,
29
+ repositoryWorktreeIsDirty,
30
+ retainConcurrentRebase,
31
+ } from "./repository-reconciliation.js";
32
+ import { codingPurposes } from "./settings.js";
13
33
 
14
34
  export {
15
- pullRequestPublicationCallbacks,
16
- pullRequestPublicationSources,
17
- readPullRequestFeedback,
18
- reconcilePullRequestSourceIssue,
35
+ createPullRequestChangeProcess,
36
+ pullRequestPublicationDefaults,
19
37
  resolvePullRequestGitIdentity,
20
38
  } from "./pull-request-publication-internal.js";
21
39
 
@@ -23,64 +41,98 @@ export {
23
41
  export interface PublicationRequest {
24
42
  /** @public */
25
43
  number: number;
44
+
26
45
  /** @public */
27
46
  html_url: string;
47
+
28
48
  /** @public */
29
49
  merged: boolean;
50
+
30
51
  /** @public */
31
52
  merge_commit_sha?: string | null;
32
53
  }
54
+
33
55
  /** @public */
34
56
  export interface PublicationPipeline {
35
57
  /** @public */
36
58
  number: number;
59
+
37
60
  /** @public */
38
61
  status: string;
62
+
39
63
  /** @public */
40
64
  [key: string]: unknown;
41
65
  }
66
+
42
67
  /** @public */
43
68
  export interface PublicationParams {
44
69
  /** @public */
45
70
  owner: string;
71
+
46
72
  /** @public */
47
73
  repo: string;
74
+
48
75
  /** @public */
49
76
  workBranch: string;
77
+
50
78
  /** @public */
51
79
  baseBranch: string;
52
80
  }
81
+
82
+ /** Narrow process params to a resolved repository before publication. @public */
83
+ export function requirePublicationParams<P>(params: P): P & PublicationParams {
84
+ const value = asUnknownRecord(params);
85
+ for (const key of ["owner", "repo", "workBranch", "baseBranch"])
86
+ if (typeof value?.[key] !== "string" || !value[key])
87
+ throw new Error("Repository binding is not resolved");
88
+ return params as P & PublicationParams;
89
+ }
90
+
53
91
  /** @public */
54
92
  export type PublicationContext<P> = FlowAutomaticRunContext<P, RepositoryChangeState>;
93
+
94
+ /** Remote reconciliation has no worker checkout or filesystem access. @public */
95
+ export type PublicationReconciliationContext<P> = Pick<
96
+ PublicationContext<P>,
97
+ "process" | "projects" | "params" | "state" | "callIntegrationTool"
98
+ >;
99
+
55
100
  /** @public */
56
101
  export type PublicationEvidence = (
57
102
  | {
58
103
  /** @public */
59
104
  kind: "feedback";
105
+
60
106
  /** @public */
61
107
  feedbackIds: PublicationFeedbackId[];
108
+
62
109
  /** @public */
63
110
  conversationCursor: number;
111
+
64
112
  /** @public */
65
113
  reviewCursor: number;
114
+
66
115
  /** @public */
67
116
  inlineCursor: number;
68
117
  }
69
118
  | {
70
119
  /** @public */
71
120
  kind: "failure";
121
+
72
122
  /** @public */
73
123
  pipeline: PublicationPipeline;
74
124
  }
75
125
  | {
76
126
  /** @public */
77
127
  kind: "conflict";
128
+
78
129
  /** @public */
79
130
  conflict: ConflictEvidence;
80
131
  }
81
132
  | {
82
133
  /** @public */
83
134
  kind: "terminal";
135
+
84
136
  /** @public */
85
137
  request: PublicationRequest;
86
138
  }
@@ -95,143 +147,270 @@ export type PublicationEvidence = (
95
147
  ) & {
96
148
  /** @public */
97
149
  observationKey?: string;
150
+ /** Current provider source revision. @internal */ remoteHeadSha?: string;
151
+ /** Coordinated repository key. @public */ projectKey?: string;
98
152
  };
153
+
99
154
  /** @public */
100
155
  export interface PublicationSource<P> {
101
156
  /** @public */
102
157
  id: string;
158
+
103
159
  /** @public */
104
160
  kind: "feedback" | "failure" | "conflict" | "terminal" | "cancelled" | "observation";
161
+
105
162
  /** @public */
106
163
  operatorId?: string;
164
+
107
165
  /** @public */
108
166
  label: string;
167
+
109
168
  /** @public */
110
169
  source: ExternalActionSource<P, RepositoryChangeState, unknown>;
170
+
111
171
  /** @public */
112
- enabled?(params: P): boolean;
172
+ enabled?(params: P, state: RepositoryChangeState): boolean;
173
+
113
174
  /** @public */
114
175
  read(input: {
115
176
  /** @public */
116
177
  params: P;
178
+
117
179
  /** @public */
118
180
  state: RepositoryChangeState;
181
+
119
182
  /** @public */
120
183
  event: unknown;
121
184
  }): PublicationEvidence;
122
185
  }
186
+
123
187
  /** @public */
124
- export interface RepositoryChangePublicationAdapter<P extends PublicationParams> {
188
+ export interface RepositoryChangePublicationAdapter<P> {
189
+ /** Optional server maintenance uses existing business turns and adds no worker positions. @public */
190
+ maintenance?: {
191
+ /** @public */ source: ExternalActionSource<
192
+ P,
193
+ RepositoryChangeState,
194
+ PublicationMaintenanceEvent
195
+ >;
196
+ /** @public */ ownershipTool: string;
197
+ /** @public */ register(
198
+ api: ServerExtensionAPI,
199
+ process: ExtensionProcessDefinition<P, RepositoryChangeState>,
200
+ ): void;
201
+ };
125
202
  /** @public */
126
203
  namespace: string;
204
+ /** Reconcile a single-repository no-change outcome. @public */
205
+ unchanged?(ctx: PublicationContext<P>): Promise<void>;
206
+ /** Optional coordinated repositories; each retains independent publication state. @public */
207
+ repositories?(params: P): readonly {
208
+ /** @internal */
209
+ key: string;
210
+ /** @internal */
211
+ params: P & PublicationParams;
212
+ }[];
213
+ /** Reconcile remote terminal state before new writes or source cancellation. @public */
214
+ observeTerminal?(
215
+ ctx: PublicationContext<P>,
216
+ current: PublicationState,
217
+ ): Promise<PublicationRequest | null>;
218
+
219
+ /** @public */
220
+ sourceCancelled?(ctx: PublicationReconciliationContext<P>): Promise<boolean>;
221
+
222
+ /** @public */
223
+ reconcileAll?(
224
+ ctx: PublicationReconciliationContext<P>,
225
+ results: readonly {
226
+ /** @internal */
227
+ key: string;
228
+ /** @internal */
229
+ current: PublicationState;
230
+ }[],
231
+ cancelled: boolean,
232
+ ): Promise<void>;
233
+
127
234
  /** @public */
128
235
  label: string;
236
+
129
237
  /** @public */
130
238
  ids: {
131
239
  /** @public */
132
240
  deliver: string;
241
+
133
242
  /** @public */
134
243
  feedback: string;
244
+
135
245
  /** @public */
136
246
  ciRepair: string;
247
+
137
248
  /** @public */
138
249
  operator: string;
139
250
  };
251
+
140
252
  /** @public */
141
253
  tools: {
142
254
  /** @public */
143
255
  delivery: readonly string[];
256
+
144
257
  /** @public */
145
258
  feedback: readonly string[];
259
+
146
260
  /** @public */
147
261
  ci: readonly string[];
148
262
  };
263
+
149
264
  /** @public */
150
265
  sources: readonly PublicationSource<P>[];
266
+
151
267
  /** @public */
152
268
  identity(ctx: PublicationContext<P>): Promise<GitIdentity>;
269
+
153
270
  /** @public */
154
271
  ensureRequest(ctx: PublicationContext<P>): Promise<PublicationRequest>;
272
+
155
273
  /** @public */
156
274
  reconcileTerminal(
157
- ctx: PublicationContext<P>,
275
+ ctx: PublicationReconciliationContext<P>,
158
276
  current: PublicationState,
159
277
  request: PublicationRequest,
160
278
  ): Promise<void>;
279
+
161
280
  /** @public */
162
281
  linkIssue(ctx: PublicationContext<P>, current: PublicationState): Promise<void>;
282
+
163
283
  /** @public */
164
284
  acknowledge(ctx: PublicationContext<P>, current: PublicationState): Promise<void>;
285
+
165
286
  /** @public */
166
287
  reply(ctx: PublicationContext<P>, current: PublicationState): Promise<void>;
288
+
167
289
  /** @public */
168
290
  afterRebase(ctx: PublicationContext<P>, current: PublicationState): Promise<void>;
291
+
169
292
  /** @public */
170
293
  head(ctx: PublicationContext<P>, current: PublicationState): Promise<string>;
294
+
171
295
  /** @public */
172
296
  prompt(kind: "feedback" | "ci", current: PublicationState): string;
297
+
173
298
  /** @public */
174
299
  commitMessage(kind: "feedback" | "ci"): string;
175
300
  }
301
+
302
+ /** @public */
303
+ export interface PublicationMaintenanceEvent {
304
+ /** @public */
305
+ state: RepositoryChangeState;
306
+ }
307
+
308
+ /** @public */
309
+ export interface FeedbackDeliveryResult {
310
+ /** @public */
311
+ published: boolean;
312
+ /** @public */
313
+ summary: string;
314
+ }
315
+
176
316
  /** @public */
177
317
  export type PublicationFeedbackId = {
178
318
  /** @public */
179
319
  kind: "conversation" | "review" | "inline";
320
+
180
321
  /** @public */
181
322
  id: number;
323
+
182
324
  /** @public */
183
325
  discussionId?: string;
184
326
  };
327
+
185
328
  /** @public */
186
329
  type AdjustmentInvocation = {
187
330
  /** @public */
188
331
  origin: "feedback" | "ci" | "rebase";
332
+
189
333
  /** @public */
190
334
  publishRequired: boolean;
335
+ /** Operator-facing no-change diagnosis retained until delivery. @internal */
336
+ summary?: string;
191
337
  };
192
338
 
193
339
  /** @public */
194
340
  export interface DeliveryState {
341
+ /** Feedback delivery retained until the server acknowledges the batch. @public */
342
+ feedbackResult?: FeedbackDeliveryResult | null;
195
343
  /** @public */
196
344
  stage: "not_started" | "branch_published" | "pull_request_ready" | "awaiting";
345
+
197
346
  /** @public */
198
347
  issueLinked: boolean;
348
+
199
349
  /** @public */
200
350
  adjustment: AdjustmentInvocation | null;
351
+
201
352
  /** @public */
202
353
  terminalPullRequest: PublicationRequest | null;
203
354
  }
204
355
 
205
356
  /** @public */
206
357
  export interface PublicationState {
358
+ /** Maintenance was stopped for this MR; it remains open and contributes a partial result. @public */ stopped?: boolean;
359
+ /** Repository had no change at first publication. @public */ noChanges?: boolean;
360
+
207
361
  /** @public */
208
362
  lastConflictKey?: string | null;
363
+
209
364
  /** @public */
210
365
  conflict?: ConflictEvidence | null;
366
+
211
367
  /** @public */
212
368
  repairReason?: "feedback" | "ci" | "rebase";
369
+ /** Staged repair retained when another maintained MR interrupts the worker. @public */
370
+ repairPending?: boolean;
371
+
213
372
  /** @public */
214
373
  headSha: string | null;
374
+
375
+ /** Baseline retained until the worker reconciles its unpublished delta. @internal */
376
+ workBaselineSha?: string | null;
377
+ /** Historical publication receipt, not an eligibility condition. @internal */
378
+ lastPublishedHeadSha?: string | null;
379
+ /** Combined tree needs validation before publication. @internal */
380
+ reconciliationRequired?: boolean;
381
+ /** Bound automatic reconciliation loops under continuously moving branches. @internal */
382
+ reconciliationCycles?: number;
383
+
215
384
  /** @public */
216
385
  prNumber: number | null;
386
+
217
387
  /** @public */
218
388
  prUrl: string | null;
389
+
219
390
  /** @public */
220
391
  conversationCursor: number;
392
+
221
393
  /** @public */
222
394
  reviewCursor: number;
395
+
223
396
  /** @public */
224
397
  inlineCursor: number;
398
+
225
399
  /** @public */
226
400
  feedbackIds: PublicationFeedbackId[];
401
+
227
402
  /** @public */
228
403
  pipeline: PublicationPipeline | null;
404
+
229
405
  /** @public */
230
406
  ciRecoveryCycles: number;
407
+
231
408
  /** @public */
232
409
  delivery: DeliveryState;
410
+
233
411
  /** @public */
234
412
  observationKey?: string;
413
+
235
414
  /** @public */
236
415
  pendingEvidence?: PublicationEvidence | null;
237
416
  }
@@ -259,6 +438,29 @@ const initialPublicationState: PublicationState = {
259
438
  /** @public */
260
439
  export const publicationObject = (value: unknown) => asUnknownRecord(value) ?? {};
261
440
 
441
+ /** Shared coordination metadata for worker publication and server maintenance. @internal */
442
+ export function createPublicationSelection(namespace: () => string) {
443
+ return {
444
+ /** @internal */
445
+ activeKey: (state: RepositoryChangeState) =>
446
+ publicationObject(state.extensionState?.[`${namespace()}.coordination`]).activeKey as
447
+ | string
448
+ | undefined,
449
+ /** @internal */
450
+ select: (state: RepositoryChangeState, key: string): RepositoryChangeState => ({
451
+ ...state,
452
+ extensionState: {
453
+ ...state.extensionState,
454
+ [`${namespace()}.coordination`]: { activeKey: key },
455
+ },
456
+ }),
457
+ };
458
+ }
459
+
460
+ /** @internal */
461
+ export const publicationFinished = (current: PublicationState): boolean =>
462
+ !!(current.stopped || current.noChanges || current.delivery.terminalPullRequest);
463
+
262
464
  /** @public */
263
465
  export function readPublicationState(
264
466
  state: RepositoryChangeState,
@@ -300,13 +502,21 @@ export function patchPublicationState(
300
502
 
301
503
  /** @public */
302
504
  export function applyPublicationEvidence(
303
- params: PublicationParams,
505
+ params: unknown,
304
506
  current: PublicationState,
305
507
  evidence: PublicationEvidence,
306
508
  countFailure = true,
307
509
  ): PublicationState {
308
510
  if (evidence.observationKey !== undefined)
309
511
  current = { ...current, observationKey: evidence.observationKey };
512
+ if (evidence.remoteHeadSha && evidence.remoteHeadSha !== current.headSha)
513
+ current = {
514
+ ...current,
515
+ workBaselineSha: current.workBaselineSha ?? current.headSha,
516
+ lastPublishedHeadSha: current.lastPublishedHeadSha ?? current.headSha,
517
+ headSha: evidence.remoteHeadSha,
518
+ pipeline: null,
519
+ };
310
520
  switch (evidence.kind) {
311
521
  case "feedback": {
312
522
  const { kind: _, ...batch } = evidence;
@@ -320,15 +530,16 @@ export function applyPublicationEvidence(
320
530
  ciRecoveryCycles: current.ciRecoveryCycles + (countFailure ? 1 : 0),
321
531
  };
322
532
  case "conflict": {
533
+ const repository = requirePublicationParams(params);
323
534
  const conflict = validateConflict(
324
535
  evidence.conflict,
325
536
  {
326
- owner: params.owner,
327
- repo: params.repo,
537
+ owner: repository.owner,
538
+ repo: repository.repo,
328
539
  prNumber: current.prNumber ?? 0,
329
540
  headSha: current.headSha ?? "",
330
- headBranch: params.workBranch,
331
- baseBranch: params.baseBranch,
541
+ headBranch: repository.workBranch,
542
+ baseBranch: repository.baseBranch,
332
543
  },
333
544
  current.lastConflictKey,
334
545
  );
@@ -395,123 +606,349 @@ function deliveryProgress(value: PublicationState, label: string, activeStepId?:
395
606
  }
396
607
 
397
608
  /** @public */
398
- export function createRepositoryChangePublication<P extends PublicationParams>(
609
+ export function createRepositoryChangePublication<P>(
399
610
  adapter: RepositoryChangePublicationAdapter<P>,
400
611
  ) {
401
612
  const ids = adapter.ids;
402
613
  const publication = flow.fragment<P, RepositoryChangeState>(`${adapter.namespace}-publication`);
403
- const remote = (state: RepositoryChangeState) => readPublicationState(state, adapter.namespace);
614
+ const { activeKey, select } = createPublicationSelection(() => adapter.namespace);
615
+ const namespace = (state: RepositoryChangeState) =>
616
+ adapter.repositories ? `${adapter.namespace}:${activeKey(state)}` : adapter.namespace;
617
+ const remote = (state: RepositoryChangeState) => readPublicationState(state, namespace(state));
618
+ const repositoryContext = (ctx: PublicationContext<P>): PublicationContext<P> => {
619
+ if (!adapter.repositories) return ctx;
620
+ const selected = adapter
621
+ .repositories(ctx.params)
622
+ .find((repo) => repo.key === activeKey(ctx.state));
623
+ if (!selected) throw new Error("Missing coordinated repository selection");
624
+ return {
625
+ ...ctx,
626
+ params: selected.params,
627
+ repo: { ...ctx.repo, get: (key) => ctx.repo.get(key === "repo" ? selected.key : key) },
628
+ callIntegrationTool: (name, args) =>
629
+ ctx.callIntegrationTool(name, { ...args, projectKey: selected.key }),
630
+ };
631
+ };
404
632
  const patchRemote = (
405
633
  state: RepositoryChangeState,
406
634
  patch: Partial<Omit<PublicationState, "delivery">> & { delivery?: Partial<DeliveryState> },
407
- ) => patchPublicationState(state, adapter.namespace, patch);
408
- async function commitWorkBranch(ctx: PublicationContext<P>, commitMessage: string) {
635
+ ) => patchPublicationState(state, namespace(state), patch);
636
+ async function commitWorkBranch(
637
+ ctx: PublicationContext<P>,
638
+ commitMessage: string,
639
+ expectedRemoteHead = remote(ctx.state).headSha,
640
+ ) {
409
641
  const repo = ctx.repo.get("repo");
642
+ const gitIdentity = await adapter.identity(ctx);
643
+ if (adapter.maintenance)
644
+ await ctx.callIntegrationTool(adapter.maintenance.ownershipTool, { projectKey: repo.key });
410
645
  return commitAndPushWorkBranch({
411
646
  repoPath: repo.fsPath,
647
+ projectKey: repo.key,
412
648
  workBranch: repo.workBranch,
413
649
  commitMessage,
650
+ gitIdentity,
651
+ expectedRemoteHead,
652
+ });
653
+ }
654
+ async function reconcile(ctx: PublicationContext<P>, current: PublicationState) {
655
+ const repo = ctx.repo.get("repo");
656
+ return reconcilePublicationRepository({
657
+ projectKey: repo.key,
658
+ repoPath: repo.fsPath,
659
+ workBranch: repo.workBranch,
660
+ baselineSha: current.workBaselineSha ?? current.headSha ?? undefined,
414
661
  gitIdentity: await adapter.identity(ctx),
415
662
  });
416
663
  }
417
- const delivery = flow
418
- .automatic<P, RepositoryChangeState>(ids.deliver)
419
- .description("Deliver")
420
- .integrationTools(...adapter.tools.delivery)
421
- .run(async (ctx) => {
422
- let current = remote(ctx.state);
423
- const update = (patch: Parameters<typeof patchRemote>[1]) => {
424
- current = { ...current, ...patch, delivery: { ...current.delivery, ...patch.delivery } };
425
- };
426
- const result = (
427
- outcome:
428
- | "awaiting"
429
- | "feedback_ready"
430
- | "completed"
431
- | "aborted"
432
- | "ci_ready"
433
- | "conflict_ready"
434
- | "operator_action",
435
- ) => ({
436
- outcome,
437
- params: { nextState: patchRemote(ctx.state, current) },
664
+ const runRepository = async (ctx: PublicationContext<P>) => {
665
+ let current = remote(ctx.state);
666
+ const update = (patch: Parameters<typeof patchRemote>[1]) => {
667
+ current = { ...current, ...patch, delivery: { ...current.delivery, ...patch.delivery } };
668
+ };
669
+ const acknowledgePublication = (headSha: string, changed: boolean) => {
670
+ update({
671
+ headSha,
672
+ workBaselineSha: headSha,
673
+ lastPublishedHeadSha: changed ? headSha : current.lastPublishedHeadSha,
674
+ reconciliationRequired: false,
675
+ reconciliationCycles: 0,
676
+ pipeline: changed ? null : current.pipeline,
438
677
  });
439
- if (current.pendingEvidence) {
440
- const evidence = current.pendingEvidence;
441
- const needsOperator = evidence.kind === "failure" && current.ciRecoveryCycles >= 3;
442
- current = applyPublicationEvidence(ctx.params, current, evidence, !needsOperator);
443
- current.pendingEvidence = null;
444
- if (evidence.kind === "cancelled") return result("aborted");
445
- if (evidence.kind === "failure")
446
- return result(needsOperator ? "operator_action" : "ci_ready");
447
- if (evidence.kind === "conflict") return result("conflict_ready");
448
- }
449
- ctx.reportProgress(deliveryProgress(current, adapter.label));
678
+ const repo = ctx.repo.get("repo");
679
+ recordRepositoryPublication(
680
+ {
681
+ projectKey: repo.key,
682
+ repoPath: repo.fsPath,
683
+ workBranch: repo.workBranch,
684
+ baselineSha: headSha,
685
+ },
686
+ headSha,
687
+ );
688
+ };
689
+ const result = (
690
+ outcome:
691
+ | "awaiting"
692
+ | "feedback_ready"
693
+ | "completed"
694
+ | "aborted"
695
+ | "ci_ready"
696
+ | "conflict_ready"
697
+ | "operator_action",
698
+ ) => ({
699
+ outcome,
700
+ params: { nextState: patchRemote(ctx.state, current) },
701
+ });
702
+ if (current.stopped) return result("aborted");
703
+ if (current.pendingEvidence) {
704
+ const evidence = current.pendingEvidence;
705
+ const needsOperator = evidence.kind === "failure" && current.ciRecoveryCycles >= 3;
706
+ current = applyPublicationEvidence(ctx.params, current, evidence, !needsOperator);
707
+ current.pendingEvidence = null;
708
+ if (evidence.kind === "cancelled") return result("aborted");
709
+ if (evidence.kind === "failure")
710
+ return result(needsOperator ? "operator_action" : "ci_ready");
711
+ if (evidence.kind === "conflict") return result("conflict_ready");
712
+ }
713
+ ctx.reportProgress(deliveryProgress(current, adapter.label));
714
+ const reconcileAgain = () => {
715
+ const cycles = (current.reconciliationCycles ?? 0) + 1;
716
+ update({
717
+ reconciliationRequired: true,
718
+ reconciliationCycles: cycles,
719
+ repairPending: true,
720
+ conflict: null,
721
+ lastConflictKey: null,
722
+ pipeline: null,
723
+ delivery: { adjustment: null, feedbackResult: null },
724
+ });
725
+ return result(cycles > 3 ? "operator_action" : "conflict_ready");
726
+ };
450
727
 
451
- if (current.delivery.terminalPullRequest) {
452
- ctx.reportProgress(deliveryProgress(current, adapter.label, "reconcile_terminal"));
453
- const pr = current.delivery.terminalPullRequest;
454
- await adapter.reconcileTerminal(ctx, current, pr);
455
- ctx.reportProgress(deliveryProgress(current, adapter.label));
456
- return result(pr.merged ? "completed" : "aborted");
457
- }
728
+ if (current.delivery.terminalPullRequest) {
729
+ ctx.reportProgress(deliveryProgress(current, adapter.label, "reconcile_terminal"));
730
+ const pr = current.delivery.terminalPullRequest;
731
+ await adapter.reconcileTerminal(ctx, current, pr);
732
+ ctx.reportProgress(deliveryProgress(current, adapter.label));
733
+ return result(pr.merged ? "completed" : "aborted");
734
+ }
458
735
 
459
- if (!current.headSha) {
460
- ctx.reportProgress(deliveryProgress(current, adapter.label, "publish_branch"));
461
- const published = await commitWorkBranch(
736
+ if (
737
+ !current.headSha &&
738
+ (adapter.repositories || adapter.unchanged) &&
739
+ !repositoryHasChanges(
740
+ ctx.repo.get("repo").fsPath,
741
+ ctx.repo.get("repo").baseBranch,
742
+ ctx.repo.get("repo").key,
743
+ )
744
+ ) {
745
+ update({ noChanges: true });
746
+ await adapter.unchanged?.(ctx);
747
+ return result("completed");
748
+ }
749
+ let publicationLease = current.headSha;
750
+ if (
751
+ (!current.headSha || current.delivery.adjustment) &&
752
+ current.delivery.adjustment?.origin !== "rebase"
753
+ ) {
754
+ const synchronized = await reconcile(ctx, current);
755
+ if (synchronized.changed || synchronized.status === "conflicts") return reconcileAgain();
756
+ // Fetch is authoritative even if the watcher has not observed a developer push yet.
757
+ publicationLease = synchronized.remoteHead;
758
+ if (current.headSha && synchronized.remoteHead && current.headSha !== synchronized.remoteHead)
759
+ update({ headSha: synchronized.remoteHead, workBaselineSha: synchronized.remoteHead });
760
+ }
761
+ if (!current.headSha) {
762
+ ctx.reportProgress(deliveryProgress(current, adapter.label, "publish_branch"));
763
+ let published: { headSha: string };
764
+ try {
765
+ published = await commitWorkBranch(
462
766
  ctx,
463
- ctx.state.finalization.generatedCommitMessage ?? "",
767
+ ctx.state.finalization.commitMessages?.[ctx.repo.get("repo").key] ??
768
+ ctx.state.finalization.generatedCommitMessage ??
769
+ "",
770
+ publicationLease,
464
771
  );
465
- update({ headSha: published.headSha, pipeline: null });
772
+ } catch (error) {
773
+ if (!(error instanceof RemoteBranchChangedError)) throw error;
774
+ return reconcileAgain();
466
775
  }
776
+ acknowledgePublication(published.headSha, true);
777
+ }
467
778
 
468
- if (!current.prNumber || !current.prUrl) {
469
- ctx.reportProgress(deliveryProgress(current, adapter.label, "open_pr"));
470
- const pr = await adapter.ensureRequest(ctx);
471
- update({ prNumber: pr.number, prUrl: pr.html_url });
472
- }
779
+ if (!current.prNumber || !current.prUrl) {
780
+ ctx.reportProgress(deliveryProgress(current, adapter.label, "open_pr"));
781
+ const pr = await adapter.ensureRequest(ctx);
782
+ update({ prNumber: pr.number, prUrl: pr.html_url });
783
+ }
473
784
 
474
- if (!current.delivery.issueLinked) {
475
- ctx.reportProgress(deliveryProgress(current, adapter.label, "link_issue"));
476
- await adapter.linkIssue(ctx, current);
477
- update({ delivery: { issueLinked: true } });
478
- }
785
+ if (!current.delivery.issueLinked) {
786
+ ctx.reportProgress(deliveryProgress(current, adapter.label, "link_issue"));
787
+ await adapter.linkIssue(ctx, current);
788
+ update({ delivery: { issueLinked: true } });
789
+ }
479
790
 
480
- if (current.delivery.adjustment) {
481
- const adjustment = current.delivery.adjustment;
482
- if (adjustment.publishRequired || adjustment.origin === "rebase") {
483
- ctx.reportProgress(deliveryProgress(current, adapter.label, "publish_adjustment"));
484
- const published =
791
+ if (current.delivery.adjustment) {
792
+ const adjustment = current.delivery.adjustment;
793
+ if (adjustment.origin === "rebase" && !hasPreparedRebase(rebaseInput(ctx)))
794
+ return reconcileAgain();
795
+ let adjustmentPublished = false;
796
+ if (adjustment.publishRequired || adjustment.origin === "rebase" || adapter.maintenance) {
797
+ ctx.reportProgress(deliveryProgress(current, adapter.label, "publish_adjustment"));
798
+ if (adapter.maintenance)
799
+ await ctx.callIntegrationTool(adapter.maintenance.ownershipTool, {
800
+ projectKey: ctx.repo.get("repo").key,
801
+ });
802
+ let published: { headSha: string };
803
+ try {
804
+ published =
485
805
  adjustment.origin === "rebase"
486
806
  ? publishRebase(rebaseInput(ctx))
487
- : await commitWorkBranch(ctx, adapter.commitMessage(adjustment.origin));
488
- if (adjustment.origin === "rebase") {
489
- const head = await adapter.head(ctx, current);
490
- if (head !== published.headSha)
491
- throw new Error("Pull request head has not caught up with rebase publication");
807
+ : await commitWorkBranch(
808
+ { ...ctx, state: patchRemote(ctx.state, current) },
809
+ adapter.commitMessage(adjustment.origin),
810
+ );
811
+ } catch (error) {
812
+ if (error instanceof ConcurrentRebaseSourceError) {
813
+ if (error.published) return reconcileAgain();
814
+ const project = ctx.repo.get("repo");
815
+ retainConcurrentRebase({
816
+ projectKey: project.key,
817
+ repoPath: project.fsPath,
818
+ workBranch: project.workBranch,
819
+ baselineSha: error.repair.originalHead,
820
+ rebasedHead: error.repair.headSha,
821
+ targetBase: error.repair.baseSha,
822
+ gitIdentity: await adapter.identity(ctx),
823
+ });
824
+ return reconcileAgain();
492
825
  }
493
- update({ headSha: published.headSha, pipeline: null });
826
+ if (!(error instanceof RemoteBranchChangedError)) throw error;
827
+ return reconcileAgain();
494
828
  }
495
- if (adjustment.origin === "rebase") await adapter.afterRebase(ctx, current);
496
- if (adjustment.origin === "feedback") {
497
- ctx.reportProgress(deliveryProgress(current, adapter.label, "reply_feedback"));
498
- await adapter.reply(ctx, current);
829
+ if (adjustment.origin === "rebase") {
830
+ const head = await adapter.head(ctx, current);
831
+ if (head !== published.headSha)
832
+ throw new Error("Pull request head has not caught up with rebase publication");
499
833
  }
500
- update({
501
- ...(adjustment.origin === "feedback" ? { feedbackIds: [] } : {}),
502
- delivery: { adjustment: null },
503
- });
834
+ adjustmentPublished = published.headSha !== publicationLease;
835
+ acknowledgePublication(published.headSha, adjustmentPublished);
504
836
  }
505
-
506
- if (current.feedbackIds.length > 0) {
837
+ if (adjustment.origin === "rebase") await adapter.afterRebase(ctx, current);
838
+ if (adjustment.origin === "feedback" && !adapter.maintenance) {
507
839
  ctx.reportProgress(deliveryProgress(current, adapter.label, "reply_feedback"));
508
- await adapter.acknowledge(ctx, current);
509
- return result("feedback_ready");
840
+ await adapter.reply(ctx, current);
510
841
  }
842
+ update({
843
+ ...(adjustment.origin === "feedback" && !adapter.maintenance ? { feedbackIds: [] } : {}),
844
+ ...(adjustment.origin === "rebase" ? { conflict: null } : {}),
845
+ delivery: {
846
+ adjustment: null,
847
+ ...(adjustment.origin === "feedback" && adapter.maintenance
848
+ ? {
849
+ feedbackResult: {
850
+ published: adjustmentPublished,
851
+ summary: adjustmentPublished
852
+ ? "Review adjustment published"
853
+ : (adjustment.summary ?? "No repository change was required"),
854
+ },
855
+ }
856
+ : {}),
857
+ },
858
+ });
859
+ }
860
+
861
+ if (current.feedbackIds.length > 0 && !adapter.maintenance) {
862
+ ctx.reportProgress(deliveryProgress(current, adapter.label, "reply_feedback"));
863
+ await adapter.acknowledge(ctx, current);
864
+ return result("feedback_ready");
865
+ }
511
866
 
512
- update({ delivery: { stage: "awaiting" } });
513
- ctx.reportProgress(deliveryProgress(current, adapter.label, "await_evidence"));
514
- return result("awaiting");
867
+ update({ delivery: { stage: "awaiting" } });
868
+ ctx.reportProgress(deliveryProgress(current, adapter.label, "await_evidence"));
869
+ return result("awaiting");
870
+ };
871
+ const delivery = flow
872
+ .automatic<P, RepositoryChangeState>(ids.deliver)
873
+ .description("Deliver")
874
+ .waitFor(({ state, params }) => {
875
+ const states = adapter.repositories
876
+ ? adapter.repositories(params).map(({ key }) => select(state, key))
877
+ : [state];
878
+ return states.some((state) => {
879
+ const current = remote(state);
880
+ if (adapter.maintenance)
881
+ return (
882
+ !current.stopped &&
883
+ !current.noChanges &&
884
+ !current.delivery.terminalPullRequest &&
885
+ (current.delivery.stage !== "awaiting" || !!current.delivery.adjustment)
886
+ );
887
+ return (
888
+ current.delivery.stage !== "awaiting" ||
889
+ !!current.pendingEvidence ||
890
+ !!current.delivery.adjustment ||
891
+ current.feedbackIds.length > 0 ||
892
+ !!current.delivery.terminalPullRequest
893
+ );
894
+ });
895
+ })
896
+ .integrationTools(...adapter.tools.delivery)
897
+ .run(async (ctx) => {
898
+ if (!adapter.repositories) return runRepository(ctx);
899
+ let state = ctx.state;
900
+ const repositories = adapter.repositories(ctx.params);
901
+ if (!repositories.length) throw new Error("No repositories are bound");
902
+ const results = () =>
903
+ repositories.map(({ key }) => ({ key, current: remote(select(state, key)) }));
904
+ const finished = () => results().every(({ current }) => publicationFinished(current));
905
+ // Terminal facts take precedence over cancellation, including after interrupted publication.
906
+ const reconcileTerminals = async () => {
907
+ for (const { key } of repositories) {
908
+ state = select(state, key);
909
+ const current = remote(state);
910
+ if (publicationFinished(current)) continue;
911
+ const terminal = await adapter.observeTerminal?.(
912
+ repositoryContext({ ...ctx, state }),
913
+ current,
914
+ );
915
+ if (terminal)
916
+ state = patchRemote(state, {
917
+ prNumber: terminal.number,
918
+ prUrl: terminal.html_url,
919
+ delivery: { terminalPullRequest: terminal },
920
+ });
921
+ }
922
+ };
923
+ await reconcileTerminals();
924
+ let cancelled = false;
925
+ for (const { key } of repositories) {
926
+ state = select(state, key);
927
+ if (publicationFinished(remote(state))) continue;
928
+ if (await adapter.sourceCancelled?.({ ...ctx, state })) {
929
+ await reconcileTerminals();
930
+ cancelled = !finished();
931
+ break;
932
+ }
933
+ const result = await runRepository(repositoryContext({ ...ctx, state }));
934
+ state = result.params.nextState;
935
+ if (!["awaiting", "completed", "aborted"].includes(result.outcome))
936
+ return { ...result, params: { nextState: state } };
937
+ }
938
+ if (cancelled || finished()) {
939
+ await adapter.reconcileAll?.({ ...ctx, state }, results(), cancelled);
940
+ const requests = results().flatMap(({ current }) =>
941
+ current.delivery.terminalPullRequest ? [current.delivery.terminalPullRequest] : [],
942
+ );
943
+ return {
944
+ outcome:
945
+ cancelled || (requests.length > 0 && requests.every((request) => !request.merged))
946
+ ? "aborted"
947
+ : "completed",
948
+ params: { nextState: state },
949
+ };
950
+ }
951
+ return { outcome: "awaiting", params: { nextState: state } };
515
952
  });
516
953
  const outcome = (o: AutomaticOutcomeBuilder<P, RepositoryChangeState>, description: string) =>
517
954
  o
@@ -520,13 +957,14 @@ export function createRepositoryChangePublication<P extends PublicationParams>(
520
957
  .state(({ event }) => event.params.nextState as RepositoryChangeState);
521
958
  delivery
522
959
  .outcome("awaiting", (o) => outcome(o, "Delivery is waiting for external evidence").wait())
523
- .outcome("feedback_ready", (o) =>
524
- outcome(o, "Pull request feedback is acknowledged and ready for revision").to(ids.feedback),
525
- )
526
960
  .outcome("completed", (o) => outcome(o, "Merged pull request was reconciled").complete())
527
961
  .outcome("aborted", (o) =>
528
962
  outcome(o, "Closed pull request was reconciled").lifecycleStatus("aborted"),
529
963
  );
964
+ if (!adapter.maintenance)
965
+ delivery.outcome("feedback_ready", (o) =>
966
+ outcome(o, "Pull request feedback is acknowledged and ready for revision").to(ids.feedback),
967
+ );
530
968
  for (const [name, target] of [
531
969
  ["ci_ready", ids.ciRepair],
532
970
  ["conflict_ready", ids.feedback],
@@ -535,13 +973,24 @@ export function createRepositoryChangePublication<P extends PublicationParams>(
535
973
  delivery.outcome(name, (o) => outcome(o, "Route observed delivery evidence").to(target));
536
974
  }
537
975
  for (const source of adapter.sources) {
976
+ if (adapter.maintenance && source.kind === "observation") continue;
538
977
  const attach = (id: string, operator: boolean) =>
539
978
  delivery.externalAction(id, source.source, (external) => {
540
979
  external
541
980
  .label(source.label)
542
981
  .when(
543
982
  ({ params, state }) =>
544
- (!source.enabled || source.enabled(params)) &&
983
+ (!source.enabled || source.enabled(params, state)) &&
984
+ (source.kind === "cancelled" ||
985
+ (adapter.repositories
986
+ ? adapter.repositories(params).map(({ key }) => remote(select(state, key)))
987
+ : [remote(state)]
988
+ ).every(
989
+ (current) =>
990
+ current.noChanges ||
991
+ current.delivery.terminalPullRequest ||
992
+ !!(current.headSha && current.prNumber && current.prUrl),
993
+ )) &&
545
994
  (source.kind !== "failure" || remote(state).ciRecoveryCycles >= 3 === operator),
546
995
  );
547
996
  if (source.kind === "cancelled") return external.lifecycleStatus("aborted");
@@ -556,10 +1005,14 @@ export function createRepositoryChangePublication<P extends PublicationParams>(
556
1005
  );
557
1006
  return external.effect((input) => {
558
1007
  const evidence = source.read(input);
559
- const current = remote(input.state);
1008
+ const state =
1009
+ adapter.repositories && evidence.projectKey
1010
+ ? select(input.state, evidence.projectKey)
1011
+ : input.state;
1012
+ const current = remote(state);
560
1013
  return {
561
1014
  state: patchRemote(
562
- input.state,
1015
+ state,
563
1016
  source.kind === "observation"
564
1017
  ? { pendingEvidence: evidence }
565
1018
  : applyPublicationEvidence(input.params, current, evidence, !operator),
@@ -570,26 +1023,56 @@ export function createRepositoryChangePublication<P extends PublicationParams>(
570
1023
  attach(source.id, false);
571
1024
  if (source.kind === "failure") attach(source.operatorId ?? `${source.id}_operator`, true);
572
1025
  }
1026
+ if (adapter.maintenance) {
1027
+ for (const [id, target] of [
1028
+ ["feedback", ids.feedback],
1029
+ ["conflict", ids.feedback],
1030
+ ["ci", ids.ciRepair],
1031
+ ["operator", ids.operator],
1032
+ ] as const)
1033
+ delivery.externalAction(`maintenance_${id}`, adapter.maintenance.source, (action) =>
1034
+ action
1035
+ .label("Maintain MR")
1036
+ .to(target)
1037
+ .effect(({ event }) => ({ state: event.state })),
1038
+ );
1039
+ }
573
1040
  publication.turn(delivery);
574
1041
  function rebaseInput(ctx: {
575
1042
  state: RepositoryChangeState;
576
1043
  repo: { get(key: string): { fsPath: string; workBranch: string } };
577
1044
  }) {
578
- const project = ctx.repo.get("repo");
1045
+ const project = ctx.repo.get(activeKey(ctx.state) ?? "repo");
579
1046
  const conflict = remote(ctx.state).conflict;
580
1047
  if (!conflict) throw new Error("Missing conflict evidence");
581
- return { projectKey: "repo", path: project.fsPath, workBranch: project.workBranch, conflict };
1048
+ return {
1049
+ projectKey: activeKey(ctx.state) ?? "repo",
1050
+ path: project.fsPath,
1051
+ workBranch: project.workBranch,
1052
+ conflict,
1053
+ };
582
1054
  }
583
1055
  function repairReason(state: RepositoryChangeState, kind: "feedback" | "ci") {
584
1056
  return kind === "feedback" && remote(state).repairReason === "rebase" ? "rebase" : kind;
585
1057
  }
586
1058
 
587
1059
  function revisionPrompt(kind: "feedback" | "ci") {
588
- return (ctx: { state: RepositoryChangeState }) => {
1060
+ return (ctx: {
1061
+ state: RepositoryChangeState;
1062
+ prepared?: unknown;
1063
+ prompts?: { initial: string };
1064
+ }) => {
589
1065
  const current = remote(ctx.state);
1066
+ const repository = adapter.repositories
1067
+ ? `Repository: ${activeKey(ctx.state)}. Apply changes only to this checkout. `
1068
+ : "";
1069
+ if (asUnknownRecord(ctx.prepared)?.deferredRebase)
1070
+ return `${repository}${reconciliationPrompt}\nThe source branch or retained local work must be reconciled before the target-branch repair. Resolve any source reconciliation, then use changes_ready. Delivery will restore and validate the result before reassessing current target conflicts.`;
1071
+ if (current.reconciliationRequired)
1072
+ return `${repository}${reconciliationPrompt}\nValidate the reconciled repository, including retained local work, against the requested change and pending feedback: ${JSON.stringify(current.feedbackIds)}. Treat the current remote as authoritative; do not restore deliberately removed code simply to match an older plan. Use changes_ready after validation, even when no further edit is needed, so retained local changes are published. If blocked use cannot_repair.\nOriginal request for context: ${ctx.prompts?.initial ?? "Inspect the current repository and retained request"}`;
590
1073
  if (repairReason(ctx.state, kind) === "rebase")
591
1074
  return `${rebasePrompt} Evidence: ${JSON.stringify(current.conflict)}. Call changes_ready or no_changes when verified complete, cannot_repair when blocked.`;
592
- return adapter.prompt(kind, current);
1075
+ return `${adapter.repositories ? `Repository: ${activeKey(ctx.state)}. Apply changes only to this checkout. ` : ""}${adapter.prompt(kind, current)}\n\n${reconciliationPrompt}`;
593
1076
  };
594
1077
  }
595
1078
 
@@ -597,52 +1080,147 @@ export function createRepositoryChangePublication<P extends PublicationParams>(
597
1080
  const turn = flow
598
1081
  .llm<P, RepositoryChangeState>(id)
599
1082
  .description(kind === "feedback" ? "Address Feedback" : "Fix CI")
1083
+ .waitFor(({ state }) => {
1084
+ const current = remote(state);
1085
+ return (
1086
+ !current.stopped &&
1087
+ !current.delivery.terminalPullRequest &&
1088
+ (kind === "feedback"
1089
+ ? current.feedbackIds.length > 0 ||
1090
+ !!current.conflict ||
1091
+ !!current.reconciliationRequired
1092
+ : current.repairReason === "ci" && current.pipeline !== null)
1093
+ );
1094
+ })
1095
+ .executionPurpose(codingPurposes.implementation)
600
1096
  .tools("read", "bash", "edit", "write")
601
1097
  .resolveIntegrationTools((_params, state) =>
602
- repairReason(state, kind) === "rebase" ? [] : adapter.tools[kind],
603
- )
604
- .prepare((ctx) =>
605
- repairReason(ctx.state, kind) === "rebase" ? startRebase(rebaseInput(ctx)) : {},
1098
+ repairReason(state, kind) === "rebase" && !remote(state).reconciliationRequired
1099
+ ? []
1100
+ : adapter.tools[kind],
606
1101
  )
1102
+ .prepare(async (ctx) => {
1103
+ const project = ctx.repo.get(activeKey(ctx.state) ?? "repo");
1104
+ const current = remote(ctx.state);
1105
+ const targetRebase =
1106
+ repairReason(ctx.state, kind) === "rebase" && !current.reconciliationRequired;
1107
+ // Resume Git's existing target repair; it must not be mistaken for source synchronization.
1108
+ if (targetRebase && hasPreparedRebase(rebaseInput(ctx)))
1109
+ return { rebase: startRebase(rebaseInput(ctx)) };
1110
+ ctx.reportProgress({
1111
+ title: "Repository reconciliation",
1112
+ steps: [
1113
+ {
1114
+ id: "reconcile_source",
1115
+ label: "Reconcile remote source and retained local work",
1116
+ status: "in_progress",
1117
+ },
1118
+ ],
1119
+ });
1120
+ const reconciliation = await reconcile(repositoryContext(ctx), current);
1121
+ ctx.reportProgress({
1122
+ title: "Repository reconciliation",
1123
+ steps: [
1124
+ {
1125
+ id: "reconcile_source",
1126
+ label:
1127
+ reconciliation.status === "conflicts"
1128
+ ? "Resolve source reconciliation conflicts"
1129
+ : "Remote source reconciled",
1130
+ status: reconciliation.status === "conflicts" ? "in_progress" : "completed",
1131
+ },
1132
+ ],
1133
+ });
1134
+ if (targetRebase) {
1135
+ if (
1136
+ reconciliation.changed ||
1137
+ reconciliation.headSha !== current.conflict?.headSha ||
1138
+ repositoryWorktreeIsDirty({ projectKey: project.key, repoPath: project.fsPath })
1139
+ )
1140
+ return { reconciliation, deferredRebase: true };
1141
+ return { rebase: startRebase(rebaseInput(ctx)) };
1142
+ }
1143
+ return { reconciliation };
1144
+ })
607
1145
  .freshPrimary()
608
1146
  .prompt(revisionPrompt(kind));
609
- for (const [name, description, publishRequired] of [
610
- ["changes_ready", "Repository changes are ready to publish", true],
611
- ["no_changes", "No repository change is required", false],
1147
+ for (const [name, description] of [
1148
+ ["changes_ready", "Repository changes are ready to publish"],
1149
+ ["no_changes", "No repository change is required"],
612
1150
  ] as const) {
613
1151
  turn.outcomeTool(name, (tool) =>
614
1152
  tool
615
1153
  .resultSummary()
616
1154
  .description(description)
617
1155
  .to(ids.deliver)
618
- .state(({ ctx }) =>
1156
+ .state(({ ctx, event }) =>
619
1157
  patchRemote(ctx.state, {
620
- delivery: { adjustment: { origin: repairReason(ctx.state, kind), publishRequired } },
1158
+ repairPending: false,
1159
+ delivery: {
1160
+ // Even no_changes must cross delivery's remote race check. It may
1161
+ // have inherited unpublished work or a concurrent developer push.
1162
+ adjustment: {
1163
+ origin: remote(ctx.state).reconciliationRequired
1164
+ ? "feedback"
1165
+ : repairReason(ctx.state, kind),
1166
+ publishRequired:
1167
+ name === "changes_ready" || !!remote(ctx.state).reconciliationRequired,
1168
+ summary: String(
1169
+ event.params?.resultSummary ?? "No repository change was required",
1170
+ ),
1171
+ },
1172
+ },
621
1173
  }),
622
1174
  ),
623
1175
  );
624
1176
  }
625
- return turn.outcomeTool("cannot_repair", (tool) =>
626
- tool.description("The adjustment requires operator action").to(ids.operator),
627
- );
1177
+ return turn.outcomeTool("cannot_repair", (tool) => {
1178
+ const outcome = tool.description("The adjustment requires operator action").to(ids.operator);
1179
+ return adapter.maintenance
1180
+ ? outcome.state(({ ctx }) => patchRemote(ctx.state, { repairPending: false }))
1181
+ : outcome;
1182
+ });
628
1183
  }
629
1184
 
630
1185
  publication.turn(revisionTurn(ids.feedback, "feedback"));
631
1186
  publication.turn(revisionTurn(ids.ciRepair, "ci"));
1187
+ const maintenanceSource = adapter.maintenance?.source;
632
1188
  publication.turn({
633
1189
  id: ids.operator,
634
1190
  definition: {
635
1191
  kind: "human",
636
1192
  description: "Repository repair needs operator action",
637
1193
  operatorAttention: "required",
1194
+ ...(maintenanceSource
1195
+ ? {
1196
+ externalActions: Object.fromEntries(
1197
+ (["feedback", "conflict"] as const).map((id) => [
1198
+ `maintenance_${id}`,
1199
+ {
1200
+ id: `maintenance_${id}`,
1201
+ source: maintenanceSource,
1202
+ to: ids.feedback,
1203
+ label: "Maintain MR",
1204
+ effect: ({ event }: { event: unknown }) => ({
1205
+ state: (event as { state: RepositoryChangeState }).state,
1206
+ }),
1207
+ },
1208
+ ]),
1209
+ ),
1210
+ }
1211
+ : {}),
638
1212
  actions: {
639
1213
  retry_repair: {
640
1214
  label: "Retry repair",
641
1215
  acceptanceState: "accepted",
642
1216
  branches: { feedback: { to: ids.feedback }, ci: { to: ids.ciRepair } },
1217
+ effect: adapter.maintenance
1218
+ ? ({ ctx }) => ({ state: patchRemote(ctx.state, { reconciliationCycles: 0 }) })
1219
+ : undefined,
643
1220
  choose: ({ ctx }) =>
644
1221
  remote(ctx.state).repairReason === "rebase" ||
645
- remote(ctx.state).repairReason === "feedback"
1222
+ remote(ctx.state).repairReason === "feedback" ||
1223
+ remote(ctx.state).reconciliationRequired
646
1224
  ? "feedback"
647
1225
  : "ci",
648
1226
  },
@@ -652,6 +1230,7 @@ export function createRepositoryChangePublication<P extends PublicationParams>(
652
1230
  to: ids.deliver,
653
1231
  effect: ({ ctx }) => ({
654
1232
  state: patchRemote(ctx.state, {
1233
+ repairPending: false,
655
1234
  feedbackIds: [],
656
1235
  delivery: { adjustment: null },
657
1236
  }),
@@ -665,8 +1244,10 @@ export function createRepositoryChangePublication<P extends PublicationParams>(
665
1244
  return {
666
1245
  /** @public */
667
1246
  entryTurnId: ids.deliver,
1247
+
668
1248
  /** @public */
669
1249
  fragment: publication,
1250
+
670
1251
  /** @public */
671
1252
  happyPath: [ids.deliver],
672
1253
  };