@promptbook/cli 0.112.0-36 → 0.112.0-38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/README.md +10 -6
  2. package/esm/index.es.js +950 -424
  3. package/esm/index.es.js.map +1 -1
  4. package/esm/scripts/find-refactor-candidates/RefactorCandidateLevel.d.ts +41 -0
  5. package/esm/scripts/find-refactor-candidates/analyzeSourceFileForRefactorCandidate.d.ts +5 -0
  6. package/esm/scripts/find-refactor-candidates/find-refactor-candidates.constants.d.ts +2 -14
  7. package/esm/scripts/find-refactor-candidates/find-refactor-candidates.d.ts +13 -1
  8. package/esm/scripts/find-refactor-candidates/findRefactorCandidatesInProject.d.ts +18 -1
  9. package/esm/src/_packages/components.index.d.ts +2 -0
  10. package/esm/src/_packages/types.index.d.ts +48 -46
  11. package/esm/src/book-components/Chat/Chat/ChatActionsBar.d.ts +7 -0
  12. package/esm/src/book-components/Chat/Chat/ChatActionsBar.test.d.ts +2 -0
  13. package/esm/src/book-components/Chat/Chat/ChatInputArea.d.ts +4 -0
  14. package/esm/src/book-components/Chat/Chat/ChatMessageItem.d.ts +8 -0
  15. package/esm/src/book-components/Chat/Chat/ChatMessageList.d.ts +2 -0
  16. package/esm/src/book-components/Chat/Chat/ChatProps.d.ts +50 -1
  17. package/esm/src/book-components/Chat/Chat/ChatReplyPreview.d.ts +19 -0
  18. package/esm/src/book-components/Chat/Chat/createProgressCardChecklistMarkdown.d.ts +2 -2
  19. package/esm/src/book-components/Chat/MockedChat/MockedChat.d.ts +1 -1
  20. package/esm/src/book-components/Chat/types/ChatMessage.d.ts +35 -0
  21. package/esm/src/book-components/Chat/utils/resolveChatMessageReplyPreviewText.d.ts +25 -0
  22. package/esm/src/book-components/Chat/utils/resolveChatMessageReplySenderLabel.d.ts +12 -0
  23. package/esm/src/cli/cli-commands/coder/agentCodingFile.d.ts +14 -0
  24. package/esm/src/cli/cli-commands/coder/agentsFile.d.ts +12 -0
  25. package/esm/src/cli/cli-commands/coder/appendBlock.d.ts +6 -0
  26. package/esm/src/cli/cli-commands/coder/boilerplateTemplates.d.ts +10 -0
  27. package/esm/src/cli/cli-commands/coder/ensureCoderEnvFile.d.ts +15 -0
  28. package/esm/src/cli/cli-commands/coder/ensureCoderGitignoreFile.d.ts +7 -0
  29. package/esm/src/cli/cli-commands/coder/ensureCoderMarkdownFile.d.ts +7 -0
  30. package/esm/src/cli/cli-commands/coder/ensureCoderPackageJsonFile.d.ts +7 -0
  31. package/esm/src/cli/cli-commands/coder/ensureCoderVscodeSettingsFile.d.ts +7 -0
  32. package/esm/src/cli/cli-commands/coder/ensureDirectory.d.ts +7 -0
  33. package/esm/src/cli/cli-commands/coder/find-refactor-candidates.d.ts +1 -1
  34. package/esm/src/cli/cli-commands/coder/find-refactor-candidates.test.d.ts +1 -0
  35. package/esm/src/cli/cli-commands/coder/formatDisplayPath.d.ts +6 -0
  36. package/esm/src/cli/cli-commands/coder/getDefaultCoderPackageJsonScripts.d.ts +6 -0
  37. package/esm/src/cli/cli-commands/coder/getDefaultCoderVscodeSettings.d.ts +6 -0
  38. package/esm/src/cli/cli-commands/coder/init.d.ts +3 -38
  39. package/esm/src/cli/cli-commands/coder/initializeCoderProjectConfiguration.d.ts +25 -0
  40. package/esm/src/cli/cli-commands/coder/mergeStringRecordJsonFile.d.ts +18 -0
  41. package/esm/src/cli/cli-commands/coder/printInitializationSummary.d.ts +7 -0
  42. package/esm/src/cli/cli-commands/coder/readTextFileIfExists.d.ts +6 -0
  43. package/esm/src/types/string_agent_url.d.ts +7 -0
  44. package/esm/src/types/string_agent_url_private.d.ts +9 -0
  45. package/esm/src/types/string_base64.d.ts +13 -0
  46. package/esm/src/types/string_base64_private.d.ts +2 -2
  47. package/esm/src/types/string_base_url.d.ts +7 -0
  48. package/esm/src/types/string_base_url_private.d.ts +9 -0
  49. package/esm/src/types/string_email.d.ts +13 -0
  50. package/esm/src/types/string_email_private.d.ts +2 -2
  51. package/esm/src/types/string_host.d.ts +42 -0
  52. package/esm/src/types/string_host_private.d.ts +7 -7
  53. package/esm/src/types/string_href.d.ts +19 -0
  54. package/esm/src/types/string_href_private.d.ts +24 -0
  55. package/esm/src/types/string_mime_type.d.ts +15 -0
  56. package/esm/src/types/string_mime_type_private.d.ts +2 -2
  57. package/esm/src/types/string_pipeline_root_url.d.ts +7 -0
  58. package/esm/src/types/string_pipeline_root_url_private.d.ts +9 -0
  59. package/esm/src/types/string_pipeline_url.d.ts +13 -0
  60. package/esm/src/types/string_pipeline_url_private.d.ts +17 -0
  61. package/esm/src/types/string_promptbook_server_url.d.ts +7 -0
  62. package/esm/src/types/string_promptbook_server_url_private.d.ts +9 -0
  63. package/esm/src/types/string_url.d.ts +14 -141
  64. package/esm/src/types/string_url_image.d.ts +7 -0
  65. package/esm/src/types/string_url_image_private.d.ts +9 -0
  66. package/esm/src/types/string_url_private.d.ts +0 -80
  67. package/esm/src/version.d.ts +1 -1
  68. package/package.json +1 -1
  69. package/umd/index.umd.js +949 -423
  70. package/umd/index.umd.js.map +1 -1
  71. package/umd/scripts/find-refactor-candidates/RefactorCandidateLevel.d.ts +41 -0
  72. package/umd/scripts/find-refactor-candidates/analyzeSourceFileForRefactorCandidate.d.ts +5 -0
  73. package/umd/scripts/find-refactor-candidates/find-refactor-candidates.constants.d.ts +2 -14
  74. package/umd/scripts/find-refactor-candidates/find-refactor-candidates.d.ts +13 -1
  75. package/umd/scripts/find-refactor-candidates/findRefactorCandidatesInProject.d.ts +18 -1
  76. package/umd/src/_packages/components.index.d.ts +2 -0
  77. package/umd/src/_packages/types.index.d.ts +48 -46
  78. package/umd/src/book-components/Chat/Chat/ChatActionsBar.d.ts +7 -0
  79. package/umd/src/book-components/Chat/Chat/ChatActionsBar.test.d.ts +2 -0
  80. package/umd/src/book-components/Chat/Chat/ChatInputArea.d.ts +4 -0
  81. package/umd/src/book-components/Chat/Chat/ChatMessageItem.d.ts +8 -0
  82. package/umd/src/book-components/Chat/Chat/ChatMessageList.d.ts +2 -0
  83. package/umd/src/book-components/Chat/Chat/ChatProps.d.ts +50 -1
  84. package/umd/src/book-components/Chat/Chat/ChatReplyPreview.d.ts +19 -0
  85. package/umd/src/book-components/Chat/Chat/createProgressCardChecklistMarkdown.d.ts +2 -2
  86. package/umd/src/book-components/Chat/MockedChat/MockedChat.d.ts +1 -1
  87. package/umd/src/book-components/Chat/types/ChatMessage.d.ts +35 -0
  88. package/umd/src/book-components/Chat/utils/resolveChatMessageReplyPreviewText.d.ts +25 -0
  89. package/umd/src/book-components/Chat/utils/resolveChatMessageReplySenderLabel.d.ts +12 -0
  90. package/umd/src/cli/cli-commands/coder/agentCodingFile.d.ts +14 -0
  91. package/umd/src/cli/cli-commands/coder/agentsFile.d.ts +12 -0
  92. package/umd/src/cli/cli-commands/coder/appendBlock.d.ts +6 -0
  93. package/umd/src/cli/cli-commands/coder/boilerplateTemplates.d.ts +10 -0
  94. package/umd/src/cli/cli-commands/coder/ensureCoderEnvFile.d.ts +15 -0
  95. package/umd/src/cli/cli-commands/coder/ensureCoderGitignoreFile.d.ts +7 -0
  96. package/umd/src/cli/cli-commands/coder/ensureCoderMarkdownFile.d.ts +7 -0
  97. package/umd/src/cli/cli-commands/coder/ensureCoderPackageJsonFile.d.ts +7 -0
  98. package/umd/src/cli/cli-commands/coder/ensureCoderVscodeSettingsFile.d.ts +7 -0
  99. package/umd/src/cli/cli-commands/coder/ensureDirectory.d.ts +7 -0
  100. package/umd/src/cli/cli-commands/coder/find-refactor-candidates.d.ts +1 -1
  101. package/umd/src/cli/cli-commands/coder/find-refactor-candidates.test.d.ts +1 -0
  102. package/umd/src/cli/cli-commands/coder/formatDisplayPath.d.ts +6 -0
  103. package/umd/src/cli/cli-commands/coder/getDefaultCoderPackageJsonScripts.d.ts +6 -0
  104. package/umd/src/cli/cli-commands/coder/getDefaultCoderVscodeSettings.d.ts +6 -0
  105. package/umd/src/cli/cli-commands/coder/init.d.ts +3 -38
  106. package/umd/src/cli/cli-commands/coder/initializeCoderProjectConfiguration.d.ts +25 -0
  107. package/umd/src/cli/cli-commands/coder/mergeStringRecordJsonFile.d.ts +18 -0
  108. package/umd/src/cli/cli-commands/coder/printInitializationSummary.d.ts +7 -0
  109. package/umd/src/cli/cli-commands/coder/readTextFileIfExists.d.ts +6 -0
  110. package/umd/src/types/string_agent_url.d.ts +7 -0
  111. package/umd/src/types/string_agent_url_private.d.ts +9 -0
  112. package/umd/src/types/string_base64.d.ts +13 -0
  113. package/umd/src/types/string_base64_private.d.ts +2 -2
  114. package/umd/src/types/string_base_url.d.ts +7 -0
  115. package/umd/src/types/string_base_url_private.d.ts +9 -0
  116. package/umd/src/types/string_email.d.ts +13 -0
  117. package/umd/src/types/string_email_private.d.ts +2 -2
  118. package/umd/src/types/string_host.d.ts +42 -0
  119. package/umd/src/types/string_host_private.d.ts +7 -7
  120. package/umd/src/types/string_href.d.ts +19 -0
  121. package/umd/src/types/string_href_private.d.ts +24 -0
  122. package/umd/src/types/string_mime_type.d.ts +15 -0
  123. package/umd/src/types/string_mime_type_private.d.ts +2 -2
  124. package/umd/src/types/string_pipeline_root_url.d.ts +7 -0
  125. package/umd/src/types/string_pipeline_root_url_private.d.ts +9 -0
  126. package/umd/src/types/string_pipeline_url.d.ts +13 -0
  127. package/umd/src/types/string_pipeline_url_private.d.ts +17 -0
  128. package/umd/src/types/string_promptbook_server_url.d.ts +7 -0
  129. package/umd/src/types/string_promptbook_server_url_private.d.ts +9 -0
  130. package/umd/src/types/string_url.d.ts +14 -141
  131. package/umd/src/types/string_url_image.d.ts +7 -0
  132. package/umd/src/types/string_url_image_private.d.ts +9 -0
  133. package/umd/src/types/string_url_private.d.ts +0 -80
  134. package/umd/src/version.d.ts +1 -1
package/esm/index.es.js CHANGED
@@ -5,7 +5,7 @@ import * as fs from 'fs';
5
5
  import { mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs';
6
6
  import * as path from 'path';
7
7
  import { join, basename, dirname, isAbsolute, relative, extname, resolve } from 'path';
8
- import { writeFile, readFile, stat, mkdir, access, constants, readdir, watch, unlink, rm, rename, rmdir } from 'fs/promises';
8
+ import { readFile, writeFile, stat, mkdir, access, constants, readdir, watch, unlink, rm, rename, rmdir } from 'fs/promises';
9
9
  import { forTime, forEver } from 'waitasecond';
10
10
  import prompts from 'prompts';
11
11
  import * as dotenv from 'dotenv';
@@ -57,7 +57,7 @@ const BOOK_LANGUAGE_VERSION = '2.0.0';
57
57
  * @generated
58
58
  * @see https://github.com/webgptorg/promptbook
59
59
  */
60
- const PROMPTBOOK_ENGINE_VERSION = '0.112.0-36';
60
+ const PROMPTBOOK_ENGINE_VERSION = '0.112.0-38';
61
61
  /**
62
62
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
63
63
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -1661,6 +1661,142 @@ function $initializeCoderFindFreshEmojiTagCommand(program) {
1661
1661
  // Note: [🟡] Code for CLI command [find-fresh-emoji-tags](src/cli/cli-commands/coder/find-fresh-emoji-tags.ts) should never be published outside of `@promptbook/cli`
1662
1662
  // Note: [💞] Ignore a discrepancy between file name and entity name
1663
1663
 
1664
+ /**
1665
+ * Root folders that contain source-like files for scanning.
1666
+ */
1667
+ const SOURCE_ROOTS = ['src', 'apps', 'scripts', 'examples', 'agents', 'other'];
1668
+ /**
1669
+ * File extensions treated as source code.
1670
+ */
1671
+ const SOURCE_FILE_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx'];
1672
+ /**
1673
+ * Glob patterns that should be ignored when scanning for source files.
1674
+ */
1675
+ const SOURCE_FILE_IGNORE_GLOBS = [
1676
+ '**/node_modules/**',
1677
+ '**/packages/**',
1678
+ '**/.*/**',
1679
+ '**/.git/**',
1680
+ '**/.idea/**',
1681
+ '**/.vscode/**',
1682
+ '**/.promptbook/**',
1683
+ '**/.next/**',
1684
+ '**/.tmp/**',
1685
+ '**/tmp/**',
1686
+ '**/coverage/**',
1687
+ '**/dist/**',
1688
+ '**/build/**',
1689
+ '**/out/**',
1690
+ '**/prompts/**',
1691
+ '**/changelog/**',
1692
+ ];
1693
+ /**
1694
+ * Glob patterns that are exempt from line-count checks.
1695
+ */
1696
+ const LINE_COUNT_EXEMPT_GLOBS = ['other/cspell-dictionaries/**/*.txt'];
1697
+ /**
1698
+ * File extensions eligible for structural AST analysis.
1699
+ */
1700
+ const STRUCTURAL_ANALYSIS_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx'];
1701
+ /**
1702
+ * Markers that identify generated files which should be skipped.
1703
+ */
1704
+ const GENERATED_CODE_MARKERS = [
1705
+ 'WARNING: This code has been generated',
1706
+ 'This code has been generated so that any manual changes will be overwritten',
1707
+ ];
1708
+ /**
1709
+ * Name of the prompts directory.
1710
+ */
1711
+ const PROMPTS_DIR_NAME = 'prompts';
1712
+ /**
1713
+ * Step size used for prompt numbering.
1714
+ */
1715
+ const PROMPT_NUMBER_STEP = 10;
1716
+ /**
1717
+ * Prefix used for generated prompt slugs.
1718
+ */
1719
+ const PROMPT_SLUG_PREFIX = 'refactor';
1720
+ /**
1721
+ * Label used to mark the target file in generated prompts.
1722
+ */
1723
+ const PROMPT_TARGET_LABEL = 'Target file';
1724
+ /**
1725
+ * Maximum length for generated prompt slugs.
1726
+ */
1727
+ const PROMPT_SLUG_MAX_LENGTH = 80;
1728
+ /**
1729
+ * Note: [?] Code in this file should never be published in any package
1730
+ */
1731
+
1732
+ /**
1733
+ * Supported aggressiveness levels for refactor-candidate scanning.
1734
+ */
1735
+ const REFACTOR_CANDIDATE_LEVEL_VALUES = ['low', 'medium', 'high', 'xhigh'];
1736
+ /**
1737
+ * Default aggressiveness level for refactor-candidate scanning.
1738
+ */
1739
+ const DEFAULT_REFACTOR_CANDIDATE_LEVEL = 'medium';
1740
+ /**
1741
+ * Threshold table for each supported refactor-candidate scanning level.
1742
+ */
1743
+ const REFACTOR_CANDIDATE_LEVEL_CONFIGURATION_BY_LEVEL = {
1744
+ low: createRefactorCandidateLevelConfiguration({
1745
+ maxLineCount: 2800,
1746
+ maxEntityCountPerFile: 28,
1747
+ maxFunctionCountPerFile: 18,
1748
+ maxFunctionComplexity: 20,
1749
+ }),
1750
+ medium: createRefactorCandidateLevelConfiguration({
1751
+ maxLineCount: 2000,
1752
+ maxEntityCountPerFile: 20,
1753
+ maxFunctionCountPerFile: 14,
1754
+ maxFunctionComplexity: 16,
1755
+ }),
1756
+ high: createRefactorCandidateLevelConfiguration({
1757
+ maxLineCount: 1500,
1758
+ maxEntityCountPerFile: 16,
1759
+ maxFunctionCountPerFile: 10,
1760
+ maxFunctionComplexity: 12,
1761
+ }),
1762
+ xhigh: createRefactorCandidateLevelConfiguration({
1763
+ maxLineCount: 1000,
1764
+ maxEntityCountPerFile: 12,
1765
+ maxFunctionCountPerFile: 8,
1766
+ maxFunctionComplexity: 8,
1767
+ }),
1768
+ };
1769
+ /**
1770
+ * Resolves the thresholds for a selected refactor-candidate scanning level.
1771
+ */
1772
+ function getRefactorCandidateLevelConfiguration(level = DEFAULT_REFACTOR_CANDIDATE_LEVEL) {
1773
+ return REFACTOR_CANDIDATE_LEVEL_CONFIGURATION_BY_LEVEL[level];
1774
+ }
1775
+ /**
1776
+ * Builds one normalized refactor-candidate level configuration entry.
1777
+ */
1778
+ function createRefactorCandidateLevelConfiguration(options) {
1779
+ const { maxLineCount, maxEntityCountPerFile, maxFunctionCountPerFile, maxFunctionComplexity } = options;
1780
+ return {
1781
+ maxDefaultLineCount: maxLineCount,
1782
+ maxLineCountByExtension: createLineCountLimits(maxLineCount),
1783
+ maxEntityCountPerFile,
1784
+ maxFunctionCountPerFile,
1785
+ maxFunctionComplexity,
1786
+ };
1787
+ }
1788
+ /**
1789
+ * Creates a per-extension line-count table using one shared threshold.
1790
+ */
1791
+ function createLineCountLimits(maxLineCount) {
1792
+ const maxLineCountByExtension = {};
1793
+ for (const extension of SOURCE_FILE_EXTENSIONS) {
1794
+ maxLineCountByExtension[extension] = maxLineCount;
1795
+ }
1796
+ return maxLineCountByExtension;
1797
+ }
1798
+ // Note: [🟡] Code for repository script [RefactorCandidateLevel](scripts/find-refactor-candidates/RefactorCandidateLevel.ts) should never be published outside of `@promptbook/cli`
1799
+
1664
1800
  /**
1665
1801
  * Initializes `coder find-refactor-candidates` command for Promptbook CLI utilities
1666
1802
  *
@@ -1673,17 +1809,23 @@ function $initializeCoderFindRefactorCandidatesCommand(program) {
1673
1809
  command.description(spaceTrim$1(`
1674
1810
  Scan source files to identify refactoring candidates
1675
1811
 
1676
- Flags files that exceed:
1677
- - Line count limits (500 lines per file by extension)
1678
- - Entity count limits (max 4 entities per file)
1812
+ Levels:
1813
+ - low: Conservative scan for only the most obvious refactor targets
1814
+ - medium: Default scan using the current standard thresholds
1815
+ - high: Stricter scan that finds more crowded or complex files
1816
+ - xhigh: Most aggressive scan for denser and more complex candidates
1679
1817
 
1680
1818
  Generates refactor prompts with guidance for identified candidates.
1681
1819
  `));
1682
- command.action(handleActionErrors(async () => {
1820
+ command.addOption(new Option('--level <level>', `Set scan aggressiveness (${REFACTOR_CANDIDATE_LEVEL_VALUES.join(', ')})`)
1821
+ .choices([...REFACTOR_CANDIDATE_LEVEL_VALUES])
1822
+ .default(DEFAULT_REFACTOR_CANDIDATE_LEVEL));
1823
+ command.action(handleActionErrors(async (cliOptions) => {
1824
+ const { level = DEFAULT_REFACTOR_CANDIDATE_LEVEL } = cliOptions;
1683
1825
  // Note: Import the function dynamically to avoid loading heavy dependencies until needed
1684
1826
  const { findRefactorCandidates } = await Promise.resolve().then(function () { return findRefactorCandidates$1; });
1685
1827
  try {
1686
- await findRefactorCandidates();
1828
+ await findRefactorCandidates({ level });
1687
1829
  }
1688
1830
  catch (error) {
1689
1831
  assertsError(error);
@@ -1729,7 +1871,9 @@ const PROMPTS_DONE_DIRECTORY_PATH = join(PROMPTS_DIRECTORY_PATH, 'done');
1729
1871
  */
1730
1872
  const PROMPTS_TEMPLATES_DIRECTORY_PATH = join(PROMPTS_DIRECTORY_PATH, 'templates');
1731
1873
  /**
1732
- * Built-in boilerplate templates shared by `coder init` and `coder generate-boilerplates`.
1874
+ * Built-in boilerplate templates available to `coder generate-boilerplates`.
1875
+ *
1876
+ * Only the project-agnostic subset is materialized by `coder init`.
1733
1877
  */
1734
1878
  const DEFAULT_CODER_PROMPT_TEMPLATE_DEFINITIONS = [
1735
1879
  {
@@ -1738,10 +1882,11 @@ const DEFAULT_CODER_PROMPT_TEMPLATE_DEFINITIONS = [
1738
1882
  slugPrefix: null,
1739
1883
  content: buildCoderPromptTemplateContent([
1740
1884
  '- @@@',
1741
- '- Keep in mind the DRY _(don\'t repeat yourself)_ principle.',
1885
+ "- Keep in mind the DRY _(don't repeat yourself)_ principle.",
1742
1886
  '- Do a proper analysis of the current functionality before you start implementing.',
1743
1887
  '- Add the changes into the [changelog](./changelog/_current-preversion.md)',
1744
1888
  ]),
1889
+ isDefaultProjectTemplate: true,
1745
1890
  },
1746
1891
  {
1747
1892
  id: 'agents-server',
@@ -1749,14 +1894,19 @@ const DEFAULT_CODER_PROMPT_TEMPLATE_DEFINITIONS = [
1749
1894
  slugPrefix: 'agents-server',
1750
1895
  content: buildCoderPromptTemplateContent([
1751
1896
  '- @@@',
1752
- '- Keep in mind the DRY _(don\'t repeat yourself)_ principle.',
1897
+ "- Keep in mind the DRY _(don't repeat yourself)_ principle.",
1753
1898
  '- Do a proper analysis of the current functionality before you start implementing.',
1754
1899
  '- You are working with the [Agents Server](apps/agents-server)',
1755
1900
  '- If you need to do the database migration, do it',
1756
1901
  '- Add the changes into the [changelog](changelog/_current-preversion.md)',
1757
1902
  ]),
1903
+ isDefaultProjectTemplate: false,
1758
1904
  },
1759
1905
  ];
1906
+ /**
1907
+ * Project-agnostic coder templates that `ptbk coder init` should materialize in any repository.
1908
+ */
1909
+ const DEFAULT_CODER_PROJECT_PROMPT_TEMPLATE_DEFINITIONS = DEFAULT_CODER_PROMPT_TEMPLATE_DEFINITIONS.filter(({ isDefaultProjectTemplate }) => isDefaultProjectTemplate);
1760
1910
  /**
1761
1911
  * Lists the built-in coder boilerplate templates.
1762
1912
  *
@@ -1765,6 +1915,14 @@ const DEFAULT_CODER_PROMPT_TEMPLATE_DEFINITIONS = [
1765
1915
  function getDefaultCoderPromptTemplateDefinitions() {
1766
1916
  return DEFAULT_CODER_PROMPT_TEMPLATE_DEFINITIONS;
1767
1917
  }
1918
+ /**
1919
+ * Lists the built-in coder prompt templates that are safe to initialize in any project.
1920
+ *
1921
+ * @private internal utility of `ptbk coder`
1922
+ */
1923
+ function getDefaultCoderProjectPromptTemplateDefinitions() {
1924
+ return DEFAULT_CODER_PROJECT_PROMPT_TEMPLATE_DEFINITIONS;
1925
+ }
1768
1926
  /**
1769
1927
  * Resolves one built-in coder boilerplate template definition by its stable identifier.
1770
1928
  *
@@ -1784,7 +1942,7 @@ function getDefaultCoderPromptTemplateDefinition(template) {
1784
1942
  */
1785
1943
  async function ensureDefaultCoderPromptTemplateFiles(projectPath) {
1786
1944
  const ensuredTemplateFiles = [];
1787
- for (const definition of DEFAULT_CODER_PROMPT_TEMPLATE_DEFINITIONS) {
1945
+ for (const definition of DEFAULT_CODER_PROJECT_PROMPT_TEMPLATE_DEFINITIONS) {
1788
1946
  const absoluteTemplatePath = join(projectPath, definition.relativeFilePath);
1789
1947
  if (await isExistingFile$1(absoluteTemplatePath)) {
1790
1948
  ensuredTemplateFiles.push({
@@ -2050,178 +2208,202 @@ function buildPromptSlug$1(templateSlugPrefix, title) {
2050
2208
  // Note: [💞] Ignore a discrepancy between file name and entity name
2051
2209
 
2052
2210
  /**
2053
- * This error indicates that the promptbook in a markdown format cannot be parsed into a valid promptbook object
2211
+ * Relative path to the shared coder context file initialized in project roots.
2054
2212
  *
2055
- * @public exported from `@promptbook/core`
2213
+ * @private internal utility of `ptbk coder`
2056
2214
  */
2057
- class ParseError extends Error {
2058
- constructor(message) {
2059
- super(message);
2060
- this.name = 'ParseError';
2061
- Object.setPrototypeOf(this, ParseError.prototype);
2062
- }
2063
- }
2064
- // TODO: Maybe split `ParseError` and `ApplyError`
2065
-
2215
+ const AGENTS_FILE_PATH = 'AGENTS.md';
2066
2216
  /**
2067
- * Required environment variables for coding-agent git identity.
2217
+ * Stable boilerplate instructions written into newly initialized `AGENTS.md` files.
2068
2218
  */
2069
- const REQUIRED_CODER_ENV_VARIABLES = [
2070
- {
2071
- name: 'CODING_AGENT_GIT_NAME',
2072
- value: 'Promptbook Coding Agent',
2073
- },
2074
- {
2075
- name: 'CODING_AGENT_GIT_EMAIL',
2076
- value: 'coding-agent@promptbook.studio',
2077
- },
2078
- {
2079
- name: 'CODING_AGENT_GIT_SIGNING_KEY',
2080
- value: '13406525ED912F938FEA85AB4046C687298B2382',
2081
- },
2219
+ const DEFAULT_CODER_AGENTS_FILE_LINES = [
2220
+ '<!-- TODO: Write instructions for the Promptbook AI Coder here -->',
2082
2221
  ];
2083
2222
  /**
2084
- * Default npm scripts initialized by `ptbk coder init`.
2223
+ * Shared markdown boilerplate written into new `AGENTS.md` files.
2085
2224
  */
2086
- const DEFAULT_CODER_PACKAGE_JSON_SCRIPTS = {
2087
- 'coder:generate-boilerplates': 'npx ptbk coder generate-boilerplates',
2088
- 'coder:run': 'npx ptbk coder run --agent github-copilot --model gpt-5.4 --thinking-level xhigh --context AGENTS.md --no-wait',
2089
- 'coder:find-refactor-candidates': 'npx ptbk coder find-refactor-candidates',
2090
- 'coder:verify': 'npx ptbk coder verify',
2091
- };
2225
+ const DEFAULT_CODER_AGENTS_FILE_CONTENT = DEFAULT_CODER_AGENTS_FILE_LINES.join('\n');
2092
2226
  /**
2093
- * Relative path to `.gitignore` in the initialized project.
2094
- */
2095
- const GITIGNORE_FILE_PATH = '.gitignore';
2096
- /**
2097
- * Relative path to `package.json` in the initialized project.
2098
- */
2099
- const PACKAGE_JSON_FILE_PATH = 'package.json';
2100
- /**
2101
- * Relative path to the VS Code settings file initialized by `ptbk coder init`.
2227
+ * Returns the default coder `AGENTS.md` boilerplate instructions.
2228
+ *
2229
+ * @private internal utility of `ptbk coder`
2102
2230
  */
2103
- const VSCODE_SETTINGS_FILE_PATH = '.vscode/settings.json';
2231
+ function getDefaultCoderAgentsFileContent() {
2232
+ return DEFAULT_CODER_AGENTS_FILE_CONTENT;
2233
+ }
2234
+ // Note: [🟡] Code for coder AGENTS file boilerplate [agentsFile](src/cli/cli-commands/coder/agentsFile.ts) should never be published outside of `@promptbook/cli`
2235
+ // Note: [💞] Ignore a discrepancy between file name and exported helper names
2236
+
2104
2237
  /**
2105
- * Relative path to the VS Code directory initialized by `ptbk coder init`.
2238
+ * Normalizes one project-relative path for human-readable CLI output and markdown.
2239
+ *
2240
+ * @private internal utility of `ptbk coder`
2106
2241
  */
2107
- const VSCODE_DIRECTORY_PATH = '.vscode';
2242
+ function formatDisplayPath(relativePath) {
2243
+ return relativePath.replace(/\\/gu, '/');
2244
+ }
2245
+ // Note: [🟡] Code for coder path formatting [formatDisplayPath](src/cli/cli-commands/coder/formatDisplayPath.ts) should never be published outside of `@promptbook/cli`
2246
+
2108
2247
  /**
2109
- * VS Code setting key used to route pasted markdown images into prompt-specific screenshots.
2248
+ * Relative path to the Promptbook Coder quick-reference file initialized in project roots.
2249
+ *
2250
+ * @private internal utility of `ptbk coder`
2110
2251
  */
2111
- const MARKDOWN_COPY_FILES_DESTINATION_SETTING_KEY = 'markdown.copyFiles.destination';
2252
+ const AGENT_CODING_FILE_PATH = 'AGENT_CODING.md';
2112
2253
  /**
2113
- * Markdown glob used for coder prompt files inside VS Code settings.
2254
+ * Returns the default coder `AGENT_CODING.md` quick-reference content.
2255
+ *
2256
+ * @private internal utility of `ptbk coder`
2114
2257
  */
2115
- const PROMPTS_MARKDOWN_FILE_GLOB = 'prompts/*md';
2258
+ function getDefaultCoderAgentCodingFileContent({ packageJsonScripts, }) {
2259
+ return [
2260
+ '# Promptbook Coder quick reference',
2261
+ '',
2262
+ `This project is prepared for the \`ptbk coder\` workflow. Promptbook Coder does not create a new model on its own; it orchestrates coding agents such as GitHub Copilot, OpenAI Codex, Claude Code, Opencode, Cline, and Gemini CLI through prompt files in \`${formatDisplayPath(PROMPTS_DIRECTORY_PATH)}/\`.`,
2263
+ '',
2264
+ '## Workflow',
2265
+ `1. Put repository-wide coding rules into \`${AGENTS_FILE_PATH}\`. The default \`npm run coder:run\` script already passes \`--context ${AGENTS_FILE_PATH}\`.`,
2266
+ `2. Create or customize prompt templates in \`${formatDisplayPath(PROMPTS_TEMPLATES_DIRECTORY_PATH)}/\`. ${buildStarterTemplateSentence()}`,
2267
+ '3. Generate prompt files with `npm run coder:generate-boilerplates` or `npx ptbk coder generate-boilerplates --template <template> --count <count>`.',
2268
+ '4. Replace every `@@@`, keep drafts as `[-]`, and switch prompts to `[ ]` when they are ready to run. Completed prompts are marked `[x]`.',
2269
+ '5. Run `npm run coder:run` to execute the next ready prompt with the configured coding agent.',
2270
+ `6. Use \`npm run coder:verify\` to archive finished prompts into \`${formatDisplayPath(PROMPTS_DONE_DIRECTORY_PATH)}/\` and append repair follow-up prompts when more work is needed.`,
2271
+ '7. Use `npm run coder:find-refactor-candidates` when you want Promptbook to suggest refactor prompts automatically.',
2272
+ '',
2273
+ '## Templates',
2274
+ `- Project-owned templates created by \`ptbk coder init\`: ${formatInlineCodeList(getDefaultCoderProjectPromptTemplateDefinitions().map(({ relativeFilePath }) => formatDisplayPath(relativeFilePath)))}`,
2275
+ `- Built-in \`--template\` aliases: ${formatInlineCodeList(getDefaultCoderPromptTemplateDefinitions().map(({ id }) => id))}`,
2276
+ `- To add a custom template, create a markdown file such as \`${formatDisplayPath(PROMPTS_TEMPLATES_DIRECTORY_PATH)}/backend.md\`.`,
2277
+ `- To use a project template, run \`npx ptbk coder generate-boilerplates --template ${formatDisplayPath(PROMPTS_TEMPLATES_DIRECTORY_PATH)}/backend.md\`.`,
2278
+ `- Keep shared repository rules in \`${AGENTS_FILE_PATH}\` and recurring task-family rules in template files so individual prompt files stay focused on the actual task.`,
2279
+ '',
2280
+ '## Created npm scripts',
2281
+ '| Script | Purpose |',
2282
+ '| --- | --- |',
2283
+ ...buildPackageJsonScriptTableLines(packageJsonScripts),
2284
+ '',
2285
+ '## Customizing the workflow',
2286
+ '- Edit `package.json` if you want `npm run coder:run` to use another coding agent, model, thinking level, context file, or wait mode.',
2287
+ '- Use direct CLI commands when you need one-off flags such as `--priority`, `--ignore-git-changes`, `--dry-run`, `--allow-credits`, or `--auto-migrate`.',
2288
+ '- Use `npx ptbk coder --help` and `npx ptbk coder <command> --help` for the full CLI reference.',
2289
+ ].join('\n');
2290
+ }
2116
2291
  /**
2117
- * Screenshot destination used for pasted prompt images inside VS Code settings.
2292
+ * Builds the sentence describing the starter templates created during initialization.
2118
2293
  */
2119
- const PROMPTS_SCREENSHOT_DESTINATION = './prompts/screenshots/${documentBaseName}.png';
2294
+ function buildStarterTemplateSentence() {
2295
+ const starterTemplatePaths = getDefaultCoderProjectPromptTemplateDefinitions().map(({ relativeFilePath }) => formatDisplayPath(relativeFilePath));
2296
+ if (starterTemplatePaths.length === 1) {
2297
+ return `The starter project template created by \`ptbk coder init\` is \`${starterTemplatePaths[0]}\`.`;
2298
+ }
2299
+ return `The starter project templates created by \`ptbk coder init\` are ${formatInlineCodeList(starterTemplatePaths)}.`;
2300
+ }
2120
2301
  /**
2121
- * Default indentation used when creating new JSON configuration files.
2302
+ * Builds the markdown table rows describing the initialized npm scripts.
2122
2303
  */
2123
- const DEFAULT_JSON_FILE_INDENTATION = ' ';
2304
+ function buildPackageJsonScriptTableLines(packageJsonScripts) {
2305
+ return Object.entries(packageJsonScripts).map(([scriptName, scriptCommand]) => `| \`npm run ${scriptName}\` | ${describeDefaultCoderPackageJsonScript(scriptName, scriptCommand)} |`);
2306
+ }
2124
2307
  /**
2125
- * Default newline used when creating new JSON configuration files.
2308
+ * Describes one initialized npm script in human-readable terms.
2126
2309
  */
2127
- const DEFAULT_JSON_FILE_NEWLINE = '\n';
2310
+ function describeDefaultCoderPackageJsonScript(scriptName, scriptCommand) {
2311
+ if (scriptName === 'coder:generate-boilerplates') {
2312
+ return `Runs \`${scriptCommand}\` to create new prompt files in \`${formatDisplayPath(PROMPTS_DIRECTORY_PATH)}/\`.`;
2313
+ }
2314
+ if (scriptName === 'coder:run') {
2315
+ return `Runs \`${scriptCommand}\` to execute the next ready prompt with shared repository context from \`${AGENTS_FILE_PATH}\`.`;
2316
+ }
2317
+ if (scriptName === 'coder:find-refactor-candidates') {
2318
+ return `Runs \`${scriptCommand}\` to generate prompt candidates for large or crowded files.`;
2319
+ }
2320
+ if (scriptName === 'coder:verify') {
2321
+ return `Runs \`${scriptCommand}\` to archive verified prompts into \`${formatDisplayPath(PROMPTS_DONE_DIRECTORY_PATH)}/\` and append repair prompts when needed.`;
2322
+ }
2323
+ return `Runs \`${scriptCommand}\`.`;
2324
+ }
2128
2325
  /**
2129
- * `.gitignore` block required by standalone Promptbook coder projects.
2326
+ * Formats one inline code list for human-readable markdown.
2130
2327
  */
2131
- const CODER_GITIGNORE_BLOCK = spaceTrim$1(`
2132
- # Promptbook Coder
2133
- /.tmp
2134
- `);
2328
+ function formatInlineCodeList(values) {
2329
+ return values.map((value) => `\`${value}\``).join(', ');
2330
+ }
2331
+ // Note: [🟡] Code for coder AGENT_CODING file boilerplate [agentCodingFile](src/cli/cli-commands/coder/agentCodingFile.ts) should never be published outside of `@promptbook/cli`
2332
+ // Note: [💞] Ignore a discrepancy between file name and exported helper names
2333
+
2135
2334
  /**
2136
- * Initializes `coder init` command for Promptbook CLI utilities.
2137
- *
2138
- * Note: `$` is used to indicate that this function is not a pure function - it registers a command in the CLI.
2335
+ * Appends one text block to existing file content while preserving readable newlines.
2139
2336
  *
2140
- * @private internal function of `promptbookCli`
2337
+ * @private function of `initializeCoderProjectConfiguration`
2141
2338
  */
2142
- function $initializeCoderInitCommand(program) {
2143
- const command = program.command('init');
2144
- command.alias('initialize');
2145
- command.description(spaceTrim$1(`
2146
- Initialize Promptbook coder configuration for current project
2147
-
2148
- Creates or updates:
2149
- - prompts/
2150
- - prompts/done/
2151
- - prompts/templates/common.md
2152
- - prompts/templates/agents-server.md
2153
- - .gitignore
2154
- - package.json
2155
- - .vscode/settings.json
2156
-
2157
- Ensures required coding-agent environment variables in .env:
2158
- - CODING_AGENT_GIT_NAME
2159
- - CODING_AGENT_GIT_EMAIL
2160
- - CODING_AGENT_GIT_SIGNING_KEY
2161
- `));
2162
- command.action(handleActionErrors(async () => {
2163
- const summary = await initializeCoderProjectConfiguration(process.cwd());
2164
- printInitializationSummary(summary);
2165
- }));
2339
+ function appendBlock(currentContent, blockToAppend) {
2340
+ if (currentContent.trim() === '') {
2341
+ return `${blockToAppend}\n`;
2342
+ }
2343
+ const normalizedCurrentContent = currentContent.endsWith('\n') ? currentContent : `${currentContent}\n`;
2344
+ return `${normalizedCurrentContent}\n${blockToAppend}\n`;
2166
2345
  }
2346
+ // Note: [🟡] Code for coder init text appending [appendBlock](src/cli/cli-commands/coder/appendBlock.ts) should never be published outside of `@promptbook/cli`
2347
+
2167
2348
  /**
2168
- * Lists the default npm scripts initialized by `ptbk coder init`.
2349
+ * Reads one text file when it exists, otherwise returns `undefined`.
2169
2350
  *
2170
- * @private internal utility of `coder init` command
2351
+ * @private function of `initializeCoderProjectConfiguration`
2171
2352
  */
2172
- function getDefaultCoderPackageJsonScripts() {
2173
- return DEFAULT_CODER_PACKAGE_JSON_SCRIPTS;
2353
+ async function readTextFileIfExists(path) {
2354
+ try {
2355
+ const fileStats = await stat(path);
2356
+ if (!fileStats.isFile()) {
2357
+ return undefined;
2358
+ }
2359
+ }
2360
+ catch (_a) {
2361
+ return undefined;
2362
+ }
2363
+ return readFile(path, 'utf-8');
2174
2364
  }
2365
+ // Note: [🟡] Code for coder init text-file reading [readTextFileIfExists](src/cli/cli-commands/coder/readTextFileIfExists.ts) should never be published outside of `@promptbook/cli`
2366
+
2175
2367
  /**
2176
- * Creates or updates all coder configuration artifacts required in the current project.
2177
- *
2178
- * @private internal utility of `coder init` command
2368
+ * Relative path to `.env` in the initialized project.
2179
2369
  */
2180
- async function initializeCoderProjectConfiguration(projectPath) {
2181
- const promptsDirectoryStatus = await ensureDirectory(projectPath, PROMPTS_DIRECTORY_PATH);
2182
- const promptsDoneDirectoryStatus = await ensureDirectory(projectPath, PROMPTS_DONE_DIRECTORY_PATH);
2183
- const promptsTemplatesDirectoryStatus = await ensureDirectory(projectPath, PROMPTS_TEMPLATES_DIRECTORY_PATH);
2184
- const promptTemplateFileStatuses = await ensureDefaultCoderPromptTemplateFiles(projectPath);
2185
- const { envFileStatus, initializedEnvVariableNames } = await ensureCoderEnvFile(projectPath);
2186
- const gitignoreFileStatus = await ensureCoderGitignoreFile(projectPath);
2187
- const packageJsonFileStatus = await ensureCoderPackageJsonFile(projectPath);
2188
- const vscodeSettingsFileStatus = await ensureCoderVscodeSettingsFile(projectPath);
2189
- return {
2190
- promptsDirectoryStatus,
2191
- promptsDoneDirectoryStatus,
2192
- promptsTemplatesDirectoryStatus,
2193
- promptTemplateFileStatuses,
2194
- envFileStatus,
2195
- gitignoreFileStatus,
2196
- packageJsonFileStatus,
2197
- vscodeSettingsFileStatus,
2198
- initializedEnvVariableNames,
2199
- };
2200
- }
2370
+ const ENV_FILE_PATH = '.env';
2201
2371
  /**
2202
- * Ensures a relative directory exists in the project root.
2372
+ * Fallback `.env` content used when no required variables need to be appended.
2203
2373
  */
2204
- async function ensureDirectory(projectPath, relativeDirectoryPath) {
2205
- const directoryPath = join(projectPath, relativeDirectoryPath);
2206
- const existedBefore = await isExistingDirectory(directoryPath);
2207
- if (!existedBefore) {
2208
- await mkdir(directoryPath, { recursive: true });
2209
- return 'created';
2210
- }
2211
- return 'unchanged';
2212
- }
2374
+ const EMPTY_CODER_ENV_FILE_CONTENT = '# Environment variables for Promptbook coder\n';
2375
+ /**
2376
+ * Required environment variables for coding-agent git identity.
2377
+ */
2378
+ const REQUIRED_CODER_ENV_VARIABLES = [
2379
+ {
2380
+ name: 'CODING_AGENT_GIT_NAME',
2381
+ value: 'Promptbook Coding Agent',
2382
+ },
2383
+ {
2384
+ name: 'CODING_AGENT_GIT_EMAIL',
2385
+ value: 'coding-agent@promptbook.studio',
2386
+ },
2387
+ {
2388
+ name: 'CODING_AGENT_GIT_SIGNING_KEY',
2389
+ value: '13406525ED912F938FEA85AB4046C687298B2382',
2390
+ },
2391
+ ];
2213
2392
  /**
2214
2393
  * Ensures `.env` exists and contains all required coder environment variables.
2394
+ *
2395
+ * @private function of `initializeCoderProjectConfiguration`
2215
2396
  */
2216
2397
  async function ensureCoderEnvFile(projectPath) {
2217
- const envFilePath = join(projectPath, '.env');
2218
- const envFileExistedBefore = await isExistingFile(envFilePath);
2219
- const currentEnvContent = envFileExistedBefore ? await readFile(envFilePath, 'utf-8') : '';
2220
- const existingEnvVariables = parseEnvVariableNames(currentEnvContent);
2221
- const missingEnvVariables = REQUIRED_CODER_ENV_VARIABLES.filter(({ name }) => !existingEnvVariables.has(name));
2398
+ const envFilePath = join(projectPath, ENV_FILE_PATH);
2399
+ const existingEnvContent = await readTextFileIfExists(envFilePath);
2400
+ const isEnvFileExisting = existingEnvContent !== undefined;
2401
+ const currentEnvContent = existingEnvContent || '';
2402
+ const existingEnvVariableNames = parseEnvVariableNames(currentEnvContent);
2403
+ const missingEnvVariables = REQUIRED_CODER_ENV_VARIABLES.filter(({ name }) => !existingEnvVariableNames.has(name));
2222
2404
  if (missingEnvVariables.length === 0) {
2223
- if (!envFileExistedBefore) {
2224
- await writeFile(envFilePath, '# Environment variables for Promptbook coder\n', 'utf-8');
2405
+ if (!isEnvFileExisting) {
2406
+ await writeFile(envFilePath, EMPTY_CODER_ENV_FILE_CONTENT, 'utf-8');
2225
2407
  return {
2226
2408
  envFileStatus: 'created',
2227
2409
  initializedEnvVariableNames: [],
@@ -2236,12 +2418,54 @@ async function ensureCoderEnvFile(projectPath) {
2236
2418
  const nextEnvContent = appendBlock(currentEnvContent, envBlockToAppend);
2237
2419
  await writeFile(envFilePath, nextEnvContent, 'utf-8');
2238
2420
  return {
2239
- envFileStatus: envFileExistedBefore ? 'updated' : 'created',
2421
+ envFileStatus: isEnvFileExisting ? 'updated' : 'created',
2240
2422
  initializedEnvVariableNames: missingEnvVariables.map(({ name }) => name),
2241
2423
  };
2242
2424
  }
2425
+ /**
2426
+ * Parses variable names currently defined in `.env` style content.
2427
+ */
2428
+ function parseEnvVariableNames(envContent) {
2429
+ const variableNames = new Set();
2430
+ for (const line of envContent.split(/\r?\n/)) {
2431
+ const trimmedLine = line.trim();
2432
+ if (trimmedLine === '' || trimmedLine.startsWith('#')) {
2433
+ continue;
2434
+ }
2435
+ const match = trimmedLine.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=/);
2436
+ if (!match || !match[1]) {
2437
+ continue;
2438
+ }
2439
+ variableNames.add(match[1]);
2440
+ }
2441
+ return variableNames;
2442
+ }
2443
+ /**
2444
+ * Builds a `.env` block containing missing coder environment variables.
2445
+ */
2446
+ function buildMissingEnvVariablesBlock(variables) {
2447
+ return spaceTrim$1(`
2448
+ # Promptbook coder identity (initialized by \`ptbk coder init\`)
2449
+ ${variables.map(({ name, value }) => `${name}=${JSON.stringify(value)}`).join('\n')}
2450
+ `);
2451
+ }
2452
+ // Note: [🟡] Code for coder init environment bootstrapping [ensureCoderEnvFile](src/cli/cli-commands/coder/ensureCoderEnvFile.ts) should never be published outside of `@promptbook/cli`
2453
+
2454
+ /**
2455
+ * Relative path to `.gitignore` in the initialized project.
2456
+ */
2457
+ const GITIGNORE_FILE_PATH = '.gitignore';
2458
+ /**
2459
+ * `.gitignore` block required by standalone Promptbook coder projects.
2460
+ */
2461
+ const CODER_GITIGNORE_BLOCK = spaceTrim$1(`
2462
+ # Promptbook Coder
2463
+ /.tmp
2464
+ `);
2243
2465
  /**
2244
2466
  * Ensures `.gitignore` contains the standalone Promptbook coder cache entry.
2467
+ *
2468
+ * @private function of `initializeCoderProjectConfiguration`
2245
2469
  */
2246
2470
  async function ensureCoderGitignoreFile(projectPath) {
2247
2471
  const gitignorePath = join(projectPath, GITIGNORE_FILE_PATH);
@@ -2254,95 +2478,339 @@ async function ensureCoderGitignoreFile(projectPath) {
2254
2478
  return currentGitignoreContent === undefined ? 'created' : 'updated';
2255
2479
  }
2256
2480
  /**
2257
- * Ensures `package.json` contains the standalone Promptbook coder helper scripts.
2481
+ * Detects whether `.gitignore` already covers the standalone coder temp directory.
2258
2482
  */
2259
- async function ensureCoderPackageJsonFile(projectPath) {
2260
- const packageJsonPath = join(projectPath, PACKAGE_JSON_FILE_PATH);
2261
- const packageJsonContent = await readTextFileIfExists(packageJsonPath);
2262
- const formatting = detectJsonFileFormatting(packageJsonContent);
2263
- const packageJson = packageJsonContent === undefined ? {} : await parseJsonObjectFile(PACKAGE_JSON_FILE_PATH, packageJsonContent);
2264
- const scripts = getStringRecordOrDefault(packageJson['scripts'], PACKAGE_JSON_FILE_PATH, 'scripts');
2265
- let hasChanges = packageJsonContent === undefined;
2266
- const nextScripts = { ...scripts };
2267
- for (const [scriptName, scriptCommand] of Object.entries(getDefaultCoderPackageJsonScripts())) {
2268
- if (nextScripts[scriptName] !== scriptCommand) {
2269
- nextScripts[scriptName] = scriptCommand;
2483
+ function hasTmpGitignoreRule(gitignoreContent) {
2484
+ return /(^|[\r\n])\/?\.tmp(?:[\r\n]|$)/u.test(gitignoreContent);
2485
+ }
2486
+ // Note: [🟡] Code for coder init gitignore bootstrapping [ensureCoderGitignoreFile](src/cli/cli-commands/coder/ensureCoderGitignoreFile.ts) should never be published outside of `@promptbook/cli`
2487
+
2488
+ /**
2489
+ * Ensures one coder markdown file exists with the provided default boilerplate.
2490
+ *
2491
+ * @private function of `initializeCoderProjectConfiguration`
2492
+ */
2493
+ async function ensureCoderMarkdownFile(projectPath, relativeFilePath, fileContent) {
2494
+ const absoluteFilePath = join(projectPath, relativeFilePath);
2495
+ if (await isExistingFile(absoluteFilePath)) {
2496
+ return 'unchanged';
2497
+ }
2498
+ await writeFile(absoluteFilePath, `${fileContent}\n`, 'utf-8');
2499
+ return 'created';
2500
+ }
2501
+ /**
2502
+ * Checks whether a path exists and is a file.
2503
+ */
2504
+ async function isExistingFile(path) {
2505
+ try {
2506
+ return (await stat(path)).isFile();
2507
+ }
2508
+ catch (_a) {
2509
+ return false;
2510
+ }
2511
+ }
2512
+ // Note: [🟡] Code for coder init markdown bootstrapping [ensureCoderMarkdownFile](src/cli/cli-commands/coder/ensureCoderMarkdownFile.ts) should never be published outside of `@promptbook/cli`
2513
+
2514
+ /**
2515
+ * Default npm scripts initialized by `ptbk coder init`.
2516
+ */
2517
+ const DEFAULT_CODER_PACKAGE_JSON_SCRIPTS = {
2518
+ 'coder:generate-boilerplates': 'npx ptbk coder generate-boilerplates',
2519
+ 'coder:run': 'npx ptbk coder run --agent github-copilot --model gpt-5.4 --thinking-level xhigh --context AGENTS.md --no-wait',
2520
+ 'coder:find-refactor-candidates': 'npx ptbk coder find-refactor-candidates',
2521
+ 'coder:verify': 'npx ptbk coder verify',
2522
+ };
2523
+ /**
2524
+ * Lists the default npm scripts initialized by `ptbk coder init`.
2525
+ *
2526
+ * @private internal utility of `coder init` command
2527
+ */
2528
+ function getDefaultCoderPackageJsonScripts() {
2529
+ return DEFAULT_CODER_PACKAGE_JSON_SCRIPTS;
2530
+ }
2531
+ // Note: [🟡] Code for coder init package scripts [getDefaultCoderPackageJsonScripts](src/cli/cli-commands/coder/getDefaultCoderPackageJsonScripts.ts) should never be published outside of `@promptbook/cli`
2532
+
2533
+ /**
2534
+ * This error indicates that the promptbook in a markdown format cannot be parsed into a valid promptbook object
2535
+ *
2536
+ * @public exported from `@promptbook/core`
2537
+ */
2538
+ class ParseError extends Error {
2539
+ constructor(message) {
2540
+ super(message);
2541
+ this.name = 'ParseError';
2542
+ Object.setPrototypeOf(this, ParseError.prototype);
2543
+ }
2544
+ }
2545
+ // TODO: Maybe split `ParseError` and `ApplyError`
2546
+
2547
+ /**
2548
+ * Default indentation used when creating new JSON configuration files.
2549
+ */
2550
+ const DEFAULT_JSON_FILE_INDENTATION = ' ';
2551
+ /**
2552
+ * Default newline used when creating new JSON configuration files.
2553
+ */
2554
+ const DEFAULT_JSON_FILE_NEWLINE = '\n';
2555
+ /**
2556
+ * Ensures one JSON object field contains the provided string-record entries.
2557
+ *
2558
+ * @private function of `initializeCoderProjectConfiguration`
2559
+ */
2560
+ async function mergeStringRecordJsonFile({ projectPath, relativeFilePath, fieldPath, nextEntries, ensureParentDirectoryPath, }) {
2561
+ if (ensureParentDirectoryPath) {
2562
+ await mkdir(join(projectPath, ensureParentDirectoryPath), { recursive: true });
2563
+ }
2564
+ const absoluteFilePath = join(projectPath, relativeFilePath);
2565
+ const fileContent = await readTextFileIfExists(absoluteFilePath);
2566
+ const formatting = detectJsonFileFormatting(fileContent);
2567
+ const jsonObject = fileContent === undefined ? {} : await parseJsonObjectFile(relativeFilePath, fileContent);
2568
+ const existingEntries = getStringRecordOrDefault(jsonObject[fieldPath], relativeFilePath, fieldPath);
2569
+ let hasChanges = fileContent === undefined;
2570
+ const mergedEntries = { ...existingEntries };
2571
+ for (const [entryKey, entryValue] of Object.entries(nextEntries)) {
2572
+ if (mergedEntries[entryKey] !== entryValue) {
2573
+ mergedEntries[entryKey] = entryValue;
2270
2574
  hasChanges = true;
2271
2575
  }
2272
2576
  }
2273
2577
  if (!hasChanges) {
2274
2578
  return 'unchanged';
2275
2579
  }
2276
- const nextPackageJson = { ...packageJson };
2277
- nextPackageJson['scripts'] = nextScripts;
2278
- await writeFile(packageJsonPath, serializeJsonObject(nextPackageJson, formatting), 'utf-8');
2279
- return packageJsonContent === undefined ? 'created' : 'updated';
2580
+ const nextJsonObject = { ...jsonObject };
2581
+ nextJsonObject[fieldPath] = mergedEntries;
2582
+ await writeFile(absoluteFilePath, serializeJsonObject(nextJsonObject, formatting), 'utf-8');
2583
+ return fileContent === undefined ? 'created' : 'updated';
2280
2584
  }
2281
2585
  /**
2282
- * Ensures VS Code routes pasted prompt images into `prompts/screenshots`.
2586
+ * Parses one JSON object file while accepting VS Code style comments and trailing commas.
2283
2587
  */
2284
- async function ensureCoderVscodeSettingsFile(projectPath) {
2285
- await mkdir(join(projectPath, VSCODE_DIRECTORY_PATH), { recursive: true });
2286
- const vscodeSettingsPath = join(projectPath, VSCODE_SETTINGS_FILE_PATH);
2287
- const vscodeSettingsContent = await readTextFileIfExists(vscodeSettingsPath);
2288
- const formatting = detectJsonFileFormatting(vscodeSettingsContent);
2289
- const vscodeSettings = vscodeSettingsContent === undefined
2290
- ? {}
2291
- : await parseJsonObjectFile(VSCODE_SETTINGS_FILE_PATH, vscodeSettingsContent);
2292
- const markdownCopyFilesDestinations = getStringRecordOrDefault(vscodeSettings[MARKDOWN_COPY_FILES_DESTINATION_SETTING_KEY], VSCODE_SETTINGS_FILE_PATH, MARKDOWN_COPY_FILES_DESTINATION_SETTING_KEY);
2293
- let hasChanges = vscodeSettingsContent === undefined;
2294
- const nextMarkdownCopyFilesDestinations = { ...markdownCopyFilesDestinations };
2295
- if (nextMarkdownCopyFilesDestinations[PROMPTS_MARKDOWN_FILE_GLOB] !== PROMPTS_SCREENSHOT_DESTINATION) {
2296
- nextMarkdownCopyFilesDestinations[PROMPTS_MARKDOWN_FILE_GLOB] = PROMPTS_SCREENSHOT_DESTINATION;
2297
- hasChanges = true;
2588
+ async function parseJsonObjectFile(relativeFilePath, fileContent) {
2589
+ if (fileContent.trim() === '') {
2590
+ return {};
2298
2591
  }
2299
- if (!hasChanges) {
2300
- return 'unchanged';
2592
+ const typescript = await import('typescript');
2593
+ const parsedFile = typescript.parseConfigFileTextToJson(relativeFilePath, fileContent);
2594
+ if (parsedFile.error) {
2595
+ throw new ParseError(spaceTrim$1(`
2596
+ Cannot parse \`${relativeFilePath}\` as JSON.
2597
+
2598
+ ${typescript.flattenDiagnosticMessageText(parsedFile.error.messageText, '\n')}
2599
+ `));
2600
+ }
2601
+ if (!isPlainObject(parsedFile.config)) {
2602
+ throw new ParseError(spaceTrim$1(`
2603
+ File \`${relativeFilePath}\` must contain one top-level JSON object.
2604
+ `));
2301
2605
  }
2302
- const nextVscodeSettings = { ...vscodeSettings };
2303
- nextVscodeSettings[MARKDOWN_COPY_FILES_DESTINATION_SETTING_KEY] = nextMarkdownCopyFilesDestinations;
2304
- await writeFile(vscodeSettingsPath, serializeJsonObject(nextVscodeSettings, formatting), 'utf-8');
2305
- return vscodeSettingsContent === undefined ? 'created' : 'updated';
2606
+ return parsedFile.config;
2306
2607
  }
2307
2608
  /**
2308
- * Parses variable names currently defined in `.env` style content.
2609
+ * Reads one JSON object field as a string-to-string record.
2309
2610
  */
2310
- function parseEnvVariableNames(envContent) {
2311
- const variableNames = new Set();
2312
- for (const line of envContent.split(/\r?\n/)) {
2313
- const trimmedLine = line.trim();
2314
- if (trimmedLine === '' || trimmedLine.startsWith('#')) {
2315
- continue;
2316
- }
2317
- const match = trimmedLine.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=/);
2318
- if (!match || !match[1]) {
2319
- continue;
2611
+ function getStringRecordOrDefault(value, relativeFilePath, fieldPath) {
2612
+ if (value === undefined) {
2613
+ return {};
2614
+ }
2615
+ if (!isPlainObject(value)) {
2616
+ throw new ParseError(spaceTrim$1(`
2617
+ File \`${relativeFilePath}\` contains invalid \`${fieldPath}\`.
2618
+
2619
+ Expected \`${fieldPath}\` to be an object with string values.
2620
+ `));
2621
+ }
2622
+ const stringRecord = {};
2623
+ for (const [key, itemValue] of Object.entries(value)) {
2624
+ if (typeof itemValue !== 'string') {
2625
+ throw new ParseError(spaceTrim$1(`
2626
+ File \`${relativeFilePath}\` contains invalid \`${fieldPath}.${key}\`.
2627
+
2628
+ Expected \`${fieldPath}\` to be an object with string values.
2629
+ `));
2320
2630
  }
2321
- variableNames.add(match[1]);
2631
+ stringRecord[key] = itemValue;
2322
2632
  }
2323
- return variableNames;
2633
+ return stringRecord;
2324
2634
  }
2325
2635
  /**
2326
- * Builds a `.env` block containing missing coder environment variables.
2636
+ * Serializes one JSON object using detected or default formatting.
2327
2637
  */
2328
- function buildMissingEnvVariablesBlock(variables) {
2329
- return spaceTrim$1(`
2330
- # Promptbook coder identity (initialized by \`ptbk coder init\`)
2331
- ${variables.map(({ name, value }) => `${name}=${JSON.stringify(value)}`).join('\n')}
2332
- `);
2638
+ function serializeJsonObject(value, formatting) {
2639
+ return `${JSON.stringify(value, null, formatting.indentation)}${formatting.newline}`;
2333
2640
  }
2334
2641
  /**
2335
- * Appends one text block to existing file content while preserving readable newlines.
2642
+ * Detects indentation and newline formatting from an existing JSON file.
2336
2643
  */
2337
- function appendBlock(currentContent, blockToAppend) {
2338
- if (currentContent.trim() === '') {
2339
- return `${blockToAppend}\n`;
2644
+ function detectJsonFileFormatting(fileContent) {
2645
+ if (!fileContent) {
2646
+ return {
2647
+ indentation: DEFAULT_JSON_FILE_INDENTATION,
2648
+ newline: DEFAULT_JSON_FILE_NEWLINE,
2649
+ };
2650
+ }
2651
+ const indentationMatch = fileContent.match(/^[ \t]+(?=")/mu);
2652
+ return {
2653
+ indentation: (indentationMatch === null || indentationMatch === void 0 ? void 0 : indentationMatch[0]) || DEFAULT_JSON_FILE_INDENTATION,
2654
+ newline: fileContent.includes('\r\n') ? '\r\n' : '\n',
2655
+ };
2656
+ }
2657
+ /**
2658
+ * Checks whether one parsed JSON value is a plain object.
2659
+ */
2660
+ function isPlainObject(value) {
2661
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
2662
+ }
2663
+ // Note: [🟡] Code for coder init JSON merging [mergeStringRecordJsonFile](src/cli/cli-commands/coder/mergeStringRecordJsonFile.ts) should never be published outside of `@promptbook/cli`
2664
+
2665
+ /**
2666
+ * Relative path to `package.json` in the initialized project.
2667
+ */
2668
+ const PACKAGE_JSON_FILE_PATH = 'package.json';
2669
+ /**
2670
+ * Ensures `package.json` contains the standalone Promptbook coder helper scripts.
2671
+ *
2672
+ * @private function of `initializeCoderProjectConfiguration`
2673
+ */
2674
+ async function ensureCoderPackageJsonFile(projectPath) {
2675
+ return mergeStringRecordJsonFile({
2676
+ projectPath,
2677
+ relativeFilePath: PACKAGE_JSON_FILE_PATH,
2678
+ fieldPath: 'scripts',
2679
+ nextEntries: getDefaultCoderPackageJsonScripts(),
2680
+ });
2681
+ }
2682
+ // Note: [🟡] Code for coder init package.json bootstrapping [ensureCoderPackageJsonFile](src/cli/cli-commands/coder/ensureCoderPackageJsonFile.ts) should never be published outside of `@promptbook/cli`
2683
+
2684
+ /**
2685
+ * VS Code setting key used to route pasted markdown images into prompt-specific screenshots.
2686
+ */
2687
+ const MARKDOWN_COPY_FILES_DESTINATION_SETTING_KEY = 'markdown.copyFiles.destination';
2688
+ /**
2689
+ * Markdown glob used for coder prompt files inside VS Code settings.
2690
+ */
2691
+ const PROMPTS_MARKDOWN_FILE_GLOB = 'prompts/*md';
2692
+ /**
2693
+ * Screenshot destination used for pasted prompt images inside VS Code settings.
2694
+ */
2695
+ const PROMPTS_SCREENSHOT_DESTINATION = './prompts/screenshots/${documentBaseName}.png';
2696
+ /**
2697
+ * Default VS Code settings initialized by `ptbk coder init`.
2698
+ */
2699
+ const DEFAULT_CODER_VSCODE_SETTINGS = {
2700
+ [MARKDOWN_COPY_FILES_DESTINATION_SETTING_KEY]: {
2701
+ [PROMPTS_MARKDOWN_FILE_GLOB]: PROMPTS_SCREENSHOT_DESTINATION,
2702
+ },
2703
+ };
2704
+ /**
2705
+ * Lists the default VS Code settings initialized by `ptbk coder init`.
2706
+ *
2707
+ * @private internal utility of `coder init` command
2708
+ */
2709
+ function getDefaultCoderVscodeSettings() {
2710
+ return DEFAULT_CODER_VSCODE_SETTINGS;
2711
+ }
2712
+ // Note: [🟡] Code for coder init VS Code settings [getDefaultCoderVscodeSettings](src/cli/cli-commands/coder/getDefaultCoderVscodeSettings.ts) should never be published outside of `@promptbook/cli`
2713
+
2714
+ /**
2715
+ * Relative path to the VS Code settings file initialized by `ptbk coder init`.
2716
+ */
2717
+ const VSCODE_SETTINGS_FILE_PATH = '.vscode/settings.json';
2718
+ /**
2719
+ * Relative path to the VS Code directory initialized by `ptbk coder init`.
2720
+ */
2721
+ const VSCODE_DIRECTORY_PATH = '.vscode';
2722
+ /**
2723
+ * Ensures VS Code routes pasted prompt images into `prompts/screenshots`.
2724
+ *
2725
+ * @private function of `initializeCoderProjectConfiguration`
2726
+ */
2727
+ async function ensureCoderVscodeSettingsFile(projectPath) {
2728
+ const [fieldPath, nextEntries] = resolveDefaultCoderVscodeSettingsEntry();
2729
+ return mergeStringRecordJsonFile({
2730
+ projectPath,
2731
+ relativeFilePath: VSCODE_SETTINGS_FILE_PATH,
2732
+ fieldPath,
2733
+ nextEntries,
2734
+ ensureParentDirectoryPath: VSCODE_DIRECTORY_PATH,
2735
+ });
2736
+ }
2737
+ /**
2738
+ * Resolves the default string-record entry that `coder init` merges into VS Code settings.
2739
+ */
2740
+ function resolveDefaultCoderVscodeSettingsEntry() {
2741
+ const [defaultVscodeSettingsEntry] = Object.entries(getDefaultCoderVscodeSettings());
2742
+ if (!defaultVscodeSettingsEntry) {
2743
+ throw new Error('Default coder VS Code settings must define at least one string-record entry.');
2744
+ }
2745
+ return defaultVscodeSettingsEntry;
2746
+ }
2747
+ // Note: [🟡] Code for coder init VS Code bootstrapping [ensureCoderVscodeSettingsFile](src/cli/cli-commands/coder/ensureCoderVscodeSettingsFile.ts) should never be published outside of `@promptbook/cli`
2748
+
2749
+ /**
2750
+ * Ensures a relative directory exists in the project root.
2751
+ *
2752
+ * @private function of `initializeCoderProjectConfiguration`
2753
+ */
2754
+ async function ensureDirectory(projectPath, relativeDirectoryPath) {
2755
+ const directoryPath = join(projectPath, relativeDirectoryPath);
2756
+ const isDirectoryExisting = await isExistingDirectory(directoryPath);
2757
+ if (!isDirectoryExisting) {
2758
+ await mkdir(directoryPath, { recursive: true });
2759
+ return 'created';
2760
+ }
2761
+ return 'unchanged';
2762
+ }
2763
+ /**
2764
+ * Checks whether a path exists and is a directory.
2765
+ */
2766
+ async function isExistingDirectory(path) {
2767
+ try {
2768
+ return (await stat(path)).isDirectory();
2769
+ }
2770
+ catch (_a) {
2771
+ return false;
2340
2772
  }
2341
- const normalizedCurrentContent = currentContent.endsWith('\n') ? currentContent : `${currentContent}\n`;
2342
- return `${normalizedCurrentContent}\n${blockToAppend}\n`;
2343
2773
  }
2774
+ // Note: [🟡] Code for coder init directory creation [ensureDirectory](src/cli/cli-commands/coder/ensureDirectory.ts) should never be published outside of `@promptbook/cli`
2775
+
2776
+ /**
2777
+ * Creates or updates all coder configuration artifacts required in the current project.
2778
+ *
2779
+ * @private internal utility of `coder init` command
2780
+ */
2781
+ async function initializeCoderProjectConfiguration(projectPath) {
2782
+ const promptsDirectoryStatus = await ensureDirectory(projectPath, PROMPTS_DIRECTORY_PATH);
2783
+ const promptsDoneDirectoryStatus = await ensureDirectory(projectPath, PROMPTS_DONE_DIRECTORY_PATH);
2784
+ const promptsTemplatesDirectoryStatus = await ensureDirectory(projectPath, PROMPTS_TEMPLATES_DIRECTORY_PATH);
2785
+ const promptTemplateFileStatuses = await ensureDefaultCoderPromptTemplateFiles(projectPath);
2786
+ const agentsFileStatus = await ensureCoderMarkdownFile(projectPath, AGENTS_FILE_PATH, getDefaultCoderAgentsFileContent());
2787
+ const agentCodingFileStatus = await ensureCoderMarkdownFile(projectPath, AGENT_CODING_FILE_PATH, getDefaultCoderAgentCodingFileContent({
2788
+ packageJsonScripts: getDefaultCoderPackageJsonScripts(),
2789
+ }));
2790
+ const { envFileStatus, initializedEnvVariableNames } = await ensureCoderEnvFile(projectPath);
2791
+ const gitignoreFileStatus = await ensureCoderGitignoreFile(projectPath);
2792
+ const packageJsonFileStatus = await ensureCoderPackageJsonFile(projectPath);
2793
+ const vscodeSettingsFileStatus = await ensureCoderVscodeSettingsFile(projectPath);
2794
+ return {
2795
+ promptsDirectoryStatus,
2796
+ promptsDoneDirectoryStatus,
2797
+ promptsTemplatesDirectoryStatus,
2798
+ promptTemplateFileStatuses,
2799
+ agentsFileStatus,
2800
+ agentCodingFileStatus,
2801
+ envFileStatus,
2802
+ gitignoreFileStatus,
2803
+ packageJsonFileStatus,
2804
+ vscodeSettingsFileStatus,
2805
+ initializedEnvVariableNames,
2806
+ };
2807
+ }
2808
+ // Note: [🟡] Code for coder init project bootstrapping [initializeCoderProjectConfiguration](src/cli/cli-commands/coder/initializeCoderProjectConfiguration.ts) should never be published outside of `@promptbook/cli`
2809
+
2344
2810
  /**
2345
2811
  * Prints a readable summary of what was initialized for the user.
2812
+ *
2813
+ * @private function of `coder init` command
2346
2814
  */
2347
2815
  function printInitializationSummary(summary) {
2348
2816
  console.info(colors.green('Promptbook coder configuration initialized.'));
@@ -2352,6 +2820,8 @@ function printInitializationSummary(summary) {
2352
2820
  for (const templateFileStatus of summary.promptTemplateFileStatuses) {
2353
2821
  printInitializationStatusLine(formatDisplayPath(templateFileStatus.relativeFilePath), templateFileStatus.status);
2354
2822
  }
2823
+ printInitializationStatusLine(AGENTS_FILE_PATH, summary.agentsFileStatus);
2824
+ printInitializationStatusLine(AGENT_CODING_FILE_PATH, summary.agentCodingFileStatus);
2355
2825
  printInitializationStatusLine('.env', summary.envFileStatus);
2356
2826
  printInitializationStatusLine('.gitignore', summary.gitignoreFileStatus);
2357
2827
  printInitializationStatusLine('package.json', summary.packageJsonFileStatus);
@@ -2387,126 +2857,48 @@ function printInitializationStatusLine(relativePath, status) {
2387
2857
  function printInitializationNote(message, colorize) {
2388
2858
  console.info(colorize(`✔ ${message}`));
2389
2859
  }
2390
- /**
2391
- * Normalizes one project-relative path for human-readable CLI output.
2392
- */
2393
- function formatDisplayPath(relativePath) {
2394
- return relativePath.replace(/\\/gu, '/');
2395
- }
2396
- /**
2397
- * Detects whether `.gitignore` already covers the standalone coder temp directory.
2398
- */
2399
- function hasTmpGitignoreRule(gitignoreContent) {
2400
- return /(^|[\r\n])\/?\.tmp(?:[\r\n]|$)/u.test(gitignoreContent);
2401
- }
2402
- /**
2403
- * Reads one text file when it exists, otherwise returns `undefined`.
2404
- */
2405
- async function readTextFileIfExists(path) {
2406
- if (!(await isExistingFile(path))) {
2407
- return undefined;
2408
- }
2409
- return readFile(path, 'utf-8');
2410
- }
2411
- /**
2412
- * Parses one JSON object file while accepting VS Code style comments and trailing commas.
2413
- */
2414
- async function parseJsonObjectFile(relativeFilePath, fileContent) {
2415
- if (fileContent.trim() === '') {
2416
- return {};
2417
- }
2418
- const typescript = await import('typescript');
2419
- const parsedFile = typescript.parseConfigFileTextToJson(relativeFilePath, fileContent);
2420
- if (parsedFile.error) {
2421
- throw new ParseError(spaceTrim$1(`
2422
- Cannot parse \`${relativeFilePath}\` as JSON.
2860
+ // Note: [🟡] Code for coder init summary printing [printInitializationSummary](src/cli/cli-commands/coder/printInitializationSummary.ts) should never be published outside of `@promptbook/cli`
2423
2861
 
2424
- ${typescript.flattenDiagnosticMessageText(parsedFile.error.messageText, '\n')}
2425
- `));
2426
- }
2427
- if (!isPlainObject(parsedFile.config)) {
2428
- throw new ParseError(spaceTrim$1(`
2429
- File \`${relativeFilePath}\` must contain one top-level JSON object.
2430
- `));
2431
- }
2432
- return parsedFile.config;
2433
- }
2434
2862
  /**
2435
- * Reads one JSON object field as a string-to-string record.
2863
+ * Initializes `coder init` command for Promptbook CLI utilities.
2864
+ *
2865
+ * Note: `$` is used to indicate that this function is not a pure function - it registers a command in the CLI.
2866
+ *
2867
+ * @private internal function of `promptbookCli`
2436
2868
  */
2437
- function getStringRecordOrDefault(value, relativeFilePath, fieldPath) {
2438
- if (value === undefined) {
2439
- return {};
2440
- }
2441
- if (!isPlainObject(value)) {
2442
- throw new ParseError(spaceTrim$1(`
2443
- File \`${relativeFilePath}\` contains invalid \`${fieldPath}\`.
2869
+ function $initializeCoderInitCommand(program) {
2870
+ const command = program.command('init');
2871
+ command.alias('initialize');
2872
+ command.description(spaceTrim$1(`
2873
+ Initialize Promptbook coder configuration for current project
2444
2874
 
2445
- Expected \`${fieldPath}\` to be an object with string values.
2446
- `));
2447
- }
2448
- const stringRecord = {};
2449
- for (const [key, itemValue] of Object.entries(value)) {
2450
- if (typeof itemValue !== 'string') {
2451
- throw new ParseError(spaceTrim$1(`
2452
- File \`${relativeFilePath}\` contains invalid \`${fieldPath}.${key}\`.
2875
+ Creates or updates:
2876
+ - prompts/
2877
+ - prompts/done/
2878
+ ${listDefaultCoderProjectPromptTemplateDisplayPaths()}
2879
+ - ${AGENTS_FILE_PATH}
2880
+ - ${AGENT_CODING_FILE_PATH}
2881
+ - .gitignore
2882
+ - package.json
2883
+ - .vscode/settings.json
2453
2884
 
2454
- Expected \`${fieldPath}\` to be an object with string values.
2455
- `));
2456
- }
2457
- stringRecord[key] = itemValue;
2458
- }
2459
- return stringRecord;
2460
- }
2461
- /**
2462
- * Serializes one JSON object using detected or default formatting.
2463
- */
2464
- function serializeJsonObject(value, formatting) {
2465
- return `${JSON.stringify(value, null, formatting.indentation)}${formatting.newline}`;
2466
- }
2467
- /**
2468
- * Detects indentation and newline formatting from an existing JSON file.
2469
- */
2470
- function detectJsonFileFormatting(fileContent) {
2471
- if (!fileContent) {
2472
- return {
2473
- indentation: DEFAULT_JSON_FILE_INDENTATION,
2474
- newline: DEFAULT_JSON_FILE_NEWLINE,
2475
- };
2476
- }
2477
- const indentationMatch = fileContent.match(/^[ \t]+(?=")/mu);
2478
- return {
2479
- indentation: (indentationMatch === null || indentationMatch === void 0 ? void 0 : indentationMatch[0]) || DEFAULT_JSON_FILE_INDENTATION,
2480
- newline: fileContent.includes('\r\n') ? '\r\n' : '\n',
2481
- };
2482
- }
2483
- /**
2484
- * Checks whether one parsed JSON value is a plain object.
2485
- */
2486
- function isPlainObject(value) {
2487
- return typeof value === 'object' && value !== null && !Array.isArray(value);
2488
- }
2489
- /**
2490
- * Checks whether a path exists and is a file.
2491
- */
2492
- async function isExistingFile(path) {
2493
- try {
2494
- return (await stat(path)).isFile();
2495
- }
2496
- catch (_a) {
2497
- return false;
2498
- }
2885
+ Ensures required coding-agent environment variables in .env:
2886
+ - CODING_AGENT_GIT_NAME
2887
+ - CODING_AGENT_GIT_EMAIL
2888
+ - CODING_AGENT_GIT_SIGNING_KEY
2889
+ `));
2890
+ command.action(handleActionErrors(async () => {
2891
+ const summary = await initializeCoderProjectConfiguration(process.cwd());
2892
+ printInitializationSummary(summary);
2893
+ }));
2499
2894
  }
2500
2895
  /**
2501
- * Checks whether a path exists and is a directory.
2896
+ * Lists the project-owned template file paths created by `ptbk coder init`.
2502
2897
  */
2503
- async function isExistingDirectory(path) {
2504
- try {
2505
- return (await stat(path)).isDirectory();
2506
- }
2507
- catch (_a) {
2508
- return false;
2509
- }
2898
+ function listDefaultCoderProjectPromptTemplateDisplayPaths() {
2899
+ return getDefaultCoderProjectPromptTemplateDefinitions()
2900
+ .map(({ relativeFilePath }) => `- ${formatDisplayPath(relativeFilePath)}`)
2901
+ .join('\n');
2510
2902
  }
2511
2903
  // Note: [🟡] Code for CLI command [init](src/cli/cli-commands/coder/init.ts) should never be published outside of `@promptbook/cli`
2512
2904
  // Note: [💞] Ignore a discrepancy between file name and entity name
@@ -40740,91 +41132,6 @@ var findFreshEmojiTags = /*#__PURE__*/Object.freeze({
40740
41132
  findFreshEmojiTag: findFreshEmojiTag
40741
41133
  });
40742
41134
 
40743
- /**
40744
- * Root folders that contain source-like files for scanning.
40745
- */
40746
- const SOURCE_ROOTS = ['src', 'apps', 'scripts', 'examples', 'agents', 'other'];
40747
- /**
40748
- * File extensions treated as source code.
40749
- */
40750
- const SOURCE_FILE_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx'];
40751
- /**
40752
- * Glob patterns that should be ignored when scanning for source files.
40753
- */
40754
- const SOURCE_FILE_IGNORE_GLOBS = [
40755
- '**/node_modules/**',
40756
- '**/packages/**',
40757
- '**/.*/**',
40758
- '**/.git/**',
40759
- '**/.idea/**',
40760
- '**/.vscode/**',
40761
- '**/.promptbook/**',
40762
- '**/.next/**',
40763
- '**/.tmp/**',
40764
- '**/tmp/**',
40765
- '**/coverage/**',
40766
- '**/dist/**',
40767
- '**/build/**',
40768
- '**/out/**',
40769
- '**/prompts/**',
40770
- '**/changelog/**',
40771
- ];
40772
- /**
40773
- * Default maximum line count for source files.
40774
- */
40775
- const DEFAULT_MAX_LINE_COUNT = 2000;
40776
- /**
40777
- * Per-extension line count limits.
40778
- */
40779
- const LINE_COUNT_LIMITS_BY_EXTENSION = {
40780
- '.ts': 2000,
40781
- '.tsx': 2000,
40782
- '.js': 2000,
40783
- '.jsx': 2000,
40784
- };
40785
- /**
40786
- * Glob patterns that are exempt from line-count checks.
40787
- */
40788
- const LINE_COUNT_EXEMPT_GLOBS = ['other/cspell-dictionaries/**/*.txt'];
40789
- /**
40790
- * Maximum number of entities before a file is flagged.
40791
- */
40792
- const MAX_ENTITIES_PER_FILE = 20;
40793
- /**
40794
- * File extensions eligible for entity counting.
40795
- */
40796
- const ENTITY_COUNT_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx'];
40797
- /**
40798
- * Markers that identify generated files which should be skipped.
40799
- */
40800
- const GENERATED_CODE_MARKERS = [
40801
- 'WARNING: This code has been generated',
40802
- 'This code has been generated so that any manual changes will be overwritten',
40803
- ];
40804
- /**
40805
- * Name of the prompts directory.
40806
- */
40807
- const PROMPTS_DIR_NAME = 'prompts';
40808
- /**
40809
- * Step size used for prompt numbering.
40810
- */
40811
- const PROMPT_NUMBER_STEP = 10;
40812
- /**
40813
- * Prefix used for generated prompt slugs.
40814
- */
40815
- const PROMPT_SLUG_PREFIX = 'refactor';
40816
- /**
40817
- * Label used to mark the target file in generated prompts.
40818
- */
40819
- const PROMPT_TARGET_LABEL = 'Target file';
40820
- /**
40821
- * Maximum length for generated prompt slugs.
40822
- */
40823
- const PROMPT_SLUG_MAX_LENGTH = 80;
40824
- /**
40825
- * Note: [?] Code in this file should never be published in any package
40826
- */
40827
-
40828
41135
  /**
40829
41136
  * Normalizes a repo-relative path to use forward slashes.
40830
41137
  *
@@ -40842,7 +41149,7 @@ function normalizeRefactorCandidatePath(pathValue) {
40842
41149
  * @private function of findRefactorCandidates
40843
41150
  */
40844
41151
  async function analyzeSourceFileForRefactorCandidate(options) {
40845
- const { filePath, lineCountExemptPaths, rootDir } = options;
41152
+ const { filePath, heuristics, lineCountExemptPaths, rootDir } = options;
40846
41153
  const normalizedAbsolutePath = normalizeAbsolutePath$1(filePath);
40847
41154
  const content = await readFile(filePath, 'utf-8');
40848
41155
  if (isGeneratedFile(content)) {
@@ -40853,15 +41160,21 @@ async function analyzeSourceFileForRefactorCandidate(options) {
40853
41160
  const reasons = [];
40854
41161
  if (!lineCountExemptPaths.has(normalizedAbsolutePath)) {
40855
41162
  const lineCount = countLines(content);
40856
- const maxLines = getMaxLinesForExtension(extension);
41163
+ const maxLines = getMaxLinesForExtension(extension, heuristics);
40857
41164
  if (lineCount > maxLines) {
40858
41165
  reasons.push(`lines ${lineCount}/${maxLines}`);
40859
41166
  }
40860
41167
  }
40861
- if (ENTITY_COUNT_EXTENSIONS.includes(extension)) {
40862
- const entityCount = countEntities(content, extension, filePath);
40863
- if (entityCount > MAX_ENTITIES_PER_FILE) {
40864
- reasons.push(`entities ${entityCount}/${MAX_ENTITIES_PER_FILE}`);
41168
+ if (STRUCTURAL_ANALYSIS_EXTENSIONS.includes(extension)) {
41169
+ const structureSummary = summarizeSourceFileStructure(content, extension, filePath);
41170
+ if (structureSummary.entityCount > heuristics.maxEntityCountPerFile) {
41171
+ reasons.push(`entities ${structureSummary.entityCount}/${heuristics.maxEntityCountPerFile}`);
41172
+ }
41173
+ if (structureSummary.functionCount > heuristics.maxFunctionCountPerFile) {
41174
+ reasons.push(`functions ${structureSummary.functionCount}/${heuristics.maxFunctionCountPerFile}`);
41175
+ }
41176
+ if (structureSummary.maxFunctionComplexity > heuristics.maxFunctionComplexity) {
41177
+ reasons.push(buildComplexityReason(structureSummary, heuristics.maxFunctionComplexity));
40865
41178
  }
40866
41179
  }
40867
41180
  if (reasons.length === 0) {
@@ -40886,9 +41199,9 @@ function isGeneratedFile(content) {
40886
41199
  *
40887
41200
  * @private function of analyzeSourceFileForRefactorCandidate
40888
41201
  */
40889
- function getMaxLinesForExtension(extension) {
41202
+ function getMaxLinesForExtension(extension, heuristics) {
40890
41203
  var _a;
40891
- return (_a = LINE_COUNT_LIMITS_BY_EXTENSION[extension]) !== null && _a !== void 0 ? _a : DEFAULT_MAX_LINE_COUNT;
41204
+ return (_a = heuristics.maxLineCountByExtension[extension]) !== null && _a !== void 0 ? _a : heuristics.maxDefaultLineCount;
40892
41205
  }
40893
41206
  /**
40894
41207
  * Counts lines while ignoring a trailing newline.
@@ -40903,14 +41216,17 @@ function countLines(content) {
40903
41216
  return lines[lines.length - 1] === '' ? lines.length - 1 : lines.length;
40904
41217
  }
40905
41218
  /**
40906
- * Counts top-level entities in a source file.
41219
+ * Summarizes the structural metrics used to score one source file.
40907
41220
  *
40908
41221
  * @private function of analyzeSourceFileForRefactorCandidate
40909
41222
  */
40910
- function countEntities(content, extension, filePath) {
41223
+ function summarizeSourceFileStructure(content, extension, filePath) {
40911
41224
  const scriptKind = getScriptKindForExtension(extension);
40912
- const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, false, scriptKind);
40913
- return countEntitiesInSourceFile(sourceFile);
41225
+ const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true, scriptKind);
41226
+ return {
41227
+ entityCount: countEntitiesInSourceFile(sourceFile),
41228
+ ...summarizeFunctionsInSourceFile(sourceFile),
41229
+ };
40914
41230
  }
40915
41231
  /**
40916
41232
  * Counts top-level entities in a parsed TypeScript source file.
@@ -40944,6 +41260,169 @@ function countEntitiesInSourceFile(sourceFile) {
40944
41260
  }
40945
41261
  return count;
40946
41262
  }
41263
+ /**
41264
+ * Summarizes named functions and methods in a parsed source file.
41265
+ *
41266
+ * @private function of analyzeSourceFileForRefactorCandidate
41267
+ */
41268
+ function summarizeFunctionsInSourceFile(sourceFile) {
41269
+ let functionCount = 0;
41270
+ let maxFunctionComplexity = 0;
41271
+ let mostComplexFunctionName = null;
41272
+ const visitNode = (node) => {
41273
+ if (isCountedFunctionLikeDeclaration(node)) {
41274
+ functionCount += 1;
41275
+ const functionComplexity = calculateFunctionComplexity(node);
41276
+ if (functionComplexity > maxFunctionComplexity) {
41277
+ maxFunctionComplexity = functionComplexity;
41278
+ mostComplexFunctionName = getFunctionDisplayName(node);
41279
+ }
41280
+ }
41281
+ ts.forEachChild(node, visitNode);
41282
+ };
41283
+ visitNode(sourceFile);
41284
+ return {
41285
+ functionCount,
41286
+ maxFunctionComplexity,
41287
+ mostComplexFunctionName,
41288
+ };
41289
+ }
41290
+ /**
41291
+ * Determines whether a node counts as a named function or method for density checks.
41292
+ *
41293
+ * @private function of analyzeSourceFileForRefactorCandidate
41294
+ */
41295
+ function isCountedFunctionLikeDeclaration(node) {
41296
+ if (ts.isFunctionDeclaration(node) ||
41297
+ ts.isMethodDeclaration(node) ||
41298
+ ts.isConstructorDeclaration(node) ||
41299
+ ts.isGetAccessorDeclaration(node) ||
41300
+ ts.isSetAccessorDeclaration(node)) {
41301
+ return true;
41302
+ }
41303
+ if (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) {
41304
+ return isNamedFunctionExpression(node);
41305
+ }
41306
+ return false;
41307
+ }
41308
+ /**
41309
+ * Determines whether a function expression is attached to a named variable or property.
41310
+ *
41311
+ * @private function of analyzeSourceFileForRefactorCandidate
41312
+ */
41313
+ function isNamedFunctionExpression(node) {
41314
+ const parent = node.parent;
41315
+ return (ts.isVariableDeclaration(parent) || ts.isPropertyDeclaration(parent) || ts.isPropertyAssignment(parent));
41316
+ }
41317
+ /**
41318
+ * Calculates a lightweight cyclomatic-complexity score for one function.
41319
+ *
41320
+ * @private function of analyzeSourceFileForRefactorCandidate
41321
+ */
41322
+ function calculateFunctionComplexity(functionNode) {
41323
+ if (!functionNode.body) {
41324
+ return 1;
41325
+ }
41326
+ let complexity = 1;
41327
+ const visitNode = (node) => {
41328
+ if (node !== functionNode.body && isCountedFunctionLikeDeclaration(node)) {
41329
+ return;
41330
+ }
41331
+ if (isComplexityDecisionNode(node)) {
41332
+ complexity += 1;
41333
+ }
41334
+ ts.forEachChild(node, visitNode);
41335
+ };
41336
+ visitNode(functionNode.body);
41337
+ return complexity;
41338
+ }
41339
+ /**
41340
+ * Determines whether a node should increase the complexity score.
41341
+ *
41342
+ * @private function of analyzeSourceFileForRefactorCandidate
41343
+ */
41344
+ function isComplexityDecisionNode(node) {
41345
+ if (ts.isIfStatement(node) ||
41346
+ ts.isConditionalExpression(node) ||
41347
+ ts.isCatchClause(node) ||
41348
+ ts.isForStatement(node) ||
41349
+ ts.isForInStatement(node) ||
41350
+ ts.isForOfStatement(node) ||
41351
+ ts.isWhileStatement(node) ||
41352
+ ts.isDoStatement(node) ||
41353
+ ts.isCaseClause(node)) {
41354
+ return true;
41355
+ }
41356
+ if (ts.isBinaryExpression(node)) {
41357
+ const operatorKind = node.operatorToken.kind;
41358
+ return (operatorKind === ts.SyntaxKind.AmpersandAmpersandToken ||
41359
+ operatorKind === ts.SyntaxKind.BarBarToken ||
41360
+ operatorKind === ts.SyntaxKind.QuestionQuestionToken);
41361
+ }
41362
+ return false;
41363
+ }
41364
+ /**
41365
+ * Resolves a readable display name for a counted function-like declaration.
41366
+ *
41367
+ * @private function of analyzeSourceFileForRefactorCandidate
41368
+ */
41369
+ function getFunctionDisplayName(functionNode) {
41370
+ if (ts.isConstructorDeclaration(functionNode)) {
41371
+ return 'constructor';
41372
+ }
41373
+ if (ts.isFunctionDeclaration(functionNode) ||
41374
+ ts.isMethodDeclaration(functionNode) ||
41375
+ ts.isGetAccessorDeclaration(functionNode) ||
41376
+ ts.isSetAccessorDeclaration(functionNode)) {
41377
+ if (!functionNode.name) {
41378
+ return null;
41379
+ }
41380
+ return getPropertyNameText(functionNode.name);
41381
+ }
41382
+ if (ts.isArrowFunction(functionNode) || ts.isFunctionExpression(functionNode)) {
41383
+ if (functionNode.name) {
41384
+ return functionNode.name.text;
41385
+ }
41386
+ const parent = functionNode.parent;
41387
+ if (ts.isVariableDeclaration(parent)) {
41388
+ return getBindingNameText(parent.name);
41389
+ }
41390
+ if (ts.isPropertyDeclaration(parent) || ts.isPropertyAssignment(parent)) {
41391
+ return getPropertyNameText(parent.name);
41392
+ }
41393
+ }
41394
+ return null;
41395
+ }
41396
+ /**
41397
+ * Resolves text for a binding name when it is a simple identifier.
41398
+ *
41399
+ * @private function of analyzeSourceFileForRefactorCandidate
41400
+ */
41401
+ function getBindingNameText(name) {
41402
+ return ts.isIdentifier(name) ? name.text : null;
41403
+ }
41404
+ /**
41405
+ * Resolves text for a property name while preserving computed names when necessary.
41406
+ *
41407
+ * @private function of analyzeSourceFileForRefactorCandidate
41408
+ */
41409
+ function getPropertyNameText(name) {
41410
+ if (ts.isIdentifier(name) || ts.isPrivateIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) {
41411
+ return name.text;
41412
+ }
41413
+ return name.getText();
41414
+ }
41415
+ /**
41416
+ * Formats the reason emitted when a function in the file exceeds the complexity threshold.
41417
+ *
41418
+ * @private function of analyzeSourceFileForRefactorCandidate
41419
+ */
41420
+ function buildComplexityReason(structureSummary, maxAllowedFunctionComplexity) {
41421
+ const functionSuffix = structureSummary.mostComplexFunctionName
41422
+ ? ` in \`${structureSummary.mostComplexFunctionName}\``
41423
+ : '';
41424
+ return `complexity ${structureSummary.maxFunctionComplexity}/${maxAllowedFunctionComplexity}${functionSuffix}`;
41425
+ }
40947
41426
  /**
40948
41427
  * Resolves the script kind for a source file extension.
40949
41428
  *
@@ -40977,13 +41456,15 @@ function normalizeAbsolutePath$1(pathValue) {
40977
41456
  *
40978
41457
  * @private function of findRefactorCandidates
40979
41458
  */
40980
- async function findRefactorCandidatesInProject(rootDir) {
41459
+ async function findRefactorCandidatesInProject(options) {
41460
+ const { heuristics, rootDir } = options;
40981
41461
  const lineCountExemptPaths = await buildExemptPathSet(rootDir, LINE_COUNT_EXEMPT_GLOBS);
40982
41462
  const sourceFiles = await listSourceFiles(rootDir);
40983
41463
  const candidates = [];
40984
41464
  for (const filePath of sourceFiles) {
40985
41465
  const candidate = await analyzeSourceFileForRefactorCandidate({
40986
41466
  filePath,
41467
+ heuristics,
40987
41468
  lineCountExemptPaths,
40988
41469
  rootDir,
40989
41470
  });
@@ -41256,11 +41737,18 @@ function buildPromptGuidance(candidate) {
41256
41737
  if (counts.entityCount !== null && counts.maxEntities !== null) {
41257
41738
  guidance.push(`- The file defines too many responsibilities (${counts.entityCount} in single file)`, ` - Keep in mind the Single Responsibility Principle (SRP)`, ` - Consider breaking it down into smaller, focused modules or components.`);
41258
41739
  }
41740
+ if (counts.functionCount !== null && counts.maxFunctions !== null) {
41741
+ guidance.push(`- The file contains too many functions (${counts.functionCount}/${counts.maxFunctions})`, ` - Keep related responsibilities grouped behind small facades or focused modules.`, ` - Consider extracting private helpers or splitting independent concerns into dedicated files.`);
41742
+ }
41743
+ if (counts.functionComplexity !== null && counts.maxFunctionComplexity !== null) {
41744
+ const functionSuffix = counts.mostComplexFunctionName ? ` in \`${counts.mostComplexFunctionName}\`` : '';
41745
+ guidance.push(`- The file contains overly complex logic${functionSuffix} (${counts.functionComplexity}/${counts.maxFunctionComplexity})`, ` - Break branching logic into smaller, focused helper functions.`, ` - Keep each function responsible for one clear step or decision.`);
41746
+ }
41259
41747
  guidance.push('- Purpose of this refactoring is to improve code maintainability and readability.', '- Look at the internal structure, the usage and also surrounding code to understand how to best refactor this file.', '- Consider breaking down large functions into smaller, more manageable ones, removing any redundant code, and ensuring that the file adheres to the project coding standards.', '- After the refactoring, ensure that (1) `npm run test-name-discrepancies` and (2) `npm run test-package-generation` are passing successfully.', ' 1. All the things you have moved to new files should correspond the thing in the file with the file name, for example `MyComponent.tsx` should export `MyComponent`.', ' 2. All the things you have moved to new files but are private things to the outside world should have `@private function of TheMainThing` JSDoc comment.', '- Keep in mind DRY *(Do not repeat yourself)* and SOLID principles while refactoring.', '- **Do not change the external behavior** of the code. Focus solely on improving the internal structure and organization of the code.', '- Before you start refactoring, make sure to read the code carefully and understand its current structure and functionality. Do a analysis of the current functionality before you start.');
41260
41748
  return guidance;
41261
41749
  }
41262
41750
  /**
41263
- * Extracts line and entity counts from refactor reasons.
41751
+ * Extracts structural counts from refactor reasons.
41264
41752
  *
41265
41753
  * @private function of buildPromptContent
41266
41754
  */
@@ -41269,6 +41757,11 @@ function extractReasonCounts(reasons) {
41269
41757
  let maxLines = null;
41270
41758
  let entityCount = null;
41271
41759
  let maxEntities = null;
41760
+ let functionCount = null;
41761
+ let maxFunctions = null;
41762
+ let functionComplexity = null;
41763
+ let maxFunctionComplexity = null;
41764
+ let mostComplexFunctionName = null;
41272
41765
  for (const reason of reasons) {
41273
41766
  const lineMatch = reason.match(/lines\s+(?<count>\d+)\/(?<max>\d+)/i);
41274
41767
  if (lineMatch === null || lineMatch === void 0 ? void 0 : lineMatch.groups) {
@@ -41280,6 +41773,19 @@ function extractReasonCounts(reasons) {
41280
41773
  if (entityMatch === null || entityMatch === void 0 ? void 0 : entityMatch.groups) {
41281
41774
  entityCount = Number(entityMatch.groups.count);
41282
41775
  maxEntities = Number(entityMatch.groups.max);
41776
+ continue;
41777
+ }
41778
+ const functionMatch = reason.match(/functions\s+(?<count>\d+)\/(?<max>\d+)/i);
41779
+ if (functionMatch === null || functionMatch === void 0 ? void 0 : functionMatch.groups) {
41780
+ functionCount = Number(functionMatch.groups.count);
41781
+ maxFunctions = Number(functionMatch.groups.max);
41782
+ continue;
41783
+ }
41784
+ const complexityMatch = reason.match(/complexity\s+(?<count>\d+)\/(?<max>\d+)(?:\s+in\s+`(?<functionName>[^`]+)`)?/i);
41785
+ if (complexityMatch === null || complexityMatch === void 0 ? void 0 : complexityMatch.groups) {
41786
+ functionComplexity = Number(complexityMatch.groups.count);
41787
+ maxFunctionComplexity = Number(complexityMatch.groups.max);
41788
+ mostComplexFunctionName = complexityMatch.groups.functionName || null;
41283
41789
  }
41284
41790
  }
41285
41791
  return {
@@ -41287,6 +41793,11 @@ function extractReasonCounts(reasons) {
41287
41793
  maxLines,
41288
41794
  entityCount,
41289
41795
  maxEntities,
41796
+ functionCount,
41797
+ maxFunctions,
41798
+ functionComplexity,
41799
+ maxFunctionComplexity,
41800
+ mostComplexFunctionName,
41290
41801
  };
41291
41802
  }
41292
41803
  /**
@@ -41295,14 +41806,23 @@ function extractReasonCounts(reasons) {
41295
41806
  * @private function of buildPromptContent
41296
41807
  */
41297
41808
  function buildDensityNote(counts) {
41298
- if (counts.lineCount !== null && counts.entityCount !== null) {
41299
- return 'The file mixes multiple concerns, making it harder to follow.';
41809
+ const activeSignalsCount = [
41810
+ counts.lineCount !== null,
41811
+ counts.entityCount !== null,
41812
+ counts.functionCount !== null,
41813
+ counts.functionComplexity !== null,
41814
+ ].filter(Boolean).length;
41815
+ if (activeSignalsCount > 1) {
41816
+ return 'The file mixes multiple concerns and dense logic, making it harder to follow.';
41300
41817
  }
41301
41818
  if (counts.lineCount !== null) {
41302
41819
  return 'The file is large enough that it is hard to follow.';
41303
41820
  }
41304
- if (counts.entityCount !== null) {
41305
- return 'The file is dense enough that it is hard to follow.';
41821
+ if (counts.entityCount !== null || counts.functionCount !== null) {
41822
+ return 'The file packs too many responsibilities into one place.';
41823
+ }
41824
+ if (counts.functionComplexity !== null) {
41825
+ return 'The file contains logic that is too complex to follow comfortably.';
41306
41826
  }
41307
41827
  return null;
41308
41828
  }
@@ -41396,13 +41916,19 @@ function initializeFindRefactorCandidatesRun() {
41396
41916
  *
41397
41917
  * @public exported from `@promptbook/cli`
41398
41918
  */
41399
- async function findRefactorCandidates() {
41919
+ async function findRefactorCandidates(options = {}) {
41920
+ const { level = DEFAULT_REFACTOR_CANDIDATE_LEVEL } = options;
41921
+ const heuristics = getRefactorCandidateLevelConfiguration(level);
41400
41922
  initializeFindRefactorCandidatesRun();
41401
- console.info(colors.cyan('?? Find refactor candidates'));
41923
+ console.info(colors.cyan('⚡🏭 Find refactor candidates'));
41924
+ console.info(colors.gray(`Using \`${level}\` scan level.`));
41402
41925
  const rootDir = process.cwd();
41403
41926
  const promptsDir = join(rootDir, PROMPTS_DIR_NAME);
41404
41927
  const existingTargets = await loadExistingPromptTargets(promptsDir);
41405
- const candidates = await findRefactorCandidatesInProject(rootDir);
41928
+ const candidates = await findRefactorCandidatesInProject({
41929
+ heuristics,
41930
+ rootDir,
41931
+ });
41406
41932
  if (candidates.length === 0) {
41407
41933
  console.info(colors.green('No refactor candidates found.'));
41408
41934
  return;