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