mindforge-cc 3.0.0 → 5.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 (114) hide show
  1. package/.agent/CLAUDE.md +50 -545
  2. package/.claude/CLAUDE.md +50 -545
  3. package/.mindforge/audit/AUDIT-SCHEMA.md +20 -1
  4. package/.mindforge/engine/nexus-tracer.js +115 -0
  5. package/.mindforge/engine/persona-factory.md +45 -0
  6. package/.mindforge/engine/swarm-controller.md +59 -0
  7. package/.mindforge/engine/wave-executor.md +104 -54
  8. package/.mindforge/memory/pattern-library.jsonl +1 -2
  9. package/.mindforge/personas/swarm-templates.json +118 -0
  10. package/.planning/ROI.jsonl +2 -0
  11. package/CHANGELOG.md +133 -22
  12. package/MINDFORGE.md +75 -106
  13. package/README.md +71 -101
  14. package/RELEASENOTES.md +41 -24
  15. package/bin/autonomous/auto-runner.js +154 -4
  16. package/bin/autonomous/context-refactorer.js +64 -0
  17. package/bin/autonomous/steer.js +19 -1
  18. package/bin/autonomous/stuck-monitor.js +43 -0
  19. package/bin/engine/feedback-loop.js +71 -0
  20. package/bin/engine/handover-manager.js +69 -0
  21. package/bin/engine/nexus-tracer.js +215 -0
  22. package/bin/engine/sre-manager.js +63 -0
  23. package/bin/engine/temporal-hindsight.js +88 -0
  24. package/bin/governance/policies/default-policies.jsonl +33 -0
  25. package/bin/governance/policy-engine.js +106 -0
  26. package/bin/governance/rbac-manager.js +109 -0
  27. package/bin/governance/trust-verifier.js +81 -0
  28. package/bin/governance/ztai-archiver.js +104 -0
  29. package/bin/governance/ztai-manager.js +203 -0
  30. package/bin/memory/eis-client.js +95 -0
  31. package/bin/memory/federated-sync.js +127 -0
  32. package/bin/memory/ghost-pattern-detector.js +69 -0
  33. package/bin/memory/knowledge-graph.js +37 -0
  34. package/bin/memory/semantic-hub.js +104 -0
  35. package/bin/models/cloud-broker.js +83 -0
  36. package/bin/models/finops-hub.js +79 -0
  37. package/bin/models/model-broker.js +129 -0
  38. package/bin/skill-validator.js +41 -0
  39. package/docs/INTELLIGENCE-MESH.md +35 -0
  40. package/docs/PERSONAS.md +63 -0
  41. package/docs/{references → References}/audit-events.md +6 -0
  42. package/docs/architecture/NEXUS-DASHBOARD.md +35 -0
  43. package/docs/architecture/PAR-ZTS-SURVEY.md +43 -0
  44. package/docs/architecture/README.md +31 -64
  45. package/docs/architecture/V4-SWARM-MESH.md +77 -0
  46. package/docs/architecture/V5-ENTERPRISE.md +113 -0
  47. package/docs/feature-dashboard.md +6 -1
  48. package/docs/governance-guide.md +47 -23
  49. package/docs/security/SECURITY.md +20 -7
  50. package/docs/security/ZTAI-OVERVIEW.md +37 -0
  51. package/docs/user-guide.md +29 -3
  52. package/docs/usp-features.md +79 -5
  53. package/package.json +1 -1
  54. /package/docs/{context → Context}/Master-Context.md +0 -0
  55. /package/docs/{references → References}/checkpoints.md +0 -0
  56. /package/docs/{references → References}/commands.md +0 -0
  57. /package/docs/{references → References}/config-reference.md +0 -0
  58. /package/docs/{references → References}/continuation-format.md +0 -0
  59. /package/docs/{references → References}/decimal-phase-calculation.md +0 -0
  60. /package/docs/{references → References}/git-integration.md +0 -0
  61. /package/docs/{references → References}/git-planning-commit.md +0 -0
  62. /package/docs/{references → References}/model-profile-resolution.md +0 -0
  63. /package/docs/{references → References}/model-profiles.md +0 -0
  64. /package/docs/{references → References}/phase-argument-parsing.md +0 -0
  65. /package/docs/{references → References}/planning-config.md +0 -0
  66. /package/docs/{references → References}/questioning.md +0 -0
  67. /package/docs/{references → References}/sdk-api.md +0 -0
  68. /package/docs/{references → References}/skills-api.md +0 -0
  69. /package/docs/{references → References}/tdd.md +0 -0
  70. /package/docs/{references → References}/ui-brand.md +0 -0
  71. /package/docs/{references → References}/user-profiling.md +0 -0
  72. /package/docs/{references → References}/verification-patterns.md +0 -0
  73. /package/docs/{references → References}/workstream-flag.md +0 -0
  74. /package/docs/{templates → Templates}/Agents/CLAUDE-MD.md +0 -0
  75. /package/docs/{templates → Templates}/Agents/COPILOT-INSTRUCTIONS.md +0 -0
  76. /package/docs/{templates → Templates}/Agents/DEBUGGER-PROMPT.md +0 -0
  77. /package/docs/{templates → Templates}/Agents/PLANNER-PROMPT.md +0 -0
  78. /package/docs/{templates/codebase → Templates/Codebase}/architecture.md +0 -0
  79. /package/docs/{templates/codebase → Templates/Codebase}/concerns.md +0 -0
  80. /package/docs/{templates/codebase → Templates/Codebase}/conventions.md +0 -0
  81. /package/docs/{templates/codebase → Templates/Codebase}/integrations.md +0 -0
  82. /package/docs/{templates/codebase → Templates/Codebase}/stack.md +0 -0
  83. /package/docs/{templates/codebase → Templates/Codebase}/structure.md +0 -0
  84. /package/docs/{templates/codebase → Templates/Codebase}/testing.md +0 -0
  85. /package/docs/{templates → Templates}/Execution/CONTINUE-HERE.md +0 -0
  86. /package/docs/{templates → Templates}/Execution/DISCUSSION-LOG.md +0 -0
  87. /package/docs/{templates → Templates}/Execution/PHASE-PROMPT.md +0 -0
  88. /package/docs/{templates → Templates}/Execution/STATE.md +0 -0
  89. /package/docs/{templates → Templates}/Execution/SUMMARY-COMPLEX.md +0 -0
  90. /package/docs/{templates → Templates}/Execution/SUMMARY-MINIMAL.md +0 -0
  91. /package/docs/{templates → Templates}/Execution/SUMMARY-STANDARD.md +0 -0
  92. /package/docs/{templates → Templates}/Execution/SUMMARY.md +0 -0
  93. /package/docs/{templates → Templates}/Profile/DEV-PREFERENCES.md +0 -0
  94. /package/docs/{templates → Templates}/Profile/USER-PROFILE.md +0 -0
  95. /package/docs/{templates → Templates}/Profile/USER-SETUP.md +0 -0
  96. /package/docs/{templates → Templates}/Project/DISCOVERY.md +0 -0
  97. /package/docs/{templates → Templates}/Project/MILESTONE-ARCHIVE.md +0 -0
  98. /package/docs/{templates → Templates}/Project/MILESTONE.md +0 -0
  99. /package/docs/{templates → Templates}/Project/PROJECT.md +0 -0
  100. /package/docs/{templates → Templates}/Project/REQUIREMENTS.md +0 -0
  101. /package/docs/{templates → Templates}/Project/RETROSPECTIVE.md +0 -0
  102. /package/docs/{templates → Templates}/Project/ROADMAP.md +0 -0
  103. /package/docs/{templates → Templates}/Quality/DEBUG.md +0 -0
  104. /package/docs/{templates → Templates}/Quality/UAT.md +0 -0
  105. /package/docs/{templates → Templates}/Quality/UI-SPEC.md +0 -0
  106. /package/docs/{templates → Templates}/Quality/VALIDATION.md +0 -0
  107. /package/docs/{templates → Templates}/Quality/VERIFICATION-REPORT.md +0 -0
  108. /package/docs/{templates/research → Templates/Research}/ARCHITECTURE.md +0 -0
  109. /package/docs/{templates/research → Templates/Research}/FEATURES.md +0 -0
  110. /package/docs/{templates/research → Templates/Research}/PITFALLS.md +0 -0
  111. /package/docs/{templates/research → Templates/Research}/STACK.md +0 -0
  112. /package/docs/{templates/research → Templates/Research}/SUMMARY.md +0 -0
  113. /package/docs/{templates → Templates}/System/CONFIG.json +0 -0
  114. /package/docs/{templates → Templates}/System/CONTEXT.md +0 -0
@@ -11,18 +11,34 @@ const stuckMonitor = require('./stuck-monitor');
11
11
  const steeringManager = require('./steer');
12
12
  const progressStream = require('./progress-stream');
13
13
  const headlessAdapter = require('./headless');
14
+ const ContextRefactorer = require('./context-refactorer');
14
15
  const KnowledgeCapture = require('../memory/knowledge-capture');
15
16
  const TemporalHub = require('../engine/temporal-hub');
16
17
  const crypto = require('crypto');
17
18
 
19
+ // MindForge v5 Core Modules
20
+ const PolicyEngine = require('../governance/policy-engine');
21
+ const RBACManager = require('../governance/rbac-manager');
22
+ const ZTAIManager = require('../governance/ztai-manager');
23
+ const HandoverManager = require('../engine/handover-manager');
24
+
18
25
  class AutoRunner {
19
26
  constructor(options = {}) {
20
27
  this.phase = options.phase;
21
28
  this.isHeadless = options.headless || false;
22
- this.auditPath = path.join(process.cwd(), '.planning/AUDIT.jsonl');
23
- this.statePath = path.join(process.cwd(), '.planning/auto-state.json');
29
+ this.auditPath = path.join(process.cwd(), '.planning', 'AUDIT.jsonl');
30
+ this.statePath = path.join(process.cwd(), '.planning', 'auto-state.json');
24
31
  this.monitor = new stuckMonitor(this.auditPath);
25
32
  this.isPaused = false;
33
+ this.handoverManager = new HandoverManager();
34
+
35
+ // v5 Governance Initialization
36
+ this.policyEngine = new PolicyEngine();
37
+ this.rbacManager = new RBACManager();
38
+
39
+ // v5 PAR Initialization
40
+ this.refactorer = new ContextRefactorer();
41
+ this.c2cThreshold = 0.65;
26
42
  }
27
43
 
28
44
  async run() {
@@ -38,10 +54,33 @@ class AutoRunner {
38
54
  // 2. Main Wave Loop
39
55
  while (await this.hasNextWave()) {
40
56
  if (this.isPaused) break;
57
+
58
+ // Pillar 2 (APO): Pre-execution Policy Check
59
+ const permit = await this.evaluateWavePolicy();
60
+ if (!permit) {
61
+ console.error('🛑 POLICY VIOLATION: Execution aborted by Agentic Policy Orchestrator.');
62
+ this.writeAudit({ event: 'auto_mode_denied', reason: 'Policy violation detected' });
63
+ break;
64
+ }
65
+
66
+ // Pillar 3 (PAR): Confidence-to-Cost Arbitrage
67
+ const isReliable = await this.checkArbitrage();
68
+ if (!isReliable) {
69
+ console.warn('⚠️ PAR ARBITRAGE: Confidence-to-Cost ratio below threshold. Escalating to human.');
70
+ this.writeAudit({ event: 'auto_mode_escalated', reason: 'Low C2C ratio' });
71
+ break;
72
+ }
73
+
74
+ // Pillar 3 (PAR): Context Density Refactoring
75
+ await this.checkContextDensity();
76
+
77
+ // Pillar 7 (DHH): Check for Human Steering
78
+ await this.checkHumanSteering(isReliable);
79
+
41
80
  await this.executeWave();
42
81
  }
43
82
 
44
- this.complete();
83
+ await this.complete();
45
84
  }
46
85
 
47
86
  runPreFlight() {
@@ -65,11 +104,20 @@ class AutoRunner {
65
104
  this.writeAudit({ event: 'auto_mode_paused', timestamp: new Date().toISOString() });
66
105
  }
67
106
 
68
- complete() {
107
+ async complete() {
69
108
  console.log('✅ Phase complete!');
70
109
  const report = progressStream.generateReport(this.auditPath, this.phase);
71
110
  fs.writeFileSync(path.join(process.cwd(), `.planning/phases/${this.phase}/AUTONOMOUS-REPORT.md`), report);
72
111
 
112
+ // v5 Pillar 1: Federated Intelligence Mesh (FIM)
113
+ try {
114
+ const { runSync } = require('../memory/federated-sync');
115
+ console.log('🔄 Finalizing organizational intelligence sync...');
116
+ await runSync();
117
+ } catch (err) {
118
+ console.warn('⚠️ Federated Sync failed at phase end:', err.message);
119
+ }
120
+
73
121
  // Auto-capture knowledge from completed phase (ADRs, findings)
74
122
  try {
75
123
  const captured = KnowledgeCapture.captureFromPhaseCompletion(this.phase);
@@ -125,6 +173,108 @@ class AutoRunner {
125
173
  Object.assign(state, update);
126
174
  fs.writeFileSync(this.statePath, JSON.stringify(state, null, 2));
127
175
  }
176
+
177
+ /**
178
+ * Evaluates the policy for the next wave's intent. (v5 APO - HARDENED)
179
+ */
180
+ async evaluateWavePolicy() {
181
+ // [HARDEN] Dynamically derive intent from ZTAI identity and phase context
182
+ const manager = new ZTAIManager();
183
+ const identity = await manager.getIdentity();
184
+
185
+ const intent = {
186
+ did: identity.did,
187
+ action: 'process_phase_wave',
188
+ resource: `projects/${process.env.MF_PROJECT_ID || 'MF-ALPHA'}/phases/${this.phase}/*`,
189
+ tier: identity.tier || 1,
190
+ metadata: {
191
+ engine: 'Nimbus-S4',
192
+ mode: 'autonomous',
193
+ wave_timestamp: new Date().toISOString()
194
+ }
195
+ };
196
+
197
+ const result = this.policyEngine.evaluate(intent);
198
+
199
+ if (result.verdict === 'DENY') {
200
+ console.warn(`[APO-DENY] Intent rejected: ${result.reason} [ReqID: ${result.requestId}]`);
201
+ return false;
202
+ }
203
+
204
+ console.log(`[APO-PERMIT] Intent approved: ${result.reason} [ReqID: ${result.requestId}]`);
205
+ return true;
206
+ }
207
+
208
+ /**
209
+ * Predictive Agentic Reliability (PAR) - C2C Arbitrage
210
+ */
211
+ async checkArbitrage() {
212
+ // Simulated C2C calculation based on recent wave success rate
213
+ const events = this.getRecentAuditEvents(10);
214
+ const successCount = events.filter(e => e.status === 'success' || e.event === 'task_completed').length;
215
+
216
+ // Confidence = SuccessRate * 0.8 + 0.2
217
+ const confidence = (successCount / Math.max(events.length, 1)) * 0.8 + 0.2;
218
+ const estimatedCost = 0.5; // Placeholder for token cost estimation
219
+
220
+ const c2c = confidence / estimatedCost;
221
+ console.log(`[PAR-C2C] Confidence: ${confidence.toFixed(2)}, Cost: ${estimatedCost.toFixed(2)}, Ratio: ${c2c.toFixed(2)}`);
222
+
223
+ return c2c >= this.c2cThreshold;
224
+ }
225
+
226
+ /**
227
+ * Predictive Agentic Reliability (PAR) - Context Refactoring
228
+ */
229
+ async checkContextDensity() {
230
+ const events = this.getRecentAuditEvents(20);
231
+ const analysis = this.refactorer.analyzeDensity(events);
232
+
233
+ if (analysis.shouldRefactor) {
234
+ console.log(`[PAR-REFACTOR] Context density low (${analysis.density}). Triggering proactive refactor.`);
235
+ const refactorEvent = this.refactorer.generateRefactorPlan(events, this.phase);
236
+ this.writeAudit(refactorEvent);
237
+
238
+ // In a real implementation, this would trigger a system_handoff summarization
239
+ // For now, we log it to the audit stream for the agent to action
240
+ }
241
+ }
242
+
243
+ async checkHumanSteering(isReliable) {
244
+ if (!isReliable) {
245
+ console.log('[DHH-AUTO] Low reliability detected. Packaging Nexus State Bundle for human review...');
246
+ const events = this.getRecentAuditEvents(20);
247
+ const bundlePath = this.handoverManager.createNexusBundle({
248
+ phase: this.phase,
249
+ wave: 'active',
250
+ recentEvents: events,
251
+ reasoningTrace: 'Reasoning isolated in SRE.'
252
+ });
253
+
254
+ this.writeAudit({
255
+ event: 'human_handover_requested',
256
+ bundle: bundlePath,
257
+ timestamp: new Date().toISOString()
258
+ });
259
+ }
260
+
261
+ // Check for mid-wave steering instructions if available
262
+ const steerPath = path.join(process.cwd(), '.planning', 'STEER.json');
263
+ if (fs.existsSync(steerPath)) {
264
+ const instructions = fs.readFileSync(steerPath, 'utf8').trim().split('\n');
265
+ if (instructions.length > 0) {
266
+ console.log(`[DHH-STEER] Processing ${instructions.length} injected human instructions...`);
267
+ // Real implementation would inject these into the agent's task list
268
+ fs.unlinkSync(steerPath); // Clear handled instructions
269
+ }
270
+ }
271
+ }
272
+
273
+ getRecentAuditEvents(count) {
274
+ if (!fs.existsSync(this.auditPath)) return [];
275
+ const lines = fs.readFileSync(this.auditPath, 'utf8').trim().split('\n');
276
+ return lines.slice(-count).map(l => JSON.parse(l));
277
+ }
128
278
  }
129
279
 
130
280
  module.exports = AutoRunner;
@@ -0,0 +1,64 @@
1
+ /**
2
+ * MindForge — Context Refactorer Engine (v5.0.0-PAR)
3
+ * Monitors context density and triggers proactive summarization/refactoring.
4
+ */
5
+ 'use strict';
6
+
7
+ const fs = require('fs');
8
+ const path = require('path');
9
+
10
+ class ContextRefactorer {
11
+ constructor(options = {}) {
12
+ this.threshold = options.threshold || 0.3; // Min density before refactor
13
+ this.windowSize = options.windowSize || 20;
14
+ this.history = [];
15
+ }
16
+
17
+ /**
18
+ * Analyze the current context density.
19
+ * Density = (Implementation Events) / (Total Events)
20
+ */
21
+ analyzeDensity(events) {
22
+ this.history = events.slice(-this.windowSize);
23
+
24
+ if (this.history.length < 5) return { density: 1.0, shouldRefactor: false };
25
+
26
+ const implementationEvents = this.history.filter(h =>
27
+ h.tool === 'run_command' ||
28
+ h.tool === 'replace_file_content' ||
29
+ h.tool === 'multi_replace_file_content' ||
30
+ h.event === 'task_completed'
31
+ );
32
+
33
+ const totalEvents = this.history.length;
34
+ const density = implementationEvents.length / totalEvents;
35
+
36
+ return {
37
+ density: parseFloat(density.toFixed(2)),
38
+ shouldRefactor: density < this.threshold
39
+ };
40
+ }
41
+
42
+ /**
43
+ * Generates a "Context Refactor" recommendation.
44
+ */
45
+ generateRefactorPlan(events, phase) {
46
+ const reasoningChain = events
47
+ .filter(e => e.event === 'reasoning_trace')
48
+ .map(e => `- ${e.thought}`)
49
+ .join('\n');
50
+
51
+ return {
52
+ event: 'context_refactor_triggered',
53
+ phase,
54
+ message: 'Context density low. Initiating proactive refactoring.',
55
+ action: 'SUMMARIZE_AND_RESET',
56
+ payload: {
57
+ summary_prompt: `The current reasoning chain has become dense (${this.threshold}). Summarize the progress for Phase ${phase} and reset the active context window.`,
58
+ trace_sample: reasoningChain.slice(-500) // Last few thoughts for context
59
+ }
60
+ };
61
+ }
62
+ }
63
+
64
+ module.exports = ContextRefactorer;
@@ -64,8 +64,26 @@ function injectSteering(planContent, guidanceItems) {
64
64
  });
65
65
  }
66
66
 
67
+ /**
68
+ * Add human steering to the unified queue (v5 Pillar VII).
69
+ */
70
+ function pushHumanSteering(instruction, bundleId = 'none') {
71
+ const STEER_PATH = path.join(process.cwd(), '.planning', 'STEER.json');
72
+ const item = {
73
+ id: `human-${Date.now()}`,
74
+ timestamp: new Date().toISOString(),
75
+ bundle_id: bundleId,
76
+ type: 'HUMAN_OVERRIDE',
77
+ instruction,
78
+ priority: 'CRITICAL'
79
+ };
80
+ fs.appendFileSync(STEER_PATH, JSON.stringify(item) + '\n');
81
+ return item.id;
82
+ }
83
+
67
84
  module.exports = {
68
85
  pushGuidance,
69
86
  popGuidance,
70
- injectSteering
87
+ injectSteering,
88
+ pushHumanSteering
71
89
  };
@@ -26,9 +26,52 @@ class StuckMonitor {
26
26
  // Check S02: Command Loop (Identical failing commands)
27
27
  if (this.detectS02(event)) return { pattern: 'S02', message: 'Stuck in command loop: identical failing commands.' };
28
28
 
29
+ // Check S03: Semantic Mirroring (Reasoning Loop)
30
+ if (this.detectS03(event)) return { pattern: 'S03', message: 'Stuck in reasoning loop: semantic mirroring detected.' };
31
+
32
+ // Check S04: Infinite Decomposition (Planning Paradox)
33
+ if (this.detectS04(event)) return { pattern: 'S04', message: 'Stuck in planning paradox: infinite decomposition detected.' };
34
+
29
35
  return null;
30
36
  }
31
37
 
38
+ detectS03(event) {
39
+ if (event.event !== 'reasoning_trace') return false;
40
+
41
+ // Compare with the last 5 thoughts in history
42
+ const reflections = this.history.filter(h => h.event === 'reasoning_trace');
43
+ if (reflections.length < 3) return false;
44
+
45
+ const currentThought = event.thought;
46
+ const previousThoughts = reflections.slice(-4, -1);
47
+
48
+ const isMirroring = previousThoughts.some(p =>
49
+ this.isContentSimilar(p.thought, currentThought)
50
+ );
51
+
52
+ return isMirroring;
53
+ }
54
+
55
+ detectS04(event) {
56
+ if (event.event !== 'reasoning_trace') return false;
57
+
58
+ const decompositions = this.history.filter(h =>
59
+ h.event === 'reasoning_trace' &&
60
+ (h.thought?.toLowerCase().includes('break down') || h.thought?.toLowerCase().includes('sub-task'))
61
+ );
62
+
63
+ // If more than 4 consecutive decompositions without a command or edit
64
+ const lastActionIndex = this.history.findLastIndex(h =>
65
+ h.tool === 'run_command' || h.tool === 'replace_file_content' || h.tool === 'multi_replace_file_content'
66
+ );
67
+
68
+ const recentDecomps = decompositions.filter(d =>
69
+ this.history.indexOf(d) > lastActionIndex
70
+ );
71
+
72
+ return recentDecomps.length >= 4;
73
+ }
74
+
32
75
  detectS01(event) {
33
76
  if (event.tool !== 'multi_replace_file_content') return false;
34
77
 
@@ -0,0 +1,71 @@
1
+ /**
2
+ * MindForge — WaveFeedbackLoop (Pillar VI: Proactive Equilibrium)
3
+ * Monitors divergence during wave execution and triggers self-healing.
4
+ */
5
+
6
+ class WaveFeedbackLoop {
7
+ constructor(config = {}) {
8
+ this.failureThreshold = config.failureThreshold || 0.20; // 20% failure rate
9
+ this.divergenceWeight = config.divergenceWeight || 1.5; // Bias for rapid divergence
10
+ this.waveState = {
11
+ completed: 0,
12
+ failed: 0,
13
+ skipped: 0,
14
+ total: 0,
15
+ };
16
+ }
17
+
18
+ /**
19
+ * Updates the feedback loop with a task result.
20
+ */
21
+ update(result) {
22
+ this.waveState.total++;
23
+ if (result.status === 'completed') {
24
+ this.waveState.completed++;
25
+ } else if (result.status === 'failed') {
26
+ this.waveState.failed++;
27
+ } else {
28
+ this.waveState.skipped++;
29
+ }
30
+ }
31
+
32
+ /**
33
+ * Calculates the current divergence rate.
34
+ * @returns {number} - 0.0 to 1.0 divergence rate.
35
+ */
36
+ calculateDivergence() {
37
+ if (this.waveState.total === 0) return 0;
38
+ const failureRate = this.waveState.failed / this.waveState.total;
39
+ const skippedRate = this.waveState.skipped / this.waveState.total;
40
+
41
+ // Divergence includes failures and unexpected skips
42
+ return (failureRate + (skippedRate * 0.5));
43
+ }
44
+
45
+ /**
46
+ * Determines if the wave is "Diverging" and needs autonomous recovery.
47
+ * @returns {Object} - Result (shouldPause, reason)
48
+ */
49
+ shouldTriggerHindsight() {
50
+ const divergence = this.calculateDivergence();
51
+ const minSample = 5; // Start checking after 5 tasks to avoid noise
52
+
53
+ if (this.waveState.total < minSample) return { shouldPause: false };
54
+
55
+ if (divergence >= this.failureThreshold) {
56
+ return {
57
+ shouldPause: true,
58
+ divergence: divergence.toFixed(2),
59
+ reason: `Wave Divergence reached critical threshold (${(divergence * 100).toFixed(0)}%). Triggering Temporal Hindsight for RCA and repair.`,
60
+ };
61
+ }
62
+
63
+ return { shouldPause: false };
64
+ }
65
+
66
+ reset() {
67
+ this.waveState = { completed: 0, failed: 0, skipped: 0, total: 0 };
68
+ }
69
+ }
70
+
71
+ module.exports = WaveFeedbackLoop;
@@ -0,0 +1,69 @@
1
+ /**
2
+ * MindForge — HandoverManager (Pillar VII: Dynamic Human-Agent Handover)
3
+ * Packages Nexus State Bundles for bidirectional steering and human escalation.
4
+ */
5
+ 'use strict';
6
+
7
+ const fs = require('fs');
8
+ const path = require('path');
9
+ const crypto = require('crypto');
10
+
11
+ class HandoverManager {
12
+ constructor(config = {}) {
13
+ this.handoffPath = path.join(process.cwd(), '.planning', 'handoffs');
14
+ }
15
+
16
+ /**
17
+ * Packages a Nexus State Bundle for human review.
18
+ * @param {Object} state - Current execution state (audit, memory, goals)
19
+ * @returns {string} - Path to the state bundle.
20
+ */
21
+ createNexusBundle(state) {
22
+ if (!fs.existsSync(this.handoffPath)) {
23
+ fs.mkdirSync(this.handoffPath, { recursive: true });
24
+ }
25
+
26
+ const bundleId = `bundle_${crypto.randomBytes(6).toString('hex')}`;
27
+ const bundle = {
28
+ id: bundleId,
29
+ timestamp: new Date().toISOString(),
30
+ version: '5.0.0-nexus',
31
+ context: {
32
+ phase: state.phase,
33
+ wave: state.wave,
34
+ last_events: state.recentEvents,
35
+ memory_shards: state.memoryShards || []
36
+ },
37
+ reasoning_snapshot: state.reasoningTrace,
38
+ steering_requirements: state.blocks || []
39
+ };
40
+
41
+ const bundlePath = path.join(this.handoffPath, `${bundleId}.json`);
42
+ fs.writeFileSync(bundlePath, JSON.stringify(bundle, null, 2));
43
+
44
+ console.log(`[DHH-BUNDLE] Nexus State Bundle packaged: ${bundlePath}`);
45
+ return bundlePath;
46
+ }
47
+
48
+ /**
49
+ * Injects human steering into the agentic flow.
50
+ * @param {string} bundleId - The bundle being steered.
51
+ * @param {Object} steeringRequest - Human instructions/overrides.
52
+ */
53
+ injectSteering(bundleId, steeringRequest) {
54
+ const steerPath = path.join(process.cwd(), '.planning', 'STEER.json');
55
+ const instruction = {
56
+ id: crypto.randomUUID(),
57
+ timestamp: new Date().toISOString(),
58
+ bundle_id: bundleId,
59
+ type: 'HUMAN_OVERRIDE',
60
+ instruction: steeringRequest.instruction,
61
+ priority: 'CRITICAL'
62
+ };
63
+
64
+ fs.appendFileSync(steerPath, JSON.stringify(instruction) + '\n');
65
+ console.log(`[DHH-STEER] Human instruction injected into autonomous stream [Ref: ${bundleId}]`);
66
+ }
67
+ }
68
+
69
+ module.exports = HandoverManager;
@@ -0,0 +1,215 @@
1
+ /**
2
+ * MindForge Nexus — Core Tracer Engine (v4.1.0-alpha.nexus)
3
+ *
4
+ * Handles Agentic Reasoning Tracing (ART) spans and OpenTelemetry-compatible
5
+ * trace context propagation across the agentic mesh.
6
+ */
7
+
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+ const crypto = require('crypto');
11
+ const ztai = require('../governance/ztai-manager');
12
+ const SREManager = require('./sre-manager');
13
+
14
+ class NexusTracer {
15
+ constructor(config = {}) {
16
+ this.projectId = config.projectId || 'mindforge-nexus';
17
+ this.auditPath = config.auditPath || path.join(process.cwd(), '.planning', 'AUDIT.jsonl');
18
+ this.currentTraceId = null;
19
+ this.activeSpans = new Map();
20
+ this.did = config.did || null; // Active Agent DID
21
+ this.enableZtai = config.enableZtai !== false;
22
+ this.sreManager = new SREManager();
23
+
24
+ // v5 Pillar IV: Agentic SBOM
25
+ this.sbom = {
26
+ manifest_version: '1.0.0',
27
+ models: new Set(),
28
+ skills: new Set(),
29
+ startTime: new Date().toISOString()
30
+ };
31
+ }
32
+
33
+ /**
34
+ * Initialize or resume a trace.
35
+ */
36
+ startTrace(traceId = null) {
37
+ this.currentTraceId = traceId || `tr_${crypto.randomBytes(8).toString('hex')}`;
38
+ return this.currentTraceId;
39
+ }
40
+
41
+ /**
42
+ * Start a new ART span.
43
+ */
44
+ startSpan(name, attributes = {}, parentSpanId = null) {
45
+ const spanId = `sp_${crypto.randomBytes(6).toString('hex')}`;
46
+ const startTime = new Date().toISOString();
47
+
48
+ const span = {
49
+ id: spanId,
50
+ trace_id: this.currentTraceId,
51
+ parent_id: parentSpanId || null,
52
+ name,
53
+ status: 'active',
54
+ start_time: startTime,
55
+ attributes: {
56
+ ...attributes,
57
+ service: 'mindforge-nexus',
58
+ }
59
+ };
60
+
61
+ this.activeSpans.set(spanId, span);
62
+
63
+ // Track model and skill in SBOM if provided in attributes
64
+ if (attributes.model_id) this.sbom.models.add(attributes.model_id);
65
+ if (attributes.skill) this.sbom.skills.add(attributes.skill);
66
+
67
+ // v5 Pillar VI: Enclave Check
68
+ if (attributes.is_confidential && !attributes.enclave_id) {
69
+ try {
70
+ span.attributes.enclave_id = this.sreManager.initializeEnclave({
71
+ tier: attributes.tier || 1,
72
+ did: this.did
73
+ });
74
+ } catch (err) {
75
+ console.warn(`[NexusTracer] Failed to initialize SRE for confidential span: ${err.message}`);
76
+ }
77
+ }
78
+
79
+ // Record span start in AUDIT.jsonl
80
+ this._recordEvent('span_started', {
81
+ span_id: spanId,
82
+ parent_span_id: parentSpanId,
83
+ span_name: name,
84
+ ...attributes,
85
+ enclave_id: span.attributes.enclave_id
86
+ });
87
+
88
+ return spanId;
89
+ }
90
+
91
+ /**
92
+ * End an active span.
93
+ */
94
+ endSpan(spanId, status = 'success', metadata = {}) {
95
+ const span = this.activeSpans.get(spanId);
96
+ if (!span) return;
97
+
98
+ span.status = status;
99
+ span.end_time = new Date().toISOString();
100
+
101
+ // v5 Pillar VI: Enclave Termination
102
+ if (span.attributes.enclave_id) {
103
+ this.sreManager.terminateEnclave(span.attributes.enclave_id);
104
+ }
105
+
106
+ this._recordEvent('span_completed', {
107
+ span_id: spanId,
108
+ status,
109
+ ...metadata
110
+ });
111
+
112
+ this.activeSpans.delete(spanId);
113
+ }
114
+
115
+ /**
116
+ * Record a Reasoning Trace event (ART granularity).
117
+ */
118
+ recordReasoning(spanId, agent, thought, resolution = 'none') {
119
+ const span = this.activeSpans.get(spanId);
120
+ let sanitizedThought = thought;
121
+
122
+ if (span && span.attributes.enclave_id) {
123
+ sanitizedThought = this.sreManager.sanitizeThoughtChain(thought, span.attributes.enclave_id);
124
+ }
125
+
126
+ this._recordEvent('reasoning_trace', {
127
+ span_id: spanId,
128
+ agent,
129
+ thought: sanitizedThought,
130
+ resolution
131
+ });
132
+ }
133
+
134
+ /**
135
+ * Internal AUDIT writer.
136
+ */
137
+ _recordEvent(event, data) {
138
+ const entry = {
139
+ id: crypto.randomUUID(),
140
+ timestamp: new Date().toISOString(),
141
+ event,
142
+ trace_id: this.currentTraceId,
143
+ ...data
144
+ };
145
+
146
+ // ZTAI Signing Logic
147
+ if (this.enableZtai && this.did) {
148
+ try {
149
+ entry.did = this.did;
150
+ // Sign the stringified entry WITHOUT the signature field itself
151
+ const payload = JSON.stringify(entry);
152
+ entry.signature = ztai.signData(this.did, payload);
153
+ } catch (err) {
154
+ console.warn(`[NexusTracer] ZTAI signing failed: ${err.message}`);
155
+ }
156
+ }
157
+
158
+ try {
159
+ if (!fs.existsSync(path.dirname(this.auditPath))) {
160
+ fs.mkdirSync(path.dirname(this.auditPath), { recursive: true });
161
+ }
162
+ fs.appendFileSync(this.auditPath, JSON.stringify(entry) + '\n');
163
+ } catch (err) {
164
+ console.error(`[NexusTracer] Failed to write audit entry: ${err.message}`);
165
+ }
166
+ }
167
+
168
+ /**
169
+ * Records a FinOps budget decision (Pillar V).
170
+ */
171
+ recordFinOps(spanId, decision) {
172
+ this._recordEvent('finops_decision', {
173
+ span_id: spanId,
174
+ ...decision
175
+ });
176
+ }
177
+
178
+ /**
179
+ * Records a Self-Healing trigger event (Pillar VI).
180
+ */
181
+ recordSelfHeal(spanId, report) {
182
+ this._recordEvent('self_heal_trigger', {
183
+ span_id: spanId,
184
+ ...report
185
+ });
186
+ }
187
+
188
+ /**
189
+ * Finalize and export the Agentic SBOM (Pillar IV).
190
+ */
191
+ exportSBOM(outputPath = null) {
192
+ const finalPath = outputPath || path.join(process.cwd(), '.planning', 'MANIFEST.sbom.json');
193
+ const manifest = {
194
+ ...this.sbom,
195
+ models: Array.from(this.sbom.models),
196
+ skills: Array.from(this.sbom.skills),
197
+ endTime: new Date().toISOString()
198
+ };
199
+
200
+ try {
201
+ if (!fs.existsSync(path.dirname(finalPath))) {
202
+ fs.mkdirSync(path.dirname(finalPath), { recursive: true });
203
+ }
204
+ fs.writeFileSync(finalPath, JSON.stringify(manifest, null, 2));
205
+
206
+ this._recordEvent('sbom_exported', { path: finalPath });
207
+ return finalPath;
208
+ } catch (err) {
209
+ console.error(`[NexusTracer] Failed to export SBOM: ${err.message}`);
210
+ return null;
211
+ }
212
+ }
213
+ }
214
+
215
+ module.exports = NexusTracer;