@leitwerk-dev/coding 0.3.1 → 0.4.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 (108) hide show
  1. package/README.md +86 -1
  2. package/dist/chunk-ABQH2WZT.js +36 -0
  3. package/dist/chunk-ABQH2WZT.js.map +1 -0
  4. package/dist/{chunk-YSC5GEQJ.js → chunk-BI45R2FH.js} +7 -3
  5. package/dist/chunk-BI45R2FH.js.map +1 -0
  6. package/dist/chunk-DNG7D77K.js +65 -0
  7. package/dist/chunk-DNG7D77K.js.map +1 -0
  8. package/dist/chunk-L2TFD72B.js +16320 -0
  9. package/dist/chunk-L2TFD72B.js.map +1 -0
  10. package/dist/chunk-M2VTUPFO.js +265 -0
  11. package/dist/chunk-M2VTUPFO.js.map +1 -0
  12. package/dist/chunk-OM2AMDTJ.js +347 -0
  13. package/dist/chunk-OM2AMDTJ.js.map +1 -0
  14. package/dist/chunk-Q24RPXOA.js +159 -0
  15. package/dist/chunk-Q24RPXOA.js.map +1 -0
  16. package/dist/chunk-SKGB4CZS.js +14 -0
  17. package/dist/chunk-SKGB4CZS.js.map +1 -0
  18. package/dist/chunk-SZ4WOGV2.js +120 -0
  19. package/dist/chunk-SZ4WOGV2.js.map +1 -0
  20. package/dist/finalization-git-internal.d.ts +3 -0
  21. package/dist/finalization-git-internal.d.ts.map +1 -1
  22. package/dist/finalization-git.d.ts +1 -1
  23. package/dist/finalization-git.d.ts.map +1 -1
  24. package/dist/finalization-git.js +5 -3
  25. package/dist/index.d.ts +1 -0
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +17 -591
  28. package/dist/index.js.map +1 -1
  29. package/dist/pull-request-publication-internal.d.ts +26 -24
  30. package/dist/pull-request-publication-internal.d.ts.map +1 -1
  31. package/dist/repository-change-launch-internal-BudnAfL7.d.ts +88 -0
  32. package/dist/repository-change-launch-internal.d.ts +32 -11
  33. package/dist/repository-change-launch-internal.d.ts.map +1 -1
  34. package/dist/repository-change-launch.d.ts +4 -3
  35. package/dist/repository-change-launch.d.ts.map +1 -1
  36. package/dist/repository-change-launch.js +162 -34
  37. package/dist/repository-change-launch.js.map +1 -1
  38. package/dist/repository-change-process-DlgF04fU.d.ts +69 -0
  39. package/dist/repository-change-process.d.ts +30 -25
  40. package/dist/repository-change-process.d.ts.map +1 -1
  41. package/dist/repository-change-publication.d.ts +62 -6
  42. package/dist/repository-change-publication.d.ts.map +1 -1
  43. package/dist/repository-change-publication.js +364 -90
  44. package/dist/repository-change-publication.js.map +1 -1
  45. package/dist/repository-change-state-internal.d.ts +18 -4
  46. package/dist/repository-change-state-internal.d.ts.map +1 -1
  47. package/dist/repository-change-ui-launcher-internal.d.ts +34 -22
  48. package/dist/repository-change-ui-launcher-internal.d.ts.map +1 -1
  49. package/dist/settings.d.ts +15 -0
  50. package/dist/settings.d.ts.map +1 -0
  51. package/dist/turns/commit-message-evidence.d.ts +35 -0
  52. package/dist/turns/commit-message-evidence.d.ts.map +1 -0
  53. package/dist/turns/commit-message-evidence.js +9 -0
  54. package/dist/turns/generate-commit-message.d.ts +4 -1
  55. package/dist/turns/generate-commit-message.d.ts.map +1 -1
  56. package/dist/turns/generate-commit-message.js +7 -5
  57. package/dist/turns/generate-plan.d.ts.map +1 -1
  58. package/dist/turns/generate-plan.js +1 -1
  59. package/dist/turns/git-inspection-profile.d.ts +25 -0
  60. package/dist/turns/git-inspection-profile.d.ts.map +1 -0
  61. package/dist/turns/git-inspection-profile.js +8 -0
  62. package/dist/turns/implement.d.ts.map +1 -1
  63. package/dist/turns/implement.js +1 -1
  64. package/dist/turns/simplify-implementation.d.ts +1 -1
  65. package/dist/turns/simplify-implementation.d.ts.map +1 -1
  66. package/dist/turns/simplify-implementation.js +3 -3
  67. package/package.json +5 -9
  68. package/src/finalization-git-internal.ts +117 -114
  69. package/src/finalization-git.ts +1 -1
  70. package/src/index.ts +4 -1
  71. package/src/pull-request-publication-internal.ts +156 -78
  72. package/src/repository-change-launch-internal.ts +119 -12
  73. package/src/repository-change-launch.ts +8 -4
  74. package/src/repository-change-process.ts +234 -523
  75. package/src/repository-change-publication.ts +516 -121
  76. package/src/repository-change-state-internal.ts +34 -20
  77. package/src/repository-change-ui-launcher-internal.ts +139 -56
  78. package/src/settings.ts +79 -0
  79. package/src/turns/commit-message-evidence.ts +241 -0
  80. package/src/turns/generate-commit-message.ts +53 -23
  81. package/src/turns/generate-plan.ts +26 -12
  82. package/src/turns/git-inspection-profile.ts +134 -0
  83. package/src/turns/implement.ts +9 -2
  84. package/src/turns/simplify-implementation.ts +10 -6
  85. package/dist/chunk-34B3Q75M.js +0 -25
  86. package/dist/chunk-34B3Q75M.js.map +0 -1
  87. package/dist/chunk-F6CEEAFE.js +0 -13
  88. package/dist/chunk-F6CEEAFE.js.map +0 -1
  89. package/dist/chunk-GO44KCUS.js +0 -154
  90. package/dist/chunk-GO44KCUS.js.map +0 -1
  91. package/dist/chunk-R3UCUGY6.js +0 -31
  92. package/dist/chunk-R3UCUGY6.js.map +0 -1
  93. package/dist/chunk-W7VJT6AN.js +0 -25
  94. package/dist/chunk-W7VJT6AN.js.map +0 -1
  95. package/dist/chunk-WKHVLLKE.js +0 -45
  96. package/dist/chunk-WKHVLLKE.js.map +0 -1
  97. package/dist/chunk-YSC5GEQJ.js.map +0 -1
  98. package/dist/repository-change-launch-internal-Dd-AONUs.d.ts +0 -67
  99. package/dist/turns/review-implementation.d.ts +0 -4
  100. package/dist/turns/review-implementation.d.ts.map +0 -1
  101. package/dist/turns/review-implementation.js +0 -8
  102. package/dist/turns/review-plan.d.ts +0 -4
  103. package/dist/turns/review-plan.d.ts.map +0 -1
  104. package/dist/turns/review-plan.js +0 -8
  105. package/src/turns/review-implementation.ts +0 -30
  106. package/src/turns/review-plan.ts +0 -24
  107. /package/dist/turns/{review-implementation.js.map → commit-message-evidence.js.map} +0 -0
  108. /package/dist/turns/{review-plan.js.map → git-inspection-profile.js.map} +0 -0
@@ -1,21 +1,26 @@
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";
9
15
  import type { RepositoryChangeState } from "./repository-change-state.js";
10
16
  import { publishRebase, startRebase } from "./repository-rebase/git.js";
11
17
  import { type ConflictEvidence, conflictKey, validateConflict } from "./repository-rebase/index.js";
12
18
  import { rebasePrompt } from "./repository-rebase/prompt.js";
19
+ import { codingPurposes } from "./settings.js";
13
20
 
14
21
  export {
15
- pullRequestPublicationCallbacks,
16
- pullRequestPublicationSources,
17
- readPullRequestFeedback,
18
- reconcilePullRequestSourceIssue,
22
+ createPullRequestChangeProcess,
23
+ pullRequestPublicationDefaults,
19
24
  resolvePullRequestGitIdentity,
20
25
  } from "./pull-request-publication-internal.js";
21
26
 
@@ -23,64 +28,92 @@ export {
23
28
  export interface PublicationRequest {
24
29
  /** @public */
25
30
  number: number;
31
+
26
32
  /** @public */
27
33
  html_url: string;
34
+
28
35
  /** @public */
29
36
  merged: boolean;
37
+
30
38
  /** @public */
31
39
  merge_commit_sha?: string | null;
32
40
  }
41
+
33
42
  /** @public */
34
43
  export interface PublicationPipeline {
35
44
  /** @public */
36
45
  number: number;
46
+
37
47
  /** @public */
38
48
  status: string;
49
+
39
50
  /** @public */
40
51
  [key: string]: unknown;
41
52
  }
53
+
42
54
  /** @public */
43
55
  export interface PublicationParams {
44
56
  /** @public */
45
57
  owner: string;
58
+
46
59
  /** @public */
47
60
  repo: string;
61
+
48
62
  /** @public */
49
63
  workBranch: string;
64
+
50
65
  /** @public */
51
66
  baseBranch: string;
52
67
  }
68
+
69
+ /** Narrow process params to a resolved repository before publication. @public */
70
+ export function requirePublicationParams<P>(params: P): P & PublicationParams {
71
+ const value = asUnknownRecord(params);
72
+ for (const key of ["owner", "repo", "workBranch", "baseBranch"])
73
+ if (typeof value?.[key] !== "string" || !value[key])
74
+ throw new Error("Repository binding is not resolved");
75
+ return params as P & PublicationParams;
76
+ }
77
+
53
78
  /** @public */
54
79
  export type PublicationContext<P> = FlowAutomaticRunContext<P, RepositoryChangeState>;
80
+
55
81
  /** @public */
56
82
  export type PublicationEvidence = (
57
83
  | {
58
84
  /** @public */
59
85
  kind: "feedback";
86
+
60
87
  /** @public */
61
88
  feedbackIds: PublicationFeedbackId[];
89
+
62
90
  /** @public */
63
91
  conversationCursor: number;
92
+
64
93
  /** @public */
65
94
  reviewCursor: number;
95
+
66
96
  /** @public */
67
97
  inlineCursor: number;
68
98
  }
69
99
  | {
70
100
  /** @public */
71
101
  kind: "failure";
102
+
72
103
  /** @public */
73
104
  pipeline: PublicationPipeline;
74
105
  }
75
106
  | {
76
107
  /** @public */
77
108
  kind: "conflict";
109
+
78
110
  /** @public */
79
111
  conflict: ConflictEvidence;
80
112
  }
81
113
  | {
82
114
  /** @public */
83
115
  kind: "terminal";
116
+
84
117
  /** @public */
85
118
  request: PublicationRequest;
86
119
  }
@@ -95,143 +128,258 @@ export type PublicationEvidence = (
95
128
  ) & {
96
129
  /** @public */
97
130
  observationKey?: string;
131
+ /** Coordinated repository key. @public */ projectKey?: string;
98
132
  };
133
+
99
134
  /** @public */
100
135
  export interface PublicationSource<P> {
101
136
  /** @public */
102
137
  id: string;
138
+
103
139
  /** @public */
104
140
  kind: "feedback" | "failure" | "conflict" | "terminal" | "cancelled" | "observation";
141
+
105
142
  /** @public */
106
143
  operatorId?: string;
144
+
107
145
  /** @public */
108
146
  label: string;
147
+
109
148
  /** @public */
110
149
  source: ExternalActionSource<P, RepositoryChangeState, unknown>;
150
+
111
151
  /** @public */
112
- enabled?(params: P): boolean;
152
+ enabled?(params: P, state: RepositoryChangeState): boolean;
153
+
113
154
  /** @public */
114
155
  read(input: {
115
156
  /** @public */
116
157
  params: P;
158
+
117
159
  /** @public */
118
160
  state: RepositoryChangeState;
161
+
119
162
  /** @public */
120
163
  event: unknown;
121
164
  }): PublicationEvidence;
122
165
  }
166
+
123
167
  /** @public */
124
- export interface RepositoryChangePublicationAdapter<P extends PublicationParams> {
168
+ export interface RepositoryChangePublicationAdapter<P> {
169
+ /** Optional server maintenance uses existing business turns and adds no worker positions. @public */
170
+ maintenance?: {
171
+ /** @public */ source: ExternalActionSource<
172
+ P,
173
+ RepositoryChangeState,
174
+ PublicationMaintenanceEvent
175
+ >;
176
+ /** @public */ ownershipTool: string;
177
+ /** @public */ register(
178
+ api: ServerExtensionAPI,
179
+ process: ExtensionProcessDefinition<P, RepositoryChangeState>,
180
+ ): void;
181
+ };
125
182
  /** @public */
126
183
  namespace: string;
184
+ /** Reconcile a single-repository no-change outcome. @public */
185
+ unchanged?(ctx: PublicationContext<P>): Promise<void>;
186
+ /** Optional coordinated repositories; each retains independent publication state. @public */
187
+ repositories?(params: P): readonly {
188
+ /** @internal */
189
+ key: string;
190
+ /** @internal */
191
+ params: P & PublicationParams;
192
+ }[];
193
+ /** Reconcile remote terminal state before new writes or source cancellation. @public */
194
+ observeTerminal?(
195
+ ctx: PublicationContext<P>,
196
+ current: PublicationState,
197
+ ): Promise<PublicationRequest | null>;
198
+
199
+ /** @public */
200
+ sourceCancelled?(ctx: PublicationContext<P>): Promise<boolean>;
201
+
202
+ /** @public */
203
+ reconcileAll?(
204
+ ctx: PublicationContext<P>,
205
+ results: readonly {
206
+ /** @internal */
207
+ key: string;
208
+ /** @internal */
209
+ current: PublicationState;
210
+ }[],
211
+ cancelled: boolean,
212
+ ): Promise<void>;
213
+
127
214
  /** @public */
128
215
  label: string;
216
+
129
217
  /** @public */
130
218
  ids: {
131
219
  /** @public */
132
220
  deliver: string;
221
+
133
222
  /** @public */
134
223
  feedback: string;
224
+
135
225
  /** @public */
136
226
  ciRepair: string;
227
+
137
228
  /** @public */
138
229
  operator: string;
139
230
  };
231
+
140
232
  /** @public */
141
233
  tools: {
142
234
  /** @public */
143
235
  delivery: readonly string[];
236
+
144
237
  /** @public */
145
238
  feedback: readonly string[];
239
+
146
240
  /** @public */
147
241
  ci: readonly string[];
148
242
  };
243
+
149
244
  /** @public */
150
245
  sources: readonly PublicationSource<P>[];
246
+
151
247
  /** @public */
152
248
  identity(ctx: PublicationContext<P>): Promise<GitIdentity>;
249
+
153
250
  /** @public */
154
251
  ensureRequest(ctx: PublicationContext<P>): Promise<PublicationRequest>;
252
+
155
253
  /** @public */
156
254
  reconcileTerminal(
157
255
  ctx: PublicationContext<P>,
158
256
  current: PublicationState,
159
257
  request: PublicationRequest,
160
258
  ): Promise<void>;
259
+
161
260
  /** @public */
162
261
  linkIssue(ctx: PublicationContext<P>, current: PublicationState): Promise<void>;
262
+
163
263
  /** @public */
164
264
  acknowledge(ctx: PublicationContext<P>, current: PublicationState): Promise<void>;
265
+
165
266
  /** @public */
166
267
  reply(ctx: PublicationContext<P>, current: PublicationState): Promise<void>;
268
+
167
269
  /** @public */
168
270
  afterRebase(ctx: PublicationContext<P>, current: PublicationState): Promise<void>;
271
+
169
272
  /** @public */
170
273
  head(ctx: PublicationContext<P>, current: PublicationState): Promise<string>;
274
+
171
275
  /** @public */
172
276
  prompt(kind: "feedback" | "ci", current: PublicationState): string;
277
+
173
278
  /** @public */
174
279
  commitMessage(kind: "feedback" | "ci"): string;
175
280
  }
281
+
282
+ /** @public */
283
+ export interface PublicationMaintenanceEvent {
284
+ /** @public */
285
+ state: RepositoryChangeState;
286
+ }
287
+
288
+ /** @public */
289
+ export interface FeedbackDeliveryResult {
290
+ /** @public */
291
+ published: boolean;
292
+ /** @public */
293
+ summary: string;
294
+ }
295
+
176
296
  /** @public */
177
297
  export type PublicationFeedbackId = {
178
298
  /** @public */
179
299
  kind: "conversation" | "review" | "inline";
300
+
180
301
  /** @public */
181
302
  id: number;
303
+
182
304
  /** @public */
183
305
  discussionId?: string;
184
306
  };
307
+
185
308
  /** @public */
186
309
  type AdjustmentInvocation = {
187
310
  /** @public */
188
311
  origin: "feedback" | "ci" | "rebase";
312
+
189
313
  /** @public */
190
314
  publishRequired: boolean;
191
315
  };
192
316
 
193
317
  /** @public */
194
318
  export interface DeliveryState {
319
+ /** Feedback delivery retained until the server acknowledges the batch. @public */
320
+ feedbackResult?: FeedbackDeliveryResult | null;
195
321
  /** @public */
196
322
  stage: "not_started" | "branch_published" | "pull_request_ready" | "awaiting";
323
+
197
324
  /** @public */
198
325
  issueLinked: boolean;
326
+
199
327
  /** @public */
200
328
  adjustment: AdjustmentInvocation | null;
329
+
201
330
  /** @public */
202
331
  terminalPullRequest: PublicationRequest | null;
203
332
  }
204
333
 
205
334
  /** @public */
206
335
  export interface PublicationState {
336
+ /** Maintenance was stopped for this MR; it remains open and contributes a partial result. @public */ stopped?: boolean;
337
+ /** Repository had no change at first publication. @public */ noChanges?: boolean;
338
+
207
339
  /** @public */
208
340
  lastConflictKey?: string | null;
341
+
209
342
  /** @public */
210
343
  conflict?: ConflictEvidence | null;
344
+
211
345
  /** @public */
212
346
  repairReason?: "feedback" | "ci" | "rebase";
347
+ /** Staged repair retained when another maintained MR interrupts the worker. @public */
348
+ repairPending?: boolean;
349
+
213
350
  /** @public */
214
351
  headSha: string | null;
352
+
215
353
  /** @public */
216
354
  prNumber: number | null;
355
+
217
356
  /** @public */
218
357
  prUrl: string | null;
358
+
219
359
  /** @public */
220
360
  conversationCursor: number;
361
+
221
362
  /** @public */
222
363
  reviewCursor: number;
364
+
223
365
  /** @public */
224
366
  inlineCursor: number;
367
+
225
368
  /** @public */
226
369
  feedbackIds: PublicationFeedbackId[];
370
+
227
371
  /** @public */
228
372
  pipeline: PublicationPipeline | null;
373
+
229
374
  /** @public */
230
375
  ciRecoveryCycles: number;
376
+
231
377
  /** @public */
232
378
  delivery: DeliveryState;
379
+
233
380
  /** @public */
234
381
  observationKey?: string;
382
+
235
383
  /** @public */
236
384
  pendingEvidence?: PublicationEvidence | null;
237
385
  }
@@ -259,6 +407,29 @@ const initialPublicationState: PublicationState = {
259
407
  /** @public */
260
408
  export const publicationObject = (value: unknown) => asUnknownRecord(value) ?? {};
261
409
 
410
+ /** Shared coordination metadata for worker publication and server maintenance. @internal */
411
+ export function createPublicationSelection(namespace: () => string) {
412
+ return {
413
+ /** @internal */
414
+ activeKey: (state: RepositoryChangeState) =>
415
+ publicationObject(state.extensionState?.[`${namespace()}.coordination`]).activeKey as
416
+ | string
417
+ | undefined,
418
+ /** @internal */
419
+ select: (state: RepositoryChangeState, key: string): RepositoryChangeState => ({
420
+ ...state,
421
+ extensionState: {
422
+ ...state.extensionState,
423
+ [`${namespace()}.coordination`]: { activeKey: key },
424
+ },
425
+ }),
426
+ };
427
+ }
428
+
429
+ /** @internal */
430
+ export const publicationFinished = (current: PublicationState): boolean =>
431
+ !!(current.stopped || current.noChanges || current.delivery.terminalPullRequest);
432
+
262
433
  /** @public */
263
434
  export function readPublicationState(
264
435
  state: RepositoryChangeState,
@@ -300,7 +471,7 @@ export function patchPublicationState(
300
471
 
301
472
  /** @public */
302
473
  export function applyPublicationEvidence(
303
- params: PublicationParams,
474
+ params: unknown,
304
475
  current: PublicationState,
305
476
  evidence: PublicationEvidence,
306
477
  countFailure = true,
@@ -320,15 +491,16 @@ export function applyPublicationEvidence(
320
491
  ciRecoveryCycles: current.ciRecoveryCycles + (countFailure ? 1 : 0),
321
492
  };
322
493
  case "conflict": {
494
+ const repository = requirePublicationParams(params);
323
495
  const conflict = validateConflict(
324
496
  evidence.conflict,
325
497
  {
326
- owner: params.owner,
327
- repo: params.repo,
498
+ owner: repository.owner,
499
+ repo: repository.repo,
328
500
  prNumber: current.prNumber ?? 0,
329
501
  headSha: current.headSha ?? "",
330
- headBranch: params.workBranch,
331
- baseBranch: params.baseBranch,
502
+ headBranch: repository.workBranch,
503
+ baseBranch: repository.baseBranch,
332
504
  },
333
505
  current.lastConflictKey,
334
506
  );
@@ -395,123 +567,258 @@ function deliveryProgress(value: PublicationState, label: string, activeStepId?:
395
567
  }
396
568
 
397
569
  /** @public */
398
- export function createRepositoryChangePublication<P extends PublicationParams>(
570
+ export function createRepositoryChangePublication<P>(
399
571
  adapter: RepositoryChangePublicationAdapter<P>,
400
572
  ) {
401
573
  const ids = adapter.ids;
402
574
  const publication = flow.fragment<P, RepositoryChangeState>(`${adapter.namespace}-publication`);
403
- const remote = (state: RepositoryChangeState) => readPublicationState(state, adapter.namespace);
575
+ const { activeKey, select } = createPublicationSelection(() => adapter.namespace);
576
+ const namespace = (state: RepositoryChangeState) =>
577
+ adapter.repositories ? `${adapter.namespace}:${activeKey(state)}` : adapter.namespace;
578
+ const remote = (state: RepositoryChangeState) => readPublicationState(state, namespace(state));
579
+ const repositoryContext = (ctx: PublicationContext<P>): PublicationContext<P> => {
580
+ if (!adapter.repositories) return ctx;
581
+ const selected = adapter
582
+ .repositories(ctx.params)
583
+ .find((repo) => repo.key === activeKey(ctx.state));
584
+ if (!selected) throw new Error("Missing coordinated repository selection");
585
+ return {
586
+ ...ctx,
587
+ params: selected.params,
588
+ repo: { ...ctx.repo, get: (key) => ctx.repo.get(key === "repo" ? selected.key : key) },
589
+ callIntegrationTool: (name, args) =>
590
+ ctx.callIntegrationTool(name, { ...args, projectKey: selected.key }),
591
+ };
592
+ };
404
593
  const patchRemote = (
405
594
  state: RepositoryChangeState,
406
595
  patch: Partial<Omit<PublicationState, "delivery">> & { delivery?: Partial<DeliveryState> },
407
- ) => patchPublicationState(state, adapter.namespace, patch);
596
+ ) => patchPublicationState(state, namespace(state), patch);
408
597
  async function commitWorkBranch(ctx: PublicationContext<P>, commitMessage: string) {
409
598
  const repo = ctx.repo.get("repo");
599
+ const gitIdentity = await adapter.identity(ctx);
600
+ if (adapter.maintenance)
601
+ await ctx.callIntegrationTool(adapter.maintenance.ownershipTool, { projectKey: repo.key });
410
602
  return commitAndPushWorkBranch({
411
603
  repoPath: repo.fsPath,
604
+ projectKey: repo.key,
412
605
  workBranch: repo.workBranch,
413
606
  commitMessage,
414
- gitIdentity: await adapter.identity(ctx),
607
+ gitIdentity,
415
608
  });
416
609
  }
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) },
438
- });
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
- }
610
+ const runRepository = async (ctx: PublicationContext<P>) => {
611
+ let current = remote(ctx.state);
612
+ const update = (patch: Parameters<typeof patchRemote>[1]) => {
613
+ current = { ...current, ...patch, delivery: { ...current.delivery, ...patch.delivery } };
614
+ };
615
+ const result = (
616
+ outcome:
617
+ | "awaiting"
618
+ | "feedback_ready"
619
+ | "completed"
620
+ | "aborted"
621
+ | "ci_ready"
622
+ | "conflict_ready"
623
+ | "operator_action",
624
+ ) => ({
625
+ outcome,
626
+ params: { nextState: patchRemote(ctx.state, current) },
627
+ });
628
+ if (current.stopped) return result("aborted");
629
+ if (current.pendingEvidence) {
630
+ const evidence = current.pendingEvidence;
631
+ const needsOperator = evidence.kind === "failure" && current.ciRecoveryCycles >= 3;
632
+ current = applyPublicationEvidence(ctx.params, current, evidence, !needsOperator);
633
+ current.pendingEvidence = null;
634
+ if (evidence.kind === "cancelled") return result("aborted");
635
+ if (evidence.kind === "failure")
636
+ return result(needsOperator ? "operator_action" : "ci_ready");
637
+ if (evidence.kind === "conflict") return result("conflict_ready");
638
+ }
639
+ ctx.reportProgress(deliveryProgress(current, adapter.label));
640
+
641
+ if (current.delivery.terminalPullRequest) {
642
+ ctx.reportProgress(deliveryProgress(current, adapter.label, "reconcile_terminal"));
643
+ const pr = current.delivery.terminalPullRequest;
644
+ await adapter.reconcileTerminal(ctx, current, pr);
449
645
  ctx.reportProgress(deliveryProgress(current, adapter.label));
646
+ return result(pr.merged ? "completed" : "aborted");
647
+ }
450
648
 
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
- }
649
+ if (
650
+ !current.headSha &&
651
+ (adapter.repositories || adapter.unchanged) &&
652
+ !repositoryHasChanges(
653
+ ctx.repo.get("repo").fsPath,
654
+ ctx.repo.get("repo").baseBranch,
655
+ ctx.repo.get("repo").key,
656
+ )
657
+ ) {
658
+ update({ noChanges: true });
659
+ await adapter.unchanged?.(ctx);
660
+ return result("completed");
661
+ }
662
+ if (!current.headSha) {
663
+ ctx.reportProgress(deliveryProgress(current, adapter.label, "publish_branch"));
664
+ const published = await commitWorkBranch(
665
+ ctx,
666
+ ctx.state.finalization.commitMessages?.[ctx.repo.get("repo").key] ??
667
+ ctx.state.finalization.generatedCommitMessage ??
668
+ "",
669
+ );
670
+ update({ headSha: published.headSha, pipeline: null });
671
+ }
458
672
 
459
- if (!current.headSha) {
460
- ctx.reportProgress(deliveryProgress(current, adapter.label, "publish_branch"));
461
- const published = await commitWorkBranch(
462
- ctx,
463
- ctx.state.finalization.generatedCommitMessage ?? "",
464
- );
673
+ if (!current.prNumber || !current.prUrl) {
674
+ ctx.reportProgress(deliveryProgress(current, adapter.label, "open_pr"));
675
+ const pr = await adapter.ensureRequest(ctx);
676
+ update({ prNumber: pr.number, prUrl: pr.html_url });
677
+ }
678
+
679
+ if (!current.delivery.issueLinked) {
680
+ ctx.reportProgress(deliveryProgress(current, adapter.label, "link_issue"));
681
+ await adapter.linkIssue(ctx, current);
682
+ update({ delivery: { issueLinked: true } });
683
+ }
684
+
685
+ if (current.delivery.adjustment) {
686
+ const adjustment = current.delivery.adjustment;
687
+ if (adjustment.publishRequired || adjustment.origin === "rebase") {
688
+ ctx.reportProgress(deliveryProgress(current, adapter.label, "publish_adjustment"));
689
+ if (adapter.maintenance)
690
+ await ctx.callIntegrationTool(adapter.maintenance.ownershipTool, {
691
+ projectKey: ctx.repo.get("repo").key,
692
+ });
693
+ const published =
694
+ adjustment.origin === "rebase"
695
+ ? publishRebase(rebaseInput(ctx))
696
+ : await commitWorkBranch(ctx, adapter.commitMessage(adjustment.origin));
697
+ if (adjustment.origin === "rebase") {
698
+ const head = await adapter.head(ctx, current);
699
+ if (head !== published.headSha)
700
+ throw new Error("Pull request head has not caught up with rebase publication");
701
+ }
465
702
  update({ headSha: published.headSha, pipeline: null });
466
703
  }
467
-
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 });
704
+ if (adjustment.origin === "rebase") await adapter.afterRebase(ctx, current);
705
+ if (adjustment.origin === "feedback" && !adapter.maintenance) {
706
+ ctx.reportProgress(deliveryProgress(current, adapter.label, "reply_feedback"));
707
+ await adapter.reply(ctx, current);
472
708
  }
709
+ update({
710
+ ...(adjustment.origin === "feedback" && !adapter.maintenance ? { feedbackIds: [] } : {}),
711
+ ...(adjustment.origin === "rebase" ? { conflict: null } : {}),
712
+ delivery: {
713
+ adjustment: null,
714
+ ...(adjustment.origin === "feedback" && adapter.maintenance
715
+ ? {
716
+ feedbackResult: {
717
+ published: adjustment.publishRequired,
718
+ summary: "Review adjustment published",
719
+ },
720
+ }
721
+ : {}),
722
+ },
723
+ });
724
+ }
473
725
 
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
- }
726
+ if (current.feedbackIds.length > 0 && !adapter.maintenance) {
727
+ ctx.reportProgress(deliveryProgress(current, adapter.label, "reply_feedback"));
728
+ await adapter.acknowledge(ctx, current);
729
+ return result("feedback_ready");
730
+ }
479
731
 
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 =
485
- adjustment.origin === "rebase"
486
- ? 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");
492
- }
493
- update({ headSha: published.headSha, pipeline: null });
732
+ update({ delivery: { stage: "awaiting" } });
733
+ ctx.reportProgress(deliveryProgress(current, adapter.label, "await_evidence"));
734
+ return result("awaiting");
735
+ };
736
+ const delivery = flow
737
+ .automatic<P, RepositoryChangeState>(ids.deliver)
738
+ .description("Deliver")
739
+ .waitFor(({ state, params }) => {
740
+ const states = adapter.repositories
741
+ ? adapter.repositories(params).map(({ key }) => select(state, key))
742
+ : [state];
743
+ return states.some((state) => {
744
+ const current = remote(state);
745
+ if (adapter.maintenance)
746
+ return (
747
+ !current.stopped &&
748
+ !current.noChanges &&
749
+ !current.delivery.terminalPullRequest &&
750
+ (current.delivery.stage !== "awaiting" ||
751
+ !!(
752
+ current.delivery.adjustment &&
753
+ (current.delivery.adjustment.publishRequired ||
754
+ current.delivery.adjustment.origin === "rebase")
755
+ ))
756
+ );
757
+ return (
758
+ current.delivery.stage !== "awaiting" ||
759
+ !!current.pendingEvidence ||
760
+ !!current.delivery.adjustment ||
761
+ current.feedbackIds.length > 0 ||
762
+ !!current.delivery.terminalPullRequest
763
+ );
764
+ });
765
+ })
766
+ .integrationTools(...adapter.tools.delivery)
767
+ .run(async (ctx) => {
768
+ if (!adapter.repositories) return runRepository(ctx);
769
+ let state = ctx.state;
770
+ const repositories = adapter.repositories(ctx.params);
771
+ if (!repositories.length) throw new Error("No repositories are bound");
772
+ const results = () =>
773
+ repositories.map(({ key }) => ({ key, current: remote(select(state, key)) }));
774
+ const finished = () => results().every(({ current }) => publicationFinished(current));
775
+ // Terminal facts take precedence over cancellation, including after interrupted publication.
776
+ const reconcileTerminals = async () => {
777
+ for (const { key } of repositories) {
778
+ state = select(state, key);
779
+ const current = remote(state);
780
+ if (publicationFinished(current)) continue;
781
+ const terminal = await adapter.observeTerminal?.(
782
+ repositoryContext({ ...ctx, state }),
783
+ current,
784
+ );
785
+ if (terminal)
786
+ state = patchRemote(state, {
787
+ prNumber: terminal.number,
788
+ prUrl: terminal.html_url,
789
+ delivery: { terminalPullRequest: terminal },
790
+ });
494
791
  }
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);
792
+ };
793
+ await reconcileTerminals();
794
+ let cancelled = false;
795
+ for (const { key } of repositories) {
796
+ state = select(state, key);
797
+ if (publicationFinished(remote(state))) continue;
798
+ if (await adapter.sourceCancelled?.({ ...ctx, state })) {
799
+ await reconcileTerminals();
800
+ cancelled = !finished();
801
+ break;
499
802
  }
500
- update({
501
- ...(adjustment.origin === "feedback" ? { feedbackIds: [] } : {}),
502
- delivery: { adjustment: null },
503
- });
803
+ const result = await runRepository(repositoryContext({ ...ctx, state }));
804
+ state = result.params.nextState;
805
+ if (!["awaiting", "completed", "aborted"].includes(result.outcome))
806
+ return { ...result, params: { nextState: state } };
504
807
  }
505
-
506
- if (current.feedbackIds.length > 0) {
507
- ctx.reportProgress(deliveryProgress(current, adapter.label, "reply_feedback"));
508
- await adapter.acknowledge(ctx, current);
509
- return result("feedback_ready");
808
+ if (cancelled || finished()) {
809
+ await adapter.reconcileAll?.({ ...ctx, state }, results(), cancelled);
810
+ const requests = results().flatMap(({ current }) =>
811
+ current.delivery.terminalPullRequest ? [current.delivery.terminalPullRequest] : [],
812
+ );
813
+ return {
814
+ outcome:
815
+ cancelled || (requests.length > 0 && requests.every((request) => !request.merged))
816
+ ? "aborted"
817
+ : "completed",
818
+ params: { nextState: state },
819
+ };
510
820
  }
511
-
512
- update({ delivery: { stage: "awaiting" } });
513
- ctx.reportProgress(deliveryProgress(current, adapter.label, "await_evidence"));
514
- return result("awaiting");
821
+ return { outcome: "awaiting", params: { nextState: state } };
515
822
  });
516
823
  const outcome = (o: AutomaticOutcomeBuilder<P, RepositoryChangeState>, description: string) =>
517
824
  o
@@ -520,28 +827,42 @@ export function createRepositoryChangePublication<P extends PublicationParams>(
520
827
  .state(({ event }) => event.params.nextState as RepositoryChangeState);
521
828
  delivery
522
829
  .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
830
  .outcome("completed", (o) => outcome(o, "Merged pull request was reconciled").complete())
527
831
  .outcome("aborted", (o) =>
528
832
  outcome(o, "Closed pull request was reconciled").lifecycleStatus("aborted"),
529
833
  );
530
- for (const [name, target] of [
531
- ["ci_ready", ids.ciRepair],
532
- ["conflict_ready", ids.feedback],
533
- ["operator_action", ids.operator],
534
- ] as const) {
834
+ if (!adapter.maintenance)
835
+ delivery.outcome("feedback_ready", (o) =>
836
+ outcome(o, "Pull request feedback is acknowledged and ready for revision").to(ids.feedback),
837
+ );
838
+ for (const [name, target] of adapter.maintenance
839
+ ? []
840
+ : ([
841
+ ["ci_ready", ids.ciRepair],
842
+ ["conflict_ready", ids.feedback],
843
+ ["operator_action", ids.operator],
844
+ ] as const)) {
535
845
  delivery.outcome(name, (o) => outcome(o, "Route observed delivery evidence").to(target));
536
846
  }
537
847
  for (const source of adapter.sources) {
848
+ if (adapter.maintenance && source.kind === "observation") continue;
538
849
  const attach = (id: string, operator: boolean) =>
539
850
  delivery.externalAction(id, source.source, (external) => {
540
851
  external
541
852
  .label(source.label)
542
853
  .when(
543
854
  ({ params, state }) =>
544
- (!source.enabled || source.enabled(params)) &&
855
+ (!source.enabled || source.enabled(params, state)) &&
856
+ (source.kind === "cancelled" ||
857
+ (adapter.repositories
858
+ ? adapter.repositories(params).map(({ key }) => remote(select(state, key)))
859
+ : [remote(state)]
860
+ ).every(
861
+ (current) =>
862
+ current.noChanges ||
863
+ current.delivery.terminalPullRequest ||
864
+ !!(current.headSha && current.prNumber && current.prUrl),
865
+ )) &&
545
866
  (source.kind !== "failure" || remote(state).ciRecoveryCycles >= 3 === operator),
546
867
  );
547
868
  if (source.kind === "cancelled") return external.lifecycleStatus("aborted");
@@ -556,10 +877,14 @@ export function createRepositoryChangePublication<P extends PublicationParams>(
556
877
  );
557
878
  return external.effect((input) => {
558
879
  const evidence = source.read(input);
559
- const current = remote(input.state);
880
+ const state =
881
+ adapter.repositories && evidence.projectKey
882
+ ? select(input.state, evidence.projectKey)
883
+ : input.state;
884
+ const current = remote(state);
560
885
  return {
561
886
  state: patchRemote(
562
- input.state,
887
+ state,
563
888
  source.kind === "observation"
564
889
  ? { pendingEvidence: evidence }
565
890
  : applyPublicationEvidence(input.params, current, evidence, !operator),
@@ -570,15 +895,34 @@ export function createRepositoryChangePublication<P extends PublicationParams>(
570
895
  attach(source.id, false);
571
896
  if (source.kind === "failure") attach(source.operatorId ?? `${source.id}_operator`, true);
572
897
  }
898
+ if (adapter.maintenance) {
899
+ for (const [id, target] of [
900
+ ["feedback", ids.feedback],
901
+ ["conflict", ids.feedback],
902
+ ["ci", ids.ciRepair],
903
+ ["operator", ids.operator],
904
+ ] as const)
905
+ delivery.externalAction(`maintenance_${id}`, adapter.maintenance.source, (action) =>
906
+ action
907
+ .label("Maintain MR")
908
+ .to(target)
909
+ .effect(({ event }) => ({ state: event.state })),
910
+ );
911
+ }
573
912
  publication.turn(delivery);
574
913
  function rebaseInput(ctx: {
575
914
  state: RepositoryChangeState;
576
915
  repo: { get(key: string): { fsPath: string; workBranch: string } };
577
916
  }) {
578
- const project = ctx.repo.get("repo");
917
+ const project = ctx.repo.get(activeKey(ctx.state) ?? "repo");
579
918
  const conflict = remote(ctx.state).conflict;
580
919
  if (!conflict) throw new Error("Missing conflict evidence");
581
- return { projectKey: "repo", path: project.fsPath, workBranch: project.workBranch, conflict };
920
+ return {
921
+ projectKey: activeKey(ctx.state) ?? "repo",
922
+ path: project.fsPath,
923
+ workBranch: project.workBranch,
924
+ conflict,
925
+ };
582
926
  }
583
927
  function repairReason(state: RepositoryChangeState, kind: "feedback" | "ci") {
584
928
  return kind === "feedback" && remote(state).repairReason === "rebase" ? "rebase" : kind;
@@ -589,7 +933,7 @@ export function createRepositoryChangePublication<P extends PublicationParams>(
589
933
  const current = remote(ctx.state);
590
934
  if (repairReason(ctx.state, kind) === "rebase")
591
935
  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);
936
+ return `${adapter.repositories ? `Repository: ${activeKey(ctx.state)}. Apply changes only to this checkout. ` : ""}${adapter.prompt(kind, current)}`;
593
937
  };
594
938
  }
595
939
 
@@ -597,6 +941,17 @@ export function createRepositoryChangePublication<P extends PublicationParams>(
597
941
  const turn = flow
598
942
  .llm<P, RepositoryChangeState>(id)
599
943
  .description(kind === "feedback" ? "Address Feedback" : "Fix CI")
944
+ .waitFor(({ state }) => {
945
+ const current = remote(state);
946
+ return (
947
+ !current.stopped &&
948
+ !current.delivery.terminalPullRequest &&
949
+ (kind === "feedback"
950
+ ? current.feedbackIds.length > 0 || !!current.conflict
951
+ : current.repairReason === "ci" && current.pipeline !== null)
952
+ );
953
+ })
954
+ .executionPurpose(codingPurposes.implementation)
600
955
  .tools("read", "bash", "edit", "write")
601
956
  .resolveIntegrationTools((_params, state) =>
602
957
  repairReason(state, kind) === "rebase" ? [] : adapter.tools[kind],
@@ -615,26 +970,63 @@ export function createRepositoryChangePublication<P extends PublicationParams>(
615
970
  .resultSummary()
616
971
  .description(description)
617
972
  .to(ids.deliver)
618
- .state(({ ctx }) =>
973
+ .state(({ ctx, event }) =>
619
974
  patchRemote(ctx.state, {
620
- delivery: { adjustment: { origin: repairReason(ctx.state, kind), publishRequired } },
975
+ repairPending: false,
976
+ delivery: {
977
+ adjustment: { origin: repairReason(ctx.state, kind), publishRequired },
978
+ ...(!publishRequired &&
979
+ adapter.maintenance &&
980
+ repairReason(ctx.state, kind) !== "rebase"
981
+ ? {
982
+ feedbackResult: {
983
+ published: false,
984
+ summary: String(
985
+ event.params.resultSummary ?? "No repository change was required",
986
+ ),
987
+ },
988
+ }
989
+ : {}),
990
+ },
621
991
  }),
622
992
  ),
623
993
  );
624
994
  }
625
- return turn.outcomeTool("cannot_repair", (tool) =>
626
- tool.description("The adjustment requires operator action").to(ids.operator),
627
- );
995
+ return turn.outcomeTool("cannot_repair", (tool) => {
996
+ const outcome = tool.description("The adjustment requires operator action").to(ids.operator);
997
+ return adapter.maintenance
998
+ ? outcome.state(({ ctx }) => patchRemote(ctx.state, { repairPending: false }))
999
+ : outcome;
1000
+ });
628
1001
  }
629
1002
 
630
1003
  publication.turn(revisionTurn(ids.feedback, "feedback"));
631
1004
  publication.turn(revisionTurn(ids.ciRepair, "ci"));
1005
+ const maintenanceSource = adapter.maintenance?.source;
632
1006
  publication.turn({
633
1007
  id: ids.operator,
634
1008
  definition: {
635
1009
  kind: "human",
636
1010
  description: "Repository repair needs operator action",
637
1011
  operatorAttention: "required",
1012
+ ...(maintenanceSource
1013
+ ? {
1014
+ externalActions: Object.fromEntries(
1015
+ (["feedback", "conflict"] as const).map((id) => [
1016
+ `maintenance_${id}`,
1017
+ {
1018
+ id: `maintenance_${id}`,
1019
+ source: maintenanceSource,
1020
+ to: ids.feedback,
1021
+ label: "Maintain MR",
1022
+ effect: ({ event }: { event: unknown }) => ({
1023
+ state: (event as { state: RepositoryChangeState }).state,
1024
+ }),
1025
+ },
1026
+ ]),
1027
+ ),
1028
+ }
1029
+ : {}),
638
1030
  actions: {
639
1031
  retry_repair: {
640
1032
  label: "Retry repair",
@@ -652,6 +1044,7 @@ export function createRepositoryChangePublication<P extends PublicationParams>(
652
1044
  to: ids.deliver,
653
1045
  effect: ({ ctx }) => ({
654
1046
  state: patchRemote(ctx.state, {
1047
+ repairPending: false,
655
1048
  feedbackIds: [],
656
1049
  delivery: { adjustment: null },
657
1050
  }),
@@ -665,8 +1058,10 @@ export function createRepositoryChangePublication<P extends PublicationParams>(
665
1058
  return {
666
1059
  /** @public */
667
1060
  entryTurnId: ids.deliver,
1061
+
668
1062
  /** @public */
669
1063
  fragment: publication,
1064
+
670
1065
  /** @public */
671
1066
  happyPath: [ids.deliver],
672
1067
  };