Skip to content

Commit c5fc2c6

Browse files
fix: valid assault-report Nickel, no spurious manifest warning, pointer-only manifest (#302)
## Summary This PR fixes five small debts. Four of them were listed under "Seen, not changed" in #300; the fifth is the S1612 closure. ## Changes, by commit 1. **7eca0cf, assault-report Nickel.** `src/report/output.rs` (the `--output-format nickel` writer) had the bug #300 fixed in the manifest export: fields written as `field = value;` and a `};\nassault_report` tail. `nickel export` 1.18.0 rejects that form with "unexpected token". - The writer now uses the a2ml module's `nickel_record` (fields separated by `,`) and a new shared `nickel_let` (`let … in`), so the two writers no longer duplicate this code. `Manifest::to_nickel` uses `nickel_let` too. - NaN and infinite floats now become `null` instead of an unparseable token. - Same commit, Sonar S1612: three `.and_then(|e| e.to_str())` closures in `src/a2ml/mod.rs` become `OsStr::to_str`. 2. **235804b, spurious warning.** `run_main` loaded the manifest with `load_default`, which errors when the file is missing. So every command run in a directory without a manifest printed `warning: failed to read AI manifest`. It now uses `load_if_exists`: a missing manifest is silent, and a manifest that exists but is unreadable or malformed still warns. 3. **66f2b59, chora deed notes.** Both parent `:notes` in `(ecosystem (related …))` named the retired ANCHOR.a2ml. They now say the parent is named in this clause, and point to `docs/history/A2ML-REMOVED.adoc` for the retired source. Only the note text changed. 4. **93469f7, pointer-only manifest (A7 Q15).** `0-AI-MANIFEST.deed` drops `:canonical-name`, `:repo-uuid` and `:beholding-chora`. `panic-attack_chora.deed` carries the same three values and is not changed. ## Tests - `report::output::tests::assault_report_nickel_uses_nickel_record_and_let_syntax` fails against the old writer. Where `nickel` is installed, it also runs `nickel export --format json` and checks that counts and scores come back as numbers. - `report::output::tests::non_finite_numbers_become_null` - In `tests/manifest_cli.rs`: `no_manifest_is_not_a_warning`, `a_valid_pointer_deed_is_not_a_warning` and `a_malformed_manifest_still_warns`. ## Verification - `cargo build`: no warnings. - `cargo test`: 816 passed, 0 failed, 4 ignored. - `cargo test --features http`: 883 passed, 0 failed, 4 ignored. - `cargo clippy --all-targets -- -D warnings` and `cargo clippy --locked --all-targets --features http,sarif,signing -- -D warnings`: clean. - `cargo fmt --check`: clean. - `deed_lint.js` gives `OK` on both deeds. - `panic-attack manifest | nickel export` gives valid JSON. - `panic-attack diagnostics` reports `[OK] AI manifest 0-AI-MANIFEST.deed parsed`. - `git diff --summary origin/main...HEAD`: no mode changes. --- _Generated by [Claude Code](https://claude.ai/code/session_0136P7ZoBy5xGnGDLk7wQ8jC)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent e9c8331 commit c5fc2c6

6 files changed

Lines changed: 213 additions & 46 deletions

File tree

‎0-AI-MANIFEST.deed‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22
;; SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell <j.d.a.jewell@open.ac.uk>
33
;
44
; The machine front door of panic-attack: pointer-only (A7 ruling Q15). It names
5-
; where to read and carries no facts of its own. Repository facts are in
5+
; where to read and carries no facts of its own: only :schema-version and the
6+
; (front-doors) clause. Repository facts, identity included, are in
67
; panic-attack_chora.deed; agent conventions are in .claude/CLAUDE.md. It
78
; replaces 0-AI-MANIFEST.a2ml, retired 2026-11-14
89
; (docs/history/A2ML-REMOVED.adoc).
@@ -13,9 +14,6 @@
1314
; filesystem).
1415
(repo-deed
1516
:schema-version "1.0.0"
16-
:canonical-name "panic-attack"
17-
:repo-uuid #uuid"a39ad6b1-51e0-854d-aa9a-d9ee97ba519b"
18-
:beholding-chora #uuid"0889b37b-defb-831f-973c-e119500db00e"
1917
(front-doors
2018
:machine "panic-attack_chora.deed"
2119
:human "README.adoc"))

‎panic-attack_chora.deed‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -101,12 +101,12 @@
101101
(related
102102
:name "boj-server"
103103
:relationship parent
104-
:notes "Parent named by ANCHOR.a2ml."
104+
: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."
105105
:uuid #uuid"6c7f9305-2a47-8f96-a1ed-bd0940e4d4e6")
106106
(related
107107
:name "ambientops"
108108
:relationship parent
109-
:notes "Parent named by .machine_readable/6a2/ANCHOR.a2ml."
109+
: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."
110110
:uuid #uuid"5c1e28a9-d8c0-8bfe-a57d-ae4abe7dc3be"))
111111
; AGENTIC.a2ml: [metadata] version and last-updated, and the five
112112
; [agent-permissions] booleans the table lists. The source has no @profile

‎src/a2ml/mod.rs‎

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ use crate::types::{AssailReport, AssaultReport, AttackResult};
1616
use crate::{abduct, adjudicate, amuck, axial};
1717
use anyhow::{anyhow, Context, Result};
1818
use serde::de::DeserializeOwned;
19+
use std::ffi::OsStr;
1920
use std::fs;
2021
use std::path::{Path, PathBuf};
2122

@@ -206,7 +207,7 @@ impl Manifest {
206207
pub fn load(path: &Path) -> Result<Self> {
207208
let raw = fs::read_to_string(path)
208209
.with_context(|| format!("reading AI manifest {}", path.display()))?;
209-
let mut manifest = if path.extension().and_then(|e| e.to_str()) == Some("deed") {
210+
let mut manifest = if path.extension().and_then(OsStr::to_str) == Some("deed") {
210211
Self::parse_deed(&raw, path)?
211212
} else {
212213
Self::parse_a2ml(&raw)?
@@ -237,7 +238,7 @@ impl Manifest {
237238
deed.head
238239
));
239240
}
240-
if path.file_name().and_then(|n| n.to_str()) == Some(MANIFEST_CANDIDATES[0]) {
241+
if path.file_name().and_then(OsStr::to_str) == Some(MANIFEST_CANDIDATES[0]) {
241242
check_pointer_profile(&deed.items)
242243
.map_err(|e| anyhow!("{}: not a pointer-only manifest: {}", path.display(), e))?;
243244
}
@@ -403,7 +404,7 @@ impl Manifest {
403404
} else {
404405
record_to_nickel(&gather_entries(&self.entries))
405406
};
406-
format!("let {} = {} in\n{}", self.root_name, body, self.root_name)
407+
nickel_let(&self.root_name, &body)
407408
}
408409

409410
/// The legacy `(reports …)` section; never read from a deed.
@@ -502,7 +503,7 @@ fn load_payload_for_kind(kind: ReportBundleKind, input: &Path) -> Result<ReportB
502503

503504
fn load_json_or_yaml<T: DeserializeOwned>(path: &Path) -> Result<T> {
504505
let raw = fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
505-
match path.extension().and_then(|e| e.to_str()) {
506+
match path.extension().and_then(OsStr::to_str) {
506507
Some(ext) if crate::yaml::is_extension(ext) => crate::yaml::from_report_str::<T>(&raw)
507508
.with_context(|| format!("parsing {}", path.display())),
508509
_ => serde_json::from_str::<T>(&raw).with_context(|| format!("parsing {}", path.display())),
@@ -982,8 +983,10 @@ fn record_to_nickel(entries: &[(String, Vec<Vec<Sexpr>>)]) -> String {
982983
nickel_record(lines)
983984
}
984985

985-
/// Field lines (`key = value`) as a Nickel record body.
986-
fn nickel_record(lines: Vec<String>) -> String {
986+
/// Field lines (`key = value`) as a Nickel record body: fields separated by
987+
/// `,`, as Nickel requires. Shared with the assault-report writer in
988+
/// `crate::report::output`.
989+
pub(crate) fn nickel_record(lines: Vec<String>) -> String {
987990
if lines.is_empty() {
988991
return "{}".to_string();
989992
}
@@ -1034,6 +1037,13 @@ fn value_to_nickel(value: &Sexpr) -> String {
10341037
}
10351038
}
10361039

1040+
/// A Nickel program that binds `body` to `name` and evaluates to it:
1041+
/// `let name = body in\nname`. Nickel has no `let name = body;` statement form.
1042+
pub(crate) fn nickel_let(name: &str, body: &str) -> String {
1043+
format!("let {name} = {body} in\n{name}")
1044+
}
1045+
1046+
/// A record key as Nickel: bare when it is an identifier, quoted otherwise.
10371047
fn key_to_nickel(key: &str) -> String {
10381048
if key
10391049
.chars()

‎src/main.rs‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1539,7 +1539,8 @@ fn main() -> Result<()> {
15391539
}
15401540

15411541
/// Parse process arguments and execute the selected command, including its output
1542-
/// and requested persistence. Default manifest settings are used if loading fails.
1542+
/// and requested persistence. Default manifest settings are used when no manifest
1543+
/// exists (silently) or when one exists but does not load (with a warning).
15431544
/// Argument parsing exits the process for help or invalid CLI syntax.
15441545
/// For assail with `--fail-on-incomplete`, exits with status 2 when coverage is
15451546
/// not `complete`, after report output and any requested attestation are written.
@@ -1549,7 +1550,10 @@ fn main() -> Result<()> {
15491550
/// operation errors that are not handled by a command-specific fallback.
15501551
fn run_main() -> Result<()> {
15511552
let cli = Cli::parse();
1552-
let manifest = match Manifest::load_default() {
1553+
// A missing manifest is the normal case for most directories: use the
1554+
// defaults without a word. Warn only when a manifest exists but cannot be
1555+
// read or parsed.
1556+
let manifest = match Manifest::load_if_exists(&Manifest::default_path()) {
15531557
Ok(manifest) => manifest,
15541558
Err(err) => {
15551559
eprintln!("warning: failed to read AI manifest: {}", err);

‎src/report/output.rs‎

Lines changed: 145 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
//! Serialization helpers for printed/exported reports
55
6+
use crate::a2ml::{nickel_let, nickel_record};
67
use crate::report::formatter::nickel_escape_string;
78
use crate::types::AssaultReport;
89
use anyhow::Result;
@@ -57,26 +58,26 @@ impl ReportOutputFormat {
5758
fn format_report_as_nickel(report: &AssaultReport) -> String {
5859
// The Nickel representation intentionally samples large collections to stay readable.
5960
let assail = &report.assail_report;
61+
// Fields are `key = value` lines; `nickel_record` joins them with `,`.
6062
let mut lines = Vec::new();
61-
lines.push("let assault_report = {".to_string());
6263
lines.push(format!(
63-
" program = {};",
64+
"program = {}",
6465
nickel_escape_string(&assail.program_path.to_string_lossy())
6566
));
6667
lines.push(format!(
67-
" language = {};",
68+
"language = {}",
6869
nickel_escape_string(&format!("{:?}", assail.language))
6970
));
70-
lines.push(format!(" framework_count = {};", assail.frameworks.len()));
71-
lines.push(format!(" weak_points = {};", assail.weak_points.len()));
72-
lines.push(format!(" total_crashes = {};", report.total_crashes));
73-
lines.push(format!(" total_signatures = {};", report.total_signatures));
71+
lines.push(format!("framework_count = {}", assail.frameworks.len()));
72+
lines.push(format!("weak_points = {}", assail.weak_points.len()));
73+
lines.push(format!("total_crashes = {}", report.total_crashes));
74+
lines.push(format!("total_signatures = {}", report.total_signatures));
7475
let axes: Vec<String> = report
7576
.attack_results
7677
.iter()
7778
.map(|r| nickel_escape_string(&format!("{:?}", r.axis)))
7879
.collect();
79-
lines.push(format!(" attack_axes = [{}];", axes.join(", ")));
80+
lines.push(format!("attack_axes = [{}]", axes.join(", ")));
8081

8182
if !assail.weak_points.is_empty() {
8283
let weak_summary: Vec<String> = assail
@@ -92,7 +93,7 @@ fn format_report_as_nickel(report: &AssaultReport) -> String {
9293
})
9394
.collect();
9495
lines.push(format!(
95-
" weak_point_samples = [{}];",
96+
"weak_point_samples = [{}]",
9697
weak_summary.join(", ")
9798
));
9899
}
@@ -104,49 +105,46 @@ fn format_report_as_nickel(report: &AssaultReport) -> String {
104105
.take(3)
105106
.map(|row| {
106107
format!(
107-
"{{ source = {}, sink = {}, severity = {:.1} }}",
108+
"{{ source = {}, sink = {}, severity = {} }}",
108109
nickel_escape_string(&format!("{:?}", row.source_category)),
109110
nickel_escape_string(&format!("{:?}", row.sink_axis)),
110-
row.severity_value
111+
nickel_number(row.severity_value, Some(1))
111112
)
112113
})
113114
.collect();
114115
if !pivot_rows.is_empty() {
115-
lines.push(format!(" pivot_samples = [{}];", pivot_rows.join(", ")));
116+
lines.push(format!("pivot_samples = [{}]", pivot_rows.join(", ")));
116117
}
117118

118119
if let Some(timeline) = &report.timeline {
119120
lines.push(format!(
120-
" timeline_duration = {};",
121-
timeline.duration.as_secs_f64()
121+
"timeline_duration = {}",
122+
nickel_number(timeline.duration.as_secs_f64(), None)
122123
));
123-
lines.push(format!(" timeline_events = {};", timeline.events.len()));
124+
lines.push(format!("timeline_events = {}", timeline.events.len()));
124125
let event_samples: Vec<String> = timeline
125126
.events
126127
.iter()
127128
.take(3)
128129
.map(|event| {
129130
format!(
130-
"{{ id = {}, axis = {}, start = {:.2}, duration = {:.2}, intensity = {} }}",
131+
"{{ id = {}, axis = {}, start = {}, duration = {}, intensity = {} }}",
131132
nickel_escape_string(&event.id),
132133
nickel_escape_string(&format!("{:?}", event.axis)),
133-
event.start_offset.as_secs_f64(),
134-
event.duration.as_secs_f64(),
134+
nickel_number(event.start_offset.as_secs_f64(), Some(2)),
135+
nickel_number(event.duration.as_secs_f64(), Some(2)),
135136
nickel_escape_string(&format!("{:?}", event.intensity))
136137
)
137138
})
138139
.collect();
139140
if !event_samples.is_empty() {
140-
lines.push(format!(
141-
" timeline_samples = [{}];",
142-
event_samples.join(", ")
143-
));
141+
lines.push(format!("timeline_samples = [{}]", event_samples.join(", ")));
144142
}
145143
}
146144

147145
lines.push(format!(
148-
" robustness_score = {:.1};",
149-
report.overall_assessment.robustness_score
146+
"robustness_score = {}",
147+
nickel_number(report.overall_assessment.robustness_score, Some(1))
150148
));
151149

152150
if !report.overall_assessment.critical_issues.is_empty() {
@@ -156,7 +154,7 @@ fn format_report_as_nickel(report: &AssaultReport) -> String {
156154
.iter()
157155
.map(|issue| nickel_escape_string(issue))
158156
.collect();
159-
lines.push(format!(" critical_issues = [{}];", issue_list.join(", ")));
157+
lines.push(format!("critical_issues = [{}]", issue_list.join(", ")));
160158
}
161159

162160
if !report.overall_assessment.recommendations.is_empty() {
@@ -166,10 +164,128 @@ fn format_report_as_nickel(report: &AssaultReport) -> String {
166164
.iter()
167165
.map(|rec| nickel_escape_string(rec))
168166
.collect();
169-
lines.push(format!(" recommendations = [{}];", rec_list.join(", ")));
167+
lines.push(format!("recommendations = [{}]", rec_list.join(", ")));
170168
}
171169

172-
lines.push("};".to_string());
173-
lines.push("assault_report".to_string());
174-
lines.join("\n")
170+
nickel_let("assault_report", &nickel_record(lines))
171+
}
172+
173+
/// An `f64` as a Nickel number with `decimals` places (or Rust's shortest
174+
/// form for `None`). NaN and the infinities have no Nickel literal, so they
175+
/// become `null` rather than an unparseable token.
176+
fn nickel_number(value: f64, decimals: Option<usize>) -> String {
177+
if !value.is_finite() {
178+
return "null".to_string();
179+
}
180+
match decimals {
181+
Some(places) => format!("{value:.places$}"),
182+
None => format!("{value}"),
183+
}
184+
}
185+
186+
#[cfg(test)]
187+
mod tests {
188+
use super::*;
189+
use crate::types::{
190+
AttackAxis, IntensityLevel, OverallAssessment, TaintMatrixRow, TimelineEventReport,
191+
TimelineReport, WeakPoint, WeakPointCategory,
192+
};
193+
use std::fs;
194+
use std::time::Duration;
195+
use tempfile::TempDir;
196+
197+
/// An assault report with every section the Nickel writer emits: weak
198+
/// points, a taint row, a timeline, issues and recommendations.
199+
fn full_report(dir: &TempDir) -> AssaultReport {
200+
fs::write(dir.path().join("main.rs"), "fn main() {}\n").expect("write");
201+
let mut assail = crate::assail::analyze(dir.path()).expect("analyze");
202+
let weak: WeakPoint = serde_json::from_value(serde_json::json!({
203+
"category": "PanicPath",
204+
"location": "main.rs:1",
205+
"severity": "High",
206+
"description": "unwrap on a None",
207+
"recommended_attack": ["cpu"],
208+
}))
209+
.expect("weak point");
210+
assail.weak_points.push(weak);
211+
assail.taint_matrix.rows.push(TaintMatrixRow {
212+
source_category: WeakPointCategory::PanicPath,
213+
sink_axis: AttackAxis::Cpu,
214+
severity_value: 3.25,
215+
files: vec!["main.rs".to_string()],
216+
frameworks: Vec::new(),
217+
relation: "direct".to_string(),
218+
});
219+
AssaultReport {
220+
schema_version: "2.5".to_string(),
221+
assail_report: assail,
222+
attack_results: Vec::new(),
223+
total_crashes: 1,
224+
total_signatures: 0,
225+
overall_assessment: OverallAssessment {
226+
robustness_score: 42.0,
227+
critical_issues: vec!["crash".to_string()],
228+
recommendations: vec!["fix it".to_string()],
229+
},
230+
timeline: Some(TimelineReport {
231+
duration: Duration::from_millis(1500),
232+
events: vec![TimelineEventReport {
233+
id: "evt-1".to_string(),
234+
axis: AttackAxis::Memory,
235+
start_offset: Duration::from_secs(5),
236+
duration: Duration::from_secs(10),
237+
intensity: IntensityLevel::Medium,
238+
args: Vec::new(),
239+
peak_memory: None,
240+
ran: true,
241+
}],
242+
}),
243+
}
244+
}
245+
246+
#[test]
247+
fn assault_report_nickel_uses_nickel_record_and_let_syntax() {
248+
// Nickel separates record fields with `,` and binds with `let … in`;
249+
// the old `field = value;` lines and `};\nassault_report` tail did not
250+
// parse (`nickel export` 1.18.0: "unexpected token").
251+
let dir = TempDir::new().expect("tempdir");
252+
let nickel = format_report_as_nickel(&full_report(&dir));
253+
assert!(nickel.starts_with("let assault_report = {\n"), "{nickel}");
254+
assert!(nickel.ends_with("\n} in\nassault_report"), "{nickel}");
255+
assert!(nickel.contains(",\n weak_points = 1,\n"), "{nickel}");
256+
assert!(!nickel.contains(';'), "{nickel}");
257+
258+
// Where the Nickel CLI is installed, it must accept the output and
259+
// keep the types: counts and scores are numbers, not strings.
260+
let file = dir.path().join("report.ncl");
261+
fs::write(&file, &nickel).expect("write");
262+
if let Ok(out) = std::process::Command::new("nickel")
263+
.args(["export", "--format", "json"])
264+
.arg(&file)
265+
.output()
266+
{
267+
assert!(
268+
out.status.success(),
269+
"{nickel}\n{}",
270+
String::from_utf8_lossy(&out.stderr)
271+
);
272+
let json: serde_json::Value =
273+
serde_json::from_slice(&out.stdout).expect("nickel export emits JSON");
274+
assert_eq!(json["weak_points"], 1);
275+
assert_eq!(json["robustness_score"], 42.0);
276+
assert_eq!(json["timeline_duration"], 1.5);
277+
assert_eq!(json["timeline_samples"][0]["start"], 5.0);
278+
assert_eq!(json["pivot_samples"][0]["severity"], 3.2);
279+
assert_eq!(json["weak_point_samples"][0]["category"], "PanicPath");
280+
assert_eq!(json["critical_issues"][0], "crash");
281+
}
282+
}
283+
284+
#[test]
285+
fn non_finite_numbers_become_null() {
286+
assert_eq!(nickel_number(f64::NAN, Some(1)), "null");
287+
assert_eq!(nickel_number(f64::INFINITY, None), "null");
288+
assert_eq!(nickel_number(2.0, Some(1)), "2.0");
289+
assert_eq!(nickel_number(1.5, None), "1.5");
290+
}
175291
}

0 commit comments

Comments
 (0)