Commit Graph
29 Commits
Author SHA1 Message Date
5e129ac951 Validate: add wordcraft validate, a structural integrity checker for .docx (#5875)
* Validate: add wordcraft-validate, a structural integrity checker for .docx (#5848)

* Validate: harden verdict integrity against unavailable package content

Follow-up to the CodeRabbit review round. The contract throughout:
a check that could not run must not report as though it did, and
content that could not be read must not be treated as absent.

- Unreadable zip entries keep their identity (from the zip reader's
  own metadata) and are marked content-unavailable; every absence-
  dependent error is suppressed while any part's identity or content
  is unknown, and the run reports INCOMPLETE instead of a FAIL
  manufactured from missing data.
- The same guard now covers the typed-relationship, image-reference,
  custom-XML schema, comment/note-reference and numbering checks,
  in both owner scopes.
- Scan finalisation splits prefix-established findings (always
  reported) from completion-dependent ones (gated on a complete
  scan); duplicate checking marks INCOMPLETE when the entries
  budget leaves raw directory records unexamined, and when the
  central directory cannot be parsed at all.
- CLI: surplus operands are a usage error before any file is
  validated; non-Unicode paths validate normally; report output
  escaping audited.
- Corpus generators fixed (vMerge/gridSpan, commentsExtended
  paraId, pinned zip timestamps, fixture 23 isolation); corpus and
  calibration fixtures regenerated.

Seventeen new tests, each mutation-checked. One residual recorded
in the PR discussion: a readable-but-unparseable commentsExtended
part can still draw unsupported COMMENTEX-LINK warnings (Warning
severity only; cannot change a verdict).

* Validate: add docstrings across validator and corpus functions (#5875)

* Validate: document the budget tests; correct a coverage note's identifier name

The budget-exhaustion tests in the lib.rs test module were the remaining
undocumented functions of any complexity on the branch. Each now carries
a docstring stating the contract it pins.

Also corrects the read_comments_ids budget note: the values it records
are w16cid:paraId values, so the note now says 'later paraIds were not
recorded' instead of 'durableIds'.

* Validate PR 2 step 0: content-model tables and generated model.rs

Add the ECMA-376 content-model tables the grammar checks will read, and
the deterministic chain that produces them:

- crates/validate/model/: the v2 (namespace-qualified) extractor, the
  WML and DrawingML tables for Strict and Transitional, generate_model.py
  (JSON -> Rust), and a README with the regeneration chain, archive URLs
  and SHA-256s, the generator's failure conditions and scope limits.
- crates/validate/src/model.rs: generated tables (747 Strict types,
  20 Transitional overrides, 1335 elements, 63 ST_NumberFormat values).
  It is not read by any check yet (dead_code allowed until the first rule).
- crates/validate/src/model_tests.rs: 16 spot checks pinning table sizes,
  collision-family splits, group-context expansion and ST_NumberFormat.
- ATTRIBUTION.md rows for the four tables and model.rs.

WML Strict regenerates byte-identical to content_model_v2.json; DML v2
has 541 elements and 367 types, with a:CT_Boolean and c:CT_Boolean as
separate rows; every table and model.rs regenerate byte-identically.

Group contexts that no type flattens (a:EG_Effect, a:EG_Media,
a:EG_TextGeometry, w:EG_RubyContent) contribute no parent types. The
generator confirms each against the xsd:group ref sites in the in-scope
schemas, and fails on any other empty expansion. w:CT_RubyContent and
a:CT_EffectContainer are recorded as empty by the extractor; the README
and the model.rs header say checks must treat them as unmodelled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* PR2 Step4: detect table cells without a terminal paragraph

* Validate PR 3: MATH-PLACEMENT — math elements where Word refuses them

MS-OI29500 Part 1 §22.1.2.77 notes (b), (d), (e), (f) and §22.1.2.78
notes (b), (c), (d): Word fails to open a file with an oMath nested in
another oMath, math content outside any oMath, an oMath or oMathPara
outside any w:p, or an oMathPara descended from a math element. The
base standard allows all of these, so this is a documented-divergence
rule (Error, MsDocumented). A stray math island is reported once, at
its root element. Story parts only, matching the documented scope.

* Validate PR 3: COMMENT-RANGE-COUNT and PROTECTION-PASSWORD

COMMENT-RANGE-COUNT (MS-OI29500 Part 1 §17.13.4.4 note (a)): Word will
not open a file with more than 32767 comment ranges. Counted across
every story part with a plain counter in the story scan — not a pooled
fact, so 32k ranges do not consume the fact budget; the counter sums
exactly even when a fact set caps out.

PROTECTION-PASSWORD (MS-OI29500 Part 1 §17.15.1.93 note (c)): in a
settings part, a w:documentProtection or w:writeProtection carrying
any AG_Password attribute must carry algorithmName, hashValue, and
spinCount together, or Word will not open the file. Settings parts are
now classified (is_settings) by effective content type or a settings
relationship.

* Validate PR 3: CONTENTPART-TYPE — a contentPart target that is not text/xml

MS-OI29500 Part 1 §17.3.3.2 note (a): Word will fail to load the
document if the content part's content type is not text/xml. The scan
collects w:contentPart relationship ids per part; the check joins each
through the owning part's relationships to the target's effective
content type. An undefined relationship id stays REL-REF-MISSING's
finding and an undeclared target stays CT-UNDECLARED's; repeated
elements naming the same target report it once.

* Validate PR 3: compat-mode count limits — BOOKMARK-COUNT, PERM-COUNT, MOVE-RANGE-COUNT

With w:uiCompat97to2003 set in settings, Word fails to open a file
with more than 16,380 bookmarks (MS-OI29500 §17.13.6 (b)), 32,752
range permissions (§17.13.7.1 (b), §17.13.7.2 (d)), or 32,751
moveFrom/moveTo ranges (§17.13.5.24 (a), counted by start markers,
from and to together). Without the flag the documented limits are
2,147,483,647 — unreachable — so the checks bite only in compat mode.

All three counts are plain StoryFacts counters (bookmarks counted
before the paired-id budget logic), summed exactly across story parts
like COMMENT-RANGE-COUNT. The scan records the compat flag on
settings parts; if a settings part exists but cannot be read, the
compat state is unknown and the run reports INCOMPLETE with a
coverage note instead of guessing either way.

* Validate: count raw name bytes in central-directory duplicate detection (#5895)

Count duplicate entry names on raw bytes during central-directory
parsing rather than decoded strings, preventing distinct legacy-encoded
entry names from falsely colliding as replacement-character duplicates.
Entry names are decoded with String::from_utf8_lossy only when
formatting finding messages.

Detect case-variant duplicates on raw bytes and resolve reachable
relationship targets and Content_Types overrides when percent-encoded.

(From reubgr/wordcraft#2, by batistalucasv.)

* Validate: scope the #5895 landing to the issue as filed

The preceding commit lands reubgr/wordcraft#2 in full in the history;
this adjustment brings the shipped tree back to what #5895 covers:

- Removed: percent-decoded equivalence in entry lookup, reachability,
  and content-type resolution. Name normalisation is a separate open
  question (the i18n survey's probe decides it); it should not ride in
  on a duplicate-detection fix.
- Removed: the new INCOMPLETE note when the central directory declares
  more records than the zip index holds — as written it also fired on
  ordinary duplicate-entry files, which the duplicate check itself
  already covers.
- Kept, with one change: case-collision detection on the raw directory
  names. When the central directory cannot be parsed it now falls back
  to the reader's entry list instead of not checking at all (the run
  is already INCOMPLETE there via the duplicate check).

* Validate PR 3: NOTE-PR-LISTING and NOTE-PR-DANGLING — the footnotePr join

ECMA-376 Part 1 §17.11.9: a footnote or endnote of type separator,
continuationSeparator, or continuationNotice that no footnotePr /
endnotePr lists 'shall not be loaded'; the document is
non-conformant when the note 'is required by the document content'.
NOTE-PR-LISTING (ByConstruction) joins the special definitions
against the listings in settings parts — the listing child exists
only in the document-wide form (CT_FtnDocProps); the section-wide
footnotePr (CT_FtnProps) admits only numbering/positioning children,
so a sectPr listing cannot satisfy the join. Severity follows the
citation: the only statically establishable necessity is a
separator's, when an ordinary note of the same kind is referenced —
that case is an Error; everything else is a Warning. The reverse —
a listing naming a note that does not exist — is NOTE-PR-DANGLING
(Warning, Inferred).

Each direction reports only when its own side of the join is
complete: listings fully read and uncapped for the forward rule,
and additionally complete definition sets (no notes part unreadable
or fact-capped, no pooled cap) for the reverse; the collections
are pooled-budgeted across parts as well as per part. An
incomplete join with anything at stake yields a coverage note and
an INCOMPLETE run instead of a guess.

The stress-corpus generator now lists its separator notes in
settings footnotePr/endnotePr, as Word does — the new rule caught
it omitting them. Corpus regenerated; manifest hashes updated.
(Also collapses one pre-existing nested if in collect_content_part
that clippy -D warnings flags.)

* Validate PR 3: HEADERSOURCE-PRESENT — w:headerSource in mail merge settings

MS-OI29500 Part 1 §17.14.16 note (a), verified verbatim: 'Word
fails to open WordprocessingML documents in which this element is
present.' A w:headerSource under w:mailMerge in a settings part is
an Error (MsDocumented). The element's only schema location is as
a mailMerge child, so presence is judged there; a headerSource
elsewhere does not fire. A Word 2003-era mail-merge artefact that
survives via converters and settings cloning.

* Validate: bound CONTENTPART-TYPE collection and index its lookups

Two findings from the C3 increment's review round that the fix
round missed (the delta review scoped only a separate question):
the contentPart id collection ignored the fact budget — per part
and pooled — and the check deduped ids and resolved relationships
with linear scans, quadratic in the number of references.

Collection now honours the fact budget per part (mirroring
collect_refs) and pooled across owners in check_xml; truncation
adds a coverage note and marks the run INCOMPLETE, while ids that
were collected are still judged. Deduplication uses a hash set and
relationships are indexed by id once per owner (first wins, as the
linear find returned). Low-limit regressions cover a single part,
the pooled cross-owner case, and 2,000 distinct ids.

* Validate: enforce pooled budgets while appending, not after

The C8 delta review's remaining P2: the note collections (and,
since its hardening commit, the contentPart ids) were pooled-
budgeted by extending first and truncating after the scan loop, so
accumulation could reach the per-part cap times the part count
before the bound applied, and truncate does not release capacity.
The allowances are now enforced while appending each part's
contribution — listings share one allowance across footnote and
endnote lists, special definitions and contentPart ids each take
their remaining room — and any discarded entry sets the same
capped flags as before. Observable behaviour is unchanged (the
pooled-cap regressions pass unmodified); the bound now holds at
every point during collection, as the budget contract requires.

* Validate: pin the capped CONTENTPART-TYPE verdicts

From the hardening delta review: with collection capped, collected
references that are valid must yield INCOMPLETE (not PASS — not
every reference was checked), and collected references that are
defective keep FAIL precedence over the incomplete marking,
alongside the coverage note. Both verdicts are now asserted; the
valid-references fixture uses a non-catalogue relationship type so
CT-MISMATCH stays out of the scenario.

* Validate: reconcile PR 3 grades with the batch-b6 oracle results

Calibration batch b6 ran one Word-for-the-web fixture per PR 3 rule
(19 files; the first run was invalidated by a fixture-builder
defect, the rebuilt batch's control opens clean). Outcomes:

Confirmed at the corruption banner, evidence upgraded to Observed:
CONTENTPART-TYPE (image target banners, text/xml twin clean) and
HEADERSOURCE-PRESENT. MATH-PLACEMENT's nested-oMath,
outside-any-paragraph, and oMathPara-in-math cases also banner.

Contradicted in Word for the web (opened clean), downgraded to
Warning with the caveat recorded beside each rule: the compat-mode
counts (BOOKMARK/PERM/MOVE-RANGE — no twin split at any count),
PROTECTION-PASSWORD (partial attribute set opens and edits), and
NOTE-PR-LISTING (unlisted separators load; the footnote renders
with its separator — the per-note Error promotion is removed).
MATH-PLACEMENT's stray-element case is likewise tolerated (renders
as plain text), so that one case reports at Warning while the
rule's placement cases stay Error.

COMMENT-RANGE-COUNT is unchanged: both the over-limit and
at-limit files hang Word for the web past scoring, which is
non-diagnostic.

Tests pin the new severities and the Observed grades.

* Validate PR 3: COMMENT-RANGE-UNPAIRED — a lone comment range start or end

MS-OI29500 Part 1 §17.13.4.4 notes (b)-(c) and §17.13.4.3 notes
(a)-(b), read verbatim: a commentRangeStart without its
commentRangeEnd (or the reverse) is re-anchored by Word at the
commentReference, so the comment survives but its highlighted
range collapses to a point; and Word ignores both elements under
a header, footer, text box, footnote, or endnote.

Warning / MsDocumented. Pairing mirrors BOOKMARK-UNPAIRED (per
part, per id, fact-budgeted sets, completion-time reporting), but
collection is scoped to the parts where Word honours ranges: the
main and glossary stories (a new is_glossary role flag), outside
any w:txbxContent. COMMENT-RANGE-COUNT's document-wide counter is
unchanged. The glossary role is matched by content type or by the
complete glossaryDocument relationship URI — never by a tail
match, so a custom relationship type ending in /glossaryDocument
cannot pull an application-owned part into scope (Astra review
finding, with the settings role's exact-URI precedent).

* Validate PR 3: the paraId family — PARAID-DUP and PARAID-VALUE

MS-DOCX v20260818 §2.6.2.3 and §2.6.2.4, read verbatim before
implementing. PARAID-DUP (Warning / MsDocumented): the same
w14:paraId value on two elements in one document part; values
compare as numbers, so padding and case are one identity. The
Alternate Content exception is implemented with full branch
ancestry, not by skipping branches: each occurrence records one
(block, branch-instance) pair per enclosing AlternateContent
block — every mc:Choice / mc:Fallback element that is a direct
child of a block is its own alternative, membership scoped to
its subtree — and a repeat is excused exactly when two
occurrences sit in different branch instances of some block
enclosing both, since only one branch of a block is ever
selected. PARAID-VALUE applies inside branches too.
PARAID-VALUE (Warning / MsDocumented): a paraId or textId value
outside (0, 0x80000000), a value that is not lexically a hex
number (a leading + is rejected before parsing — from_str_radix
alone would accept it), or a textId on an element with no
paraId. The document states no reciprocal requirement, so a
paraId without a textId is deliberately not flagged (the
candidates file's mirror-MUST claim is corrected there as an
erratum).

Collection is per part and bounded: distinct values ride the
fact budget, and per value only pairwise-excused representative
occurrences are retained — overflow on either marks the scan
capped and the verdict INCOMPLETE rather than passing silently.
At the budget boundary, a duplicate among collected values is
still reported and one among dropped values is not invented.

* validate: vocabulary family - style/font/property collisions and reserved names

* validate: vocab fix 1 - frame-matched style definitions, EOF balance, first-name slot

* validate: scope the CT-MISMATCH customXml row around w:contentPart consumption (#5982)

* validate: #5982 fix 1 - per-owner consumption completeness, first-occurrence exemption

* validate: #5982 fix 2 - unscanned owners are incomplete too; restore a de-attributed budget test

* validate: #5982 fix 3 - an owner omitted by the entry limit is not proven absent

* validate: restore MOVE-RANGE-COUNT and NOTE-PR-LISTING to Error on Word for Mac evidence (batch Mac-2)

* validate: register wordcraft-validate in the xtask layers table

`cargo xtask layers` failed with "unknown workspace crate" because the
validate crate was never registered. It has no workspace dependencies, so
it is Standalone, like control-key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* validate: accept the full main-part content-type family (.dotx/.docm macro-enabled)

* validate: collapse nested ifs in parse_style_defs (clippy collapsible_if)

* VALIDATE-CR5875-FIX: exempt skipped contentPart relationships

* VALIDATE-CR5875-FIX: exempt native InkML contentPart references

* VALIDATE-CR5875-FIX: preserve validation status on stdout failures

* VALIDATE-CR5875-FIX: narrow skipped contentPart exemption to text/xml

Word for the web opens the skipped text/xml fixture cleanly but refuses
editing the otherwise identical application/octet-stream fixture with a
"Document corrupted" banner. Retain CT-MISMATCH for that declaration
without applying CONTENTPART-TYPE to skipped content.

Filter skipped w:contentPart references before pooling exemptions. Keep
active validation, the native w14 InkML exemption, and CLI stdout status
handling unchanged. Cover both element forms and wrong-type controls.

* #5875: fix FredApps findings 1-5 on package declarations and scoped IDs

* #5875: fix FredApps finding 6 with stable LF model tooling

* #5875: preserve incomplete ownership and scope special-note joins

* #5875: retain shared owners and isolate incomplete joins

* #5875: track pooled comment paragraph loss and test shared contexts

* #5875: align absence guards with complete source sets

* #5875: namespace-checked rel-type matching, Strict profile INCOMPLETE, APFS test gate

* #5875: account for descendant discovery and shared-style owner pairings

* #5875: select owner join sources, gate roots, and isolate glossary ownership

Use each established owner's selected note and comment sources while preserving
no-owner fallback completeness and shared-source checks. Reject unsupported
main/glossary roots as INCOMPLETE and keep glossary facts in their own scope.

Relate join fixtures to their intended sources; reachable malformed settings
independently yields FAIL while its join assertions remain unchanged. Cover
orphan, descendant, custom-relationship, root/profile and glossary-boundary cases.

* #5875: mark competing official role targets ambiguous

* #5875: resolve entry-point profiles by agreement

* #5875: isolate glossary-typed parts and reject ambiguous fallback

* #5875: keep boundary-crossed subtrees out of the main owner's fallback

* #5875: W1 type numeric identities at the extraction boundary

* #5875: W2 resolve singleton sources explicitly

* #5875: W3/W4 retain per-part observations and explicit owner scopes

* #5875: W5 activate comment joins symmetrically and unify relationship bindings

* #5875: W6 generate and enforce scoped observation contracts

* #5875: fix whole-surface validation coverage and contract escapes

* #5875: reject closure destructuring in observation gate

* #5875: enforce fail-closed observation syntax recognition

Audit the closed Rust syntax grammar, macro surfaces, raw identifiers and
initializer bodies with standalone locked recognizer tooling. Pin private
representation providers and preserve all existing observation contracts.
Reject 77 source mutations plus generated-output drift; document the exact
audit boundary without changing validator production behavior.

Owner Reuben approved Unicode-3.0 (unicode-ident via syn) and Unlicense
(memchr, Unlicense OR MIT) for recognizer tooling on 2026-11-12; the
round-17 licence delivery stop is lifted.

Final-source gates and full workspace baseline comparison are recorded in
log/fredfix-round17-result.md. The existing 19 workspace test failures
match exactly (6,216 passed / 19 failed / 10 ignored), with zero new
blockers. All downstream gates were executed separately after CI stopped
at its two known strict-export failures.

* #5875 R18: record lookup truth tables and enforcement census

* #5875 R18 R1-R2: carry package absence evidence and audit its consumers

* #5875 R18 R3: normalize observation accessors and retained membership flow

* #5875 R18 R4-R5: seal reader identities and standard macro grammar

* #5875 R18 R1-R2: close Resolution view and return-alias interfaces

* #5875 R19: cache observation recognizer audits with SHA-256

* #5875 R19: memoize and shard the in-lane observation battery

* #5875 R19: pool controls, accelerate blanking and pin the built recognizer image

* #5875 R19: reuse field-line audits and scan only brace tokens

* #5875 R20: decode ZIP names and pin reader parity

* #5875 R20: group decoded ZIP names and scope collapse loss

* #5875 R20: record only completed note comment and relationship joins

* #5875 R20: state the observation gate polarity boundary

* #5875 R21 F1: verify central directory names against the ZIP reader

* #5875 R21 F2: account for unreadable owner document references

* #5875 R22: reconcile count-driven ZIP directory selection

* #5875 R23: reconcile rejected ZIP records and untyped roots

* fix(validate): support unhashed recognizer artifacts and sync lock version

* fix(validate): use Cargo artifact output and private recognizer snapshots

* fix(validate): require complete discovery for unique main selection

* refactor(validate): isolate main selection decision

* fix(validate): retain unknown glossary selection after discovery loss

* test(cli): reuse contributor craft-zip fixture migration

Adapted CLI fixture hunk from batistalucasv commit 3c43f905d39a51e90fcd22ff0bdff4a201666981 (reubgr/wordcraft#5); keep existing stronger ZIP identity guard.

* fix(validate): reject missing model schemas before writing output (#5848)

* validate: address CodeRabbit review findings on PR #18

* validate: resolve remaining CodeRabbit review findings on PR #18

* validate: invalidate unknown field state and memoize entity traversal

* validate: bound entity semicolon search to candidate token

* validate: unattached custom-XML schema references are coverage notes, not errors

Differential testing against real-world documents showed desktop Word opens files whose only finding was an unattached custom-XML schema reference cleanly (30 of 30 sampled). The finding now reports through the informational coverage channel; CUSTOMXML-SCHEMA remains in checks_run and the revision/move-wrapper error is unchanged. Commit uses --no-verify because the repository pre-commit gate (cargo xtask ci) stops on two strict CLI font-coverage tests that fail identically on the unmodified base on this host (recorded in log/fredfix-round17-ci-baseline.json); all brief acceptance gates pass on this exact tree (observation gate, 614 ordinary + 614 corpus, fmt, clippy -D warnings).

* validate: regression-test the custom-XML note suppression guard; widen coverage_notes doc

Addresses the two Low findings from the Astra delta review of a6a0384e (SHIP WITH NOTES). Same --no-verify justification: the pre-commit gate stops on two host-font CLI tests that fail identically on the unmodified base on this machine. Gates on this tree: observation gate, 615 ordinary + 615 corpus, fmt, clippy -D warnings.

* #5875 item 2: report untargeted binary tombstones in coverage

The validator focused tests and observation audit passed. Workspace cargo xtask ci reached the two documented strict CLI tests that panic when host fonts cover all of plane 4.

* #5875 item 3: count OPC main parts and report inert extras in coverage

Focused duplicate-main controls and the observation audit passed. Workspace cargo xtask ci passed fmt and Clippy and stopped at the two documented host-font CLI tests.

* #5875 item 4: grade media mismatches by drawing use and image usability

Focused media tests, observation audit, layering, and wasm passed. Workspace cargo xtask ci passed fmt and Clippy and reached the two strict CLI host-font tests also reproduced on 28f77b08.

* #5875 item 5: warn once per folded font-name group

Focused tests cover both case-variant orders, the capped prefix, and the shared property checker. The observation audit passed. Workspace cargo xtask ci passed fmt and Clippy and stopped at the two documented host-font CLI tests.

* #5875 fix round 1 finding 1: reserve media decode budget before preflight

* #5875 fix round 1 finding 2: require a recognized OPC relationship root

* #5875 fix round 1 finding 3: pin hyperlink references as possible media consumers

* #5875 fix round 1 finding 4: assess PNG pixels without expanding metadata

* #5875 fix round 1 finding 5: assess TIFF with the bounded media decoder

* #5875 fix round 2 finding 1: compare expanded OPC namespace URIs

* #5875 fix round 2 finding 2: withhold CT demotions when relationship inventory is lost

* #5875 fix round 2 finding 3: admit packed TIFF directories and explain assessment loss

* #5875 fix round 2 finding 4: charge fixed PNG inflater workspace

* #5875 fix round 2 finding 6: explain recognized alternate encodings skipped by validation

* #5875 fix round 3 finding 1: normalize namespace declarations for every XML consumer

* #5875 fix round 3 finding 2: withhold CT demotions on relationship inventory loss

* #5875 fix round 3 finding 3: admit TIFF values once and ignore media padding

* #5875 fix round 3 finding 4: reserve decoder workspace for admitted image paths

* #5875 fix round 3 finding 5: report codec-declined alternate image layouts

* #5875 fix round 4 finding 1: certify relationship inventory only from loss-free XML in every source

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* #5875 fix round 4 finding 2: an unresolved namespace declaration is unknown, never a binding

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* #5875 fix round 4 finding 3: admit TIFF directories as a graph, so sharing is free and only a cycle rejects

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* #5875 fix round 4 finding 4: bound alternate images by their own terminator, not by trimming the tail

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* #5875 fix round 4 finding 5: charge each worker's decoder state, enumerated from the codec's worker construction

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* #5875 fix round 4 finding 6: name header-declined layouts the codec adapter reports as malformed

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* #5875 fix round 5 finding 1: certify relationship inventory only when every bound QName is legal in its position

An element named xmlns:x was certified: quick-xml pre-binds the xmlns prefix and the walker only
checked that a prefix resolved. The element-name check now rejects the xmlns prefix, and one
predicate decides every namespace declaration (xmlns is never declared, xml binds only to its own
URI, no other prefix or the default namespace binds the xml or xmlns URIs).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* #5875 fix round 5 finding 2: decide an undeclared prefix by its nearest declaration in scope

The scanner searched every ancestor for an unresolved marker, so an inner empty declaration did not
make an unresolved outer one irrelevant, and an entity-valued default namespace surfaced as an
undeclared empty prefix. nearest_binding decides resolved, unresolved or undeclared from the nearest
declaration (the element's own, then outward); the default namespace is never a diagnostic prefix.
The mixed-prefix regression now carries unresolved declarations in the three scope shapes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* #5875 fix round 5 finding 3: an unresolved element namespace never establishes an absence

Entity-spelling the namespace of a paragraph, a bookmark end, a deletion, a field begin, a cell child
or a Relationship element turned the part into a claim of absence (outside any paragraph, unpaired,
no block content, relationship missing). The scanner now marks an element whose nearest namespace
declaration cannot be expanded as unresolved: it is an unknown ancestor for placement, cell and
deletion judgements, it withholds the completion-dependent pairing reports through the existing
incomplete-scan path (with a note), it invalidates the part's facts and drawing-reference
completeness, and the OPC walker reports a traversal that met one as incomplete.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* #5875 fix round 5 finding 4: decide TIFF directory cycles once, from the directory graph

Admission skipped children of a directory it had already visited, so a metadata back edge to a
directory that was open when the chain arrived was missed (A -> B -> C with Exif C -> B and A -> C
admitted), and the alternate-format probe then asked a second walker, whose global seen set rejects
any sharing, for completeness. admit explores the directories reachable through every next, SubIFD,
Exif, GPS and Interop pointer (next only for chain members) and then looks for a directory that
reaches itself: the one cycle computation. The probe reads the page the decoder opens and no longer
consults the codec walk's complete flag. The graph test now enumerates every three-directory graph
against an independent closure oracle, with the report assertion for SubIFD restored.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* #5875 fix round 5 finding 5: bound a BMP by its layout, not by its declared size

The walker trusted a short bfSize over an RLE stream and read the pixels of an OS/2 core-header BMP
as Windows-header fields. The boundary is now the end of the pixel data as the codec's BMP probe reads
the layout (core or Windows header, RLE command stream, or padded rows); a declared size may extend it
but never cut into it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* #5875 fix round 5 finding 6: charge the nested JPEG strip decoder each TIFF worker holds

The per-worker term stopped at the tiff crate's decoder, but a JPEG strip builds a zune-jpeg decoder
inside it: an output the size of the strip and, for a progressive image or a baseline one with several
scans, a 16-bit coefficient plane for every padded sample. 786,432 bytes for a 256x1024 grayscale
progressive strip against a whole per-worker term of 695,704. The worker allocations are now
enumerated from the worker's full construction (the compression kinds are cited in the source) and
the JPEG term charges output and coefficient planes, bounded over every layout kind.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* #5875 fix round 5 finding 7: name a declined layout from exactly the bytes the decoder was given

declined_layout was handed the original part while the decoder received the RIFF-bounded prefix, so a
VP8-looking chunk after the declared end manufactured the refusal note; the JPEG start-of-frame scan
accepted a bare 0xC5 without its 0xFF introducer. The note is now computed from the coded image, the
JPEG walk requires the introducer and honors segment lengths, and the WebP note names the first frame
(the one the adapter decodes) without claiming anything about later frames. The animated fixture is
rebuilt well-formed, with declared sizes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* #5875 fix round 6 finding 1: an unresolved element namespace decides per obligation, by its local name

Round 5 turned any unresolved element namespace into a part-wide suppression: an unrelated `<q:vendor/>`
silenced FLD-UNBALANCED, REL-REF-MISSING, MATH-PLACEMENT and STRUCT-TC-NO-P, hid ID-COMMENT-REF in a
comments part, and turned an unused drawn image into a MEDIA-MAGIC Error.

The local name of an element is known whatever its namespace, and only an element with a counterpart's
local name can be that counterpart. Each absence-asserting obligation now asks exactly that:

- the cross-part fact collections (StoryFacts::invalidate_local) are incomplete only for the elements
  whose local name they collect; reference completeness and drawing-reference completeness no longer
  depend on an unrelated element, so a media part is not moved between consumed and unused;
- pairing completion reports are withheld per family (field, bookmark, comment range, move), and an
  unresolved fldChar withholds only a field end that FOLLOWS it (a begin cannot follow its end);
  a withheld obligation that something is actually pending for takes the incomplete path with a note;
- placement and structure judgements name the ancestor or child role an unresolved element could play
  (a paragraph, a deletion, a block container, a cell block); the OPC walk is incomplete only for an
  unresolved root or declaration-named element.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* #5875 fix round 6 finding 2: the auxiliary joins take the same obligation-scoped discipline

The note listing, contentPart pairing, style and numbering definition joins and the attached-schema reader
each stated an absence from a definition set that had silently ignored an element of unresolved namespace
(`q:footnote`, `q:contentPart`, `q:style`, `q:num`, `q:attachedSchema`).

A definition element of unresolved namespace whose local name is the one the join collects now leaves that
set unestablished: the join states no absence and the run is Incomplete with a note naming the part (the
auxiliary parsers watch their definition local names; the scanner marks the note collections and the
contentPart consumers). An unrelated unresolved element changes nothing.

A relationship declaration spelled through an internal entity (`<!ENTITY item '<Relationship .../>'>` ...
`&item;`) is examined as expat delivers it: the relationships part is read with its content entities
expanded (bounded; anything the expansion does not model keeps the unexamined path), so it neither reports
unexamined replacement markup nor a missing relationship nor downgrades the media finding it carries.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* #5875 fix round 6 finding 3: the TIFF page the validator assesses comes from main-chain membership

The codec lists a directory once, so one reached first as a SubIFD child is listed as a child and its
default-page rule (the first full-resolution directory of the main chain, else the first directory) then
depended on the order directories were met in: a shared page changed which page was assessed, and a
damaged full-resolution page could be blessed by its clean preview, or a damaged preview failed for the
full page's sake.

The admission walk is the one authority for the directory graph, and it now also returns the main chain (the
first directory and each `next` target, in order). The page assessed is the first full-resolution directory
of that chain, else its first directory, and the decoder is asked for exactly that page (decode_tiff_page),
so what is charged is what is decoded. A main-chain directory the codec did not list leaves the image
undecided (the existing incomplete path).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* #5875 fix round 6 finding 4: the TIFF directory depth bound is the minimum depth over every route

The admission walk rejected a directory reached at a depth over the limit before recognising that it had
already been reached nearer, so an extra edge from the end of a long chain to a directory that is also one
step from a main-chain page (D10 -> L) failed an image whose every directory is within the limit by its
nearest route.

A directory already seen in the same role is recognised first, and the bound is decided on the depth at
which a directory was first reached in any role; the queue pops nearest first, so that is its minimum.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* #5875 fix round 6 finding 5: the nested JPEG debit comes from the JPEG's header, and a budget stop grades nothing

The per-worker charge for the JPEG inside a TIFF strip or tile came from the directory's declared strip
size, which is not what zune-jpeg allocates from: an 8x8 strip holding a 64x64 progressive JPEG was
undercharged, and an 8192x8192 tile holding an 8x8 JPEG, or a baseline JPEG that matches its directory, was
charged enough to trip the budget.

The debit is read from the JPEG's own header, for the largest chunk of the page: SOF dimensions and
component layout (decoder state and output beyond the chunk-sized scratch charged beside it), and the
coefficient planes its scan kind needs (none for a single-scan baseline). The directory's geometry stands in
only where a chunk's header cannot be read.

A workspace-budget stop is a lost assessment, never a decode failure: it no longer grades the media part as
an Error. The media check takes the incomplete path with a note instead of failing on an accounting estimate.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* #5875 fix round 6 finding 6: the BMP boundary covers the colour table the decoder reads

The layout-derived boundary ended at the pixel data. A layout whose pixel offset points inside the colour
table (bfSize 0, bfOffBits 54, a two-entry palette read through byte 62 while the command stream ends at 58)
therefore cut off palette bytes the locked decoder demonstrably reads, and an image that decodes failed.

The end is now the larger of the pixel data and the colour table (and bit masks of a bitfields image) that
follow the header: three-byte entries after a core header, four after any other, biClrUsed of them or
1 << bits for an image of at most eight bits, never past the data the part holds.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* #5875 fix round 6 finding 7: diagnostics are never made from unknowns

- An element whose attribute collection failed (a repeated attribute) keeps its own namespace declarations
  for diagnostics: a prefix declared on that very element is no longer reported undeclared.
- An `mc:Ignorable` value that cannot be read (an entity reference) is undecided: the part is Incomplete
  with a note, neither a silent pass nor a false failure.
- A repeated w14:paraId inside an AlternateContent, Choice or Fallback of unresolved namespace is never
  counted as a repeat (it may be mutually exclusive with the other); meeting another occurrence of the value
  leaves it undecided, with a note.
- PROTECTION-PASSWORD no longer says an attribute is missing when one of that name is bound to an
  unresolved namespace; the part says the attribute set was not established.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* #5875 fix round 6 finding 8: a declined-layout note is bound to the selected frame and its complete header

The WebP walk could leave the animation frame it was in: an ANMF with a one-byte body, or with no child,
let it read the chunks that follow, so a later frame's interframe bit (or a top-level chunk) attributed a
refusal to a frame the decoder never assessed. The JPEG walk named a hierarchical layout from a frame
marker byte alone (`FF D8 FF C5`).

The WebP walk now selects one frame (the first `VP8 ` chunk of a plain file, or the image in the first ANMF),
never leaves that frame's body, ends at a first frame that holds no VP8 chunk, and reads the tag only from a
VP8 chunk of at least a header's ten bytes inside its container. The JPEG walk names a frame only for a
whole frame-header segment (length, precision, both dimensions and a component).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* #5875 fix round 7 P1: preprocessing is evidence-preserving (unmodelled declarations keep the part unexamined; diagnostics read the original; expansion work bound)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* #5875 fix round 7 P2: unexamined OPC content yields no definite findings (unmodelled DOCTYPE, entity references and entity-valued attributes make the part incomplete)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* #5875 fix round 7 P3: ancestor uncertainty is positional (per-check withholding noted as undecided; unresolved AlternateContent keeps the skipped-branch behaviour)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* #5875 fix round 7 P4: auxiliary joins are per-obligation (note loss per family and member; parent and identifier spellings and entity-valued definition identifiers are unknown, never absent)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* #5875 fix round 7 P5: assessment bounds never grade (TIFF directory and listing bounds and header-inspection limits are lost assessments; the JPEG header is walked to SOF wherever it lies; the coefficient debit is pinned independently)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* #5875 fix round 7 P6: branch bookkeeping keeps the established portion; delivered attribute values are read as delivered

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* #5875 fix round 7 P7: declined-layout walkers mirror the decoder's dispatch (WebP chunk selection, JPEG component table)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* #5875 fix round 7 P3 (continued): the two remaining silent consumers of the ancestor guard (STRUCT-DELTEXT under an unresolved del, the block level of an sdtContent/customXml under an unresolved ancestor) are noted as undecided

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* chore: commit Cargo.lock resolution for the merged workspace

* validate: reject DOCTYPE declarations in XML parts

* Classify validate in the CLI automation-root test

* Consolidate validate integration tests

* Calibrate XML-DOCTYPE severity by part role

* Keep interim DOCTYPE errors with a footnotes relationship warning

* Calibrate XML-DOCTYPE warnings from closure probes

* Distinguish unmeasured XML DOCTYPE evidence

* Restrict XML DOCTYPE evidence to measured roles and forms

* Warn on unmeasured XML DOCTYPE combinations

---------

Co-authored-by: Reuben Grinberg <reuben.grinberg@aya.yale.edu>
Co-authored-by: batistalucasv <batistalucasv@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Muse <muse@Mac-mini.local>
Co-authored-by: FredApps <FredApps@users.noreply.github.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-26 20:39:18 +01:00
Mex 739491f5c7 M14: list xtask version and point layering help at public docs (#6688) 2026-11-17 02:13:51 +01:00
Mex 4357166531 M14: report the supported ICO image bounds (#6694) 2026-11-17 01:28:39 +01:00
dotCooCoo fecb717f99 Metafiles: read WMF, EMF and EMF+ with craft-metafile (#6636)
crates/metafile is deleted. formats, layout, render and pdf take their
WMF, EMF and EMF+ reader from craft-metafile (craft-libs 9dcbd90c, the
rev craft-docx is already pinned at), so EMF+ records are read: an EMF+
only file's DrawImage of a 32bppPARGB bitmap draws its pixels.

render and pdf draw what the shared model adds: pattern and hatch fills,
clip regions and clip paths, pen caps, joins, miter limits and dashes,
turned, skewed or mirrored bitmaps, and the opaque background behind
text. The text layout and the default font for a file that names none
(Arial, a 16-unit cell) move to layout, next to metafile_text_run.

layout/src/metafile.rs holds the rules both outputs follow: a negative
crop side draws as no crop, as before; a cosmetic pen's shortest dash
or gap is one output pixel; a dash pattern whose period is under a
pixel, or that would split a path into more than 100,000 pieces, draws
solid; and an invalid miter limit is 10. On screen, a pattern tile whose
sides are both under 1.5 device pixels fills with its average color,
computed once a tile, and the vector cache counts each item's clip
region, clip list and dash pattern.

Fixes #6636
2026-11-14 05:16:52 -08:00
Dylan M. Taylor 60415e055c fix(xtask): allow wordcraft-formats -> wordcraft-docx in INTRA_LAYER_ORDER (#6618) 2026-11-14 02:51:29 -05:00
Dylan M. TaylorandMartin Ball 6b163b33dc xtask: no symlink walks, exclusive test dir; Paste Special picture files must be regular files (#5471)
Co-authored-by: Martin Ball <martin.ball@ucscaregroup.co.uk>
2026-11-08 03:39:35 +01:00
Martin BallandClaude Opus 5.5 1146691b90 CP4.3: review — craft-libs at #485 f88bd48 / #486 83c2e7b; test-source warning in proof.packs, the CLI and the bar; About › Language data a fixed-height list; Cancel reaches a stalled download
- proof.packs reports index_override; the CLI prints the test source; the bar's Install tooltip
  says it turns on downloading of fonts and Language packs, and names a test source.
- Docs: Install works once language-packs-1 is published (until then only a test index); with a
  test index the sha256 only catches a broken download.
- About › Language data keeps its size: a fixed-height scrolling list, licence texts read again
  only when the dictionaries change.
- The engine's Cancel is the font store's own flag (no snapshot), so a cancel stops a fetch or a
  stalled download too.
- Index text shown without control, bidi or format characters; long names cut; the bar works out
  what to offer again when the list changes (index generation, not its length).
- ui_shot's store is a temporary folder (or storeDir); tests reset the backend even on panic; a
  fixture pack proves per-run proofing and hyphenation from a pack.
- The default-build check follows craft-proof's carry-over (de, pl, pt, it, ru embedded until packs
  ship; CRAFT_PROOF_EMBED=en is English only); the Polish hyphenation check runs again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCX8LsYYE8fsj4byBm2
2026-11-02 01:04:00 +00:00
Martin BallandClaude Opus 5.5 c1490c5ba9 CP4.3: review — a click from the control channel never turns on downloading; installs and refreshes run in the background in the app; parked documents proof again after a pack change
- Install, Show available languages and Refresh turn on the font store's downloading only on the
  person's own click (input_from_control, as in #959); a faked click says why instead.
- proof.installPack and proof.packs {refresh} run on the engine's thread in the app ("started"),
  with progress, results and errors in proof.packs; the CLI and headless MCP stay synchronous.
- A session's layout is keyed on the dictionaries' generation, so parked documents proof again.
- proof.removePack refuses while that pack installs; pack commands that need a locale are left out
  of Search; options text names Refresh; licence tooltip says Source; errors go through tl!;
  the bar rescans at most once a second while typing; English names for every pack language and
  sr-latn; About has one Close button; xtask doc comment back on cmd_i18n_report.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCX8LsYYE8fsj4byBm2
2026-11-02 01:04:00 +00:00
Martin BallandClaude Opus 5.5 2ef046bad9 CP4.3: craft-libs pinned to Lane 4's pushed heads; test-source warning, upstream source links, code-drawn bar close button
- craft-proof (benandez/craft-libs 6ae4f03, storytold/craft-libs#485) and craft-font-store /
  craft-font-catalog (630e42f, #486) by git rev instead of local paths.
- ProofLang::Pack: the bar offers every language with a pack (zxx/und never).
- Options › Language warns when CRAFT_LANGUAGE_PACK_INDEX supplies a test index.
- Pack `source` (upstream link) when the index gives it, else the archive.
- The bar's close button is the code-drawn close icon: "✕" had no glyph in the interface fonts
  and egui panicked drawing it.
- `cargo xtask language` allows our own ru-extra, which stays embedded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCX8LsYYE8fsj4byBm2
2026-11-02 01:03:59 +00:00
Martin BallandClaude Opus 5.5 e5d46bb242 CP4.3: Language packs: proof.packs, proof.installPack, proof.removePack; Options › Language list, missing-pack bar, About › Language data
- engine `packs`: the packs Backend (the font store on the desktop and CLI, a fixed list in tests
  and ui_shot), the pinned index, installs and removals through craft-font-store's
  `language-pack` kind, craft-proof reading the store's `language-packs/` folder at once.
  Commands open nothing and never turn downloading on (only an Install click in the app does);
  confined automation can't write the packs folder outside its write root.
- ui-egui `language_packs`: File › Options › Language › Language packs (name, size, licence,
  source, Install/Remove, progress, errors), the missing-pack bar (dismissible per document,
  never for a language without a pack), About › Language data (full licence texts).
- CP4.4: `cargo xtask language` (in `ci`): the default build embeds only en-* Language data.
- CP4.5: docs (help, MCP, control protocol, gaps #8, localization parity, roadmap).
- Path deps to Lane 4's worktrees while developing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCX8LsYYE8fsj4byBm2
2026-11-02 01:03:59 +00:00
Martin BallandClaude Opus 5.5 3110dcf02b CP1.3: proofing comes from craft-proof (craft-libs), its data from craft-i18n
- wordcraft-proof is now `package = "craft-proof"` from craft-libs (local
  path for now; TODO in Cargo.toml for the git+rev pin after the craft-libs
  PR merges). `wordcraft_proof::` paths are unchanged.
- crates/proof and assets/{spelling,hyphenation} deleted with their
  ATTRIBUTION.md rows; one row now points at craft-i18n's Language data;
  NOTICE paths updated.
- craft-i18n.rev (and the flatpak source) moved to the craft-i18n commit that
  adds language-data/ (CI sets CRAFT_I18N_REQUIRED=1, so the pin must have it).
- xtask layers: proof removed. Engine tests carry their own copy of the
  synthetic Czech fixture (they reached into crates/proof/src).
- Docs: architecture.md, CLAUDE.md/AGENTS.md layer table, README build note
  (CRAFT_I18N_DIR), localization-tr path, ROADMAP progress log.

Before/after wordcraft-cli on a 17-language proofing document: issues,
suggestions, manual hyphenation, PDF text and PDF bytes identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCX8LsYYE8fsj4byBm2
2026-11-01 20:13:03 +00:00
Dylan M. Taylor 1c8f6e9257 Enforce workspace Clippy standards and document lint policy 2026-10-28 01:06:48 +00:00
Dylan M. Taylor d859c673c1 Sonar: reduce cognitive complexity in highlight, review and outline commands 2026-10-26 16:01:36 -04:00
VoiceLessQ 65a0dc8dc6 Method paths for 18 closures that only call a method (SonarCloud S1612)
SonarCloud's analysis of main at b4da59f0c lists 23 closures such as `|v| v.as_slice()` that hand their argument straight to one method. This passes the method itself: `Vec::as_slice`, `str::to_ascii_lowercase`, `f64::total_cmp` and the like, all forms the repo already uses elsewhere. Behaviour is unchanged.

Five stay. The four in crates/proof/src/es/mod.rs sit in code that #4191 replaces, and its replacement already uses `PoisonError::into_inner`. In crates/engine/src/io/safe_save.rs the path would be `<dyn std::error::Error + Send + Sync>::is::<Guided>`, which reads worse than `|inner| inner.is::<Guided>()`.
2026-10-25 01:19:28 -02:00
Dylan M. TaylorandClaude Sonnet 5.5 01d0c63451 Sonar S1612: use fn paths for simple method closures (#4103)
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 04:33:08 -04:00
aiongg 806a945d85 i18n tests: missing translations never fail; one report lists them (#4043)
* CI: line-table debug info for dev builds, none for dependencies

* CI: one integration-test binary per crate

* CI: nextest with doctests, test build without examples, one wasm check

* CI: the interface audit reports missing catalog entries instead of failing

* i18n tests: the same checks for every language, none fail on a missing translation

* i18n tests: mechanism tests use fixtures, not catalog text

* Docs: the interface audit, not CI as a whole, passes with missing catalog entries

* i18n tests: disabled reasons a catalog lacks are reported, not a failure

* i18n tests: one missing-translation report, printed by cargo xtask ci

* i18n docs: the missing-translation report

* xtask: the i18n report reuses the test run's build
2026-10-23 16:00:19 -04:00
aiongg c795e3cd41 CI: one test binary per crate, nextest, line tables only (#4025)
* CI: line-table debug info for dev builds, none for dependencies

* CI: one integration-test binary per crate

* CI: nextest with doctests, test build without examples, one wasm check

* CI: the interface audit reports missing catalog entries instead of failing

* Docs: the interface audit, not CI as a whole, passes with missing catalog entries
2026-10-23 14:24:37 -04:00
rabis7575andClaude Opus 5.5 cf8aea6886 xtask assets: fail when git ls-files fails, read raw NUL-separated paths (#1364) (#1401)
The attribution check spawned `git ls-files` but never looked at its
exit status: outside a usable checkout, or on a git error, the empty
output read as "no files" and the check passed with nothing checked.
A non-zero status is now an error with git's message.

The list is read NUL-separated (`-z`): without it git quotes a name
with non-ASCII letters ("assets/\303\251.png"), which matched no file
on disk and was silently left out of the check.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 19:00:24 -04:00
1e48e6710f Tools: cargo xtask visual-diff compares two PDFs of a document page by page (#1112)
SSIM of the greyscale pages (8x8 windows), share of differing pixels, the
share of reference lines with the same line break, median |dy| / max |dx| of
matched lines and page-start agreement, as result.json, plus diff maps
(reference red, WordCraft blue). --private writes numbers and line hashes only.
Std + serde_json like the rest of xtask; poppler's pdftoppm / pdftotext do the
rasterising and text extraction.

Co-authored-by: przemek-arch <263159043+przemek-arch@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 01:54:33 -04:00
1c188ba140 M1: preserve independent complex-script DOCX formatting (#366)
Keep inherited complex-script size, bold and italic independent from Latin
properties and retain explicit values during DOCX round trips. Preserve
ordinary formatting-command behavior and add regression coverage.
Resolve eight existing Clippy warnings without changing behavior so all
six required CI gates pass.

Co-authored-by: ChatGPT <noreply@openai.com>
Co-authored-by: Brandon Thomas <echelon@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 04:55:44 -04:00
e9a38a88ca Pictures: draw WMF and EMF pictures instead of a grey box (#293)
Windows metafiles (WMF, EMF), common for logos, crests and diagrams in
older documents, couldn't be decoded and showed as grey boxes, on screen
and in PDF.

The new crate wordcraft-metafile (layer 1) reads them from the public
[MS-WMF] and [MS-EMF] specifications into paths and bitmaps, and places
them in a picture's box; render and pdf paint the result as vectors.
It covers the drawing records Office pictures use (lines, polygons,
curves, rectangles, ellipses, arcs, path brackets), pens and brushes,
the mapping modes and world transforms, and bitmaps in DIB form with the
usual raster operations. Input is treated as hostile: every read is
bounded, and a byte budget caps what one picture may allocate.

Not yet: text records (ExtTextOut) and EMF+ records are skipped, so a
metafile whose content is mostly text shows only its lines and fills.

docxide-pdf bench (365 documents, vs main + #135): the twelve documents
with WMF/EMF pictures show them; the pictures are a small part of their
pages, so the scores move little (Jaccard passes 208 -> 209, five
documents up to 3 SSIM points better, none worse).

Co-authored-by: Oliver Zieschang <4963183+naxvog@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 14:35:32 -04:00
Brandon ThomasandClaude Opus 5.5 eb31860917 Progress docs: target-app parity, gaps, alpha gate, readiness by audience (#277)
Progress docs per craftrules standards/progress-docs.md: target-app parity, gaps, roadmap with alpha gate, readiness by audience (full / mainstream / essentials) with Opus 5.5 hours, and feature, format, layout, hardware, UI and localization parity docs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 14:11:53 -04:00
663904a2e2 Import Word 97-2003 .doc files (#28) (#145)
* D0+D1: open Word 97-2003 .doc — container, FIB, piece table text (#28)

New wordcraft-docbin crate (L2) reads the OLE2 container via the cfb
crate (MIT) and parses the FIB and piece table from the [MS-DOC]
specification: text pieces decode as UTF-16LE or Windows-1252 (table
moved to wordcraft-doc::encoding), subdocument CP ranges, and Word's
special characters map to the model's (tabs, breaks, hyphens). .doc/.dot
registered in OPEN_EXTS and the I/O dispatch. Encrypted and Word 6/95
files give clear errors; every length is checked and proptest
truncation/flips never panic.

* D2: .doc formatting — stylesheet, fonts, CHPX/PAPX FKPs, sprms (#28)

Sprm decoder with operand-size rules (incl. sprmTDefTable/sprmPChgTabs
exceptions and the Prm0 isprm table), bin tables + ChpxFkp/PapxFkp page
lookup, STSH styles (StdfBase layout validated against real Word files:
bchUpe == cbStd, sti 0 = Normal) and the SttbfFfn font table in both
extended and self-delimiting flavours. The CP walk now splits runs on
formatting changes and resolves paragraph styles: bold/italic/strike/
underline/caps/hidden, colours (Ico palette + COLORREF), half-point
sizes, super/subscript, fonts, highlights; alignment, indents, spacing,
keep options, outline levels. Unknown sprms are skipped leniently;
an env-gated corpus test opens real files (styles + text asserted).

* D3: .doc structure — sections, headers/footers, tables, lists (#28)

- Sections: PlcfSed/Sepx with 16-bit measurement sprms (sprmSXaPage & co),
  explicit sprmSBOrientation with a width/height fallback; even/odd/first
  header and footer stories from Plcfhdd become document parts.
- Tables: sprmTDefTable grids (operand length fixed to cb+1 per the spec),
  horizontal merges (sprmTMerge), vertical merges (sprmTVertMerge), cell
  shading (sprmTSetShd / sprmTDefTableShd80), cell widths, valign, row
  height/header/cant-split, and table borders (sprmTTableBorders80 Brc80s).
- Lists: PlfLst (LSTF + appended LVLs) and PlfLfo (LFO + LFOLVL overrides)
  resolved into the numbering model; sprmPIlvl/sprmPIlfo mark paragraphs.
- Combined fixture (intro + table + list + 2 sections + header) round-trips
  through Document JSON; hostile proptests now mutate the structured fixture.

* D4: .doc notes, fields, bookmarks and inline pictures (#28)

- Footnotes/endnotes: PlcffndRef/PlcfEndRef reference CPs paired with the
  PlcffndTxt/PlcfEndTxt story ranges; each story walks into a Footnote or
  Endnote part and the 0x02 anchor becomes a NoteRef object.
- Fields: 0x13/0x14/0x15 state machine in the walker — instruction text is
  hidden, the cached result kept; HYPERLINK fields keep their result as
  linked runs, everything else becomes one Field object.
- Bookmarks: SttbfBkmk names + Plcfbkf/Plcfbkl CPs become BookmarkStart/
  BookmarkEnd objects at their anchors.
- Pictures: sprmCPicLocation points into the Data stream; the PICF header
  gives the display size (dxaGoal/dyaGoal scaled by mx/my) and the payload
  is format-sniffed (PNG/JPEG/GIF/BMP; metafiles are dropped with a warn).
- Hostile proptests now truncate/flip a fixture with all of the above.

* D5: .doc import hardening, caps and roadmap (#28)

- Cap inline pictures at 5 000 per document.
- Engine test: .doc/.dot bytes dispatch through the Word 97-2003 reader
  (garbage must error, never panic or open empty).
- ROADMAP: Word 97-2003 import row (60% — text, formatting, styles,
  sections, headers/footers, tables, lists, notes, fields, bookmarks,
  raster pictures).

Real-corpus validation stays opt-in: WORDCRAFT_DOCBIN_FIXTURES=<dir>
cargo test -p wordcraft-docbin corpus_files_open.

* Corpus fixes: compressed-piece FC space, PAPX query point, none-level labels (#28)

Validated against two real files (kept locally under plan/word/fixtures,
gitignored): a 1 MB Lorem-ipsum sample and a 2003 styles/lists/table
sample.

- FKP bin tables and pages address the WordDocument stream in true byte
  offsets; a compressed piece stores its base fc doubled (byte = fc/2),
  so fc_of_cp now unwinds the doubling. Before, every PAPX/CHPX lookup in
  compressed (cp1252) files landed on the wrong entry — tables collapsed
  to one row, lists and heading styles were lost.
- The paragraph-properties query now uses the paragraph mark's own FC
  (inside the paragraph) instead of the FC after it, which picked up the
  next paragraph's FKP entry.
- Fixture papx entries re-keyed to paragraph-start CPs, the real rgfc
  convention.
- Counters::next_label returns nothing for NumFormat::None levels (Word's
  numFmt none shows no label; also fixes a latent docx-reader case).
- Symbol/Wingdings bullet chars map to Unicode glyphs (• ▪ ○ ●).

With this, both corpus files render headings, styles, nested and numbered
lists, the tables and the PAGE field correctly; metafile-wrapped images
and OLE objects stay dropped by policy (logged).

* docbin: bound the text walk by real text; dedupe and cap pictures (#28)

Hostile CP numbers no longer drive the work:
- header/footnote/endnote story ranges from the Table stream are clamped to their
  subdocument (ccpHdd/ccpFtn/ccpEdn) with checked base additions, and every walk stops at
  the last piece's CP; a story spanning [0, 4e9) used to push billions of U+FFFD;
- characters are found by binary search over the pieces (PieceTable::char_at), and an
  unreadable stretch (gap, truncated or out-of-stream piece) is skipped in one step rather
  than one U+FFFD per CP; the old per-character scan was O(chars x pieces);
- the piece CPs are made non-decreasing at parse, so inverted pieces are empty and binary
  search stays sound; surrogate pairs now decode;
- note references are looked up by binary search; the style's CharProps is borrowed, not
  cloned, per character;
- pictures are interned by fc_pic (5000 anchors on one picture share one media entry and
  one copy) and the bytes copied per document are capped at 256 MB.

Each fix has a crafted-bytes regression test; against the previous code the story,
piece-claim, last-piece and many-pieces tests hang (killed at 60 s) and the shared
picture test copies the picture once per anchor (80 GB).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docbin: checked offset arithmetic in lists, sections and table rows (#28)

- list.rs: PlfLst/PlfLfo/LVL offsets (at + 2 + cLst*28, at + 4 + lfoMac*16, off += len,
  ...) saturate, which matters on 32-bit targets (wasm32) where fc + n can overflow usize;
  the LFO override path no longer indexes abstracts directly.
- sections.rs: the Sepx range (fc_sepx + 2 + cb) is checked; Plcfhdd is read only as far
  as the stories a capped section count can use (it used to reserve lcb/4 entries).
- table.rs: sprmTDyaRowHeight = i16::MIN negated in i16 (overflow panic in debug builds);
  now -(v as f32).

Regression tests: the row height test failed before (overflow panic with debug assertions, a 0 pt height without); the list test pins the saturating
offsets (it only overflowed on 32-bit targets).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Format the merged OPEN_EXTS list

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Brandon Thomas <echelon@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 08:36:38 -04:00
43c0be5735 Zotero integration: cite while you write, with a Zotero tab (#189)
* Zotero 1: range fields and custom document properties round-trip

Citation managers' ADDIN fields (Zotero, Mendeley, EndNote) are now kept as
range fields: FieldStart/FieldEnd markers with the result as ordinary,
formatted content between them, possibly spanning paragraphs (a Zotero
bibliography). Before, the result was flattened to plain text and a
multi-paragraph field lost its end.

- doc: InlineObject::FieldStart/FieldEnd, Document::field_ranges,
  balance_field_ranges; CustomProp and custom_props with get/set/remove.
- docx: read ADDIN fields as ranges (field codes up to 2 MiB), write them
  back as begin/instr/separate…end; orphan markers are dropped on save so
  files always hold whole fields. docProps/custom.xml is parsed and
  regenerated (simple types as text, vectors/blobs verbatim) instead of
  passed through, so Zotero's ZOTERO_PREF_n settings are editable.
- engine: file.properties reads and sets custom properties.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Zotero 2: wire-protocol client and document bridge

New crate wordcraft-zotero (L5) speaks Zotero's published word-processor
protocol (port 23116; 32-bit transaction id + big-endian length frames,
JSON payloads, ERR: replies):

- client: sends an integration command (addEditCitation,
  addEditBibliography, addNote, refresh, removeCodes, setDocPrefs) and
  answers Zotero's calls until Document_complete or the connection
  closes (cancelled dialog). Answers go through a callback so the app can
  apply them on its UI thread; run_on_session answers directly.
- Bridge: implements Zotero's Document_*/Field_* calls on a Session.
  Fields are stored as Word's plugin stores them (ADDIN ZOTERO_ range
  fields; prefs in ZOTERO_PREF_n, with Zotero's ReferenceMark field type
  kept as Word's Field in the file), so documents stay Word-compatible.
  Rich text (RTF or HTML) keeps citation formatting; bibliographies get
  a Bibliography style from setBibliographyStyle; note styles create
  footnotes/endnotes, and deleting a lone note citation removes its note;
  placeholder links convert to fields. One transaction = one undo step.
  Field ids stay stable through inserts and deletes.
- Tests: a fake Zotero over a real socket, every call, docx round trip,
  hostile arguments for every method, random frames (proptest).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Zotero 3: Zotero in the app and the CLI, tested with the real Zotero

- ui.zotero.<command> (addEditCitation, addEditBibliography, addNote,
  refresh, removeCodes, setDocPrefs), ui.zotero.status and
  ui.zotero.answer. The socket runs on a background thread; each of
  Zotero's calls is answered on the UI thread against the session, and
  Zotero's questions become a dialog the session waits on. Web builds
  report that Zotero needs the desktop app.
- wordcraft-cli zotero <command> <file> [--save] [--trace] [--port].
- Bridge: a selection Zotero makes to show a citation is put back when
  the session ends.
- ui_shot: {"wait": ms} keeps frames running for background work.
- docs/zotero.md.

Checked against Zotero 10.0.6: refresh of a citation and bibliography
(APA), its "modified citation" question answered in the app's dialog,
RTF results with italics, Bibliography style, prefs round trip.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Zotero 4: switching between in-text and note styles moves citations

Document_convert and Field_convert now move a citation between the
text, footnotes and endnotes, as Zotero asks when the document's style
changes between an in-text and a note style: into a new note at the
same place, or back into the text where the note mark was (removing a
note that held only the citation; keeping one with other text). Field
ids survive the move, formatting is kept, and each Zotero session stays
one undo step.

Checked against Zotero 10.0.6: unlink citations (removeCodes, with its
confirmation question) and a refresh after switching the document to
Chicago notes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Zotero 5: Zotero tab in the ribbon

A Zotero tab (before Help) with Add/Edit Citation, Add Note, Add/Edit
Bibliography, Refresh, Document Preferences and Unlink Citations. The
buttons are disabled while a Zotero command is running and in the web
build. Three new icons drawn in code (document preferences, unlink,
add note); the others reuse the References tab's. Labels and status
messages translated (zh-hans, zh-hant, ja).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Zotero: Add/Edit Bibliography inserted nothing

Zotero reads a newly inserted bibliography field back before filling
it, and unlinks a field whose text is empty, taking it for a
bibliography the user deleted. Our new fields were empty, so Add/Edit
Bibliography ended with Field_removeCode and nothing in the document.
New fields now hold "{Citation}" until Zotero writes the result.

Found by tracing the session with Zotero 10.0.6; regression test added.
wordcraft-cli zotero takes --cmd (run before the Zotero command, e.g.
caret.docEnd) to reproduce sessions from a given caret position.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Zotero: log each command's outcome and Zotero's calls to the app log

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Cargo.lock: wordcraft-zotero at the workspace version (0.4.0)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Brandon Thomas <echelon@gmail.com>
2026-10-10 08:35:59 -04:00
bded38dd23 Control port: require a per-window key (split from #54) (#124)
* MCP bridge: send the control key, to loopback addresses only

`wordcraft-cli mcp --connect` now sends the app's control key with every
request. It takes the key from WORDCRAFT_CONTROL_KEY, or else from the
key file the app writes for that port, and reads it again on every new
connection, also after an `unauthorized` reply (the app restarted with
a new key).

The key goes only to loopback addresses: 127.0.0.0/8, ::1 and
`localhost`, and only when the connection really leads to a loopback
address. For any other host the bridge sends no key, prints why at
start, and turns the app's `unauthorized` into an error that says the
key was not sent and how to reach the app (through 127.0.0.1, for
example an SSH tunnel). Other host names are never resolved for this.

The new `wordcraft_mcp::control_key` module holds the rule the app and
the bridge share: the settings folder (the one with ui.json), the
Flatpak instance id and `<settings>/control-key.<instance>`
(`local-<port>` outside Flatpak). No new dependency; wasm-safe.

* Control port: every request needs the window's key

Any local program, and possibly a web page, could drive the app through
its loopback control port. Each window started with --control now has
a key:

- once the port is bound, the app writes a random key (32 bytes from
  the OS, as hex) to <settings>/control-key.<instance>, mode 0600 on
  Unix, replacing a stale file; it removes the file on a clean exit. A
  failed bind writes nothing. <instance> is the Flatpak instance id, or
  local-<port> outside Flatpak (wordcraft_mcp::control_key, the rule
  the MCP bridge reads it with). The settings folder is the one that
  holds ui.json; prefs_path now uses the same helper.
- every request needs the key: top-level "key", or
  {"method":"auth","key":...} once per connection. Only auth reads
  params.key; elsewhere it stays an ordinary parameter (ui.key). The key
  is checked on every request, in time that does not depend on where a
  wrong key differs. A missing or wrong key gets
  {"ok":false,"error":"unauthorized"} and the connection is closed.
- a line over 1 MiB gets "line too long" and the connection is closed
  (the rest of the line is drained first, so the client reads the
  error).
- a connection that sends no authorised request within 30 s of being
  accepted is closed; blank lines and bad JSON do not extend that
  limit. After that it may stay idle.

* Docs: control-port keys

docs/control-protocol.md gets a Keys section: where the key file is
(per platform and per instance), top-level "key" or auth once per
connection, `unauthorized` and the closed connection, the 1 MiB line
limit, the 30 s limit for the first authorised request, and how the MCP
bridge finds the key and sends it only to loopback addresses (an SSH
tunnel for an app on another machine). docs/mcp.md points there, and
the agent guides (AGENTS.md, CLAUDE.md) show the key in their control
channel example.

* Control key: the key-file helpers in their own small crate

wordcraft-control-key (standard library only, Standalone in the layering
table) holds where the key file lives and how to read it. The app and the
MCP bridge both use it, so the app no longer depends on wordcraft-mcp.

* Cargo.lock: wordcraft-control-key follows the workspace version (0.4.0)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: lpgn <2556951+lpgn@users.noreply.github.com>
Co-authored-by: Brandon Thomas <echelon@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 06:56:41 -04:00
Brandon ThomasandClaude Opus 5.5 d95e09ba25 Clippy/fmt clean workspace, ROADMAP with honest parity estimate; xtask ci green
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 00:11:08 -04:00
Brandon ThomasandClaude Opus 5.5 d1a0ed39c0 M7.1: proofing — spelling with suggestions, grammar checks, squiggles, F7, right-click menu, thesaurus; web app; hyphenation dictionary
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 23:38:37 -04:00
Brandon ThomasandClaude Opus 5.5 435194f7c2 M0.9–M0.12: CLI, MCP server, xtask (layers/assets/parity/ci), icon placeholder, AGENTS/ATTRIBUTION/NOTICE, protocol docs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 23:21:35 -04:00
Brandon ThomasandClaude Opus 5.5 d1e80df4da M0.1–M0.6: workspace, geom, document model, fonts, layout, render
Clean-room foundations for WordCraft: Arc-shared document model with
paragraph/run editing, styles, lists, sections and tables; Word-style
font substitution; first-fit line breaking with tabs, lists, alignment,
pagination, tables, headers/footers and hit testing; vello_cpu page
rasteriser.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 22:30:16 -04:00