@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
@@ -0,0 +1,770 @@
1
+ import {
2
+ commitAndPushWorkBranch
3
+ } from "./chunk-GO44KCUS.js";
4
+ import {
5
+ conflictKey,
6
+ validateConflict
7
+ } from "./chunk-KFELB7ZC.js";
8
+ import "./chunk-PX6F3LHL.js";
9
+
10
+ // src/repository-change-publication.ts
11
+ import { asUnknownRecord } from "@leitwerk-dev/domain";
12
+ import {
13
+ flow
14
+ } from "@leitwerk-dev/process-sdk";
15
+
16
+ // src/repository-rebase/git.ts
17
+ import { execFileSync } from "child_process";
18
+ import { existsSync, readFileSync, renameSync, writeFileSync } from "fs";
19
+ import { join } from "path";
20
+ import { repositoryGitArgs, repositoryGitSubprocessEnv } from "@leitwerk-dev/process-sdk";
21
+ import { resolveGitBinary } from "@leitwerk-dev/process-sdk/git-binary";
22
+
23
+ // src/repository-rebase/policy.ts
24
+ function requireRebaseTarget(workBranch, conflict, record) {
25
+ if (workBranch !== conflict.headBranch || workBranch === conflict.baseBranch)
26
+ throw new Error("Expected evidence for the tracked work branch and a distinct base");
27
+ if (record && (record.branch !== workBranch || record.originalHead !== conflict.headSha))
28
+ throw new Error("Missing matching rebase metadata");
29
+ if (record?.baseBranch && record.baseBranch !== conflict.baseBranch)
30
+ throw new Error("Rebase base branch changed since preparation");
31
+ }
32
+ function requireRebaseOrigin(record, origin) {
33
+ if (record?.originUrl && origin.originUrl !== record.originUrl || record?.originPushUrl && origin.originPushUrl !== record.originPushUrl)
34
+ throw new Error("Rebase origin changed since preparation");
35
+ }
36
+ function requireRebaseWorktree(workBranch, observation) {
37
+ if (observation.branch !== workBranch) throw new Error("Expected tracked work branch for rebase");
38
+ if (observation.dirty)
39
+ throw new Error("Rebase requires a clean worktree with no unresolved conflicts");
40
+ }
41
+ function requireRebaseHead(expected, local, remote) {
42
+ if (remote !== expected || local !== expected)
43
+ throw new Error("Tracked branch changed before repair");
44
+ }
45
+ function rebasePublicationDecision(originalHead, headSha, remoteHead2) {
46
+ if (remoteHead2 === headSha) return "already_published";
47
+ if (remoteHead2 !== originalHead)
48
+ throw new Error("Concurrent remote change rejected by rebase lease");
49
+ return "push";
50
+ }
51
+
52
+ // src/repository-rebase/git.ts
53
+ function git(input, ...args) {
54
+ return execFileSync(resolveGitBinary(), repositoryGitArgs(args), {
55
+ cwd: input.path,
56
+ encoding: "utf8",
57
+ env: repositoryGitSubprocessEnv(input.projectKey, {
58
+ GIT_TERMINAL_PROMPT: "0",
59
+ GIT_EDITOR: "true"
60
+ }),
61
+ stdio: ["ignore", "pipe", "pipe"]
62
+ }).trim();
63
+ }
64
+ function area(input) {
65
+ return git(input, "rev-parse", "--absolute-git-dir");
66
+ }
67
+ function active(gitDir) {
68
+ return ["rebase-merge", "rebase-apply"].some((name) => existsSync(join(gitDir, name)));
69
+ }
70
+ function save(gitDir, record) {
71
+ const path = join(gitDir, "leitwerk-rebase.json");
72
+ writeFileSync(`${path}.tmp`, JSON.stringify(record), { mode: 384 });
73
+ renameSync(`${path}.tmp`, path);
74
+ }
75
+ function read(gitDir) {
76
+ const file = join(gitDir, "leitwerk-rebase.json");
77
+ return existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : null;
78
+ }
79
+ function requireWorktree(input) {
80
+ requireRebaseWorktree(input.workBranch, {
81
+ branch: git(input, "branch", "--show-current"),
82
+ dirty: Boolean(git(input, "status", "--porcelain"))
83
+ });
84
+ }
85
+ function remoteHead(input) {
86
+ return git(input, "ls-remote", "--heads", "origin", `refs/heads/${input.workBranch}`).split(
87
+ /\s+/
88
+ )[0];
89
+ }
90
+ function requireTarget(input, record) {
91
+ requireRebaseTarget(input.workBranch, input.conflict, record);
92
+ git(input, "check-ref-format", `refs/heads/${input.workBranch}`);
93
+ git(input, "check-ref-format", `refs/heads/${input.conflict.baseBranch}`);
94
+ requireRebaseOrigin(record, {
95
+ originUrl: record?.originUrl ? git(input, "remote", "get-url", "origin") : void 0,
96
+ originPushUrl: record?.originPushUrl ? git(input, "remote", "get-url", "--push", "--all", "origin") : void 0
97
+ });
98
+ }
99
+ function verifyCurrentBase(input, record) {
100
+ git(
101
+ input,
102
+ "fetch",
103
+ "origin",
104
+ `+refs/heads/${input.conflict.baseBranch}:refs/leitwerk/rebase-base`
105
+ );
106
+ git(input, "merge-base", "--is-ancestor", record.baseSha, "refs/leitwerk/rebase-base");
107
+ }
108
+ function verifyNoRepairNeeded(input, headSha, baseSha) {
109
+ if (input.conflict.reason === "behind")
110
+ git(input, "merge-base", "--is-ancestor", baseSha, headSha);
111
+ else git(input, "merge-tree", "--write-tree", headSha, baseSha);
112
+ }
113
+ function prepareRebase(input) {
114
+ const gitDir = area(input);
115
+ const old = read(gitDir);
116
+ requireTarget(input, old?.key === conflictKey(input.conflict) ? old : null);
117
+ if (old?.key === conflictKey(input.conflict)) {
118
+ verifyCurrentBase(input, old);
119
+ return old;
120
+ }
121
+ if (active(gitDir)) throw new Error("An unrelated rebase is already in progress");
122
+ requireWorktree(input);
123
+ git(
124
+ input,
125
+ "fetch",
126
+ "origin",
127
+ `+refs/heads/${input.workBranch}:refs/leitwerk/rebase-head`,
128
+ `+refs/heads/${input.conflict.baseBranch}:refs/leitwerk/rebase-base`
129
+ );
130
+ const [remoteSha, headSha, baseSha] = git(
131
+ input,
132
+ "rev-parse",
133
+ "refs/leitwerk/rebase-head",
134
+ "HEAD",
135
+ "refs/leitwerk/rebase-base"
136
+ ).split("\n");
137
+ requireRebaseHead(input.conflict.headSha, headSha, remoteSha);
138
+ git(input, "merge-base", "--is-ancestor", input.conflict.baseSha, baseSha);
139
+ const record = {
140
+ key: conflictKey(input.conflict),
141
+ branch: input.workBranch,
142
+ originalHead: input.conflict.headSha,
143
+ baseSha,
144
+ status: "prepared",
145
+ originUrl: git(input, "remote", "get-url", "origin"),
146
+ originPushUrl: git(input, "remote", "get-url", "--push", "--all", "origin"),
147
+ baseBranch: input.conflict.baseBranch
148
+ };
149
+ git(input, "update-ref", "refs/leitwerk/rebase-original", record.originalHead);
150
+ save(gitDir, record);
151
+ return record;
152
+ }
153
+ function startRebase(input) {
154
+ const record = prepareRebase(input);
155
+ const gitDir = area(input);
156
+ if (active(gitDir)) return record;
157
+ if (record.status === "clean") return record;
158
+ requireWorktree(input);
159
+ if (record.status === "rebasing" && git(input, "rev-parse", "HEAD") !== record.originalHead)
160
+ return record;
161
+ try {
162
+ verifyNoRepairNeeded(input, record.originalHead, record.baseSha);
163
+ record.status = "clean";
164
+ save(gitDir, record);
165
+ return record;
166
+ } catch (error) {
167
+ if (error.status !== 1) throw error;
168
+ }
169
+ record.status = "rebasing";
170
+ save(gitDir, record);
171
+ try {
172
+ git(input, "rebase", "--rebase-merges", record.baseSha);
173
+ } catch (error) {
174
+ if (!active(gitDir)) throw error;
175
+ }
176
+ return record;
177
+ }
178
+ function verifyRebase(input) {
179
+ const gitDir = area(input);
180
+ const record = read(gitDir);
181
+ if (!record || record.key !== conflictKey(input.conflict))
182
+ throw new Error("Missing matching rebase metadata");
183
+ requireTarget(input, record);
184
+ if (active(gitDir)) throw new Error("Rebase is incomplete");
185
+ requireWorktree(input);
186
+ const headSha = git(input, "rev-parse", "HEAD");
187
+ if (record.status === "clean") {
188
+ if (headSha !== record.originalHead)
189
+ throw new Error("Clean conflict report must not rewrite the branch");
190
+ verifyNoRepairNeeded(input, headSha, record.baseSha);
191
+ } else {
192
+ if (record.status !== "rebasing") throw new Error("Rebase was not started");
193
+ git(input, "merge-base", "--is-ancestor", record.baseSha, headSha);
194
+ }
195
+ return {
196
+ headSha,
197
+ changed: headSha !== record.originalHead,
198
+ originalHead: record.originalHead,
199
+ baseSha: record.baseSha
200
+ };
201
+ }
202
+ function publishRebase(input) {
203
+ const result = verifyRebase(input);
204
+ const gitDir = area(input);
205
+ const record = read(gitDir);
206
+ if (!record) throw new Error("Missing matching rebase metadata");
207
+ verifyCurrentBase(input, record);
208
+ const remote = remoteHead(input);
209
+ if (rebasePublicationDecision(result.originalHead, result.headSha, remote) === "already_published")
210
+ return result;
211
+ git(
212
+ input,
213
+ "push",
214
+ `--force-with-lease=refs/heads/${input.workBranch}:${result.originalHead}`,
215
+ "origin",
216
+ `${result.headSha}:refs/heads/${input.workBranch}`
217
+ );
218
+ if (remoteHead(input) !== result.headSha)
219
+ throw new Error("Rebase publication could not be verified");
220
+ return result;
221
+ }
222
+
223
+ // src/repository-rebase/prompt.ts
224
+ var 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.`;
225
+
226
+ // src/pull-request-publication-internal.ts
227
+ var callFor = (ctx, provider) => (name, args) => ctx.callIntegrationTool(`${provider}_${name}`, { projectKey: "repo", ...args });
228
+ async function resolvePullRequestGitIdentity(ctx, provider, profile) {
229
+ const project = ctx.projects.find((candidate) => candidate.key === "repo");
230
+ const identity = publicationObject(publicationObject(project?.metadata)["leitwerk.gitIdentity"]);
231
+ if (identity.provider === provider && identity.profile === profile && [identity.login, identity.name, identity.email].every(
232
+ (value) => typeof value === "string" && value.trim()
233
+ ))
234
+ return identity;
235
+ return callFor(ctx, provider)("resolve_git_identity", {});
236
+ }
237
+ function readPullRequestFeedback(current, event) {
238
+ const value = publicationObject(event);
239
+ const cursors = publicationObject(value.cursors);
240
+ return {
241
+ kind: "feedback",
242
+ conversationCursor: Number(cursors.conversationCursor ?? current.conversationCursor),
243
+ reviewCursor: Number(cursors.reviewCursor ?? current.reviewCursor),
244
+ inlineCursor: Number(cursors.inlineCursor ?? current.inlineCursor),
245
+ feedbackIds: value.feedbackIds ?? []
246
+ };
247
+ }
248
+ function reconcilePullRequestSourceIssue(provider, labelKey, issueOrigin) {
249
+ return async (ctx, _current, pr) => {
250
+ const params = issueOrigin(ctx.params);
251
+ if (!params) return;
252
+ const call = callFor(ctx, provider);
253
+ const issue = await call("get_issue", {
254
+ issueNumber: params.issueNumber
255
+ });
256
+ let labels = issue.labels.filter((label) => label.name !== params.triggerLabel).map((label) => label[labelKey]);
257
+ if (pr.merged) {
258
+ const done = await call("ensure_label", {
259
+ name: params.doneLabel
260
+ });
261
+ labels = [.../* @__PURE__ */ new Set([...labels, done[labelKey]])];
262
+ }
263
+ await call("update_issue", {
264
+ issueNumber: params.issueNumber,
265
+ patch: { labels, ...pr.merged ? { state: "closed" } : {} },
266
+ writeKey: `${provider}:${ctx.process.id}:${pr.merged ? "complete-source-issue" : "remove-source-trigger"}`
267
+ });
268
+ await call("add_issue_comment", {
269
+ issueNumber: params.issueNumber,
270
+ body: pr.merged ? `Merged ${pr.html_url}${pr.merge_commit_sha ? ` at ${pr.merge_commit_sha}` : ""}.` : `Leitwerk stopped because ${pr.html_url} was closed without merge.`,
271
+ writeKey: `${provider}:${ctx.process.id}:${pr.merged ? "merged" : "closed"}-pr-comment`
272
+ });
273
+ };
274
+ }
275
+ function pullRequestPublicationSources(provider, label, external, profile, issueOrigin) {
276
+ const remote = (state) => readPublicationState(state, `${provider}RepoChange`);
277
+ function requirePr(state) {
278
+ const value = remote(state);
279
+ if (!value.headSha || !value.prNumber || !value.prUrl)
280
+ throw new Error("Pull request delivery state is incomplete");
281
+ return {
282
+ ...value,
283
+ /** @internal */
284
+ headSha: value.headSha,
285
+ /** @internal */
286
+ prNumber: value.prNumber,
287
+ /** @internal */
288
+ prUrl: value.prUrl
289
+ };
290
+ }
291
+ const feedback = {
292
+ id: `${provider}_feedback`,
293
+ kind: "feedback",
294
+ label: `${label} pull request feedback`,
295
+ source: external.pullRequestFeedback(({ params, state }) => ({
296
+ profile: profile(params),
297
+ owner: params.owner,
298
+ repo: params.repo,
299
+ prNumber: requirePr(state).prNumber,
300
+ conversationCursor: remote(state).conversationCursor,
301
+ reviewCursor: remote(state).reviewCursor,
302
+ inlineCursor: remote(state).inlineCursor,
303
+ quietPeriodMs: 12e4,
304
+ pollInterval: "30s"
305
+ })),
306
+ read: ({ state, event }) => readPullRequestFeedback(remote(state), event)
307
+ };
308
+ const terminal = ["merged", "closed"].map(
309
+ (terminalOutcome) => ({
310
+ id: `${provider}_pr_${terminalOutcome}`,
311
+ kind: "terminal",
312
+ label: `${label} pull request ${terminalOutcome}`,
313
+ source: external.pullRequestTerminal(({ params, state }) => ({
314
+ profile: profile(params),
315
+ owner: params.owner,
316
+ repo: params.repo,
317
+ prNumber: requirePr(state).prNumber,
318
+ terminalOutcome,
319
+ pollInterval: "30s"
320
+ })),
321
+ read: ({ event }) => ({
322
+ kind: "terminal",
323
+ request: publicationObject(event).pullRequest
324
+ })
325
+ })
326
+ );
327
+ const cancelled = {
328
+ id: "source_cancelled",
329
+ kind: "cancelled",
330
+ label: "Source issue cancelled",
331
+ enabled: (params) => issueOrigin(params) !== void 0,
332
+ source: external.issueCancelled(({ params }) => {
333
+ const issue = issueOrigin(params);
334
+ if (!issue) throw new Error(`${label} source issue metadata is unavailable`);
335
+ return {
336
+ profile: profile(params),
337
+ owner: params.owner,
338
+ repo: params.repo,
339
+ issueNumber: issue.issueNumber,
340
+ triggerLabel: issue.triggerLabel,
341
+ pollInterval: "30s"
342
+ };
343
+ }),
344
+ read: () => ({ kind: "cancelled" })
345
+ };
346
+ return {
347
+ /** @internal */
348
+ requirePr,
349
+ /** @internal */
350
+ feedback,
351
+ /** @internal */
352
+ terminal,
353
+ /** @internal */
354
+ cancelled
355
+ };
356
+ }
357
+ function pullRequestPublicationCallbacks(provider, label, issueOrigin) {
358
+ const call = (ctx) => callFor(ctx, provider);
359
+ return {
360
+ async ensureRequest(ctx) {
361
+ const project = ctx.repo.get("repo");
362
+ const issue = issueOrigin(ctx.params);
363
+ const pr = await call(ctx)("ensure_pull_request", {
364
+ title: ctx.process.title ?? (issue ? `Issue #${issue.issueNumber}` : "Leitwerk change"),
365
+ body: issue ? `Implements ${issue.issueUrl}
366
+
367
+ Leitwerk process: ${ctx.process.id}` : `Leitwerk process: ${ctx.process.id}`,
368
+ head: project.workBranch,
369
+ base: project.baseBranch
370
+ });
371
+ if (!pr) throw new Error(`${label} pull request could not be created or found`);
372
+ return pr;
373
+ },
374
+ async linkIssue(ctx, current) {
375
+ const issue = issueOrigin(ctx.params);
376
+ if (issue)
377
+ await call(ctx)("add_issue_comment", {
378
+ issueNumber: issue.issueNumber,
379
+ body: `Leitwerk opened pull request ${current.prUrl}.`,
380
+ writeKey: `${provider}:${ctx.process.id}:source-pr-link:${current.prNumber}`
381
+ });
382
+ },
383
+ async reply(ctx, current) {
384
+ const invoke = call(ctx);
385
+ for (const feedback of current.feedbackIds)
386
+ await invoke("reply_to_pull_request_feedback", {
387
+ pullRequestNumber: current.prNumber,
388
+ feedbackKind: feedback.kind,
389
+ feedbackId: feedback.id,
390
+ body: `Addressed in ${current.headSha?.slice(0, 8) ?? "the current revision"}.`,
391
+ writeKey: `${provider}:${ctx.process.id}:feedback-reply:${feedback.kind}:${feedback.id}:${current.headSha}`
392
+ });
393
+ },
394
+ async acknowledge(ctx, current) {
395
+ const invoke = call(ctx);
396
+ for (const feedback of current.feedbackIds) {
397
+ if (feedback.kind === "review") continue;
398
+ await invoke("add_pull_request_feedback_reaction", {
399
+ pullRequestNumber: current.prNumber,
400
+ feedbackKind: feedback.kind,
401
+ feedbackId: feedback.id,
402
+ writeKey: `${provider}:${ctx.process.id}:feedback-eyes:${feedback.kind}:${feedback.id}`
403
+ });
404
+ }
405
+ },
406
+ async head(ctx, current) {
407
+ return (await call(ctx)("get_pull_request", {
408
+ pullRequestNumber: current.prNumber
409
+ })).head.sha;
410
+ },
411
+ async afterRebase(ctx, current) {
412
+ await call(ctx)("add_pull_request_comment", {
413
+ pullRequestNumber: current.prNumber,
414
+ body: `Merge conflict repair completed at ${current.headSha}; base ${current.conflict?.baseSha}.`,
415
+ writeKey: `rebase:${ctx.process.id}:${current.lastConflictKey}:${current.headSha}`
416
+ });
417
+ }
418
+ };
419
+ }
420
+
421
+ // src/repository-change-publication.ts
422
+ var initialDeliveryState = {
423
+ stage: "not_started",
424
+ issueLinked: false,
425
+ adjustment: null,
426
+ terminalPullRequest: null
427
+ };
428
+ var initialPublicationState = {
429
+ headSha: null,
430
+ prNumber: null,
431
+ prUrl: null,
432
+ conversationCursor: 0,
433
+ reviewCursor: 0,
434
+ inlineCursor: 0,
435
+ feedbackIds: [],
436
+ pipeline: null,
437
+ ciRecoveryCycles: 0,
438
+ delivery: initialDeliveryState
439
+ };
440
+ var publicationObject = (value) => asUnknownRecord(value) ?? {};
441
+ function readPublicationState(state, namespace) {
442
+ const stored = publicationObject(publicationObject(state.extensionState)[namespace]);
443
+ return {
444
+ ...initialPublicationState,
445
+ ...stored,
446
+ delivery: {
447
+ ...initialDeliveryState,
448
+ ...publicationObject(stored.delivery)
449
+ }
450
+ };
451
+ }
452
+ function patchPublicationState(state, namespace, patch) {
453
+ const current = readPublicationState(state, namespace);
454
+ return {
455
+ ...state,
456
+ extensionState: {
457
+ ...state.extensionState,
458
+ [namespace]: {
459
+ ...current,
460
+ ...patch,
461
+ delivery: { ...current.delivery, ...patch.delivery }
462
+ }
463
+ }
464
+ };
465
+ }
466
+ function applyPublicationEvidence(params, current, evidence, countFailure = true) {
467
+ if (evidence.observationKey !== void 0)
468
+ current = { ...current, observationKey: evidence.observationKey };
469
+ switch (evidence.kind) {
470
+ case "feedback": {
471
+ const { kind: _, ...batch } = evidence;
472
+ return { ...current, ...batch, repairReason: "feedback" };
473
+ }
474
+ case "failure":
475
+ return {
476
+ ...current,
477
+ repairReason: "ci",
478
+ pipeline: evidence.pipeline,
479
+ ciRecoveryCycles: current.ciRecoveryCycles + (countFailure ? 1 : 0)
480
+ };
481
+ case "conflict": {
482
+ const conflict = validateConflict(
483
+ evidence.conflict,
484
+ {
485
+ owner: params.owner,
486
+ repo: params.repo,
487
+ prNumber: current.prNumber ?? 0,
488
+ headSha: current.headSha ?? "",
489
+ headBranch: params.workBranch,
490
+ baseBranch: params.baseBranch
491
+ },
492
+ current.lastConflictKey
493
+ );
494
+ return {
495
+ ...current,
496
+ conflict,
497
+ lastConflictKey: conflictKey(conflict),
498
+ repairReason: "rebase"
499
+ };
500
+ }
501
+ case "terminal":
502
+ return {
503
+ ...current,
504
+ delivery: { ...current.delivery, terminalPullRequest: evidence.request }
505
+ };
506
+ default:
507
+ return current;
508
+ }
509
+ }
510
+ function deliveryProgress(value, label, activeStepId) {
511
+ const delivery = value.delivery;
512
+ const step = (id, label2, done) => ({
513
+ id,
514
+ label: label2,
515
+ status: activeStepId === id ? "in_progress" : done ? "completed" : "incomplete"
516
+ });
517
+ const adjustmentHandled = delivery.adjustment === null && delivery.stage === "awaiting" && value.headSha !== null;
518
+ return {
519
+ title: "Delivery progress",
520
+ steps: [
521
+ step("publish_branch", "Publish work branch", value.headSha !== null),
522
+ step("open_pr", "Create or find pull request", value.prNumber !== null),
523
+ step("link_issue", "Link source issue when applicable", delivery.issueLinked),
524
+ step("publish_adjustment", "Publish an adjustment when applicable", adjustmentHandled),
525
+ step(
526
+ "reply_feedback",
527
+ "Acknowledge or reply to feedback when applicable",
528
+ value.feedbackIds.length === 0
529
+ ),
530
+ step("await_evidence", "Await external evidence", delivery.stage === "awaiting"),
531
+ step(
532
+ "reconcile_terminal",
533
+ "Reconcile terminal pull request",
534
+ delivery.terminalPullRequest !== null
535
+ )
536
+ ],
537
+ ...value.prNumber && value.prUrl ? {
538
+ links: [
539
+ {
540
+ id: `${label}-pr-${value.prNumber}`,
541
+ label: `${label} #${value.prNumber}`,
542
+ url: value.prUrl,
543
+ kind: "pull_request"
544
+ }
545
+ ]
546
+ } : {}
547
+ };
548
+ }
549
+ function createRepositoryChangePublication(adapter) {
550
+ const ids = adapter.ids;
551
+ const publication = flow.fragment(`${adapter.namespace}-publication`);
552
+ const remote = (state) => readPublicationState(state, adapter.namespace);
553
+ const patchRemote = (state, patch) => patchPublicationState(state, adapter.namespace, patch);
554
+ async function commitWorkBranch(ctx, commitMessage) {
555
+ const repo = ctx.repo.get("repo");
556
+ return commitAndPushWorkBranch({
557
+ repoPath: repo.fsPath,
558
+ workBranch: repo.workBranch,
559
+ commitMessage,
560
+ gitIdentity: await adapter.identity(ctx)
561
+ });
562
+ }
563
+ const delivery = flow.automatic(ids.deliver).description("Deliver").integrationTools(...adapter.tools.delivery).run(async (ctx) => {
564
+ let current = remote(ctx.state);
565
+ const update = (patch) => {
566
+ current = { ...current, ...patch, delivery: { ...current.delivery, ...patch.delivery } };
567
+ };
568
+ const result = (outcome2) => ({
569
+ outcome: outcome2,
570
+ params: { nextState: patchRemote(ctx.state, current) }
571
+ });
572
+ if (current.pendingEvidence) {
573
+ const evidence = current.pendingEvidence;
574
+ const needsOperator = evidence.kind === "failure" && current.ciRecoveryCycles >= 3;
575
+ current = applyPublicationEvidence(ctx.params, current, evidence, !needsOperator);
576
+ current.pendingEvidence = null;
577
+ if (evidence.kind === "cancelled") return result("aborted");
578
+ if (evidence.kind === "failure")
579
+ return result(needsOperator ? "operator_action" : "ci_ready");
580
+ if (evidence.kind === "conflict") return result("conflict_ready");
581
+ }
582
+ ctx.reportProgress(deliveryProgress(current, adapter.label));
583
+ if (current.delivery.terminalPullRequest) {
584
+ ctx.reportProgress(deliveryProgress(current, adapter.label, "reconcile_terminal"));
585
+ const pr = current.delivery.terminalPullRequest;
586
+ await adapter.reconcileTerminal(ctx, current, pr);
587
+ ctx.reportProgress(deliveryProgress(current, adapter.label));
588
+ return result(pr.merged ? "completed" : "aborted");
589
+ }
590
+ if (!current.headSha) {
591
+ ctx.reportProgress(deliveryProgress(current, adapter.label, "publish_branch"));
592
+ const published = await commitWorkBranch(
593
+ ctx,
594
+ ctx.state.finalization.generatedCommitMessage ?? ""
595
+ );
596
+ update({ headSha: published.headSha, pipeline: null });
597
+ }
598
+ if (!current.prNumber || !current.prUrl) {
599
+ ctx.reportProgress(deliveryProgress(current, adapter.label, "open_pr"));
600
+ const pr = await adapter.ensureRequest(ctx);
601
+ update({ prNumber: pr.number, prUrl: pr.html_url });
602
+ }
603
+ if (!current.delivery.issueLinked) {
604
+ ctx.reportProgress(deliveryProgress(current, adapter.label, "link_issue"));
605
+ await adapter.linkIssue(ctx, current);
606
+ update({ delivery: { issueLinked: true } });
607
+ }
608
+ if (current.delivery.adjustment) {
609
+ const adjustment = current.delivery.adjustment;
610
+ if (adjustment.publishRequired || adjustment.origin === "rebase") {
611
+ ctx.reportProgress(deliveryProgress(current, adapter.label, "publish_adjustment"));
612
+ const published = adjustment.origin === "rebase" ? publishRebase(rebaseInput(ctx)) : await commitWorkBranch(ctx, adapter.commitMessage(adjustment.origin));
613
+ if (adjustment.origin === "rebase") {
614
+ const head = await adapter.head(ctx, current);
615
+ if (head !== published.headSha)
616
+ throw new Error("Pull request head has not caught up with rebase publication");
617
+ }
618
+ update({ headSha: published.headSha, pipeline: null });
619
+ }
620
+ if (adjustment.origin === "rebase") await adapter.afterRebase(ctx, current);
621
+ if (adjustment.origin === "feedback") {
622
+ ctx.reportProgress(deliveryProgress(current, adapter.label, "reply_feedback"));
623
+ await adapter.reply(ctx, current);
624
+ }
625
+ update({
626
+ ...adjustment.origin === "feedback" ? { feedbackIds: [] } : {},
627
+ delivery: { adjustment: null }
628
+ });
629
+ }
630
+ if (current.feedbackIds.length > 0) {
631
+ ctx.reportProgress(deliveryProgress(current, adapter.label, "reply_feedback"));
632
+ await adapter.acknowledge(ctx, current);
633
+ return result("feedback_ready");
634
+ }
635
+ update({ delivery: { stage: "awaiting" } });
636
+ ctx.reportProgress(deliveryProgress(current, adapter.label, "await_evidence"));
637
+ return result("awaiting");
638
+ });
639
+ const outcome = (o, description) => o.description(description).object("nextState").state(({ event }) => event.params.nextState);
640
+ delivery.outcome("awaiting", (o) => outcome(o, "Delivery is waiting for external evidence").wait()).outcome(
641
+ "feedback_ready",
642
+ (o) => outcome(o, "Pull request feedback is acknowledged and ready for revision").to(ids.feedback)
643
+ ).outcome("completed", (o) => outcome(o, "Merged pull request was reconciled").complete()).outcome(
644
+ "aborted",
645
+ (o) => outcome(o, "Closed pull request was reconciled").lifecycleStatus("aborted")
646
+ );
647
+ for (const [name, target] of [
648
+ ["ci_ready", ids.ciRepair],
649
+ ["conflict_ready", ids.feedback],
650
+ ["operator_action", ids.operator]
651
+ ]) {
652
+ delivery.outcome(name, (o) => outcome(o, "Route observed delivery evidence").to(target));
653
+ }
654
+ for (const source of adapter.sources) {
655
+ const attach = (id, operator) => delivery.externalAction(id, source.source, (external) => {
656
+ external.label(source.label).when(
657
+ ({ params, state }) => (!source.enabled || source.enabled(params)) && (source.kind !== "failure" || remote(state).ciRecoveryCycles >= 3 === operator)
658
+ );
659
+ if (source.kind === "cancelled") return external.lifecycleStatus("aborted");
660
+ external.to(
661
+ source.kind === "conflict" ? ids.feedback : source.kind === "failure" ? operator ? ids.operator : ids.ciRepair : ids.deliver
662
+ );
663
+ return external.effect((input) => {
664
+ const evidence = source.read(input);
665
+ const current = remote(input.state);
666
+ return {
667
+ state: patchRemote(
668
+ input.state,
669
+ source.kind === "observation" ? { pendingEvidence: evidence } : applyPublicationEvidence(input.params, current, evidence, !operator)
670
+ )
671
+ };
672
+ });
673
+ });
674
+ attach(source.id, false);
675
+ if (source.kind === "failure") attach(source.operatorId ?? `${source.id}_operator`, true);
676
+ }
677
+ publication.turn(delivery);
678
+ function rebaseInput(ctx) {
679
+ const project = ctx.repo.get("repo");
680
+ const conflict = remote(ctx.state).conflict;
681
+ if (!conflict) throw new Error("Missing conflict evidence");
682
+ return { projectKey: "repo", path: project.fsPath, workBranch: project.workBranch, conflict };
683
+ }
684
+ function repairReason(state, kind) {
685
+ return kind === "feedback" && remote(state).repairReason === "rebase" ? "rebase" : kind;
686
+ }
687
+ function revisionPrompt(kind) {
688
+ return (ctx) => {
689
+ const current = remote(ctx.state);
690
+ if (repairReason(ctx.state, kind) === "rebase")
691
+ return `${rebasePrompt} Evidence: ${JSON.stringify(current.conflict)}. Call changes_ready or no_changes when verified complete, cannot_repair when blocked.`;
692
+ return adapter.prompt(kind, current);
693
+ };
694
+ }
695
+ function revisionTurn(id, kind) {
696
+ const turn = flow.llm(id).description(kind === "feedback" ? "Address Feedback" : "Fix CI").tools("read", "bash", "edit", "write").resolveIntegrationTools(
697
+ (_params, state) => repairReason(state, kind) === "rebase" ? [] : adapter.tools[kind]
698
+ ).prepare(
699
+ (ctx) => repairReason(ctx.state, kind) === "rebase" ? startRebase(rebaseInput(ctx)) : {}
700
+ ).freshPrimary().prompt(revisionPrompt(kind));
701
+ for (const [name, description, publishRequired] of [
702
+ ["changes_ready", "Repository changes are ready to publish", true],
703
+ ["no_changes", "No repository change is required", false]
704
+ ]) {
705
+ turn.outcomeTool(
706
+ name,
707
+ (tool) => tool.resultSummary().description(description).to(ids.deliver).state(
708
+ ({ ctx }) => patchRemote(ctx.state, {
709
+ delivery: { adjustment: { origin: repairReason(ctx.state, kind), publishRequired } }
710
+ })
711
+ )
712
+ );
713
+ }
714
+ return turn.outcomeTool(
715
+ "cannot_repair",
716
+ (tool) => tool.description("The adjustment requires operator action").to(ids.operator)
717
+ );
718
+ }
719
+ publication.turn(revisionTurn(ids.feedback, "feedback"));
720
+ publication.turn(revisionTurn(ids.ciRepair, "ci"));
721
+ publication.turn({
722
+ id: ids.operator,
723
+ definition: {
724
+ kind: "human",
725
+ description: "Repository repair needs operator action",
726
+ operatorAttention: "required",
727
+ actions: {
728
+ retry_repair: {
729
+ label: "Retry repair",
730
+ acceptanceState: "accepted",
731
+ branches: { feedback: { to: ids.feedback }, ci: { to: ids.ciRepair } },
732
+ choose: ({ ctx }) => remote(ctx.state).repairReason === "rebase" || remote(ctx.state).repairReason === "feedback" ? "feedback" : "ci"
733
+ },
734
+ resume_waiting: {
735
+ label: "Resume waiting",
736
+ acceptanceState: "accepted",
737
+ to: ids.deliver,
738
+ effect: ({ ctx }) => ({
739
+ state: patchRemote(ctx.state, {
740
+ feedbackIds: [],
741
+ delivery: { adjustment: null }
742
+ })
743
+ })
744
+ },
745
+ abort: { label: "Abort process", acceptanceState: "neutral", lifecycleStatus: "aborted" }
746
+ }
747
+ }
748
+ });
749
+ return {
750
+ /** @public */
751
+ entryTurnId: ids.deliver,
752
+ /** @public */
753
+ fragment: publication,
754
+ /** @public */
755
+ happyPath: [ids.deliver]
756
+ };
757
+ }
758
+ export {
759
+ applyPublicationEvidence,
760
+ createRepositoryChangePublication,
761
+ patchPublicationState,
762
+ publicationObject,
763
+ pullRequestPublicationCallbacks,
764
+ pullRequestPublicationSources,
765
+ readPublicationState,
766
+ readPullRequestFeedback,
767
+ reconcilePullRequestSourceIssue,
768
+ resolvePullRequestGitIdentity
769
+ };
770
+ //# sourceMappingURL=repository-change-publication.js.map