swarm-engine-core 0.1.6

Core types and orchestration for SwarmEngine
Documentation
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
//! 結果マージフェーズの処理
//!
//! - merge_results(): Worker 実行結果を State に反映
//! - build_worker_result_snapshots(): スナップショット構築

use std::time::Duration;

use tracing::{debug, info};

use crate::agent::WorkResult;
use crate::events::{ActionContext, ActionEventBuilder, ActionEventResult};
use crate::exploration::MapNodeId;
use crate::state::HistoryEntry;
use crate::types::{SwarmTask, WorkerId};

use super::adapter::WorkResultAdapter;
use super::Orchestrator;

impl Orchestrator {
    /// 結果を State にマージ
    pub(super) fn merge_results(&mut self, results: &[(usize, WorkResult)]) {
        let current_tick = self.state.shared.tick;

        for (worker_idx, result) in results {
            let worker_id = WorkerId(*worker_idx);

            // 成功/失敗判定 & state_delta 抽出 & アクション名取得 & Agent申告Escalation & output & 追加メタデータ & discovered_targets
            let (
                success,
                is_failure,
                state_delta,
                action_name,
                agent_escalation,
                action_output,
                extra_metadata,
                discovered_targets,
            ) = match result {
                WorkResult::Acted {
                    action_result,
                    state_delta,
                } => {
                    // output を String として取得
                    let output_str = action_result.output.as_ref().map(|o| o.as_text());
                    // Guidance からアクション名を取得(なければ "acted")
                    // 所有権を取得してライフタイム問題を回避
                    let name = self
                        .current_guidances
                        .get(&worker_id)
                        .and_then(|g| g.actions.first())
                        .map(|a| a.name.clone())
                        .unwrap_or_else(|| "acted".to_string());
                    (
                        action_result.success,
                        !action_result.success,
                        state_delta.as_ref(),
                        name,
                        None,
                        output_str,
                        vec![],
                        action_result.discovered_targets.clone(),
                    )
                }
                WorkResult::Continuing { progress } => (
                    true,
                    false,
                    None,
                    "continuing".to_string(),
                    None,
                    None,
                    vec![("progress".to_string(), progress.to_string())],
                    vec![],
                ),
                WorkResult::NeedsGuidance { reason, context } => (
                    true,
                    false,
                    None,
                    "needs_guidance".to_string(),
                    None,
                    None,
                    vec![
                        ("reason".to_string(), reason.clone()),
                        ("context".to_string(), format!("{:?}", context)),
                    ],
                    vec![],
                ),
                WorkResult::Escalate { reason, context } => {
                    // Agent 申告の Escalation
                    let escalation = crate::agent::Escalation {
                        reason: reason.clone(),
                        raised_at_tick: current_tick,
                        context: context.clone(),
                    };
                    (
                        true,
                        false,
                        None,
                        "escalate".to_string(),
                        Some(escalation),
                        None,
                        vec![
                            ("reason".to_string(), format!("{:?}", reason)),
                            ("context".to_string(), context.clone().unwrap_or_default()),
                        ],
                        vec![],
                    )
                }
                WorkResult::Idle => (
                    true,
                    false,
                    None,
                    "idle".to_string(),
                    None,
                    None,
                    vec![],
                    vec![],
                ),
                WorkResult::Done { success, message } => {
                    info!(
                        "Worker {} done: success={}, message={:?}",
                        worker_idx, success, message
                    );
                    (
                        *success,
                        !*success,
                        None,
                        "done".to_string(),
                        None,
                        message.clone(),
                        vec![],
                        vec![],
                    )
                }
            };

            // ActionEvent を作成
            // ターゲットを取得(Guidance の exploration_target から)
            let target = self
                .current_guidances
                .get(&worker_id)
                .and_then(|g| g.exploration_target.as_ref())
                .map(|t| format!("node:{}", t.node_id.0));

            // コンテキストを構築(extra_metadata と guidance_received を含める)
            let mut context = ActionContext::new().with_selection_logic(
                self.current_guidances
                    .get(&worker_id)
                    .and_then(|g| g.exploration_target.as_ref())
                    .map(|_| "exploration_v2")
                    .unwrap_or("default"),
            );
            for (key, value) in extra_metadata {
                context = context.with_metadata(key, value);
            }
            // guidance_received を metadata に追加
            if let Some(guidance) = self.current_guidances.get(&worker_id) {
                context = context.with_guidance();
                // Guidance の概要を metadata に追加
                if !guidance.actions.is_empty() {
                    let actions_str = guidance
                        .actions
                        .iter()
                        .map(|a| a.name.as_str())
                        .collect::<Vec<_>>()
                        .join(",");
                    context = context.with_metadata("guidance_actions", actions_str);
                }
                if let Some(ref content) = guidance.content {
                    // content は長い可能性があるので、最初の100文字だけ
                    let truncated = if content.len() > 100 {
                        format!("{}...", &content[..100])
                    } else {
                        content.clone()
                    };
                    context = context.with_metadata("guidance_content", truncated);
                }
            }

            // 結果を構築
            let event_result = if success {
                match &action_output {
                    Some(output) => ActionEventResult::success_with_output(output.clone()),
                    None => ActionEventResult::success(),
                }
            } else {
                ActionEventResult::failure("action_failed")
            };

            // SwarmTask から task_id と group_id を取得
            let (task_id, group_id) = self
                .state
                .shared
                .extensions
                .get::<SwarmTask>()
                .map(|t| (t.id, t.group_id))
                .unwrap_or_else(|| (crate::types::TaskId::new(), None));

            let event = ActionEventBuilder::new(current_tick, worker_id, &action_name)
                .task_id(task_id)
                .group_id_opt(group_id)
                .target(target.unwrap_or_default())
                .result(event_result)
                .duration(Duration::ZERO) // TODO: 実際の実行時間を取得
                .context(context)
                .build();

            // SharedState.stats に直接記録(Single Source of Truth)
            self.state.shared.stats.record(&event);

            // ActionEventPublisher がある場合は broadcast も行う(JSONL 出力等)
            if let Some(ref collector) = self.action_collector {
                collector.record(event);
            }

            // Record WorkResult::Done via TerminationJudge (Single Source of Truth)
            // Note: We check for "done" action name which comes from WorkResult::Done
            if action_name == "done" {
                // Notify TerminationJudge - it will handle all state updates
                self.termination_judge.notify_worker_done(
                    worker_id,
                    success,
                    action_output.clone(),
                );

                // Also update SharedState for backward compatibility
                if success {
                    self.state.shared.mark_worker_done(worker_id);
                }

                // ExplorationSpaceV2 の完了をマーク (success の場合のみ)
                if success {
                    if let Some(ref mut space_v2) = self.space_v2 {
                        if !space_v2.has_completed() {
                            space_v2.mark_completed();
                            info!(
                                worker_id = worker_idx,
                                "ExplorationSpaceV2: marked as completed (from Done)"
                            );
                        }
                    }
                }
            }

            // ExplorationSpaceV2 自動トラッキング
            // Guidance の exploration_target があれば、ActionResult を自動記録
            if let Some(guidance) = self.current_guidances.get(&worker_id) {
                if let Some(ref target) = guidance.exploration_target {
                    // Action 情報を取得(Guidance の最初の action、またはデフォルト)
                    let action =
                        guidance
                            .actions
                            .first()
                            .cloned()
                            .unwrap_or_else(|| crate::types::Action {
                                name: action_name.to_string(),
                                params: crate::types::ActionParams::default(),
                            });

                    // Worker の出力を exploration に反映
                    // 成功時: discovered_targets を ExploMap に渡して新しいノードとして展開
                    let discovery: Option<serde_json::Value> =
                        if success && !discovered_targets.is_empty() {
                            // discovered_targets を JSON 配列として渡す
                            Some(serde_json::Value::Array(
                                discovered_targets
                                    .iter()
                                    .map(|s| serde_json::Value::String(s.clone()))
                                    .collect(),
                            ))
                        } else {
                            None
                        };

                    // "Continue" アクションは探索空間に記録しない(ノードを進めない)
                    // LLM が有効な JSON を出力できなかった場合のフォールバックなので、
                    // 同じノードに留まって再試行させる
                    let is_continue_action = action_name.eq_ignore_ascii_case("continue");

                    // ========================================================
                    // ExplorationSpaceV2 への適用
                    // ========================================================
                    if !is_continue_action {
                        if let Some(ref mut space_v2) = self.space_v2 {
                            // action.params.target から取得、なければ args["target"] を使用
                            // param_variants で設定した値は args に入るため
                            let target_str =
                                action.params.target.as_deref().or_else(|| {
                                    action.params.args.get("target").map(|s| s.as_str())
                                });
                            debug!(
                                action_name = %action_name,
                                params_target = ?action.params.target,
                                params_args = ?action.params.args,
                                resolved_target = ?target_str,
                                success = success,
                                "ExplorationSpaceV2: applying result"
                            );
                            let adapter = WorkResultAdapter::new(
                                MapNodeId::new(target.node_id.0),
                                &action_name,
                                target_str,
                                success,
                                discovery.as_ref(),
                            );
                            let v2_results = space_v2.apply(&adapter, &self.state.shared.stats);
                            debug!(
                                worker_id = worker_idx,
                                node_id = target.node_id.0,
                                v2_results = ?v2_results,
                                frontiers = space_v2.frontiers().len(),
                                "ExplorationSpaceV2 applied"
                            );
                        }
                    }
                }
            }

            // 履歴に記録 & Escalation 処理 & StateDelta 適用
            if let Some(ctx) = self
                .state
                .workers
                .get_mut(crate::types::AgentId(*worker_idx))
            {
                ctx.history.push(HistoryEntry {
                    tick: current_tick,
                    action_name: action_name.to_string(),
                    success,
                });

                // last_output を保存(Environment からの結果)
                ctx.last_output = action_output.clone();

                // SharedData に output を保存(env:{worker_id}:{tick} でどんどん追記)
                if let Some(ref output) = action_output {
                    let key = format!("env:{}:{}", worker_idx, current_tick);
                    self.state
                        .shared
                        .shared_data
                        .kv
                        .insert(key, output.as_bytes().to_vec());
                }

                // Escalation 判定(3回連続失敗で Escalation)
                if is_failure {
                    let escalated = ctx.record_failure(current_tick, 3);
                    if escalated {
                        debug!(
                            worker_id = worker_idx,
                            consecutive_failures = ctx.consecutive_failures,
                            "Worker escalated (consecutive failures)"
                        );
                    }
                } else {
                    ctx.record_success();
                }

                // Agent 申告の Escalation を設定
                if let Some(escalation) = agent_escalation.clone() {
                    debug!(
                        worker_id = worker_idx,
                        reason = ?escalation.reason,
                        "Worker escalated (agent requested)"
                    );
                    ctx.escalation = Some(crate::state::Escalation {
                        reason: match &escalation.reason {
                            crate::agent::EscalationReason::ConsecutiveFailures(n) => {
                                crate::state::EscalationReason::ConsecutiveFailures(*n)
                            }
                            crate::agent::EscalationReason::ResourceExhausted => {
                                crate::state::EscalationReason::ResourceExhausted
                            }
                            crate::agent::EscalationReason::Timeout => {
                                crate::state::EscalationReason::Timeout
                            }
                            crate::agent::EscalationReason::AgentRequested(s) => {
                                crate::state::EscalationReason::AgentRequested(s.clone())
                            }
                            crate::agent::EscalationReason::Unknown(s) => {
                                crate::state::EscalationReason::Unknown(s.clone())
                            }
                        },
                        raised_at_tick: escalation.raised_at_tick,
                        context: escalation.context.clone(),
                    });
                }

                // StateDelta 適用: キャッシュ更新
                if let Some(delta) = state_delta {
                    for update in &delta.cache_updates {
                        ctx.cache
                            .set(&update.key, update.value.clone(), update.ttl_ticks);
                    }
                }
            }

            // StateDelta 適用: SharedData 更新
            if let Some(delta) = state_delta {
                for update in &delta.shared_updates {
                    self.state
                        .shared
                        .shared_data
                        .kv
                        .insert(update.key.clone(), update.value.clone());
                }

                // StateDelta 適用: 非同期タスク発行
                for task_req in &delta.async_tasks {
                    let params = crate::async_task::TaskParams {
                        data: task_req.params.clone(),
                    };
                    if let Some(task) = self.async_system.create_task(&task_req.task_type, params) {
                        let task_id = self.async_system.spawn_boxed(task);
                        // Agent の pending_tasks に追加
                        if let Some(ctx) = self
                            .state
                            .workers
                            .get_mut(crate::types::AgentId(*worker_idx))
                        {
                            ctx.pending_tasks.insert(task_id);
                        }
                        debug!(
                            worker_id = worker_idx,
                            task_type = %task_req.task_type,
                            task_id = task_id.0,
                            "Async task spawned"
                        );
                    } else {
                        debug!(
                            worker_id = worker_idx,
                            task_type = %task_req.task_type,
                            "Unknown async task type, factory not registered"
                        );
                    }
                }
            }
        }
    }
}