@leitwerk-dev/coding 0.4.0 → 0.4.2

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 (46) hide show
  1. package/README.md +67 -11
  2. package/dist/{chunk-Q24RPXOA.js → chunk-3WJRJ3Q7.js} +68 -7
  3. package/dist/chunk-3WJRJ3Q7.js.map +1 -0
  4. package/dist/chunk-B3PE6DPF.js +820 -0
  5. package/dist/chunk-B3PE6DPF.js.map +1 -0
  6. package/dist/chunk-E3DB4TIZ.js +49 -0
  7. package/dist/chunk-E3DB4TIZ.js.map +1 -0
  8. package/dist/{chunk-BI45R2FH.js → chunk-QD6FI4HR.js} +1 -1
  9. package/dist/chunk-QD6FI4HR.js.map +1 -0
  10. package/dist/finalization-git-internal.d.ts +6 -0
  11. package/dist/finalization-git-internal.d.ts.map +1 -1
  12. package/dist/finalization-git.js +2 -1
  13. package/dist/index.js +3 -2
  14. package/dist/index.js.map +1 -1
  15. package/dist/pull-request-publication-internal.d.ts +8 -0
  16. package/dist/pull-request-publication-internal.d.ts.map +1 -1
  17. package/dist/repository-change-process.d.ts.map +1 -1
  18. package/dist/repository-change-publication.d.ts +16 -3
  19. package/dist/repository-change-publication.d.ts.map +1 -1
  20. package/dist/repository-change-publication.js +283 -69
  21. package/dist/repository-change-publication.js.map +1 -1
  22. package/dist/repository-publication-receipt.d.ts +23 -0
  23. package/dist/repository-publication-receipt.d.ts.map +1 -0
  24. package/dist/repository-rebase/git.d.ts +8 -0
  25. package/dist/repository-rebase/git.d.ts.map +1 -1
  26. package/dist/repository-reconciliation.d.ts +47 -0
  27. package/dist/repository-reconciliation.d.ts.map +1 -0
  28. package/dist/repository-record.d.ts +6 -0
  29. package/dist/repository-record.d.ts.map +1 -0
  30. package/dist/turns/implement.d.ts +1 -1
  31. package/dist/turns/implement.d.ts.map +1 -1
  32. package/dist/turns/implement.js +1 -1
  33. package/package.json +5 -5
  34. package/src/finalization-git-internal.ts +75 -6
  35. package/src/pull-request-publication-internal.ts +3 -2
  36. package/src/repository-change-process.ts +19 -2
  37. package/src/repository-change-publication.ts +243 -57
  38. package/src/repository-publication-receipt.ts +71 -0
  39. package/src/repository-rebase/git.ts +108 -29
  40. package/src/repository-reconciliation.ts +600 -0
  41. package/src/repository-record.ts +14 -0
  42. package/src/turns/implement.ts +4 -1
  43. package/dist/chunk-BI45R2FH.js.map +0 -1
  44. package/dist/chunk-OM2AMDTJ.js +0 -347
  45. package/dist/chunk-OM2AMDTJ.js.map +0 -1
  46. package/dist/chunk-Q24RPXOA.js.map +0 -1
@@ -0,0 +1,820 @@
1
+ import {
2
+ buildRepositoryCommitMessagesPrompt,
3
+ parseRepositoryCommitMessages
4
+ } from "./chunk-DNG7D77K.js";
5
+ import {
6
+ buildGeneratePlanPrompt
7
+ } from "./chunk-ABQH2WZT.js";
8
+ import {
9
+ buildImplementPrompt
10
+ } from "./chunk-QD6FI4HR.js";
11
+ import {
12
+ buildStreamlinedSimplificationPrompt
13
+ } from "./chunk-SKGB4CZS.js";
14
+ import {
15
+ readPublicationReceipt,
16
+ readRepositoryBinding,
17
+ repositoryBindingMatches,
18
+ repositoryRecord,
19
+ savePublicationReceipt
20
+ } from "./chunk-E3DB4TIZ.js";
21
+ import {
22
+ codingPurposes,
23
+ prepareRepositoryCommitMessageEvidence
24
+ } from "./chunk-M2VTUPFO.js";
25
+
26
+ // src/actions.ts
27
+ var codingActionIds = {
28
+ /** @public */
29
+ approvePlan: "approve_plan",
30
+ /** @internal */
31
+ requestRevision: "request_revision",
32
+ /** @internal */
33
+ runReview: "run_review",
34
+ /** @internal */
35
+ simplify: "simplify",
36
+ /** @internal */
37
+ acceptReview: "accept_review",
38
+ /** @internal */
39
+ requestReviewChanges: "request_review_changes",
40
+ /** @internal */
41
+ dismissReview: "dismiss_review",
42
+ /** @public */
43
+ finalizeChange: "finalize_change"
44
+ };
45
+ function notesForm(id, title, label, description) {
46
+ return {
47
+ id,
48
+ title,
49
+ fields: [
50
+ { id: "message", label, kind: "textarea", primaryPrompt: true, required: true, description }
51
+ ],
52
+ submitLabel: title
53
+ };
54
+ }
55
+ var requestRevisionForm = notesForm(
56
+ codingActionIds.requestRevision,
57
+ "Request revision",
58
+ "Revision notes",
59
+ "Instructions for the next implementation pass."
60
+ );
61
+ var requestReviewChangesForm = notesForm(
62
+ codingActionIds.requestReviewChanges,
63
+ "Request review changes",
64
+ "Review notes",
65
+ "Instructions for the next review pass."
66
+ );
67
+ var acceptReviewForm = {
68
+ id: codingActionIds.acceptReview,
69
+ title: "Accept review",
70
+ fields: [
71
+ {
72
+ id: "message",
73
+ label: "Review adjustment",
74
+ kind: "textarea",
75
+ primaryPrompt: true,
76
+ description: "Optional instructions to apply with the accepted review, such as dropping one finding."
77
+ }
78
+ ],
79
+ submitLabel: "Accept review"
80
+ };
81
+
82
+ // src/repository-reconciliation.ts
83
+ import { execFileSync } from "child_process";
84
+ import { randomUUID } from "crypto";
85
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "fs";
86
+ import { hostname } from "os";
87
+ import { join } from "path";
88
+ import { repositoryGitArgs, repositoryGitSubprocessEnv } from "@leitwerk-dev/process-sdk";
89
+ import { resolveGitBinary } from "@leitwerk-dev/process-sdk/git-binary";
90
+ function repository(input) {
91
+ function git(args, extra = {}) {
92
+ const output = execFileSync(resolveGitBinary(), repositoryGitArgs(args), {
93
+ cwd: input.repoPath,
94
+ encoding: "utf8",
95
+ env: repositoryGitSubprocessEnv(input.projectKey, {
96
+ GIT_TERMINAL_PROMPT: "0",
97
+ GIT_EDITOR: "true",
98
+ GIT_SEQUENCE_EDITOR: "true",
99
+ ...extra
100
+ }),
101
+ stdio: ["ignore", "pipe", "pipe"],
102
+ maxBuffer: 16 * 1024 * 1024
103
+ });
104
+ return output.endsWith("\0") ? output : output.replace(/\r?\n$/, "");
105
+ }
106
+ const directory = git(["rev-parse", "--absolute-git-dir"]);
107
+ if (git(["remote", "get-url", "--push", "--all", "origin"]) !== git(["remote", "get-url", "origin"]))
108
+ throw new Error(
109
+ "Repository reconciliation binding changed: fetch and push endpoints must match"
110
+ );
111
+ const { read, save } = repositoryRecord(directory, "reconciliation");
112
+ const binding = (branch) => readRepositoryBinding((...args) => git(args), branch);
113
+ return { git, directory, read, save, binding };
114
+ }
115
+ function integrationIdentityEnv(identity) {
116
+ if (!identity?.name.trim() || !identity.email.trim() || /[\r\n\0]/.test(identity.name + identity.email))
117
+ throw new Error(
118
+ "A trusted Git identity is required for source integration; local work was retained"
119
+ );
120
+ return {
121
+ GIT_AUTHOR_NAME: identity.name,
122
+ GIT_AUTHOR_EMAIL: identity.email,
123
+ GIT_COMMITTER_NAME: identity.name,
124
+ GIT_COMMITTER_EMAIL: identity.email
125
+ };
126
+ }
127
+ function ignoredPaths(git) {
128
+ return git([
129
+ "ls-files",
130
+ "--others",
131
+ "--ignored",
132
+ "--exclude-standard",
133
+ "--directory",
134
+ "--no-empty-directory",
135
+ "-z"
136
+ ]).split("\0").filter(Boolean).map((file) => file.replace(/\/$/, ""));
137
+ }
138
+ function assertIgnoredProtection(git, protectedPaths = []) {
139
+ if (!protectedPaths.length) return;
140
+ const visible = git(["ls-files", "--cached", "--others", "--exclude-standard", "-z"]).split("\0");
141
+ if (protectedPaths.some(
142
+ (ignored) => visible.some((file) => file === ignored || file.startsWith(`${ignored}/`))
143
+ ))
144
+ throw new Error(
145
+ "Previously ignored local files became publishable; review ignore rules before continuing. Local files were retained"
146
+ );
147
+ }
148
+ function ignoredPathsCollide(git, ignored, target, replayRange) {
149
+ const paths = [
150
+ ...git(["ls-tree", "-r", "--name-only", "-z", target]).split("\0"),
151
+ ...git(["log", "--format=", "--full-history", "-m", "--name-only", "-z", replayRange]).split(
152
+ "\0"
153
+ )
154
+ ];
155
+ return ignored.some(
156
+ (file) => paths.some((p) => p === file || p.startsWith(`${file}/`) || file.startsWith(`${p}/`))
157
+ );
158
+ }
159
+ function ancestor(git, a, b) {
160
+ try {
161
+ git(["merge-base", "--is-ancestor", a, b]);
162
+ return true;
163
+ } catch (error) {
164
+ if (error.status === 1) return false;
165
+ throw error;
166
+ }
167
+ }
168
+ function withLock(directory, run) {
169
+ const lock = join(directory, "leitwerk-reconciliation.lock");
170
+ try {
171
+ mkdirSync(lock);
172
+ } catch (error) {
173
+ if (error.code !== "EEXIST") throw error;
174
+ const owner = JSON.parse(readFileSync(join(lock, "owner.json"), "utf8"));
175
+ if (owner.host !== hostname())
176
+ throw new Error("Repository reconciliation is owned by another worker");
177
+ try {
178
+ process.kill(owner.pid, 0);
179
+ } catch (failure) {
180
+ if (failure.code !== "ESRCH") throw failure;
181
+ rmSync(lock, { recursive: true });
182
+ return withLock(directory, run);
183
+ }
184
+ throw new Error("Repository reconciliation is already running");
185
+ }
186
+ try {
187
+ writeFileSync(
188
+ join(lock, "owner.json"),
189
+ JSON.stringify({ host: hostname(), pid: process.pid }),
190
+ { mode: 384 }
191
+ );
192
+ return run();
193
+ } finally {
194
+ rmSync(lock, { recursive: true });
195
+ }
196
+ }
197
+ function reconcileRepository(input) {
198
+ const { git, directory, read, save, binding: readBinding } = repository(input);
199
+ return withLock(directory, () => {
200
+ git(["check-ref-format", `refs/heads/${input.workBranch}`]);
201
+ const binding = readBinding(input.workBranch);
202
+ let record = read();
203
+ if (!repositoryBindingMatches(record, binding))
204
+ throw new Error("Repository reconciliation binding changed");
205
+ if (record?.sourceIntegration) {
206
+ if (git(["branch", "--show-current"]) !== input.workBranch)
207
+ throw new Error("Source integration checkout branch changed; local work was retained");
208
+ const { previous, replacement } = record.sourceIntegration;
209
+ const current = git(["rev-parse", "HEAD"]);
210
+ if (current === previous)
211
+ git(["update-ref", `refs/heads/${input.workBranch}`, replacement, previous]);
212
+ else if (current !== replacement)
213
+ throw new Error("Checkout changed during source integration; recovery refs were retained");
214
+ delete record.sourceIntegration;
215
+ save(record);
216
+ }
217
+ const rebaseActive = () => ["rebase-merge", "rebase-apply"].some((name) => existsSync(join(directory, name)));
218
+ if (rebaseActive() && !record?.operation)
219
+ throw new Error("An unrelated rebase is already in progress; local work was retained");
220
+ if (existsSync(join(directory, "MERGE_HEAD")) || existsSync(join(directory, "CHERRY_PICK_HEAD")))
221
+ throw new Error("An unrelated Git operation is in progress; local work was retained");
222
+ if (!rebaseActive() && git(["branch", "--show-current"]) !== input.workBranch)
223
+ throw new Error(`Expected checkout on '${input.workBranch}'; local work was retained`);
224
+ if (!record?.operation) {
225
+ assertIgnoredProtection(git, record?.protectedIgnored);
226
+ const ignored = ignoredPaths(git);
227
+ git([
228
+ "fetch",
229
+ "--no-tags",
230
+ "origin",
231
+ `+refs/heads/${input.workBranch}:refs/leitwerk/reconcile-remote`
232
+ ]);
233
+ const remote = git(["rev-parse", "refs/leitwerk/reconcile-remote"]);
234
+ const head = git(["rev-parse", "HEAD"]);
235
+ let baseline = record?.baseline ?? input.baselineSha;
236
+ const receipt = readPublicationReceipt(directory);
237
+ if (!repositoryBindingMatches(receipt, binding))
238
+ throw new Error("Repository publication receipt binding changed");
239
+ if (receipt?.status === "attempting") {
240
+ if (remote === receipt.candidate || ancestor(git, receipt.candidate, remote)) {
241
+ receipt.status = "accepted";
242
+ savePublicationReceipt(directory, receipt);
243
+ } else {
244
+ throw new Error(
245
+ "Prior publication outcome is uncertain; local work was retained for operator reconciliation"
246
+ );
247
+ }
248
+ }
249
+ if (receipt?.status === "accepted" && record?.publicationReceiptSha !== receipt.candidate)
250
+ baseline = receipt.candidate;
251
+ git(["cat-file", "-e", `${baseline}^{commit}`]);
252
+ if (!ancestor(git, baseline, head))
253
+ throw new Error(
254
+ "Cannot establish unpublished work from the retained baseline; local work was retained"
255
+ );
256
+ record = {
257
+ ...record,
258
+ ...binding,
259
+ baseline,
260
+ remoteSeen: true,
261
+ protectedIgnored: [.../* @__PURE__ */ new Set([...record?.protectedIgnored ?? [], ...ignored])],
262
+ publicationReceiptSha: receipt?.status === "accepted" ? receipt.candidate : record?.publicationReceiptSha
263
+ };
264
+ if ((remote === baseline || remote === head) && !record.joinParent) {
265
+ record.baseline = remote;
266
+ save(record);
267
+ return { status: "ready", remoteHead: remote, headSha: head, changed: false };
268
+ }
269
+ if (git(["diff", "--name-only", "--diff-filter=U"]))
270
+ throw new Error("Unresolved local conflicts must be repaired before reconciliation");
271
+ if (git(["submodule", "foreach", "--quiet", "git status --porcelain"]))
272
+ throw new Error("Commit or preserve dirty submodule work before reconciliation");
273
+ if (ignoredPathsCollide(git, ignored, remote, `${record.baseline}..${head}`))
274
+ throw new Error("Remote changes collide with ignored files; local files were retained");
275
+ if (ancestor(git, head, remote)) record.baseline = head;
276
+ const id = randomUUID();
277
+ const temporaryIndex = join(directory, `leitwerk-index-${id}`);
278
+ const identity = {
279
+ GIT_AUTHOR_NAME: "Leitwerk checkpoint",
280
+ GIT_AUTHOR_EMAIL: "checkpoint@leitwerk.invalid",
281
+ GIT_COMMITTER_NAME: "Leitwerk checkpoint",
282
+ GIT_COMMITTER_EMAIL: "checkpoint@leitwerk.invalid"
283
+ };
284
+ try {
285
+ const stagedTree = git(["write-tree"]);
286
+ const index = git(
287
+ ["commit-tree", stagedTree, "-p", head, "-m", `Leitwerk index checkpoint ${id}`],
288
+ identity
289
+ );
290
+ git(["read-tree", stagedTree], { GIT_INDEX_FILE: temporaryIndex });
291
+ git(["add", "--all"], { GIT_INDEX_FILE: temporaryIndex });
292
+ const workTree = git(["write-tree"], { GIT_INDEX_FILE: temporaryIndex });
293
+ const work = git(
294
+ ["commit-tree", workTree, "-p", index, "-m", `Leitwerk worktree checkpoint ${id}`],
295
+ identity
296
+ );
297
+ git(["update-ref", `refs/leitwerk/checkpoints/${id}`, work]);
298
+ const replayIdentity = record.joinIdentity ?? input.gitIdentity;
299
+ if (replayIdentity || record.baseline !== head) integrationIdentityEnv(replayIdentity);
300
+ record.operation = {
301
+ id,
302
+ head,
303
+ index,
304
+ work,
305
+ remote,
306
+ phase: "captured",
307
+ identity: replayIdentity
308
+ };
309
+ save(record);
310
+ } finally {
311
+ rmSync(temporaryIndex, { force: true });
312
+ }
313
+ }
314
+ const operation = record.operation;
315
+ if (!operation) throw new Error("Missing reconciliation checkpoint");
316
+ if (operation.phase === "captured") {
317
+ if (operation.identity || record.baseline !== operation.head)
318
+ integrationIdentityEnv(operation.identity);
319
+ const current = git(["rev-parse", "HEAD"]);
320
+ const indexTree = git(["write-tree"]);
321
+ if (![operation.head, operation.work].includes(current) || ![
322
+ git(["rev-parse", `${operation.index}^{tree}`]),
323
+ git(["rev-parse", `${operation.work}^{tree}`])
324
+ ].includes(indexTree))
325
+ throw new Error(
326
+ "Checkout changed after its checkpoint; new local work and recovery refs were retained"
327
+ );
328
+ git(["read-tree", operation.work]);
329
+ if (current !== operation.work)
330
+ git(["update-ref", `refs/heads/${input.workBranch}`, operation.work, operation.head]);
331
+ operation.phase = "rebasing";
332
+ save(record);
333
+ }
334
+ if (operation.phase === "rebasing") {
335
+ const conflicts = () => ({
336
+ status: "conflicts",
337
+ remoteHead: operation.remote,
338
+ headSha: git(["rev-parse", "HEAD"]),
339
+ changed: true
340
+ });
341
+ if (rebaseActive()) return conflicts();
342
+ if (git(["rev-parse", "HEAD"]) === operation.work) {
343
+ try {
344
+ git(
345
+ [
346
+ "-c",
347
+ "core.hooksPath=/dev/null",
348
+ "-c",
349
+ "commit.gpgSign=false",
350
+ "rebase",
351
+ "--rebase-merges",
352
+ "--reapply-cherry-picks",
353
+ "--empty=keep",
354
+ "--onto",
355
+ operation.remote,
356
+ record.baseline
357
+ ],
358
+ {
359
+ GIT_COMMITTER_NAME: operation.identity?.name ?? "Leitwerk checkpoint",
360
+ GIT_COMMITTER_EMAIL: operation.identity?.email ?? "checkpoint@leitwerk.invalid"
361
+ }
362
+ );
363
+ } catch (error) {
364
+ if (!rebaseActive()) throw error;
365
+ return conflicts();
366
+ }
367
+ }
368
+ if (git(["log", "-1", "--format=%s"]) !== `Leitwerk worktree checkpoint ${operation.id}` || git(["log", "-1", "--format=%s", "HEAD^"]) !== `Leitwerk index checkpoint ${operation.id}`)
369
+ throw new Error(
370
+ "Reconciliation checkpoint commits were changed or skipped; recovery refs were retained"
371
+ );
372
+ operation.resultHead = git(["rev-parse", "HEAD~2"]);
373
+ operation.resultIndex = git(["rev-parse", "HEAD~1^{tree}"]);
374
+ git(["update-ref", `refs/leitwerk/reconciled/${operation.id}`, git(["rev-parse", "HEAD"])]);
375
+ operation.phase = "restoring";
376
+ save(record);
377
+ }
378
+ if (!operation.resultHead || !operation.resultIndex)
379
+ throw new Error("Incomplete reconciliation result");
380
+ if (record.joinParent && !ancestor(git, record.joinParent, operation.resultHead)) {
381
+ operation.resultHead = git(
382
+ [
383
+ "commit-tree",
384
+ git(["rev-parse", `${operation.resultHead}^{tree}`]),
385
+ "-p",
386
+ operation.resultHead,
387
+ "-p",
388
+ record.joinParent,
389
+ "-m",
390
+ "Integrate target branch with concurrent source changes"
391
+ ],
392
+ integrationIdentityEnv(record.joinIdentity)
393
+ );
394
+ git([
395
+ "update-ref",
396
+ `refs/leitwerk/target-integrations/${operation.id}`,
397
+ operation.resultHead
398
+ ]);
399
+ save(record);
400
+ }
401
+ const integrated = git(["rev-parse", `refs/leitwerk/reconciled/${operation.id}`]);
402
+ const currentHead = git(["rev-parse", "HEAD"]);
403
+ const currentIndex = git(["write-tree"]);
404
+ if (![operation.resultHead, integrated].includes(currentHead) || ![operation.resultIndex, git(["rev-parse", `${integrated}^{tree}`])].includes(currentIndex))
405
+ throw new Error(
406
+ "Checkout changed during interrupted restoration; local work and recovery refs were retained"
407
+ );
408
+ git(["update-ref", `refs/heads/${input.workBranch}`, operation.resultHead, currentHead]);
409
+ git(["read-tree", operation.resultIndex]);
410
+ record.baseline = operation.remote;
411
+ delete record.operation;
412
+ delete record.joinParent;
413
+ delete record.joinIdentity;
414
+ save(record);
415
+ assertIgnoredProtection(git, record.protectedIgnored);
416
+ return {
417
+ status: "ready",
418
+ remoteHead: operation.remote,
419
+ headSha: operation.resultHead,
420
+ changed: true
421
+ };
422
+ });
423
+ }
424
+ function assertReconciliationTargetSafe(input, targetSha) {
425
+ const { git, read } = repository(input);
426
+ assertIgnoredProtection(git, read()?.protectedIgnored);
427
+ if (ignoredPathsCollide(git, ignoredPaths(git), targetSha, `${targetSha}..HEAD`))
428
+ throw new Error("Target changes collide with ignored files; local files were retained");
429
+ }
430
+ function retainConcurrentRebase(input) {
431
+ const { git, directory, read, save, binding: readBinding } = repository(input);
432
+ withLock(directory, () => {
433
+ const old = read();
434
+ if (old?.operation || old?.sourceIntegration)
435
+ throw new Error("Source reconciliation is already in progress");
436
+ if (git(["branch", "--show-current"]) !== input.workBranch || git(["rev-parse", "HEAD"]) !== input.rebasedHead || git(["status", "--porcelain"]))
437
+ throw new Error(
438
+ "Target rebase changed before source reconciliation; local work was retained"
439
+ );
440
+ const binding = readBinding(input.workBranch);
441
+ if (!repositoryBindingMatches(old, binding))
442
+ throw new Error("Repository reconciliation binding changed");
443
+ const identity = integrationIdentityEnv(input.gitIdentity);
444
+ const id = randomUUID();
445
+ git(["update-ref", `refs/leitwerk/target-repairs/${id}`, input.rebasedHead]);
446
+ const replacement = git(
447
+ [
448
+ "commit-tree",
449
+ git(["rev-parse", `${input.rebasedHead}^{tree}`]),
450
+ "-p",
451
+ input.baselineSha,
452
+ "-m",
453
+ "Reconcile target-branch repair"
454
+ ],
455
+ identity
456
+ );
457
+ git(["update-ref", `refs/leitwerk/target-deltas/${id}`, replacement]);
458
+ save({
459
+ ...binding,
460
+ baseline: input.baselineSha,
461
+ remoteSeen: true,
462
+ joinParent: input.targetBase,
463
+ joinIdentity: input.gitIdentity,
464
+ protectedIgnored: old?.protectedIgnored,
465
+ publicationReceiptSha: old?.publicationReceiptSha,
466
+ sourceIntegration: { previous: input.rebasedHead, replacement }
467
+ });
468
+ });
469
+ }
470
+ function repositoryWorktreeIsDirty(input) {
471
+ return Boolean(repository(input).git(["status", "--porcelain"]));
472
+ }
473
+ function prepareInitialRepository(input) {
474
+ const { git, read, save, directory, binding } = repository(input);
475
+ withLock(directory, () => {
476
+ if (!read())
477
+ save({
478
+ ...binding(input.workBranch),
479
+ baseline: git(["rev-parse", "HEAD"]),
480
+ protectedIgnored: ignoredPaths(git)
481
+ });
482
+ });
483
+ return reconcilePublicationRepository(input);
484
+ }
485
+ function reconcilePublicationRepository(input) {
486
+ const { git, read, directory } = repository(input);
487
+ const record = read();
488
+ const receipt = readPublicationReceipt(directory);
489
+ const baselineSha = record?.baseline ?? input.baselineSha ?? (receipt?.status === "accepted" ? receipt.candidate : receipt?.expectedHead ?? (receipt?.status === "attempting" ? receipt.candidate : void 0));
490
+ assertIgnoredProtection(git, record?.protectedIgnored);
491
+ const remote = git(["ls-remote", "--heads", "origin", `refs/heads/${input.workBranch}`]).split(
492
+ /\s+/
493
+ )[0];
494
+ if (!remote && !input.baselineSha && !record?.remoteSeen && !record?.operation && (!receipt || receipt.status === "rejected" && receipt.expectedHead === null))
495
+ return {
496
+ status: "ready",
497
+ remoteHead: null,
498
+ headSha: git(["rev-parse", "HEAD"]),
499
+ changed: false
500
+ };
501
+ if (!remote)
502
+ throw new Error(
503
+ "Remote source branch is missing or its publication is uncertain; local work was retained and the branch will not be recreated automatically"
504
+ );
505
+ if (!baselineSha)
506
+ throw new Error("Cannot establish the retained work baseline; local work was retained");
507
+ return reconcileRepository({ ...input, baselineSha });
508
+ }
509
+ function recordRepositoryPublication(input, headSha) {
510
+ const { directory, read, save, binding: readBinding } = repository(input);
511
+ withLock(directory, () => {
512
+ const old = read();
513
+ if (old?.operation) throw new Error("Cannot acknowledge publication during reconciliation");
514
+ const binding = readBinding(input.workBranch);
515
+ if (!repositoryBindingMatches(old, binding))
516
+ throw new Error("Repository reconciliation binding changed");
517
+ save({
518
+ ...binding,
519
+ baseline: headSha,
520
+ publicationReceiptSha: headSha,
521
+ remoteSeen: true,
522
+ protectedIgnored: old?.protectedIgnored
523
+ });
524
+ });
525
+ }
526
+ var reconciliationPrompt = `Repository synchronization preserves the current remote source branch and unpublished local work. If preparation left a rebase in progress, inspect git status and .git/leitwerk-reconciliation.json. Resolve conflicts preserving both intended changes and the original authors/sign-offs, then git add and GIT_EDITOR=true git rebase --continue until complete. Use the captured operation.identity for the committer when continuing, if present. Do not skip commits, remove the two Leitwerk checkpoint commits, reset, abort, or push. Checkpoint commits will be removed automatically by delivery; do not amend them. After resolving, finish with the turn's required success outcome so delivery can restore the ordinary checkout and request validation. If blocked, use cannot_repair when available or abort_turn otherwise, and retain the checkout. When no rebase is active, perform the requested adjustment and validate the combined result against the current repository instructions before the required success outcome. Never publish without validation after reconciliation.`;
527
+
528
+ // src/repository-change-process.ts
529
+ import { asUnknownRecord, trimString as normalizeMessage } from "@leitwerk-dev/domain";
530
+ import {
531
+ flow,
532
+ humanTurn,
533
+ revisionAction
534
+ } from "@leitwerk-dev/process-sdk";
535
+
536
+ // src/repository-change-state-internal.ts
537
+ import { parseStructuralProcessState } from "@leitwerk-dev/process-sdk";
538
+ function toRecord(value) {
539
+ return typeof value === "object" && value !== null ? value : {};
540
+ }
541
+ function parseFinalizationState(value) {
542
+ const record = toRecord(value);
543
+ return {
544
+ generatedCommitMessage: typeof record.generatedCommitMessage === "string" ? record.generatedCommitMessage : null,
545
+ ...record.commitMessages ? {
546
+ commitMessages: Object.fromEntries(
547
+ Object.entries(toRecord(record.commitMessages)).filter(
548
+ (entry) => typeof entry[1] === "string"
549
+ )
550
+ )
551
+ } : {}
552
+ };
553
+ }
554
+ var repositoryChangeStateCodec = {
555
+ parse(value) {
556
+ const record = toRecord(value);
557
+ return {
558
+ ...parseStructuralProcessState(record),
559
+ finalization: parseFinalizationState(record.finalization),
560
+ extensionState: toRecord(record.extensionState),
561
+ routing: toRecord(record.routing)
562
+ };
563
+ },
564
+ serialize(value) {
565
+ return value;
566
+ }
567
+ };
568
+
569
+ // src/repository-change-process.ts
570
+ function createRepositoryChangeProcess(config) {
571
+ const tools = ["read", "bash", "edit", "write"];
572
+ const planDecision = humanTurn({
573
+ description: "Review Plan",
574
+ reviewSemanticRef: "plan",
575
+ notesFields: [
576
+ {
577
+ id: "message",
578
+ label: "Revision notes",
579
+ placeholder: "Describe what the next plan revision should improve",
580
+ required: true
581
+ }
582
+ ],
583
+ commentary: "Approve this plan or request a revision with comments.",
584
+ actions: {
585
+ [codingActionIds.approvePlan]: {
586
+ label: "Approve plan",
587
+ description: "Accept the current plan and continue into implementation.",
588
+ acceptanceState: "accepted",
589
+ to: "implement",
590
+ effect: ({ ctx }) => {
591
+ if (!ctx.state.semanticEntryRefs.plan?.turnRecordId?.trim())
592
+ throw new Error("No plan is available for approval");
593
+ return {
594
+ emit: [
595
+ {
596
+ type: "plan_approved",
597
+ data: {
598
+ externalId: ctx.process.externalId,
599
+ planRevision: ctx.process.planRevision
600
+ }
601
+ }
602
+ ]
603
+ };
604
+ }
605
+ },
606
+ [codingActionIds.requestRevision]: revisionAction({
607
+ label: "Request revision",
608
+ description: "Send the plan back for another draft revision.",
609
+ acceptanceState: "requires_changes",
610
+ form: requestRevisionForm,
611
+ schedulable: true,
612
+ to: "generate_plan",
613
+ queueTarget: { semanticRef: "currentPrimaryPathLeaf" },
614
+ effect: ({ input }) => ({
615
+ emit: [
616
+ { type: "plan_revision_requested", data: { message: normalizeMessage(input.message) } }
617
+ ]
618
+ })
619
+ })
620
+ }
621
+ });
622
+ if (config.workflow?.planBypassSource)
623
+ planDecision.externalActions = {
624
+ bypass_plan: {
625
+ id: "bypass_plan",
626
+ label: "Skip plan approval",
627
+ source: config.workflow.planBypassSource,
628
+ to: "implement",
629
+ effect: ({ state, process: process2, event }) => {
630
+ if (event.planRevision !== process2.planRevision)
631
+ throw new Error("Stale plan bypass event");
632
+ return {
633
+ state: {
634
+ ...state,
635
+ routing: {
636
+ ...state.routing,
637
+ plan: { planRevision: process2.planRevision, skip: true, reason: "Jira label" }
638
+ }
639
+ },
640
+ emit: [
641
+ {
642
+ type: "plan_approved",
643
+ data: {
644
+ planRevision: process2.planRevision,
645
+ actor: "system",
646
+ bypassed: true,
647
+ reason: "Jira label"
648
+ }
649
+ }
650
+ ]
651
+ };
652
+ }
653
+ }
654
+ };
655
+ const generatePlan = flow.llm("generate_plan").description("Plan").executionPurpose(codingPurposes.planning).tools("read", "bash").askQuestions().freshPrimary().buildPrompt(buildGeneratePlanPrompt).outcomeTool(
656
+ "plan_saved",
657
+ (tool) => tool.description(
658
+ "Save a finished, implementable plan after resolving design-critical questions. Required investigation and access must be complete. If blocked, use abort_turn. Use ask_questions for operator decisions when available; otherwise decide within the requested scope and document assumptions."
659
+ ).requiredString("summary", "One concise sentence summarizing the proposed plan").requiredStringArray(
660
+ "acceptanceCriteria",
661
+ "Requested outcomes for the repository change, without expanding scope"
662
+ ).routeByState(
663
+ {
664
+ approval: {
665
+ to: "plan_decision",
666
+ label: "Approval required",
667
+ description: "When the process policy requires an operator to approve the saved plan."
668
+ },
669
+ bypass: {
670
+ to: "implement",
671
+ label: "Skip plan approval",
672
+ description: "When the process policy skips plan approval, for example through the Skip plan approval launcher option."
673
+ }
674
+ },
675
+ ({ ctx }) => ctx.state.routing?.plan?.skip ? "bypass" : "approval"
676
+ ).effect(async ({ ctx, event }) => {
677
+ const planRevision = ctx.process.planRevision + 1;
678
+ const policy = await config.workflow?.planDecision?.(ctx.params).catch(() => ({ skip: false, reason: "Source unavailable; approval required" })) ?? {
679
+ skip: false,
680
+ reason: "Human approval required"
681
+ };
682
+ const summary = normalizeMessage(event.params.summary);
683
+ const acceptanceCriteria = Array.isArray(event.params.acceptanceCriteria) ? event.params.acceptanceCriteria.filter(
684
+ (entry) => typeof entry === "string" && entry.trim() !== ""
685
+ ) : [];
686
+ return {
687
+ state: {
688
+ ...ctx.state,
689
+ routing: { ...ctx.state.routing, plan: { ...policy, planRevision } }
690
+ },
691
+ processPatch: { planRevision },
692
+ broadcasts: [
693
+ {
694
+ type: "plan.updated",
695
+ payload: {
696
+ planRevision,
697
+ reviewState: policy.skip ? "accepted" : "awaiting_approval",
698
+ approved: policy.skip,
699
+ summary
700
+ }
701
+ }
702
+ ],
703
+ emit: [
704
+ ...policy.skip ? [
705
+ {
706
+ type: "plan_approved",
707
+ data: {
708
+ planRevision,
709
+ actor: "system",
710
+ bypassed: true,
711
+ reason: policy.reason
712
+ }
713
+ }
714
+ ] : [],
715
+ {
716
+ type: "plan_saved",
717
+ data: {
718
+ planRevision,
719
+ summary,
720
+ planMarkdown: ctx.output?.content ?? "",
721
+ acceptanceCriteria
722
+ }
723
+ }
724
+ ]
725
+ };
726
+ })
727
+ ).publish("plan");
728
+ const implement = flow.llm("implement").description("Implement").waitFor(({ state }) => !!state.productRefs.plan).executionPurpose(codingPurposes.implementation).tools(...tools).freshSeededPrimary().startFromRoot().consume("plan").prepare((ctx) => ({
729
+ reconciliation: ctx.repo.all().map((repo) => {
730
+ const identity = asUnknownRecord(
731
+ ctx.projects.find((p) => p.key === repo.key)?.metadata?.["leitwerk.gitIdentity"]
732
+ );
733
+ return prepareInitialRepository({
734
+ projectKey: repo.key,
735
+ repoPath: repo.fsPath,
736
+ workBranch: repo.workBranch,
737
+ gitIdentity: typeof identity?.name === "string" && typeof identity.email === "string" ? { name: identity.name, email: identity.email } : void 0
738
+ });
739
+ })
740
+ })).buildPrompt((ctx) => `${buildImplementPrompt(ctx)}
741
+
742
+ ${reconciliationPrompt}`).outcomeTool(
743
+ "implementation_ready",
744
+ (tool) => tool.description("Implementation and checks are complete; continue to delivery").routeByState(
745
+ {
746
+ simplify: {
747
+ to: "simplify_implementation",
748
+ label: "Simplification enabled",
749
+ description: "When the process policy enables simplification. This is the default unless a launcher option or source policy skips it."
750
+ },
751
+ skip: {
752
+ to: "generate_commit_message",
753
+ label: "Skip simplification",
754
+ description: "When simplification is skipped, for example through the Skip simplification launcher option or the leitwerk-skip-simplification source label."
755
+ }
756
+ },
757
+ ({ ctx }) => ctx.state.routing?.simplification?.skip ? "skip" : "simplify"
758
+ ).effect(async ({ ctx }) => ({
759
+ state: {
760
+ ...ctx.state,
761
+ routing: {
762
+ ...ctx.state.routing,
763
+ simplification: ctx.state.routing?.simplification ?? await config.workflow?.simplification?.(ctx.params) ?? {
764
+ skip: false,
765
+ reason: "Simplification enabled by default"
766
+ }
767
+ }
768
+ }
769
+ }))
770
+ ).publish("implementation-summary");
771
+ const simplify = flow.llm("simplify_implementation").description("Simplify").executionPurpose(codingPurposes.review).tools("read", "bash").rootBranchReview().startFromProductBranch("simplification-plan").buildPrompt(buildStreamlinedSimplificationPrompt).publish("simplification-plan").to("apply_simplification");
772
+ const applySimplification = flow.llm("apply_simplification").description("Apply simplification").executionPurpose(codingPurposes.implementation).tools(...tools).freshSeededPrimary().consume("plan").consume("simplification-plan").buildPrompt(
773
+ (ctx) => `Apply justified simplifications to each repository, preserving the accepted plan and behavior. Rerun the required checks. Empty findings require no edits. Leave changes uncommitted for delivery.
774
+
775
+ Accepted plan:
776
+ ${ctx.input.plan}
777
+
778
+ Findings by repository:
779
+ ${ctx.input["simplification-plan"]}`
780
+ ).publish("implementation-summary").to("generate_commit_message");
781
+ const generateCommitMessage = flow.llm("generate_commit_message").description("Write Commit Message").executionPurpose(codingPurposes.implementation).tools("read", "grep", "find", "ls").rootBranchReview().startFromRoot().consume("plan").consume("implementation-summary").prepare(prepareRepositoryCommitMessageEvidence).buildPrompt(buildRepositoryCommitMessagesPrompt).publish("commit-message").to(config.publication.entryTurnId).state(({ ctx }) => ({
782
+ ...ctx.state,
783
+ finalization: {
784
+ ...ctx.state.finalization,
785
+ commitMessages: parseRepositoryCommitMessages(
786
+ ctx.output?.content,
787
+ ctx.projects.map((p) => p.key)
788
+ )
789
+ }
790
+ }));
791
+ const builder = flow.process(config.processId).displayName(config.displayName).entry("generate_plan").happyPath(
792
+ "generate_plan",
793
+ "implement",
794
+ "simplify_implementation",
795
+ "apply_simplification",
796
+ "generate_commit_message",
797
+ ...config.publication.happyPath ?? [config.publication.entryTurnId]
798
+ ).piConfig(config.workflow?.multiRepository ? {} : { sessionCwdTemplate: "{{{projectKey}}}" }).codecs({ params: config.paramsCodec, state: repositoryChangeStateCodec }).initialState(() => repositoryChangeStateCodec.parse({})).turn(generatePlan).turn({ id: "plan_decision", definition: planDecision }).turn(implement).turn(simplify).turn(applySimplification).turn(generateCommitMessage).use(config.publication.fragment);
799
+ if (config.repositoryCredentials) builder.repositoryCredentials(config.repositoryCredentials);
800
+ if (config.launcher) builder.launcher(config.launcher);
801
+ return {
802
+ /** @public */
803
+ process: builder.define()
804
+ };
805
+ }
806
+
807
+ export {
808
+ codingActionIds,
809
+ requestRevisionForm,
810
+ requestReviewChangesForm,
811
+ acceptReviewForm,
812
+ assertReconciliationTargetSafe,
813
+ retainConcurrentRebase,
814
+ repositoryWorktreeIsDirty,
815
+ reconcilePublicationRepository,
816
+ recordRepositoryPublication,
817
+ reconciliationPrompt,
818
+ createRepositoryChangeProcess
819
+ };
820
+ //# sourceMappingURL=chunk-B3PE6DPF.js.map