@leitwerk-dev/coding 0.3.0 → 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 (45) hide show
  1. package/README.md +34 -1
  2. package/dist/auto-work-branch.js +3 -24
  3. package/dist/auto-work-branch.js.map +1 -1
  4. package/dist/chunk-6E5VQPC4.js +28 -0
  5. package/dist/chunk-6E5VQPC4.js.map +1 -0
  6. package/dist/chunk-KFELB7ZC.js +70 -0
  7. package/dist/chunk-KFELB7ZC.js.map +1 -0
  8. package/dist/profile-bindings-internal.d.ts +3 -0
  9. package/dist/profile-bindings-internal.d.ts.map +1 -0
  10. package/dist/pull-request-publication-internal.d.ts +73 -0
  11. package/dist/pull-request-publication-internal.d.ts.map +1 -0
  12. package/dist/repository-change-launch-internal-Dd-AONUs.d.ts +67 -0
  13. package/dist/repository-change-launch-internal.d.ts +30 -0
  14. package/dist/repository-change-launch-internal.d.ts.map +1 -1
  15. package/dist/repository-change-launch.d.ts +4 -2
  16. package/dist/repository-change-launch.d.ts.map +1 -1
  17. package/dist/repository-change-launch.js +235 -6
  18. package/dist/repository-change-launch.js.map +1 -1
  19. package/dist/repository-change-publication.d.ts +2 -2
  20. package/dist/repository-change-publication.d.ts.map +1 -1
  21. package/dist/repository-change-publication.js +429 -27
  22. package/dist/repository-change-publication.js.map +1 -1
  23. package/dist/repository-change-ui-launcher-internal.d.ts +53 -0
  24. package/dist/repository-change-ui-launcher-internal.d.ts.map +1 -0
  25. package/dist/repository-rebase/git.d.ts +31 -0
  26. package/dist/repository-rebase/git.d.ts.map +1 -0
  27. package/dist/repository-rebase/index.d.ts +42 -0
  28. package/dist/repository-rebase/index.d.ts.map +1 -0
  29. package/dist/repository-rebase/index.js +16 -0
  30. package/dist/repository-rebase/index.js.map +1 -0
  31. package/dist/repository-rebase/policy.d.ts +37 -0
  32. package/dist/repository-rebase/policy.d.ts.map +1 -0
  33. package/dist/repository-rebase/prompt.d.ts +3 -0
  34. package/dist/repository-rebase/prompt.d.ts.map +1 -0
  35. package/package.json +9 -5
  36. package/src/profile-bindings-internal.ts +39 -0
  37. package/src/pull-request-publication-internal.ts +286 -0
  38. package/src/repository-change-launch-internal.ts +76 -0
  39. package/src/repository-change-launch.ts +9 -0
  40. package/src/repository-change-publication.ts +29 -45
  41. package/src/repository-change-ui-launcher-internal.ts +225 -0
  42. package/src/repository-rebase/git.ts +219 -0
  43. package/src/repository-rebase/index.ts +144 -0
  44. package/src/repository-rebase/policy.ts +75 -0
  45. package/src/repository-rebase/prompt.ts +2 -0
@@ -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
+ }
@@ -0,0 +1,75 @@
1
+ import type { ConflictEvidence } from "./index.js";
2
+
3
+ /** Durable preparation evidence; optional identity fields support older records. @internal */
4
+ export interface RebaseRecord {
5
+ /** @internal */
6
+ key: string;
7
+ /** @internal */
8
+ branch: string;
9
+ /** @internal */
10
+ originalHead: string;
11
+ /** @internal */
12
+ baseSha: string;
13
+ /** @internal */
14
+ status: "prepared" | "rebasing" | "clean";
15
+ /** @internal */
16
+ originUrl?: string;
17
+ /** @internal */
18
+ originPushUrl?: string;
19
+ /** @internal */
20
+ baseBranch?: string;
21
+ }
22
+
23
+ /** Validate provider evidence against the tracked branch and retained preparation. @internal */
24
+ export function requireRebaseTarget(
25
+ workBranch: string,
26
+ conflict: ConflictEvidence,
27
+ record?: RebaseRecord | null,
28
+ ): void {
29
+ if (workBranch !== conflict.headBranch || workBranch === conflict.baseBranch)
30
+ throw new Error("Expected evidence for the tracked work branch and a distinct base");
31
+ if (record && (record.branch !== workBranch || record.originalHead !== conflict.headSha))
32
+ throw new Error("Missing matching rebase metadata");
33
+ if (record?.baseBranch && record.baseBranch !== conflict.baseBranch)
34
+ throw new Error("Rebase base branch changed since preparation");
35
+ }
36
+
37
+ /** Compare observed remote identity only where preparation retained it. @internal */
38
+ export function requireRebaseOrigin(
39
+ record: RebaseRecord | null | undefined,
40
+ origin: { originUrl?: string; originPushUrl?: string },
41
+ ): void {
42
+ if (
43
+ (record?.originUrl && origin.originUrl !== record.originUrl) ||
44
+ (record?.originPushUrl && origin.originPushUrl !== record.originPushUrl)
45
+ )
46
+ throw new Error("Rebase origin changed since preparation");
47
+ }
48
+
49
+ /** A repair may operate only on the clean tracked checkout. @internal */
50
+ export function requireRebaseWorktree(
51
+ workBranch: string,
52
+ observation: { branch: string; dirty: boolean },
53
+ ): void {
54
+ if (observation.branch !== workBranch) throw new Error("Expected tracked work branch for rebase");
55
+ if (observation.dirty)
56
+ throw new Error("Rebase requires a clean worktree with no unresolved conflicts");
57
+ }
58
+
59
+ /** Both local and remote heads must still match the provider's evidence. @internal */
60
+ export function requireRebaseHead(expected: string, local: string, remote: string): void {
61
+ if (remote !== expected || local !== expected)
62
+ throw new Error("Tracked branch changed before repair");
63
+ }
64
+
65
+ /** Recognize a completed write without accepting somebody else's remote update. @internal */
66
+ export function rebasePublicationDecision(
67
+ originalHead: string,
68
+ headSha: string,
69
+ remoteHead: string,
70
+ ): "already_published" | "push" {
71
+ if (remoteHead === headSha) return "already_published";
72
+ if (remoteHead !== originalHead)
73
+ throw new Error("Concurrent remote change rejected by rebase lease");
74
+ return "push";
75
+ }
@@ -0,0 +1,2 @@
1
+ /** @internal */
2
+ export const rebasePrompt = `Repair only the recorded pull request merge conflict or behind-base condition. Deterministic preparation has fetched and verified the tracked head and current base, retained the original head and lease in .git/leitwerk-rebase.json, and started the rebase if the conflict or missing base commits are confirmed locally. Inspect that metadata and git status first. For behind-base evidence, incorporate the fetched base even when merging would be clean. A clean preparation result means no rewrite is needed. Resolve conflicts preserving the requested behavior, original authors, and existing Signed-off-by trailers. You may use git add and GIT_EDITOR=true git rebase --continue until finished. This explicitly overrides the prohibition on creating commits only for rebase continuation. Do not create unrelated commits, reset the branch, skip commits, abort the rebase, or push. Run focused repository checks after resolution. Delivery verifies the completed rebase and publishes with the recorded pre-repair lease. If blocked, retain the workspace and explain the failure for retry or abort. Record a concise repair result.`;