@aspruyt/xfg 7.2.1 → 7.3.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 (69) 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/sync-command.js +2 -0
  21. package/dist/cli/types.d.ts +1 -0
  22. package/dist/cli/unified-summary.d.ts +3 -1
  23. package/dist/cli/unified-summary.js +14 -26
  24. package/dist/config/index.d.ts +1 -1
  25. package/dist/config/index.js +0 -2
  26. package/dist/config/normalizer.js +17 -24
  27. package/dist/config/types.d.ts +17 -1
  28. package/dist/config/validator.js +2 -4
  29. package/dist/config/validators/ai-validator.d.ts +1 -0
  30. package/dist/config/validators/ai-validator.js +39 -0
  31. package/dist/config/validators/group-validator.js +3 -0
  32. package/dist/config/validators/repo-entry-validator.js +2 -0
  33. package/dist/lifecycle/formatter.d.ts +0 -4
  34. package/dist/lifecycle/formatter.js +2 -6
  35. package/dist/output/github-summary.d.ts +4 -3
  36. package/dist/output/github-summary.js +22 -5
  37. package/dist/output/lifecycle-report.d.ts +3 -2
  38. package/dist/output/lifecycle-report.js +20 -26
  39. package/dist/output/settings-report.d.ts +3 -2
  40. package/dist/output/settings-report.js +36 -47
  41. package/dist/output/summary-budget.d.ts +12 -0
  42. package/dist/output/summary-budget.js +125 -0
  43. package/dist/output/sync-report.d.ts +6 -3
  44. package/dist/output/sync-report.js +33 -34
  45. package/dist/settings/labels/formatter.d.ts +0 -3
  46. package/dist/settings/labels/formatter.js +10 -17
  47. package/dist/settings/rulesets/formatter.d.ts +0 -6
  48. package/dist/settings/rulesets/formatter.js +4 -32
  49. package/dist/settings/secrets/formatter.js +4 -3
  50. package/dist/settings/variables/formatter.js +6 -5
  51. package/dist/shared/markdown-fence.d.ts +3 -0
  52. package/dist/shared/markdown-fence.js +32 -0
  53. package/dist/shared/string-utils.d.ts +1 -3
  54. package/dist/shared/string-utils.js +5 -4
  55. package/dist/sync/commit-push-manager.js +2 -2
  56. package/dist/sync/index.d.ts +1 -1
  57. package/dist/sync/pr-merge-handler.js +3 -1
  58. package/dist/sync/repository-processor.d.ts +5 -0
  59. package/dist/sync/repository-processor.js +4 -1
  60. package/dist/sync/sync-workflow.d.ts +4 -1
  61. package/dist/sync/sync-workflow.js +29 -2
  62. package/dist/sync/types.d.ts +14 -3
  63. package/dist/vcs/ado-pr-strategy.js +43 -1
  64. package/dist/vcs/git-commit-strategy.js +3 -5
  65. package/dist/vcs/graphql-commit-strategy.js +3 -6
  66. package/dist/vcs/pr-creator.d.ts +5 -10
  67. package/dist/vcs/pr-creator.js +34 -20
  68. package/dist/vcs/types.d.ts +1 -0
  69. package/package.json +3 -2
@@ -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
  }
@@ -73,7 +73,7 @@ export class GraphQLCommitStrategy {
73
73
  * @throws GraphQLApiError if the API call fails
74
74
  */
75
75
  async commit(options) {
76
- const { repoInfo, branchName, message, fileChanges, workDir, retries = 3, token, } = options;
76
+ const { repoInfo, branchName, message, body, fileChanges, workDir, retries = 3, token, } = options;
77
77
  if (!isGitHubRepo(repoInfo)) {
78
78
  throw new ValidationError(`GraphQL commit strategy requires GitHub repositories. Got: ${repoInfo.type}`);
79
79
  }
@@ -108,7 +108,7 @@ export class GraphQLCommitStrategy {
108
108
  }
109
109
  await gitOps.fetchBranch(branchName);
110
110
  const headSha = await this.executor.exec("git", ["rev-parse", `origin/${branchName}`], workDir);
111
- const result = await this.executeGraphQLMutation(repoInfo, branchName, message, headSha.trim(), additions, deletions, workDir, token);
111
+ const result = await this.executeGraphQLMutation(repoInfo, branchName, { headline: message, ...(body ? { body } : {}) }, headSha.trim(), additions, deletions, workDir, token);
112
112
  return result;
113
113
  }
114
114
  catch (error) {
@@ -150,9 +150,7 @@ export class GraphQLCommitStrategy {
150
150
  branchName,
151
151
  },
152
152
  expectedHeadOid,
153
- message: {
154
- headline: message,
155
- },
153
+ message,
156
154
  fileChanges,
157
155
  },
158
156
  };
@@ -236,7 +234,6 @@ export class GraphQLCommitStrategy {
236
234
  const originalMessage = toErrorMessage(error);
237
235
  let cleanMessage;
238
236
  if (originalMessage.startsWith("Command failed:")) {
239
- // Extract stderr: everything after the first newline
240
237
  const newlineIndex = originalMessage.indexOf("\n");
241
238
  cleanMessage =
242
239
  newlineIndex >= 0
@@ -12,18 +12,17 @@ interface PROptions {
12
12
  dryRun?: boolean;
13
13
  /** Number of retries for API operations (default: 3) */
14
14
  retries?: number;
15
- /** Custom PR body template */
16
15
  prTemplate?: string;
17
- /** Command executor for shell commands */
18
16
  executor: ICommandExecutor;
19
- /** GitHub App installation token for authentication */
20
17
  token?: string;
21
- /** Labels to apply to the created PR */
22
18
  labels?: string[];
23
19
  /** Optional logger for PR strategy debug/warn/info messages */
24
20
  log?: IPRStrategyLogger;
25
21
  /** Pre-constructed PR strategy to reuse (avoids redundant instantiation) */
26
22
  strategy?: IPRStrategy;
23
+ /** Overrides the default "chore: sync ..." title */
24
+ title?: string;
25
+ aiSummary?: string;
27
26
  }
28
27
  export type { PRResult } from "./types.js";
29
28
  /**
@@ -33,13 +32,11 @@ export type { PRResult } from "./types.js";
33
32
  * - ${xfg:pr.fileChanges} - formatted list of changed files
34
33
  * - ${xfg:pr.fileCount} - number of changed files
35
34
  * - ${xfg:pr.title} - the PR title
35
+ * - ${xfg:pr.aiSummary} - AI-generated summary (empty when AI is off)
36
36
  *
37
37
  * Plus all standard repo variables (repo.name, repo.owner, etc.)
38
38
  */
39
- export declare function formatPRBody(files: FileAction[], repoInfo: RepoInfo, customTemplate?: string): string;
40
- /**
41
- * Generate PR title based on files changed (excludes skipped files)
42
- */
39
+ export declare function formatPRBody(files: FileAction[], repoInfo: RepoInfo, customTemplate?: string, aiSummary?: string, title?: string): string;
43
40
  export declare function formatPRTitle(files: FileAction[]): string;
44
41
  export declare function createPR(options: PROptions): Promise<PRResult>;
45
42
  interface MergePROptions {
@@ -49,9 +46,7 @@ interface MergePROptions {
49
46
  workDir: string;
50
47
  dryRun?: boolean;
51
48
  retries?: number;
52
- /** Command executor for shell commands */
53
49
  executor: ICommandExecutor;
54
- /** GitHub App installation token for authentication */
55
50
  token?: string;
56
51
  /** Optional logger for PR strategy debug/warn/info messages */
57
52
  log?: IPRStrategyLogger;
@@ -4,19 +4,20 @@ import { fileURLToPath } from "node:url";
4
4
  import { createPRStrategy } from "./pr-strategy-factory.js";
5
5
  import { PRWorkflowExecutor } from "./pr-strategy.js";
6
6
  import { interpolateXfgContent } from "../shared/xfg-template.js";
7
+ import { inlineCode } from "../shared/markdown-fence.js";
7
8
  function loadDefaultTemplate() {
8
- // Try to find PR.md in the project root
9
9
  const __filename = fileURLToPath(import.meta.url);
10
10
  const __dirname = dirname(__filename);
11
11
  const templatePath = join(__dirname, "..", "PR.md");
12
12
  if (existsSync(templatePath)) {
13
13
  return readFileSync(templatePath, "utf-8");
14
14
  }
15
- // Fallback template
16
15
  return `## Summary
17
16
 
18
17
  Automated sync of configuration files to \${xfg:repo.fullName}.
19
18
 
19
+ \${xfg:pr.aiSummary}
20
+
20
21
  ## Changes
21
22
 
22
23
  \${xfg:pr.fileChanges}
@@ -29,9 +30,21 @@ Configuration synced using [xfg](https://github.com/anthony-spruyt/xfg).
29
30
 
30
31
  _This PR was automatically generated by [xfg](https://github.com/anthony-spruyt/xfg)_`;
31
32
  }
32
- /**
33
- * Format file changes list, excluding skipped files
34
- */
33
+ const AI_SUMMARY_VAR = "${xfg:pr.aiSummary}";
34
+ const UNESCAPED_AI_SUMMARY_VAR = /(?<!\$)\$\{xfg:pr\.aiSummary\}/;
35
+ const AI_SUMMARY_LINE = /^[ \t]*\$\{xfg:pr\.aiSummary\}[ \t]*(?:\n|$)/m;
36
+ function dropAiSummaryLine(template) {
37
+ const match = AI_SUMMARY_LINE.exec(template);
38
+ if (!match)
39
+ return template;
40
+ const before = template.slice(0, match.index);
41
+ let after = template.slice(match.index + match[0].length);
42
+ // A placeholder between blank lines would otherwise leave a double blank.
43
+ if ((before === "" || before.endsWith("\n\n")) && after.startsWith("\n")) {
44
+ after = after.slice(1);
45
+ }
46
+ return before + after;
47
+ }
35
48
  function formatFileChanges(files) {
36
49
  const changedFiles = files.filter((f) => f.action !== "skip");
37
50
  return changedFiles
@@ -47,7 +60,7 @@ function formatFileChanges(files) {
47
60
  case "delete":
48
61
  actionText = "Deleted";
49
62
  break;
50
- /* c8 ignore next 3 -- filtered out by line 77 */
63
+ /* c8 ignore next 3 -- skipped files are filtered out above */
51
64
  case "skip":
52
65
  actionText = "Skipped";
53
66
  break;
@@ -57,7 +70,7 @@ function formatFileChanges(files) {
57
70
  throw new Error(`Unexpected action: ${_exhaustive}`);
58
71
  }
59
72
  }
60
- return `- ${actionText} \`${f.fileName}\``;
73
+ return `- ${actionText} ${inlineCode(f.fileName)}`;
61
74
  })
62
75
  .join("\n");
63
76
  }
@@ -68,29 +81,32 @@ function formatFileChanges(files) {
68
81
  * - ${xfg:pr.fileChanges} - formatted list of changed files
69
82
  * - ${xfg:pr.fileCount} - number of changed files
70
83
  * - ${xfg:pr.title} - the PR title
84
+ * - ${xfg:pr.aiSummary} - AI-generated summary (empty when AI is off)
71
85
  *
72
86
  * Plus all standard repo variables (repo.name, repo.owner, etc.)
73
87
  */
74
- export function formatPRBody(files, repoInfo, customTemplate) {
75
- const template = customTemplate ?? loadDefaultTemplate();
88
+ export function formatPRBody(files, repoInfo, customTemplate, aiSummary, title) {
89
+ let template = customTemplate ?? loadDefaultTemplate();
90
+ if (!aiSummary) {
91
+ template = dropAiSummaryLine(template);
92
+ }
93
+ else if (!UNESCAPED_AI_SUMMARY_VAR.test(template)) {
94
+ template = `${template.trimEnd()}\n\n## AI Summary\n\n${AI_SUMMARY_VAR}\n`;
95
+ }
76
96
  const fileChanges = formatFileChanges(files);
77
97
  const changedFiles = files.filter((f) => f.action !== "skip");
78
- const title = formatPRTitle(files);
79
- // Create context with PR-specific variables
80
98
  const result = interpolateXfgContent(template, {
81
99
  repoInfo,
82
100
  fileName: "PR.md",
83
101
  vars: {
84
102
  "pr.fileChanges": fileChanges,
85
103
  "pr.fileCount": String(changedFiles.length),
86
- "pr.title": title,
104
+ "pr.title": title ?? formatPRTitle(files),
105
+ "pr.aiSummary": aiSummary ?? "",
87
106
  },
88
107
  });
89
108
  return result;
90
109
  }
91
- /**
92
- * Generate PR title based on files changed (excludes skipped files)
93
- */
94
110
  export function formatPRTitle(files) {
95
111
  const changedFiles = files.filter((f) => f.action !== "skip");
96
112
  if (changedFiles.length === 1) {
@@ -103,16 +119,15 @@ export function formatPRTitle(files) {
103
119
  return `chore: sync ${changedFiles.length} config files`;
104
120
  }
105
121
  export function createPR(options) {
106
- const { repoInfo, branchName, baseBranch, files, workDir, dryRun, retries, prTemplate, executor, token, labels, log, } = options;
107
- const title = formatPRTitle(files);
108
- const body = formatPRBody(files, repoInfo, prTemplate);
122
+ const { repoInfo, branchName, baseBranch, files, workDir, dryRun, retries, prTemplate, executor, token, labels, log, aiSummary, } = options;
123
+ const title = options.title ?? formatPRTitle(files);
124
+ const body = formatPRBody(files, repoInfo, prTemplate, aiSummary, title);
109
125
  if (dryRun) {
110
126
  return Promise.resolve({
111
127
  success: true,
112
128
  message: `[DRY RUN] Would create PR: "${title}"`,
113
129
  });
114
130
  }
115
- // Get the appropriate strategy and execute via workflow executor
116
131
  const resolvedStrategy = options.strategy ?? createPRStrategy(repoInfo, executor, log);
117
132
  const workflow = new PRWorkflowExecutor(resolvedStrategy, log);
118
133
  return workflow.execute({
@@ -141,7 +156,6 @@ export function mergePR(options) {
141
156
  merged: false,
142
157
  });
143
158
  }
144
- // Get the appropriate strategy and execute merge
145
159
  const resolvedStrategy = options.strategy ?? createPRStrategy(repoInfo, executor, log);
146
160
  return resolvedStrategy.merge({
147
161
  prUrl,