@releasekit/notes 0.32.1 → 0.34.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.
package/README.md CHANGED
@@ -1,5 +1,8 @@
1
1
  # @releasekit/notes
2
2
 
3
+ > [!WARNING]
4
+ > 🚧 **Pre-1.0.0** — ReleaseKit is evolving fast and **💥 breaking changes are common**; it's **not production-ready** until `v1.0.0`. Pin exact versions. See the [main README](../../README.md) for details.
5
+
3
6
  [![@releasekit/notes](https://img.shields.io/badge/@releasekit-notes-9feaf9?labelColor=1a1a1a&style=plastic)](https://www.npmjs.com/package/@releasekit/notes)
4
7
  [![Version](https://img.shields.io/npm/v/@releasekit/notes?color=28a745&labelColor=1a1a1a)](https://www.npmjs.com/package/@releasekit/notes)
5
8
  [![Downloads](https://img.shields.io/npm/dw/@releasekit/notes?color=6f42c1&labelColor=1a1a1a)](https://www.npmjs.com/package/@releasekit/notes)
@@ -65,14 +65,8 @@ var GitConfigSchema = z.object({
65
65
  skipHooks: z.boolean().optional().describe("Skip Git hooks when committing")
66
66
  });
67
67
  var MonorepoConfigSchema = z.object({
68
- mode: z.enum(["root", "packages", "both"]).optional().describe("Changelog aggregation mode"),
69
68
  rootPath: z.string().optional().describe("Path to root changelog"),
70
- packagesPath: z.string().optional().describe("Path to packages directory"),
71
- mainPackage: z.string().optional().describe("Main package name for versioning")
72
- });
73
- var BranchPatternSchema = z.object({
74
- pattern: z.string().describe("Glob or regex matched against the branch name (e.g. 'release/*')"),
75
- releaseType: z.enum(["major", "minor", "patch", "prerelease"]).describe("Version bump type applied when this pattern matches")
69
+ packagesPath: z.string().optional().describe("Path to packages directory")
76
70
  });
77
71
  var VersionCargoConfigSchema = z.object({
78
72
  enabled: z.boolean().default(true).describe("Enable Cargo.toml version handling"),
@@ -121,12 +115,8 @@ var VersionConfigSchema = z.object({
121
115
  `How the "Project-wide changes" block is bounded in package-specific-tag mode. "union" (default): repo-level commits accrue from the union of the releasing packages' ranges, floored by the OLDEST unreleased baseline \u2014 so a genuinely-global commit recurs in every release until the oldest-baselined package is released past it. "sinceLastRelease": floor the block by the single nearest tag reachable across the repo, so global commits already shown by the most recent release don't recur (recommended for per-package-tag monorepos). No effect in sync mode, where one shared tag already consumes repo-level commits on each release.`
122
116
  ),
123
117
  mainPackage: z.string().optional().describe("Package to use for version determination"),
124
- updateInternalDependencies: z.enum(["major", "minor", "patch", "no-internal-update"]).default("minor").describe("How to bump internal dependencies"),
125
118
  skip: z.array(z.string()).optional().describe("Packages to exclude from versioning"),
126
119
  commitMessage: z.string().optional().describe("Template for release commit messages"),
127
- versionStrategy: z.enum(["branchPattern", "commitMessage"]).default("commitMessage").describe("Strategy for determining version bumps"),
128
- branchPatterns: z.array(BranchPatternSchema).optional().describe("Branch name patterns for version determination"),
129
- defaultReleaseType: z.enum(["major", "minor", "patch", "prerelease"]).optional().describe("Default release type when no pattern matches"),
130
120
  mismatchStrategy: z.enum(["error", "warn", "ignore", "prefer-package", "prefer-git"]).default("warn").describe("How to handle version mismatches"),
131
121
  versionPrefix: z.string().default("").describe("Prefix for version tags"),
132
122
  prereleaseIdentifier: z.string().optional().describe("Identifier for prerelease versions (e.g., 'alpha', 'beta')"),
@@ -161,7 +151,7 @@ var PubPublishConfigSchema = z.object({
161
151
  publishOrder: z.array(z.string()).default([]).describe("Order in which to publish packages")
162
152
  });
163
153
  var PublishGitConfigSchema = z.object({
164
- push: z.boolean().default(true).describe("Push tags and commits to remote"),
154
+ push: z.boolean().optional().describe("Push tags and commits to remote. When unset, inherits the top-level git.push (which defaults to push)."),
165
155
  pushMethod: z.enum(["auto", "ssh", "https"]).optional().describe("Push method override"),
166
156
  remote: z.string().optional().describe("Remote name override"),
167
157
  branch: z.string().optional().describe("Branch name override"),
@@ -415,7 +405,9 @@ var NotesConfigSchema = z.object({
415
405
  )
416
406
  });
417
407
  var CILabelsConfigSchema = z.object({
418
- stable: z.string().default("channel:stable").describe("Label to graduate a prerelease to stable"),
408
+ graduate: z.string().default("release:graduate").describe(
409
+ "Label that graduates a prerelease to its stable base version (e.g. 1.0.0-next.6 \u2192 1.0.0). A standalone release trigger in label/direct mode; in standing-pr mode it sets the next merge to graduate."
410
+ ),
419
411
  prerelease: z.string().default("channel:prerelease").describe("Label to create a prerelease"),
420
412
  skip: z.string().default("release:skip").describe("Label to suppress a release on this PR"),
421
413
  immediate: z.string().default("release:immediate").describe("Label to bypass the standing PR for one merge \u2014 triggers a direct release. Standing-pr mode only."),
@@ -473,16 +465,21 @@ var CIConfigSchema = z.object({
473
465
  releaseTrigger: z.enum(["commit", "label"]).default("label").describe(
474
466
  "What triggers a release. 'label': a PR bump label (bump:patch/minor/major) is required. 'commit': conventional commits drive the bump automatically; every merge can trigger a release."
475
467
  ),
476
- prPreview: z.boolean().default(true).describe(
477
- "Enable PR preview comments showing what would be released if the PR is merged. Set to false to disable."
478
- ),
479
- autoRelease: z.boolean().default(false).describe("Automatically trigger a release when CI conditions are met, without manual intervention."),
480
- skipPatterns: z.array(z.string()).default(["chore: release "]).describe(
481
- "Commit message prefixes that suppress a release. The default matches the release commit template to prevent release loops."
468
+ prPreview: z.union([
469
+ z.boolean(),
470
+ z.object({
471
+ enabled: z.boolean().default(true).describe("Whether PR preview comments are posted."),
472
+ refreshAfterRelease: z.boolean().default(false).describe(
473
+ 'After a release completes, replay the preview comment on still-open feeder PRs so their "what would release" estimate is not left stale against the moved baseline. Cosmetic and best-effort \u2014 a failure here never fails the release. Requires the refresh-after-release step in your release workflow.'
474
+ )
475
+ })
476
+ ]).default(true).transform(
477
+ (v) => typeof v === "boolean" ? { enabled: v, refreshAfterRelease: false } : { enabled: v.enabled ?? true, refreshAfterRelease: v.refreshAfterRelease ?? false }
478
+ ).describe(
479
+ "PR preview comments showing what would be released if the PR is merged. `true`/`false` toggles them; the object form additionally enables `refreshAfterRelease` to refresh feeder-PR previews after a release."
482
480
  ),
483
- minChanges: z.number().int().positive().default(1).describe("Minimum number of packages with releasable changes required to trigger a release."),
484
481
  labels: CILabelsConfigSchema.default({
485
- stable: "channel:stable",
482
+ graduate: "release:graduate",
486
483
  prerelease: "channel:prerelease",
487
484
  skip: "release:skip",
488
485
  immediate: "release:immediate",
@@ -610,6 +607,36 @@ function assertNoRemovedReleaseNotesFields(config) {
610
607
  `notes.releaseNotes no longer supports ${removed.join(", ")}. Release notes go to the GitHub release body by default; for in-repo per-version files set notes.releaseNotes.file to { "dir": "release-notes" }. For a cumulative changelog file, use changelog.mode.`
611
608
  );
612
609
  }
610
+ function assertNoRemovedVersionFields(config) {
611
+ if (!isRecord(config) || !isRecord(config.version)) return;
612
+ const v = config.version;
613
+ const removed = ["versionStrategy", "branchPatterns", "defaultReleaseType", "updateInternalDependencies"].filter(
614
+ (k) => k in v
615
+ );
616
+ if (removed.length === 0) return;
617
+ throw new ConfigError(
618
+ `version no longer supports ${removed.join(", ")}. Branch-pattern versioning was never functional \u2014 use Conventional Commits or --bump for version bumps. For coupled packages use version.groups; to release a package's changed dependencies use release:with-prerequisites / --include-prerequisites.`
619
+ );
620
+ }
621
+ function assertNoRemovedTopLevelFields(config) {
622
+ if (!isRecord(config)) return;
623
+ if (isRecord(config.ci)) {
624
+ const removed = ["autoRelease", "skipPatterns", "minChanges"].filter((k) => k in config.ci);
625
+ if (removed.length > 0) {
626
+ throw new ConfigError(
627
+ `ci no longer supports ${removed.join(", ")}. autoRelease was removed (it had no effect); skipPatterns and minChanges live under release.ci (release.ci.skipPatterns / release.ci.minChanges).`
628
+ );
629
+ }
630
+ }
631
+ if (isRecord(config.monorepo) && "mainPackage" in config.monorepo) {
632
+ throw new ConfigError("monorepo.mainPackage was removed \u2014 use version.mainPackage instead.");
633
+ }
634
+ }
635
+ function assertNoRemovedMonorepoMode(config) {
636
+ if (isRecord(config) && isRecord(config.monorepo) && "mode" in config.monorepo) {
637
+ throw new ConfigError("monorepo.mode was removed \u2014 changelog aggregation is controlled by notes.changelog.mode.");
638
+ }
639
+ }
613
640
  function loadConfigFile(configPath) {
614
641
  if (!fs3.existsSync(configPath)) {
615
642
  return {};
@@ -619,6 +646,9 @@ function loadConfigFile(configPath) {
619
646
  const parsed = parseJsonc(content);
620
647
  const substituted = substituteInObject(parsed);
621
648
  assertNoRemovedReleaseNotesFields(substituted);
649
+ assertNoRemovedVersionFields(substituted);
650
+ assertNoRemovedTopLevelFields(substituted);
651
+ assertNoRemovedMonorepoMode(substituted);
622
652
  return ReleaseKitConfigSchema.parse(substituted);
623
653
  } catch (error2) {
624
654
  if (error2 instanceof z2.ZodError) {
@@ -845,6 +875,7 @@ function forgeErrorStatus(error2) {
845
875
  }
846
876
  var REPO_PERMISSIONS = ["admin", "maintain", "write", "triage", "read", "none"];
847
877
  var MAX_RELEASE_PAGES = 3;
878
+ var MAX_OPEN_PR_PAGES = 5;
848
879
  function labelNames(labels) {
849
880
  return (labels ?? []).map((label) => typeof label === "string" ? label : label.name ?? "");
850
881
  }
@@ -860,6 +891,9 @@ var GitHubForge = class {
860
891
  this.owner = owner;
861
892
  this.repo = repo;
862
893
  }
894
+ octokit;
895
+ owner;
896
+ repo;
863
897
  get base() {
864
898
  return { owner: this.owner, repo: this.repo };
865
899
  }
@@ -891,6 +925,24 @@ var GitHubForge = class {
891
925
  });
892
926
  return data.map((pr) => ({ number: pr.number, mergedAt: pr.merged_at }));
893
927
  }
928
+ async listOpenPullRequests() {
929
+ const prs = [];
930
+ for (let page = 1; page <= MAX_OPEN_PR_PAGES; page++) {
931
+ const { data } = await this.octokit.rest.pulls.list({
932
+ ...this.base,
933
+ state: "open",
934
+ sort: "updated",
935
+ direction: "desc",
936
+ per_page: 100,
937
+ page
938
+ });
939
+ for (const pr of data) {
940
+ prs.push({ number: pr.number, headRef: pr.head.ref, draft: pr.draft ?? false, baseSha: pr.base.sha });
941
+ }
942
+ if (data.length < 100) break;
943
+ }
944
+ return prs;
945
+ }
894
946
  async getIssue(issueNumber) {
895
947
  const { data } = await this.octokit.rest.issues.get({ ...this.base, issue_number: issueNumber });
896
948
  return {
@@ -1279,7 +1331,18 @@ import Anthropic from "@anthropic-ai/sdk";
1279
1331
  // src/llm/base.ts
1280
1332
  var BaseLLMProvider = class {
1281
1333
  getTimeout(options) {
1282
- return options?.timeout ?? LLM_DEFAULTS.timeout;
1334
+ const timeout = options?.timeout ?? LLM_DEFAULTS.timeout;
1335
+ const MAX_TIMEOUT_MS = 2147483647;
1336
+ if (!Number.isFinite(timeout) || timeout < 1) return LLM_DEFAULTS.timeout;
1337
+ return Math.min(Math.trunc(timeout), MAX_TIMEOUT_MS);
1338
+ }
1339
+ /**
1340
+ * An AbortSignal that fires after the configured request timeout. Pass it to the provider's
1341
+ * request (SDK `{ signal }` request option, or fetch's `signal`). When it fires the request
1342
+ * aborts; providers check `signal.aborted` in their catch to surface a clear timeout error.
1343
+ */
1344
+ timeoutSignal(options) {
1345
+ return AbortSignal.timeout(this.getTimeout(options));
1283
1346
  }
1284
1347
  getMaxTokens(options) {
1285
1348
  return options?.maxTokens ?? LLM_DEFAULTS.maxTokens;
@@ -1322,23 +1385,27 @@ var AnthropicProvider = class extends BaseLLMProvider {
1322
1385
  debugLogMessages(this.name, messages);
1323
1386
  const systemMsg = messages.find((m) => m.role === "system");
1324
1387
  const nonSystemMessages = messages.filter((m) => m.role !== "system").map((m) => ({ role: m.role, content: m.content }));
1388
+ const signal = this.timeoutSignal(options);
1325
1389
  try {
1326
1390
  if (options?.schema) {
1327
1391
  const toolName = options.toolName ?? "emit_release_notes";
1328
- const response2 = await this.client.messages.create({
1329
- model: this.model,
1330
- max_tokens: this.getMaxTokens(options),
1331
- system: systemMsg?.content,
1332
- tools: [
1333
- {
1334
- name: toolName,
1335
- description: "Emit structured release notes data as JSON",
1336
- input_schema: options.schema
1337
- }
1338
- ],
1339
- tool_choice: { type: "tool", name: toolName },
1340
- messages: nonSystemMessages
1341
- });
1392
+ const response2 = await this.client.messages.create(
1393
+ {
1394
+ model: this.model,
1395
+ max_tokens: this.getMaxTokens(options),
1396
+ system: systemMsg?.content,
1397
+ tools: [
1398
+ {
1399
+ name: toolName,
1400
+ description: "Emit structured release notes data as JSON",
1401
+ input_schema: options.schema
1402
+ }
1403
+ ],
1404
+ tool_choice: { type: "tool", name: toolName },
1405
+ messages: nonSystemMessages
1406
+ },
1407
+ { signal }
1408
+ );
1342
1409
  const toolBlock = response2.content.find((b) => b.type === "tool_use");
1343
1410
  if (toolBlock?.type === "tool_use") {
1344
1411
  const structured = toolBlock.input;
@@ -1346,12 +1413,15 @@ var AnthropicProvider = class extends BaseLLMProvider {
1346
1413
  }
1347
1414
  throw new LLMError("Expected tool_use block in Anthropic response");
1348
1415
  }
1349
- const response = await this.client.messages.create({
1350
- model: this.model,
1351
- max_tokens: this.getMaxTokens(options),
1352
- system: systemMsg?.content,
1353
- messages: nonSystemMessages
1354
- });
1416
+ const response = await this.client.messages.create(
1417
+ {
1418
+ model: this.model,
1419
+ max_tokens: this.getMaxTokens(options),
1420
+ system: systemMsg?.content,
1421
+ messages: nonSystemMessages
1422
+ },
1423
+ { signal }
1424
+ );
1355
1425
  const firstBlock = response.content[0];
1356
1426
  if (!firstBlock || firstBlock.type !== "text") {
1357
1427
  throw new LLMError("Unexpected response format from Anthropic");
@@ -1359,6 +1429,7 @@ var AnthropicProvider = class extends BaseLLMProvider {
1359
1429
  return { content: firstBlock.text };
1360
1430
  } catch (error2) {
1361
1431
  if (error2 instanceof LLMError) throw error2;
1432
+ if (signal.aborted) throw new LLMError(`Anthropic request timed out after ${this.getTimeout(options)}ms`);
1362
1433
  throw new LLMError(`Anthropic API error: ${error2 instanceof Error ? error2.message : String(error2)}`);
1363
1434
  }
1364
1435
  }
@@ -1405,6 +1476,7 @@ var OllamaProvider = class extends BaseLLMProvider {
1405
1476
  if (options?.schema) {
1406
1477
  requestBody.format = options.schema;
1407
1478
  }
1479
+ const signal = this.timeoutSignal(options);
1408
1480
  try {
1409
1481
  const headers = {
1410
1482
  "Content-Type": "application/json"
@@ -1416,7 +1488,8 @@ var OllamaProvider = class extends BaseLLMProvider {
1416
1488
  const response = await fetch(`${baseUrl}/api/chat`, {
1417
1489
  method: "POST",
1418
1490
  headers,
1419
- body: JSON.stringify(requestBody)
1491
+ body: JSON.stringify(requestBody),
1492
+ signal
1420
1493
  });
1421
1494
  if (!response.ok) {
1422
1495
  if (response.status === 401 || response.status === 403) {
@@ -1446,6 +1519,7 @@ var OllamaProvider = class extends BaseLLMProvider {
1446
1519
  return { content };
1447
1520
  } catch (error2) {
1448
1521
  if (error2 instanceof LLMError) throw error2;
1522
+ if (signal.aborted) throw new LLMError(`Ollama request timed out after ${this.getTimeout(options)}ms`);
1449
1523
  throw new LLMError(`Ollama error: ${error2 instanceof Error ? error2.message : String(error2)}`);
1450
1524
  }
1451
1525
  }
@@ -1476,6 +1550,7 @@ var OpenAIProvider = class extends BaseLLMProvider {
1476
1550
  }
1477
1551
  async complete(messages, options) {
1478
1552
  debugLogMessages(this.name, messages);
1553
+ const signal = this.timeoutSignal(options);
1479
1554
  try {
1480
1555
  const openaiMessages = messages.map((m) => ({ role: m.role, content: m.content }));
1481
1556
  const requestParams = {
@@ -1496,7 +1571,7 @@ var OpenAIProvider = class extends BaseLLMProvider {
1496
1571
  }
1497
1572
  }
1498
1573
  };
1499
- const response = await this.client.chat.completions.create(requestParams);
1574
+ const response = await this.client.chat.completions.create(requestParams, { signal });
1500
1575
  const content = response.choices[0]?.message?.content;
1501
1576
  if (!content) {
1502
1577
  throw new LLMError("Empty response from OpenAI");
@@ -1513,6 +1588,7 @@ var OpenAIProvider = class extends BaseLLMProvider {
1513
1588
  return { content };
1514
1589
  } catch (error2) {
1515
1590
  if (error2 instanceof LLMError) throw error2;
1591
+ if (signal.aborted) throw new LLMError(`OpenAI request timed out after ${this.getTimeout(options)}ms`);
1516
1592
  throw new LLMError(`OpenAI API error: ${error2 instanceof Error ? error2.message : String(error2)}`);
1517
1593
  }
1518
1594
  }
@@ -1540,6 +1616,7 @@ var OpenAICompatibleProvider = class extends BaseLLMProvider {
1540
1616
  }
1541
1617
  async complete(messages, options) {
1542
1618
  debugLogMessages(this.name, messages);
1619
+ const signal = this.timeoutSignal(options);
1543
1620
  try {
1544
1621
  const openaiMessages = messages.map((m) => ({ role: m.role, content: m.content }));
1545
1622
  const requestParams = {
@@ -1549,7 +1626,7 @@ var OpenAICompatibleProvider = class extends BaseLLMProvider {
1549
1626
  temperature: this.getTemperature(options),
1550
1627
  stream: false
1551
1628
  };
1552
- const response = await this.client.chat.completions.create(requestParams);
1629
+ const response = await this.client.chat.completions.create(requestParams, { signal });
1553
1630
  const content = response.choices[0]?.message?.content;
1554
1631
  if (!content) {
1555
1632
  throw new LLMError("Empty response from LLM");
@@ -1557,32 +1634,12 @@ var OpenAICompatibleProvider = class extends BaseLLMProvider {
1557
1634
  return { content };
1558
1635
  } catch (error2) {
1559
1636
  if (error2 instanceof LLMError) throw error2;
1637
+ if (signal.aborted) throw new LLMError(`${this.name} request timed out after ${this.getTimeout(options)}ms`);
1560
1638
  throw new LLMError(`LLM API error: ${error2 instanceof Error ? error2.message : String(error2)}`);
1561
1639
  }
1562
1640
  }
1563
1641
  };
1564
1642
 
1565
- // src/llm/correctiveRetry.ts
1566
- async function withCorrectiveRetry(call, validate, buildCorrectionMessages3, initialMessages, maxCorrectiveAttempts = 2) {
1567
- let messages = initialMessages;
1568
- let lastError = "";
1569
- for (let attempt = 0; attempt <= maxCorrectiveAttempts; attempt++) {
1570
- const result = await call(messages, attempt === 0);
1571
- const validation = validate(result);
1572
- if (validation.valid) return validation.value;
1573
- lastError = validation.error;
1574
- if (attempt < maxCorrectiveAttempts) {
1575
- const badContent = typeof result.structured !== "undefined" ? JSON.stringify(result.structured) : result.content;
1576
- messages = [
1577
- ...messages,
1578
- { role: "assistant", content: badContent },
1579
- ...buildCorrectionMessages3(badContent, validation.error)
1580
- ];
1581
- }
1582
- }
1583
- throw new LLMError(`Structured output validation failed after ${maxCorrectiveAttempts + 1} attempts: ${lastError}`);
1584
- }
1585
-
1586
1643
  // src/llm/prompts.ts
1587
1644
  function resolveSystemPrompt(taskName, defaultSystemPrompt, promptsConfig) {
1588
1645
  const instructions = promptsConfig?.instructions?.[taskName];
@@ -1680,10 +1737,20 @@ function getAllowedScopesFromCategories(categories) {
1680
1737
  }
1681
1738
  return scopeMap;
1682
1739
  }
1740
+ function expandPackageScopes(packageNames) {
1741
+ const forms = /* @__PURE__ */ new Set();
1742
+ for (const name of packageNames) {
1743
+ forms.add(name);
1744
+ forms.add(name.replace(/^@/, ""));
1745
+ const slash = name.lastIndexOf("/");
1746
+ forms.add(slash >= 0 ? name.slice(slash + 1) : name);
1747
+ }
1748
+ return [...forms];
1749
+ }
1683
1750
  function resolveAllowedScopes(scopeConfig, categories, packageNames) {
1684
1751
  if (!scopeConfig || scopeConfig.mode === "unrestricted") return null;
1685
1752
  if (scopeConfig.mode === "none") return [];
1686
- if (scopeConfig.mode === "packages") return packageNames ?? [];
1753
+ if (scopeConfig.mode === "packages") return expandPackageScopes(packageNames ?? []);
1687
1754
  if (scopeConfig.mode === "restricted") {
1688
1755
  const explicit = scopeConfig.rules?.allowed ?? [];
1689
1756
  const all = new Set(explicit);
@@ -1704,8 +1771,8 @@ function validateScope(scope, allowedScopes, caseSensitive = false) {
1704
1771
  const isAllowed = allowedScopes.some((a) => normalise(a) === normalise(scope));
1705
1772
  return isAllowed ? scope : void 0;
1706
1773
  }
1707
- function validateEntryScopes(entries, scopeConfig, categories) {
1708
- const allowedScopes = resolveAllowedScopes(scopeConfig, categories);
1774
+ function validateEntryScopes(entries, scopeConfig, categories, packageNames) {
1775
+ const allowedScopes = resolveAllowedScopes(scopeConfig, categories, packageNames);
1709
1776
  if (allowedScopes === null) return { valid: true, entries, errors: [] };
1710
1777
  const caseSensitive = scopeConfig?.rules?.caseSensitive ?? false;
1711
1778
  const action = scopeConfig?.rules?.invalidScopeAction ?? "remove";
@@ -1732,6 +1799,27 @@ function validateEntryScopes(entries, scopeConfig, categories) {
1732
1799
  return { valid: true, entries: validatedEntries, errors };
1733
1800
  }
1734
1801
 
1802
+ // src/llm/correctiveRetry.ts
1803
+ async function withCorrectiveRetry(call, validate, buildCorrectionMessages2, initialMessages, maxCorrectiveAttempts = 2) {
1804
+ let messages = initialMessages;
1805
+ let lastError = "";
1806
+ for (let attempt = 0; attempt <= maxCorrectiveAttempts; attempt++) {
1807
+ const result = await call(messages, attempt === 0);
1808
+ const validation = validate(result);
1809
+ if (validation.valid) return validation.value;
1810
+ lastError = validation.error;
1811
+ if (attempt < maxCorrectiveAttempts) {
1812
+ const badContent = typeof result.structured !== "undefined" ? JSON.stringify(result.structured) : result.content;
1813
+ messages = [
1814
+ ...messages,
1815
+ { role: "assistant", content: badContent },
1816
+ ...buildCorrectionMessages2(badContent, validation.error)
1817
+ ];
1818
+ }
1819
+ }
1820
+ throw new LLMError(`Structured output validation failed after ${maxCorrectiveAttempts + 1} attempts: ${lastError}`);
1821
+ }
1822
+
1735
1823
  // src/llm/tasks/shared.ts
1736
1824
  function escAttr(s) {
1737
1825
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/"/g, "&quot;");
@@ -1762,27 +1850,68 @@ function groupByCategory(llmEntries, entries) {
1762
1850
  }
1763
1851
  return result;
1764
1852
  }
1765
-
1766
- // src/llm/tasks/categorize.ts
1767
- function buildSystemPrompt(categories) {
1768
- const categorySection = categories && categories.length > 0 ? `Categories (use ONLY these exact names):
1769
- ${categories.map((c) => {
1853
+ function buildCategorySection(categories, fallback) {
1854
+ if (!categories || categories.length === 0) return fallback;
1855
+ const lines = categories.map((c) => {
1770
1856
  const scopeInfo = c.scopes?.length ? ` Allowed scopes: ${c.scopes.join(", ")}.` : "";
1771
1857
  return `- "${c.name}": ${c.description}${scopeInfo}`;
1772
- }).join("\n")}` : `Categories: Group into meaningful categories (e.g., "Core", "UI", "API", "Performance", "Bug Fixes", "Documentation").`;
1773
- let scopeInstruction = "";
1774
- if (categories && categories.length > 0) {
1775
- const scopeMap = getAllowedScopesFromCategories(categories);
1776
- if (scopeMap.size > 0) {
1777
- const parts = [];
1778
- for (const [catName, scopes] of scopeMap) {
1779
- parts.push(`For "${catName}", use a scope from: ${scopes.join(", ")}.`);
1780
- }
1781
- scopeInstruction = `
1858
+ });
1859
+ return `Categories (use ONLY these exact names):
1860
+ ${lines.join("\n")}`;
1861
+ }
1862
+ function renderScopeInstruction(pairs, entrySuffix) {
1863
+ if (pairs.length === 0) return "";
1864
+ const parts = pairs.map((p) => `For "${p.name}"${entrySuffix}, use a scope from: ${p.scopes.join(", ")}.`);
1865
+ return `
1782
1866
  ${parts.join("\n")}
1783
1867
  Only use scopes from these predefined lists. Set scope to null if no scope applies.`;
1868
+ }
1869
+ function buildCorrectionMessages(_badContent, error2) {
1870
+ return [
1871
+ {
1872
+ role: "user",
1873
+ content: `Your previous response had an error: ${error2}
1874
+
1875
+ Please fix the issue and output only valid JSON matching the required schema.`
1784
1876
  }
1785
- }
1877
+ ];
1878
+ }
1879
+ function parseLLMResult(result) {
1880
+ try {
1881
+ const data = typeof result.structured !== "undefined" ? result.structured : JSON.parse(extractJsonFromResponse(result.content));
1882
+ return { ok: true, data };
1883
+ } catch (e) {
1884
+ return { ok: false, error: `Invalid JSON: ${e instanceof Error ? e.message : String(e)}` };
1885
+ }
1886
+ }
1887
+ function checkCategoryNames(llmEntries, categoryNames) {
1888
+ if (!categoryNames?.length) return null;
1889
+ const invalid = llmEntries.filter((e) => !categoryNames.includes(e.category)).map((e) => e.category);
1890
+ if (invalid.length === 0) return null;
1891
+ const unique = [...new Set(invalid)];
1892
+ return `Unknown categories: ${unique.join(", ")}. Valid categories: ${categoryNames.join(", ")}`;
1893
+ }
1894
+ async function runCorrectiveTask(opts) {
1895
+ const { provider, initialMessages, schema, toolName, validate } = opts;
1896
+ return withCorrectiveRetry(
1897
+ (messages, isFirstAttempt) => provider.complete(
1898
+ messages,
1899
+ isFirstAttempt && provider.capabilities.structuredOutputs ? { schema, toolName } : void 0
1900
+ ),
1901
+ validate,
1902
+ buildCorrectionMessages,
1903
+ initialMessages
1904
+ );
1905
+ }
1906
+
1907
+ // src/llm/tasks/categorize.ts
1908
+ function buildSystemPrompt(categories) {
1909
+ const categorySection = buildCategorySection(
1910
+ categories,
1911
+ `Categories: Group into meaningful categories (e.g., "Core", "UI", "API", "Performance", "Bug Fixes", "Documentation").`
1912
+ );
1913
+ const pairs = categories && categories.length > 0 ? [...getAllowedScopesFromCategories(categories)].map(([name, scopes]) => ({ name, scopes })) : [];
1914
+ const scopeInstruction = renderScopeInstruction(pairs, "");
1786
1915
  return `You are categorizing changelog entries for a software release.
1787
1916
 
1788
1917
  ${categorySection}${scopeInstruction}
@@ -1796,26 +1925,12 @@ function buildUserPrompt(entries) {
1796
1925
  return `Entries:
1797
1926
  ${text}`;
1798
1927
  }
1799
- function buildCorrectionMessages(_badContent, error2) {
1800
- return [
1801
- {
1802
- role: "user",
1803
- content: `Your previous response had an error: ${error2}
1804
-
1805
- Please fix the issue and output only valid JSON matching the required schema.`
1806
- }
1807
- ];
1808
- }
1809
- function makeValidator(entries, context) {
1928
+ function createCategorizeValidator(entries, context) {
1810
1929
  const cleanEntries = entries.map((e) => ({ ...e, scope: void 0 }));
1811
1930
  return (result) => {
1812
- let parsed;
1813
- try {
1814
- parsed = typeof result.structured !== "undefined" ? result.structured : JSON.parse(extractJsonFromResponse(result.content));
1815
- } catch (e) {
1816
- return { valid: false, error: `Invalid JSON: ${e instanceof Error ? e.message : String(e)}` };
1817
- }
1818
- const zodResult = CategorizeOutputSchema.safeParse(parsed);
1931
+ const parsed = parseLLMResult(result);
1932
+ if (!parsed.ok) return { valid: false, error: parsed.error };
1933
+ const zodResult = CategorizeOutputSchema.safeParse(parsed.data);
1819
1934
  if (!zodResult.success) {
1820
1935
  return { valid: false, error: `Schema error: ${zodResult.error.message}` };
1821
1936
  }
@@ -1825,23 +1940,17 @@ function makeValidator(entries, context) {
1825
1940
  error: `Expected ${entries.length} entries, got ${zodResult.data.entries.length}`
1826
1941
  };
1827
1942
  }
1828
- const categoryNames = context.categories?.map((c) => c.name);
1829
- if (categoryNames?.length) {
1830
- const invalid = zodResult.data.entries.filter((e) => !categoryNames.includes(e.category)).map((e) => e.category);
1831
- if (invalid.length > 0) {
1832
- const unique = [...new Set(invalid)];
1833
- return {
1834
- valid: false,
1835
- error: `Unknown categories: ${unique.join(", ")}. Valid categories: ${categoryNames.join(", ")}`
1836
- };
1837
- }
1838
- }
1943
+ const categoryError = checkCategoryNames(
1944
+ zodResult.data.entries,
1945
+ context.categories?.map((c) => c.name)
1946
+ );
1947
+ if (categoryError) return { valid: false, error: categoryError };
1839
1948
  const withScopes = cleanEntries.map((entry, i) => {
1840
1949
  const llmEntry = zodResult.data.entries[i];
1841
1950
  const scope = llmEntry?.scope ?? void 0;
1842
1951
  return scope ? { ...entry, scope } : entry;
1843
1952
  });
1844
- const scopeResult = validateEntryScopes(withScopes, context.scopes, context.categories);
1953
+ const scopeResult = validateEntryScopes(withScopes, context.scopes, context.categories, context.packageNames);
1845
1954
  if (scopeResult.errors.length > 0) {
1846
1955
  const offenders = [...new Set(scopeResult.errors.map((e) => e.providedScope))];
1847
1956
  warn(
@@ -1860,18 +1969,14 @@ async function categorizeEntries(provider, entries, context) {
1860
1969
  { role: "system", content: systemPrompt },
1861
1970
  { role: "user", content: buildUserPrompt(entries) }
1862
1971
  ];
1863
- const schema = buildCategorizeSchema(context.categories ?? []);
1864
- const validate = makeValidator(entries, context);
1865
1972
  try {
1866
- return await withCorrectiveRetry(
1867
- (messages, isFirstAttempt) => provider.complete(
1868
- messages,
1869
- isFirstAttempt && provider.capabilities.structuredOutputs ? { schema, toolName: "categorize_entries" } : void 0
1870
- ),
1871
- validate,
1872
- buildCorrectionMessages,
1873
- initialMessages
1874
- );
1973
+ return await runCorrectiveTask({
1974
+ provider,
1975
+ initialMessages,
1976
+ schema: buildCategorizeSchema(context.categories ?? []),
1977
+ toolName: "categorize_entries",
1978
+ validate: createCategorizeValidator(entries, context)
1979
+ });
1875
1980
  } catch (error2) {
1876
1981
  if (error2 instanceof LLMError) {
1877
1982
  warn(`categorizeEntries failed after all attempts: ${error2.message}. Returning entries under General.`);
@@ -1935,21 +2040,12 @@ async function enhanceEntries(provider, entries, context, concurrency = LLM_DEFA
1935
2040
  // src/llm/tasks/enhance-and-categorize.ts
1936
2041
  function buildSystemPrompt3(categories, style) {
1937
2042
  const styleText = style || 'Use past tense ("Added feature" not "Add feature"). Be concise.';
1938
- const categorySection = categories && categories.length > 0 ? `Categories (use ONLY these exact names):
1939
- ${categories.map((c) => {
1940
- const scopeInfo = c.scopes?.length ? ` Allowed scopes: ${c.scopes.join(", ")}.` : "";
1941
- return `- "${c.name}": ${c.description}${scopeInfo}`;
1942
- }).join("\n")}` : `Categories: Group into meaningful categories (e.g., "New", "Fixed", "Changed", "Removed").`;
1943
- let scopeInstruction = "";
1944
- if (categories && categories.length > 0) {
1945
- const withScopes = categories.filter((c) => c.scopes?.length);
1946
- if (withScopes.length > 0) {
1947
- const parts = withScopes.map((c) => `For "${c.name}" entries, use a scope from: ${c.scopes?.join(", ")}.`);
1948
- scopeInstruction = `
1949
- ${parts.join("\n")}
1950
- Only use scopes from these predefined lists. Set scope to null if no scope applies.`;
1951
- }
1952
- }
2043
+ const categorySection = buildCategorySection(
2044
+ categories,
2045
+ `Categories: Group into meaningful categories (e.g., "New", "Fixed", "Changed", "Removed").`
2046
+ );
2047
+ const pairs = categories && categories.length > 0 ? categories.filter((c) => c.scopes?.length).map((c) => ({ name: c.name, scopes: c.scopes })) : [];
2048
+ const scopeInstruction = renderScopeInstruction(pairs, " entries");
1953
2049
  return `You are generating release notes for a software project. Given changelog entries, rewrite each as a clear user-friendly description and categorize it.
1954
2050
 
1955
2051
  Style guidelines:
@@ -1980,25 +2076,11 @@ ${prBlocks}` : header;
1980
2076
  return `Entries:
1981
2077
  ${entriesText}`;
1982
2078
  }
1983
- function buildCorrectionMessages2(_badContent, error2) {
1984
- return [
1985
- {
1986
- role: "user",
1987
- content: `Your previous response had an error: ${error2}
1988
-
1989
- Please fix the issue and output only valid JSON matching the required schema.`
1990
- }
1991
- ];
1992
- }
1993
- function makeValidator2(entries, context) {
2079
+ function createEnhanceAndCategorizeValidator(entries, context) {
1994
2080
  return (result) => {
1995
- let parsed;
1996
- try {
1997
- parsed = typeof result.structured !== "undefined" ? result.structured : JSON.parse(extractJsonFromResponse(result.content));
1998
- } catch (e) {
1999
- return { valid: false, error: `Invalid JSON: ${e instanceof Error ? e.message : String(e)}` };
2000
- }
2001
- const zodResult = EnhanceAndCategorizeOutputSchema.safeParse(parsed);
2081
+ const parsed = parseLLMResult(result);
2082
+ if (!parsed.ok) return { valid: false, error: parsed.error };
2083
+ const zodResult = EnhanceAndCategorizeOutputSchema.safeParse(parsed.data);
2002
2084
  if (!zodResult.success) {
2003
2085
  return { valid: false, error: `Schema error: ${zodResult.error.message}` };
2004
2086
  }
@@ -2013,17 +2095,11 @@ function makeValidator2(entries, context) {
2013
2095
  warn(`LLM returned ${receivedCount} entries for ${entries.length} inputs; truncating to expected count.`);
2014
2096
  zodResult.data.entries.length = entries.length;
2015
2097
  }
2016
- const categoryNames = context.categories?.map((c) => c.name);
2017
- if (categoryNames?.length) {
2018
- const invalid = zodResult.data.entries.filter((e) => !categoryNames.includes(e.category)).map((e) => e.category);
2019
- if (invalid.length > 0) {
2020
- const unique = [...new Set(invalid)];
2021
- return {
2022
- valid: false,
2023
- error: `Unknown categories: ${unique.join(", ")}. Valid categories: ${categoryNames.join(", ")}`
2024
- };
2025
- }
2026
- }
2098
+ const categoryError = checkCategoryNames(
2099
+ zodResult.data.entries,
2100
+ context.categories?.map((c) => c.name)
2101
+ );
2102
+ if (categoryError) return { valid: false, error: categoryError };
2027
2103
  const enhancedEntries = entries.map((original, i) => {
2028
2104
  const llmEntry = zodResult.data.entries[i];
2029
2105
  if (!llmEntry) return original;
@@ -2035,7 +2111,7 @@ function makeValidator2(entries, context) {
2035
2111
  leadIn: llmEntry.leadIn ?? void 0
2036
2112
  };
2037
2113
  });
2038
- const scopeResult = validateEntryScopes(enhancedEntries, context.scopes, context.categories);
2114
+ const scopeResult = validateEntryScopes(enhancedEntries, context.scopes, context.categories, context.packageNames);
2039
2115
  if (scopeResult.errors.length > 0) {
2040
2116
  const offenders = [...new Set(scopeResult.errors.map((e) => e.providedScope))];
2041
2117
  warn(
@@ -2064,18 +2140,14 @@ async function enhanceAndCategorize(provider, entries, context) {
2064
2140
  { role: "system", content: systemPrompt },
2065
2141
  { role: "user", content: buildUserPrompt3(entries) }
2066
2142
  ];
2067
- const schema = buildEnhanceAndCategorizeSchema(context.categories ?? []);
2068
- const validate = makeValidator2(entries, context);
2069
2143
  try {
2070
- return await withCorrectiveRetry(
2071
- (messages, isFirstAttempt) => provider.complete(
2072
- messages,
2073
- isFirstAttempt && provider.capabilities.structuredOutputs ? { schema, toolName: "emit_release_notes" } : void 0
2074
- ),
2075
- validate,
2076
- buildCorrectionMessages2,
2077
- initialMessages
2078
- );
2144
+ return await runCorrectiveTask({
2145
+ provider,
2146
+ initialMessages,
2147
+ schema: buildEnhanceAndCategorizeSchema(context.categories ?? []),
2148
+ toolName: "emit_release_notes",
2149
+ validate: createEnhanceAndCategorizeValidator(entries, context)
2150
+ });
2079
2151
  } catch (error2) {
2080
2152
  if (error2 instanceof LLMError) {
2081
2153
  warn(`enhanceAndCategorize failed after all attempts: ${error2.message}. Returning entries ungrouped.`);
@@ -2610,7 +2682,7 @@ function createDocumentContext(contexts, repoUrl) {
2610
2682
  compareUrls: Object.keys(compareUrls).length > 0 ? compareUrls : void 0
2611
2683
  };
2612
2684
  }
2613
- async function processWithLLM(context, llmConfig, examples) {
2685
+ async function processWithLLM(context, llmConfig, examples, packageNames) {
2614
2686
  const tasks = llmConfig.tasks ?? {};
2615
2687
  const llmContext = {
2616
2688
  packageName: context.packageName,
@@ -2621,7 +2693,8 @@ async function processWithLLM(context, llmConfig, examples) {
2621
2693
  style: llmConfig.style,
2622
2694
  scopes: llmConfig.scopes,
2623
2695
  prompts: llmConfig.prompts,
2624
- examples
2696
+ examples,
2697
+ packageNames
2625
2698
  };
2626
2699
  const enhanced = {
2627
2700
  entries: context.entries
@@ -2782,8 +2855,11 @@ async function runPipeline(input, config, dryRun, pipelineOptions) {
2782
2855
  })
2783
2856
  }));
2784
2857
  }
2858
+ const allPackageNames = contexts.map((c) => c.packageName);
2785
2859
  contexts = await Promise.all(
2786
- contexts.map((ctx) => processWithLLM(ctx, llmConfig, examplesByPackage.get(ctx.packageName) ?? []))
2860
+ contexts.map(
2861
+ (ctx) => processWithLLM(ctx, llmConfig, examplesByPackage.get(ctx.packageName) ?? [], allPackageNames)
2862
+ )
2787
2863
  );
2788
2864
  }
2789
2865
  const files = [];
@@ -3022,7 +3098,6 @@ function createNotesCommand() {
3022
3098
  }
3023
3099
  if (options.monorepo) {
3024
3100
  const monoMode = options.monorepo;
3025
- config.monorepo = { ...config.monorepo, mode: monoMode };
3026
3101
  if (config.changelog !== false && !options.changelogMode) {
3027
3102
  config.changelog = { ...config.changelog ?? {}, mode: monoMode };
3028
3103
  }
package/dist/cli.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  createNotesCommand
4
- } from "./chunk-DDZPVGJJ.js";
4
+ } from "./chunk-4G6BQOIR.js";
5
5
  import {
6
6
  readPackageVersion
7
7
  } from "./chunk-IC4SXXRM.js";
package/dist/index.js CHANGED
@@ -18,7 +18,7 @@ import {
18
18
  runPipeline,
19
19
  saveAuth,
20
20
  versionOutputToChangelogInput
21
- } from "./chunk-DDZPVGJJ.js";
21
+ } from "./chunk-4G6BQOIR.js";
22
22
  import {
23
23
  aggregateToRoot,
24
24
  detectMonorepo,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@releasekit/notes",
3
- "version": "0.32.1",
3
+ "version": "0.34.0",
4
4
  "description": "Release notes and changelog generation with LLM-powered enhancement and flexible templating",
5
5
  "type": "module",
6
6
  "module": "./dist/index.js",
@@ -71,7 +71,8 @@
71
71
  "vitest": "^4.1.9",
72
72
  "@releasekit/config": "0.0.0",
73
73
  "@releasekit/forge": "0.0.0",
74
- "@releasekit/core": "0.0.0"
74
+ "@releasekit/core": "0.0.0",
75
+ "@releasekit/git": "0.0.0"
75
76
  },
76
77
  "engines": {
77
78
  "node": ">=22"