From 573628910475abaf540afd8934f81881594ba7f6 Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 11:59:09 -0500 Subject: [PATCH 1/2] docs: agent skills for the recurring task types (#10) Adds .claude/skills/ with one SKILL.md per recurring task type, each with frontmatter, step-by-step instructions whose commands were run in this checkout, a worked example that references files in the repository, and a checklist: - picking-up-an-issue: the CLAUDE.md/CONTRIBUTING.md flow made operational (unblocked-issue search, claim, worktree and branch, verification commands, commit trailers via -F, PR body via --body-file, Phase 0-1 self-merge vs later owner review, rebasing over Broadside.slnx conflicts, cleanup). - updating-the-conformance-map: file and row lookup, cell formats (backticked fully qualified types and Namespace.Class.Method tests, as #7 formalizes), third-level splits, XML doc citations, the #7 checker command marked as arriving. - writing-a-corpus-file: generate.py building blocks, naming, scratch regeneration and diff, qpdf/poppler verification, README row, Corpus.cs lists, Verify snapshot refresh; worked example text-type1-embedded.pdf (described, not added). - adding-a-benchmark: bench layout, MemoryDiagnoser and --job conventions, zero-allocation proof, dry/short/full runs, what the Phase 3I regression gate needs. - adding-a-fuzz-target: FuzzTargets.All registration, the contract, seeds, modes, same-PR rule; worked example pdf-header. - adding-a-filter, adding-a-font-program-parser, adding-a-rendering-backend: design briefs for the extension points that #18, Phase 2A and Phase 3A define, with a note to replace the contract section once the real signatures land. Adds .claude/skills/README.md as the index and a "Skills" subsection under "Picking up work" in CLAUDE.md that lists the skills and says to invoke the matching one before starting that kind of task. Signed-off-by: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Co-Authored-By: Claude Fable 5.1 --- .claude/skills/README.md | 16 +++ .claude/skills/adding-a-benchmark/SKILL.md | 89 ++++++++++++ .claude/skills/adding-a-filter/SKILL.md | 58 ++++++++ .../adding-a-font-program-parser/SKILL.md | 58 ++++++++ .claude/skills/adding-a-fuzz-target/SKILL.md | 77 +++++++++++ .../adding-a-rendering-backend/SKILL.md | 58 ++++++++ .claude/skills/picking-up-an-issue/SKILL.md | 127 ++++++++++++++++++ .../updating-the-conformance-map/SKILL.md | 98 ++++++++++++++ .claude/skills/writing-a-corpus-file/SKILL.md | 90 +++++++++++++ CLAUDE.md | 11 ++ 10 files changed, 682 insertions(+) create mode 100644 .claude/skills/README.md create mode 100644 .claude/skills/adding-a-benchmark/SKILL.md create mode 100644 .claude/skills/adding-a-filter/SKILL.md create mode 100644 .claude/skills/adding-a-font-program-parser/SKILL.md create mode 100644 .claude/skills/adding-a-fuzz-target/SKILL.md create mode 100644 .claude/skills/adding-a-rendering-backend/SKILL.md create mode 100644 .claude/skills/picking-up-an-issue/SKILL.md create mode 100644 .claude/skills/updating-the-conformance-map/SKILL.md create mode 100644 .claude/skills/writing-a-corpus-file/SKILL.md diff --git a/.claude/skills/README.md b/.claude/skills/README.md new file mode 100644 index 00000000..87e78809 --- /dev/null +++ b/.claude/skills/README.md @@ -0,0 +1,16 @@ +# Agent skills + +Each directory holds a `SKILL.md`: YAML frontmatter (`name`, `description`) followed by step-by-step instructions, a worked example that references files in this repository, and a checklist. Invoke the matching skill before starting that kind of task (`CLAUDE.md`, "Skills"). Skills assume you have read `CLAUDE.md` and nothing else. + +| Skill | Use it when | +|---|---| +| [`picking-up-an-issue`](picking-up-an-issue/SKILL.md) | Starting any unit of work: find an unblocked issue, claim it, worktree and branch, verify, commit, PR, merge policy, clean up. | +| [`updating-the-conformance-map`](updating-the-conformance-map/SKILL.md) | A PR touches a spec clause: find the row, cell formats, third-level splits, XML doc citations, the checker. | +| [`writing-a-corpus-file`](writing-a-corpus-file/SKILL.md) | A test needs a minimal PDF that `tests/Corpus/` does not have: `generate.py`, verification, README, `Corpus.cs`, snapshot. | +| [`adding-a-benchmark`](adding-a-benchmark/SKILL.md) | A PR touches a hot path: `[MemoryDiagnoser]` class, zero-allocation proof, dry/short/full runs, the regression gate. | +| [`adding-a-fuzz-target`](adding-a-fuzz-target/SKILL.md) | A PR adds or changes a parser or codec: register a SharpFuzz target, seeds, smoke mode. | +| [`adding-a-filter`](adding-a-filter/SKILL.md) | Implementing a stream filter or image codec behind the filter extension point (design brief until #18 lands). | +| [`adding-a-font-program-parser`](adding-a-font-program-parser/SKILL.md) | Implementing a TrueType, CFF, Type 1 or OpenType parser behind the font program extension point (design brief until Phase 2A lands). | +| [`adding-a-rendering-backend`](adding-a-rendering-backend/SKILL.md) | Implementing a backend that consumes display lists (design brief until Phase 3A lands). | + +Skills whose extension point does not exist in code yet say so at the top and must have their contract section replaced with the real signatures in the PR that defines the contract. diff --git a/.claude/skills/adding-a-benchmark/SKILL.md b/.claude/skills/adding-a-benchmark/SKILL.md new file mode 100644 index 00000000..609fe7bc --- /dev/null +++ b/.claude/skills/adding-a-benchmark/SKILL.md @@ -0,0 +1,89 @@ +--- +name: adding-a-benchmark +description: "Use when a PR touches a hot path (lexer, content interpreter, rasterizer, codecs) or adds any performance-sensitive code: add a BenchmarkDotNet class with MemoryDiagnoser, prove zero allocations, and run it in dry, short and full modes." +--- + +# Adding a benchmark + +`CLAUDE.md` ("Code conventions") requires that hot paths allocate nothing per token, operator, glyph or scanline and that a BenchmarkDotNet benchmark with a `MemoryDiagnoser` assertion proves it. Benchmarks also become the baseline for the Phase 3I regression gate. + +## Where benchmarks live + +`bench/Broadside.Benchmarks/`, namespace `Broadside.Benchmarks`, one class per hot path (`LexerBenchmarks`, `FlateBenchmarks`, `RasterizerBenchmarks`). The project: + +- references `src/Broadside/Broadside.csproj`; add a `ProjectReference` to `src/Broadside.Rendering/Broadside.Rendering.csproj` when you benchmark the rasterizer; +- links `tests/Broadside.TestSupport/CorpusLocator.cs` as source, so `CorpusLocator.CorpusDirectory` and `CorpusLocator.CorpusFiles()` are available, but nothing from `Broadside.TestSupport` itself (it would drag xunit and Verify in); +- sees `internal` members of every `src/` package (`InternalsVisibleTo` in `src/Directory.Build.props`), so you can benchmark the internal implementation directly; +- builds optimized; BenchmarkDotNet refuses a Debug assembly. + +`Program.cs` runs `BenchmarkSwitcher` with `BenchmarkConfig`, and exits 1 when any benchmark fails validation or execution; that exit code is the CI smoke signal. + +## Conventions + +- `[MemoryDiagnoser]` on every class. It adds the `Allocated` column. +- No job attributes (`[ShortRunJob]`, `[SimpleJob]`, `[DryJob]`) on the class. `BenchmarkConfig` supplies the job from `--job short` / `--job dry`; without `--job` it is `Job.Default`. A class-level job attribute would add a second job to every run. +- `[GlobalSetup]` loads the inputs once (corpus bytes via `CorpusLocator`), outside the measured body. +- The benchmark body is the hot path and nothing else, and returns a value derived from the work so the JIT cannot discard it. +- `[Params]` over corpus file names when the input matters; keep the values stable, they are part of the result key. +- Method names are stable identifiers; renaming one breaks its history in the regression gate. +- Per-item costs: set `[Benchmark(OperationsPerInvoke = n)]` when one call processes `n` tokens or scanlines, so the mean is per item. + +## Asserting zero allocations + +Two layers: + +1. The benchmark. With `[MemoryDiagnoser]` the `Allocated` column must read `-` (0 B) for a hot path. Any number there is a regression, whatever the baseline says. Read it from the console table or from `BenchmarkDotNet.Artifacts/results/-report-github.md`. +2. A unit test next to the feature that fails the build on regressions, because BenchmarkDotNet only reports. After one warm-up call: + + ```csharp + [Fact] + public void Tokenizing_allocates_nothing() + { + byte[] bytes = Corpus.Bytes("text-standard14.pdf"); + RunHotPath(bytes); // warm up: JIT, static init + long before = GC.GetAllocatedBytesForCurrentThread(); + RunHotPath(bytes); + Assert.Equal(0, GC.GetAllocatedBytesForCurrentThread() - before); + } + ``` + + Put only the per-item work inside `RunHotPath`; one-time buffers (`ArrayPool` rentals, the output list) are allowed per call, so size the input to make per-token allocations visible. + +## Running + +```sh +dotnet run -c Release --project bench/Broadside.Benchmarks -- --list flat # names +dotnet run -c Release --project bench/Broadside.Benchmarks -- --filter '*CorpusBenchmarks*' --job dry # one in-process iteration, proves it runs (CI) +dotnet run -c Release --project bench/Broadside.Benchmarks -- --filter '*' --job short # 3 iterations, quick local signal +dotnet run -c Release --project bench/Broadside.Benchmarks -- --filter '*' # full Job.Default run for numbers you quote +dotnet run -c Release --project bench/Broadside.Benchmarks -- --filter '*' --job dry --exporters json # adds -report-full-compressed.json +``` + +Results land in `BenchmarkDotNet.Artifacts/results/` (gitignored). `--job dry` numbers are meaningless; use them only to prove the benchmark executes. Quote `--job short` or full-run numbers in the PR's Verification section, with `Mean` and `Allocated`. + +## The Phase 3I regression gate + +Track 3I (`docs/plan/README.md`) adds a CI job that runs the suite and compares each benchmark's mean and allocated bytes against a baseline recorded from `main`, using the JSON exporter output above. What that gate needs from you now: + +- stable class, method and `[Params]` names, since the comparison is keyed by them; +- `Allocated` already at `-` on hot paths, so the gate can treat any allocation as a failure rather than a percentage; +- one benchmark per operation, not one per test case, so the baseline stays small enough to run on every PR. + +## Worked example: `CorpusBenchmarks` + +`bench/Broadside.Benchmarks/CorpusBenchmarks.cs` is the placeholder that proves the harness: `[MemoryDiagnoser]` on the class, `[GlobalSetup]` fills `_files` from `CorpusLocator.CorpusFiles()`, and `ReadAllCorpusFiles` reads every file and returns the byte total. A dry run prints: + +``` +| Method | Mean | Error | Allocated | +| ReadAllCorpusFiles | 7.612 ms | NA | 22.13 KB | +``` + +`Allocated` is non-zero because `File.ReadAllBytes` allocates; that is fine for a placeholder and would be a failure for a lexer. A lexer benchmark that replaces it keeps the same shape: `[Params("text-standard14.pdf", "xref-stream.pdf")] public string File`, `[GlobalSetup]` reads the bytes once, and `[Benchmark] public int Tokenize()` walks every token and returns the count, with `Allocated` expected to read `-`. + +## Checklist + +- [ ] Class in `bench/Broadside.Benchmarks/`, `[MemoryDiagnoser]`, no job attributes +- [ ] Inputs loaded in `[GlobalSetup]`; body is only the hot path; result returned +- [ ] `--job dry` exits 0; `--job short` numbers quoted in the PR +- [ ] `Allocated` reads `-` on hot paths; `GC.GetAllocatedBytesForCurrentThread` test added next to the feature +- [ ] Names stable; any rename called out in the PR body diff --git a/.claude/skills/adding-a-filter/SKILL.md b/.claude/skills/adding-a-filter/SKILL.md new file mode 100644 index 00000000..421ef9d9 --- /dev/null +++ b/.claude/skills/adding-a-filter/SKILL.md @@ -0,0 +1,58 @@ +--- +name: adding-a-filter +description: "Use when implementing a stream filter or image codec (FlateDecode, LZWDecode, ASCII85Decode, RunLengthDecode, DCTDecode, CCITTFaxDecode, JBIG2Decode, JPXDecode, Crypt, predictors) behind the filter extension point in Broadside.Filters." +--- + +# Adding a filter + +> **The filter contract is defined by issue #18 (Standard filters, plan row 1.8). When it lands, replace the "Contract" section of this skill with the real signatures from `src/Broadside/Filters/` and `src/Broadside/PublicAPI.Unshipped.txt`.** Until then this is a design brief: it says what the contract must provide and what a filter PR must deliver. It does not spell the methods. + +A filter is "a stream encoding named in a stream's `/Filter` entry, and the codec that decodes or encodes it. Image codecs are filters." (`CONTEXT.md`). Filters are an extension point: a public contract in the core with a fully managed default (`CLAUDE.md`, "Hard rules"; ADR 0001). + +## Where it lives + +- Contract and standard filters: namespace `Broadside.Filters` in `src/Broadside/`. Image codecs (DCT, CCITT, JBIG2, JPX; Phase 2B) implement the same contract, in the same namespace or a sub-namespace per codec. +- Tests: `tests/Broadside.Tests/Filters/`, namespace `Broadside.Tests.Filters`, one class per filter. +- Corpus: `tests/Corpus/-stream.pdf` (`flate-stream.pdf`, `lzw-stream.pdf`, `ascii85-stream.pdf`, `asciihex-stream.pdf`, `runlength-stream.pdf`, `filter-chain.pdf`, `png-predictor.pdf` exist); the encoder side of each lives in `tests/Corpus/generate.py` (`lzw_encode`, `ascii85_encode`, `png_up_predict`, ...). +- Benchmarks: `bench/Broadside.Benchmarks/Benchmarks.cs`. Fuzz: `tests/Broadside.Fuzz/FuzzTargets.cs`, target `filter-`. + +## Contract (responsibilities, not signatures) + +An implementation must be able to: + +- name the filter as it appears in `/Filter` (§7.4 Table 6) and its inline-image abbreviation (§8.9.7 Table 92: `/Fl`, `/LZW`, `/A85`, `/AHx`, `/RL`, `/CCF`, `/DCT`); +- decode a stream body given its `/DecodeParms` dictionary (§7.4.1; predictor parameters in §7.4.4.4 Table 10, CCITT in Table 11, JBIG2 in Table 12, DCT in Table 13, JPX in §7.4.9, Crypt in §7.4.10) into a caller-provided or pooled buffer, without per-byte or per-row allocation (codecs are a hot path); +- participate in a chain: the `/Filter` array is applied in order on decode (`filter-chain.pdf` is `[/ASCII85Decode /FlateDecode]`), each stage consuming the previous stage's output; +- repair and record in lenient mode: truncated data, a missing EOD marker, a wrong predictor row length produce a `Diagnostic` and the bytes decoded so far; strict mode throws (ADR 0005); +- for image codecs, deliver samples as a planar or interleaved buffer with a declared colour space and bit depth (plan, Track 2B), including the DCT Adobe-marker CMYK/YCCK and JPX colour-space and SMask-in-data cases; +- encode, for the filters the writer uses (Flate, DCT baseline, PNG predictors; Phase 4A). Decode-only filters say so. + +Registration goes through the options object: `PdfOptions.UseFilter(...)` (plan row 1.12; `Use*` selects an implementation, `CLAUDE.md` "Code conventions") replaces or adds a filter for one engine instance. There is no static registry: a consumer must be able to run two engines with different filter sets in one process, and tests must be able to inject a fake. + +## Managed default + +Every filter the PDF file format depends on ships in the core, written in C#. Allowed dependencies are `System.*` only: Flate uses `System.IO.Compression` (`ZLibStream` or `DeflateStream`); everything else (LZW, ASCII, RunLength, predictors, and in Phase 2B the DCT, CCITT, JBIG2 and JPX decoders) is implemented here. Do not add a NuGet package to save time; stub behind the extension point and open an issue (`CLAUDE.md`, "Do not"). + +## Deliverables of a filter PR + +1. Implementation in `Broadside.Filters`, `sealed`, XML docs on every public member with `ISO 32000-2 §7.4.x` (plus the codec's own reference: ITU-T T.81 for DCT, T.4/T.6 for CCITT, T.88 for JBIG2, ISO/IEC 15444-1 for JPX, cited from `Specs/References/`). +2. `PublicAPI.Unshipped.txt` entries for the new public surface, explained in the PR body. +3. Conformance rows: split `7.4` in `docs/conformance/iso-32000-2.md` to third level (`7.4.2` ASCIIHexDecode ... `7.4.10` Crypt) and mark the ones you implemented (skill `updating-the-conformance-map`). +4. Corpus file(s): one `-stream.pdf` per filter and one per distinctive parameter set (`png-predictor.pdf` covers Predictor 12), generated by `generate.py` (skill `writing-a-corpus-file`). Truncated and EOD-less variants belong in the "Deliberately broken files" table. +5. Unit tests: known-answer vectors from the spec (the LZW example in §7.4.4.2, the ASCII85 `~>` and `z` cases), round trip against the generator's encoder, the broken variants in lenient and strict mode, and the chain. +6. Fuzz target `filter-` over raw stream bodies (skill `adding-a-fuzz-target`). +7. Benchmark `Benchmarks` with `[MemoryDiagnoser]`, `Allocated` at `-` for the decode loop (skill `adding-a-benchmark`). +8. Fuzz smoke and `dotnet test Broadside.Core.slnf` green. + +## Worked example: LZWDecode + +`tests/Corpus/lzw-stream.pdf` holds a content stream encoded by `lzw_encode` in `generate.py` (9–12-bit codes, clear code 256 first, EOD 257 last, `EarlyChange` 1). The decoder lives in `Broadside.Filters`, cites `ISO 32000-2 §7.4.4.2.`, handles `/EarlyChange 0` from `/DecodeParms` (Table 8), and then the TIFF and PNG predictors from §7.4.4.4 run as a second stage shared with Flate. Tests: the Table 7 sequence `45 45 45 45 45 65 45 45 45 66` decodes from `80 0B 60 50 22 0C 0C 85 01` (the known answer `self_test()` in `generate.py` already checks for the encoder); `lzw-stream.pdf` decodes to the bytes `pdftotext` shows (`LZWDecode`); a truncated body yields a diagnostic in lenient mode and throws in strict mode. Fuzz target `filter-lzw`, benchmark `LzwBenchmarks.Decode` over the corpus stream, row `7.4.4` done with those tests named. + +## Checklist + +- [ ] Contract section of this skill replaced with the real signatures once #18 has landed +- [ ] Implementation in `Broadside.Filters`, managed only, `sealed`, clause-cited XML docs +- [ ] Registered through `PdfOptions`, not a static registry +- [ ] Lenient repairs recorded as `Diagnostic`; strict mode throws +- [ ] `PublicAPI.Unshipped.txt`, conformance rows, corpus file(s), unit tests, fuzz target, benchmark +- [ ] No per-byte or per-row allocation (`Allocated` reads `-`) diff --git a/.claude/skills/adding-a-font-program-parser/SKILL.md b/.claude/skills/adding-a-font-program-parser/SKILL.md new file mode 100644 index 00000000..8f4a4522 --- /dev/null +++ b/.claude/skills/adding-a-font-program-parser/SKILL.md @@ -0,0 +1,58 @@ +--- +name: adding-a-font-program-parser +description: "Use when implementing a parser for an embedded or substituted font program format (TrueType, OpenType, CFF/Type 2, Type 1, CID-keyed CFF, Type 3) behind the font program parser extension point in Broadside.Fonts." +--- + +# Adding a font program parser + +> **The font program parser contract is defined by the Phase 2A Fonts track (`docs/plan/README.md`, "Track 2A Fonts"); its issues are not filed yet. When the contract issue lands, replace the "Contract" section of this skill with the real signatures from `src/Broadside/Fonts/` and `src/Broadside/PublicAPI.Unshipped.txt`.** Until then this is a design brief: responsibilities and deliverables, not method names. + +A font program is "the embedded or substituted glyph data in one of the formats PDF allows: TrueType, OpenType, CFF, Type 1, or Type 3 content streams" (`CONTEXT.md`). Font program parsers are extension points with a managed default (ADR 0001); the font resolver (which finds a program for a non-embedded font) is a separate extension point and not covered here. + +## Where it lives + +- Contract and parsers: namespace `Broadside.Fonts` in `src/Broadside/`, one sub-namespace or folder per format (`Fonts/TrueType`, `Fonts/Cff`, `Fonts/Type1`). Standard 14 metrics (AFM) are in the core; their glyphs ship in `src/Broadside.Fonts.Standard14` (ADR 0007). Predefined CMaps ship in `src/Broadside.Fonts.Cmaps`. +- Tests: `tests/Broadside.Tests/Fonts//`, namespace `Broadside.Tests.Fonts`. +- Corpus: `tests/Corpus/text--embedded.pdf`. `text-truetype-embedded.pdf` exists, built by `minimal_truetype()` in `generate.py`; the font is synthesized (`.notdef`, `H`, `I` as rectangles), carries no licence, and every other format follows that pattern. Never embed a real typeface. +- Fuzz: target `font-` over the raw program bytes. Benchmarks: `bench/Broadside.Benchmarks/Benchmarks.cs`. + +## Contract (responsibilities, not signatures) + +A parser for one format must: + +- accept the bytes of a `/FontFile` (Type 1), `/FontFile2` (TrueType) or `/FontFile3` (`/Subtype /Type1C`, `/CIDFontType0C`, `/OpenType`) stream (§9.9 Table 125), using `/Length1 /Length2 /Length3` when present and tolerating their absence or wrong values in lenient mode (ADR 0005), with a `Diagnostic` for every repair; +- expose, for a glyph selected by glyph index, CID or character name as the format allows, its outline as path segments in glyph space with the format's units-per-em or `FontMatrix`, and its advance width; `Pdf`-layer code maps character codes to glyphs through encodings (§9.6.6), CMaps (§9.7.5) and `/CIDToGIDMap` (§9.7.4.2), not the parser; +- expose the mapping tables the font dictionary layer needs: TrueType `cmap` subtables (3,1), (3,0), (1,0) for the §9.6.6.4 lookup rules, `post` glyph names; CFF charset and encoding; Type 1 `/Encoding` and charstring names; CID-keyed CFF `FDSelect`; +- expose the metrics needed when the font dictionary omits them: bounding box, ascent, descent, `hmtx`/`hhea` advances, CFF `nominalWidthX`/`defaultWidthX`; +- parse lazily and allocate nothing per glyph after the tables are located: charstring interpretation (Type 1, Type 2 with hints, `hintmask`, subroutines, `seac`/`endchar` accents, flex) and `glyf` composite resolution run on a hot path (`CLAUDE.md`, "Code conventions"); +- be safe on hostile input: every offset and count is bounds-checked, recursion (composite glyphs, subroutine depth) is capped, and the parser never throws in lenient mode on a malformed program; a program that cannot be parsed at all yields a diagnostic and the glyphs fall back to `.notdef`; +- state which format(s) it handles so the engine can pick a parser from the `/Subtype` of the font file stream and, when that lies, from the program's magic bytes (`OTTO`, `true`, `0x00010000`, `%!PS-AdobeFont`, `0x80` PFB segment header, CFF header `01 00`). + +Registration goes through the options object (`PdfOptions.Use*`, plan row 1.12), per engine instance. No static registry: a consumer substitutes a parser for one engine without affecting another, and tests inject fakes. + +## Managed default + +The core ships parsers for every format a PDF can embed: TrueType (`glyf`, `loca`, `cmap`, `post`, `hmtx`, `head`, `hhea`, `maxp`, composite glyphs), OpenType wrapper (`CFF ` table), CFF with Type 2 charstrings and CID-keyed CFF, Type 1 (PFA/PFB segments, eexec, Type 1 charstrings), Type 3 (content streams, handled by the interpreter rather than a parser). Written in C# with `System.*` only (ADR 0001). The references in `Specs/References/` (OpenType specification, Adobe Type 1 Font Format, CFF and Type 2 Charstring Format) are the sources to cite. + +## Deliverables of a parser PR + +1. Implementation in `Broadside.Fonts.`, `sealed` types, XML docs on every public member citing `ISO 32000-2 §9.9` and the format reference (e.g. "OpenType `glyf` table", "Type 1 Font Format §6.4"). +2. `PublicAPI.Unshipped.txt` entries, explained in the PR body. +3. Conformance rows: `9.9` (Embedded font programs) and the dictionary-level clauses touched (`9.6.3`, `9.7.4`, `9.8`) in `docs/conformance/iso-32000-2.md`, split to third level. +4. Corpus file `text--embedded.pdf` from a synthesized font (skill `writing-a-corpus-file`), plus a broken variant (truncated program, wrong `/Length1`) in the broken-files table. +5. Unit tests: table parsing against the synthesized font, charstring interpretation of each operator, composite and subroutine depth limits, lenient vs strict on the broken variant, and a corpus test that every font in `corpus/` (fetched by `tools/CorpusFetcher`) parses without an exception. +6. Fuzz target `font-` (skill `adding-a-fuzz-target`), seeded from the program extracted out of the corpus file (`qpdf --show-object=7 --raw-stream-data tests/Corpus/text-truetype-embedded.pdf`). +7. Benchmark `Benchmarks` with `[MemoryDiagnoser]`: outline extraction for every glyph, `Allocated` at `-` (skill `adding-a-benchmark`). + +## Worked example: the TrueType parser + +`tests/Corpus/text-truetype-embedded.pdf` embeds a font with tables `head hhea maxp OS/2 hmtx cmap(3,1 format 4) loca glyf name post` and the glyph set `.notdef`, `H` (code 72), `I` (code 73), 1000 units per em. The parser reads the table directory, locates the tables by tag, resolves `loca` by `indexToLocFormat`, and returns two rectangles for `H` and `I` with the widths `hmtx` stores; `cmap` (3,1) maps 0x48 and 0x49 to glyphs 1 and 2. Tests assert exactly that, since the generator defines every value. A `font-truetype` fuzz target parses the whole program and walks every glyph; `TrueTypeBenchmarks.Outlines` extracts every glyph's outline and returns the segment count. Rows `9.9` and `9.6.3` become `partial` or `done` with those tests named. + +## Checklist + +- [ ] Contract section of this skill replaced with the real signatures once the 2A contract issue has landed +- [ ] Parser in `Broadside.Fonts`, managed only, `sealed`, clause-cited XML docs with the format reference +- [ ] Registered through `PdfOptions`, not a static registry +- [ ] Bounds-checked, recursion-capped, lenient on malformed programs with a `Diagnostic` +- [ ] `PublicAPI.Unshipped.txt`, conformance rows, corpus file from a synthesized font, unit tests, fuzz target, benchmark +- [ ] No per-glyph allocation after table lookup (`Allocated` reads `-`) diff --git a/.claude/skills/adding-a-fuzz-target/SKILL.md b/.claude/skills/adding-a-fuzz-target/SKILL.md new file mode 100644 index 00000000..54bb7f74 --- /dev/null +++ b/.claude/skills/adding-a-fuzz-target/SKILL.md @@ -0,0 +1,77 @@ +--- +name: adding-a-fuzz-target +description: "Use in the same PR that adds or changes any parser or codec (lexer, object parser, xref reader, filters, font program parsers, image decoders, CMaps, content interpreter): register a SharpFuzz target in tests/Broadside.Fuzz and run the smoke mode." +--- + +# Adding a fuzz target + +`CLAUDE.md` ("Code conventions") requires a fuzz target for every parser and codec. The harness is `tests/Broadside.Fuzz`, a console application built on SharpFuzz; its README documents the modes and how to run libFuzzer or AFL. The rule is simple: the PR that adds the parser adds the target. + +## How targets are registered + +`tests/Broadside.Fuzz/FuzzTargets.cs` holds a dictionary from a stable kebab-case name to a `ReadOnlySpanAction` (SharpFuzz's `void (ReadOnlySpan)` delegate): + +```csharp +public static IReadOnlyDictionary All { get; } = new Dictionary(StringComparer.Ordinal) +{ + ["pdf-header"] = PdfHeader, +}; +``` + +`Program.cs` resolves the name with `TryGetTarget` for every mode and prints `All.Keys` for `--list`, so registration is the whole wiring: add a method, add an entry. The project references `src/Broadside` and can call `internal` members (`InternalsVisibleTo` in `src/Directory.Build.props`), links `CorpusLocator.cs` for the seed directory, and must not reference `Broadside.TestSupport`. + +## The contract + +- Input: one `ReadOnlySpan`. The target decides what it is (a whole file, a raw stream body, a font program). +- Call the parser in lenient mode and let everything escape. Any exception that leaves the target is a finding; the harness catches and reports it. Under ADR 0005 lenient reading records a `Diagnostic` instead of throwing, so an exception is a bug by definition. Do not wrap the call in `try`/`catch`. +- Assert only invariants that must hold for every input (decoded length within the declared bound, no token past the end of input), and throw when they do not. +- Keep the target small and deterministic: no file I/O, no randomness, no shared mutable state between calls, because libFuzzer calls it millions of times in one process. +- Cite the clause the target exercises in ``. + +Names: `lexer`, `object-parser`, `xref`, `filter-flate`, `filter-lzw`, `filter-dct`, `font-truetype`, `font-cff`, `cmap`, `content-stream`. One target per parser; a filter with several decode parameters still gets one target that reads the parameters from the input. + +## Seeds + +`--smoke` seeds every target with every file in `tests/Corpus/` (`CorpusLocator.CorpusFiles()`), then mutates them. That is right for whole-file targets. For a target that takes a raw stream body or a font program: + +- the corpus already contains the bytes inside a file (`lzw-stream.pdf`, `text-truetype-embedded.pdf`); the smoke runner still feeds whole files, which is a weak seed for a raw-body target, so the target should tolerate arbitrary bytes and the real seeds go to libFuzzer and AFL in `artifacts/fuzz/seeds/` (extract the stream with `qpdf --show-object=4 --raw-stream-data tests/Corpus/lzw-stream.pdf > artifacts/fuzz/seeds/lzw.bin`); +- say so in `tests/Broadside.Fuzz/README.md` under "Adding a target", step 4. + +## Modes + +```sh +dotnet run -c Release --project tests/Broadside.Fuzz -- --list # target names +dotnet run -c Release --project tests/Broadside.Fuzz -- --smoke pdf-header 60 # corpus + mutations for 60 s, random seed (what CI runs) +dotnet run -c Release --project tests/Broadside.Fuzz -- --smoke pdf-header 5 12345 # fixed seed to replay a run +dotnet run -c Release --project tests/Broadside.Fuzz -- --run pdf-header # one input once; replays a finding +``` + +Smoke output ends with `no failures` and exit 0; a finding is written to `artifacts/fuzz//` with the `--run` command to replay it, exit 1. `--fuzz` (libFuzzer through the libfuzzer-dotnet driver, target name from the argument or `BROADSIDE_FUZZ_TARGET`) and `--afl` (afl-fuzz) need an instrumented `Broadside.dll` (`sharpfuzz artifacts/bin/Broadside.Fuzz/release/Broadside.dll`) and the fuzzer binary; the README has the per-platform steps. Smoke mode has no coverage feedback: run a real fuzzer for anything that parses before calling the parser done, and the Phase 1 exit gate (#25) is a 24 h run with no findings. + +## Worked example: `pdf-header` + +The only target today, in `FuzzTargets.cs`: + +```csharp +/// Placeholder until the lexer lands (#11): decides whether the input starts with the %PDF- header marker. +/// ISO 32000-2 §7.5.2. +private static void PdfHeader(ReadOnlySpan data) +{ + bool hasHeader = data.StartsWith("%PDF-"u8); + if (hasHeader && data.Length < "%PDF-"u8.Length) + { + throw new InvalidOperationException("StartsWith claimed a header shorter than the marker; the input cannot be both."); + } +} +``` + +It shows the shape: a span in, a call, an invariant that throws. `--smoke pdf-header 5 12345` reports all 30 corpus files passing and roughly 20 million mutated inputs in 5 s with no failures. When the lexer lands, a `lexer` target replaces it: construct the lexer over `data` in lenient mode, loop until end of input, and throw if a token's range lies outside the input; the method and the dictionary entry are the whole change. + +## Checklist + +- [ ] Method `private static void (ReadOnlySpan data)` in `FuzzTargets.cs` with `` citing the clause +- [ ] Registered in `FuzzTargets.All` under a stable kebab-case name +- [ ] Lenient mode, no `try`/`catch`, only always-true invariants asserted +- [ ] Extra seeds documented in `tests/Broadside.Fuzz/README.md` when whole corpus files are not the right input +- [ ] `--smoke 60` run locally: `no failures`, exit 0; output quoted in the PR +- [ ] Same PR as the parser or codec diff --git a/.claude/skills/adding-a-rendering-backend/SKILL.md b/.claude/skills/adding-a-rendering-backend/SKILL.md new file mode 100644 index 00000000..dc48f64a --- /dev/null +++ b/.claude/skills/adding-a-rendering-backend/SKILL.md @@ -0,0 +1,58 @@ +--- +name: adding-a-rendering-backend +description: "Use when implementing a rendering backend (software rasterizer, SkiaSharp, CoreGraphics, Direct2D, Android Canvas, or a new one) that consumes display lists through the backend contract in Broadside.Rendering." +--- + +# Adding a rendering backend + +> **The backend contract is defined by Track 3A Display list (`docs/plan/README.md`, Phase 3; ADR 0006); its issues are not filed yet. When the contract issue lands, replace the "Contract" section of this skill with the real signatures from `src/Broadside/Rendering/` and `src/Broadside/PublicAPI.Unshipped.txt`.** Until then this is a design brief: responsibilities and deliverables, not method names. + +A backend is "a concrete implementation of the rendering surface contract that knows how to draw on one technology" (`CONTEXT.md`). Backends consume display lists; nothing renders from content-stream operators directly (ADR 0006, `CLAUDE.md` "Hard rules"). The software rasterizer is the reference every other backend is measured against. + +## Where it lives + +- Contract: namespace `Broadside.Rendering` in the core package `src/Broadside/` (the plan lists "display list + backend contract" under `Broadside`). Types in `Rendering` carry no `Pdf`/`Cos` prefix (`CLAUDE.md`, "Code conventions"). +- Software rasterizer, ICC engine and PNG encoder: `src/Broadside.Rendering/` (no native dependencies; Track 3B, 3C). +- Each other backend is its own package: `src/Broadside.Rendering.Skia/` (references `Broadside.Rendering` and `SkiaSharp`), `src/Broadside.Rendering.CoreGraphics/`, `src/Broadside.Rendering.Direct2D/` (CsWin32), `src/Broadside.Rendering.Android/`. A backend may depend on its platform library and nothing else (ADR 0001). The CoreGraphics and Android projects only build when their workloads exist (`-p:BroadsideBuildPlatformBackends=true|false`). +- Tests: `tests/Broadside.Rendering.Tests/` (rasterizer, snapshots) and `tests/Broadside.Rendering.Skia.Tests/`; the platform backends get a test project and a CI leg when they exist (`tests/README.md`). + +## Contract (responsibilities, not signatures) + +A backend must: + +- replay a display list (ADR 0006: a struct-based operation buffer with interned resources) onto its surface: paths with fill rules, strokes (joins, caps, dashes, minimum width), clipping (path and text, intersect), decoded images with transforms and resampling, shadings 1–7, tiling patterns, glyph runs (font reference + glyph ids + positions, native glyph rendering where the platform has it with an outline fallback when `ForceOutlines` is set), and the transparency model (§11: isolated and non-isolated groups, knockout, soft masks, the 16 blend modes, constant alpha); +- honour the render options of Track 3A: scale or DPI, rotation, clip rectangle (tiled region rendering), layer selection (annotations and forms are separate replayable lists), rendering intent, anti-aliasing, cancellation and progress; +- be replayable on any thread while nobody mutates the document (the thread-safety contract in `CLAUDE.md`), and keep per-surface resource caches (glyphs, images, shaders) within the deterministic memory budgets the viewer relies on; +- fall back to the software rasterizer for any group or blend it cannot express (plan, Track 3D: "group fallback to 3B where Skia cannot express a blend/knockout") rather than approximate silently, and record a `Diagnostic` when it does; +- allocate nothing per operation, glyph or scanline during replay; buffers are pooled per surface (`CLAUDE.md`, "Code conventions"); +- produce, for the golden-image suite, pixels in the reference format (premultiplied BGRA8 at a fixed DPI) so the perceptual comparison against the rasterizer's snapshots applies (Track 3H). + +Registration goes through the options object (`PdfOptions.Use*`, plan row 1.12) or the package's one fluent configuration call, the same shape as `Broadside.Fonts.Standard14` (ADR 0007). No static registry: two engines in one process may use different backends, and the viewer selects one per surface. + +## Managed default + +The software rasterizer in `src/Broadside.Rendering/` is the default and the oracle: fully managed, `System.*` only, on every platform. Native backends are exempt from the managed rule (ADR 0001) but are never the default and never a dependency of the core. + +## Deliverables of a backend PR + +1. Package `src/Broadside.Rendering./` with `PublicAPI.Shipped.txt`/`Unshipped.txt`, a `Description` in the csproj, and the platform conditioning the existing backend projects use; added to `Broadside.slnx` under `/src/` (and to `Broadside.Core.slnf` only if it builds everywhere). +2. XML docs citing the clauses each operation implements (`ISO 32000-2 §8.5.3` for path painting, `§11.3` for compositing, `§9.3` for text state); the backend contract itself cites ADR 0006. +3. Conformance rows: the backend-affected clauses in §8, §9.3–§9.4, §10 and §11 of `docs/conformance/iso-32000-2.md` with the snapshot tests named; the rows stay `partial` until the golden-image suite passes within threshold. +4. Test project `tests/Broadside.Rendering..Tests/` (xUnit v3, `InternalsVisibleTo` granted by `src/Directory.Build.props`) that renders every corpus page (`tests/Corpus/`) and compares with the rasterizer's Verify snapshots within the perceptual threshold; snapshots live in `Snapshots/` next to the test (`tests/README.md`). +5. A CI leg on the backend's platform (ubuntu, windows or macos matrix entry) that builds and runs that test project. +6. Fuzz: none for a backend (it consumes a trusted display list), but any new decoder the backend introduces gets a target. +7. Benchmark `BackendBenchmarks` with `[MemoryDiagnoser]`: replay of the corpus display lists at a fixed DPI, `Allocated` at `-` (skill `adding-a-benchmark`); these feed the Track 3I regression gate alongside the rasterizer's numbers. + +## Worked example: the Skia backend + +`src/Broadside.Rendering.Skia/Broadside.Rendering.Skia.csproj` already exists with a `ProjectReference` to `Broadside.Rendering` and a `PackageReference` to `SkiaSharp`, and `tests/Broadside.Rendering.Skia.Tests/PackageSmokeTests.cs` proves the wiring. The backend PR replaces `AssemblyMarker` with the surface type that maps display-list paths to `SKPath`, glyph runs to `SKFont`/`SKTextBlob` (outlines when `ForceOutlines`), images to `SKImage` with the sampling the options ask for, shadings to `SKShader`, and groups to `SKCanvas.SaveLayer`; knockout groups and the blend modes Skia lacks fall back to the rasterizer. The test project renders `tests/Corpus/inline-image.pdf` (a 2x2 checkerboard scaled to 100x100 at (72, 600)) and `text-truetype-embedded.pdf` (two block glyphs) and compares them with `tests/Broadside.Rendering.Tests` snapshots. The CI leg runs on all three operating systems because SkiaSharp ships native assets for each. + +## Checklist + +- [ ] Contract section of this skill replaced with the real signatures once the 3A contract issue has landed +- [ ] Backend consumes display lists only; no operator interpretation in the backend +- [ ] Own package with platform conditioning; depends on its platform library and `Broadside.Rendering` only +- [ ] Registered through `PdfOptions` or the package's fluent call, not a static registry +- [ ] Falls back to the software rasterizer for unsupported groups and blends, with a `Diagnostic` +- [ ] `PublicAPI.*.txt`, clause-cited XML docs, conformance rows, snapshot test project, CI leg, benchmark +- [ ] No per-operation allocation during replay (`Allocated` reads `-`) diff --git a/.claude/skills/picking-up-an-issue/SKILL.md b/.claude/skills/picking-up-an-issue/SKILL.md new file mode 100644 index 00000000..cacfdbc2 --- /dev/null +++ b/.claude/skills/picking-up-an-issue/SKILL.md @@ -0,0 +1,127 @@ +--- +name: picking-up-an-issue +description: "Use when starting any unit of work in Broadside: find an unblocked issue in the current milestone, claim it, branch in a worktree, implement, verify, commit, open the PR, and clean up." +--- + +# Picking up an issue + +The flow from `CLAUDE.md` ("Picking up work") and `CONTRIBUTING.md`, made operational. Humans and agents follow the same steps. Pass `--repo michaelstonis/Broadside` to every `gh` call; it then works from any directory. + +## 1. Find an unblocked issue + +The current milestone is the lowest-numbered one that still has open issues. + +```sh +gh api repos/michaelstonis/Broadside/milestones --jq '.[] | "\(.number) \(.title) open=\(.open_issues)"' +gh issue list --repo michaelstonis/Broadside --milestone "Phase 1: COS layer" --search "no:assignee" --state open +``` + +An issue is unblocked when every issue under its `### Blocked by` heading is closed (`none` means no blockers). List the blockers, then check each one: + +```sh +gh issue list --repo michaelstonis/Broadside --milestone "Phase 1: COS layer" --search "no:assignee" --state open \ + --json number,title,body --jq '.[] | "\(.number) \(.title) | blocked by: \(.body | capture("### Blocked by\\n(?[^\\n]*)").b)"' +gh issue view 2 --repo michaelstonis/Broadside --json state --jq .state # CLOSED: the blocker is done +``` + +Take the lowest-numbered unblocked issue unless the caller named one. + +## 2. Claim it + +```sh +gh issue edit --repo michaelstonis/Broadside --add-assignee "@me" --add-label in-progress +``` + +## 3. Worktree and branch + +The branch is `-`, slug from the title in kebab-case: issue 11 "[COS] Lexer" becomes `11-lexer`. + +```sh +git fetch origin +git worktree add ../- -b - origin/main +cd ../- +``` + +When the session already runs inside an isolated worktree (the path contains `.claude/worktrees/`), stay there and only create the branch with `git checkout -b -`, after confirming `git log --oneline -1` matches `git log --oneline -1 origin/main`. + +## 4. Read before writing + +- The issue's `### Spec clauses`, opened from `Specs/` (local, gitignored), never from memory. Example: `pdftotext Specs/ISO_32000-2_sponsored_EC3.pdf - | grep -nE '^7\.2\.[0-9] '` shows that §7.2 is 7.2.1 General, 7.2.2 Representation, 7.2.3 Character set, 7.2.4 Comments, which is not what older editions say. +- The plan row the issue links (`docs/plan/phase-N-issues.md`), the research report for the area in `docs/research/`, and the current conformance rows in `docs/conformance/`. +- The skill for the task type, listed in `.claude/skills/README.md`. + +## 5. Implement and verify + +Every PR carries: code with `ISO 32000-2 §x.y.z` on spec-implementing public members, tests next to the feature, conformance rows (skill `updating-the-conformance-map`), `PublicAPI.Unshipped.txt` entries (the public API analyzer fails the build until they exist), a fuzz target for every parser or codec (skill `adding-a-fuzz-target`), and a benchmark on a hot path (skill `adding-a-benchmark`). Before pushing: + +```sh +dotnet build Broadside.Core.slnf -warnaserror +dotnet test Broadside.Core.slnf +dotnet format Broadside.Core.slnf --verify-no-changes +dotnet run -c Release --project tests/Broadside.Fuzz -- --smoke 60 # if you added a target +dotnet run -c Release --project bench/Broadside.Benchmarks -- --filter '*' --job dry # if you added a benchmark +``` + +`Broadside.slnx` also holds the Android and CoreGraphics backends, which need their workloads; build the full solution with `-p:BroadsideBuildPlatformBackends=false` on a machine without them. + +## 6. Commit + +Conventional Commits with the area as scope, the issue number in the subject, and two trailers at the end: the DCO sign-off `CONTRIBUTING.md` requires and the co-author line. Some sandboxes refuse any command whose text contains `git commit -s` or `.github`, so write the message to a scratch file and pass it with `-F`; the `Signed-off-by` line written by hand is exactly what `-s` appends. + +```sh +cat > /tmp/commit-msg.txt <<'MSG' +feat(cos): lexer over ReadOnlySpan (#11) + +Tokenizes the character set, delimiters, numbers, names, strings and +comments of ISO 32000-2 clause 7.2 without allocating per token. + +Signed-off-by: Your Name +Co-Authored-By: Claude Fable 5.1 +MSG +git add -A && git -c commit.gpgsign=false commit -F /tmp/commit-msg.txt +``` + +## 7. Push and open the PR + +```sh +git push -u origin - +gh pr create --repo michaelstonis/Broadside --title "" --body-file /tmp/pr-body.md +``` + +The body follows `.github/PULL_REQUEST_TEMPLATE.md`: first line `Closes #`; Summary; the Deliverables checklist; Public API changes (what and why, or "none"); Verification with the commands you ran and their output; last line `🤖 Generated with [Claude Code](https://claude.com/claude-code)`. An additive change to `CLAUDE.md` or `CONTEXT.md` states in the body why it is justified. + +## 8. Merge policy + +- Phase 0 and 1: `gh pr checks --repo michaelstonis/Broadside --watch`, then `gh pr merge --repo michaelstonis/Broadside --squash --delete-branch` once green and the checklist is complete. +- Phase 2 onward: `gh pr edit --repo michaelstonis/Broadside --add-reviewer michaelstonis` and stop. Never merge. + +## 9. Rebasing when main moved + +`Broadside.slnx` conflicts whenever two PRs add a project to the same folder. Keep both `` lines. + +```sh +git fetch origin && git rebase origin/main +# resolve Broadside.slnx by keeping both lines, then: +git add Broadside.slnx && GIT_EDITOR=true git rebase --continue +dotnet build Broadside.Core.slnf && git push --force-with-lease +``` + +## 10. Clean up + +```sh +gh issue edit --repo michaelstonis/Broadside --remove-label in-progress # closing via "Closes #n" does not remove labels +git worktree remove ../- && git branch -D - # from the main checkout, after the merge +``` + +## Checklist + +- [ ] Issue is in the current milestone, unassigned, and every blocker is closed +- [ ] Self-assigned, `in-progress` label added +- [ ] Branch `-` from `origin/main` in a worktree +- [ ] Spec clauses read from `Specs/`; plan row, research report and conformance rows read +- [ ] Code, tests, conformance rows, `PublicAPI.Unshipped.txt`, fuzz target and benchmark as the issue requires +- [ ] `dotnet build -warnaserror`, `dotnet test`, `dotnet format --verify-no-changes` clean +- [ ] Conventional Commit with `Signed-off-by` and `Co-Authored-By` trailers +- [ ] PR body starts with `Closes #` and ends with the Claude Code footer +- [ ] Phase 0–1: self-merged when green; Phase 2+: owner review requested, not merged +- [ ] `in-progress` removed, worktree and branch deleted diff --git a/.claude/skills/updating-the-conformance-map/SKILL.md b/.claude/skills/updating-the-conformance-map/SKILL.md new file mode 100644 index 00000000..b209a9bd --- /dev/null +++ b/.claude/skills/updating-the-conformance-map/SKILL.md @@ -0,0 +1,98 @@ +--- +name: updating-the-conformance-map +description: "Use whenever a PR implements, extends or tests a specification clause: find its row in docs/conformance/, set the status, fill the type and test cells in the required format, split to third-level rows, cite the clause in XML docs, and run the checker." +--- + +# Updating the conformance map + +The conformance map is the per-clause record of what Broadside implements (`CONTEXT.md`, "Conformance map"). Whoever touches a clause updates its row in the same PR as the code (`CLAUDE.md`, "Where things are"). CI fails on a `done` row without a test. + +## 1. Find the file and the row + +`docs/conformance/README.md` maps each specification to a file: ISO 32000-2 is `docs/conformance/iso-32000-2.md`, the technical specifications are `iso-ts-3200N.md`, the application notes `pdf20-an00N.md`, and so on. Rows are keyed by clause number without `§`: + +```sh +grep -n '^| 7\.2 ' docs/conformance/iso-32000-2.md +``` + +Today every row is at the second level (`7.2`, `7.3`, ...), all `not started`. + +## 2. Row format + +``` +| Clause | Title | Status | Implementing types | Tests | Notes | +``` + +- **Clause**: the number as the spec prints it (`7.2`, `7.2.3`), no `§`, no trailing dot. +- **Title**: the heading from `Specs/`, read with `pdftotext Specs/ISO_32000-2_sponsored_EC3.pdf - | grep -nE '^7\.2\.[0-9] '`, never from memory. +- **Status**: one of `not started`, `partial`, `done`, `n/a`. `n/a` is for clauses with no implementable content or that `CLAUDE.md` lists as out of scope; say which in Notes. +- **Implementing types**: fully qualified type names, each in backticks, comma-separated: `` `Broadside.Cos.CosLexer`, `Broadside.Cos.CosToken` ``. Leave empty for `not started` and `n/a`. +- **Tests**: fully qualified test identifiers `Namespace.Class.Method`, each in backticks, comma-separated: `` `Broadside.Tests.Objects.LexerTests.Tokenizes_names` ``. For a theory, name the method once. A `done` row needs at least one; give `partial` rows their tests too so the checker's counts mean something. Issue #7 formalizes these two cell formats; use them now. +- **Notes**: for `partial`, what is still missing; for `n/a`, why; otherwise anything a reader needs to find the code (an ADR number, a corpus file name). + +Keep cells on one line; the table has no multi-line cells. + +## 3. When to split a row + +Split a second-level row into its third-level clauses when the sub-clauses differ in status, or when one row would otherwise list several unrelated types and tests. Replace the second-level row with one row per third-level clause in clause order, titles from `Specs/`, each with its own status; sub-clauses you did not touch get `not started`. Do not go to the fourth level unless a clause is so large that a third-level row would again hide the gaps (§7.6.4 algorithms, §12.5.6 annotation subtypes). + +Example for §7.2, which `Specs/` lists as 7.2.1 General, 7.2.2 Representation, 7.2.3 Character set, 7.2.4 Comments: + +``` +| 7.2.1 | General | n/a | | | Introductory text | +| 7.2.2 | Representation | done | `Broadside.Cos.CosLexer` | `Broadside.Tests.Objects.LexerTests.Tokenizes_names` | | +| 7.2.3 | Character set | done | `Broadside.Cos.CosLexer` | `Broadside.Tests.Objects.LexerTests.Tokenizes_names` | | +| 7.2.4 | Comments | not started | | | | +``` + +## 4. Cite the clause in the code + +Every public type and member that implements a spec concept carries the clause in its XML docs, so the row's "Implementing types" cell can be followed back to the code: + +```csharp +/// Tokenizes a PDF file body. +/// ISO 32000-2 §7.2. +public ref struct CosLexer { ... } + +/// Reads one string object, literal or hexadecimal. +/// ISO 32000-2 §7.3.4. +public CosToken ReadString() { ... } +``` + +For the other documents use their own prefix: `ISO/TS 32003 §5`, `PDF 2.0 Application Note 002 §3`, `Well-Tagged PDF 1.0 §4.2`. + +## 5. Run the checker + +`tools/ConformanceCheck` arrives with issue #7. Once it has landed: + +```sh +dotnet run --project tools/ConformanceCheck -- --root . --summary +``` + +It fails on a `done` row without a test and prints counts per status; CI runs it on every PR. Until it lands, check by hand that each row you touched has backticked identifiers in both cells and that every test named exists (`grep -rn 'Tokenizes_names' tests/`). + +## Worked example: marking §7.2 partial + +A lexer PR tokenizes names and numbers but not yet strings or comments. In `docs/conformance/iso-32000-2.md`, the row + +``` +| 7.2 | Lexical conventions | not started | | | | +``` + +becomes + +``` +| 7.2 | Lexical conventions | partial | `Broadside.Cos.CosLexer` | `Broadside.Tests.Objects.LexerTests.Tokenizes_names` | Strings (7.3.4) and comments (7.2.4) pending | +``` + +and `CosLexer` carries `ISO 32000-2 §7.2.`. When the follow-up PR finishes comments, split the row as in section 3 rather than growing the Notes cell. (`CosLexer` and `LexerTests` are illustrative names; the real ones come from issue #11.) + +## Checklist + +- [ ] Every clause the PR touches has a row in the right `docs/conformance/.md` +- [ ] Status is one of the four values; `done` rows name at least one test +- [ ] Types and tests are fully qualified, backticked, comma-separated +- [ ] Split to third-level rows where statuses differ; titles copied from `Specs/` +- [ ] Each implementing public type and member carries `ISO 32000-2 §x.y.z` +- [ ] `dotnet run --project tools/ConformanceCheck -- --root . --summary` passes (once #7 has landed) +- [ ] The PR body lists the clauses as they appear in the map diff --git a/.claude/skills/writing-a-corpus-file/SKILL.md b/.claude/skills/writing-a-corpus-file/SKILL.md new file mode 100644 index 00000000..8e915cc7 --- /dev/null +++ b/.claude/skills/writing-a-corpus-file/SKILL.md @@ -0,0 +1,90 @@ +--- +name: writing-a-corpus-file +description: "Use when a test needs a hand-written minimal PDF that does not exist yet in tests/Corpus/: add a generator to generate.py, regenerate deterministically, verify with qpdf and poppler, and register the file in the README, Corpus.cs and the Verify snapshot." +--- + +# Writing a corpus file + +`tests/Corpus/` holds hand-written PDFs, one feature per file, all emitted by `tests/Corpus/generate.py` (stdlib only, deterministic). A file is as small as it can be while remaining a complete document: catalog, page tree, one page, plus only the objects the feature needs. If a test needs two features combined, that is a new file. + +## 1. How the script defines a file + +`FILES` at the bottom of `generate.py` maps a file name to a zero-argument function that returns the bytes: + +```python +FILES = { + "empty-page.pdf": gen_empty_page, + "text-truetype-embedded.pdf": gen_text_truetype_embedded, + ... +} +``` + +Building blocks, in the order the script defines them: + +- Serialization (§7.3, §7.5): `header(version, binary)`, `obj(num, body)`, `stream(dict_entries, data, length=None)`, `catalog()`, `pages(kids)`, `page(parent, mediabox, contents, font, resources, extra)`, `HELVETICA`, `text_content(text)`, `xref_table(...)`. +- `simple_file(objects, version, binary, trailer_extra)`: a list of `(num, body)` pairs becomes a file with a classic cross-reference table and a `/Size /Root` trailer; offsets are computed for you. `text_file(content)` is the one-Helvetica-line shortcut. +- `File`: for anything the simple path cannot express. `add(num, body)` records the offset, `raw(bytes)` appends verbatim, `pos()` is the current offset, `finish_classic(trailer)` writes the table. `gen_xref_stream`, `gen_object_stream`, `gen_incremental_update` and `gen_hybrid_xref` show cross-reference streams (`xref_stream_rows`), object streams (`object_stream`) and update sections. +- Filters (§7.4): `flate`, `lzw_encode`, `ascii85_encode`, `asciihex_encode`, `runlength_encode`, `png_up_predict`. +- Encryption (§7.6): `encrypted_file(name, version, label, encrypt_dict, encrypt_stream)` with `gen_encrypted_legacy` (R2–R4) and `gen_encrypted_aes_256` (R6); primitives `rc4`, `aes_cbc_encrypt`, `legacy_file_key`, `legacy_o_entry`, `legacy_u_entry`, `object_key`, `hash_2b`. +- Determinism: every value the spec wants random comes from `file_id(name)` or `fixed_bytes(label, n)`. Never call `os.urandom` or `random`. +- Font programs: `minimal_truetype()` synthesizes a licence-free TrueType font with `.notdef`, `H`, `I` as rectangles. Follow that pattern for other formats; never embed a real typeface. +- `self_test()` runs known-answer tests for the codecs before anything is written; add one when you add a codec. + +## 2. Naming + +Kebab-case, feature first, variant second: `flate-stream.pdf`, `encrypted-aes-256.pdf`, `text-truetype-embedded.pdf`. Deliberately broken files are named by the defect: `missing-endobj.pdf`. The README table and `Corpus.cs` use the same name. + +## 3. Steps + +1. Write `gen_()` next to its neighbours in `generate.py` and register it in `FILES`. Cite the clauses in the docstring. +2. Regenerate into a scratch directory and diff. Only your new file may differ ("Only in"); any other difference means you changed shared code and must explain it in the PR: + + ```sh + python3 -I tests/Corpus/generate.py /tmp/corpus-regen + diff -rq /tmp/corpus-regen tests/Corpus --exclude=README.md --exclude=generate.py + python3 -I tests/Corpus/generate.py # then write in place + ``` + +3. Verify with external tools and record what they print: + + ```sh + qpdf --check tests/Corpus/.pdf # exit 0, "No syntax or stream encoding errors found" + pdfinfo tests/Corpus/.pdf # one Letter page, no syntax message + pdftotext tests/Corpus/.pdf - # the text the content stream draws + pdffonts tests/Corpus/.pdf # for font files: type, encoding, emb=yes + ``` + + A broken file is verified the other way round: record exactly which complaint qpdf and poppler produce. +4. Add a row to the right table in `tests/Corpus/README.md` (well-formed: File, Feature, Clauses, How to verify, Result; broken: File, Defect, Clauses, What the tools report, Lenient mode). +5. Add the name to `WellFormed` or `Malformed` in `tests/Broadside.TestSupport/Corpus.cs`, in the same position as the README row. +6. Refresh the Verify snapshot. `CorpusSmokeTests.Corpus_file_names_match_snapshot` fails once, writes a `.received.txt`, and you accept it: + + ```sh + dotnet test tests/Broadside.Tests + mv tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.received.txt \ + tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt + dotnet test tests/Broadside.Tests # green: File_lists_match_the_corpus_directory and the snapshot agree + ``` + +7. Commit the PDF, `generate.py`, the README, `Corpus.cs` and the snapshot together, and update the conformance rows for the clauses the file exercises. + +## Worked example: `text-type1-embedded.pdf` + +Goal: one line of text in an embedded Type 1 font, the `/FontFile` counterpart of `text-truetype-embedded.pdf` (§9.6.2, §9.8.2, §9.9 Table 125). + +1. Add `minimal_type1()` next to `minimal_truetype()`: a cleartext portion (`%!PS-AdobeFont-1.0`, `/FontName /BroadsideMinimal`, `/Encoding` mapping codes 72 and 73 to `/H` and `/I`, `/FontMatrix [0.001 0 0 0.001 0 0]`), an eexec-encrypted private portion with Type 1 charstrings for `.notdef`, `H` and `I` drawn as rectangles with `hsbw`, `rlineto`, `closepath`, `endchar`, and the 512 zeros trailer. The eexec and charstring ciphers (r = 55665 and 4330) come from the Type 1 Font Format specification, not ISO 32000-2; implement them in the script with a known-answer check in `self_test()`. Return the three section lengths too; `/Length1 /Length2 /Length3` need them. +2. `gen_text_type1_embedded()` mirrors `gen_text_truetype_embedded()`: objects 1–4 as there; object 5 is `/Subtype /Type1 /BaseFont /BroadsideMinimal /FirstChar 72 /LastChar 73 /Widths [...] /FontDescriptor 6 0 R`; object 6 the descriptor with `/FontFile 7 0 R`; object 7 `stream(b"/Length1 %d /Length2 %d /Length3 %d" % lengths, font)`. Use `binary=True` because the eexec portion is binary. +3. Register `"text-type1-embedded.pdf": gen_text_type1_embedded` after the TrueType entry. +4. Expected verification: `qpdf --check` clean; `pdftotext` prints `HI`; `pdffonts` shows `Type 1 WinAnsi emb=yes`; `pdftoppm` renders two block glyphs. Record those in the README row with clauses `9.6.2, 9.8.2, 9.9 Table 125`. +5. Insert the name after `text-truetype-embedded.pdf` in `Corpus.cs`, refresh the snapshot, and update the §9.9 conformance row if the PR also implements the reader. + +## Checklist + +- [ ] `gen_()` registered in `FILES`; docstring cites the clauses +- [ ] No randomness: file identifiers and keys come from `file_id` / `fixed_bytes` +- [ ] Scratch regeneration diffs only in the new file; then regenerated in place +- [ ] `qpdf --check`, `pdfinfo`, `pdftotext` (and `pdffonts`, `pdftoppm` where relevant) run and recorded +- [ ] Row added to `tests/Corpus/README.md` +- [ ] Name added to `Corpus.cs` (`WellFormed` or `Malformed`) +- [ ] Verify snapshot refreshed; `dotnet test tests/Broadside.Tests` green +- [ ] Conformance rows updated for the clauses the file exercises diff --git a/CLAUDE.md b/CLAUDE.md index a254e575..552d968f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -17,6 +17,17 @@ Broadside is a fully managed .NET PDF library (read, write, edit, render) with v 4. Open a PR that references the issue, updates the conformance map, updates `PublicAPI.Unshipped.txt`, and adds tests. CI must be green. 5. Phase 0 and 1: self-merge when green. Phase 2 onward: request review from the owner. +### Skills + +`.claude/skills/` holds one skill per recurring task type (index in `.claude/skills/README.md`). Invoke the matching skill before starting that kind of task: + +- `picking-up-an-issue`: the flow above, step by step, with the exact commands. +- `updating-the-conformance-map`: row and cell formats, third-level splits, clause citations, the checker. +- `writing-a-corpus-file`: adding a file to `tests/Corpus/` through `generate.py`, verifying it, registering it. +- `adding-a-benchmark`: `[MemoryDiagnoser]` conventions, zero-allocation proof, run modes, the regression gate. +- `adding-a-fuzz-target`: registering a target in `tests/Broadside.Fuzz`, seeds, smoke mode. +- `adding-a-filter`, `adding-a-font-program-parser`, `adding-a-rendering-backend`: design briefs for the three extension points; their contract sections are replaced with real signatures when the defining issues land. + ## Hard rules - **Dependencies.** The core package and `Broadside.Rendering` depend only on packages Microsoft ships with no native component (BCL, `System.*`, `Microsoft.Extensions.*` abstractions). Nothing else, ever. Backends other than the software rasterizer may depend on their platform library and nothing else. See ADR 0001. From 55e972a89ab3f441a579bf23138d58877167b9f6 Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:02:16 -0500 Subject: [PATCH 2/2] docs(skills): point at the re-sliced Phase 1 and 2 tickets Phase 1 issues 11-25 were superseded by vertical slices under #33. Filter contract is now #38, font program contract #50, COS parser #36. Co-Authored-By: Claude Opus 5.5 --- .claude/skills/README.md | 4 ++-- .claude/skills/adding-a-filter/SKILL.md | 4 ++-- .claude/skills/adding-a-font-program-parser/SKILL.md | 2 +- .claude/skills/adding-a-fuzz-target/SKILL.md | 2 +- .claude/skills/picking-up-an-issue/SKILL.md | 2 +- .claude/skills/updating-the-conformance-map/SKILL.md | 2 +- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.claude/skills/README.md b/.claude/skills/README.md index 87e78809..935cc089 100644 --- a/.claude/skills/README.md +++ b/.claude/skills/README.md @@ -9,8 +9,8 @@ Each directory holds a `SKILL.md`: YAML frontmatter (`name`, `description`) foll | [`writing-a-corpus-file`](writing-a-corpus-file/SKILL.md) | A test needs a minimal PDF that `tests/Corpus/` does not have: `generate.py`, verification, README, `Corpus.cs`, snapshot. | | [`adding-a-benchmark`](adding-a-benchmark/SKILL.md) | A PR touches a hot path: `[MemoryDiagnoser]` class, zero-allocation proof, dry/short/full runs, the regression gate. | | [`adding-a-fuzz-target`](adding-a-fuzz-target/SKILL.md) | A PR adds or changes a parser or codec: register a SharpFuzz target, seeds, smoke mode. | -| [`adding-a-filter`](adding-a-filter/SKILL.md) | Implementing a stream filter or image codec behind the filter extension point (design brief until #18 lands). | -| [`adding-a-font-program-parser`](adding-a-font-program-parser/SKILL.md) | Implementing a TrueType, CFF, Type 1 or OpenType parser behind the font program extension point (design brief until Phase 2A lands). | +| [`adding-a-filter`](adding-a-filter/SKILL.md) | Implementing a stream filter or image codec behind the filter extension point (design brief until #38 lands). | +| [`adding-a-font-program-parser`](adding-a-font-program-parser/SKILL.md) | Implementing a TrueType, CFF, Type 1 or OpenType parser behind the font program extension point (design brief until #50 lands). | | [`adding-a-rendering-backend`](adding-a-rendering-backend/SKILL.md) | Implementing a backend that consumes display lists (design brief until Phase 3A lands). | Skills whose extension point does not exist in code yet say so at the top and must have their contract section replaced with the real signatures in the PR that defines the contract. diff --git a/.claude/skills/adding-a-filter/SKILL.md b/.claude/skills/adding-a-filter/SKILL.md index 421ef9d9..22b37049 100644 --- a/.claude/skills/adding-a-filter/SKILL.md +++ b/.claude/skills/adding-a-filter/SKILL.md @@ -5,7 +5,7 @@ description: "Use when implementing a stream filter or image codec (FlateDecode, # Adding a filter -> **The filter contract is defined by issue #18 (Standard filters, plan row 1.8). When it lands, replace the "Contract" section of this skill with the real signatures from `src/Broadside/Filters/` and `src/Broadside/PublicAPI.Unshipped.txt`.** Until then this is a design brief: it says what the contract must provide and what a filter PR must deliver. It does not spell the methods. +> **The filter contract is defined by issue #38 (Decode streams through filters). When it lands, replace the "Contract" section of this skill with the real signatures from `src/Broadside/Filters/` and `src/Broadside/PublicAPI.Unshipped.txt`.** Until then this is a design brief: it says what the contract must provide and what a filter PR must deliver. It does not spell the methods. A filter is "a stream encoding named in a stream's `/Filter` entry, and the codec that decodes or encodes it. Image codecs are filters." (`CONTEXT.md`). Filters are an extension point: a public contract in the core with a fully managed default (`CLAUDE.md`, "Hard rules"; ADR 0001). @@ -50,7 +50,7 @@ Every filter the PDF file format depends on ships in the core, written in C#. Al ## Checklist -- [ ] Contract section of this skill replaced with the real signatures once #18 has landed +- [ ] Contract section of this skill replaced with the real signatures once #38 has landed - [ ] Implementation in `Broadside.Filters`, managed only, `sealed`, clause-cited XML docs - [ ] Registered through `PdfOptions`, not a static registry - [ ] Lenient repairs recorded as `Diagnostic`; strict mode throws diff --git a/.claude/skills/adding-a-font-program-parser/SKILL.md b/.claude/skills/adding-a-font-program-parser/SKILL.md index 8f4a4522..3901590e 100644 --- a/.claude/skills/adding-a-font-program-parser/SKILL.md +++ b/.claude/skills/adding-a-font-program-parser/SKILL.md @@ -5,7 +5,7 @@ description: "Use when implementing a parser for an embedded or substituted font # Adding a font program parser -> **The font program parser contract is defined by the Phase 2A Fonts track (`docs/plan/README.md`, "Track 2A Fonts"); its issues are not filed yet. When the contract issue lands, replace the "Contract" section of this skill with the real signatures from `src/Broadside/Fonts/` and `src/Broadside/PublicAPI.Unshipped.txt`.** Until then this is a design brief: responsibilities and deliverables, not method names. +> **The font program parser contract is defined by issue #50 (Embedded TrueType glyph outlines), the first Phase 2A Fonts ticket. When it lands, replace the "Contract" section of this skill with the real signatures from `src/Broadside/Fonts/` and `src/Broadside/PublicAPI.Unshipped.txt`.** Until then this is a design brief: responsibilities and deliverables, not method names. A font program is "the embedded or substituted glyph data in one of the formats PDF allows: TrueType, OpenType, CFF, Type 1, or Type 3 content streams" (`CONTEXT.md`). Font program parsers are extension points with a managed default (ADR 0001); the font resolver (which finds a program for a non-embedded font) is a separate extension point and not covered here. diff --git a/.claude/skills/adding-a-fuzz-target/SKILL.md b/.claude/skills/adding-a-fuzz-target/SKILL.md index 54bb7f74..55746117 100644 --- a/.claude/skills/adding-a-fuzz-target/SKILL.md +++ b/.claude/skills/adding-a-fuzz-target/SKILL.md @@ -53,7 +53,7 @@ Smoke output ends with `no failures` and exit 0; a finding is written to `artifa The only target today, in `FuzzTargets.cs`: ```csharp -/// Placeholder until the lexer lands (#11): decides whether the input starts with the %PDF- header marker. +/// Placeholder until the COS parser lands (#36): decides whether the input starts with the %PDF- header marker. /// ISO 32000-2 §7.5.2. private static void PdfHeader(ReadOnlySpan data) { diff --git a/.claude/skills/picking-up-an-issue/SKILL.md b/.claude/skills/picking-up-an-issue/SKILL.md index cacfdbc2..dc637546 100644 --- a/.claude/skills/picking-up-an-issue/SKILL.md +++ b/.claude/skills/picking-up-an-issue/SKILL.md @@ -70,7 +70,7 @@ Conventional Commits with the area as scope, the issue number in the subject, an ```sh cat > /tmp/commit-msg.txt <<'MSG' -feat(cos): lexer over ReadOnlySpan (#11) +feat(cos): parse COS objects from bytes (#36) Tokenizes the character set, delimiters, numbers, names, strings and comments of ISO 32000-2 clause 7.2 without allocating per token. diff --git a/.claude/skills/updating-the-conformance-map/SKILL.md b/.claude/skills/updating-the-conformance-map/SKILL.md index b209a9bd..5c7d20ab 100644 --- a/.claude/skills/updating-the-conformance-map/SKILL.md +++ b/.claude/skills/updating-the-conformance-map/SKILL.md @@ -85,7 +85,7 @@ becomes | 7.2 | Lexical conventions | partial | `Broadside.Cos.CosLexer` | `Broadside.Tests.Objects.LexerTests.Tokenizes_names` | Strings (7.3.4) and comments (7.2.4) pending | ``` -and `CosLexer` carries `ISO 32000-2 §7.2.`. When the follow-up PR finishes comments, split the row as in section 3 rather than growing the Notes cell. (`CosLexer` and `LexerTests` are illustrative names; the real ones come from issue #11.) +and `CosLexer` carries `ISO 32000-2 §7.2.`. When the follow-up PR finishes comments, split the row as in section 3 rather than growing the Notes cell. (`CosLexer` and `LexerTests` are illustrative names; the real ones come from issue #36.) ## Checklist