mindforge-cc 3.0.0 → 4.3.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.
package/MINDFORGE.md CHANGED
@@ -1,110 +1,79 @@
1
- # MINDFORGE.md — Project Constitution
2
-
3
- ## NON-OVERRIDABLE RULES (read-only — these cannot be changed in MINDFORGE.md)
4
-
5
- The following CLAUDE.md behaviors are governance primitives and cannot be
6
- disabled or overridden by MINDFORGE.md:
7
-
8
- - Security auto-trigger for auth/payment/PII changes
9
- - Plan-first rule (no implementation without a PLAN)
10
- - Secret detection gate
11
- - AUDIT writing requirement
12
- - Critical security and secret-related quality gates
13
-
14
- Any attempted override is ignored and logged.
15
-
16
- ## Parsing rule for multiline values
17
- Values wrapped in triple quotes are parsed as a verbatim multi-line string from
18
- the first `"""` to the next `"""`.
19
-
20
- ## Model validation
21
- If a configured model is unavailable, fallback to `inherit` and warn.
22
-
23
- ## Project identity
24
- NAME=MindForge
25
- VERSION=2.0.0
26
- DESCRIPTION=Enterprise agentic framework with Multi-Model Intelligence Layer
27
- MINDFORGE_VERSION_REQUIRED=2.0.0
28
-
29
- ## Model preferences
30
- PLANNER_MODEL=claude-opus-4-5
31
- EXECUTOR_MODEL=claude-sonnet-4-5
32
- REVIEWER_MODEL=claude-sonnet-4-5
33
- VERIFIER_MODEL=claude-sonnet-4-5
34
- SECURITY_MODEL=claude-opus-4-5
35
- DEBUG_MODEL=claude-opus-4-5
36
- RESEARCH_MODEL=gemini-1.5-pro
37
- QA_MODEL=claude-4-5-sonnet
38
- QUICK_MODEL=claude-4-5-haiku
39
-
40
- ## Cost Management
41
- MODEL_COST_WARN_USD=1.00
42
- MODEL_COST_HARD_LIMIT_USD=10.00
43
- MODEL_PREFER_CHEAP_BELOW_DIFFICULTY=2.0
44
- REQUIRE_CROSS_REVIEW=false
45
-
46
- ## Execution behavior
47
- TIER1_AUTO_APPROVE=true
48
- WAVE_CONFIRMATION_REQUIRED=false
49
- AUTO_DISCUSS_PHASE=false
50
- VERIFY_PASS_RATE_WARNING_THRESHOLD=0.75
51
- COMPACTION_THRESHOLD_PCT=70
52
- MAX_TASKS_PER_PHASE=15
53
-
54
- ## Quality standards
55
- MIN_TEST_COVERAGE_PCT=80
56
- MAX_FUNCTION_LINES=40
57
- MAX_CYCLOMATIC_COMPLEXITY=10
58
- REQUIRE_ADR_FOR_ALL_DECISIONS=false
59
- BLOCK_ON_MEDIUM_SECURITY_FINDINGS=false
60
-
61
- ## Skills behavior
62
- ALWAYS_LOAD_SKILLS=security-review
63
- DISABLED_SKILLS=
64
- MAX_FULL_SKILL_INJECTIONS=3
65
-
66
- ## Governance
67
- DISCUSS_PHASE_REQUIRED_ABOVE_DIFFICULTY=3.5
68
- ANTIPATTERN_SENSITIVITY=standard
69
- BLOCK_ON_HIGH_ANTIPATTERNS=false
70
-
71
- ## Autonomous mode settings
72
- AUTO_MODE_DEFAULT_TIMEOUT_MINUTES=120
73
- AUTO_PUSH_ON_WAVE_COMPLETE=false
74
- AUTO_NODE_REPAIR_BUDGET=2
75
- AUTO_PLAN_AMBIGUITY_THRESHOLD=3.5
76
- SLACK_WEBHOOK_URL=
77
-
78
- ## Browser Runtime
79
- BROWSER_PORT=7338
80
- BROWSER_HEADLESS=true
81
- DEV_SERVER_URL=http://localhost:3000
82
- AUTO_RUN_QA_AFTER_UI_WAVES=true
83
- BROWSER_IDLE_TIMEOUT_MINUTES=30
84
- AUTO_RUN_UI_REVIEW_AFTER_UI_WAVES=true
85
- UI_PHASE_ACCESSIBILITY_STANDARD=WCAG_AA
86
-
87
- ## Project-specific agent instructions
88
- ADDITIONAL_AGENT_INSTRUCTIONS="""
89
- - Check packages/shared before creating utilities.
90
- - Backend middleware semantics follow Fastify conventions.
91
- - Keep dependency direction one-way from frontend to backend APIs.
92
- - Prefer date-fns for date manipulation.
93
- """
94
-
95
- ## Project-specific forbidden patterns
96
- PROJECT_FORBIDDEN_PATTERNS="""
97
- - No direct DB access from frontend packages
1
+ # MINDFORGE.md — Parameter Registry (v4.1.0-alpha.nexus)
2
+
3
+ ## 1. IDENTITY & VERSIONING
4
+
5
+ [NAME] = MindForge
6
+ [VERSION] = 4.2.0-alpha.ztai
7
+ [STABLE] = false
8
+ [MODE] = "Zero-Trust Identity"
9
+ [REQUIRED_CORE_VERSION] = 4.2.0
10
+
11
+ ## 2. INTELLIGENCE TOGGLES (V4 UPDATES)
12
+
13
+ [SWARM_ORCHESTRATION] = true
14
+ [AUTO_SWARM_THRESHOLD] = 7.0
15
+ [CONTEXT7_DEPTH] = "EXTENDED"
16
+ [DYNAMISM_LEVEL] = 5
17
+ [REACTIVE_MODE] = true
18
+ [CONTEXT_SHARDING] = true
19
+ [ADS_LOOP_ENFORCED] = true
20
+ [TEMPORAL_VISION] = true
21
+ [RAG_2_AUTO_SHADOW] = true
22
+ [ENABLE_ART_TRACING] = true
23
+ [ENABLE_ZTAI] = true
24
+ [ZTAI_KEY_TYPE] = "Ed25519"
25
+ [NEXUS_TRACE_RETENTION_DAYS] = 30
26
+
27
+ ---
28
+
29
+ ## 3. MODEL TOPOLOGY
30
+
31
+ # Persona to Model mapping
32
+ [PLANNER] = claude-opus-4-5
33
+ [EXECUTOR] = claude-sonnet-4-5
34
+ [REVIEWER] = claude-sonnet-4-5
35
+ [VERIFIER] = claude-sonnet-4-5
36
+ [SECURITY] = claude-opus-4-5
37
+ [DEBUG] = claude-opus-4-5
38
+ [RESEARCH] = gemini-1.5-pro
39
+ [QA] = claude-4-5-sonnet
40
+
41
+ ---
42
+
43
+ ## 4. GOVERNANCE & ECONOMICS
44
+
45
+ # Limits and safety gates
46
+ [COST_WARN_USD] = 2.00
47
+ [COST_HARD_LIMIT_USD] = 25.00
48
+ [ADS_DEBATE_ROUNDS] = 2
49
+ [MIN_SOUL_SCORE] = 7.0
50
+ [REQUIRE_ADR] = true
51
+ [BLOCK_ON_SECURITY] = true
52
+
53
+ ---
54
+
55
+ ## 5. RESOURCE GEOMETRY
56
+
57
+ # Paths and ports
58
+ [BROWSER_PORT] = 7338
59
+ [DASHBOARD_PORT] = 7339
60
+ [API_URL] = <http://localhost:3000>
61
+ [SHARD_RETAIN_DAYS] = 7
62
+
63
+ ---
64
+
65
+ ## 6. PROJECT CONSTRAINTS
66
+
67
+ # Static rules for the agent
68
+ [FORBIDDEN] = """
69
+ - No direct DB access from frontend
98
70
  - No synchronous I/O in API handlers
99
- - No console.log in API services
71
+ - No console.log in production services
100
72
  - No TODO comments in committed code
101
73
  """
102
74
 
103
- ## Self-Building Skills
104
- AUTO_CAPTURE_SKILLS=false
105
- AUTO_CAPTURE_MIN_PATTERN_COUNT=2
106
- AUTO_CAPTURE_MIN_CONFIDENCE=0.75
107
- LEARN_MODEL=inherit
108
- MARKETPLACE_REGISTRY=https://registry.mindforge.dev/v1
109
- MARKETPLACE_DAILY_FETCH_LIMIT=50
110
- SKILL_QUALITY_MIN_SCORE=60
75
+ [INSTRUCTIONS] = """
76
+ - Check packages/shared before creating utilities.
77
+ - Backend middleware follows Fastify conventions.
78
+ - Date manipulation using date-fns only.
79
+ """
package/README.md CHANGED
@@ -1,17 +1,17 @@
1
- # MindForge — Enterprise Agentic Framework (v3.0.0-rc1)
1
+ # MindForge — Enterprise Agentic Framework (v4.2.5)
2
2
 
3
3
  MindForge turns Claude Code and Antigravity into production-grade engineering
4
4
  partners with governance, observability, and a reactive autonomous intelligence engine.
5
- Release published: v3.0.0-rc1.
5
+ Release published: v4.1.0-alpha.nexus.
6
6
 
7
7
  # Install
8
8
  ```bash
9
- npx mindforge-cc@latest
9
+ npx mindforge-cc@v4-alpha
10
10
  ```
11
11
 
12
- # Install V3 (Latest)
12
+ # Install V4 (Experimental)
13
13
  ```bash
14
- npm install -g mindforge-cc@latest
14
+ npm install -g mindforge-cc@v4-alpha
15
15
  ```
16
16
 
17
17
  ---
@@ -21,6 +21,10 @@ npm install -g mindforge-cc@latest
21
21
  AI coding agents degrade over long sessions. Context fills up. Quality drops.
22
22
  Decisions get forgotten. MindForge fixes that with:
23
23
 
24
+ - **MindForge Nexus (v4.1)** — High-fidelity **ART** (Agentic Reasoning Tracing) for the agentic mesh
25
+ - **Dynamic Swarm Orchestration (v4)** — parallel "Agentic Mesh" with shared state (v4)
26
+ - **Zero-Trust Identity (v4.2)** — DID-signed non-repudiable audit logs with HSM/Enclave support (v4.2.5)
27
+ - **Global Intelligence Mesh (v4.2)** — Cross-repo knowledge sharing and Ghost Pattern Detection (v4.2.5)
24
28
  - **Context Sharding (v3)** — relevance-dense memory management (40% token savings)
25
29
  - **Adversarial Synthesis (v3)** — zero-drift logic through red/blue model debate
26
30
  - **Temporal Vision (v3)** — full history scrubbing and hindsight state repair
@@ -343,17 +347,31 @@ See `.mindforge/production/token-optimiser.md`.
343
347
 
344
348
  ---
345
349
 
346
- ## What's new in v3.0.0-rc1
350
+ ---
351
+
352
+ ## What's new in v4.2 (Intelligence Mesh)
353
+
354
+ MindForge V4.2 focuses on **Identity** and **Memory** within the agentic swarm.
355
+
356
+ - **ZTAI Beast Mode**: Every agent action is cryptographically signed using asymmetric keys. Tier 3 agents use a simulated **Secure Enclave (HSM)** for top-level non-repudiation.
357
+ - **Audit Integrity**: High-fidelity audit manifests generated with **Merkle-root** cumulative hash chains.
358
+ - **Semantic Hub**: Synchronization between local repository memory and the global organizational store (`~/.mindforge/`).
359
+ - **Ghost Pattern Detection**: Proactive risk detection that warns agents when a proposed design matches a past organizational failure.
347
360
 
348
- 🚀 **The Reactive Intelligence Era**
361
+ ## What's new in v4.1 (Nexus)
349
362
 
350
- MindForge V3 transforms the framework from a "disciplined workflow engine" into a **Reactive Autonomous Intelligence**.
363
+ 🚀 **The High-Fidelity Observability Era**
364
+
365
+ MindForge V4.1 introduces **Nexus**, the definitive observability layer for autonomous agents.
366
+
367
+ - **Agentic Reasoning Tracing (ART)**: Deep visibility into "thought chains" and parallel mesh reasoning via hierarchical spans.
368
+ - **Trace Context Propagation**: OpenTelemetry-compatible trace IDs across waves, tasks, and swarm clusters.
369
+ - **Reasoning Heatmaps**: Automated visualization of adversarial disagreement and consensus synthesis.
370
+ - **Mesh Visibility**: Live tracing of ephemeral specialist clusters in the agentic mesh.
371
+
372
+ ---
351
373
 
352
- - **Context Sharding (SRD)**: Achieve a **40% reduction in token waste** via relevance-dense memory management.
353
- - **Adversarial Decision Synthesis (ADS)**: Zero-drift architectural logic through a 3-model debate and SOUL-scoring engine.
354
- - **Temporal Vision**: Full-fidelity history navigation, hindsight state injection, and automated repair.
355
- - **RAG 2.0 (Auto-Shadowing)**: Background pattern retrieval from the local knowledge graph without manual prompts.
356
- - **V3 Core Guide**: New definitive architecture guide in `docs/architecture/V3-CORE.md`.
374
+ ## What's new in v4.0.0 (Swarm)
357
375
 
358
376
  ---
359
377
 
package/RELEASENOTES.md CHANGED
@@ -1,41 +1,46 @@
1
- # MindForge v2.1.1Core Migration & Persona Expansion
1
+ # MindForge v4.3.0Enterprise Mesh & Proactive Equilibrium
2
2
 
3
3
  ## Top Summary
4
-
5
- MindForge v2.1.1 is a major structural update that finalizes the migration of the MindForge framework into the MindForge ecosystem. This release establishes a unified `.agent/` asset structure, expands the persona count from 8 to 32+, and hardens the 4-pillar workflow (`plan`, `execute`, `verify`, `ship`) for enterprise-scale AI orchestration.
4
+ MindForge v4.3.0 introduces the **Enterprise Intelligence Mesh**, finalizing the v4 roadmap with autonomous FinOps and self-healing reliability. This release also implements **ZTAI Beast Mode**, hardens agentic identity with asymmetric cryptographic signing, and introduces simulated Secure Enclaves (HSM) for Tier 3 principal agents.
6
5
 
7
6
  ## Highlights
8
7
 
9
- - **Unified .agent/ Structure**: 120+ framework assets consolidated for maximum compatibility across Claude Code, Antigravity, and Cursor.
10
- - **32-Persona Expansion**: Integrated advanced personas including `advisor-researcher`, `nyquist-auditor`, and `ui-auditor`.
11
- - **Zero-Watermark Integrity**: 100% removal of legacy rebranding fragments across the entire core and documentation.
12
- - **Enterprise Manifest**: Single source of truth via `file-manifest.json` for multi-project codebase intelligence.
13
- - **Hardened Governance**: Unified settings and non-bypassable quality gates across all runtimes.
8
+ - **Pillar V: Autonomous FinOps Hub**: Dynamic **C2C (Confidence-to-Cost)** model routing and real-time Agentic ROI tracking.
9
+ - **Pillar VI: Proactive Equilibrium**: Real-time **Wave Divergence** monitoring and autonomous **Temporal Hindsight** repair loops.
10
+ - **Global Intelligence Mesh**: Synchronizes local project memory with a repository-agnostic organizational store (`~/.mindforge/`).
11
+ - **Ghost Pattern Detection**: Proactive risk detection that warns agents when a proposed design matches a past organizational failure.
12
+ - **ZTAI Beast Mode**: Every agent action in the mesh is now cryptographically signed using Ed25519 asymmetric keys.
13
+ - **Secure Enclave (HSM) Simulation**: Tier 3 agents (Principal/Architect) now use simulated hardware-secured enclaves for signing.
14
+ - **Audit Integrity Manifests**: Automated generation of Merkle-root based manifests for the `AUDIT.jsonl` log.
15
+ - **Tiered Governance**: Full integration of Trust Tiers [0-3] across the 32-persona library.
14
16
 
15
17
  ## Developer Experience
16
18
 
17
- - **Consolidated Documentation**: Modernized guides for Skills Authoring, Architecture, and Persona-based engineering.
18
- - **Enhanced Hooks**: New lifecycle hooks for better context monitoring and real-time status reporting.
19
- - **Command Parity**: Full support for `/mindforge:browse`, `/mindforge:remember`, and `/mindforge:costs`.
19
+ - **New Command Hooks**: Integration of `semantic-hub` and `ztai-archiver` into the core planning and execution loops.
20
+ - **Enhanced PERSONAS.md**: Detailed trust-tier mappings for all specialists.
21
+ - **Proactive Risk Warnings**: Real-time "Ghost Pattern" matches surfaced during the `/mindforge:plan-phase` process.
20
22
 
21
23
  ## Quality & Stability
22
24
 
23
- - **Grep-Audit Verified**: Verified zero residual branding through recursive deep scanning.
24
- - **Path-Aligned Workflows**: All 60+ workflows now strictly follow the v2.1.1 directory standards.
25
- - **Cross-IDE Tested**: Core features validated across multiple AI-native IDE runtimes.
25
+ - **Verified Identity**: 100% of Tier 3 actions require valid cryptographic signatures.
26
+ - **Tamper-Detection**: Audit manifestations allow for historical integrity verification of the entire session.
27
+ - **Cross-Repo Intelligence**: Validated knowledge sharing between isolated project workspaces via the Semantic Hub.
26
28
 
27
- ## Getting Started
29
+ ## Upgrade Notes
28
30
 
29
- - Install: `npx mindforge-cc@latest --claude --local`
30
- - Verify Health: `/mindforge:health`
31
- - Docs Entry: `README.md`
31
+ - Projects on v4.1.0 should run `/mindforge:update --apply` to enable the ZTAI and Mesh features.
32
+ - Initial global sync will occur automatically upon the first `plan-phase` or `execute-phase`.
33
+ - Legacy memory stores will be semantically indexed for the global store during the first sync.
32
34
 
33
- ## Upgrade Notes
35
+ ---
34
36
 
35
- - Projects on v1.0.0 or v2.0.0 should run `/mindforge:migrate` to align with the new path standards.
36
- - Residual custom skills in legacy folders may need manual relocation to `.agent/skills/`.
37
+ # MindForge v4.1.0 Nexus & High-Fidelity Observability
37
38
 
38
- ## Breaking Changes
39
+ ## Highlights
40
+ - **MindForge Nexus**: Agentic Reasoning Tracing (ART) for deep visibility into thought chains.
41
+ - **Trace Context Propagation**: OpenTelemetry-compatible tracing across parallel waves and swarm clusters.
42
+
43
+ ---
39
44
 
40
- - Legacy `.agent/workflows` (without YAML frontmatter) is no longer automatically registered in Antigravity mode.
41
- - See `docs/upgrade.md` for detailed migration paths.
45
+ # MindForge v2.1.1 Core Migration & Persona Expansion
46
+ ...
@@ -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,150 @@
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
+
13
+ class NexusTracer {
14
+ constructor(config = {}) {
15
+ this.projectId = config.projectId || 'mindforge-nexus';
16
+ this.auditPath = config.auditPath || path.join(process.cwd(), '.planning', 'AUDIT.jsonl');
17
+ this.currentTraceId = null;
18
+ this.activeSpans = new Map();
19
+ this.did = config.did || null; // Active Agent DID
20
+ this.enableZtai = config.enableZtai !== false;
21
+ }
22
+
23
+ /**
24
+ * Initialize or resume a trace.
25
+ */
26
+ startTrace(traceId = null) {
27
+ this.currentTraceId = traceId || `tr_${crypto.randomBytes(8).toString('hex')}`;
28
+ return this.currentTraceId;
29
+ }
30
+
31
+ /**
32
+ * Start a new ART span.
33
+ */
34
+ startSpan(name, attributes = {}, parentSpanId = null) {
35
+ const spanId = `sp_${crypto.randomBytes(6).toString('hex')}`;
36
+ const startTime = new Date().toISOString();
37
+
38
+ const span = {
39
+ id: spanId,
40
+ trace_id: this.currentTraceId,
41
+ parent_id: parentSpanId || null,
42
+ name,
43
+ status: 'active',
44
+ start_time: startTime,
45
+ attributes: {
46
+ ...attributes,
47
+ service: 'mindforge-nexus',
48
+ }
49
+ };
50
+
51
+ this.activeSpans.set(spanId, span);
52
+
53
+ // Record span start in AUDIT.jsonl
54
+ this._recordEvent('span_started', {
55
+ span_id: spanId,
56
+ parent_span_id: parentSpanId,
57
+ span_name: name,
58
+ ...attributes
59
+ });
60
+
61
+ return spanId;
62
+ }
63
+
64
+ /**
65
+ * End an active span.
66
+ */
67
+ endSpan(spanId, status = 'success', metadata = {}) {
68
+ const span = this.activeSpans.get(spanId);
69
+ if (!span) return;
70
+
71
+ span.status = status;
72
+ span.end_time = new Date().toISOString();
73
+
74
+ this._recordEvent('span_completed', {
75
+ span_id: spanId,
76
+ status,
77
+ ...metadata
78
+ });
79
+
80
+ this.activeSpans.delete(spanId);
81
+ }
82
+
83
+ /**
84
+ * Record a Reasoning Trace event (ART granularity).
85
+ */
86
+ recordReasoning(spanId, agent, thought, resolution = 'none') {
87
+ this._recordEvent('reasoning_trace', {
88
+ span_id: spanId,
89
+ agent,
90
+ thought,
91
+ resolution
92
+ });
93
+ }
94
+
95
+ /**
96
+ * Internal AUDIT writer.
97
+ */
98
+ _recordEvent(event, data) {
99
+ const entry = {
100
+ id: crypto.randomUUID(),
101
+ timestamp: new Date().toISOString(),
102
+ event,
103
+ trace_id: this.currentTraceId,
104
+ ...data
105
+ };
106
+
107
+ // ZTAI Signing Logic
108
+ if (this.enableZtai && this.did) {
109
+ try {
110
+ entry.did = this.did;
111
+ // Sign the stringified entry WITHOUT the signature field itself
112
+ const payload = JSON.stringify(entry);
113
+ entry.signature = ztai.signData(this.did, payload);
114
+ } catch (err) {
115
+ console.warn(`[NexusTracer] ZTAI signing failed: ${err.message}`);
116
+ }
117
+ }
118
+
119
+ try {
120
+ if (!fs.existsSync(path.dirname(this.auditPath))) {
121
+ fs.mkdirSync(path.dirname(this.auditPath), { recursive: true });
122
+ }
123
+ fs.appendFileSync(this.auditPath, JSON.stringify(entry) + '\n');
124
+ } catch (err) {
125
+ console.error(`[NexusTracer] Failed to write audit entry: ${err.message}`);
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Records a FinOps budget decision (Pillar V).
131
+ */
132
+ recordFinOps(spanId, decision) {
133
+ this._recordEvent('finops_decision', {
134
+ span_id: spanId,
135
+ ...decision
136
+ });
137
+ }
138
+
139
+ /**
140
+ * Records a Self-Healing trigger event (Pillar VI).
141
+ */
142
+ recordSelfHeal(spanId, report) {
143
+ this._recordEvent('self_heal_trigger', {
144
+ span_id: spanId,
145
+ ...report
146
+ });
147
+ }
148
+ }
149
+
150
+ module.exports = NexusTracer;
@@ -0,0 +1,88 @@
1
+ /**
2
+ * MindForge — TemporalHindsight (Pillar VI: Proactive Equilibrium)
3
+ * Performs automated RCA and generates repair plans for diverging waves.
4
+ */
5
+
6
+ const fs = require('fs');
7
+ const path = require('path');
8
+
9
+ class TemporalHindsight {
10
+ constructor(config = {}) {
11
+ this.projectRoot = config.projectRoot || process.cwd();
12
+ this.historyLimit = config.historyLimit || 10; // Analyze last 10 failed tasks
13
+ }
14
+
15
+ /**
16
+ * Performs Root Cause Analysis (RCA) on a failed wave.
17
+ * @param {Object} waveReport - Current wave results (failed tasks, logs)
18
+ * @returns {Object} - Diagnosis and Repair Plan
19
+ */
20
+ async analyze(waveReport) {
21
+ const { failedTasks, divergence, phase } = waveReport;
22
+ const diagnosis = this.diagnoseFailures(failedTasks);
23
+
24
+ return {
25
+ timestamp: new Date().toISOString(),
26
+ phase,
27
+ divergence,
28
+ diagnosis,
29
+ repairPlan: this.generateRepairPlan(diagnosis, phase),
30
+ };
31
+ }
32
+
33
+ /**
34
+ * Diagnoses common failure patterns in agentic workloads.
35
+ */
36
+ diagnoseFailures(tasks) {
37
+ const errorMessages = tasks.map(t => t.error || '').join(' ').toLowerCase();
38
+
39
+ if (errorMessages.includes('permission denied') || errorMessages.includes('eacces')) {
40
+ return { type: 'ENVIRONMENTAL', cause: 'File system permission issues detected in multiple tasks.', severity: 'CRITICAL' };
41
+ }
42
+
43
+ if (errorMessages.includes('timeout') || errorMessages.includes('deadline exceeded')) {
44
+ return { type: 'RESOURCE', cause: 'Wave execution timeout. Tasks are too large or the model response is slow.', severity: 'HIGH' };
45
+ }
46
+
47
+ if (errorMessages.includes('lint') || errorMessages.includes('syntax error')) {
48
+ return { type: 'LOGIC', cause: 'Cumulative coding errors. The existing plan is producing invalid syntax consistently.', severity: 'STRICT' };
49
+ }
50
+
51
+ return { type: 'UNKNOWN', cause: 'Generic wave divergence. Multiple unrelated failures detected.', severity: 'MEDIUM' };
52
+ }
53
+
54
+ /**
55
+ * Generates a "Self-Healing" Plan.md entry.
56
+ */
57
+ generateRepairPlan(diagnosis, phase) {
58
+ const steps = [];
59
+
60
+ switch (diagnosis.type) {
61
+ case 'ENVIRONMENTAL':
62
+ steps.push('PAUSE execution immediately.');
63
+ steps.push('Run `chmod -R u+w .` (simulated) on the affected directories.');
64
+ steps.push('Re-verify task 0.1 before resuming the wave.');
65
+ break;
66
+ case 'RESOURCE':
67
+ steps.push('PAUSE execution and increase `taskTimeoutMs` by 50%.');
68
+ steps.push('Request `EXECUTOR_MODEL` upgrade to `claude-3-opus` for complex tasks.');
69
+ steps.push('Serialise the next wave (concurrency = 1) to reduce resource contention.');
70
+ break;
71
+ case 'LOGIC':
72
+ steps.push('STOP active wave.');
73
+ steps.push('Rewrite Sub-tasks in PLAN.md for Phase ' + phase + ' with stricter TDD requirements.');
74
+ steps.push('Inject `Quality-Auditor` persona into the review loop.');
75
+ break;
76
+ default:
77
+ steps.push('PAUSE and request human review for divergence RCA.');
78
+ }
79
+
80
+ return {
81
+ title: `AUTONOMOUS REPAIR PLAN: PHASE ${phase}`,
82
+ steps,
83
+ autoApplyStatus: 'PENDING_SIGNATURE',
84
+ };
85
+ }
86
+ }
87
+
88
+ module.exports = TemporalHindsight;