File size: 2,183 Bytes
6a0ff33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/**
 * AutoForge DAG Engine — Implementation
 */

#include "dag_engine.h"
#include <algorithm>
#include <queue>
#include <unordered_set>
#include <iostream>

namespace autoforge {

DAGEngine::DAGEngine() = default;
DAGEngine::~DAGEngine() = default;

std::string DAGEngine::version() {
    return "0.1.0";
}

void DAGEngine::add_node(const DAGNode& node) {
    std::lock_guard<std::mutex> lock(mutex_);
    index_[node.id] = nodes_.size();
    nodes_.push_back(node);
}

size_t DAGEngine::node_count() const {
    std::lock_guard<std::mutex> lock(mutex_);
    return nodes_.size();
}

void DAGEngine::clear() {
    std::lock_guard<std::mutex> lock(mutex_);
    nodes_.clear();
    index_.clear();
}

bool DAGEngine::validate() const {
    std::lock_guard<std::mutex> lock(mutex_);

    // Kahn's algorithm for cycle detection
    std::unordered_map<std::string, int> in_degree;
    for (const auto& node : nodes_) {
        if (in_degree.find(node.id) == in_degree.end()) {
            in_degree[node.id] = 0;
        }
        for (const auto& dep : node.deps) {
            in_degree[node.id]++;
        }
    }

    std::queue<std::string> ready;
    for (const auto& [id, deg] : in_degree) {
        if (deg == 0) {
            ready.push(id);
        }
    }

    size_t processed = 0;
    while (!ready.empty()) {
        auto current = ready.front();
        ready.pop();
        processed++;

        // Find nodes that depend on current
        for (const auto& node : nodes_) {
            for (const auto& dep : node.deps) {
                if (dep == current) {
                    in_degree[node.id]--;
                    if (in_degree[node.id] == 0) {
                        ready.push(node.id);
                    }
                }
            }
        }
    }

    return processed == nodes_.size();
}

bool DAGEngine::execute() {
    // Phase 2: actual concurrent task execution
    if (!validate()) {
        std::cerr << "[DAGEngine] Invalid DAG — contains cycles" << std::endl;
        return false;
    }

    std::cout << "[DAGEngine] DAG validated. Execution not yet implemented (Phase 2)." << std::endl;
    return true;
}

} // namespace autoforge