@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.
- package/README.md +67 -11
- package/dist/{chunk-Q24RPXOA.js → chunk-3WJRJ3Q7.js} +68 -7
- package/dist/chunk-3WJRJ3Q7.js.map +1 -0
- package/dist/chunk-B3PE6DPF.js +820 -0
- package/dist/chunk-B3PE6DPF.js.map +1 -0
- package/dist/chunk-E3DB4TIZ.js +49 -0
- package/dist/chunk-E3DB4TIZ.js.map +1 -0
- package/dist/{chunk-BI45R2FH.js → chunk-QD6FI4HR.js} +1 -1
- package/dist/chunk-QD6FI4HR.js.map +1 -0
- package/dist/finalization-git-internal.d.ts +6 -0
- package/dist/finalization-git-internal.d.ts.map +1 -1
- package/dist/finalization-git.js +2 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/pull-request-publication-internal.d.ts +8 -0
- package/dist/pull-request-publication-internal.d.ts.map +1 -1
- package/dist/repository-change-process.d.ts.map +1 -1
- package/dist/repository-change-publication.d.ts +16 -3
- package/dist/repository-change-publication.d.ts.map +1 -1
- package/dist/repository-change-publication.js +283 -69
- package/dist/repository-change-publication.js.map +1 -1
- package/dist/repository-publication-receipt.d.ts +23 -0
- package/dist/repository-publication-receipt.d.ts.map +1 -0
- package/dist/repository-rebase/git.d.ts +8 -0
- package/dist/repository-rebase/git.d.ts.map +1 -1
- package/dist/repository-reconciliation.d.ts +47 -0
- package/dist/repository-reconciliation.d.ts.map +1 -0
- package/dist/repository-record.d.ts +6 -0
- package/dist/repository-record.d.ts.map +1 -0
- package/dist/turns/implement.d.ts +1 -1
- package/dist/turns/implement.d.ts.map +1 -1
- package/dist/turns/implement.js +1 -1
- package/package.json +5 -5
- package/src/finalization-git-internal.ts +75 -6
- package/src/pull-request-publication-internal.ts +3 -2
- package/src/repository-change-process.ts +19 -2
- package/src/repository-change-publication.ts +243 -57
- package/src/repository-publication-receipt.ts +71 -0
- package/src/repository-rebase/git.ts +108 -29
- package/src/repository-reconciliation.ts +600 -0
- package/src/repository-record.ts +14 -0
- package/src/turns/implement.ts +4 -1
- package/dist/chunk-BI45R2FH.js.map +0 -1
- package/dist/chunk-OM2AMDTJ.js +0 -347
- package/dist/chunk-OM2AMDTJ.js.map +0 -1
- package/dist/chunk-Q24RPXOA.js.map +0 -1
|
@@ -0,0 +1,600 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { hostname } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { repositoryGitArgs, repositoryGitSubprocessEnv } from "@leitwerk-dev/process-sdk";
|
|
7
|
+
import { resolveGitBinary } from "@leitwerk-dev/process-sdk/git-binary";
|
|
8
|
+
import type { GitIdentity } from "./finalization-git.js";
|
|
9
|
+
import {
|
|
10
|
+
type RepositoryBinding,
|
|
11
|
+
readPublicationReceipt,
|
|
12
|
+
readRepositoryBinding,
|
|
13
|
+
repositoryBindingMatches,
|
|
14
|
+
savePublicationReceipt,
|
|
15
|
+
} from "./repository-publication-receipt.js";
|
|
16
|
+
import { repositoryRecord } from "./repository-record.js";
|
|
17
|
+
|
|
18
|
+
/** @internal */
|
|
19
|
+
export interface ReconciliationInput {
|
|
20
|
+
projectKey: string;
|
|
21
|
+
repoPath: string;
|
|
22
|
+
workBranch: string;
|
|
23
|
+
/** Last remote baseline, not the latest observation. */
|
|
24
|
+
baselineSha: string;
|
|
25
|
+
/** Trusted project identity for replaying unpublished commits. */
|
|
26
|
+
gitIdentity?: GitIdentity;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** @internal */
|
|
30
|
+
export interface ReconciliationResult {
|
|
31
|
+
status: "ready" | "conflicts";
|
|
32
|
+
remoteHead: string | null;
|
|
33
|
+
headSha: string;
|
|
34
|
+
changed: boolean;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
interface RecordState extends RepositoryBinding {
|
|
38
|
+
baseline: string;
|
|
39
|
+
remoteSeen?: boolean;
|
|
40
|
+
protectedIgnored?: string[];
|
|
41
|
+
publicationReceiptSha?: string;
|
|
42
|
+
joinParent?: string;
|
|
43
|
+
joinIdentity?: GitIdentity;
|
|
44
|
+
sourceIntegration?: { previous: string; replacement: string };
|
|
45
|
+
operation?: {
|
|
46
|
+
id: string;
|
|
47
|
+
head: string;
|
|
48
|
+
index: string;
|
|
49
|
+
work: string;
|
|
50
|
+
remote: string;
|
|
51
|
+
phase: "captured" | "rebasing" | "restoring";
|
|
52
|
+
resultHead?: string;
|
|
53
|
+
resultIndex?: string;
|
|
54
|
+
identity?: GitIdentity;
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function repository(input: Pick<ReconciliationInput, "projectKey" | "repoPath">) {
|
|
59
|
+
function git(args: string[], extra: NodeJS.ProcessEnv = {}): string {
|
|
60
|
+
const output = execFileSync(resolveGitBinary(), repositoryGitArgs(args), {
|
|
61
|
+
cwd: input.repoPath,
|
|
62
|
+
encoding: "utf8",
|
|
63
|
+
env: repositoryGitSubprocessEnv(input.projectKey, {
|
|
64
|
+
GIT_TERMINAL_PROMPT: "0",
|
|
65
|
+
GIT_EDITOR: "true",
|
|
66
|
+
GIT_SEQUENCE_EDITOR: "true",
|
|
67
|
+
...extra,
|
|
68
|
+
}),
|
|
69
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
70
|
+
maxBuffer: 16 * 1024 * 1024,
|
|
71
|
+
});
|
|
72
|
+
return output.endsWith("\0") ? output : output.replace(/\r?\n$/, "");
|
|
73
|
+
}
|
|
74
|
+
const directory = git(["rev-parse", "--absolute-git-dir"]);
|
|
75
|
+
if (
|
|
76
|
+
git(["remote", "get-url", "--push", "--all", "origin"]) !== git(["remote", "get-url", "origin"])
|
|
77
|
+
)
|
|
78
|
+
throw new Error(
|
|
79
|
+
"Repository reconciliation binding changed: fetch and push endpoints must match",
|
|
80
|
+
);
|
|
81
|
+
const { read, save } = repositoryRecord<RecordState>(directory, "reconciliation");
|
|
82
|
+
const binding = (branch: string) => readRepositoryBinding((...args) => git(args), branch);
|
|
83
|
+
return { git, directory, read, save, binding };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function integrationIdentityEnv(identity: GitIdentity | undefined): NodeJS.ProcessEnv {
|
|
87
|
+
if (
|
|
88
|
+
!identity?.name.trim() ||
|
|
89
|
+
!identity.email.trim() ||
|
|
90
|
+
/[\r\n\0]/.test(identity.name + identity.email)
|
|
91
|
+
)
|
|
92
|
+
throw new Error(
|
|
93
|
+
"A trusted Git identity is required for source integration; local work was retained",
|
|
94
|
+
);
|
|
95
|
+
return {
|
|
96
|
+
GIT_AUTHOR_NAME: identity.name,
|
|
97
|
+
GIT_AUTHOR_EMAIL: identity.email,
|
|
98
|
+
GIT_COMMITTER_NAME: identity.name,
|
|
99
|
+
GIT_COMMITTER_EMAIL: identity.email,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function ignoredPaths(git: ReturnType<typeof repository>["git"]): string[] {
|
|
104
|
+
return git([
|
|
105
|
+
"ls-files",
|
|
106
|
+
"--others",
|
|
107
|
+
"--ignored",
|
|
108
|
+
"--exclude-standard",
|
|
109
|
+
"--directory",
|
|
110
|
+
"--no-empty-directory",
|
|
111
|
+
"-z",
|
|
112
|
+
])
|
|
113
|
+
.split("\0")
|
|
114
|
+
.filter(Boolean)
|
|
115
|
+
.map((file) => file.replace(/\/$/, ""));
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function assertIgnoredProtection(
|
|
119
|
+
git: ReturnType<typeof repository>["git"],
|
|
120
|
+
protectedPaths: string[] = [],
|
|
121
|
+
): void {
|
|
122
|
+
if (!protectedPaths.length) return;
|
|
123
|
+
const visible = git(["ls-files", "--cached", "--others", "--exclude-standard", "-z"]).split("\0");
|
|
124
|
+
if (
|
|
125
|
+
protectedPaths.some((ignored) =>
|
|
126
|
+
visible.some((file) => file === ignored || file.startsWith(`${ignored}/`)),
|
|
127
|
+
)
|
|
128
|
+
)
|
|
129
|
+
throw new Error(
|
|
130
|
+
"Previously ignored local files became publishable; review ignore rules before continuing. Local files were retained",
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function ignoredPathsCollide(
|
|
135
|
+
git: ReturnType<typeof repository>["git"],
|
|
136
|
+
ignored: string[],
|
|
137
|
+
target: string,
|
|
138
|
+
replayRange: string,
|
|
139
|
+
): boolean {
|
|
140
|
+
const paths = [
|
|
141
|
+
...git(["ls-tree", "-r", "--name-only", "-z", target]).split("\0"),
|
|
142
|
+
...git(["log", "--format=", "--full-history", "-m", "--name-only", "-z", replayRange]).split(
|
|
143
|
+
"\0",
|
|
144
|
+
),
|
|
145
|
+
];
|
|
146
|
+
return ignored.some((file) =>
|
|
147
|
+
paths.some((p) => p === file || p.startsWith(`${file}/`) || file.startsWith(`${p}/`)),
|
|
148
|
+
);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function ancestor(git: ReturnType<typeof repository>["git"], a: string, b: string): boolean {
|
|
152
|
+
try {
|
|
153
|
+
git(["merge-base", "--is-ancestor", a, b]);
|
|
154
|
+
return true;
|
|
155
|
+
} catch (error) {
|
|
156
|
+
if ((error as { status?: number }).status === 1) return false;
|
|
157
|
+
throw error;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function withLock<T>(directory: string, run: () => T): T {
|
|
162
|
+
const lock = join(directory, "leitwerk-reconciliation.lock");
|
|
163
|
+
try {
|
|
164
|
+
mkdirSync(lock);
|
|
165
|
+
} catch (error) {
|
|
166
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
|
167
|
+
// Never steal a lock from another node or a living process.
|
|
168
|
+
const owner = JSON.parse(readFileSync(join(lock, "owner.json"), "utf8"));
|
|
169
|
+
if (owner.host !== hostname())
|
|
170
|
+
throw new Error("Repository reconciliation is owned by another worker");
|
|
171
|
+
try {
|
|
172
|
+
process.kill(owner.pid, 0);
|
|
173
|
+
} catch (failure) {
|
|
174
|
+
if ((failure as NodeJS.ErrnoException).code !== "ESRCH") throw failure;
|
|
175
|
+
rmSync(lock, { recursive: true });
|
|
176
|
+
return withLock(directory, run);
|
|
177
|
+
}
|
|
178
|
+
throw new Error("Repository reconciliation is already running");
|
|
179
|
+
}
|
|
180
|
+
try {
|
|
181
|
+
writeFileSync(
|
|
182
|
+
join(lock, "owner.json"),
|
|
183
|
+
JSON.stringify({ host: hostname(), pid: process.pid }),
|
|
184
|
+
{ mode: 0o600 },
|
|
185
|
+
);
|
|
186
|
+
return run();
|
|
187
|
+
} finally {
|
|
188
|
+
rmSync(lock, { recursive: true });
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Reconcile only unpublished work onto the fetched source branch. Checkpoint commits
|
|
194
|
+
* retain the index and working tree separately, including non-ignored untracked files.
|
|
195
|
+
* They are retained under private refs and removed from HEAD before publication.
|
|
196
|
+
* A conflicted rebase is deliberately left in place for the existing adjustment turn.
|
|
197
|
+
* @internal
|
|
198
|
+
*/
|
|
199
|
+
export function reconcileRepository(input: ReconciliationInput): ReconciliationResult {
|
|
200
|
+
const { git, directory, read, save, binding: readBinding } = repository(input);
|
|
201
|
+
return withLock(directory, () => {
|
|
202
|
+
git(["check-ref-format", `refs/heads/${input.workBranch}`]);
|
|
203
|
+
const binding = readBinding(input.workBranch);
|
|
204
|
+
let record = read();
|
|
205
|
+
if (!repositoryBindingMatches(record, binding))
|
|
206
|
+
throw new Error("Repository reconciliation binding changed");
|
|
207
|
+
if (record?.sourceIntegration) {
|
|
208
|
+
if (git(["branch", "--show-current"]) !== input.workBranch)
|
|
209
|
+
throw new Error("Source integration checkout branch changed; local work was retained");
|
|
210
|
+
const { previous, replacement } = record.sourceIntegration;
|
|
211
|
+
const current = git(["rev-parse", "HEAD"]);
|
|
212
|
+
if (current === previous)
|
|
213
|
+
git(["update-ref", `refs/heads/${input.workBranch}`, replacement, previous]);
|
|
214
|
+
else if (current !== replacement)
|
|
215
|
+
throw new Error("Checkout changed during source integration; recovery refs were retained");
|
|
216
|
+
delete record.sourceIntegration;
|
|
217
|
+
save(record);
|
|
218
|
+
}
|
|
219
|
+
const rebaseActive = () =>
|
|
220
|
+
["rebase-merge", "rebase-apply"].some((name) => existsSync(join(directory, name)));
|
|
221
|
+
if (rebaseActive() && !record?.operation)
|
|
222
|
+
throw new Error("An unrelated rebase is already in progress; local work was retained");
|
|
223
|
+
if (
|
|
224
|
+
existsSync(join(directory, "MERGE_HEAD")) ||
|
|
225
|
+
existsSync(join(directory, "CHERRY_PICK_HEAD"))
|
|
226
|
+
)
|
|
227
|
+
throw new Error("An unrelated Git operation is in progress; local work was retained");
|
|
228
|
+
if (!rebaseActive() && git(["branch", "--show-current"]) !== input.workBranch)
|
|
229
|
+
throw new Error(`Expected checkout on '${input.workBranch}'; local work was retained`);
|
|
230
|
+
|
|
231
|
+
if (!record?.operation) {
|
|
232
|
+
assertIgnoredProtection(git, record?.protectedIgnored);
|
|
233
|
+
const ignored = ignoredPaths(git);
|
|
234
|
+
// Fetch to a private ref: remote-tracking refs are not publication leases.
|
|
235
|
+
git([
|
|
236
|
+
"fetch",
|
|
237
|
+
"--no-tags",
|
|
238
|
+
"origin",
|
|
239
|
+
`+refs/heads/${input.workBranch}:refs/leitwerk/reconcile-remote`,
|
|
240
|
+
]);
|
|
241
|
+
const remote = git(["rev-parse", "refs/leitwerk/reconcile-remote"]);
|
|
242
|
+
const head = git(["rev-parse", "HEAD"]);
|
|
243
|
+
let baseline = record?.baseline ?? input.baselineSha;
|
|
244
|
+
const receipt = readPublicationReceipt(directory);
|
|
245
|
+
if (!repositoryBindingMatches(receipt, binding))
|
|
246
|
+
throw new Error("Repository publication receipt binding changed");
|
|
247
|
+
if (receipt?.status === "attempting") {
|
|
248
|
+
if (remote === receipt.candidate || ancestor(git, receipt.candidate, remote)) {
|
|
249
|
+
receipt.status = "accepted";
|
|
250
|
+
savePublicationReceipt(directory, receipt);
|
|
251
|
+
} else {
|
|
252
|
+
throw new Error(
|
|
253
|
+
"Prior publication outcome is uncertain; local work was retained for operator reconciliation",
|
|
254
|
+
);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
if (receipt?.status === "accepted" && record?.publicationReceiptSha !== receipt.candidate)
|
|
258
|
+
baseline = receipt.candidate;
|
|
259
|
+
git(["cat-file", "-e", `${baseline}^{commit}`]);
|
|
260
|
+
if (!ancestor(git, baseline, head))
|
|
261
|
+
throw new Error(
|
|
262
|
+
"Cannot establish unpublished work from the retained baseline; local work was retained",
|
|
263
|
+
);
|
|
264
|
+
record = {
|
|
265
|
+
...record,
|
|
266
|
+
...binding,
|
|
267
|
+
baseline,
|
|
268
|
+
remoteSeen: true,
|
|
269
|
+
protectedIgnored: [...new Set([...(record?.protectedIgnored ?? []), ...ignored])],
|
|
270
|
+
publicationReceiptSha:
|
|
271
|
+
receipt?.status === "accepted" ? receipt.candidate : record?.publicationReceiptSha,
|
|
272
|
+
};
|
|
273
|
+
if ((remote === baseline || remote === head) && !record.joinParent) {
|
|
274
|
+
record.baseline = remote;
|
|
275
|
+
save(record);
|
|
276
|
+
return { status: "ready", remoteHead: remote, headSha: head, changed: false };
|
|
277
|
+
}
|
|
278
|
+
if (git(["diff", "--name-only", "--diff-filter=U"]))
|
|
279
|
+
throw new Error("Unresolved local conflicts must be repaired before reconciliation");
|
|
280
|
+
// Dirty submodule work cannot be represented by the parent's tree checkpoint.
|
|
281
|
+
if (git(["submodule", "foreach", "--quiet", "git status --porcelain"]))
|
|
282
|
+
throw new Error("Commit or preserve dirty submodule work before reconciliation");
|
|
283
|
+
if (ignoredPathsCollide(git, ignored, remote, `${record.baseline}..${head}`))
|
|
284
|
+
throw new Error("Remote changes collide with ignored files; local files were retained");
|
|
285
|
+
// A verified remote descendant already contains these local commits, including
|
|
286
|
+
// publication that succeeded before its receipt reached the server.
|
|
287
|
+
if (ancestor(git, head, remote)) record.baseline = head;
|
|
288
|
+
const id = randomUUID();
|
|
289
|
+
const temporaryIndex = join(directory, `leitwerk-index-${id}`);
|
|
290
|
+
const identity = {
|
|
291
|
+
GIT_AUTHOR_NAME: "Leitwerk checkpoint",
|
|
292
|
+
GIT_AUTHOR_EMAIL: "checkpoint@leitwerk.invalid",
|
|
293
|
+
GIT_COMMITTER_NAME: "Leitwerk checkpoint",
|
|
294
|
+
GIT_COMMITTER_EMAIL: "checkpoint@leitwerk.invalid",
|
|
295
|
+
};
|
|
296
|
+
try {
|
|
297
|
+
const stagedTree = git(["write-tree"]);
|
|
298
|
+
const index = git(
|
|
299
|
+
["commit-tree", stagedTree, "-p", head, "-m", `Leitwerk index checkpoint ${id}`],
|
|
300
|
+
identity,
|
|
301
|
+
);
|
|
302
|
+
git(["read-tree", stagedTree], { GIT_INDEX_FILE: temporaryIndex });
|
|
303
|
+
git(["add", "--all"], { GIT_INDEX_FILE: temporaryIndex });
|
|
304
|
+
const workTree = git(["write-tree"], { GIT_INDEX_FILE: temporaryIndex });
|
|
305
|
+
const work = git(
|
|
306
|
+
["commit-tree", workTree, "-p", index, "-m", `Leitwerk worktree checkpoint ${id}`],
|
|
307
|
+
identity,
|
|
308
|
+
);
|
|
309
|
+
// Reachability and journal precede every change to the checkout.
|
|
310
|
+
git(["update-ref", `refs/leitwerk/checkpoints/${id}`, work]);
|
|
311
|
+
const replayIdentity = record.joinIdentity ?? input.gitIdentity;
|
|
312
|
+
if (replayIdentity || record.baseline !== head) integrationIdentityEnv(replayIdentity);
|
|
313
|
+
record.operation = {
|
|
314
|
+
id,
|
|
315
|
+
head,
|
|
316
|
+
index,
|
|
317
|
+
work,
|
|
318
|
+
remote,
|
|
319
|
+
phase: "captured",
|
|
320
|
+
identity: replayIdentity,
|
|
321
|
+
};
|
|
322
|
+
save(record);
|
|
323
|
+
} finally {
|
|
324
|
+
rmSync(temporaryIndex, { force: true });
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
const operation = record.operation;
|
|
328
|
+
if (!operation) throw new Error("Missing reconciliation checkpoint");
|
|
329
|
+
if (operation.phase === "captured") {
|
|
330
|
+
if (operation.identity || record.baseline !== operation.head)
|
|
331
|
+
integrationIdentityEnv(operation.identity);
|
|
332
|
+
const current = git(["rev-parse", "HEAD"]);
|
|
333
|
+
const indexTree = git(["write-tree"]);
|
|
334
|
+
if (
|
|
335
|
+
![operation.head, operation.work].includes(current) ||
|
|
336
|
+
![
|
|
337
|
+
git(["rev-parse", `${operation.index}^{tree}`]),
|
|
338
|
+
git(["rev-parse", `${operation.work}^{tree}`]),
|
|
339
|
+
].includes(indexTree)
|
|
340
|
+
)
|
|
341
|
+
throw new Error(
|
|
342
|
+
"Checkout changed after its checkpoint; new local work and recovery refs were retained",
|
|
343
|
+
);
|
|
344
|
+
// read-tree changes only the index; the worktree already has this exact tree.
|
|
345
|
+
git(["read-tree", operation.work]);
|
|
346
|
+
if (current !== operation.work)
|
|
347
|
+
git(["update-ref", `refs/heads/${input.workBranch}`, operation.work, operation.head]);
|
|
348
|
+
operation.phase = "rebasing";
|
|
349
|
+
save(record);
|
|
350
|
+
}
|
|
351
|
+
if (operation.phase === "rebasing") {
|
|
352
|
+
const conflicts = (): ReconciliationResult => ({
|
|
353
|
+
status: "conflicts",
|
|
354
|
+
remoteHead: operation.remote,
|
|
355
|
+
headSha: git(["rev-parse", "HEAD"]),
|
|
356
|
+
changed: true,
|
|
357
|
+
});
|
|
358
|
+
if (rebaseActive()) return conflicts();
|
|
359
|
+
// Retry after Git completed the rebase but before the result was journaled.
|
|
360
|
+
if (git(["rev-parse", "HEAD"]) === operation.work) {
|
|
361
|
+
try {
|
|
362
|
+
git(
|
|
363
|
+
[
|
|
364
|
+
"-c",
|
|
365
|
+
"core.hooksPath=/dev/null",
|
|
366
|
+
"-c",
|
|
367
|
+
"commit.gpgSign=false",
|
|
368
|
+
"rebase",
|
|
369
|
+
"--rebase-merges",
|
|
370
|
+
"--reapply-cherry-picks",
|
|
371
|
+
"--empty=keep",
|
|
372
|
+
"--onto",
|
|
373
|
+
operation.remote,
|
|
374
|
+
record.baseline,
|
|
375
|
+
],
|
|
376
|
+
{
|
|
377
|
+
GIT_COMMITTER_NAME: operation.identity?.name ?? "Leitwerk checkpoint",
|
|
378
|
+
GIT_COMMITTER_EMAIL: operation.identity?.email ?? "checkpoint@leitwerk.invalid",
|
|
379
|
+
},
|
|
380
|
+
);
|
|
381
|
+
} catch (error) {
|
|
382
|
+
if (!rebaseActive()) throw error;
|
|
383
|
+
return conflicts();
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
if (
|
|
387
|
+
git(["log", "-1", "--format=%s"]) !== `Leitwerk worktree checkpoint ${operation.id}` ||
|
|
388
|
+
git(["log", "-1", "--format=%s", "HEAD^"]) !== `Leitwerk index checkpoint ${operation.id}`
|
|
389
|
+
)
|
|
390
|
+
throw new Error(
|
|
391
|
+
"Reconciliation checkpoint commits were changed or skipped; recovery refs were retained",
|
|
392
|
+
);
|
|
393
|
+
operation.resultHead = git(["rev-parse", "HEAD~2"]);
|
|
394
|
+
operation.resultIndex = git(["rev-parse", "HEAD~1^{tree}"]);
|
|
395
|
+
// Preserve the integrated working tree/index before removing checkpoint commits.
|
|
396
|
+
git(["update-ref", `refs/leitwerk/reconciled/${operation.id}`, git(["rev-parse", "HEAD"])]);
|
|
397
|
+
operation.phase = "restoring";
|
|
398
|
+
save(record);
|
|
399
|
+
}
|
|
400
|
+
if (!operation.resultHead || !operation.resultIndex)
|
|
401
|
+
throw new Error("Incomplete reconciliation result");
|
|
402
|
+
if (record.joinParent && !ancestor(git, record.joinParent, operation.resultHead)) {
|
|
403
|
+
// The net repair was replayed against the current source. Retain the target
|
|
404
|
+
// ancestry without re-merging (and thereby losing the replayed resolution).
|
|
405
|
+
operation.resultHead = git(
|
|
406
|
+
[
|
|
407
|
+
"commit-tree",
|
|
408
|
+
git(["rev-parse", `${operation.resultHead}^{tree}`]),
|
|
409
|
+
"-p",
|
|
410
|
+
operation.resultHead,
|
|
411
|
+
"-p",
|
|
412
|
+
record.joinParent,
|
|
413
|
+
"-m",
|
|
414
|
+
"Integrate target branch with concurrent source changes",
|
|
415
|
+
],
|
|
416
|
+
integrationIdentityEnv(record.joinIdentity),
|
|
417
|
+
);
|
|
418
|
+
git([
|
|
419
|
+
"update-ref",
|
|
420
|
+
`refs/leitwerk/target-integrations/${operation.id}`,
|
|
421
|
+
operation.resultHead,
|
|
422
|
+
]);
|
|
423
|
+
save(record);
|
|
424
|
+
}
|
|
425
|
+
const integrated = git(["rev-parse", `refs/leitwerk/reconciled/${operation.id}`]);
|
|
426
|
+
const currentHead = git(["rev-parse", "HEAD"]);
|
|
427
|
+
const currentIndex = git(["write-tree"]);
|
|
428
|
+
if (
|
|
429
|
+
![operation.resultHead, integrated].includes(currentHead) ||
|
|
430
|
+
![operation.resultIndex, git(["rev-parse", `${integrated}^{tree}`])].includes(currentIndex)
|
|
431
|
+
)
|
|
432
|
+
throw new Error(
|
|
433
|
+
"Checkout changed during interrupted restoration; local work and recovery refs were retained",
|
|
434
|
+
);
|
|
435
|
+
git(["update-ref", `refs/heads/${input.workBranch}`, operation.resultHead, currentHead]);
|
|
436
|
+
git(["read-tree", operation.resultIndex]);
|
|
437
|
+
record.baseline = operation.remote;
|
|
438
|
+
delete record.operation;
|
|
439
|
+
delete record.joinParent;
|
|
440
|
+
delete record.joinIdentity;
|
|
441
|
+
save(record);
|
|
442
|
+
assertIgnoredProtection(git, record.protectedIgnored);
|
|
443
|
+
return {
|
|
444
|
+
status: "ready",
|
|
445
|
+
remoteHead: operation.remote,
|
|
446
|
+
headSha: operation.resultHead,
|
|
447
|
+
changed: true,
|
|
448
|
+
};
|
|
449
|
+
});
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/** Reject ignored-file collisions before a target checkout/rebase can overwrite them. @internal */
|
|
453
|
+
export function assertReconciliationTargetSafe(
|
|
454
|
+
input: Pick<ReconciliationInput, "repoPath" | "projectKey">,
|
|
455
|
+
targetSha: string,
|
|
456
|
+
): void {
|
|
457
|
+
const { git, read } = repository(input);
|
|
458
|
+
assertIgnoredProtection(git, read()?.protectedIgnored);
|
|
459
|
+
if (ignoredPathsCollide(git, ignoredPaths(git), targetSha, `${targetSha}..HEAD`))
|
|
460
|
+
throw new Error("Target changes collide with ignored files; local files were retained");
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/** Preserve a target rebase as a net local delta when its source lease changes. @internal */
|
|
464
|
+
export function retainConcurrentRebase(
|
|
465
|
+
input: ReconciliationInput & {
|
|
466
|
+
rebasedHead: string;
|
|
467
|
+
targetBase: string;
|
|
468
|
+
gitIdentity: GitIdentity;
|
|
469
|
+
},
|
|
470
|
+
): void {
|
|
471
|
+
const { git, directory, read, save, binding: readBinding } = repository(input);
|
|
472
|
+
withLock(directory, () => {
|
|
473
|
+
const old = read();
|
|
474
|
+
if (old?.operation || old?.sourceIntegration)
|
|
475
|
+
throw new Error("Source reconciliation is already in progress");
|
|
476
|
+
if (
|
|
477
|
+
git(["branch", "--show-current"]) !== input.workBranch ||
|
|
478
|
+
git(["rev-parse", "HEAD"]) !== input.rebasedHead ||
|
|
479
|
+
git(["status", "--porcelain"])
|
|
480
|
+
)
|
|
481
|
+
throw new Error(
|
|
482
|
+
"Target rebase changed before source reconciliation; local work was retained",
|
|
483
|
+
);
|
|
484
|
+
const binding = readBinding(input.workBranch);
|
|
485
|
+
if (!repositoryBindingMatches(old, binding))
|
|
486
|
+
throw new Error("Repository reconciliation binding changed");
|
|
487
|
+
const identity = integrationIdentityEnv(input.gitIdentity);
|
|
488
|
+
const id = randomUUID();
|
|
489
|
+
git(["update-ref", `refs/leitwerk/target-repairs/${id}`, input.rebasedHead]);
|
|
490
|
+
const replacement = git(
|
|
491
|
+
[
|
|
492
|
+
"commit-tree",
|
|
493
|
+
git(["rev-parse", `${input.rebasedHead}^{tree}`]),
|
|
494
|
+
"-p",
|
|
495
|
+
input.baselineSha,
|
|
496
|
+
"-m",
|
|
497
|
+
"Reconcile target-branch repair",
|
|
498
|
+
],
|
|
499
|
+
identity,
|
|
500
|
+
);
|
|
501
|
+
git(["update-ref", `refs/leitwerk/target-deltas/${id}`, replacement]);
|
|
502
|
+
// The original source tree is the merge baseline, not the old target branch.
|
|
503
|
+
// This preserves developer deletions as well as the agent's conflict resolution.
|
|
504
|
+
save({
|
|
505
|
+
...binding,
|
|
506
|
+
baseline: input.baselineSha,
|
|
507
|
+
remoteSeen: true,
|
|
508
|
+
joinParent: input.targetBase,
|
|
509
|
+
joinIdentity: input.gitIdentity,
|
|
510
|
+
protectedIgnored: old?.protectedIgnored,
|
|
511
|
+
publicationReceiptSha: old?.publicationReceiptSha,
|
|
512
|
+
sourceIntegration: { previous: input.rebasedHead, replacement },
|
|
513
|
+
});
|
|
514
|
+
});
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/** @internal */
|
|
518
|
+
export function repositoryWorktreeIsDirty(
|
|
519
|
+
input: Pick<ReconciliationInput, "repoPath" | "projectKey">,
|
|
520
|
+
): boolean {
|
|
521
|
+
return Boolean(repository(input).git(["status", "--porcelain"]));
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/** Capture the baseline before the first implementation, including an unpublished branch. @internal */
|
|
525
|
+
export function prepareInitialRepository(
|
|
526
|
+
input: Omit<ReconciliationInput, "baselineSha">,
|
|
527
|
+
): ReconciliationResult {
|
|
528
|
+
const { git, read, save, directory, binding } = repository(input);
|
|
529
|
+
withLock(directory, () => {
|
|
530
|
+
if (!read())
|
|
531
|
+
save({
|
|
532
|
+
...binding(input.workBranch),
|
|
533
|
+
baseline: git(["rev-parse", "HEAD"]),
|
|
534
|
+
protectedIgnored: ignoredPaths(git),
|
|
535
|
+
});
|
|
536
|
+
});
|
|
537
|
+
return reconcilePublicationRepository(input);
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
/** Missing branches are allowed only before first publication. @internal */
|
|
541
|
+
export function reconcilePublicationRepository(
|
|
542
|
+
input: Omit<ReconciliationInput, "baselineSha"> & { baselineSha?: string },
|
|
543
|
+
): ReconciliationResult {
|
|
544
|
+
const { git, read, directory } = repository(input);
|
|
545
|
+
const record = read();
|
|
546
|
+
const receipt = readPublicationReceipt(directory);
|
|
547
|
+
const baselineSha =
|
|
548
|
+
record?.baseline ??
|
|
549
|
+
input.baselineSha ??
|
|
550
|
+
(receipt?.status === "accepted"
|
|
551
|
+
? receipt.candidate
|
|
552
|
+
: (receipt?.expectedHead ??
|
|
553
|
+
(receipt?.status === "attempting" ? receipt.candidate : undefined)));
|
|
554
|
+
assertIgnoredProtection(git, record?.protectedIgnored);
|
|
555
|
+
const remote = git(["ls-remote", "--heads", "origin", `refs/heads/${input.workBranch}`]).split(
|
|
556
|
+
/\s+/,
|
|
557
|
+
)[0];
|
|
558
|
+
if (
|
|
559
|
+
!remote &&
|
|
560
|
+
!input.baselineSha &&
|
|
561
|
+
!record?.remoteSeen &&
|
|
562
|
+
!record?.operation &&
|
|
563
|
+
(!receipt || (receipt.status === "rejected" && receipt.expectedHead === null))
|
|
564
|
+
)
|
|
565
|
+
return {
|
|
566
|
+
status: "ready",
|
|
567
|
+
remoteHead: null,
|
|
568
|
+
headSha: git(["rev-parse", "HEAD"]),
|
|
569
|
+
changed: false,
|
|
570
|
+
};
|
|
571
|
+
if (!remote)
|
|
572
|
+
throw new Error(
|
|
573
|
+
"Remote source branch is missing or its publication is uncertain; local work was retained and the branch will not be recreated automatically",
|
|
574
|
+
);
|
|
575
|
+
if (!baselineSha)
|
|
576
|
+
throw new Error("Cannot establish the retained work baseline; local work was retained");
|
|
577
|
+
return reconcileRepository({ ...input, baselineSha });
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
/** Record only a remotely verified publication, including recovery after a lost reply. @internal */
|
|
581
|
+
export function recordRepositoryPublication(input: ReconciliationInput, headSha: string): void {
|
|
582
|
+
const { directory, read, save, binding: readBinding } = repository(input);
|
|
583
|
+
withLock(directory, () => {
|
|
584
|
+
const old = read();
|
|
585
|
+
if (old?.operation) throw new Error("Cannot acknowledge publication during reconciliation");
|
|
586
|
+
const binding = readBinding(input.workBranch);
|
|
587
|
+
if (!repositoryBindingMatches(old, binding))
|
|
588
|
+
throw new Error("Repository reconciliation binding changed");
|
|
589
|
+
save({
|
|
590
|
+
...binding,
|
|
591
|
+
baseline: headSha,
|
|
592
|
+
publicationReceiptSha: headSha,
|
|
593
|
+
remoteSeen: true,
|
|
594
|
+
protectedIgnored: old?.protectedIgnored,
|
|
595
|
+
});
|
|
596
|
+
});
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
/** @internal */
|
|
600
|
+
export const 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.`;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
|
|
4
|
+
/** Repository-local JSON with atomic replacement. Callers own validation and locking. @internal */
|
|
5
|
+
export function repositoryRecord<T>(gitDirectory: string, name: string) {
|
|
6
|
+
const file = join(gitDirectory, `leitwerk-${name}.json`);
|
|
7
|
+
return {
|
|
8
|
+
read: (): T | null => (existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : null),
|
|
9
|
+
save: (record: T): void => {
|
|
10
|
+
writeFileSync(`${file}.tmp`, JSON.stringify(record), { mode: 0o600 });
|
|
11
|
+
renameSync(`${file}.tmp`, file);
|
|
12
|
+
},
|
|
13
|
+
};
|
|
14
|
+
}
|
package/src/turns/implement.ts
CHANGED
|
@@ -2,7 +2,10 @@ import type { FlowPromptContext, StructuralProcessState } from "@leitwerk-dev/pr
|
|
|
2
2
|
|
|
3
3
|
/** @internal */
|
|
4
4
|
export function buildImplementPrompt(
|
|
5
|
-
ctx:
|
|
5
|
+
ctx: Pick<
|
|
6
|
+
FlowPromptContext<unknown, StructuralProcessState, "plan">,
|
|
7
|
+
"prompts" | "input" | "repo"
|
|
8
|
+
>,
|
|
6
9
|
): string {
|
|
7
10
|
return `Implement this requested change:
|
|
8
11
|
${ctx.prompts.initial}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/turns/implement.ts"],"sourcesContent":["import type { FlowPromptContext, StructuralProcessState } from \"@leitwerk-dev/process-sdk\";\n\n/** @internal */\nexport function buildImplementPrompt(\n\tctx: FlowPromptContext<unknown, StructuralProcessState, \"plan\">,\n): string {\n\treturn `Implement this requested change:\n${ctx.prompts.initial}\n\nRepository checkouts: ${ctx.repo\n\t\t.all()\n\t\t.map((repo) => `${repo.key}: ${repo.fsPath}`)\n\t\t.join(\"; \")}\n\nFollow this plan:\n${ctx.input.plan}\n\nRules:\n- keep going until the change is complete; do any necessary additional passes without asking\n- make repository changes only inside the current working directory\n- run file edits, Git commands, and checks in the appropriate checkout\n- follow each repository’s instructions and validate every affected repository\n- leave changes uncommitted; delivery owns commits and pushes\n- do not read from or write to any original source repository path outside the process workspace\n- keep the implementation coherent and complete\n- keep the number of changed files small\n- when documenting, be sparse. Do not narrate the implementation or maintain a prose inventory of tests, helpers, internal environment variables, or cleanup mechanics.\n- publish the implementation summary when done`;\n}\n"],"mappings":";AAGO,SAAS,qBACf,KACS;AACT,SAAO;AAAA,EACN,IAAI,QAAQ,OAAO;AAAA;AAAA,wBAEG,IAAI,KACzB,IAAI,EACJ,IAAI,CAAC,SAAS,GAAG,KAAK,GAAG,KAAK,KAAK,MAAM,EAAE,EAC3C,KAAK,IAAI,CAAC;AAAA;AAAA;AAAA,EAGX,IAAI,MAAM,IAAI;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAahB;","names":[]}
|