routa-server 0.14.3

Routa.js HTTP Server — axum adapter on top of routa-core
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
use std::path::Path;
use std::process::Stdio;
use std::time::Duration;

use serde_json::{json, Value};
use tokio::process::Command;
use tokio::time::timeout;

const AUDIT_SPECIALIST_ID: &str = "agents-md-auditor";
const AUDIT_COMMAND_TIMEOUT_MS: u64 = 120_000;

fn value_to_i64(value: &Value) -> Option<i64> {
    value
        .as_i64()
        .or_else(|| value.as_u64().and_then(|raw| i64::try_from(raw).ok()))
        .or_else(|| value.as_f64().map(|raw| raw.round() as i64))
}

fn to_score(value: Option<&Value>) -> Option<i64> {
    let score = value.and_then(value_to_i64)?;
    if (0..=5).contains(&score) {
        Some(score)
    } else {
        None
    }
}

fn infer_overall(
    routing: i64,
    protection: i64,
    reflection: i64,
    verification: i64,
    has_agent_side_effects: bool,
) -> &'static str {
    let scores = [routing, protection, reflection, verification];

    if scores.iter().any(|score| *score <= 2) {
        return "不通过";
    }

    if has_agent_side_effects && (protection < 4 || verification < 4) {
        return "有条件通过";
    }

    if scores.iter().all(|score| *score >= 4) {
        return "通过";
    }

    if scores.iter().all(|score| *score > 1)
        && scores.iter().filter(|score| **score >= 3).count() >= 3
    {
        return "有条件通过";
    }

    "不通过"
}

fn build_heuristic_audit(
    source: &str,
    duration_ms: u64,
    provider: &str,
    error: Option<&str>,
) -> Value {
    let normalized = source.to_lowercase();
    let has_agent_side_effects = [
        "tool",
        "tools",
        "execute",
        "command",
        "write file",
        "修改",
        "执行命令",
        "调用工具",
        "发消息",
        "external system",
        "外部系统",
    ]
    .iter()
    .any(|signal| normalized.contains(signal));

    let routing = [
        normalized.contains("repository map")
            || normalized.contains("feature tree")
            || source.contains("目录"),
        normalized.contains("start here")
            || normalized.contains("entry point")
            || normalized.contains("follow this sequence")
            || source.contains("先定位")
            || source.contains("按需"),
        normalized.contains("docs/")
            || normalized.contains("path")
            || normalized.contains("module")
            || normalized.contains("workspace")
            || source.contains("文件路径"),
        normalized.contains("do not")
            && (normalized.contains("knowledge dump")
                || source.contains("最小上下文")
                || source.contains("最小化")),
        normalized.contains("phase")
            || normalized.contains(" when ")
            || normalized.starts_with("when ")
            || source.contains("阶段"),
    ]
    .iter()
    .filter(|signal| **signal)
    .count()
    .min(5) as i64;

    let protection = [
        normalized.contains("do not")
            || normalized.contains("don't")
            || normalized.contains("never")
            || normalized.contains("must not")
            || source.contains("不得")
            || source.contains("禁止"),
        normalized.contains("allowlist")
            || normalized.contains("denylist")
            || normalized.contains("scope")
            || normalized.contains("boundary")
            || source.contains("权限边界")
            || source.contains("范围限制"),
        normalized.contains("confirm")
            || normalized.contains("approval")
            || normalized.contains("escalat")
            || source.contains("升级"),
        normalized.contains("injection")
            || normalized.contains("prompt injection")
            || source.contains("注入"),
        normalized.contains("drift")
            || source.contains("越权")
            || source.contains("误操作")
            || source.contains("风险"),
    ]
    .iter()
    .filter(|signal| **signal)
    .count()
    .min(5) as i64;

    let reflection = [
        normalized.contains("fail") || source.contains("失败") || source.contains("错误"),
        normalized.contains("retry") || source.contains("重试") || source.contains("最多"),
        normalized.contains("analyze")
            || normalized.contains("analyse")
            || normalized.contains("reason")
            || source.contains("原因")
            || source.contains("根因")
            || source.contains("第一性原理"),
        normalized.contains("switch strategy")
            || source.contains("换策略")
            || source.contains("分解任务")
            || source.contains("缩小问题"),
        normalized.contains("stop") || source.contains("卡住") || source.contains("升级处理"),
    ]
    .iter()
    .filter(|signal| **signal)
    .count()
    .min(5) as i64;

    let verification = [
        normalized.contains("definition of done")
            || source.contains("完成标准")
            || source.contains("验收条件"),
        normalized.contains("lint")
            || normalized.contains("test")
            || normalized.contains("typecheck")
            || normalized.contains("build")
            || normalized.contains("dry-run")
            || normalized.contains("checklist")
            || normalized.contains("schema check"),
        normalized.contains("if any step fails")
            || normalized.contains("fix and re-validate")
            || source.contains("未通过验证")
            || source.contains("不得宣称完成"),
        normalized.contains("evidence")
            || normalized.contains("report")
            || source.contains("输出验证结果")
            || source.contains("失败原因"),
        normalized.contains("before any pr")
            || normalized.contains("must run")
            || source.contains("完成前"),
    ]
    .iter()
    .filter(|signal| **signal)
    .count()
    .min(5) as i64;

    let total_score = routing + protection + reflection + verification;
    let overall = infer_overall(
        routing,
        protection,
        reflection,
        verification,
        has_agent_side_effects,
    );
    let mut audit = json!({
        "status": "heuristic",
        "provider": provider,
        "generatedAt": chrono::Utc::now().to_rfc3339(),
        "durationMs": duration_ms,
        "totalScore": total_score,
        "overall": overall,
        "oneSentence": "specialist 调用失败,当前展示为本地启发式评分(用于 UI 可用性,不作为最终审计结论)。",
        "principles": {
            "routing": routing,
            "protection": protection,
            "reflection": reflection,
            "verification": verification,
        }
    });
    if let Some(error) = error {
        audit["error"] = Value::String(error.to_string());
    }
    audit
}

fn parse_audit_payload(payload: &Value, duration_ms: u64, provider: &str) -> Value {
    let routing = to_score(payload.pointer("/principles/routing/score"));
    let protection = to_score(payload.pointer("/principles/protection/score"));
    let reflection = to_score(payload.pointer("/principles/reflection/score"));
    let verification = to_score(payload.pointer("/principles/verification/score"));

    let total_score = payload
        .pointer("/audit_conclusion/total_score")
        .and_then(value_to_i64)
        .map(|score| score.clamp(0, 20));
    let overall = payload
        .pointer("/audit_conclusion/overall")
        .and_then(Value::as_str)
        .and_then(|overall| match overall {
            "通过" | "有条件通过" | "不通过" => Some(overall),
            _ => None,
        });
    let one_sentence = payload
        .pointer("/audit_conclusion/one_sentence")
        .and_then(Value::as_str);

    json!({
        "status": "ok",
        "provider": provider,
        "generatedAt": chrono::Utc::now().to_rfc3339(),
        "durationMs": duration_ms,
        "totalScore": total_score,
        "overall": overall,
        "oneSentence": one_sentence,
        "principles": {
            "routing": routing,
            "protection": protection,
            "reflection": reflection,
            "verification": verification,
        }
    })
}

fn extract_json_output(raw: &str) -> Result<String, String> {
    let candidate = raw.trim();
    if candidate.is_empty() {
        return Err("Command produced no output".to_string());
    }

    if serde_json::from_str::<Value>(candidate).is_ok() {
        return Ok(candidate.to_string());
    }

    let opens = candidate
        .match_indices('{')
        .map(|(index, _)| index)
        .collect::<Vec<_>>();
    for index in opens.into_iter().rev() {
        let snippet = candidate[index..].trim();
        if !snippet.ends_with('}') {
            continue;
        }
        if serde_json::from_str::<Value>(snippet).is_ok() {
            return Ok(snippet.to_string());
        }
    }

    Err("Unable to parse command JSON output".to_string())
}

async fn execute_auditor_command(
    repo_root: &Path,
    workspace_id: &str,
    source: &str,
    provider: &str,
) -> Result<String, String> {
    // Quick pre-check: verify specialist binary exists before attempting execution
    let local_binary_path = repo_root.join("target/debug/routa");

    // If we're using local binary, check if it exists
    if local_binary_path.is_file() {
        // Quick check if specialist exists by running --help
        let check = Command::new(&local_binary_path)
            .args(["specialist", "run", "--help"])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .await;

        // If basic help command fails, bail early
        if check.is_err() {
            return Err("Local routa binary is not functional".to_string());
        }
    }

    let specialist_args = vec![
        "specialist".to_string(),
        "run".to_string(),
        "--json".to_string(),
        "--workspace-id".to_string(),
        workspace_id.to_string(),
        "--provider".to_string(),
        provider.to_string(),
        "--provider-timeout-ms".to_string(),
        "30000".to_string(),
        "--provider-retries".to_string(),
        "0".to_string(),
        "-p".to_string(),
        source.to_string(),
        AUDIT_SPECIALIST_ID.to_string(),
    ];

    let mut command = if local_binary_path.is_file() {
        let mut command = Command::new(local_binary_path);
        command.args(&specialist_args);
        command
    } else {
        let mut cargo_args = vec![
            "run".to_string(),
            "-p".to_string(),
            "routa-cli".to_string(),
            "--".to_string(),
        ];
        cargo_args.extend(specialist_args);
        let mut command = Command::new("cargo");
        command.args(cargo_args);
        command
    };

    command
        .current_dir(repo_root)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());

    let output = timeout(
        Duration::from_millis(AUDIT_COMMAND_TIMEOUT_MS),
        command.output(),
    )
    .await
    .map_err(|_| {
        format!(
            "Instruction audit command timed out after {}ms",
            AUDIT_COMMAND_TIMEOUT_MS
        )
    })?
    .map_err(|error| format!("Instruction audit command failed to execute: {error}"))?;

    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
    if !output.status.success() {
        let error_output = if stderr.trim().is_empty() {
            stdout.trim().to_string()
        } else {
            stderr.trim().to_string()
        };
        return Err(format!(
            "Instruction audit command failed (exit {}): {}",
            output.status.code().unwrap_or(1),
            error_output
        ));
    }

    Ok(stdout)
}

pub(crate) async fn run_instruction_audit(
    repo_root: &Path,
    workspace_id: &str,
    source: &str,
    provider: &str,
) -> Value {
    let started = std::time::Instant::now();
    let to_duration_ms = || u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX);

    // Fast-fail: If provider requires an API key and it's not configured, skip execution
    let requires_api_key = matches!(provider, "codex" | "claude" | "openai" | "anthropic");
    if requires_api_key {
        let api_key_configured = match provider {
            "codex" => std::env::var("CODEX_API_KEY").is_ok(),
            "claude" | "anthropic" => std::env::var("ANTHROPIC_API_KEY").is_ok(),
            "openai" => std::env::var("OPENAI_API_KEY").is_ok(),
            _ => false,
        };

        if !api_key_configured {
            return build_heuristic_audit(
                source,
                to_duration_ms(),
                provider,
                Some(&format!(
                    "Provider '{}' API key not configured, using heuristic fallback",
                    provider
                )),
            );
        }
    }

    match execute_auditor_command(repo_root, workspace_id, source, provider).await {
        Ok(stdout) => match extract_json_output(&stdout) {
            Ok(extracted) => match serde_json::from_str::<Value>(&extracted) {
                Ok(payload) => parse_audit_payload(&payload, to_duration_ms(), provider),
                Err(error) => build_heuristic_audit(
                    source,
                    to_duration_ms(),
                    provider,
                    Some(&error.to_string()),
                ),
            },
            Err(error) => build_heuristic_audit(source, to_duration_ms(), provider, Some(&error)),
        },
        Err(error) => build_heuristic_audit(source, to_duration_ms(), provider, Some(&error)),
    }
}