cap-pro 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (275) hide show
  1. package/.claude-plugin/README.md +26 -0
  2. package/.claude-plugin/marketplace.json +24 -0
  3. package/.claude-plugin/plugin.json +24 -0
  4. package/LICENSE +21 -0
  5. package/README.ja-JP.md +834 -0
  6. package/README.ko-KR.md +823 -0
  7. package/README.md +806 -0
  8. package/README.pt-BR.md +452 -0
  9. package/README.zh-CN.md +800 -0
  10. package/agents/cap-architect.md +269 -0
  11. package/agents/cap-brainstormer.md +207 -0
  12. package/agents/cap-curator.md +276 -0
  13. package/agents/cap-debugger.md +365 -0
  14. package/agents/cap-designer.md +246 -0
  15. package/agents/cap-historian.md +464 -0
  16. package/agents/cap-migrator.md +291 -0
  17. package/agents/cap-prototyper.md +197 -0
  18. package/agents/cap-validator.md +308 -0
  19. package/bin/install.js +5433 -0
  20. package/cap/bin/cap-tools.cjs +853 -0
  21. package/cap/bin/lib/arc-scanner.cjs +344 -0
  22. package/cap/bin/lib/cap-affinity-engine.cjs +862 -0
  23. package/cap/bin/lib/cap-anchor.cjs +228 -0
  24. package/cap/bin/lib/cap-annotation-writer.cjs +340 -0
  25. package/cap/bin/lib/cap-checkpoint.cjs +434 -0
  26. package/cap/bin/lib/cap-cluster-detect.cjs +945 -0
  27. package/cap/bin/lib/cap-cluster-display.cjs +52 -0
  28. package/cap/bin/lib/cap-cluster-format.cjs +245 -0
  29. package/cap/bin/lib/cap-cluster-helpers.cjs +295 -0
  30. package/cap/bin/lib/cap-cluster-io.cjs +212 -0
  31. package/cap/bin/lib/cap-completeness.cjs +540 -0
  32. package/cap/bin/lib/cap-deps.cjs +583 -0
  33. package/cap/bin/lib/cap-design-families.cjs +332 -0
  34. package/cap/bin/lib/cap-design.cjs +966 -0
  35. package/cap/bin/lib/cap-divergence-detector.cjs +400 -0
  36. package/cap/bin/lib/cap-doctor.cjs +752 -0
  37. package/cap/bin/lib/cap-feature-map-internals.cjs +19 -0
  38. package/cap/bin/lib/cap-feature-map-migrate.cjs +335 -0
  39. package/cap/bin/lib/cap-feature-map-monorepo.cjs +885 -0
  40. package/cap/bin/lib/cap-feature-map-shard.cjs +315 -0
  41. package/cap/bin/lib/cap-feature-map.cjs +1943 -0
  42. package/cap/bin/lib/cap-fitness-score.cjs +1075 -0
  43. package/cap/bin/lib/cap-impact-analysis.cjs +652 -0
  44. package/cap/bin/lib/cap-learn-review.cjs +1072 -0
  45. package/cap/bin/lib/cap-learning-signals.cjs +627 -0
  46. package/cap/bin/lib/cap-loader.cjs +227 -0
  47. package/cap/bin/lib/cap-logger.cjs +57 -0
  48. package/cap/bin/lib/cap-memory-bridge.cjs +764 -0
  49. package/cap/bin/lib/cap-memory-confidence.cjs +452 -0
  50. package/cap/bin/lib/cap-memory-dir.cjs +987 -0
  51. package/cap/bin/lib/cap-memory-engine.cjs +698 -0
  52. package/cap/bin/lib/cap-memory-extends.cjs +398 -0
  53. package/cap/bin/lib/cap-memory-graph.cjs +790 -0
  54. package/cap/bin/lib/cap-memory-migrate.cjs +2015 -0
  55. package/cap/bin/lib/cap-memory-pin.cjs +183 -0
  56. package/cap/bin/lib/cap-memory-platform.cjs +490 -0
  57. package/cap/bin/lib/cap-memory-prune.cjs +707 -0
  58. package/cap/bin/lib/cap-memory-schema.cjs +812 -0
  59. package/cap/bin/lib/cap-migrate-tags.cjs +309 -0
  60. package/cap/bin/lib/cap-migrate.cjs +540 -0
  61. package/cap/bin/lib/cap-pattern-apply.cjs +1203 -0
  62. package/cap/bin/lib/cap-pattern-pipeline.cjs +1034 -0
  63. package/cap/bin/lib/cap-plugin-manifest.cjs +80 -0
  64. package/cap/bin/lib/cap-realtime-affinity.cjs +399 -0
  65. package/cap/bin/lib/cap-reconcile.cjs +570 -0
  66. package/cap/bin/lib/cap-research-gate.cjs +218 -0
  67. package/cap/bin/lib/cap-scope-filter.cjs +402 -0
  68. package/cap/bin/lib/cap-semantic-pipeline.cjs +1038 -0
  69. package/cap/bin/lib/cap-session-extract.cjs +987 -0
  70. package/cap/bin/lib/cap-session.cjs +445 -0
  71. package/cap/bin/lib/cap-snapshot-linkage.cjs +963 -0
  72. package/cap/bin/lib/cap-stack-docs.cjs +646 -0
  73. package/cap/bin/lib/cap-tag-observer.cjs +371 -0
  74. package/cap/bin/lib/cap-tag-scanner.cjs +1766 -0
  75. package/cap/bin/lib/cap-telemetry.cjs +466 -0
  76. package/cap/bin/lib/cap-test-audit.cjs +1438 -0
  77. package/cap/bin/lib/cap-thread-migrator.cjs +307 -0
  78. package/cap/bin/lib/cap-thread-synthesis.cjs +545 -0
  79. package/cap/bin/lib/cap-thread-tracker.cjs +519 -0
  80. package/cap/bin/lib/cap-trace.cjs +399 -0
  81. package/cap/bin/lib/cap-trust-mode.cjs +336 -0
  82. package/cap/bin/lib/cap-ui-design-editor.cjs +642 -0
  83. package/cap/bin/lib/cap-ui-mind-map.cjs +712 -0
  84. package/cap/bin/lib/cap-ui-thread-nav.cjs +693 -0
  85. package/cap/bin/lib/cap-ui.cjs +1245 -0
  86. package/cap/bin/lib/cap-upgrade.cjs +1028 -0
  87. package/cap/bin/lib/cli/arg-helpers.cjs +49 -0
  88. package/cap/bin/lib/cli/frontmatter-router.cjs +31 -0
  89. package/cap/bin/lib/cli/init-router.cjs +68 -0
  90. package/cap/bin/lib/cli/phase-router.cjs +102 -0
  91. package/cap/bin/lib/cli/state-router.cjs +61 -0
  92. package/cap/bin/lib/cli/template-router.cjs +37 -0
  93. package/cap/bin/lib/cli/uat-router.cjs +29 -0
  94. package/cap/bin/lib/cli/validation-router.cjs +26 -0
  95. package/cap/bin/lib/cli/verification-router.cjs +31 -0
  96. package/cap/bin/lib/cli/workstream-router.cjs +39 -0
  97. package/cap/bin/lib/commands.cjs +961 -0
  98. package/cap/bin/lib/config.cjs +467 -0
  99. package/cap/bin/lib/convention-reader.cjs +258 -0
  100. package/cap/bin/lib/core.cjs +1241 -0
  101. package/cap/bin/lib/feature-aggregator.cjs +423 -0
  102. package/cap/bin/lib/frontmatter.cjs +337 -0
  103. package/cap/bin/lib/init.cjs +1443 -0
  104. package/cap/bin/lib/manifest-generator.cjs +383 -0
  105. package/cap/bin/lib/milestone.cjs +253 -0
  106. package/cap/bin/lib/model-profiles.cjs +69 -0
  107. package/cap/bin/lib/monorepo-context.cjs +226 -0
  108. package/cap/bin/lib/monorepo-migrator.cjs +509 -0
  109. package/cap/bin/lib/phase.cjs +889 -0
  110. package/cap/bin/lib/profile-output.cjs +989 -0
  111. package/cap/bin/lib/profile-pipeline.cjs +540 -0
  112. package/cap/bin/lib/roadmap.cjs +330 -0
  113. package/cap/bin/lib/security.cjs +394 -0
  114. package/cap/bin/lib/session-manager.cjs +292 -0
  115. package/cap/bin/lib/skeleton-generator.cjs +179 -0
  116. package/cap/bin/lib/state.cjs +1032 -0
  117. package/cap/bin/lib/template.cjs +231 -0
  118. package/cap/bin/lib/test-detector.cjs +62 -0
  119. package/cap/bin/lib/uat.cjs +283 -0
  120. package/cap/bin/lib/verify.cjs +889 -0
  121. package/cap/bin/lib/workspace-detector.cjs +371 -0
  122. package/cap/bin/lib/workstream.cjs +492 -0
  123. package/cap/commands/gsd/workstreams.md +63 -0
  124. package/cap/references/arc-standard.md +315 -0
  125. package/cap/references/cap-agent-architecture.md +101 -0
  126. package/cap/references/cap-gitignore-template +9 -0
  127. package/cap/references/cap-zero-deps.md +158 -0
  128. package/cap/references/checkpoints.md +778 -0
  129. package/cap/references/continuation-format.md +249 -0
  130. package/cap/references/contract-test-templates.md +312 -0
  131. package/cap/references/feature-map-template.md +25 -0
  132. package/cap/references/git-integration.md +295 -0
  133. package/cap/references/git-planning-commit.md +38 -0
  134. package/cap/references/model-profiles.md +174 -0
  135. package/cap/references/phase-numbering.md +126 -0
  136. package/cap/references/planning-config.md +202 -0
  137. package/cap/references/property-test-templates.md +316 -0
  138. package/cap/references/security-test-templates.md +347 -0
  139. package/cap/references/session-template.json +8 -0
  140. package/cap/references/tdd.md +263 -0
  141. package/cap/references/user-profiling.md +681 -0
  142. package/cap/references/verification-patterns.md +612 -0
  143. package/cap/templates/UAT.md +265 -0
  144. package/cap/templates/claude-md.md +175 -0
  145. package/cap/templates/codebase/architecture.md +255 -0
  146. package/cap/templates/codebase/concerns.md +310 -0
  147. package/cap/templates/codebase/conventions.md +307 -0
  148. package/cap/templates/codebase/integrations.md +280 -0
  149. package/cap/templates/codebase/stack.md +186 -0
  150. package/cap/templates/codebase/structure.md +285 -0
  151. package/cap/templates/codebase/testing.md +480 -0
  152. package/cap/templates/config.json +44 -0
  153. package/cap/templates/context.md +352 -0
  154. package/cap/templates/continue-here.md +78 -0
  155. package/cap/templates/copilot-instructions.md +7 -0
  156. package/cap/templates/debug-subagent-prompt.md +91 -0
  157. package/cap/templates/discussion-log.md +63 -0
  158. package/cap/templates/milestone-archive.md +123 -0
  159. package/cap/templates/milestone.md +115 -0
  160. package/cap/templates/phase-prompt.md +610 -0
  161. package/cap/templates/planner-subagent-prompt.md +117 -0
  162. package/cap/templates/project.md +186 -0
  163. package/cap/templates/requirements.md +231 -0
  164. package/cap/templates/research-project/ARCHITECTURE.md +204 -0
  165. package/cap/templates/research-project/FEATURES.md +147 -0
  166. package/cap/templates/research-project/PITFALLS.md +200 -0
  167. package/cap/templates/research-project/STACK.md +120 -0
  168. package/cap/templates/research-project/SUMMARY.md +170 -0
  169. package/cap/templates/research.md +552 -0
  170. package/cap/templates/roadmap.md +202 -0
  171. package/cap/templates/state.md +176 -0
  172. package/cap/templates/summary.md +364 -0
  173. package/cap/templates/user-preferences.md +498 -0
  174. package/cap/templates/verification-report.md +322 -0
  175. package/cap/workflows/add-phase.md +112 -0
  176. package/cap/workflows/add-tests.md +351 -0
  177. package/cap/workflows/add-todo.md +158 -0
  178. package/cap/workflows/audit-milestone.md +340 -0
  179. package/cap/workflows/audit-uat.md +109 -0
  180. package/cap/workflows/autonomous.md +891 -0
  181. package/cap/workflows/check-todos.md +177 -0
  182. package/cap/workflows/cleanup.md +152 -0
  183. package/cap/workflows/complete-milestone.md +767 -0
  184. package/cap/workflows/diagnose-issues.md +231 -0
  185. package/cap/workflows/discovery-phase.md +289 -0
  186. package/cap/workflows/discuss-phase-assumptions.md +653 -0
  187. package/cap/workflows/discuss-phase.md +1049 -0
  188. package/cap/workflows/do.md +104 -0
  189. package/cap/workflows/execute-phase.md +846 -0
  190. package/cap/workflows/execute-plan.md +514 -0
  191. package/cap/workflows/fast.md +105 -0
  192. package/cap/workflows/forensics.md +265 -0
  193. package/cap/workflows/health.md +181 -0
  194. package/cap/workflows/help.md +660 -0
  195. package/cap/workflows/insert-phase.md +130 -0
  196. package/cap/workflows/list-phase-assumptions.md +178 -0
  197. package/cap/workflows/list-workspaces.md +56 -0
  198. package/cap/workflows/manager.md +362 -0
  199. package/cap/workflows/map-codebase.md +377 -0
  200. package/cap/workflows/milestone-summary.md +223 -0
  201. package/cap/workflows/new-milestone.md +486 -0
  202. package/cap/workflows/new-project.md +1250 -0
  203. package/cap/workflows/new-workspace.md +237 -0
  204. package/cap/workflows/next.md +97 -0
  205. package/cap/workflows/node-repair.md +92 -0
  206. package/cap/workflows/note.md +156 -0
  207. package/cap/workflows/pause-work.md +176 -0
  208. package/cap/workflows/plan-milestone-gaps.md +273 -0
  209. package/cap/workflows/plan-phase.md +857 -0
  210. package/cap/workflows/plant-seed.md +169 -0
  211. package/cap/workflows/pr-branch.md +129 -0
  212. package/cap/workflows/profile-user.md +449 -0
  213. package/cap/workflows/progress.md +507 -0
  214. package/cap/workflows/quick.md +757 -0
  215. package/cap/workflows/remove-phase.md +155 -0
  216. package/cap/workflows/remove-workspace.md +90 -0
  217. package/cap/workflows/research-phase.md +82 -0
  218. package/cap/workflows/resume-project.md +326 -0
  219. package/cap/workflows/review.md +228 -0
  220. package/cap/workflows/session-report.md +146 -0
  221. package/cap/workflows/settings.md +283 -0
  222. package/cap/workflows/ship.md +228 -0
  223. package/cap/workflows/stats.md +60 -0
  224. package/cap/workflows/transition.md +671 -0
  225. package/cap/workflows/ui-phase.md +298 -0
  226. package/cap/workflows/ui-review.md +161 -0
  227. package/cap/workflows/update.md +323 -0
  228. package/cap/workflows/validate-phase.md +170 -0
  229. package/cap/workflows/verify-phase.md +254 -0
  230. package/cap/workflows/verify-work.md +637 -0
  231. package/commands/cap/annotate.md +165 -0
  232. package/commands/cap/brainstorm.md +393 -0
  233. package/commands/cap/checkpoint.md +106 -0
  234. package/commands/cap/completeness.md +94 -0
  235. package/commands/cap/continue.md +72 -0
  236. package/commands/cap/debug.md +588 -0
  237. package/commands/cap/deps.md +169 -0
  238. package/commands/cap/design.md +479 -0
  239. package/commands/cap/init.md +354 -0
  240. package/commands/cap/iterate.md +249 -0
  241. package/commands/cap/learn.md +459 -0
  242. package/commands/cap/memory.md +275 -0
  243. package/commands/cap/migrate-feature-map.md +91 -0
  244. package/commands/cap/migrate-memory.md +108 -0
  245. package/commands/cap/migrate-tags.md +91 -0
  246. package/commands/cap/migrate.md +131 -0
  247. package/commands/cap/prototype.md +510 -0
  248. package/commands/cap/reconcile.md +121 -0
  249. package/commands/cap/review.md +360 -0
  250. package/commands/cap/save.md +72 -0
  251. package/commands/cap/scan.md +404 -0
  252. package/commands/cap/start.md +356 -0
  253. package/commands/cap/status.md +118 -0
  254. package/commands/cap/test-audit.md +262 -0
  255. package/commands/cap/test.md +394 -0
  256. package/commands/cap/trace.md +133 -0
  257. package/commands/cap/ui.md +167 -0
  258. package/hooks/dist/cap-check-update.js +115 -0
  259. package/hooks/dist/cap-context-monitor.js +185 -0
  260. package/hooks/dist/cap-learn-review-hook.js +114 -0
  261. package/hooks/dist/cap-learning-hook.js +192 -0
  262. package/hooks/dist/cap-memory.js +299 -0
  263. package/hooks/dist/cap-prompt-guard.js +97 -0
  264. package/hooks/dist/cap-statusline.js +157 -0
  265. package/hooks/dist/cap-tag-observer.js +115 -0
  266. package/hooks/dist/cap-version-check.js +112 -0
  267. package/hooks/dist/cap-workflow-guard.js +175 -0
  268. package/hooks/hooks.json +55 -0
  269. package/package.json +58 -0
  270. package/scripts/base64-scan.sh +262 -0
  271. package/scripts/build-hooks.js +93 -0
  272. package/scripts/cap-removal-checklist.md +202 -0
  273. package/scripts/prompt-injection-scan.sh +199 -0
  274. package/scripts/run-tests.cjs +181 -0
  275. package/scripts/secret-scan.sh +227 -0
@@ -0,0 +1,383 @@
1
+ // @cap-context Manifest generator for monorepo shared packages -- extracts public API surface and produces markdown summaries
2
+ // @cap-decision Scans index/barrel files and TypeScript .d.ts files rather than full AST parsing -- regex is sufficient for export extraction
3
+ // @cap-constraint Zero external dependencies -- uses only Node.js built-ins (fs, path)
4
+ // @cap-ref(ref:AC-5) Shared packages get auto-generated API manifests stored in root .planning/manifests/
5
+ // @cap-pattern Manifest output is markdown so it can be injected directly into agent context as lightweight reference
6
+
7
+ 'use strict';
8
+
9
+ // @cap-feature(feature:F-012) Monorepo Support — API manifest generator for shared packages
10
+
11
+ const fs = require('node:fs');
12
+ const path = require('node:path');
13
+
14
+ // @cap-api generateManifest(packagePath, options) -- returns ManifestData object with exports, types, and description
15
+
16
+ /**
17
+ * @typedef {Object} ExportEntry
18
+ * @property {string} name - Exported symbol name
19
+ * @property {'function'|'class'|'const'|'type'|'interface'|'enum'|'default'|'unknown'} kind - Export kind
20
+ * @property {string|null} description - One-line description if available from JSDoc/comment
21
+ */
22
+
23
+ /**
24
+ * @typedef {Object} ManifestData
25
+ * @property {string} packageName - Package name from package.json
26
+ * @property {string} packagePath - Relative path in monorepo
27
+ * @property {string|null} description - Package description from package.json
28
+ * @property {string|null} version - Package version
29
+ * @property {ExportEntry[]} exports - Public API exports
30
+ * @property {string[]} dependencies - Internal monorepo dependencies (workspace:*)
31
+ * @property {string} generatedAt - ISO timestamp
32
+ */
33
+
34
+ /**
35
+ * Generate a manifest for a single shared package.
36
+ *
37
+ * @param {string} packageAbsPath - Absolute path to the package directory
38
+ * @param {Object} [options]
39
+ * @param {string} [options.rootPath] - Monorepo root for computing relative paths
40
+ * @returns {ManifestData}
41
+ */
42
+ function generateManifest(packageAbsPath, options) {
43
+ options = options || {};
44
+ const rootPath = options.rootPath || path.dirname(path.dirname(packageAbsPath));
45
+
46
+ const pkgJsonPath = path.join(packageAbsPath, 'package.json');
47
+ const pkg = safeReadJson(pkgJsonPath) || {};
48
+
49
+ const manifest = {
50
+ packageName: pkg.name || path.basename(packageAbsPath),
51
+ packagePath: path.relative(rootPath, packageAbsPath),
52
+ description: pkg.description || null,
53
+ version: pkg.version || null,
54
+ exports: [],
55
+ dependencies: [],
56
+ generatedAt: new Date().toISOString(),
57
+ };
58
+
59
+ // @cap-decision Extract workspace:* dependencies to identify internal monorepo links
60
+ manifest.dependencies = extractWorkspaceDeps(pkg);
61
+
62
+ // @cap-context Find and scan the main entry point / barrel file for exports
63
+ const entryFile = resolveEntryFile(packageAbsPath, pkg);
64
+ if (entryFile) {
65
+ manifest.exports = scanExports(entryFile);
66
+ } else {
67
+ // Fallback: scan .d.ts files for TypeScript type exports when no barrel file is found
68
+ const dtsExports = scanDtsFiles(packageAbsPath);
69
+ manifest.exports = dtsExports;
70
+ }
71
+
72
+ return manifest;
73
+ }
74
+
75
+ /**
76
+ * Resolve the main entry/barrel file for a package.
77
+ *
78
+ * @param {string} packageAbsPath
79
+ * @param {Object} pkg - Parsed package.json
80
+ * @returns {string|null} Absolute path to entry file, or null
81
+ */
82
+ function resolveEntryFile(packageAbsPath, pkg) {
83
+ // @cap-decision Check package.json exports/main/module fields, then fall back to index.ts/index.js convention
84
+ const candidates = [];
85
+
86
+ // From package.json fields
87
+ if (pkg.exports && typeof pkg.exports === 'string') {
88
+ candidates.push(pkg.exports);
89
+ } else if (pkg.exports && pkg.exports['.']) {
90
+ const dotExport = pkg.exports['.'];
91
+ if (typeof dotExport === 'string') candidates.push(dotExport);
92
+ else if (dotExport.import) candidates.push(dotExport.import);
93
+ else if (dotExport.require) candidates.push(dotExport.require);
94
+ else if (dotExport.default) candidates.push(dotExport.default);
95
+ }
96
+ if (pkg.main) candidates.push(pkg.main);
97
+ if (pkg.module) candidates.push(pkg.module);
98
+
99
+ // Convention-based fallbacks
100
+ candidates.push('src/index.ts', 'src/index.tsx', 'src/index.js', 'index.ts', 'index.js', 'lib/index.ts', 'lib/index.js');
101
+
102
+ for (const candidate of candidates) {
103
+ const absCandidate = path.join(packageAbsPath, candidate);
104
+ if (fs.existsSync(absCandidate)) {
105
+ return absCandidate;
106
+ }
107
+ }
108
+
109
+ return null;
110
+ }
111
+
112
+ /**
113
+ * Scan a file for export statements and extract public API entries.
114
+ *
115
+ * @param {string} filePath - Absolute path to the file
116
+ * @returns {ExportEntry[]}
117
+ */
118
+ function scanExports(filePath) {
119
+ // @cap-decision Use regex to extract exports rather than AST parsing -- language-agnostic and zero-dep
120
+ // @cap-risk Regex export extraction may miss complex re-export patterns like `export * from './module'` chains
121
+ let content;
122
+ try {
123
+ content = fs.readFileSync(filePath, 'utf-8');
124
+ } catch {
125
+ return [];
126
+ }
127
+
128
+ const exports = [];
129
+
130
+ // Named exports: export function foo, export class Bar, export const baz, export type Qux
131
+ const namedExportRe = /^[ \t]*export\s+(function|class|const|let|var|type|interface|enum|abstract\s+class)\s+(\w+)/gm;
132
+ for (const match of content.matchAll(namedExportRe)) {
133
+ let kind = match[1].trim();
134
+ if (kind === 'let' || kind === 'var') kind = 'const';
135
+ if (kind.startsWith('abstract')) kind = 'class';
136
+
137
+ const name = match[2];
138
+ const description = extractPrecedingComment(content, match.index);
139
+
140
+ exports.push({ name, kind, description });
141
+ }
142
+
143
+ // Default export: export default function/class
144
+ const defaultExportRe = /^[ \t]*export\s+default\s+(function|class)\s+(\w+)?/gm;
145
+ for (const match of content.matchAll(defaultExportRe)) {
146
+ exports.push({
147
+ name: match[2] || 'default',
148
+ kind: 'default',
149
+ description: extractPrecedingComment(content, match.index),
150
+ });
151
+ }
152
+
153
+ // Re-exports: export { Foo, Bar } from './module'
154
+ const reExportRe = /^[ \t]*export\s*\{([^}]+)\}\s*from\s*['"][^'"]+['"]/gm;
155
+ for (const match of content.matchAll(reExportRe)) {
156
+ const names = match[1].split(',').map(n => n.trim().split(/\s+as\s+/).pop().trim()).filter(Boolean);
157
+ for (const name of names) {
158
+ exports.push({ name, kind: 'unknown', description: null });
159
+ }
160
+ }
161
+
162
+ return exports;
163
+ }
164
+
165
+ /**
166
+ * Extract the first line of a comment block immediately preceding a given position.
167
+ *
168
+ * @param {string} content - Full file content
169
+ * @param {number} position - Character position of the export statement
170
+ * @returns {string|null}
171
+ */
172
+ function extractPrecedingComment(content, position) {
173
+ // Look at lines immediately above the export
174
+ const before = content.slice(0, position);
175
+ const lines = before.split('\n');
176
+ const lastLine = lines[lines.length - 1];
177
+
178
+ // Check the line above (lines.length - 2 because last element is partial line)
179
+ if (lines.length < 2) return null;
180
+ const prevLine = lines[lines.length - 2].trim();
181
+
182
+ // Single-line comment
183
+ if (prevLine.startsWith('//')) {
184
+ return prevLine.replace(/^\/\/\s*/, '').trim() || null;
185
+ }
186
+ // Block comment end
187
+ if (prevLine.endsWith('*/')) {
188
+ const commentText = prevLine.replace(/^\*\/?\s*|\s*\*\/$/g, '').replace(/^\*\s*/, '').trim();
189
+ return commentText || null;
190
+ }
191
+ // JSDoc @description or first line
192
+ if (prevLine.startsWith('*')) {
193
+ return prevLine.replace(/^\*\s*/, '').replace(/@\w+\s*/, '').trim() || null;
194
+ }
195
+
196
+ return null;
197
+ }
198
+
199
+ /**
200
+ * Extract workspace:* dependencies from package.json.
201
+ *
202
+ * @param {Object} pkg - Parsed package.json
203
+ * @returns {string[]} List of internal package names
204
+ */
205
+ function extractWorkspaceDeps(pkg) {
206
+ const deps = [];
207
+ const allDeps = { ...(pkg.dependencies || {}), ...(pkg.devDependencies || {}), ...(pkg.peerDependencies || {}) };
208
+
209
+ for (const [name, version] of Object.entries(allDeps)) {
210
+ if (typeof version === 'string' && version.startsWith('workspace:')) {
211
+ deps.push(name);
212
+ }
213
+ }
214
+
215
+ return deps;
216
+ }
217
+
218
+ /**
219
+ * Format a ManifestData object as a markdown document.
220
+ *
221
+ * @param {ManifestData} manifest
222
+ * @returns {string}
223
+ */
224
+ function formatManifestMarkdown(manifest) {
225
+ const lines = [
226
+ `# ${manifest.packageName}`,
227
+ ``,
228
+ `**Path:** ${manifest.packagePath}`,
229
+ `**Version:** ${manifest.version || 'n/a'}`,
230
+ `**Generated:** ${manifest.generatedAt}`,
231
+ ``,
232
+ ];
233
+
234
+ if (manifest.description) {
235
+ lines.push(`> ${manifest.description}`, ``);
236
+ }
237
+
238
+ // Exports table
239
+ if (manifest.exports.length > 0) {
240
+ lines.push(`## Exports`, ``);
241
+ lines.push(`| Name | Kind | Description |`);
242
+ lines.push(`|------|------|-------------|`);
243
+ for (const exp of manifest.exports) {
244
+ lines.push(`| ${exp.name} | ${exp.kind} | ${exp.description || '--'} |`);
245
+ }
246
+ lines.push(``);
247
+ } else {
248
+ lines.push(`## Exports`, ``, `No exports detected.`, ``);
249
+ }
250
+
251
+ // Internal dependencies
252
+ if (manifest.dependencies.length > 0) {
253
+ lines.push(`## Internal Dependencies`, ``);
254
+ for (const dep of manifest.dependencies) {
255
+ lines.push(`- ${dep}`);
256
+ }
257
+ lines.push(``);
258
+ }
259
+
260
+ return lines.join('\n');
261
+ }
262
+
263
+ /**
264
+ * Generate manifests for all packages in a workspace and write them to .planning/manifests/.
265
+ *
266
+ * @param {string} rootPath - Monorepo root
267
+ * @param {Array<{name: string, path: string, absolutePath: string}>} packages - Workspace packages
268
+ * @param {Object} [options]
269
+ * @param {string} [options.outputDir] - Override manifest output directory
270
+ * @returns {string[]} Paths to generated manifest files
271
+ */
272
+ // @cap-api generateAllManifests(rootPath, packages, options) -- writes markdown manifests to .planning/manifests/ and returns file paths
273
+ function generateAllManifests(rootPath, packages, options) {
274
+ options = options || {};
275
+ const outputDir = options.outputDir || path.join(rootPath, '.planning', 'manifests');
276
+
277
+ fs.mkdirSync(outputDir, { recursive: true });
278
+
279
+ const writtenFiles = [];
280
+
281
+ for (const pkg of packages) {
282
+ const manifest = generateManifest(pkg.absolutePath, { rootPath });
283
+ const markdown = formatManifestMarkdown(manifest);
284
+ const safeName = manifest.packageName.replace(/^@/, '').replace(/\//g, '__');
285
+ const outFile = path.join(outputDir, `${safeName}.md`);
286
+
287
+ fs.writeFileSync(outFile, markdown, 'utf-8');
288
+ writtenFiles.push(outFile);
289
+ }
290
+
291
+ return writtenFiles;
292
+ }
293
+
294
+ /**
295
+ * CLI entry point for generate-manifest subcommand.
296
+ *
297
+ * @param {string} cwd - Current working directory
298
+ * @param {string} packagePath - Relative path to the package
299
+ * @param {boolean} raw - Whether to output raw JSON
300
+ */
301
+ function cmdGenerateManifest(cwd, packagePath, raw) {
302
+ if (!packagePath) {
303
+ process.stderr.write('Usage: generate-manifest <package-path>\n');
304
+ process.exitCode = 1;
305
+ return;
306
+ }
307
+
308
+ const absPath = path.resolve(cwd, packagePath);
309
+ const manifest = generateManifest(absPath, { rootPath: cwd });
310
+
311
+ if (raw) {
312
+ process.stdout.write(JSON.stringify(manifest, null, 2) + '\n');
313
+ } else {
314
+ process.stdout.write(formatManifestMarkdown(manifest) + '\n');
315
+ }
316
+ }
317
+
318
+ /**
319
+ * Scan .d.ts files in a package root and src/ for type exports.
320
+ * Limited to first 5 .d.ts files to bound scan time.
321
+ *
322
+ * @param {string} packageAbsPath - Absolute path to package directory
323
+ * @returns {ExportEntry[]}
324
+ */
325
+ function scanDtsFiles(packageAbsPath) {
326
+ const dtsFiles = [];
327
+
328
+ // Collect .d.ts files from package root and src/
329
+ const dirsToScan = [packageAbsPath, path.join(packageAbsPath, 'src')];
330
+ for (const dir of dirsToScan) {
331
+ try {
332
+ const entries = fs.readdirSync(dir);
333
+ for (const entry of entries) {
334
+ if (entry.endsWith('.d.ts') && entry !== 'node_modules') {
335
+ dtsFiles.push(path.join(dir, entry));
336
+ }
337
+ if (dtsFiles.length >= 5) break;
338
+ }
339
+ } catch {
340
+ // Directory does not exist or not readable
341
+ }
342
+ if (dtsFiles.length >= 5) break;
343
+ }
344
+
345
+ // Scan each .d.ts file and merge exports, deduplicate by name
346
+ const allExports = [];
347
+ const seenNames = new Set();
348
+ for (const dtsFile of dtsFiles) {
349
+ const exports = scanExports(dtsFile);
350
+ for (const exp of exports) {
351
+ if (!seenNames.has(exp.name)) {
352
+ seenNames.add(exp.name);
353
+ allExports.push(exp);
354
+ }
355
+ }
356
+ }
357
+
358
+ return allExports;
359
+ }
360
+
361
+ /**
362
+ * Safely read and parse a JSON file.
363
+ * @param {string} filePath
364
+ * @returns {Object|null}
365
+ */
366
+ function safeReadJson(filePath) {
367
+ try {
368
+ return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
369
+ } catch {
370
+ return null;
371
+ }
372
+ }
373
+
374
+ module.exports = {
375
+ generateManifest,
376
+ generateAllManifests,
377
+ formatManifestMarkdown,
378
+ scanExports,
379
+ scanDtsFiles,
380
+ resolveEntryFile,
381
+ extractWorkspaceDeps,
382
+ cmdGenerateManifest,
383
+ };
@@ -0,0 +1,253 @@
1
+ /**
2
+ * Milestone — Milestone and requirements lifecycle operations
3
+ */
4
+ // @cap-feature(feature:F-011) Legacy GSD Modules — milestone and requirements lifecycle operations
5
+
6
+ const fs = require('fs');
7
+ const path = require('path');
8
+ const { escapeRegex, getMilestonePhaseFilter, extractOneLinerFromBody, normalizeMd, planningPaths, output, error } = require('./core.cjs');
9
+ const { extractFrontmatter } = require('./frontmatter.cjs');
10
+ const { writeStateMd, stateReplaceFieldWithFallback } = require('./state.cjs');
11
+
12
+ function cmdRequirementsMarkComplete(cwd, reqIdsRaw, raw) {
13
+ if (!reqIdsRaw || reqIdsRaw.length === 0) {
14
+ error('requirement IDs required. Usage: requirements mark-complete REQ-01,REQ-02 or REQ-01 REQ-02');
15
+ }
16
+
17
+ // Accept comma-separated, space-separated, or bracket-wrapped: [REQ-01, REQ-02]
18
+ const reqIds = reqIdsRaw
19
+ .join(' ')
20
+ .replace(/[\[\]]/g, '')
21
+ .split(/[,\s]+/)
22
+ .map(r => r.trim())
23
+ .filter(Boolean);
24
+
25
+ if (reqIds.length === 0) {
26
+ error('no valid requirement IDs found');
27
+ }
28
+
29
+ const reqPath = planningPaths(cwd).requirements;
30
+ if (!fs.existsSync(reqPath)) {
31
+ output({ updated: false, reason: 'REQUIREMENTS.md not found', ids: reqIds }, raw, 'no requirements file');
32
+ return;
33
+ }
34
+
35
+ let reqContent = fs.readFileSync(reqPath, 'utf-8');
36
+ const updated = [];
37
+ const alreadyComplete = [];
38
+ const notFound = [];
39
+
40
+ for (const reqId of reqIds) {
41
+ let found = false;
42
+ const reqEscaped = escapeRegex(reqId);
43
+
44
+ // Update checkbox: - [ ] **REQ-ID** → - [x] **REQ-ID**
45
+ const checkboxPattern = new RegExp(`(-\\s*\\[)[ ](\\]\\s*\\*\\*${reqEscaped}\\*\\*)`, 'gi');
46
+ if (checkboxPattern.test(reqContent)) {
47
+ reqContent = reqContent.replace(checkboxPattern, '$1x$2');
48
+ found = true;
49
+ }
50
+
51
+ // Update traceability table: | REQ-ID | Phase N | Pending | → | REQ-ID | Phase N | Complete |
52
+ const tablePattern = new RegExp(`(\\|\\s*${reqEscaped}\\s*\\|[^|]+\\|)\\s*Pending\\s*(\\|)`, 'gi');
53
+ if (tablePattern.test(reqContent)) {
54
+ // Re-read since test() advances lastIndex for global regex
55
+ reqContent = reqContent.replace(
56
+ new RegExp(`(\\|\\s*${reqEscaped}\\s*\\|[^|]+\\|)\\s*Pending\\s*(\\|)`, 'gi'),
57
+ '$1 Complete $2'
58
+ );
59
+ found = true;
60
+ }
61
+
62
+ if (found) {
63
+ updated.push(reqId);
64
+ } else {
65
+ // Check if already complete before declaring not_found
66
+ const doneCheckbox = new RegExp(`-\\s*\\[x\\]\\s*\\*\\*${reqEscaped}\\*\\*`, 'gi');
67
+ const doneTable = new RegExp(`\\|\\s*${reqEscaped}\\s*\\|[^|]+\\|\\s*Complete\\s*\\|`, 'gi');
68
+ if (doneCheckbox.test(reqContent) || doneTable.test(reqContent)) {
69
+ alreadyComplete.push(reqId);
70
+ } else {
71
+ notFound.push(reqId);
72
+ }
73
+ }
74
+ }
75
+
76
+ if (updated.length > 0) {
77
+ fs.writeFileSync(reqPath, reqContent, 'utf-8');
78
+ }
79
+
80
+ output({
81
+ updated: updated.length > 0,
82
+ marked_complete: updated,
83
+ already_complete: alreadyComplete,
84
+ not_found: notFound,
85
+ total: reqIds.length,
86
+ }, raw, `${updated.length}/${reqIds.length} requirements marked complete`);
87
+ }
88
+
89
+ function cmdMilestoneComplete(cwd, version, options, raw) {
90
+ if (!version) {
91
+ error('version required for milestone complete (e.g., v1.0)');
92
+ }
93
+
94
+ const roadmapPath = planningPaths(cwd).roadmap;
95
+ const reqPath = planningPaths(cwd).requirements;
96
+ const statePath = planningPaths(cwd).state;
97
+ const milestonesPath = path.join(cwd, '.planning', 'MILESTONES.md');
98
+ const archiveDir = path.join(cwd, '.planning', 'milestones');
99
+ const phasesDir = planningPaths(cwd).phases;
100
+ const today = new Date().toISOString().split('T')[0];
101
+ const milestoneName = options.name || version;
102
+
103
+ // Ensure archive directory exists
104
+ fs.mkdirSync(archiveDir, { recursive: true });
105
+
106
+ // Scope stats and accomplishments to only the phases belonging to the
107
+ // current milestone's ROADMAP. Uses the shared filter from core.cjs
108
+ // (same logic used by cmdPhasesList and other callers).
109
+ const isDirInMilestone = getMilestonePhaseFilter(cwd);
110
+
111
+ // Gather stats from phases (scoped to current milestone only)
112
+ let phaseCount = 0;
113
+ let totalPlans = 0;
114
+ let totalTasks = 0;
115
+ const accomplishments = [];
116
+
117
+ try {
118
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
119
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort();
120
+
121
+ for (const dir of dirs) {
122
+ if (!isDirInMilestone(dir)) continue;
123
+
124
+ phaseCount++;
125
+ const phaseFiles = fs.readdirSync(path.join(phasesDir, dir));
126
+ const plans = phaseFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md');
127
+ const summaries = phaseFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
128
+ totalPlans += plans.length;
129
+
130
+ // Extract one-liners from summaries
131
+ for (const s of summaries) {
132
+ try {
133
+ const content = fs.readFileSync(path.join(phasesDir, dir, s), 'utf-8');
134
+ const fm = extractFrontmatter(content);
135
+ const oneLiner = fm['one-liner'] || extractOneLinerFromBody(content);
136
+ if (oneLiner) {
137
+ accomplishments.push(oneLiner);
138
+ }
139
+ // Count tasks: prefer **Tasks:** N from Performance section,
140
+ // then <task XML tags, then ## Task N markdown headers
141
+ const tasksFieldMatch = content.match(/\*\*Tasks:\*\*\s*(\d+)/);
142
+ if (tasksFieldMatch) {
143
+ totalTasks += parseInt(tasksFieldMatch[1], 10);
144
+ } else {
145
+ const xmlTaskMatches = content.match(/<task[\s>]/gi) || [];
146
+ const mdTaskMatches = content.match(/##\s*Task\s*\d+/gi) || [];
147
+ totalTasks += xmlTaskMatches.length || mdTaskMatches.length;
148
+ }
149
+ } catch { /* intentionally empty */ }
150
+ }
151
+ }
152
+ } catch { /* intentionally empty */ }
153
+
154
+ // Archive ROADMAP.md
155
+ if (fs.existsSync(roadmapPath)) {
156
+ const roadmapContent = fs.readFileSync(roadmapPath, 'utf-8');
157
+ fs.writeFileSync(path.join(archiveDir, `${version}-ROADMAP.md`), roadmapContent, 'utf-8');
158
+ }
159
+
160
+ // Archive REQUIREMENTS.md
161
+ if (fs.existsSync(reqPath)) {
162
+ const reqContent = fs.readFileSync(reqPath, 'utf-8');
163
+ const archiveHeader = `# Requirements Archive: ${version} ${milestoneName}\n\n**Archived:** ${today}\n**Status:** SHIPPED\n\nFor current requirements, see \`.planning/REQUIREMENTS.md\`.\n\n---\n\n`;
164
+ fs.writeFileSync(path.join(archiveDir, `${version}-REQUIREMENTS.md`), archiveHeader + reqContent, 'utf-8');
165
+ }
166
+
167
+ // Archive audit file if exists
168
+ const auditFile = path.join(cwd, '.planning', `${version}-MILESTONE-AUDIT.md`);
169
+ if (fs.existsSync(auditFile)) {
170
+ fs.renameSync(auditFile, path.join(archiveDir, `${version}-MILESTONE-AUDIT.md`));
171
+ }
172
+
173
+ // Create/append MILESTONES.md entry
174
+ const accomplishmentsList = accomplishments.map(a => `- ${a}`).join('\n');
175
+ const milestoneEntry = `## ${version} ${milestoneName} (Shipped: ${today})\n\n**Phases completed:** ${phaseCount} phases, ${totalPlans} plans, ${totalTasks} tasks\n\n**Key accomplishments:**\n${accomplishmentsList || '- (none recorded)'}\n\n---\n\n`;
176
+
177
+ if (fs.existsSync(milestonesPath)) {
178
+ const existing = fs.readFileSync(milestonesPath, 'utf-8');
179
+ if (!existing.trim()) {
180
+ // Empty file — treat like new
181
+ fs.writeFileSync(milestonesPath, normalizeMd(`# Milestones\n\n${milestoneEntry}`), 'utf-8');
182
+ } else {
183
+ // Insert after the header line(s) for reverse chronological order (newest first)
184
+ const headerMatch = existing.match(/^(#{1,3}\s+[^\n]*\n\n?)/);
185
+ if (headerMatch) {
186
+ const header = headerMatch[1];
187
+ const rest = existing.slice(header.length);
188
+ fs.writeFileSync(milestonesPath, normalizeMd(header + milestoneEntry + rest), 'utf-8');
189
+ } else {
190
+ // No recognizable header — prepend the entry
191
+ fs.writeFileSync(milestonesPath, normalizeMd(milestoneEntry + existing), 'utf-8');
192
+ }
193
+ }
194
+ } else {
195
+ fs.writeFileSync(milestonesPath, normalizeMd(`# Milestones\n\n${milestoneEntry}`), 'utf-8');
196
+ }
197
+
198
+ // Update STATE.md — use shared helpers that handle both **bold:** and plain Field: formats
199
+ if (fs.existsSync(statePath)) {
200
+ let stateContent = fs.readFileSync(statePath, 'utf-8');
201
+
202
+ stateContent = stateReplaceFieldWithFallback(stateContent, 'Status', null, `${version} milestone complete`);
203
+ stateContent = stateReplaceFieldWithFallback(stateContent, 'Last Activity', 'Last activity', today);
204
+ stateContent = stateReplaceFieldWithFallback(stateContent, 'Last Activity Description', null,
205
+ `${version} milestone completed and archived`);
206
+
207
+ writeStateMd(statePath, stateContent, cwd);
208
+ }
209
+
210
+ // Archive phase directories if requested
211
+ let phasesArchived = false;
212
+ if (options.archivePhases) {
213
+ try {
214
+ const phaseArchiveDir = path.join(archiveDir, `${version}-phases`);
215
+ fs.mkdirSync(phaseArchiveDir, { recursive: true });
216
+
217
+ const phaseEntries = fs.readdirSync(phasesDir, { withFileTypes: true });
218
+ const phaseDirNames = phaseEntries.filter(e => e.isDirectory()).map(e => e.name);
219
+ let archivedCount = 0;
220
+ for (const dir of phaseDirNames) {
221
+ if (!isDirInMilestone(dir)) continue;
222
+ fs.renameSync(path.join(phasesDir, dir), path.join(phaseArchiveDir, dir));
223
+ archivedCount++;
224
+ }
225
+ phasesArchived = archivedCount > 0;
226
+ } catch { /* intentionally empty */ }
227
+ }
228
+
229
+ const result = {
230
+ version,
231
+ name: milestoneName,
232
+ date: today,
233
+ phases: phaseCount,
234
+ plans: totalPlans,
235
+ tasks: totalTasks,
236
+ accomplishments,
237
+ archived: {
238
+ roadmap: fs.existsSync(path.join(archiveDir, `${version}-ROADMAP.md`)),
239
+ requirements: fs.existsSync(path.join(archiveDir, `${version}-REQUIREMENTS.md`)),
240
+ audit: fs.existsSync(path.join(archiveDir, `${version}-MILESTONE-AUDIT.md`)),
241
+ phases: phasesArchived,
242
+ },
243
+ milestones_updated: true,
244
+ state_updated: fs.existsSync(statePath),
245
+ };
246
+
247
+ output(result, raw);
248
+ }
249
+
250
+ module.exports = {
251
+ cmdRequirementsMarkComplete,
252
+ cmdMilestoneComplete,
253
+ };