@leitwerk-dev/coding 0.1.9 → 0.2.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 (38) hide show
  1. package/README.md +7 -2
  2. package/dist/auto-work-branch.js +86 -86
  3. package/dist/auto-work-branch.js.map +1 -1
  4. package/dist/{chunk-R3S5KR3J.js → chunk-73LKROYK.js} +135 -155
  5. package/dist/chunk-73LKROYK.js.map +1 -0
  6. package/dist/finalization-git.d.ts +6 -1
  7. package/dist/finalization-git.d.ts.map +1 -1
  8. package/dist/finalization-git.js +13 -593
  9. package/dist/finalization-git.js.map +1 -1
  10. package/dist/index.js +650 -6
  11. package/dist/index.js.map +1 -1
  12. package/dist/repository-change-launch.js +17 -182
  13. package/dist/repository-change-launch.js.map +1 -1
  14. package/dist/repository-change-process.d.ts.map +1 -1
  15. package/dist/repository-change-state.js +12 -51
  16. package/dist/repository-change-state.js.map +1 -1
  17. package/dist/turns/generate-commit-message.js +9 -38
  18. package/dist/turns/generate-commit-message.js.map +1 -1
  19. package/dist/turns/generate-plan.js +7 -19
  20. package/dist/turns/generate-plan.js.map +1 -1
  21. package/dist/turns/implement.js +7 -17
  22. package/dist/turns/implement.js.map +1 -1
  23. package/dist/turns/resolve-merge-conflict.js +7 -21
  24. package/dist/turns/resolve-merge-conflict.js.map +1 -1
  25. package/dist/turns/review-implementation.js +7 -25
  26. package/dist/turns/review-implementation.js.map +1 -1
  27. package/dist/turns/review-plan.js +7 -19
  28. package/dist/turns/review-plan.js.map +1 -1
  29. package/dist/turns/simplify-implementation.js +7 -7
  30. package/dist/turns/simplify-implementation.js.map +1 -1
  31. package/package.json +5 -4
  32. package/src/finalization-git.ts +170 -167
  33. package/src/repository-change-process.ts +81 -165
  34. package/dist/actions.js +0 -45
  35. package/dist/actions.js.map +0 -1
  36. package/dist/chunk-R3S5KR3J.js.map +0 -1
  37. package/dist/repository-change-process.js +0 -689
  38. package/dist/repository-change-process.js.map +0 -1
@@ -1,20 +1,8 @@
1
- export function buildReviewPlanPrompt(ctx) {
2
- return `Review the plan against this requested change:
3
- ${ctx.prompts.initial}
4
-
5
- Repository root: . (the current working directory)
6
-
7
- Plan:
8
- ${ctx.input.plan}
9
-
10
- Rules:
11
- - review the plan only; do not rewrite the plan
12
- - if you inspect repository files for context, read only inside the current working directory
13
- - use bash only for read-only inspection (e.g. git diff, git status, rg, tree, file listing, read-only http/CLI calls)
14
- - do not modify files, branches, commits, or git index state
15
- - do not read from or write to any original source repository path outside the process workspace
16
- - evaluate scope, sequencing, risks, and acceptance criteria
17
- - publish a short Markdown approval note when the plan is solid
18
- - publish concise, actionable Markdown feedback when the plan needs changes`;
19
- }
1
+ import {
2
+ buildReviewPlanPrompt
3
+ } from "../chunk-EP3ZC37F.js";
4
+ import "../chunk-PX6F3LHL.js";
5
+ export {
6
+ buildReviewPlanPrompt
7
+ };
20
8
  //# sourceMappingURL=review-plan.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"review-plan.js","sourceRoot":"","sources":["../../src/turns/review-plan.ts"],"names":[],"mappings":"AAEA,MAAM,UAAU,qBAAqB,CACpC,GAA+D;IAE/D,OAAO;EACN,GAAG,CAAC,OAAO,CAAC,OAAO;;;;;EAKnB,GAAG,CAAC,KAAK,CAAC,IAAI;;;;;;;;;;4EAU4D,CAAC;AAC7E,CAAC"}
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1,8 +1,8 @@
1
- export function buildSimplifyImplementationPrompt(_ctx) {
2
- return `Repository root: . (the current working directory)
3
-
4
- Find worthwhile ways to simplify the current implementation and nearby code, reducing lines without reducing clarity or behavior. If the implementation is already appropriately simple, say so.
5
-
6
- Inspect the repository read-only and publish a concise simplification plan. Do not modify any files.`;
7
- }
1
+ import {
2
+ buildSimplifyImplementationPrompt
3
+ } from "../chunk-OFDNIT5X.js";
4
+ import "../chunk-PX6F3LHL.js";
5
+ export {
6
+ buildSimplifyImplementationPrompt
7
+ };
8
8
  //# sourceMappingURL=simplify-implementation.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"simplify-implementation.js","sourceRoot":"","sources":["../../src/turns/simplify-implementation.ts"],"names":[],"mappings":"AAEA,MAAM,UAAU,iCAAiC,CAChD,IAAwD;IAExD,OAAO;;;;qGAI6F,CAAC;AACtG,CAAC"}
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leitwerk-dev/coding",
3
- "version": "0.1.9",
3
+ "version": "0.2.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/leitwerk-dev/leitwerk.git",
@@ -50,10 +50,11 @@
50
50
  "build": "tsup --silent"
51
51
  },
52
52
  "dependencies": {
53
- "@leitwerk-dev/domain": "0.1.9",
54
- "@leitwerk-dev/process-sdk": "0.1.9"
53
+ "@leitwerk-dev/domain": "0.2.0",
54
+ "@leitwerk-dev/process-sdk": "0.2.0"
55
55
  },
56
56
  "devDependencies": {
57
+ "@leitwerk-dev/test-support": "0.2.0",
57
58
  "tsup": "^8.5.1"
58
59
  },
59
60
  "license": "Apache-2.0",
@@ -61,7 +62,7 @@
61
62
  "access": "public"
62
63
  },
63
64
  "engines": {
64
- "node": ">=22"
65
+ "node": ">=26 <27"
65
66
  },
66
67
  "files": [
67
68
  "dist/**",
@@ -14,6 +14,11 @@ import { resolveGitBinary } from "@leitwerk-dev/process-sdk/git-binary";
14
14
 
15
15
  export type DeterministicFinalizationMergeMode = "noop" | "fast_forward" | "merge_commit";
16
16
 
17
+ export interface GitIdentity {
18
+ name: string;
19
+ email: string;
20
+ }
21
+
17
22
  interface DeterministicFinalizationInput {
18
23
  repoPath: string;
19
24
  workspaceClonePath: string;
@@ -22,6 +27,7 @@ interface DeterministicFinalizationInput {
22
27
  expectedPostConflictHeadSha?: string | null;
23
28
  usedConflictResolution?: boolean;
24
29
  commitMessage: string;
30
+ gitIdentity?: GitIdentity;
25
31
  }
26
32
 
27
33
  export type DeterministicFinalizationResult =
@@ -57,7 +63,6 @@ interface GitExecResult {
57
63
  ok: boolean;
58
64
  stdout: string;
59
65
  stderr: string;
60
- status: number | null;
61
66
  }
62
67
 
63
68
  interface LocalSourceRepo {
@@ -106,9 +111,19 @@ function gitConfigIdentityEnv(): NodeJS.ProcessEnv {
106
111
  return env;
107
112
  }
108
113
 
109
- function runGit(repoPath: string, args: readonly string[]): GitExecResult {
114
+ function gitIdentityArgs(identity: GitIdentity): string[] {
115
+ const name = trimToNull(identity.name);
116
+ const email = trimToNull(identity.email);
117
+ if (!name || !email || /[\r\n\0]/.test(name) || /[\r\n\0]/.test(email)) {
118
+ throw new DeterministicGitError("Git identity requires a valid name and email");
119
+ }
120
+ return ["-c", `user.name=${name}`, "-c", `user.email=${email}`];
121
+ }
122
+
123
+ function runGit(repoPath: string, args: readonly string[], identity?: GitIdentity): GitExecResult {
124
+ const trustedArgs = identity ? [...gitIdentityArgs(identity), ...args] : args;
110
125
  try {
111
- const stdout = execFileSync(resolveGitBinary(), repositoryGitArgs(args), {
126
+ const stdout = execFileSync(resolveGitBinary(), repositoryGitArgs(trustedArgs), {
112
127
  cwd: repoPath,
113
128
  encoding: "utf8",
114
129
  env: gitConfigIdentityEnv(),
@@ -118,42 +133,40 @@ function runGit(repoPath: string, args: readonly string[]): GitExecResult {
118
133
  ok: true,
119
134
  stdout,
120
135
  stderr: "",
121
- status: 0,
122
136
  };
123
137
  } catch (error) {
124
138
  const execError = error as {
125
- status?: number | null;
126
139
  stdout?: string | Buffer;
127
140
  stderr?: string | Buffer;
128
141
  message?: string;
129
142
  };
130
143
  return {
131
144
  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
+ stdout: execError.stdout?.toString() ?? "",
146
+ stderr: execError.stderr?.toString() ?? trimToNull(execError.message) ?? "",
145
147
  };
146
148
  }
147
149
  }
148
150
 
149
- function git(repoPath: string, ...args: string[]): string {
150
- const result = runGit(repoPath, args);
151
+ function gitFailureDetail(result: GitExecResult): string {
152
+ return trimToNull(result.stderr) ?? trimToNull(result.stdout) ?? "unknown git error";
153
+ }
154
+
155
+ function checkedGit(
156
+ repoPath: string,
157
+ args: readonly string[],
158
+ failureMessage: string,
159
+ identity?: GitIdentity,
160
+ ): string {
161
+ const result = runGit(repoPath, args, identity);
151
162
  if (!result.ok) {
152
- throw new DeterministicGitError(
153
- `git ${args.join(" ")} failed in '${repoPath}': ${trimToNull(result.stderr) ?? trimToNull(result.stdout) ?? "unknown git error"}`,
154
- );
163
+ throw new DeterministicGitError(`${failureMessage}: ${gitFailureDetail(result)}`);
155
164
  }
156
- return result.stdout.trim();
165
+ return result.stdout;
166
+ }
167
+
168
+ function git(repoPath: string, ...args: string[]): string {
169
+ return checkedGit(repoPath, args, `git ${args.join(" ")} failed in '${repoPath}'`).trim();
157
170
  }
158
171
 
159
172
  function gitOrNull(repoPath: string, ...args: string[]): string | null {
@@ -232,15 +245,14 @@ function resolveLocalSourceRepo(repoPath: string): LocalSourceRepo | null {
232
245
  };
233
246
  }
234
247
 
235
- function workingTreeStatus(repoPath: string): { dirtyFiles: string[] } {
248
+ function workingTreeStatus(repoPath: string): string[] {
236
249
  const rawStatus = gitOrNull(repoPath, "status", "--porcelain");
237
- const dirtyFiles = (rawStatus ?? "")
250
+ return (rawStatus ?? "")
238
251
  .split(/\r?\n/)
239
252
  .map((line) => line.replace(/\s+$/, ""))
240
253
  .filter((line) => line !== "")
241
254
  .map((line) => line.slice(2).trim())
242
255
  .filter((line) => line !== "");
243
- return { dirtyFiles };
244
256
  }
245
257
 
246
258
  function conflictedFiles(repoPath: string): string[] {
@@ -265,46 +277,66 @@ function assertExpectedCheckout(repoPath: string, workBranch: string): void {
265
277
  }
266
278
  }
267
279
 
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) {
280
+ function assertFinalizationCheckout(input: {
281
+ repoPath: string;
282
+ workBranch: string;
283
+ commitMessage: string;
284
+ missingCommitMessage: string;
285
+ }): void {
286
+ if (!repoExists(input.repoPath)) {
272
287
  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.",
288
+ `Repository workspace '${input.repoPath}' does not exist or is not a git repository`,
274
289
  );
275
290
  }
291
+ assertExpectedCheckout(input.repoPath, input.workBranch);
292
+ if (!trimToNull(input.commitMessage)) {
293
+ throw new DeterministicGitError(input.missingCommitMessage);
294
+ }
276
295
  }
277
296
 
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) {
297
+ function assertGitIdentity(repoPath: string, identity?: GitIdentity): void {
298
+ const author = runGit(repoPath, ["var", "GIT_AUTHOR_IDENT"], identity);
299
+ const committer = runGit(repoPath, ["var", "GIT_COMMITTER_IDENT"], identity);
300
+ if (!author.ok || !committer.ok) {
295
301
  throw new DeterministicGitError(
296
- `Failed to commit the completed change: ${trimToNull(commitResult.stderr) ?? trimToNull(commitResult.stdout) ?? "unknown git error"}`,
302
+ "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.",
297
303
  );
298
304
  }
305
+ }
306
+
307
+ function commitDirtyWorktree(
308
+ repoPath: string,
309
+ commitMessage: string,
310
+ identity?: GitIdentity,
311
+ ): string {
312
+ assertGitIdentity(repoPath, identity);
313
+ checkedGit(repoPath, ["add", "--all"], "Failed to stage the completed change");
314
+ checkedGit(
315
+ repoPath,
316
+ ["-c", "core.hooksPath=/dev/null", "commit", "--no-gpg-sign", "-m", commitMessage],
317
+ "Failed to commit the completed change",
318
+ identity,
319
+ );
299
320
  const remaining = workingTreeStatus(repoPath);
300
- if (remaining.dirtyFiles.length > 0) {
321
+ if (remaining.length > 0) {
301
322
  throw new DeterministicGitError(
302
- `Deterministic commit left uncommitted changes: ${remaining.dirtyFiles.join(", ")}`,
323
+ `Deterministic commit left uncommitted changes: ${remaining.join(", ")}`,
303
324
  );
304
325
  }
305
326
  return currentHeadSha(repoPath);
306
327
  }
307
328
 
329
+ function commitIfDirty(input: {
330
+ repoPath: string;
331
+ commitMessage: string;
332
+ gitIdentity?: GitIdentity;
333
+ }): string {
334
+ const status = workingTreeStatus(input.repoPath);
335
+ return status.length > 0
336
+ ? commitDirtyWorktree(input.repoPath, input.commitMessage, input.gitIdentity)
337
+ : currentHeadSha(input.repoPath);
338
+ }
339
+
308
340
  function assertPostConflictCheckpoint(
309
341
  input: DeterministicFinalizationInput,
310
342
  repoPath: string,
@@ -318,21 +350,16 @@ function assertPostConflictCheckpoint(
318
350
  );
319
351
  }
320
352
  const status = workingTreeStatus(repoPath);
321
- if (status.dirtyFiles.length > 0) {
353
+ if (status.length > 0) {
322
354
  throw new DeterministicGitError(
323
- `Conflict-resolution helper reported a clean merge, but the repository still has uncommitted changes: ${status.dirtyFiles.join(", ")}`,
355
+ `Conflict-resolution helper reported a clean merge, but the repository still has uncommitted changes: ${status.join(", ")}`,
324
356
  );
325
357
  }
326
358
  }
327
359
 
328
360
  function fetchOriginBase(repoPath: string, baseBranch: string): string {
329
361
  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
- }
362
+ checkedGit(repoPath, ["fetch", "origin", baseBranch], `Failed to fetch '${ref}'`);
336
363
  const baseSha = gitOrNull(repoPath, "rev-parse", ref);
337
364
  if (!baseSha) {
338
365
  throw new DeterministicGitError(`Fetched '${ref}' but could not resolve its commit sha`);
@@ -349,6 +376,7 @@ function deterministicMerge(input: {
349
376
  baseBranch: string;
350
377
  headBefore: string;
351
378
  baseSha: string;
379
+ gitIdentity?: GitIdentity;
352
380
  }):
353
381
  | { ok: true; mergeMode: DeterministicFinalizationMergeMode; headSha: string }
354
382
  | { ok: false; conflict: true; headSha: string; conflictedFiles: string[] } {
@@ -362,12 +390,7 @@ function deterministicMerge(input: {
362
390
  }
363
391
 
364
392
  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
- }
393
+ checkedGit(repoPath, ["merge", "--ff-only", ref], `Fast-forward merge from '${ref}' failed`);
371
394
  return {
372
395
  ok: true,
373
396
  mergeMode: "fast_forward",
@@ -375,15 +398,12 @@ function deterministicMerge(input: {
375
398
  };
376
399
  }
377
400
 
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
- ]);
401
+ assertGitIdentity(repoPath, input.gitIdentity);
402
+ const mergeResult = runGit(
403
+ repoPath,
404
+ ["-c", "core.hooksPath=/dev/null", "merge", "--no-edit", "--no-gpg-sign", ref],
405
+ input.gitIdentity,
406
+ );
387
407
  if (!mergeResult.ok) {
388
408
  const conflicts = conflictedFiles(repoPath);
389
409
  if (mergeInProgress(repoPath) || conflicts.length > 0) {
@@ -395,7 +415,7 @@ function deterministicMerge(input: {
395
415
  };
396
416
  }
397
417
  throw new DeterministicGitError(
398
- `Deterministic merge from '${ref}' failed: ${trimToNull(mergeResult.stderr) ?? trimToNull(mergeResult.stdout) ?? "unknown git error"}`,
418
+ `Deterministic merge from '${ref}' failed: ${gitFailureDetail(mergeResult)}`,
399
419
  );
400
420
  }
401
421
 
@@ -411,12 +431,19 @@ function branchRef(branch: string): string {
411
431
  return `refs/heads/${branch}`;
412
432
  }
413
433
 
414
- function pushHeadToBranch(repoPath: string, branch: string): string {
434
+ function pushAndVerify(repoPath: string, branch: string, expectedHeadSha: string): string {
415
435
  const pushTarget = `origin/${branch}`;
416
- const pushResult = runGit(repoPath, ["push", "origin", `HEAD:${branchRef(branch)}`]);
417
- if (!pushResult.ok) {
436
+ checkedGit(
437
+ repoPath,
438
+ ["push", "origin", `HEAD:${branchRef(branch)}`],
439
+ `Failed to push HEAD to '${pushTarget}'`,
440
+ );
441
+ const remoteHead = gitOrNull(repoPath, "ls-remote", "--heads", "origin", branchRef(branch))
442
+ ?.split(/\s+/)[0]
443
+ ?.trim();
444
+ if (remoteHead !== expectedHeadSha) {
418
445
  throw new DeterministicGitError(
419
- `Failed to push HEAD to '${pushTarget}': ${trimToNull(pushResult.stderr) ?? trimToNull(pushResult.stdout) ?? "unknown git error"}`,
446
+ `Published '${pushTarget}' resolved to '${remoteHead ?? "missing"}', expected '${expectedHeadSha}'`,
420
447
  );
421
448
  }
422
449
  return pushTarget;
@@ -471,12 +498,11 @@ function pushLocalSourceBaseBranchToOriginIfPresent(input: {
471
498
  });
472
499
  const ref = branchRef(input.baseBranch);
473
500
  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
- }
501
+ checkedGit(
502
+ input.localSourceRepoPath,
503
+ ["push", "origin", `${ref}:${ref}`],
504
+ `Failed to push local source repo '${input.localSourceRepoPath}' base branch '${input.baseBranch}' to '${pushTarget}'`,
505
+ );
480
506
  return pushTarget;
481
507
  }
482
508
 
@@ -497,9 +523,9 @@ function assertLocalBaseRepoReady(
497
523
  );
498
524
  }
499
525
  const status = workingTreeStatus(localBaseRepoPath);
500
- if (status.dirtyFiles.length > 0) {
526
+ if (status.length > 0) {
501
527
  throw new DeterministicGitError(
502
- `Local source repo '${localBaseRepoPath}' must be clean before finalization updates '${baseBranch}': ${status.dirtyFiles.join(", ")}`,
528
+ `Local source repo '${localBaseRepoPath}' must be clean before finalization updates '${baseBranch}': ${status.join(", ")}`,
503
529
  );
504
530
  }
505
531
  const actualBaseSha = currentHeadSha(localBaseRepoPath);
@@ -518,16 +544,11 @@ function mergeWorkBranchIntoLocalBaseRepo(input: {
518
544
  expectedHeadSha: string;
519
545
  }): void {
520
546
  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
- }
547
+ checkedGit(
548
+ input.localBaseRepoPath,
549
+ ["merge", "--ff-only", `refs/heads/${input.workBranch}`],
550
+ `Failed to fast-forward local source repo '${input.localBaseRepoPath}' branch '${input.baseBranch}' from '${input.workBranch}'`,
551
+ );
531
552
  const actualHeadSha = currentHeadSha(input.localBaseRepoPath);
532
553
  if (actualHeadSha !== input.expectedHeadSha) {
533
554
  throw new DeterministicGitError(
@@ -541,12 +562,11 @@ function updateLocalBaseRef(repoPath: string, baseBranch: string): void {
541
562
  if (branch === baseBranch) {
542
563
  return;
543
564
  }
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
- }
565
+ checkedGit(
566
+ repoPath,
567
+ ["branch", "--force", baseBranch, "HEAD"],
568
+ `Failed to update the local '${baseBranch}' ref to the finalized HEAD`,
569
+ );
550
570
  }
551
571
 
552
572
  function buildFinalizationMarkdown(input: {
@@ -610,49 +630,37 @@ export function commitAndPushWorkBranch(input: {
610
630
  repoPath: string;
611
631
  workBranch: string;
612
632
  commitMessage: string;
633
+ gitIdentity: GitIdentity;
613
634
  }) {
614
635
  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
- }
636
+ assertFinalizationCheckout({
637
+ repoPath,
638
+ workBranch: input.workBranch,
639
+ commitMessage: input.commitMessage,
640
+ missingCommitMessage: "A generated commit message is required before publication",
641
+ });
624
642
  const conflicts = conflictedFiles(repoPath);
625
643
  if (mergeInProgress(repoPath) || conflicts.length > 0) {
626
644
  throw new DeterministicGitError(
627
645
  `Cannot publish a work branch with unresolved conflicts: ${conflicts.join(", ") || "merge in progress"}`,
628
646
  );
629
647
  }
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(
648
+ const headSha = commitIfDirty({
636
649
  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
- }
650
+ commitMessage: input.commitMessage,
651
+ gitIdentity: input.gitIdentity,
652
+ });
653
+ const pushTarget = pushAndVerify(repoPath, input.workBranch, headSha);
649
654
  return { headSha, pushTarget };
650
655
  }
651
656
 
652
657
  export function runDeterministicFinalization<
653
658
  TParams,
654
659
  TState extends RepositoryChangeFinalizationContextState,
655
- >(ctx: FlowAutomaticRunContext<TParams, TState>): DeterministicFinalizationResult {
660
+ >(
661
+ ctx: FlowAutomaticRunContext<TParams, TState>,
662
+ gitIdentity?: GitIdentity,
663
+ ): DeterministicFinalizationResult {
656
664
  const progressSteps = [
657
665
  ["validate_checkout", "Validate the repository checkout"],
658
666
  ["fetch_base", "Fetch and verify the latest base branch"],
@@ -664,7 +672,7 @@ export function runDeterministicFinalization<
664
672
  completedCount: number,
665
673
  failure?: { index: number; detail: string },
666
674
  ) =>
667
- ctx.reportProgress({
675
+ ctx.reportProgress?.({
668
676
  title: "Finalization progress",
669
677
  steps: progressSteps.map(([id, label], index) => ({
670
678
  id,
@@ -690,19 +698,16 @@ export function runDeterministicFinalization<
690
698
  expectedPostConflictHeadSha: ctx.state.finalization.expectedPostConflictHeadSha,
691
699
  usedConflictResolution: ctx.state.finalization.usedConflictResolution,
692
700
  commitMessage: ctx.state.finalization.generatedCommitMessage ?? "",
701
+ gitIdentity,
693
702
  };
694
703
  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(
704
+ assertFinalizationCheckout({
705
+ repoPath,
706
+ workBranch: input.workBranch,
707
+ commitMessage: input.commitMessage,
708
+ missingCommitMessage:
703
709
  "No generated commit message is available; retry commit-message generation before finalization",
704
- );
705
- }
710
+ });
706
711
  assertPostConflictCheckpoint(input, repoPath);
707
712
  reportProgress(1, 1);
708
713
 
@@ -732,15 +737,17 @@ export function runDeterministicFinalization<
732
737
  }
733
738
  reportProgress(2, 2);
734
739
 
735
- const status = workingTreeStatus(repoPath);
736
- if (status.dirtyFiles.length > 0) {
737
- headSha = commitDirtyWorktree(repoPath, input.commitMessage);
738
- }
740
+ headSha = commitIfDirty({
741
+ repoPath,
742
+ commitMessage: input.commitMessage,
743
+ gitIdentity: input.gitIdentity,
744
+ });
739
745
  const mergeResult = deterministicMerge({
740
746
  repoPath,
741
747
  baseBranch: input.baseBranch,
742
748
  headBefore: headSha,
743
749
  baseSha,
750
+ gitIdentity: input.gitIdentity,
744
751
  });
745
752
  if (!mergeResult.ok) {
746
753
  reportProgress(null, 2, {
@@ -761,33 +768,29 @@ export function runDeterministicFinalization<
761
768
  let pushTarget: string;
762
769
  let workspacePushTarget: string | null = null;
763
770
  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
- });
771
+ if (localSourceRepo) {
772
+ if (localSourceRepo.kind === "non_bare") {
773
+ assertLocalBaseRepoReady(localSourceRepo.path, input.baseBranch, baseSha);
774
+ workspacePushTarget = pushAndVerify(repoPath, input.workBranch, mergeResult.headSha);
775
+ mergeWorkBranchIntoLocalBaseRepo({
776
+ localBaseRepoPath: localSourceRepo.path,
777
+ baseBranch: input.baseBranch,
778
+ workBranch: input.workBranch,
779
+ expectedBaseSha: baseSha,
780
+ expectedHeadSha: mergeResult.headSha,
781
+ });
782
+ } else {
783
+ assertLocalBareSourceRepoReady(localSourceRepo.path, input.baseBranch, baseSha);
784
+ workspacePushTarget = pushAndVerify(repoPath, input.baseBranch, mergeResult.headSha);
785
+ }
774
786
  sourceOriginPushTarget = pushLocalSourceBaseBranchToOriginIfPresent({
775
787
  localSourceRepoPath: localSourceRepo.path,
776
788
  baseBranch: input.baseBranch,
777
789
  expectedHeadSha: mergeResult.headSha,
778
790
  });
779
791
  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
792
  } else {
790
- pushTarget = pushHeadToBranch(repoPath, input.baseBranch);
793
+ pushTarget = pushAndVerify(repoPath, input.baseBranch, mergeResult.headSha);
791
794
  }
792
795
  updateLocalBaseRef(repoPath, input.baseBranch);
793
796
  const finalHeadSha = currentHeadSha(repoPath);