symforge 8.6.0

SymForge — in-memory code intelligence MCP server for Claude Code, Codex, and Gemini CLI
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
//! Phase 2 compact-surface battery gate computation (H3/H4/H5).
//!
//! Formulas match [`docs/v8-gap-closure-plan.md`](../../docs/v8-gap-closure-plan.md) §5.1
//! with A-012 serve-only H3 scope when no `*_small` rows are present.

#![allow(non_snake_case)] // sf-bench / compare-results JSON field names

use serde::{Deserialize, Serialize};

/// STEL extension block required on each battery row (Phase 2 contract).
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct BatteryRowStel {
    pub plan_id: String,
    pub decision: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tools_called: Vec<String>,
    pub predicted_tokens: u32,
    pub actual_tokens: u32,
    pub net_vs_manual: i32,
    pub route_confidence: String,
}

/// One measured compact-surface battery row.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct BatteryRow {
    pub id: String,
    #[serde(default)]
    pub corpus: String,
    pub S: u32,
    pub M: u32,
    pub sGteM: bool,
    pub acceptedServe: bool,
    pub equivalence: String,
    #[serde(default)]
    pub goldenId: String,
    pub decision: String,
    #[serde(default = "default_chain")]
    pub chain: String,
    pub mcpCalls: u32,
    pub eligibleH6: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stel: Option<BatteryRowStel>,
}

fn default_chain() -> String {
    "single".to_string()
}

/// sf-bench-style battery output consumed by compare-results.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct BatteryResults {
    #[serde(default)]
    pub measuredAt: String,
    #[serde(default)]
    pub symforgeBin: String,
    #[serde(default)]
    pub surface: String,
    #[serde(default)]
    pub method: String,
    #[serde(default)]
    pub baselineCommit: String,
    pub rows: Vec<BatteryRow>,
    #[serde(default)]
    pub session_net_accepted: i64,
    #[serde(default)]
    pub session_net_all36: i64,
    #[serde(default)]
    pub rowCount: usize,
    #[serde(default)]
    pub skippedRows: Vec<String>,
}

/// Per-gate PASS/FAIL/NOT_CLAIMED status.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum GateStatus {
    Pass,
    Fail,
    NotClaimed,
}

impl GateStatus {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Pass => "PASS",
            Self::Fail => "FAIL",
            Self::NotClaimed => "NOT_CLAIMED",
        }
    }
}

/// Computed H3/H4/H5 gate report for Phase 2 evidence.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct Phase2GateReport {
    pub report_id: String,
    pub surface: String,
    pub baseline_commit: String,
    pub candidate_results: String,
    pub compare_results_command: String,
    pub session_net_accepted: i64,
    pub session_net_all36: i64,
    pub h3_small_serve_s_gte_m_count: usize,
    pub h3_scope_row_count: usize,
    pub h3_policy_ref: String,
    pub h5_single_chain_violations: Vec<String>,
    pub gates: Phase2GateStatuses,
    pub diagnostics: String,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct Phase2GateStatuses {
    pub H1: GateStatus,
    pub H2: GateStatus,
    pub H3: GateStatus,
    pub H4: GateStatus,
    pub H5: GateStatus,
    pub H6: GateStatus,
    pub H7: GateStatus,
    pub H8: GateStatus,
}

/// Whether a row id matches the sf-bench small-file task suffix.
pub fn is_small_file_task_id(id: &str) -> bool {
    id.contains("_small") || id.ends_with("/small")
}

/// Rows in scope for H3 under A-012 serve-only policy.
pub fn h3_scope_rows(rows: &[BatteryRow]) -> Vec<&BatteryRow> {
    let serve_accepted: Vec<_> = rows
        .iter()
        .filter(|row| row.decision == "serve" && row.acceptedServe)
        .collect();
    let small: Vec<_> = serve_accepted
        .iter()
        .copied()
        .filter(|row| is_small_file_task_id(&row.id))
        .collect();
    if small.is_empty() {
        serve_accepted
    } else {
        small
    }
}

/// Recompute session nets and sGteM flags from row economics.
pub fn normalize_battery_results(mut results: BatteryResults) -> BatteryResults {
    for row in &mut results.rows {
        row.sGteM = row.S >= row.M;
        row.acceptedServe = row.decision == "serve" && row.equivalence == "EQUIVALENT";
        if row.goldenId.is_empty() {
            row.goldenId.clone_from(&row.id);
        }
    }
    results.session_net_accepted = results
        .rows
        .iter()
        .filter(|row| row.acceptedServe)
        .map(|row| i64::from(row.M) - i64::from(row.S))
        .sum();
    results.session_net_all36 = results
        .rows
        .iter()
        .map(|row| i64::from(row.M) - i64::from(row.S))
        .sum();
    results.rowCount = results.rows.len();
    results
}

/// Compute Phase 2 gate statuses from normalized battery results.
pub fn compute_phase2_gates(results: &BatteryResults) -> Phase2GateReport {
    let h3_rows = h3_scope_rows(&results.rows);
    let h3_violations: Vec<_> = h3_rows.iter().filter(|row| row.sGteM).collect();
    let h3_status = if h3_violations.is_empty() {
        GateStatus::Pass
    } else {
        GateStatus::Fail
    };

    let h4_status = if results.session_net_accepted >= 0 {
        GateStatus::Pass
    } else {
        GateStatus::Fail
    };

    let h5_violations: Vec<String> = results
        .rows
        .iter()
        .filter(|row| row.chain == "single" && row.mcpCalls > 1)
        .map(|row| format!("{}: mcpCalls={}", row.id, row.mcpCalls))
        .collect();
    let h5_status = if h5_violations.is_empty() {
        GateStatus::Pass
    } else {
        GateStatus::Fail
    };

    let mut diagnostics = String::new();
    if !h3_violations.is_empty() {
        diagnostics.push_str("H3 violations (accepted serve rows with sGteM): ");
        for row in &h3_violations {
            diagnostics.push_str(&format!("{} (S={} M={}); ", row.id, row.S, row.M));
        }
    }
    if results.session_net_accepted < 0 {
        diagnostics.push_str(&format!(
            "H4 session_net_accepted={} < 0. ",
            results.session_net_accepted
        ));
    }
    if !h5_violations.is_empty() {
        diagnostics.push_str(&format!("H5 violations: {}. ", h5_violations.join(", ")));
    }
    if !results.skippedRows.is_empty() {
        diagnostics.push_str(&format!(
            "Skipped {} rows (missing corpus): {}. ",
            results.skippedRows.len(),
            results.skippedRows.join(", ")
        ));
    }
    if diagnostics.is_empty() {
        diagnostics.push_str("All computed Phase 2 gates passed on measured rows.");
    }

    Phase2GateReport {
        report_id: format!("phase2-gate-{}", chrono_date_stub()),
        surface: if results.surface.is_empty() {
            "compact".to_string()
        } else {
            results.surface.clone()
        },
        baseline_commit: results.baselineCommit.clone(),
        candidate_results: String::new(),
        compare_results_command: String::new(),
        session_net_accepted: results.session_net_accepted,
        session_net_all36: results.session_net_all36,
        h3_small_serve_s_gte_m_count: h3_violations.len(),
        h3_scope_row_count: h3_rows.len(),
        h3_policy_ref: "docs/research/A-012-bypass-policy.md".to_string(),
        h5_single_chain_violations: h5_violations,
        gates: Phase2GateStatuses {
            H1: GateStatus::NotClaimed,
            H2: GateStatus::NotClaimed,
            H3: h3_status,
            H4: h4_status,
            H5: h5_status,
            H6: GateStatus::NotClaimed,
            H7: GateStatus::NotClaimed,
            H8: GateStatus::NotClaimed,
        },
        diagnostics: diagnostics.trim().to_string(),
    }
}

fn chrono_date_stub() -> String {
    use std::time::{SystemTime, UNIX_EPOCH};
    let days = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs() / 86_400)
        .unwrap_or(0);
    format!("epoch-day-{days}")
}

/// Render gate report as markdown (typically written to `phase2-gate-report.generated.md`).
pub fn format_gate_report_markdown(report: &Phase2GateReport) -> String {
    let gates = &report.gates;
    format!(
        "# Phase 2 compact-surface gate report\n\n\
         **Report ID:** {report_id}  \n\
         **Surface:** {surface}  \n\
         **Baseline commit:** `{baseline}`  \n\
         **Candidate results:** `{candidate}`  \n\
         **Compare command:** `{command}`  \n\
         **H3 policy:** [{h3_policy}]({h3_policy})\n\n\
         ## Gate statuses\n\n\
         | Gate | Status |\n\
         |------|--------|\n\
         | H1 | {h1} |\n\
         | H2 | {h2} |\n\
         | H3 | {h3} |\n\
         | H4 | {h4} |\n\
         | H5 | {h5} |\n\
         | H6 | {h6} |\n\
         | H7 | {h7} |\n\
         | H8 | {h8} |\n\n\
         ## Computed metrics\n\n\
         - `session_net_accepted`: {accepted}\n\
         - `session_net_all36`: {all36}\n\
         - H3 scope rows: {h3_scope}\n\
         - H3 sGteM violations: {h3_violations}\n\
         - H5 single-chain violations: {h5_count}\n\n\
         ## Diagnostics\n\n\
         {diagnostics}\n\n\
         ## H3 scope note (A-012)\n\n\
         H3 evaluates **accepted serve** rows only (bypass/degrade/cache_hit excluded). \
         When no `*_small` task ids are present, all accepted serve rows in the golden corpus \
         are used (Phase 2 golden naming uses `tN` ids, not sf-bench `*_small` suffix).\n\n\
         ## H5 note\n\n\
         Compact surface uses one external `symforge` MCP call per task. Multi-hop rows \
         (`chain=multi`) may execute multiple legacy tools in-process but must still report \
         `mcpCalls=1`.\n",
        report_id = report.report_id,
        surface = report.surface,
        baseline = report.baseline_commit,
        candidate = report.candidate_results,
        command = report.compare_results_command,
        h3_policy = report.h3_policy_ref,
        h1 = gates.H1.as_str(),
        h2 = gates.H2.as_str(),
        h3 = gates.H3.as_str(),
        h4 = gates.H4.as_str(),
        h5 = gates.H5.as_str(),
        h6 = gates.H6.as_str(),
        h7 = gates.H7.as_str(),
        h8 = gates.H8.as_str(),
        accepted = report.session_net_accepted,
        all36 = report.session_net_all36,
        h3_scope = report.h3_scope_row_count,
        h3_violations = report.h3_small_serve_s_gte_m_count,
        h5_count = report.h5_single_chain_violations.len(),
        diagnostics = report.diagnostics,
    )
}

/// Phase 2 minimum exit gates (H3 + H4; H5 strongly recommended).
pub fn phase2_minimum_gates_pass(report: &Phase2GateReport) -> bool {
    report.gates.H3 == GateStatus::Pass && report.gates.H4 == GateStatus::Pass
}

#[cfg(test)]
mod tests {
    use super::*;

    fn sample_row(
        id: &str,
        decision: &str,
        equiv: &str,
        s: u32,
        m: u32,
        chain: &str,
    ) -> BatteryRow {
        BatteryRow {
            id: id.to_string(),
            corpus: "test".to_string(),
            S: s,
            M: m,
            sGteM: s >= m,
            acceptedServe: decision == "serve" && equiv == "EQUIVALENT",
            equivalence: equiv.to_string(),
            goldenId: id.to_string(),
            decision: decision.to_string(),
            chain: chain.to_string(),
            mcpCalls: 1,
            eligibleH6: true,
            stel: None,
        }
    }

    #[test]
    fn h3_passes_when_no_accepted_serve_s_gte_m() {
        let results = normalize_battery_results(BatteryResults {
            measuredAt: String::new(),
            symforgeBin: String::new(),
            surface: "compact".to_string(),
            method: String::new(),
            baselineCommit: "abc".to_string(),
            rows: vec![
                sample_row(
                    "cfg-if/t1_search",
                    "serve",
                    "EQUIVALENT",
                    100,
                    500,
                    "single",
                ),
                sample_row(
                    "cfg-if/pff_whole_lib",
                    "bypass",
                    "BYPASS",
                    50,
                    500,
                    "single",
                ),
            ],
            session_net_accepted: 0,
            session_net_all36: 0,
            rowCount: 0,
            skippedRows: vec![],
        });
        let report = compute_phase2_gates(&results);
        assert_eq!(report.gates.H3, GateStatus::Pass);
        assert_eq!(report.h3_scope_row_count, 1);
    }

    #[test]
    fn h3_fails_on_accepted_serve_s_gte_m() {
        let results = normalize_battery_results(BatteryResults {
            measuredAt: String::new(),
            symforgeBin: String::new(),
            surface: "compact".to_string(),
            method: String::new(),
            baselineCommit: String::new(),
            rows: vec![sample_row(
                "tokio/t2_small",
                "serve",
                "EQUIVALENT",
                600,
                500,
                "single",
            )],
            session_net_accepted: 0,
            session_net_all36: 0,
            rowCount: 0,
            skippedRows: vec![],
        });
        let report = compute_phase2_gates(&results);
        assert_eq!(report.gates.H3, GateStatus::Fail);
        assert_eq!(report.h3_small_serve_s_gte_m_count, 1);
    }

    #[test]
    fn h4_uses_accepted_serve_net_only() {
        let results = normalize_battery_results(BatteryResults {
            measuredAt: String::new(),
            symforgeBin: String::new(),
            surface: "compact".to_string(),
            method: String::new(),
            baselineCommit: String::new(),
            rows: vec![
                sample_row("a/t1", "serve", "EQUIVALENT", 100, 500, "single"),
                sample_row("b/pff", "bypass", "BYPASS", 900, 500, "single"),
            ],
            session_net_accepted: 0,
            session_net_all36: 0,
            rowCount: 0,
            skippedRows: vec![],
        });
        assert_eq!(results.session_net_accepted, 400);
        let report = compute_phase2_gates(&results);
        assert_eq!(report.gates.H4, GateStatus::Pass);
        assert!(results.session_net_all36 < results.session_net_accepted);
    }

    #[test]
    fn h5_fails_when_single_chain_exceeds_one_mcp_call() {
        let mut row = sample_row("x/t1", "serve", "EQUIVALENT", 10, 100, "single");
        row.mcpCalls = 2;
        let results = normalize_battery_results(BatteryResults {
            measuredAt: String::new(),
            symforgeBin: String::new(),
            surface: "compact".to_string(),
            method: String::new(),
            baselineCommit: String::new(),
            rows: vec![row],
            session_net_accepted: 0,
            session_net_all36: 0,
            rowCount: 0,
            skippedRows: vec![],
        });
        let report = compute_phase2_gates(&results);
        assert_eq!(report.gates.H5, GateStatus::Fail);
    }
}