@leitwerk-dev/coding 0.1.9 → 0.2.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 (113) hide show
  1. package/README.md +19 -2
  2. package/dist/actions.d.ts +14 -0
  3. package/dist/actions.d.ts.map +1 -1
  4. package/dist/auto-work-branch-internal.d.ts +20 -0
  5. package/dist/auto-work-branch-internal.d.ts.map +1 -0
  6. package/dist/auto-work-branch.d.ts +2 -12
  7. package/dist/auto-work-branch.d.ts.map +1 -1
  8. package/dist/auto-work-branch.js +84 -86
  9. package/dist/auto-work-branch.js.map +1 -1
  10. package/dist/{chunk-EP3ZC37F.js → chunk-34B3Q75M.js} +1 -1
  11. package/dist/chunk-34B3Q75M.js.map +1 -0
  12. package/dist/{chunk-OFDNIT5X.js → chunk-F6CEEAFE.js} +1 -1
  13. package/dist/chunk-F6CEEAFE.js.map +1 -0
  14. package/dist/{chunk-YIP4MP64.js → chunk-HUVXPZSF.js} +2 -2
  15. package/dist/chunk-HUVXPZSF.js.map +1 -0
  16. package/dist/{chunk-R3S5KR3J.js → chunk-MY6XFGHM.js} +146 -168
  17. package/dist/chunk-MY6XFGHM.js.map +1 -0
  18. package/dist/{chunk-5LVPKVI2.js → chunk-OERAYSVI.js} +1 -1
  19. package/dist/chunk-OERAYSVI.js.map +1 -0
  20. package/dist/{chunk-WQEPA35Z.js → chunk-R3UCUGY6.js} +1 -1
  21. package/dist/chunk-R3UCUGY6.js.map +1 -0
  22. package/dist/{chunk-67YKGZLM.js → chunk-W7VJT6AN.js} +1 -1
  23. package/dist/chunk-W7VJT6AN.js.map +1 -0
  24. package/dist/{chunk-NIJCT4VK.js → chunk-WKHVLLKE.js} +1 -1
  25. package/dist/chunk-WKHVLLKE.js.map +1 -0
  26. package/dist/{chunk-UBVLJV3V.js → chunk-YSC5GEQJ.js} +1 -1
  27. package/dist/chunk-YSC5GEQJ.js.map +1 -0
  28. package/dist/finalization-git-internal.d.ts +72 -0
  29. package/dist/finalization-git-internal.d.ts.map +1 -0
  30. package/dist/finalization-git.d.ts +2 -42
  31. package/dist/finalization-git.d.ts.map +1 -1
  32. package/dist/finalization-git.js +7 -593
  33. package/dist/finalization-git.js.map +1 -1
  34. package/dist/index.d.ts +3 -7
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +654 -6
  37. package/dist/index.js.map +1 -1
  38. package/dist/repository-change-launch-internal.d.ts +116 -0
  39. package/dist/repository-change-launch-internal.d.ts.map +1 -0
  40. package/dist/repository-change-launch.d.ts +2 -64
  41. package/dist/repository-change-launch.d.ts.map +1 -1
  42. package/dist/repository-change-launch.js +177 -174
  43. package/dist/repository-change-launch.js.map +1 -1
  44. package/dist/repository-change-process.d.ts +32 -2
  45. package/dist/repository-change-process.d.ts.map +1 -1
  46. package/dist/repository-change-state-internal.d.ts +30 -0
  47. package/dist/repository-change-state-internal.d.ts.map +1 -0
  48. package/dist/repository-change-state.d.ts +2 -17
  49. package/dist/repository-change-state.d.ts.map +1 -1
  50. package/dist/repository-change-state.js +6 -51
  51. package/dist/repository-change-state.js.map +1 -1
  52. package/dist/turns/generate-commit-message.d.ts +2 -0
  53. package/dist/turns/generate-commit-message.d.ts.map +1 -1
  54. package/dist/turns/generate-commit-message.js +9 -38
  55. package/dist/turns/generate-commit-message.js.map +1 -1
  56. package/dist/turns/generate-plan.d.ts +1 -0
  57. package/dist/turns/generate-plan.d.ts.map +1 -1
  58. package/dist/turns/generate-plan.js +7 -19
  59. package/dist/turns/generate-plan.js.map +1 -1
  60. package/dist/turns/implement.d.ts +1 -0
  61. package/dist/turns/implement.d.ts.map +1 -1
  62. package/dist/turns/implement.js +7 -17
  63. package/dist/turns/implement.js.map +1 -1
  64. package/dist/turns/resolve-merge-conflict.d.ts +1 -0
  65. package/dist/turns/resolve-merge-conflict.d.ts.map +1 -1
  66. package/dist/turns/resolve-merge-conflict.js +7 -21
  67. package/dist/turns/resolve-merge-conflict.js.map +1 -1
  68. package/dist/turns/review-implementation.d.ts +1 -0
  69. package/dist/turns/review-implementation.d.ts.map +1 -1
  70. package/dist/turns/review-implementation.js +7 -25
  71. package/dist/turns/review-implementation.js.map +1 -1
  72. package/dist/turns/review-plan.d.ts +1 -0
  73. package/dist/turns/review-plan.d.ts.map +1 -1
  74. package/dist/turns/review-plan.js +7 -19
  75. package/dist/turns/review-plan.js.map +1 -1
  76. package/dist/turns/simplify-implementation.d.ts +1 -0
  77. package/dist/turns/simplify-implementation.d.ts.map +1 -1
  78. package/dist/turns/simplify-implementation.js +7 -7
  79. package/dist/turns/simplify-implementation.js.map +1 -1
  80. package/package.json +19 -8
  81. package/src/actions.ts +17 -1
  82. package/src/auto-work-branch-internal.ts +149 -0
  83. package/src/auto-work-branch.ts +7 -140
  84. package/src/finalization-git-internal.ts +855 -0
  85. package/src/finalization-git.ts +2 -825
  86. package/src/index.ts +16 -4
  87. package/src/repository-change-launch-internal.ts +328 -0
  88. package/src/repository-change-launch.ts +15 -264
  89. package/src/repository-change-process.ts +112 -168
  90. package/src/repository-change-state-internal.ts +90 -0
  91. package/src/repository-change-state.ts +2 -78
  92. package/src/turns/generate-commit-message.ts +2 -0
  93. package/src/turns/generate-plan.ts +1 -0
  94. package/src/turns/implement.ts +1 -0
  95. package/src/turns/resolve-merge-conflict.ts +1 -0
  96. package/src/turns/review-implementation.ts +1 -0
  97. package/src/turns/review-plan.ts +1 -0
  98. package/src/turns/simplify-implementation.ts +1 -0
  99. package/dist/actions.js +0 -45
  100. package/dist/actions.js.map +0 -1
  101. package/dist/chunk-5LVPKVI2.js.map +0 -1
  102. package/dist/chunk-67YKGZLM.js.map +0 -1
  103. package/dist/chunk-EP3ZC37F.js.map +0 -1
  104. package/dist/chunk-NIJCT4VK.js.map +0 -1
  105. package/dist/chunk-OFDNIT5X.js.map +0 -1
  106. package/dist/chunk-R3S5KR3J.js.map +0 -1
  107. package/dist/chunk-UBVLJV3V.js.map +0 -1
  108. package/dist/chunk-WQEPA35Z.js.map +0 -1
  109. package/dist/chunk-Y2S6JFVO.js +0 -185
  110. package/dist/chunk-Y2S6JFVO.js.map +0 -1
  111. package/dist/chunk-YIP4MP64.js.map +0 -1
  112. package/dist/repository-change-process.js +0 -689
  113. package/dist/repository-change-process.js.map +0 -1
@@ -1,825 +1,2 @@
1
- import { execFileSync } from "node:child_process";
2
- import { existsSync, readFileSync } from "node:fs";
3
- import { homedir } from "node:os";
4
- import path from "node:path";
5
- import { fileURLToPath } from "node:url";
6
- import { detectRepoLocatorKind, trimToNull, type WorkerErrorClass } from "@leitwerk-dev/domain";
7
- import {
8
- type FlowAutomaticRunContext,
9
- repositoryGitArgs,
10
- repositoryGitSubprocessEnv,
11
- type StructuralProcessState,
12
- } from "@leitwerk-dev/process-sdk";
13
- import { resolveGitBinary } from "@leitwerk-dev/process-sdk/git-binary";
14
-
15
- export type DeterministicFinalizationMergeMode = "noop" | "fast_forward" | "merge_commit";
16
-
17
- interface DeterministicFinalizationInput {
18
- repoPath: string;
19
- workspaceClonePath: string;
20
- baseBranch: string;
21
- workBranch: string;
22
- expectedPostConflictHeadSha?: string | null;
23
- usedConflictResolution?: boolean;
24
- commitMessage: string;
25
- }
26
-
27
- export type DeterministicFinalizationResult =
28
- | {
29
- outcome: "merge_conflict";
30
- params: {
31
- headSha: string;
32
- conflictedFiles: string[];
33
- fetchedBaseSha: string | null;
34
- };
35
- }
36
- | {
37
- outcome: "finalized";
38
- params: {
39
- headSha: string;
40
- mergeMode: DeterministicFinalizationMergeMode;
41
- pushTarget: string;
42
- usedConflictResolution: boolean;
43
- };
44
- markdown: string;
45
- };
46
-
47
- export class DeterministicGitError extends Error {
48
- readonly errorClass: WorkerErrorClass = "git_error";
49
-
50
- constructor(message: string) {
51
- super(message);
52
- this.name = "DeterministicGitError";
53
- }
54
- }
55
-
56
- interface GitExecResult {
57
- ok: boolean;
58
- stdout: string;
59
- stderr: string;
60
- status: number | null;
61
- }
62
-
63
- interface LocalSourceRepo {
64
- path: string;
65
- kind: "bare" | "non_bare";
66
- }
67
-
68
- function normalizeLines(value: string | null | undefined): string[] {
69
- if (!value) {
70
- return [];
71
- }
72
- return value
73
- .split(/\r?\n/)
74
- .map((line) => line.trim())
75
- .filter((line) => line !== "");
76
- }
77
-
78
- function abbreviateSha(sha: string): string {
79
- return sha.slice(0, 12);
80
- }
81
-
82
- function describeMergeMode(mode: DeterministicFinalizationMergeMode): string {
83
- switch (mode) {
84
- case "noop":
85
- return "Already up to date";
86
- case "fast_forward":
87
- return "Fast-forwarded from origin";
88
- case "merge_commit":
89
- return "Created a merge commit";
90
- }
91
- }
92
-
93
- function gitConfigIdentityEnv(): NodeJS.ProcessEnv {
94
- const env = repositoryGitSubprocessEnv("repo", { GIT_TERMINAL_PROMPT: "0" });
95
- // Identity is operator-owned repository/global Git configuration, never an
96
- // ambient worker identity or a Leitwerk override.
97
- for (const key of [
98
- "GIT_AUTHOR_NAME",
99
- "GIT_AUTHOR_EMAIL",
100
- "GIT_AUTHOR_DATE",
101
- "GIT_COMMITTER_NAME",
102
- "GIT_COMMITTER_EMAIL",
103
- "GIT_COMMITTER_DATE",
104
- ])
105
- delete env[key];
106
- return env;
107
- }
108
-
109
- function runGit(repoPath: string, args: readonly string[]): GitExecResult {
110
- try {
111
- const stdout = execFileSync(resolveGitBinary(), repositoryGitArgs(args), {
112
- cwd: repoPath,
113
- encoding: "utf8",
114
- env: gitConfigIdentityEnv(),
115
- stdio: ["ignore", "pipe", "pipe"],
116
- });
117
- return {
118
- ok: true,
119
- stdout,
120
- stderr: "",
121
- status: 0,
122
- };
123
- } catch (error) {
124
- const execError = error as {
125
- status?: number | null;
126
- stdout?: string | Buffer;
127
- stderr?: string | Buffer;
128
- message?: string;
129
- };
130
- return {
131
- ok: false,
132
- stdout:
133
- typeof execError.stdout === "string"
134
- ? execError.stdout
135
- : execError.stdout
136
- ? execError.stdout.toString("utf8")
137
- : "",
138
- stderr:
139
- typeof execError.stderr === "string"
140
- ? execError.stderr
141
- : execError.stderr
142
- ? execError.stderr.toString("utf8")
143
- : (trimToNull(execError.message) ?? ""),
144
- status: execError.status ?? null,
145
- };
146
- }
147
- }
148
-
149
- function git(repoPath: string, ...args: string[]): string {
150
- const result = runGit(repoPath, args);
151
- if (!result.ok) {
152
- throw new DeterministicGitError(
153
- `git ${args.join(" ")} failed in '${repoPath}': ${trimToNull(result.stderr) ?? trimToNull(result.stdout) ?? "unknown git error"}`,
154
- );
155
- }
156
- return result.stdout.trim();
157
- }
158
-
159
- function gitOrNull(repoPath: string, ...args: string[]): string | null {
160
- const result = runGit(repoPath, args);
161
- if (!result.ok) {
162
- return null;
163
- }
164
- return trimToNull(result.stdout);
165
- }
166
-
167
- function repoExists(repoPath: string): boolean {
168
- return existsSync(repoPath) && existsSync(path.join(repoPath, ".git"));
169
- }
170
-
171
- function gitRepositoryExists(repoPath: string): boolean {
172
- return existsSync(repoPath) && runGit(repoPath, ["rev-parse", "--git-dir"]).ok;
173
- }
174
-
175
- function currentBranch(repoPath: string): string {
176
- return git(repoPath, "branch", "--show-current");
177
- }
178
-
179
- function currentHeadSha(repoPath: string): string {
180
- return git(repoPath, "rev-parse", "HEAD");
181
- }
182
-
183
- function originBaseRef(baseBranch: string): string {
184
- return `origin/${baseBranch}`;
185
- }
186
-
187
- function remoteOriginUrl(repoPath: string): string {
188
- const remoteUrl = gitOrNull(repoPath, "remote", "get-url", "origin");
189
- if (!remoteUrl) {
190
- throw new DeterministicGitError(`Repository '${repoPath}' does not have an 'origin' remote`);
191
- }
192
- return remoteUrl;
193
- }
194
-
195
- function expandHomePath(value: string): string {
196
- if (value === "~") {
197
- return homedir();
198
- }
199
- if (value.startsWith("~/")) {
200
- return path.join(homedir(), value.slice(2));
201
- }
202
- return value;
203
- }
204
-
205
- function resolveLocalRepoPath(repoPath: string, repoLocator: string): string | null {
206
- if (detectRepoLocatorKind(repoLocator) !== "local_path") {
207
- return null;
208
- }
209
- if (repoLocator.startsWith("file://")) {
210
- try {
211
- return fileURLToPath(repoLocator);
212
- } catch {
213
- return null;
214
- }
215
- }
216
- return path.resolve(repoPath, expandHomePath(repoLocator));
217
- }
218
-
219
- function isBareRepository(repoPath: string): boolean {
220
- return git(repoPath, "rev-parse", "--is-bare-repository") === "true";
221
- }
222
-
223
- function resolveLocalSourceRepo(repoPath: string): LocalSourceRepo | null {
224
- const remoteUrl = remoteOriginUrl(repoPath);
225
- const localRepoPath = resolveLocalRepoPath(repoPath, remoteUrl);
226
- if (!localRepoPath || !gitRepositoryExists(localRepoPath)) {
227
- return null;
228
- }
229
- return {
230
- path: localRepoPath,
231
- kind: isBareRepository(localRepoPath) ? "bare" : "non_bare",
232
- };
233
- }
234
-
235
- function workingTreeStatus(repoPath: string): { dirtyFiles: string[] } {
236
- const rawStatus = gitOrNull(repoPath, "status", "--porcelain");
237
- const dirtyFiles = (rawStatus ?? "")
238
- .split(/\r?\n/)
239
- .map((line) => line.replace(/\s+$/, ""))
240
- .filter((line) => line !== "")
241
- .map((line) => line.slice(2).trim())
242
- .filter((line) => line !== "");
243
- return { dirtyFiles };
244
- }
245
-
246
- function conflictedFiles(repoPath: string): string[] {
247
- return normalizeLines(gitOrNull(repoPath, "diff", "--name-only", "--diff-filter=U"));
248
- }
249
-
250
- function mergeHeadPath(repoPath: string): string {
251
- const gitDir = git(repoPath, "rev-parse", "--git-dir");
252
- return path.resolve(repoPath, gitDir, "MERGE_HEAD");
253
- }
254
-
255
- function mergeInProgress(repoPath: string): boolean {
256
- return existsSync(mergeHeadPath(repoPath));
257
- }
258
-
259
- function assertExpectedCheckout(repoPath: string, workBranch: string): void {
260
- const branch = currentBranch(repoPath);
261
- if (branch !== workBranch) {
262
- throw new DeterministicGitError(
263
- `Expected '${repoPath}' to be checked out on '${workBranch}', but found '${branch || "detached HEAD"}'`,
264
- );
265
- }
266
- }
267
-
268
- function assertGitIdentity(repoPath: string): void {
269
- const author = runGit(repoPath, ["var", "GIT_AUTHOR_IDENT"]);
270
- const committer = runGit(repoPath, ["var", "GIT_COMMITTER_IDENT"]);
271
- if (!author.ok || !committer.ok) {
272
- throw new DeterministicGitError(
273
- "Git author/committer identity is not configured. Configure user.name and user.email in this repository or the operator's global Git config, then retry finalization.",
274
- );
275
- }
276
- }
277
-
278
- function commitDirtyWorktree(repoPath: string, commitMessage: string): string {
279
- assertGitIdentity(repoPath);
280
- const addResult = runGit(repoPath, ["add", "--all"]);
281
- if (!addResult.ok) {
282
- throw new DeterministicGitError(
283
- `Failed to stage the completed change: ${trimToNull(addResult.stderr) ?? trimToNull(addResult.stdout) ?? "unknown git error"}`,
284
- );
285
- }
286
- const commitResult = runGit(repoPath, [
287
- "-c",
288
- "core.hooksPath=/dev/null",
289
- "commit",
290
- "--no-gpg-sign",
291
- "-m",
292
- commitMessage,
293
- ]);
294
- if (!commitResult.ok) {
295
- throw new DeterministicGitError(
296
- `Failed to commit the completed change: ${trimToNull(commitResult.stderr) ?? trimToNull(commitResult.stdout) ?? "unknown git error"}`,
297
- );
298
- }
299
- const remaining = workingTreeStatus(repoPath);
300
- if (remaining.dirtyFiles.length > 0) {
301
- throw new DeterministicGitError(
302
- `Deterministic commit left uncommitted changes: ${remaining.dirtyFiles.join(", ")}`,
303
- );
304
- }
305
- return currentHeadSha(repoPath);
306
- }
307
-
308
- function assertPostConflictCheckpoint(
309
- input: DeterministicFinalizationInput,
310
- repoPath: string,
311
- ): void {
312
- if (!trimToNull(input.expectedPostConflictHeadSha)) {
313
- return;
314
- }
315
- if (mergeInProgress(repoPath) || conflictedFiles(repoPath).length > 0) {
316
- throw new DeterministicGitError(
317
- "Conflict-resolution helper reported a clean merge, but the repository is still in a merge-conflict state",
318
- );
319
- }
320
- const status = workingTreeStatus(repoPath);
321
- if (status.dirtyFiles.length > 0) {
322
- throw new DeterministicGitError(
323
- `Conflict-resolution helper reported a clean merge, but the repository still has uncommitted changes: ${status.dirtyFiles.join(", ")}`,
324
- );
325
- }
326
- }
327
-
328
- function fetchOriginBase(repoPath: string, baseBranch: string): string {
329
- const ref = originBaseRef(baseBranch);
330
- const fetchResult = runGit(repoPath, ["fetch", "origin", baseBranch]);
331
- if (!fetchResult.ok) {
332
- throw new DeterministicGitError(
333
- `Failed to fetch '${ref}': ${trimToNull(fetchResult.stderr) ?? trimToNull(fetchResult.stdout) ?? "unknown git error"}`,
334
- );
335
- }
336
- const baseSha = gitOrNull(repoPath, "rev-parse", ref);
337
- if (!baseSha) {
338
- throw new DeterministicGitError(`Fetched '${ref}' but could not resolve its commit sha`);
339
- }
340
- return baseSha;
341
- }
342
-
343
- function isAncestor(repoPath: string, olderRef: string, newerRef: string): boolean {
344
- return runGit(repoPath, ["merge-base", "--is-ancestor", olderRef, newerRef]).ok;
345
- }
346
-
347
- function deterministicMerge(input: {
348
- repoPath: string;
349
- baseBranch: string;
350
- headBefore: string;
351
- baseSha: string;
352
- }):
353
- | { ok: true; mergeMode: DeterministicFinalizationMergeMode; headSha: string }
354
- | { ok: false; conflict: true; headSha: string; conflictedFiles: string[] } {
355
- const { repoPath, baseBranch, headBefore, baseSha } = input;
356
- const ref = originBaseRef(baseBranch);
357
- const headIsAncestorOfBase = isAncestor(repoPath, headBefore, ref);
358
- const baseIsAncestorOfHead = isAncestor(repoPath, ref, headBefore);
359
-
360
- if (baseIsAncestorOfHead) {
361
- return { ok: true, mergeMode: "noop", headSha: headBefore };
362
- }
363
-
364
- if (headIsAncestorOfBase) {
365
- const ffResult = runGit(repoPath, ["merge", "--ff-only", ref]);
366
- if (!ffResult.ok) {
367
- throw new DeterministicGitError(
368
- `Fast-forward merge from '${ref}' failed: ${trimToNull(ffResult.stderr) ?? trimToNull(ffResult.stdout) ?? "unknown git error"}`,
369
- );
370
- }
371
- return {
372
- ok: true,
373
- mergeMode: "fast_forward",
374
- headSha: currentHeadSha(repoPath),
375
- };
376
- }
377
-
378
- assertGitIdentity(repoPath);
379
- const mergeResult = runGit(repoPath, [
380
- "-c",
381
- "core.hooksPath=/dev/null",
382
- "merge",
383
- "--no-edit",
384
- "--no-gpg-sign",
385
- ref,
386
- ]);
387
- if (!mergeResult.ok) {
388
- const conflicts = conflictedFiles(repoPath);
389
- if (mergeInProgress(repoPath) || conflicts.length > 0) {
390
- return {
391
- ok: false,
392
- conflict: true,
393
- headSha: currentHeadSha(repoPath),
394
- conflictedFiles: conflicts,
395
- };
396
- }
397
- throw new DeterministicGitError(
398
- `Deterministic merge from '${ref}' failed: ${trimToNull(mergeResult.stderr) ?? trimToNull(mergeResult.stdout) ?? "unknown git error"}`,
399
- );
400
- }
401
-
402
- const headAfter = currentHeadSha(repoPath);
403
- return {
404
- ok: true,
405
- mergeMode: headAfter === baseSha ? "fast_forward" : "merge_commit",
406
- headSha: headAfter,
407
- };
408
- }
409
-
410
- function branchRef(branch: string): string {
411
- return `refs/heads/${branch}`;
412
- }
413
-
414
- function pushHeadToBranch(repoPath: string, branch: string): string {
415
- const pushTarget = `origin/${branch}`;
416
- const pushResult = runGit(repoPath, ["push", "origin", `HEAD:${branchRef(branch)}`]);
417
- if (!pushResult.ok) {
418
- throw new DeterministicGitError(
419
- `Failed to push HEAD to '${pushTarget}': ${trimToNull(pushResult.stderr) ?? trimToNull(pushResult.stdout) ?? "unknown git error"}`,
420
- );
421
- }
422
- return pushTarget;
423
- }
424
-
425
- function assertLocalSourceBaseRef(input: {
426
- localSourceRepoPath: string;
427
- baseBranch: string;
428
- expectedHeadSha: string;
429
- operation: string;
430
- }): void {
431
- const ref = branchRef(input.baseBranch);
432
- const actualHeadSha = gitOrNull(input.localSourceRepoPath, "rev-parse", ref);
433
- if (!actualHeadSha) {
434
- throw new DeterministicGitError(
435
- `Local source repo '${input.localSourceRepoPath}' does not have '${ref}' ${input.operation}`,
436
- );
437
- }
438
- if (actualHeadSha !== input.expectedHeadSha) {
439
- throw new DeterministicGitError(
440
- `Local source repo '${input.localSourceRepoPath}' has '${ref}' at '${actualHeadSha}', but expected '${input.expectedHeadSha}' ${input.operation}`,
441
- );
442
- }
443
- }
444
-
445
- function assertLocalBareSourceRepoReady(
446
- localSourceRepoPath: string,
447
- baseBranch: string,
448
- expectedBaseSha: string,
449
- ): void {
450
- assertLocalSourceBaseRef({
451
- localSourceRepoPath,
452
- baseBranch,
453
- expectedHeadSha: expectedBaseSha,
454
- operation: "before finalization could publish the workspace branch. Retry finalization.",
455
- });
456
- }
457
-
458
- function pushLocalSourceBaseBranchToOriginIfPresent(input: {
459
- localSourceRepoPath: string;
460
- baseBranch: string;
461
- expectedHeadSha: string;
462
- }): string | null {
463
- if (!runGit(input.localSourceRepoPath, ["remote", "get-url", "origin"]).ok) {
464
- return null;
465
- }
466
- assertLocalSourceBaseRef({
467
- localSourceRepoPath: input.localSourceRepoPath,
468
- baseBranch: input.baseBranch,
469
- expectedHeadSha: input.expectedHeadSha,
470
- operation: "before pushing it to its origin remote",
471
- });
472
- const ref = branchRef(input.baseBranch);
473
- const pushTarget = originBaseRef(input.baseBranch);
474
- const pushResult = runGit(input.localSourceRepoPath, ["push", "origin", `${ref}:${ref}`]);
475
- if (!pushResult.ok) {
476
- throw new DeterministicGitError(
477
- `Failed to push local source repo '${input.localSourceRepoPath}' base branch '${input.baseBranch}' to '${pushTarget}': ${trimToNull(pushResult.stderr) ?? trimToNull(pushResult.stdout) ?? "unknown git error"}`,
478
- );
479
- }
480
- return pushTarget;
481
- }
482
-
483
- function assertLocalBaseRepoReady(
484
- localBaseRepoPath: string,
485
- baseBranch: string,
486
- expectedBaseSha: string,
487
- ): void {
488
- const branch = currentBranch(localBaseRepoPath);
489
- if (branch !== baseBranch) {
490
- throw new DeterministicGitError(
491
- `Expected local source repo '${localBaseRepoPath}' to be checked out on '${baseBranch}', but found '${branch || "detached HEAD"}'`,
492
- );
493
- }
494
- if (mergeInProgress(localBaseRepoPath) || conflictedFiles(localBaseRepoPath).length > 0) {
495
- throw new DeterministicGitError(
496
- `Local source repo '${localBaseRepoPath}' must not already be in a merge-conflict state before finalization updates '${baseBranch}'`,
497
- );
498
- }
499
- const status = workingTreeStatus(localBaseRepoPath);
500
- if (status.dirtyFiles.length > 0) {
501
- throw new DeterministicGitError(
502
- `Local source repo '${localBaseRepoPath}' must be clean before finalization updates '${baseBranch}': ${status.dirtyFiles.join(", ")}`,
503
- );
504
- }
505
- const actualBaseSha = currentHeadSha(localBaseRepoPath);
506
- if (actualBaseSha !== expectedBaseSha) {
507
- throw new DeterministicGitError(
508
- `Local source repo '${localBaseRepoPath}' moved on '${baseBranch}' from '${expectedBaseSha}' to '${actualBaseSha}' before finalization could continue. Retry finalization.`,
509
- );
510
- }
511
- }
512
-
513
- function mergeWorkBranchIntoLocalBaseRepo(input: {
514
- localBaseRepoPath: string;
515
- baseBranch: string;
516
- workBranch: string;
517
- expectedBaseSha: string;
518
- expectedHeadSha: string;
519
- }): void {
520
- assertLocalBaseRepoReady(input.localBaseRepoPath, input.baseBranch, input.expectedBaseSha);
521
- const mergeResult = runGit(input.localBaseRepoPath, [
522
- "merge",
523
- "--ff-only",
524
- `refs/heads/${input.workBranch}`,
525
- ]);
526
- if (!mergeResult.ok) {
527
- throw new DeterministicGitError(
528
- `Failed to fast-forward local source repo '${input.localBaseRepoPath}' branch '${input.baseBranch}' from '${input.workBranch}': ${trimToNull(mergeResult.stderr) ?? trimToNull(mergeResult.stdout) ?? "unknown git error"}`,
529
- );
530
- }
531
- const actualHeadSha = currentHeadSha(input.localBaseRepoPath);
532
- if (actualHeadSha !== input.expectedHeadSha) {
533
- throw new DeterministicGitError(
534
- `Local source repo '${input.localBaseRepoPath}' finished finalization at '${actualHeadSha}', but expected '${input.expectedHeadSha}' after merging '${input.workBranch}' into '${input.baseBranch}'`,
535
- );
536
- }
537
- }
538
-
539
- function updateLocalBaseRef(repoPath: string, baseBranch: string): void {
540
- const branch = currentBranch(repoPath);
541
- if (branch === baseBranch) {
542
- return;
543
- }
544
- const updateResult = runGit(repoPath, ["branch", "--force", baseBranch, "HEAD"]);
545
- if (!updateResult.ok) {
546
- throw new DeterministicGitError(
547
- `Failed to update the local '${baseBranch}' ref to the finalized HEAD: ${trimToNull(updateResult.stderr) ?? trimToNull(updateResult.stdout) ?? "unknown git error"}`,
548
- );
549
- }
550
- }
551
-
552
- function buildFinalizationMarkdown(input: {
553
- workspaceClonePath: string;
554
- baseBranch: string;
555
- workBranch: string;
556
- headSha: string;
557
- mergeMode: DeterministicFinalizationMergeMode;
558
- pushTarget: string;
559
- localSourceRepoPath: string | null;
560
- localSourceRepoKind: LocalSourceRepo["kind"] | null;
561
- workspacePushTarget: string | null;
562
- sourceOriginPushTarget: string | null;
563
- usedConflictResolution: boolean;
564
- }): string {
565
- const lines = [
566
- "## Finalized change",
567
- "",
568
- `- Repository workspace: ${input.workspaceClonePath}`,
569
- `- Work branch: ${input.workBranch}`,
570
- `- Base branch: ${input.baseBranch}`,
571
- `- Merge result: ${describeMergeMode(input.mergeMode)}`,
572
- ];
573
- if (input.localSourceRepoPath) {
574
- lines.push(
575
- `- Local source repo: ${input.localSourceRepoPath} (${input.localSourceRepoKind === "bare" ? "bare" : "non-bare"})`,
576
- );
577
- if (input.workspacePushTarget) {
578
- lines.push(`- Workspace publish: HEAD -> ${input.workspacePushTarget}`);
579
- }
580
- if (input.localSourceRepoKind === "non_bare") {
581
- lines.push(`- Base repo merge: ${input.workBranch} -> ${input.baseBranch}`);
582
- }
583
- if (input.sourceOriginPushTarget) {
584
- lines.push(
585
- `- Source origin push: ${branchRef(input.baseBranch)} -> ${input.sourceOriginPushTarget}`,
586
- );
587
- } else {
588
- lines.push("- Source origin push: skipped (local source repo has no origin remote)");
589
- }
590
- } else {
591
- lines.push(`- Pushed: HEAD -> ${input.pushTarget}`);
592
- }
593
- lines.push(
594
- `- Final HEAD: \`${abbreviateSha(input.headSha)}\``,
595
- `- Conflict resolution used: ${input.usedConflictResolution ? "yes" : "no"}`,
596
- );
597
- return lines.join("\n");
598
- }
599
-
600
- export interface RepositoryChangeFinalizationContextState extends StructuralProcessState {
601
- finalization: {
602
- expectedPostConflictHeadSha: string | null;
603
- usedConflictResolution: boolean;
604
- generatedCommitMessage: string | null;
605
- };
606
- }
607
-
608
- /** Commit the current workspace change and non-force push only the feature branch. */
609
- export function commitAndPushWorkBranch(input: {
610
- repoPath: string;
611
- workBranch: string;
612
- commitMessage: string;
613
- }) {
614
- const repoPath = path.resolve(input.repoPath);
615
- if (!repoExists(repoPath)) {
616
- throw new DeterministicGitError(
617
- `Repository workspace '${repoPath}' does not exist or is not a git repository`,
618
- );
619
- }
620
- assertExpectedCheckout(repoPath, input.workBranch);
621
- if (!trimToNull(input.commitMessage)) {
622
- throw new DeterministicGitError("A generated commit message is required before publication");
623
- }
624
- const conflicts = conflictedFiles(repoPath);
625
- if (mergeInProgress(repoPath) || conflicts.length > 0) {
626
- throw new DeterministicGitError(
627
- `Cannot publish a work branch with unresolved conflicts: ${conflicts.join(", ") || "merge in progress"}`,
628
- );
629
- }
630
- const dirty = workingTreeStatus(repoPath).dirtyFiles.length > 0;
631
- const headSha = dirty
632
- ? commitDirtyWorktree(repoPath, input.commitMessage)
633
- : currentHeadSha(repoPath);
634
- const pushTarget = pushHeadToBranch(repoPath, input.workBranch);
635
- const remoteHead = gitOrNull(
636
- repoPath,
637
- "ls-remote",
638
- "--heads",
639
- "origin",
640
- branchRef(input.workBranch),
641
- )
642
- ?.split(/\s+/)[0]
643
- ?.trim();
644
- if (remoteHead !== headSha) {
645
- throw new DeterministicGitError(
646
- `Published '${pushTarget}' resolved to '${remoteHead ?? "missing"}', expected '${headSha}'`,
647
- );
648
- }
649
- return { headSha, pushTarget };
650
- }
651
-
652
- export function runDeterministicFinalization<
653
- TParams,
654
- TState extends RepositoryChangeFinalizationContextState,
655
- >(ctx: FlowAutomaticRunContext<TParams, TState>): DeterministicFinalizationResult {
656
- const progressSteps = [
657
- ["validate_checkout", "Validate the repository checkout"],
658
- ["fetch_base", "Fetch and verify the latest base branch"],
659
- ["commit_merge", "Commit changes and integrate the base branch"],
660
- ["publish", "Push the finalized branch"],
661
- ] as const;
662
- const reportProgress = (
663
- activeIndex: number | null,
664
- completedCount: number,
665
- failure?: { index: number; detail: string },
666
- ) =>
667
- ctx.reportProgress({
668
- title: "Finalization progress",
669
- steps: progressSteps.map(([id, label], index) => ({
670
- id,
671
- label,
672
- status:
673
- index === failure?.index
674
- ? "failed"
675
- : index < completedCount
676
- ? "completed"
677
- : index === activeIndex
678
- ? "in_progress"
679
- : "incomplete",
680
- ...(index === failure?.index ? { detail: failure.detail } : {}),
681
- })),
682
- });
683
- reportProgress(0, 0);
684
- const repo = ctx.repo.get("repo");
685
- const input: DeterministicFinalizationInput = {
686
- repoPath: repo.fsPath,
687
- workspaceClonePath: repo.workspaceClonePath,
688
- baseBranch: repo.baseBranch,
689
- workBranch: repo.workBranch,
690
- expectedPostConflictHeadSha: ctx.state.finalization.expectedPostConflictHeadSha,
691
- usedConflictResolution: ctx.state.finalization.usedConflictResolution,
692
- commitMessage: ctx.state.finalization.generatedCommitMessage ?? "",
693
- };
694
- const repoPath = path.resolve(input.repoPath);
695
- if (!repoExists(repoPath)) {
696
- throw new DeterministicGitError(
697
- `Repository workspace '${repoPath}' does not exist or is not a git repository`,
698
- );
699
- }
700
- assertExpectedCheckout(repoPath, input.workBranch);
701
- if (!trimToNull(input.commitMessage)) {
702
- throw new DeterministicGitError(
703
- "No generated commit message is available; retry commit-message generation before finalization",
704
- );
705
- }
706
- assertPostConflictCheckpoint(input, repoPath);
707
- reportProgress(1, 1);
708
-
709
- let headSha = currentHeadSha(repoPath);
710
- const conflicts = conflictedFiles(repoPath);
711
- if (mergeInProgress(repoPath) || conflicts.length > 0) {
712
- reportProgress(null, 1, {
713
- index: 2,
714
- detail: "The checkout already contains merge conflicts",
715
- });
716
- return {
717
- outcome: "merge_conflict",
718
- params: {
719
- headSha,
720
- conflictedFiles: conflicts,
721
- fetchedBaseSha: null,
722
- },
723
- };
724
- }
725
-
726
- const baseSha = fetchOriginBase(repoPath, input.baseBranch);
727
- const localSourceRepo = resolveLocalSourceRepo(repoPath);
728
- if (localSourceRepo?.kind === "non_bare") {
729
- assertLocalBaseRepoReady(localSourceRepo.path, input.baseBranch, baseSha);
730
- } else if (localSourceRepo?.kind === "bare") {
731
- assertLocalBareSourceRepoReady(localSourceRepo.path, input.baseBranch, baseSha);
732
- }
733
- reportProgress(2, 2);
734
-
735
- const status = workingTreeStatus(repoPath);
736
- if (status.dirtyFiles.length > 0) {
737
- headSha = commitDirtyWorktree(repoPath, input.commitMessage);
738
- }
739
- const mergeResult = deterministicMerge({
740
- repoPath,
741
- baseBranch: input.baseBranch,
742
- headBefore: headSha,
743
- baseSha,
744
- });
745
- if (!mergeResult.ok) {
746
- reportProgress(null, 2, {
747
- index: 2,
748
- detail: "Base integration produced merge conflicts",
749
- });
750
- return {
751
- outcome: "merge_conflict",
752
- params: {
753
- headSha: mergeResult.headSha,
754
- conflictedFiles: mergeResult.conflictedFiles,
755
- fetchedBaseSha: baseSha,
756
- },
757
- };
758
- }
759
-
760
- reportProgress(3, 3);
761
- let pushTarget: string;
762
- let workspacePushTarget: string | null = null;
763
- let sourceOriginPushTarget: string | null = null;
764
- if (localSourceRepo?.kind === "non_bare") {
765
- assertLocalBaseRepoReady(localSourceRepo.path, input.baseBranch, baseSha);
766
- workspacePushTarget = pushHeadToBranch(repoPath, input.workBranch);
767
- mergeWorkBranchIntoLocalBaseRepo({
768
- localBaseRepoPath: localSourceRepo.path,
769
- baseBranch: input.baseBranch,
770
- workBranch: input.workBranch,
771
- expectedBaseSha: baseSha,
772
- expectedHeadSha: mergeResult.headSha,
773
- });
774
- sourceOriginPushTarget = pushLocalSourceBaseBranchToOriginIfPresent({
775
- localSourceRepoPath: localSourceRepo.path,
776
- baseBranch: input.baseBranch,
777
- expectedHeadSha: mergeResult.headSha,
778
- });
779
- pushTarget = sourceOriginPushTarget ?? originBaseRef(input.baseBranch);
780
- } else if (localSourceRepo?.kind === "bare") {
781
- assertLocalBareSourceRepoReady(localSourceRepo.path, input.baseBranch, baseSha);
782
- workspacePushTarget = pushHeadToBranch(repoPath, input.baseBranch);
783
- sourceOriginPushTarget = pushLocalSourceBaseBranchToOriginIfPresent({
784
- localSourceRepoPath: localSourceRepo.path,
785
- baseBranch: input.baseBranch,
786
- expectedHeadSha: mergeResult.headSha,
787
- });
788
- pushTarget = sourceOriginPushTarget ?? workspacePushTarget;
789
- } else {
790
- pushTarget = pushHeadToBranch(repoPath, input.baseBranch);
791
- }
792
- updateLocalBaseRef(repoPath, input.baseBranch);
793
- const finalHeadSha = currentHeadSha(repoPath);
794
- reportProgress(null, 4);
795
- return {
796
- outcome: "finalized",
797
- params: {
798
- headSha: finalHeadSha,
799
- mergeMode: mergeResult.mergeMode,
800
- pushTarget,
801
- usedConflictResolution: input.usedConflictResolution === true,
802
- },
803
- markdown: buildFinalizationMarkdown({
804
- workspaceClonePath: input.workspaceClonePath,
805
- baseBranch: input.baseBranch,
806
- workBranch: input.workBranch,
807
- headSha: finalHeadSha,
808
- mergeMode: mergeResult.mergeMode,
809
- pushTarget,
810
- localSourceRepoPath: localSourceRepo?.path ?? null,
811
- localSourceRepoKind: localSourceRepo?.kind ?? null,
812
- workspacePushTarget,
813
- sourceOriginPushTarget,
814
- usedConflictResolution: input.usedConflictResolution === true,
815
- }),
816
- };
817
- }
818
-
819
- export function readMergeMessage(repoPath: string): string | null {
820
- const messagePath = path.resolve(repoPath, git(repoPath, "rev-parse", "--git-dir"), "MERGE_MSG");
821
- if (!existsSync(messagePath)) {
822
- return null;
823
- }
824
- return trimToNull(readFileSync(messagePath, "utf8"));
825
- }
1
+ export type { GitIdentity } from "./finalization-git-internal.js";
2
+ export { commitAndPushWorkBranch } from "./finalization-git-internal.js";