From 7eca0cf14a74fea0fb6ed134b787c8f81de2a758 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 23:03:01 +0000 Subject: [PATCH 1/4] fix(report): emit assault-report Nickel that the Nickel parser accepts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The --output-format nickel writer used `field = value;` lines and a `};\nassault_report` tail, the same invalid form #300 fixed in the manifest export; nickel export 1.18.0 rejects it. It now builds its fields with the a2ml module's nickel_record (`,` separators) and the new shared nickel_let (`let … in`). Non-finite floats become null instead of a NaN token. Also replaces three |e| e.to_str() closures in src/a2ml/mod.rs with OsStr::to_str (Sonar S1612). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0136P7ZoBy5xGnGDLk7wQ8jC --- src/a2ml/mod.rs | 22 ++++-- src/report/output.rs | 174 +++++++++++++++++++++++++++++++++++-------- 2 files changed, 161 insertions(+), 35 deletions(-) diff --git a/src/a2ml/mod.rs b/src/a2ml/mod.rs index 04c8eb6..5556bd4 100644 --- a/src/a2ml/mod.rs +++ b/src/a2ml/mod.rs @@ -16,6 +16,7 @@ use crate::types::{AssailReport, AssaultReport, AttackResult}; use crate::{abduct, adjudicate, amuck, axial}; use anyhow::{anyhow, Context, Result}; use serde::de::DeserializeOwned; +use std::ffi::OsStr; use std::fs; use std::path::{Path, PathBuf}; @@ -206,7 +207,7 @@ impl Manifest { pub fn load(path: &Path) -> Result { let raw = fs::read_to_string(path) .with_context(|| format!("reading AI manifest {}", path.display()))?; - let mut manifest = if path.extension().and_then(|e| e.to_str()) == Some("deed") { + let mut manifest = if path.extension().and_then(OsStr::to_str) == Some("deed") { Self::parse_deed(&raw, path)? } else { Self::parse_a2ml(&raw)? @@ -237,7 +238,7 @@ impl Manifest { deed.head )); } - if path.file_name().and_then(|n| n.to_str()) == Some(MANIFEST_CANDIDATES[0]) { + if path.file_name().and_then(OsStr::to_str) == Some(MANIFEST_CANDIDATES[0]) { check_pointer_profile(&deed.items) .map_err(|e| anyhow!("{}: not a pointer-only manifest: {}", path.display(), e))?; } @@ -403,7 +404,7 @@ impl Manifest { } else { record_to_nickel(&gather_entries(&self.entries)) }; - format!("let {} = {} in\n{}", self.root_name, body, self.root_name) + nickel_let(&self.root_name, &body) } /// The legacy `(reports …)` section; never read from a deed. @@ -502,7 +503,7 @@ fn load_payload_for_kind(kind: ReportBundleKind, input: &Path) -> Result(path: &Path) -> Result { let raw = fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?; - match path.extension().and_then(|e| e.to_str()) { + match path.extension().and_then(OsStr::to_str) { Some(ext) if crate::yaml::is_extension(ext) => crate::yaml::from_report_str::(&raw) .with_context(|| format!("parsing {}", path.display())), _ => serde_json::from_str::(&raw).with_context(|| format!("parsing {}", path.display())), @@ -982,8 +983,10 @@ fn record_to_nickel(entries: &[(String, Vec>)]) -> String { nickel_record(lines) } -/// Field lines (`key = value`) as a Nickel record body. -fn nickel_record(lines: Vec) -> String { +/// Field lines (`key = value`) as a Nickel record body: fields separated by +/// `,`, as Nickel requires. Shared with the assault-report writer in +/// `crate::report::output`. +pub(crate) fn nickel_record(lines: Vec) -> String { if lines.is_empty() { return "{}".to_string(); } @@ -1034,6 +1037,13 @@ fn value_to_nickel(value: &Sexpr) -> String { } } +/// A Nickel program that binds `body` to `name` and evaluates to it: +/// `let name = body in\nname`. Nickel has no `let name = body;` statement form. +pub(crate) fn nickel_let(name: &str, body: &str) -> String { + format!("let {name} = {body} in\n{name}") +} + +/// A record key as Nickel: bare when it is an identifier, quoted otherwise. fn key_to_nickel(key: &str) -> String { if key .chars() diff --git a/src/report/output.rs b/src/report/output.rs index 410ced3..079c8b2 100644 --- a/src/report/output.rs +++ b/src/report/output.rs @@ -3,6 +3,7 @@ //! Serialization helpers for printed/exported reports +use crate::a2ml::{nickel_let, nickel_record}; use crate::report::formatter::nickel_escape_string; use crate::types::AssaultReport; use anyhow::Result; @@ -57,26 +58,26 @@ impl ReportOutputFormat { fn format_report_as_nickel(report: &AssaultReport) -> String { // The Nickel representation intentionally samples large collections to stay readable. let assail = &report.assail_report; + // Fields are `key = value` lines; `nickel_record` joins them with `,`. let mut lines = Vec::new(); - lines.push("let assault_report = {".to_string()); lines.push(format!( - " program = {};", + "program = {}", nickel_escape_string(&assail.program_path.to_string_lossy()) )); lines.push(format!( - " language = {};", + "language = {}", nickel_escape_string(&format!("{:?}", assail.language)) )); - lines.push(format!(" framework_count = {};", assail.frameworks.len())); - lines.push(format!(" weak_points = {};", assail.weak_points.len())); - lines.push(format!(" total_crashes = {};", report.total_crashes)); - lines.push(format!(" total_signatures = {};", report.total_signatures)); + lines.push(format!("framework_count = {}", assail.frameworks.len())); + lines.push(format!("weak_points = {}", assail.weak_points.len())); + lines.push(format!("total_crashes = {}", report.total_crashes)); + lines.push(format!("total_signatures = {}", report.total_signatures)); let axes: Vec = report .attack_results .iter() .map(|r| nickel_escape_string(&format!("{:?}", r.axis))) .collect(); - lines.push(format!(" attack_axes = [{}];", axes.join(", "))); + lines.push(format!("attack_axes = [{}]", axes.join(", "))); if !assail.weak_points.is_empty() { let weak_summary: Vec = assail @@ -92,7 +93,7 @@ fn format_report_as_nickel(report: &AssaultReport) -> String { }) .collect(); lines.push(format!( - " weak_point_samples = [{}];", + "weak_point_samples = [{}]", weak_summary.join(", ") )); } @@ -104,49 +105,46 @@ fn format_report_as_nickel(report: &AssaultReport) -> String { .take(3) .map(|row| { format!( - "{{ source = {}, sink = {}, severity = {:.1} }}", + "{{ source = {}, sink = {}, severity = {} }}", nickel_escape_string(&format!("{:?}", row.source_category)), nickel_escape_string(&format!("{:?}", row.sink_axis)), - row.severity_value + nickel_number(row.severity_value, Some(1)) ) }) .collect(); if !pivot_rows.is_empty() { - lines.push(format!(" pivot_samples = [{}];", pivot_rows.join(", "))); + lines.push(format!("pivot_samples = [{}]", pivot_rows.join(", "))); } if let Some(timeline) = &report.timeline { lines.push(format!( - " timeline_duration = {};", - timeline.duration.as_secs_f64() + "timeline_duration = {}", + nickel_number(timeline.duration.as_secs_f64(), None) )); - lines.push(format!(" timeline_events = {};", timeline.events.len())); + lines.push(format!("timeline_events = {}", timeline.events.len())); let event_samples: Vec = timeline .events .iter() .take(3) .map(|event| { format!( - "{{ id = {}, axis = {}, start = {:.2}, duration = {:.2}, intensity = {} }}", + "{{ id = {}, axis = {}, start = {}, duration = {}, intensity = {} }}", nickel_escape_string(&event.id), nickel_escape_string(&format!("{:?}", event.axis)), - event.start_offset.as_secs_f64(), - event.duration.as_secs_f64(), + nickel_number(event.start_offset.as_secs_f64(), Some(2)), + nickel_number(event.duration.as_secs_f64(), Some(2)), nickel_escape_string(&format!("{:?}", event.intensity)) ) }) .collect(); if !event_samples.is_empty() { - lines.push(format!( - " timeline_samples = [{}];", - event_samples.join(", ") - )); + lines.push(format!("timeline_samples = [{}]", event_samples.join(", "))); } } lines.push(format!( - " robustness_score = {:.1};", - report.overall_assessment.robustness_score + "robustness_score = {}", + nickel_number(report.overall_assessment.robustness_score, Some(1)) )); if !report.overall_assessment.critical_issues.is_empty() { @@ -156,7 +154,7 @@ fn format_report_as_nickel(report: &AssaultReport) -> String { .iter() .map(|issue| nickel_escape_string(issue)) .collect(); - lines.push(format!(" critical_issues = [{}];", issue_list.join(", "))); + lines.push(format!("critical_issues = [{}]", issue_list.join(", "))); } if !report.overall_assessment.recommendations.is_empty() { @@ -166,10 +164,128 @@ fn format_report_as_nickel(report: &AssaultReport) -> String { .iter() .map(|rec| nickel_escape_string(rec)) .collect(); - lines.push(format!(" recommendations = [{}];", rec_list.join(", "))); + lines.push(format!("recommendations = [{}]", rec_list.join(", "))); } - lines.push("};".to_string()); - lines.push("assault_report".to_string()); - lines.join("\n") + nickel_let("assault_report", &nickel_record(lines)) +} + +/// An `f64` as a Nickel number with `decimals` places (or Rust's shortest +/// form for `None`). NaN and the infinities have no Nickel literal, so they +/// become `null` rather than an unparseable token. +fn nickel_number(value: f64, decimals: Option) -> String { + if !value.is_finite() { + return "null".to_string(); + } + match decimals { + Some(places) => format!("{value:.places$}"), + None => format!("{value}"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::types::{ + AttackAxis, IntensityLevel, OverallAssessment, TaintMatrixRow, TimelineEventReport, + TimelineReport, WeakPoint, WeakPointCategory, + }; + use std::fs; + use std::time::Duration; + use tempfile::TempDir; + + /// An assault report with every section the Nickel writer emits: weak + /// points, a taint row, a timeline, issues and recommendations. + fn full_report(dir: &TempDir) -> AssaultReport { + fs::write(dir.path().join("main.rs"), "fn main() {}\n").expect("write"); + let mut assail = crate::assail::analyze(dir.path()).expect("analyze"); + let weak: WeakPoint = serde_json::from_value(serde_json::json!({ + "category": "PanicPath", + "location": "main.rs:1", + "severity": "High", + "description": "unwrap on a None", + "recommended_attack": ["cpu"], + })) + .expect("weak point"); + assail.weak_points.push(weak); + assail.taint_matrix.rows.push(TaintMatrixRow { + source_category: WeakPointCategory::PanicPath, + sink_axis: AttackAxis::Cpu, + severity_value: 3.25, + files: vec!["main.rs".to_string()], + frameworks: Vec::new(), + relation: "direct".to_string(), + }); + AssaultReport { + schema_version: "2.5".to_string(), + assail_report: assail, + attack_results: Vec::new(), + total_crashes: 1, + total_signatures: 0, + overall_assessment: OverallAssessment { + robustness_score: 42.0, + critical_issues: vec!["crash".to_string()], + recommendations: vec!["fix it".to_string()], + }, + timeline: Some(TimelineReport { + duration: Duration::from_millis(1500), + events: vec![TimelineEventReport { + id: "evt-1".to_string(), + axis: AttackAxis::Memory, + start_offset: Duration::from_secs(5), + duration: Duration::from_secs(10), + intensity: IntensityLevel::Medium, + args: Vec::new(), + peak_memory: None, + ran: true, + }], + }), + } + } + + #[test] + fn assault_report_nickel_uses_nickel_record_and_let_syntax() { + // Nickel separates record fields with `,` and binds with `let … in`; + // the old `field = value;` lines and `};\nassault_report` tail did not + // parse (`nickel export` 1.18.0: "unexpected token"). + let dir = TempDir::new().expect("tempdir"); + let nickel = format_report_as_nickel(&full_report(&dir)); + assert!(nickel.starts_with("let assault_report = {\n"), "{nickel}"); + assert!(nickel.ends_with("\n} in\nassault_report"), "{nickel}"); + assert!(nickel.contains(",\n weak_points = 1,\n"), "{nickel}"); + assert!(!nickel.contains(';'), "{nickel}"); + + // Where the Nickel CLI is installed, it must accept the output and + // keep the types: counts and scores are numbers, not strings. + let file = dir.path().join("report.ncl"); + fs::write(&file, &nickel).expect("write"); + if let Ok(out) = std::process::Command::new("nickel") + .args(["export", "--format", "json"]) + .arg(&file) + .output() + { + assert!( + out.status.success(), + "{nickel}\n{}", + String::from_utf8_lossy(&out.stderr) + ); + let json: serde_json::Value = + serde_json::from_slice(&out.stdout).expect("nickel export emits JSON"); + assert_eq!(json["weak_points"], 1); + assert_eq!(json["robustness_score"], 42.0); + assert_eq!(json["timeline_duration"], 1.5); + assert_eq!(json["timeline_samples"][0]["start"], 5.0); + assert_eq!(json["pivot_samples"][0]["severity"], 3.2); + assert_eq!(json["weak_point_samples"][0]["category"], "PanicPath"); + assert_eq!(json["critical_issues"][0], "crash"); + } + } + + #[test] + fn non_finite_numbers_become_null() { + assert_eq!(nickel_number(f64::NAN, Some(1)), "null"); + assert_eq!(nickel_number(f64::INFINITY, None), "null"); + assert_eq!(nickel_number(2.0, Some(1)), "2.0"); + assert_eq!(nickel_number(1.5, None), "1.5"); + } } From 235804be9235e654cb07ed54d43a6f3be725f3c5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 23:03:01 +0000 Subject: [PATCH 2/4] fix(cli): do not warn when no AI manifest exists run_main loaded the manifest with load_default, which errors on a missing file, so every command run outside a repo with a manifest printed "warning: failed to read AI manifest". It now uses load_if_exists: a missing manifest means the defaults, silently; one that exists but cannot be read or parsed still warns. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0136P7ZoBy5xGnGDLk7wQ8jC --- src/main.rs | 8 ++++++-- tests/manifest_cli.rs | 45 ++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 48 insertions(+), 5 deletions(-) diff --git a/src/main.rs b/src/main.rs index 257196d..0b264ca 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1539,7 +1539,8 @@ fn main() -> Result<()> { } /// Parse process arguments and execute the selected command, including its output -/// and requested persistence. Default manifest settings are used if loading fails. +/// and requested persistence. Default manifest settings are used when no manifest +/// exists (silently) or when one exists but does not load (with a warning). /// Argument parsing exits the process for help or invalid CLI syntax. /// For assail with `--fail-on-incomplete`, exits with status 2 when coverage is /// not `complete`, after report output and any requested attestation are written. @@ -1549,7 +1550,10 @@ fn main() -> Result<()> { /// operation errors that are not handled by a command-specific fallback. fn run_main() -> Result<()> { let cli = Cli::parse(); - let manifest = match Manifest::load_default() { + // A missing manifest is the normal case for most directories: use the + // defaults without a word. Warn only when a manifest exists but cannot be + // read or parsed. + let manifest = match Manifest::load_if_exists(&Manifest::default_path()) { Ok(manifest) => manifest, Err(err) => { eprintln!("warning: failed to read AI manifest: {}", err); diff --git a/tests/manifest_cli.rs b/tests/manifest_cli.rs index f83db60..511f59a 100644 --- a/tests/manifest_cli.rs +++ b/tests/manifest_cli.rs @@ -1,9 +1,10 @@ // SPDX-License-Identifier: MPL-2.0 // SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell -//! CLI contract for `panic-attack manifest` and `panic-attack diagnostics`: -//! a manifest that exists but does not load is an error, never the built-in -//! defaults. +//! CLI contract for `panic-attack manifest`, `panic-attack diagnostics` and +//! the start-up manifest load. A missing manifest means the built-in defaults, +//! silently. A manifest that exists but does not load is an error (at start-up, +//! a warning), never silently the defaults. use std::fs; use std::path::Path; @@ -81,3 +82,41 @@ fn diagnostics_fails_on_a_malformed_default_deed() { "{o:?}" ); } + +/// stderr of `panic-attack completions bash`, a command that reads no +/// manifest itself, so only the start-up manifest load can speak. +fn startup_stderr(dir: &Path) -> String { + let o = run(dir, &["completions", "bash"]); + assert!(o.status.success(), "{o:?}"); + String::from_utf8_lossy(&o.stderr).into_owned() +} + +#[test] +fn no_manifest_is_not_a_warning() { + let dir = TempDir::new().unwrap(); + let stderr = startup_stderr(dir.path()); + assert!(!stderr.contains("failed to read AI manifest"), "{stderr}"); +} + +#[test] +fn a_valid_pointer_deed_is_not_a_warning() { + let dir = TempDir::new().unwrap(); + fs::write(dir.path().join("0-AI-MANIFEST.deed"), POINTER_MANIFEST).unwrap(); + let stderr = startup_stderr(dir.path()); + assert!(!stderr.contains("failed to read AI manifest"), "{stderr}"); +} + +#[test] +fn a_malformed_manifest_still_warns() { + let dir = TempDir::new().unwrap(); + fs::write( + dir.path().join("0-AI-MANIFEST.deed"), + "(manifest (project \"x\"))\n", + ) + .unwrap(); + let stderr = startup_stderr(dir.path()); + assert!( + stderr.contains("failed to read AI manifest") && stderr.contains("0-AI-MANIFEST.deed"), + "{stderr}" + ); +} From 66f2b59ad2882639ad2e53fe5d57cfcc5713b4a9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 23:03:01 +0000 Subject: [PATCH 3/4] deed: point the parent notes at where the parent is named now The two (ecosystem (related :relationship parent)) notes still said the parent was named by ANCHOR.a2ml, which is retired. The parent is named by this clause; the retired source is in docs/history/A2ML-REMOVED.adoc. Only the note text changes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0136P7ZoBy5xGnGDLk7wQ8jC --- panic-attack_chora.deed | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/panic-attack_chora.deed b/panic-attack_chora.deed index 14d84ea..b6d4bc9 100644 --- a/panic-attack_chora.deed +++ b/panic-attack_chora.deed @@ -101,12 +101,12 @@ (related :name "boj-server" :relationship parent - :notes "Parent named by ANCHOR.a2ml." + :notes "Parent edge (A7 6.4, J26): named here, in this (ecosystem) clause; panic-attack has no (anchor) clause. Retired source: docs/history/A2ML-REMOVED.adoc." :uuid #uuid"6c7f9305-2a47-8f96-a1ed-bd0940e4d4e6") (related :name "ambientops" :relationship parent - :notes "Parent named by .machine_readable/6a2/ANCHOR.a2ml." + :notes "Parent edge (A7 6.4, J26): named here, in this (ecosystem) clause; panic-attack has no (anchor) clause. Retired source: docs/history/A2ML-REMOVED.adoc." :uuid #uuid"5c1e28a9-d8c0-8bfe-a57d-ae4abe7dc3be")) ; AGENTIC.a2ml: [metadata] version and last-updated, and the five ; [agent-permissions] booleans the table lists. The source has no @profile From 93469f7a1e9dad4226aa2832076231639e4ed939 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 23:03:01 +0000 Subject: [PATCH 4/4] deed(manifest): make 0-AI-MANIFEST.deed pointer-only (A7 Q15) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Q15: the front door holds :schema-version and (front-doors …) and no facts. :canonical-name, :repo-uuid and :beholding-chora are removed; the same three values are in panic-attack_chora.deed, which is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0136P7ZoBy5xGnGDLk7wQ8jC --- 0-AI-MANIFEST.deed | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/0-AI-MANIFEST.deed b/0-AI-MANIFEST.deed index be6ba94..de507a7 100644 --- a/0-AI-MANIFEST.deed +++ b/0-AI-MANIFEST.deed @@ -2,7 +2,8 @@ ;; SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell ; ; The machine front door of panic-attack: pointer-only (A7 ruling Q15). It names -; where to read and carries no facts of its own. Repository facts are in +; where to read and carries no facts of its own: only :schema-version and the +; (front-doors) clause. Repository facts, identity included, are in ; panic-attack_chora.deed; agent conventions are in .claude/CLAUDE.md. It ; replaces 0-AI-MANIFEST.a2ml, retired 2026-11-14 ; (docs/history/A2ML-REMOVED.adoc). @@ -13,9 +14,6 @@ ; filesystem). (repo-deed :schema-version "1.0.0" - :canonical-name "panic-attack" - :repo-uuid #uuid"a39ad6b1-51e0-854d-aa9a-d9ee97ba519b" - :beholding-chora #uuid"0889b37b-defb-831f-973c-e119500db00e" (front-doors :machine "panic-attack_chora.deed" :human "README.adoc"))