@aspruyt/xfg 7.2.1 → 7.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 (91) hide show
  1. package/PR.md +2 -0
  2. package/dist/ai/anthropic-client.d.ts +16 -0
  3. package/dist/ai/anthropic-client.js +35 -0
  4. package/dist/ai/change-describer.d.ts +16 -0
  5. package/dist/ai/change-describer.js +170 -0
  6. package/dist/ai/client-factory.d.ts +2 -0
  7. package/dist/ai/client-factory.js +33 -0
  8. package/dist/ai/http.d.ts +3 -0
  9. package/dist/ai/http.js +33 -0
  10. package/dist/ai/index.d.ts +5 -0
  11. package/dist/ai/index.js +4 -0
  12. package/dist/ai/openai-compatible-client.d.ts +16 -0
  13. package/dist/ai/openai-compatible-client.js +36 -0
  14. package/dist/ai/types.d.ts +22 -0
  15. package/dist/ai/types.js +1 -0
  16. package/dist/cli/program.d.ts +7 -0
  17. package/dist/cli/program.js +15 -11
  18. package/dist/cli/repo-sync-runner.js +1 -0
  19. package/dist/cli/secrets-command.js +1 -0
  20. package/dist/cli/settings-factories.d.ts +2 -1
  21. package/dist/cli/settings-factories.js +7 -1
  22. package/dist/cli/settings-report-builder.d.ts +6 -1
  23. package/dist/cli/settings-report-builder.js +15 -0
  24. package/dist/cli/settings-runner.js +12 -0
  25. package/dist/cli/sync-command.js +2 -0
  26. package/dist/cli/types.d.ts +5 -2
  27. package/dist/cli/unified-summary.d.ts +3 -1
  28. package/dist/cli/unified-summary.js +14 -26
  29. package/dist/config/index.d.ts +1 -1
  30. package/dist/config/index.js +0 -2
  31. package/dist/config/normalizer.js +49 -27
  32. package/dist/config/types.d.ts +30 -1
  33. package/dist/config/validator.js +11 -4
  34. package/dist/config/validators/ai-validator.d.ts +1 -0
  35. package/dist/config/validators/ai-validator.js +39 -0
  36. package/dist/config/validators/group-validator.js +3 -0
  37. package/dist/config/validators/repo-entry-validator.js +2 -0
  38. package/dist/config/validators/shared.js +33 -0
  39. package/dist/lifecycle/formatter.d.ts +0 -4
  40. package/dist/lifecycle/formatter.js +2 -6
  41. package/dist/lifecycle/github-lifecycle-provider.d.ts +1 -0
  42. package/dist/lifecycle/github-lifecycle-provider.js +30 -14
  43. package/dist/output/github-summary.d.ts +4 -3
  44. package/dist/output/github-summary.js +22 -5
  45. package/dist/output/lifecycle-report.d.ts +3 -2
  46. package/dist/output/lifecycle-report.js +20 -26
  47. package/dist/output/settings-report.d.ts +12 -2
  48. package/dist/output/settings-report.js +49 -47
  49. package/dist/output/summary-budget.d.ts +12 -0
  50. package/dist/output/summary-budget.js +125 -0
  51. package/dist/output/sync-report.d.ts +6 -3
  52. package/dist/output/sync-report.js +33 -34
  53. package/dist/settings/collaborators/diff.d.ts +17 -0
  54. package/dist/settings/collaborators/diff.js +64 -0
  55. package/dist/settings/collaborators/formatter.d.ts +14 -0
  56. package/dist/settings/collaborators/formatter.js +41 -0
  57. package/dist/settings/collaborators/github-collaborators-strategy.d.ts +18 -0
  58. package/dist/settings/collaborators/github-collaborators-strategy.js +43 -0
  59. package/dist/settings/collaborators/index.d.ts +4 -0
  60. package/dist/settings/collaborators/index.js +2 -0
  61. package/dist/settings/collaborators/processor.d.ts +21 -0
  62. package/dist/settings/collaborators/processor.js +77 -0
  63. package/dist/settings/collaborators/types.d.ts +19 -0
  64. package/dist/settings/collaborators/types.js +1 -0
  65. package/dist/settings/index.d.ts +1 -0
  66. package/dist/settings/index.js +1 -0
  67. package/dist/settings/labels/formatter.d.ts +0 -3
  68. package/dist/settings/labels/formatter.js +10 -17
  69. package/dist/settings/rulesets/formatter.d.ts +0 -6
  70. package/dist/settings/rulesets/formatter.js +4 -32
  71. package/dist/settings/secrets/formatter.js +4 -3
  72. package/dist/settings/variables/formatter.js +6 -5
  73. package/dist/shared/markdown-fence.d.ts +3 -0
  74. package/dist/shared/markdown-fence.js +32 -0
  75. package/dist/shared/string-utils.d.ts +1 -3
  76. package/dist/shared/string-utils.js +5 -4
  77. package/dist/sync/commit-push-manager.js +2 -2
  78. package/dist/sync/index.d.ts +1 -1
  79. package/dist/sync/pr-merge-handler.js +3 -1
  80. package/dist/sync/repository-processor.d.ts +5 -0
  81. package/dist/sync/repository-processor.js +4 -1
  82. package/dist/sync/sync-workflow.d.ts +4 -1
  83. package/dist/sync/sync-workflow.js +29 -2
  84. package/dist/sync/types.d.ts +14 -3
  85. package/dist/vcs/ado-pr-strategy.js +43 -1
  86. package/dist/vcs/git-commit-strategy.js +3 -5
  87. package/dist/vcs/graphql-commit-strategy.js +3 -6
  88. package/dist/vcs/pr-creator.d.ts +5 -10
  89. package/dist/vcs/pr-creator.js +34 -20
  90. package/dist/vcs/types.d.ts +1 -0
  91. package/package.json +4 -2
@@ -1,8 +1,6 @@
1
1
  import chalk from "chalk";
2
2
  import { countActions } from "../base-processor.js";
3
- /**
4
- * Format label changes as a Terraform-style plan.
5
- */
3
+ import { formatScalarValue, quoted } from "../../shared/string-utils.js";
6
4
  export function formatLabelsPlan(changes) {
7
5
  const lines = [];
8
6
  const entries = [];
@@ -16,15 +14,14 @@ export function formatLabelsPlan(changes) {
16
14
  for (const c of changes) {
17
15
  grouped[c.action].push(c);
18
16
  }
19
- // Format creates
20
17
  if (grouped.create.length > 0) {
21
18
  lines.push(chalk.bold(" Create:"));
22
19
  for (const change of grouped.create) {
23
- lines.push(chalk.green(` + label "${change.name}"`));
20
+ lines.push(chalk.green(` + label ${quoted(change.name)}`));
24
21
  if (change.desired) {
25
- lines.push(chalk.green(` color: "${change.desired.color}"`));
22
+ lines.push(chalk.green(` color: ${quoted(change.desired.color)}`));
26
23
  if (change.desired.description !== undefined) {
27
- lines.push(chalk.green(` description: "${change.desired.description}"`));
24
+ lines.push(chalk.green(` description: ${quoted(change.desired.description)}`));
28
25
  }
29
26
  }
30
27
  entries.push({
@@ -35,25 +32,24 @@ export function formatLabelsPlan(changes) {
35
32
  lines.push("");
36
33
  }
37
34
  }
38
- // Format updates
39
35
  if (grouped.update.length > 0) {
40
36
  lines.push(chalk.bold(" Update:"));
41
37
  for (const change of grouped.update) {
42
38
  if (change.newName) {
43
- lines.push(chalk.yellow(` ~ label "${change.name}" \u2192 "${change.newName}"`));
39
+ lines.push(chalk.yellow(` ~ label ${quoted(change.name)} \u2192 ${quoted(change.newName)}`));
44
40
  }
45
41
  else {
46
- lines.push(chalk.yellow(` ~ label "${change.name}"`));
42
+ lines.push(chalk.yellow(` ~ label ${quoted(change.name)}`));
47
43
  }
48
44
  if (change.propertyChanges) {
49
45
  for (const prop of change.propertyChanges) {
50
46
  if (prop.property === "new_name")
51
- continue; // shown in header
47
+ continue;
52
48
  if (prop.oldValue !== undefined) {
53
- lines.push(chalk.yellow(` ${prop.property}: "${prop.oldValue}" \u2192 "${prop.newValue}"`));
49
+ lines.push(chalk.yellow(` ${prop.property}: ${formatScalarValue(prop.oldValue)} \u2192 ${formatScalarValue(prop.newValue)}`));
54
50
  }
55
51
  else {
56
- lines.push(chalk.yellow(` ${prop.property}: "${prop.newValue}"`));
52
+ lines.push(chalk.yellow(` ${prop.property}: ${formatScalarValue(prop.newValue)}`));
57
53
  }
58
54
  }
59
55
  }
@@ -66,20 +62,17 @@ export function formatLabelsPlan(changes) {
66
62
  lines.push("");
67
63
  }
68
64
  }
69
- // Format deletes
70
65
  if (grouped.delete.length > 0) {
71
66
  lines.push(chalk.bold(" Delete:"));
72
67
  for (const change of grouped.delete) {
73
- lines.push(chalk.red(` - label "${change.name}"`));
68
+ lines.push(chalk.red(` - label ${quoted(change.name)}`));
74
69
  entries.push({ name: change.name, action: "delete" });
75
70
  }
76
71
  lines.push("");
77
72
  }
78
- // Unchanged (entries only, no output lines)
79
73
  for (const change of grouped.unchanged) {
80
74
  entries.push({ name: change.name, action: "unchanged" });
81
75
  }
82
- // Summary line
83
76
  const total = creates + updates + deletes;
84
77
  if (total > 0) {
85
78
  const parts = [];
@@ -21,11 +21,5 @@ export interface RulesetPlanResult {
21
21
  unchanged: number;
22
22
  entries: RulesetPlanEntry[];
23
23
  }
24
- /**
25
- * Format property diffs as an indented tree structure.
26
- */
27
24
  export declare function formatPropertyTree(diffs: PropertyDiff[]): string[];
28
- /**
29
- * Format ruleset changes as a Terraform-style plan.
30
- */
31
25
  export declare function formatRulesetPlan(changes: RulesetChange[]): RulesetPlanResult;
@@ -1,11 +1,8 @@
1
1
  import chalk from "chalk";
2
2
  import { projectToDesiredShape, normalizeRuleset, } from "./diff.js";
3
- import { formatScalarValue } from "../../shared/string-utils.js";
3
+ import { formatScalarValue, quoted } from "../../shared/string-utils.js";
4
4
  import { computePropertyDiffs, } from "./diff-algorithm.js";
5
5
  import { isPlainObject } from "../../shared/type-guards.js";
6
- /**
7
- * Build a tree structure from flat property diffs.
8
- */
9
6
  function buildTree(diffs) {
10
7
  const root = { name: "", children: new Map() };
11
8
  for (const diff of diffs) {
@@ -26,7 +23,6 @@ function buildTree(diffs) {
26
23
  child.newValue = diff.newValue;
27
24
  }
28
25
  else {
29
- // Intermediate node - mark as change if any child changes
30
26
  if (!child.action) {
31
27
  child.action = "change";
32
28
  }
@@ -36,9 +32,6 @@ function buildTree(diffs) {
36
32
  }
37
33
  return root;
38
34
  }
39
- /**
40
- * Format a value for inline display (scalars and simple arrays only).
41
- */
42
35
  function formatValue(val) {
43
36
  const scalar = formatScalarValue(val);
44
37
  if (scalar !== undefined)
@@ -56,9 +49,6 @@ function formatValue(val) {
56
49
  }
57
50
  return String(val);
58
51
  }
59
- /**
60
- * Render a nested value (object or array) as indented tree lines.
61
- */
62
52
  function renderNestedValue(val, action, indent) {
63
53
  const lines = [];
64
54
  const style = getActionStyle(action);
@@ -103,9 +93,6 @@ function renderNestedObject(obj, action, indent) {
103
93
  }
104
94
  return lines;
105
95
  }
106
- /**
107
- * Get the symbol and color for an action.
108
- */
109
96
  function getActionStyle(action) {
110
97
  switch (action) {
111
98
  case "add":
@@ -166,9 +153,6 @@ function renderLeafNode(child, style, indentStr, indent) {
166
153
  }
167
154
  return [renderSimpleLeaf(child, style, indentStr)];
168
155
  }
169
- /**
170
- * Recursively render tree nodes to formatted lines.
171
- */
172
156
  function renderTree(node, indent = 0) {
173
157
  const lines = [];
174
158
  const indentStr = " ".repeat(indent);
@@ -178,7 +162,6 @@ function renderTree(node, indent = 0) {
178
162
  : { symbol: " ", color: chalk.gray };
179
163
  const hasChildren = child.children.size > 0;
180
164
  if (hasChildren) {
181
- // Intermediate node
182
165
  lines.push(style.color(`${indentStr}${style.symbol} ${child.name}:`));
183
166
  lines.push(...renderTree(child, indent + 1));
184
167
  }
@@ -188,9 +171,6 @@ function renderTree(node, indent = 0) {
188
171
  }
189
172
  return lines;
190
173
  }
191
- /**
192
- * Format property diffs as an indented tree structure.
193
- */
194
174
  export function formatPropertyTree(diffs) {
195
175
  if (diffs.length === 0) {
196
176
  return [];
@@ -198,22 +178,14 @@ export function formatPropertyTree(diffs) {
198
178
  const tree = buildTree(diffs);
199
179
  return renderTree(tree);
200
180
  }
201
- /**
202
- * Format a full ruleset config as tree lines (for create action).
203
- * Delegates to renderNestedObject which handles recursive rendering.
204
- */
205
181
  function formatFullConfig(ruleset, indent = 2) {
206
182
  // Object.entries works on any object; the cast avoids a double assertion
207
183
  const entries = Object.entries(ruleset);
208
184
  return renderNestedObject(Object.fromEntries(entries), "add", indent);
209
185
  }
210
- /**
211
- * Format ruleset changes as a Terraform-style plan.
212
- */
213
186
  export function formatRulesetPlan(changes) {
214
187
  const lines = [];
215
188
  const entries = [];
216
- // Group by action in a single pass
217
189
  const grouped = {
218
190
  create: [],
219
191
  update: [],
@@ -227,7 +199,7 @@ export function formatRulesetPlan(changes) {
227
199
  lines.push(chalk.bold(" Create:"));
228
200
  }
229
201
  for (const change of grouped.create) {
230
- lines.push(chalk.green(` + ruleset "${change.name}"`));
202
+ lines.push(chalk.green(` + ruleset ${quoted(change.name)}`));
231
203
  if (change.desired) {
232
204
  lines.push(...formatFullConfig(change.desired, 2));
233
205
  }
@@ -246,7 +218,7 @@ export function formatRulesetPlan(changes) {
246
218
  lines.push(chalk.bold(" Update:"));
247
219
  }
248
220
  for (const change of grouped.update) {
249
- lines.push(chalk.yellow(` ~ ruleset "${change.name}"`));
221
+ lines.push(chalk.yellow(` ~ ruleset ${quoted(change.name)}`));
250
222
  if (change.current && change.desired) {
251
223
  const currentNorm = normalizeRuleset(change.current);
252
224
  const desiredNorm = normalizeRuleset(change.desired);
@@ -274,7 +246,7 @@ export function formatRulesetPlan(changes) {
274
246
  if (grouped.delete.length > 0) {
275
247
  lines.push(chalk.bold(" Delete:"));
276
248
  for (const change of grouped.delete) {
277
- lines.push(chalk.red(` - ruleset "${change.name}"`));
249
+ lines.push(chalk.red(` - ruleset ${quoted(change.name)}`));
278
250
  entries.push({ name: change.name, action: "delete" });
279
251
  }
280
252
  lines.push("");
@@ -1,4 +1,5 @@
1
1
  import chalk from "chalk";
2
+ import { quoted } from "../../shared/string-utils.js";
2
3
  import { countActions, isActiveAction, } from "../base-processor.js";
3
4
  import { formatActionCountEntry } from "../../shared/count-format.js";
4
5
  const ACTION_ORDER = {
@@ -10,11 +11,11 @@ const ACTION_ORDER = {
10
11
  function formatEntry(entry) {
11
12
  switch (entry.action) {
12
13
  case "create":
13
- return chalk.green(` + secret "${entry.name}"`);
14
+ return chalk.green(` + secret ${quoted(entry.name)}`);
14
15
  case "update":
15
- return chalk.yellow(` ~ secret "${entry.name}" (update, value write-only)`);
16
+ return chalk.yellow(` ~ secret ${quoted(entry.name)} (update, value write-only)`);
16
17
  case "delete":
17
- return chalk.red(` - secret "${entry.name}"`);
18
+ return chalk.red(` - secret ${quoted(entry.name)}`);
18
19
  }
19
20
  }
20
21
  export function formatSecretsPlan(changes, dryRun) {
@@ -1,4 +1,5 @@
1
1
  import chalk from "chalk";
2
+ import { quoted } from "../../shared/string-utils.js";
2
3
  import { countActions } from "../base-processor.js";
3
4
  export function formatVariablesPlan(changes) {
4
5
  const lines = [];
@@ -16,9 +17,9 @@ export function formatVariablesPlan(changes) {
16
17
  if (grouped.create.length > 0) {
17
18
  lines.push(chalk.bold(" Create:"));
18
19
  for (const change of grouped.create) {
19
- lines.push(chalk.green(` + variable "${change.name}"`));
20
+ lines.push(chalk.green(` + variable ${quoted(change.name)}`));
20
21
  if (change.newValue !== undefined) {
21
- lines.push(chalk.green(` value: "${change.newValue}"`));
22
+ lines.push(chalk.green(` value: ${quoted(change.newValue)}`));
22
23
  }
23
24
  entries.push({
24
25
  name: change.name,
@@ -31,9 +32,9 @@ export function formatVariablesPlan(changes) {
31
32
  if (grouped.update.length > 0) {
32
33
  lines.push(chalk.bold(" Update:"));
33
34
  for (const change of grouped.update) {
34
- lines.push(chalk.yellow(` ~ variable "${change.name}"`));
35
+ lines.push(chalk.yellow(` ~ variable ${quoted(change.name)}`));
35
36
  if (change.oldValue !== undefined && change.newValue !== undefined) {
36
- lines.push(chalk.yellow(` value: "${change.oldValue}" → "${change.newValue}"`));
37
+ lines.push(chalk.yellow(` value: ${quoted(change.oldValue)} → ${quoted(change.newValue)}`));
37
38
  }
38
39
  entries.push({
39
40
  name: change.name,
@@ -47,7 +48,7 @@ export function formatVariablesPlan(changes) {
47
48
  if (grouped.delete.length > 0) {
48
49
  lines.push(chalk.bold(" Delete:"));
49
50
  for (const change of grouped.delete) {
50
- lines.push(chalk.red(` - variable "${change.name}"`));
51
+ lines.push(chalk.red(` - variable ${quoted(change.name)}`));
51
52
  entries.push({ name: change.name, action: "delete" });
52
53
  }
53
54
  lines.push("");
@@ -0,0 +1,3 @@
1
+ export declare function diffFence(diffLines: string[]): string;
2
+ export declare function appendDiffBlock(lines: string[], diffLines: string[]): void;
3
+ export declare function inlineCode(text: string): string;
@@ -0,0 +1,32 @@
1
+ function longestBacktickRun(text) {
2
+ let longest = 0;
3
+ for (const run of text.match(/`+/g) ?? []) {
4
+ longest = Math.max(longest, run.length);
5
+ }
6
+ return longest;
7
+ }
8
+ // Fences must outrun any backtick run inside, or content like ``` closes them early.
9
+ export function diffFence(diffLines) {
10
+ let longest = 0;
11
+ for (const line of diffLines) {
12
+ longest = Math.max(longest, longestBacktickRun(line));
13
+ }
14
+ return "`".repeat(Math.max(3, longest + 1));
15
+ }
16
+ export function appendDiffBlock(lines, diffLines) {
17
+ if (diffLines.length === 0)
18
+ return;
19
+ const fence = diffFence(diffLines);
20
+ lines.push(`${fence}diff`);
21
+ // Loop, not push(...diffLines) - spreading huge diffs overflows the call stack.
22
+ for (const line of diffLines)
23
+ lines.push(line);
24
+ lines.push(fence, "");
25
+ }
26
+ export function inlineCode(text) {
27
+ const fence = "`".repeat(longestBacktickRun(text) + 1);
28
+ // CommonMark strips one space from each end when both ends are spaces.
29
+ const bothSpaces = /^ .* $/s.test(text) && text.trim() !== "";
30
+ const pad = text.startsWith("`") || text.endsWith("`") || bothSpaces ? " " : "";
31
+ return `${fence}${pad}${text}${pad}${fence}`;
32
+ }
@@ -1,7 +1,5 @@
1
- /**
2
- * Convert a camelCase string to snake_case.
3
- */
4
1
  export declare function camelToSnake(str: string): string;
2
+ export declare function quoted(text: string): string;
5
3
  /**
6
4
  * Format a scalar value for display: null, undefined, string, boolean.
7
5
  * Returns undefined for non-scalar types (arrays, objects) so callers
@@ -1,9 +1,10 @@
1
- /**
2
- * Convert a camelCase string to snake_case.
3
- */
4
1
  export function camelToSnake(str) {
5
2
  return str.replace(/([A-Z])/g, "_$1").toLowerCase();
6
3
  }
4
+ // Escapes only line breaks: JSON-style escaping would double user-written backslashes (^feat\( -> ^feat\\().
5
+ export function quoted(text) {
6
+ return `"${text.replace(/\r/g, "\\r").replace(/\n/g, "\\n")}"`;
7
+ }
7
8
  /**
8
9
  * Format a scalar value for display: null, undefined, string, boolean.
9
10
  * Returns undefined for non-scalar types (arrays, objects) so callers
@@ -15,7 +16,7 @@ export function formatScalarValue(val) {
15
16
  if (val === undefined)
16
17
  return "undefined";
17
18
  if (typeof val === "string")
18
- return `"${val}"`;
19
+ return quoted(val);
19
20
  if (typeof val === "boolean")
20
21
  return val ? "true" : "false";
21
22
  return undefined;
@@ -13,7 +13,7 @@ export class CommitPushManager {
13
13
  const { repoInfo, gitOps, workDir, fileChanges, commitMessage, pushBranch, isDirectMode, dryRun, retries, token, executor, } = options;
14
14
  if (dryRun) {
15
15
  this.log.debug("Staging changes...");
16
- this.log.info(`Would commit: ${commitMessage}`);
16
+ this.log.info(`Would commit: ${(await commitMessage()).message}`);
17
17
  this.log.info(`Would push to ${pushBranch}`);
18
18
  return { success: true };
19
19
  }
@@ -38,7 +38,7 @@ export class CommitPushManager {
38
38
  repoInfo,
39
39
  branchName: pushBranch,
40
40
  baseBranch: options.baseBranch,
41
- message: commitMessage,
41
+ ...(await commitMessage()),
42
42
  fileChanges: changes,
43
43
  workDir,
44
44
  retries,
@@ -1,2 +1,2 @@
1
- export type { FileChangeDetail, GitOpsFactory, IAuthOptionsBuilder, IBranchManager, ICommitPushManager, IFileSyncOrchestrator, IPRMergeHandler, IRepositoryProcessor, IRepositorySession, IWorkStrategy, ProcessorResult, SessionContext, WorkResult, } from "./types.js";
1
+ export type { CommitMessage, FileChangeDetail, GitOpsFactory, IAuthOptionsBuilder, IBranchManager, ICommitPushManager, IFileSyncOrchestrator, IPRMergeHandler, IRepositoryProcessor, IRepositorySession, IWorkStrategy, ProcessorOptions, ProcessorResult, CreateAndMergeInput, SessionContext, WorkResult, } from "./types.js";
2
2
  export { RepositoryProcessor } from "./repository-processor.js";
@@ -5,7 +5,7 @@ export class PRMergeHandler {
5
5
  this.log = log;
6
6
  }
7
7
  async createAndMerge(input) {
8
- const { repoInfo, prOptions, options, changedFiles, repoName, diffStats, fileChanges, } = input;
8
+ const { repoInfo, prOptions, options, changedFiles, repoName, diffStats, fileChanges, prTitle, prSummary, } = input;
9
9
  this.log.info("Creating pull request...");
10
10
  const strategy = options.dryRun
11
11
  ? undefined
@@ -24,6 +24,8 @@ export class PRMergeHandler {
24
24
  labels: prOptions?.labels,
25
25
  log: this.log,
26
26
  strategy,
27
+ title: prTitle,
28
+ aiSummary: prSummary,
27
29
  });
28
30
  const mergeMode = prOptions?.merge ?? "auto";
29
31
  let mergeResult;
@@ -2,6 +2,7 @@ import type { RepoConfig } from "../config/index.js";
2
2
  import type { RepoInfo } from "../repo/index.js";
3
3
  import type { ILogger } from "../shared/logger.js";
4
4
  import { type GitHubAppTokenManager } from "../vcs/index.js";
5
+ import { type FetchFn, type IChangeDescriber } from "../ai/index.js";
5
6
  import type { IFileWriter, IManifestManager, IBranchManager, IAuthOptionsBuilder, IRepositorySession, ICommitPushManager, IFileSyncOrchestrator, IPRMergeHandler, ISyncWorkflow, IRepositoryProcessor, GitOpsFactory, ProcessorOptions, ProcessorResult } from "./types.js";
6
7
  /**
7
8
  * Thin facade that delegates to SyncWorkflow with FileSyncStrategy.
@@ -19,8 +20,12 @@ export declare class RepositoryProcessor implements IRepositoryProcessor {
19
20
  fileSyncOrchestrator?: IFileSyncOrchestrator;
20
21
  prMergeHandler?: IPRMergeHandler;
21
22
  syncWorkflow?: ISyncWorkflow;
23
+ changeDescriber?: IChangeDescriber;
22
24
  tokenManager?: GitHubAppTokenManager | null;
23
25
  envToken?: string;
26
+ /** Environment the AI client reads API keys from */
27
+ aiEnv?: Record<string, string | undefined>;
28
+ fetch?: FetchFn;
24
29
  });
25
30
  process(repoConfig: RepoConfig, repoInfo: RepoInfo, options: ProcessorOptions): Promise<ProcessorResult>;
26
31
  }
@@ -9,6 +9,7 @@ import { FileSyncOrchestrator } from "./file-sync-orchestrator.js";
9
9
  import { PRMergeHandler } from "./pr-merge-handler.js";
10
10
  import { FileSyncStrategy } from "./file-sync-strategy.js";
11
11
  import { SyncWorkflow } from "./sync-workflow.js";
12
+ import { AiChangeDescriber, createAiClient, } from "../ai/index.js";
12
13
  /**
13
14
  * Thin facade that delegates to SyncWorkflow with FileSyncStrategy.
14
15
  */
@@ -37,12 +38,14 @@ export class RepositoryProcessor {
37
38
  const repositorySession = components?.repositorySession ?? new RepositorySession(factory, log);
38
39
  const commitPushManager = components?.commitPushManager ?? new CommitPushManager(log);
39
40
  const prMergeHandler = components?.prMergeHandler ?? new PRMergeHandler(log);
41
+ const changeDescriber = components?.changeDescriber ??
42
+ new AiChangeDescriber((opts) => createAiClient(opts, components?.aiEnv ?? {}, components?.fetch ?? globalThis.fetch), log);
40
43
  this.fileSyncOrchestrator =
41
44
  components?.fileSyncOrchestrator ??
42
45
  new FileSyncOrchestrator(fileWriter, manifestManager, log);
43
46
  this.syncWorkflow =
44
47
  components?.syncWorkflow ??
45
- new SyncWorkflow(authOptionsBuilder, repositorySession, branchManager, commitPushManager, prMergeHandler, log);
48
+ new SyncWorkflow(authOptionsBuilder, repositorySession, branchManager, commitPushManager, prMergeHandler, changeDescriber, log);
46
49
  }
47
50
  async process(repoConfig, repoInfo, options) {
48
51
  const strategy = new FileSyncStrategy(this.fileSyncOrchestrator);
@@ -1,6 +1,7 @@
1
1
  import type { RepoConfig } from "../config/index.js";
2
2
  import { type RepoInfo } from "../repo/index.js";
3
3
  import type { DebugInfoLog } from "../shared/logger.js";
4
+ import type { IChangeDescriber } from "../ai/index.js";
4
5
  import type { ISyncWorkflow, IWorkStrategy, IAuthOptionsBuilder, IRepositorySession, IBranchManager, ICommitPushManager, IPRMergeHandler, ProcessorOptions, ProcessorResult } from "./types.js";
5
6
  /**
6
7
  * Orchestrates the common sync workflow steps.
@@ -12,7 +13,9 @@ export declare class SyncWorkflow implements ISyncWorkflow {
12
13
  private readonly branchManager;
13
14
  private readonly commitPushManager;
14
15
  private readonly prMergeHandler;
16
+ private readonly changeDescriber;
15
17
  private readonly log;
16
- constructor(authOptionsBuilder: IAuthOptionsBuilder, repositorySession: IRepositorySession, branchManager: IBranchManager, commitPushManager: ICommitPushManager, prMergeHandler: IPRMergeHandler, log: DebugInfoLog);
18
+ constructor(authOptionsBuilder: IAuthOptionsBuilder, repositorySession: IRepositorySession, branchManager: IBranchManager, commitPushManager: ICommitPushManager, prMergeHandler: IPRMergeHandler, changeDescriber: IChangeDescriber, log: DebugInfoLog);
17
19
  execute(repoConfig: RepoConfig, repoInfo: RepoInfo, options: ProcessorOptions, workStrategy: IWorkStrategy): Promise<ProcessorResult>;
20
+ private describeChanges;
18
21
  }
@@ -10,13 +10,15 @@ export class SyncWorkflow {
10
10
  branchManager;
11
11
  commitPushManager;
12
12
  prMergeHandler;
13
+ changeDescriber;
13
14
  log;
14
- constructor(authOptionsBuilder, repositorySession, branchManager, commitPushManager, prMergeHandler, log) {
15
+ constructor(authOptionsBuilder, repositorySession, branchManager, commitPushManager, prMergeHandler, changeDescriber, log) {
15
16
  this.authOptionsBuilder = authOptionsBuilder;
16
17
  this.repositorySession = repositorySession;
17
18
  this.branchManager = branchManager;
18
19
  this.commitPushManager = commitPushManager;
19
20
  this.prMergeHandler = prMergeHandler;
21
+ this.changeDescriber = changeDescriber;
20
22
  this.log = log;
21
23
  }
22
24
  async execute(repoConfig, repoInfo, options, workStrategy) {
@@ -61,13 +63,21 @@ export class SyncWorkflow {
61
63
  skipped: true,
62
64
  };
63
65
  }
66
+ let description;
67
+ const commitMessage = async () => {
68
+ description = await this.describeChanges(repoConfig, options, runCtx, workResult);
69
+ if (!description)
70
+ return { message: workResult.commitMessage };
71
+ const { subject, body } = description;
72
+ return body ? { message: subject, body } : { message: subject };
73
+ };
64
74
  const pushBranch = isDirectMode ? session.baseBranch : branchName;
65
75
  const commitResult = await this.commitPushManager.commitAndPush({
66
76
  ...runCtx,
67
77
  repoInfo,
68
78
  gitOps: session.gitOps,
69
79
  fileChanges: workResult.fileChanges,
70
- commitMessage: workResult.commitMessage,
80
+ commitMessage,
71
81
  pushBranch,
72
82
  baseBranch: session.baseBranch,
73
83
  isDirectMode,
@@ -109,6 +119,8 @@ export class SyncWorkflow {
109
119
  repoName,
110
120
  diffStats: workResult.diffStats,
111
121
  fileChanges: workResult.fileChangeDetails,
122
+ prTitle: description?.subject,
123
+ prSummary: description?.prSummary,
112
124
  });
113
125
  }
114
126
  finally {
@@ -118,4 +130,19 @@ export class SyncWorkflow {
118
130
  }
119
131
  }
120
132
  }
133
+ async describeChanges(repoConfig, options, runCtx, workResult) {
134
+ const aiOptions = repoConfig.prOptions?.ai;
135
+ if (!aiOptions || options.noAi)
136
+ return null;
137
+ if (runCtx.dryRun) {
138
+ this.log.info(`Would generate AI commit message (${aiOptions.provider})`);
139
+ return null;
140
+ }
141
+ this.log.info("Generating AI commit message...");
142
+ return this.changeDescriber.describe({
143
+ files: workResult.fileChangeDetails,
144
+ options: aiOptions,
145
+ retries: runCtx.retries,
146
+ });
147
+ }
121
148
  }
@@ -1,4 +1,4 @@
1
- import type { FileContent, RepoConfig, PRMergeOptions } from "../config/index.js";
1
+ import type { FileContent, RepoConfig, RepoPROptions } from "../config/index.js";
2
2
  import type { RepoInfo } from "../repo/index.js";
3
3
  import type { ActiveAction } from "../settings/index.js";
4
4
  import type { ILocalGitOps, IGitOps, GitAuthOptions, GitOpsOptions, FileAction, FileActionKind } from "../vcs/index.js";
@@ -101,11 +101,16 @@ export interface SessionContext {
101
101
  export interface IRepositorySession {
102
102
  setup(repoInfo: RepoInfo, options: SessionOptions): Promise<SessionContext>;
103
103
  }
104
+ export interface CommitMessage {
105
+ message: string;
106
+ body?: string;
107
+ }
104
108
  export interface CommitPushOptions extends RunContext {
105
109
  repoInfo: RepoInfo;
106
110
  gitOps: IGitOps;
107
111
  fileChanges: Map<string, FileWriteResult>;
108
- commitMessage: string;
112
+ /** Called only once there is something to commit */
113
+ commitMessage: () => Promise<CommitMessage>;
109
114
  pushBranch: string;
110
115
  baseBranch: string;
111
116
  isDirectMode: boolean;
@@ -137,6 +142,8 @@ export interface ProcessorOptions {
137
142
  token?: string;
138
143
  /** True when using GraphQL commit strategy (GitHub App) */
139
144
  hasAppCredentials?: boolean;
145
+ /** Disables prOptions.ai for this run */
146
+ noAi?: boolean;
140
147
  }
141
148
  export interface FileChangeDetail {
142
149
  path: string;
@@ -176,12 +183,16 @@ export interface PRHandlerOptions extends RunContext {
176
183
  }
177
184
  export interface CreateAndMergeInput {
178
185
  repoInfo: RepoInfo;
179
- prOptions?: PRMergeOptions;
186
+ prOptions?: RepoPROptions;
180
187
  options: PRHandlerOptions;
181
188
  changedFiles: FileAction[];
182
189
  repoName: string;
183
190
  diffStats?: DiffStats;
184
191
  fileChanges?: FileChangeDetail[];
192
+ /** AI-generated PR title; falls back to the default title when unset */
193
+ prTitle?: string;
194
+ /** AI-generated summary for the PR body */
195
+ prSummary?: string;
185
196
  }
186
197
  export interface IPRMergeHandler {
187
198
  createAndMerge(input: CreateAndMergeInput): Promise<ProcessorResult>;
@@ -9,6 +9,47 @@ import { safeCleanup } from "../shared/cleanup-utils.js";
9
9
  import { NO_OP_DEBUG_LOG } from "../shared/logger.js";
10
10
  import { sanitizeCredentials } from "../shared/sanitize-utils.js";
11
11
  import { getStderr } from "../shared/command-executor.js";
12
+ const MAX_DESCRIPTION_CHARS = 4000;
13
+ const TRUNCATION_NOTE = "\n\n_(description truncated)_\n\n";
14
+ const FENCE = "```";
15
+ const FENCE_LINE = /^```/gm;
16
+ function isInsideFence(text) {
17
+ return (text.match(FENCE_LINE) ?? []).length % 2 === 1;
18
+ }
19
+ function isHighSurrogate(code) {
20
+ return code >= 0xd800 && code <= 0xdbff;
21
+ }
22
+ function headOf(body, budget) {
23
+ const lineEnd = body.lastIndexOf("\n", budget);
24
+ if (lineEnd > 0)
25
+ return body.slice(0, lineEnd);
26
+ const end = isHighSurrogate(body.charCodeAt(budget - 1))
27
+ ? budget - 1
28
+ : budget;
29
+ return body.slice(0, end);
30
+ }
31
+ function tailStartOf(body, budget) {
32
+ const start = body.length - budget;
33
+ const lineStart = body.indexOf("\n", start - 1) + 1;
34
+ if (lineStart > 0)
35
+ return lineStart;
36
+ return isHighSurrogate(body.charCodeAt(start - 1)) ? start + 1 : start;
37
+ }
38
+ // Azure DevOps rejects PR descriptions over 4000 characters.
39
+ // Cuts the middle: the head has the file list, the tail has the appended AI summary.
40
+ function fitDescription(body) {
41
+ if (body.length <= MAX_DESCRIPTION_CHARS)
42
+ return body;
43
+ const fenceRoom = 2 * (FENCE.length + 1);
44
+ const room = MAX_DESCRIPTION_CHARS - TRUNCATION_NOTE.length - fenceRoom;
45
+ const head = headOf(body, Math.ceil(room / 2));
46
+ const tailStart = tailStartOf(body, Math.floor(room / 2));
47
+ return (head +
48
+ (isInsideFence(head) ? `\n${FENCE}` : "") +
49
+ TRUNCATION_NOTE +
50
+ (isInsideFence(body.slice(0, tailStart)) ? `${FENCE}\n` : "") +
51
+ body.slice(tailStart));
52
+ }
12
53
  export class AdoPRStrategy extends BasePRStrategy {
13
54
  bodyFilePath = ".pr-description.md";
14
55
  getOrgUrl(repoInfo) {
@@ -141,7 +182,8 @@ export class AdoPRStrategy extends BasePRStrategy {
141
182
  return { status: "closed" };
142
183
  }
143
184
  async create(options) {
144
- const { repoInfo, title, body, branchName, baseBranch, workDir, retries = 3, } = options;
185
+ const { repoInfo, title, branchName, baseBranch, workDir, retries = 3, } = options;
186
+ const body = fitDescription(options.body);
145
187
  assertAzureDevOpsRepo(repoInfo, "Azure PR strategy");
146
188
  const azureRepoInfo = repoInfo;
147
189
  const orgUrl = this.getOrgUrl(azureRepoInfo);
@@ -16,11 +16,9 @@ export class GitCommitStrategy {
16
16
  * @returns Commit result with SHA and verified: false (no signature)
17
17
  */
18
18
  async commit(options) {
19
- const { branchName, message, workDir, retries = 3, force = true, gitOps, } = options;
20
- // Commit with the message (--no-verify to skip pre-commit hooks)
21
- // Staging is handled by CommitPushManager before calling commit()
22
- await this.executor.exec("git", ["commit", "--no-verify", "-m", message], workDir);
23
- // Push with authentication via gitOps if available
19
+ const { branchName, message, body, workDir, retries = 3, force = true, gitOps, } = options;
20
+ // Staging is done by CommitPushManager before commit() is called.
21
+ await this.executor.exec("git", ["commit", "--no-verify", "-m", message, ...(body ? ["-m", body] : [])], workDir);
24
22
  if (gitOps) {
25
23
  await gitOps.push(branchName, { force });
26
24
  }