framework-aidf 0.0.0-stage → 0.2.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 (154) hide show
  1. package/CHANGELOG.md +174 -0
  2. package/INSTALLATION.md +140 -0
  3. package/LICENSE +21 -0
  4. package/QODER.md +88 -0
  5. package/README.md +142 -2
  6. package/UTILISATION.md +188 -0
  7. package/assets/adapters/qoder/agents/aidf-orchestrator.md +30 -0
  8. package/assets/adapters/qoder/rules/00-core.md +28 -0
  9. package/assets/adapters/qoder/rules/10-security.md +33 -0
  10. package/assets/adapters/qoder/rules/20-context.md +39 -0
  11. package/assets/core/AGENTS.fragment.md +18 -0
  12. package/assets/core/AIDF.md +107 -0
  13. package/assets/docs/APPFLOW.md +66 -0
  14. package/assets/docs/BACKEND.md +71 -0
  15. package/assets/docs/CHANGELOG.md +25 -0
  16. package/assets/docs/CONVENTIONS.md +95 -0
  17. package/assets/docs/DECISIONS.md +60 -0
  18. package/assets/docs/PLAN.md +53 -0
  19. package/assets/docs/PRD.md +88 -0
  20. package/assets/docs/SECURITY.md +94 -0
  21. package/assets/docs/TRD.md +78 -0
  22. package/assets/docs/UI-UX.md +71 -0
  23. package/assets/docs/constitution.md +86 -0
  24. package/assets/hooks/audit.mjs +45 -0
  25. package/assets/hooks/session-context.mjs +53 -0
  26. package/assets/integrations/spec-kit/mapping.yaml +92 -0
  27. package/assets/knowledge/best-practices/testing.md +53 -0
  28. package/assets/knowledge/best-practices/web-dev-baseline.md +39 -0
  29. package/assets/knowledge/rules/api.md +45 -0
  30. package/assets/knowledge/rules/sql.md +44 -0
  31. package/assets/knowledge/rules/typescript.md +50 -0
  32. package/assets/knowledge/security-references/owasp-baseline.md +58 -0
  33. package/assets/registry/activation-map.yaml +83 -0
  34. package/assets/registry/dependencies.yaml +35 -0
  35. package/assets/registry/skills.yaml +541 -0
  36. package/assets/registry/sources.yaml +396 -0
  37. package/assets/schemas/architecture/v1.json +110 -0
  38. package/assets/schemas/constraints/v1.json +93 -0
  39. package/assets/schemas/decision/v1.json +106 -0
  40. package/assets/schemas/discovery/v1.json +91 -0
  41. package/assets/schemas/requirement/v1.json +136 -0
  42. package/assets/schemas/security/threat-model/v1.json +127 -0
  43. package/assets/schemas/test-plan/v1.json +108 -0
  44. package/assets/skills/aidf-architecture-review/SKILL.md +49 -0
  45. package/assets/skills/aidf-backend-implementation/SKILL.md +47 -0
  46. package/assets/skills/aidf-database-design/SKILL.md +48 -0
  47. package/assets/skills/aidf-devops-engineering/SKILL.md +41 -0
  48. package/assets/skills/aidf-documentation-maintenance/SKILL.md +41 -0
  49. package/assets/skills/aidf-frontend-implementation/SKILL.md +44 -0
  50. package/assets/skills/aidf-phase-transition/SKILL.md +48 -0
  51. package/assets/skills/aidf-product-analysis/SKILL.md +47 -0
  52. package/assets/skills/aidf-project-context/SKILL.md +57 -0
  53. package/assets/skills/aidf-requirements-engineering/SKILL.md +52 -0
  54. package/assets/skills/aidf-security-review/SKILL.md +57 -0
  55. package/assets/skills/aidf-testing-validation/SKILL.md +48 -0
  56. package/assets/skills/aidf-ui-ux-implementation/SKILL.md +43 -0
  57. package/assets/workflows/gates.yaml +232 -0
  58. package/assets/workflows/phases.yaml +161 -0
  59. package/bin/aidf.mjs +12 -0
  60. package/demo/run-demo.mjs +97 -0
  61. package/docs/aidf/ADR-001-artefacts-architectur.md +126 -0
  62. package/docs/aidf/ADR-002-requirements-registry.md +145 -0
  63. package/docs/aidf/ADR-003-traceability-chain.md +145 -0
  64. package/docs/aidf/ADR-004-markdown-generation.md +134 -0
  65. package/docs/aidf/ADR-005-validation-and-tests.md +170 -0
  66. package/docs/aidf/ADR-006-cli-commands.md +189 -0
  67. package/docs/aidf/ADR-007-compatibility-and-migration.md +119 -0
  68. package/docs/aidf/ADR-008-schema-versioning.md +115 -0
  69. package/docs/aidf/ADR-009-artefacts-scope.md +84 -0
  70. package/docs/aidf/ARCHITECTURE.md +137 -0
  71. package/docs/aidf/COMPATIBILITY.md +90 -0
  72. package/docs/aidf/DECISIONS.md +200 -0
  73. package/docs/aidf/FRAMEWORK.md +38 -0
  74. package/docs/aidf/IDE-QODER.md +61 -0
  75. package/docs/aidf/INSTALL.md +99 -0
  76. package/docs/aidf/INVENTORY.md +72 -0
  77. package/docs/aidf/L1-ARCHITECTURE-RAPPORT.md +353 -0
  78. package/docs/aidf/LIMITATIONS.md +69 -0
  79. package/docs/aidf/MATRICE-0.1.0-vers-0.2.0.md +155 -0
  80. package/docs/aidf/SECURITY.md +86 -0
  81. package/docs/aidf/SKILLS.md +78 -0
  82. package/docs/aidf/SPECKIT.md +67 -0
  83. package/docs/aidf/USAGE.md +113 -0
  84. package/docs/aidf/VALIDATION.md +55 -0
  85. package/package.json +37 -4
  86. package/src/cli.mjs +148 -0
  87. package/src/commands/artefacts.mjs +129 -0
  88. package/src/commands/config.mjs +130 -0
  89. package/src/commands/context.mjs +55 -0
  90. package/src/commands/decision.mjs +142 -0
  91. package/src/commands/design.mjs +141 -0
  92. package/src/commands/docs.mjs +133 -0
  93. package/src/commands/doctor.mjs +210 -0
  94. package/src/commands/evidence.mjs +178 -0
  95. package/src/commands/install.mjs +154 -0
  96. package/src/commands/release.mjs +214 -0
  97. package/src/commands/requirements.mjs +196 -0
  98. package/src/commands/resources.mjs +181 -0
  99. package/src/commands/scan.mjs +139 -0
  100. package/src/commands/security.mjs +97 -0
  101. package/src/commands/setup.mjs +68 -0
  102. package/src/commands/skills.mjs +204 -0
  103. package/src/commands/speckit.mjs +78 -0
  104. package/src/commands/tests.mjs +81 -0
  105. package/src/commands/traceability.mjs +116 -0
  106. package/src/commands/uninstall.mjs +238 -0
  107. package/src/commands/validate.mjs +84 -0
  108. package/src/commands/workflow.mjs +137 -0
  109. package/src/core/adapters/base.mjs +32 -0
  110. package/src/core/adapters/generic.mjs +70 -0
  111. package/src/core/adapters/index.mjs +24 -0
  112. package/src/core/adapters/opencode.mjs +115 -0
  113. package/src/core/adapters/qoder.mjs +228 -0
  114. package/src/core/artefacts/index.mjs +1 -0
  115. package/src/core/artefacts/validation.mjs +161 -0
  116. package/src/core/bootstrap.mjs +179 -0
  117. package/src/core/config.mjs +123 -0
  118. package/src/core/context.mjs +187 -0
  119. package/src/core/design-engineering/complexity-classifier.mjs +78 -0
  120. package/src/core/design-engineering/engine.mjs +197 -0
  121. package/src/core/design-engineering/fallback/mockups.mjs +221 -0
  122. package/src/core/design-engineering/fallback/wireframes.mjs +114 -0
  123. package/src/core/design-engineering/figma/validators.mjs +178 -0
  124. package/src/core/design-engineering/index.mjs +9 -0
  125. package/src/core/design-engineering/visual-parity/capture.mjs +172 -0
  126. package/src/core/detect.mjs +220 -0
  127. package/src/core/docsgen.mjs +175 -0
  128. package/src/core/evidence.mjs +210 -0
  129. package/src/core/installer.mjs +377 -0
  130. package/src/core/manifest.mjs +53 -0
  131. package/src/core/paths.mjs +94 -0
  132. package/src/core/requirements/index.mjs +13 -0
  133. package/src/core/requirements/registry.mjs +234 -0
  134. package/src/core/resource-inventory.mjs +434 -0
  135. package/src/core/resources.mjs +280 -0
  136. package/src/core/security/threat-model.mjs +235 -0
  137. package/src/core/skills.mjs +353 -0
  138. package/src/core/source-skills.mjs +213 -0
  139. package/src/core/speckit.mjs +195 -0
  140. package/src/core/technology-decision/analyzer-deterministic.mjs +240 -0
  141. package/src/core/technology-decision/engine.mjs +157 -0
  142. package/src/core/technology-decision/generator.mjs +204 -0
  143. package/src/core/technology-decision/index.mjs +17 -0
  144. package/src/core/technology-decision/options/index.mjs +10 -0
  145. package/src/core/testplan.mjs +176 -0
  146. package/src/core/traceability/chain.mjs +488 -0
  147. package/src/core/traceability/index.mjs +12 -0
  148. package/src/core/workflow.mjs +471 -0
  149. package/src/util/args.mjs +69 -0
  150. package/src/util/frontmatter.mjs +26 -0
  151. package/src/util/fsx.mjs +208 -0
  152. package/src/util/logger.mjs +74 -0
  153. package/src/util/text.mjs +66 -0
  154. package/src/util/yaml.mjs +379 -0
@@ -0,0 +1,157 @@
1
+ import { validateHardConstraints, calculateSoftConstraints, detectIncompatibilities, rankOptions } from './analyzer-deterministic.mjs';
2
+ import { generateDecisionDocument, exportToJSON, exportToMarkdown } from './generator.mjs';
3
+
4
+ /**
5
+ * Evaluate technology decision based on project context.
6
+ * Returns a complete decision document.
7
+ */
8
+ export async function evaluateTechnologyDecision(projectContext, options = {}) {
9
+ const context = {
10
+ projectType: projectContext.projectType,
11
+ businessGoals: projectContext.businessGoals || [],
12
+ functionalConstraints: projectContext.functionalConstraints || [],
13
+ nonFunctionalConstraints: projectContext.nonFunctionalConstraints || [],
14
+ skills: projectContext.skills || [],
15
+ budget: projectContext.budget,
16
+ timeline: projectContext.timeline,
17
+ platform: projectContext.platform || [],
18
+ license: projectContext.license || [],
19
+ features: projectContext.features || [],
20
+ compliance: projectContext.compliance || [],
21
+ scalability: projectContext.scalability
22
+ };
23
+
24
+ // Step 1: Validate hard constraints
25
+ const { validOptions, eliminated } = await validateHardConstraints(
26
+ options.technologyOptions || [],
27
+ context
28
+ );
29
+
30
+ // Step 2: Calculate soft constraints
31
+ const scores = calculateSoftConstraints(validOptions, context);
32
+
33
+ // Step 3: Detect incompatibilities
34
+ const incompatibilities = detectIncompatibilities(validOptions);
35
+
36
+ // Step 4: Rank options
37
+ const ranked = rankOptions(validOptions, scores, incompatibilities);
38
+
39
+ // Step 5: AIDF provides deterministic facts only. Interpretation of
40
+ // trade-offs, risks and uncertainties is delegated to the AI agent that
41
+ // invokes the command; no AIDF-owned model exists or is required.
42
+ const agentAnalysis = buildAgentDelegation(ranked);
43
+
44
+ // Step 6: Generate recommendation
45
+ const recommendation = generateRecommendation(ranked, agentAnalysis);
46
+
47
+ // Step 7: Generate document
48
+ const document = generateDecisionDocument(context, {
49
+ deterministic: {
50
+ summary: {
51
+ totalOptions: options.technologyOptions?.length || 0,
52
+ validOptions: validOptions.length,
53
+ shortlistedOptions: ranked.shortlisted?.length || 0,
54
+ eliminatedOptions: eliminated.length
55
+ },
56
+ eliminated,
57
+ scores,
58
+ incompatibilities
59
+ },
60
+ llm: null,
61
+ delegation: agentAnalysis.delegation
62
+ }, recommendation);
63
+
64
+ return document;
65
+ }
66
+
67
+ /**
68
+ * Build the delegation record for interpretive analysis.
69
+ * AIDF is a governance framework, not an application: it owns no model.
70
+ * The invoking AI agent performs trade-off, risk and architecture
71
+ * interpretation on top of the deterministic facts emitted here.
72
+ */
73
+ function buildAgentDelegation(ranked) {
74
+ const shortlisted = ranked.shortlisted ?? [];
75
+ const uncertainties = shortlisted.slice(0, 3).map((s) => ({
76
+ component: s.option,
77
+ unknowns: [
78
+ 'trade-off interpretation',
79
+ 'risk assessment',
80
+ 'architecture fit',
81
+ 'option data completeness',
82
+ ],
83
+ }));
84
+ return {
85
+ tradeoffs: [],
86
+ risks: [],
87
+ uncertainties,
88
+ architecture: [],
89
+ delegation: {
90
+ delegatedTo: 'invoking-agent',
91
+ note: 'AIDF provides deterministic facts only (constraints, scores, eliminations). Trade-off, risk and uncertainty interpretation is performed by the AI agent invoking the command; AIDF configures no model and requires no credentials.',
92
+ },
93
+ };
94
+ }
95
+
96
+ /**
97
+ * Generate recommendation from analysis results.
98
+ */
99
+ function generateRecommendation(ranked, llmAnalysis) {
100
+ if (!ranked.shortlisted || ranked.shortlisted.length === 0) {
101
+ return {
102
+ stack: [],
103
+ confidence: 'low',
104
+ risks: ['No viable options found'],
105
+ uncertainties: [],
106
+ suggestedTests: []
107
+ };
108
+ }
109
+
110
+ // Get top option as recommendation
111
+ const topOption = ranked.shortlisted[0];
112
+
113
+ // Build stack
114
+ const stack = [
115
+ {
116
+ component: 'primary',
117
+ option: topOption.option,
118
+ version: '1.0.0', // Would be filled from option definition
119
+ reason: `Highest score: ${topOption.totalScore.toFixed(2)}`
120
+ }
121
+ ];
122
+
123
+ // Add risks from LLM analysis
124
+ const risks = llmAnalysis.risks || [];
125
+
126
+ // Add uncertainties from LLM analysis
127
+ const uncertainties = llmAnalysis.uncertainties || [];
128
+
129
+ // Determine confidence based on scores and uncertainties
130
+ let confidence = 'medium';
131
+ if (topOption.totalScore >= 0.8 && uncertainties.length === 0) {
132
+ confidence = 'high';
133
+ } else if (topOption.totalScore < 0.6) {
134
+ confidence = 'low';
135
+ }
136
+
137
+ return {
138
+ stack,
139
+ confidence,
140
+ risks: risks.map(r => ({
141
+ risk: r.vulnerabilities?.join(', ') || r.description || 'Unknown risk',
142
+ impact: 'medium',
143
+ mitigation: r.mitigation?.join(', ')
144
+ })),
145
+ uncertainties: uncertainties.map(u => ({
146
+ component: u.component,
147
+ uncertainty: u.unknowns?.join(', ') || 'Unknown'
148
+ })),
149
+ suggestedTests: [
150
+ `Performance benchmark for ${topOption.option}`,
151
+ `Security audit for ${topOption.option}`,
152
+ `Team skill assessment for ${topOption.option}`
153
+ ]
154
+ };
155
+ }
156
+
157
+
@@ -0,0 +1,204 @@
1
+ /**
2
+ * Decision document generator for technology decisions.
3
+ */
4
+
5
+ import { generateRequirementId } from '../requirements/registry.mjs';
6
+
7
+ /**
8
+ * Generate a complete decision document.
9
+ */
10
+ export function generateDecisionDocument(context, analysis, recommendation) {
11
+ const document = {
12
+ meta: {
13
+ version: '1.0.0',
14
+ id: `TECH-DECISION-${new Date().getFullYear()}-${String(Math.floor(Math.random() * 1000)).padStart(3, '0')}`,
15
+ timestamp: new Date().toISOString(),
16
+ author: 'Kiro',
17
+ status: 'draft'
18
+ },
19
+ context,
20
+ analysis: {
21
+ deterministic: analysis.deterministic,
22
+ llm: analysis.llm ?? null,
23
+ delegation: analysis.delegation ?? null
24
+ },
25
+ options: {
26
+ shortlisted: [],
27
+ eliminated: analysis.deterministic?.eliminated || [],
28
+ incompatible: analysis.deterministic?.incompatible || []
29
+ },
30
+ comparison: {
31
+ matrix: generateComparisonMatrix(analysis),
32
+ tradeoffs: generateTradeoffs(analysis)
33
+ },
34
+ recommendation: {
35
+ stack: recommendation.stack || [],
36
+ confidence: recommendation.confidence || 'medium',
37
+ risks: recommendation.risks || [],
38
+ uncertainties: recommendation.uncertainties || [],
39
+ suggestedTests: recommendation.suggestedTests || []
40
+ },
41
+ humanApproval: {
42
+ required: true,
43
+ approved: false,
44
+ approver: null,
45
+ comments: null,
46
+ timestamp: null
47
+ }
48
+ };
49
+
50
+ // Add shortlisted options from analysis
51
+ if (analysis.deterministic?.scores) {
52
+ document.options.shortlisted = analysis.deterministic.scores.map(s => ({
53
+ id: s.option,
54
+ reason: `Score: ${s.totalScore.toFixed(2)}`
55
+ }));
56
+ }
57
+
58
+ return document;
59
+ }
60
+
61
+ /**
62
+ * Generate comparison matrix.
63
+ */
64
+ function generateComparisonMatrix(analysis) {
65
+ const matrix = [];
66
+
67
+ if (!analysis.deterministic?.scores) return matrix;
68
+
69
+ const scores = analysis.deterministic.scores;
70
+ if (scores.length < 2) return matrix;
71
+
72
+ const criteria = ['cost', 'performance', 'ecosystem', 'maintenance', 'scalability'];
73
+
74
+ for (const criterion of criteria) {
75
+ const option1 = scores[0];
76
+ const option2 = scores[1];
77
+
78
+ let value1 = '-', value2 = '-';
79
+ let winner = '-';
80
+
81
+ // Simple comparison logic
82
+ if (criterion === 'cost' && option1.scores?.totalScore && option2.scores?.totalScore) {
83
+ value1 = option1.totalScore.toFixed(2);
84
+ value2 = option2.totalScore.toFixed(2);
85
+ winner = option1.totalScore > option2.totalScore ? option1.option : option2.option;
86
+ }
87
+
88
+ matrix.push({
89
+ criteria: criterion,
90
+ [option1.option]: value1,
91
+ [option2.option]: value2,
92
+ winner
93
+ });
94
+ }
95
+
96
+ return matrix;
97
+ }
98
+
99
+ /**
100
+ * Generate trade-offs summary.
101
+ */
102
+ function generateTradeoffs(analysis) {
103
+ const tradeoffs = [];
104
+
105
+ if (analysis.llm?.tradeoffs) {
106
+ for (const tradeoff of analysis.llm.tradeoffs) {
107
+ tradeoffs.push(tradeoff.tradeOff);
108
+ }
109
+ }
110
+
111
+ return tradeoffs;
112
+ }
113
+
114
+ /**
115
+ * Export document as JSON string.
116
+ */
117
+ export function exportToJSON(document) {
118
+ return JSON.stringify(document, null, 2);
119
+ }
120
+
121
+ /**
122
+ * Export document as Markdown (ADR format).
123
+ */
124
+ export function exportToMarkdown(document) {
125
+ let md = `# ${document.meta.id}: ${document.context.projectType || 'Technology Decision'}\n\n`;
126
+ md += `**Date**: ${new Date().toISOString().split('T')[0]}\n`;
127
+ md += `**Status**: ${document.meta.status}\n\n`;
128
+
129
+ md += '## Context\n\n';
130
+ for (const [key, value] of Object.entries(document.context)) {
131
+ if (typeof value === 'object' && value !== null) {
132
+ md += `**${key}**: ${JSON.stringify(value)}\n\n`;
133
+ } else {
134
+ md += `**${key}**: ${value}\n\n`;
135
+ }
136
+ }
137
+
138
+ md += '## Analysis\n\n';
139
+ md += '### Deterministic Analysis\n\n';
140
+ md += `- Total options: ${document.analysis.deterministic?.summary?.totalOptions || 0}\n`;
141
+ md += `- Valid options: ${document.analysis.deterministic?.summary?.validOptions || 0}\n`;
142
+ md += `- Eliminated: ${document.options.eliminated?.length || 0}\n`;
143
+ md += `- Shortlisted: ${document.options.shortlisted?.length || 0}\n`;
144
+
145
+ if (document.analysis.llm?.tradeoffs) {
146
+ md += '\n### LLM Trade-offs\n\n';
147
+ for (const tradeoff of document.analysis.llm.tradeoffs) {
148
+ md += `- **${tradeoff.option1} vs ${tradeoff.option2}**: ${tradeoff.tradeOff}\n`;
149
+ }
150
+ }
151
+
152
+ md += '\n## Options\n\n';
153
+ md += '### Shortlisted\n\n';
154
+ for (const option of document.options.shortlisted) {
155
+ md += `- ${option.id}: ${option.reason}\n`;
156
+ }
157
+
158
+ if (document.options.eliminated.length > 0) {
159
+ md += '\n### Eliminated\n\n';
160
+ for (const option of document.options.eliminated) {
161
+ md += `- **${option.option}**:\n`;
162
+ for (const violation of option.violations) {
163
+ md += ` - ${violation.reason}\n`;
164
+ }
165
+ }
166
+ }
167
+
168
+ md += '\n## Recommendation\n\n';
169
+ md += '### Proposed Stack\n\n';
170
+ for (const component of document.recommendation.stack) {
171
+ md += `- **${component.component}**: ${component.option} v${component.version}\n`;
172
+ if (component.reason) {
173
+ md += ` - ${component.reason}\n`;
174
+ }
175
+ }
176
+
177
+ md += `\n**Confidence**: ${document.recommendation.confidence}\n\n`;
178
+
179
+ if (document.recommendation.risks.length > 0) {
180
+ md += '### Risks\n\n';
181
+ for (const risk of document.recommendation.risks) {
182
+ md += `- **${risk.risk || risk.component}**: ${risk.impact || 'unknown'} impact\n`;
183
+ if (risk.mitigation) {
184
+ md += ` - Mitigation: ${risk.mitigation}\n`;
185
+ }
186
+ }
187
+ }
188
+
189
+ if (document.recommendation.uncertainties.length > 0) {
190
+ md += '\n### Uncertainties\n\n';
191
+ for (const uncertainty of document.recommendation.uncertainties) {
192
+ md += `- **${uncertainty.component}**: ${uncertainty.uncertainty}\n`;
193
+ }
194
+ }
195
+
196
+ md += '\n## Human Approval\n\n';
197
+ md += `- Required: ${document.humanApproval.required}\n`;
198
+ md += `- Approved: ${document.humanApproval.approved}\n`;
199
+ if (document.humanApproval.comments) {
200
+ md += `- Comments: ${document.humanApproval.comments}\n`;
201
+ }
202
+
203
+ return md;
204
+ }
@@ -0,0 +1,17 @@
1
+ // L2: Technology Decision Engine
2
+ // Main entry point for the technology decision engine
3
+
4
+ export { evaluateTechnologyDecision } from './engine.mjs';
5
+ export {
6
+ validateHardConstraints,
7
+ calculateSoftConstraints,
8
+ detectIncompatibilities,
9
+ rankOptions
10
+ } from './analyzer-deterministic.mjs';
11
+ // Interpretation of trade-offs, risks and uncertainties is delegated to the
12
+ // invoking AI agent by design; AIDF owns no model (see engine delegation).
13
+ export {
14
+ generateDecisionDocument,
15
+ exportToJSON,
16
+ exportToMarkdown
17
+ } from './generator.mjs';
@@ -0,0 +1,10 @@
1
+ // Technology options definitions
2
+ // This is a placeholder - in production, you would define actual technology options
3
+
4
+ export const FRAMEWORKS = {};
5
+
6
+ export const databases = {};
7
+ export const servers = {};
8
+ export const cloud = {};
9
+ export const languages = {};
10
+ export const tools = {};
@@ -0,0 +1,176 @@
1
+ import path from 'node:path';
2
+ import { aidfPaths } from './paths.mjs';
3
+ import { writeJson, readJson, ensureDir } from '../util/fsx.mjs';
4
+ import { detectProject } from './detect.mjs';
5
+ import { loadConfig, defaultConfig } from './config.mjs';
6
+ import { loadRequirementsRegistry } from './requirements/registry.mjs';
7
+ import { collectArtefactFiles } from './traceability/chain.mjs';
8
+
9
+ function nextTestPlanId(existingIds) {
10
+ let max = 0;
11
+ for (const id of existingIds) {
12
+ const m = /^TP-(\d+)$/.exec(id);
13
+ if (m) max = Math.max(max, parseInt(m[1], 10));
14
+ }
15
+ return `TP-${String(max + 1).padStart(3, '0')}`;
16
+ }
17
+
18
+ function guessTestType(text) {
19
+ const t = String(text ?? '').toLowerCase();
20
+ if (/e2e|end[- ]to[- ]end|browser/.test(t)) return 'e2e';
21
+ if (/api|endpoint|http|rest/.test(t)) return 'api';
22
+ if (/security|auth|permission|secret/.test(t)) return 'security';
23
+ if (/accessib|a11y|wcag/.test(t)) return 'accessibility';
24
+ if (/perf|latency|throughput|load/.test(t)) return 'performance';
25
+ return 'unit';
26
+ }
27
+
28
+ function slugify(text) {
29
+ return String(text ?? 'case')
30
+ .toLowerCase()
31
+ .replace(/[^a-z0-9]+/g, '-')
32
+ .replace(/^-+|-+$/g, '')
33
+ .slice(0, 48) || 'case';
34
+ }
35
+
36
+ /**
37
+ * Generate a test plan artefact (TP-###) from the requirements registry and
38
+ * detected test runners. Test cases are planned, never claimed passing.
39
+ */
40
+ export async function generateTestPlan(root, options = {}) {
41
+ const now = new Date().toISOString();
42
+ const project = await detectProject(root);
43
+ const config = await loadConfig(root).catch(() => defaultConfig({}));
44
+ const registry = await loadRequirementsRegistry(root);
45
+ const files = await collectArtefactFiles(root);
46
+
47
+ const requirements = (registry.requirements ?? []).filter((r) => r.status !== 'BLOCKED');
48
+ const testDir = project.tests.directories[0] ?? 'tests';
49
+ const testCommand = config.commands?.test ?? null;
50
+
51
+ const testCases = [];
52
+ for (const req of requirements) {
53
+ const criteria = req.acceptanceCriteria?.length
54
+ ? req.acceptanceCriteria
55
+ : [{ id: `${req.id}-AC1`, description: req.title ?? req.id }];
56
+ criteria.forEach((criterion, index) => {
57
+ const critText = typeof criterion === 'string' ? criterion : (criterion.description ?? criterion.text ?? criterion.id);
58
+ const id = `TC-${req.id}-${index + 1}`;
59
+ testCases.push({
60
+ id,
61
+ name: `${req.id}: ${String(critText).slice(0, 80)}`,
62
+ type: options.type ?? guessTestType(critText),
63
+ path: path.posix.join(testDir, `${slugify(req.id)}-${index + 1}.test.mjs`),
64
+ command: testCommand ?? 'NOT_CONFIGURED',
65
+ status: 'planned',
66
+ requirement: req.id,
67
+ criterion: typeof criterion === 'object' ? criterion.id : null,
68
+ });
69
+ });
70
+ }
71
+
72
+ const runners = project.tests.runners.filter((r) => r !== 'npm:test');
73
+ const artefact = {
74
+ id: nextTestPlanId(files.map((f) => f.id)),
75
+ schemaVersion: '1.0.0',
76
+ type: 'test-plan',
77
+ createdAt: now,
78
+ updatedAt: now,
79
+ status: 'DRAFT',
80
+ strategy: {
81
+ approach: 'One planned test case per acceptance criterion; types inferred from criterion wording and confirmed by a human.',
82
+ coverageGoals: {},
83
+ tools: [
84
+ ...runners.map((r) => ({ name: r, source: 'detected' })),
85
+ { name: 'aidf evidence', source: 'framework', note: 'results recorded via aidf evidence record' },
86
+ ],
87
+ mockPolicy: 'Mocks are allowed for external services in unit tests; integration and e2e cases must exercise real boundaries or be marked NOT_PROVEN.',
88
+ },
89
+ testCases,
90
+ source: {
91
+ type: 'generated',
92
+ author: 'aidf',
93
+ createdAt: now,
94
+ generator: 'test-plan@0.2.0',
95
+ },
96
+ links: {
97
+ covers: requirements.map((r) => r.id),
98
+ },
99
+ validation: {
100
+ schemaVersion: '1.0.0',
101
+ timestamp: now,
102
+ valid: true,
103
+ errors: [],
104
+ warnings: [
105
+ 'Test cases are planned, not executed. Update status only with real test output evidence.',
106
+ ...(testCommand ? [] : ['No test command configured (.aidf/config.json commands.test); set it to enable execution.']),
107
+ ],
108
+ },
109
+ detection: {
110
+ runners: project.tests.runners,
111
+ testDirectories: project.tests.directories,
112
+ packageManager: project.tests.packageManager,
113
+ },
114
+ };
115
+
116
+ return artefact;
117
+ }
118
+
119
+ export async function saveTestPlan(root, artefact) {
120
+ const file = aidfPaths(root).artefacts.testPlan;
121
+ await ensureDir(path.dirname(file));
122
+ await writeJson(file, artefact);
123
+ return file;
124
+ }
125
+
126
+ export async function loadTestPlan(root) {
127
+ const file = aidfPaths(root).artefacts.testPlan;
128
+ return readJson(file, null);
129
+ }
130
+
131
+ /**
132
+ * Coverage of requirements by planned/present test artefacts.
133
+ * A requirement is covered when the test plan contains at least one case
134
+ * linked to it, or a TEST-* artefact verifies it.
135
+ */
136
+ export async function testCoverage(root) {
137
+ const registry = await loadRequirementsRegistry(root);
138
+ const plan = await loadTestPlan(root);
139
+ const artefacts = await collectArtefactFiles(root);
140
+
141
+ const plannedByReq = new Map();
142
+ for (const tc of plan?.testCases ?? []) {
143
+ if (!tc.requirement) continue;
144
+ if (!plannedByReq.has(tc.requirement)) plannedByReq.set(tc.requirement, []);
145
+ plannedByReq.get(tc.requirement).push(tc.id);
146
+ }
147
+
148
+ const verifiedByArtefact = new Set();
149
+ for (const { body } of artefacts) {
150
+ if (!String(body.id ?? '').startsWith('TEST-')) continue;
151
+ for (const target of body.links?.['verified-by'] ?? body.links?.verifiedBy ?? []) {
152
+ verifiedByArtefact.add(target);
153
+ }
154
+ for (const target of body.links?.implements ?? []) {
155
+ verifiedByArtefact.add(target);
156
+ }
157
+ }
158
+
159
+ const details = (registry.requirements ?? [])
160
+ .filter((r) => r.status !== 'BLOCKED')
161
+ .map((r) => ({
162
+ requirement: r.id,
163
+ acceptanceCriteria: r.acceptanceCriteria?.length ?? 0,
164
+ plannedCases: plannedByReq.get(r.id) ?? [],
165
+ hasTestArtefact: verifiedByArtefact.has(r.id),
166
+ covered: (plannedByReq.get(r.id) ?? []).length > 0 || verifiedByArtefact.has(r.id),
167
+ }));
168
+
169
+ return {
170
+ testPlan: plan?.id ?? null,
171
+ total: details.length,
172
+ covered: details.filter((d) => d.covered).length,
173
+ uncovered: details.filter((d) => !d.covered).map((d) => d.requirement),
174
+ details,
175
+ };
176
+ }