req-cli 0.5.0-rc.7

Managed requirements CLI for LLM agents and humans
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
// REQ-0175..0184: external test-system integration.
//
// Two halves of one versioned contract with an external test orchestrator
// (e.g. the AugTronic at_test bench):
//   • EXPORT a machine-readable list of the requirements due for verification
//     (REQ-0175/0176), so the bench knows what the spec expects of it.
//   • INGEST the results it produces back into project.req as test records
//     (REQ-0177..0180), mapping its verdict vocabulary onto the local model
//     (REQ-0182), populating a verification dossier from its per-requirement
//     decision (REQ-0183), and never auto-promoting a safety requirement on
//     external evidence alone (REQ-0184).
//
// `req test pull` (REQ-0181) is the thin transport: an authenticated HTTP GET
// of a result payload that feeds the same ingest core a local file would.
use anyhow::{anyhow, Context, Result};
use chrono::Utc;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

use crate::cli::{TestIngestArgs, TestPullArgs, TestRequestsArgs};
use crate::model::{
    EvidenceKind, ExternalSource, Project, Status, TestOutcome, TestRecord, Verification,
    VerificationActivity,
};
use crate::storage::{self, load_for_mutation, load_resolved};

/// REQ-0176: the versioned schema tags. An ingested payload declaring an
/// unsupported version is rejected rather than mis-read.
pub const REQUEST_SCHEMA: &str = "req-test-request-v1";
pub const RESULT_SCHEMA: &str = "req-test-result-v1";

// --------------------------------------------------------------------------
// payloads (the published contract)
// --------------------------------------------------------------------------

#[derive(Serialize, Deserialize)]
pub struct RequestPayload {
    pub schema: String,
    pub commit: String,
    pub requirements: Vec<RequestItem>,
}

#[derive(Serialize, Deserialize)]
pub struct RequestItem {
    pub id: String,
    pub statement: String,
    pub acceptance: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sil: Option<String>,
}

#[derive(Deserialize)]
pub struct ResultPayload {
    pub schema: String,
    pub system: String,
    #[serde(default)]
    pub environment: Option<String>,
    pub commit: String,
    pub results: Vec<ResultItem>,
}

#[derive(Deserialize)]
pub struct ResultItem {
    pub req_id: String,
    pub verdict: String,
    #[serde(default)]
    pub notes: Option<String>,
    #[serde(default)]
    pub evidence_kind: Option<String>,
    #[serde(default)]
    pub decision: Option<Decision>,
}

#[derive(Deserialize)]
pub struct Decision {
    pub plan: String,
    #[serde(default)]
    pub analysis: Option<String>,
    #[serde(default)]
    pub statement: Option<String>,
}

// --------------------------------------------------------------------------
// REQ-0182: verdict mapping
// --------------------------------------------------------------------------

/// The built-in mapping from common external verdicts to the local model.
/// `bench_cap_suspected` and `error` map to Fail (not a clean pass);
/// `operator_override` maps to Pass but the raw verdict is preserved so the
/// nuance is never lost. A project may override any entry via config.
fn default_verdict(raw: &str) -> Option<TestOutcome> {
    match raw {
        "pass" => Some(TestOutcome::Pass),
        "fail" => Some(TestOutcome::Fail),
        "error" => Some(TestOutcome::Fail),
        "bench_cap_suspected" => Some(TestOutcome::Fail),
        "operator_override" => Some(TestOutcome::Pass),
        _ => None,
    }
}

/// Resolve an external verdict to a local outcome, honouring the project's
/// configured overrides first, then the built-in defaults. Returns an error
/// for an unmapped verdict (REQ-0182: never default to pass).
fn resolve_verdict(project: &Project, raw: &str) -> Result<TestOutcome> {
    if let Some(map) = project
        .config
        .as_ref()
        .and_then(|c| c.test_integration.as_ref())
        .and_then(|t| t.verdict_map.as_ref())
    {
        if let Some(v) = map.get(raw) {
            return match v.to_lowercase().as_str() {
                "pass" => Ok(TestOutcome::Pass),
                "fail" => Ok(TestOutcome::Fail),
                other => Err(anyhow!(
                    "verdict map entry '{}' => '{}' must be 'pass' or 'fail'",
                    raw,
                    other
                )),
            };
        }
    }
    default_verdict(raw).ok_or_else(|| {
        anyhow!(
            "external verdict '{}' has no mapping — add it to _config.test_integration.verdict_map (pass|fail); refusing to default to pass",
            raw
        )
    })
}

// --------------------------------------------------------------------------
// REQ-0175: export the requirements due for verification
// --------------------------------------------------------------------------

fn build_request(project: &Project) -> RequestPayload {
    let commit = current_head();
    let mut requirements = Vec::new();
    // "Due for verification" = an active requirement not yet Verified, past Draft.
    for (id, r) in &project.requirements {
        if matches!(r.status, Status::Approved | Status::Implemented) {
            requirements.push(RequestItem {
                id: id.clone(),
                statement: r.statement.clone(),
                acceptance: r.acceptance.clone(),
                sil: None,
            });
        }
    }
    for (id, sr) in &project.safety_requirements {
        if matches!(sr.status, Status::Approved | Status::Implemented) {
            requirements.push(RequestItem {
                id: id.clone(),
                statement: sr.statement.clone(),
                acceptance: sr.acceptance.clone(),
                sil: project.inherited_sil(sr).map(|s| s.as_str().to_string()),
            });
        }
    }
    requirements.sort_by(|a, b| a.id.cmp(&b.id));
    RequestPayload {
        schema: REQUEST_SCHEMA.to_string(),
        commit,
        requirements,
    }
}

pub fn requests(args: TestRequestsArgs, file: &Option<PathBuf>) -> Result<()> {
    let (_p, project) = load_resolved(file)?;
    let payload = build_request(&project);
    let body = serde_json::to_string_pretty(&payload)?;
    match &args.out {
        Some(path) => {
            std::fs::write(path, &body).with_context(|| format!("write {}", path))?;
            println!(
                "Wrote {} requirement(s) due for verification to {} (commit {}).",
                payload.requirements.len(),
                path,
                short(&payload.commit)
            );
        }
        None => println!("{}", body),
    }
    Ok(())
}

// --------------------------------------------------------------------------
// REQ-0177..0184: ingest results
// --------------------------------------------------------------------------

/// Outcome of an ingest, for the caller to render.
pub struct IngestReport {
    pub attached: usize,
    pub skipped_duplicate: usize,
    pub promoted: Vec<String>,
    pub withheld_safety: Vec<String>,
}

/// REQ-0178: check the whole payload before any mutation, so a malformed
/// or partially-unknown payload leaves project.req byte-identical.
fn preflight(project: &Project, payload: &ResultPayload) -> Result<()> {
    if payload.schema != RESULT_SCHEMA {
        return Err(anyhow!(
            "unsupported result schema '{}' (this binary speaks '{}')",
            payload.schema,
            RESULT_SCHEMA
        ));
    }
    if payload.commit.trim().is_empty() {
        return Err(anyhow!(
            "payload is missing the commit it was produced against"
        ));
    }
    if payload.system.trim().is_empty() {
        return Err(anyhow!(
            "payload is missing the originating system identity"
        ));
    }
    for r in &payload.results {
        let (id, fam) = crate::commands::verification::resolve(project, &r.req_id)
            .map_err(|_| anyhow!("result references unknown requirement '{}'", r.req_id))?;
        resolve_verdict(project, &r.verdict)?;
        // REQ-0183: a decision may only attach to a dossier anchored at the
        // same commit (or one with no conclusion yet).
        if r.decision.is_some() {
            let existing = crate::commands::verification::dossier(project, &id, fam);
            if let Some(v) = existing {
                if let Some(cc) = &v.concluded_commit {
                    if cc != &payload.commit {
                        return Err(anyhow!(
                            "{}: external decision is for commit {} but the dossier is anchored at {}",
                            id,
                            short(&payload.commit),
                            short(cc)
                        ));
                    }
                }
            }
        }
    }
    Ok(())
}

pub fn ingest_payload(
    project: &mut Project,
    payload: &ResultPayload,
    promote: bool,
) -> Result<IngestReport> {
    preflight(project, payload)?;
    let now = Utc::now();
    let mut report = IngestReport {
        attached: 0,
        skipped_duplicate: 0,
        promoted: Vec::new(),
        withheld_safety: Vec::new(),
    };
    for r in &payload.results {
        let (id, fam) = crate::commands::verification::resolve(project, &r.req_id)?;
        let outcome = resolve_verdict(project, &r.verdict)?;
        let kind = match r.evidence_kind.as_deref() {
            Some("composition") => EvidenceKind::Composition,
            Some("inspection") => EvidenceKind::Inspection,
            _ => EvidenceKind::Automated,
        };
        // REQ-0182: stamp the verdict-mapping version in effect onto the record.
        let external = ExternalSource {
            system: payload.system.clone(),
            environment: payload.environment.clone(),
            raw_verdict: Some(r.verdict.clone()),
            mapping_version: project
                .config
                .as_ref()
                .and_then(|c| c.test_integration.as_ref())
                .and_then(|t| t.version.clone()),
        };
        let record = TestRecord {
            at: now,
            actor: super::current_actor(),
            commit: payload.commit.clone(),
            outcome,
            notes: r.notes.clone().unwrap_or_default(),
            kind,
            content_hash: None,
            linked_files: None,
            sil_gate_exception: false,
            sil_at_verification: None,
            external: Some(external),
        };

        // REQ-0177: idempotent — skip an identical prior ingest.
        let is_sr = matches!(fam, crate::commands::verification::Family::Sr);
        let tests = if is_sr {
            &project.safety_requirements[&id].tests
        } else {
            &project.requirements[&id].tests
        };
        let dup = tests.iter().any(|t| {
            t.commit == record.commit
                && t.outcome == record.outcome
                && t.external.as_ref().map(|e| (&e.system, &e.raw_verdict))
                    == record
                        .external
                        .as_ref()
                        .map(|e| (&e.system, &e.raw_verdict))
        });
        if dup {
            report.skipped_duplicate += 1;
            continue;
        }

        // REQ-0183: populate the dossier from the external decision.
        let dossier = r.decision.as_ref().map(|d| {
            let mut v = Verification::opened(
                d.plan.clone(),
                payload.system.clone(),
                payload.commit.clone(),
                now,
            );
            if let Some(a) = &d.analysis {
                v.analysis = Some(VerificationActivity {
                    summary: a.clone(),
                    outcome,
                    references: Vec::new(),
                    at: now,
                    actor: payload.system.clone(),
                });
            }
            v.testing = Some(VerificationActivity {
                summary: r
                    .notes
                    .clone()
                    .unwrap_or_else(|| "external bench result".into()),
                outcome,
                references: Vec::new(),
                at: now,
                actor: payload.system.clone(),
            });
            v.statement = d.statement.clone();
            v.verdict = Some(outcome);
            v.concluded = Some(now);
            v.concluded_commit = Some(payload.commit.clone());
            v
        });

        if is_sr {
            let sr = project.safety_requirements.get_mut(&id).unwrap();
            sr.tests.push(record);
            if let Some(v) = dossier {
                sr.verification = Some(v);
            }
            sr.updated = now;
            sr.history.push(super::history(
                "external evidence ingested",
                r.notes.clone(),
            ));
            // REQ-0184: never auto-promote a safety requirement on external
            // evidence — that needs the human walkthrough + co-sign.
            if promote {
                report.withheld_safety.push(id.clone());
            }
        } else {
            let req = project.requirements.get_mut(&id).unwrap();
            req.tests.push(record);
            if let Some(v) = dossier {
                req.verification = Some(v);
            }
            req.updated = now;
            req.history.push(super::history(
                "external evidence ingested",
                r.notes.clone(),
            ));
            // REQ-0184: an ordinary requirement MAY be promoted when its
            // dossier is now complete and it is sitting at Implemented.
            if promote
                && matches!(outcome, TestOutcome::Pass)
                && matches!(req.status, Status::Implemented)
                && req
                    .verification
                    .as_ref()
                    .map(|v| v.passed())
                    .unwrap_or(false)
            {
                req.status = Status::Verified;
                req.history.push(super::history(
                    "promoted to verified (external dossier)",
                    None,
                ));
                report.promoted.push(id.clone());
            }
        }
        report.attached += 1;
    }
    Ok(report)
}

fn render_report(report: &IngestReport, system: &str) {
    println!(
        "Ingested {} result(s) from {} ({} duplicate(s) skipped).",
        report.attached, system, report.skipped_duplicate
    );
    if !report.promoted.is_empty() {
        println!("  promoted to Verified: {}", report.promoted.join(", "));
    }
    for id in &report.withheld_safety {
        println!(
            "  {}: safety requirement NOT promoted on external evidence — record a human walkthrough + co-sign (REQ-0184)",
            id
        );
    }
}

pub fn ingest(args: TestIngestArgs, file: &Option<PathBuf>) -> Result<()> {
    let raw = std::fs::read_to_string(&args.source)
        .with_context(|| format!("read result payload {}", args.source))?;
    let payload: ResultPayload = serde_json::from_str(&raw).map_err(|e| {
        anyhow!(
            "result payload is not valid JSON ({}). See `req schema test-result`.",
            e
        )
    })?;
    let (path, mut project, _lock) = load_for_mutation(file)?;
    let report = ingest_payload(&mut project, &payload, args.promote)?;
    if report.attached > 0 || !report.promoted.is_empty() {
        project.updated = Utc::now();
        storage::save(&path, &project)?;
    }
    render_report(&report, &payload.system);
    Ok(())
}

// --------------------------------------------------------------------------
// REQ-0181: authenticated HTTP pull
// --------------------------------------------------------------------------

pub fn pull(args: TestPullArgs, file: &Option<PathBuf>) -> Result<()> {
    // Fetch first; only touch project.req once we have a valid payload, so a
    // network or auth failure leaves the spec unchanged.
    let mut req = ureq::get(&args.from);
    if let Some(token) = &args.token {
        req = req.set("Authorization", &format!("Bearer {}", token));
    }
    let body = req
        .call()
        .map_err(|e| anyhow!("fetch {} failed: {}", args.from, e))?
        .into_string()
        .context("read response body")?;
    let payload: ResultPayload = serde_json::from_str(&body)
        .map_err(|e| anyhow!("response is not a valid result payload ({})", e))?;
    let (path, mut project, _lock) = load_for_mutation(file)?;
    let report = ingest_payload(&mut project, &payload, args.promote)?;
    if report.attached > 0 || !report.promoted.is_empty() {
        project.updated = Utc::now();
        storage::save(&path, &project)?;
    }
    render_report(&report, &payload.system);
    Ok(())
}

// --------------------------------------------------------------------------
// helpers
// --------------------------------------------------------------------------

fn current_head() -> String {
    std::process::Command::new("git")
        .args(["rev-parse", "HEAD"])
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
        .unwrap_or_default()
}

fn short(sha: &str) -> &str {
    &sha[..sha.len().min(8)]
}