Repository Public
1<!--2ORIX Docs3File: docs/research/technology-evaluation.md4Author: Simon-Pierre Boucher5Contact: contact@spboucher.ai6-->7# Technology evaluation89Status: research input for v1.0. Access date for every URL in this document: 2026-11-21.1011This document records, for each technology decision, what was evaluated, the options, an assessment, and the decision with its rationale and risks. Decisions marked "architect" were taken before this research; they are documented and challenged here, not re-opened silently.1213## How to read the evidence labels1415| Label | Meaning |16|---|---|17| **SDK** | Read in the headers or `.swiftinterface` files of the macOS 27.2 SDK installed on the build machine (`MacOSX27.2.sdk`). |18| **Probe** | Observed by running a small throw-away program on the build machine (macOS 27.0, build 26A5425a). A probe is one observation on one machine and one OS build, not a guarantee. Probe sources were kept outside the repository and are not part of the project. |19| **Web** | Read on the vendor's or project's own page or repository on 2026-11-21. |20| **Not verified** | Stated from general knowledge or from a secondary source; must be checked before anything depends on it. |2122Assessment tables use: ++ strong, + adequate, 0 neutral or unknown, − weak, −− blocking. "n/a" means the criterion does not apply.2324## 0. Environment2526| Item | Value | Evidence |27|---|---|---|28| Operating system | macOS 27.0 (26A5425a) | `sw_vers` |29| Machine | Apple M5 Max, 18 cores, 48 GB | `sysctl` (`hw.ncpu` 18, `hw.memsize` 51 539 607 552) |30| Xcode | 27.2 (27B52) | `xcodebuild -version` |31| Swift | 6.4.2 (swiftlang-6.4.2.1.9), target `arm64-apple-macosx27.0.0` | `swift --version` |32| macOS SDK | 27.2 (`MacOSX27.2.sdk`) | `xcrun --sdk macosx --show-sdk-version` with `DEVELOPER_DIR` pointing at Xcode |33| Deployment target | macOS 15 (`platforms: [.macOS(.v15)]`) | `Packages/ORIXDocsKit/Package.swift` |34| Signing identity | `Developer ID Application: Simon-Pierre Boucher (3YM54G49SN)` present | `security find-identity -v -p codesigning` (hash not recorded) |35| Notarization | Existing `notarytool` keychain profile | Stated in the brief; **not verified** (not queried, to avoid touching credentials) |36| Microsoft Word | 16.115.1 | `Info.plist` of `/Applications/Microsoft Word.app` |37| LibreOffice | 26.8.2.2 (`soffice`) | `soffice --version` |38| Apple Pages | Present as `Pages Creator Studio.app` | `/Applications` listing; version not read |39| pandoc | 3.9.0.2 (upstream latest release is 3.14, 2026-11-12) | `pandoc --version`; GitHub API |40| textutil | `/usr/bin/textutil` | `which` |41| pdffonts, pdftotext | `/opt/homebrew/bin` (Poppler) | `which` |42| veraPDF, qpdf | **Not installed** | `which` |4344Two environment facts matter later:4546* `xcrun` without `DEVELOPER_DIR` resolves to `/Library/Developer/CommandLineTools` on this machine and fails to find the macOS SDK (`xcodebuild: error: SDK ".../CommandLineTools/SDKs/MacOSX.sdk" cannot be located`), although `xcode-select -p` reports Xcode. Build scripts should export `DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer`.47* No PDF/A or PDF/UA validator is installed. Section 8 depends on one.4849The architecture this document evaluates is the one in `docs/architecture/overview.md`: a Swift package (`ORIXDocsKit`) of engines that do not import SwiftUI (`DocModel`, `DocContainer`, `DocDOCX`, `DocFormats`, `DocMath`, `DocReferences`, `DocLayout`, `DocReview`, `DocAudit`, `DocTemplates`, `DocAutomation`, and the `orixdocs` executable), with one third-party dependency (SwiftMath) and no network access in the package. At the time of writing `DocModel` and `DocContainer` contain code; the other targets are placeholders.5051---5253## 1. Text layout and editing5455### What was evaluated5657Which Apple text stack can drive a paginated word processor: multi-page and multi-column flow, footnotes at page bottoms, tables that split across pages with repeated header rows, widow/orphan and keep-with-next control, floating objects with wrap, and one layout shared by the screen and the PDF.5859### Options60611. **TextKit 2** — `NSTextLayoutManager`, `NSTextContentStorage`, `NSTextLayoutFragment`, viewport-based layout, used through `NSTextView` or a custom view.622. **TextKit 1** — `NSLayoutManager` with an array of `NSTextContainer`s, `NSTextTable`, `NSTextView` per container.633. **Core Text** — `CTTypesetter`, `CTLine`, `CTRun`, `CTRunDelegate`, with a custom pagination engine and a custom `NSView` that implements `NSTextInputClient` (architect's decision).6465### Findings6667**TextKit 2 has one text container per layout manager.** In the macOS 27.2 SDK, `NSTextLayoutManager` exposes `@property (nullable, strong, readwrite) NSTextContainer *textContainer;` (singular) and `usageBoundsForTextContainer`; there is no public `addTextContainer:` (**SDK**; a probe confirmed the instance does not respond to `addTextContainer:`). The only supported multiplicity is several layout managers on one content storage, which duplicates the text into each view rather than flowing it from one page to the next. An Apple Frameworks Engineer answered the question "Page-based layouts with TextKit 2?" in June 2021 with "This functionality is not available in macOS Monterey Beta 1 … we are actively investigating"; the thread shows no later Apple reply (**Web**: https://developer.apple.com/forums/thread/682251). The WWDC 2026 TextKit session ("2027 releases") adds rendering surfaces, public `NSTextViewportLayoutControllerDelegate` conformance on `NSTextView`/`UITextView`, and text-attachment view-provider reuse; it does not mention multiple containers, pagination, tables or printing (**Web**: https://developer.apple.com/videos/play/wwdc2026/370/; the matching additions are visible in `NSTextView.h` and `NSTextLayoutManager.h`, **SDK**).6869**TextKit 2 is viewport-driven.** Layout is computed for the visible region and estimated elsewhere. A paginating word processor needs exact geometry for the whole document (page count, page of a cross-reference target, "page X of Y"), which works against that design. This is an architectural observation from the API shape, not a measured result.7071**TextKit 1 paginates, with limits.** `NSLayoutManager` accepts many `NSTextContainer`s and is how page layout was done historically. It is not deprecated as a class in the 27.2 SDK (only individual old glyph methods and `containerSize` are) (**SDK**). It offers no footnote placement, no repeated table header rows, no keep-with-next or widow/orphan control, and `NSTextTable` has no API for splitting a row across pages; these would have to be built on top by intercepting line-fragment generation. `NSTextView` drops from TextKit 2 to TextKit 1 permanently as soon as `layoutManager` is accessed (**Probe**: `textLayoutManager` became `nil` after reading `layoutManager`).7273**`NSTextTable` and TextKit 2 on macOS 27.** In a probe, an `NSTextView(usingTextLayoutManager: true)` that received an attributed string containing `NSTextTableBlock` paragraphs kept its `textLayoutManager` after layout. The 27.2 SDK also adds `CGRectEdge`-based accessors to `NSTextBlock` (`setWidth:type:forLayer:rectEdge:`, `setBorderColor:rectEdge:`, `API_AVAILABLE(macos(27.0))`) and annotates the table classes for iOS. This suggests that the long-standing automatic fallback to TextKit 1 for tables no longer happens on macOS 27. The probe was off-screen (no window), and it says nothing about macOS 15–26; treat it as **not verified** for shipping purposes. It does not change the pagination conclusion.7475**Core Text gives line-level control and nothing above it.** `CTTypesetterSuggestLineBreak` / `CTTypesetterCreateLine` return one line at a time for a width the caller chooses, so the caller decides where each line goes (which column, which page, around which float). `CTRunDelegate` reserves space for inline objects (the model's U+FFFC runs). Everything else is the application's job.7677### Assessment7879| Criterion | TextKit 2 | TextKit 1 | Core Text + own engine |80|---|---|---|---|81| Functionality for pagination | −− single container; no footnotes, table splitting, keeps | − multi-container only; the rest must be built | ++ whatever is implemented; nothing is free |82| Editing features for free (IME, selection, spelling, accessibility, Writing Tools) | ++ | ++ | −− all by hand |83| Reliability | + (Apple-maintained) | + (mature) | 0 depends entirely on own tests |84| Performance on long documents | + viewport layout | 0 full layout | 0 own incremental layout required |85| Same layout for screen and PDF | − printing path differs | + | ++ one renderer draws into any `CGContext` |86| License | Apple SDK | Apple SDK | Apple SDK |87| Maintenance | Apple | Apple, in maintenance mode (**not verified** as an official statement) | Own team, permanent |88| Security | n/a | n/a | Own code parses nothing external at this layer |89| Apple silicon | ++ | ++ | ++ |90| Notarization | ++ | ++ | ++ |91| Offline | ++ | ++ | ++ |9293### Decision (architect) and rationale9495Core Text typesetter with a custom pagination engine in `DocLayout`, and a custom `NSView` implementing `NSTextInputClient`. TextKit 2 stays in use for auxiliary text fields (comment editors, dialogs, search fields).9697The research supports the decision on its central point: as of the macOS 27.2 SDK, TextKit 2 still cannot flow text through a sequence of pages, and neither TextKit generation offers footnote placement, row splitting with repeated headers, or keep rules. A word processor built on either would have to bypass the framework for exactly the features that define the product.9899### Costs of the decision (must be budgeted, none is optional)100101| Area | What `NSTextView` provides and the custom view must implement |102|---|---|103| Input methods | Full `NSTextInputClient`: `insertText(_:replacementRange:)`, `setMarkedText(_:selectedRange:replacementRange:)`, `unmarkText()`, `markedRange()`, `selectedRange()`, `attributedSubstring(forProposedRange:actualRange:)`, `firstRect(forCharacterRange:actualRange:)`, `characterIndex(for:)`, `validAttributesForMarkedText()`, plus the newer optional members (`unionRectInVisibleSelectedRange`, `documentVisibleRect`, macOS 14; `supportsAdaptiveImageGlyph`, macOS 15) (**SDK**). CJK composition, dead keys, the press-and-hold accent popup, emoji picker and dictation all go through this protocol. The model's UTF-16 offsets match the protocol's `NSRange` convention, which removes one class of bugs. |104| Key bindings | Route `keyDown` through `interpretKeyEvents` / `inputContext.handleEvent` and implement the `NSStandardKeyBindingResponding` selectors (movement, selection extension, deletion by word/line/paragraph, transposition, Emacs-style bindings, user `DefaultKeyBinding.dict`). |105| Selection | Caret geometry and blinking, bidirectional text carets, word/line/paragraph selection, drag selection across pages and table cells, autoscroll, drag and drop of text. |106| Spell and grammar checking | `NSSpellChecker` requests, underline drawing, contextual menu, panels, autocorrection, text replacement, smart quotes/dashes (section 11). |107| Accessibility | `NSAccessibility` text protocols (role `textArea`; value, selected range, range for position, string and frame for range, line for index, insertion point line number, attributed string for range), plus announcements and a document structure for tables and headings. VoiceOver quality depends on this entirely. |108| System services | Services menu (`validRequestor(forSendType:returnType:)`), Look Up (`showDefinition(for:at:)` or `NSTextInputClient` quick-look path), Find (`NSTextFinderClient`), Share, Writing Tools (the `NSTextView` properties `writingToolsBehavior`, `isWritingToolsActive` are not inherited; a custom view needs `NSWritingToolsCoordinator`, **not verified** for effort), inline predictions, Touch Bar, AutoFill. |109| Text rendering details | Font fallback and cascade lists, emoji, variable fonts, ligatures, tab stops, justification, hanging punctuation, vertical metrics consistency between runs. Core Text does the shaping; line placement is the engine's. |110| Undo | Coalescing of typing, integration with `NSDocument`'s `UndoManager` (the value-type model makes snapshots cheap, see `overview.md`). |111112### Risks and open questions113114* **Largest schedule risk in the project.** The editing surface, not the pagination engine, is where custom text views usually fall short of `NSTextView`. A degraded IME or VoiceOver experience would contradict the "native" positioning. Recommendation: write a conformance checklist from the table above and test with at least a Japanese and a Chinese input method, dictation, and VoiceOver before any external build.115* **Accessibility is a release criterion, not a later improvement.** Without it the editor is unusable with VoiceOver; competitors built on `NSTextView` get it for free.116* **Hyphenation and justification quality** are the engine's responsibility (section 11); Core Text's suggested breaks are first-fit, not paragraph-optimal. LibreOffice 26.8 has just added a paragraph composer (see `competitive-analysis.md`).117* **Not verified:** the in-window behaviour of `NSTextTable` under TextKit 2 on macOS 27, and whether Apple intends to add pagination to TextKit 2. Neither affects v1.0.118119---120121## 2. Document architecture122123### What was evaluated124125How the app owns files: open, save, autosave, versions, conflicts, windows and undo.126127### Options1281291. **`NSDocument`** subclass hosting SwiftUI views through `NSHostingController` / `NSHostingView` (architect's decision).1302. **SwiftUI `DocumentGroup` with `FileDocument`** (value type).1313. **SwiftUI `DocumentGroup` with `ReferenceFileDocument`** (reference type with snapshots).132133### Findings134135* `NSDocument` is declared `@MainActor class NSDocument` and conforms to `NSFilePresenter` (**Web**: https://developer.apple.com/documentation/appkit/nsdocument). It exposes `autosavesInPlace`, `autosavesDrafts`, `preservesVersions`, `browseVersions(_:)`, `canAsynchronouslyWrite(to:ofType:for:)`, `unblockUserInteraction()`, `canConcurrentlyReadDocuments(ofType:)`, `presentedItemDidChange()`, `presentedItemDidGain(_:)`/`presentedItemDidResolveConflict(_:)` for file versions, `fileModificationDate`, `performAsynchronousFileAccess(_:)`, window restoration, printing (`printOperation(withSettings:)`, `pdfPrintOperation`) and the AppleScript handlers `handleSave(_:)`, `handleClose(_:)`, `handlePrint(_:)`.136* `ReferenceFileDocument` requires `snapshot(contentType:)` and `fileWrapper(snapshot:configuration:)`; the documentation states "SwiftUI can't detect changes to your document's properties on its own. Register an undo action with the environment's `UndoManager` whenever you mutate the document" and "SwiftUI calls the protocol's methods from different isolation domains. Don't perform serialization and deserialization on `MainActor`" (**Web**: https://developer.apple.com/documentation/swiftui/referencefiledocument). Dirty state is therefore coupled to undo registration.137* `DocumentGroup` is implemented on top of the AppKit document architecture on macOS (**not verified** from a primary source; widely reported), but it does not expose the `NSDocument` instance, its window controllers, or its save pipeline.138139### Assessment140141| Criterion | `NSDocument` + SwiftUI views | `DocumentGroup` + `FileDocument` | `DocumentGroup` + `ReferenceFileDocument` |142|---|---|---|---|143| Autosave in place | ++ `autosavesInPlace`, explicit control of timing | + automatic, not configurable | + automatic, driven by undo registration |144| Versions browser | ++ `preservesVersions`, `browseVersions` | + inherited, not controllable (**not verified**) | + same |145| Conflict detection / file coordination | ++ `NSFilePresenter` callbacks can be overridden | 0 handled internally, no hooks | 0 same |146| Asynchronous saving | ++ `canAsynchronouslyWrite` + `unblockUserInteraction` after taking a snapshot | − `fileWrapper` is called with a value copy; large serialisations are opaque | + snapshot then background serialisation |147| Custom window chrome, multiple windows per document, inspectors | ++ `NSWindowController` | − limited to scene modifiers | − same |148| Control over undo | ++ own `UndoManager` policy (snapshot stack of model values) | − automatic, whole-value | − must register every change |149| Import with warnings sheet, export accessory views, "Save As" type lists | ++ `prepareSavePanel`, `writableTypes(for:)` | − | − |150| AppleScript document suite | ++ built in | −− not exposed | −− not exposed |151| Reliability | ++ 20+ years in production apps | + | + |152| License / notarization / Apple silicon / offline | Apple SDK, no impact | same | same |153| Maintenance cost | 0 more code, Objective-C-era callback APIs under Swift 6 strict concurrency | ++ least code | + |154155### Decision (architect) and rationale156157`NSDocument` hosting SwiftUI. The research supports it: the product needs asynchronous saving of a ZIP container, an import path that reports `FormatWarning`s before the document becomes editable, a controlled undo stack, custom windows, and AppleScript; `DocumentGroup` hides each of these.158159### Risks and open questions160161* **Swift 6 friction.** `NSDocument` is `@MainActor` but its asynchronous-save contract (`write(to:ofType:)` may run off the main thread after `unblockUserInteraction()`) predates Swift concurrency. Because `DocumentModel` is a `Sendable` value, the safe pattern is: capture the value on the main actor, call `unblockUserInteraction()`, serialise the captured value in a `nonisolated` function. This should be written once and tested under the thread sanitizer.162* **Autosave cost.** Autosave in place rewrites the whole `.orixdoc` (section 3). For documents with many images, measure before enabling `autosavesInPlace` unconditionally.163* **Not verified:** exact behaviour of `DocumentGroup` regarding versions and conflict UI on macOS 15–27.164165---166167## 3. Native format `.orixdoc`168169### What was evaluated170171The on-disk format for native documents.172173### Options1741751. **Single-file ZIP container** with a manifest, a SHA-256 per entry and a JSON model (architect's decision).1762. **Directory package** (`NSFileWrapper` bundle with `LSTypeIsPackage`).1773. **SQLite** database file.1784. **ODF (`.odt`) as the native format.**1795. **DOCX as the native format.**180181### Assessment182183| Criterion | ZIP + JSON | Directory package | SQLite | ODF native | DOCX native |184|---|---|---|---|---|---|185| Functionality (carries the whole `DocModel` losslessly) | ++ format is the model | ++ | ++ | − model must be bent to ODF; ORIX-only features need extension namespaces | − same with OOXML; every save is a lossy export risk |186| Reliability (atomic save, partial-write safety) | ++ one file, written to a temporary and swapped | 0 multi-file; atomicity depends on `NSFileWrapper` + safe-save | + journaled; `-wal`/`-shm` side files complicate atomic replace | ++ | ++ |187| Behaviour in e-mail, web uploads, non-Apple cloud sync, Git, Windows/Linux | ++ ordinary file | −− appears as a folder off the Mac; sync services may split or half-sync it | + ordinary file | ++ | ++ |188| Incremental save performance | − whole archive rewritten on every save | ++ only changed files rewritten | ++ page-level writes | − | − |189| Inspectability / recoverability | ++ unzip + JSON | ++ | 0 needs tooling | + | + |190| License | Own | Own | Public domain | OASIS standard, free to implement | ECMA-376 / ISO 29500, free to implement |191| Maintenance | + own schema with `schemaVersion` | + | 0 schema migrations | −− tracks a 1 000-page standard | −− tracks a 5 000-page standard plus Word behaviour |192| Security (hostile file) | + small attack surface: own ZIP reader, `JSONDecoder` | + path handling inside the package | − SQLite on untrusted files needs defensive configuration | − XML | − XML |193| Apple silicon / notarization / offline | No impact | same | same | same | same |194195### Decision (architect) and rationale196197Single-file ZIP container with `manifest` + per-entry SHA-256 + JSON model. The research supports it. The decisive properties are a format that is exactly the model (`DocumentModel` is `Codable`, with `schemaVersion`; images live in `DocumentModel.assets` and are excluded from the JSON), and a single ordinary file that survives every transport. Adopting ODF or DOCX natively would make every save a conversion and would tie the model's evolution to an external standard; both remain import/export formats.198199### Extension and type identifier200201* **Extension collision check.** A web search for "orixdoc" returned no file format using that extension, and `UTType(filenameExtension: "orixdoc")` on the build machine returns a dynamic, undeclared type (`dyn.…`, `isDeclared == false`), meaning no installed application claims it (**Web**, **Probe**). The common extension registries (fileinfo.com, IANA media types) were **not** queried one by one; treat "no known collision" as the result of one search, not a guarantee.202* **Name.** "ORIX" is also the name of a large Japanese financial group (ORIX Corporation). That is not a file-format collision; whether it matters for trademarks is a legal question outside this document (**not verified**).203* **UTI.** `ai.spboucher.orix.docs.document`, to be declared under `UTExportedTypeDeclarations` in the app's `Info.plist` with extension `orixdoc`. Recommendations: conform to `public.data` and `public.content` (and `public.composite-content` if desired); do **not** conform to `public.zip-archive`, otherwise the system may offer Archive Utility for the file and expand it on double-click when the app is not installed; provide a MIME type of the form `application/vnd.spboucher.orixdoc+zip` (unregistered; **not verified** that no such registration exists).204205### Risks and open questions206207* **Whole-file rewrite and memory.** `ZipReader(data:)` and `ZipWriter.finalize()` work on whole `Data` values (`Packages/ORIXDocsKit/Sources/DocContainer/ZipArchive.swift`). A document with 300 MB of images is read and written through memory in one piece; peak memory is roughly the archive plus the largest entry. Acceptable for v1.0 if measured and documented; a memory-mapped read (`Data(contentsOf:options: .mappedIfSafe)`) removes most of the read-side cost.208* **Hashes give integrity, not authenticity.** A per-entry SHA-256 in a manifest stored in the same archive detects corruption, not tampering. The documentation must not describe it as a signature.209* **Identify the format without unzipping.** Follow the EPUB/ODF convention: first entry named `mimetype`, stored uncompressed, containing the MIME type (the writer's `compress: false` option already exists for this purpose).210* **Forward compatibility.** `FormatError.unsupportedVersion` exists; decide now whether unknown JSON keys from a newer minor version are preserved or dropped on save.211212---213214## 4. ZIP implementation215216### What was evaluated217218How `.orixdoc` and `.docx` containers are read and written.219220### Options2212221. **Own minimal reader/writer** over Apple's Compression framework (`compression_decode_buffer` / `compression_encode_buffer`, `COMPRESSION_ZLIB` = raw deflate) (architect's decision; implemented in `DocContainer/ZipArchive.swift`).2232. **ZIPFoundation** (https://github.com/weichsel/ZIPFoundation).2243. **libarchive** (https://github.com/libarchive/libarchive), which also ships with macOS without public headers in the SDK (**not verified**).2254. **`NSFileCoordinator` with `.forUploading`**, which makes the system zip a directory, and other tricks (`/usr/bin/zip`, `ditto` subprocesses).226227### Library state (GitHub API, 2026-11-21)228229| Library | Latest release | License | Last push | Open issues + PRs | Notes |230|---|---|---|---|---|---|231| ZIPFoundation | 0.9.20 (2025-09-24) | MIT | 2026-11-20 | 25 | README lists "Large File Support" and in-memory archives; uses libcompression on Apple platforms; states no traversal or decompression-bomb protections; still 0.x after several years (**Web**) |232| libarchive | 3.8.11 (2026-10-30) | BSD-2-Clause (repository `COPYING`; GitHub reports a non-standard license file) | 2026-11-17 | 577 | C; many formats; frequent security fixes, large surface (**Web**; license text itself **not verified** line by line) |233234### Assessment235236| Criterion | Own reader/writer | ZIPFoundation | libarchive | `NSFileCoordinator` / subprocess |237|---|---|---|---|---|238| Functionality | + stored + deflate, no ZIP64, no encryption — sufficient for DOCX/ODT/own format | ++ ZIP64, streaming, files and memory | ++ everything | −− write-only (zip a directory), no entry control, no read |239| Reliability | 0 new code; depends on tests | + widely used | + very widely used | − undocumented output details |240| Performance | + in-memory, one-shot decode | + streaming | ++ | − |241| License | Own | MIT | BSD | Apple |242| Maintenance | 0 ~270 lines owned | + upstream active | + upstream active | n/a |243| Security | ++ limits are explicit and auditable; minimal surface | 0 caller must add limits and name validation | − large C surface, regular CVEs | 0 |244| Apple silicon / notarization | ++ | ++ pure Swift | + must be built and signed | ++ |245| Offline | ++ | ++ | ++ | ++ |246| Dependency policy ("no third-party dependency except SwiftMath") | ++ | − | − | ++ |247248### Decision (architect) and rationale249250Own minimal reader/writer. Supported: the features needed are few (two compression methods), the Compression framework does the only algorithmically hard part, and a small reader with explicit limits is easier to defend than a general-purpose library whose defaults are permissive.251252### Security review of the current implementation253254Read from `ZipArchive.swift` on 2026-11-21.255256| Threat | Current behaviour | Assessment |257|---|---|---|258| Decompression bomb, single entry | `maxEntrySize` 256 MB; ratio > 1000 rejected for entries over 1 MB; inflation into a buffer of declared size + 1 and rejection if the output differs | Good. The buffer bound means a lying header cannot expand memory beyond the declared (already limited) size. |259| Decompression bomb, many entries / overlapping entries | `maxEntries` 20 000; sum of declared sizes capped at 1 GB; entries decompressed on demand | Good in principle. 1 GB is a high ceiling for a text document; consider a lower default for DOCX XML parts (for example 64 MB per XML part) while keeping the media limit. |260| Path traversal ("zip slip") | Names that are empty, absolute, contain `\`, NUL, `:` or a `..` component are rejected | Good. Entries are never written to disk by name, which is the stronger protection. |261| Encrypted entries | Rejected (general-purpose bit 0) | Correct; state it in the UI ("password-protected documents are not supported"). |262| Unsupported methods | Only 0 and 8 accepted | Correct. |263| ZIP64 | Rejected when a size field is `0xFFFFFFFF`; writer refuses to produce it | Acceptable, with the risk below. |264| CRC | CRC-32 verified on every read | Good. |265| **Duplicate entry names** | *As evaluated:* the index was `idx[name] = out.count`; a second central-directory entry with the same name silently replaced the first. **Fixed since:** the reader now rejects duplicate names and checks that each local header names the same entry (`ZipArchive.swift`). | **Gap at evaluation time (closed).** Duplicate names are the basis of parser-differential attacks (a scanner sees one `word/document.xml`, the app another). OPC forbids them. Reject archives with duplicate names, including names equal under ASCII case folding (OPC part names are compared case-insensitively). |266| **Central directory vs local header disagreement** | Sizes and names come from the central directory only; the local header is checked for its signature | Minor gap. Compare the local header's name with the central directory's and reject on mismatch. |267| Multi-disk archives, EOCD in a comment, prepended data | Not examined in this review | **Not verified.** Add corpus tests. |268269### Risks and open questions270271* **ZIP64 in the wild.** Some producers emit ZIP64 structures even for small archives (streaming writers that do not know sizes in advance). If a real-world DOCX uses ZIP64 extra fields, the reader refuses a legitimate document. How common this is among DOCX producers is **not verified**; the DOCX test corpus (`Tests/DocDOCXTests/Corpus`) should include files from Word (Mac, Windows, web), Google Docs export, LibreOffice, Pages, pandoc and at least one server-side generator, and the importer should produce a specific error message for ZIP64 rather than "corrupted".272* **Data descriptors (bit 3).** The reader takes sizes from the central directory, so streamed archives should work; add a test with a bit-3 archive to prove it.273* **Fuzzing.** A hand-written binary parser fed with hostile input should be fuzzed (libFuzzer via `swift build -sanitize=fuzzer` or a simple mutation harness) before 1.0.274275---276277## 5. DOCX278279### What was evaluated280281How to read and write WordprocessingML (`.docx`) with tracked changes, comments, footnotes, tables, styles, numbering, fields, sections and images mapped to and from `DocModel`.282283### Options surveyed284285| Option | What it is | State on 2026-11-21 | License | Fit |286|---|---|---|---|---|287| **Own reader/writer** (`DocDOCX`) | Swift, over `DocContainer` and an XML parser | Placeholder target | Own | Architect's decision |288| `NSAttributedString` with `.officeOpenXML` (`NSOfficeOpenXMLTextDocumentType`; also what `textutil` uses) | Apple's built-in DOCX reader/writer | Ships with macOS | Apple SDK | See probe below: far too lossy |289| DocX (shinjukunian/DocX) | Swift library that **writes** `NSAttributedString`/`AttributedString` to DOCX | 0.8.14 (2026-11-04), 107 stars, depends on AEXML fork + ZIPFoundation | MIT | Write-only; no reading; README does not mention tables or tracked changes (**Web**) |290| docx4j | Java library, JAXB object model for OOXML | Tag `docx4j-parent-11.5.2`, active | Apache-2.0 (per project documentation; GitHub API reports no detected license — **not verified**) | Requires a bundled JVM (hundreds of MB, signing of every nested binary) |291| python-docx | Python library | 1.2.0, 554 open issues/PRs | MIT | Requires a bundled Python; no layout, partial feature coverage (no tracked changes API — **not verified**) |292| Open XML SDK | .NET library from Microsoft | **Not verified** | MIT (**not verified**) | Requires a bundled .NET runtime |293| LibreOfficeKit / UNO | LibreOffice's core as a library | LibreOffice 26.8.2 installed locally | MPL-2.0 for the core, with LGPL-3.0+ and other components (**not verified** component by component) | Best open-source DOCX fidelity; ~hundreds of MB; MPL obligations (source of modified MPL files, notices); the resulting model is LibreOffice's, not `DocModel` |294| pandoc as a subprocess | Haskell document converter | 3.14 (2026-11-12); 3.9.0.2 installed | GPL-2.0-or-later | Semantic conversion only: no page layout, no tracked-change round trip in the app's terms; GPL applies to distributing the binary |295| Aspose.Words | Commercial library (.NET, Java, C++, Python) | **Not verified** | Commercial, per-developer and distribution licensing; no Swift binding (**not verified**) | Highest third-party fidelity claims; cost, closed source, large C++/runtime payload |296297### Probe: what `NSAttributedString` keeps from a DOCX298299A DOCX produced by pandoc 3.9.0.2 (title, heading, a footnote, italic and bold, a hyperlink, inline and display equations, a 2×2 table with header, a numbered list) was read with `NSAttributedString(url:options:documentAttributes:)` on macOS 27.0 and written back with `.officeOpenXML`.300301| Feature in the source | Result after reading |302|---|---|303| Body text, bold, italic | Kept |304| Table | Kept as `NSTextTable` blocks |305| Footnote | **Lost entirely** (reference and text) |306| Hyperlink | Text kept, **link attribute lost** (0 `.link` attributes) |307| Inline and display equations (OMML) | **Lost** (the sentence reads "inline math ." with nothing in between) |308| Heading and title styles | **Lost**: every run is Times 12 pt; no style names; only `NSFont` and `NSParagraphStyle` attributes |309| Numbered list | Turned into bullets ("•") |310| Written back | Archive contains `document.xml`, a theme and core/app properties; no `styles.xml`, `numbering.xml`, `footnotes.xml` or `comments.xml` |311312This confirms that the system reader is not a basis for a word processor. It remains useful as a last-resort text extractor.313314### Assessment315316| Criterion | Own reader/writer | `NSAttributedString` | LibreOfficeKit | pandoc subprocess | docx4j / python-docx | Aspose |317|---|---|---|---|---|---|---|318| Functionality (maps to `DocModel`, tracked changes, comments, notes, fields) | + what is implemented; explicit `FormatWarning`s for the rest | −− | + via an intermediate format; mapping to `DocModel` still required | − | 0 | + |319| Reliability on real-world files | 0 unproven until the corpus is large | + never crashes, loses silently | ++ | + | + | ++ (vendor claim, **not verified**) |320| Performance | ++ native, in-process | ++ | − process/library start-up, large memory | − subprocess | −− runtime start-up | 0 |321| License for a closed, notarized distribution | ++ | ++ | 0 MPL-2.0 is file-level copyleft and compatible with closed distribution if notices and modified-file sources are provided; mixed-license components need an audit | − GPL binary: can be shipped as a separate executable with source offer; legal review needed; contradicts a simple "proprietary" notice | + Apache/MIT, but the JVM/Python runtimes add their own licenses | − paid, redistribution terms |322| Maintenance | −− permanent, large | ++ | 0 track upstream | 0 | 0 | + vendor |323| Security | + hostile-input rules applied in own code (section 13) | + | − very large C++ attack surface | 0 | 0 | 0 |324| Apple silicon | ++ | ++ | + arm64 builds exist | + | + | **not verified** |325| Notarization | ++ | ++ | − hundreds of nested Mach-O files to sign with hardened runtime | + one binary | − JIT runtimes may need `allow-jit` / `allow-unsigned-executable-memory` | **not verified** |326| Offline | ++ | ++ | ++ | ++ | ++ | ++ |327328### Decision (architect) and rationale329330Own WordprocessingML reader and writer in `DocDOCX`. The research supports the direction: no Swift library reads DOCX into a structured model; every non-Swift option brings a runtime, a license question, or an intermediate model that would still have to be mapped onto `DocModel`. `DocModel` was visibly designed with this mapping in mind (Word style ids, `vMerge`, section breaks carrying the next section's `PageSetup`, tracked insertions/deletions on runs).331332### Risks and open questions333334* **This is the second-largest risk in the project and the one users will judge first.** Word's behaviour is defined by ECMA-376 plus two decades of undocumented compatibility behaviour. A v1.0 own implementation will be measurably below Word, LibreOffice and Pages on arbitrary documents. The product must say so (see `competitive-analysis.md`) and must surface `FormatWarning`s prominently instead of presenting an import as faithful.335* **Round-trip safety.** Opening a DOCX, editing one word and saving it back through a lossy model can destroy content the model does not represent (content controls, SmartArt, charts, embedded OLE objects, custom XML, VML, text boxes). Decide before 1.0: either (a) never overwrite the original DOCX silently — "Save" on an imported DOCX becomes "Save as `.orixdoc`" with DOCX as an explicit export — or (b) preserve unknown parts and elements opaquely. Option (a) is the honest default for v1.0.336* **OMML ↔ LaTeX.** DOCX equations are Office Math Markup; the model stores LaTeX (`Equation`). A converter in both directions is needed and SwiftMath's LaTeX subset bounds what survives (section 6).337* **Interoperability testing is available locally** (Word 16.115.1, LibreOffice 26.8.2.2, pandoc, `textutil`): exports should be opened in Word and LibreOffice headlessly (`soffice --headless --convert-to pdf`) in CI-style scripts. Driving Word requires a GUI session and AppleScript and was not exercised in this research.338* **Not verified:** licensing details of docx4j, Open XML SDK, Aspose and the individual LibreOffice components; python-docx's coverage of tracked changes.339340---341342## 6. Math343344### What was evaluated345346Typesetting of LaTeX math stored in the model (`Equation`), inline and display, drawn into the same Core Graphics context as the page (screen and PDF).347348### Options and library state (GitHub API and repository contents, 2026-11-21)349350| Option | Latest release | License | Activity | Rendering | Notes |351|---|---|---|---|---|---|352| **SwiftMath** (mgriebling/SwiftMath) | **1.7.3, tagged 2025-08-03**; `main` is **111 commits ahead** (last push 2026-10-28) | MIT (code); bundled fonts under GUST Font License and SIL OFL | 1 open issue/PR, 411 stars | Core Text glyph drawing using the OpenType MATH table (pre-extracted to plists) | Architect's decision; pinned at 1.7.3 in `Package.resolved` |353| iosMath (kostub/iosMath) | 2.5.0 (2026-07-13) | MIT | 26 open, 1 475 stars | Same approach, Objective-C | SwiftMath's origin; upstream is alive again |354| KaTeX in `WKWebView` | 0.19.1 (2026-10-23) | MIT | very active | HTML/CSS in a web view | Broad LaTeX coverage; output is a web view, not vector drawing in the page context |355| MathJax in `WKWebView` | 4.1.3 (2026-07-03) | Apache-2.0 | active | SVG or HTML in a web view | Broadest coverage (AMS, mhchem); SVG output could be converted to paths |356| Bundled TeX engine | — | LPPL / GPL / mixed | — | DVI/PDF | Hundreds of MB for a usable distribution; subprocess; **not evaluated in depth** |357| Own implementation over the OpenType MATH table | — | Own | — | Core Text | Full control; months of work to reach SwiftMath's current state |358359### SwiftMath in detail360361Verified in the checkout used by the build (`.build/checkouts/SwiftMath`, revision `fa8244e`, tag 1.7.3) and against upstream `main`:362363* **Scope stated by the project:** "SwiftMath only supports the commands in LaTeX's math mode" and "this is not a complete implementation of LaTeX math mode"; missing pieces listed by the README at 1.7.3 include explicit big delimiters (`\bigl`, `\bigr`) and "missing plain TeX commands".364* **Environments found in the 1.7.3 source:** `matrix`, `pmatrix`, `bmatrix`, `Bmatrix`, `vmatrix`, `Vmatrix`, `eqalign`, `split`, `aligned`, `gather`, `displaylines`, `eqnarray`, `cases`.365* **Not found in the 1.7.3 source (string search of the builder, factory and typesetter):** `\operatorname`, `\dfrac`, `\tfrac`, `\substack`, `smallmatrix`, `\bigl`/`\Bigg` family, `\boldsymbol`, `\underbrace`, `\overbrace`, `\overset`, `\underset`, `\stackrel`, `\boxed`, `\cancel`, `\phantom`, `\xrightarrow`, `\tag`, `\newcommand`, and the `align` and `array` environments.366* **Present on `main` but in no release:** `\operatorname`, `\dfrac`/`\tfrac`, `\substack`, `smallmatrix`, the `\big…` delimiter family, `\boldsymbol`, `\middle`, automatic line wrapping, and several crash fixes — the two most recent merged pull requests are titled "Don't trap on a row break inside a single-atom argument" and "typesetting must never change its input" (2026-09 and 2026-10).367* **Still absent on `main`:** `\underbrace`/`\overbrace`, `\overset`/`\underset`/`\stackrel`, `\boxed`, `\cancel`, `\phantom`, `\xrightarrow`, `\tag`, `\newcommand`, `align`, `array`.368* **Update, 2026-11-21 (implementation):** the package is now pinned to upstream revision `0b0222e` (main, after 1.7.3) and every expression passes `MathGuard` first; `Tests/DocLayoutTests/MathRobustnessTests.swift` fuzzes both. The findings below describe 1.7.3.369* **Robustness:** the 1.7.3 render sources contain 29 uses of `fatalError`/`precondition`/`assert`/`try!` across the builder, list, display and typesetter files. Some are reachable from input, as the upstream "don't trap" fixes show.370* **Fonts:** `mathFonts.bundle` is 7.1 MB and contains twelve math fonts (Latin Modern Math, TeX Gyre Termes Math, XITS, Asana, Euler, Fira Math, Garamond Math, KpMath Light and Sans, Lete Sans Math, Libertinus Math, Noto Sans Math). Only the license files for GUST and OFL are present; the README names licenses for Latin Modern, TeX Gyre Termes, XITS and KpMath only. The licenses of the other eight fonts are **not verified** (they are OFL upstream as far as known, but the bundle does not document it).371* **Language mode:** `swift-tools-version: 5.7`; the package is not written for Swift 6 strict concurrency (seven occurrences of `NSLock`/`Sendable`/`@MainActor` in the sources). `DocMath` must confine it to one isolation domain.372* **Text in math:** "no language support for other than west European languages and some Cyrillic characters" (README).373374### Assessment375376| Criterion | SwiftMath | iosMath | KaTeX / MathJax in `WKWebView` | Bundled TeX | Own MATH-table engine |377|---|---|---|---|---|---|378| Functionality (LaTeX coverage) | 0 common school/undergraduate math; gaps listed above | 0 similar | ++ | ++ | 0 → + over time |379| Vector output in the page's `CGContext` (screen = PDF) | ++ | ++ | −− web view; needs SVG-to-path conversion or bitmap snapshots | + PDF fragments to embed | ++ |380| Reliability | − reachable traps at the pinned version | 0 | + | + | 0 |381| Performance | ++ in-process | ++ | − web process, asynchronous | −− subprocess | ++ |382| License | MIT + font licenses to document | MIT | MIT / Apache-2.0 | mixed, heavy | Own |383| Maintenance | 0 single maintainer; no release for 15 months despite 111 commits | 0 | ++ | + | −− |384| Security | 0 parser of user-controlled strings with traps | 0 | + sandboxed web content process; JavaScript engine in the app | − | + |385| Apple silicon / notarization / offline | ++ pure Swift, resources only | + Objective-C | + (bundled JS, no network) | − many binaries | ++ |386387### Decision (architect) and rationale388389SwiftMath, wrapped by `DocMath`. Supported as the pragmatic choice: it is the only maintained option that draws LaTeX math as vector glyphs directly into a Core Graphics context, which the "same renderer for screen and PDF" requirement demands.390391### Risks and open questions392393* **The pinned release is stale and contains known crashers.** `from: "1.7.0"` resolves to 1.7.3 (August 2025). Fixes for input-triggered traps and widely used commands (`\operatorname`, `\dfrac`, `\substack`) exist only on `main`. Options: pin a specific `main` revision after review; ask the maintainer for a release; or vendor a fork. Whichever is chosen, a malformed equation in an untrusted document must never crash the app: `DocMath` needs a fuzz/regression suite and, where SwiftMath can still trap, a pre-validation pass that rejects constructs known to trap.394* **Coverage is below what academic users expect.** `align`, `\underbrace`, `\overset`, `\boxed`, `\tag` and user macros are routine in papers. The product should describe its math support as "a LaTeX math subset", list unsupported commands, and show a clear inline error for unsupported input rather than rendering nothing. Equation numbering is handled by the model (`Numbering`), not by `\tag`.395* **Font licensing.** Ship only the math fonts actually offered in the UI, with their license texts in the app's acknowledgements. Dropping unused fonts also removes most of the 7.1 MB.396* **PDF text extraction and accessibility of equations.** Glyphs drawn from a math font extract as symbols at best. For tagged PDF, each equation should be wrapped in a `Formula` structure element with alternative text (the LaTeX source or a spoken form); Word exports MathML in an attribute of `<Formula>` (section 8).397* **Not verified:** rendering equivalence with LaTeX ("rendered exactly as LaTeX would render them" is the README's claim, not a measured result).398399---400401## 7. Citations and bibliography402403### What was evaluated404405Parsing of reference data, formatting of in-text citations and bibliographies, and the choice between a fixed set of built-in styles and a CSL processor.406407### Reference formats408409| Format | What it expresses well | Limits relevant to the importer |410|---|---|---|411| **BibTeX** (`.bib`) | Entry types (`article`, `book`, `inproceedings`, …), a flat set of fields, `@string` macros, `crossref`, name lists separated by `and` with "von Last, Jr, First" parsing, braces to protect capitalisation | No standard for dates beyond `year`/`month`; LaTeX markup inside fields (`{\"o}`, `\emph{}`, math) must be decoded; 14 standard types; real files contain non-standard fields; encoding is often not declared |412| **BibLaTeX** (`.bib`) | Superset: `date` (ISO 8601 with ranges and uncertainty), `journaltitle`, `location`, `langid`, many more types (`online`, `report`, `thesis`, `dataset`, `software`), `related` entries, `xdata`, name options | Larger field vocabulary; inheritance rules for `crossref` differ from BibTeX; same LaTeX-in-fields problem |413| **RIS** | Line-oriented tags (`TY`, `AU`, `TI`, `PY`, `JO`, `SP`, `EP`, `DO`, `ER`); exported by most publisher sites and databases | Tag meanings vary by exporter (two dialects of several tags); weak name structure ("Last, First, Suffix"); dates as `YYYY/MM/DD/other`; little typographic information |414| **CSL-JSON** | The data model CSL processors consume: typed items (`article-journal`, `chapter`, `thesis`, …), structured names (`family`, `given`, `non-dropping-particle`, `suffix`, `literal`), structured dates (`date-parts`, `raw`, `circa`), numbers, rich-text subset in fields | No macro facility; no cross-reference inheritance; a schema, not a file-management format; exported by Zotero and others |415416`DocModel` stores `BibEntry` values with `PersonName`s; mapping all four formats onto a CSL-like internal schema is the natural design, because CSL-JSON is the most structured of the four and is what any future CSL processor would need.417418### Formatting options and state (GitHub API, 2026-11-21)419420| Option | State | License | Notes |421|---|---|---|---|422| **Own formatter for a fixed set**: APA 7, Chicago author-date, MLA 9, IEEE, Vancouver, numeric (architect's decision) | To be written in `DocReferences` | Own | No dependency |423| citeproc-js (Juris-M/citeproc-js) via JavaScriptCore | Active (pushed 2026-11-10), no GitHub releases, tags only | Dual: CPAL or AGPL (repository `LICENSE`, **Web**) | The reference CSL implementation used by Zotero; CPAL requires attribution display, AGPL is incompatible with a closed app; JavaScriptCore is a system framework, no JIT entitlement needed for the interpreter (**not verified** for performance) |424| citeproc-rs (zotero/citeproc-rs) | **Archived**; last release `wasm-v0.2.0`, 2021-12-14; last push 2024-08 | MPL-2.0 (per project README; GitHub reports a non-standard license) | Not a viable dependency |425| Haskell citeproc (jgm/citeproc), used by pandoc | 0.14.2 tag, active | BSD-2-Clause | Would require shipping a Haskell binary or pandoc itself (GPL) as a subprocess |426| A Swift CSL processor | None found | — | One web search returned only the Haskell library; the Swift Package Index was **not** searched exhaustively |427428The CSL style repository contains more than ten thousand styles (**not verified** count); a processor gives access to all of them, a fixed formatter to six.429430### Assessment431432| Criterion | Own fixed-style formatter | citeproc-js in JavaScriptCore | pandoc/citeproc subprocess |433|---|---|---|---|434| Functionality | − six styles; each style's edge cases (et al. rules, disambiguation, sorting, locators, title casing, non-English names) implemented by hand | ++ every CSL style, locales, disambiguation | ++ |435| Reliability / correctness | 0 correctness per style must be proven against the official manuals and the CSL test fixtures | ++ reference implementation | ++ |436| Performance | ++ | + | − |437| License | ++ | − CPAL attribution or AGPL | − GPL (pandoc) / needs a Haskell binary |438| Maintenance | − style manuals change (APA 7 → 8 one day) | + upstream | + |439| Security | ++ | 0 a JavaScript engine evaluating bundled code only | 0 |440| Apple silicon / notarization / offline | ++ | ++ | + |441| Dependency policy | ++ | − | − |442443### Decision (architect) and rationale444445Own formatter for six styles plus own parsers for BibTeX, BibLaTeX, RIS and CSL-JSON. Supportable for v1.0: no CSL processor exists in Swift, the Rust one is archived, and the JavaScript one carries a license that needs legal attention.446447### Risks and open questions448449* **Six styles do not cover academic reality.** Journals mandate their own styles; Zotero, EndNote and Word users choose from thousands. This is a functional gap against every academic competitor and should be listed as such. The design should not preclude a CSL processor later: keep `CitationFormatting` (already a protocol per `overview.md`) free of style-specific assumptions and keep the internal entry schema CSL-compatible.450* **"APA 7" is a claim that can be tested.** Use the publicly available CSL test-suite fixtures and each manual's own examples as regression tests; where behaviour deviates, document it. Do not describe output as conforming to a style manual without those tests.451* **BibTeX parsing is harder than it looks**: nested braces, `@string` concatenation with `#`, `@preamble`, `@comment`, name parsing with particles and suffixes, LaTeX accents and commands, and case protection. Budget for it and test with large real libraries (Zotero/JabRef exports).452* **No reference-manager integration.** Zotero's official word-processor plugins exist for Word, LibreOffice and Google Docs only (**Web**: https://www.zotero.org/support/word_processor_integration). ORIX Docs' citation fields will not be live Zotero fields; DOCX exported from ORIX Docs will contain plain-text citations unless Word-compatible citation fields are written (and Zotero's field codes are a separate, undocumented-by-ECMA convention). State this limitation.453* **Not verified:** JavaScriptCore performance for citeproc-js; whether CPAL's attribution requirement is acceptable for this product.454455---456457## 8. PDF output458459### What was evaluated460461Producing PDF from the page renderer, with document outline, metadata, links, tagged structure, and the possibility of PDF/A and PDF/UA output.462463### Approach (architect)464465`DocLayout` draws each page into a `CGPDFContext` using the same code that draws the screen; the outline is written with `CGPDFContextSetOutline` and metadata through the context's auxiliary dictionary.466467> **Update, 2026-11-21 (implementation).** The first implementation added the outline with PDFKit after drawing. On macOS 27.0 `PDFDocument.dataRepresentation()` and `write(to:)` did not persist an `outlineRoot` set in code (checked with a minimal program), so the publisher now uses `CGPDFContextSetOutline`. Its dictionary format is documented in `CGPDFDocument.h` (a root holding only `kCGPDFOutlineChildren`; items with `kCGPDFOutlineTitle`, `kCGPDFOutlineDestination` as a 1-based page number and an optional `kCGPDFOutlineDestinationRect`). No PDFKit post-processing remains, which also removes the risk noted below of a rewrite altering the structure tree. Validated by `PDFTests.outlineMirrorsTheHeadings`.468469### What Core Graphics offers (macOS 27.2 SDK headers, plus a probe on macOS 27.0)470471| Capability | API | Availability | Evidence and notes |472|---|---|---|---|473| Info dictionary (title, author, subject, keywords, creator) | `kCGPDFContextTitle`, `…Author`, `…Subject`, `…Keywords`, `…Creator` | macOS 10.4–10.5 | **SDK** |474| XMP metadata | `CGPDFContextAddDocumentMetadata` | macOS 10.7 | **SDK** |475| URL links | `CGPDFContextSetURLForRect` (Swift: `CGContext.setURL(_:for:)`) | macOS 10.4 | **SDK**; **Probe**: produces a `/URI` action |476| Internal destinations and links | `CGPDFContextAddDestinationAtPoint`, `CGPDFContextSetDestinationForRect` | macOS 10.4 | **SDK**; needed for cross-references, table of contents and footnote links |477| Outline (bookmarks) | `CGPDFContextSetOutline(context, CFDictionary)` | macOS 10.13 | **SDK**. The dictionary format is not described in the header. **Probe**: a dictionary with guessed keys (`Title`, `Children`, `Destination`) produced a PDF with no outline. Building the outline with PDFKit (`PDFOutline`) is therefore a reasonable choice. |478| Output intent, ICC profile | `kCGPDFContextOutputIntent`, `kCGPDFContextOutputIntents`, `kCGPDFXOutputIntentSubtype`, `kCGPDFXOutputConditionIdentifier`, `kCGPDFXOutputCondition`, `kCGPDFXRegistryName`, `kCGPDFXInfo`, `kCGPDFXDestinationOutputProfile` | macOS 10.4 | **SDK**. The header describes these for PDF/X (`GTS_PDFX`). |479| Linearization | `kCGPDFContextCreateLinearizedPDF` | macOS 11.0 | **SDK** |480| **PDF/A** | `kCGPDFContextCreatePDFA` | macOS 11.0 | **SDK**: the key exists; the header comment reads "Output a PDF that conforms to PDF/A-2u (ISO 19005-2)". **Probe** on macOS 27.0: the file gains an XMP packet declaring `pdfaid:part` = 2 and `pdfaid:conformance` = **B** (not U), an `/OutputIntents` array with `/S /GTS_PDFA1` and an embedded sRGB profile, and subset-embedded fonts. The header and the emitted metadata disagree about the conformance level. |481| Tagged PDF, legacy | `CGPDFContextBeginTag(context, CGPDFTagType, properties)`, `CGPDFContextEndTag`; properties `kCGPDFTagPropertyActualText`, `…AlternativeText`, `…TitleText`, `…LanguageText` | macOS 10.15 | **SDK**; **Probe**: output contains `/MarkInfo << /Marked true >>`, a `/StructTreeRoot`, a parent tree and `BDC … EMC` marked content. The structure tree is built implicitly from the nesting of calls **within the drawing order**. |482| Tag types | `CGPDFTagType`: `Document`, `Part`, `Art`, `Section`, `Div`, `BlockQuote`, `Caption`, `TOC`, `TOCI`, `Index`, `NonStructure`, `Private`; `Paragraph`, `Header`, `Header1`–`Header6`; `List`, `ListItem`, `Label`, `ListBody`; `Table`, `TableRow`, `TableHeaderCell`, `TableDataCell`, `TableHeader`, `TableBody`, `TableFooter`; `Span`, `Quote`, `Note`, `Reference`, `Bibliography`, `Code`, `Link`, `Annotation`; ruby/warichu types; `Figure`, `Formula`, `Form`; `Object` | macOS 10.15 | **SDK** (PDF 1.7 standard structure types) |483| **Tagged PDF, new API** | `CGPDFStructureElement(tagType:)`, `addChild(_:)`, `addMarkedContentItem(_:)`, setters for title, language, alternative text, expansion text and actual text; `CGContext.beginMarkedContentSequence(_:)` returning a `CGPDFMarkedContentItem`, `endMarkedContentSequence()`, `beginObjectReference()` / `endObjectReference()`, `addStructureTreeRootChild(_:)` | **macOS 27.0 only** | **SDK** (`CGPDFStructureElement.h`, `CGPDFMarkedContentItem.h`, and the section "New Tagged PDF Authoring" in `CGPDFContext.h`, where the 10.15 functions are now headed "Legacy Tagged PDF Authoring"). **Probe**: produced a structure tree with per-element `/Lang`. This API separates the logical tree from drawing order, which is what a paginated document needs (a paragraph or table that continues on the next page is one structure element with marked content on two pages). |484| **Artifacts** (headers, footers, page numbers) | `CGPDFTagTypeArtifact` with `CGContext.beginNonStructuralMarkedContentSequence(_:)` | **macOS 27.0 only** | **SDK**; **Probe**: emits `/Artifact BMC … EMC`. With the legacy API there is no way to mark artifacts. |485| Lower-level hooks | `CGPDFContextSetParentTree`, `CGPDFContextSetIDTree`, `CGPDFContextSetPageTagStructureTree` | No availability annotation | **SDK**; undocumented in the header; **not verified** |486487What the probe's output did **not** contain, with either tagging API: a document-level `/Lang` in the catalog, `/ViewerPreferences << /DisplayDocTitle true >>`, a `pdfuaid:part` entry in the XMP, or `/ToUnicode` maps for the simple TrueType font used (`pdffonts` reports `uni: no`; the font uses MacRoman encoding, from which Unicode is derivable, and `pdftotext` did extract the text correctly, including "é" and the "fi" ligature). The PDF header version was `%PDF-1.3` in all four test files.488489### Validators490491| Validator | License / cost | What it checks | State |492|---|---|---|---|493| veraPDF (https://verapdf.org, veraPDF/veraPDF-library) | Open source, dual GPL-3.0+ / MPL-2.0+ (GitHub reports GPL-3.0; dual licensing **not verified** from the license file); latest release v1.30.4 (2026-11-10) | PDF/A-1/2/3/4 and PDF/UA-1 (machine-checkable rules; PDF/UA-2 support **not verified**) | **Not installed** on the build machine; Java-based CLI, suitable for scripts |494| Adobe Acrobat Pro Preflight | Commercial | PDF/A, PDF/X, PDF/UA syntax checks, fix-ups | **Not available** on the build machine (**not verified**) |495| PAC (PDF Accessibility Checker) | Free, Windows only (**not verified**) | PDF/UA (Matterhorn Protocol) | Not usable locally |496497A PDF/UA claim cannot rest on software alone: the Matterhorn Protocol includes checks that require human judgement (reading order makes sense, alternative text is meaningful).498499### Assessment500501| Criterion | Core Graphics `CGPDFContext` + PDFKit | Alternative: own PDF writer | Alternative: print system (`NSPrintOperation` to PDF) |502|---|---|---|---|503| Functionality | + vector text, fonts, images, links, tags; outline via PDFKit | ++ full control of every object | − no tags, no control of structure |504| Same renderer as the screen | ++ | − second backend | + |505| Reliability | ++ system PDF generator | − new code | ++ |506| PDF/A | 0 a flag exists; output unvalidated; header and metadata disagree on the level | + possible with full control, large effort | − |507| PDF/UA | 0 feasible on macOS 27 with the new API plus post-processing; weak on macOS 15–26 (no artifacts, tree tied to drawing order) | + | −− |508| License / Apple silicon / notarization / offline | Apple SDK | Own | Apple SDK |509| Maintenance | + | −− | + |510511### Decision (architect) and rationale512513Core Graphics drawing, outline included (see the update above; the PDFKit post-processing first planned was dropped). It is the only option that keeps one renderer.514515### Requirements that follow from the findings5165171. **No conformance claims without validation.** The export UI and documentation must not say "PDF/A" or "PDF/UA" (or "accessible PDF" as a compliance statement) until veraPDF passes on a representative corpus, and for PDF/UA until a manual review has been done. Until then use neutral wording: "tagged PDF (structure tags for headings, paragraphs, lists, tables, figures)". If `kCGPDFContextCreatePDFA` is offered, label it "PDF/A-2 (experimental, not validated)" or hold it back.5182. **Two tagging code paths.** The deployment target is macOS 15. Use the structure-element API under `if #available(macOS 27.0, *)` and the legacy begin/end-tag API otherwise, and document that artifact marking of headers/footers and correct structure for content split across pages are only available on macOS 27 or later. Alternatively restrict tagged export to macOS 27+ for v1.0.5193. **Post-processing must not destroy the structure.** Rewriting the file through `PDFDocument.write(to:)` to add an outline may drop or alter the structure tree, output intents or XMP. This is **not verified** either way; test it before relying on PDFKit for anything on a tagged or PDF/A file. If it is destructive, write the outline and document-level entries through Core Graphics (`CGPDFContextSetOutline`, once its dictionary format is established from Apple documentation or a working sample) and the XMP through `CGPDFContextAddDocumentMetadata`.5204. **Missing PDF/UA prerequisites to add:** catalog `/Lang` (from the document language), `DisplayDocTitle`, a `dc:title` in XMP, `pdfuaid:part`, alternative text on figures (`ImageObject` needs an alt-text field if it does not have one), table header cells, link annotations tied to `Link` structure elements via object references, and `Formula` elements with alternative text for equations. Which of these Core Graphics can express is **not verified** beyond what the table above lists.5215. **Install veraPDF** on the build machine and add a script that validates exported samples; record its version in the environment table.522523### Risks and open questions524525* Core Graphics PDF/A output has never been validated in this project; the conformance-level discrepancy (header "2u", XMP "2B") is a warning sign in itself.526* Font embedding restrictions (fonts whose license forbids embedding), transparency and colour-space handling under PDF/A are **not verified**.527* PDF outline creation through Core Graphics is undocumented in the SDK header.528* The 27.0-only tagged PDF API is new; its behaviour on edge cases (nested tables, content across pages, links) is **not verified** beyond the single probe.529530---531532## 9. Local AI533534### What was evaluated535536On-device text assistance (rewrite, summarise, proof-read suggestions presented as accept/reject changes) and classical language analysis, with no network use.537538### Options5395401. **Foundation Models framework** (`FoundationModels`): `SystemLanguageModel`, `LanguageModelSession`, guided generation (`@Generable`, `GenerationSchema`), tools.5412. **NaturalLanguage framework**: tokenisation, language identification, lemmatisation and part-of-speech tagging, named entities, word/sentence/contextual embeddings.5423. **Core ML** with a bundled or downloaded model.5434. **MLX** (ml-explore/mlx-swift) with optional downloadable models.544545### Foundation Models: verified facts546547| Topic | Fact | Evidence |548|---|---|---|549| OS availability | `SystemLanguageModel` and `LanguageModelSession` are `@available(macOS 26.0, iOS 26.0, visionOS 26.0, *)`. **They do not exist on macOS 15**, the deployment target. | **SDK**, **Web** (https://developer.apple.com/documentation/foundationmodels/systemlanguagemodel) |550| Hardware / region | "Model availability depends on whether the device and region supports Apple Intelligence." The list of devices is maintained at apple.com/apple-intelligence. Apple silicon is required; Intel Macs are not eligible (**not verified** from that page in this research). | **Web** |551| Availability states | `SystemLanguageModel.Availability`: `.available`, `.unavailable(reason)` with reasons `.deviceNotEligible`, `.appleIntelligenceNotEnabled`, `.modelNotReady` (downloading or "other system reasons"). The enum of reasons is not frozen: handle unknown future cases. `isAvailable` is a convenience. The model object is `Observable`. | **SDK**, **Web** |552| Context window | `contextSize` is back-deployed and returns the constant 4096 before macOS 27; on macOS 27 it returns a device-dependent value. On the build machine (M5 Max, macOS 27.0) it returns **8192**. A WWDC 2026 session shows 4096 on 26.0 and 8192 on 27.0 "for newer devices". Input and output share the window. | **SDK**, **Probe**, **Web** (WWDC26 session 319 as summarised by search; the session itself was **not** read directly) |553| Token counting | `tokenCount(for:)` exists only from macOS 26.4. | **SDK** |554| Model versions | Three model versions so far: OS 26.0–26.3, 26.4, 27.0. "Apple periodically updates `SystemLanguageModel` in routine OS updates." On macOS 27 a `variant` property exists (`core3`, `coreAdvanced3`); the build machine reports "AFM 3 Core Advanced". Output for a given prompt therefore changes with OS updates and between machines. | **Web**, **SDK**, **Probe** |555| Languages | `supportedLanguages` on the build machine: Danish, German, English (AU, GB, IN, US), Spanish (419, ES, US), French (CA, FR), Italian, Japanese, Korean, Norwegian Bokmål, Dutch, Portuguese (BR, PT), Swedish, Turkish, Vietnamese, Chinese (Simplified; Traditional HK and TW). Use `supportsLocale(_:)` at run time; do not hard-code the list. A developer-forum report says the framework is unavailable when the system language is unsupported (secondary source). | **Probe**, **Web** |556| Guided generation | `respond(to:generating:)`, `GenerationSchema`, `@Generable`, `includeSchemaInPrompt`; the schema consumes context tokens. | **SDK** |557| Guardrails | `SystemLanguageModel.Guardrails.default` and `.permissiveContentTransformations`. Guardrail violations and refusals surface as errors; a rewrite request on a document about a sensitive subject can be refused. | **SDK** |558| Errors | `LanguageModelSession.GenerationError` cases (`exceededContextWindowSize`, `assetsUnavailable`, `guardrailViolation`, `unsupportedGenerationGuide`, …) are **deprecated in macOS 27** in favour of `LanguageModelError` and `SystemLanguageModel.Error`. Code must handle both families across OS versions. | **SDK** |559| Adapters | `SystemLanguageModel(adapter:)` is deprecated in 26.4 and **obsoleted in 27.0**. Custom adapters are not an option. | **SDK** |560| **Server-side model in the same framework** | `PrivateCloudComputeLanguageModel` (macOS 27.0+) "runs on Private Cloud Compute", has quotas and network failure errors, and requires a managed entitlement. It is a drop-in replacement for the model argument of `LanguageModelSession`. | **SDK**, **Web** (https://developer.apple.com/documentation/foundationmodels/privatecloudcomputelanguagemodel) |561562### NaturalLanguage: verified on the build machine563564For English, French, German, Spanish, Italian and Portuguese: word embeddings, sentence embeddings, contextual embeddings (`NLContextualEmbedding`) and the lemma tag scheme are all reported available (**Probe**). Contextual embedding assets may need to be downloaded on first use on other machines (`hasAvailableAssets` / `requestAssets`) — **not verified**; a download is network activity initiated by the system and must be acknowledged in the privacy description if triggered.565566### Assessment567568| Criterion | Foundation Models | NaturalLanguage | Core ML (bundled model) | MLX (optional models) |569|---|---|---|---|---|570| Functionality | + rewriting, summarising, structured output within 4k–8k tokens | + deterministic analysis: tokens, lemmas, language, similarity | 0 depends on the model shipped | ++ larger open models, longer context |571| Reliability / reproducibility | − output changes with OS model versions; refusals | ++ | + fixed model | + fixed model |572| Performance | + system-managed, shared model | ++ | + | + needs memory proportional to the model |573| License | Apple SDK; acceptable-use requirements apply (**not verified** in detail) | Apple SDK | Model license | MIT framework (0.33.0, 2026-10-27); model licenses vary |574| Maintenance | + Apple | + | − own model lifecycle | − model downloads, updates |575| Security / privacy | ++ on device (when `SystemLanguageModel` is used) | ++ | ++ | + model files are downloaded data; verify hashes |576| Apple silicon | Required | Works on all | Works on all | Required |577| Notarization | ++ | ++ | ++ | + (Metal shaders, no JIT entitlement expected — **not verified**) |578| Offline | ++ once the system model is present | ++ | ++ | ++ after download; the download itself is a network operation |579| App size | 0 | 0 | −− hundreds of MB to GB | 0 in the app; GB on disk per model |580581### Decision and rationale582583* **Foundation Models (`SystemLanguageModel` only)** for generative features, behind `#available(macOS 26.0, *)` and a run-time availability check.584* **NaturalLanguage** for deterministic checks in `DocAudit` and for retrieval over long documents (chunk selection by embedding similarity).585* **Core ML / MLX**: not in v1.0. An MLX backend can be added later as an explicit, user-initiated model download; it contradicts "no network" unless the user starts it.586587### What must be disabled gracefully588589| Condition | Required behaviour |590|---|---|591| macOS 15.x (no framework) | AI commands hidden or shown disabled with "Requires macOS 26 or later with Apple Intelligence". The package must compile and link with the framework weakly; `DocAutomation`/`DocAudit` must not import `FoundationModels` unconditionally. |592| `.deviceNotEligible` | Same, with the reason. No retry. |593| `.appleIntelligenceNotEnabled` | Explain where to enable it; do not open System Settings without a user action. |594| `.modelNotReady` | "The on-device model is being prepared"; observe availability and re-enable. |595| Unknown future reason | Generic "not available" message. |596| Unsupported document or system language | Disable per request with the reason (`supportsLocale`). |597| Context overflow | Chunk by paragraphs with a token budget (`tokenCount` on 26.4+, a conservative character estimate before), never send a whole long document; handle both the deprecated and the new overflow errors. |598| Guardrail violation / refusal | Show "the model declined this request"; leave the text untouched. |599| Every successful generation | Present as a proposed change (the model already has tracked `Revision`s); never apply silently. |600601### Risks and open questions602603* **`PrivateCloudComputeLanguageModel` must never be instantiated.** It lives in the same framework and is one line away from the on-device model. "Local AI" and "no network" stay true only if the code base uses `SystemLanguageModel` exclusively. Add a source-level check (a test that greps the package for the symbol) and do not request the PCC entitlement.604* **The deployment target excludes AI on macOS 15.** The feature list must say "on macOS 26 or later, on Macs that support Apple Intelligence".605* **4 096 tokens on macOS 26** is a few pages of text including instructions and output. "Summarise this 200-page thesis" requires hierarchical summarisation and will be slow and lossy; set expectations in the UI.606* **Quality is not measured.** No evaluation of the system model on proof-reading or academic rewriting was done; nothing may be claimed about it.607* **Non-determinism across OS updates** makes snapshot tests of model output impossible; test the plumbing with a mock `LanguageModel`.608* **Not verified:** the Apple Intelligence device list, acceptable-use policy wording, behaviour on a Mac whose system language is unsupported, on-first-use asset downloads for NaturalLanguage contextual embeddings.609610---611612## 10. Automation and updates613614### 10a. Automation615616| Option | What it gives | Cost and constraints | Recommendation for v1.0 |617|---|---|---|---|618| **Bundled command-line tool** (`orixdocs`, already an executable target over `DocAutomation`) | Convert, export to PDF, audit, batch processing; usable in scripts and CI; no GUI | Must be signed with hardened runtime and notarized inside the app bundle; installing a symlink into `/usr/local/bin` needs user consent; if the app is sandboxed the tool should **not** inherit the sandbox when run from Terminal (section 12) | **Yes.** It is nearly free given the package design and is the most robust automation surface. |619| **App Intents / Shortcuts** | "Convert document", "Export PDF", "Run audit" actions in Shortcuts, Spotlight and Siri; parameters typed as files (`IntentFile`) | Intents run in the app process or an extension; file access follows the app's sandbox state; intents taking files work headlessly only if the engine can run without a document window (it can) | **Yes, a small set** (3–5 intents wrapping the same `DocAutomation` entry points as the CLI). |620| **AppleScript** (`.sdef`, `NSScriptCommand`, Cocoa scripting) | Object model access (`documents`, `paragraphs`, `make`, `save … as PDF`); `NSDocument` already implements the standard suite's save/close/print handlers | A real text suite over a custom model is a large, long-lived API surface; Cocoa scripting is Objective-C KVC-based and sits awkwardly with Swift 6 value types | **Standard suite only** (open, save, close, print, export) in v1.0; a text object model later, if ever. |621622These three are complementary, not alternatives. Sources: `NSDocument` scripting handlers (**Web**, Apple documentation cited in section 2). App Intents availability and Shortcuts behaviour for non-sandboxed apps were **not verified** against documentation in this research.623624### 10b. Updates625626**Sparkle 2** (https://sparkle-project.org, sparkle-project/Sparkle): latest release **2.10.1 (2026-10-25)**, last push 2026-11-20, 12 open issues/PRs, 9 951 stars (**Web**, GitHub API). License: MIT-style for Sparkle itself, with bundled components under BSD-2-Clause-style (bsdiff/bspatch, signature verifier), MIT-style (sais-lite) and zlib-style (Ed25519) terms (**Web**, repository `LICENSE`; names inferred from the license texts). Updates are authenticated by an EdDSA (Ed25519) signature over the archive, verified against a public key in the app's `Info.plist`, in addition to Apple code signing; the appcast is fetched over HTTPS. Signing of the appcast feed itself is available in recent 2.x releases (**not verified** in this research).627628Sandbox and hardened runtime (**Web**: https://sparkle-project.org/documentation/sandboxing/): Sparkle's XPC services and helpers ship "signed with an ad-hoc signature and Hardened Runtime enabled" and are re-signed on export. A sandboxed app must set `SUEnableInstallerLauncherService`, add a mach-lookup temporary exception for `$(PRODUCT_BUNDLE_IDENTIFIER)-spks` and `-spki`, and optionally enable the downloader service if it lacks the network-client entitlement. A non-sandboxed app needs none of that.629630| Criterion | Sparkle 2 | No updater (manual download) |631|---|---|---|632| Functionality | ++ check, download, verify, install, delta updates, release notes | −− user must notice and reinstall |633| Reliability | ++ de-facto standard outside the App Store | n/a |634| Security | + EdDSA + Developer ID verification; a private key must be protected; the app gains a network client | − users stay on vulnerable versions; + no network code at all |635| License | Permissive (attribution in acknowledgements) | n/a |636| Maintenance | + active; requires hosting an appcast and a release script | ++ none |637| Apple silicon / notarization | ++ universal; nested helpers must be signed (handled by Xcode archive/export; a manual `codesign` pipeline must sign inside-out) | ++ |638| Offline operation | 0 the app works offline; the update check is the app's only network use and must be optional | ++ |639| Consistency with "local-first, no account, no network" | 0 needs explicit disclosure and an off switch | ++ |640641**Recommendation for v1.0: ship Sparkle 2, with update checks that the user explicitly accepts on first launch** (Sparkle's standard permission prompt; `SUEnableAutomaticChecks` left unset so the user is asked), no system-profile submission (`SUEnableSystemProfiling` off), and a visible "Check for Updates…" menu item.642643Reasons: (1) the app opens untrusted DOCX, ZIP, XML, RTF, HTML and PDF with newly written parsers; the realistic way to deliver a parser fix to users is an in-app updater; (2) a v1.0 of this scope will need frequent corrective releases; (3) Sparkle sits in the app target only, so the package's "no network access" rule is unaffected; (4) the privacy statement stays simple and true: "the only network connection the app makes is the optional update check to <host>; no document content, no identifiers".644645Conditions: the EdDSA private key must be kept out of the repository and backed up (losing it strands existing users; leaking it lets an attacker with control of the feed ship updates that still need a valid Developer ID signature to pass Gatekeeper, **not verified** in detail); the appcast host must be HTTPS and under the author's control; the release script must sign nested Sparkle components correctly before notarization. If that infrastructure cannot be ready for 1.0, the fallback is "no updater, plus a manual check that opens the download page" — acceptable, but then the security argument above becomes a known weakness that should be stated in the release notes.646647---648649## 11. Spell checking, grammar, hyphenation, smart quotes650651### Spell and grammar checking with a custom view652653`NSSpellChecker` works without `NSTextView`. Relevant API (**SDK**, `NSSpellChecker.h`): `uniqueSpellDocumentTag()` / `closeSpellDocument(withTag:)`; synchronous `check(_:range:types:options:inSpellDocumentWithTag:orthography:wordCount:)`; asynchronous `requestChecking(of:range:types:options:inSpellDocumentWithTag:completionHandler:)`; `guesses(forWordRange:in:language:inSpellDocumentWithTag:)`; `correction(forWordRange:…)`; `completions(forPartialWordRange:…)`; `learnWord`/`unlearnWord`/`ignoreWord(_:inSpellDocumentWithTag:)`; `menu(for:string:options:atLocation:in:)`; the correction indicator (`showCorrectionIndicator(of:primaryString:alternativeStrings:forStringIn:view:completionHandler:)`); `userQuotesArray(forLanguage:)`; `userReplacementsDictionary`; the class properties `isAutomaticSpellingCorrectionEnabled`, `isAutomaticQuoteSubstitutionEnabled`, `isAutomaticDashSubstitutionEnabled`, `isAutomaticTextReplacementEnabled`, `isAutomaticCapitalizationEnabled`, `isAutomaticPeriodSubstitutionEnabled`, `isAutomaticInlinePredictionEnabled` (macOS 14). New in macOS 27: `ignoreGrammarRange(_:inSentence:inSpellDocumentWithTag:)`. `NSTextCheckingController` with the `NSTextCheckingClient` protocol is the supported bridge for custom text views and drives the standard contextual menu and panels.654655**Probe** (macOS 27.0, French system locale):656657* `availableLanguages` returned 44 entries: `fr`, `en` and ten regional English variants, `ar`, `ars`, `bg`, `cs`, `da`, `de`, `el`, `es`, `fi`, `ga`, `he`, `hi`, `hu`, `id`, `is`, `it`, `ko`, `lt`, `nb`, `nl`, `nn`, `pa`, `pl`, `pt_BR`, `pt_PT`, `ro`, `ru`, `sl`, `sv`, `te`, `tr`, `uk`, `vi`. The list depends on the user's installed dictionaries.658* Checking "Ths is a sentense with with errors. He go to school." with spelling and grammar types returned the two misspellings and one grammar result covering the first sentence (the repeated word). The agreement error "He go" was **not** flagged. The system grammar checker is shallow; the product must not describe it as a grammar checker comparable to Word's Editor or dedicated tools.659* `userQuotesArray(forLanguage:)` returned French guillemets for both `"en"` and `"fr"` on this French-locale machine: the method reflects the **user's** quote preference, not the typographic convention of the language passed. Smart quotes per document language therefore need an own table (language → opening/closing primary and secondary quotes, spacing rules such as the French narrow no-break space) with the system preference as the default for the user's own language.660661What must be built by hand in the custom view: scheduling checks on edited paragraphs only, mapping result ranges through the model (skipping U+FFFC inline objects, deleted tracked text, fields and citations), drawing the underline styles, the contextual menu, the Spelling and Grammar panel protocol (`changeSpelling:`, `ignoreSpelling:`, `checkSpelling:`, `showGuessPanel:`), autocorrection with undo, per-run language (`CharProps` language → `language:` parameter), and keeping the document's ignored-word list.662663### Hyphenation664665`CFStringGetHyphenationLocationBeforeIndex(string, location, limitRange, options, locale, &character)` returns the nearest hyphenation point before an index, and `CFStringIsHyphenationAvailableForLocale(locale)` reports whether data exists; both are available since macOS 10.7; "Hyphenation data is not available for all locales" (**SDK**, `CFString.h`).666667**Probe** (macOS 27.0), 46 locales tested:668669| Hyphenation available (24) | Not available (22) |670|---|---|671| en_US, en_GB, fr_FR, fr_CA, de_DE, es_ES, it_IT, pt_BR, pt_PT, nl_NL, sv_SE, da_DK, nb_NO, fi_FI, pl_PL, cs_CZ, ru_RU, uk_UA, el_GR, hu_HU, ro_RO, ca_ES, hr_HR, sk_SK | tr_TR, sl_SI, bg_BG, lt_LT, lv_LV, et_EE, is_IS, ga_IE, cy_GB, eu_ES, gl_ES, la, af_ZA, id_ID, vi_VN, hi_IN, ar_SA, he_IL, ja_JP, zh_CN, ko_KR, th_TH |672673For "internationalization" (en_US) the function returned index 11 before index 12 with suggested character U+002D. The list may differ on other OS versions; query at run time.674675| Criterion | `CFStringGetHyphenationLocationBeforeIndex` | Bundled TeX hyphenation patterns (own Liang implementation) |676|---|---|---|677| Functionality | + 24 of 46 probed locales; one break point per call | ++ 70+ languages (**not verified** count); all break points per word; user exceptions |678| Reliability / quality | + system dictionaries; quality per language **not verified** | + well-known patterns |679| License | Apple SDK | Per-language pattern licenses (mostly permissive; each must be checked) |680| Maintenance | ++ none | − pattern files to ship and credit |681| Offline / notarization / Apple silicon | ++ | ++ |682683**Decision:** use the Core Foundation function in v1.0, expose hyphenation only for languages where `CFStringIsHyphenationAvailableForLocale` is true, and keep the line breaker's hyphenation interface abstract so that pattern-based hyphenation can be added later. Core Text's own automatic hyphenation (the paragraph-style hyphenation factor) is not usable here because the engine, not `CTFramesetter`, decides line breaks.684685### Risks and open questions686687* Hyphenation minimums (characters before/after the break, no hyphenation of the last word of a paragraph or across pages, consecutive hyphen limit) are engine policy and need settings compatible with Word's (`w:autoHyphenation`, `w:consecutiveHyphenLimit`, `w:hyphenationZone`).688* Non-Latin scripts without hyphenation (CJK, Thai) need dictionary- or rule-based line breaking that `CTTypesetter` provides, **not verified** for quality here.689* **Not verified:** `NSTextCheckingController` behaviour with a non-`NSTextView` client on macOS 15–27; Writing Tools integration effort.690691---692693## 12. Distribution694695### Current notarization requirements (Apple documentation, read 2026-11-21)696697From "Resolving common notarization issues" (https://developer.apple.com/documentation/security/resolving-common-notarization-issues) and "Hardened Runtime" (https://developer.apple.com/documentation/security/hardened-runtime):698699| Requirement | Apple's wording or message |700|---|---|701| Valid code signature on all code | "The signature of the binary is invalid." Verify with `codesign -vvv --deep --strict`. |702| Developer ID certificate | "You can only notarize apps that you sign with a Developer ID certificate." Developer ID Application for apps, tools, disk images; Developer ID Installer for packages. |703| Secure timestamp | "The signature does not include a secure timestamp." Requires `--timestamp` and internet access to `timestamp.apple.com` at signing time. |704| No `get-task-allow` | "The executable requests the com.apple.security.get-task-allow entitlement." Set `CODE_SIGN_INJECT_BASE_ENTITLEMENTS = NO` in custom pipelines. |705| SDK | "notarization only works for binaries linked against macOS 10.9 or later." |706| Hardened runtime | "To upload a macOS app to be notarized, you must enable the Hardened Runtime capability." (`--options=runtime`). |707| Entitlements format | ASCII XML property list, no BOM, not binary plist. |708| Tooling | `notarytool` (Xcode 14 or later); `altool` uploads have been refused since 2023-11-01 (from the notarization overview as returned by search; the overview page itself was not re-read line by line). |709| Stapling | `stapler staple` on the app, disk image or package so Gatekeeper can verify offline. A bare command-line binary cannot be stapled; ship it inside the app bundle or a stapled disk image/package (**not verified** against current documentation). |710711Signing order for this product: nested code first (Sparkle's helpers and XPC services, the `orixdocs` tool, any frameworks), then the app; each with hardened runtime and timestamp; then notarize the disk image or zip; then staple.712713### App Sandbox for a Developer ID app714715The App Sandbox is mandatory for the Mac App Store and optional for Developer ID distribution (**not verified** against a specific Apple sentence in this research; it is long-standing policy). What it would change here:716717| Area | Without sandbox | With sandbox |718|---|---|---|719| Opening and saving documents | Unrestricted within the user's permissions (TCC still protects Desktop/Documents/Downloads on first access) | Through Powerbox open/save panels and `NSDocument`, which work transparently; entitlement `com.apple.security.files.user-selected.read-write` |720| Files next to the document (a `.bib` file, linked images, a template, the DOCX original beside an `.orixdoc`) | Direct access | Not accessible without a separate user grant or related-item declarations; security-scoped bookmarks needed to remember grants; a major source of friction for a "project folder" workflow |721| Recent documents, window restoration | Work | Work (handled by `NSDocumentController`) |722| Fonts | All installed fonts | Same |723| Shortcuts / App Intents with file parameters | Work | Work; files are passed with access rights |724| AppleScript (being scripted) | Works | Works; sending Apple events to other apps needs entitlements |725| Bundled CLI run from Terminal | Reads and writes any path the user can | If the tool is sandboxed it cannot open arbitrary paths given on the command line, which defeats its purpose. The tool must be signed **without** the sandbox entitlement (allowed for Developer ID; not for the App Store) or the CLI must be dropped. |726| Sparkle | Works with default configuration | Requires the installer XPC service and mach-lookup exceptions (section 10) |727| Damage from a parser exploit | Full user-level file and network access | Confined to the container plus files the user opened; no network unless entitled |728| Foundation Models, NaturalLanguage, spell checker | Work | Work (**not verified** for every API) |729730### Decision and rationale731732* **Developer ID Application signature + hardened runtime (no exception entitlements) + notarytool + stapling.** Not negotiable for a downloadable app in 2026; the identity and tooling are in place.733* **App Sandbox: recommended for the GUI app, with the CLI left unsandboxed.** The architect has not recorded a decision. The argument for: the app's whole job is to parse untrusted files with new parsers, and `NSDocument` makes the common paths sandbox-compatible at little cost. The argument against: linked/sibling files and bibliography files need extra user grants, Sparkle setup is more involved, and debugging time is real. If the sandbox is not adopted for 1.0, the mitigations in section 13 carry more weight and the decision should be revisited once the importers have been fuzzed. Either way the app should request **no** network-server entitlement and, if sandboxed, the network-client entitlement only if Sparkle's downloader service is not used.734735### Risks and open questions736737* The Sparkle private key and the notarization credentials are single points of failure for releases; document the recovery procedure.738* A DMG downloaded by a browser is quarantined; first launch goes through Gatekeeper's check. Staple the ticket so the check works offline.739* **Not verified:** current Gatekeeper first-launch behaviour on macOS 27 for notarized Developer ID apps; stapling rules for standalone tools; whether any API used by the app misbehaves under the sandbox.740741---742743## 13. Security requirements for opening untrusted files744745### Platform mechanisms746747| Mechanism | What it does | What the app must do |748|---|---|---|749| Quarantine (`com.apple.quarantine` extended attribute) | Set by browsers, mail clients and AirDrop on downloaded files; Gatekeeper evaluates quarantined **executables and apps**, not documents. A quarantined document opens normally. | Do not strip the attribute. When exporting or converting a quarantined document, propagate quarantine to the output (`LSFileQuarantineEnabled` in `Info.plist` makes files the app creates quarantined; whether that is desirable for a word processor's own saves is a product decision — **not verified** in practice). Never execute or `open` embedded content. |750| Gatekeeper / notarization | Verifies the app, not its documents. | Section 12. |751| Hardened runtime | Blocks code injection, unsigned executable memory, DYLD environment variables, debugging. | Ship with **none** of the runtime exceptions (**Web**: Apple's list): `com.apple.security.cs.allow-jit`, `…allow-unsigned-executable-memory`, `…allow-dyld-environment-variables`, `…disable-library-validation`, `…disable-executable-page-protection`, `…debugger`; and without `com.apple.security.get-task-allow`. Nothing in the chosen stack needs them (no JIT, no plug-ins). Do not add `com.apple.security.automation.apple-events` unless the app sends Apple events. |752| App Sandbox | Confines a compromised process. | Section 12. |753754### Parser rules755756| Risk | Rule | Evidence / status |757|---|---|---|758| ZIP bombs, traversal, duplicate entries | Section 4. Limits exist; duplicate-name rejection is missing. | Code review |759| XML external entities (XXE) | Foundation's `XMLParser.shouldResolveExternalEntities` defaults to `false`; "If you set this property to true, you may cause other I/O operations, either network-based or disk-based" (**Web**: https://developer.apple.com/documentation/foundation/xmlparser/shouldresolveexternalentities). **Probe** (macOS 27.0, default settings): an external entity pointing at a local file was not read. Never set the property to `true`. |760| Entity expansion ("billion laughs") and DTDs in general | **Probe**: nested internal entities expanding to 10^5 characters and to 10^10 characters both aborted parsing with error 111 and delivered no characters; simple internal entities parsed without error but their replacement text was **not delivered** to `parser(_:foundCharacters:)` in the probe's minimal delegate. So the default parser does not explode, but a DTD can make content disappear silently. The Open Packaging Conventions forbid DTD declarations in package parts (**not verified** against the ECMA-376 Part 2 text in this research). **Rule: reject any DOCX/ODT part that contains `<!DOCTYPE`**, before parsing, and report it. |761| Oversized or deeply nested XML | Cap part size (section 4), element depth and attribute count in the SAX delegate; `XMLParser` is event-based, so memory stays bounded if the importer does not build unbounded intermediate trees. | Design rule |762| Macros and active content | `DocFormat` maps `docm` and `dotx` to the DOCX importer (`FormatTypes.swift`). A `.docm` contains `word/vbaProject.bin`. **Rule:** never execute, never parse VBA; import the document content, emit a `FormatWarning` ("macros were present and were not imported"), and never write a macro-enabled file. The same applies to ActiveX controls, OLE embeddings (`word/embeddings/*`), and `DDE`/`DDEAUTO` fields, which must be imported as inert text or dropped with a warning. |763| Remote resources | DOCX relationships with `TargetMode="External"` (linked images, remote templates via `attachedTemplate`, `INCLUDEPICTURE`/`INCLUDETEXT` fields, hyperlinks), HTML `<img src="http…">`, RTF `\field` links, Markdown image URLs. **Rule:** the importers never fetch anything; external images become placeholders with a warning; hyperlinks are kept as inert data and opened only on an explicit user click, with the destination visible. This is also what keeps "no network access in the package" true. |764| Embedded images | Decoding goes through ImageIO, a large attack surface historically. Limit accepted types to those in `Asset` (JPEG, PNG, GIF, TIFF, HEIC, PDF), cap pixel dimensions and file size before decoding, decode with `CGImageSource` thumbnail options for display, and treat embedded PDF and EMF/WMF separately (EMF/WMF: do not render; warn). |765| PDF text import | PDFKit parses hostile PDFs in-process. Extract text only; never run PDF JavaScript (PDFKit does not in this use — **not verified**), never follow launch actions. |766| HTML and RTF import | Do not use `NSAttributedString(html:)` for untrusted HTML: it runs WebKit in-process and can load remote resources (**not verified** on macOS 27 in this research). Use an own tolerant tokenizer limited to a tag whitelist, or a sandboxed web content process without network. RTF: own parser or `NSAttributedString` RTF reader with attachments ignored; `\object`/`\objdata` must be dropped. |767| LaTeX math strings | Treated as hostile input to SwiftMath (section 6): length cap, pre-validation, no traps. |768| JSON model in `.orixdoc` | `JSONDecoder` on a size-capped entry; validate offsets against the "UTF-16, composed-character boundary" invariant after decoding; verify the manifest hashes before decoding; cap array sizes and nesting. A hostile `.orixdoc` is as untrusted as a hostile DOCX. |769| Hyperlinks in the editor | Open only `http`, `https`, `mailto` (and internal anchors) on click; show the target; never pass `file:`, `smb:`, custom schemes or anything executable to `NSWorkspace.open`. |770| Fields | `Field` in the model is a closed enum (page number, page count, date, title, author, sequence, heading text). Keep it closed: no field type that reads files, environment or the network. |771| Crashes | Importers must return errors, never trap: no `!`, `try!`, unchecked indexing or integer overflow on file-derived values in `DocContainer`, `DocDOCX`, `DocFormats`. Fuzz each importer before release. |772773### Risks and open questions774775* The importers do not exist yet (placeholder targets); every rule above is a requirement, not a description of current behaviour.776* SwiftMath is the one third-party parser in the process and has known input-triggered traps at the pinned version (section 6).777* **Not verified:** OPC's exact wording on DTDs; `NSAttributedString(html:)` network behaviour on macOS 27; PDFKit's handling of active PDF content during text extraction; the effect of `LSFileQuarantineEnabled` on ordinary document saves.778779---780781## Summary of decisions782783| # | Decision | Research verdict | Most important risk |784|---|---|---|---|785| 1 | Core Text + own pagination + custom `NSTextInputClient` view | Supported: TextKit 2 still has a single container in the macOS 27.2 SDK | Cost of re-implementing input methods, accessibility, spell checking and system text services |786| 2 | `NSDocument` hosting SwiftUI | Supported | Swift 6 concurrency around asynchronous saving |787| 3 | `.orixdoc` = single-file ZIP + manifest + SHA-256 + JSON | Supported; no extension collision found | Whole-file rewrite and in-memory I/O for image-heavy documents |788| 4 | Own ZIP over the Compression framework | Supported | Duplicate entry names are accepted; ZIP64 files are refused |789| 5 | Own DOCX reader/writer | Supported: nothing usable exists for Swift; the system reader loses footnotes, links, math, styles | Fidelity far below incumbents; round-trip data loss unless saves to DOCX are explicit exports |790| 6 | SwiftMath | Supported with reservations | Pinned release is 15 months old, lacks common commands and crash fixes that exist on `main` |791| 7 | Own formatter for six styles + four parsers | Acceptable for v1.0 | Six styles versus thousands in CSL; no reference-manager integration |792| 8 | Core Graphics PDF + PDFKit post-processing | Supported | PDF/A flag unvalidated and inconsistent; modern tagging API exists only on macOS 27; no validator installed |793| 9 | Foundation Models + NaturalLanguage | Supported with constraints | Unavailable on the deployment target (macOS 15); 4k–8k context; a server-side model sits in the same framework |794| 10 | CLI + small App Intents set + standard AppleScript suite; Sparkle 2 with opt-in checks | Recommended | Key custody and release pipeline |795| 11 | `NSSpellChecker` with custom view; CF hyphenation | Supported | Shallow system grammar checking; hyphenation for about half of the probed locales |796| 12 | Developer ID + hardened runtime + notarization; sandbox recommended for the GUI app | Supported / open | Sandbox decision not yet taken |797| 13 | Hostile-input rules for every importer | Requirements defined | Importers not yet written |798799## Claims not verified in this research800801* Existence and name of the `notarytool` keychain profile (not queried).802* TextKit 2 behaviour with `NSTextTable` inside a window on macOS 27, and on macOS 15–26; Apple's future plans for pagination in TextKit 2; "maintenance mode" status of TextKit 1.803* Effort to support Writing Tools in a custom view (`NSWritingToolsCoordinator`).804* `DocumentGroup` internals and its versions/conflict behaviour.805* Absence of `.orixdoc` in every file-extension registry; trademark implications of the name "ORIX"; absence of a registered `application/vnd.…orixdoc` type.806* How common ZIP64 structures are in real-world DOCX files; reader behaviour on multi-disk archives and prepended data.807* Licenses of docx4j, Open XML SDK, Aspose.Words, LibreOffice components, libarchive (text not read), veraPDF (dual-license detail), citeproc-rs; python-docx's tracked-change coverage; Aspose platform support.808* Licenses of eight of the twelve math fonts bundled with SwiftMath; SwiftMath's claim of rendering "exactly as LaTeX".809* Count of CSL styles; JavaScriptCore performance with citeproc-js; non-existence of a Swift CSL processor beyond one search.810* Whether `PDFDocument.write(to:)` preserves structure trees, output intents and XMP; the dictionary format of `CGPDFContextSetOutline`; the undocumented `CGPDFContextSetParentTree`/`SetIDTree`/`SetPageTagStructureTree`; PDF/A validity of Core Graphics output (no validator run); veraPDF's PDF/UA-2 coverage; availability of Acrobat Preflight and PAC.811* The Apple Intelligence device list and acceptable-use terms; WWDC26 session 319 content (seen only through a search summary); Foundation Models behaviour when the system language is unsupported; asset downloads for NaturalLanguage contextual embeddings; any quality level of the on-device model.812* App Intents behaviour details; Sparkle appcast-signing feature; consequences of a leaked EdDSA key.813* Hyphenation quality per language; number of languages covered by TeX patterns; `NSTextCheckingController` with a custom client.814* The sentence in Apple's documentation stating that the sandbox is optional for Developer ID apps; stapling rules for standalone tools; Gatekeeper first-launch behaviour on macOS 27.815* OPC wording on DTDs; `NSAttributedString(html:)` network behaviour; PDFKit active-content handling; `LSFileQuarantineEnabled` effects.816817## Sources818819Primary, read on 2026-11-21:820821* macOS 27.2 SDK headers and Swift interfaces: `CoreGraphics/CGPDFContext.h`, `CGPDFStructureElement.h`, `CGPDFMarkedContentItem.h`; `AppKit/NSTextLayoutManager.h`, `NSTextContainer.h`, `NSTextView.h`, `NSTextTable.h`, `NSLayoutManager.h`, `NSSpellChecker.h`, `NSTextInputClient.h`, `NSTextCheckingClient.h`; `CoreFoundation/CFString.h`; `CoreText/CTTypesetter.h`, `CTRunDelegate.h`; `FoundationModels.swiftinterface`.822* Apple documentation: https://developer.apple.com/documentation/appkit/nsdocument · https://developer.apple.com/documentation/swiftui/referencefiledocument · https://developer.apple.com/documentation/foundationmodels/systemlanguagemodel · https://developer.apple.com/documentation/foundationmodels/privatecloudcomputelanguagemodel · https://developer.apple.com/documentation/security/resolving-common-notarization-issues · https://developer.apple.com/documentation/security/notarizing-macos-software-before-distribution · https://developer.apple.com/documentation/security/hardened-runtime · https://developer.apple.com/documentation/foundation/xmlparser/shouldresolveexternalentities823* Apple videos and forums: https://developer.apple.com/videos/play/wwdc2026/370/ · https://developer.apple.com/forums/thread/682251824* Repositories (GitHub API and raw files): https://github.com/mgriebling/SwiftMath · https://github.com/kostub/iosMath · https://github.com/weichsel/ZIPFoundation · https://github.com/libarchive/libarchive · https://github.com/KaTeX/KaTeX · https://github.com/mathjax/MathJax · https://github.com/Juris-M/citeproc-js · https://github.com/zotero/citeproc-rs · https://github.com/jgm/citeproc · https://github.com/jgm/pandoc · https://github.com/shinjukunian/DocX · https://github.com/python-openxml/python-docx · https://github.com/plutext/docx4j · https://github.com/veraPDF/veraPDF-library · https://github.com/ml-explore/mlx-swift · https://github.com/sparkle-project/Sparkle825* Sparkle documentation: https://sparkle-project.org/documentation/sandboxing/826* Zotero: https://www.zotero.org/support/word_processor_integration827* Microsoft: https://learn.microsoft.com/en-us/office/pdf/word/wordpdfaccessibility828* Project files: `docs/architecture/overview.md`, `Packages/ORIXDocsKit/Package.swift`, `Package.resolved`, `Sources/DocModel/*`, `Sources/DocContainer/ZipArchive.swift`, `Sources/DocContainer/FormatTypes.swift`.829