@leitwerk-dev/coding 0.4.0 → 0.4.2

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 (46) hide show
  1. package/README.md +67 -11
  2. package/dist/{chunk-Q24RPXOA.js → chunk-3WJRJ3Q7.js} +68 -7
  3. package/dist/chunk-3WJRJ3Q7.js.map +1 -0
  4. package/dist/chunk-B3PE6DPF.js +820 -0
  5. package/dist/chunk-B3PE6DPF.js.map +1 -0
  6. package/dist/chunk-E3DB4TIZ.js +49 -0
  7. package/dist/chunk-E3DB4TIZ.js.map +1 -0
  8. package/dist/{chunk-BI45R2FH.js → chunk-QD6FI4HR.js} +1 -1
  9. package/dist/chunk-QD6FI4HR.js.map +1 -0
  10. package/dist/finalization-git-internal.d.ts +6 -0
  11. package/dist/finalization-git-internal.d.ts.map +1 -1
  12. package/dist/finalization-git.js +2 -1
  13. package/dist/index.js +3 -2
  14. package/dist/index.js.map +1 -1
  15. package/dist/pull-request-publication-internal.d.ts +8 -0
  16. package/dist/pull-request-publication-internal.d.ts.map +1 -1
  17. package/dist/repository-change-process.d.ts.map +1 -1
  18. package/dist/repository-change-publication.d.ts +16 -3
  19. package/dist/repository-change-publication.d.ts.map +1 -1
  20. package/dist/repository-change-publication.js +283 -69
  21. package/dist/repository-change-publication.js.map +1 -1
  22. package/dist/repository-publication-receipt.d.ts +23 -0
  23. package/dist/repository-publication-receipt.d.ts.map +1 -0
  24. package/dist/repository-rebase/git.d.ts +8 -0
  25. package/dist/repository-rebase/git.d.ts.map +1 -1
  26. package/dist/repository-reconciliation.d.ts +47 -0
  27. package/dist/repository-reconciliation.d.ts.map +1 -0
  28. package/dist/repository-record.d.ts +6 -0
  29. package/dist/repository-record.d.ts.map +1 -0
  30. package/dist/turns/implement.d.ts +1 -1
  31. package/dist/turns/implement.d.ts.map +1 -1
  32. package/dist/turns/implement.js +1 -1
  33. package/package.json +5 -5
  34. package/src/finalization-git-internal.ts +75 -6
  35. package/src/pull-request-publication-internal.ts +3 -2
  36. package/src/repository-change-process.ts +19 -2
  37. package/src/repository-change-publication.ts +243 -57
  38. package/src/repository-publication-receipt.ts +71 -0
  39. package/src/repository-rebase/git.ts +108 -29
  40. package/src/repository-reconciliation.ts +600 -0
  41. package/src/repository-record.ts +14 -0
  42. package/src/turns/implement.ts +4 -1
  43. package/dist/chunk-BI45R2FH.js.map +0 -1
  44. package/dist/chunk-OM2AMDTJ.js +0 -347
  45. package/dist/chunk-OM2AMDTJ.js.map +0 -1
  46. package/dist/chunk-Q24RPXOA.js.map +0 -1
@@ -1,14 +1,29 @@
1
1
  import {
2
+ RemoteBranchChangedError,
2
3
  commitAndPushWorkBranch,
3
4
  repositoryHasChanges
4
- } from "./chunk-Q24RPXOA.js";
5
+ } from "./chunk-3WJRJ3Q7.js";
5
6
  import {
6
- createRepositoryChangeProcess
7
- } from "./chunk-OM2AMDTJ.js";
7
+ assertReconciliationTargetSafe,
8
+ createRepositoryChangeProcess,
9
+ reconcilePublicationRepository,
10
+ reconciliationPrompt,
11
+ recordRepositoryPublication,
12
+ repositoryWorktreeIsDirty,
13
+ retainConcurrentRebase
14
+ } from "./chunk-B3PE6DPF.js";
8
15
  import "./chunk-DNG7D77K.js";
9
16
  import "./chunk-ABQH2WZT.js";
10
- import "./chunk-BI45R2FH.js";
17
+ import "./chunk-QD6FI4HR.js";
11
18
  import "./chunk-SKGB4CZS.js";
19
+ import {
20
+ pushWasRejected,
21
+ readPublicationReceipt,
22
+ readRepositoryBinding,
23
+ repositoryBindingMatches,
24
+ repositoryRecord,
25
+ savePublicationReceipt
26
+ } from "./chunk-E3DB4TIZ.js";
12
27
  import {
13
28
  conflictKey,
14
29
  validateConflict
@@ -27,7 +42,7 @@ import {
27
42
 
28
43
  // src/repository-rebase/git.ts
29
44
  import { execFileSync } from "child_process";
30
- import { existsSync, readFileSync, renameSync, writeFileSync } from "fs";
45
+ import { existsSync } from "fs";
31
46
  import { join } from "path";
32
47
  import { repositoryGitArgs, repositoryGitSubprocessEnv } from "@leitwerk-dev/process-sdk";
33
48
  import { resolveGitBinary } from "@leitwerk-dev/process-sdk/git-binary";
@@ -54,12 +69,6 @@ function requireRebaseHead(expected, local, remote) {
54
69
  if (remote !== expected || local !== expected)
55
70
  throw new Error("Tracked branch changed before repair");
56
71
  }
57
- function rebasePublicationDecision(originalHead, headSha, remoteHead2) {
58
- if (remoteHead2 === headSha) return "already_published";
59
- if (remoteHead2 !== originalHead)
60
- throw new Error("Concurrent remote change rejected by rebase lease");
61
- return "push";
62
- }
63
72
 
64
73
  // src/repository-rebase/git.ts
65
74
  function git(input, ...args) {
@@ -79,15 +88,7 @@ function area(input) {
79
88
  function active(gitDir) {
80
89
  return ["rebase-merge", "rebase-apply"].some((name) => existsSync(join(gitDir, name)));
81
90
  }
82
- function save(gitDir, record) {
83
- const path = join(gitDir, "leitwerk-rebase.json");
84
- writeFileSync(`${path}.tmp`, JSON.stringify(record), { mode: 384 });
85
- renameSync(`${path}.tmp`, path);
86
- }
87
- function read(gitDir) {
88
- const file = join(gitDir, "leitwerk-rebase.json");
89
- return existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : null;
90
- }
91
+ var recordFile = (gitDir) => repositoryRecord(gitDir, "rebase");
91
92
  function requireWorktree(input) {
92
93
  requireRebaseWorktree(input.workBranch, {
93
94
  branch: git(input, "branch", "--show-current"),
@@ -122,9 +123,12 @@ function verifyNoRepairNeeded(input, headSha, baseSha) {
122
123
  git(input, "merge-base", "--is-ancestor", baseSha, headSha);
123
124
  else git(input, "merge-tree", "--write-tree", headSha, baseSha);
124
125
  }
126
+ function hasPreparedRebase(input) {
127
+ return recordFile(area(input)).read()?.key === conflictKey(input.conflict);
128
+ }
125
129
  function prepareRebase(input) {
126
130
  const gitDir = area(input);
127
- const old = read(gitDir);
131
+ const old = recordFile(gitDir).read();
128
132
  requireTarget(input, old?.key === conflictKey(input.conflict) ? old : null);
129
133
  if (old?.key === conflictKey(input.conflict)) {
130
134
  verifyCurrentBase(input, old);
@@ -159,7 +163,7 @@ function prepareRebase(input) {
159
163
  baseBranch: input.conflict.baseBranch
160
164
  };
161
165
  git(input, "update-ref", "refs/leitwerk/rebase-original", record.originalHead);
162
- save(gitDir, record);
166
+ recordFile(gitDir).save(record);
163
167
  return record;
164
168
  }
165
169
  function startRebase(input) {
@@ -173,13 +177,17 @@ function startRebase(input) {
173
177
  try {
174
178
  verifyNoRepairNeeded(input, record.originalHead, record.baseSha);
175
179
  record.status = "clean";
176
- save(gitDir, record);
180
+ recordFile(gitDir).save(record);
177
181
  return record;
178
182
  } catch (error) {
179
183
  if (error.status !== 1) throw error;
180
184
  }
185
+ assertReconciliationTargetSafe(
186
+ { projectKey: input.projectKey, repoPath: input.path },
187
+ record.baseSha
188
+ );
181
189
  record.status = "rebasing";
182
- save(gitDir, record);
190
+ recordFile(gitDir).save(record);
183
191
  try {
184
192
  git(input, "rebase", "--rebase-merges", record.baseSha);
185
193
  } catch (error) {
@@ -189,7 +197,7 @@ function startRebase(input) {
189
197
  }
190
198
  function verifyRebase(input) {
191
199
  const gitDir = area(input);
192
- const record = read(gitDir);
200
+ const record = recordFile(gitDir).read();
193
201
  if (!record || record.key !== conflictKey(input.conflict))
194
202
  throw new Error("Missing matching rebase metadata");
195
203
  requireTarget(input, record);
@@ -211,24 +219,94 @@ function verifyRebase(input) {
211
219
  baseSha: record.baseSha
212
220
  };
213
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
+ };
214
231
  function publishRebase(input) {
215
232
  const result = verifyRebase(input);
233
+ assertReconciliationTargetSafe(
234
+ { projectKey: input.projectKey, repoPath: input.path },
235
+ result.baseSha
236
+ );
216
237
  const gitDir = area(input);
217
- const record = read(gitDir);
238
+ const record = recordFile(gitDir).read();
218
239
  if (!record) throw new Error("Missing matching rebase metadata");
219
240
  verifyCurrentBase(input, record);
220
241
  const remote = remoteHead(input);
221
- 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" });
222
256
  return result;
223
- git(
224
- input,
225
- "push",
226
- `--force-with-lease=refs/heads/${input.workBranch}:${result.originalHead}`,
227
- "origin",
228
- `${result.headSha}:refs/heads/${input.workBranch}`
229
- );
230
- if (remoteHead(input) !== result.headSha)
231
- 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);
232
310
  return result;
233
311
  }
234
312
 
@@ -583,6 +661,14 @@ function patchPublicationState(state, namespace, patch) {
583
661
  function applyPublicationEvidence(params, current, evidence, countFailure = true) {
584
662
  if (evidence.observationKey !== void 0)
585
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
+ };
586
672
  switch (evidence.kind) {
587
673
  case "feedback": {
588
674
  const { kind: _, ...batch } = evidence;
@@ -682,7 +768,7 @@ function createRepositoryChangePublication(adapter) {
682
768
  };
683
769
  };
684
770
  const patchRemote = (state, patch) => patchPublicationState(state, namespace(state), patch);
685
- async function commitWorkBranch(ctx, commitMessage) {
771
+ async function commitWorkBranch(ctx, commitMessage, expectedRemoteHead = remote(ctx.state).headSha) {
686
772
  const repo = ctx.repo.get("repo");
687
773
  const gitIdentity = await adapter.identity(ctx);
688
774
  if (adapter.maintenance)
@@ -692,7 +778,18 @@ function createRepositoryChangePublication(adapter) {
692
778
  projectKey: repo.key,
693
779
  workBranch: repo.workBranch,
694
780
  commitMessage,
695
- gitIdentity
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,
792
+ gitIdentity: await adapter.identity(ctx)
696
793
  });
697
794
  }
698
795
  const runRepository = async (ctx) => {
@@ -700,6 +797,26 @@ function createRepositoryChangePublication(adapter) {
700
797
  const update = (patch) => {
701
798
  current = { ...current, ...patch, delivery: { ...current.delivery, ...patch.delivery } };
702
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
+ };
703
820
  const result = (outcome2) => ({
704
821
  outcome: outcome2,
705
822
  params: { nextState: patchRemote(ctx.state, current) }
@@ -716,6 +833,19 @@ function createRepositoryChangePublication(adapter) {
716
833
  if (evidence.kind === "conflict") return result("conflict_ready");
717
834
  }
718
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
+ };
719
849
  if (current.delivery.terminalPullRequest) {
720
850
  ctx.reportProgress(deliveryProgress(current, adapter.label, "reconcile_terminal"));
721
851
  const pr = current.delivery.terminalPullRequest;
@@ -732,13 +862,28 @@ function createRepositoryChangePublication(adapter) {
732
862
  await adapter.unchanged?.(ctx);
733
863
  return result("completed");
734
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
+ }
735
873
  if (!current.headSha) {
736
874
  ctx.reportProgress(deliveryProgress(current, adapter.label, "publish_branch"));
737
- const published = await commitWorkBranch(
738
- ctx,
739
- ctx.state.finalization.commitMessages?.[ctx.repo.get("repo").key] ?? ctx.state.finalization.generatedCommitMessage ?? ""
740
- );
741
- 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);
742
887
  }
743
888
  if (!current.prNumber || !current.prUrl) {
744
889
  ctx.reportProgress(deliveryProgress(current, adapter.label, "open_pr"));
@@ -752,19 +897,46 @@ function createRepositoryChangePublication(adapter) {
752
897
  }
753
898
  if (current.delivery.adjustment) {
754
899
  const adjustment = current.delivery.adjustment;
755
- 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) {
756
904
  ctx.reportProgress(deliveryProgress(current, adapter.label, "publish_adjustment"));
757
905
  if (adapter.maintenance)
758
906
  await ctx.callIntegrationTool(adapter.maintenance.ownershipTool, {
759
907
  projectKey: ctx.repo.get("repo").key
760
908
  });
761
- const published = adjustment.origin === "rebase" ? publishRebase(rebaseInput(ctx)) : await commitWorkBranch(ctx, adapter.commitMessage(adjustment.origin));
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
+ }
762
933
  if (adjustment.origin === "rebase") {
763
934
  const head = await adapter.head(ctx, current);
764
935
  if (head !== published.headSha)
765
936
  throw new Error("Pull request head has not caught up with rebase publication");
766
937
  }
767
- update({ headSha: published.headSha, pipeline: null });
938
+ adjustmentPublished = published.headSha !== publicationLease;
939
+ acknowledgePublication(published.headSha, adjustmentPublished);
768
940
  }
769
941
  if (adjustment.origin === "rebase") await adapter.afterRebase(ctx, current);
770
942
  if (adjustment.origin === "feedback" && !adapter.maintenance) {
@@ -778,8 +950,8 @@ function createRepositoryChangePublication(adapter) {
778
950
  adjustment: null,
779
951
  ...adjustment.origin === "feedback" && adapter.maintenance ? {
780
952
  feedbackResult: {
781
- published: adjustment.publishRequired,
782
- summary: "Review adjustment published"
953
+ published: adjustmentPublished,
954
+ summary: adjustmentPublished ? "Review adjustment published" : adjustment.summary ?? "No repository change was required"
783
955
  }
784
956
  } : {}
785
957
  }
@@ -799,7 +971,7 @@ function createRepositoryChangePublication(adapter) {
799
971
  return states.some((state2) => {
800
972
  const current = remote(state2);
801
973
  if (adapter.maintenance)
802
- return !current.stopped && !current.noChanges && !current.delivery.terminalPullRequest && (current.delivery.stage !== "awaiting" || !!(current.delivery.adjustment && (current.delivery.adjustment.publishRequired || current.delivery.adjustment.origin === "rebase")));
974
+ return !current.stopped && !current.noChanges && !current.delivery.terminalPullRequest && (current.delivery.stage !== "awaiting" || !!current.delivery.adjustment);
803
975
  return current.delivery.stage !== "awaiting" || !!current.pendingEvidence || !!current.delivery.adjustment || current.feedbackIds.length > 0 || !!current.delivery.terminalPullRequest;
804
976
  });
805
977
  }).integrationTools(...adapter.tools.delivery).run(async (ctx) => {
@@ -863,7 +1035,7 @@ function createRepositoryChangePublication(adapter) {
863
1035
  "feedback_ready",
864
1036
  (o) => outcome(o, "Pull request feedback is acknowledged and ready for revision").to(ids.feedback)
865
1037
  );
866
- for (const [name, target] of adapter.maintenance ? [] : [
1038
+ for (const [name, target] of [
867
1039
  ["ci_ready", ids.ciRepair],
868
1040
  ["conflict_ready", ids.feedback],
869
1041
  ["operator_action", ids.operator]
@@ -928,23 +1100,64 @@ function createRepositoryChangePublication(adapter) {
928
1100
  function revisionPrompt(kind) {
929
1101
  return (ctx) => {
930
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"}`;
931
1111
  if (repairReason(ctx.state, kind) === "rebase")
932
1112
  return `${rebasePrompt} Evidence: ${JSON.stringify(current.conflict)}. Call changes_ready or no_changes when verified complete, cannot_repair when blocked.`;
933
- return `${adapter.repositories ? `Repository: ${activeKey(ctx.state)}. Apply changes only to this checkout. ` : ""}${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}`;
934
1116
  };
935
1117
  }
936
1118
  function revisionTurn(id, kind) {
937
1119
  const turn = flow.llm(id).description(kind === "feedback" ? "Address Feedback" : "Fix CI").waitFor(({ state }) => {
938
1120
  const current = remote(state);
939
- return !current.stopped && !current.delivery.terminalPullRequest && (kind === "feedback" ? current.feedbackIds.length > 0 || !!current.conflict : current.repairReason === "ci" && current.pipeline !== null);
1121
+ return !current.stopped && !current.delivery.terminalPullRequest && (kind === "feedback" ? current.feedbackIds.length > 0 || !!current.conflict || !!current.reconciliationRequired : current.repairReason === "ci" && current.pipeline !== null);
940
1122
  }).executionPurpose(codingPurposes.implementation).tools("read", "bash", "edit", "write").resolveIntegrationTools(
941
- (_params, state) => repairReason(state, kind) === "rebase" ? [] : adapter.tools[kind]
942
- ).prepare(
943
- (ctx) => repairReason(ctx.state, kind) === "rebase" ? startRebase(rebaseInput(ctx)) : {}
944
- ).freshPrimary().prompt(revisionPrompt(kind));
945
- for (const [name, description, publishRequired] of [
946
- ["changes_ready", "Repository changes are ready to publish", true],
947
- ["no_changes", "No repository change is required", false]
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"]
948
1161
  ]) {
949
1162
  turn.outcomeTool(
950
1163
  name,
@@ -952,15 +1165,15 @@ function createRepositoryChangePublication(adapter) {
952
1165
  ({ ctx, event }) => patchRemote(ctx.state, {
953
1166
  repairPending: false,
954
1167
  delivery: {
955
- adjustment: { origin: repairReason(ctx.state, kind), publishRequired },
956
- ...!publishRequired && adapter.maintenance && repairReason(ctx.state, kind) !== "rebase" ? {
957
- feedbackResult: {
958
- published: false,
959
- summary: String(
960
- event.params.resultSummary ?? "No repository change was required"
961
- )
962
- }
963
- } : {}
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
+ }
964
1177
  }
965
1178
  })
966
1179
  )
@@ -1001,7 +1214,8 @@ function createRepositoryChangePublication(adapter) {
1001
1214
  label: "Retry repair",
1002
1215
  acceptanceState: "accepted",
1003
1216
  branches: { feedback: { to: ids.feedback }, ci: { to: ids.ciRepair } },
1004
- 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"
1005
1219
  },
1006
1220
  resume_waiting: {
1007
1221
  label: "Resume waiting",