@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,10 +1,37 @@
1
1
  import {
2
- commitAndPushWorkBranch
3
- } from "./chunk-GO44KCUS.js";
2
+ RemoteBranchChangedError,
3
+ commitAndPushWorkBranch,
4
+ repositoryHasChanges
5
+ } from "./chunk-3WJRJ3Q7.js";
6
+ import {
7
+ assertReconciliationTargetSafe,
8
+ createRepositoryChangeProcess,
9
+ reconcilePublicationRepository,
10
+ reconciliationPrompt,
11
+ recordRepositoryPublication,
12
+ repositoryWorktreeIsDirty,
13
+ retainConcurrentRebase
14
+ } from "./chunk-B3PE6DPF.js";
15
+ import "./chunk-DNG7D77K.js";
16
+ import "./chunk-ABQH2WZT.js";
17
+ import "./chunk-QD6FI4HR.js";
18
+ import "./chunk-SKGB4CZS.js";
19
+ import {
20
+ pushWasRejected,
21
+ readPublicationReceipt,
22
+ readRepositoryBinding,
23
+ repositoryBindingMatches,
24
+ repositoryRecord,
25
+ savePublicationReceipt
26
+ } from "./chunk-E3DB4TIZ.js";
4
27
  import {
5
28
  conflictKey,
6
29
  validateConflict
7
30
  } from "./chunk-KFELB7ZC.js";
31
+ import {
32
+ codingPurposes
33
+ } from "./chunk-M2VTUPFO.js";
34
+ import "./chunk-SZ4WOGV2.js";
8
35
  import "./chunk-PX6F3LHL.js";
9
36
 
10
37
  // src/repository-change-publication.ts
@@ -15,7 +42,7 @@ import {
15
42
 
16
43
  // src/repository-rebase/git.ts
17
44
  import { execFileSync } from "child_process";
18
- import { existsSync, readFileSync, renameSync, writeFileSync } from "fs";
45
+ import { existsSync } from "fs";
19
46
  import { join } from "path";
20
47
  import { repositoryGitArgs, repositoryGitSubprocessEnv } from "@leitwerk-dev/process-sdk";
21
48
  import { resolveGitBinary } from "@leitwerk-dev/process-sdk/git-binary";
@@ -42,12 +69,6 @@ function requireRebaseHead(expected, local, remote) {
42
69
  if (remote !== expected || local !== expected)
43
70
  throw new Error("Tracked branch changed before repair");
44
71
  }
45
- function rebasePublicationDecision(originalHead, headSha, remoteHead2) {
46
- if (remoteHead2 === headSha) return "already_published";
47
- if (remoteHead2 !== originalHead)
48
- throw new Error("Concurrent remote change rejected by rebase lease");
49
- return "push";
50
- }
51
72
 
52
73
  // src/repository-rebase/git.ts
53
74
  function git(input, ...args) {
@@ -67,15 +88,7 @@ function area(input) {
67
88
  function active(gitDir) {
68
89
  return ["rebase-merge", "rebase-apply"].some((name) => existsSync(join(gitDir, name)));
69
90
  }
70
- function save(gitDir, record) {
71
- const path = join(gitDir, "leitwerk-rebase.json");
72
- writeFileSync(`${path}.tmp`, JSON.stringify(record), { mode: 384 });
73
- renameSync(`${path}.tmp`, path);
74
- }
75
- function read(gitDir) {
76
- const file = join(gitDir, "leitwerk-rebase.json");
77
- return existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : null;
78
- }
91
+ var recordFile = (gitDir) => repositoryRecord(gitDir, "rebase");
79
92
  function requireWorktree(input) {
80
93
  requireRebaseWorktree(input.workBranch, {
81
94
  branch: git(input, "branch", "--show-current"),
@@ -110,9 +123,12 @@ function verifyNoRepairNeeded(input, headSha, baseSha) {
110
123
  git(input, "merge-base", "--is-ancestor", baseSha, headSha);
111
124
  else git(input, "merge-tree", "--write-tree", headSha, baseSha);
112
125
  }
126
+ function hasPreparedRebase(input) {
127
+ return recordFile(area(input)).read()?.key === conflictKey(input.conflict);
128
+ }
113
129
  function prepareRebase(input) {
114
130
  const gitDir = area(input);
115
- const old = read(gitDir);
131
+ const old = recordFile(gitDir).read();
116
132
  requireTarget(input, old?.key === conflictKey(input.conflict) ? old : null);
117
133
  if (old?.key === conflictKey(input.conflict)) {
118
134
  verifyCurrentBase(input, old);
@@ -147,7 +163,7 @@ function prepareRebase(input) {
147
163
  baseBranch: input.conflict.baseBranch
148
164
  };
149
165
  git(input, "update-ref", "refs/leitwerk/rebase-original", record.originalHead);
150
- save(gitDir, record);
166
+ recordFile(gitDir).save(record);
151
167
  return record;
152
168
  }
153
169
  function startRebase(input) {
@@ -161,13 +177,17 @@ function startRebase(input) {
161
177
  try {
162
178
  verifyNoRepairNeeded(input, record.originalHead, record.baseSha);
163
179
  record.status = "clean";
164
- save(gitDir, record);
180
+ recordFile(gitDir).save(record);
165
181
  return record;
166
182
  } catch (error) {
167
183
  if (error.status !== 1) throw error;
168
184
  }
185
+ assertReconciliationTargetSafe(
186
+ { projectKey: input.projectKey, repoPath: input.path },
187
+ record.baseSha
188
+ );
169
189
  record.status = "rebasing";
170
- save(gitDir, record);
190
+ recordFile(gitDir).save(record);
171
191
  try {
172
192
  git(input, "rebase", "--rebase-merges", record.baseSha);
173
193
  } catch (error) {
@@ -177,7 +197,7 @@ function startRebase(input) {
177
197
  }
178
198
  function verifyRebase(input) {
179
199
  const gitDir = area(input);
180
- const record = read(gitDir);
200
+ const record = recordFile(gitDir).read();
181
201
  if (!record || record.key !== conflictKey(input.conflict))
182
202
  throw new Error("Missing matching rebase metadata");
183
203
  requireTarget(input, record);
@@ -199,24 +219,94 @@ function verifyRebase(input) {
199
219
  baseSha: record.baseSha
200
220
  };
201
221
  }
222
+ var ConcurrentRebaseSourceError = class extends Error {
223
+ constructor(repair, published = false) {
224
+ super("Concurrent remote change rejected by rebase lease; local repair was retained");
225
+ this.repair = repair;
226
+ this.published = published;
227
+ }
228
+ repair;
229
+ published;
230
+ };
202
231
  function publishRebase(input) {
203
232
  const result = verifyRebase(input);
233
+ assertReconciliationTargetSafe(
234
+ { projectKey: input.projectKey, repoPath: input.path },
235
+ result.baseSha
236
+ );
204
237
  const gitDir = area(input);
205
- const record = read(gitDir);
238
+ const record = recordFile(gitDir).read();
206
239
  if (!record) throw new Error("Missing matching rebase metadata");
207
240
  verifyCurrentBase(input, record);
208
241
  const remote = remoteHead(input);
209
- if (rebasePublicationDecision(result.originalHead, result.headSha, remote) === "already_published")
242
+ const binding = readRepositoryBinding((...args) => git(input, ...args), input.workBranch);
243
+ if (binding.origin !== binding.pushOrigin)
244
+ throw new Error("Fetch and push endpoints must match for publication");
245
+ const previous = readPublicationReceipt(gitDir);
246
+ if (!repositoryBindingMatches(previous, binding))
247
+ throw new Error("Repository publication receipt binding changed");
248
+ const receipt = {
249
+ ...binding,
250
+ expectedHead: result.originalHead,
251
+ candidate: result.headSha,
252
+ status: "attempting"
253
+ };
254
+ if (remote === result.headSha) {
255
+ savePublicationReceipt(gitDir, { ...receipt, status: "accepted" });
210
256
  return result;
211
- git(
212
- input,
213
- "push",
214
- `--force-with-lease=refs/heads/${input.workBranch}:${result.originalHead}`,
215
- "origin",
216
- `${result.headSha}:refs/heads/${input.workBranch}`
217
- );
218
- if (remoteHead(input) !== result.headSha)
219
- throw new Error("Rebase publication could not be verified");
257
+ }
258
+ if (previous?.candidate === result.headSha && previous.status === "accepted")
259
+ throw new ConcurrentRebaseSourceError(result, true);
260
+ if (previous?.status === "attempting") {
261
+ git(
262
+ input,
263
+ "fetch",
264
+ "--no-tags",
265
+ "origin",
266
+ `+refs/heads/${input.workBranch}:refs/leitwerk/rebase-publication-proof`
267
+ );
268
+ try {
269
+ git(
270
+ input,
271
+ "merge-base",
272
+ "--is-ancestor",
273
+ previous.candidate,
274
+ "refs/leitwerk/rebase-publication-proof"
275
+ );
276
+ } catch {
277
+ throw new Error(
278
+ "Prior target publication outcome is uncertain; local repair was retained for operator reconciliation"
279
+ );
280
+ }
281
+ savePublicationReceipt(gitDir, { ...previous, status: "accepted" });
282
+ throw new ConcurrentRebaseSourceError(result, previous.candidate === result.headSha);
283
+ }
284
+ if (remote !== result.originalHead) throw new ConcurrentRebaseSourceError(result);
285
+ savePublicationReceipt(gitDir, receipt);
286
+ try {
287
+ git(
288
+ input,
289
+ "push",
290
+ "--porcelain",
291
+ "--no-follow-tags",
292
+ "--recurse-submodules=no",
293
+ `--force-with-lease=refs/heads/${input.workBranch}:${result.originalHead}`,
294
+ "origin",
295
+ `${result.headSha}:refs/heads/${input.workBranch}`
296
+ );
297
+ } catch (error) {
298
+ const rejected = pushWasRejected(error.stdout?.toString() ?? "");
299
+ if (rejected) savePublicationReceipt(gitDir, { ...receipt, status: "rejected" });
300
+ const latest = remoteHead(input);
301
+ if (latest === result.headSha) {
302
+ savePublicationReceipt(gitDir, { ...receipt, status: "accepted" });
303
+ return result;
304
+ }
305
+ if (rejected && latest !== result.originalHead) throw new ConcurrentRebaseSourceError(result);
306
+ throw error;
307
+ }
308
+ savePublicationReceipt(gitDir, { ...receipt, status: "accepted" });
309
+ if (remoteHead(input) !== result.headSha) throw new ConcurrentRebaseSourceError(result, true);
220
310
  return result;
221
311
  }
222
312
 
@@ -224,14 +314,49 @@ function publishRebase(input) {
224
314
  var rebasePrompt = `Repair only the recorded pull request merge conflict or behind-base condition. Deterministic preparation has fetched and verified the tracked head and current base, retained the original head and lease in .git/leitwerk-rebase.json, and started the rebase if the conflict or missing base commits are confirmed locally. Inspect that metadata and git status first. For behind-base evidence, incorporate the fetched base even when merging would be clean. A clean preparation result means no rewrite is needed. Resolve conflicts preserving the requested behavior, original authors, and existing Signed-off-by trailers. You may use git add and GIT_EDITOR=true git rebase --continue until finished. This explicitly overrides the prohibition on creating commits only for rebase continuation. Do not create unrelated commits, reset the branch, skip commits, abort the rebase, or push. Run focused repository checks after resolution. Delivery verifies the completed rebase and publishes with the recorded pre-repair lease. If blocked, retain the workspace and explain the failure for retry or abort. Record a concise repair result.`;
225
315
 
226
316
  // src/pull-request-publication-internal.ts
317
+ function createPullRequestChangeProcess(provider, label, docker, config) {
318
+ const { watcher, publication: adapter, ...definition } = config;
319
+ const publication = createRepositoryChangePublication(adapter);
320
+ publication.fragment.watcher({
321
+ ...watcher,
322
+ id: "use_leitwerk",
323
+ label: `${label} use-leitwerk issues`,
324
+ description: `Launch a remote repository change for ${label} issues carrying the trigger label`
325
+ });
326
+ const { process } = createRepositoryChangeProcess({
327
+ ...definition,
328
+ publication,
329
+ processId: `${provider}_repo_change_process`,
330
+ displayName: `${label} Repo Change`,
331
+ repositoryCredentials: ({ params }) => [
332
+ { projectKey: "repo", kind: "git_ssh", credentialRef: params.sshCredentialRef }
333
+ ]
334
+ });
335
+ process.runtime = { ...process.runtime, docker };
336
+ return process;
337
+ }
338
+ function pullRequestDeliveryTools(provider) {
339
+ return [
340
+ "get_pull_request",
341
+ "add_pull_request_comment",
342
+ "resolve_git_identity",
343
+ "ensure_pull_request",
344
+ "add_issue_comment",
345
+ "add_pull_request_feedback_reaction",
346
+ "reply_to_pull_request_feedback",
347
+ "get_issue",
348
+ "ensure_label",
349
+ "update_issue"
350
+ ].map((name) => `${provider}_${name}`);
351
+ }
227
352
  var callFor = (ctx, provider) => (name, args) => ctx.callIntegrationTool(`${provider}_${name}`, { projectKey: "repo", ...args });
228
- async function resolvePullRequestGitIdentity(ctx, provider, profile) {
229
- const project = ctx.projects.find((candidate) => candidate.key === "repo");
230
- const identity = publicationObject(publicationObject(project?.metadata)["leitwerk.gitIdentity"]);
231
- if (identity.provider === provider && identity.profile === profile && [identity.login, identity.name, identity.email].every(
232
- (value) => typeof value === "string" && value.trim()
233
- ))
353
+ async function resolvePullRequestGitIdentity(ctx, provider, profile, allowLookup = true) {
354
+ const project = ctx.repo.get("repo");
355
+ const metadata = ctx.projects.find((candidate) => candidate.key === project.key)?.metadata;
356
+ const identity = publicationObject(metadata?.["leitwerk.gitIdentity"]);
357
+ if (identity.provider === provider && identity.profile === profile && (!allowLookup || typeof identity.login === "string" && identity.login.trim()) && [identity.name, identity.email].every((value) => typeof value === "string" && value.trim()))
234
358
  return identity;
359
+ if (!allowLookup) throw new Error(`Pinned ${provider} Git identity is unavailable`);
235
360
  return callFor(ctx, provider)("resolve_git_identity", {});
236
361
  }
237
362
  function readPullRequestFeedback(current, event) {
@@ -245,34 +370,7 @@ function readPullRequestFeedback(current, event) {
245
370
  feedbackIds: value.feedbackIds ?? []
246
371
  };
247
372
  }
248
- function reconcilePullRequestSourceIssue(provider, labelKey, issueOrigin) {
249
- return async (ctx, _current, pr) => {
250
- const params = issueOrigin(ctx.params);
251
- if (!params) return;
252
- const call = callFor(ctx, provider);
253
- const issue = await call("get_issue", {
254
- issueNumber: params.issueNumber
255
- });
256
- let labels = issue.labels.filter((label) => label.name !== params.triggerLabel).map((label) => label[labelKey]);
257
- if (pr.merged) {
258
- const done = await call("ensure_label", {
259
- name: params.doneLabel
260
- });
261
- labels = [.../* @__PURE__ */ new Set([...labels, done[labelKey]])];
262
- }
263
- await call("update_issue", {
264
- issueNumber: params.issueNumber,
265
- patch: { labels, ...pr.merged ? { state: "closed" } : {} },
266
- writeKey: `${provider}:${ctx.process.id}:${pr.merged ? "complete-source-issue" : "remove-source-trigger"}`
267
- });
268
- await call("add_issue_comment", {
269
- issueNumber: params.issueNumber,
270
- body: pr.merged ? `Merged ${pr.html_url}${pr.merge_commit_sha ? ` at ${pr.merge_commit_sha}` : ""}.` : `Leitwerk stopped because ${pr.html_url} was closed without merge.`,
271
- writeKey: `${provider}:${ctx.process.id}:${pr.merged ? "merged" : "closed"}-pr-comment`
272
- });
273
- };
274
- }
275
- function pullRequestPublicationSources(provider, label, external, profile, issueOrigin) {
373
+ function pullRequestPublicationDefaults(provider, label, external, profile, issueOrigin, labelKey, ci) {
276
374
  const remote = (state) => readPublicationState(state, `${provider}RepoChange`);
277
375
  function requirePr(state) {
278
376
  const value = remote(state);
@@ -343,20 +441,70 @@ function pullRequestPublicationSources(provider, label, external, profile, issue
343
441
  }),
344
442
  read: () => ({ kind: "cancelled" })
345
443
  };
346
- return {
444
+ async function finalizeIssue(ctx, pr) {
445
+ const params = issueOrigin(ctx.params);
446
+ if (!params) return;
447
+ const call2 = callFor(ctx, provider);
448
+ const issue = await call2("get_issue", {
449
+ issueNumber: params.issueNumber
450
+ });
451
+ let labels = issue.labels.filter((label2) => label2.name !== params.triggerLabel).map((label2) => label2[labelKey]);
452
+ if (pr?.merged) {
453
+ const done = await call2("ensure_label", {
454
+ name: params.doneLabel
455
+ });
456
+ labels = [.../* @__PURE__ */ new Set([...labels, done[labelKey]])];
457
+ }
458
+ await call2("update_issue", {
459
+ issueNumber: params.issueNumber,
460
+ patch: { labels, ...pr?.merged ? { state: "closed" } : {} },
461
+ writeKey: `${provider}:${ctx.process.id}:${pr?.merged ? "complete-source-issue" : pr ? "remove-source-trigger" : "no-changes-trigger"}`
462
+ });
463
+ await call2("add_issue_comment", {
464
+ issueNumber: params.issueNumber,
465
+ body: !pr ? "No repository changes were needed. No pull request was opened." : pr.merged ? `Merged ${pr.html_url}${pr.merge_commit_sha ? ` at ${pr.merge_commit_sha}` : ""}.` : `Leitwerk stopped because ${pr.html_url} was closed without merge.`,
466
+ writeKey: `${provider}:${ctx.process.id}:${pr ? `${pr.merged ? "merged" : "closed"}-pr-comment` : "no-changes-comment"}`
467
+ });
468
+ }
469
+ const call = (ctx) => callFor(ctx, provider);
470
+ const adapter = {
347
471
  /** @internal */
348
- requirePr,
472
+ namespace: `${provider}RepoChange`,
349
473
  /** @internal */
350
- feedback,
474
+ label: `${label} PR`,
351
475
  /** @internal */
352
- terminal,
476
+ ids: {
477
+ /** @internal */
478
+ deliver: "deliver_change",
479
+ /** @internal */
480
+ feedback: "revise_from_pull_request_feedback",
481
+ /** @internal */
482
+ ciRepair: ci.id,
483
+ /** @internal */
484
+ operator: "ci_operator_action"
485
+ },
353
486
  /** @internal */
354
- cancelled
355
- };
356
- }
357
- function pullRequestPublicationCallbacks(provider, label, issueOrigin) {
358
- const call = (ctx) => callFor(ctx, provider);
359
- return {
487
+ tools: {
488
+ /** @internal */
489
+ delivery: pullRequestDeliveryTools(provider),
490
+ /** @internal */
491
+ feedback: [
492
+ `${provider}_get_pull_request`,
493
+ `${provider}_list_pull_request_feedback`
494
+ ],
495
+ /** @internal */
496
+ ci: ci.tools
497
+ },
498
+ /** @internal */
499
+ commitMessage: (kind) => kind === "feedback" ? `fix: address ${label} review feedback` : `fix: repair ${ci.label}`,
500
+ /** @internal */
501
+ prompt: (kind, current) => kind === "feedback" ? `Address the unseen ${label} pull-request feedback batch for PR #${current.prNumber}. Feedback identifiers: ${JSON.stringify(current.feedbackIds)}. Inspect the current checkout and use ${label} tools to read the full feedback. Do not rely on an earlier plan or conversation. Make only justified repository changes. Call changes_ready if files need publishing, no_changes after an explicit diagnosis that no repository change is needed, or cannot_repair when operator action is required.` : ci.prompt(current),
502
+ /** @internal */
503
+ identity: (ctx) => resolvePullRequestGitIdentity(ctx, provider, profile(ctx.params)),
504
+ /** @internal */
505
+ reconcileTerminal: (ctx, _current, pr) => finalizeIssue(ctx, pr),
506
+ /** @internal */
507
+ unchanged: (ctx) => finalizeIssue(ctx, null),
360
508
  async ensureRequest(ctx) {
361
509
  const project = ctx.repo.get("repo");
362
510
  const issue = issueOrigin(ctx.params);
@@ -382,24 +530,24 @@ Leitwerk process: ${ctx.process.id}` : `Leitwerk process: ${ctx.process.id}`,
382
530
  },
383
531
  async reply(ctx, current) {
384
532
  const invoke = call(ctx);
385
- for (const feedback of current.feedbackIds)
533
+ for (const feedback2 of current.feedbackIds)
386
534
  await invoke("reply_to_pull_request_feedback", {
387
535
  pullRequestNumber: current.prNumber,
388
- feedbackKind: feedback.kind,
389
- feedbackId: feedback.id,
536
+ feedbackKind: feedback2.kind,
537
+ feedbackId: feedback2.id,
390
538
  body: `Addressed in ${current.headSha?.slice(0, 8) ?? "the current revision"}.`,
391
- writeKey: `${provider}:${ctx.process.id}:feedback-reply:${feedback.kind}:${feedback.id}:${current.headSha}`
539
+ writeKey: `${provider}:${ctx.process.id}:feedback-reply:${feedback2.kind}:${feedback2.id}:${current.headSha}`
392
540
  });
393
541
  },
394
542
  async acknowledge(ctx, current) {
395
543
  const invoke = call(ctx);
396
- for (const feedback of current.feedbackIds) {
397
- if (feedback.kind === "review") continue;
544
+ for (const feedback2 of current.feedbackIds) {
545
+ if (feedback2.kind === "review") continue;
398
546
  await invoke("add_pull_request_feedback_reaction", {
399
547
  pullRequestNumber: current.prNumber,
400
- feedbackKind: feedback.kind,
401
- feedbackId: feedback.id,
402
- writeKey: `${provider}:${ctx.process.id}:feedback-eyes:${feedback.kind}:${feedback.id}`
548
+ feedbackKind: feedback2.kind,
549
+ feedbackId: feedback2.id,
550
+ writeKey: `${provider}:${ctx.process.id}:feedback-eyes:${feedback2.kind}:${feedback2.id}`
403
551
  });
404
552
  }
405
553
  },
@@ -416,9 +564,41 @@ Leitwerk process: ${ctx.process.id}` : `Leitwerk process: ${ctx.process.id}`,
416
564
  });
417
565
  }
418
566
  };
567
+ return {
568
+ /** @internal */
569
+ adapter,
570
+ /** @internal */
571
+ conflict(source) {
572
+ return {
573
+ id: `${provider}_merge_conflict`,
574
+ kind: "conflict",
575
+ label: "Rebase conflicting pull request",
576
+ source,
577
+ read: ({ event }) => ({
578
+ kind: "conflict",
579
+ conflict: publicationObject(event).conflict
580
+ })
581
+ };
582
+ },
583
+ /** @internal */
584
+ requirePr,
585
+ /** @internal */
586
+ feedback,
587
+ /** @internal */
588
+ terminal,
589
+ /** @internal */
590
+ cancelled
591
+ };
419
592
  }
420
593
 
421
594
  // src/repository-change-publication.ts
595
+ function requirePublicationParams(params) {
596
+ const value = asUnknownRecord(params);
597
+ for (const key of ["owner", "repo", "workBranch", "baseBranch"])
598
+ if (typeof value?.[key] !== "string" || !value[key])
599
+ throw new Error("Repository binding is not resolved");
600
+ return params;
601
+ }
422
602
  var initialDeliveryState = {
423
603
  stage: "not_started",
424
604
  issueLinked: false,
@@ -438,6 +618,21 @@ var initialPublicationState = {
438
618
  delivery: initialDeliveryState
439
619
  };
440
620
  var publicationObject = (value) => asUnknownRecord(value) ?? {};
621
+ function createPublicationSelection(namespace) {
622
+ return {
623
+ /** @internal */
624
+ activeKey: (state) => publicationObject(state.extensionState?.[`${namespace()}.coordination`]).activeKey,
625
+ /** @internal */
626
+ select: (state, key) => ({
627
+ ...state,
628
+ extensionState: {
629
+ ...state.extensionState,
630
+ [`${namespace()}.coordination`]: { activeKey: key }
631
+ }
632
+ })
633
+ };
634
+ }
635
+ var publicationFinished = (current) => !!(current.stopped || current.noChanges || current.delivery.terminalPullRequest);
441
636
  function readPublicationState(state, namespace) {
442
637
  const stored = publicationObject(publicationObject(state.extensionState)[namespace]);
443
638
  return {
@@ -466,6 +661,14 @@ function patchPublicationState(state, namespace, patch) {
466
661
  function applyPublicationEvidence(params, current, evidence, countFailure = true) {
467
662
  if (evidence.observationKey !== void 0)
468
663
  current = { ...current, observationKey: evidence.observationKey };
664
+ if (evidence.remoteHeadSha && evidence.remoteHeadSha !== current.headSha)
665
+ current = {
666
+ ...current,
667
+ workBaselineSha: current.workBaselineSha ?? current.headSha,
668
+ lastPublishedHeadSha: current.lastPublishedHeadSha ?? current.headSha,
669
+ headSha: evidence.remoteHeadSha,
670
+ pipeline: null
671
+ };
469
672
  switch (evidence.kind) {
470
673
  case "feedback": {
471
674
  const { kind: _, ...batch } = evidence;
@@ -479,15 +682,16 @@ function applyPublicationEvidence(params, current, evidence, countFailure = true
479
682
  ciRecoveryCycles: current.ciRecoveryCycles + (countFailure ? 1 : 0)
480
683
  };
481
684
  case "conflict": {
685
+ const repository = requirePublicationParams(params);
482
686
  const conflict = validateConflict(
483
687
  evidence.conflict,
484
688
  {
485
- owner: params.owner,
486
- repo: params.repo,
689
+ owner: repository.owner,
690
+ repo: repository.repo,
487
691
  prNumber: current.prNumber ?? 0,
488
692
  headSha: current.headSha ?? "",
489
- headBranch: params.workBranch,
490
- baseBranch: params.baseBranch
693
+ headBranch: repository.workBranch,
694
+ baseBranch: repository.baseBranch
491
695
  },
492
696
  current.lastConflictKey
493
697
  );
@@ -549,26 +753,75 @@ function deliveryProgress(value, label, activeStepId) {
549
753
  function createRepositoryChangePublication(adapter) {
550
754
  const ids = adapter.ids;
551
755
  const publication = flow.fragment(`${adapter.namespace}-publication`);
552
- const remote = (state) => readPublicationState(state, adapter.namespace);
553
- const patchRemote = (state, patch) => patchPublicationState(state, adapter.namespace, patch);
554
- async function commitWorkBranch(ctx, commitMessage) {
756
+ const { activeKey, select } = createPublicationSelection(() => adapter.namespace);
757
+ const namespace = (state) => adapter.repositories ? `${adapter.namespace}:${activeKey(state)}` : adapter.namespace;
758
+ const remote = (state) => readPublicationState(state, namespace(state));
759
+ const repositoryContext = (ctx) => {
760
+ if (!adapter.repositories) return ctx;
761
+ const selected = adapter.repositories(ctx.params).find((repo) => repo.key === activeKey(ctx.state));
762
+ if (!selected) throw new Error("Missing coordinated repository selection");
763
+ return {
764
+ ...ctx,
765
+ params: selected.params,
766
+ repo: { ...ctx.repo, get: (key) => ctx.repo.get(key === "repo" ? selected.key : key) },
767
+ callIntegrationTool: (name, args) => ctx.callIntegrationTool(name, { ...args, projectKey: selected.key })
768
+ };
769
+ };
770
+ const patchRemote = (state, patch) => patchPublicationState(state, namespace(state), patch);
771
+ async function commitWorkBranch(ctx, commitMessage, expectedRemoteHead = remote(ctx.state).headSha) {
555
772
  const repo = ctx.repo.get("repo");
773
+ const gitIdentity = await adapter.identity(ctx);
774
+ if (adapter.maintenance)
775
+ await ctx.callIntegrationTool(adapter.maintenance.ownershipTool, { projectKey: repo.key });
556
776
  return commitAndPushWorkBranch({
557
777
  repoPath: repo.fsPath,
778
+ projectKey: repo.key,
558
779
  workBranch: repo.workBranch,
559
780
  commitMessage,
781
+ gitIdentity,
782
+ expectedRemoteHead
783
+ });
784
+ }
785
+ async function reconcile(ctx, current) {
786
+ const repo = ctx.repo.get("repo");
787
+ return reconcilePublicationRepository({
788
+ projectKey: repo.key,
789
+ repoPath: repo.fsPath,
790
+ workBranch: repo.workBranch,
791
+ baselineSha: current.workBaselineSha ?? current.headSha ?? void 0,
560
792
  gitIdentity: await adapter.identity(ctx)
561
793
  });
562
794
  }
563
- const delivery = flow.automatic(ids.deliver).description("Deliver").integrationTools(...adapter.tools.delivery).run(async (ctx) => {
795
+ const runRepository = async (ctx) => {
564
796
  let current = remote(ctx.state);
565
797
  const update = (patch) => {
566
798
  current = { ...current, ...patch, delivery: { ...current.delivery, ...patch.delivery } };
567
799
  };
800
+ const acknowledgePublication = (headSha, changed) => {
801
+ update({
802
+ headSha,
803
+ workBaselineSha: headSha,
804
+ lastPublishedHeadSha: changed ? headSha : current.lastPublishedHeadSha,
805
+ reconciliationRequired: false,
806
+ reconciliationCycles: 0,
807
+ pipeline: changed ? null : current.pipeline
808
+ });
809
+ const repo = ctx.repo.get("repo");
810
+ recordRepositoryPublication(
811
+ {
812
+ projectKey: repo.key,
813
+ repoPath: repo.fsPath,
814
+ workBranch: repo.workBranch,
815
+ baselineSha: headSha
816
+ },
817
+ headSha
818
+ );
819
+ };
568
820
  const result = (outcome2) => ({
569
821
  outcome: outcome2,
570
822
  params: { nextState: patchRemote(ctx.state, current) }
571
823
  });
824
+ if (current.stopped) return result("aborted");
572
825
  if (current.pendingEvidence) {
573
826
  const evidence = current.pendingEvidence;
574
827
  const needsOperator = evidence.kind === "failure" && current.ciRecoveryCycles >= 3;
@@ -580,6 +833,19 @@ function createRepositoryChangePublication(adapter) {
580
833
  if (evidence.kind === "conflict") return result("conflict_ready");
581
834
  }
582
835
  ctx.reportProgress(deliveryProgress(current, adapter.label));
836
+ const reconcileAgain = () => {
837
+ const cycles = (current.reconciliationCycles ?? 0) + 1;
838
+ update({
839
+ reconciliationRequired: true,
840
+ reconciliationCycles: cycles,
841
+ repairPending: true,
842
+ conflict: null,
843
+ lastConflictKey: null,
844
+ pipeline: null,
845
+ delivery: { adjustment: null, feedbackResult: null }
846
+ });
847
+ return result(cycles > 3 ? "operator_action" : "conflict_ready");
848
+ };
583
849
  if (current.delivery.terminalPullRequest) {
584
850
  ctx.reportProgress(deliveryProgress(current, adapter.label, "reconcile_terminal"));
585
851
  const pr = current.delivery.terminalPullRequest;
@@ -587,13 +853,37 @@ function createRepositoryChangePublication(adapter) {
587
853
  ctx.reportProgress(deliveryProgress(current, adapter.label));
588
854
  return result(pr.merged ? "completed" : "aborted");
589
855
  }
856
+ if (!current.headSha && (adapter.repositories || adapter.unchanged) && !repositoryHasChanges(
857
+ ctx.repo.get("repo").fsPath,
858
+ ctx.repo.get("repo").baseBranch,
859
+ ctx.repo.get("repo").key
860
+ )) {
861
+ update({ noChanges: true });
862
+ await adapter.unchanged?.(ctx);
863
+ return result("completed");
864
+ }
865
+ let publicationLease = current.headSha;
866
+ if ((!current.headSha || current.delivery.adjustment) && current.delivery.adjustment?.origin !== "rebase") {
867
+ const synchronized = await reconcile(ctx, current);
868
+ if (synchronized.changed || synchronized.status === "conflicts") return reconcileAgain();
869
+ publicationLease = synchronized.remoteHead;
870
+ if (current.headSha && synchronized.remoteHead && current.headSha !== synchronized.remoteHead)
871
+ update({ headSha: synchronized.remoteHead, workBaselineSha: synchronized.remoteHead });
872
+ }
590
873
  if (!current.headSha) {
591
874
  ctx.reportProgress(deliveryProgress(current, adapter.label, "publish_branch"));
592
- const published = await commitWorkBranch(
593
- ctx,
594
- ctx.state.finalization.generatedCommitMessage ?? ""
595
- );
596
- update({ headSha: published.headSha, pipeline: null });
875
+ let published;
876
+ try {
877
+ published = await commitWorkBranch(
878
+ ctx,
879
+ ctx.state.finalization.commitMessages?.[ctx.repo.get("repo").key] ?? ctx.state.finalization.generatedCommitMessage ?? "",
880
+ publicationLease
881
+ );
882
+ } catch (error) {
883
+ if (!(error instanceof RemoteBranchChangedError)) throw error;
884
+ return reconcileAgain();
885
+ }
886
+ acknowledgePublication(published.headSha, true);
597
887
  }
598
888
  if (!current.prNumber || !current.prUrl) {
599
889
  ctx.reportProgress(deliveryProgress(current, adapter.label, "open_pr"));
@@ -607,27 +897,67 @@ function createRepositoryChangePublication(adapter) {
607
897
  }
608
898
  if (current.delivery.adjustment) {
609
899
  const adjustment = current.delivery.adjustment;
610
- if (adjustment.publishRequired || adjustment.origin === "rebase") {
900
+ if (adjustment.origin === "rebase" && !hasPreparedRebase(rebaseInput(ctx)))
901
+ return reconcileAgain();
902
+ let adjustmentPublished = false;
903
+ if (adjustment.publishRequired || adjustment.origin === "rebase" || adapter.maintenance) {
611
904
  ctx.reportProgress(deliveryProgress(current, adapter.label, "publish_adjustment"));
612
- const published = adjustment.origin === "rebase" ? publishRebase(rebaseInput(ctx)) : await commitWorkBranch(ctx, adapter.commitMessage(adjustment.origin));
905
+ if (adapter.maintenance)
906
+ await ctx.callIntegrationTool(adapter.maintenance.ownershipTool, {
907
+ projectKey: ctx.repo.get("repo").key
908
+ });
909
+ let published;
910
+ try {
911
+ published = adjustment.origin === "rebase" ? publishRebase(rebaseInput(ctx)) : await commitWorkBranch(
912
+ { ...ctx, state: patchRemote(ctx.state, current) },
913
+ adapter.commitMessage(adjustment.origin)
914
+ );
915
+ } catch (error) {
916
+ if (error instanceof ConcurrentRebaseSourceError) {
917
+ if (error.published) return reconcileAgain();
918
+ const project = ctx.repo.get("repo");
919
+ retainConcurrentRebase({
920
+ projectKey: project.key,
921
+ repoPath: project.fsPath,
922
+ workBranch: project.workBranch,
923
+ baselineSha: error.repair.originalHead,
924
+ rebasedHead: error.repair.headSha,
925
+ targetBase: error.repair.baseSha,
926
+ gitIdentity: await adapter.identity(ctx)
927
+ });
928
+ return reconcileAgain();
929
+ }
930
+ if (!(error instanceof RemoteBranchChangedError)) throw error;
931
+ return reconcileAgain();
932
+ }
613
933
  if (adjustment.origin === "rebase") {
614
934
  const head = await adapter.head(ctx, current);
615
935
  if (head !== published.headSha)
616
936
  throw new Error("Pull request head has not caught up with rebase publication");
617
937
  }
618
- update({ headSha: published.headSha, pipeline: null });
938
+ adjustmentPublished = published.headSha !== publicationLease;
939
+ acknowledgePublication(published.headSha, adjustmentPublished);
619
940
  }
620
941
  if (adjustment.origin === "rebase") await adapter.afterRebase(ctx, current);
621
- if (adjustment.origin === "feedback") {
942
+ if (adjustment.origin === "feedback" && !adapter.maintenance) {
622
943
  ctx.reportProgress(deliveryProgress(current, adapter.label, "reply_feedback"));
623
944
  await adapter.reply(ctx, current);
624
945
  }
625
946
  update({
626
- ...adjustment.origin === "feedback" ? { feedbackIds: [] } : {},
627
- delivery: { adjustment: null }
947
+ ...adjustment.origin === "feedback" && !adapter.maintenance ? { feedbackIds: [] } : {},
948
+ ...adjustment.origin === "rebase" ? { conflict: null } : {},
949
+ delivery: {
950
+ adjustment: null,
951
+ ...adjustment.origin === "feedback" && adapter.maintenance ? {
952
+ feedbackResult: {
953
+ published: adjustmentPublished,
954
+ summary: adjustmentPublished ? "Review adjustment published" : adjustment.summary ?? "No repository change was required"
955
+ }
956
+ } : {}
957
+ }
628
958
  });
629
959
  }
630
- if (current.feedbackIds.length > 0) {
960
+ if (current.feedbackIds.length > 0 && !adapter.maintenance) {
631
961
  ctx.reportProgress(deliveryProgress(current, adapter.label, "reply_feedback"));
632
962
  await adapter.acknowledge(ctx, current);
633
963
  return result("feedback_ready");
@@ -635,15 +965,76 @@ function createRepositoryChangePublication(adapter) {
635
965
  update({ delivery: { stage: "awaiting" } });
636
966
  ctx.reportProgress(deliveryProgress(current, adapter.label, "await_evidence"));
637
967
  return result("awaiting");
968
+ };
969
+ const delivery = flow.automatic(ids.deliver).description("Deliver").waitFor(({ state, params }) => {
970
+ const states = adapter.repositories ? adapter.repositories(params).map(({ key }) => select(state, key)) : [state];
971
+ return states.some((state2) => {
972
+ const current = remote(state2);
973
+ if (adapter.maintenance)
974
+ return !current.stopped && !current.noChanges && !current.delivery.terminalPullRequest && (current.delivery.stage !== "awaiting" || !!current.delivery.adjustment);
975
+ return current.delivery.stage !== "awaiting" || !!current.pendingEvidence || !!current.delivery.adjustment || current.feedbackIds.length > 0 || !!current.delivery.terminalPullRequest;
976
+ });
977
+ }).integrationTools(...adapter.tools.delivery).run(async (ctx) => {
978
+ if (!adapter.repositories) return runRepository(ctx);
979
+ let state = ctx.state;
980
+ const repositories = adapter.repositories(ctx.params);
981
+ if (!repositories.length) throw new Error("No repositories are bound");
982
+ const results = () => repositories.map(({ key }) => ({ key, current: remote(select(state, key)) }));
983
+ const finished = () => results().every(({ current }) => publicationFinished(current));
984
+ const reconcileTerminals = async () => {
985
+ for (const { key } of repositories) {
986
+ state = select(state, key);
987
+ const current = remote(state);
988
+ if (publicationFinished(current)) continue;
989
+ const terminal = await adapter.observeTerminal?.(
990
+ repositoryContext({ ...ctx, state }),
991
+ current
992
+ );
993
+ if (terminal)
994
+ state = patchRemote(state, {
995
+ prNumber: terminal.number,
996
+ prUrl: terminal.html_url,
997
+ delivery: { terminalPullRequest: terminal }
998
+ });
999
+ }
1000
+ };
1001
+ await reconcileTerminals();
1002
+ let cancelled = false;
1003
+ for (const { key } of repositories) {
1004
+ state = select(state, key);
1005
+ if (publicationFinished(remote(state))) continue;
1006
+ if (await adapter.sourceCancelled?.({ ...ctx, state })) {
1007
+ await reconcileTerminals();
1008
+ cancelled = !finished();
1009
+ break;
1010
+ }
1011
+ const result = await runRepository(repositoryContext({ ...ctx, state }));
1012
+ state = result.params.nextState;
1013
+ if (!["awaiting", "completed", "aborted"].includes(result.outcome))
1014
+ return { ...result, params: { nextState: state } };
1015
+ }
1016
+ if (cancelled || finished()) {
1017
+ await adapter.reconcileAll?.({ ...ctx, state }, results(), cancelled);
1018
+ const requests = results().flatMap(
1019
+ ({ current }) => current.delivery.terminalPullRequest ? [current.delivery.terminalPullRequest] : []
1020
+ );
1021
+ return {
1022
+ outcome: cancelled || requests.length > 0 && requests.every((request) => !request.merged) ? "aborted" : "completed",
1023
+ params: { nextState: state }
1024
+ };
1025
+ }
1026
+ return { outcome: "awaiting", params: { nextState: state } };
638
1027
  });
639
1028
  const outcome = (o, description) => o.description(description).object("nextState").state(({ event }) => event.params.nextState);
640
- delivery.outcome("awaiting", (o) => outcome(o, "Delivery is waiting for external evidence").wait()).outcome(
641
- "feedback_ready",
642
- (o) => outcome(o, "Pull request feedback is acknowledged and ready for revision").to(ids.feedback)
643
- ).outcome("completed", (o) => outcome(o, "Merged pull request was reconciled").complete()).outcome(
1029
+ delivery.outcome("awaiting", (o) => outcome(o, "Delivery is waiting for external evidence").wait()).outcome("completed", (o) => outcome(o, "Merged pull request was reconciled").complete()).outcome(
644
1030
  "aborted",
645
1031
  (o) => outcome(o, "Closed pull request was reconciled").lifecycleStatus("aborted")
646
1032
  );
1033
+ if (!adapter.maintenance)
1034
+ delivery.outcome(
1035
+ "feedback_ready",
1036
+ (o) => outcome(o, "Pull request feedback is acknowledged and ready for revision").to(ids.feedback)
1037
+ );
647
1038
  for (const [name, target] of [
648
1039
  ["ci_ready", ids.ciRepair],
649
1040
  ["conflict_ready", ids.feedback],
@@ -652,9 +1043,12 @@ function createRepositoryChangePublication(adapter) {
652
1043
  delivery.outcome(name, (o) => outcome(o, "Route observed delivery evidence").to(target));
653
1044
  }
654
1045
  for (const source of adapter.sources) {
1046
+ if (adapter.maintenance && source.kind === "observation") continue;
655
1047
  const attach = (id, operator) => delivery.externalAction(id, source.source, (external) => {
656
1048
  external.label(source.label).when(
657
- ({ params, state }) => (!source.enabled || source.enabled(params)) && (source.kind !== "failure" || remote(state).ciRecoveryCycles >= 3 === operator)
1049
+ ({ params, state }) => (!source.enabled || source.enabled(params, state)) && (source.kind === "cancelled" || (adapter.repositories ? adapter.repositories(params).map(({ key }) => remote(select(state, key))) : [remote(state)]).every(
1050
+ (current) => current.noChanges || current.delivery.terminalPullRequest || !!(current.headSha && current.prNumber && current.prUrl)
1051
+ )) && (source.kind !== "failure" || remote(state).ciRecoveryCycles >= 3 === operator)
658
1052
  );
659
1053
  if (source.kind === "cancelled") return external.lifecycleStatus("aborted");
660
1054
  external.to(
@@ -662,10 +1056,11 @@ function createRepositoryChangePublication(adapter) {
662
1056
  );
663
1057
  return external.effect((input) => {
664
1058
  const evidence = source.read(input);
665
- const current = remote(input.state);
1059
+ const state = adapter.repositories && evidence.projectKey ? select(input.state, evidence.projectKey) : input.state;
1060
+ const current = remote(state);
666
1061
  return {
667
1062
  state: patchRemote(
668
- input.state,
1063
+ state,
669
1064
  source.kind === "observation" ? { pendingEvidence: evidence } : applyPublicationEvidence(input.params, current, evidence, !operator)
670
1065
  )
671
1066
  };
@@ -674,12 +1069,30 @@ function createRepositoryChangePublication(adapter) {
674
1069
  attach(source.id, false);
675
1070
  if (source.kind === "failure") attach(source.operatorId ?? `${source.id}_operator`, true);
676
1071
  }
1072
+ if (adapter.maintenance) {
1073
+ for (const [id, target] of [
1074
+ ["feedback", ids.feedback],
1075
+ ["conflict", ids.feedback],
1076
+ ["ci", ids.ciRepair],
1077
+ ["operator", ids.operator]
1078
+ ])
1079
+ delivery.externalAction(
1080
+ `maintenance_${id}`,
1081
+ adapter.maintenance.source,
1082
+ (action) => action.label("Maintain MR").to(target).effect(({ event }) => ({ state: event.state }))
1083
+ );
1084
+ }
677
1085
  publication.turn(delivery);
678
1086
  function rebaseInput(ctx) {
679
- const project = ctx.repo.get("repo");
1087
+ const project = ctx.repo.get(activeKey(ctx.state) ?? "repo");
680
1088
  const conflict = remote(ctx.state).conflict;
681
1089
  if (!conflict) throw new Error("Missing conflict evidence");
682
- return { projectKey: "repo", path: project.fsPath, workBranch: project.workBranch, conflict };
1090
+ return {
1091
+ projectKey: activeKey(ctx.state) ?? "repo",
1092
+ path: project.fsPath,
1093
+ workBranch: project.workBranch,
1094
+ conflict
1095
+ };
683
1096
  }
684
1097
  function repairReason(state, kind) {
685
1098
  return kind === "feedback" && remote(state).repairReason === "rebase" ? "rebase" : kind;
@@ -687,49 +1100,122 @@ function createRepositoryChangePublication(adapter) {
687
1100
  function revisionPrompt(kind) {
688
1101
  return (ctx) => {
689
1102
  const current = remote(ctx.state);
1103
+ const repository = adapter.repositories ? `Repository: ${activeKey(ctx.state)}. Apply changes only to this checkout. ` : "";
1104
+ if (asUnknownRecord(ctx.prepared)?.deferredRebase)
1105
+ return `${repository}${reconciliationPrompt}
1106
+ The 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.`;
1107
+ if (current.reconciliationRequired)
1108
+ return `${repository}${reconciliationPrompt}
1109
+ Validate 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.
1110
+ Original request for context: ${ctx.prompts?.initial ?? "Inspect the current repository and retained request"}`;
690
1111
  if (repairReason(ctx.state, kind) === "rebase")
691
1112
  return `${rebasePrompt} Evidence: ${JSON.stringify(current.conflict)}. Call changes_ready or no_changes when verified complete, cannot_repair when blocked.`;
692
- return adapter.prompt(kind, current);
1113
+ return `${adapter.repositories ? `Repository: ${activeKey(ctx.state)}. Apply changes only to this checkout. ` : ""}${adapter.prompt(kind, current)}
1114
+
1115
+ ${reconciliationPrompt}`;
693
1116
  };
694
1117
  }
695
1118
  function revisionTurn(id, kind) {
696
- const turn = flow.llm(id).description(kind === "feedback" ? "Address Feedback" : "Fix CI").tools("read", "bash", "edit", "write").resolveIntegrationTools(
697
- (_params, state) => repairReason(state, kind) === "rebase" ? [] : adapter.tools[kind]
698
- ).prepare(
699
- (ctx) => repairReason(ctx.state, kind) === "rebase" ? startRebase(rebaseInput(ctx)) : {}
700
- ).freshPrimary().prompt(revisionPrompt(kind));
701
- for (const [name, description, publishRequired] of [
702
- ["changes_ready", "Repository changes are ready to publish", true],
703
- ["no_changes", "No repository change is required", false]
1119
+ const turn = flow.llm(id).description(kind === "feedback" ? "Address Feedback" : "Fix CI").waitFor(({ state }) => {
1120
+ const current = remote(state);
1121
+ return !current.stopped && !current.delivery.terminalPullRequest && (kind === "feedback" ? current.feedbackIds.length > 0 || !!current.conflict || !!current.reconciliationRequired : current.repairReason === "ci" && current.pipeline !== null);
1122
+ }).executionPurpose(codingPurposes.implementation).tools("read", "bash", "edit", "write").resolveIntegrationTools(
1123
+ (_params, state) => repairReason(state, kind) === "rebase" && !remote(state).reconciliationRequired ? [] : adapter.tools[kind]
1124
+ ).prepare(async (ctx) => {
1125
+ const project = ctx.repo.get(activeKey(ctx.state) ?? "repo");
1126
+ const current = remote(ctx.state);
1127
+ const targetRebase = repairReason(ctx.state, kind) === "rebase" && !current.reconciliationRequired;
1128
+ if (targetRebase && hasPreparedRebase(rebaseInput(ctx)))
1129
+ return { rebase: startRebase(rebaseInput(ctx)) };
1130
+ ctx.reportProgress({
1131
+ title: "Repository reconciliation",
1132
+ steps: [
1133
+ {
1134
+ id: "reconcile_source",
1135
+ label: "Reconcile remote source and retained local work",
1136
+ status: "in_progress"
1137
+ }
1138
+ ]
1139
+ });
1140
+ const reconciliation = await reconcile(repositoryContext(ctx), current);
1141
+ ctx.reportProgress({
1142
+ title: "Repository reconciliation",
1143
+ steps: [
1144
+ {
1145
+ id: "reconcile_source",
1146
+ label: reconciliation.status === "conflicts" ? "Resolve source reconciliation conflicts" : "Remote source reconciled",
1147
+ status: reconciliation.status === "conflicts" ? "in_progress" : "completed"
1148
+ }
1149
+ ]
1150
+ });
1151
+ if (targetRebase) {
1152
+ if (reconciliation.changed || reconciliation.headSha !== current.conflict?.headSha || repositoryWorktreeIsDirty({ projectKey: project.key, repoPath: project.fsPath }))
1153
+ return { reconciliation, deferredRebase: true };
1154
+ return { rebase: startRebase(rebaseInput(ctx)) };
1155
+ }
1156
+ return { reconciliation };
1157
+ }).freshPrimary().prompt(revisionPrompt(kind));
1158
+ for (const [name, description] of [
1159
+ ["changes_ready", "Repository changes are ready to publish"],
1160
+ ["no_changes", "No repository change is required"]
704
1161
  ]) {
705
1162
  turn.outcomeTool(
706
1163
  name,
707
1164
  (tool) => tool.resultSummary().description(description).to(ids.deliver).state(
708
- ({ ctx }) => patchRemote(ctx.state, {
709
- delivery: { adjustment: { origin: repairReason(ctx.state, kind), publishRequired } }
1165
+ ({ ctx, event }) => patchRemote(ctx.state, {
1166
+ repairPending: false,
1167
+ delivery: {
1168
+ // Even no_changes must cross delivery's remote race check. It may
1169
+ // have inherited unpublished work or a concurrent developer push.
1170
+ adjustment: {
1171
+ origin: remote(ctx.state).reconciliationRequired ? "feedback" : repairReason(ctx.state, kind),
1172
+ publishRequired: name === "changes_ready" || !!remote(ctx.state).reconciliationRequired,
1173
+ summary: String(
1174
+ event.params?.resultSummary ?? "No repository change was required"
1175
+ )
1176
+ }
1177
+ }
710
1178
  })
711
1179
  )
712
1180
  );
713
1181
  }
714
- return turn.outcomeTool(
715
- "cannot_repair",
716
- (tool) => tool.description("The adjustment requires operator action").to(ids.operator)
717
- );
1182
+ return turn.outcomeTool("cannot_repair", (tool) => {
1183
+ const outcome2 = tool.description("The adjustment requires operator action").to(ids.operator);
1184
+ return adapter.maintenance ? outcome2.state(({ ctx }) => patchRemote(ctx.state, { repairPending: false })) : outcome2;
1185
+ });
718
1186
  }
719
1187
  publication.turn(revisionTurn(ids.feedback, "feedback"));
720
1188
  publication.turn(revisionTurn(ids.ciRepair, "ci"));
1189
+ const maintenanceSource = adapter.maintenance?.source;
721
1190
  publication.turn({
722
1191
  id: ids.operator,
723
1192
  definition: {
724
1193
  kind: "human",
725
1194
  description: "Repository repair needs operator action",
726
1195
  operatorAttention: "required",
1196
+ ...maintenanceSource ? {
1197
+ externalActions: Object.fromEntries(
1198
+ ["feedback", "conflict"].map((id) => [
1199
+ `maintenance_${id}`,
1200
+ {
1201
+ id: `maintenance_${id}`,
1202
+ source: maintenanceSource,
1203
+ to: ids.feedback,
1204
+ label: "Maintain MR",
1205
+ effect: ({ event }) => ({
1206
+ state: event.state
1207
+ })
1208
+ }
1209
+ ])
1210
+ )
1211
+ } : {},
727
1212
  actions: {
728
1213
  retry_repair: {
729
1214
  label: "Retry repair",
730
1215
  acceptanceState: "accepted",
731
1216
  branches: { feedback: { to: ids.feedback }, ci: { to: ids.ciRepair } },
732
- choose: ({ ctx }) => remote(ctx.state).repairReason === "rebase" || remote(ctx.state).repairReason === "feedback" ? "feedback" : "ci"
1217
+ effect: adapter.maintenance ? ({ ctx }) => ({ state: patchRemote(ctx.state, { reconciliationCycles: 0 }) }) : void 0,
1218
+ choose: ({ ctx }) => remote(ctx.state).repairReason === "rebase" || remote(ctx.state).repairReason === "feedback" || remote(ctx.state).reconciliationRequired ? "feedback" : "ci"
733
1219
  },
734
1220
  resume_waiting: {
735
1221
  label: "Resume waiting",
@@ -737,6 +1223,7 @@ function createRepositoryChangePublication(adapter) {
737
1223
  to: ids.deliver,
738
1224
  effect: ({ ctx }) => ({
739
1225
  state: patchRemote(ctx.state, {
1226
+ repairPending: false,
740
1227
  feedbackIds: [],
741
1228
  delivery: { adjustment: null }
742
1229
  })
@@ -757,14 +1244,15 @@ function createRepositoryChangePublication(adapter) {
757
1244
  }
758
1245
  export {
759
1246
  applyPublicationEvidence,
1247
+ createPublicationSelection,
1248
+ createPullRequestChangeProcess,
760
1249
  createRepositoryChangePublication,
761
1250
  patchPublicationState,
1251
+ publicationFinished,
762
1252
  publicationObject,
763
- pullRequestPublicationCallbacks,
764
- pullRequestPublicationSources,
1253
+ pullRequestPublicationDefaults,
765
1254
  readPublicationState,
766
- readPullRequestFeedback,
767
- reconcilePullRequestSourceIssue,
1255
+ requirePublicationParams,
768
1256
  resolvePullRequestGitIdentity
769
1257
  };
770
1258
  //# sourceMappingURL=repository-change-publication.js.map