@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
@@ -3,14 +3,6 @@ import { parseStructuralProcessState } from "@leitwerk-dev/process-sdk";
3
3
 
4
4
  /** @public */
5
5
  export interface RepositoryChangeFinalizationState {
6
- /** @internal */
7
- expectedPostConflictHeadSha: string | null;
8
- /** @internal */
9
- usedConflictResolution: boolean;
10
- /** @internal */
11
- finalizationSummaryMarkdown: string | null;
12
- /** @internal */
13
- finalizedHeadSha: string | null;
14
6
  /** @public */
15
7
  generatedCommitMessage: string | null;
16
8
  }
@@ -19,19 +11,14 @@ export interface RepositoryChangeFinalizationState {
19
11
  export interface RepositoryChangeState extends StructuralProcessState {
20
12
  /** @public */
21
13
  finalization: RepositoryChangeFinalizationState;
22
- /** Namespaced state owned by a caller-supplied publication workflow. @public */
14
+ /** Namespaced state owned by a caller-supplied publication workflow. */
15
+ /** @public */
23
16
  extensionState?: Record<string, unknown>;
24
17
  }
25
18
 
26
19
  /** @internal */
27
20
  export function createEmptyRepositoryChangeFinalizationState(): RepositoryChangeFinalizationState {
28
- return {
29
- expectedPostConflictHeadSha: null,
30
- usedConflictResolution: false,
31
- finalizationSummaryMarkdown: null,
32
- finalizedHeadSha: null,
33
- generatedCommitMessage: null,
34
- };
21
+ return { generatedCommitMessage: null };
35
22
  }
36
23
 
37
24
  function stringOrNull(value: unknown): string | null {
@@ -44,14 +31,7 @@ function toRecord(value: unknown): Record<string, unknown> {
44
31
 
45
32
  function parseFinalizationState(value: unknown): RepositoryChangeFinalizationState {
46
33
  const record = toRecord(value);
47
- return {
48
- expectedPostConflictHeadSha: stringOrNull(record.expectedPostConflictHeadSha),
49
- usedConflictResolution: record.usedConflictResolution === true,
50
- finalizationSummaryMarkdown: stringOrNull(record.finalizationSummaryMarkdown),
51
- finalizedHeadSha: stringOrNull(record.finalizedHeadSha),
52
- // Backward-compatible decoding for state persisted before commit-message generation.
53
- generatedCommitMessage: stringOrNull(record.generatedCommitMessage),
54
- };
34
+ return { generatedCommitMessage: stringOrNull(record.generatedCommitMessage) };
55
35
  }
56
36
 
57
37
  /** @internal */
@@ -78,13 +58,3 @@ export function clearReviewRefs(
78
58
  review: null,
79
59
  };
80
60
  }
81
-
82
- /** @internal */
83
- export function resetRepositoryChangeFinalizationState(
84
- overrides: Partial<RepositoryChangeFinalizationState> = {},
85
- ): RepositoryChangeFinalizationState {
86
- return {
87
- ...createEmptyRepositoryChangeFinalizationState(),
88
- ...overrides,
89
- };
90
- }
@@ -1,2 +1 @@
1
1
  export type { RepositoryChangeState } from "./repository-change-state-internal.js";
2
- export { resetRepositoryChangeFinalizationState } from "./repository-change-state-internal.js";
@@ -0,0 +1,225 @@
1
+ import { trimString } from "@leitwerk-dev/domain";
2
+ import {
3
+ type LauncherValidationError,
4
+ type LaunchPreparationCheck,
5
+ type ProcessLaunchConfig,
6
+ type ProcessLauncherDefinition,
7
+ type RepositoryIssue,
8
+ type RepositoryIssueWatcherConfig,
9
+ SafeLaunchPreparationError,
10
+ } from "@leitwerk-dev/process-sdk";
11
+ import { buildAutoWorkBranchFromSeed } from "./auto-work-branch.js";
12
+
13
+ /** Recheck provider-owned repository visibility before launch. @internal */
14
+ export function repositoryVisibilityCheck(
15
+ provider: string,
16
+ isVisible: () => Promise<boolean>,
17
+ ): LaunchPreparationCheck {
18
+ return {
19
+ id: "repository_visibility",
20
+ label: "Check repository visibility",
21
+ async run({ signal }) {
22
+ signal.throwIfAborted();
23
+ const visible = await isVisible();
24
+ signal.throwIfAborted();
25
+ if (!visible)
26
+ throw new SafeLaunchPreparationError(
27
+ "Repository is not visible",
28
+ `Grant the selected ${provider} profile access to the repository, then try again.`,
29
+ );
30
+ },
31
+ };
32
+ }
33
+
34
+ /** Shared UI mechanics; providers retain credentials, preparation and launch metadata. @internal */
35
+ export function createRepositoryChangeUiLauncher<
36
+ P,
37
+ R extends {
38
+ /** @internal */
39
+ full_name: string;
40
+ /** @internal */
41
+ html_url: string;
42
+ /** @internal */
43
+ ssh_url: string;
44
+ /** @internal */
45
+ default_branch: string;
46
+ },
47
+ B,
48
+ I,
49
+ >(options: {
50
+ /** @internal */
51
+ id: string;
52
+ /** @internal */
53
+ provider: string;
54
+ /** @internal */
55
+ providerId: string;
56
+ /** @internal */
57
+ assertConfigured(): void;
58
+ /** @internal */
59
+ profiles(): readonly string[];
60
+ /** @internal */
61
+ repositories(profile: string): Promise<readonly R[]>;
62
+ /** @internal */
63
+ resolveProfiles(profile: string): B;
64
+ /** @internal */
65
+ resolveGitIdentity(profile: string): Promise<I>;
66
+ /** @internal */
67
+ params(
68
+ repository: R,
69
+ input: B & {
70
+ /** @internal */
71
+ profile: string;
72
+ /** @internal */
73
+ prompt: string;
74
+ /** @internal */
75
+ workBranch: string;
76
+ },
77
+ ): P;
78
+ /** @internal */
79
+ launchConfig(params: P, title: string, identity: I): ProcessLaunchConfig<P>;
80
+ /** @internal */
81
+ preparationChecks: NonNullable<ProcessLauncherDefinition<P>["ui"]>["preparationChecks"];
82
+ }): ProcessLauncherDefinition<P> & {
83
+ /** Resolve issue launches using the same provider wiring as UI launches. @internal */
84
+ resolveIssueLaunchConfig(event: {
85
+ /** @internal */ profile: string;
86
+ /** @internal */ repository: R;
87
+ /** @internal */ issue: Pick<RepositoryIssue, "number" | "title" | "body" | "html_url">;
88
+ /** @internal */ labels: RepositoryIssueWatcherConfig["labels"];
89
+ }): Promise<ProcessLaunchConfig<P>>;
90
+ } {
91
+ const { provider, providerId } = options;
92
+ const profileField = `${providerId}Profile`;
93
+ function validationError(
94
+ fieldId: string,
95
+ message: string,
96
+ code: LauncherValidationError["code"] = "required",
97
+ ): LauncherValidationError {
98
+ return { code, fieldId, message };
99
+ }
100
+ return {
101
+ async resolveIssueLaunchConfig({ profile, repository, issue, labels }) {
102
+ const title = issue.title.trim();
103
+ const body = issue.body?.trim() ?? "";
104
+ const binding = options.resolveProfiles(profile);
105
+ const identity = await options.resolveGitIdentity(profile);
106
+ return options.launchConfig(
107
+ {
108
+ ...options.params(repository, {
109
+ ...binding,
110
+ profile,
111
+ workBranch: `leitwerk/issue-${issue.number}`,
112
+ prompt: `${title}${body ? `\n\n${body}` : ""}`,
113
+ }),
114
+ origin: "issue",
115
+ issueNumber: issue.number,
116
+ issueUrl: issue.html_url,
117
+ triggerLabel: labels.trigger,
118
+ doneLabel: labels.done,
119
+ },
120
+ title,
121
+ identity,
122
+ );
123
+ },
124
+ id: options.id,
125
+ label: `${provider} Repo Change`,
126
+ description: `Plan, implement, review, and publish a ${provider} change without a source issue`,
127
+ visibility: "ui",
128
+ ui: {
129
+ card: {
130
+ title: `${provider} Repo Change`,
131
+ description: `Start a repository change and publish it as a ${provider} pull request.`,
132
+ },
133
+ launchConfigSchema: {
134
+ id: `${providerId}_repo_change_form`,
135
+ title: `${provider} Repo Change`,
136
+ fields: [
137
+ {
138
+ id: profileField,
139
+ label: `${provider} profile`,
140
+ kind: "select",
141
+ required: true,
142
+ description: `${provider} profile with server-configured CI and Git SSH access.`,
143
+ },
144
+ {
145
+ id: "repository",
146
+ label: "Repository",
147
+ kind: "select",
148
+ required: true,
149
+ description: `Repository visible to the selected ${provider} profile.`,
150
+ },
151
+ {
152
+ id: "prompt",
153
+ label: "Requested change",
154
+ kind: "textarea",
155
+ required: true,
156
+ placeholder: "Describe the change to plan, implement, review, and publish.",
157
+ },
158
+ ],
159
+ submitLabel: "Start change",
160
+ },
161
+ resolveDefaults() {
162
+ return { [profileField]: options.profiles()[0] ?? "", repository: "", prompt: "" };
163
+ },
164
+ async resolveOptions(input) {
165
+ const profile = trimString(input[profileField]);
166
+ return {
167
+ [profileField]: options.profiles().map((value) => ({ value, label: value })),
168
+ repository: (await options.repositories(profile)).map((repository) => ({
169
+ value: repository.full_name,
170
+ label: repository.full_name,
171
+ description: repository.html_url,
172
+ })),
173
+ };
174
+ },
175
+ preparationChecks: options.preparationChecks,
176
+ resolveRelaunchInput(input) {
177
+ return {
178
+ [profileField]: trimString(input[profileField]),
179
+ repository: trimString(input.repository),
180
+ prompt: trimString(input.prompt),
181
+ };
182
+ },
183
+ async resolveLaunchConfig(input) {
184
+ const profile = trimString(input[profileField]);
185
+ const repositoryName = trimString(input.repository);
186
+ const prompt = trimString(input.prompt);
187
+ const errors: LauncherValidationError[] = [];
188
+ const invalid = (fieldId: string, message: string) => ({
189
+ ok: false as const,
190
+ errors: [validationError(fieldId, message, "custom_rule")],
191
+ });
192
+ options.assertConfigured();
193
+ if (!profile) errors.push(validationError(profileField, `${provider} profile is required`));
194
+ else if (!options.profiles().includes(profile))
195
+ errors.push(
196
+ validationError(profileField, `${provider} profile is not available`, "custom_rule"),
197
+ );
198
+ if (!repositoryName) errors.push(validationError("repository", "Repository is required"));
199
+ if (!prompt) errors.push(validationError("prompt", "Requested change is required"));
200
+ if (errors.length > 0) return { ok: false, errors };
201
+ const repository = (await options.repositories(profile)).find(
202
+ (candidate) => candidate.full_name === repositoryName,
203
+ );
204
+ if (!repository)
205
+ return invalid(
206
+ "repository",
207
+ `Repository is not available to the selected ${provider} profile`,
208
+ );
209
+ let binding: B;
210
+ try {
211
+ binding = options.resolveProfiles(profile);
212
+ } catch (error) {
213
+ return invalid(profileField, (error as Error).message);
214
+ }
215
+ const identity = await options.resolveGitIdentity(profile);
216
+ const workBranch = buildAutoWorkBranchFromSeed(
217
+ prompt,
218
+ `${repository.ssh_url}:${repository.default_branch}`,
219
+ );
220
+ const params = options.params(repository, { ...binding, profile, prompt, workBranch });
221
+ return { ok: true, launchConfig: options.launchConfig(params, prompt, identity) };
222
+ },
223
+ },
224
+ };
225
+ }
@@ -0,0 +1,219 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { repositoryGitArgs, repositoryGitSubprocessEnv } from "@leitwerk-dev/process-sdk";
5
+ import { resolveGitBinary } from "@leitwerk-dev/process-sdk/git-binary";
6
+
7
+ import { type ConflictEvidence, conflictKey } from "./index.js";
8
+ import {
9
+ type RebaseRecord,
10
+ rebasePublicationDecision,
11
+ requireRebaseHead,
12
+ requireRebaseOrigin,
13
+ requireRebaseTarget,
14
+ requireRebaseWorktree,
15
+ } from "./policy.js";
16
+
17
+ /** @internal */
18
+ export interface RebaseInput {
19
+ /** @internal */
20
+ projectKey: string;
21
+ /** @internal */
22
+ path: string;
23
+ /** @internal */
24
+ workBranch: string;
25
+ /** @internal */
26
+ conflict: ConflictEvidence;
27
+ }
28
+ function git(input: RebaseInput, ...args: string[]): string {
29
+ return execFileSync(resolveGitBinary(), repositoryGitArgs(args), {
30
+ cwd: input.path,
31
+ encoding: "utf8",
32
+ env: repositoryGitSubprocessEnv(input.projectKey, {
33
+ GIT_TERMINAL_PROMPT: "0",
34
+ GIT_EDITOR: "true",
35
+ }),
36
+ stdio: ["ignore", "pipe", "pipe"],
37
+ }).trim();
38
+ }
39
+ function area(input: RebaseInput): string {
40
+ return git(input, "rev-parse", "--absolute-git-dir");
41
+ }
42
+ function active(gitDir: string): boolean {
43
+ return ["rebase-merge", "rebase-apply"].some((name) => existsSync(join(gitDir, name)));
44
+ }
45
+ function save(gitDir: string, record: RebaseRecord): void {
46
+ const path = join(gitDir, "leitwerk-rebase.json");
47
+ writeFileSync(`${path}.tmp`, JSON.stringify(record), { mode: 0o600 });
48
+ renameSync(`${path}.tmp`, path);
49
+ }
50
+ function read(gitDir: string): RebaseRecord | null {
51
+ const file = join(gitDir, "leitwerk-rebase.json");
52
+ return existsSync(file) ? (JSON.parse(readFileSync(file, "utf8")) as RebaseRecord) : null;
53
+ }
54
+ function requireWorktree(input: RebaseInput): void {
55
+ requireRebaseWorktree(input.workBranch, {
56
+ branch: git(input, "branch", "--show-current"),
57
+ dirty: Boolean(git(input, "status", "--porcelain")),
58
+ });
59
+ }
60
+ function remoteHead(input: RebaseInput): string {
61
+ return git(input, "ls-remote", "--heads", "origin", `refs/heads/${input.workBranch}`).split(
62
+ /\s+/,
63
+ )[0];
64
+ }
65
+
66
+ function requireTarget(input: RebaseInput, record?: RebaseRecord | null): void {
67
+ requireRebaseTarget(input.workBranch, input.conflict, record);
68
+ git(input, "check-ref-format", `refs/heads/${input.workBranch}`);
69
+ git(input, "check-ref-format", `refs/heads/${input.conflict.baseBranch}`);
70
+ requireRebaseOrigin(record, {
71
+ originUrl: record?.originUrl ? git(input, "remote", "get-url", "origin") : undefined,
72
+ originPushUrl: record?.originPushUrl
73
+ ? git(input, "remote", "get-url", "--push", "--all", "origin")
74
+ : undefined,
75
+ });
76
+ }
77
+
78
+ function verifyCurrentBase(input: RebaseInput, record: RebaseRecord): void {
79
+ git(
80
+ input,
81
+ "fetch",
82
+ "origin",
83
+ `+refs/heads/${input.conflict.baseBranch}:refs/leitwerk/rebase-base`,
84
+ );
85
+ // A fast-forward is compatible with captured preparation; a rewritten base is not.
86
+ git(input, "merge-base", "--is-ancestor", record.baseSha, "refs/leitwerk/rebase-base");
87
+ }
88
+
89
+ function verifyNoRepairNeeded(input: RebaseInput, headSha: string, baseSha: string): void {
90
+ if (input.conflict.reason === "behind")
91
+ git(input, "merge-base", "--is-ancestor", baseSha, headSha);
92
+ else git(input, "merge-tree", "--write-tree", headSha, baseSha);
93
+ }
94
+
95
+ /** Persist the lease before changing HEAD; a retry resumes Git's own rebase state. @internal */
96
+ export function prepareRebase(input: RebaseInput): RebaseRecord {
97
+ const gitDir = area(input);
98
+ const old = read(gitDir);
99
+ requireTarget(input, old?.key === conflictKey(input.conflict) ? old : null);
100
+ if (old?.key === conflictKey(input.conflict)) {
101
+ verifyCurrentBase(input, old);
102
+ return old;
103
+ }
104
+ if (active(gitDir)) throw new Error("An unrelated rebase is already in progress");
105
+ requireWorktree(input);
106
+ git(
107
+ input,
108
+ "fetch",
109
+ "origin",
110
+ `+refs/heads/${input.workBranch}:refs/leitwerk/rebase-head`,
111
+ `+refs/heads/${input.conflict.baseBranch}:refs/leitwerk/rebase-base`,
112
+ );
113
+ const [remoteSha, headSha, baseSha] = git(
114
+ input,
115
+ "rev-parse",
116
+ "refs/leitwerk/rebase-head",
117
+ "HEAD",
118
+ "refs/leitwerk/rebase-base",
119
+ ).split("\n");
120
+ requireRebaseHead(input.conflict.headSha, headSha, remoteSha);
121
+ // Use the current fetched base, retaining the provider pair for deduplication.
122
+ git(input, "merge-base", "--is-ancestor", input.conflict.baseSha, baseSha);
123
+ const record: RebaseRecord = {
124
+ key: conflictKey(input.conflict),
125
+ branch: input.workBranch,
126
+ originalHead: input.conflict.headSha,
127
+ baseSha,
128
+ status: "prepared",
129
+ originUrl: git(input, "remote", "get-url", "origin"),
130
+ originPushUrl: git(input, "remote", "get-url", "--push", "--all", "origin"),
131
+ baseBranch: input.conflict.baseBranch,
132
+ };
133
+ git(input, "update-ref", "refs/leitwerk/rebase-original", record.originalHead);
134
+ save(gitDir, record);
135
+ return record;
136
+ }
137
+ /** @internal */
138
+ export function startRebase(input: RebaseInput): RebaseRecord {
139
+ const record = prepareRebase(input);
140
+ const gitDir = area(input);
141
+ if (active(gitDir)) return record;
142
+ if (record.status === "clean") return record;
143
+ requireWorktree(input);
144
+ if (record.status === "rebasing" && git(input, "rev-parse", "HEAD") !== record.originalHead)
145
+ return record;
146
+ try {
147
+ verifyNoRepairNeeded(input, record.originalHead, record.baseSha);
148
+ record.status = "clean";
149
+ save(gitDir, record);
150
+ return record;
151
+ } catch (error) {
152
+ if ((error as { status?: number }).status !== 1) throw error;
153
+ }
154
+ record.status = "rebasing";
155
+ save(gitDir, record);
156
+ try {
157
+ git(input, "rebase", "--rebase-merges", record.baseSha);
158
+ } catch (error) {
159
+ if (!active(gitDir)) throw error;
160
+ }
161
+ return record;
162
+ }
163
+ /** @internal */
164
+ export function verifyRebase(input: RebaseInput): {
165
+ /** @internal */
166
+ headSha: string;
167
+ /** @internal */
168
+ changed: boolean;
169
+ /** @internal */
170
+ originalHead: string;
171
+ /** @internal */
172
+ baseSha: string;
173
+ } {
174
+ const gitDir = area(input);
175
+ const record = read(gitDir);
176
+ if (!record || record.key !== conflictKey(input.conflict))
177
+ throw new Error("Missing matching rebase metadata");
178
+ requireTarget(input, record);
179
+ if (active(gitDir)) throw new Error("Rebase is incomplete");
180
+ requireWorktree(input);
181
+ const headSha = git(input, "rev-parse", "HEAD");
182
+ if (record.status === "clean") {
183
+ if (headSha !== record.originalHead)
184
+ throw new Error("Clean conflict report must not rewrite the branch");
185
+ verifyNoRepairNeeded(input, headSha, record.baseSha);
186
+ } else {
187
+ if (record.status !== "rebasing") throw new Error("Rebase was not started");
188
+ git(input, "merge-base", "--is-ancestor", record.baseSha, headSha);
189
+ }
190
+ return {
191
+ headSha,
192
+ changed: headSha !== record.originalHead,
193
+ originalHead: record.originalHead,
194
+ baseSha: record.baseSha,
195
+ };
196
+ }
197
+ /** @internal */
198
+ export function publishRebase(input: RebaseInput): ReturnType<typeof verifyRebase> {
199
+ const result = verifyRebase(input);
200
+ const gitDir = area(input);
201
+ const record = read(gitDir);
202
+ if (!record) throw new Error("Missing matching rebase metadata");
203
+ verifyCurrentBase(input, record);
204
+ const remote = remoteHead(input);
205
+ if (
206
+ rebasePublicationDecision(result.originalHead, result.headSha, remote) === "already_published"
207
+ )
208
+ return result;
209
+ git(
210
+ input,
211
+ "push",
212
+ `--force-with-lease=refs/heads/${input.workBranch}:${result.originalHead}`,
213
+ "origin",
214
+ `${result.headSha}:refs/heads/${input.workBranch}`,
215
+ );
216
+ if (remoteHead(input) !== result.headSha)
217
+ throw new Error("Rebase publication could not be verified");
218
+ return result;
219
+ }
@@ -0,0 +1,144 @@
1
+ import type {
2
+ ExternalEventDescription,
3
+ ExternalObservationInput,
4
+ ExternalSourceArmingLike,
5
+ ExternalSourcePollReporter,
6
+ RepositoryPullRequest,
7
+ } from "@leitwerk-dev/process-sdk";
8
+
9
+ /** @public */
10
+ export interface ConflictEvidence {
11
+ /** @public */
12
+ reason?: "behind";
13
+ /** @public */
14
+ owner: string;
15
+ /** @public */
16
+ repo: string;
17
+ /** @public */
18
+ prNumber: number;
19
+ /** @public */
20
+ headBranch: string;
21
+ /** @public */
22
+ baseBranch: string;
23
+ /** @public */
24
+ headSha: string;
25
+ /** @public */
26
+ baseSha: string;
27
+ /** @public */
28
+ url: string;
29
+ }
30
+ /** @public */
31
+ export function conflictKey(value: ConflictEvidence): string {
32
+ return JSON.stringify([value.owner, value.repo, value.prNumber, value.headSha, value.baseSha]);
33
+ }
34
+ /** @public */
35
+ export function validateConflict(
36
+ value: unknown,
37
+ expected: Omit<ConflictEvidence, "baseSha" | "url">,
38
+ lastKey?: string | null,
39
+ ): ConflictEvidence {
40
+ const evidence = value as ConflictEvidence | null;
41
+ if (
42
+ !evidence ||
43
+ typeof evidence !== "object" ||
44
+ Array.isArray(evidence) ||
45
+ ["owner", "repo", "headBranch", "baseBranch", "headSha", "baseSha"].some(
46
+ (key) =>
47
+ typeof evidence[key as keyof ConflictEvidence] !== "string" ||
48
+ !String(evidence[key as keyof ConflictEvidence]).trim(),
49
+ ) ||
50
+ !Number.isSafeInteger(evidence.prNumber) ||
51
+ evidence.prNumber <= 0 ||
52
+ (evidence.reason !== undefined && evidence.reason !== "behind") ||
53
+ Object.entries(expected).some(
54
+ ([key, val]) => evidence[key as keyof ConflictEvidence] !== val,
55
+ ) ||
56
+ !/^[a-f0-9]{40,64}$/i.test(evidence.baseSha) ||
57
+ !/^[a-f0-9]{40,64}$/i.test(evidence.headSha) ||
58
+ typeof evidence.url !== "string" ||
59
+ conflictKey(evidence) === lastKey
60
+ )
61
+ throw new Error("Stale or invalid pull request conflict evidence");
62
+ return evidence;
63
+ }
64
+ /** @public */
65
+ export function describeConflict(event: unknown): ExternalEventDescription {
66
+ const evidence = (event as { conflict: ConflictEvidence }).conflict;
67
+ return {
68
+ summary: `${evidence.reason === "behind" ? "Pull request behind base in" : "Merge conflict in"} ${evidence.owner}/${evidence.repo}#${evidence.prNumber}: ${evidence.headBranch} (${evidence.headSha}) against ${evidence.baseBranch} (${evidence.baseSha})`,
69
+ links: [
70
+ {
71
+ id: "conflicting-pr",
72
+ label: `PR #${evidence.prNumber}`,
73
+ url: evidence.url,
74
+ kind: "pull_request",
75
+ },
76
+ ],
77
+ };
78
+ }
79
+ /** @public */
80
+ export function conflictEvidence(
81
+ config: {
82
+ /** @public */
83
+ owner: string;
84
+ /** @public */
85
+ repo: string;
86
+ /** @public */
87
+ prNumber: number;
88
+ /** @public */
89
+ headSha: string;
90
+ },
91
+ pr: Pick<
92
+ RepositoryPullRequest,
93
+ "number" | "state" | "merged" | "mergeable" | "mergeable_state" | "head" | "base" | "html_url"
94
+ >,
95
+ provider: "github" | "forgejo",
96
+ ): ConflictEvidence | null {
97
+ const behind = provider === "github" && pr.mergeable === true && pr.mergeable_state === "behind";
98
+ const conflicting =
99
+ pr.mergeable === false && (provider === "forgejo" || pr.mergeable_state === "dirty");
100
+ if (
101
+ pr.number !== config.prNumber ||
102
+ pr.state !== "open" ||
103
+ pr.merged ||
104
+ pr.head.sha !== config.headSha ||
105
+ (!behind && !conflicting) ||
106
+ !pr.base?.sha
107
+ )
108
+ return null;
109
+ return {
110
+ ...(behind ? { reason: "behind" as const } : {}),
111
+ owner: config.owner,
112
+ repo: config.repo,
113
+ prNumber: pr.number,
114
+ headBranch: pr.head.ref,
115
+ baseBranch: pr.base.ref,
116
+ headSha: pr.head.sha,
117
+ baseSha: pr.base.sha,
118
+ url: pr.html_url,
119
+ };
120
+ }
121
+
122
+ /** Observe every refresh; fire each conflict pair once per live subscription. @public */
123
+ export function createConflictReporter(kind: string) {
124
+ const accepted = new Map<string, string>();
125
+ return async (
126
+ report: ExternalSourcePollReporter,
127
+ armed: ExternalSourceArmingLike,
128
+ conflict: ConflictEvidence | null,
129
+ lastKey: unknown,
130
+ observation: NonNullable<ExternalObservationInput["observation"]>,
131
+ ): Promise<boolean> => {
132
+ await report.observe(armed, {
133
+ observation: { ...observation, ...(conflict ? describeConflict({ conflict }) : {}) },
134
+ });
135
+ if (!conflict) return false;
136
+ const pair = conflictKey(conflict);
137
+ const key = `${armed.instanceId}:${armed.id}:${armed.generation ?? ""}`;
138
+ if (pair === lastKey || accepted.get(key) === pair || !report.isCurrent(kind, armed))
139
+ return false;
140
+ if (await report.fire(armed, { kind: "merge_conflict", conflict }, pair))
141
+ accepted.set(key, pair);
142
+ return true;
143
+ };
144
+ }