@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
@@ -5,33 +5,56 @@ import { parseStructuralProcessState } from "@leitwerk-dev/process-sdk";
5
5
  export interface RepositoryChangeFinalizationState {
6
6
  /** @public */
7
7
  generatedCommitMessage: string | null;
8
+ /** Messages keyed by process project key. @public */
9
+ commitMessages?: Record<string, string>;
8
10
  }
9
11
 
10
12
  /** @public */
11
13
  export interface RepositoryChangeState extends StructuralProcessState {
12
14
  /** @public */
13
15
  finalization: RepositoryChangeFinalizationState;
16
+ /** Completed routing decisions survive recovery. @public */
17
+ routing?: {
18
+ /** @public */
19
+ plan?: {
20
+ /** @internal */
21
+ planRevision: number;
22
+ /** @internal */ skip: boolean;
23
+ /** @internal */ reason: string;
24
+ };
25
+
26
+ /** @public */
27
+ simplification?: {
28
+ /** @internal */
29
+ skip: boolean;
30
+ /** @internal */ reason: string;
31
+ };
32
+ };
14
33
  /** Namespaced state owned by a caller-supplied publication workflow. */
34
+
15
35
  /** @public */
16
36
  extensionState?: Record<string, unknown>;
17
37
  }
18
38
 
19
- /** @internal */
20
- export function createEmptyRepositoryChangeFinalizationState(): RepositoryChangeFinalizationState {
21
- return { generatedCommitMessage: null };
22
- }
23
-
24
- function stringOrNull(value: unknown): string | null {
25
- return typeof value === "string" ? value : null;
26
- }
27
-
28
39
  function toRecord(value: unknown): Record<string, unknown> {
29
40
  return typeof value === "object" && value !== null ? (value as Record<string, unknown>) : {};
30
41
  }
31
42
 
32
43
  function parseFinalizationState(value: unknown): RepositoryChangeFinalizationState {
33
44
  const record = toRecord(value);
34
- return { generatedCommitMessage: stringOrNull(record.generatedCommitMessage) };
45
+ return {
46
+ generatedCommitMessage:
47
+ typeof record.generatedCommitMessage === "string" ? record.generatedCommitMessage : null,
48
+ ...(record.commitMessages
49
+ ? {
50
+ commitMessages: Object.fromEntries(
51
+ Object.entries(toRecord(record.commitMessages)).filter(
52
+ (entry): entry is [string, string] => typeof entry[1] === "string",
53
+ ),
54
+ ),
55
+ }
56
+ : {}),
57
+ };
35
58
  }
36
59
 
37
60
  /** @internal */
@@ -42,19 +65,10 @@ export const repositoryChangeStateCodec: Codec<RepositoryChangeState> = {
42
65
  ...parseStructuralProcessState(record),
43
66
  finalization: parseFinalizationState(record.finalization),
44
67
  extensionState: toRecord(record.extensionState),
68
+ routing: toRecord(record.routing) as RepositoryChangeState["routing"],
45
69
  };
46
70
  },
47
71
  serialize(value) {
48
72
  return value;
49
73
  },
50
74
  };
51
-
52
- /** @internal */
53
- export function clearReviewRefs(
54
- semanticEntryRefs: RepositoryChangeState["semanticEntryRefs"],
55
- ): RepositoryChangeState["semanticEntryRefs"] {
56
- return {
57
- ...semanticEntryRefs,
58
- review: null,
59
- };
60
- }
@@ -9,31 +9,23 @@ import {
9
9
  SafeLaunchPreparationError,
10
10
  } from "@leitwerk-dev/process-sdk";
11
11
  import { buildAutoWorkBranchFromSeed } from "./auto-work-branch.js";
12
+ import {
13
+ type RepositoryChangeLaunchParams,
14
+ type RepositoryIssueOriginParams,
15
+ type RepositoryUiOriginParams,
16
+ repositoryChangeOptionFields,
17
+ repositoryChangeOptions,
18
+ repositoryChangeWorkflow,
19
+ } from "./repository-change-launch-internal.js";
12
20
 
13
- /** Recheck provider-owned repository visibility before launch. @internal */
14
- export function repositoryVisibilityCheck(
15
- provider: string,
16
- isVisible: () => Promise<boolean>,
17
- ): LaunchPreparationCheck {
18
- return {
19
- id: "repository_visibility",
20
- label: "Check repository visibility",
21
- async run({ signal }) {
22
- signal.throwIfAborted();
23
- const visible = await isVisible();
24
- signal.throwIfAborted();
25
- if (!visible)
26
- throw new SafeLaunchPreparationError(
27
- "Repository is not visible",
28
- `Grant the selected ${provider} profile access to the repository, then try again.`,
29
- );
30
- },
31
- };
32
- }
33
-
34
- /** Shared UI mechanics; providers retain credentials, preparation and launch metadata. @internal */
35
- export function createRepositoryChangeUiLauncher<
36
- P,
21
+ /** Shared launch mechanics; providers retain credentials, preparation and launch metadata. @internal */
22
+ export function createRepositoryChangeLauncher<
23
+ P extends RepositoryChangeLaunchParams<{
24
+ /** @internal */ owner: string;
25
+ /** @internal */ repo: string;
26
+ }> &
27
+ (RepositoryIssueOriginParams | RepositoryUiOriginParams),
28
+ D,
37
29
  R extends {
38
30
  /** @internal */
39
31
  full_name: string;
@@ -54,15 +46,22 @@ export function createRepositoryChangeUiLauncher<
54
46
  /** @internal */
55
47
  providerId: string;
56
48
  /** @internal */
57
- assertConfigured(): void;
58
- /** @internal */
59
- profiles(): readonly string[];
60
- /** @internal */
61
- repositories(profile: string): Promise<readonly R[]>;
49
+ integration(dependencies: D): {
50
+ /** @internal */ profiles?(): readonly string[];
51
+ /** @internal */ client(profile: string): {
52
+ /** @internal */ listRepositories(): Promise<readonly R[]>;
53
+ /** @internal */ resolveGitIdentity(profile: string): Promise<I>;
54
+ /** @internal */ getIssue(
55
+ owner: string,
56
+ repo: string,
57
+ number: number,
58
+ ): Promise<Pick<RepositoryIssue, "html_url" | "labels">>;
59
+ };
60
+ };
62
61
  /** @internal */
63
- resolveProfiles(profile: string): B;
62
+ profile(params: P): string;
64
63
  /** @internal */
65
- resolveGitIdentity(profile: string): Promise<I>;
64
+ resolveProfiles(profile: string, dependencies: D): B;
66
65
  /** @internal */
67
66
  params(
68
67
  repository: R,
@@ -76,20 +75,64 @@ export function createRepositoryChangeUiLauncher<
76
75
  },
77
76
  ): P;
78
77
  /** @internal */
79
- launchConfig(params: P, title: string, identity: I): ProcessLaunchConfig<P>;
78
+ launchConfig(
79
+ params: P,
80
+ title: string,
81
+ identity: I,
82
+ repository: NoInfer<R>,
83
+ ): ProcessLaunchConfig<P>;
80
84
  /** @internal */
81
- preparationChecks: NonNullable<ProcessLauncherDefinition<P>["ui"]>["preparationChecks"];
82
- }): ProcessLauncherDefinition<P> & {
83
- /** Resolve issue launches using the same provider wiring as UI launches. @internal */
84
- resolveIssueLaunchConfig(event: {
85
- /** @internal */ profile: string;
86
- /** @internal */ repository: R;
87
- /** @internal */ issue: Pick<RepositoryIssue, "number" | "title" | "body" | "html_url">;
88
- /** @internal */ labels: RepositoryIssueWatcherConfig["labels"];
89
- }): Promise<ProcessLaunchConfig<P>>;
90
- } {
85
+ preparationChecks(params: P, dependencies: () => D): readonly LaunchPreparationCheck<P>[];
86
+ }) {
91
87
  const { provider, providerId } = options;
92
88
  const profileField = `${providerId}Profile`;
89
+ let dependencies: D | null = null;
90
+ function requireDependencies(): D {
91
+ if (!dependencies) throw new Error(`${provider} repository launcher is not configured`);
92
+ return dependencies;
93
+ }
94
+ const integration = () => options.integration(requireDependencies());
95
+ const profiles = () => integration().profiles?.() ?? [];
96
+ async function repositories(profile: string): Promise<readonly R[]> {
97
+ return profile && profiles().includes(profile)
98
+ ? integration().client(profile).listRepositories()
99
+ : [];
100
+ }
101
+ /** @internal */
102
+ function resolveProfiles(profile: string) {
103
+ if (!profiles().includes(profile)) throw new Error(`${provider} profile is not available`);
104
+ return options.resolveProfiles(profile, requireDependencies());
105
+ }
106
+ /** @internal */
107
+ async function resolveGitIdentity(profile: string): Promise<I> {
108
+ if (!profile) throw new Error(`A ${provider} profile is required to resolve Git identity`);
109
+ return integration().client(profile).resolveGitIdentity(profile);
110
+ }
111
+ /** @internal */
112
+ function preparationChecks(
113
+ _input: unknown,
114
+ { params }: ProcessLaunchConfig<P>,
115
+ ): LaunchPreparationCheck<P>[] {
116
+ return [
117
+ {
118
+ id: "repository_visibility",
119
+ label: "Check repository visibility",
120
+ async run({ signal }) {
121
+ signal.throwIfAborted();
122
+ const visible = (await repositories(options.profile(params))).some(
123
+ (candidate) => candidate.full_name === `${params.owner}/${params.repo}`,
124
+ );
125
+ signal.throwIfAborted();
126
+ if (!visible)
127
+ throw new SafeLaunchPreparationError(
128
+ "Repository is not visible",
129
+ `Grant the selected ${provider} profile access to the repository, then try again.`,
130
+ );
131
+ },
132
+ },
133
+ ...options.preparationChecks(params, requireDependencies),
134
+ ];
135
+ }
93
136
  function validationError(
94
137
  fieldId: string,
95
138
  message: string,
@@ -97,12 +140,20 @@ export function createRepositoryChangeUiLauncher<
97
140
  ): LauncherValidationError {
98
141
  return { code, fieldId, message };
99
142
  }
100
- return {
143
+ const launcher: ProcessLauncherDefinition<P> & {
144
+ /** @internal */
145
+ resolveIssueLaunchConfig(event: {
146
+ /** @internal */ profile: string;
147
+ /** @internal */ repository: R;
148
+ /** @internal */ issue: Pick<RepositoryIssue, "number" | "title" | "body" | "html_url">;
149
+ /** @internal */ labels: RepositoryIssueWatcherConfig["labels"];
150
+ }): Promise<ProcessLaunchConfig<P>>;
151
+ } = {
101
152
  async resolveIssueLaunchConfig({ profile, repository, issue, labels }) {
102
153
  const title = issue.title.trim();
103
154
  const body = issue.body?.trim() ?? "";
104
- const binding = options.resolveProfiles(profile);
105
- const identity = await options.resolveGitIdentity(profile);
155
+ const binding = resolveProfiles(profile);
156
+ const identity = await resolveGitIdentity(profile);
106
157
  return options.launchConfig(
107
158
  {
108
159
  ...options.params(repository, {
@@ -119,6 +170,7 @@ export function createRepositoryChangeUiLauncher<
119
170
  },
120
171
  title,
121
172
  identity,
173
+ repository,
122
174
  );
123
175
  },
124
176
  id: options.id,
@@ -134,6 +186,7 @@ export function createRepositoryChangeUiLauncher<
134
186
  id: `${providerId}_repo_change_form`,
135
187
  title: `${provider} Repo Change`,
136
188
  fields: [
189
+ ...repositoryChangeOptionFields,
137
190
  {
138
191
  id: profileField,
139
192
  label: `${provider} profile`,
@@ -159,22 +212,28 @@ export function createRepositoryChangeUiLauncher<
159
212
  submitLabel: "Start change",
160
213
  },
161
214
  resolveDefaults() {
162
- return { [profileField]: options.profiles()[0] ?? "", repository: "", prompt: "" };
215
+ return {
216
+ [profileField]: profiles()[0] ?? "",
217
+ repository: "",
218
+ prompt: "",
219
+ ...repositoryChangeOptions({}),
220
+ };
163
221
  },
164
222
  async resolveOptions(input) {
165
223
  const profile = trimString(input[profileField]);
166
224
  return {
167
- [profileField]: options.profiles().map((value) => ({ value, label: value })),
168
- repository: (await options.repositories(profile)).map((repository) => ({
225
+ [profileField]: profiles().map((value) => ({ value, label: value })),
226
+ repository: (await repositories(profile)).map((repository) => ({
169
227
  value: repository.full_name,
170
228
  label: repository.full_name,
171
229
  description: repository.html_url,
172
230
  })),
173
231
  };
174
232
  },
175
- preparationChecks: options.preparationChecks,
233
+ preparationChecks,
176
234
  resolveRelaunchInput(input) {
177
235
  return {
236
+ ...repositoryChangeOptions(input),
178
237
  [profileField]: trimString(input[profileField]),
179
238
  repository: trimString(input.repository),
180
239
  prompt: trimString(input.prompt),
@@ -189,16 +248,16 @@ export function createRepositoryChangeUiLauncher<
189
248
  ok: false as const,
190
249
  errors: [validationError(fieldId, message, "custom_rule")],
191
250
  });
192
- options.assertConfigured();
251
+ requireDependencies();
193
252
  if (!profile) errors.push(validationError(profileField, `${provider} profile is required`));
194
- else if (!options.profiles().includes(profile))
253
+ else if (!profiles().includes(profile))
195
254
  errors.push(
196
255
  validationError(profileField, `${provider} profile is not available`, "custom_rule"),
197
256
  );
198
257
  if (!repositoryName) errors.push(validationError("repository", "Repository is required"));
199
258
  if (!prompt) errors.push(validationError("prompt", "Requested change is required"));
200
259
  if (errors.length > 0) return { ok: false, errors };
201
- const repository = (await options.repositories(profile)).find(
260
+ const repository = (await repositories(profile)).find(
202
261
  (candidate) => candidate.full_name === repositoryName,
203
262
  );
204
263
  if (!repository)
@@ -208,18 +267,42 @@ export function createRepositoryChangeUiLauncher<
208
267
  );
209
268
  let binding: B;
210
269
  try {
211
- binding = options.resolveProfiles(profile);
270
+ binding = resolveProfiles(profile);
212
271
  } catch (error) {
213
272
  return invalid(profileField, (error as Error).message);
214
273
  }
215
- const identity = await options.resolveGitIdentity(profile);
274
+ const identity = await resolveGitIdentity(profile);
216
275
  const workBranch = buildAutoWorkBranchFromSeed(
217
276
  prompt,
218
277
  `${repository.ssh_url}:${repository.default_branch}`,
219
278
  );
220
- const params = options.params(repository, { ...binding, profile, prompt, workBranch });
221
- return { ok: true, launchConfig: options.launchConfig(params, prompt, identity) };
279
+ const params = {
280
+ ...options.params(repository, { ...binding, profile, prompt, workBranch }),
281
+ ...repositoryChangeOptions(input),
282
+ };
283
+ return {
284
+ ok: true,
285
+ launchConfig: options.launchConfig(params, prompt, identity, repository),
286
+ };
222
287
  },
223
288
  },
224
289
  };
290
+ return {
291
+ /** @internal */ configure(value: D | null) {
292
+ dependencies = value;
293
+ },
294
+ /** @internal */ preparationChecks,
295
+ /** @internal */ resolveProfiles,
296
+ /** @internal */ resolveGitIdentity,
297
+ /** @internal */ launcher,
298
+ /** @internal */ workflow: repositoryChangeWorkflow(async (params: P) => {
299
+ if (params.origin !== "issue") throw new Error(`Missing ${provider} source issue`);
300
+ const issue = await integration()
301
+ .client(options.profile(params))
302
+ .getIssue(params.owner, params.repo, params.issueNumber);
303
+ if (issue.html_url !== params.issueUrl)
304
+ throw new Error(`${provider} source issue installation changed`);
305
+ return issue.labels.map((label) => label.name);
306
+ }),
307
+ };
225
308
  }
@@ -0,0 +1,71 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { repositoryRecord } from "./repository-record.js";
4
+
5
+ /** @internal */
6
+ export interface RepositoryBinding {
7
+ branch: string;
8
+ origin: string;
9
+ pushOrigin: string;
10
+ }
11
+
12
+ /** @internal */
13
+ export function readRepositoryBinding(
14
+ git: (...args: string[]) => string,
15
+ branch: string,
16
+ ): RepositoryBinding {
17
+ return {
18
+ branch,
19
+ origin: git("remote", "get-url", "origin"),
20
+ pushOrigin: git("remote", "get-url", "--push", "--all", "origin"),
21
+ };
22
+ }
23
+
24
+ /** @internal */
25
+ export function repositoryBindingMatches(
26
+ record: RepositoryBinding | null,
27
+ binding: RepositoryBinding,
28
+ ): boolean {
29
+ return (
30
+ !record ||
31
+ (record.branch === binding.branch &&
32
+ record.origin === binding.origin &&
33
+ record.pushOrigin === binding.pushOrigin)
34
+ );
35
+ }
36
+
37
+ /** A local write-ahead receipt, not a replacement for the server-owned process state. @internal */
38
+ export interface RepositoryPublicationReceipt extends RepositoryBinding {
39
+ expectedHead: string | null;
40
+ candidate: string;
41
+ status: "attempting" | "accepted" | "rejected";
42
+ }
43
+
44
+ /** @internal */
45
+ export function readPublicationReceipt(gitDirectory: string): RepositoryPublicationReceipt | null {
46
+ const file = join(gitDirectory, "leitwerk-publication.json");
47
+ if (!existsSync(file)) return null;
48
+ const value = JSON.parse(readFileSync(file, "utf8"));
49
+ if (
50
+ !value ||
51
+ typeof value.branch !== "string" ||
52
+ typeof value.origin !== "string" ||
53
+ typeof value.pushOrigin !== "string" ||
54
+ !["attempting", "accepted", "rejected"].includes(value.status) ||
55
+ !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(value.candidate) ||
56
+ !(value.expectedHead === null || /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(value.expectedHead))
57
+ )
58
+ throw new Error("Invalid repository publication receipt; local work was retained");
59
+ return value;
60
+ }
61
+
62
+ /** Persist intent before sending and acceptance before checking for subsequent remote movement. @internal */
63
+ export const savePublicationReceipt = (
64
+ gitDirectory: string,
65
+ receipt: RepositoryPublicationReceipt,
66
+ ) => repositoryRecord(gitDirectory, "publication").save(receipt);
67
+
68
+ /** Porcelain rejection is proof of no write; transport failures are not. @internal */
69
+ export function pushWasRejected(porcelain: string): boolean {
70
+ return porcelain.split("\n").some((line) => /^!\t[^\t]+\t\[(?:remote )?rejected\]/.test(line));
71
+ }
@@ -1,13 +1,22 @@
1
1
  import { execFileSync } from "node:child_process";
2
- import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
+ import { existsSync } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  import { repositoryGitArgs, repositoryGitSubprocessEnv } from "@leitwerk-dev/process-sdk";
5
5
  import { resolveGitBinary } from "@leitwerk-dev/process-sdk/git-binary";
6
+ import {
7
+ pushWasRejected,
8
+ type RepositoryPublicationReceipt,
9
+ readPublicationReceipt,
10
+ readRepositoryBinding,
11
+ repositoryBindingMatches,
12
+ savePublicationReceipt,
13
+ } from "../repository-publication-receipt.js";
14
+ import { assertReconciliationTargetSafe } from "../repository-reconciliation.js";
15
+ import { repositoryRecord } from "../repository-record.js";
6
16
 
7
17
  import { type ConflictEvidence, conflictKey } from "./index.js";
8
18
  import {
9
19
  type RebaseRecord,
10
- rebasePublicationDecision,
11
20
  requireRebaseHead,
12
21
  requireRebaseOrigin,
13
22
  requireRebaseTarget,
@@ -42,15 +51,7 @@ function area(input: RebaseInput): string {
42
51
  function active(gitDir: string): boolean {
43
52
  return ["rebase-merge", "rebase-apply"].some((name) => existsSync(join(gitDir, name)));
44
53
  }
45
- function save(gitDir: string, record: RebaseRecord): void {
46
- const path = join(gitDir, "leitwerk-rebase.json");
47
- writeFileSync(`${path}.tmp`, JSON.stringify(record), { mode: 0o600 });
48
- renameSync(`${path}.tmp`, path);
49
- }
50
- function read(gitDir: string): RebaseRecord | null {
51
- const file = join(gitDir, "leitwerk-rebase.json");
52
- return existsSync(file) ? (JSON.parse(readFileSync(file, "utf8")) as RebaseRecord) : null;
53
- }
54
+ const recordFile = (gitDir: string) => repositoryRecord<RebaseRecord>(gitDir, "rebase");
54
55
  function requireWorktree(input: RebaseInput): void {
55
56
  requireRebaseWorktree(input.workBranch, {
56
57
  branch: git(input, "branch", "--show-current"),
@@ -92,10 +93,15 @@ function verifyNoRepairNeeded(input: RebaseInput, headSha: string, baseSha: stri
92
93
  else git(input, "merge-tree", "--write-tree", headSha, baseSha);
93
94
  }
94
95
 
96
+ /** @internal */
97
+ export function hasPreparedRebase(input: RebaseInput): boolean {
98
+ return recordFile(area(input)).read()?.key === conflictKey(input.conflict);
99
+ }
100
+
95
101
  /** Persist the lease before changing HEAD; a retry resumes Git's own rebase state. @internal */
96
102
  export function prepareRebase(input: RebaseInput): RebaseRecord {
97
103
  const gitDir = area(input);
98
- const old = read(gitDir);
104
+ const old = recordFile(gitDir).read();
99
105
  requireTarget(input, old?.key === conflictKey(input.conflict) ? old : null);
100
106
  if (old?.key === conflictKey(input.conflict)) {
101
107
  verifyCurrentBase(input, old);
@@ -131,7 +137,7 @@ export function prepareRebase(input: RebaseInput): RebaseRecord {
131
137
  baseBranch: input.conflict.baseBranch,
132
138
  };
133
139
  git(input, "update-ref", "refs/leitwerk/rebase-original", record.originalHead);
134
- save(gitDir, record);
140
+ recordFile(gitDir).save(record);
135
141
  return record;
136
142
  }
137
143
  /** @internal */
@@ -146,13 +152,17 @@ export function startRebase(input: RebaseInput): RebaseRecord {
146
152
  try {
147
153
  verifyNoRepairNeeded(input, record.originalHead, record.baseSha);
148
154
  record.status = "clean";
149
- save(gitDir, record);
155
+ recordFile(gitDir).save(record);
150
156
  return record;
151
157
  } catch (error) {
152
158
  if ((error as { status?: number }).status !== 1) throw error;
153
159
  }
160
+ assertReconciliationTargetSafe(
161
+ { projectKey: input.projectKey, repoPath: input.path },
162
+ record.baseSha,
163
+ );
154
164
  record.status = "rebasing";
155
- save(gitDir, record);
165
+ recordFile(gitDir).save(record);
156
166
  try {
157
167
  git(input, "rebase", "--rebase-merges", record.baseSha);
158
168
  } catch (error) {
@@ -172,7 +182,7 @@ export function verifyRebase(input: RebaseInput): {
172
182
  baseSha: string;
173
183
  } {
174
184
  const gitDir = area(input);
175
- const record = read(gitDir);
185
+ const record = recordFile(gitDir).read();
176
186
  if (!record || record.key !== conflictKey(input.conflict))
177
187
  throw new Error("Missing matching rebase metadata");
178
188
  requireTarget(input, record);
@@ -194,26 +204,95 @@ export function verifyRebase(input: RebaseInput): {
194
204
  baseSha: record.baseSha,
195
205
  };
196
206
  }
207
+ /** @internal */
208
+ export class ConcurrentRebaseSourceError extends Error {
209
+ constructor(
210
+ readonly repair: ReturnType<typeof verifyRebase>,
211
+ readonly published = false,
212
+ ) {
213
+ super("Concurrent remote change rejected by rebase lease; local repair was retained");
214
+ }
215
+ }
216
+
197
217
  /** @internal */
198
218
  export function publishRebase(input: RebaseInput): ReturnType<typeof verifyRebase> {
199
219
  const result = verifyRebase(input);
220
+ assertReconciliationTargetSafe(
221
+ { projectKey: input.projectKey, repoPath: input.path },
222
+ result.baseSha,
223
+ );
200
224
  const gitDir = area(input);
201
- const record = read(gitDir);
225
+ const record = recordFile(gitDir).read();
202
226
  if (!record) throw new Error("Missing matching rebase metadata");
203
227
  verifyCurrentBase(input, record);
204
228
  const remote = remoteHead(input);
205
- if (
206
- rebasePublicationDecision(result.originalHead, result.headSha, remote) === "already_published"
207
- )
229
+ const binding = readRepositoryBinding((...args) => git(input, ...args), input.workBranch);
230
+ if (binding.origin !== binding.pushOrigin)
231
+ throw new Error("Fetch and push endpoints must match for publication");
232
+ const previous = readPublicationReceipt(gitDir);
233
+ if (!repositoryBindingMatches(previous, binding))
234
+ throw new Error("Repository publication receipt binding changed");
235
+ const receipt: RepositoryPublicationReceipt = {
236
+ ...binding,
237
+ expectedHead: result.originalHead,
238
+ candidate: result.headSha,
239
+ status: "attempting",
240
+ };
241
+ if (remote === result.headSha) {
242
+ savePublicationReceipt(gitDir, { ...receipt, status: "accepted" });
208
243
  return result;
209
- git(
210
- input,
211
- "push",
212
- `--force-with-lease=refs/heads/${input.workBranch}:${result.originalHead}`,
213
- "origin",
214
- `${result.headSha}:refs/heads/${input.workBranch}`,
215
- );
216
- if (remoteHead(input) !== result.headSha)
217
- throw new Error("Rebase publication could not be verified");
244
+ }
245
+ if (previous?.candidate === result.headSha && previous.status === "accepted")
246
+ throw new ConcurrentRebaseSourceError(result, true);
247
+ if (previous?.status === "attempting") {
248
+ git(
249
+ input,
250
+ "fetch",
251
+ "--no-tags",
252
+ "origin",
253
+ `+refs/heads/${input.workBranch}:refs/leitwerk/rebase-publication-proof`,
254
+ );
255
+ try {
256
+ git(
257
+ input,
258
+ "merge-base",
259
+ "--is-ancestor",
260
+ previous.candidate,
261
+ "refs/leitwerk/rebase-publication-proof",
262
+ );
263
+ } catch {
264
+ throw new Error(
265
+ "Prior target publication outcome is uncertain; local repair was retained for operator reconciliation",
266
+ );
267
+ }
268
+ savePublicationReceipt(gitDir, { ...previous, status: "accepted" });
269
+ throw new ConcurrentRebaseSourceError(result, previous.candidate === result.headSha);
270
+ }
271
+ if (remote !== result.originalHead) throw new ConcurrentRebaseSourceError(result);
272
+ savePublicationReceipt(gitDir, receipt);
273
+ try {
274
+ git(
275
+ input,
276
+ "push",
277
+ "--porcelain",
278
+ "--no-follow-tags",
279
+ "--recurse-submodules=no",
280
+ `--force-with-lease=refs/heads/${input.workBranch}:${result.originalHead}`,
281
+ "origin",
282
+ `${result.headSha}:refs/heads/${input.workBranch}`,
283
+ );
284
+ } catch (error) {
285
+ const rejected = pushWasRejected((error as { stdout?: Buffer }).stdout?.toString() ?? "");
286
+ if (rejected) savePublicationReceipt(gitDir, { ...receipt, status: "rejected" });
287
+ const latest = remoteHead(input);
288
+ if (latest === result.headSha) {
289
+ savePublicationReceipt(gitDir, { ...receipt, status: "accepted" });
290
+ return result;
291
+ }
292
+ if (rejected && latest !== result.originalHead) throw new ConcurrentRebaseSourceError(result);
293
+ throw error;
294
+ }
295
+ savePublicationReceipt(gitDir, { ...receipt, status: "accepted" });
296
+ if (remoteHead(input) !== result.headSha) throw new ConcurrentRebaseSourceError(result, true);
218
297
  return result;
219
298
  }