@promptbook/cli 0.112.0-35 → 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 (138) hide show
  1. package/README.md +119 -18
  2. package/esm/index.es.js +1289 -323
  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 +137 -0
  27. package/esm/src/cli/cli-commands/coder/boilerplateTemplates.test.d.ts +1 -0
  28. package/esm/src/cli/cli-commands/coder/ensureCoderEnvFile.d.ts +15 -0
  29. package/esm/src/cli/cli-commands/coder/ensureCoderGitignoreFile.d.ts +7 -0
  30. package/esm/src/cli/cli-commands/coder/ensureCoderMarkdownFile.d.ts +7 -0
  31. package/esm/src/cli/cli-commands/coder/ensureCoderPackageJsonFile.d.ts +7 -0
  32. package/esm/src/cli/cli-commands/coder/ensureCoderVscodeSettingsFile.d.ts +7 -0
  33. package/esm/src/cli/cli-commands/coder/ensureDirectory.d.ts +7 -0
  34. package/esm/src/cli/cli-commands/coder/find-refactor-candidates.d.ts +1 -1
  35. package/esm/src/cli/cli-commands/coder/find-refactor-candidates.test.d.ts +1 -0
  36. package/esm/src/cli/cli-commands/coder/formatDisplayPath.d.ts +6 -0
  37. package/esm/src/cli/cli-commands/coder/generate-boilerplates.d.ts +10 -0
  38. package/esm/src/cli/cli-commands/coder/getDefaultCoderPackageJsonScripts.d.ts +6 -0
  39. package/esm/src/cli/cli-commands/coder/getDefaultCoderVscodeSettings.d.ts +6 -0
  40. package/esm/src/cli/cli-commands/coder/init.d.ts +3 -0
  41. package/esm/src/cli/cli-commands/coder/initializeCoderProjectConfiguration.d.ts +25 -0
  42. package/esm/src/cli/cli-commands/coder/mergeStringRecordJsonFile.d.ts +18 -0
  43. package/esm/src/cli/cli-commands/coder/printInitializationSummary.d.ts +7 -0
  44. package/esm/src/cli/cli-commands/coder/readTextFileIfExists.d.ts +6 -0
  45. package/esm/src/types/string_agent_url.d.ts +7 -0
  46. package/esm/src/types/string_agent_url_private.d.ts +9 -0
  47. package/esm/src/types/string_base64.d.ts +13 -0
  48. package/esm/src/types/string_base64_private.d.ts +2 -2
  49. package/esm/src/types/string_base_url.d.ts +7 -0
  50. package/esm/src/types/string_base_url_private.d.ts +9 -0
  51. package/esm/src/types/string_email.d.ts +13 -0
  52. package/esm/src/types/string_email_private.d.ts +2 -2
  53. package/esm/src/types/string_host.d.ts +42 -0
  54. package/esm/src/types/string_host_private.d.ts +7 -7
  55. package/esm/src/types/string_href.d.ts +19 -0
  56. package/esm/src/types/string_href_private.d.ts +24 -0
  57. package/esm/src/types/string_mime_type.d.ts +15 -0
  58. package/esm/src/types/string_mime_type_private.d.ts +2 -2
  59. package/esm/src/types/string_pipeline_root_url.d.ts +7 -0
  60. package/esm/src/types/string_pipeline_root_url_private.d.ts +9 -0
  61. package/esm/src/types/string_pipeline_url.d.ts +13 -0
  62. package/esm/src/types/string_pipeline_url_private.d.ts +17 -0
  63. package/esm/src/types/string_promptbook_server_url.d.ts +7 -0
  64. package/esm/src/types/string_promptbook_server_url_private.d.ts +9 -0
  65. package/esm/src/types/string_url.d.ts +14 -141
  66. package/esm/src/types/string_url_image.d.ts +7 -0
  67. package/esm/src/types/string_url_image_private.d.ts +9 -0
  68. package/esm/src/types/string_url_private.d.ts +0 -80
  69. package/esm/src/version.d.ts +1 -1
  70. package/package.json +1 -1
  71. package/umd/index.umd.js +1287 -321
  72. package/umd/index.umd.js.map +1 -1
  73. package/umd/scripts/find-refactor-candidates/RefactorCandidateLevel.d.ts +41 -0
  74. package/umd/scripts/find-refactor-candidates/analyzeSourceFileForRefactorCandidate.d.ts +5 -0
  75. package/umd/scripts/find-refactor-candidates/find-refactor-candidates.constants.d.ts +2 -14
  76. package/umd/scripts/find-refactor-candidates/find-refactor-candidates.d.ts +13 -1
  77. package/umd/scripts/find-refactor-candidates/findRefactorCandidatesInProject.d.ts +18 -1
  78. package/umd/src/_packages/components.index.d.ts +2 -0
  79. package/umd/src/_packages/types.index.d.ts +48 -46
  80. package/umd/src/book-components/Chat/Chat/ChatActionsBar.d.ts +7 -0
  81. package/umd/src/book-components/Chat/Chat/ChatActionsBar.test.d.ts +2 -0
  82. package/umd/src/book-components/Chat/Chat/ChatInputArea.d.ts +4 -0
  83. package/umd/src/book-components/Chat/Chat/ChatMessageItem.d.ts +8 -0
  84. package/umd/src/book-components/Chat/Chat/ChatMessageList.d.ts +2 -0
  85. package/umd/src/book-components/Chat/Chat/ChatProps.d.ts +50 -1
  86. package/umd/src/book-components/Chat/Chat/ChatReplyPreview.d.ts +19 -0
  87. package/umd/src/book-components/Chat/Chat/createProgressCardChecklistMarkdown.d.ts +2 -2
  88. package/umd/src/book-components/Chat/MockedChat/MockedChat.d.ts +1 -1
  89. package/umd/src/book-components/Chat/types/ChatMessage.d.ts +35 -0
  90. package/umd/src/book-components/Chat/utils/resolveChatMessageReplyPreviewText.d.ts +25 -0
  91. package/umd/src/book-components/Chat/utils/resolveChatMessageReplySenderLabel.d.ts +12 -0
  92. package/umd/src/cli/cli-commands/coder/agentCodingFile.d.ts +14 -0
  93. package/umd/src/cli/cli-commands/coder/agentsFile.d.ts +12 -0
  94. package/umd/src/cli/cli-commands/coder/appendBlock.d.ts +6 -0
  95. package/umd/src/cli/cli-commands/coder/boilerplateTemplates.d.ts +137 -0
  96. package/umd/src/cli/cli-commands/coder/boilerplateTemplates.test.d.ts +1 -0
  97. package/umd/src/cli/cli-commands/coder/ensureCoderEnvFile.d.ts +15 -0
  98. package/umd/src/cli/cli-commands/coder/ensureCoderGitignoreFile.d.ts +7 -0
  99. package/umd/src/cli/cli-commands/coder/ensureCoderMarkdownFile.d.ts +7 -0
  100. package/umd/src/cli/cli-commands/coder/ensureCoderPackageJsonFile.d.ts +7 -0
  101. package/umd/src/cli/cli-commands/coder/ensureCoderVscodeSettingsFile.d.ts +7 -0
  102. package/umd/src/cli/cli-commands/coder/ensureDirectory.d.ts +7 -0
  103. package/umd/src/cli/cli-commands/coder/find-refactor-candidates.d.ts +1 -1
  104. package/umd/src/cli/cli-commands/coder/find-refactor-candidates.test.d.ts +1 -0
  105. package/umd/src/cli/cli-commands/coder/formatDisplayPath.d.ts +6 -0
  106. package/umd/src/cli/cli-commands/coder/generate-boilerplates.d.ts +10 -0
  107. package/umd/src/cli/cli-commands/coder/getDefaultCoderPackageJsonScripts.d.ts +6 -0
  108. package/umd/src/cli/cli-commands/coder/getDefaultCoderVscodeSettings.d.ts +6 -0
  109. package/umd/src/cli/cli-commands/coder/init.d.ts +3 -0
  110. package/umd/src/cli/cli-commands/coder/initializeCoderProjectConfiguration.d.ts +25 -0
  111. package/umd/src/cli/cli-commands/coder/mergeStringRecordJsonFile.d.ts +18 -0
  112. package/umd/src/cli/cli-commands/coder/printInitializationSummary.d.ts +7 -0
  113. package/umd/src/cli/cli-commands/coder/readTextFileIfExists.d.ts +6 -0
  114. package/umd/src/types/string_agent_url.d.ts +7 -0
  115. package/umd/src/types/string_agent_url_private.d.ts +9 -0
  116. package/umd/src/types/string_base64.d.ts +13 -0
  117. package/umd/src/types/string_base64_private.d.ts +2 -2
  118. package/umd/src/types/string_base_url.d.ts +7 -0
  119. package/umd/src/types/string_base_url_private.d.ts +9 -0
  120. package/umd/src/types/string_email.d.ts +13 -0
  121. package/umd/src/types/string_email_private.d.ts +2 -2
  122. package/umd/src/types/string_host.d.ts +42 -0
  123. package/umd/src/types/string_host_private.d.ts +7 -7
  124. package/umd/src/types/string_href.d.ts +19 -0
  125. package/umd/src/types/string_href_private.d.ts +24 -0
  126. package/umd/src/types/string_mime_type.d.ts +15 -0
  127. package/umd/src/types/string_mime_type_private.d.ts +2 -2
  128. package/umd/src/types/string_pipeline_root_url.d.ts +7 -0
  129. package/umd/src/types/string_pipeline_root_url_private.d.ts +9 -0
  130. package/umd/src/types/string_pipeline_url.d.ts +13 -0
  131. package/umd/src/types/string_pipeline_url_private.d.ts +17 -0
  132. package/umd/src/types/string_promptbook_server_url.d.ts +7 -0
  133. package/umd/src/types/string_promptbook_server_url_private.d.ts +9 -0
  134. package/umd/src/types/string_url.d.ts +14 -141
  135. package/umd/src/types/string_url_image.d.ts +7 -0
  136. package/umd/src/types/string_url_image_private.d.ts +9 -0
  137. package/umd/src/types/string_url_private.d.ts +0 -80
  138. package/umd/src/version.d.ts +1 -1
package/umd/index.umd.js CHANGED
@@ -60,7 +60,7 @@
60
60
  * @generated
61
61
  * @see https://github.com/webgptorg/promptbook
62
62
  */
63
- const PROMPTBOOK_ENGINE_VERSION = '0.112.0-35';
63
+ const PROMPTBOOK_ENGINE_VERSION = '0.112.0-38';
64
64
  /**
65
65
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
66
66
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -1664,6 +1664,142 @@
1664
1664
  // 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`
1665
1665
  // Note: [💞] Ignore a discrepancy between file name and entity name
1666
1666
 
1667
+ /**
1668
+ * Root folders that contain source-like files for scanning.
1669
+ */
1670
+ const SOURCE_ROOTS = ['src', 'apps', 'scripts', 'examples', 'agents', 'other'];
1671
+ /**
1672
+ * File extensions treated as source code.
1673
+ */
1674
+ const SOURCE_FILE_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx'];
1675
+ /**
1676
+ * Glob patterns that should be ignored when scanning for source files.
1677
+ */
1678
+ const SOURCE_FILE_IGNORE_GLOBS = [
1679
+ '**/node_modules/**',
1680
+ '**/packages/**',
1681
+ '**/.*/**',
1682
+ '**/.git/**',
1683
+ '**/.idea/**',
1684
+ '**/.vscode/**',
1685
+ '**/.promptbook/**',
1686
+ '**/.next/**',
1687
+ '**/.tmp/**',
1688
+ '**/tmp/**',
1689
+ '**/coverage/**',
1690
+ '**/dist/**',
1691
+ '**/build/**',
1692
+ '**/out/**',
1693
+ '**/prompts/**',
1694
+ '**/changelog/**',
1695
+ ];
1696
+ /**
1697
+ * Glob patterns that are exempt from line-count checks.
1698
+ */
1699
+ const LINE_COUNT_EXEMPT_GLOBS = ['other/cspell-dictionaries/**/*.txt'];
1700
+ /**
1701
+ * File extensions eligible for structural AST analysis.
1702
+ */
1703
+ const STRUCTURAL_ANALYSIS_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx'];
1704
+ /**
1705
+ * Markers that identify generated files which should be skipped.
1706
+ */
1707
+ const GENERATED_CODE_MARKERS = [
1708
+ 'WARNING: This code has been generated',
1709
+ 'This code has been generated so that any manual changes will be overwritten',
1710
+ ];
1711
+ /**
1712
+ * Name of the prompts directory.
1713
+ */
1714
+ const PROMPTS_DIR_NAME = 'prompts';
1715
+ /**
1716
+ * Step size used for prompt numbering.
1717
+ */
1718
+ const PROMPT_NUMBER_STEP = 10;
1719
+ /**
1720
+ * Prefix used for generated prompt slugs.
1721
+ */
1722
+ const PROMPT_SLUG_PREFIX = 'refactor';
1723
+ /**
1724
+ * Label used to mark the target file in generated prompts.
1725
+ */
1726
+ const PROMPT_TARGET_LABEL = 'Target file';
1727
+ /**
1728
+ * Maximum length for generated prompt slugs.
1729
+ */
1730
+ const PROMPT_SLUG_MAX_LENGTH = 80;
1731
+ /**
1732
+ * Note: [?] Code in this file should never be published in any package
1733
+ */
1734
+
1735
+ /**
1736
+ * Supported aggressiveness levels for refactor-candidate scanning.
1737
+ */
1738
+ const REFACTOR_CANDIDATE_LEVEL_VALUES = ['low', 'medium', 'high', 'xhigh'];
1739
+ /**
1740
+ * Default aggressiveness level for refactor-candidate scanning.
1741
+ */
1742
+ const DEFAULT_REFACTOR_CANDIDATE_LEVEL = 'medium';
1743
+ /**
1744
+ * Threshold table for each supported refactor-candidate scanning level.
1745
+ */
1746
+ const REFACTOR_CANDIDATE_LEVEL_CONFIGURATION_BY_LEVEL = {
1747
+ low: createRefactorCandidateLevelConfiguration({
1748
+ maxLineCount: 2800,
1749
+ maxEntityCountPerFile: 28,
1750
+ maxFunctionCountPerFile: 18,
1751
+ maxFunctionComplexity: 20,
1752
+ }),
1753
+ medium: createRefactorCandidateLevelConfiguration({
1754
+ maxLineCount: 2000,
1755
+ maxEntityCountPerFile: 20,
1756
+ maxFunctionCountPerFile: 14,
1757
+ maxFunctionComplexity: 16,
1758
+ }),
1759
+ high: createRefactorCandidateLevelConfiguration({
1760
+ maxLineCount: 1500,
1761
+ maxEntityCountPerFile: 16,
1762
+ maxFunctionCountPerFile: 10,
1763
+ maxFunctionComplexity: 12,
1764
+ }),
1765
+ xhigh: createRefactorCandidateLevelConfiguration({
1766
+ maxLineCount: 1000,
1767
+ maxEntityCountPerFile: 12,
1768
+ maxFunctionCountPerFile: 8,
1769
+ maxFunctionComplexity: 8,
1770
+ }),
1771
+ };
1772
+ /**
1773
+ * Resolves the thresholds for a selected refactor-candidate scanning level.
1774
+ */
1775
+ function getRefactorCandidateLevelConfiguration(level = DEFAULT_REFACTOR_CANDIDATE_LEVEL) {
1776
+ return REFACTOR_CANDIDATE_LEVEL_CONFIGURATION_BY_LEVEL[level];
1777
+ }
1778
+ /**
1779
+ * Builds one normalized refactor-candidate level configuration entry.
1780
+ */
1781
+ function createRefactorCandidateLevelConfiguration(options) {
1782
+ const { maxLineCount, maxEntityCountPerFile, maxFunctionCountPerFile, maxFunctionComplexity } = options;
1783
+ return {
1784
+ maxDefaultLineCount: maxLineCount,
1785
+ maxLineCountByExtension: createLineCountLimits(maxLineCount),
1786
+ maxEntityCountPerFile,
1787
+ maxFunctionCountPerFile,
1788
+ maxFunctionComplexity,
1789
+ };
1790
+ }
1791
+ /**
1792
+ * Creates a per-extension line-count table using one shared threshold.
1793
+ */
1794
+ function createLineCountLimits(maxLineCount) {
1795
+ const maxLineCountByExtension = {};
1796
+ for (const extension of SOURCE_FILE_EXTENSIONS) {
1797
+ maxLineCountByExtension[extension] = maxLineCount;
1798
+ }
1799
+ return maxLineCountByExtension;
1800
+ }
1801
+ // Note: [🟡] Code for repository script [RefactorCandidateLevel](scripts/find-refactor-candidates/RefactorCandidateLevel.ts) should never be published outside of `@promptbook/cli`
1802
+
1667
1803
  /**
1668
1804
  * Initializes `coder find-refactor-candidates` command for Promptbook CLI utilities
1669
1805
  *
@@ -1676,17 +1812,23 @@
1676
1812
  command.description(_spaceTrim.spaceTrim(`
1677
1813
  Scan source files to identify refactoring candidates
1678
1814
 
1679
- Flags files that exceed:
1680
- - Line count limits (500 lines per file by extension)
1681
- - Entity count limits (max 4 entities per file)
1815
+ Levels:
1816
+ - low: Conservative scan for only the most obvious refactor targets
1817
+ - medium: Default scan using the current standard thresholds
1818
+ - high: Stricter scan that finds more crowded or complex files
1819
+ - xhigh: Most aggressive scan for denser and more complex candidates
1682
1820
 
1683
1821
  Generates refactor prompts with guidance for identified candidates.
1684
1822
  `));
1685
- command.action(handleActionErrors(async () => {
1823
+ command.addOption(new commander.Option('--level <level>', `Set scan aggressiveness (${REFACTOR_CANDIDATE_LEVEL_VALUES.join(', ')})`)
1824
+ .choices([...REFACTOR_CANDIDATE_LEVEL_VALUES])
1825
+ .default(DEFAULT_REFACTOR_CANDIDATE_LEVEL));
1826
+ command.action(handleActionErrors(async (cliOptions) => {
1827
+ const { level = DEFAULT_REFACTOR_CANDIDATE_LEVEL } = cliOptions;
1686
1828
  // Note: Import the function dynamically to avoid loading heavy dependencies until needed
1687
1829
  const { findRefactorCandidates } = await Promise.resolve().then(function () { return findRefactorCandidates$1; });
1688
1830
  try {
1689
- await findRefactorCandidates();
1831
+ await findRefactorCandidates({ level });
1690
1832
  }
1691
1833
  catch (error) {
1692
1834
  assertsError(error);
@@ -1700,6 +1842,236 @@
1700
1842
  // Note: [🟡] Code for CLI command [find-refactor-candidates](src/cli/cli-commands/coder/find-refactor-candidates.ts) should never be published outside of `@promptbook/cli`
1701
1843
  // Note: [💞] Ignore a discrepancy between file name and entity name
1702
1844
 
1845
+ /**
1846
+ * This error indicates that promptbook not found in the collection
1847
+ *
1848
+ * @public exported from `@promptbook/core`
1849
+ */
1850
+ class NotFoundError extends Error {
1851
+ constructor(message) {
1852
+ super(message);
1853
+ this.name = 'NotFoundError';
1854
+ Object.setPrototypeOf(this, NotFoundError.prototype);
1855
+ }
1856
+ }
1857
+
1858
+ /**
1859
+ * Relative path to the root prompts directory used by Promptbook coder utilities.
1860
+ *
1861
+ * @private internal utility of `ptbk coder`
1862
+ */
1863
+ const PROMPTS_DIRECTORY_PATH = 'prompts';
1864
+ /**
1865
+ * Relative path to the archive directory used by `coder verify`.
1866
+ *
1867
+ * @private internal utility of `ptbk coder`
1868
+ */
1869
+ const PROMPTS_DONE_DIRECTORY_PATH = path.join(PROMPTS_DIRECTORY_PATH, 'done');
1870
+ /**
1871
+ * Relative path to the project-owned boilerplate templates directory.
1872
+ *
1873
+ * @private internal utility of `ptbk coder`
1874
+ */
1875
+ const PROMPTS_TEMPLATES_DIRECTORY_PATH = path.join(PROMPTS_DIRECTORY_PATH, 'templates');
1876
+ /**
1877
+ * Built-in boilerplate templates available to `coder generate-boilerplates`.
1878
+ *
1879
+ * Only the project-agnostic subset is materialized by `coder init`.
1880
+ */
1881
+ const DEFAULT_CODER_PROMPT_TEMPLATE_DEFINITIONS = [
1882
+ {
1883
+ id: 'common',
1884
+ relativeFilePath: path.join(PROMPTS_TEMPLATES_DIRECTORY_PATH, 'common.md'),
1885
+ slugPrefix: null,
1886
+ content: buildCoderPromptTemplateContent([
1887
+ '- @@@',
1888
+ "- Keep in mind the DRY _(don't repeat yourself)_ principle.",
1889
+ '- Do a proper analysis of the current functionality before you start implementing.',
1890
+ '- Add the changes into the [changelog](./changelog/_current-preversion.md)',
1891
+ ]),
1892
+ isDefaultProjectTemplate: true,
1893
+ },
1894
+ {
1895
+ id: 'agents-server',
1896
+ relativeFilePath: path.join(PROMPTS_TEMPLATES_DIRECTORY_PATH, 'agents-server.md'),
1897
+ slugPrefix: 'agents-server',
1898
+ content: buildCoderPromptTemplateContent([
1899
+ '- @@@',
1900
+ "- Keep in mind the DRY _(don't repeat yourself)_ principle.",
1901
+ '- Do a proper analysis of the current functionality before you start implementing.',
1902
+ '- You are working with the [Agents Server](apps/agents-server)',
1903
+ '- If you need to do the database migration, do it',
1904
+ '- Add the changes into the [changelog](changelog/_current-preversion.md)',
1905
+ ]),
1906
+ isDefaultProjectTemplate: false,
1907
+ },
1908
+ ];
1909
+ /**
1910
+ * Project-agnostic coder templates that `ptbk coder init` should materialize in any repository.
1911
+ */
1912
+ const DEFAULT_CODER_PROJECT_PROMPT_TEMPLATE_DEFINITIONS = DEFAULT_CODER_PROMPT_TEMPLATE_DEFINITIONS.filter(({ isDefaultProjectTemplate }) => isDefaultProjectTemplate);
1913
+ /**
1914
+ * Lists the built-in coder boilerplate templates.
1915
+ *
1916
+ * @private internal utility of `ptbk coder`
1917
+ */
1918
+ function getDefaultCoderPromptTemplateDefinitions() {
1919
+ return DEFAULT_CODER_PROMPT_TEMPLATE_DEFINITIONS;
1920
+ }
1921
+ /**
1922
+ * Lists the built-in coder prompt templates that are safe to initialize in any project.
1923
+ *
1924
+ * @private internal utility of `ptbk coder`
1925
+ */
1926
+ function getDefaultCoderProjectPromptTemplateDefinitions() {
1927
+ return DEFAULT_CODER_PROJECT_PROMPT_TEMPLATE_DEFINITIONS;
1928
+ }
1929
+ /**
1930
+ * Resolves one built-in coder boilerplate template definition by its stable identifier.
1931
+ *
1932
+ * @private internal utility of `ptbk coder`
1933
+ */
1934
+ function getDefaultCoderPromptTemplateDefinition(template) {
1935
+ const definition = getDefaultCoderPromptTemplateDefinitionOrUndefined(template);
1936
+ if (!definition) {
1937
+ throw new NotFoundError(`Built-in coder prompt template \`${template}\` was not found.`);
1938
+ }
1939
+ return definition;
1940
+ }
1941
+ /**
1942
+ * Ensures the default project-owned coder template files exist without overwriting user customizations.
1943
+ *
1944
+ * @private internal utility of `ptbk coder`
1945
+ */
1946
+ async function ensureDefaultCoderPromptTemplateFiles(projectPath) {
1947
+ const ensuredTemplateFiles = [];
1948
+ for (const definition of DEFAULT_CODER_PROJECT_PROMPT_TEMPLATE_DEFINITIONS) {
1949
+ const absoluteTemplatePath = path.join(projectPath, definition.relativeFilePath);
1950
+ if (await isExistingFile$1(absoluteTemplatePath)) {
1951
+ ensuredTemplateFiles.push({
1952
+ id: definition.id,
1953
+ relativeFilePath: definition.relativeFilePath,
1954
+ status: 'unchanged',
1955
+ });
1956
+ continue;
1957
+ }
1958
+ await promises.writeFile(absoluteTemplatePath, `${definition.content}\n`, 'utf-8');
1959
+ ensuredTemplateFiles.push({
1960
+ id: definition.id,
1961
+ relativeFilePath: definition.relativeFilePath,
1962
+ status: 'created',
1963
+ });
1964
+ }
1965
+ return ensuredTemplateFiles;
1966
+ }
1967
+ /**
1968
+ * Resolves the template requested by `coder generate-boilerplates`.
1969
+ *
1970
+ * Supports three modes:
1971
+ * - omitted option => built-in `common`
1972
+ * - built-in alias => one of the shared default templates
1973
+ * - relative path => markdown template file resolved from the project root
1974
+ *
1975
+ * @private internal utility of `ptbk coder`
1976
+ */
1977
+ async function resolveCoderPromptTemplate({ projectPath, templateOption, }) {
1978
+ const normalizedTemplateOption = normalizeCoderPromptTemplateOption(templateOption);
1979
+ if (!normalizedTemplateOption) {
1980
+ return createResolvedBuiltInCoderPromptTemplate('common');
1981
+ }
1982
+ const builtInTemplateDefinition = getDefaultCoderPromptTemplateDefinitionOrUndefined(normalizedTemplateOption);
1983
+ if (builtInTemplateDefinition) {
1984
+ return createResolvedBuiltInCoderPromptTemplate(builtInTemplateDefinition.id);
1985
+ }
1986
+ const absoluteTemplatePath = path.join(projectPath, normalizedTemplateOption);
1987
+ try {
1988
+ const content = (await promises.readFile(absoluteTemplatePath, 'utf-8')).trim();
1989
+ return {
1990
+ identifier: normalizedTemplateOption,
1991
+ relativeFilePath: normalizedTemplateOption,
1992
+ content,
1993
+ slugPrefix: deriveCoderPromptSlugPrefix(normalizedTemplateOption),
1994
+ };
1995
+ }
1996
+ catch (error) {
1997
+ if (isNodeJsErrorWithCode(error, 'ENOENT')) {
1998
+ throw new NotFoundError(_spaceTrim.spaceTrim(`
1999
+ Prompt boilerplate template was not found at \`${normalizedTemplateOption}\`.
2000
+
2001
+ - The \`--template\` option resolves paths relative to the current project root: \`${projectPath}\`
2002
+ - Run \`ptbk coder init\` to create the default project templates in \`${PROMPTS_TEMPLATES_DIRECTORY_PATH}\`
2003
+ - Or omit \`--template\` / use the built-in aliases \`common\` or \`agents-server\`
2004
+ `));
2005
+ }
2006
+ throw error;
2007
+ }
2008
+ }
2009
+ /**
2010
+ * Normalizes one raw `--template` option to either a trimmed string or `undefined`.
2011
+ */
2012
+ function normalizeCoderPromptTemplateOption(templateOption) {
2013
+ const normalizedTemplateOption = templateOption === null || templateOption === void 0 ? void 0 : templateOption.trim();
2014
+ if (!normalizedTemplateOption) {
2015
+ return undefined;
2016
+ }
2017
+ return normalizedTemplateOption;
2018
+ }
2019
+ /**
2020
+ * Resolves one built-in template definition without throwing.
2021
+ */
2022
+ function getDefaultCoderPromptTemplateDefinitionOrUndefined(template) {
2023
+ return DEFAULT_CODER_PROMPT_TEMPLATE_DEFINITIONS.find((definition) => definition.id === template);
2024
+ }
2025
+ /**
2026
+ * Builds stable markdown content for one coder prompt template without indentation drift.
2027
+ */
2028
+ function buildCoderPromptTemplateContent(lines) {
2029
+ return lines.join('\n');
2030
+ }
2031
+ /**
2032
+ * Creates a fully resolved template payload from one built-in definition.
2033
+ */
2034
+ function createResolvedBuiltInCoderPromptTemplate(template) {
2035
+ const definition = getDefaultCoderPromptTemplateDefinition(template);
2036
+ return {
2037
+ identifier: definition.id,
2038
+ relativeFilePath: definition.relativeFilePath,
2039
+ content: definition.content,
2040
+ slugPrefix: definition.slugPrefix,
2041
+ };
2042
+ }
2043
+ /**
2044
+ * Derives the filename slug prefix from a project-relative template path.
2045
+ */
2046
+ function deriveCoderPromptSlugPrefix(relativeTemplatePath) {
2047
+ const templateBasename = path.basename(relativeTemplatePath)
2048
+ .replace(/\.[^.]+$/u, '')
2049
+ .replace(/\.template$/u, '');
2050
+ if (templateBasename === 'common') {
2051
+ return null;
2052
+ }
2053
+ return templateBasename;
2054
+ }
2055
+ /**
2056
+ * Checks whether the provided error object exposes a specific Node.js `code`.
2057
+ */
2058
+ function isNodeJsErrorWithCode(error, code) {
2059
+ return typeof error === 'object' && error !== null && 'code' in error && error.code === code;
2060
+ }
2061
+ /**
2062
+ * Checks whether a path exists and is a file.
2063
+ */
2064
+ async function isExistingFile$1(path) {
2065
+ try {
2066
+ return (await promises.stat(path)).isFile();
2067
+ }
2068
+ catch (_a) {
2069
+ return false;
2070
+ }
2071
+ }
2072
+ // Note: [🟡] Code for coder boilerplate templates [boilerplateTemplates](src/cli/cli-commands/coder/boilerplateTemplates.ts) should never be published outside of `@promptbook/cli`
2073
+ // Note: [💞] Ignore a discrepancy between file name and exported helper names
2074
+
1703
2075
  /**
1704
2076
  * Initializes `coder generate-boilerplates` command for Promptbook CLI utilities
1705
2077
  *
@@ -1713,12 +2085,21 @@
1713
2085
  Generate prompt boilerplate files with unique emoji tags
1714
2086
  `));
1715
2087
  command.option('--count <count>', `Number of prompt boilerplate files to generate`, '5');
1716
- command.option('--template <template>', `Prompt template to use: common | agents-server`, 'common');
2088
+ command.option('--template <template>', _spaceTrim.spaceTrim(`
2089
+ Prompt template to use.
2090
+
2091
+ Accepts either a built-in alias (${getDefaultCoderPromptTemplateDefinitions()
2092
+ .map(({ id }) => id)
2093
+ .join(', ')}) or a markdown file path relative to the current project root.
2094
+ `));
1717
2095
  command.action(handleActionErrors(async (cliOptions) => {
1718
2096
  const { count: countOption, template: templateOption } = cliOptions;
1719
2097
  const filesCount = parseFilesCount(countOption);
1720
- const template = parsePromptTemplate(templateOption);
1721
- await generatePromptBoilerplate({ filesCount, template });
2098
+ await generatePromptBoilerplate({
2099
+ projectPath: process.cwd(),
2100
+ filesCount,
2101
+ templateOption,
2102
+ });
1722
2103
  return process.exit(0);
1723
2104
  }));
1724
2105
  }
@@ -1727,14 +2108,15 @@
1727
2108
  *
1728
2109
  * @private internal function of `generatePromptBoilerplate` command
1729
2110
  */
1730
- async function generatePromptBoilerplate({ filesCount, template, }) {
2111
+ async function generatePromptBoilerplate({ projectPath, filesCount, templateOption, }) {
1731
2112
  // Note: Import these dynamically to avoid circular dependencies and keep CLI fast
1732
2113
  const { buildPromptFilename, getPromptNumbering } = await Promise.resolve().then(function () { return getPromptNumbering$1; });
1733
2114
  const { formatPromptEmojiTag, getFreshPromptEmojiTags } = await Promise.resolve().then(function () { return promptEmojiTags; });
1734
2115
  console.info(`🚀 Generate prompt boilerplate files`);
1735
- const promptTemplateContent = loadPromptTemplate(template);
2116
+ fs.mkdirSync(path.join(projectPath, PROMPTS_DIRECTORY_PATH), { recursive: true });
2117
+ const promptTemplate = await resolveCoderPromptTemplate({ projectPath, templateOption });
1736
2118
  const promptNumbering = await getPromptNumbering({
1737
- promptsDir: path.join(process.cwd(), 'prompts'),
2119
+ promptsDir: path.join(projectPath, PROMPTS_DIRECTORY_PATH),
1738
2120
  step: 10,
1739
2121
  ignoreGlobs: ['**/node_modules/**'],
1740
2122
  });
@@ -1743,7 +2125,7 @@
1743
2125
  console.info(colors__default["default"].blue(`Highest existing number for ${promptNumbering.datePrefix} found: ${highestNumberFormatted}`));
1744
2126
  const { availableCount, selectedEmojis } = await getFreshPromptEmojiTags({
1745
2127
  count: filesCount,
1746
- rootDir: process.cwd(),
2128
+ rootDir: projectPath,
1747
2129
  });
1748
2130
  console.info(colors__default["default"].green(`Found ${availableCount} available fresh emojis`));
1749
2131
  console.info(colors__default["default"].green(`Selected emojis: ${selectedEmojis.map((emoji) => formatPromptEmojiTag(emoji)).join(' ')}`));
@@ -1755,8 +2137,9 @@
1755
2137
  const number = promptNumbering.startNumber + i * promptNumbering.step;
1756
2138
  const title = titles[i % titles.length];
1757
2139
  const emoji = selectedEmojis[i];
1758
- const filename = buildPromptFilename(promptNumbering.datePrefix, number, buildPromptSlug$1(template, title));
1759
- const filepath = path.join('prompts', filename);
2140
+ const filename = buildPromptFilename(promptNumbering.datePrefix, number, buildPromptSlug$1(promptTemplate.slugPrefix, title));
2141
+ const filepath = path.join(PROMPTS_DIRECTORY_PATH, filename);
2142
+ const absoluteFilepath = path.join(projectPath, filepath);
1760
2143
  const emojiTag = formatPromptEmojiTag(emoji);
1761
2144
  const one = _spaceTrim.spaceTrim((block) => `
1762
2145
 
@@ -1764,7 +2147,7 @@
1764
2147
 
1765
2148
  ${emojiTag} ${title}
1766
2149
 
1767
- ${block(promptTemplateContent)}
2150
+ ${block(promptTemplate.content)}
1768
2151
  `);
1769
2152
  const content = _spaceTrim.spaceTrim((block) => `
1770
2153
 
@@ -1785,6 +2168,7 @@
1785
2168
  `);
1786
2169
  filesToCreate.push({
1787
2170
  filepath,
2171
+ absoluteFilepath,
1788
2172
  filename,
1789
2173
  content,
1790
2174
  emoji,
@@ -1794,7 +2178,7 @@
1794
2178
  // Create the files
1795
2179
  console.info(colors__default["default"].yellow(`Creating ${filesToCreate.length} files:`));
1796
2180
  for (const file of filesToCreate) {
1797
- fs.writeFileSync(file.filepath, file.content, 'utf-8');
2181
+ fs.writeFileSync(file.absoluteFilepath, file.content, 'utf-8');
1798
2182
  console.info(colors__default["default"].green(`✓ Created: ${file.filename} with ${formatPromptEmojiTag(file.emoji)}`));
1799
2183
  }
1800
2184
  console.info(colors__default["default"].bgGreen(` Successfully created ${filesToCreate.length} prompt boilerplate files! `));
@@ -1813,51 +2197,184 @@
1813
2197
  return Math.floor(filesCount);
1814
2198
  }
1815
2199
  /**
1816
- * Parses and validates the prompt template name.
2200
+ * Builds filename slug from template and placeholder title.
1817
2201
  *
1818
2202
  * @private internal utility of `generatePromptBoilerplate` command
1819
2203
  */
1820
- function parsePromptTemplate(templateOption) {
1821
- if (templateOption === 'common' ||
1822
- templateOption === 'agents-server'
1823
- // <- TODO: Unhardcode and allow this dynamically by the template files.
1824
- ) {
1825
- return templateOption;
2204
+ function buildPromptSlug$1(templateSlugPrefix, title) {
2205
+ if (!templateSlugPrefix) {
2206
+ return title;
1826
2207
  }
1827
- console.info(colors__default["default"].yellow(`Invalid --template '${templateOption}'. Falling back to default 'common'.`));
1828
- return 'common';
2208
+ return `${templateSlugPrefix}-${title}`;
1829
2209
  }
2210
+ // Note: [🟡] Code for CLI command [generate-boilerplates](src/cli/cli-commands/coder/generate-boilerplates.ts) should never be published outside of `@promptbook/cli`
2211
+ // Note: [💞] Ignore a discrepancy between file name and entity name
2212
+
1830
2213
  /**
1831
- * Loads prompt template markdown content from the local templates folder.
2214
+ * Relative path to the shared coder context file initialized in project roots.
1832
2215
  *
1833
- * @private internal utility of `generatePromptBoilerplate` command
2216
+ * @private internal utility of `ptbk coder`
1834
2217
  */
1835
- function loadPromptTemplate(template) {
1836
- const templateFilePath = path.join(__dirname, '../../../../scripts/generate-prompt-boilerplate/templates', `${template}.template.md`);
1837
- return fs.readFileSync(templateFilePath, 'utf-8').trim();
2218
+ const AGENTS_FILE_PATH = 'AGENTS.md';
2219
+ /**
2220
+ * Stable boilerplate instructions written into newly initialized `AGENTS.md` files.
2221
+ */
2222
+ const DEFAULT_CODER_AGENTS_FILE_LINES = [
2223
+ '<!-- TODO: Write instructions for the Promptbook AI Coder here -->',
2224
+ ];
2225
+ /**
2226
+ * Shared markdown boilerplate written into new `AGENTS.md` files.
2227
+ */
2228
+ const DEFAULT_CODER_AGENTS_FILE_CONTENT = DEFAULT_CODER_AGENTS_FILE_LINES.join('\n');
2229
+ /**
2230
+ * Returns the default coder `AGENTS.md` boilerplate instructions.
2231
+ *
2232
+ * @private internal utility of `ptbk coder`
2233
+ */
2234
+ function getDefaultCoderAgentsFileContent() {
2235
+ return DEFAULT_CODER_AGENTS_FILE_CONTENT;
1838
2236
  }
2237
+ // Note: [🟡] Code for coder AGENTS file boilerplate [agentsFile](src/cli/cli-commands/coder/agentsFile.ts) should never be published outside of `@promptbook/cli`
2238
+ // Note: [💞] Ignore a discrepancy between file name and exported helper names
2239
+
1839
2240
  /**
1840
- * Builds filename slug from template and placeholder title.
2241
+ * Normalizes one project-relative path for human-readable CLI output and markdown.
1841
2242
  *
1842
- * @private internal utility of `generatePromptBoilerplate` command
2243
+ * @private internal utility of `ptbk coder`
1843
2244
  */
1844
- function buildPromptSlug$1(template, title) {
1845
- if (template === 'common') {
1846
- return title;
2245
+ function formatDisplayPath(relativePath) {
2246
+ return relativePath.replace(/\\/gu, '/');
2247
+ }
2248
+ // Note: [🟡] Code for coder path formatting [formatDisplayPath](src/cli/cli-commands/coder/formatDisplayPath.ts) should never be published outside of `@promptbook/cli`
2249
+
2250
+ /**
2251
+ * Relative path to the Promptbook Coder quick-reference file initialized in project roots.
2252
+ *
2253
+ * @private internal utility of `ptbk coder`
2254
+ */
2255
+ const AGENT_CODING_FILE_PATH = 'AGENT_CODING.md';
2256
+ /**
2257
+ * Returns the default coder `AGENT_CODING.md` quick-reference content.
2258
+ *
2259
+ * @private internal utility of `ptbk coder`
2260
+ */
2261
+ function getDefaultCoderAgentCodingFileContent({ packageJsonScripts, }) {
2262
+ return [
2263
+ '# Promptbook Coder quick reference',
2264
+ '',
2265
+ `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)}/\`.`,
2266
+ '',
2267
+ '## Workflow',
2268
+ `1. Put repository-wide coding rules into \`${AGENTS_FILE_PATH}\`. The default \`npm run coder:run\` script already passes \`--context ${AGENTS_FILE_PATH}\`.`,
2269
+ `2. Create or customize prompt templates in \`${formatDisplayPath(PROMPTS_TEMPLATES_DIRECTORY_PATH)}/\`. ${buildStarterTemplateSentence()}`,
2270
+ '3. Generate prompt files with `npm run coder:generate-boilerplates` or `npx ptbk coder generate-boilerplates --template <template> --count <count>`.',
2271
+ '4. Replace every `@@@`, keep drafts as `[-]`, and switch prompts to `[ ]` when they are ready to run. Completed prompts are marked `[x]`.',
2272
+ '5. Run `npm run coder:run` to execute the next ready prompt with the configured coding agent.',
2273
+ `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.`,
2274
+ '7. Use `npm run coder:find-refactor-candidates` when you want Promptbook to suggest refactor prompts automatically.',
2275
+ '',
2276
+ '## Templates',
2277
+ `- Project-owned templates created by \`ptbk coder init\`: ${formatInlineCodeList(getDefaultCoderProjectPromptTemplateDefinitions().map(({ relativeFilePath }) => formatDisplayPath(relativeFilePath)))}`,
2278
+ `- Built-in \`--template\` aliases: ${formatInlineCodeList(getDefaultCoderPromptTemplateDefinitions().map(({ id }) => id))}`,
2279
+ `- To add a custom template, create a markdown file such as \`${formatDisplayPath(PROMPTS_TEMPLATES_DIRECTORY_PATH)}/backend.md\`.`,
2280
+ `- To use a project template, run \`npx ptbk coder generate-boilerplates --template ${formatDisplayPath(PROMPTS_TEMPLATES_DIRECTORY_PATH)}/backend.md\`.`,
2281
+ `- 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.`,
2282
+ '',
2283
+ '## Created npm scripts',
2284
+ '| Script | Purpose |',
2285
+ '| --- | --- |',
2286
+ ...buildPackageJsonScriptTableLines(packageJsonScripts),
2287
+ '',
2288
+ '## Customizing the workflow',
2289
+ '- Edit `package.json` if you want `npm run coder:run` to use another coding agent, model, thinking level, context file, or wait mode.',
2290
+ '- Use direct CLI commands when you need one-off flags such as `--priority`, `--ignore-git-changes`, `--dry-run`, `--allow-credits`, or `--auto-migrate`.',
2291
+ '- Use `npx ptbk coder --help` and `npx ptbk coder <command> --help` for the full CLI reference.',
2292
+ ].join('\n');
2293
+ }
2294
+ /**
2295
+ * Builds the sentence describing the starter templates created during initialization.
2296
+ */
2297
+ function buildStarterTemplateSentence() {
2298
+ const starterTemplatePaths = getDefaultCoderProjectPromptTemplateDefinitions().map(({ relativeFilePath }) => formatDisplayPath(relativeFilePath));
2299
+ if (starterTemplatePaths.length === 1) {
2300
+ return `The starter project template created by \`ptbk coder init\` is \`${starterTemplatePaths[0]}\`.`;
1847
2301
  }
1848
- return `${template}-${title}`;
2302
+ return `The starter project templates created by \`ptbk coder init\` are ${formatInlineCodeList(starterTemplatePaths)}.`;
1849
2303
  }
1850
- // Note: [🟡] Code for CLI command [generate-boilerplates](src/cli/cli-commands/coder/generate-boilerplates.ts) should never be published outside of `@promptbook/cli`
1851
- // Note: [💞] Ignore a discrepancy between file name and entity name
2304
+ /**
2305
+ * Builds the markdown table rows describing the initialized npm scripts.
2306
+ */
2307
+ function buildPackageJsonScriptTableLines(packageJsonScripts) {
2308
+ return Object.entries(packageJsonScripts).map(([scriptName, scriptCommand]) => `| \`npm run ${scriptName}\` | ${describeDefaultCoderPackageJsonScript(scriptName, scriptCommand)} |`);
2309
+ }
2310
+ /**
2311
+ * Describes one initialized npm script in human-readable terms.
2312
+ */
2313
+ function describeDefaultCoderPackageJsonScript(scriptName, scriptCommand) {
2314
+ if (scriptName === 'coder:generate-boilerplates') {
2315
+ return `Runs \`${scriptCommand}\` to create new prompt files in \`${formatDisplayPath(PROMPTS_DIRECTORY_PATH)}/\`.`;
2316
+ }
2317
+ if (scriptName === 'coder:run') {
2318
+ return `Runs \`${scriptCommand}\` to execute the next ready prompt with shared repository context from \`${AGENTS_FILE_PATH}\`.`;
2319
+ }
2320
+ if (scriptName === 'coder:find-refactor-candidates') {
2321
+ return `Runs \`${scriptCommand}\` to generate prompt candidates for large or crowded files.`;
2322
+ }
2323
+ if (scriptName === 'coder:verify') {
2324
+ return `Runs \`${scriptCommand}\` to archive verified prompts into \`${formatDisplayPath(PROMPTS_DONE_DIRECTORY_PATH)}/\` and append repair prompts when needed.`;
2325
+ }
2326
+ return `Runs \`${scriptCommand}\`.`;
2327
+ }
2328
+ /**
2329
+ * Formats one inline code list for human-readable markdown.
2330
+ */
2331
+ function formatInlineCodeList(values) {
2332
+ return values.map((value) => `\`${value}\``).join(', ');
2333
+ }
2334
+ // Note: [🟡] Code for coder AGENT_CODING file boilerplate [agentCodingFile](src/cli/cli-commands/coder/agentCodingFile.ts) should never be published outside of `@promptbook/cli`
2335
+ // Note: [💞] Ignore a discrepancy between file name and exported helper names
1852
2336
 
1853
2337
  /**
1854
- * Relative path to the root prompts directory used by Promptbook coder utilities.
2338
+ * Appends one text block to existing file content while preserving readable newlines.
2339
+ *
2340
+ * @private function of `initializeCoderProjectConfiguration`
1855
2341
  */
1856
- const PROMPTS_DIRECTORY_PATH = 'prompts';
2342
+ function appendBlock(currentContent, blockToAppend) {
2343
+ if (currentContent.trim() === '') {
2344
+ return `${blockToAppend}\n`;
2345
+ }
2346
+ const normalizedCurrentContent = currentContent.endsWith('\n') ? currentContent : `${currentContent}\n`;
2347
+ return `${normalizedCurrentContent}\n${blockToAppend}\n`;
2348
+ }
2349
+ // Note: [🟡] Code for coder init text appending [appendBlock](src/cli/cli-commands/coder/appendBlock.ts) should never be published outside of `@promptbook/cli`
2350
+
1857
2351
  /**
1858
- * Relative path to the archive directory used by `coder verify`.
2352
+ * Reads one text file when it exists, otherwise returns `undefined`.
2353
+ *
2354
+ * @private function of `initializeCoderProjectConfiguration`
1859
2355
  */
1860
- const PROMPTS_DONE_DIRECTORY_PATH = path.join(PROMPTS_DIRECTORY_PATH, 'done');
2356
+ async function readTextFileIfExists(path) {
2357
+ try {
2358
+ const fileStats = await promises.stat(path);
2359
+ if (!fileStats.isFile()) {
2360
+ return undefined;
2361
+ }
2362
+ }
2363
+ catch (_a) {
2364
+ return undefined;
2365
+ }
2366
+ return promises.readFile(path, 'utf-8');
2367
+ }
2368
+ // Note: [🟡] Code for coder init text-file reading [readTextFileIfExists](src/cli/cli-commands/coder/readTextFileIfExists.ts) should never be published outside of `@promptbook/cli`
2369
+
2370
+ /**
2371
+ * Relative path to `.env` in the initialized project.
2372
+ */
2373
+ const ENV_FILE_PATH = '.env';
2374
+ /**
2375
+ * Fallback `.env` content used when no required variables need to be appended.
2376
+ */
2377
+ const EMPTY_CODER_ENV_FILE_CONTENT = '# Environment variables for Promptbook coder\n';
1861
2378
  /**
1862
2379
  * Required environment variables for coding-agent git identity.
1863
2380
  */
@@ -1875,6 +2392,476 @@
1875
2392
  value: '13406525ED912F938FEA85AB4046C687298B2382',
1876
2393
  },
1877
2394
  ];
2395
+ /**
2396
+ * Ensures `.env` exists and contains all required coder environment variables.
2397
+ *
2398
+ * @private function of `initializeCoderProjectConfiguration`
2399
+ */
2400
+ async function ensureCoderEnvFile(projectPath) {
2401
+ const envFilePath = path.join(projectPath, ENV_FILE_PATH);
2402
+ const existingEnvContent = await readTextFileIfExists(envFilePath);
2403
+ const isEnvFileExisting = existingEnvContent !== undefined;
2404
+ const currentEnvContent = existingEnvContent || '';
2405
+ const existingEnvVariableNames = parseEnvVariableNames(currentEnvContent);
2406
+ const missingEnvVariables = REQUIRED_CODER_ENV_VARIABLES.filter(({ name }) => !existingEnvVariableNames.has(name));
2407
+ if (missingEnvVariables.length === 0) {
2408
+ if (!isEnvFileExisting) {
2409
+ await promises.writeFile(envFilePath, EMPTY_CODER_ENV_FILE_CONTENT, 'utf-8');
2410
+ return {
2411
+ envFileStatus: 'created',
2412
+ initializedEnvVariableNames: [],
2413
+ };
2414
+ }
2415
+ return {
2416
+ envFileStatus: 'unchanged',
2417
+ initializedEnvVariableNames: [],
2418
+ };
2419
+ }
2420
+ const envBlockToAppend = buildMissingEnvVariablesBlock(missingEnvVariables);
2421
+ const nextEnvContent = appendBlock(currentEnvContent, envBlockToAppend);
2422
+ await promises.writeFile(envFilePath, nextEnvContent, 'utf-8');
2423
+ return {
2424
+ envFileStatus: isEnvFileExisting ? 'updated' : 'created',
2425
+ initializedEnvVariableNames: missingEnvVariables.map(({ name }) => name),
2426
+ };
2427
+ }
2428
+ /**
2429
+ * Parses variable names currently defined in `.env` style content.
2430
+ */
2431
+ function parseEnvVariableNames(envContent) {
2432
+ const variableNames = new Set();
2433
+ for (const line of envContent.split(/\r?\n/)) {
2434
+ const trimmedLine = line.trim();
2435
+ if (trimmedLine === '' || trimmedLine.startsWith('#')) {
2436
+ continue;
2437
+ }
2438
+ const match = trimmedLine.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=/);
2439
+ if (!match || !match[1]) {
2440
+ continue;
2441
+ }
2442
+ variableNames.add(match[1]);
2443
+ }
2444
+ return variableNames;
2445
+ }
2446
+ /**
2447
+ * Builds a `.env` block containing missing coder environment variables.
2448
+ */
2449
+ function buildMissingEnvVariablesBlock(variables) {
2450
+ return _spaceTrim.spaceTrim(`
2451
+ # Promptbook coder identity (initialized by \`ptbk coder init\`)
2452
+ ${variables.map(({ name, value }) => `${name}=${JSON.stringify(value)}`).join('\n')}
2453
+ `);
2454
+ }
2455
+ // Note: [🟡] Code for coder init environment bootstrapping [ensureCoderEnvFile](src/cli/cli-commands/coder/ensureCoderEnvFile.ts) should never be published outside of `@promptbook/cli`
2456
+
2457
+ /**
2458
+ * Relative path to `.gitignore` in the initialized project.
2459
+ */
2460
+ const GITIGNORE_FILE_PATH = '.gitignore';
2461
+ /**
2462
+ * `.gitignore` block required by standalone Promptbook coder projects.
2463
+ */
2464
+ const CODER_GITIGNORE_BLOCK = _spaceTrim.spaceTrim(`
2465
+ # Promptbook Coder
2466
+ /.tmp
2467
+ `);
2468
+ /**
2469
+ * Ensures `.gitignore` contains the standalone Promptbook coder cache entry.
2470
+ *
2471
+ * @private function of `initializeCoderProjectConfiguration`
2472
+ */
2473
+ async function ensureCoderGitignoreFile(projectPath) {
2474
+ const gitignorePath = path.join(projectPath, GITIGNORE_FILE_PATH);
2475
+ const currentGitignoreContent = await readTextFileIfExists(gitignorePath);
2476
+ if (currentGitignoreContent !== undefined && hasTmpGitignoreRule(currentGitignoreContent)) {
2477
+ return 'unchanged';
2478
+ }
2479
+ const nextGitignoreContent = appendBlock(currentGitignoreContent || '', CODER_GITIGNORE_BLOCK);
2480
+ await promises.writeFile(gitignorePath, nextGitignoreContent, 'utf-8');
2481
+ return currentGitignoreContent === undefined ? 'created' : 'updated';
2482
+ }
2483
+ /**
2484
+ * Detects whether `.gitignore` already covers the standalone coder temp directory.
2485
+ */
2486
+ function hasTmpGitignoreRule(gitignoreContent) {
2487
+ return /(^|[\r\n])\/?\.tmp(?:[\r\n]|$)/u.test(gitignoreContent);
2488
+ }
2489
+ // Note: [🟡] Code for coder init gitignore bootstrapping [ensureCoderGitignoreFile](src/cli/cli-commands/coder/ensureCoderGitignoreFile.ts) should never be published outside of `@promptbook/cli`
2490
+
2491
+ /**
2492
+ * Ensures one coder markdown file exists with the provided default boilerplate.
2493
+ *
2494
+ * @private function of `initializeCoderProjectConfiguration`
2495
+ */
2496
+ async function ensureCoderMarkdownFile(projectPath, relativeFilePath, fileContent) {
2497
+ const absoluteFilePath = path.join(projectPath, relativeFilePath);
2498
+ if (await isExistingFile(absoluteFilePath)) {
2499
+ return 'unchanged';
2500
+ }
2501
+ await promises.writeFile(absoluteFilePath, `${fileContent}\n`, 'utf-8');
2502
+ return 'created';
2503
+ }
2504
+ /**
2505
+ * Checks whether a path exists and is a file.
2506
+ */
2507
+ async function isExistingFile(path) {
2508
+ try {
2509
+ return (await promises.stat(path)).isFile();
2510
+ }
2511
+ catch (_a) {
2512
+ return false;
2513
+ }
2514
+ }
2515
+ // Note: [🟡] Code for coder init markdown bootstrapping [ensureCoderMarkdownFile](src/cli/cli-commands/coder/ensureCoderMarkdownFile.ts) should never be published outside of `@promptbook/cli`
2516
+
2517
+ /**
2518
+ * Default npm scripts initialized by `ptbk coder init`.
2519
+ */
2520
+ const DEFAULT_CODER_PACKAGE_JSON_SCRIPTS = {
2521
+ 'coder:generate-boilerplates': 'npx ptbk coder generate-boilerplates',
2522
+ 'coder:run': 'npx ptbk coder run --agent github-copilot --model gpt-5.4 --thinking-level xhigh --context AGENTS.md --no-wait',
2523
+ 'coder:find-refactor-candidates': 'npx ptbk coder find-refactor-candidates',
2524
+ 'coder:verify': 'npx ptbk coder verify',
2525
+ };
2526
+ /**
2527
+ * Lists the default npm scripts initialized by `ptbk coder init`.
2528
+ *
2529
+ * @private internal utility of `coder init` command
2530
+ */
2531
+ function getDefaultCoderPackageJsonScripts() {
2532
+ return DEFAULT_CODER_PACKAGE_JSON_SCRIPTS;
2533
+ }
2534
+ // Note: [🟡] Code for coder init package scripts [getDefaultCoderPackageJsonScripts](src/cli/cli-commands/coder/getDefaultCoderPackageJsonScripts.ts) should never be published outside of `@promptbook/cli`
2535
+
2536
+ /**
2537
+ * This error indicates that the promptbook in a markdown format cannot be parsed into a valid promptbook object
2538
+ *
2539
+ * @public exported from `@promptbook/core`
2540
+ */
2541
+ class ParseError extends Error {
2542
+ constructor(message) {
2543
+ super(message);
2544
+ this.name = 'ParseError';
2545
+ Object.setPrototypeOf(this, ParseError.prototype);
2546
+ }
2547
+ }
2548
+ // TODO: Maybe split `ParseError` and `ApplyError`
2549
+
2550
+ /**
2551
+ * Default indentation used when creating new JSON configuration files.
2552
+ */
2553
+ const DEFAULT_JSON_FILE_INDENTATION = ' ';
2554
+ /**
2555
+ * Default newline used when creating new JSON configuration files.
2556
+ */
2557
+ const DEFAULT_JSON_FILE_NEWLINE = '\n';
2558
+ /**
2559
+ * Ensures one JSON object field contains the provided string-record entries.
2560
+ *
2561
+ * @private function of `initializeCoderProjectConfiguration`
2562
+ */
2563
+ async function mergeStringRecordJsonFile({ projectPath, relativeFilePath, fieldPath, nextEntries, ensureParentDirectoryPath, }) {
2564
+ if (ensureParentDirectoryPath) {
2565
+ await promises.mkdir(path.join(projectPath, ensureParentDirectoryPath), { recursive: true });
2566
+ }
2567
+ const absoluteFilePath = path.join(projectPath, relativeFilePath);
2568
+ const fileContent = await readTextFileIfExists(absoluteFilePath);
2569
+ const formatting = detectJsonFileFormatting(fileContent);
2570
+ const jsonObject = fileContent === undefined ? {} : await parseJsonObjectFile(relativeFilePath, fileContent);
2571
+ const existingEntries = getStringRecordOrDefault(jsonObject[fieldPath], relativeFilePath, fieldPath);
2572
+ let hasChanges = fileContent === undefined;
2573
+ const mergedEntries = { ...existingEntries };
2574
+ for (const [entryKey, entryValue] of Object.entries(nextEntries)) {
2575
+ if (mergedEntries[entryKey] !== entryValue) {
2576
+ mergedEntries[entryKey] = entryValue;
2577
+ hasChanges = true;
2578
+ }
2579
+ }
2580
+ if (!hasChanges) {
2581
+ return 'unchanged';
2582
+ }
2583
+ const nextJsonObject = { ...jsonObject };
2584
+ nextJsonObject[fieldPath] = mergedEntries;
2585
+ await promises.writeFile(absoluteFilePath, serializeJsonObject(nextJsonObject, formatting), 'utf-8');
2586
+ return fileContent === undefined ? 'created' : 'updated';
2587
+ }
2588
+ /**
2589
+ * Parses one JSON object file while accepting VS Code style comments and trailing commas.
2590
+ */
2591
+ async function parseJsonObjectFile(relativeFilePath, fileContent) {
2592
+ if (fileContent.trim() === '') {
2593
+ return {};
2594
+ }
2595
+ const typescript = await import('typescript');
2596
+ const parsedFile = typescript.parseConfigFileTextToJson(relativeFilePath, fileContent);
2597
+ if (parsedFile.error) {
2598
+ throw new ParseError(_spaceTrim.spaceTrim(`
2599
+ Cannot parse \`${relativeFilePath}\` as JSON.
2600
+
2601
+ ${typescript.flattenDiagnosticMessageText(parsedFile.error.messageText, '\n')}
2602
+ `));
2603
+ }
2604
+ if (!isPlainObject(parsedFile.config)) {
2605
+ throw new ParseError(_spaceTrim.spaceTrim(`
2606
+ File \`${relativeFilePath}\` must contain one top-level JSON object.
2607
+ `));
2608
+ }
2609
+ return parsedFile.config;
2610
+ }
2611
+ /**
2612
+ * Reads one JSON object field as a string-to-string record.
2613
+ */
2614
+ function getStringRecordOrDefault(value, relativeFilePath, fieldPath) {
2615
+ if (value === undefined) {
2616
+ return {};
2617
+ }
2618
+ if (!isPlainObject(value)) {
2619
+ throw new ParseError(_spaceTrim.spaceTrim(`
2620
+ File \`${relativeFilePath}\` contains invalid \`${fieldPath}\`.
2621
+
2622
+ Expected \`${fieldPath}\` to be an object with string values.
2623
+ `));
2624
+ }
2625
+ const stringRecord = {};
2626
+ for (const [key, itemValue] of Object.entries(value)) {
2627
+ if (typeof itemValue !== 'string') {
2628
+ throw new ParseError(_spaceTrim.spaceTrim(`
2629
+ File \`${relativeFilePath}\` contains invalid \`${fieldPath}.${key}\`.
2630
+
2631
+ Expected \`${fieldPath}\` to be an object with string values.
2632
+ `));
2633
+ }
2634
+ stringRecord[key] = itemValue;
2635
+ }
2636
+ return stringRecord;
2637
+ }
2638
+ /**
2639
+ * Serializes one JSON object using detected or default formatting.
2640
+ */
2641
+ function serializeJsonObject(value, formatting) {
2642
+ return `${JSON.stringify(value, null, formatting.indentation)}${formatting.newline}`;
2643
+ }
2644
+ /**
2645
+ * Detects indentation and newline formatting from an existing JSON file.
2646
+ */
2647
+ function detectJsonFileFormatting(fileContent) {
2648
+ if (!fileContent) {
2649
+ return {
2650
+ indentation: DEFAULT_JSON_FILE_INDENTATION,
2651
+ newline: DEFAULT_JSON_FILE_NEWLINE,
2652
+ };
2653
+ }
2654
+ const indentationMatch = fileContent.match(/^[ \t]+(?=")/mu);
2655
+ return {
2656
+ indentation: (indentationMatch === null || indentationMatch === void 0 ? void 0 : indentationMatch[0]) || DEFAULT_JSON_FILE_INDENTATION,
2657
+ newline: fileContent.includes('\r\n') ? '\r\n' : '\n',
2658
+ };
2659
+ }
2660
+ /**
2661
+ * Checks whether one parsed JSON value is a plain object.
2662
+ */
2663
+ function isPlainObject(value) {
2664
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
2665
+ }
2666
+ // Note: [🟡] Code for coder init JSON merging [mergeStringRecordJsonFile](src/cli/cli-commands/coder/mergeStringRecordJsonFile.ts) should never be published outside of `@promptbook/cli`
2667
+
2668
+ /**
2669
+ * Relative path to `package.json` in the initialized project.
2670
+ */
2671
+ const PACKAGE_JSON_FILE_PATH = 'package.json';
2672
+ /**
2673
+ * Ensures `package.json` contains the standalone Promptbook coder helper scripts.
2674
+ *
2675
+ * @private function of `initializeCoderProjectConfiguration`
2676
+ */
2677
+ async function ensureCoderPackageJsonFile(projectPath) {
2678
+ return mergeStringRecordJsonFile({
2679
+ projectPath,
2680
+ relativeFilePath: PACKAGE_JSON_FILE_PATH,
2681
+ fieldPath: 'scripts',
2682
+ nextEntries: getDefaultCoderPackageJsonScripts(),
2683
+ });
2684
+ }
2685
+ // Note: [🟡] Code for coder init package.json bootstrapping [ensureCoderPackageJsonFile](src/cli/cli-commands/coder/ensureCoderPackageJsonFile.ts) should never be published outside of `@promptbook/cli`
2686
+
2687
+ /**
2688
+ * VS Code setting key used to route pasted markdown images into prompt-specific screenshots.
2689
+ */
2690
+ const MARKDOWN_COPY_FILES_DESTINATION_SETTING_KEY = 'markdown.copyFiles.destination';
2691
+ /**
2692
+ * Markdown glob used for coder prompt files inside VS Code settings.
2693
+ */
2694
+ const PROMPTS_MARKDOWN_FILE_GLOB = 'prompts/*md';
2695
+ /**
2696
+ * Screenshot destination used for pasted prompt images inside VS Code settings.
2697
+ */
2698
+ const PROMPTS_SCREENSHOT_DESTINATION = './prompts/screenshots/${documentBaseName}.png';
2699
+ /**
2700
+ * Default VS Code settings initialized by `ptbk coder init`.
2701
+ */
2702
+ const DEFAULT_CODER_VSCODE_SETTINGS = {
2703
+ [MARKDOWN_COPY_FILES_DESTINATION_SETTING_KEY]: {
2704
+ [PROMPTS_MARKDOWN_FILE_GLOB]: PROMPTS_SCREENSHOT_DESTINATION,
2705
+ },
2706
+ };
2707
+ /**
2708
+ * Lists the default VS Code settings initialized by `ptbk coder init`.
2709
+ *
2710
+ * @private internal utility of `coder init` command
2711
+ */
2712
+ function getDefaultCoderVscodeSettings() {
2713
+ return DEFAULT_CODER_VSCODE_SETTINGS;
2714
+ }
2715
+ // Note: [🟡] Code for coder init VS Code settings [getDefaultCoderVscodeSettings](src/cli/cli-commands/coder/getDefaultCoderVscodeSettings.ts) should never be published outside of `@promptbook/cli`
2716
+
2717
+ /**
2718
+ * Relative path to the VS Code settings file initialized by `ptbk coder init`.
2719
+ */
2720
+ const VSCODE_SETTINGS_FILE_PATH = '.vscode/settings.json';
2721
+ /**
2722
+ * Relative path to the VS Code directory initialized by `ptbk coder init`.
2723
+ */
2724
+ const VSCODE_DIRECTORY_PATH = '.vscode';
2725
+ /**
2726
+ * Ensures VS Code routes pasted prompt images into `prompts/screenshots`.
2727
+ *
2728
+ * @private function of `initializeCoderProjectConfiguration`
2729
+ */
2730
+ async function ensureCoderVscodeSettingsFile(projectPath) {
2731
+ const [fieldPath, nextEntries] = resolveDefaultCoderVscodeSettingsEntry();
2732
+ return mergeStringRecordJsonFile({
2733
+ projectPath,
2734
+ relativeFilePath: VSCODE_SETTINGS_FILE_PATH,
2735
+ fieldPath,
2736
+ nextEntries,
2737
+ ensureParentDirectoryPath: VSCODE_DIRECTORY_PATH,
2738
+ });
2739
+ }
2740
+ /**
2741
+ * Resolves the default string-record entry that `coder init` merges into VS Code settings.
2742
+ */
2743
+ function resolveDefaultCoderVscodeSettingsEntry() {
2744
+ const [defaultVscodeSettingsEntry] = Object.entries(getDefaultCoderVscodeSettings());
2745
+ if (!defaultVscodeSettingsEntry) {
2746
+ throw new Error('Default coder VS Code settings must define at least one string-record entry.');
2747
+ }
2748
+ return defaultVscodeSettingsEntry;
2749
+ }
2750
+ // Note: [🟡] Code for coder init VS Code bootstrapping [ensureCoderVscodeSettingsFile](src/cli/cli-commands/coder/ensureCoderVscodeSettingsFile.ts) should never be published outside of `@promptbook/cli`
2751
+
2752
+ /**
2753
+ * Ensures a relative directory exists in the project root.
2754
+ *
2755
+ * @private function of `initializeCoderProjectConfiguration`
2756
+ */
2757
+ async function ensureDirectory(projectPath, relativeDirectoryPath) {
2758
+ const directoryPath = path.join(projectPath, relativeDirectoryPath);
2759
+ const isDirectoryExisting = await isExistingDirectory(directoryPath);
2760
+ if (!isDirectoryExisting) {
2761
+ await promises.mkdir(directoryPath, { recursive: true });
2762
+ return 'created';
2763
+ }
2764
+ return 'unchanged';
2765
+ }
2766
+ /**
2767
+ * Checks whether a path exists and is a directory.
2768
+ */
2769
+ async function isExistingDirectory(path) {
2770
+ try {
2771
+ return (await promises.stat(path)).isDirectory();
2772
+ }
2773
+ catch (_a) {
2774
+ return false;
2775
+ }
2776
+ }
2777
+ // Note: [🟡] Code for coder init directory creation [ensureDirectory](src/cli/cli-commands/coder/ensureDirectory.ts) should never be published outside of `@promptbook/cli`
2778
+
2779
+ /**
2780
+ * Creates or updates all coder configuration artifacts required in the current project.
2781
+ *
2782
+ * @private internal utility of `coder init` command
2783
+ */
2784
+ async function initializeCoderProjectConfiguration(projectPath) {
2785
+ const promptsDirectoryStatus = await ensureDirectory(projectPath, PROMPTS_DIRECTORY_PATH);
2786
+ const promptsDoneDirectoryStatus = await ensureDirectory(projectPath, PROMPTS_DONE_DIRECTORY_PATH);
2787
+ const promptsTemplatesDirectoryStatus = await ensureDirectory(projectPath, PROMPTS_TEMPLATES_DIRECTORY_PATH);
2788
+ const promptTemplateFileStatuses = await ensureDefaultCoderPromptTemplateFiles(projectPath);
2789
+ const agentsFileStatus = await ensureCoderMarkdownFile(projectPath, AGENTS_FILE_PATH, getDefaultCoderAgentsFileContent());
2790
+ const agentCodingFileStatus = await ensureCoderMarkdownFile(projectPath, AGENT_CODING_FILE_PATH, getDefaultCoderAgentCodingFileContent({
2791
+ packageJsonScripts: getDefaultCoderPackageJsonScripts(),
2792
+ }));
2793
+ const { envFileStatus, initializedEnvVariableNames } = await ensureCoderEnvFile(projectPath);
2794
+ const gitignoreFileStatus = await ensureCoderGitignoreFile(projectPath);
2795
+ const packageJsonFileStatus = await ensureCoderPackageJsonFile(projectPath);
2796
+ const vscodeSettingsFileStatus = await ensureCoderVscodeSettingsFile(projectPath);
2797
+ return {
2798
+ promptsDirectoryStatus,
2799
+ promptsDoneDirectoryStatus,
2800
+ promptsTemplatesDirectoryStatus,
2801
+ promptTemplateFileStatuses,
2802
+ agentsFileStatus,
2803
+ agentCodingFileStatus,
2804
+ envFileStatus,
2805
+ gitignoreFileStatus,
2806
+ packageJsonFileStatus,
2807
+ vscodeSettingsFileStatus,
2808
+ initializedEnvVariableNames,
2809
+ };
2810
+ }
2811
+ // Note: [🟡] Code for coder init project bootstrapping [initializeCoderProjectConfiguration](src/cli/cli-commands/coder/initializeCoderProjectConfiguration.ts) should never be published outside of `@promptbook/cli`
2812
+
2813
+ /**
2814
+ * Prints a readable summary of what was initialized for the user.
2815
+ *
2816
+ * @private function of `coder init` command
2817
+ */
2818
+ function printInitializationSummary(summary) {
2819
+ console.info(colors__default["default"].green('Promptbook coder configuration initialized.'));
2820
+ printInitializationStatusLine('prompts/', summary.promptsDirectoryStatus);
2821
+ printInitializationStatusLine('prompts/done/', summary.promptsDoneDirectoryStatus);
2822
+ printInitializationStatusLine('prompts/templates/', summary.promptsTemplatesDirectoryStatus);
2823
+ for (const templateFileStatus of summary.promptTemplateFileStatuses) {
2824
+ printInitializationStatusLine(formatDisplayPath(templateFileStatus.relativeFilePath), templateFileStatus.status);
2825
+ }
2826
+ printInitializationStatusLine(AGENTS_FILE_PATH, summary.agentsFileStatus);
2827
+ printInitializationStatusLine(AGENT_CODING_FILE_PATH, summary.agentCodingFileStatus);
2828
+ printInitializationStatusLine('.env', summary.envFileStatus);
2829
+ printInitializationStatusLine('.gitignore', summary.gitignoreFileStatus);
2830
+ printInitializationStatusLine('package.json', summary.packageJsonFileStatus);
2831
+ printInitializationStatusLine('.vscode/settings.json', summary.vscodeSettingsFileStatus);
2832
+ if (summary.initializedEnvVariableNames.length > 0) {
2833
+ printInitializationNote(`Added env variables: ${summary.initializedEnvVariableNames.join(', ')}`, colors__default["default"].cyan);
2834
+ }
2835
+ else {
2836
+ printInitializationNote('Required coder env variables are already present.', colors__default["default"].gray);
2837
+ }
2838
+ }
2839
+ /**
2840
+ * Formats one initialization status into a human-readable label.
2841
+ */
2842
+ function formatInitializationStatus(status) {
2843
+ if (status === 'created') {
2844
+ return 'created';
2845
+ }
2846
+ if (status === 'updated') {
2847
+ return 'updated';
2848
+ }
2849
+ return 'unchanged';
2850
+ }
2851
+ /**
2852
+ * Prints one checked initialization-status line.
2853
+ */
2854
+ function printInitializationStatusLine(relativePath, status) {
2855
+ console.info(colors__default["default"].gray(`✔ ${relativePath}: ${formatInitializationStatus(status)}`));
2856
+ }
2857
+ /**
2858
+ * Prints one checked initialization note.
2859
+ */
2860
+ function printInitializationNote(message, colorize) {
2861
+ console.info(colorize(`✔ ${message}`));
2862
+ }
2863
+ // Note: [🟡] Code for coder init summary printing [printInitializationSummary](src/cli/cli-commands/coder/printInitializationSummary.ts) should never be published outside of `@promptbook/cli`
2864
+
1878
2865
  /**
1879
2866
  * Initializes `coder init` command for Promptbook CLI utilities.
1880
2867
  *
@@ -1888,9 +2875,15 @@
1888
2875
  command.description(_spaceTrim.spaceTrim(`
1889
2876
  Initialize Promptbook coder configuration for current project
1890
2877
 
1891
- Creates:
2878
+ Creates or updates:
1892
2879
  - prompts/
1893
2880
  - prompts/done/
2881
+ ${listDefaultCoderProjectPromptTemplateDisplayPaths()}
2882
+ - ${AGENTS_FILE_PATH}
2883
+ - ${AGENT_CODING_FILE_PATH}
2884
+ - .gitignore
2885
+ - package.json
2886
+ - .vscode/settings.json
1894
2887
 
1895
2888
  Ensures required coding-agent environment variables in .env:
1896
2889
  - CODING_AGENT_GIT_NAME
@@ -1903,146 +2896,12 @@
1903
2896
  }));
1904
2897
  }
1905
2898
  /**
1906
- * Creates or updates all coder configuration artifacts required in the current project.
1907
- */
1908
- async function initializeCoderProjectConfiguration(projectPath) {
1909
- const promptsDirectoryStatus = await ensureDirectory(projectPath, PROMPTS_DIRECTORY_PATH);
1910
- const promptsDoneDirectoryStatus = await ensureDirectory(projectPath, PROMPTS_DONE_DIRECTORY_PATH);
1911
- const { envFileStatus, initializedEnvVariableNames } = await ensureCoderEnvFile(projectPath);
1912
- return {
1913
- promptsDirectoryStatus,
1914
- promptsDoneDirectoryStatus,
1915
- envFileStatus,
1916
- initializedEnvVariableNames,
1917
- };
1918
- }
1919
- /**
1920
- * Ensures a relative directory exists in the project root.
1921
- */
1922
- async function ensureDirectory(projectPath, relativeDirectoryPath) {
1923
- const directoryPath = path.join(projectPath, relativeDirectoryPath);
1924
- const existedBefore = await isExistingDirectory(directoryPath);
1925
- if (!existedBefore) {
1926
- await promises.mkdir(directoryPath, { recursive: true });
1927
- return 'created';
1928
- }
1929
- return 'unchanged';
1930
- }
1931
- /**
1932
- * Ensures `.env` exists and contains all required coder environment variables.
2899
+ * Lists the project-owned template file paths created by `ptbk coder init`.
1933
2900
  */
1934
- async function ensureCoderEnvFile(projectPath) {
1935
- const envFilePath = path.join(projectPath, '.env');
1936
- const envFileExistedBefore = await isExistingFile(envFilePath);
1937
- const currentEnvContent = envFileExistedBefore ? await promises.readFile(envFilePath, 'utf-8') : '';
1938
- const existingEnvVariables = parseEnvVariableNames(currentEnvContent);
1939
- const missingEnvVariables = REQUIRED_CODER_ENV_VARIABLES.filter(({ name }) => !existingEnvVariables.has(name));
1940
- if (missingEnvVariables.length === 0) {
1941
- if (!envFileExistedBefore) {
1942
- await promises.writeFile(envFilePath, '# Environment variables for Promptbook coder\n', 'utf-8');
1943
- return {
1944
- envFileStatus: 'created',
1945
- initializedEnvVariableNames: [],
1946
- };
1947
- }
1948
- return {
1949
- envFileStatus: 'unchanged',
1950
- initializedEnvVariableNames: [],
1951
- };
1952
- }
1953
- const envBlockToAppend = buildMissingEnvVariablesBlock(missingEnvVariables);
1954
- const nextEnvContent = appendBlock(currentEnvContent, envBlockToAppend);
1955
- await promises.writeFile(envFilePath, nextEnvContent, 'utf-8');
1956
- return {
1957
- envFileStatus: envFileExistedBefore ? 'updated' : 'created',
1958
- initializedEnvVariableNames: missingEnvVariables.map(({ name }) => name),
1959
- };
1960
- }
1961
- /**
1962
- * Parses variable names currently defined in `.env` style content.
1963
- */
1964
- function parseEnvVariableNames(envContent) {
1965
- const variableNames = new Set();
1966
- for (const line of envContent.split(/\r?\n/)) {
1967
- const trimmedLine = line.trim();
1968
- if (trimmedLine === '' || trimmedLine.startsWith('#')) {
1969
- continue;
1970
- }
1971
- const match = trimmedLine.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=/);
1972
- if (!match || !match[1]) {
1973
- continue;
1974
- }
1975
- variableNames.add(match[1]);
1976
- }
1977
- return variableNames;
1978
- }
1979
- /**
1980
- * Builds a `.env` block containing missing coder environment variables.
1981
- */
1982
- function buildMissingEnvVariablesBlock(variables) {
1983
- return _spaceTrim.spaceTrim(`
1984
- # Promptbook coder identity (initialized by \`ptbk coder init\`)
1985
- ${variables.map(({ name, value }) => `${name}=${JSON.stringify(value)}`).join('\n')}
1986
- `);
1987
- }
1988
- /**
1989
- * Appends one text block to existing file content while preserving readable newlines.
1990
- */
1991
- function appendBlock(currentContent, blockToAppend) {
1992
- if (currentContent.trim() === '') {
1993
- return `${blockToAppend}\n`;
1994
- }
1995
- const normalizedCurrentContent = currentContent.endsWith('\n') ? currentContent : `${currentContent}\n`;
1996
- return `${normalizedCurrentContent}\n${blockToAppend}\n`;
1997
- }
1998
- /**
1999
- * Prints a readable summary of what was initialized for the user.
2000
- */
2001
- function printInitializationSummary(summary) {
2002
- console.info(colors__default["default"].green('Promptbook coder configuration initialized.'));
2003
- console.info(colors__default["default"].gray(`- prompts/: ${formatInitializationStatus(summary.promptsDirectoryStatus)}`));
2004
- console.info(colors__default["default"].gray(`- prompts/done/: ${formatInitializationStatus(summary.promptsDoneDirectoryStatus)}`));
2005
- console.info(colors__default["default"].gray(`- .env: ${formatInitializationStatus(summary.envFileStatus)}`));
2006
- if (summary.initializedEnvVariableNames.length > 0) {
2007
- console.info(colors__default["default"].cyan(`- Added env variables: ${summary.initializedEnvVariableNames.join(', ')}`));
2008
- }
2009
- else {
2010
- console.info(colors__default["default"].gray('- Required coder env variables are already present.'));
2011
- }
2012
- }
2013
- /**
2014
- * Formats one initialization status into a human-readable label.
2015
- */
2016
- function formatInitializationStatus(status) {
2017
- if (status === 'created') {
2018
- return 'created';
2019
- }
2020
- if (status === 'updated') {
2021
- return 'updated';
2022
- }
2023
- return 'unchanged';
2024
- }
2025
- /**
2026
- * Checks whether a path exists and is a file.
2027
- */
2028
- async function isExistingFile(path) {
2029
- try {
2030
- return (await promises.stat(path)).isFile();
2031
- }
2032
- catch (_a) {
2033
- return false;
2034
- }
2035
- }
2036
- /**
2037
- * Checks whether a path exists and is a directory.
2038
- */
2039
- async function isExistingDirectory(path) {
2040
- try {
2041
- return (await promises.stat(path)).isDirectory();
2042
- }
2043
- catch (_a) {
2044
- return false;
2045
- }
2901
+ function listDefaultCoderProjectPromptTemplateDisplayPaths() {
2902
+ return getDefaultCoderProjectPromptTemplateDefinitions()
2903
+ .map(({ relativeFilePath }) => `- ${formatDisplayPath(relativeFilePath)}`)
2904
+ .join('\n');
2046
2905
  }
2047
2906
  // Note: [🟡] Code for CLI command [init](src/cli/cli-commands/coder/init.ts) should never be published outside of `@promptbook/cli`
2048
2907
  // Note: [💞] Ignore a discrepancy between file name and entity name
@@ -4046,33 +4905,6 @@
4046
4905
  }
4047
4906
  }
4048
4907
 
4049
- /**
4050
- * This error indicates that promptbook not found in the collection
4051
- *
4052
- * @public exported from `@promptbook/core`
4053
- */
4054
- class NotFoundError extends Error {
4055
- constructor(message) {
4056
- super(message);
4057
- this.name = 'NotFoundError';
4058
- Object.setPrototypeOf(this, NotFoundError.prototype);
4059
- }
4060
- }
4061
-
4062
- /**
4063
- * This error indicates that the promptbook in a markdown format cannot be parsed into a valid promptbook object
4064
- *
4065
- * @public exported from `@promptbook/core`
4066
- */
4067
- class ParseError extends Error {
4068
- constructor(message) {
4069
- super(message);
4070
- this.name = 'ParseError';
4071
- Object.setPrototypeOf(this, ParseError.prototype);
4072
- }
4073
- }
4074
- // TODO: Maybe split `ParseError` and `ApplyError`
4075
-
4076
4908
  /**
4077
4909
  * Generates random token
4078
4910
  *
@@ -40303,91 +41135,6 @@
40303
41135
  findFreshEmojiTag: findFreshEmojiTag
40304
41136
  });
40305
41137
 
40306
- /**
40307
- * Root folders that contain source-like files for scanning.
40308
- */
40309
- const SOURCE_ROOTS = ['src', 'apps', 'scripts', 'examples', 'agents', 'other'];
40310
- /**
40311
- * File extensions treated as source code.
40312
- */
40313
- const SOURCE_FILE_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx'];
40314
- /**
40315
- * Glob patterns that should be ignored when scanning for source files.
40316
- */
40317
- const SOURCE_FILE_IGNORE_GLOBS = [
40318
- '**/node_modules/**',
40319
- '**/packages/**',
40320
- '**/.*/**',
40321
- '**/.git/**',
40322
- '**/.idea/**',
40323
- '**/.vscode/**',
40324
- '**/.promptbook/**',
40325
- '**/.next/**',
40326
- '**/.tmp/**',
40327
- '**/tmp/**',
40328
- '**/coverage/**',
40329
- '**/dist/**',
40330
- '**/build/**',
40331
- '**/out/**',
40332
- '**/prompts/**',
40333
- '**/changelog/**',
40334
- ];
40335
- /**
40336
- * Default maximum line count for source files.
40337
- */
40338
- const DEFAULT_MAX_LINE_COUNT = 2000;
40339
- /**
40340
- * Per-extension line count limits.
40341
- */
40342
- const LINE_COUNT_LIMITS_BY_EXTENSION = {
40343
- '.ts': 2000,
40344
- '.tsx': 2000,
40345
- '.js': 2000,
40346
- '.jsx': 2000,
40347
- };
40348
- /**
40349
- * Glob patterns that are exempt from line-count checks.
40350
- */
40351
- const LINE_COUNT_EXEMPT_GLOBS = ['other/cspell-dictionaries/**/*.txt'];
40352
- /**
40353
- * Maximum number of entities before a file is flagged.
40354
- */
40355
- const MAX_ENTITIES_PER_FILE = 20;
40356
- /**
40357
- * File extensions eligible for entity counting.
40358
- */
40359
- const ENTITY_COUNT_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx'];
40360
- /**
40361
- * Markers that identify generated files which should be skipped.
40362
- */
40363
- const GENERATED_CODE_MARKERS = [
40364
- 'WARNING: This code has been generated',
40365
- 'This code has been generated so that any manual changes will be overwritten',
40366
- ];
40367
- /**
40368
- * Name of the prompts directory.
40369
- */
40370
- const PROMPTS_DIR_NAME = 'prompts';
40371
- /**
40372
- * Step size used for prompt numbering.
40373
- */
40374
- const PROMPT_NUMBER_STEP = 10;
40375
- /**
40376
- * Prefix used for generated prompt slugs.
40377
- */
40378
- const PROMPT_SLUG_PREFIX = 'refactor';
40379
- /**
40380
- * Label used to mark the target file in generated prompts.
40381
- */
40382
- const PROMPT_TARGET_LABEL = 'Target file';
40383
- /**
40384
- * Maximum length for generated prompt slugs.
40385
- */
40386
- const PROMPT_SLUG_MAX_LENGTH = 80;
40387
- /**
40388
- * Note: [?] Code in this file should never be published in any package
40389
- */
40390
-
40391
41138
  /**
40392
41139
  * Normalizes a repo-relative path to use forward slashes.
40393
41140
  *
@@ -40405,7 +41152,7 @@
40405
41152
  * @private function of findRefactorCandidates
40406
41153
  */
40407
41154
  async function analyzeSourceFileForRefactorCandidate(options) {
40408
- const { filePath, lineCountExemptPaths, rootDir } = options;
41155
+ const { filePath, heuristics, lineCountExemptPaths, rootDir } = options;
40409
41156
  const normalizedAbsolutePath = normalizeAbsolutePath$1(filePath);
40410
41157
  const content = await promises.readFile(filePath, 'utf-8');
40411
41158
  if (isGeneratedFile(content)) {
@@ -40416,15 +41163,21 @@
40416
41163
  const reasons = [];
40417
41164
  if (!lineCountExemptPaths.has(normalizedAbsolutePath)) {
40418
41165
  const lineCount = countLines(content);
40419
- const maxLines = getMaxLinesForExtension(extension);
41166
+ const maxLines = getMaxLinesForExtension(extension, heuristics);
40420
41167
  if (lineCount > maxLines) {
40421
41168
  reasons.push(`lines ${lineCount}/${maxLines}`);
40422
41169
  }
40423
41170
  }
40424
- if (ENTITY_COUNT_EXTENSIONS.includes(extension)) {
40425
- const entityCount = countEntities(content, extension, filePath);
40426
- if (entityCount > MAX_ENTITIES_PER_FILE) {
40427
- reasons.push(`entities ${entityCount}/${MAX_ENTITIES_PER_FILE}`);
41171
+ if (STRUCTURAL_ANALYSIS_EXTENSIONS.includes(extension)) {
41172
+ const structureSummary = summarizeSourceFileStructure(content, extension, filePath);
41173
+ if (structureSummary.entityCount > heuristics.maxEntityCountPerFile) {
41174
+ reasons.push(`entities ${structureSummary.entityCount}/${heuristics.maxEntityCountPerFile}`);
41175
+ }
41176
+ if (structureSummary.functionCount > heuristics.maxFunctionCountPerFile) {
41177
+ reasons.push(`functions ${structureSummary.functionCount}/${heuristics.maxFunctionCountPerFile}`);
41178
+ }
41179
+ if (structureSummary.maxFunctionComplexity > heuristics.maxFunctionComplexity) {
41180
+ reasons.push(buildComplexityReason(structureSummary, heuristics.maxFunctionComplexity));
40428
41181
  }
40429
41182
  }
40430
41183
  if (reasons.length === 0) {
@@ -40449,9 +41202,9 @@
40449
41202
  *
40450
41203
  * @private function of analyzeSourceFileForRefactorCandidate
40451
41204
  */
40452
- function getMaxLinesForExtension(extension) {
41205
+ function getMaxLinesForExtension(extension, heuristics) {
40453
41206
  var _a;
40454
- return (_a = LINE_COUNT_LIMITS_BY_EXTENSION[extension]) !== null && _a !== void 0 ? _a : DEFAULT_MAX_LINE_COUNT;
41207
+ return (_a = heuristics.maxLineCountByExtension[extension]) !== null && _a !== void 0 ? _a : heuristics.maxDefaultLineCount;
40455
41208
  }
40456
41209
  /**
40457
41210
  * Counts lines while ignoring a trailing newline.
@@ -40466,14 +41219,17 @@
40466
41219
  return lines[lines.length - 1] === '' ? lines.length - 1 : lines.length;
40467
41220
  }
40468
41221
  /**
40469
- * Counts top-level entities in a source file.
41222
+ * Summarizes the structural metrics used to score one source file.
40470
41223
  *
40471
41224
  * @private function of analyzeSourceFileForRefactorCandidate
40472
41225
  */
40473
- function countEntities(content, extension, filePath) {
41226
+ function summarizeSourceFileStructure(content, extension, filePath) {
40474
41227
  const scriptKind = getScriptKindForExtension(extension);
40475
- const sourceFile = ts__namespace.createSourceFile(filePath, content, ts__namespace.ScriptTarget.Latest, false, scriptKind);
40476
- return countEntitiesInSourceFile(sourceFile);
41228
+ const sourceFile = ts__namespace.createSourceFile(filePath, content, ts__namespace.ScriptTarget.Latest, true, scriptKind);
41229
+ return {
41230
+ entityCount: countEntitiesInSourceFile(sourceFile),
41231
+ ...summarizeFunctionsInSourceFile(sourceFile),
41232
+ };
40477
41233
  }
40478
41234
  /**
40479
41235
  * Counts top-level entities in a parsed TypeScript source file.
@@ -40507,6 +41263,169 @@
40507
41263
  }
40508
41264
  return count;
40509
41265
  }
41266
+ /**
41267
+ * Summarizes named functions and methods in a parsed source file.
41268
+ *
41269
+ * @private function of analyzeSourceFileForRefactorCandidate
41270
+ */
41271
+ function summarizeFunctionsInSourceFile(sourceFile) {
41272
+ let functionCount = 0;
41273
+ let maxFunctionComplexity = 0;
41274
+ let mostComplexFunctionName = null;
41275
+ const visitNode = (node) => {
41276
+ if (isCountedFunctionLikeDeclaration(node)) {
41277
+ functionCount += 1;
41278
+ const functionComplexity = calculateFunctionComplexity(node);
41279
+ if (functionComplexity > maxFunctionComplexity) {
41280
+ maxFunctionComplexity = functionComplexity;
41281
+ mostComplexFunctionName = getFunctionDisplayName(node);
41282
+ }
41283
+ }
41284
+ ts__namespace.forEachChild(node, visitNode);
41285
+ };
41286
+ visitNode(sourceFile);
41287
+ return {
41288
+ functionCount,
41289
+ maxFunctionComplexity,
41290
+ mostComplexFunctionName,
41291
+ };
41292
+ }
41293
+ /**
41294
+ * Determines whether a node counts as a named function or method for density checks.
41295
+ *
41296
+ * @private function of analyzeSourceFileForRefactorCandidate
41297
+ */
41298
+ function isCountedFunctionLikeDeclaration(node) {
41299
+ if (ts__namespace.isFunctionDeclaration(node) ||
41300
+ ts__namespace.isMethodDeclaration(node) ||
41301
+ ts__namespace.isConstructorDeclaration(node) ||
41302
+ ts__namespace.isGetAccessorDeclaration(node) ||
41303
+ ts__namespace.isSetAccessorDeclaration(node)) {
41304
+ return true;
41305
+ }
41306
+ if (ts__namespace.isArrowFunction(node) || ts__namespace.isFunctionExpression(node)) {
41307
+ return isNamedFunctionExpression(node);
41308
+ }
41309
+ return false;
41310
+ }
41311
+ /**
41312
+ * Determines whether a function expression is attached to a named variable or property.
41313
+ *
41314
+ * @private function of analyzeSourceFileForRefactorCandidate
41315
+ */
41316
+ function isNamedFunctionExpression(node) {
41317
+ const parent = node.parent;
41318
+ return (ts__namespace.isVariableDeclaration(parent) || ts__namespace.isPropertyDeclaration(parent) || ts__namespace.isPropertyAssignment(parent));
41319
+ }
41320
+ /**
41321
+ * Calculates a lightweight cyclomatic-complexity score for one function.
41322
+ *
41323
+ * @private function of analyzeSourceFileForRefactorCandidate
41324
+ */
41325
+ function calculateFunctionComplexity(functionNode) {
41326
+ if (!functionNode.body) {
41327
+ return 1;
41328
+ }
41329
+ let complexity = 1;
41330
+ const visitNode = (node) => {
41331
+ if (node !== functionNode.body && isCountedFunctionLikeDeclaration(node)) {
41332
+ return;
41333
+ }
41334
+ if (isComplexityDecisionNode(node)) {
41335
+ complexity += 1;
41336
+ }
41337
+ ts__namespace.forEachChild(node, visitNode);
41338
+ };
41339
+ visitNode(functionNode.body);
41340
+ return complexity;
41341
+ }
41342
+ /**
41343
+ * Determines whether a node should increase the complexity score.
41344
+ *
41345
+ * @private function of analyzeSourceFileForRefactorCandidate
41346
+ */
41347
+ function isComplexityDecisionNode(node) {
41348
+ if (ts__namespace.isIfStatement(node) ||
41349
+ ts__namespace.isConditionalExpression(node) ||
41350
+ ts__namespace.isCatchClause(node) ||
41351
+ ts__namespace.isForStatement(node) ||
41352
+ ts__namespace.isForInStatement(node) ||
41353
+ ts__namespace.isForOfStatement(node) ||
41354
+ ts__namespace.isWhileStatement(node) ||
41355
+ ts__namespace.isDoStatement(node) ||
41356
+ ts__namespace.isCaseClause(node)) {
41357
+ return true;
41358
+ }
41359
+ if (ts__namespace.isBinaryExpression(node)) {
41360
+ const operatorKind = node.operatorToken.kind;
41361
+ return (operatorKind === ts__namespace.SyntaxKind.AmpersandAmpersandToken ||
41362
+ operatorKind === ts__namespace.SyntaxKind.BarBarToken ||
41363
+ operatorKind === ts__namespace.SyntaxKind.QuestionQuestionToken);
41364
+ }
41365
+ return false;
41366
+ }
41367
+ /**
41368
+ * Resolves a readable display name for a counted function-like declaration.
41369
+ *
41370
+ * @private function of analyzeSourceFileForRefactorCandidate
41371
+ */
41372
+ function getFunctionDisplayName(functionNode) {
41373
+ if (ts__namespace.isConstructorDeclaration(functionNode)) {
41374
+ return 'constructor';
41375
+ }
41376
+ if (ts__namespace.isFunctionDeclaration(functionNode) ||
41377
+ ts__namespace.isMethodDeclaration(functionNode) ||
41378
+ ts__namespace.isGetAccessorDeclaration(functionNode) ||
41379
+ ts__namespace.isSetAccessorDeclaration(functionNode)) {
41380
+ if (!functionNode.name) {
41381
+ return null;
41382
+ }
41383
+ return getPropertyNameText(functionNode.name);
41384
+ }
41385
+ if (ts__namespace.isArrowFunction(functionNode) || ts__namespace.isFunctionExpression(functionNode)) {
41386
+ if (functionNode.name) {
41387
+ return functionNode.name.text;
41388
+ }
41389
+ const parent = functionNode.parent;
41390
+ if (ts__namespace.isVariableDeclaration(parent)) {
41391
+ return getBindingNameText(parent.name);
41392
+ }
41393
+ if (ts__namespace.isPropertyDeclaration(parent) || ts__namespace.isPropertyAssignment(parent)) {
41394
+ return getPropertyNameText(parent.name);
41395
+ }
41396
+ }
41397
+ return null;
41398
+ }
41399
+ /**
41400
+ * Resolves text for a binding name when it is a simple identifier.
41401
+ *
41402
+ * @private function of analyzeSourceFileForRefactorCandidate
41403
+ */
41404
+ function getBindingNameText(name) {
41405
+ return ts__namespace.isIdentifier(name) ? name.text : null;
41406
+ }
41407
+ /**
41408
+ * Resolves text for a property name while preserving computed names when necessary.
41409
+ *
41410
+ * @private function of analyzeSourceFileForRefactorCandidate
41411
+ */
41412
+ function getPropertyNameText(name) {
41413
+ if (ts__namespace.isIdentifier(name) || ts__namespace.isPrivateIdentifier(name) || ts__namespace.isStringLiteral(name) || ts__namespace.isNumericLiteral(name)) {
41414
+ return name.text;
41415
+ }
41416
+ return name.getText();
41417
+ }
41418
+ /**
41419
+ * Formats the reason emitted when a function in the file exceeds the complexity threshold.
41420
+ *
41421
+ * @private function of analyzeSourceFileForRefactorCandidate
41422
+ */
41423
+ function buildComplexityReason(structureSummary, maxAllowedFunctionComplexity) {
41424
+ const functionSuffix = structureSummary.mostComplexFunctionName
41425
+ ? ` in \`${structureSummary.mostComplexFunctionName}\``
41426
+ : '';
41427
+ return `complexity ${structureSummary.maxFunctionComplexity}/${maxAllowedFunctionComplexity}${functionSuffix}`;
41428
+ }
40510
41429
  /**
40511
41430
  * Resolves the script kind for a source file extension.
40512
41431
  *
@@ -40540,13 +41459,15 @@
40540
41459
  *
40541
41460
  * @private function of findRefactorCandidates
40542
41461
  */
40543
- async function findRefactorCandidatesInProject(rootDir) {
41462
+ async function findRefactorCandidatesInProject(options) {
41463
+ const { heuristics, rootDir } = options;
40544
41464
  const lineCountExemptPaths = await buildExemptPathSet(rootDir, LINE_COUNT_EXEMPT_GLOBS);
40545
41465
  const sourceFiles = await listSourceFiles(rootDir);
40546
41466
  const candidates = [];
40547
41467
  for (const filePath of sourceFiles) {
40548
41468
  const candidate = await analyzeSourceFileForRefactorCandidate({
40549
41469
  filePath,
41470
+ heuristics,
40550
41471
  lineCountExemptPaths,
40551
41472
  rootDir,
40552
41473
  });
@@ -40819,11 +41740,18 @@
40819
41740
  if (counts.entityCount !== null && counts.maxEntities !== null) {
40820
41741
  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.`);
40821
41742
  }
41743
+ if (counts.functionCount !== null && counts.maxFunctions !== null) {
41744
+ 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.`);
41745
+ }
41746
+ if (counts.functionComplexity !== null && counts.maxFunctionComplexity !== null) {
41747
+ const functionSuffix = counts.mostComplexFunctionName ? ` in \`${counts.mostComplexFunctionName}\`` : '';
41748
+ 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.`);
41749
+ }
40822
41750
  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.');
40823
41751
  return guidance;
40824
41752
  }
40825
41753
  /**
40826
- * Extracts line and entity counts from refactor reasons.
41754
+ * Extracts structural counts from refactor reasons.
40827
41755
  *
40828
41756
  * @private function of buildPromptContent
40829
41757
  */
@@ -40832,6 +41760,11 @@
40832
41760
  let maxLines = null;
40833
41761
  let entityCount = null;
40834
41762
  let maxEntities = null;
41763
+ let functionCount = null;
41764
+ let maxFunctions = null;
41765
+ let functionComplexity = null;
41766
+ let maxFunctionComplexity = null;
41767
+ let mostComplexFunctionName = null;
40835
41768
  for (const reason of reasons) {
40836
41769
  const lineMatch = reason.match(/lines\s+(?<count>\d+)\/(?<max>\d+)/i);
40837
41770
  if (lineMatch === null || lineMatch === void 0 ? void 0 : lineMatch.groups) {
@@ -40843,6 +41776,19 @@
40843
41776
  if (entityMatch === null || entityMatch === void 0 ? void 0 : entityMatch.groups) {
40844
41777
  entityCount = Number(entityMatch.groups.count);
40845
41778
  maxEntities = Number(entityMatch.groups.max);
41779
+ continue;
41780
+ }
41781
+ const functionMatch = reason.match(/functions\s+(?<count>\d+)\/(?<max>\d+)/i);
41782
+ if (functionMatch === null || functionMatch === void 0 ? void 0 : functionMatch.groups) {
41783
+ functionCount = Number(functionMatch.groups.count);
41784
+ maxFunctions = Number(functionMatch.groups.max);
41785
+ continue;
41786
+ }
41787
+ const complexityMatch = reason.match(/complexity\s+(?<count>\d+)\/(?<max>\d+)(?:\s+in\s+`(?<functionName>[^`]+)`)?/i);
41788
+ if (complexityMatch === null || complexityMatch === void 0 ? void 0 : complexityMatch.groups) {
41789
+ functionComplexity = Number(complexityMatch.groups.count);
41790
+ maxFunctionComplexity = Number(complexityMatch.groups.max);
41791
+ mostComplexFunctionName = complexityMatch.groups.functionName || null;
40846
41792
  }
40847
41793
  }
40848
41794
  return {
@@ -40850,6 +41796,11 @@
40850
41796
  maxLines,
40851
41797
  entityCount,
40852
41798
  maxEntities,
41799
+ functionCount,
41800
+ maxFunctions,
41801
+ functionComplexity,
41802
+ maxFunctionComplexity,
41803
+ mostComplexFunctionName,
40853
41804
  };
40854
41805
  }
40855
41806
  /**
@@ -40858,14 +41809,23 @@
40858
41809
  * @private function of buildPromptContent
40859
41810
  */
40860
41811
  function buildDensityNote(counts) {
40861
- if (counts.lineCount !== null && counts.entityCount !== null) {
40862
- return 'The file mixes multiple concerns, making it harder to follow.';
41812
+ const activeSignalsCount = [
41813
+ counts.lineCount !== null,
41814
+ counts.entityCount !== null,
41815
+ counts.functionCount !== null,
41816
+ counts.functionComplexity !== null,
41817
+ ].filter(Boolean).length;
41818
+ if (activeSignalsCount > 1) {
41819
+ return 'The file mixes multiple concerns and dense logic, making it harder to follow.';
40863
41820
  }
40864
41821
  if (counts.lineCount !== null) {
40865
41822
  return 'The file is large enough that it is hard to follow.';
40866
41823
  }
40867
- if (counts.entityCount !== null) {
40868
- return 'The file is dense enough that it is hard to follow.';
41824
+ if (counts.entityCount !== null || counts.functionCount !== null) {
41825
+ return 'The file packs too many responsibilities into one place.';
41826
+ }
41827
+ if (counts.functionComplexity !== null) {
41828
+ return 'The file contains logic that is too complex to follow comfortably.';
40869
41829
  }
40870
41830
  return null;
40871
41831
  }
@@ -40959,13 +41919,19 @@
40959
41919
  *
40960
41920
  * @public exported from `@promptbook/cli`
40961
41921
  */
40962
- async function findRefactorCandidates() {
41922
+ async function findRefactorCandidates(options = {}) {
41923
+ const { level = DEFAULT_REFACTOR_CANDIDATE_LEVEL } = options;
41924
+ const heuristics = getRefactorCandidateLevelConfiguration(level);
40963
41925
  initializeFindRefactorCandidatesRun();
40964
- console.info(colors__default["default"].cyan('?? Find refactor candidates'));
41926
+ console.info(colors__default["default"].cyan('⚡🏭 Find refactor candidates'));
41927
+ console.info(colors__default["default"].gray(`Using \`${level}\` scan level.`));
40965
41928
  const rootDir = process.cwd();
40966
41929
  const promptsDir = path.join(rootDir, PROMPTS_DIR_NAME);
40967
41930
  const existingTargets = await loadExistingPromptTargets(promptsDir);
40968
- const candidates = await findRefactorCandidatesInProject(rootDir);
41931
+ const candidates = await findRefactorCandidatesInProject({
41932
+ heuristics,
41933
+ rootDir,
41934
+ });
40969
41935
  if (candidates.length === 0) {
40970
41936
  console.info(colors__default["default"].green('No refactor candidates found.'));
40971
41937
  return;
@@ -44051,11 +45017,11 @@
44051
45017
  ${block(options.prompt)}
44052
45018
 
44053
45019
  ${delimiter}
44054
- )" \
44055
- --yolo \
44056
- --no-ask-user \
44057
- --no-color \
44058
- --output-format json \
45020
+ )" \\
45021
+ --yolo \\
45022
+ --no-ask-user \\
45023
+ --no-color \\
45024
+ --output-format json \\
44059
45025
  --stream off${modelArgument}${thinkingLevelArgument}
44060
45026
  `);
44061
45027
  }