@releasekit/notes 0.19.3 → 0.20.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.
@@ -10,7 +10,7 @@ import {
10
10
  success,
11
11
  warn,
12
12
  writeMarkdown
13
- } from "./chunk-77FGMGVD.js";
13
+ } from "./chunk-QCJ545PJ.js";
14
14
 
15
15
  // ../config/dist/index.js
16
16
  import * as fs from "fs";
@@ -241,9 +241,7 @@ var LLMCategorySchema = z.object({
241
241
  });
242
242
  var ScopeRulesSchema = z.object({
243
243
  allowed: z.array(z.string()).optional(),
244
- caseSensitive: z.boolean().default(false),
245
- invalidScopeAction: z.enum(["remove", "keep", "fallback"]).default("remove"),
246
- fallbackScope: z.string().optional()
244
+ caseSensitive: z.boolean().default(false)
247
245
  });
248
246
  var ScopeConfigSchema = z.object({
249
247
  mode: z.enum(["restricted", "packages", "none", "unrestricted"]).default("unrestricted"),
@@ -257,8 +255,7 @@ var LLMPromptOverridesSchema = z.object({
257
255
  releaseNotes: z.string().optional()
258
256
  });
259
257
  var LLMPromptsConfigSchema = z.object({
260
- instructions: LLMPromptOverridesSchema.optional(),
261
- templates: LLMPromptOverridesSchema.optional()
258
+ instructions: LLMPromptOverridesSchema.optional()
262
259
  });
263
260
  var LLMConfigSchema = z.object({
264
261
  provider: z.string(),
@@ -269,16 +266,34 @@ var LLMConfigSchema = z.object({
269
266
  concurrency: z.number().int().positive().optional(),
270
267
  retry: LLMRetryConfigSchema.optional(),
271
268
  tasks: LLMTasksConfigSchema.optional(),
272
- categories: z.array(LLMCategorySchema).optional(),
273
- style: z.string().optional(),
269
+ categories: z.array(LLMCategorySchema).default(() => [
270
+ { name: "Breaking", description: "Breaking changes that require user action to upgrade" },
271
+ { name: "New", description: "New features and capabilities" },
272
+ { name: "Changed", description: "Changes to existing functionality" },
273
+ { name: "Fixed", description: "Bug fixes" },
274
+ { name: "Developer", description: "Internal changes: CI, tooling, dependencies, refactoring" }
275
+ ]),
276
+ style: z.string().default(
277
+ 'Write in past tense ("Added feature", not "Add feature"). Be concise and user-focused. Lead with the impact, not the implementation detail.'
278
+ ),
274
279
  scopes: ScopeConfigSchema.optional(),
275
- prompts: LLMPromptsConfigSchema.optional()
280
+ prompts: LLMPromptsConfigSchema.optional(),
281
+ examples: z.number().int().min(0).max(5).default(3),
282
+ context: z.object({
283
+ pullRequests: z.boolean().default(true)
284
+ }).default({ pullRequests: true }),
285
+ categoryOrder: z.array(z.string()).optional()
276
286
  });
277
287
  var ReleaseNotesConfigSchema = z.object({
278
288
  mode: LocationModeSchema.optional(),
279
289
  file: z.string().optional(),
280
290
  templates: TemplateConfigSchema.optional(),
281
- llm: LLMConfigSchema.optional()
291
+ llm: LLMConfigSchema.optional(),
292
+ links: z.object({
293
+ items: z.array(z.object({ label: z.string(), url: z.string().url() })).optional(),
294
+ fromPRBodyMarker: z.string().optional(),
295
+ title: z.string().optional()
296
+ }).optional()
282
297
  });
283
298
  var NotesInputConfigSchema = z.object({
284
299
  source: z.string().optional(),
@@ -607,13 +622,97 @@ function getDefaultConfig() {
607
622
  }
608
623
 
609
624
  // src/core/pipeline.ts
610
- import * as fs9 from "fs";
611
- import * as path8 from "path";
625
+ import * as fs10 from "fs";
626
+ import * as path9 from "path";
627
+
628
+ // src/llm/context/prFetcher.ts
629
+ import { RequestError } from "@octokit/request-error";
630
+ import { Octokit } from "@octokit/rest";
631
+ var BODY_CAP = 2048;
632
+ function stripHtmlComments(input) {
633
+ let result = "";
634
+ let i = 0;
635
+ while (i < input.length) {
636
+ if (input.startsWith("<!--", i)) {
637
+ const end = input.indexOf("-->", i + 4);
638
+ i = end === -1 ? input.length : end + 3;
639
+ } else {
640
+ result += input[i++];
641
+ }
642
+ }
643
+ return result;
644
+ }
645
+ function stripDetailsTags(input) {
646
+ let result = "";
647
+ let i = 0;
648
+ let depth = 0;
649
+ const lower = input.toLowerCase();
650
+ while (i < input.length) {
651
+ if (lower.startsWith("<details", i)) {
652
+ depth++;
653
+ const tagEnd = lower.indexOf(">", i);
654
+ i = tagEnd === -1 ? input.length : tagEnd + 1;
655
+ } else if (lower.startsWith("</details>", i)) {
656
+ if (depth > 0) depth--;
657
+ i += 10;
658
+ } else {
659
+ if (depth === 0) result += input[i];
660
+ i++;
661
+ }
662
+ }
663
+ return result;
664
+ }
665
+ function sanitiseBody(raw) {
666
+ return stripDetailsTags(stripHtmlComments(raw)).replace(/!\[.*?\]\(.*?\)/g, "").replace(/\n{3,}/g, "\n\n").trim();
667
+ }
668
+ function truncateBody(body) {
669
+ if (body.length <= BODY_CAP) return body;
670
+ const headingPos = body.lastIndexOf("\n#", BODY_CAP);
671
+ const cutAt = headingPos > BODY_CAP / 2 ? headingPos : BODY_CAP;
672
+ return `${body.slice(0, cutAt).trimEnd()}
673
+ \u2026`;
674
+ }
675
+ var FETCH_CONCURRENCY = 5;
676
+ async function fetchPullRequestContext(owner, repo, issueNumbers, token, cache) {
677
+ const octokit = new Octokit({ auth: token });
678
+ const needed = issueNumbers.filter((n) => !cache.has(n));
679
+ for (let i = 0; i < needed.length; i += FETCH_CONCURRENCY) {
680
+ const batch = needed.slice(i, i + FETCH_CONCURRENCY);
681
+ await Promise.all(
682
+ batch.map(async (number) => {
683
+ try {
684
+ const { data } = await octokit.rest.issues.get({ owner, repo, issue_number: number });
685
+ if (!data.pull_request) {
686
+ cache.set(number, null);
687
+ return;
688
+ }
689
+ const raw = data.body ?? "";
690
+ const body = truncateBody(sanitiseBody(raw));
691
+ cache.set(number, { number, title: data.title, body });
692
+ } catch (error2) {
693
+ if (error2 instanceof RequestError && (error2.status === 401 || error2.status === 403)) {
694
+ warn(`GitHub API auth error fetching PR #${number} (${error2.status}): check GITHUB_TOKEN permissions`);
695
+ } else {
696
+ debug(`Failed to fetch PR #${number}: ${error2 instanceof Error ? error2.message : String(error2)}`);
697
+ }
698
+ }
699
+ })
700
+ );
701
+ }
702
+ }
703
+ function parseIssueNumbers(issueIds) {
704
+ return issueIds.map((id) => parseInt(id.replace(/^#/, ""), 10)).filter((n) => !isNaN(n) && n > 0);
705
+ }
706
+ function resolveGitHubToken() {
707
+ return process.env.GITHUB_TOKEN || process.env.GH_TOKEN || void 0;
708
+ }
612
709
 
613
710
  // src/llm/defaults.ts
614
711
  var LLM_DEFAULTS = {
615
712
  timeout: 6e4,
713
+ // 16k tokens accommodates large changelogs without hitting most model ceilings.
616
714
  maxTokens: 16384,
715
+ // 0.7 balances coherence (low temp) with natural-sounding variation (high temp).
617
716
  temperature: 0.7,
618
717
  concurrency: 5,
619
718
  retry: {
@@ -630,6 +729,150 @@ var LLM_DEFAULTS = {
630
729
  }
631
730
  };
632
731
 
732
+ // src/llm/examples/fetcher.ts
733
+ import { createHash } from "crypto";
734
+ import * as fs5 from "fs";
735
+ import * as os2 from "os";
736
+ import * as path5 from "path";
737
+ import { RequestError as RequestError2 } from "@octokit/request-error";
738
+ import { Octokit as Octokit2 } from "@octokit/rest";
739
+
740
+ // src/llm/examples/parser.ts
741
+ var LEAD_IN_RE = /^\*\*([^*]+)\*\*:\s*/;
742
+ var BULLET_RE = /^[-*]\s+/;
743
+ function parseReleaseBodyToExample(markdown, version) {
744
+ const lines = markdown.split("\n");
745
+ const entries = [];
746
+ let currentCategory = "General";
747
+ for (const raw of lines) {
748
+ const line = raw.trim();
749
+ if (!line) continue;
750
+ const headingMatch = /^#{2,4} (.+)/.exec(line);
751
+ if (headingMatch) {
752
+ currentCategory = headingMatch[1].trim();
753
+ continue;
754
+ }
755
+ if (line.startsWith("#")) continue;
756
+ if (BULLET_RE.test(line)) {
757
+ const text = line.replace(BULLET_RE, "");
758
+ const leadInMatch = LEAD_IN_RE.exec(text);
759
+ const entry = {
760
+ description: leadInMatch ? text.slice(leadInMatch[0].length) : text,
761
+ category: currentCategory
762
+ };
763
+ if (leadInMatch) entry.leadIn = leadInMatch[1];
764
+ if (/\*\*BREAKING\*\*/i.test(text)) entry.breaking = true;
765
+ entries.push(entry);
766
+ }
767
+ }
768
+ if (entries.length === 0) return null;
769
+ return { version, entries };
770
+ }
771
+ function renderExamplesBlock(examples) {
772
+ if (examples.length === 0) return "";
773
+ const blocks = examples.map((ex) => {
774
+ const entryLines = ex.entries.map((e) => {
775
+ const leadIn = e.leadIn ? `**${e.leadIn}**: ` : "";
776
+ const scope = e.scope ? ` (${e.scope})` : "";
777
+ const breaking = e.breaking ? " **BREAKING**" : "";
778
+ return ` - [${e.category}]${scope}: ${leadIn}${e.description}${breaking}`;
779
+ }).join("\n");
780
+ return `<example version="${ex.version}">
781
+ ${entryLines}
782
+ </example>`;
783
+ });
784
+ return `
785
+ Examples from prior releases (use these as style references):
786
+ ${blocks.join("\n")}
787
+ `;
788
+ }
789
+
790
+ // src/llm/examples/fetcher.ts
791
+ function cacheDir() {
792
+ return path5.join(os2.tmpdir(), "releasekit", "examples");
793
+ }
794
+ function cacheKey(owner, repo, packageName) {
795
+ const safe = packageName.replace(/[^a-zA-Z0-9-]/g, "_");
796
+ const hash = createHash("sha256").update(packageName).digest("hex").slice(0, 8);
797
+ return path5.join(cacheDir(), owner, repo, `${safe}_${hash}.json`);
798
+ }
799
+ function readCache(key, latestTag, count) {
800
+ try {
801
+ const raw = fs5.readFileSync(key, "utf-8");
802
+ const entry = JSON.parse(raw);
803
+ if (entry.latestTag !== latestTag || entry.count < count) return null;
804
+ return entry.examples;
805
+ } catch {
806
+ return null;
807
+ }
808
+ }
809
+ function writeCache(key, latestTag, count, examples) {
810
+ try {
811
+ fs5.mkdirSync(path5.dirname(key), { recursive: true });
812
+ fs5.writeFileSync(key, JSON.stringify({ latestTag, count, examples }), "utf-8");
813
+ } catch {
814
+ }
815
+ }
816
+ function matchesPackageScoped(tagName, packageName) {
817
+ const escaped = packageName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
818
+ return new RegExp(`^${escaped}@`).test(tagName);
819
+ }
820
+ function matchesBareVersion(tagName) {
821
+ return /^v?\d/.test(tagName);
822
+ }
823
+ async function fetchExamples(options) {
824
+ const { owner, repo, packageName, count, githubToken, isMonorepo } = options;
825
+ if (count === 0) return [];
826
+ const token = githubToken ?? process.env.GITHUB_TOKEN ?? process.env.GH_TOKEN;
827
+ if (!token) {
828
+ debug("No GitHub token available \u2014 skipping examples fetch");
829
+ return [];
830
+ }
831
+ const octokit = new Octokit2({ auth: token });
832
+ try {
833
+ const allReleases = [];
834
+ for (let page = 1; page <= 3; page++) {
835
+ const { data } = await octokit.rest.repos.listReleases({ owner, repo, per_page: 100, page });
836
+ allReleases.push(...data);
837
+ const totalScoped = allReleases.filter(
838
+ (r) => !r.draft && !r.prerelease && matchesPackageScoped(r.tag_name, packageName)
839
+ ).length;
840
+ if (totalScoped >= count || data.length < 100) break;
841
+ }
842
+ const nonDraft = allReleases.filter((r) => !r.draft && !r.prerelease);
843
+ const packageScoped = nonDraft.filter((r) => matchesPackageScoped(r.tag_name, packageName));
844
+ const matching = (packageScoped.length > 0 ? packageScoped : isMonorepo ? [] : nonDraft.filter((r) => matchesBareVersion(r.tag_name))).slice(0, count);
845
+ if (matching.length === 0) {
846
+ debug(`No matching releases found for ${packageName}`);
847
+ return [];
848
+ }
849
+ const latestTag = matching[0].tag_name;
850
+ const key = cacheKey(owner, repo, packageName);
851
+ const cached = readCache(key, latestTag, count);
852
+ if (cached) {
853
+ debug(`Using cached examples for ${packageName} (tag: ${latestTag})`);
854
+ return cached.slice(0, count);
855
+ }
856
+ const examples = [];
857
+ for (const release of matching) {
858
+ if (!release.body) continue;
859
+ const version = release.tag_name.replace(/^.*@/, "").replace(/^v/, "");
860
+ const example = parseReleaseBodyToExample(release.body, version);
861
+ if (example) examples.push(example);
862
+ }
863
+ if (examples.length > 0) writeCache(key, latestTag, count, examples);
864
+ debug(`Fetched ${examples.length} examples for ${packageName}`);
865
+ return examples;
866
+ } catch (error2) {
867
+ if (error2 instanceof RequestError2 && (error2.status === 401 || error2.status === 403)) {
868
+ warn(`GitHub API auth error (${error2.status}) \u2014 skipping examples fetch; check GITHUB_TOKEN permissions`);
869
+ } else {
870
+ debug(`Failed to fetch examples: ${error2 instanceof Error ? error2.message : String(error2)}`);
871
+ }
872
+ return [];
873
+ }
874
+ }
875
+
633
876
  // src/llm/anthropic.ts
634
877
  import Anthropic from "@anthropic-ai/sdk";
635
878
 
@@ -646,9 +889,24 @@ var BaseLLMProvider = class {
646
889
  }
647
890
  };
648
891
 
892
+ // src/llm/messages.ts
893
+ function debugLogMessages(providerName, messages) {
894
+ if (process.env.RELEASEKIT_DEBUG !== "1") return;
895
+ console.error(`[RELEASEKIT_DEBUG] ${providerName} messages (${messages.length}):`);
896
+ for (const msg of messages) {
897
+ const preview = msg.content.length > 300 ? `${msg.content.slice(0, 300)}\u2026` : msg.content;
898
+ console.error(` [${msg.role}]: ${preview}`);
899
+ }
900
+ }
901
+
649
902
  // src/llm/anthropic.ts
650
903
  var AnthropicProvider = class extends BaseLLMProvider {
651
904
  name = "anthropic";
905
+ capabilities = {
906
+ systemRole: true,
907
+ structuredOutputs: true,
908
+ toolUse: true
909
+ };
652
910
  client;
653
911
  model;
654
912
  constructor(config = {}) {
@@ -660,18 +918,45 @@ var AnthropicProvider = class extends BaseLLMProvider {
660
918
  this.client = new Anthropic({ apiKey });
661
919
  this.model = config.model ?? LLM_DEFAULTS.models.anthropic;
662
920
  }
663
- async complete(prompt, options) {
921
+ async complete(messages, options) {
922
+ debugLogMessages(this.name, messages);
923
+ const systemMsg = messages.find((m) => m.role === "system");
924
+ const nonSystemMessages = messages.filter((m) => m.role !== "system").map((m) => ({ role: m.role, content: m.content }));
664
925
  try {
926
+ if (options?.schema) {
927
+ const toolName = options.toolName ?? "emit_release_notes";
928
+ const response2 = await this.client.messages.create({
929
+ model: this.model,
930
+ max_tokens: this.getMaxTokens(options),
931
+ system: systemMsg?.content,
932
+ tools: [
933
+ {
934
+ name: toolName,
935
+ description: "Emit structured release notes data as JSON",
936
+ input_schema: options.schema
937
+ }
938
+ ],
939
+ tool_choice: { type: "tool", name: toolName },
940
+ messages: nonSystemMessages
941
+ });
942
+ const toolBlock = response2.content.find((b) => b.type === "tool_use");
943
+ if (toolBlock?.type === "tool_use") {
944
+ const structured = toolBlock.input;
945
+ return { content: JSON.stringify(structured), structured };
946
+ }
947
+ throw new LLMError("Expected tool_use block in Anthropic response");
948
+ }
665
949
  const response = await this.client.messages.create({
666
950
  model: this.model,
667
951
  max_tokens: this.getMaxTokens(options),
668
- messages: [{ role: "user", content: prompt }]
952
+ system: systemMsg?.content,
953
+ messages: nonSystemMessages
669
954
  });
670
955
  const firstBlock = response.content[0];
671
956
  if (!firstBlock || firstBlock.type !== "text") {
672
957
  throw new LLMError("Unexpected response format from Anthropic");
673
958
  }
674
- return firstBlock.text;
959
+ return { content: firstBlock.text };
675
960
  } catch (error2) {
676
961
  if (error2 instanceof LLMError) throw error2;
677
962
  throw new LLMError(`Anthropic API error: ${error2 instanceof Error ? error2.message : String(error2)}`);
@@ -682,6 +967,11 @@ var AnthropicProvider = class extends BaseLLMProvider {
682
967
  // src/llm/ollama.ts
683
968
  var OllamaProvider = class extends BaseLLMProvider {
684
969
  name = "ollama";
970
+ capabilities = {
971
+ systemRole: true,
972
+ structuredOutputs: true,
973
+ toolUse: false
974
+ };
685
975
  baseURL;
686
976
  model;
687
977
  apiKey;
@@ -691,16 +981,20 @@ var OllamaProvider = class extends BaseLLMProvider {
691
981
  this.model = config.model ?? process.env.OLLAMA_MODEL ?? LLM_DEFAULTS.models.ollama;
692
982
  this.apiKey = config.apiKey ?? process.env.OLLAMA_API_KEY;
693
983
  }
694
- async complete(prompt, options) {
984
+ async complete(messages, options) {
985
+ debugLogMessages(this.name, messages);
695
986
  const requestBody = {
696
987
  model: this.model,
697
- messages: [{ role: "user", content: prompt }],
988
+ messages: messages.map((m) => ({ role: m.role, content: m.content })),
698
989
  stream: false,
699
990
  options: {
700
991
  num_predict: this.getMaxTokens(options),
701
992
  temperature: this.getTemperature(options)
702
993
  }
703
994
  };
995
+ if (options?.schema) {
996
+ requestBody.format = options.schema;
997
+ }
704
998
  try {
705
999
  const headers = {
706
1000
  "Content-Type": "application/json"
@@ -729,7 +1023,17 @@ var OllamaProvider = class extends BaseLLMProvider {
729
1023
  if (!data.message?.content) {
730
1024
  throw new LLMError("Empty response from Ollama");
731
1025
  }
732
- return data.message.content;
1026
+ const content = data.message.content;
1027
+ if (options?.schema) {
1028
+ try {
1029
+ const structured = JSON.parse(content);
1030
+ return { content, structured };
1031
+ } catch (e) {
1032
+ debug(`Ollama: failed to parse structured response: ${e instanceof Error ? e.message : String(e)}`);
1033
+ return { content };
1034
+ }
1035
+ }
1036
+ return { content };
733
1037
  } catch (error2) {
734
1038
  if (error2 instanceof LLMError) throw error2;
735
1039
  throw new LLMError(`Ollama error: ${error2 instanceof Error ? error2.message : String(error2)}`);
@@ -741,6 +1045,11 @@ var OllamaProvider = class extends BaseLLMProvider {
741
1045
  import OpenAI from "openai";
742
1046
  var OpenAIProvider = class extends BaseLLMProvider {
743
1047
  name = "openai";
1048
+ capabilities = {
1049
+ systemRole: true,
1050
+ structuredOutputs: true,
1051
+ toolUse: false
1052
+ };
744
1053
  client;
745
1054
  model;
746
1055
  constructor(config = {}) {
@@ -755,19 +1064,43 @@ var OpenAIProvider = class extends BaseLLMProvider {
755
1064
  });
756
1065
  this.model = config.model ?? LLM_DEFAULTS.models.openai;
757
1066
  }
758
- async complete(prompt, options) {
1067
+ async complete(messages, options) {
1068
+ debugLogMessages(this.name, messages);
759
1069
  try {
760
- const response = await this.client.chat.completions.create({
1070
+ const openaiMessages = messages.map((m) => ({ role: m.role, content: m.content }));
1071
+ const requestParams = {
761
1072
  model: this.model,
762
- messages: [{ role: "user", content: prompt }],
1073
+ messages: openaiMessages,
763
1074
  max_tokens: this.getMaxTokens(options),
764
- temperature: this.getTemperature(options)
765
- });
1075
+ temperature: this.getTemperature(options),
1076
+ stream: false,
1077
+ ...options?.schema && {
1078
+ response_format: {
1079
+ type: "json_schema",
1080
+ json_schema: {
1081
+ name: options.toolName ?? "release_notes",
1082
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1083
+ schema: options.schema,
1084
+ strict: true
1085
+ }
1086
+ }
1087
+ }
1088
+ };
1089
+ const response = await this.client.chat.completions.create(requestParams);
766
1090
  const content = response.choices[0]?.message?.content;
767
1091
  if (!content) {
768
1092
  throw new LLMError("Empty response from OpenAI");
769
1093
  }
770
- return content;
1094
+ if (options?.schema) {
1095
+ try {
1096
+ const structured = JSON.parse(content);
1097
+ return { content, structured };
1098
+ } catch (e) {
1099
+ debug(`OpenAI: failed to parse structured response: ${e instanceof Error ? e.message : String(e)}`);
1100
+ return { content };
1101
+ }
1102
+ }
1103
+ return { content };
771
1104
  } catch (error2) {
772
1105
  if (error2 instanceof LLMError) throw error2;
773
1106
  throw new LLMError(`OpenAI API error: ${error2 instanceof Error ? error2.message : String(error2)}`);
@@ -779,6 +1112,11 @@ var OpenAIProvider = class extends BaseLLMProvider {
779
1112
  import OpenAI2 from "openai";
780
1113
  var OpenAICompatibleProvider = class extends BaseLLMProvider {
781
1114
  name = "openai-compatible";
1115
+ capabilities = {
1116
+ systemRole: true,
1117
+ structuredOutputs: false,
1118
+ toolUse: false
1119
+ };
782
1120
  client;
783
1121
  model;
784
1122
  constructor(config) {
@@ -790,19 +1128,23 @@ var OpenAICompatibleProvider = class extends BaseLLMProvider {
790
1128
  });
791
1129
  this.model = config.model ?? LLM_DEFAULTS.models["openai-compatible"];
792
1130
  }
793
- async complete(prompt, options) {
1131
+ async complete(messages, options) {
1132
+ debugLogMessages(this.name, messages);
794
1133
  try {
795
- const response = await this.client.chat.completions.create({
1134
+ const openaiMessages = messages.map((m) => ({ role: m.role, content: m.content }));
1135
+ const requestParams = {
796
1136
  model: this.model,
797
- messages: [{ role: "user", content: prompt }],
1137
+ messages: openaiMessages,
798
1138
  max_tokens: this.getMaxTokens(options),
799
- temperature: this.getTemperature(options)
800
- });
1139
+ temperature: this.getTemperature(options),
1140
+ stream: false
1141
+ };
1142
+ const response = await this.client.chat.completions.create(requestParams);
801
1143
  const content = response.choices[0]?.message?.content;
802
1144
  if (!content) {
803
1145
  throw new LLMError("Empty response from LLM");
804
1146
  }
805
- return content;
1147
+ return { content };
806
1148
  } catch (error2) {
807
1149
  if (error2 instanceof LLMError) throw error2;
808
1150
  throw new LLMError(`LLM API error: ${error2 instanceof Error ? error2.message : String(error2)}`);
@@ -820,26 +1162,112 @@ function extractJsonFromResponse(response) {
820
1162
  return stripped;
821
1163
  }
822
1164
 
823
- // src/llm/prompts.ts
824
- function resolvePrompt(taskName, defaultPrompt, promptsConfig) {
825
- if (!promptsConfig) return defaultPrompt;
826
- const fullTemplate = promptsConfig.templates?.[taskName];
827
- if (fullTemplate) return fullTemplate;
828
- const additionalInstructions = promptsConfig.instructions?.[taskName];
829
- if (additionalInstructions) {
830
- const insertionPoint = defaultPrompt.lastIndexOf("Output only valid JSON");
831
- if (insertionPoint !== -1) {
832
- return `${defaultPrompt.slice(0, insertionPoint)}Additional instructions:
833
- ${additionalInstructions}
834
-
835
- ${defaultPrompt.slice(insertionPoint)}`;
1165
+ // src/llm/correctiveRetry.ts
1166
+ async function withCorrectiveRetry(call, validate, buildCorrectionMessages3, initialMessages, maxCorrectiveAttempts = 2) {
1167
+ let messages = initialMessages;
1168
+ let lastError = "";
1169
+ for (let attempt = 0; attempt <= maxCorrectiveAttempts; attempt++) {
1170
+ const result = await call(messages, attempt === 0);
1171
+ const validation = validate(result);
1172
+ if (validation.valid) return validation.value;
1173
+ lastError = validation.error;
1174
+ if (attempt < maxCorrectiveAttempts) {
1175
+ const badContent = typeof result.structured !== "undefined" ? JSON.stringify(result.structured) : result.content;
1176
+ messages = [
1177
+ ...messages,
1178
+ { role: "assistant", content: badContent },
1179
+ ...buildCorrectionMessages3(badContent, validation.error)
1180
+ ];
836
1181
  }
837
- return `${defaultPrompt}
1182
+ }
1183
+ throw new LLMError(`Structured output validation failed after ${maxCorrectiveAttempts + 1} attempts: ${lastError}`);
1184
+ }
1185
+
1186
+ // src/llm/prompts.ts
1187
+ function resolveSystemPrompt(taskName, defaultSystemPrompt, promptsConfig) {
1188
+ const instructions = promptsConfig?.instructions?.[taskName];
1189
+ if (instructions) {
1190
+ return `${defaultSystemPrompt}
838
1191
 
839
1192
  Additional instructions:
840
- ${additionalInstructions}`;
1193
+ ${instructions}`;
841
1194
  }
842
- return defaultPrompt;
1195
+ return defaultSystemPrompt;
1196
+ }
1197
+
1198
+ // src/llm/schemas.ts
1199
+ import { z as z3 } from "zod";
1200
+ var EntryOutputSchema = z3.object({
1201
+ description: z3.string(),
1202
+ category: z3.string(),
1203
+ scope: z3.string().nullable(),
1204
+ breaking: z3.boolean().nullable(),
1205
+ leadIn: z3.string().nullable()
1206
+ });
1207
+ var EnhanceAndCategorizeOutputSchema = z3.object({
1208
+ entries: z3.array(EntryOutputSchema)
1209
+ });
1210
+ var CategorizeEntryOutputSchema = z3.object({
1211
+ category: z3.string(),
1212
+ scope: z3.string().nullable()
1213
+ });
1214
+ var CategorizeOutputSchema = z3.object({
1215
+ entries: z3.array(CategorizeEntryOutputSchema)
1216
+ });
1217
+ function nullableString() {
1218
+ return { anyOf: [{ type: "string" }, { type: "null" }] };
1219
+ }
1220
+ function nullableBoolean() {
1221
+ return { anyOf: [{ type: "boolean" }, { type: "null" }] };
1222
+ }
1223
+ function buildEnhanceAndCategorizeSchema(categories) {
1224
+ const categoryNames = categories.map((c) => c.name);
1225
+ const categoryField = categoryNames.length > 0 ? { type: "string", enum: categoryNames } : { type: "string" };
1226
+ return {
1227
+ type: "object",
1228
+ properties: {
1229
+ entries: {
1230
+ type: "array",
1231
+ items: {
1232
+ type: "object",
1233
+ properties: {
1234
+ description: { type: "string" },
1235
+ category: categoryField,
1236
+ scope: nullableString(),
1237
+ breaking: nullableBoolean(),
1238
+ leadIn: nullableString()
1239
+ },
1240
+ required: ["description", "category", "scope", "breaking", "leadIn"],
1241
+ additionalProperties: false
1242
+ }
1243
+ }
1244
+ },
1245
+ required: ["entries"],
1246
+ additionalProperties: false
1247
+ };
1248
+ }
1249
+ function buildCategorizeSchema(categories) {
1250
+ const categoryNames = categories.map((c) => c.name);
1251
+ const categoryField = categoryNames.length > 0 ? { type: "string", enum: categoryNames } : { type: "string" };
1252
+ return {
1253
+ type: "object",
1254
+ properties: {
1255
+ entries: {
1256
+ type: "array",
1257
+ items: {
1258
+ type: "object",
1259
+ properties: {
1260
+ category: categoryField,
1261
+ scope: nullableString()
1262
+ },
1263
+ required: ["category", "scope"],
1264
+ additionalProperties: false
1265
+ }
1266
+ }
1267
+ },
1268
+ required: ["entries"],
1269
+ additionalProperties: false
1270
+ };
843
1271
  }
844
1272
 
845
1273
  // src/llm/scopes.ts
@@ -869,127 +1297,186 @@ function resolveAllowedScopes(scopeConfig, categories, packageNames) {
869
1297
  }
870
1298
  return null;
871
1299
  }
872
- function validateScope(scope, allowedScopes, rules) {
1300
+ function validateScope(scope, allowedScopes, caseSensitive = false) {
873
1301
  if (!scope || allowedScopes === null) return scope;
874
1302
  if (allowedScopes.length === 0) return void 0;
875
- const caseSensitive = rules?.caseSensitive ?? false;
876
1303
  const normalise = (s) => caseSensitive ? s : s.toLowerCase();
877
1304
  const isAllowed = allowedScopes.some((a) => normalise(a) === normalise(scope));
878
- if (isAllowed) return scope;
879
- switch (rules?.invalidScopeAction ?? "remove") {
880
- case "keep":
881
- return scope;
882
- case "fallback":
883
- return rules?.fallbackScope;
884
- default:
885
- return void 0;
886
- }
1305
+ return isAllowed ? scope : void 0;
887
1306
  }
888
1307
  function validateEntryScopes(entries, scopeConfig, categories) {
889
1308
  const allowedScopes = resolveAllowedScopes(scopeConfig, categories);
890
- if (allowedScopes === null) return entries;
891
- return entries.map((entry) => ({
892
- ...entry,
893
- scope: validateScope(entry.scope, allowedScopes, scopeConfig?.rules)
894
- }));
1309
+ if (allowedScopes === null) return { valid: true, entries, errors: [] };
1310
+ const caseSensitive = scopeConfig?.rules?.caseSensitive ?? false;
1311
+ const errors = [];
1312
+ const validatedEntries = entries.map((entry, index) => {
1313
+ const cleaned = validateScope(entry.scope, allowedScopes, caseSensitive);
1314
+ if (entry.scope && cleaned === void 0) {
1315
+ errors.push({
1316
+ entryIndex: index,
1317
+ providedScope: entry.scope,
1318
+ allowedScopes
1319
+ });
1320
+ return { ...entry, scope: void 0 };
1321
+ }
1322
+ return entry.scope !== cleaned ? { ...entry, scope: cleaned } : entry;
1323
+ });
1324
+ return { valid: errors.length === 0, entries: validatedEntries, errors };
895
1325
  }
896
1326
 
897
- // src/llm/tasks/categorize.ts
898
- var DEFAULT_CATEGORIZE_PROMPT = `You are categorizing changelog entries for a software release.
899
-
900
- Given the following entries, group them into meaningful categories (e.g., "Core", "UI", "API", "Performance", "Bug Fixes", "Documentation").
901
-
902
- Output a JSON object where keys are category names and values are arrays of entry indices (0-based).
903
-
904
- Entries:
905
- {{entries}}
1327
+ // src/llm/tasks/shared.ts
1328
+ function escAttr(s) {
1329
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/"/g, "&quot;");
1330
+ }
1331
+ function escBody(s) {
1332
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1333
+ }
1334
+ function renderPRBlocks(entry) {
1335
+ if (!entry.context?.prs.length) return "";
1336
+ return entry.context.prs.map(
1337
+ (pr) => `<pr number="${pr.number}" title="${escAttr(pr.title)}">${pr.body ? `
1338
+ ${escBody(pr.body)}
1339
+ ` : ""}</pr>`
1340
+ ).join("\n");
1341
+ }
1342
+ function groupByCategory(llmEntries, entries) {
1343
+ const categoryMap = /* @__PURE__ */ new Map();
1344
+ for (let i = 0; i < llmEntries.length; i++) {
1345
+ const category = llmEntries[i]?.category ?? "Unknown";
1346
+ const entry = entries[i];
1347
+ if (!entry) continue;
1348
+ if (!categoryMap.has(category)) categoryMap.set(category, []);
1349
+ categoryMap.get(category).push(entry);
1350
+ }
1351
+ const result = [];
1352
+ for (const [category, catEntries] of categoryMap) {
1353
+ result.push({ category, entries: catEntries });
1354
+ }
1355
+ return result;
1356
+ }
906
1357
 
907
- Output only valid JSON, nothing else:`;
908
- function buildCustomCategorizePrompt(categories) {
909
- const categoryList = categories.map((c) => {
1358
+ // src/llm/tasks/categorize.ts
1359
+ function buildSystemPrompt(categories) {
1360
+ const categorySection = categories && categories.length > 0 ? `Categories (use ONLY these exact names):
1361
+ ${categories.map((c) => {
910
1362
  const scopeInfo = c.scopes?.length ? ` Allowed scopes: ${c.scopes.join(", ")}.` : "";
911
1363
  return `- "${c.name}": ${c.description}${scopeInfo}`;
912
- }).join("\n");
913
- const scopeMap = getAllowedScopesFromCategories(categories);
914
- let scopeInstructions = "";
915
- if (scopeMap.size > 0) {
916
- const entries = [];
917
- for (const [catName, scopes] of scopeMap) {
918
- entries.push(`For "${catName}", assign a scope from: ${scopes.join(", ")}.`);
919
- }
920
- scopeInstructions = `
921
-
922
- ${entries.join("\n")}
923
- Only use scopes from these predefined lists. If an entry does not fit any scope, set scope to null.`;
1364
+ }).join("\n")}` : `Categories: Group into meaningful categories (e.g., "Core", "UI", "API", "Performance", "Bug Fixes", "Documentation").`;
1365
+ let scopeInstruction = "";
1366
+ if (categories && categories.length > 0) {
1367
+ const scopeMap = getAllowedScopesFromCategories(categories);
1368
+ if (scopeMap.size > 0) {
1369
+ const parts = [];
1370
+ for (const [catName, scopes] of scopeMap) {
1371
+ parts.push(`For "${catName}", use a scope from: ${scopes.join(", ")}.`);
1372
+ }
1373
+ scopeInstruction = `
1374
+ ${parts.join("\n")}
1375
+ Only use scopes from these predefined lists. Set scope to null if no scope applies.`;
1376
+ }
924
1377
  }
925
1378
  return `You are categorizing changelog entries for a software release.
926
1379
 
927
- Given the following entries, group them into the specified categories. Only use the categories listed below in this exact order:
928
-
929
- Categories:
930
- ${categoryList}${scopeInstructions}
931
-
932
- Output a JSON object with two fields:
933
- - "categories": an object where keys are category names and values are arrays of entry indices (0-based)
934
- - "scopes": an object where keys are entry indices (as strings) and values are scope labels. Only include entries that have a valid scope from the predefined list.
1380
+ ${categorySection}${scopeInstruction}
935
1381
 
936
- Entries:
937
- {{entries}}
1382
+ Output a JSON object with an "entries" array. Each element (same order as input) must have:
1383
+ - "category": category name from the list above
1384
+ - "scope": subcategory label or null`;
1385
+ }
1386
+ function buildUserPrompt(entries) {
1387
+ const text = entries.map((e, i) => `${i}. [${e.type}]: ${e.description}`).join("\n");
1388
+ return `Entries:
1389
+ ${text}`;
1390
+ }
1391
+ function buildCorrectionMessages(_badContent, error2) {
1392
+ return [
1393
+ {
1394
+ role: "user",
1395
+ content: `Your previous response had an error: ${error2}
938
1396
 
939
- Output only valid JSON, nothing else:`;
1397
+ Please fix the issue and output only valid JSON matching the required schema.`
1398
+ }
1399
+ ];
1400
+ }
1401
+ function makeValidator(entries, context) {
1402
+ const cleanEntries = entries.map((e) => ({ ...e, scope: void 0 }));
1403
+ return (result) => {
1404
+ let parsed;
1405
+ try {
1406
+ parsed = typeof result.structured !== "undefined" ? result.structured : JSON.parse(extractJsonFromResponse(result.content));
1407
+ } catch (e) {
1408
+ return { valid: false, error: `Invalid JSON: ${e instanceof Error ? e.message : String(e)}` };
1409
+ }
1410
+ const zodResult = CategorizeOutputSchema.safeParse(parsed);
1411
+ if (!zodResult.success) {
1412
+ return { valid: false, error: `Schema error: ${zodResult.error.message}` };
1413
+ }
1414
+ if (zodResult.data.entries.length !== entries.length) {
1415
+ return {
1416
+ valid: false,
1417
+ error: `Expected ${entries.length} entries, got ${zodResult.data.entries.length}`
1418
+ };
1419
+ }
1420
+ const categoryNames = context.categories?.map((c) => c.name);
1421
+ if (categoryNames?.length) {
1422
+ const invalid = zodResult.data.entries.filter((e) => !categoryNames.includes(e.category)).map((e) => e.category);
1423
+ if (invalid.length > 0) {
1424
+ const unique = [...new Set(invalid)];
1425
+ return {
1426
+ valid: false,
1427
+ error: `Unknown categories: ${unique.join(", ")}. Valid categories: ${categoryNames.join(", ")}`
1428
+ };
1429
+ }
1430
+ }
1431
+ const withScopes = cleanEntries.map((entry, i) => {
1432
+ const llmEntry = zodResult.data.entries[i];
1433
+ const scope = llmEntry?.scope ?? void 0;
1434
+ return scope ? { ...entry, scope } : entry;
1435
+ });
1436
+ const scopeResult = validateEntryScopes(withScopes, context.scopes, context.categories);
1437
+ if (!scopeResult.valid) {
1438
+ const msg = scopeResult.errors.map(
1439
+ (e) => `entry ${e.entryIndex} scope "${e.providedScope}" (${e.allowedScopes.length ? `valid: ${e.allowedScopes.join(", ")}` : "no scopes permitted"})`
1440
+ ).join("; ");
1441
+ return { valid: false, error: `Invalid scopes: ${msg}` };
1442
+ }
1443
+ return { valid: true, value: groupByCategory(zodResult.data.entries, scopeResult.entries) };
1444
+ };
940
1445
  }
941
1446
  async function categorizeEntries(provider, entries, context) {
942
1447
  if (entries.length === 0) {
943
1448
  return [];
944
1449
  }
945
- const entriesCopy = entries.map((e) => ({ ...e, scope: void 0 }));
946
- const entriesText = entriesCopy.map((e, i) => `${i}. [${e.type}]: ${e.description}`).join("\n");
947
- const hasCustomCategories = context.categories && context.categories.length > 0;
948
- const defaultPrompt = hasCustomCategories ? buildCustomCategorizePrompt(context.categories) : DEFAULT_CATEGORIZE_PROMPT;
949
- const promptTemplate = resolvePrompt("categorize", defaultPrompt, context.prompts);
950
- const prompt = promptTemplate.replace("{{entries}}", entriesText);
1450
+ const systemPrompt = resolveSystemPrompt("categorize", buildSystemPrompt(context.categories), context.prompts);
1451
+ const initialMessages = [
1452
+ { role: "system", content: systemPrompt },
1453
+ { role: "user", content: buildUserPrompt(entries) }
1454
+ ];
1455
+ const schema = buildCategorizeSchema(context.categories ?? []);
1456
+ const validate = makeValidator(entries, context);
951
1457
  try {
952
- const response = await provider.complete(prompt);
953
- const parsed = JSON.parse(extractJsonFromResponse(response));
954
- const result = [];
955
- if (hasCustomCategories && parsed.categories) {
956
- const categoryMap = parsed.categories;
957
- const scopeMap = parsed.scopes || {};
958
- for (const [indexStr, scope] of Object.entries(scopeMap)) {
959
- const idx = Number.parseInt(indexStr, 10);
960
- if (entriesCopy[idx] && scope?.trim()) {
961
- entriesCopy[idx] = { ...entriesCopy[idx], scope: scope.trim() };
962
- }
963
- }
964
- const validatedEntries = validateEntryScopes(entriesCopy, context.scopes, context.categories);
965
- for (const [category, rawIndices] of Object.entries(categoryMap)) {
966
- const indices = Array.isArray(rawIndices) ? rawIndices : [];
967
- const categoryEntries = indices.map((i) => validatedEntries[i]).filter((e) => e !== void 0);
968
- if (categoryEntries.length > 0) {
969
- result.push({ category, entries: categoryEntries });
970
- }
971
- }
972
- } else {
973
- const categoryMap = parsed;
974
- for (const [category, rawIndices] of Object.entries(categoryMap)) {
975
- const indices = Array.isArray(rawIndices) ? rawIndices : [];
976
- const categoryEntries = indices.map((i) => entriesCopy[i]).filter((e) => e !== void 0);
977
- if (categoryEntries.length > 0) {
978
- result.push({ category, entries: categoryEntries });
979
- }
980
- }
981
- }
982
- return result;
983
- } catch (error2) {
984
- warn(
985
- `LLM categorization failed, falling back to General: ${error2 instanceof Error ? error2.message : String(error2)}`
1458
+ return await withCorrectiveRetry(
1459
+ (messages, isFirstAttempt) => provider.complete(
1460
+ messages,
1461
+ isFirstAttempt && provider.capabilities.structuredOutputs ? { schema, toolName: "categorize_entries" } : void 0
1462
+ ),
1463
+ validate,
1464
+ buildCorrectionMessages,
1465
+ initialMessages
986
1466
  );
987
- return [{ category: "General", entries: entriesCopy }];
1467
+ } catch (error2) {
1468
+ if (error2 instanceof LLMError) {
1469
+ warn(`categorizeEntries failed after all attempts: ${error2.message}. Returning entries under General.`);
1470
+ return [{ category: "General", entries: entries.map((e) => ({ ...e, scope: void 0 })) }];
1471
+ }
1472
+ throw error2;
988
1473
  }
989
1474
  }
990
1475
 
991
1476
  // src/llm/tasks/enhance.ts
992
- var DEFAULT_ENHANCE_PROMPT = `You are improving changelog entries for a software project.
1477
+ function buildSystemPrompt2(style) {
1478
+ const styleText = style ? `- ${style}` : '- Use past tense ("Added feature" not "Add feature")';
1479
+ return `You are improving changelog entries for a software project.
993
1480
  Given a technical commit message, rewrite it as a clear, user-friendly changelog entry.
994
1481
 
995
1482
  Rules:
@@ -997,20 +1484,26 @@ Rules:
997
1484
  - Focus on user impact, not implementation details
998
1485
  - Don't use technical jargon unless necessary
999
1486
  - Preserve the scope if mentioned (e.g., "core:", "api:")
1000
- {{style}}
1487
+ ${styleText}
1001
1488
 
1002
- Original entry:
1003
- Type: {{type}}
1004
- {{#if scope}}Scope: {{scope}}{{/if}}
1005
- Description: {{description}}
1006
-
1007
- Rewritten description (only output the new description, nothing else):`;
1489
+ Output only the rewritten description, nothing else.`;
1490
+ }
1491
+ function buildUserPrompt2(entry) {
1492
+ const lines = [`Type: ${entry.type}`];
1493
+ if (entry.scope) lines.push(`Scope: ${entry.scope}`);
1494
+ lines.push(`Description: ${entry.description}`);
1495
+ const prBlocks = renderPRBlocks(entry);
1496
+ if (prBlocks) lines.push(prBlocks);
1497
+ return lines.join("\n");
1498
+ }
1008
1499
  async function enhanceEntry(provider, entry, context) {
1009
- const styleText = context.style ? `- ${context.style}` : '- Use present tense ("Add feature" not "Added feature")';
1010
- const defaultPrompt = DEFAULT_ENHANCE_PROMPT.replace("{{style}}", styleText).replace("{{type}}", entry.type).replace("{{#if scope}}Scope: {{scope}}{{/if}}", entry.scope ? `Scope: ${entry.scope}` : "").replace("{{description}}", entry.description);
1011
- const prompt = resolvePrompt("enhance", defaultPrompt, context.prompts);
1012
- const response = await provider.complete(prompt);
1013
- return response.trim();
1500
+ const systemPrompt = resolveSystemPrompt("enhance", buildSystemPrompt2(context.style), context.prompts);
1501
+ const messages = [
1502
+ { role: "system", content: systemPrompt },
1503
+ { role: "user", content: buildUserPrompt2(entry) }
1504
+ ];
1505
+ const result = await provider.complete(messages);
1506
+ return result.content.trim();
1014
1507
  }
1015
1508
  async function enhanceEntries(provider, entries, context, concurrency = LLM_DEFAULTS.concurrency) {
1016
1509
  const results = [];
@@ -1031,57 +1524,25 @@ async function enhanceEntries(provider, entries, context, concurrency = LLM_DEFA
1031
1524
  return results;
1032
1525
  }
1033
1526
 
1034
- // src/utils/retry.ts
1035
- function sleep(ms) {
1036
- return new Promise((resolve2) => setTimeout(resolve2, ms));
1037
- }
1038
- async function withRetry(fn, options = {}) {
1039
- const maxAttempts = options.maxAttempts ?? 3;
1040
- const initialDelay = options.initialDelay ?? 1e3;
1041
- const maxDelay = options.maxDelay ?? 3e4;
1042
- const backoffFactor = options.backoffFactor ?? 2;
1043
- let lastError;
1044
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
1045
- try {
1046
- return await fn();
1047
- } catch (error2) {
1048
- lastError = error2;
1049
- if (attempt < maxAttempts - 1) {
1050
- const base = Math.min(initialDelay * backoffFactor ** attempt, maxDelay);
1051
- const jitter = base * 0.2 * (Math.random() * 2 - 1);
1052
- await sleep(Math.max(0, base + jitter));
1053
- }
1054
- }
1055
- }
1056
- throw lastError;
1057
- }
1058
-
1059
1527
  // src/llm/tasks/enhance-and-categorize.ts
1060
- function buildPrompt(entries, categories, style) {
1061
- const entriesText = entries.map((e, i) => `${i}. [${e.type}]${e.scope ? ` (${e.scope})` : ""}: ${e.description}`).join("\n");
1062
- const styleText = style || 'Use present tense ("Add feature" not "Added feature"). Be concise.';
1063
- const categorySection = categories ? `Categories (use ONLY these):
1528
+ function buildSystemPrompt3(categories, style) {
1529
+ const styleText = style || 'Use past tense ("Added feature" not "Add feature"). Be concise.';
1530
+ const categorySection = categories && categories.length > 0 ? `Categories (use ONLY these exact names):
1064
1531
  ${categories.map((c) => {
1065
1532
  const scopeInfo = c.scopes?.length ? ` Allowed scopes: ${c.scopes.join(", ")}.` : "";
1066
1533
  return `- "${c.name}": ${c.description}${scopeInfo}`;
1067
1534
  }).join("\n")}` : `Categories: Group into meaningful categories (e.g., "New", "Fixed", "Changed", "Removed").`;
1068
1535
  let scopeInstruction = "";
1069
- if (categories) {
1070
- const scopeMap = getAllowedScopesFromCategories(categories);
1071
- if (scopeMap.size > 0) {
1072
- const parts = [];
1073
- for (const [catName, scopes] of scopeMap) {
1074
- parts.push(`For "${catName}" entries, assign a scope from: ${scopes.join(", ")}.`);
1075
- }
1536
+ if (categories && categories.length > 0) {
1537
+ const withScopes = categories.filter((c) => c.scopes?.length);
1538
+ if (withScopes.length > 0) {
1539
+ const parts = withScopes.map((c) => `For "${c.name}" entries, use a scope from: ${c.scopes?.join(", ")}.`);
1076
1540
  scopeInstruction = `
1077
1541
  ${parts.join("\n")}
1078
1542
  Only use scopes from these predefined lists. Set scope to null if no scope applies.`;
1079
1543
  }
1080
1544
  }
1081
- return `You are generating release notes for a software project. Given the following changelog entries, do two things:
1082
-
1083
- 1. **Rewrite** each entry as a clear, user-friendly description
1084
- 2. **Categorize** each entry into the appropriate category
1545
+ return `You are generating release notes for a software project. Given changelog entries, rewrite each as a clear user-friendly description and categorize it.
1085
1546
 
1086
1547
  Style guidelines:
1087
1548
  - ${styleText}
@@ -1090,70 +1551,130 @@ Style guidelines:
1090
1551
 
1091
1552
  ${categorySection}${scopeInstruction}
1092
1553
 
1093
- Entries:
1094
- ${entriesText}
1554
+ leadIn guidelines:
1555
+ - Set leadIn ONLY when an entry introduces a named API, feature, or concept worth scanning for (e.g. "Deeplink testing", "browser.electron.triggerDeeplink()")
1556
+ - Leave leadIn null for routine fixes, dependency bumps, small tweaks, and refactors
1095
1557
 
1096
- Output a JSON object with:
1097
- - "entries": array of objects, one per input entry (same order), each with: { "description": "rewritten text", "category": "CategoryName", "scope": "optional subcategory label or null" }
1558
+ Output a JSON object with an "entries" array. Each element (same order as input) must have:
1559
+ - "description": rewritten user-friendly text
1560
+ - "category": category name (from the list above)
1561
+ - "scope": subcategory label or null
1562
+ - "breaking": true if this is a breaking change, false or null otherwise
1563
+ - "leadIn": short noun phrase for scanning (e.g. "Streaming API") or null`;
1564
+ }
1565
+ function buildUserPrompt3(entries) {
1566
+ const entriesText = entries.map((e, i) => {
1567
+ const prBlocks = renderPRBlocks(e);
1568
+ const header = `${i}. [${e.type}]${e.scope ? ` (${e.scope})` : ""}: ${e.description}`;
1569
+ return prBlocks ? `${header}
1570
+ ${prBlocks}` : header;
1571
+ }).join("\n");
1572
+ return `Entries:
1573
+ ${entriesText}`;
1574
+ }
1575
+ function buildCorrectionMessages2(_badContent, error2) {
1576
+ return [
1577
+ {
1578
+ role: "user",
1579
+ content: `Your previous response had an error: ${error2}
1098
1580
 
1099
- Output only valid JSON, nothing else:`;
1581
+ Please fix the issue and output only valid JSON matching the required schema.`
1582
+ }
1583
+ ];
1584
+ }
1585
+ function makeValidator2(entries, context) {
1586
+ return (result) => {
1587
+ let parsed;
1588
+ try {
1589
+ parsed = typeof result.structured !== "undefined" ? result.structured : JSON.parse(extractJsonFromResponse(result.content));
1590
+ } catch (e) {
1591
+ return { valid: false, error: `Invalid JSON: ${e instanceof Error ? e.message : String(e)}` };
1592
+ }
1593
+ const zodResult = EnhanceAndCategorizeOutputSchema.safeParse(parsed);
1594
+ if (!zodResult.success) {
1595
+ return { valid: false, error: `Schema error: ${zodResult.error.message}` };
1596
+ }
1597
+ if (zodResult.data.entries.length !== entries.length) {
1598
+ return {
1599
+ valid: false,
1600
+ error: `Expected ${entries.length} entries, got ${zodResult.data.entries.length}`
1601
+ };
1602
+ }
1603
+ const categoryNames = context.categories?.map((c) => c.name);
1604
+ if (categoryNames?.length) {
1605
+ const invalid = zodResult.data.entries.filter((e) => !categoryNames.includes(e.category)).map((e) => e.category);
1606
+ if (invalid.length > 0) {
1607
+ const unique = [...new Set(invalid)];
1608
+ return {
1609
+ valid: false,
1610
+ error: `Unknown categories: ${unique.join(", ")}. Valid categories: ${categoryNames.join(", ")}`
1611
+ };
1612
+ }
1613
+ }
1614
+ const enhancedEntries = entries.map((original, i) => {
1615
+ const llmEntry = zodResult.data.entries[i];
1616
+ if (!llmEntry) return original;
1617
+ return {
1618
+ ...original,
1619
+ description: llmEntry.description,
1620
+ scope: llmEntry.scope ?? void 0,
1621
+ breaking: llmEntry.breaking ?? original.breaking,
1622
+ leadIn: llmEntry.leadIn ?? void 0
1623
+ };
1624
+ });
1625
+ const scopeResult = validateEntryScopes(enhancedEntries, context.scopes, context.categories);
1626
+ if (!scopeResult.valid) {
1627
+ const msg = scopeResult.errors.map(
1628
+ (e) => `entry ${e.entryIndex} scope "${e.providedScope}" (${e.allowedScopes.length ? `valid: ${e.allowedScopes.join(", ")}` : "no scopes permitted"})`
1629
+ ).join("; ");
1630
+ return { valid: false, error: `Invalid scopes: ${msg}` };
1631
+ }
1632
+ const categories = groupByCategory(zodResult.data.entries, scopeResult.entries);
1633
+ return {
1634
+ valid: true,
1635
+ value: { enhancedEntries: scopeResult.entries, categories }
1636
+ };
1637
+ };
1100
1638
  }
1101
1639
  async function enhanceAndCategorize(provider, entries, context) {
1102
1640
  if (entries.length === 0) {
1103
1641
  return { enhancedEntries: [], categories: [] };
1104
1642
  }
1105
- const retryOpts = LLM_DEFAULTS.retry;
1643
+ const basePrompt = buildSystemPrompt3(context.categories, context.style);
1644
+ const examplesBlock = renderExamplesBlock(context.examples ?? []);
1645
+ const systemPrompt = resolveSystemPrompt(
1646
+ "enhanceAndCategorize",
1647
+ examplesBlock ? `${basePrompt}${examplesBlock}` : basePrompt,
1648
+ context.prompts
1649
+ );
1650
+ const initialMessages = [
1651
+ { role: "system", content: systemPrompt },
1652
+ { role: "user", content: buildUserPrompt3(entries) }
1653
+ ];
1654
+ const schema = buildEnhanceAndCategorizeSchema(context.categories ?? []);
1655
+ const validate = makeValidator2(entries, context);
1106
1656
  try {
1107
- return await withRetry(async () => {
1108
- const defaultPrompt = buildPrompt(entries, context.categories, context.style);
1109
- const prompt = resolvePrompt("enhanceAndCategorize", defaultPrompt, context.prompts);
1110
- const response = await provider.complete(prompt);
1111
- const parsed = JSON.parse(extractJsonFromResponse(response));
1112
- if (!Array.isArray(parsed.entries)) {
1113
- throw new Error('Response missing "entries" array');
1114
- }
1115
- const enhancedEntries = entries.map((original, i) => {
1116
- const result = parsed.entries[i];
1117
- if (!result) return original;
1118
- return {
1119
- ...original,
1120
- description: result.description || original.description,
1121
- scope: result.scope || original.scope
1122
- };
1123
- });
1124
- const validatedEntries = validateEntryScopes(enhancedEntries, context.scopes, context.categories);
1125
- const categoryMap = /* @__PURE__ */ new Map();
1126
- for (let i = 0; i < parsed.entries.length; i++) {
1127
- const result = parsed.entries[i];
1128
- const category = result?.category || "General";
1129
- const entry = validatedEntries[i];
1130
- if (!entry) continue;
1131
- if (!categoryMap.has(category)) {
1132
- categoryMap.set(category, []);
1133
- }
1134
- categoryMap.get(category)?.push(entry);
1135
- }
1136
- const categories = [];
1137
- for (const [category, catEntries] of categoryMap) {
1138
- categories.push({ category, entries: catEntries });
1139
- }
1140
- return { enhancedEntries: validatedEntries, categories };
1141
- }, retryOpts);
1142
- } catch (error2) {
1143
- warn(
1144
- `Combined enhance+categorize failed after ${retryOpts.maxAttempts} attempts: ${error2 instanceof Error ? error2.message : String(error2)}`
1657
+ return await withCorrectiveRetry(
1658
+ (messages, isFirstAttempt) => provider.complete(
1659
+ messages,
1660
+ isFirstAttempt && provider.capabilities.structuredOutputs ? { schema, toolName: "emit_release_notes" } : void 0
1661
+ ),
1662
+ validate,
1663
+ buildCorrectionMessages2,
1664
+ initialMessages
1145
1665
  );
1146
- return {
1147
- enhancedEntries: entries,
1148
- categories: [{ category: "General", entries }]
1149
- };
1666
+ } catch (error2) {
1667
+ if (error2 instanceof LLMError) {
1668
+ warn(`enhanceAndCategorize failed after all attempts: ${error2.message}. Returning entries ungrouped.`);
1669
+ const stripped = entries.map((e) => ({ ...e, scope: void 0, leadIn: void 0 }));
1670
+ return { enhancedEntries: stripped, categories: [{ category: "General", entries: stripped }] };
1671
+ }
1672
+ throw error2;
1150
1673
  }
1151
1674
  }
1152
1675
 
1153
1676
  // src/llm/tasks/release-notes.ts
1154
- var DEFAULT_RELEASE_NOTES_PROMPT = `You are writing release notes for a software project.
1155
-
1156
- Create engaging, user-friendly release notes for the following changes.
1677
+ var DEFAULT_SYSTEM_PROMPT = `You are writing release notes for a software project.
1157
1678
 
1158
1679
  Rules:
1159
1680
  - Start with a brief introduction (1-2 sentences)
@@ -1163,54 +1684,68 @@ Rules:
1163
1684
  - End with a brief conclusion or call to action
1164
1685
  - Use markdown formatting
1165
1686
 
1166
- Version: {{version}}
1167
- {{#if previousVersion}}Previous version: {{previousVersion}}{{/if}}
1168
- Date: {{date}}
1687
+ Output only the markdown content.`;
1688
+ function buildUserPrompt4(entries, context) {
1689
+ const version = context.version ?? "v1.0.0";
1690
+ const date = context.date ?? (/* @__PURE__ */ new Date()).toISOString().split("T")[0] ?? "";
1691
+ const prevLine = context.previousVersion ? `Previous version: ${context.previousVersion}
1692
+ ` : "";
1693
+ const entriesText = entries.map((e) => {
1694
+ let line = `- [${e.type}]`;
1695
+ if (e.scope) line += ` (${e.scope})`;
1696
+ line += `: ${e.description}`;
1697
+ if (e.breaking) line += " **BREAKING**";
1698
+ const prBlocks = renderPRBlocks(e);
1699
+ if (prBlocks) line += `
1700
+ ${prBlocks}`;
1701
+ return line;
1702
+ }).join("\n");
1703
+ return `Version: ${version}
1704
+ ${prevLine}Date: ${date}
1169
1705
 
1170
1706
  Changes:
1171
- {{entries}}
1172
-
1173
- Release notes (output only the markdown content):`;
1707
+ ${entriesText}`;
1708
+ }
1174
1709
  async function generateReleaseNotes(provider, entries, context) {
1175
1710
  if (entries.length === 0) {
1176
1711
  return `## Release ${context.version ?? "v1.0.0"}
1177
1712
 
1178
1713
  No notable changes in this release.`;
1179
1714
  }
1180
- const entriesText = entries.map((e) => {
1181
- let line = `- [${e.type}]`;
1182
- if (e.scope) line += ` (${e.scope})`;
1183
- line += `: ${e.description}`;
1184
- if (e.breaking) line += " **BREAKING**";
1185
- return line;
1186
- }).join("\n");
1187
- const defaultPrompt = DEFAULT_RELEASE_NOTES_PROMPT.replace("{{version}}", context.version ?? "v1.0.0").replace(
1188
- "{{#if previousVersion}}Previous version: {{previousVersion}}{{/if}}",
1189
- context.previousVersion ? `Previous version: ${context.previousVersion}` : ""
1190
- ).replace("{{date}}", context.date ?? (/* @__PURE__ */ new Date()).toISOString().split("T")[0] ?? "").replace("{{entries}}", entriesText);
1191
- const prompt = resolvePrompt("releaseNotes", defaultPrompt, context.prompts);
1192
- const response = await provider.complete(prompt);
1193
- return response.trim();
1715
+ const examplesBlock = renderExamplesBlock(context.examples ?? []);
1716
+ const systemPrompt = resolveSystemPrompt(
1717
+ "releaseNotes",
1718
+ examplesBlock ? `${DEFAULT_SYSTEM_PROMPT}${examplesBlock}` : DEFAULT_SYSTEM_PROMPT,
1719
+ context.prompts
1720
+ );
1721
+ const messages = [
1722
+ { role: "system", content: systemPrompt },
1723
+ { role: "user", content: buildUserPrompt4(entries, context) }
1724
+ ];
1725
+ const result = await provider.complete(messages);
1726
+ return result.content.trim();
1194
1727
  }
1195
1728
 
1196
1729
  // src/llm/tasks/summarize.ts
1197
- var DEFAULT_SUMMARIZE_PROMPT = `You are creating a summary of changes for a software release.
1198
-
1199
- Given the following changelog entries, create a brief summary (2-3 sentences) that captures the main themes of this release.
1200
-
1201
- Entries:
1202
- {{entries}}
1203
-
1204
- Summary (only output the summary, nothing else):`;
1730
+ var DEFAULT_SYSTEM_PROMPT2 = `You are creating a summary of changes for a software release.
1731
+ Create a brief summary (2-3 sentences) that captures the main themes of this release.
1732
+ Output only the summary text, nothing else.`;
1733
+ function buildUserPrompt5(entries) {
1734
+ const text = entries.map((e) => `- [${e.type}]${e.scope ? ` (${e.scope})` : ""}: ${e.description}`).join("\n");
1735
+ return `Entries:
1736
+ ${text}`;
1737
+ }
1205
1738
  async function summarizeEntries(provider, entries, context) {
1206
1739
  if (entries.length === 0) {
1207
1740
  return "";
1208
1741
  }
1209
- const entriesText = entries.map((e) => `- [${e.type}]${e.scope ? ` (${e.scope})` : ""}: ${e.description}`).join("\n");
1210
- const defaultPrompt = DEFAULT_SUMMARIZE_PROMPT.replace("{{entries}}", entriesText);
1211
- const prompt = resolvePrompt("summarize", defaultPrompt, context.prompts);
1212
- const response = await provider.complete(prompt);
1213
- return response.trim();
1742
+ const systemPrompt = resolveSystemPrompt("summarize", DEFAULT_SYSTEM_PROMPT2, context.prompts);
1743
+ const messages = [
1744
+ { role: "system", content: systemPrompt },
1745
+ { role: "user", content: buildUserPrompt5(entries) }
1746
+ ];
1747
+ const result = await provider.complete(messages);
1748
+ return result.content.trim();
1214
1749
  }
1215
1750
 
1216
1751
  // src/llm/index.ts
@@ -1251,7 +1786,7 @@ function createProvider(config) {
1251
1786
  }
1252
1787
 
1253
1788
  // src/templates/ejs.ts
1254
- import * as fs5 from "fs";
1789
+ import * as fs6 from "fs";
1255
1790
  import ejs from "ejs";
1256
1791
  function renderEjs(template, context) {
1257
1792
  try {
@@ -1261,16 +1796,16 @@ function renderEjs(template, context) {
1261
1796
  }
1262
1797
  }
1263
1798
  function renderEjsFile(filePath, context) {
1264
- if (!fs5.existsSync(filePath)) {
1799
+ if (!fs6.existsSync(filePath)) {
1265
1800
  throw new TemplateError(`Template file not found: ${filePath}`);
1266
1801
  }
1267
- const template = fs5.readFileSync(filePath, "utf-8");
1802
+ const template = fs6.readFileSync(filePath, "utf-8");
1268
1803
  return renderEjs(template, context);
1269
1804
  }
1270
1805
 
1271
1806
  // src/templates/handlebars.ts
1272
- import * as fs6 from "fs";
1273
- import * as path5 from "path";
1807
+ import * as fs7 from "fs";
1808
+ import * as path6 from "path";
1274
1809
  import Handlebars from "handlebars";
1275
1810
  function registerHandlebarsHelpers() {
1276
1811
  Handlebars.registerHelper("capitalize", (str) => {
@@ -1296,28 +1831,28 @@ function renderHandlebars(template, context) {
1296
1831
  }
1297
1832
  }
1298
1833
  function renderHandlebarsFile(filePath, context) {
1299
- if (!fs6.existsSync(filePath)) {
1834
+ if (!fs7.existsSync(filePath)) {
1300
1835
  throw new TemplateError(`Template file not found: ${filePath}`);
1301
1836
  }
1302
- const template = fs6.readFileSync(filePath, "utf-8");
1837
+ const template = fs7.readFileSync(filePath, "utf-8");
1303
1838
  return renderHandlebars(template, context);
1304
1839
  }
1305
1840
  function renderHandlebarsComposable(templateDir, context) {
1306
1841
  registerHandlebarsHelpers();
1307
- const versionPath = path5.join(templateDir, "version.hbs");
1308
- const entryPath = path5.join(templateDir, "entry.hbs");
1309
- const documentPath = path5.join(templateDir, "document.hbs");
1310
- if (!fs6.existsSync(documentPath)) {
1842
+ const versionPath = path6.join(templateDir, "version.hbs");
1843
+ const entryPath = path6.join(templateDir, "entry.hbs");
1844
+ const documentPath = path6.join(templateDir, "document.hbs");
1845
+ if (!fs7.existsSync(documentPath)) {
1311
1846
  throw new TemplateError(`Document template not found: ${documentPath}`);
1312
1847
  }
1313
- if (fs6.existsSync(versionPath)) {
1314
- Handlebars.registerPartial("version", fs6.readFileSync(versionPath, "utf-8"));
1848
+ if (fs7.existsSync(versionPath)) {
1849
+ Handlebars.registerPartial("version", fs7.readFileSync(versionPath, "utf-8"));
1315
1850
  }
1316
- if (fs6.existsSync(entryPath)) {
1317
- Handlebars.registerPartial("entry", fs6.readFileSync(entryPath, "utf-8"));
1851
+ if (fs7.existsSync(entryPath)) {
1852
+ Handlebars.registerPartial("entry", fs7.readFileSync(entryPath, "utf-8"));
1318
1853
  }
1319
1854
  try {
1320
- const compiled = Handlebars.compile(fs6.readFileSync(documentPath, "utf-8"));
1855
+ const compiled = Handlebars.compile(fs7.readFileSync(documentPath, "utf-8"));
1321
1856
  return compiled(context);
1322
1857
  } catch (error2) {
1323
1858
  throw new TemplateError(`Handlebars render error: ${error2 instanceof Error ? error2.message : String(error2)}`);
@@ -1325,8 +1860,8 @@ function renderHandlebarsComposable(templateDir, context) {
1325
1860
  }
1326
1861
 
1327
1862
  // src/templates/liquid.ts
1328
- import * as fs7 from "fs";
1329
- import * as path6 from "path";
1863
+ import * as fs8 from "fs";
1864
+ import * as path7 from "path";
1330
1865
  import { Liquid } from "liquidjs";
1331
1866
  function createLiquidEngine(root) {
1332
1867
  return new Liquid({
@@ -1344,15 +1879,15 @@ function renderLiquid(template, context) {
1344
1879
  }
1345
1880
  }
1346
1881
  function renderLiquidFile(filePath, context) {
1347
- if (!fs7.existsSync(filePath)) {
1882
+ if (!fs8.existsSync(filePath)) {
1348
1883
  throw new TemplateError(`Template file not found: ${filePath}`);
1349
1884
  }
1350
- const template = fs7.readFileSync(filePath, "utf-8");
1885
+ const template = fs8.readFileSync(filePath, "utf-8");
1351
1886
  return renderLiquid(template, context);
1352
1887
  }
1353
1888
  function renderLiquidComposable(templateDir, context) {
1354
- const documentPath = path6.join(templateDir, "document.liquid");
1355
- if (!fs7.existsSync(documentPath)) {
1889
+ const documentPath = path7.join(templateDir, "document.liquid");
1890
+ if (!fs8.existsSync(documentPath)) {
1356
1891
  throw new TemplateError(`Document template not found: ${documentPath}`);
1357
1892
  }
1358
1893
  const engine = createLiquidEngine(templateDir);
@@ -1364,10 +1899,10 @@ function renderLiquidComposable(templateDir, context) {
1364
1899
  }
1365
1900
 
1366
1901
  // src/templates/loader.ts
1367
- import * as fs8 from "fs";
1368
- import * as path7 from "path";
1902
+ import * as fs9 from "fs";
1903
+ import * as path8 from "path";
1369
1904
  function getEngineFromFile(filePath) {
1370
- const ext = path7.extname(filePath).toLowerCase();
1905
+ const ext = path8.extname(filePath).toLowerCase();
1371
1906
  switch (ext) {
1372
1907
  case ".liquid":
1373
1908
  return "liquid";
@@ -1401,10 +1936,10 @@ function getRenderFileFn(engine) {
1401
1936
  }
1402
1937
  }
1403
1938
  function detectTemplateMode(templatePath) {
1404
- if (!fs8.existsSync(templatePath)) {
1939
+ if (!fs9.existsSync(templatePath)) {
1405
1940
  throw new TemplateError(`Template path not found: ${templatePath}`);
1406
1941
  }
1407
- const stat = fs8.statSync(templatePath);
1942
+ const stat = fs9.statSync(templatePath);
1408
1943
  if (stat.isFile()) {
1409
1944
  return "single";
1410
1945
  }
@@ -1422,7 +1957,7 @@ function renderSingleFile(templatePath, context, engine) {
1422
1957
  };
1423
1958
  }
1424
1959
  function renderComposable(templateDir, context, engine) {
1425
- const files = fs8.readdirSync(templateDir);
1960
+ const files = fs9.readdirSync(templateDir);
1426
1961
  const engineMap = {
1427
1962
  liquid: { document: "document.liquid", version: "version.liquid", entry: "entry.liquid" },
1428
1963
  handlebars: { document: "document.hbs", version: "version.hbs", entry: "entry.hbs" },
@@ -1445,15 +1980,15 @@ function renderComposable(templateDir, context, engine) {
1445
1980
  return { content: renderHandlebarsComposable(templateDir, context), engine: resolvedEngine };
1446
1981
  }
1447
1982
  const expectedFiles = engineMap[resolvedEngine];
1448
- const documentPath = path7.join(templateDir, expectedFiles.document);
1449
- if (!fs8.existsSync(documentPath)) {
1983
+ const documentPath = path8.join(templateDir, expectedFiles.document);
1984
+ if (!fs9.existsSync(documentPath)) {
1450
1985
  throw new TemplateError(`Document template not found: ${expectedFiles.document}`);
1451
1986
  }
1452
- const versionPath = path7.join(templateDir, expectedFiles.version);
1453
- const entryPath = path7.join(templateDir, expectedFiles.entry);
1987
+ const versionPath = path8.join(templateDir, expectedFiles.version);
1988
+ const entryPath = path8.join(templateDir, expectedFiles.entry);
1454
1989
  const render = getRenderFn(resolvedEngine);
1455
- const entryTemplate = fs8.existsSync(entryPath) ? fs8.readFileSync(entryPath, "utf-8") : null;
1456
- const versionTemplate = fs8.existsSync(versionPath) ? fs8.readFileSync(versionPath, "utf-8") : null;
1990
+ const entryTemplate = fs9.existsSync(entryPath) ? fs9.readFileSync(entryPath, "utf-8") : null;
1991
+ const versionTemplate = fs9.existsSync(versionPath) ? fs9.readFileSync(versionPath, "utf-8") : null;
1457
1992
  if (entryTemplate && versionTemplate) {
1458
1993
  const versionsWithEntries = context.versions.map((versionCtx) => {
1459
1994
  const entries = versionCtx.entries.map((entry) => {
@@ -1464,7 +1999,7 @@ function renderComposable(templateDir, context, engine) {
1464
1999
  });
1465
2000
  const docContext = { ...context, renderedVersions: versionsWithEntries };
1466
2001
  return {
1467
- content: render(fs8.readFileSync(documentPath, "utf-8"), docContext),
2002
+ content: render(fs9.readFileSync(documentPath, "utf-8"), docContext),
1468
2003
  engine: resolvedEngine
1469
2004
  };
1470
2005
  }
@@ -1504,7 +2039,44 @@ function renderTemplate(templatePath, context, engine) {
1504
2039
  return renderComposable(templatePath, context, engine);
1505
2040
  }
1506
2041
 
2042
+ // src/utils/retry.ts
2043
+ function sleep(ms) {
2044
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
2045
+ }
2046
+ async function withRetry(fn, options = {}) {
2047
+ const maxAttempts = options.maxAttempts ?? 3;
2048
+ const initialDelay = options.initialDelay ?? 1e3;
2049
+ const maxDelay = options.maxDelay ?? 3e4;
2050
+ const backoffFactor = options.backoffFactor ?? 2;
2051
+ let lastError;
2052
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
2053
+ try {
2054
+ return await fn();
2055
+ } catch (error2) {
2056
+ lastError = error2;
2057
+ if (attempt < maxAttempts - 1) {
2058
+ const base = Math.min(initialDelay * backoffFactor ** attempt, maxDelay);
2059
+ const jitter = base * 0.2 * (Math.random() * 2 - 1);
2060
+ await sleep(Math.max(0, base + jitter));
2061
+ }
2062
+ }
2063
+ }
2064
+ throw lastError;
2065
+ }
2066
+
1507
2067
  // src/core/pipeline.ts
2068
+ function parseOwnerRepo(repoUrl) {
2069
+ const scpMatch = repoUrl.match(/^git@github\.com:([^/]+)\/(.+?)(?:\.git)?$/);
2070
+ if (scpMatch) return { owner: scpMatch[1], repo: scpMatch[2] };
2071
+ try {
2072
+ const url = new URL(repoUrl);
2073
+ if (url.hostname !== "github.com") return null;
2074
+ const parts = url.pathname.replace(/^\//, "").replace(/\.git$/, "").split("/");
2075
+ if (parts.length >= 2) return { owner: parts[0], repo: parts[1] };
2076
+ } catch {
2077
+ }
2078
+ return null;
2079
+ }
1508
2080
  function findCompoundTagSepPos(tag) {
1509
2081
  let pos = tag.lastIndexOf("-");
1510
2082
  while (pos > 0) {
@@ -1590,7 +2162,7 @@ function createDocumentContext(contexts, repoUrl) {
1590
2162
  compareUrls: Object.keys(compareUrls).length > 0 ? compareUrls : void 0
1591
2163
  };
1592
2164
  }
1593
- async function processWithLLM(context, llmConfig) {
2165
+ async function processWithLLM(context, llmConfig, examples) {
1594
2166
  const tasks = llmConfig.tasks ?? {};
1595
2167
  const llmContext = {
1596
2168
  packageName: context.packageName,
@@ -1600,7 +2172,8 @@ async function processWithLLM(context, llmConfig) {
1600
2172
  categories: llmConfig.categories,
1601
2173
  style: llmConfig.style,
1602
2174
  scopes: llmConfig.scopes,
1603
- prompts: llmConfig.prompts
2175
+ prompts: llmConfig.prompts,
2176
+ examples
1604
2177
  };
1605
2178
  const enhanced = {
1606
2179
  entries: context.entries
@@ -1615,7 +2188,8 @@ async function processWithLLM(context, llmConfig) {
1615
2188
  const configOptions = llmConfig.options;
1616
2189
  const provider = {
1617
2190
  name: rawProvider.name,
1618
- complete: (prompt, opts) => withRetry(() => rawProvider.complete(prompt, { ...configOptions, ...opts }), retryOpts)
2191
+ capabilities: rawProvider.capabilities,
2192
+ complete: (messages, opts) => withRetry(() => rawProvider.complete(messages, { ...configOptions, ...opts }), retryOpts)
1619
2193
  };
1620
2194
  const activeTasks = Object.entries(tasks).filter(([, enabled]) => enabled).map(([name]) => name);
1621
2195
  info(`Running LLM tasks: ${activeTasks.join(", ")}`);
@@ -1663,7 +2237,7 @@ async function processWithLLM(context, llmConfig) {
1663
2237
  };
1664
2238
  } catch (error2) {
1665
2239
  warn(`LLM processing failed: ${error2 instanceof Error ? error2.message : String(error2)}`);
1666
- warn("Falling back to raw entries");
2240
+ warn("Falling back to non-LLM changelog rendering. Check your LLM config or set RELEASEKIT_DEBUG=1 for details.");
1667
2241
  return context;
1668
2242
  }
1669
2243
  }
@@ -1671,17 +2245,17 @@ function getBuiltinTemplatePath(style) {
1671
2245
  let packageRoot;
1672
2246
  try {
1673
2247
  const currentUrl = import.meta.url;
1674
- packageRoot = path8.dirname(new URL(currentUrl).pathname);
1675
- packageRoot = path8.join(packageRoot, "..", "..");
2248
+ packageRoot = path9.dirname(new URL(currentUrl).pathname);
2249
+ packageRoot = path9.join(packageRoot, "..", "..");
1676
2250
  } catch {
1677
2251
  packageRoot = __dirname;
1678
2252
  }
1679
- return path8.join(packageRoot, "templates", style);
2253
+ return path9.join(packageRoot, "templates", style);
1680
2254
  }
1681
2255
  async function generateWithTemplate(contexts, templatesConfig, outputPath, repoUrl, dryRun) {
1682
2256
  let templatePath;
1683
2257
  if (templatesConfig?.path) {
1684
- templatePath = path8.resolve(templatesConfig.path);
2258
+ templatePath = path9.resolve(templatesConfig.path);
1685
2259
  } else {
1686
2260
  templatePath = getBuiltinTemplatePath("keep-a-changelog");
1687
2261
  }
@@ -1696,11 +2270,11 @@ async function generateWithTemplate(contexts, templatesConfig, outputPath, repoU
1696
2270
  process.stdout.write(result.content);
1697
2271
  return;
1698
2272
  }
1699
- const dir = path8.dirname(outputPath);
1700
- if (!fs9.existsSync(dir)) {
1701
- fs9.mkdirSync(dir, { recursive: true });
2273
+ const dir = path9.dirname(outputPath);
2274
+ if (!fs10.existsSync(dir)) {
2275
+ fs10.mkdirSync(dir, { recursive: true });
1702
2276
  }
1703
- fs9.writeFileSync(outputPath, result.content, "utf-8");
2277
+ fs10.writeFileSync(outputPath, result.content, "utf-8");
1704
2278
  const label = /changelog/i.test(outputPath) ? "Changelog" : "Release notes";
1705
2279
  success(`${label} written to ${outputPath} (using ${result.engine} template)`);
1706
2280
  }
@@ -1712,11 +2286,62 @@ async function runPipeline(input, config, dryRun) {
1712
2286
  const llmConfig = releaseNotesConfig?.llm;
1713
2287
  if (llmConfig && !process.env.CHANGELOG_NO_LLM) {
1714
2288
  info("Processing with LLM enhancement");
1715
- contexts = await Promise.all(contexts.map((ctx) => processWithLLM(ctx, llmConfig)));
2289
+ const examplesCount = llmConfig.examples ?? 3;
2290
+ const repoUrl = contexts[0]?.repoUrl ?? input.metadata?.repoUrl;
2291
+ const ownerRepo = repoUrl ? parseOwnerRepo(repoUrl) : null;
2292
+ const examplesByPackage = /* @__PURE__ */ new Map();
2293
+ if (examplesCount > 0 && ownerRepo) {
2294
+ await Promise.all(
2295
+ contexts.map(async (ctx) => {
2296
+ const examples = await fetchExamples({
2297
+ owner: ownerRepo.owner,
2298
+ repo: ownerRepo.repo,
2299
+ packageName: ctx.packageName,
2300
+ count: examplesCount,
2301
+ isMonorepo: contexts.length > 1
2302
+ });
2303
+ examplesByPackage.set(ctx.packageName, examples);
2304
+ if (examples.length > 0) {
2305
+ debug(`Loaded ${examples.length} example(s) for ${ctx.packageName}`);
2306
+ }
2307
+ })
2308
+ );
2309
+ }
2310
+ const prCache = /* @__PURE__ */ new Map();
2311
+ const pullRequestsEnabled = llmConfig.context?.pullRequests !== false;
2312
+ if (pullRequestsEnabled && ownerRepo) {
2313
+ const allIssueNumbers = [
2314
+ ...new Set(contexts.flatMap((ctx) => ctx.entries.flatMap((e) => parseIssueNumbers(e.issueIds ?? []))))
2315
+ ];
2316
+ if (allIssueNumbers.length > 0) {
2317
+ const token = resolveGitHubToken();
2318
+ if (!token) {
2319
+ warn("No GitHub token available \u2014 skipping PR context fetch (set GITHUB_TOKEN to enable)");
2320
+ } else {
2321
+ debug(`Fetching PR context for ${allIssueNumbers.length} issue(s)`);
2322
+ await fetchPullRequestContext(ownerRepo.owner, ownerRepo.repo, allIssueNumbers, token, prCache);
2323
+ debug(`Loaded PR context for ${prCache.size} issue(s)`);
2324
+ }
2325
+ }
2326
+ }
2327
+ if (prCache.size > 0) {
2328
+ contexts = contexts.map((ctx) => ({
2329
+ ...ctx,
2330
+ entries: ctx.entries.map((entry) => {
2331
+ const prs = parseIssueNumbers(entry.issueIds ?? []).map((n) => prCache.get(n)).filter((pr) => pr != null);
2332
+ return prs.length > 0 ? { ...entry, context: { prs } } : entry;
2333
+ })
2334
+ }));
2335
+ }
2336
+ contexts = await Promise.all(
2337
+ contexts.map((ctx) => processWithLLM(ctx, llmConfig, examplesByPackage.get(ctx.packageName) ?? []))
2338
+ );
1716
2339
  }
1717
2340
  const files = [];
1718
2341
  const fmtOpts = {
1719
- includePackageName: contexts.length > 1 || contexts.some((c) => c.packageName.includes("/"))
2342
+ includePackageName: contexts.length > 1 || contexts.some((c) => c.packageName.includes("/")),
2343
+ categoryOrder: llmConfig?.categoryOrder,
2344
+ links: releaseNotesConfig?.links
1720
2345
  };
1721
2346
  if (changelogConfig !== false && changelogConfig.mode) {
1722
2347
  const fileName = changelogConfig.file ?? "CHANGELOG.md";
@@ -1786,7 +2411,7 @@ async function runPipeline(input, config, dryRun) {
1786
2411
  } else if (releaseNotesConfig) {
1787
2412
  if (releaseNotesConfig.templates?.path) {
1788
2413
  try {
1789
- const templatePath = path8.resolve(releaseNotesConfig.templates.path);
2414
+ const templatePath = path9.resolve(releaseNotesConfig.templates.path);
1790
2415
  const docCtx = { ...createDocumentContext([ctx], void 0), perPackage: true };
1791
2416
  const rendered = renderTemplate(
1792
2417
  templatePath,
@@ -1819,7 +2444,7 @@ async function processInput(inputJson, config, dryRun) {
1819
2444
  return runPipeline(input, config, dryRun);
1820
2445
  }
1821
2446
  async function writeMonorepoFiles(contexts, config, dryRun, fileName) {
1822
- const { detectMonorepo, writeMonorepoChangelogs } = await import("./aggregator-CGD3KEVU.js");
2447
+ const { detectMonorepo, writeMonorepoChangelogs } = await import("./aggregator-GXJXPM7O.js");
1823
2448
  const cwd = process.cwd();
1824
2449
  const detected = detectMonorepo(cwd);
1825
2450
  if (!detected.isMonorepo) return [];
@@ -1838,7 +2463,7 @@ async function writeMonorepoFiles(contexts, config, dryRun, fileName) {
1838
2463
  }
1839
2464
 
1840
2465
  // src/command.ts
1841
- import * as fs10 from "fs";
2466
+ import * as fs11 from "fs";
1842
2467
  import * as readline from "readline";
1843
2468
  import { Command } from "commander";
1844
2469
  function createNotesCommand() {
@@ -1941,7 +2566,7 @@ function createNotesCommand() {
1941
2566
  }
1942
2567
  let inputJson;
1943
2568
  if (options.input) {
1944
- inputJson = fs10.readFileSync(options.input, "utf-8");
2569
+ inputJson = fs11.readFileSync(options.input, "utf-8");
1945
2570
  } else {
1946
2571
  inputJson = await readStdin();
1947
2572
  }