remem-ai 0.6.78

Local-first coding agent memory for Claude Code and OpenAI Codex
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
use std::collections::BTreeSet;
use std::fs;
use std::path::Path;

use rusqlite::{Connection, OpenFlags};
use serde_json::Value;
use sha2::{Digest, Sha256};

use super::{
    read_json, rel_display, require_artifact_key, require_non_blank, scan_private_json,
    validate_artifact_map, validate_environment, VerifyState,
};
use crate::eval::bench_artifact::types::{
    BenchmarkLayer, CodingMemoryContract, CodingRunArtifact, PublicBenchmarkReport,
};
use crate::eval::coding_bench::{
    verify_context_audit_snapshot, verify_snapshot_against_persisted_injection,
    RememContextAuditStatus,
};

#[cfg(test)]
mod tests;

const CODING_ARTIFACT_KEYS: [&str; 3] = ["patch", "tool_log", "test_log"];

const PUBLIC_CODING_CONDITIONS: [&str; 11] = [
    "no_memory",
    "curated_file_budgeted",
    "remem_e2e",
    "remem_seeded_sessionstart",
    "curated_file_expert",
    "oracle_evidence",
    "remem_oracle_retrieval",
    "full_history",
    "remem_no_enrichment",
    "remem_fts_only",
    "remem_preloaded",
];

const CODING_FAILURE_REASONS: [&str; 11] = [
    "test_failure",
    "timeout",
    "compile_failure",
    "wrong_file_modified",
    "ignored_memory",
    "missing_memory",
    "stale_memory_followed",
    "irrelevant_memory_distracted",
    "over_context_budget",
    "agent_hallucinated_memory",
    "oracle_inconclusive",
];

pub(super) fn validate_coding_run_artifact(
    run_path: &Path,
    report: &PublicBenchmarkReport,
    _manifest_path: &Path,
    state: &mut VerifyState,
) -> Option<String> {
    state.run_artifacts_checked += 1;
    let raw_run = read_json::<Value>(run_path, state, "coding run artifact")?;
    let run = match serde_json::from_value::<CodingRunArtifact>(raw_run.clone()) {
        Ok(run) => run,
        Err(error) => {
            state.fail(
                rel_display(&state.root, run_path),
                format!("validate coding run artifact schema: {error}"),
            );
            return None;
        }
    };
    let label = rel_display(&state.root, run_path);
    if run.schema_version != 1 {
        state.fail(label.clone(), "coding run schema_version must be 1");
    }
    require_non_blank(&run.benchmark_id, &label, "benchmark_id", state);
    require_non_blank(&run.benchmark_version, &label, "benchmark_version", state);
    require_non_blank(&run.run_phase, &label, "run_phase", state);
    require_non_blank(&run.matrix_namespace, &label, "matrix_namespace", state);
    if run.benchmark_id != report.benchmark_id
        || run.benchmark_version != report.benchmark_version
        || Some(run.run_phase.as_str()) != report.run_phase.as_deref()
        || Some(run.matrix_namespace.as_str()) != report.matrix_namespace.as_deref()
    {
        state.fail(
            label.clone(),
            "coding run benchmark identity must match its report",
        );
    }
    if run.layer != BenchmarkLayer::CodingAgentOutcome || run.layer != report.layer {
        state.fail(
            label.clone(),
            "coding run layer must be coding_agent_outcome",
        );
    }
    require_non_blank(&run.benchmark_version, &label, "benchmark_version", state);
    require_non_blank(&run.condition, &label, "condition", state);
    if !is_public_coding_condition(&run.condition) {
        state.fail(label.clone(), "coding run has unknown condition identity");
    }
    if !report.conditions.contains(&run.condition) {
        state.fail(
            label.clone(),
            "coding run condition must be declared by its report",
        );
    }
    require_non_blank(&run.task_id, &label, "task_id", state);
    let run_key = format!(
        "{}\0{}\0{}\0{}\0{}",
        report.benchmark_id, report.benchmark_version, run.condition, run.task_id, run.run_index
    );
    if !state.coding_run_keys.insert(run_key) {
        state.fail(
            label.clone(),
            "coding task/condition/run_index key must be unique within a benchmark version",
        );
    }
    validate_attempt_state(&run, &raw_run, &label, state);
    validate_environment(&run.environment, &label, state);
    if run.model.is_null() {
        state.fail(label.clone(), "coding run model must be present");
    }
    validate_outcome(&run, &label, state);
    validate_coding_metrics(&run, &label, state);
    validate_artifact_map(&run.artifacts, CODING_ARTIFACT_KEYS, &label, state);
    if requires_remem_evidence(&run.condition) {
        require_artifact_key(&run.artifacts, "injected_context", &label, state);
        require_artifact_key(&run.artifacts, "remem_db_snapshot", &label, state);
        if let Some(contract) = &run.memory_contract {
            validate_coding_memory_contract(contract, run.failure_reason.as_deref(), &label, state);
        } else {
            state.fail(
                label.clone(),
                "remem-backed coding run must include memory_contract",
            );
        }
    } else if run.memory_contract.is_some() {
        state.fail(
            label.clone(),
            "non-remem coding condition must not include memory_contract",
        );
    }
    validate_coding_context_audit(&run, &raw_run, &label, state);
    scan_private_json(
        &serde_json::to_value(&run).unwrap_or(Value::Null),
        run_path,
        "$",
        state,
    );
    Some(run.condition)
}

fn validate_outcome(run: &CodingRunArtifact, label: &str, state: &mut VerifyState) {
    if run.resolved {
        if run.failure_reason.is_some() {
            state.fail(
                label.to_string(),
                "resolved coding run must not carry failure_reason",
            );
        }
    } else {
        let Some(reason) = run.failure_reason.as_deref().map(str::trim) else {
            state.fail(
                label.to_string(),
                "failed coding run must carry failure_reason",
            );
            return;
        };
        if !CODING_FAILURE_REASONS.contains(&reason) {
            state.fail(
                label.to_string(),
                "coding run has unknown failure_reason enum",
            );
        }
    }
}

fn validate_attempt_state(
    run: &CodingRunArtifact,
    raw_run: &Value,
    label: &str,
    state: &mut VerifyState,
) {
    let official = run.run_phase == "official";
    if official {
        for field in ["attempt_id", "target_started"] {
            if raw_run.get(field).is_none() {
                state.fail(
                    label.to_string(),
                    format!("official coding run must include explicit {field}"),
                );
            }
        }
    }

    match run.attempt_id.as_deref() {
        Some(attempt_id) if attempt_id.trim().is_empty() => {
            state.fail(label.to_string(), "coding run attempt_id must not be blank");
        }
        Some(attempt_id) if !state.coding_attempt_ids.insert(attempt_id.to_string()) => {
            state.fail(
                label.to_string(),
                "coding run attempt_id must be unique across the public artifact suite",
            );
        }
        Some(_) => {}
        None if official => {
            state.fail(
                label.to_string(),
                "official coding run attempt_id must be a non-blank string",
            );
        }
        None => {}
    }

    if official && run.target_started.is_none() {
        state.fail(
            label.to_string(),
            "official coding run target_started must be a boolean",
        );
    }
    if run.resolved && run.target_started == Some(false) {
        state.fail(
            label.to_string(),
            "resolved coding run cannot report target_started=false",
        );
    }
    if run.attempt_id.is_some() != run.target_started.is_some() {
        state.fail(
            label.to_string(),
            "coding run attempt_id and target_started must be present together",
        );
    }
}

fn validate_coding_metrics(run: &CodingRunArtifact, label: &str, state: &mut VerifyState) {
    if let (Some(input), Some(output), Some(total)) = (
        run.metrics.tokens_input,
        run.metrics.tokens_output,
        run.metrics.tokens_total,
    ) {
        if input.saturating_add(output) != total {
            state.fail(label.to_string(), "coding run token totals do not add up");
        }
    } else {
        state.fail(
            label.to_string(),
            "coding run must include complete token accounting",
        );
    }
    if run.metrics.turns.is_none() {
        state.fail(label.to_string(), "coding run is missing turns");
    }
    if run.metrics.wall_time_ms.is_none() {
        state.fail(label.to_string(), "coding run is missing wall_time_ms");
    }
    if run.metrics.tool_calls.is_none() {
        state.fail(label.to_string(), "coding run is missing tool_calls");
    }
    if run.metrics.commands_run.is_none() {
        state.fail(label.to_string(), "coding run is missing commands_run");
    }
}

fn validate_coding_context_audit(
    run: &CodingRunArtifact,
    raw_run: &Value,
    label: &str,
    state: &mut VerifyState,
) {
    if requires_context_audit(&run.condition) {
        require_explicit_audit_fields(raw_run, label, state);
        if run.context_audit_status != Some(RememContextAuditStatus::Verified) {
            state.fail(
                label.to_string(),
                "current remem-backed coding run must carry verified ContextAudit status",
            );
        }
        if run.context_audit_failure_reason.is_some() {
            state.fail(
                label.to_string(),
                "verified ContextAudit must not carry a failure reason",
            );
        }
        let Some(snapshot) = &run.remem_context_audit else {
            state.fail(
                label.to_string(),
                "current remem-backed coding run must include a ContextAudit snapshot",
            );
            return;
        };
        if let Err(error) = verify_context_audit_snapshot(snapshot) {
            state.fail(
                label.to_string(),
                format!("invalid ContextAudit snapshot: {error}"),
            );
        } else {
            validate_persisted_context_audit_provenance(run, snapshot, label, state);
        }
    } else if run.condition == "remem_preloaded" {
        if run.context_audit_status.is_some()
            || run.context_audit_failure_reason.is_some()
            || run.remem_context_audit.is_some()
            || run.injected_context_sha256.is_some()
        {
            state.fail(
                label.to_string(),
                "historical remem_preloaded run must not claim current ContextAudit evidence",
            );
        }
    } else {
        require_explicit_audit_fields(raw_run, label, state);
        if run.context_audit_status != Some(RememContextAuditStatus::NotApplicable) {
            state.fail(
                label.to_string(),
                "non-remem coding condition must mark ContextAudit not_applicable",
            );
        }
        if run.context_audit_failure_reason.is_some()
            || run.remem_context_audit.is_some()
            || run.injected_context_sha256.is_some()
        {
            state.fail(
                label.to_string(),
                "not_applicable ContextAudit must not carry a failure reason or snapshot",
            );
        }
    }
}

fn validate_persisted_context_audit_provenance(
    run: &CodingRunArtifact,
    snapshot: &crate::eval::coding_bench::RememContextAuditSnapshot,
    label: &str,
    state: &mut VerifyState,
) {
    let Some(context_path) = artifact_file_path(run, "injected_context", label, state) else {
        return;
    };
    let Some(database_path) = artifact_file_path(run, "remem_db_snapshot", label, state) else {
        return;
    };
    let injected_context = match fs::read_to_string(&context_path) {
        Ok(context) => context,
        Err(error) => {
            state.fail(
                label.to_string(),
                format!("read injected_context artifact: {error}"),
            );
            return;
        }
    };
    let actual_sha256 = format!("{:x}", Sha256::digest(injected_context.as_bytes()));
    if run.injected_context_sha256.as_deref() != Some(actual_sha256.as_str()) {
        state.fail(
            label.to_string(),
            "injected_context_sha256 must bind the exact injected_context bytes",
        );
        return;
    }
    let connection = match Connection::open_with_flags(
        &database_path,
        OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
    ) {
        Ok(connection) => connection,
        Err(error) => {
            state.fail(
                label.to_string(),
                format!("open read-only remem_db_snapshot: {error}"),
            );
            return;
        }
    };
    if let Err(error) =
        verify_snapshot_against_persisted_injection(&connection, snapshot, &injected_context)
    {
        state.fail(
            label.to_string(),
            format!("ContextAudit provenance verification failed: {error}"),
        );
    }
}

fn artifact_file_path(
    run: &CodingRunArtifact,
    key: &str,
    label: &str,
    state: &mut VerifyState,
) -> Option<std::path::PathBuf> {
    let raw_path = run.artifacts.get(key)?;
    let path = super::resolve_public_path(state, raw_path, raw_path)?;
    if !path.is_file() {
        state.fail(
            label.to_string(),
            format!("artifact file for {key} is missing"),
        );
        return None;
    }
    Some(path)
}

fn require_explicit_audit_fields(raw_run: &Value, label: &str, state: &mut VerifyState) {
    for field in [
        "context_audit_status",
        "context_audit_failure_reason",
        "remem_context_audit",
        "injected_context_sha256",
    ] {
        if raw_run.get(field).is_none() {
            state.fail(
                label.to_string(),
                format!("coding run must include explicit {field}"),
            );
        }
    }
}

pub(super) fn is_public_coding_condition(condition: &str) -> bool {
    PUBLIC_CODING_CONDITIONS.contains(&condition)
}

#[cfg(test)]
pub(in crate::eval::bench_artifact) fn public_coding_conditions() -> &'static [&'static str] {
    &PUBLIC_CODING_CONDITIONS
}

pub(in crate::eval::bench_artifact) fn requires_remem_evidence(condition: &str) -> bool {
    condition.starts_with("remem_")
}

fn requires_context_audit(condition: &str) -> bool {
    requires_remem_evidence(condition) && condition != "remem_preloaded"
}

fn validate_coding_memory_contract(
    contract: &CodingMemoryContract,
    failure_reason: Option<&str>,
    label: &str,
    state: &mut VerifyState,
) {
    validate_rate(
        contract.citation_precision,
        "memory_contract.citation_precision",
        label,
        state,
    );
    validate_rate(
        contract.citation_recall,
        "memory_contract.citation_recall",
        label,
        state,
    );
    require_unique_positive_ids(
        &contract.injected_memory_ids,
        "memory_contract.injected_memory_ids",
        label,
        state,
    );
    require_unique_positive_ids(
        &contract.used_memory_ids,
        "memory_contract.used_memory_ids",
        label,
        state,
    );
    if contract.memory_helped && contract.memory_hurt {
        state.fail(
            label.to_string(),
            "memory_contract cannot mark both memory_helped and memory_hurt",
        );
    }
    if failure_reason.is_some_and(is_memory_specific_failure_reason) && !contract.memory_hurt {
        state.fail(
            label.to_string(),
            "memory-specific failure_reason requires memory_contract.memory_hurt=true",
        );
    }
}

fn validate_rate(value: f64, field: &str, label: &str, state: &mut VerifyState) {
    if !(0.0..=1.0).contains(&value) || !value.is_finite() {
        state.fail(
            label.to_string(),
            format!("{field} must be a finite rate between 0 and 1"),
        );
    }
}

fn require_unique_positive_ids(ids: &[i64], field: &str, label: &str, state: &mut VerifyState) {
    let mut seen = BTreeSet::new();
    for id in ids {
        if *id <= 0 {
            state.fail(
                label.to_string(),
                format!("{field} contains non-positive id"),
            );
        }
        if !seen.insert(*id) {
            state.fail(label.to_string(), format!("{field} contains duplicate id"));
        }
    }
}

fn is_memory_specific_failure_reason(reason: &str) -> bool {
    matches!(
        reason,
        "ignored_memory"
            | "missing_memory"
            | "stale_memory_followed"
            | "irrelevant_memory_distracted"
            | "agent_hallucinated_memory"
    )
}