a3s 0.10.7

a3s — A3S coding agent CLI; `a3s code` launches the interactive TUI
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
//! Structural source audit for a materialized research report.
//!
//! Natural-language claims are never matched back to evidence text here.
//! Closed claim/source IDs and their bindings are validated before generation;
//! this final gate verifies only exact accepted source anchors in rendered
//! citations.

use comrak::{nodes::NodeValue, parse_document, Arena, Options};
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashSet};
use std::sync::OnceLock;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum CitationRequirement {
    AtLeastOne,
    #[cfg(test)]
    EveryDeclared,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ReportSourceReference {
    pub(crate) source_id: String,
    pub(crate) anchor: String,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct ReportAudit {
    pub(crate) passed: bool,
    pub(crate) accepted_sources: usize,
    pub(crate) cited_sources: usize,
    #[serde(default)]
    pub(crate) issues: Vec<ReportAuditIssue>,
    pub(crate) reason: String,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub(crate) enum ReportAuditIssue {
    AcceptedSourcesEmpty,
    SourceCatalogInvalid {
        source_id: String,
    },
    SourceNotCited {
        source_id: String,
    },
    SemanticBoundaryViolation {
        target_id: String,
        category: String,
        excerpt: String,
        detail: String,
    },
}

pub(crate) fn audit_report(
    markdown: &str,
    html: &str,
    sources: &[ReportSourceReference],
    requirement: CitationRequirement,
) -> ReportAudit {
    if sources.is_empty() {
        return ReportAudit {
            passed: false,
            accepted_sources: 0,
            cited_sources: 0,
            issues: vec![ReportAuditIssue::AcceptedSourcesEmpty],
            reason: "report audit received no accepted source catalog".to_string(),
        };
    }

    let mut catalog = BTreeMap::new();
    let mut issues = Vec::new();
    for source in sources {
        let source_id = source.source_id.as_str();
        let normalized_anchor = normalize_citation_target(&source.anchor);
        let valid_id = !source_id.is_empty() && source_id.trim() == source_id;
        let duplicate = catalog.contains_key(source_id);
        if !valid_id || normalized_anchor.is_none() || duplicate {
            issues.push(ReportAuditIssue::SourceCatalogInvalid {
                source_id: source.source_id.clone(),
            });
            continue;
        }
        catalog.insert(
            source.source_id.clone(),
            normalized_anchor.expect("checked above"),
        );
    }

    let citation_targets = extract_citation_targets(markdown, html);
    let cited_source_ids = catalog
        .iter()
        .filter_map(|(source_id, anchor)| {
            citation_targets
                .contains(anchor)
                .then_some(source_id.clone())
        })
        .collect::<HashSet<_>>();

    match requirement {
        CitationRequirement::AtLeastOne if cited_source_ids.is_empty() => {
            issues.extend(
                catalog
                    .keys()
                    .cloned()
                    .map(|source_id| ReportAuditIssue::SourceNotCited { source_id }),
            );
        }
        #[cfg(test)]
        CitationRequirement::EveryDeclared => {
            issues.extend(
                catalog
                    .keys()
                    .filter(|source_id| !cited_source_ids.contains(*source_id))
                    .cloned()
                    .map(|source_id| ReportAuditIssue::SourceNotCited { source_id }),
            );
        }
        CitationRequirement::AtLeastOne => {}
    }

    let passed = issues.is_empty();
    let reason = if issues
        .iter()
        .any(|issue| matches!(issue, ReportAuditIssue::SourceCatalogInvalid { .. }))
    {
        "report source catalog is not a closed set of unique IDs and valid anchors"
    } else if issues
        .iter()
        .any(|issue| matches!(issue, ReportAuditIssue::SourceNotCited { .. }))
    {
        match requirement {
            CitationRequirement::AtLeastOne => "report cites none of the accepted evidence sources",
            #[cfg(test)]
            CitationRequirement::EveryDeclared => {
                "report does not cite every source declared by its closed evidence plan"
            }
        }
    } else {
        "report citations resolve to the exact accepted source anchors"
    };

    ReportAudit {
        passed,
        accepted_sources: sources.len(),
        cited_sources: cited_source_ids.len(),
        issues,
        reason: reason.to_string(),
    }
}

#[cfg(test)]
pub(crate) fn report_citation_targets(markdown: &str, html: &str) -> HashSet<String> {
    extract_citation_targets(markdown, html)
}

#[cfg(test)]
pub(crate) fn canonical_citation_target(target: &str) -> Option<String> {
    normalize_citation_target(target)
}

fn extract_citation_targets(markdown: &str, html: &str) -> HashSet<String> {
    let arena = Arena::new();
    let mut options = Options::default();
    options.extension.autolink = true;
    let root = parse_document(&arena, markdown, &options);
    let mut targets = HashSet::new();
    for node in root.descendants() {
        if node.ancestors().skip(1).any(|ancestor| {
            matches!(
                &ancestor.data.borrow().value,
                NodeValue::Heading(heading) if heading.level == 1
            )
        }) {
            continue;
        }
        let data = node.data.borrow();
        match &data.value {
            NodeValue::Link(link) => {
                if let Some(target) = normalize_citation_target(&link.url) {
                    targets.insert(target);
                }
            }
            NodeValue::HtmlInline(fragment) => {
                extract_html_href_targets(fragment, &mut targets);
            }
            NodeValue::HtmlBlock(block) => {
                extract_html_href_targets(&block.literal, &mut targets);
            }
            _ => {}
        }
    }
    extract_html_href_targets(html, &mut targets);
    targets
}

fn extract_html_href_targets(document: &str, targets: &mut HashSet<String>) {
    for captures in html_href_regex().captures_iter(document) {
        let Some(target) = captures
            .name("double")
            .or_else(|| captures.name("single"))
            .or_else(|| captures.name("bare"))
            .map(|capture| decode_basic_html_entities(capture.as_str()))
            .and_then(|target| normalize_citation_target(&target))
        else {
            continue;
        };
        targets.insert(target);
    }
}

fn normalize_citation_target(target: &str) -> Option<String> {
    let target = target.trim();
    let target = target
        .strip_prefix('<')
        .and_then(|target| target.strip_suffix('>'))
        .unwrap_or(target)
        .trim();
    if target.is_empty() {
        return None;
    }
    if target.starts_with('#') {
        return Some(target.to_string());
    }
    if let Some(scheme_end) = target.find("://") {
        let scheme = target[..scheme_end].to_ascii_lowercase();
        let remainder = &target[scheme_end + 3..];
        let authority_end = remainder.find(['/', '?', '#']).unwrap_or(remainder.len());
        let authority = remainder[..authority_end].to_ascii_lowercase();
        if authority.is_empty() {
            return None;
        }
        let suffix = &remainder[authority_end..];
        let suffix = if suffix.is_empty() { "/" } else { suffix };
        return Some(format!("{scheme}://{authority}{suffix}"));
    }
    Some(normalize_local_target(target))
}

fn normalize_local_target(target: &str) -> String {
    let target = target.replace('\\', "/");
    let suffix_start = target.find(['?', '#']).unwrap_or(target.len());
    let (path, suffix) = target.split_at(suffix_start);
    let absolute = path.starts_with('/');
    let mut components = Vec::new();
    for component in path.split('/') {
        match component {
            "" | "." => {}
            ".." if components.last().is_some_and(|last| *last != "..") => {
                components.pop();
            }
            ".." if !absolute => components.push(component),
            ".." => {}
            _ => components.push(component),
        }
    }
    let mut normalized = if absolute {
        format!("/{}", components.join("/"))
    } else {
        components.join("/")
    };
    if normalized.is_empty() && !absolute {
        normalized.push('.');
    }
    normalized.push_str(suffix);
    normalized
}

fn decode_basic_html_entities(target: &str) -> String {
    target
        .replace("&amp;", "&")
        .replace("&#38;", "&")
        .replace("&#x26;", "&")
        .replace("&#X26;", "&")
        .replace("&quot;", "\"")
        .replace("&#34;", "\"")
        .replace("&#x22;", "\"")
        .replace("&#X22;", "\"")
}

fn html_href_regex() -> &'static Regex {
    static REGEX: OnceLock<Regex> = OnceLock::new();
    REGEX.get_or_init(|| {
        Regex::new(
            r#"(?is)(?:^|[\s<])href\s*=\s*(?:\"(?P<double>[^\"]*)\"|'(?P<single>[^']*)'|(?P<bare>[^\s\"'=<>`]+))"#,
        )
        .expect("HTML href regex must compile")
    })
}

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

    fn source(id: &str, anchor: &str) -> ReportSourceReference {
        ReportSourceReference {
            source_id: id.to_string(),
            anchor: anchor.to_string(),
        }
    }

    #[test]
    fn accepts_exact_declared_source_citations_without_inspecting_prose() {
        let audit = audit_report(
            "任意语言的综合结论。[来源](https://example.gov/release)",
            "",
            &[source("source:release", "https://example.gov/release")],
            CitationRequirement::EveryDeclared,
        );
        assert!(audit.passed);
        assert_eq!(audit.cited_sources, 1);
    }

    #[test]
    fn rejects_source_anchor_that_is_only_a_prefix_of_a_link_target() {
        let audit = audit_report(
            "[Source](https://example.gov/release-notes)",
            "",
            &[source("source:release", "https://example.gov/release")],
            CitationRequirement::EveryDeclared,
        );
        assert!(!audit.passed);
        assert_eq!(
            audit.issues,
            vec![ReportAuditIssue::SourceNotCited {
                source_id: "source:release".to_string(),
            }]
        );
    }

    #[test]
    fn every_declared_requires_each_exact_source_anchor() {
        let audit = audit_report(
            "[One](https://example.gov/one)",
            "",
            &[
                source("source:one", "https://example.gov/one"),
                source("source:two", "https://example.gov/two"),
            ],
            CitationRequirement::EveryDeclared,
        );
        assert!(!audit.passed);
        assert_eq!(audit.cited_sources, 1);
        assert_eq!(
            audit.issues,
            vec![ReportAuditIssue::SourceNotCited {
                source_id: "source:two".to_string(),
            }]
        );
    }

    #[test]
    fn at_least_one_accepts_one_exact_anchor_from_a_larger_catalog() {
        let audit = audit_report(
            "[One](https://example.gov/one)",
            "",
            &[
                source("source:one", "https://example.gov/one"),
                source("source:two", "https://example.gov/two"),
            ],
            CitationRequirement::AtLeastOne,
        );
        assert!(audit.passed);
        assert_eq!(audit.cited_sources, 1);
    }

    #[test]
    fn extracts_inline_autolink_and_reference_citation_targets() {
        for markdown in [
            "[Source](https://example.gov/release)",
            "<https://example.gov/release>",
            "https://example.gov/release",
            "[Source][release]\n\n[release]: https://example.gov/release",
        ] {
            let audit = audit_report(
                markdown,
                "",
                &[source("source:release", "https://example.gov/release")],
                CitationRequirement::EveryDeclared,
            );
            assert!(audit.passed, "{markdown}: {}", audit.reason);
        }
    }

    #[test]
    fn local_citation_targets_match_exact_normalized_paths() {
        let accepted = audit_report(
            "[Workspace source](docs/./research.md)",
            "",
            &[source("source:local", "./docs/research.md")],
            CitationRequirement::EveryDeclared,
        );
        assert!(accepted.passed, "{}", accepted.reason);

        let rejected = audit_report(
            "[Nested readme](docs/README.md)",
            "",
            &[source("source:local", "README.md")],
            CitationRequirement::EveryDeclared,
        );
        assert!(!rejected.passed);
    }

    #[test]
    fn link_like_text_inside_a_code_fence_is_not_a_citation() {
        let audit = audit_report(
            "```html\n<a href=\"https://example.gov/release\">not a citation</a>\n```",
            "",
            &[source("source:release", "https://example.gov/release")],
            CitationRequirement::EveryDeclared,
        );
        assert!(!audit.passed);
    }

    #[test]
    fn html_citations_require_the_exact_href_attribute_name() {
        let targets = report_citation_targets(
            "",
            "<a data-href=\"https://example.gov/metadata\" xhref=\"https://example.gov/lookalike\" href=\"https://example.gov/source\">source</a>",
        );
        assert_eq!(
            targets,
            HashSet::from(["https://example.gov/source".to_string()])
        );
    }

    #[test]
    fn same_document_fragments_remain_non_source_targets() {
        assert_eq!(
            canonical_citation_target("#section-1"),
            Some("#section-1".to_string())
        );
    }

    #[test]
    fn markdown_report_title_links_are_not_evidence_citations() {
        let targets = report_citation_targets("# Analyze https://example.gov/request\n\nBody.", "");
        assert!(!targets.contains("https://example.gov/request"));

        let body_targets = report_citation_targets(
            "# Analyze https://example.gov/request\n\nBody citation: https://example.gov/request",
            "",
        );
        assert!(body_targets.contains("https://example.gov/request"));
    }

    #[test]
    fn rejects_empty_duplicate_or_unaddressable_source_catalogs() {
        let empty = audit_report("", "", &[], CitationRequirement::AtLeastOne);
        assert_eq!(empty.issues, vec![ReportAuditIssue::AcceptedSourcesEmpty]);

        let duplicate = audit_report(
            "[Source](https://example.gov/release)",
            "",
            &[
                source("source:release", "https://example.gov/release"),
                source("source:release", "https://example.gov/other"),
            ],
            CitationRequirement::EveryDeclared,
        );
        assert!(duplicate.issues.iter().any(|issue| matches!(
            issue,
            ReportAuditIssue::SourceCatalogInvalid { source_id }
                if source_id == "source:release"
        )));
    }
}