@leitwerk-dev/coding 0.5.10 → 0.5.12

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 (32) hide show
  1. package/README.md +1 -0
  2. package/dist/{chunk-JL53OV5M.js → chunk-5M3DTAVU.js} +25 -9
  3. package/dist/chunk-5M3DTAVU.js.map +1 -0
  4. package/dist/{chunk-E3DB4TIZ.js → chunk-DVQWH5SN.js} +22 -2
  5. package/dist/chunk-DVQWH5SN.js.map +1 -0
  6. package/dist/{chunk-VG6XF3OK.js → chunk-GIWVCTYT.js} +20 -14
  7. package/dist/chunk-GIWVCTYT.js.map +1 -0
  8. package/dist/finalization-git-internal.d.ts +2 -0
  9. package/dist/finalization-git-internal.d.ts.map +1 -1
  10. package/dist/finalization-git.js +2 -2
  11. package/dist/index.js +2 -2
  12. package/dist/{repository-change-launch-internal-CP2jJJCR.d.ts → repository-change-launch-internal-D_QWCQAN.d.ts} +1 -1
  13. package/dist/{repository-change-process-DbcnkzLw.d.ts → repository-change-process-Dc-jsbCL.d.ts} +2 -0
  14. package/dist/repository-change-process.d.ts +2 -0
  15. package/dist/repository-change-process.d.ts.map +1 -1
  16. package/dist/repository-change-publication.d.ts +4 -0
  17. package/dist/repository-change-publication.d.ts.map +1 -1
  18. package/dist/repository-change-publication.js +41 -33
  19. package/dist/repository-change-publication.js.map +1 -1
  20. package/dist/repository-reconciliation.d.ts +15 -13
  21. package/dist/repository-reconciliation.d.ts.map +1 -1
  22. package/dist/submodule-staging.d.ts +11 -0
  23. package/dist/submodule-staging.d.ts.map +1 -0
  24. package/package.json +5 -5
  25. package/src/finalization-git-internal.ts +19 -17
  26. package/src/repository-change-process.ts +24 -6
  27. package/src/repository-change-publication.ts +41 -33
  28. package/src/repository-reconciliation.ts +17 -27
  29. package/src/submodule-staging.ts +27 -0
  30. package/dist/chunk-E3DB4TIZ.js.map +0 -1
  31. package/dist/chunk-JL53OV5M.js.map +0 -1
  32. package/dist/chunk-VG6XF3OK.js.map +0 -1
@@ -0,0 +1,11 @@
1
+ import { type TurnDiagnosticReport } from "@leitwerk-dev/process-sdk";
2
+ /** @internal */
3
+ export declare function prepareSubmodules(repo: {
4
+ key: string;
5
+ fsPath: string;
6
+ }, ctx: {
7
+ reportDiagnostic(report: TurnDiagnosticReport): void;
8
+ }): Promise<string | undefined>;
9
+ /** @internal */
10
+ export declare function assertSafeSubmoduleStaging(git: (args: string[]) => string): void;
11
+ //# sourceMappingURL=submodule-staging.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"submodule-staging.d.ts","sourceRoot":"","sources":["../src/submodule-staging.ts"],"names":[],"mappings":"AAAA,OAAO,EAA+B,KAAK,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AAEnG,gBAAgB;AAChB,wBAAsB,iBAAiB,CACtC,IAAI,EAAE;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,EACrC,GAAG,EAAE;IAAE,gBAAgB,CAAC,MAAM,EAAE,oBAAoB,GAAG,IAAI,CAAA;CAAE,+BAK7D;AAID,gBAAgB;AAChB,wBAAgB,0BAA0B,CAAC,GAAG,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,MAAM,GAAG,IAAI,CAWhF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leitwerk-dev/coding",
3
- "version": "0.5.10",
3
+ "version": "0.5.12",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/leitwerk-dev/leitwerk.git",
@@ -65,12 +65,12 @@
65
65
  "build": "tsup --silent"
66
66
  },
67
67
  "dependencies": {
68
- "@leitwerk-dev/domain": "0.5.10",
69
- "@leitwerk-dev/process-sdk": "0.5.10"
68
+ "@leitwerk-dev/domain": "0.5.12",
69
+ "@leitwerk-dev/process-sdk": "0.5.12"
70
70
  },
71
71
  "devDependencies": {
72
- "@leitwerk-dev/extension-runtime": "0.5.10",
73
- "@leitwerk-dev/test-support": "0.5.10",
72
+ "@leitwerk-dev/extension-runtime": "0.5.12",
73
+ "@leitwerk-dev/test-support": "0.5.12",
74
74
  "tsup": "^8.5.1"
75
75
  },
76
76
  "license": "Apache-2.0",
@@ -12,6 +12,7 @@ import {
12
12
  repositoryBindingMatches,
13
13
  savePublicationReceipt,
14
14
  } from "./repository-publication-receipt.js";
15
+ import { assertSafeSubmoduleStaging } from "./submodule-staging.js";
15
16
 
16
17
  /** @public */
17
18
  export interface GitIdentity {
@@ -116,14 +117,7 @@ function repositoryGit(projectKey: string, repoPath: string) {
116
117
  return result.ok ? trimToNull(result.stdout) : null;
117
118
  }
118
119
 
119
- function workingTreeStatus(): string[] {
120
- return (gitOrNull("status", "--porcelain") ?? "")
121
- .split(/\r?\n/)
122
- .map((line) => line.replace(/\s+$/, ""))
123
- .filter(Boolean)
124
- .map((line) => line.slice(2).trim())
125
- .filter(Boolean);
126
- }
120
+ const workingTreeStatus = () => git("status", "--porcelain", "--ignore-submodules=dirty");
127
121
 
128
122
  function conflictedFiles(): string[] {
129
123
  return (gitOrNull("diff", "--name-only", "--diff-filter=U") ?? "")
@@ -147,14 +141,13 @@ function repositoryGit(projectKey: string, repoPath: string) {
147
141
  }
148
142
 
149
143
  function commitIfDirty(commitMessage: string, identity: GitIdentity): string {
150
- if (workingTreeStatus().length === 0) return git("rev-parse", "HEAD");
144
+ if (!workingTreeStatus()) return git("rev-parse", "HEAD");
151
145
  assertGitIdentity(identity);
152
146
  checkedGit(["add", "--all"], "Failed to stage the completed change");
153
147
  checkedGit(["commit", "--no-gpg-sign", "-m", commitMessage], "Commit failed", identity);
154
148
  const remaining = workingTreeStatus();
155
- if (remaining.length > 0) {
156
- throw new DeterministicGitError(`Commit left uncommitted changes: ${remaining.join(", ")}`);
157
- }
149
+ if (remaining)
150
+ throw new DeterministicGitError(`Commit left uncommitted changes:\n${remaining}`);
158
151
  return git("rev-parse", "HEAD");
159
152
  }
160
153
 
@@ -223,7 +216,15 @@ function repositoryGit(projectKey: string, repoPath: string) {
223
216
  return pushTarget;
224
217
  }
225
218
 
226
- return { runGit, git, conflictedFiles, mergeInProgress, commitIfDirty, pushAndVerify };
219
+ return {
220
+ runGit,
221
+ git,
222
+ workingTreeStatus,
223
+ conflictedFiles,
224
+ mergeInProgress,
225
+ commitIfDirty,
226
+ pushAndVerify,
227
+ };
227
228
  }
228
229
 
229
230
  /** Inspect staged, unstaged, untracked, and already committed unpublished changes. @public */
@@ -232,10 +233,8 @@ export function repositoryHasChanges(
232
233
  baseBranch: string,
233
234
  projectKey = "repo",
234
235
  ): boolean {
235
- const { git } = repositoryGit(projectKey, repoPath);
236
- return Boolean(
237
- git("status", "--porcelain") || git("diff", "--name-only", `origin/${baseBranch}...HEAD`),
238
- );
236
+ const { git, workingTreeStatus } = repositoryGit(projectKey, repoPath);
237
+ return Boolean(workingTreeStatus() || git("diff", "--name-only", `origin/${baseBranch}...HEAD`));
239
238
  }
240
239
 
241
240
  /** Commit the current workspace change and non-force push only the feature branch. */
@@ -252,6 +251,8 @@ export function commitAndPushWorkBranch(input: {
252
251
  gitIdentity: GitIdentity;
253
252
  /** Captured remote head; null requires branch creation. @internal */
254
253
  expectedRemoteHead?: string | null;
254
+ /** Require explicit staging of submodule Git link changes. @internal */
255
+ protectSubmodules?: boolean;
255
256
  }) {
256
257
  const repoPath = path.resolve(input.repoPath);
257
258
  const { runGit, git, conflictedFiles, mergeInProgress, commitIfDirty, pushAndVerify } =
@@ -276,6 +277,7 @@ export function commitAndPushWorkBranch(input: {
276
277
  `Cannot publish a work branch with unresolved conflicts: ${conflicts.join(", ") || "merge in progress"}`,
277
278
  );
278
279
  }
280
+ if (input.protectSubmodules) assertSafeSubmoduleStaging((args) => git(...args));
279
281
  const headSha = commitIfDirty(input.commitMessage, input.gitIdentity);
280
282
  return {
281
283
  /** @public */
@@ -18,6 +18,7 @@ import {
18
18
  } from "./repository-change-state-internal.js";
19
19
  import { prepareInitialRepository, reconciliationPrompt } from "./repository-reconciliation.js";
20
20
  import { codingPurposes } from "./settings.js";
21
+ import { prepareSubmodules } from "./submodule-staging.js";
21
22
  import { prepareRepositoryCommitMessageEvidence } from "./turns/commit-message-evidence.js";
22
23
  import {
23
24
  buildRepositoryCommitMessagesPrompt,
@@ -87,6 +88,8 @@ export interface RepositoryChangeProcessConfig<TParams extends RepositoryChangeP
87
88
  fragment: FlowFragmentBuilder<TParams, RepositoryChangeState>;
88
89
  /** @public */
89
90
  happyPath?: readonly string[];
91
+ /** @internal */
92
+ prepareSubmodules?: boolean;
90
93
  };
91
94
  }
92
95
 
@@ -274,6 +277,7 @@ export function createRepositoryChangeProcess<TParams extends RepositoryChangePa
274
277
  )
275
278
  .publish("plan");
276
279
  const refreshTarget = config.workflow?.refreshTargetBeforeImplementation;
280
+ const prepareDependencies = config.publication.prepareSubmodules;
277
281
  const implement = flow
278
282
  .llm<TParams, RepositoryChangeState>("implement")
279
283
  .description("Implement")
@@ -283,24 +287,37 @@ export function createRepositoryChangeProcess<TParams extends RepositoryChangePa
283
287
  .freshSeededPrimary()
284
288
  .startFromRoot()
285
289
  .consume("plan")
286
- .prepare((ctx) => ({
287
- reconciliation: ctx.repo.all().map((repo) => {
290
+ .prepare(async (ctx) => {
291
+ const submoduleWarnings: string[] = [];
292
+ for (const repo of ctx.repo.all()) {
288
293
  const identity = asUnknownRecord(
289
294
  ctx.projects.find((p) => p.key === repo.key)?.metadata?.["leitwerk.gitIdentity"],
290
295
  );
291
- return prepareInitialRepository({
296
+ const result = prepareInitialRepository({
292
297
  projectKey: repo.key,
293
298
  repoPath: repo.fsPath,
294
299
  workBranch: repo.workBranch,
295
300
  baseBranch: refreshTarget ? repo.baseBranch : undefined,
301
+ protectSubmodules: prepareDependencies,
296
302
  gitIdentity:
297
303
  typeof identity?.name === "string" && typeof identity.email === "string"
298
304
  ? { name: identity.name, email: identity.email }
299
305
  : undefined,
300
306
  });
301
- }),
302
- }))
303
- .buildPrompt((ctx) => `${buildImplementPrompt(ctx, refreshTarget)}\n\n${reconciliationPrompt}`)
307
+ if (prepareDependencies && result.status !== "conflicts") {
308
+ const warning = await prepareSubmodules(repo, ctx);
309
+ if (warning) submoduleWarnings.push(warning);
310
+ }
311
+ }
312
+ return { submoduleWarnings };
313
+ })
314
+ .buildPrompt((ctx) =>
315
+ [
316
+ buildImplementPrompt(ctx, refreshTarget),
317
+ reconciliationPrompt,
318
+ ...(ctx.prepared?.submoduleWarnings ?? []),
319
+ ].join("\n\n"),
320
+ )
304
321
  .outcomeTool("implementation_ready", (tool) =>
305
322
  tool
306
323
  .description("Implementation and checks are complete; continue to delivery")
@@ -412,6 +429,7 @@ ${ctx.input["simplification-plan"]}`,
412
429
  .turn(applySimplification)
413
430
  .turn(generateCommitMessage)
414
431
  .use(config.publication.fragment);
432
+ if (prepareDependencies) builder.runtime({ repositorySubmodules: "best_effort" });
415
433
  if (config.repositoryCredentials) builder.repositoryCredentials(config.repositoryCredentials);
416
434
  if (config.launcher) builder.launcher(config.launcher);
417
435
  return {
@@ -30,6 +30,7 @@ import {
30
30
  retainConcurrentRebase,
31
31
  } from "./repository-reconciliation.js";
32
32
  import { codingPurposes } from "./settings.js";
33
+ import { prepareSubmodules } from "./submodule-staging.js";
33
34
 
34
35
  export {
35
36
  createPullRequestChangeProcess,
@@ -201,6 +202,8 @@ export interface RepositoryChangePublicationAdapter<P> {
201
202
  };
202
203
  /** @public */
203
204
  namespace: string;
205
+ /** Prepare pinned submodules after revision reconciliation. @public */
206
+ prepareSubmodules?: boolean;
204
207
  /** Reconcile a single-repository no-change outcome. @public */
205
208
  unchanged?(ctx: PublicationContext<P>): Promise<void>;
206
209
  /** Optional coordinated repositories; each retains independent publication state. @public */
@@ -649,6 +652,7 @@ export function createRepositoryChangePublication<P>(
649
652
  commitMessage,
650
653
  gitIdentity,
651
654
  expectedRemoteHead,
655
+ protectSubmodules: adapter.prepareSubmodules,
652
656
  });
653
657
  }
654
658
  async function reconcile(ctx: PublicationContext<P>, current: PublicationState) {
@@ -660,6 +664,7 @@ export function createRepositoryChangePublication<P>(
660
664
  baseBranch: repo.baseBranch,
661
665
  baselineSha: current.workBaselineSha ?? current.headSha ?? undefined,
662
666
  gitIdentity: await adapter.identity(ctx),
667
+ protectSubmodules: adapter.prepareSubmodules,
663
668
  });
664
669
  }
665
670
  const runRepository = async (ctx: PublicationContext<P>) => {
@@ -1056,26 +1061,6 @@ export function createRepositoryChangePublication<P>(
1056
1061
  return kind === "feedback" && remote(state).repairReason === "rebase" ? "rebase" : kind;
1057
1062
  }
1058
1063
 
1059
- function revisionPrompt(kind: "feedback" | "ci") {
1060
- return (ctx: {
1061
- state: RepositoryChangeState;
1062
- prepared?: unknown;
1063
- prompts?: { initial: string };
1064
- }) => {
1065
- const current = remote(ctx.state);
1066
- const repository = adapter.repositories
1067
- ? `Repository: ${activeKey(ctx.state)}. Apply changes only to this checkout. `
1068
- : "";
1069
- if (asUnknownRecord(ctx.prepared)?.deferredRebase)
1070
- return `${repository}${reconciliationPrompt}\nThe source branch or retained local work must be reconciled before the target-branch repair. Resolve any source reconciliation, then use changes_ready. Delivery will restore and validate the result before reassessing current target conflicts.`;
1071
- if (current.reconciliationRequired)
1072
- return `${repository}${reconciliationPrompt}\nValidate the reconciled repository, including any upstream target changes and retained local work, against the requested change and pending feedback: ${JSON.stringify(current.feedbackIds)}. Treat the current remote as authoritative; do not restore deliberately removed code simply to match an older plan. Use changes_ready after validation, even when no further edit is needed, so retained local changes are published. If blocked use cannot_repair.\nOriginal request for context: ${ctx.prompts?.initial ?? "Inspect the current repository and retained request"}`;
1073
- if (repairReason(ctx.state, kind) === "rebase")
1074
- return `${rebasePrompt} Evidence: ${JSON.stringify(current.conflict)}. Call changes_ready or no_changes when verified complete, cannot_repair when blocked.`;
1075
- return `${adapter.repositories ? `Repository: ${activeKey(ctx.state)}. Apply changes only to this checkout. ` : ""}${adapter.prompt(kind, current)}\n\n${reconciliationPrompt}`;
1076
- };
1077
- }
1078
-
1079
1064
  function revisionTurn(id: string, kind: "feedback" | "ci") {
1080
1065
  const turn = flow
1081
1066
  .llm<P, RepositoryChangeState>(id)
@@ -1102,11 +1087,16 @@ export function createRepositoryChangePublication<P>(
1102
1087
  .prepare(async (ctx) => {
1103
1088
  const project = ctx.repo.get(activeKey(ctx.state) ?? "repo");
1104
1089
  const current = remote(ctx.state);
1090
+ const prepareDependencies = () =>
1091
+ adapter.prepareSubmodules ? prepareSubmodules(project, ctx) : undefined;
1092
+ const prepareRebase = async () => {
1093
+ startRebase(rebaseInput(ctx));
1094
+ return { deferredRebase: false, submoduleWarning: await prepareDependencies() };
1095
+ };
1105
1096
  const targetRebase =
1106
1097
  repairReason(ctx.state, kind) === "rebase" && !current.reconciliationRequired;
1107
1098
  // Resume Git's existing target repair; it must not be mistaken for source synchronization.
1108
- if (targetRebase && hasPreparedRebase(rebaseInput(ctx)))
1109
- return { rebase: startRebase(rebaseInput(ctx)) };
1099
+ if (targetRebase && hasPreparedRebase(rebaseInput(ctx))) return prepareRebase();
1110
1100
  const report = (label: string, status: "in_progress" | "completed") =>
1111
1101
  ctx.reportProgress({
1112
1102
  title: "Repository reconciliation",
@@ -1117,19 +1107,35 @@ export function createRepositoryChangePublication<P>(
1117
1107
  if (reconciliation.status === "conflicts")
1118
1108
  report("Resolve reconciliation conflicts", "in_progress");
1119
1109
  else report("Repository reconciled", "completed");
1120
- if (targetRebase) {
1121
- if (
1122
- reconciliation.status !== "unchanged" ||
1123
- reconciliation.headSha !== current.conflict?.headSha ||
1124
- repositoryWorktreeIsDirty({ projectKey: project.key, repoPath: project.fsPath })
1125
- )
1126
- return { reconciliation, deferredRebase: true };
1127
- return { rebase: startRebase(rebaseInput(ctx)) };
1128
- }
1129
- return { reconciliation };
1110
+ if (
1111
+ targetRebase &&
1112
+ reconciliation.status === "unchanged" &&
1113
+ reconciliation.headSha === current.conflict?.headSha &&
1114
+ !repositoryWorktreeIsDirty({ projectKey: project.key, repoPath: project.fsPath })
1115
+ )
1116
+ return prepareRebase();
1117
+ return {
1118
+ deferredRebase: targetRebase,
1119
+ submoduleWarning:
1120
+ reconciliation.status !== "conflicts" ? await prepareDependencies() : undefined,
1121
+ };
1130
1122
  })
1131
1123
  .freshPrimary()
1132
- .prompt(revisionPrompt(kind));
1124
+ .buildPrompt((ctx) => {
1125
+ const current = remote(ctx.state);
1126
+ const repository = adapter.repositories
1127
+ ? `Repository: ${activeKey(ctx.state)}. Apply changes only to this checkout. `
1128
+ : "";
1129
+ let prompt: string;
1130
+ if (ctx.prepared?.deferredRebase)
1131
+ prompt = `${repository}${reconciliationPrompt}\nThe source branch or retained local work must be reconciled before the target-branch repair. Resolve any source reconciliation, then use changes_ready. Delivery will restore and validate the result before reassessing current target conflicts.`;
1132
+ else if (current.reconciliationRequired)
1133
+ prompt = `${repository}${reconciliationPrompt}\nValidate the reconciled repository, including any upstream target changes and retained local work, against the requested change and pending feedback: ${JSON.stringify(current.feedbackIds)}. Treat the current remote as authoritative; do not restore deliberately removed code simply to match an older plan. Use changes_ready after validation, even when no further edit is needed, so retained local changes are published. If blocked use cannot_repair.\nOriginal request for context: ${ctx.prompts.initial || "Inspect the current repository and retained request"}`;
1134
+ else if (repairReason(ctx.state, kind) === "rebase")
1135
+ prompt = `${rebasePrompt} Evidence: ${JSON.stringify(current.conflict)}. Call changes_ready or no_changes when verified complete, cannot_repair when blocked.`;
1136
+ else prompt = `${repository}${adapter.prompt(kind, current)}\n\n${reconciliationPrompt}`;
1137
+ return [prompt, ctx.prepared?.submoduleWarning].filter(Boolean).join("\n\n");
1138
+ });
1133
1139
  for (const [name, description] of [
1134
1140
  ["changes_ready", "Repository changes are ready to publish"],
1135
1141
  ["no_changes", "No repository change is required"],
@@ -1236,5 +1242,7 @@ export function createRepositoryChangePublication<P>(
1236
1242
 
1237
1243
  /** @public */
1238
1244
  happyPath: [ids.deliver],
1245
+ /** @internal */
1246
+ prepareSubmodules: adapter.prepareSubmodules,
1239
1247
  };
1240
1248
  }
@@ -14,21 +14,17 @@ import {
14
14
  savePublicationReceipt,
15
15
  } from "./repository-publication-receipt.js";
16
16
  import { repositoryRecord } from "./repository-record.js";
17
+ import { assertSafeSubmoduleStaging } from "./submodule-staging.js";
17
18
 
18
- /** @internal */
19
- export interface ReconciliationInput {
20
- projectKey: string;
21
- repoPath: string;
22
- workBranch: string;
19
+ type RepositoryLocation = { projectKey: string; repoPath: string };
20
+ type WorkBranch = RepositoryLocation & { workBranch: string };
21
+ type ReconciliationInput = WorkBranch & {
23
22
  /** Last remote baseline, not the latest observation. */
24
- baselineSha: string;
25
- /** Trusted project identity for replaying unpublished commits. */
26
- gitIdentity?: GitIdentity;
27
- }
28
-
29
- type WorkBranchInput = Omit<ReconciliationInput, "baselineSha"> & {
30
23
  baselineSha?: string;
31
24
  baseBranch?: string;
25
+ protectSubmodules?: boolean;
26
+ /** Trusted project identity for replaying unpublished commits. */
27
+ gitIdentity?: GitIdentity;
32
28
  };
33
29
 
34
30
  /** @internal */
@@ -60,7 +56,7 @@ interface RecordState extends RepositoryBinding {
60
56
  };
61
57
  }
62
58
 
63
- function repository(input: Pick<ReconciliationInput, "projectKey" | "repoPath">) {
59
+ function repository(input: RepositoryLocation) {
64
60
  function git(args: string[], extra: NodeJS.ProcessEnv = {}): string {
65
61
  const output = execFileSync(resolveGitBinary(), repositoryGitArgs(args), {
66
62
  cwd: input.repoPath,
@@ -200,7 +196,7 @@ function withLock<T>(directory: string, run: () => T): T {
200
196
  * They are retained under private refs and removed from HEAD before publication.
201
197
  * A conflicted rebase is deliberately left in place for the existing adjustment turn.
202
198
  */
203
- function reconcile(input: WorkBranchInput, preparing: boolean): ReconciliationResult {
199
+ function reconcile(input: ReconciliationInput, preparing: boolean): ReconciliationResult {
204
200
  const { git, directory, read, save, binding: readBinding } = repository(input);
205
201
  return withLock(directory, () => {
206
202
  git(["check-ref-format", `refs/heads/${input.workBranch}`]);
@@ -336,6 +332,7 @@ function reconcile(input: WorkBranchInput, preparing: boolean): ReconciliationRe
336
332
  }
337
333
  if (git(["diff", "--name-only", "--diff-filter=U"]))
338
334
  throw new Error("Unresolved local conflicts must be repaired before reconciliation");
335
+ if (input.protectSubmodules) assertSafeSubmoduleStaging(git);
339
336
  // Dirty submodule work cannot be represented by the parent's tree checkpoint.
340
337
  if (git(["submodule", "foreach", "--quiet", "git status --porcelain"]))
341
338
  throw new Error("Commit or preserve dirty submodule work before reconciliation");
@@ -504,10 +501,7 @@ function reconcile(input: WorkBranchInput, preparing: boolean): ReconciliationRe
504
501
  }
505
502
 
506
503
  /** Reject ignored-file collisions before a target checkout/rebase can overwrite them. @internal */
507
- export function assertReconciliationTargetSafe(
508
- input: Pick<ReconciliationInput, "repoPath" | "projectKey">,
509
- targetSha: string,
510
- ): void {
504
+ export function assertReconciliationTargetSafe(input: RepositoryLocation, targetSha: string): void {
511
505
  const { git, read } = repository(input);
512
506
  assertIgnoredProtection(git, read()?.protectedIgnored);
513
507
  if (ignoredPathsCollide(git, ignoredPaths(git), targetSha, `${targetSha}..HEAD`))
@@ -516,7 +510,8 @@ export function assertReconciliationTargetSafe(
516
510
 
517
511
  /** Preserve a target rebase as a net local delta when its source lease changes. @internal */
518
512
  export function retainConcurrentRebase(
519
- input: ReconciliationInput & {
513
+ input: WorkBranch & {
514
+ baselineSha: string;
520
515
  rebasedHead: string;
521
516
  targetBase: string;
522
517
  gitIdentity: GitIdentity;
@@ -569,29 +564,24 @@ export function retainConcurrentRebase(
569
564
  }
570
565
 
571
566
  /** @internal */
572
- export function repositoryWorktreeIsDirty(
573
- input: Pick<ReconciliationInput, "repoPath" | "projectKey">,
574
- ): boolean {
567
+ export function repositoryWorktreeIsDirty(input: RepositoryLocation): boolean {
575
568
  return Boolean(repository(input).git(["status", "--porcelain"]));
576
569
  }
577
570
 
578
571
  /** Capture the baseline before the first implementation, including an unpublished branch. @internal */
579
572
  export function prepareInitialRepository(
580
- input: Omit<WorkBranchInput, "baselineSha">,
573
+ input: Omit<ReconciliationInput, "baselineSha">,
581
574
  ): ReconciliationResult {
582
575
  return reconcile(input, true);
583
576
  }
584
577
 
585
578
  /** Missing branches are allowed only before first publication. @internal */
586
- export function reconcilePublicationRepository(input: WorkBranchInput): ReconciliationResult {
579
+ export function reconcilePublicationRepository(input: ReconciliationInput): ReconciliationResult {
587
580
  return reconcile(input, false);
588
581
  }
589
582
 
590
583
  /** Record only a remotely verified publication, including recovery after a lost reply. @internal */
591
- export function recordRepositoryPublication(
592
- input: Omit<ReconciliationInput, "baselineSha" | "gitIdentity">,
593
- headSha: string,
594
- ): void {
584
+ export function recordRepositoryPublication(input: WorkBranch, headSha: string): void {
595
585
  const { directory, read, save, binding: readBinding } = repository(input);
596
586
  withLock(directory, () => {
597
587
  const old = read();
@@ -0,0 +1,27 @@
1
+ import { prepareRepositorySubmodules, type TurnDiagnosticReport } from "@leitwerk-dev/process-sdk";
2
+
3
+ /** @internal */
4
+ export async function prepareSubmodules(
5
+ repo: { key: string; fsPath: string },
6
+ ctx: { reportDiagnostic(report: TurnDiagnosticReport): void },
7
+ ) {
8
+ const message = await prepareRepositorySubmodules(repo.key, repo.fsPath);
9
+ if (message) ctx.reportDiagnostic({ level: "warn", code: "repository.submodules", message });
10
+ return message;
11
+ }
12
+
13
+ // A failed refresh can leave a retained submodule at its previous commit. Do
14
+ // not let a parent-wide git add turn that checkout into a pointer change.
15
+ /** @internal */
16
+ export function assertSafeSubmoduleStaging(git: (args: string[]) => string): void {
17
+ const unstaged = git(["diff", "--raw", "--no-renames", "--ignore-submodules=dirty", "-z"]);
18
+ const changesGitlink = /(?:^|\0):(?:160000 \d{6}|\d{6} 160000) /.test(unstaged);
19
+ const untracked = git(["ls-files", "--others", "--exclude-standard", "-z"]);
20
+ // git ls-files reports an embedded worktree as a path ending in slash,
21
+ // unlike ordinary untracked files.
22
+ const embeddedCheckout = untracked.split("\0").some((entry) => entry.endsWith("/"));
23
+ if (changesGitlink || embeddedCheckout)
24
+ throw new Error(
25
+ "Cannot automatically stage an out-of-sync or untracked submodule. Restore the checkout or explicitly stage the intended Git link change.",
26
+ );
27
+ }
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/repository-record.ts","../src/repository-publication-receipt.ts"],"sourcesContent":["import { existsSync, readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/** Repository-local JSON with atomic replacement. Callers own validation and locking. @internal */\nexport function repositoryRecord<T>(gitDirectory: string, name: string) {\n\tconst file = join(gitDirectory, `leitwerk-${name}.json`);\n\treturn {\n\t\tread: (): T | null => (existsSync(file) ? JSON.parse(readFileSync(file, \"utf8\")) : null),\n\t\tsave: (record: T): void => {\n\t\t\twriteFileSync(`${file}.tmp`, JSON.stringify(record), { mode: 0o600 });\n\t\t\trenameSync(`${file}.tmp`, file);\n\t\t},\n\t};\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { repositoryRecord } from \"./repository-record.js\";\n\n/** @internal */\nexport interface RepositoryBinding {\n\tbranch: string;\n\torigin: string;\n\tpushOrigin: string;\n}\n\n/** @internal */\nexport function readRepositoryBinding(\n\tgit: (...args: string[]) => string,\n\tbranch: string,\n): RepositoryBinding {\n\treturn {\n\t\tbranch,\n\t\torigin: git(\"remote\", \"get-url\", \"origin\"),\n\t\tpushOrigin: git(\"remote\", \"get-url\", \"--push\", \"--all\", \"origin\"),\n\t};\n}\n\n/** @internal */\nexport function repositoryBindingMatches(\n\trecord: RepositoryBinding | null,\n\tbinding: RepositoryBinding,\n): boolean {\n\treturn (\n\t\t!record ||\n\t\t(record.branch === binding.branch &&\n\t\t\trecord.origin === binding.origin &&\n\t\t\trecord.pushOrigin === binding.pushOrigin)\n\t);\n}\n\n/** A local write-ahead receipt, not a replacement for the server-owned process state. @internal */\nexport interface RepositoryPublicationReceipt extends RepositoryBinding {\n\texpectedHead: string | null;\n\tcandidate: string;\n\tstatus: \"attempting\" | \"accepted\" | \"rejected\";\n}\n\n/** @internal */\nexport function readPublicationReceipt(gitDirectory: string): RepositoryPublicationReceipt | null {\n\tconst file = join(gitDirectory, \"leitwerk-publication.json\");\n\tif (!existsSync(file)) return null;\n\tconst value = JSON.parse(readFileSync(file, \"utf8\"));\n\tif (\n\t\t!value ||\n\t\ttypeof value.branch !== \"string\" ||\n\t\ttypeof value.origin !== \"string\" ||\n\t\ttypeof value.pushOrigin !== \"string\" ||\n\t\t![\"attempting\", \"accepted\", \"rejected\"].includes(value.status) ||\n\t\t!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(value.candidate) ||\n\t\t!(value.expectedHead === null || /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(value.expectedHead))\n\t)\n\t\tthrow new Error(\"Invalid repository publication receipt; local work was retained\");\n\treturn value;\n}\n\n/** Persist intent before sending and acceptance before checking for subsequent remote movement. @internal */\nexport const savePublicationReceipt = (\n\tgitDirectory: string,\n\treceipt: RepositoryPublicationReceipt,\n) => repositoryRecord(gitDirectory, \"publication\").save(receipt);\n\n/** Porcelain rejection is proof of no write; transport failures are not. @internal */\nexport function pushWasRejected(porcelain: string): boolean {\n\treturn porcelain.split(\"\\n\").some((line) => /^!\\t[^\\t]+\\t\\[(?:remote )?rejected\\]/.test(line));\n}\n"],"mappings":";AAAA,SAAS,YAAY,cAAc,YAAY,qBAAqB;AACpE,SAAS,YAAY;AAGd,SAAS,iBAAoB,cAAsB,MAAc;AACvE,QAAM,OAAO,KAAK,cAAc,YAAY,IAAI,OAAO;AACvD,SAAO;AAAA,IACN,MAAM,MAAiB,WAAW,IAAI,IAAI,KAAK,MAAM,aAAa,MAAM,MAAM,CAAC,IAAI;AAAA,IACnF,MAAM,CAAC,WAAoB;AAC1B,oBAAc,GAAG,IAAI,QAAQ,KAAK,UAAU,MAAM,GAAG,EAAE,MAAM,IAAM,CAAC;AACpE,iBAAW,GAAG,IAAI,QAAQ,IAAI;AAAA,IAC/B;AAAA,EACD;AACD;;;ACbA,SAAS,cAAAA,aAAY,gBAAAC,qBAAoB;AACzC,SAAS,QAAAC,aAAY;AAWd,SAAS,sBACf,KACA,QACoB;AACpB,SAAO;AAAA,IACN;AAAA,IACA,QAAQ,IAAI,UAAU,WAAW,QAAQ;AAAA,IACzC,YAAY,IAAI,UAAU,WAAW,UAAU,SAAS,QAAQ;AAAA,EACjE;AACD;AAGO,SAAS,yBACf,QACA,SACU;AACV,SACC,CAAC,UACA,OAAO,WAAW,QAAQ,UAC1B,OAAO,WAAW,QAAQ,UAC1B,OAAO,eAAe,QAAQ;AAEjC;AAUO,SAAS,uBAAuB,cAA2D;AACjG,QAAM,OAAOC,MAAK,cAAc,2BAA2B;AAC3D,MAAI,CAACC,YAAW,IAAI,EAAG,QAAO;AAC9B,QAAM,QAAQ,KAAK,MAAMC,cAAa,MAAM,MAAM,CAAC;AACnD,MACC,CAAC,SACD,OAAO,MAAM,WAAW,YACxB,OAAO,MAAM,WAAW,YACxB,OAAO,MAAM,eAAe,YAC5B,CAAC,CAAC,cAAc,YAAY,UAAU,EAAE,SAAS,MAAM,MAAM,KAC7D,CAAC,kCAAkC,KAAK,MAAM,SAAS,KACvD,EAAE,MAAM,iBAAiB,QAAQ,kCAAkC,KAAK,MAAM,YAAY;AAE1F,UAAM,IAAI,MAAM,iEAAiE;AAClF,SAAO;AACR;AAGO,IAAM,yBAAyB,CACrC,cACA,YACI,iBAAiB,cAAc,aAAa,EAAE,KAAK,OAAO;AAGxD,SAAS,gBAAgB,WAA4B;AAC3D,SAAO,UAAU,MAAM,IAAI,EAAE,KAAK,CAAC,SAAS,uCAAuC,KAAK,IAAI,CAAC;AAC9F;","names":["existsSync","readFileSync","join","join","existsSync","readFileSync"]}