codex-genesis-harness 0.1.4 → 0.1.6

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 (153) hide show
  1. package/.codebase/ARCHITECTURE_REVIEW_COMPLETE.md +216 -216
  2. package/.codebase/CURRENT_STATE.md +9 -7
  3. package/.codebase/FILE_NAMING_CLARIFICATION.md +161 -161
  4. package/.codebase/HARNESS_COMPLETENESS_AUDIT.md +613 -613
  5. package/.codebase/IMPLEMENTATION_COMPLETE.md +429 -429
  6. package/.codebase/IMPLEMENTATION_HANDOFF.md +351 -351
  7. package/.codebase/IMPROVEMENTS_SUMMARY.md +419 -419
  8. package/.codebase/PHASE3_SKILLS_NAMING_COMPLETE.md +292 -292
  9. package/.codebase/PHASE_DEPENDENCY_MAP.md +486 -486
  10. package/.codebase/QUICK_START_SPEC_IMPACT.md +456 -456
  11. package/.codebase/README.md +139 -139
  12. package/.codebase/RECOVERY_POINTS.md +438 -438
  13. package/.codebase/state.json +37 -0
  14. package/.codex/skills/genesis-api-sync/SKILL.md +354 -354
  15. package/.codex/skills/genesis-api-sync/checklists/api-sync-checklist.md +101 -101
  16. package/.codex/skills/genesis-api-sync/templates/api-change-template.md +257 -257
  17. package/.codex/skills/genesis-debug-guide/SKILL.md +479 -479
  18. package/.codex/skills/genesis-debug-guide/checklists/flaky-test-investigation.md +339 -339
  19. package/.codex/skills/genesis-debug-guide/checklists/production-bug-debug.md +210 -210
  20. package/.codex/skills/genesis-debug-guide/checklists/test-failure-debug.md +158 -158
  21. package/.codex/skills/genesis-debug-guide/observability/debug-commands.md +365 -365
  22. package/.codex/skills/genesis-debug-guide/playbooks/unit-test-failures.md +289 -289
  23. package/.codex/skills/genesis-debug-guide/templates/debug-investigation-log.md +288 -288
  24. package/.codex/skills/genesis-docs-automation/SKILL.md +1003 -1003
  25. package/.codex/skills/genesis-docs-automation/checklists/docs-validation.md +359 -359
  26. package/.codex/skills/genesis-docs-automation/checklists/spec-alignment.md +312 -312
  27. package/.codex/skills/genesis-docs-automation/observability/docs-tracking.md +382 -382
  28. package/.codex/skills/genesis-docs-automation/playbooks/auto-update-flow.md +851 -851
  29. package/.codex/skills/genesis-docs-automation/playbooks/changelog-generation.md +491 -491
  30. package/.codex/skills/genesis-docs-automation/templates/changelog-entry-template.md +187 -187
  31. package/.codex/skills/genesis-docs-automation/templates/handoff-template.md +297 -297
  32. package/.codex/skills/genesis-harness/SKILL.md +1427 -1418
  33. package/.codex/skills/genesis-harness/agents/openai.yaml +7 -7
  34. package/.codex/skills/genesis-harness/checklists/bug-fix-qa.md +169 -169
  35. package/.codex/skills/genesis-harness/checklists/new-feature-qa.md +157 -157
  36. package/.codex/skills/genesis-harness/checklists/refactor-qa.md +216 -216
  37. package/.codex/skills/genesis-harness/checklists/requirements-validation.md +211 -211
  38. package/.codex/skills/genesis-harness/references/planning-schema.md +35 -35
  39. package/.codex/skills/genesis-harness/references/quality-rubric.md +21 -21
  40. package/.codex/skills/genesis-harness/references/research-rubric.md +41 -41
  41. package/.codex/skills/genesis-harness/references/workflows.md +33 -33
  42. package/.codex/skills/genesis-harness/resources/agents-template.md +27 -27
  43. package/.codex/skills/genesis-harness/resources/api-docs-template.md +32 -32
  44. package/.codex/skills/genesis-harness/resources/architecture-template.md +30 -30
  45. package/.codex/skills/genesis-harness/resources/audit-template.md +26 -26
  46. package/.codex/skills/genesis-harness/resources/bug-template.md +34 -34
  47. package/.codex/skills/genesis-harness/resources/change-impact-matrix-template.md +204 -204
  48. package/.codex/skills/genesis-harness/resources/check-template.md +21 -21
  49. package/.codex/skills/genesis-harness/resources/conventions-template.md +42 -42
  50. package/.codex/skills/genesis-harness/resources/decision-template.md +33 -33
  51. package/.codex/skills/genesis-harness/resources/design-template.md +26 -26
  52. package/.codex/skills/genesis-harness/resources/escalation-template.md +21 -21
  53. package/.codex/skills/genesis-harness/resources/feature-template.md +49 -49
  54. package/.codex/skills/genesis-harness/resources/foundation-phase-template.md +131 -131
  55. package/.codex/skills/genesis-harness/resources/integrations-template.md +32 -32
  56. package/.codex/skills/genesis-harness/resources/journeys-template.md +13 -13
  57. package/.codex/skills/genesis-harness/resources/lessons-learned-template.md +12 -12
  58. package/.codex/skills/genesis-harness/resources/observability-template.md +34 -34
  59. package/.codex/skills/genesis-harness/resources/phase-00-foundation-template.md +76 -76
  60. package/.codex/skills/genesis-harness/resources/phase-template.md +34 -34
  61. package/.codex/skills/genesis-harness/resources/pitfalls-template.md +22 -22
  62. package/.codex/skills/genesis-harness/resources/planning-tree-template.md +39 -39
  63. package/.codex/skills/genesis-harness/resources/post-implementation-guide.md +347 -347
  64. package/.codex/skills/genesis-harness/resources/project-template.md +38 -38
  65. package/.codex/skills/genesis-harness/resources/quality-score-template.md +11 -11
  66. package/.codex/skills/genesis-harness/resources/requirements-template.md +26 -26
  67. package/.codex/skills/genesis-harness/resources/research-template.md +26 -26
  68. package/.codex/skills/genesis-harness/resources/review-template.md +22 -22
  69. package/.codex/skills/genesis-harness/resources/spec-changelog-template.md +6 -6
  70. package/.codex/skills/genesis-harness/resources/stack-template.md +33 -33
  71. package/.codex/skills/genesis-harness/resources/verification-template.md +26 -26
  72. package/.codex/skills/genesis-harness/scripts/check-architecture-boundaries.sh +0 -0
  73. package/.codex/skills/genesis-harness/scripts/check-docs-sync.sh +0 -0
  74. package/.codex/skills/genesis-harness/scripts/check-no-debug-logs.sh +0 -0
  75. package/.codex/skills/genesis-harness/scripts/check-required-planning-files.sh +0 -0
  76. package/.codex/skills/genesis-harness/scripts/check-spec-changelog.sh +0 -0
  77. package/.codex/skills/genesis-harness/scripts/check-task-tracking.sh +0 -0
  78. package/.codex/skills/genesis-harness/scripts/compact-context.sh +0 -0
  79. package/.codex/skills/genesis-harness/scripts/create-adr.sh +0 -0
  80. package/.codex/skills/genesis-harness/scripts/create-bug.sh +0 -0
  81. package/.codex/skills/genesis-harness/scripts/create-feature.sh +0 -0
  82. package/.codex/skills/genesis-harness/scripts/detect-stack.sh +0 -0
  83. package/.codex/skills/genesis-harness/scripts/init-planning.sh +0 -0
  84. package/.codex/skills/genesis-harness/scripts/list-changed-files.sh +0 -0
  85. package/.codex/skills/genesis-harness/scripts/offload-log.sh +0 -0
  86. package/.codex/skills/genesis-harness/scripts/run-verification.sh +0 -0
  87. package/.codex/skills/genesis-harness/scripts/run-verify-loop.sh +0 -0
  88. package/.codex/skills/genesis-harness/scripts/update-state.sh +0 -0
  89. package/.codex/skills/genesis-mvp-planning/SKILL.md +114 -0
  90. package/.codex/skills/genesis-mvp-planning/agents/openai.yaml +6 -0
  91. package/.codex/skills/genesis-mvp-planning/checklists/mvp-readiness.md +18 -0
  92. package/.codex/skills/genesis-mvp-planning/examples/5-phase-roadmap-example.md +43 -0
  93. package/.codex/skills/genesis-mvp-planning/templates/phase-1-core.md +17 -0
  94. package/.codex/skills/genesis-mvp-planning/templates/phase-2-auth.md +17 -0
  95. package/.codex/skills/genesis-mvp-planning/templates/phase-3-features.md +17 -0
  96. package/.codex/skills/genesis-mvp-planning/templates/phase-4-integrations.md +17 -0
  97. package/.codex/skills/genesis-mvp-planning/templates/phase-5-readiness.md +17 -0
  98. package/.codex/skills/genesis-new-design/agents/openai.yaml +3 -3
  99. package/.codex/skills/genesis-observability-automation/checklists/.gitkeep +0 -0
  100. package/.codex/skills/genesis-observability-automation/observability/.gitkeep +0 -0
  101. package/.codex/skills/genesis-observability-automation/playbooks/.gitkeep +0 -0
  102. package/.codex/skills/genesis-observability-automation/templates/.gitkeep +0 -0
  103. package/.codex/skills/genesis-release-orchestration/SKILL.md +653 -653
  104. package/.codex/skills/genesis-release-orchestration/checklists/post-deployment-verification.md +274 -274
  105. package/.codex/skills/genesis-release-orchestration/checklists/pre-release-validation.md +220 -220
  106. package/.codex/skills/genesis-release-orchestration/observability/release-tracking.md +253 -253
  107. package/.codex/skills/genesis-release-orchestration/playbooks/canary-deployment-orchestration.md +472 -472
  108. package/.codex/skills/genesis-release-orchestration/playbooks/semantic-versioning-automation.md +494 -494
  109. package/.codex/skills/genesis-release-orchestration/templates/deployment-strategy-template.md +303 -303
  110. package/.codex/skills/genesis-release-orchestration/templates/release-runbook-template.md +420 -420
  111. package/.codex/skills/genesis-research-first/SKILL.md +237 -237
  112. package/.codex/skills/genesis-research-first/templates/.gitkeep +0 -0
  113. package/.codex/skills/genesis-spec-propagation/SKILL.md +534 -534
  114. package/.codex/skills/genesis-spec-propagation/checklists/phase-update-verification.md +384 -384
  115. package/.codex/skills/genesis-spec-propagation/checklists/spec-change-detection.md +257 -257
  116. package/.codex/skills/genesis-spec-propagation/observability/propagation-tracking.md +373 -373
  117. package/.codex/skills/genesis-spec-propagation/playbooks/breaking-change-propagation.md +692 -692
  118. package/.codex/skills/genesis-spec-propagation/playbooks/feature-change-propagation.md +434 -434
  119. package/.codex/skills/genesis-spec-propagation/templates/migration-guide-template.md +407 -407
  120. package/.codex/skills/genesis-state-machine/SKILL.md +34 -0
  121. package/.codex/skills/genesis-upgrade-design/agents/openai.yaml +3 -3
  122. package/.codex/skills/spec-impact-engine/SKILL.md +504 -504
  123. package/.codex/skills/spec-impact-engine/detect-spec-changes.sh +0 -0
  124. package/.codex-plugin/plugin.json +24 -24
  125. package/CHANGELOG.md +42 -0
  126. package/LICENSE +22 -22
  127. package/README.EN.md +784 -719
  128. package/README.VI.md +776 -712
  129. package/README.md +113 -253
  130. package/VERSION +2 -2
  131. package/bin/genesis-harness.js +90 -87
  132. package/package.json +68 -43
  133. package/scripts/README.md +342 -342
  134. package/scripts/compact-context.sh +0 -0
  135. package/scripts/contract_integrity_gate.js +83 -0
  136. package/scripts/detect-changes.sh +0 -0
  137. package/scripts/healing_telemetry.js +118 -0
  138. package/scripts/install.sh +4 -1
  139. package/scripts/offload-log.sh +0 -0
  140. package/scripts/prompt_sentinel.js +84 -0
  141. package/scripts/run-evals.sh +1 -0
  142. package/scripts/run-verify-loop.sh +11 -0
  143. package/scripts/spec_visual_sync.js +157 -0
  144. package/scripts/test_generator.js +142 -0
  145. package/scripts/transition_state.sh +67 -0
  146. package/scripts/uninstall.sh +1 -0
  147. package/scripts/validation_gates.sh +85 -0
  148. package/scripts/verify.sh +5 -0
  149. package/tests/unit/contract_integrity_gate.test.js +74 -0
  150. package/tests/unit/healing_telemetry.test.js +58 -0
  151. package/tests/unit/prompt_sentinel.test.js +50 -0
  152. package/tests/unit/spec_visual_sync.test.js +77 -0
  153. package/tests/unit/test_generator.test.js +62 -0
@@ -0,0 +1,83 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * AST Contract-Code Integrity Gate
5
+ * Part of Genesis Codex Harness v0.1.8
6
+ */
7
+
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+
11
+ function printUsage() {
12
+ console.log('Usage:');
13
+ console.log(' node scripts/contract_integrity_gate.js --code <code-file-path> --contract <response-json-path>');
14
+ process.exit(1);
15
+ }
16
+
17
+ const args = process.argv.slice(2);
18
+ const codeIndex = args.indexOf('--code');
19
+ const contractIndex = args.indexOf('--contract');
20
+
21
+ if (codeIndex === -1 || contractIndex === -1 || !args[codeIndex + 1] || !args[contractIndex + 1]) {
22
+ printUsage();
23
+ }
24
+
25
+ const codePath = path.resolve(process.cwd(), args[codeIndex + 1]);
26
+ const contractPath = path.resolve(process.cwd(), args[contractIndex + 1]);
27
+
28
+ if (!fs.existsSync(codePath)) {
29
+ console.error(`Error: Source code file does not exist at: ${codePath}`);
30
+ process.exit(1);
31
+ }
32
+
33
+ if (!fs.existsSync(contractPath)) {
34
+ console.error(`Error: Contract JSON file does not exist at: ${contractPath}`);
35
+ process.exit(1);
36
+ }
37
+
38
+ // 1. Parse Contract JSON Schema
39
+ let contractSchema = {};
40
+ try {
41
+ contractSchema = JSON.parse(fs.readFileSync(contractPath, 'utf8'));
42
+ } catch (err) {
43
+ console.error(`[ERROR] Failed to parse JSON contract:`, err.message);
44
+ process.exit(1);
45
+ }
46
+
47
+ const properties = contractSchema.properties || {};
48
+ const requiredFields = contractSchema.required || Object.keys(properties);
49
+
50
+ // 2. Parse Source Code File (Static scan)
51
+ const codeContent = fs.readFileSync(codePath, 'utf8');
52
+
53
+ console.log(`[Integrity Gate] Auditing static code alignment:`);
54
+ console.log(` - Code file: ${path.basename(codePath)}`);
55
+ console.log(` - Contract: ${path.basename(contractPath)}`);
56
+
57
+ let integrityFailed = false;
58
+ const missingFields = [];
59
+
60
+ // For each required field in the contract, verify its presence inside the code
61
+ for (const field of requiredFields) {
62
+ // Use a simple, robust regex to match field names in common object/JSON structures
63
+ // Matches: "field", 'field', field:, field =
64
+ const fieldRegex = new RegExp(`['"]?${field}['"]?\\s*[:=]`, 'g');
65
+
66
+ if (!fieldRegex.test(codeContent)) {
67
+ missingFields.push(field);
68
+ integrityFailed = true;
69
+ }
70
+ }
71
+
72
+ if (integrityFailed) {
73
+ console.error(`\n❌ [INTEGRITY FAILURE] [STATIC ALIGNMENT DRIFT]`);
74
+ console.error(` The source code file is missing implementations/properties for the following required contract fields:`);
75
+ for (const field of missingFields) {
76
+ console.error(` - Missing property: "${field}" (Expected type: "${properties[field]?.type || 'any'}")`);
77
+ }
78
+ console.error(` Transition Blocked. Please align your source implementation with the API contracts.`);
79
+ process.exit(1);
80
+ } else {
81
+ console.log(`\n✅ [INTEGRITY SUCCESS] Code matches all ${requiredFields.length} required fields from contract.`);
82
+ process.exit(0);
83
+ }
File without changes
@@ -0,0 +1,118 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Healing Telemetry & Lessons-Learned System
5
+ * Part of Genesis Codex Harness v0.1.8
6
+ */
7
+
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+
11
+ function printUsage() {
12
+ console.log('Usage:');
13
+ console.log(' node scripts/healing_telemetry.js --record --error "<error>" --file "<file>" --fix "<fix-desc>"');
14
+ console.log(' node scripts/healing_telemetry.js --recall --error "<error>"');
15
+ process.exit(1);
16
+ }
17
+
18
+ const args = process.argv.slice(2);
19
+ const recordMode = args.includes('--record');
20
+ const recallMode = args.includes('--recall');
21
+
22
+ if (!recordMode && !recallMode) {
23
+ printUsage();
24
+ }
25
+
26
+ const LESSONS_PATH = path.resolve(process.cwd(), '.codebase/failures/lessons_learned.md');
27
+
28
+ // Helper to sanitize text for markdown table/list compatibility
29
+ const sanitize = (text) => text.replace(/[\n\r]/g, ' ').replace(/\|/g, '\\|').trim();
30
+
31
+ // 1. Record Mode
32
+ if (recordMode) {
33
+ const errorIndex = args.indexOf('--error');
34
+ const fileIndex = args.indexOf('--file');
35
+ const fixIndex = args.indexOf('--fix');
36
+
37
+ if (errorIndex === -1 || fileIndex === -1 || fixIndex === -1 || !args[errorIndex + 1] || !args[fileIndex + 1] || !args[fixIndex + 1]) {
38
+ printUsage();
39
+ }
40
+
41
+ const error = args[errorIndex + 1];
42
+ const file = args[fileIndex + 1];
43
+ const fix = args[fixIndex + 1];
44
+
45
+ console.log(`[Healing Telemetry] Recording lessons-learned telemetry entry...`);
46
+
47
+ // Ensure directories exist
48
+ fs.mkdirSync(path.dirname(LESSONS_PATH), { recursive: true });
49
+
50
+ let header = '';
51
+ if (!fs.existsSync(LESSONS_PATH)) {
52
+ header = `# Self-Healing Lessons Learned Database\n\nThis file persists recorded error-fix telemetry signatures to facilitate immediate 1-turn recovery.\n\n| Timestamp | Target File | Error Signature | Remedial Fix Applied |\n| :--- | :--- | :--- | :--- |\n`;
53
+ }
54
+
55
+ const timestamp = new Date().toISOString().replace('T', ' ').substring(0, 19);
56
+ const rowEntry = `| ${timestamp} | ${sanitize(file)} | ${sanitize(error)} | ${sanitize(fix)} |\n`;
57
+
58
+ fs.appendFileSync(LESSONS_PATH, header + rowEntry, 'utf8');
59
+ console.log(`✓ Telemetry successfully recorded inside lessons_learned.md`);
60
+ process.exit(0);
61
+ }
62
+
63
+ // 2. Recall Mode
64
+ if (recallMode) {
65
+ const errorIndex = args.indexOf('--error');
66
+ if (errorIndex === -1 || !args[errorIndex + 1]) {
67
+ printUsage();
68
+ }
69
+
70
+ const queryError = args[errorIndex + 1].toLowerCase();
71
+ console.log(`[Healing Telemetry] Querying telemetry for: "${queryError}"`);
72
+
73
+ if (!fs.existsSync(LESSONS_PATH)) {
74
+ console.log('No telemetry lessons-learned database available yet. Proceeding with standard healing.');
75
+ process.exit(0);
76
+ }
77
+
78
+ const content = fs.readFileSync(LESSONS_PATH, 'utf8');
79
+ const lines = content.split('\n');
80
+
81
+ let matchFound = false;
82
+ let bestMatch = null;
83
+
84
+ for (const line of lines) {
85
+ if (!line.startsWith('|') || line.includes('Timestamp') || line.includes(':---')) continue;
86
+
87
+ const parts = line.split('|').map(p => p.trim());
88
+ if (parts.length >= 5) {
89
+ const errorSignature = parts[3].toLowerCase();
90
+ const refactoringFix = parts[4];
91
+
92
+ // Simple keyword intersection/substring search
93
+ if (queryError.includes(errorSignature) || errorSignature.includes(queryError)) {
94
+ bestMatch = {
95
+ file: parts[2],
96
+ signature: parts[3],
97
+ fix: refactoringFix
98
+ };
99
+ matchFound = true;
100
+ break; // Return first closest match
101
+ }
102
+ }
103
+ }
104
+
105
+ if (matchFound && bestMatch) {
106
+ console.log(`\n🎯 [RECALL MATCH FOUND] [1-TURN RECOVERY SUGGESTION]:`);
107
+ console.log(` - Target file: ${bestMatch.file}`);
108
+ console.log(` - Signature matched: "${bestMatch.signature}"`);
109
+ console.log(` - Recommended Fix: ${bestMatch.fix}`);
110
+
111
+ // Output key snippet directly for script parsing/AI intake
112
+ console.log(`\nSUGGESTED_FIX_START: ${bestMatch.fix} :SUGGESTED_FIX_END`);
113
+ process.exit(0);
114
+ } else {
115
+ console.log('No matching error-fix signature found. Defaulting to general code analysis.');
116
+ process.exit(0);
117
+ }
118
+ }
@@ -8,6 +8,7 @@ skill_names=(
8
8
  genesis-upgrade-design
9
9
  genesis-architecture
10
10
  genesis-planning
11
+ genesis-mvp-planning
11
12
  genesis-codebase-map
12
13
  genesis-design-spec
13
14
  genesis-api-contract
@@ -79,7 +80,9 @@ install_one() {
79
80
  local target_dir="$target_root/$skill_name"
80
81
 
81
82
  if [ -e "$target_dir" ]; then
82
- backup_dir="${target_dir}.backup.$(date +%Y%m%d%H%M%S)"
83
+ local backup_parent="$(dirname "$target_root")/backups"
84
+ mkdir -p "$backup_parent"
85
+ backup_dir="${backup_parent}/${skill_name}.backup.$(date +%Y%m%d%H%M%S)"
83
86
  mv "$target_dir" "$backup_dir"
84
87
  echo "Existing skill backed up to: $backup_dir"
85
88
  fi
File without changes
@@ -0,0 +1,84 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Pre-emptive Prompt Sentinel
5
+ * Part of Genesis Codex Harness v0.1.7
6
+ */
7
+
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+ const { execSync } = require('child_process');
11
+
12
+ function printUsage() {
13
+ console.log('Usage:');
14
+ console.log(' node scripts/prompt_sentinel.js --check <file-or-log-path> [--threshold <tokens>]');
15
+ process.exit(1);
16
+ }
17
+
18
+ const args = process.argv.slice(2);
19
+ if (args.length < 2 || args[0] !== '--check') {
20
+ printUsage();
21
+ }
22
+
23
+ const targetPath = path.resolve(process.cwd(), args[1]);
24
+ let threshold = 20000; // Default safety threshold is 20k tokens
25
+
26
+ const thresholdIndex = args.indexOf('--threshold');
27
+ if (thresholdIndex !== -1 && args[thresholdIndex + 1]) {
28
+ threshold = parseInt(args[thresholdIndex + 1], 10);
29
+ }
30
+
31
+ if (!fs.existsSync(targetPath)) {
32
+ console.error(`Target file/log does not exist: ${targetPath}`);
33
+ process.exit(1);
34
+ }
35
+
36
+ const stats = fs.statSync(targetPath);
37
+ const fileSizeChars = stats.size;
38
+ const estimatedTokens = Math.ceil(fileSizeChars / 4);
39
+
40
+ console.log(`[Prompt Sentinel] Evaluating token load for: ${path.basename(targetPath)}`);
41
+ console.log(` - File size: ${fileSizeChars} characters`);
42
+ console.log(` - Estimated token payload: ${estimatedTokens} tokens (Safety threshold: ${threshold})`);
43
+
44
+ if (estimatedTokens > threshold) {
45
+ console.warn(`\n[WARNING] [PROMPT SENTINEL] Payload of ${estimatedTokens} tokens exceeds the safety threshold of ${threshold}!`);
46
+ console.warn(`[WARNING] Risk of context rot, model amnesia, and high API billing costs detected.`);
47
+ console.warn(`[ACTION] Automatically triggering context compaction and log optimization...\n`);
48
+
49
+ // Trigger compact-context script if it exists
50
+ const compactionScript = path.resolve(process.cwd(), 'scripts/compact-context.sh');
51
+ if (fs.existsSync(compactionScript)) {
52
+ try {
53
+ console.log(`Executing: ${compactionScript}`);
54
+ const output = execSync(`bash "${compactionScript}"`, { encoding: 'utf8' });
55
+ console.log(output);
56
+ console.log(`[Prompt Sentinel] Context compaction successfully executed. ✓`);
57
+ } catch (err) {
58
+ console.error(`[ERROR] Failed to execute context compaction:`, err.message);
59
+ }
60
+ } else {
61
+ console.warn(`[WARNING] Compaction script not found at ${compactionScript}. Skipping auto-compaction.`);
62
+ }
63
+
64
+ // Pre-emptively truncate the bloated log file to keep the window safe
65
+ try {
66
+ const fileContent = fs.readFileSync(targetPath, 'utf8');
67
+ // Keep only the first 500 lines and last 500 lines of the file, strip the rest
68
+ const lines = fileContent.split('\n');
69
+ if (lines.length > 1000) {
70
+ const truncatedContent = [
71
+ ...lines.slice(0, 500),
72
+ `\n... [PROMPT SENTINEL AUTO-TRUNCATION: Stript ${lines.length - 1000} lines of redundant log data to protect token bounds] ...\n`,
73
+ ...lines.slice(-500)
74
+ ].join('\n');
75
+
76
+ fs.writeFileSync(targetPath, truncatedContent, 'utf8');
77
+ console.log(`[Prompt Sentinel] Bloated file truncated successfully to safeguard token bounds. ✓`);
78
+ }
79
+ } catch (err) {
80
+ console.error(`[ERROR] Failed to truncate target file:`, err.message);
81
+ }
82
+ } else {
83
+ console.log(`✓ [Prompt Sentinel] Token payload is within safe boundaries. No action required.`);
84
+ }
@@ -10,6 +10,7 @@ skill_names=(
10
10
  genesis-upgrade-design
11
11
  genesis-architecture
12
12
  genesis-planning
13
+ genesis-mvp-planning
13
14
  genesis-codebase-map
14
15
  genesis-design-spec
15
16
  genesis-api-contract
@@ -54,6 +54,12 @@ if [ "$CURRENT_ITERATION" -gt "$MAX_ITERATIONS" ]; then
54
54
  exit 99
55
55
  fi
56
56
 
57
+ # Recall prior lessons learned if there was a previous failure log
58
+ if [ -f "$FAILURE_LOG" ]; then
59
+ echo "==> [HEALING TELEMETRY] Analyzing previous failure logs for matching recorded lessons..."
60
+ node "$(dirname "$0")/healing_telemetry.js" --recall --error "$(head -n 2 "$FAILURE_LOG" | tr '\n' ' ')" || true
61
+ fi
62
+
57
63
  # Execute verification command
58
64
  set +e
59
65
  "$@" > "$FAILURE_LOG" 2>&1
@@ -62,6 +68,10 @@ set -e
62
68
 
63
69
  if [ $EXIT_CODE -eq 0 ]; then
64
70
  echo "==> [VERIFY LOOP] Pass! Verification completed successfully."
71
+ if [ "$CURRENT_ITERATION" -gt 1 ]; then
72
+ echo "==> [HEALING TELEMETRY] Capturing successful self-healing fix to telemetry database..."
73
+ node "$(dirname "$0")/healing_telemetry.js" --record --error "Verify command failure" --file "codebase" --fix "Resolved verify check regression at iteration $CURRENT_ITERATION" || true
74
+ fi
65
75
  rm -f "$LOOP_COUNT_FILE"
66
76
  rm -f "$FAILURE_LOG"
67
77
  else
@@ -73,3 +83,4 @@ else
73
83
  fi
74
84
 
75
85
  exit $EXIT_CODE
86
+
@@ -0,0 +1,157 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Spec Visual Sync - Bi-directional AST Sync between Mermaid ERD and JSON Contracts
5
+ * Part of Genesis Codex Harness v0.1.7
6
+ */
7
+
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+
11
+ function printUsage() {
12
+ console.log('Usage:');
13
+ console.log(' node scripts/spec_visual_sync.js --from-erd # Sync ERD diagram to API contracts');
14
+ console.log(' node scripts/spec_visual_sync.js --to-erd # Sync API contracts to ERD diagram');
15
+ process.exit(1);
16
+ }
17
+
18
+ const args = process.argv.slice(2);
19
+ if (args.length !== 1 || (args[0] !== '--from-erd' && args[0] !== '--to-erd')) {
20
+ printUsage();
21
+ }
22
+
23
+ const ERD_PATH = path.resolve(process.cwd(), '.planning/diagrams/database-erd.mmd');
24
+ const CONTRACTS_DIR = path.resolve(process.cwd(), 'contracts/api');
25
+
26
+ // 1. Sync from ERD to API Contracts
27
+ function syncFromErd() {
28
+ if (!fs.existsSync(ERD_PATH)) {
29
+ console.error(`ERD file not found at: ${ERD_PATH}`);
30
+ process.exit(1);
31
+ }
32
+
33
+ const erdContent = fs.readFileSync(ERD_PATH, 'utf8');
34
+ console.log(`Parsing Mermaid ERD from: ${ERD_PATH}`);
35
+
36
+ // Regular expression to parse erDiagram blocks
37
+ // e.g. ENTITY { type name }
38
+ const entityRegex = /(\w+)\s*\{\s*([^}]+)\}/g;
39
+ let match;
40
+ let parsedEntities = 0;
41
+
42
+ while ((match = entityRegex.exec(erdContent)) !== null) {
43
+ const entityName = match[1].toLowerCase();
44
+ const fieldsBlock = match[2];
45
+
46
+ const properties = {};
47
+ const required = [];
48
+
49
+ // Parse individual fields
50
+ const fieldLines = fieldsBlock.split('\n');
51
+ for (let line of fieldLines) {
52
+ line = line.trim();
53
+ if (!line || line.startsWith('%%')) continue; // Skip comments/empty
54
+
55
+ // Format: <type> <name> "comment" or <type> <name>
56
+ const parts = line.split(/\s+/);
57
+ if (parts.length >= 2) {
58
+ const type = parts[0].toLowerCase();
59
+ const name = parts[1].replace(/["']/g, ''); // strip quotes
60
+
61
+ let schemaType = 'string';
62
+ if (type.includes('int') || type.includes('number') || type.includes('float')) {
63
+ schemaType = 'number';
64
+ } else if (type.includes('bool')) {
65
+ schemaType = 'boolean';
66
+ } else if (type.includes('array') || type.includes('list')) {
67
+ schemaType = 'array';
68
+ } else if (type.includes('object')) {
69
+ schemaType = 'object';
70
+ }
71
+
72
+ properties[name] = { type: schemaType };
73
+ // For simplicity, let's treat id or key fields as required
74
+ if (name === 'id' || line.includes('PK') || line.includes('FK')) {
75
+ required.push(name);
76
+ }
77
+ }
78
+ }
79
+
80
+ // Build the JSON schema for response.json
81
+ const schema = {
82
+ $schema: 'http://json-schema.org/draft-07/schema#',
83
+ title: `${entityName.charAt(0).toUpperCase() + entityName.slice(1)} Contract`,
84
+ type: 'object',
85
+ properties: properties,
86
+ required: required.length > 0 ? required : undefined
87
+ };
88
+
89
+ // Ensure directory exists
90
+ const entityDir = path.join(CONTRACTS_DIR, entityName);
91
+ fs.mkdirSync(entityDir, { recursive: true });
92
+
93
+ const contractPath = path.join(entityDir, 'response.json');
94
+ fs.writeFileSync(contractPath, JSON.stringify(schema, null, 2), 'utf8');
95
+ console.log(`✓ Synchronized contract schema for: ${entityName} -> ${contractPath}`);
96
+ parsedEntities++;
97
+ }
98
+
99
+ console.log(`Success: Synchronized ${parsedEntities} entities from ERD to Contracts.`);
100
+ }
101
+
102
+ // 2. Sync from API Contracts to ERD Diagram
103
+ function syncToErd() {
104
+ if (!fs.existsSync(CONTRACTS_DIR)) {
105
+ console.error(`Contracts directory not found: ${CONTRACTS_DIR}`);
106
+ process.exit(1);
107
+ }
108
+
109
+ console.log(`Scanning API contracts under: ${CONTRACTS_DIR}`);
110
+ const entities = fs.readdirSync(CONTRACTS_DIR);
111
+
112
+ let erdContent = 'erDiagram\n\n';
113
+ let hasContent = false;
114
+
115
+ for (const entity of entities) {
116
+ const responsePath = path.join(CONTRACTS_DIR, entity, 'response.json');
117
+ if (!fs.existsSync(responsePath)) continue;
118
+
119
+ try {
120
+ const schema = JSON.parse(fs.readFileSync(responsePath, 'utf8'));
121
+ const properties = schema.properties || {};
122
+
123
+ const entityUpper = entity.toUpperCase();
124
+ erdContent += ` ${entityUpper} {\n`;
125
+
126
+ for (const [fieldName, fieldMeta] of Object.entries(properties)) {
127
+ let fieldType = fieldMeta.type || 'string';
128
+ if (fieldType === 'number') fieldType = 'int';
129
+ if (fieldType === 'boolean') fieldType = 'bool';
130
+
131
+ erdContent += ` ${fieldType} ${fieldName}\n`;
132
+ }
133
+
134
+ erdContent += ` }\n\n`;
135
+ hasContent = true;
136
+ } catch (err) {
137
+ console.error(`Error parsing contract for ${entity}:`, err.message);
138
+ }
139
+ }
140
+
141
+ if (!hasContent) {
142
+ console.log('No valid response.json contracts found to synchronize.');
143
+ return;
144
+ }
145
+
146
+ // Ensure diagram directory exists
147
+ fs.mkdirSync(path.dirname(ERD_PATH), { recursive: true });
148
+ fs.writeFileSync(ERD_PATH, erdContent.trim() + '\n', 'utf8');
149
+ console.log(`✓ Successfully compiled and synchronized database-erd.mmd: ${ERD_PATH}`);
150
+ }
151
+
152
+ // Execute core flow
153
+ if (args[0] === '--from-erd') {
154
+ syncFromErd();
155
+ } else {
156
+ syncToErd();
157
+ }
@@ -0,0 +1,142 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Contract-Driven Test Auto-Generator
5
+ * Part of Genesis Codex Harness v0.1.7
6
+ */
7
+
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+
11
+ function printUsage() {
12
+ console.log('Usage:');
13
+ console.log(' node scripts/test_generator.js <endpoint-name>');
14
+ console.log('Example:');
15
+ console.log(' node scripts/test_generator.js products');
16
+ process.exit(1);
17
+ }
18
+
19
+ const args = process.argv.slice(2);
20
+ if (args.length !== 1) {
21
+ printUsage();
22
+ }
23
+
24
+ const endpoint = args[0].toLowerCase();
25
+ const CONTRACT_DIR = path.resolve(process.cwd(), 'contracts/api', endpoint);
26
+ const OUTPUT_DIR = path.resolve(process.cwd(), 'tests/integration');
27
+
28
+ if (!fs.existsSync(CONTRACT_DIR)) {
29
+ console.error(`Error: API Contract directory does not exist for: ${endpoint}`);
30
+ console.error(`Please define contracts at: ${CONTRACT_DIR}`);
31
+ process.exit(1);
32
+ }
33
+
34
+ const requestPath = path.join(CONTRACT_DIR, 'request.json');
35
+ const responsePath = path.join(CONTRACT_DIR, 'response.json');
36
+
37
+ if (!fs.existsSync(responsePath)) {
38
+ console.error(`Error: Response contract not found: ${responsePath}`);
39
+ process.exit(1);
40
+ }
41
+
42
+ // Read and parse response schema/contract
43
+ let schema = {};
44
+ try {
45
+ schema = JSON.parse(fs.readFileSync(responsePath, 'utf8'));
46
+ } catch (e) {
47
+ console.error(`Error parsing response.json:`, e.message);
48
+ process.exit(1);
49
+ }
50
+
51
+ // Read request sample if available
52
+ let requestSample = '{}';
53
+ if (fs.existsSync(requestPath)) {
54
+ try {
55
+ requestSample = fs.readFileSync(requestPath, 'utf8');
56
+ } catch (e) {}
57
+ }
58
+
59
+ const properties = schema.properties || {};
60
+ const requiredFields = schema.required || Object.keys(properties);
61
+
62
+ // Construct test cases content
63
+ let testSuiteCode = `/**
64
+ * Integration Test for Endpoint: /api/${endpoint}
65
+ * Automatically generated by Genesis Contract-Driven Test Generator (v0.1.7)
66
+ * Strictly Enforces TDD Contract Compliance.
67
+ */
68
+
69
+ const assert = require('assert');
70
+
71
+ describe('GET /api/${endpoint} - TDD Contract Compliance Test Suite', () => {
72
+
73
+ it('should respond with 200 OK and match the API response contract keys', async () => {
74
+ // Mock or execute fetch to the implementation endpoint
75
+ // In production, replace with real server request:
76
+ // const res = await fetch('http://localhost:3000/api/${endpoint}');
77
+
78
+ // For TDD skeletal validation, we verify structural alignment
79
+ const mockResponse = {
80
+ status: 200,
81
+ data: ${JSON.stringify(generateMockData(properties), null, 6)}
82
+ };
83
+
84
+ assert.strictEqual(mockResponse.status, 200, 'Response status must be 200 OK');
85
+ const data = mockResponse.data;
86
+
87
+ // Validate presence of required contract keys
88
+ const requiredKeys = ${JSON.stringify(requiredFields)};
89
+ for (const key of requiredKeys) {
90
+ assert.ok(key in data, \`Contract mismatch: Required property "\${key}" is missing from the API response\`);
91
+ }
92
+
93
+ // Validate value types
94
+ `;
95
+
96
+ for (const [key, meta] of Object.entries(properties)) {
97
+ const expectedType = meta.type || 'string';
98
+ testSuiteCode += ` assert.strictEqual(typeof data.${key}, '${expectedType}', 'Property "${key}" must be of type "${expectedType}"');\n`;
99
+ }
100
+
101
+ testSuiteCode += ` });
102
+
103
+ it('should reject invalid or malformed payloads with 400 Bad Request', async () => {
104
+ const invalidPayload = {}; // Empty payload
105
+ const mockErrResponse = {
106
+ status: 400,
107
+ error: 'Bad Request - Malformed schema structure'
108
+ };
109
+
110
+ assert.strictEqual(mockErrResponse.status, 400, 'Must return 400 Bad Request');
111
+ assert.ok('error' in mockErrResponse, 'Must contain error message');
112
+ });
113
+ });
114
+ `;
115
+
116
+ // Ensure output tests directory exists
117
+ fs.mkdirSync(OUTPUT_DIR, { recursive: true });
118
+ const outputFilePath = path.join(OUTPUT_DIR, `${endpoint}.test.js`);
119
+ fs.writeFileSync(outputFilePath, testSuiteCode, 'utf8');
120
+
121
+ console.log(`✓ Executable TDD Integration Test Suite successfully generated:`);
122
+ console.log(` -> ${outputFilePath}`);
123
+
124
+ // Helper to generate mock data from properties
125
+ function generateMockData(props) {
126
+ const mock = {};
127
+ for (const [key, val] of Object.entries(props)) {
128
+ const type = val.type || 'string';
129
+ if (type === 'number') {
130
+ mock[key] = 123;
131
+ } else if (type === 'boolean') {
132
+ mock[key] = true;
133
+ } else if (type === 'array') {
134
+ mock[key] = [];
135
+ } else if (type === 'object') {
136
+ mock[key] = {};
137
+ } else {
138
+ mock[key] = 'mock_string_value';
139
+ }
140
+ }
141
+ return mock;
142
+ }