@leitwerk-dev/coding 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/README.md +120 -2
  2. package/dist/auto-work-branch.js +3 -24
  3. package/dist/auto-work-branch.js.map +1 -1
  4. package/dist/chunk-6E5VQPC4.js +28 -0
  5. package/dist/chunk-6E5VQPC4.js.map +1 -0
  6. package/dist/chunk-ABQH2WZT.js +36 -0
  7. package/dist/chunk-ABQH2WZT.js.map +1 -0
  8. package/dist/{chunk-YSC5GEQJ.js → chunk-BI45R2FH.js} +7 -3
  9. package/dist/chunk-BI45R2FH.js.map +1 -0
  10. package/dist/chunk-DNG7D77K.js +65 -0
  11. package/dist/chunk-DNG7D77K.js.map +1 -0
  12. package/dist/chunk-KFELB7ZC.js +70 -0
  13. package/dist/chunk-KFELB7ZC.js.map +1 -0
  14. package/dist/chunk-L2TFD72B.js +16320 -0
  15. package/dist/chunk-L2TFD72B.js.map +1 -0
  16. package/dist/chunk-M2VTUPFO.js +265 -0
  17. package/dist/chunk-M2VTUPFO.js.map +1 -0
  18. package/dist/chunk-OM2AMDTJ.js +347 -0
  19. package/dist/chunk-OM2AMDTJ.js.map +1 -0
  20. package/dist/chunk-Q24RPXOA.js +159 -0
  21. package/dist/chunk-Q24RPXOA.js.map +1 -0
  22. package/dist/chunk-SKGB4CZS.js +14 -0
  23. package/dist/chunk-SKGB4CZS.js.map +1 -0
  24. package/dist/chunk-SZ4WOGV2.js +120 -0
  25. package/dist/chunk-SZ4WOGV2.js.map +1 -0
  26. package/dist/finalization-git-internal.d.ts +3 -0
  27. package/dist/finalization-git-internal.d.ts.map +1 -1
  28. package/dist/finalization-git.d.ts +1 -1
  29. package/dist/finalization-git.d.ts.map +1 -1
  30. package/dist/finalization-git.js +5 -3
  31. package/dist/index.d.ts +1 -0
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/index.js +17 -591
  34. package/dist/index.js.map +1 -1
  35. package/dist/profile-bindings-internal.d.ts +3 -0
  36. package/dist/profile-bindings-internal.d.ts.map +1 -0
  37. package/dist/pull-request-publication-internal.d.ts +75 -0
  38. package/dist/pull-request-publication-internal.d.ts.map +1 -0
  39. package/dist/repository-change-launch-internal-BudnAfL7.d.ts +88 -0
  40. package/dist/repository-change-launch-internal.d.ts +62 -11
  41. package/dist/repository-change-launch-internal.d.ts.map +1 -1
  42. package/dist/repository-change-launch.d.ts +5 -2
  43. package/dist/repository-change-launch.d.ts.map +1 -1
  44. package/dist/repository-change-launch.js +363 -6
  45. package/dist/repository-change-launch.js.map +1 -1
  46. package/dist/repository-change-process-DlgF04fU.d.ts +69 -0
  47. package/dist/repository-change-process.d.ts +30 -25
  48. package/dist/repository-change-process.d.ts.map +1 -1
  49. package/dist/repository-change-publication.d.ts +63 -7
  50. package/dist/repository-change-publication.d.ts.map +1 -1
  51. package/dist/repository-change-publication.js +732 -56
  52. package/dist/repository-change-publication.js.map +1 -1
  53. package/dist/repository-change-state-internal.d.ts +18 -4
  54. package/dist/repository-change-state-internal.d.ts.map +1 -1
  55. package/dist/repository-change-ui-launcher-internal.d.ts +65 -0
  56. package/dist/repository-change-ui-launcher-internal.d.ts.map +1 -0
  57. package/dist/repository-rebase/git.d.ts +31 -0
  58. package/dist/repository-rebase/git.d.ts.map +1 -0
  59. package/dist/repository-rebase/index.d.ts +42 -0
  60. package/dist/repository-rebase/index.d.ts.map +1 -0
  61. package/dist/repository-rebase/index.js +16 -0
  62. package/dist/repository-rebase/policy.d.ts +37 -0
  63. package/dist/repository-rebase/policy.d.ts.map +1 -0
  64. package/dist/repository-rebase/prompt.d.ts +3 -0
  65. package/dist/repository-rebase/prompt.d.ts.map +1 -0
  66. package/dist/settings.d.ts +15 -0
  67. package/dist/settings.d.ts.map +1 -0
  68. package/dist/turns/commit-message-evidence.d.ts +35 -0
  69. package/dist/turns/commit-message-evidence.d.ts.map +1 -0
  70. package/dist/turns/commit-message-evidence.js +9 -0
  71. package/dist/turns/generate-commit-message.d.ts +4 -1
  72. package/dist/turns/generate-commit-message.d.ts.map +1 -1
  73. package/dist/turns/generate-commit-message.js +7 -5
  74. package/dist/turns/generate-plan.d.ts.map +1 -1
  75. package/dist/turns/generate-plan.js +1 -1
  76. package/dist/turns/git-inspection-profile.d.ts +25 -0
  77. package/dist/turns/git-inspection-profile.d.ts.map +1 -0
  78. package/dist/turns/git-inspection-profile.js +8 -0
  79. package/dist/turns/git-inspection-profile.js.map +1 -0
  80. package/dist/turns/implement.d.ts.map +1 -1
  81. package/dist/turns/implement.js +1 -1
  82. package/dist/turns/simplify-implementation.d.ts +1 -1
  83. package/dist/turns/simplify-implementation.d.ts.map +1 -1
  84. package/dist/turns/simplify-implementation.js +3 -3
  85. package/package.json +10 -10
  86. package/src/finalization-git-internal.ts +117 -114
  87. package/src/finalization-git.ts +1 -1
  88. package/src/index.ts +4 -1
  89. package/src/profile-bindings-internal.ts +39 -0
  90. package/src/pull-request-publication-internal.ts +364 -0
  91. package/src/repository-change-launch-internal.ts +194 -11
  92. package/src/repository-change-launch.ts +13 -0
  93. package/src/repository-change-process.ts +234 -523
  94. package/src/repository-change-publication.ts +535 -156
  95. package/src/repository-change-state-internal.ts +34 -20
  96. package/src/repository-change-ui-launcher-internal.ts +308 -0
  97. package/src/repository-rebase/git.ts +219 -0
  98. package/src/repository-rebase/index.ts +144 -0
  99. package/src/repository-rebase/policy.ts +75 -0
  100. package/src/repository-rebase/prompt.ts +2 -0
  101. package/src/settings.ts +79 -0
  102. package/src/turns/commit-message-evidence.ts +241 -0
  103. package/src/turns/generate-commit-message.ts +53 -23
  104. package/src/turns/generate-plan.ts +26 -12
  105. package/src/turns/git-inspection-profile.ts +134 -0
  106. package/src/turns/implement.ts +9 -2
  107. package/src/turns/simplify-implementation.ts +10 -6
  108. package/dist/chunk-34B3Q75M.js +0 -25
  109. package/dist/chunk-34B3Q75M.js.map +0 -1
  110. package/dist/chunk-F6CEEAFE.js +0 -13
  111. package/dist/chunk-F6CEEAFE.js.map +0 -1
  112. package/dist/chunk-GO44KCUS.js +0 -154
  113. package/dist/chunk-GO44KCUS.js.map +0 -1
  114. package/dist/chunk-R3UCUGY6.js +0 -31
  115. package/dist/chunk-R3UCUGY6.js.map +0 -1
  116. package/dist/chunk-W7VJT6AN.js +0 -25
  117. package/dist/chunk-W7VJT6AN.js.map +0 -1
  118. package/dist/chunk-WKHVLLKE.js +0 -45
  119. package/dist/chunk-WKHVLLKE.js.map +0 -1
  120. package/dist/chunk-YSC5GEQJ.js.map +0 -1
  121. package/dist/turns/review-implementation.d.ts +0 -4
  122. package/dist/turns/review-implementation.d.ts.map +0 -1
  123. package/dist/turns/review-implementation.js +0 -8
  124. package/dist/turns/review-plan.d.ts +0 -4
  125. package/dist/turns/review-plan.d.ts.map +0 -1
  126. package/dist/turns/review-plan.js +0 -8
  127. package/src/turns/review-implementation.ts +0 -30
  128. package/src/turns/review-plan.ts +0 -24
  129. /package/dist/{turns/review-implementation.js.map → repository-rebase/index.js.map} +0 -0
  130. /package/dist/turns/{review-plan.js.map → commit-message-evidence.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
- }
@@ -0,0 +1,308 @@
1
+ import { trimString } from "@leitwerk-dev/domain";
2
+ import {
3
+ type LauncherValidationError,
4
+ type LaunchPreparationCheck,
5
+ type ProcessLaunchConfig,
6
+ type ProcessLauncherDefinition,
7
+ type RepositoryIssue,
8
+ type RepositoryIssueWatcherConfig,
9
+ SafeLaunchPreparationError,
10
+ } from "@leitwerk-dev/process-sdk";
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";
20
+
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,
29
+ R extends {
30
+ /** @internal */
31
+ full_name: string;
32
+ /** @internal */
33
+ html_url: string;
34
+ /** @internal */
35
+ ssh_url: string;
36
+ /** @internal */
37
+ default_branch: string;
38
+ },
39
+ B,
40
+ I,
41
+ >(options: {
42
+ /** @internal */
43
+ id: string;
44
+ /** @internal */
45
+ provider: string;
46
+ /** @internal */
47
+ providerId: string;
48
+ /** @internal */
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
+ };
61
+ /** @internal */
62
+ profile(params: P): string;
63
+ /** @internal */
64
+ resolveProfiles(profile: string, dependencies: D): B;
65
+ /** @internal */
66
+ params(
67
+ repository: R,
68
+ input: B & {
69
+ /** @internal */
70
+ profile: string;
71
+ /** @internal */
72
+ prompt: string;
73
+ /** @internal */
74
+ workBranch: string;
75
+ },
76
+ ): P;
77
+ /** @internal */
78
+ launchConfig(
79
+ params: P,
80
+ title: string,
81
+ identity: I,
82
+ repository: NoInfer<R>,
83
+ ): ProcessLaunchConfig<P>;
84
+ /** @internal */
85
+ preparationChecks(params: P, dependencies: () => D): readonly LaunchPreparationCheck<P>[];
86
+ }) {
87
+ const { provider, providerId } = options;
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
+ }
136
+ function validationError(
137
+ fieldId: string,
138
+ message: string,
139
+ code: LauncherValidationError["code"] = "required",
140
+ ): LauncherValidationError {
141
+ return { code, fieldId, message };
142
+ }
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
+ } = {
152
+ async resolveIssueLaunchConfig({ profile, repository, issue, labels }) {
153
+ const title = issue.title.trim();
154
+ const body = issue.body?.trim() ?? "";
155
+ const binding = resolveProfiles(profile);
156
+ const identity = await resolveGitIdentity(profile);
157
+ return options.launchConfig(
158
+ {
159
+ ...options.params(repository, {
160
+ ...binding,
161
+ profile,
162
+ workBranch: `leitwerk/issue-${issue.number}`,
163
+ prompt: `${title}${body ? `\n\n${body}` : ""}`,
164
+ }),
165
+ origin: "issue",
166
+ issueNumber: issue.number,
167
+ issueUrl: issue.html_url,
168
+ triggerLabel: labels.trigger,
169
+ doneLabel: labels.done,
170
+ },
171
+ title,
172
+ identity,
173
+ repository,
174
+ );
175
+ },
176
+ id: options.id,
177
+ label: `${provider} Repo Change`,
178
+ description: `Plan, implement, review, and publish a ${provider} change without a source issue`,
179
+ visibility: "ui",
180
+ ui: {
181
+ card: {
182
+ title: `${provider} Repo Change`,
183
+ description: `Start a repository change and publish it as a ${provider} pull request.`,
184
+ },
185
+ launchConfigSchema: {
186
+ id: `${providerId}_repo_change_form`,
187
+ title: `${provider} Repo Change`,
188
+ fields: [
189
+ ...repositoryChangeOptionFields,
190
+ {
191
+ id: profileField,
192
+ label: `${provider} profile`,
193
+ kind: "select",
194
+ required: true,
195
+ description: `${provider} profile with server-configured CI and Git SSH access.`,
196
+ },
197
+ {
198
+ id: "repository",
199
+ label: "Repository",
200
+ kind: "select",
201
+ required: true,
202
+ description: `Repository visible to the selected ${provider} profile.`,
203
+ },
204
+ {
205
+ id: "prompt",
206
+ label: "Requested change",
207
+ kind: "textarea",
208
+ required: true,
209
+ placeholder: "Describe the change to plan, implement, review, and publish.",
210
+ },
211
+ ],
212
+ submitLabel: "Start change",
213
+ },
214
+ resolveDefaults() {
215
+ return {
216
+ [profileField]: profiles()[0] ?? "",
217
+ repository: "",
218
+ prompt: "",
219
+ ...repositoryChangeOptions({}),
220
+ };
221
+ },
222
+ async resolveOptions(input) {
223
+ const profile = trimString(input[profileField]);
224
+ return {
225
+ [profileField]: profiles().map((value) => ({ value, label: value })),
226
+ repository: (await repositories(profile)).map((repository) => ({
227
+ value: repository.full_name,
228
+ label: repository.full_name,
229
+ description: repository.html_url,
230
+ })),
231
+ };
232
+ },
233
+ preparationChecks,
234
+ resolveRelaunchInput(input) {
235
+ return {
236
+ ...repositoryChangeOptions(input),
237
+ [profileField]: trimString(input[profileField]),
238
+ repository: trimString(input.repository),
239
+ prompt: trimString(input.prompt),
240
+ };
241
+ },
242
+ async resolveLaunchConfig(input) {
243
+ const profile = trimString(input[profileField]);
244
+ const repositoryName = trimString(input.repository);
245
+ const prompt = trimString(input.prompt);
246
+ const errors: LauncherValidationError[] = [];
247
+ const invalid = (fieldId: string, message: string) => ({
248
+ ok: false as const,
249
+ errors: [validationError(fieldId, message, "custom_rule")],
250
+ });
251
+ requireDependencies();
252
+ if (!profile) errors.push(validationError(profileField, `${provider} profile is required`));
253
+ else if (!profiles().includes(profile))
254
+ errors.push(
255
+ validationError(profileField, `${provider} profile is not available`, "custom_rule"),
256
+ );
257
+ if (!repositoryName) errors.push(validationError("repository", "Repository is required"));
258
+ if (!prompt) errors.push(validationError("prompt", "Requested change is required"));
259
+ if (errors.length > 0) return { ok: false, errors };
260
+ const repository = (await repositories(profile)).find(
261
+ (candidate) => candidate.full_name === repositoryName,
262
+ );
263
+ if (!repository)
264
+ return invalid(
265
+ "repository",
266
+ `Repository is not available to the selected ${provider} profile`,
267
+ );
268
+ let binding: B;
269
+ try {
270
+ binding = resolveProfiles(profile);
271
+ } catch (error) {
272
+ return invalid(profileField, (error as Error).message);
273
+ }
274
+ const identity = await resolveGitIdentity(profile);
275
+ const workBranch = buildAutoWorkBranchFromSeed(
276
+ prompt,
277
+ `${repository.ssh_url}:${repository.default_branch}`,
278
+ );
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
+ };
287
+ },
288
+ },
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
+ };
308
+ }
@@ -0,0 +1,219 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { repositoryGitArgs, repositoryGitSubprocessEnv } from "@leitwerk-dev/process-sdk";
5
+ import { resolveGitBinary } from "@leitwerk-dev/process-sdk/git-binary";
6
+
7
+ import { type ConflictEvidence, conflictKey } from "./index.js";
8
+ import {
9
+ type RebaseRecord,
10
+ rebasePublicationDecision,
11
+ requireRebaseHead,
12
+ requireRebaseOrigin,
13
+ requireRebaseTarget,
14
+ requireRebaseWorktree,
15
+ } from "./policy.js";
16
+
17
+ /** @internal */
18
+ export interface RebaseInput {
19
+ /** @internal */
20
+ projectKey: string;
21
+ /** @internal */
22
+ path: string;
23
+ /** @internal */
24
+ workBranch: string;
25
+ /** @internal */
26
+ conflict: ConflictEvidence;
27
+ }
28
+ function git(input: RebaseInput, ...args: string[]): string {
29
+ return execFileSync(resolveGitBinary(), repositoryGitArgs(args), {
30
+ cwd: input.path,
31
+ encoding: "utf8",
32
+ env: repositoryGitSubprocessEnv(input.projectKey, {
33
+ GIT_TERMINAL_PROMPT: "0",
34
+ GIT_EDITOR: "true",
35
+ }),
36
+ stdio: ["ignore", "pipe", "pipe"],
37
+ }).trim();
38
+ }
39
+ function area(input: RebaseInput): string {
40
+ return git(input, "rev-parse", "--absolute-git-dir");
41
+ }
42
+ function active(gitDir: string): boolean {
43
+ return ["rebase-merge", "rebase-apply"].some((name) => existsSync(join(gitDir, name)));
44
+ }
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
+ function requireWorktree(input: RebaseInput): void {
55
+ requireRebaseWorktree(input.workBranch, {
56
+ branch: git(input, "branch", "--show-current"),
57
+ dirty: Boolean(git(input, "status", "--porcelain")),
58
+ });
59
+ }
60
+ function remoteHead(input: RebaseInput): string {
61
+ return git(input, "ls-remote", "--heads", "origin", `refs/heads/${input.workBranch}`).split(
62
+ /\s+/,
63
+ )[0];
64
+ }
65
+
66
+ function requireTarget(input: RebaseInput, record?: RebaseRecord | null): void {
67
+ requireRebaseTarget(input.workBranch, input.conflict, record);
68
+ git(input, "check-ref-format", `refs/heads/${input.workBranch}`);
69
+ git(input, "check-ref-format", `refs/heads/${input.conflict.baseBranch}`);
70
+ requireRebaseOrigin(record, {
71
+ originUrl: record?.originUrl ? git(input, "remote", "get-url", "origin") : undefined,
72
+ originPushUrl: record?.originPushUrl
73
+ ? git(input, "remote", "get-url", "--push", "--all", "origin")
74
+ : undefined,
75
+ });
76
+ }
77
+
78
+ function verifyCurrentBase(input: RebaseInput, record: RebaseRecord): void {
79
+ git(
80
+ input,
81
+ "fetch",
82
+ "origin",
83
+ `+refs/heads/${input.conflict.baseBranch}:refs/leitwerk/rebase-base`,
84
+ );
85
+ // A fast-forward is compatible with captured preparation; a rewritten base is not.
86
+ git(input, "merge-base", "--is-ancestor", record.baseSha, "refs/leitwerk/rebase-base");
87
+ }
88
+
89
+ function verifyNoRepairNeeded(input: RebaseInput, headSha: string, baseSha: string): void {
90
+ if (input.conflict.reason === "behind")
91
+ git(input, "merge-base", "--is-ancestor", baseSha, headSha);
92
+ else git(input, "merge-tree", "--write-tree", headSha, baseSha);
93
+ }
94
+
95
+ /** Persist the lease before changing HEAD; a retry resumes Git's own rebase state. @internal */
96
+ export function prepareRebase(input: RebaseInput): RebaseRecord {
97
+ const gitDir = area(input);
98
+ const old = read(gitDir);
99
+ requireTarget(input, old?.key === conflictKey(input.conflict) ? old : null);
100
+ if (old?.key === conflictKey(input.conflict)) {
101
+ verifyCurrentBase(input, old);
102
+ return old;
103
+ }
104
+ if (active(gitDir)) throw new Error("An unrelated rebase is already in progress");
105
+ requireWorktree(input);
106
+ git(
107
+ input,
108
+ "fetch",
109
+ "origin",
110
+ `+refs/heads/${input.workBranch}:refs/leitwerk/rebase-head`,
111
+ `+refs/heads/${input.conflict.baseBranch}:refs/leitwerk/rebase-base`,
112
+ );
113
+ const [remoteSha, headSha, baseSha] = git(
114
+ input,
115
+ "rev-parse",
116
+ "refs/leitwerk/rebase-head",
117
+ "HEAD",
118
+ "refs/leitwerk/rebase-base",
119
+ ).split("\n");
120
+ requireRebaseHead(input.conflict.headSha, headSha, remoteSha);
121
+ // Use the current fetched base, retaining the provider pair for deduplication.
122
+ git(input, "merge-base", "--is-ancestor", input.conflict.baseSha, baseSha);
123
+ const record: RebaseRecord = {
124
+ key: conflictKey(input.conflict),
125
+ branch: input.workBranch,
126
+ originalHead: input.conflict.headSha,
127
+ baseSha,
128
+ status: "prepared",
129
+ originUrl: git(input, "remote", "get-url", "origin"),
130
+ originPushUrl: git(input, "remote", "get-url", "--push", "--all", "origin"),
131
+ baseBranch: input.conflict.baseBranch,
132
+ };
133
+ git(input, "update-ref", "refs/leitwerk/rebase-original", record.originalHead);
134
+ save(gitDir, record);
135
+ return record;
136
+ }
137
+ /** @internal */
138
+ export function startRebase(input: RebaseInput): RebaseRecord {
139
+ const record = prepareRebase(input);
140
+ const gitDir = area(input);
141
+ if (active(gitDir)) return record;
142
+ if (record.status === "clean") return record;
143
+ requireWorktree(input);
144
+ if (record.status === "rebasing" && git(input, "rev-parse", "HEAD") !== record.originalHead)
145
+ return record;
146
+ try {
147
+ verifyNoRepairNeeded(input, record.originalHead, record.baseSha);
148
+ record.status = "clean";
149
+ save(gitDir, record);
150
+ return record;
151
+ } catch (error) {
152
+ if ((error as { status?: number }).status !== 1) throw error;
153
+ }
154
+ record.status = "rebasing";
155
+ save(gitDir, record);
156
+ try {
157
+ git(input, "rebase", "--rebase-merges", record.baseSha);
158
+ } catch (error) {
159
+ if (!active(gitDir)) throw error;
160
+ }
161
+ return record;
162
+ }
163
+ /** @internal */
164
+ export function verifyRebase(input: RebaseInput): {
165
+ /** @internal */
166
+ headSha: string;
167
+ /** @internal */
168
+ changed: boolean;
169
+ /** @internal */
170
+ originalHead: string;
171
+ /** @internal */
172
+ baseSha: string;
173
+ } {
174
+ const gitDir = area(input);
175
+ const record = read(gitDir);
176
+ if (!record || record.key !== conflictKey(input.conflict))
177
+ throw new Error("Missing matching rebase metadata");
178
+ requireTarget(input, record);
179
+ if (active(gitDir)) throw new Error("Rebase is incomplete");
180
+ requireWorktree(input);
181
+ const headSha = git(input, "rev-parse", "HEAD");
182
+ if (record.status === "clean") {
183
+ if (headSha !== record.originalHead)
184
+ throw new Error("Clean conflict report must not rewrite the branch");
185
+ verifyNoRepairNeeded(input, headSha, record.baseSha);
186
+ } else {
187
+ if (record.status !== "rebasing") throw new Error("Rebase was not started");
188
+ git(input, "merge-base", "--is-ancestor", record.baseSha, headSha);
189
+ }
190
+ return {
191
+ headSha,
192
+ changed: headSha !== record.originalHead,
193
+ originalHead: record.originalHead,
194
+ baseSha: record.baseSha,
195
+ };
196
+ }
197
+ /** @internal */
198
+ export function publishRebase(input: RebaseInput): ReturnType<typeof verifyRebase> {
199
+ const result = verifyRebase(input);
200
+ const gitDir = area(input);
201
+ const record = read(gitDir);
202
+ if (!record) throw new Error("Missing matching rebase metadata");
203
+ verifyCurrentBase(input, record);
204
+ const remote = remoteHead(input);
205
+ if (
206
+ rebasePublicationDecision(result.originalHead, result.headSha, remote) === "already_published"
207
+ )
208
+ 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");
218
+ return result;
219
+ }