@leitwerk-dev/coding 0.3.1 → 0.4.0

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 (108) hide show
  1. package/README.md +86 -1
  2. package/dist/chunk-ABQH2WZT.js +36 -0
  3. package/dist/chunk-ABQH2WZT.js.map +1 -0
  4. package/dist/{chunk-YSC5GEQJ.js → chunk-BI45R2FH.js} +7 -3
  5. package/dist/chunk-BI45R2FH.js.map +1 -0
  6. package/dist/chunk-DNG7D77K.js +65 -0
  7. package/dist/chunk-DNG7D77K.js.map +1 -0
  8. package/dist/chunk-L2TFD72B.js +16320 -0
  9. package/dist/chunk-L2TFD72B.js.map +1 -0
  10. package/dist/chunk-M2VTUPFO.js +265 -0
  11. package/dist/chunk-M2VTUPFO.js.map +1 -0
  12. package/dist/chunk-OM2AMDTJ.js +347 -0
  13. package/dist/chunk-OM2AMDTJ.js.map +1 -0
  14. package/dist/chunk-Q24RPXOA.js +159 -0
  15. package/dist/chunk-Q24RPXOA.js.map +1 -0
  16. package/dist/chunk-SKGB4CZS.js +14 -0
  17. package/dist/chunk-SKGB4CZS.js.map +1 -0
  18. package/dist/chunk-SZ4WOGV2.js +120 -0
  19. package/dist/chunk-SZ4WOGV2.js.map +1 -0
  20. package/dist/finalization-git-internal.d.ts +3 -0
  21. package/dist/finalization-git-internal.d.ts.map +1 -1
  22. package/dist/finalization-git.d.ts +1 -1
  23. package/dist/finalization-git.d.ts.map +1 -1
  24. package/dist/finalization-git.js +5 -3
  25. package/dist/index.d.ts +1 -0
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +17 -591
  28. package/dist/index.js.map +1 -1
  29. package/dist/pull-request-publication-internal.d.ts +26 -24
  30. package/dist/pull-request-publication-internal.d.ts.map +1 -1
  31. package/dist/repository-change-launch-internal-BudnAfL7.d.ts +88 -0
  32. package/dist/repository-change-launch-internal.d.ts +32 -11
  33. package/dist/repository-change-launch-internal.d.ts.map +1 -1
  34. package/dist/repository-change-launch.d.ts +4 -3
  35. package/dist/repository-change-launch.d.ts.map +1 -1
  36. package/dist/repository-change-launch.js +162 -34
  37. package/dist/repository-change-launch.js.map +1 -1
  38. package/dist/repository-change-process-DlgF04fU.d.ts +69 -0
  39. package/dist/repository-change-process.d.ts +30 -25
  40. package/dist/repository-change-process.d.ts.map +1 -1
  41. package/dist/repository-change-publication.d.ts +62 -6
  42. package/dist/repository-change-publication.d.ts.map +1 -1
  43. package/dist/repository-change-publication.js +364 -90
  44. package/dist/repository-change-publication.js.map +1 -1
  45. package/dist/repository-change-state-internal.d.ts +18 -4
  46. package/dist/repository-change-state-internal.d.ts.map +1 -1
  47. package/dist/repository-change-ui-launcher-internal.d.ts +34 -22
  48. package/dist/repository-change-ui-launcher-internal.d.ts.map +1 -1
  49. package/dist/settings.d.ts +15 -0
  50. package/dist/settings.d.ts.map +1 -0
  51. package/dist/turns/commit-message-evidence.d.ts +35 -0
  52. package/dist/turns/commit-message-evidence.d.ts.map +1 -0
  53. package/dist/turns/commit-message-evidence.js +9 -0
  54. package/dist/turns/generate-commit-message.d.ts +4 -1
  55. package/dist/turns/generate-commit-message.d.ts.map +1 -1
  56. package/dist/turns/generate-commit-message.js +7 -5
  57. package/dist/turns/generate-plan.d.ts.map +1 -1
  58. package/dist/turns/generate-plan.js +1 -1
  59. package/dist/turns/git-inspection-profile.d.ts +25 -0
  60. package/dist/turns/git-inspection-profile.d.ts.map +1 -0
  61. package/dist/turns/git-inspection-profile.js +8 -0
  62. package/dist/turns/implement.d.ts.map +1 -1
  63. package/dist/turns/implement.js +1 -1
  64. package/dist/turns/simplify-implementation.d.ts +1 -1
  65. package/dist/turns/simplify-implementation.d.ts.map +1 -1
  66. package/dist/turns/simplify-implementation.js +3 -3
  67. package/package.json +5 -9
  68. package/src/finalization-git-internal.ts +117 -114
  69. package/src/finalization-git.ts +1 -1
  70. package/src/index.ts +4 -1
  71. package/src/pull-request-publication-internal.ts +156 -78
  72. package/src/repository-change-launch-internal.ts +119 -12
  73. package/src/repository-change-launch.ts +8 -4
  74. package/src/repository-change-process.ts +234 -523
  75. package/src/repository-change-publication.ts +516 -121
  76. package/src/repository-change-state-internal.ts +34 -20
  77. package/src/repository-change-ui-launcher-internal.ts +139 -56
  78. package/src/settings.ts +79 -0
  79. package/src/turns/commit-message-evidence.ts +241 -0
  80. package/src/turns/generate-commit-message.ts +53 -23
  81. package/src/turns/generate-plan.ts +26 -12
  82. package/src/turns/git-inspection-profile.ts +134 -0
  83. package/src/turns/implement.ts +9 -2
  84. package/src/turns/simplify-implementation.ts +10 -6
  85. package/dist/chunk-34B3Q75M.js +0 -25
  86. package/dist/chunk-34B3Q75M.js.map +0 -1
  87. package/dist/chunk-F6CEEAFE.js +0 -13
  88. package/dist/chunk-F6CEEAFE.js.map +0 -1
  89. package/dist/chunk-GO44KCUS.js +0 -154
  90. package/dist/chunk-GO44KCUS.js.map +0 -1
  91. package/dist/chunk-R3UCUGY6.js +0 -31
  92. package/dist/chunk-R3UCUGY6.js.map +0 -1
  93. package/dist/chunk-W7VJT6AN.js +0 -25
  94. package/dist/chunk-W7VJT6AN.js.map +0 -1
  95. package/dist/chunk-WKHVLLKE.js +0 -45
  96. package/dist/chunk-WKHVLLKE.js.map +0 -1
  97. package/dist/chunk-YSC5GEQJ.js.map +0 -1
  98. package/dist/repository-change-launch-internal-Dd-AONUs.d.ts +0 -67
  99. package/dist/turns/review-implementation.d.ts +0 -4
  100. package/dist/turns/review-implementation.d.ts.map +0 -1
  101. package/dist/turns/review-implementation.js +0 -8
  102. package/dist/turns/review-plan.d.ts +0 -4
  103. package/dist/turns/review-plan.d.ts.map +0 -1
  104. package/dist/turns/review-plan.js +0 -8
  105. package/src/turns/review-implementation.ts +0 -30
  106. package/src/turns/review-plan.ts +0 -24
  107. /package/dist/turns/{review-implementation.js.map → commit-message-evidence.js.map} +0 -0
  108. /package/dist/turns/{review-plan.js.map → git-inspection-profile.js.map} +0 -0
@@ -5,33 +5,56 @@ import { parseStructuralProcessState } from "@leitwerk-dev/process-sdk";
5
5
  export interface RepositoryChangeFinalizationState {
6
6
  /** @public */
7
7
  generatedCommitMessage: string | null;
8
+ /** Messages keyed by process project key. @public */
9
+ commitMessages?: Record<string, string>;
8
10
  }
9
11
 
10
12
  /** @public */
11
13
  export interface RepositoryChangeState extends StructuralProcessState {
12
14
  /** @public */
13
15
  finalization: RepositoryChangeFinalizationState;
16
+ /** Completed routing decisions survive recovery. @public */
17
+ routing?: {
18
+ /** @public */
19
+ plan?: {
20
+ /** @internal */
21
+ planRevision: number;
22
+ /** @internal */ skip: boolean;
23
+ /** @internal */ reason: string;
24
+ };
25
+
26
+ /** @public */
27
+ simplification?: {
28
+ /** @internal */
29
+ skip: boolean;
30
+ /** @internal */ reason: string;
31
+ };
32
+ };
14
33
  /** Namespaced state owned by a caller-supplied publication workflow. */
34
+
15
35
  /** @public */
16
36
  extensionState?: Record<string, unknown>;
17
37
  }
18
38
 
19
- /** @internal */
20
- export function createEmptyRepositoryChangeFinalizationState(): RepositoryChangeFinalizationState {
21
- return { generatedCommitMessage: null };
22
- }
23
-
24
- function stringOrNull(value: unknown): string | null {
25
- return typeof value === "string" ? value : null;
26
- }
27
-
28
39
  function toRecord(value: unknown): Record<string, unknown> {
29
40
  return typeof value === "object" && value !== null ? (value as Record<string, unknown>) : {};
30
41
  }
31
42
 
32
43
  function parseFinalizationState(value: unknown): RepositoryChangeFinalizationState {
33
44
  const record = toRecord(value);
34
- return { generatedCommitMessage: stringOrNull(record.generatedCommitMessage) };
45
+ return {
46
+ generatedCommitMessage:
47
+ typeof record.generatedCommitMessage === "string" ? record.generatedCommitMessage : null,
48
+ ...(record.commitMessages
49
+ ? {
50
+ commitMessages: Object.fromEntries(
51
+ Object.entries(toRecord(record.commitMessages)).filter(
52
+ (entry): entry is [string, string] => typeof entry[1] === "string",
53
+ ),
54
+ ),
55
+ }
56
+ : {}),
57
+ };
35
58
  }
36
59
 
37
60
  /** @internal */
@@ -42,19 +65,10 @@ export const repositoryChangeStateCodec: Codec<RepositoryChangeState> = {
42
65
  ...parseStructuralProcessState(record),
43
66
  finalization: parseFinalizationState(record.finalization),
44
67
  extensionState: toRecord(record.extensionState),
68
+ routing: toRecord(record.routing) as RepositoryChangeState["routing"],
45
69
  };
46
70
  },
47
71
  serialize(value) {
48
72
  return value;
49
73
  },
50
74
  };
51
-
52
- /** @internal */
53
- export function clearReviewRefs(
54
- semanticEntryRefs: RepositoryChangeState["semanticEntryRefs"],
55
- ): RepositoryChangeState["semanticEntryRefs"] {
56
- return {
57
- ...semanticEntryRefs,
58
- review: null,
59
- };
60
- }
@@ -9,31 +9,23 @@ import {
9
9
  SafeLaunchPreparationError,
10
10
  } from "@leitwerk-dev/process-sdk";
11
11
  import { buildAutoWorkBranchFromSeed } from "./auto-work-branch.js";
12
+ import {
13
+ type RepositoryChangeLaunchParams,
14
+ type RepositoryIssueOriginParams,
15
+ type RepositoryUiOriginParams,
16
+ repositoryChangeOptionFields,
17
+ repositoryChangeOptions,
18
+ repositoryChangeWorkflow,
19
+ } from "./repository-change-launch-internal.js";
12
20
 
13
- /** Recheck provider-owned repository visibility before launch. @internal */
14
- export function repositoryVisibilityCheck(
15
- provider: string,
16
- isVisible: () => Promise<boolean>,
17
- ): LaunchPreparationCheck {
18
- return {
19
- id: "repository_visibility",
20
- label: "Check repository visibility",
21
- async run({ signal }) {
22
- signal.throwIfAborted();
23
- const visible = await isVisible();
24
- signal.throwIfAborted();
25
- if (!visible)
26
- throw new SafeLaunchPreparationError(
27
- "Repository is not visible",
28
- `Grant the selected ${provider} profile access to the repository, then try again.`,
29
- );
30
- },
31
- };
32
- }
33
-
34
- /** Shared UI mechanics; providers retain credentials, preparation and launch metadata. @internal */
35
- export function createRepositoryChangeUiLauncher<
36
- P,
21
+ /** Shared launch mechanics; providers retain credentials, preparation and launch metadata. @internal */
22
+ export function createRepositoryChangeLauncher<
23
+ P extends RepositoryChangeLaunchParams<{
24
+ /** @internal */ owner: string;
25
+ /** @internal */ repo: string;
26
+ }> &
27
+ (RepositoryIssueOriginParams | RepositoryUiOriginParams),
28
+ D,
37
29
  R extends {
38
30
  /** @internal */
39
31
  full_name: string;
@@ -54,15 +46,22 @@ export function createRepositoryChangeUiLauncher<
54
46
  /** @internal */
55
47
  providerId: string;
56
48
  /** @internal */
57
- assertConfigured(): void;
58
- /** @internal */
59
- profiles(): readonly string[];
60
- /** @internal */
61
- repositories(profile: string): Promise<readonly R[]>;
49
+ integration(dependencies: D): {
50
+ /** @internal */ profiles?(): readonly string[];
51
+ /** @internal */ client(profile: string): {
52
+ /** @internal */ listRepositories(): Promise<readonly R[]>;
53
+ /** @internal */ resolveGitIdentity(profile: string): Promise<I>;
54
+ /** @internal */ getIssue(
55
+ owner: string,
56
+ repo: string,
57
+ number: number,
58
+ ): Promise<Pick<RepositoryIssue, "html_url" | "labels">>;
59
+ };
60
+ };
62
61
  /** @internal */
63
- resolveProfiles(profile: string): B;
62
+ profile(params: P): string;
64
63
  /** @internal */
65
- resolveGitIdentity(profile: string): Promise<I>;
64
+ resolveProfiles(profile: string, dependencies: D): B;
66
65
  /** @internal */
67
66
  params(
68
67
  repository: R,
@@ -76,20 +75,64 @@ export function createRepositoryChangeUiLauncher<
76
75
  },
77
76
  ): P;
78
77
  /** @internal */
79
- launchConfig(params: P, title: string, identity: I): ProcessLaunchConfig<P>;
78
+ launchConfig(
79
+ params: P,
80
+ title: string,
81
+ identity: I,
82
+ repository: NoInfer<R>,
83
+ ): ProcessLaunchConfig<P>;
80
84
  /** @internal */
81
- preparationChecks: NonNullable<ProcessLauncherDefinition<P>["ui"]>["preparationChecks"];
82
- }): ProcessLauncherDefinition<P> & {
83
- /** Resolve issue launches using the same provider wiring as UI launches. @internal */
84
- resolveIssueLaunchConfig(event: {
85
- /** @internal */ profile: string;
86
- /** @internal */ repository: R;
87
- /** @internal */ issue: Pick<RepositoryIssue, "number" | "title" | "body" | "html_url">;
88
- /** @internal */ labels: RepositoryIssueWatcherConfig["labels"];
89
- }): Promise<ProcessLaunchConfig<P>>;
90
- } {
85
+ preparationChecks(params: P, dependencies: () => D): readonly LaunchPreparationCheck<P>[];
86
+ }) {
91
87
  const { provider, providerId } = options;
92
88
  const profileField = `${providerId}Profile`;
89
+ let dependencies: D | null = null;
90
+ function requireDependencies(): D {
91
+ if (!dependencies) throw new Error(`${provider} repository launcher is not configured`);
92
+ return dependencies;
93
+ }
94
+ const integration = () => options.integration(requireDependencies());
95
+ const profiles = () => integration().profiles?.() ?? [];
96
+ async function repositories(profile: string): Promise<readonly R[]> {
97
+ return profile && profiles().includes(profile)
98
+ ? integration().client(profile).listRepositories()
99
+ : [];
100
+ }
101
+ /** @internal */
102
+ function resolveProfiles(profile: string) {
103
+ if (!profiles().includes(profile)) throw new Error(`${provider} profile is not available`);
104
+ return options.resolveProfiles(profile, requireDependencies());
105
+ }
106
+ /** @internal */
107
+ async function resolveGitIdentity(profile: string): Promise<I> {
108
+ if (!profile) throw new Error(`A ${provider} profile is required to resolve Git identity`);
109
+ return integration().client(profile).resolveGitIdentity(profile);
110
+ }
111
+ /** @internal */
112
+ function preparationChecks(
113
+ _input: unknown,
114
+ { params }: ProcessLaunchConfig<P>,
115
+ ): LaunchPreparationCheck<P>[] {
116
+ return [
117
+ {
118
+ id: "repository_visibility",
119
+ label: "Check repository visibility",
120
+ async run({ signal }) {
121
+ signal.throwIfAborted();
122
+ const visible = (await repositories(options.profile(params))).some(
123
+ (candidate) => candidate.full_name === `${params.owner}/${params.repo}`,
124
+ );
125
+ signal.throwIfAborted();
126
+ if (!visible)
127
+ throw new SafeLaunchPreparationError(
128
+ "Repository is not visible",
129
+ `Grant the selected ${provider} profile access to the repository, then try again.`,
130
+ );
131
+ },
132
+ },
133
+ ...options.preparationChecks(params, requireDependencies),
134
+ ];
135
+ }
93
136
  function validationError(
94
137
  fieldId: string,
95
138
  message: string,
@@ -97,12 +140,20 @@ export function createRepositoryChangeUiLauncher<
97
140
  ): LauncherValidationError {
98
141
  return { code, fieldId, message };
99
142
  }
100
- return {
143
+ const launcher: ProcessLauncherDefinition<P> & {
144
+ /** @internal */
145
+ resolveIssueLaunchConfig(event: {
146
+ /** @internal */ profile: string;
147
+ /** @internal */ repository: R;
148
+ /** @internal */ issue: Pick<RepositoryIssue, "number" | "title" | "body" | "html_url">;
149
+ /** @internal */ labels: RepositoryIssueWatcherConfig["labels"];
150
+ }): Promise<ProcessLaunchConfig<P>>;
151
+ } = {
101
152
  async resolveIssueLaunchConfig({ profile, repository, issue, labels }) {
102
153
  const title = issue.title.trim();
103
154
  const body = issue.body?.trim() ?? "";
104
- const binding = options.resolveProfiles(profile);
105
- const identity = await options.resolveGitIdentity(profile);
155
+ const binding = resolveProfiles(profile);
156
+ const identity = await resolveGitIdentity(profile);
106
157
  return options.launchConfig(
107
158
  {
108
159
  ...options.params(repository, {
@@ -119,6 +170,7 @@ export function createRepositoryChangeUiLauncher<
119
170
  },
120
171
  title,
121
172
  identity,
173
+ repository,
122
174
  );
123
175
  },
124
176
  id: options.id,
@@ -134,6 +186,7 @@ export function createRepositoryChangeUiLauncher<
134
186
  id: `${providerId}_repo_change_form`,
135
187
  title: `${provider} Repo Change`,
136
188
  fields: [
189
+ ...repositoryChangeOptionFields,
137
190
  {
138
191
  id: profileField,
139
192
  label: `${provider} profile`,
@@ -159,22 +212,28 @@ export function createRepositoryChangeUiLauncher<
159
212
  submitLabel: "Start change",
160
213
  },
161
214
  resolveDefaults() {
162
- return { [profileField]: options.profiles()[0] ?? "", repository: "", prompt: "" };
215
+ return {
216
+ [profileField]: profiles()[0] ?? "",
217
+ repository: "",
218
+ prompt: "",
219
+ ...repositoryChangeOptions({}),
220
+ };
163
221
  },
164
222
  async resolveOptions(input) {
165
223
  const profile = trimString(input[profileField]);
166
224
  return {
167
- [profileField]: options.profiles().map((value) => ({ value, label: value })),
168
- repository: (await options.repositories(profile)).map((repository) => ({
225
+ [profileField]: profiles().map((value) => ({ value, label: value })),
226
+ repository: (await repositories(profile)).map((repository) => ({
169
227
  value: repository.full_name,
170
228
  label: repository.full_name,
171
229
  description: repository.html_url,
172
230
  })),
173
231
  };
174
232
  },
175
- preparationChecks: options.preparationChecks,
233
+ preparationChecks,
176
234
  resolveRelaunchInput(input) {
177
235
  return {
236
+ ...repositoryChangeOptions(input),
178
237
  [profileField]: trimString(input[profileField]),
179
238
  repository: trimString(input.repository),
180
239
  prompt: trimString(input.prompt),
@@ -189,16 +248,16 @@ export function createRepositoryChangeUiLauncher<
189
248
  ok: false as const,
190
249
  errors: [validationError(fieldId, message, "custom_rule")],
191
250
  });
192
- options.assertConfigured();
251
+ requireDependencies();
193
252
  if (!profile) errors.push(validationError(profileField, `${provider} profile is required`));
194
- else if (!options.profiles().includes(profile))
253
+ else if (!profiles().includes(profile))
195
254
  errors.push(
196
255
  validationError(profileField, `${provider} profile is not available`, "custom_rule"),
197
256
  );
198
257
  if (!repositoryName) errors.push(validationError("repository", "Repository is required"));
199
258
  if (!prompt) errors.push(validationError("prompt", "Requested change is required"));
200
259
  if (errors.length > 0) return { ok: false, errors };
201
- const repository = (await options.repositories(profile)).find(
260
+ const repository = (await repositories(profile)).find(
202
261
  (candidate) => candidate.full_name === repositoryName,
203
262
  );
204
263
  if (!repository)
@@ -208,18 +267,42 @@ export function createRepositoryChangeUiLauncher<
208
267
  );
209
268
  let binding: B;
210
269
  try {
211
- binding = options.resolveProfiles(profile);
270
+ binding = resolveProfiles(profile);
212
271
  } catch (error) {
213
272
  return invalid(profileField, (error as Error).message);
214
273
  }
215
- const identity = await options.resolveGitIdentity(profile);
274
+ const identity = await resolveGitIdentity(profile);
216
275
  const workBranch = buildAutoWorkBranchFromSeed(
217
276
  prompt,
218
277
  `${repository.ssh_url}:${repository.default_branch}`,
219
278
  );
220
- const params = options.params(repository, { ...binding, profile, prompt, workBranch });
221
- return { ok: true, launchConfig: options.launchConfig(params, prompt, identity) };
279
+ const params = {
280
+ ...options.params(repository, { ...binding, profile, prompt, workBranch }),
281
+ ...repositoryChangeOptions(input),
282
+ };
283
+ return {
284
+ ok: true,
285
+ launchConfig: options.launchConfig(params, prompt, identity, repository),
286
+ };
222
287
  },
223
288
  },
224
289
  };
290
+ return {
291
+ /** @internal */ configure(value: D | null) {
292
+ dependencies = value;
293
+ },
294
+ /** @internal */ preparationChecks,
295
+ /** @internal */ resolveProfiles,
296
+ /** @internal */ resolveGitIdentity,
297
+ /** @internal */ launcher,
298
+ /** @internal */ workflow: repositoryChangeWorkflow(async (params: P) => {
299
+ if (params.origin !== "issue") throw new Error(`Missing ${provider} source issue`);
300
+ const issue = await integration()
301
+ .client(options.profile(params))
302
+ .getIssue(params.owner, params.repo, params.issueNumber);
303
+ if (issue.html_url !== params.issueUrl)
304
+ throw new Error(`${provider} source issue installation changed`);
305
+ return issue.labels.map((label) => label.name);
306
+ }),
307
+ };
225
308
  }
@@ -0,0 +1,79 @@
1
+ import type { ScopedSettingsDeclaration, SettingDefinition } from "@leitwerk-dev/process-sdk";
2
+
3
+ /** @public */
4
+ export const codingPurposes = {
5
+ /** @public */
6
+ planning: "coding.planning",
7
+ /** @public */
8
+ implementation: "coding.implementation",
9
+ /** @public */
10
+ review: "coding.review",
11
+ } as const;
12
+
13
+ /** @internal */
14
+ export const commitMessageGitTimeout: SettingDefinition<number> = {
15
+ key: "coding.commit_message_git_timeout_ms",
16
+ schemaVersion: 1,
17
+ scopes: ["instance", "repository"],
18
+ merge: "replace",
19
+ defaultValue: 60_000,
20
+ schema: {
21
+ parse(value) {
22
+ if (
23
+ typeof value !== "number" ||
24
+ !Number.isSafeInteger(value) ||
25
+ value <= 0 ||
26
+ value > 2_147_483_647
27
+ ) {
28
+ throw new Error(
29
+ "Git timeout must be a positive integer of at most 2147483647 milliseconds",
30
+ );
31
+ }
32
+ return value;
33
+ },
34
+ },
35
+ form: {
36
+ label: "Commit-message Git timeout (milliseconds)",
37
+ group: "Implementation",
38
+ control: "number",
39
+ description: "Deadline per Git inspection command. Defaults to 60000 ms (60 seconds).",
40
+ },
41
+ };
42
+
43
+ function model(key: string, label: string, group: string): SettingDefinition<string | null> {
44
+ return {
45
+ key,
46
+ schemaVersion: 1,
47
+ scopes: ["instance", "repository"],
48
+ merge: "replace",
49
+ defaultValue: null,
50
+ schema: {
51
+ parse(value) {
52
+ if (value === null || (typeof value === "string" && value.length > 0)) return value;
53
+ throw new Error("Choose a model profile or inherit the runtime default");
54
+ },
55
+ },
56
+ form: {
57
+ label,
58
+ group,
59
+ control: "model",
60
+ description: "Used by future steps unless the process has an explicit model choice.",
61
+ },
62
+ };
63
+ }
64
+
65
+ /** @public */
66
+ export const codingSettings: ScopedSettingsDeclaration = {
67
+ settings: [
68
+ model("coding.planning_model", "Planning model", "Planning"),
69
+ model("coding.implementation_model", "Implementation model", "Implementation"),
70
+ model("coding.review_model", "Review model", "Review"),
71
+ commitMessageGitTimeout,
72
+ ],
73
+ purposes: Object.entries(codingPurposes).map(([name, id]) => ({
74
+ id,
75
+ label: name,
76
+ modelSettingKey: `coding.${name}_model`,
77
+ ...(name === "implementation" ? { settingKeys: [commitMessageGitTimeout.key] } : {}),
78
+ })),
79
+ };
@@ -0,0 +1,241 @@
1
+ import { spawn } from "node:child_process";
2
+ import { chmod, copyFile, mkdtemp, rm, stat, utimes } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import path from "node:path";
5
+ import type { ScopedSettingsSnapshot } from "@leitwerk-dev/domain";
6
+ import {
7
+ repositoryGitArgs,
8
+ sanitizeWorkerSubprocessEnv,
9
+ type TurnDiagnosticReport,
10
+ } from "@leitwerk-dev/process-sdk";
11
+ import { resolveGitBinary } from "@leitwerk-dev/process-sdk/git-binary";
12
+ import { commitMessageGitTimeout } from "../settings.js";
13
+ import { GitTrace2Collector } from "./git-inspection-profile.js";
14
+
15
+ interface GitOutput {
16
+ text: string;
17
+ truncated: boolean;
18
+ }
19
+
20
+ interface RepositoryChanges {
21
+ key: string;
22
+ path: string;
23
+ head: string;
24
+ status: GitOutput;
25
+ stagedDiff: GitOutput;
26
+ unstagedDiff: GitOutput;
27
+ untrackedFiles: GitOutput;
28
+ }
29
+
30
+ /** @internal */
31
+ export interface RepositoryCommitMessagePreparation {
32
+ /** @internal */
33
+ repositories: RepositoryChanges[];
34
+ }
35
+
36
+ // Preparation checkpoints have a 64 KiB limit. Leave room for checkpoint metadata.
37
+ const MAX_SNAPSHOT_BYTES = 60 * 1024;
38
+
39
+ interface GitInspectionContext {
40
+ key: string;
41
+ cwd: string;
42
+ timeoutMs: number;
43
+ indexFile?: string;
44
+ reportDiagnostic?: (report: TurnDiagnosticReport) => void;
45
+ }
46
+
47
+ function inspectionEnv(indexFile: string | undefined): NodeJS.ProcessEnv {
48
+ const env = sanitizeWorkerSubprocessEnv(process.env);
49
+ // Ambient index selection and trace destinations must not change this inspection
50
+ // or persist raw Trace2 events. Only fd 3 receives our temporary trace stream.
51
+ for (const key of Object.keys(env)) {
52
+ if (key.startsWith("GIT_TRACE") || key === "GIT_INDEX_FILE") delete env[key];
53
+ }
54
+ return {
55
+ ...env,
56
+ ...(indexFile ? { GIT_INDEX_FILE: indexFile } : {}),
57
+ GIT_OPTIONAL_LOCKS: indexFile ? "1" : "0",
58
+ GIT_TERMINAL_PROMPT: "0",
59
+ GIT_TRACE2: "0",
60
+ GIT_TRACE2_PERF: "0",
61
+ GIT_TRACE2_EVENT: "3",
62
+ };
63
+ }
64
+
65
+ async function readGit(
66
+ ctx: GitInspectionContext,
67
+ command: string,
68
+ args: string[],
69
+ ): Promise<GitOutput> {
70
+ const started = performance.now();
71
+ const trace = new GitTrace2Collector();
72
+ let exitCode: number | null = null;
73
+ let exitSignal: NodeJS.Signals | null = null;
74
+ let timedOut = false;
75
+ let succeeded = false;
76
+ let outputBytes = 0;
77
+ try {
78
+ const output = await new Promise<GitOutput>((resolve, reject) => {
79
+ const child = spawn(
80
+ resolveGitBinary(),
81
+ repositoryGitArgs([
82
+ ...(ctx.indexFile
83
+ ? ["-c", "core.splitIndex=false", "-c", "splitIndex.sharedIndexExpire=never"]
84
+ : ["--no-optional-locks"]),
85
+ "-c",
86
+ "core.fsmonitor=false",
87
+ ...args,
88
+ ]),
89
+ {
90
+ cwd: ctx.cwd,
91
+ env: inspectionEnv(ctx.indexFile),
92
+ stdio: ["ignore", "pipe", "ignore", "pipe"],
93
+ timeout: ctx.timeoutMs,
94
+ },
95
+ );
96
+ child.stdio[3]?.on("data", (chunk: Buffer) => trace.write(chunk));
97
+ const chunks: Buffer[] = [];
98
+ let bytes = 0;
99
+ let truncated = false;
100
+ child.stdout?.on("data", (chunk: Buffer) => {
101
+ outputBytes += chunk.length;
102
+ const remaining = MAX_SNAPSHOT_BYTES - bytes;
103
+ if (chunk.length > remaining) truncated = true;
104
+ const retained = chunk.subarray(0, remaining);
105
+ if (retained.length) chunks.push(retained);
106
+ bytes += retained.length;
107
+ });
108
+ child.once("error", reject);
109
+ child.once("close", (code, signal) => {
110
+ exitCode = code;
111
+ exitSignal = signal;
112
+ timedOut = child.killed;
113
+ if (code !== 0) {
114
+ if (timedOut) {
115
+ reject(
116
+ new Error(
117
+ `Cannot inspect '${ctx.key}': git ${args[0]} timed out after ${ctx.timeoutMs}ms`,
118
+ ),
119
+ );
120
+ return;
121
+ }
122
+ reject(
123
+ new Error(`Cannot inspect '${ctx.key}': git ${args[0]} failed (${signal ?? code})`),
124
+ );
125
+ return;
126
+ }
127
+ resolve({ text: Buffer.concat(chunks).toString("utf8"), truncated });
128
+ });
129
+ });
130
+ succeeded = true;
131
+ return output;
132
+ } finally {
133
+ const report: TurnDiagnosticReport = {
134
+ level: succeeded ? "info" : "warn",
135
+ code: "coding.git_inspection",
136
+ message: "Commit-message Git inspection command completed",
137
+ details: {
138
+ repository: ctx.key,
139
+ command,
140
+ durationMs: Math.round((performance.now() - started) * 1_000) / 1_000,
141
+ timeoutMs: ctx.timeoutMs,
142
+ outcome: succeeded ? "succeeded" : timedOut ? "timed_out" : "failed",
143
+ exitCode,
144
+ signal: exitSignal,
145
+ outputBytes,
146
+ trace2: trace.finish(),
147
+ },
148
+ };
149
+ // Diagnostics are best-effort and must not replace a Git result or failure.
150
+ try {
151
+ ctx.reportDiagnostic?.(report);
152
+ } catch {}
153
+ }
154
+ }
155
+
156
+ /** @internal */
157
+ export async function prepareRepositoryCommitMessageEvidence(ctx: {
158
+ projects: readonly { key: string }[];
159
+ repo: { get(key: string): { fsPath: string } };
160
+ scopedSettings?: ScopedSettingsSnapshot;
161
+ reportDiagnostic?: (report: TurnDiagnosticReport) => void;
162
+ }): Promise<RepositoryCommitMessagePreparation> {
163
+ const capturedTimeout = ctx.scopedSettings?.values.find(
164
+ ({ key }) => key === commitMessageGitTimeout.key,
165
+ );
166
+ const timeoutMs = commitMessageGitTimeout.schema.parse(
167
+ capturedTimeout ? capturedTimeout.value : commitMessageGitTimeout.defaultValue,
168
+ );
169
+ const repositories: RepositoryChanges[] = [];
170
+ for (const project of ctx.projects) {
171
+ const cwd = ctx.repo.get(project.key).fsPath;
172
+ const inspection = { key: project.key, cwd, timeoutMs, reportDiagnostic: ctx.reportDiagnostic };
173
+ const head = await readGit(inspection, "rev-parse.head", ["rev-parse", "HEAD"]);
174
+ const indexPath = await readGit(inspection, "rev-parse.index", [
175
+ "rev-parse",
176
+ "--path-format=absolute",
177
+ "--git-path",
178
+ "index",
179
+ ]);
180
+ if (indexPath.truncated)
181
+ throw new Error(`Cannot inspect '${project.key}': Git index path too long`);
182
+ const scratch = await mkdtemp(path.join(tmpdir(), "leitwerk-git-inspection-"));
183
+ try {
184
+ const indexFile = path.join(scratch, "index");
185
+ try {
186
+ const originalIndex = indexPath.text.replace(/\n$/, "");
187
+ const metadata = await stat(originalIndex);
188
+ await copyFile(originalIndex, indexFile);
189
+ await chmod(indexFile, 0o600);
190
+ // A newer copy timestamp could hide racy-clean entries. Millisecond
191
+ // rounding moves this timestamp earlier, conservatively retaining scans.
192
+ await utimes(indexFile, metadata.atime, metadata.mtime);
193
+ } catch (error) {
194
+ // An absent index is a valid checkout state. Git may create only the scratch copy.
195
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
196
+ }
197
+ // Status can persist refreshed stat data here. Later diffs reuse it without
198
+ // rehashing clean files or updating the checkout's staging state.
199
+ const git = (command: string, args: string[]) =>
200
+ readGit({ ...inspection, indexFile }, command, args);
201
+ const status = await git("status", ["status", "--porcelain=v1", "--untracked-files=all"]);
202
+ const diffOptions = ["--no-ext-diff", "--no-textconv", "--no-color"];
203
+ const stagedDiff = await git("diff.staged", ["diff", "--cached", ...diffOptions]);
204
+ const unstagedDiff = await git("diff.unstaged", ["diff", ...diffOptions]);
205
+ const untrackedFiles = await git("ls-files.untracked", [
206
+ "ls-files",
207
+ "--others",
208
+ "--exclude-standard",
209
+ ]);
210
+ repositories.push({
211
+ key: project.key,
212
+ path: cwd,
213
+ head: head.text.trim(),
214
+ status,
215
+ stagedDiff,
216
+ unstagedDiff,
217
+ untrackedFiles,
218
+ });
219
+ } finally {
220
+ await rm(scratch, { recursive: true, force: true });
221
+ }
222
+ }
223
+ const prepared = { repositories };
224
+ const outputs = repositories.flatMap((repo) => [
225
+ repo.status,
226
+ repo.stagedDiff,
227
+ repo.unstagedDiff,
228
+ repo.untrackedFiles,
229
+ ]);
230
+ while (Buffer.byteLength(JSON.stringify(prepared), "utf8") > MAX_SNAPSHOT_BYTES) {
231
+ const largest = outputs.reduce<GitOutput | undefined>(
232
+ (current, output) =>
233
+ !current || output.text.length > current.text.length ? output : current,
234
+ undefined,
235
+ );
236
+ if (!largest?.text.length) throw new Error("Repository identities exceed the evidence limit");
237
+ largest.text = largest.text.slice(0, Math.floor(largest.text.length / 2));
238
+ largest.truncated = true;
239
+ }
240
+ return prepared;
241
+ }