jubarte_edit/capabilities.rs
1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! What this build can do. Agents read it before choosing an operation:
6//! `jubarte capabilities --json`, `jubarte_redlines.capabilities()`.
7//!
8//! Every operation is compiled into the library unconditionally: the crate's
9//! features (`cli`, `fast-alloc`, `self-update`, `perf-profile`) gate the
10//! binary, its allocator, updating and profiling, not an operation, so there
11//! is no feature to derive `operations` from and each is reported `true`. A
12//! wrapper that compiles an operation out overrides that field in its own
13//! manifest, as jubarte-wasm does for `pdf` (its `pdf` feature) and `png`
14//! (never). The rest is read from the modules that implement it: the v1 plan
15//! version and the story kinds come from `crate::inspect`, and whether a
16//! runtime dispatches PlanV2 from its own surface, so the manifest cannot
17//! drift from what a host can actually run.
18
19mod discovery;
20pub use discovery::{discovery, discovery_text};
21
22use std::collections::BTreeMap;
23
24use serde::{Deserialize, Serialize};
25
26/// Machine-readable capability manifest reported by
27/// `jubarte capabilities --json` and `capabilities::capabilities_json`.
28/// `schema_version` is `1`; the schema is intentionally narrow so an agent
29/// can detect an old build without parsing every field.
30#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
31pub struct Capabilities {
32 /// Manifest schema version; `1` for this build.
33 pub schema_version: u32,
34 /// Engine crate version, as `CARGO_PKG_VERSION`.
35 pub engine_version: String,
36 /// The surface reporting (`cli`, `python`, `rust`, `wasm`, …); the
37 /// value a host passes to [`capabilities`].
38 pub runtime: String,
39 /// Operation name to availability in this build.
40 pub operations: Operations,
41 /// Edit plan schema versions `runtime` dispatches: `1`, plus `2`
42 /// where the runtime routes plans through [`crate::edit::prepare_v2`]
43 /// (the CLI and a Rust embedder; the Python and WASM bindings have
44 /// no PlanV2 entry point yet).
45 pub edit_plan_versions: Vec<u32>,
46 /// Operation kinds an edit plan may contain
47 /// ([`crate::edit::OperationKind`] variants, in a stable order).
48 pub edit_operations: Vec<String>,
49 /// Scope limits an agent must plan around (story kinds, opaque ranges,
50 /// legacy `.doc` support, and the package budgets).
51 pub limits: Limits,
52 /// Audit codes `validate --rules` accepts, in
53 /// [`crate::audit::RULES`] order.
54 #[serde(default)]
55 pub audit_rules: Vec<String>,
56 /// Rule sets `validate --rules` accepts, with `word` (the default)
57 /// first (`crate::validate::RULE_SETS`).
58 #[serde(default)]
59 pub validate_rules: Vec<String>,
60 /// The file extensions each task's `-o` writes, indexed by task name
61 /// ([`OUTPUT_FORMATS`]; `diff` writes text under `.md`, `.markdown`,
62 /// `.txt`, `.patch`, `.diff`).
63 #[serde(default)]
64 pub formats: BTreeMap<String, Vec<String>>,
65 /// The id spellings each kind of target takes, as sample tokens plus a
66 /// shell-safety note ([`crate::ids`]).
67 #[serde(default)]
68 pub ids: Ids,
69 /// Native CLI options offered while choosing revision settlement;
70 /// other surfaces omit the entry (#1279).
71 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
72 pub settlement_options: BTreeMap<String, String>,
73}
74
75/// The id spellings the CLI, plans and selectors take, by kind
76/// ([`crate::ids`]).
77#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
78pub struct Ids {
79 /// Sample change-id spellings (`r12`, `r1+2`, `header1.r1`, …)
80 /// used by `accept` / `reject --id` and `edit -p … --accept` /
81 /// `--reject`.
82 pub change: Vec<String>,
83 /// Sample comment-id spellings (`c27`) used by `edit` / `add
84 /// -p` and an edit plan's `comment_id`.
85 pub comment: Vec<String>,
86 /// The text a comment covers (`edit -p`, a plan's `paragraph`).
87 #[serde(default)]
88 pub comment_text: Vec<String>,
89 /// Paragraphs (`edit`/`add -p`, a plan's anchors); `read -p` takes only
90 /// `pN`, `pN-pM` and `tN`.
91 pub paragraph: Vec<String>,
92 /// Tables: `read -p tN` selects one; `edit`/`add -p` address a cell as
93 /// `tN.rowR.cellC`.
94 pub table: Vec<String>,
95 /// Content controls (a plan's `fill_control`): `ccN` for a block
96 /// control, `pN.ccK` for one in a paragraph.
97 #[serde(default)]
98 pub control: Vec<String>,
99 /// How ids print.
100 pub note: String,
101}
102
103/// Per-operation availability in this build. Every operation is compiled
104/// unconditionally; features do not gate an operation, so each field is
105/// `true` in the default build. A wrapper that compiles an operation out
106/// (for example jubarte-wasm drops `pdf` and `png`) overrides the
107/// matching field in its own manifest.
108#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
109pub struct Operations {
110 /// Two documents into a Word tracked-changes document
111 /// ([`crate::document_comparer::compare_documents`]).
112 pub compare: bool,
113 /// Accept every revision
114 /// ([`crate::document_comparer::accept_revisions`]).
115 pub accept_revisions: bool,
116 /// Reject every revision
117 /// ([`crate::document_comparer::reject_revisions`]).
118 pub reject_revisions: bool,
119 /// List tracked changes by id and accept or reject a selection of them
120 /// ([`crate::changes`]); also the edit-plan `resolve_revisions` entry.
121 #[serde(default)]
122 pub selective_revisions: bool,
123 /// List revision records.
124 pub revision_records: bool,
125 /// DOCX to PDF (`jubarte::convert::docx_to_pdf`).
126 pub pdf: bool,
127 /// DOCX pages to PNG (`jubarte::convert::docx_to_png`).
128 pub png: bool,
129 /// Body paragraph inspection ([`crate::inspect::paragraphs`],
130 /// [`crate::inspect::summary`]).
131 pub inspect_body: bool,
132 /// Markdown projection with paragraph ids ([`crate::inspect::markdown`]).
133 pub markdown: bool,
134 /// Edit plans (clean copy, redline, report; [`crate::edit::apply_plan`]).
135 pub edit: bool,
136 /// Comments authored by an edit plan (`comment`, `reply_comment`,
137 /// `resolve_comment`, `edit_comment`, `delete_comment`).
138 pub comments: bool,
139 /// Markdown → DOCX, CriticMarkup as tracked changes and comments
140 /// ([`crate::markdown::markdown_to_docx`]).
141 #[serde(default)]
142 pub markdown_to_docx: bool,
143 /// Two Markdown documents as CriticMarkup, or Word / Markdown as a
144 /// Word redline ([`crate::markdown::diff_markdown`],
145 /// [`crate::markdown::redline`]).
146 #[serde(default)]
147 pub markdown_diff: bool,
148 /// The changes between two documents, Word or Markdown, as a patch
149 /// over the changed paragraphs at their ids
150 /// ([`crate::markdown::diff_markdown`] at the patch level; `jubarte
151 /// diff`).
152 #[serde(default)]
153 pub patch: bool,
154 /// Which pages of two documents differ, pixel for pixel, with overlays
155 /// of the changed region (`jubarte::convert::diff_render`; `jubarte
156 /// visual-diff`).
157 #[serde(default)]
158 pub diff_render: bool,
159 /// Rasterize selected pages after one layout pass of the whole
160 /// document (`convert --pages`).
161 #[serde(default)]
162 pub page_ranges: bool,
163 /// Comment threads: `jubarte comments` lists them, and edit plans
164 /// reply, resolve, edit and delete comments.
165 #[serde(default)]
166 pub comment_threads: bool,
167 /// Edit plans accept `existing_revisions: "keep"`: another party's
168 /// tracked changes stay, and the plan's edits become new revisions
169 /// beside them.
170 #[serde(default)]
171 pub edit_keeps_revisions: bool,
172 /// One document after another, carrying images, links, styles, lists
173 /// and notes (`jubarte::append::append_documents`; `jubarte append`).
174 #[serde(default)]
175 pub append: bool,
176 /// `read --json` lists the body's content controls and edit plans fill
177 /// them (`fill_control`).
178 #[serde(default)]
179 pub content_controls: bool,
180 /// Word-validity findings and the tracked-edit audit
181 /// ([`crate::validate::validate`]; `jubarte validate` with
182 /// `--original` / `--author`).
183 #[serde(default)]
184 pub validate: bool,
185 /// Repairable findings fixed ([`crate::validate::repair`]; `jubarte
186 /// validate --repair`).
187 #[serde(default)]
188 pub repair: bool,
189 /// Refresh `PAGEREF`, `REF`, `NUMPAGES`, `SEQ` and `TOC` results from
190 /// jubarte's layout ([`crate::fields::update_fields`]; `jubarte fields
191 /// update`, the edit-plan `update_fields`).
192 #[serde(default)]
193 pub fields: bool,
194 /// Remove authors, rsids, document properties and comments
195 /// ([`crate::scrub::scrub`]; `jubarte scrub`); edit plans take `redact`.
196 #[serde(default)]
197 pub scrub: bool,
198 /// Accessibility, style and structure findings by paragraph id
199 /// ([`crate::audit::audit_report`]; `jubarte validate --rules
200 /// a11y,style,structure`).
201 #[serde(default)]
202 pub audit: bool,
203 /// Edit plans run with `--skip-failed`
204 /// ([`crate::edit::PrepareOptions::skip_failed`]): the operations that
205 /// pass are applied, and the failed ones are written as a plan of
206 /// their own.
207 #[serde(default)]
208 pub edit_skip_failed: bool,
209}
210
211impl Operations {
212 /// Each operation and whether this build has it, in declaration order
213 /// (the same order as the field list). Used by [`capabilities_text`].
214 pub fn entries(&self) -> Vec<(&'static str, bool)> {
215 let Self {
216 compare,
217 accept_revisions,
218 reject_revisions,
219 selective_revisions,
220 revision_records,
221 pdf,
222 png,
223 inspect_body,
224 markdown,
225 edit,
226 comments,
227 markdown_to_docx,
228 markdown_diff,
229 patch,
230 diff_render,
231 page_ranges,
232 comment_threads,
233 edit_keeps_revisions,
234 append,
235 content_controls,
236 validate,
237 repair,
238 fields,
239 scrub,
240 audit,
241 edit_skip_failed,
242 } = self;
243 vec![
244 ("compare", *compare),
245 ("accept_revisions", *accept_revisions),
246 ("reject_revisions", *reject_revisions),
247 ("selective_revisions", *selective_revisions),
248 ("revision_records", *revision_records),
249 ("pdf", *pdf),
250 ("png", *png),
251 ("inspect_body", *inspect_body),
252 ("markdown", *markdown),
253 ("edit", *edit),
254 ("comments", *comments),
255 ("markdown_to_docx", *markdown_to_docx),
256 ("markdown_diff", *markdown_diff),
257 ("patch", *patch),
258 ("diff_render", *diff_render),
259 ("page_ranges", *page_ranges),
260 ("comment_threads", *comment_threads),
261 ("edit_keeps_revisions", *edit_keeps_revisions),
262 ("append", *append),
263 ("content_controls", *content_controls),
264 ("validate", *validate),
265 ("repair", *repair),
266 ("fields", *fields),
267 ("scrub", *scrub),
268 ("audit", *audit),
269 ("edit_skip_failed", *edit_skip_failed),
270 ]
271 }
272}
273
274/// Documented scope limits an agent must plan around.
275#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
276pub struct Limits {
277 /// Story kinds `read` and `edit` address: `body`, then the `kind` of
278 /// each entry of the snapshot's `stories` (`header`, `footer`, `footnotes`,
279 /// `endnotes`). A selector names a story by its id, the part's file stem
280 /// (`header1`, `{"story": "footnotes", "index": 0}`), which
281 /// `read --json` lists for the document at hand. Comments are counted in
282 /// `summary` but are not stories; text boxes are not stories either, and
283 /// their owner paragraph carries the `text_box_omitted` limitation.
284 pub stories: Vec<String>,
285 /// `false`: an inserted run is plain text, so a `\t` or `\n` writes a
286 /// tab or line break; other control characters and the symbol
287 /// placeholder U+FFFC are refused.
288 pub plain_text_runs: bool,
289 /// `true`: edit ranges crossing fields, hyperlinks, content controls,
290 /// revisions and symbols are refused. A range over a tab, a line
291 /// break or a non-breaking hyphen removes it; a page or column break
292 /// stays. A comment edits nothing and may cover any of them; its
293 /// anchor text is the paragraph as it reads, so it cannot start or
294 /// end in deleted text.
295 pub refuses_opaque_ranges: bool,
296 /// `false`: legacy `.doc` input is not read. An OLE compound file (a
297 /// Word 97-2003 `.doc`, or an encrypted document of any Word version)
298 /// is refused with `LEGACY_DOC` on every entry point, and RTF with
299 /// `UNSUPPORTED_PACKAGE`.
300 pub reads_legacy_doc: bool,
301 /// Package budgets [`crate::admission::admit`] enforces (`read` and
302 /// `edit` use these defaults; the redline comparer uses the roomier
303 /// `compare`). Larger input is refused with `INPUT_LIMIT`.
304 #[serde(default)]
305 pub input: InputBudget,
306}
307
308/// Package budgets as the manifest reports them, in the same units
309/// [`crate::admission::InputLimits`] uses.
310#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
311pub struct InputBudget {
312 /// Maximum compressed (.docx) size in bytes.
313 pub max_compressed_bytes: u64,
314 /// Maximum number of ZIP entries the package may contain.
315 pub max_entries: usize,
316 /// Maximum inflated size of any one part, in bytes.
317 pub max_part_bytes: u64,
318 /// Maximum total inflated size of all parts, in bytes.
319 pub max_uncompressed_bytes: u64,
320 /// Maximum element nesting depth in any XML part.
321 pub max_xml_depth: usize,
322 /// Maximum XML element start tags across all the package's parts
323 /// (#2014). `None` in a manifest written before 0.17.0, whose engine
324 /// had no element limit.
325 #[serde(default, skip_serializing_if = "Option::is_none")]
326 pub max_xml_elements: Option<u64>,
327 /// Maximum characters of text plus elements in one compared side
328 /// (#2024). `None` in a manifest written before 0.17.0, whose comparer
329 /// had no such limit.
330 #[serde(default, skip_serializing_if = "Option::is_none")]
331 pub max_story_units: Option<u64>,
332}
333
334impl From<crate::admission::InputLimits> for InputBudget {
335 /// Converts an [`crate::admission::InputLimits`] budget into the
336 /// manifest-facing [`InputBudget`] (same fields, different struct).
337 fn from(l: crate::admission::InputLimits) -> Self {
338 Self {
339 max_compressed_bytes: l.max_compressed_bytes,
340 max_entries: l.max_entries,
341 max_part_bytes: l.max_part_bytes,
342 max_uncompressed_bytes: l.max_uncompressed_bytes,
343 max_xml_depth: l.max_xml_depth,
344 max_xml_elements: Some(l.max_xml_elements),
345 max_story_units: Some(l.max_story_units),
346 }
347 }
348}
349
350/// The extensions each task's `-o` writes, by task name: Word, the agent
351/// view (`md`), a rendered PDF, PNG pages and the JSON snapshot. `diff -o`
352/// writes text under any of `DIFF_EXTENSIONS`. The CLI's `-o` rule reads this
353/// table, so its refusals and its help agree.
354pub const OUTPUT_FORMATS: &[(&str, &[&str])] = &[
355 ("compare", &["docx", "md", "pdf", "png", "json"]),
356 ("convert", &["docx", "md", "pdf", "png", "json"]),
357 ("read", &["md", "json"]),
358 ("diff", &["md"]),
359 ("accept", &["docx", "md", "pdf", "png", "json"]),
360 ("reject", &["docx", "md", "pdf", "png", "json"]),
361 ("append", &["docx", "md", "pdf", "png", "json"]),
362 ("scrub", &["docx", "md", "pdf", "png", "json"]),
363 ("edit", &["docx"]),
364 ("add", &["docx"]),
365];
366
367/// File extensions `diff -o` writes as text output: Markdown, plain text,
368/// and the two patch file extensions (`patch` and `diff`). Replaces the
369/// `md` row of [`OUTPUT_FORMATS`] for the `diff` task.
370pub(crate) const DIFF_EXTENSIONS: &[&str] = &["md", "markdown", "txt", "patch", "diff"];
371
372/// One-line note describing how ids print, used as [`Ids::note`] in the
373/// manifest. Records the body vs. story prefix and the shell-safety rule.
374pub(crate) const IDS_NOTE: &str = "body ids print without a story (r12); every other story prints \
375 {story}.r{id} (header1.r1, footnotes.r3); rows and cells sit under their table \
376 (t0.row1.cell2); every id is safe unquoted in bash, csh and zsh";
377
378/// Whether `runtime` dispatches PlanV2 end to end. The CLI runs `edit
379/// apply --plan` and inline edits through [`crate::edit::prepare_v2`];
380/// `edit template` generates a PlanV2 that `edit apply --plan` then runs.
381/// A Rust embedder calls `prepare_v2` directly. The Python and WASM bindings
382/// expose no PlanV2 entry point yet, so their hosts stay on plan version 1.
383///
384/// Runtime names form a closed set: `cli`, `rust`, `python`, `wasm`, used
385/// by `src/bin/jubarte.rs`, the library tests, `jubarte-python/src/lib.rs`
386/// and `jubarte-wasm/src/lib.rs`, respectively. Any other name gets plan
387/// version 1 only.
388fn dispatches_v2(runtime: &str) -> bool {
389 matches!(runtime, "cli" | "rust")
390}
391
392/// Whether `runtime` runs an edit plan with `--skip-failed`: the CLI and a
393/// Rust embedder ([`crate::edit::PrepareOptions::skip_failed`]). The Python
394/// and WASM bindings take no such option.
395fn skips_failed(runtime: &str) -> bool {
396 matches!(runtime, "cli" | "rust")
397}
398
399/// The plan versions `runtime` dispatches, ascending: the manifest's
400/// `edit_plan_versions` and the focused matrix agree on it.
401fn dispatched_plan_versions(runtime: &str) -> Vec<u32> {
402 if dispatches_v2(runtime) {
403 vec![crate::inspect::SCHEMA_VERSION, 2]
404 } else {
405 vec![crate::inspect::SCHEMA_VERSION]
406 }
407}
408
409/// Builds a [`Capabilities`] manifest for `runtime` (typically `cli`,
410/// `python`, `rust`, `wasm`). Every operation in the default build is
411/// `true`, but what a runtime has no entry point for (`edit_skip_failed`,
412/// the plan versions); a wrapper overrides fields in its own manifest when
413/// it compiles an operation out.
414#[must_use]
415pub fn capabilities(runtime: &str) -> Capabilities {
416 Capabilities {
417 schema_version: 1,
418 engine_version: env!("CARGO_PKG_VERSION").to_string(),
419 runtime: runtime.to_string(),
420 operations: Operations {
421 compare: true,
422 accept_revisions: true,
423 reject_revisions: true,
424 selective_revisions: true,
425 revision_records: true,
426 pdf: true,
427 png: true,
428 inspect_body: true,
429 markdown: true,
430 edit: true,
431 comments: true,
432 markdown_to_docx: true,
433 markdown_diff: true,
434 patch: true,
435 diff_render: true,
436 page_ranges: true,
437 comment_threads: true,
438 edit_keeps_revisions: true,
439 append: true,
440 content_controls: true,
441 validate: true,
442 repair: true,
443 fields: true,
444 scrub: true,
445 audit: true,
446 edit_skip_failed: skips_failed(runtime),
447 },
448 edit_plan_versions: dispatched_plan_versions(runtime),
449 edit_operations: crate::edit::dispatched_operation_kinds(),
450 limits: Limits {
451 stories: std::iter::once(crate::inspect::BODY_STORY)
452 .chain(crate::inspect::STORY_KINDS.iter().copied())
453 .map(str::to_string)
454 .collect(),
455 plain_text_runs: false,
456 refuses_opaque_ranges: true,
457 reads_legacy_doc: false,
458 input: crate::admission::InputLimits::default().into(),
459 },
460 audit_rules: crate::audit::RULES
461 .iter()
462 .map(|rule| rule.0.to_string())
463 .collect(),
464 validate_rules: crate::validate::RULE_SETS
465 .iter()
466 .map(|set| set.to_string())
467 .collect(),
468 formats: OUTPUT_FORMATS
469 .iter()
470 .map(|(task, names)| {
471 let names = if *task == "diff" {
472 DIFF_EXTENSIONS
473 } else {
474 names
475 };
476 let extensions = names.iter().map(|name| format!(".{name}")).collect();
477 ((*task).to_string(), extensions)
478 })
479 .collect(),
480 ids: Ids {
481 change: strings(crate::ids::CHANGE_SPELLINGS),
482 comment: strings(crate::ids::COMMENT_SPELLINGS),
483 comment_text: strings(crate::ids::COMMENT_TEXT_SPELLINGS),
484 paragraph: strings(crate::ids::PARAGRAPH_SPELLINGS),
485 table: strings(crate::ids::TABLE_SPELLINGS),
486 control: strings(crate::ids::CONTROL_SPELLINGS),
487 note: IDS_NOTE.to_string(),
488 },
489 settlement_options: if runtime == "cli" {
490 [("--keep-nested-comment".into(), "accept / reject; convert with --track-changes accept|reject: keep wholly removed comment threads on empty anchors (default: remove)".into())].into()
491 } else {
492 BTreeMap::new()
493 },
494 }
495}
496
497fn strings(values: &[&str]) -> Vec<String> {
498 values.iter().map(|value| (*value).to_string()).collect()
499}
500
501/// Renders a [`Capabilities`] as text, one line per field: an `engine:`
502/// header, `NAME: yes|no` per operation, plan versions and operations,
503/// stories, limits, validate rules, audit codes, `-o` formats and id
504/// spellings, ending with `run with --json for the manifest`. The format
505/// `jubarte capabilities` prints without `--json`.
506#[must_use]
507pub fn capabilities_text(c: &Capabilities) -> String {
508 let yes = |b: bool| if b { "yes" } else { "no" };
509 let mut out = format!("engine: jubarte {} ({})\n", c.engine_version, c.runtime);
510 for (name, has) in c.operations.entries() {
511 out.push_str(&format!("{name}: {}\n", yes(has)));
512 }
513 let versions: Vec<String> = c.edit_plan_versions.iter().map(u32::to_string).collect();
514 out.push_str(&format!("edit plan versions: {}\n", versions.join(", ")));
515 out.push_str(&format!(
516 "edit operations: {}\n",
517 c.edit_operations.join(", ")
518 ));
519 out.push_str(&format!("stories: {}\n", c.limits.stories.join(", ")));
520 let input = &c.limits.input;
521 out.push_str(&format!(
522 "limits: plain text runs {}, refuses opaque ranges {}, reads legacy .doc {}, \
523 {} bytes compressed, {} entries, {} bytes per part, {} bytes uncompressed, \
524 XML depth {}, {}, {}\n",
525 yes(c.limits.plain_text_runs),
526 yes(c.limits.refuses_opaque_ranges),
527 yes(c.limits.reads_legacy_doc),
528 input.max_compressed_bytes,
529 input.max_entries,
530 input.max_part_bytes,
531 input.max_uncompressed_bytes,
532 input.max_xml_depth,
533 input.max_xml_elements.map_or_else(
534 || "no XML element limit".to_string(),
535 |n| format!("{n} XML elements")
536 ),
537 input.max_story_units.map_or_else(
538 || "no story unit limit".to_string(),
539 |n| format!("{n} story units per compared side")
540 )
541 ));
542 let rules: Vec<String> = c
543 .validate_rules
544 .iter()
545 .map(|rule| {
546 if rule == "word" {
547 format!("{rule} (default)")
548 } else {
549 rule.clone()
550 }
551 })
552 .collect();
553 out.push_str(&format!("validate rules: {}\n", rules.join(", ")));
554 out.push_str(&format!("audit codes: {}\n", c.audit_rules.join(", ")));
555 let formats: Vec<String> = OUTPUT_FORMATS
556 .iter()
557 .filter_map(|(task, _)| {
558 let extensions = c.formats.get(*task)?;
559 Some(format!("{task} {}", extensions.join(" ")))
560 })
561 .collect();
562 out.push_str(&format!("formats: {}\n", formats.join("; ")));
563 out.push_str(&format!(
564 "ids: revisions {}; comments {}; comment text {}; paragraphs {}; tables {}; controls {}\n",
565 c.ids.change.join(", "),
566 c.ids.comment.join(", "),
567 c.ids.comment_text.join(", "),
568 c.ids.paragraph.join(", "),
569 c.ids.table.join(", "),
570 c.ids.control.join(", ")
571 ));
572 out.push_str(&format!("ids note: {}\n", c.ids.note));
573 for (flag, meaning) in &c.settlement_options {
574 out.push_str(&format!("{flag}: {meaning}\n"));
575 }
576 out.push_str("run with --json for the manifest\n");
577 out
578}
579
580/// The manifest serialized as pretty-printed JSON; the body
581/// `jubarte capabilities --json` prints and the form a host stores.
582#[must_use]
583pub fn capabilities_json(runtime: &str) -> String {
584 serde_json::to_string_pretty(&capabilities(runtime)).expect("manifest serializes")
585}
586
587#[cfg(test)]
588#[cfg_attr(all(coverage_nightly, test), coverage(off))]
589mod tests {
590 use super::*;
591
592 /// A manifest from before the element budget (#2014) reads as having
593 /// none, not as a budget of 0; today's carries the default's.
594 #[test]
595 fn an_older_manifest_has_no_element_limit() {
596 let older: InputBudget = serde_json::from_str(
597 r#"{"max_compressed_bytes":1,"max_entries":2,"max_part_bytes":3,"max_uncompressed_bytes":4,"max_xml_depth":5}"#,
598 )
599 .unwrap();
600 assert_eq!(older.max_xml_elements, None);
601 assert_eq!(older.max_story_units, None);
602 assert!(
603 !serde_json::to_string(&older)
604 .unwrap()
605 .contains("max_xml_elements")
606 );
607 let today = InputBudget::from(crate::admission::InputLimits::default());
608 assert_eq!(today.max_xml_elements, Some(2_000_000));
609 assert_eq!(today.max_story_units, Some(2_000_000));
610 }
611
612 #[test]
613 fn manifest_reports_the_crate_version_and_every_edit_kind() {
614 let c = capabilities("rust");
615 assert_eq!(c.engine_version, env!("CARGO_PKG_VERSION"));
616 assert_eq!(c.runtime, "rust");
617 assert_eq!(c.edit_plan_versions, [1, 2]);
618 assert_eq!(c.edit_operations.len(), 26);
619 assert!(c.operations.fields);
620 for op in ["insert_toc", "redact", "settings", "strike", "restore"] {
621 assert!(c.edit_operations.iter().any(|o| o == op), "{op}");
622 }
623 assert!(c.edit_operations.iter().any(|kind| kind == "rewrite"));
624 assert!(
625 c.edit_operations
626 .iter()
627 .any(|kind| kind == "delete_comment")
628 );
629 assert!(c.operations.comment_threads);
630 assert!(c.edit_operations.iter().any(|kind| kind == "fill_control"));
631 assert!(c.operations.content_controls);
632 assert!(c.operations.markdown_to_docx && c.operations.markdown_diff);
633 let json: serde_json::Value = serde_json::from_str(&capabilities_json("cli")).unwrap();
634 assert_eq!(json["runtime"], "cli");
635 assert_eq!(json["operations"]["png"], true);
636 assert_eq!(json["operations"]["comment_threads"], true);
637 assert_eq!(json["operations"]["selective_revisions"], true);
638 assert_eq!(json["operations"]["diff_render"], true);
639 assert_eq!(json["operations"]["page_ranges"], true);
640 assert_eq!(json["operations"]["edit_keeps_revisions"], true);
641 assert_eq!(json["operations"]["scrub"], true);
642 assert_eq!(json["operations"]["append"], true);
643 assert_eq!(json["limits"]["reads_legacy_doc"], false);
644 assert_eq!(json["limits"]["input"]["max_entries"], 10_000);
645 assert_eq!(json["limits"]["input"]["max_xml_depth"], 256);
646 let back: Capabilities = serde_json::from_value(json).unwrap();
647 assert_eq!(
648 back.limits.stories,
649 ["body", "header", "footer", "footnotes", "endnotes"]
650 );
651 assert!(back.operations.validate && back.operations.repair);
652 assert_eq!(back.limits.input.max_part_bytes, 64 * 1024 * 1024);
653 }
654}