SPB Git

Repository Public

technology-evaluation.md 98.3 KB

# Technology evaluation

Status: research input for v1.0. Access date for every URL in this document: 2026-11-21.

This 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.

# How to read the evidence labels

Label Meaning
SDK Read in the headers or .swiftinterface files of the macOS 27.2 SDK installed on the build machine (MacOSX27.2.sdk).
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.
Web Read on the vendor's or project's own page or repository on 2026-11-21.
Not verified Stated from general knowledge or from a secondary source; must be checked before anything depends on it.

Assessment tables use: ++ strong, + adequate, 0 neutral or unknown, − weak, −− blocking. "n/a" means the criterion does not apply.

# 0. Environment

Item Value Evidence
Operating system macOS 27.0 (26A5425a) sw_vers
Machine Apple M5 Max, 18 cores, 48 GB sysctl (hw.ncpu 18, hw.memsize 51 539 607 552)
Xcode 27.2 (27B52) xcodebuild -version
Swift 6.4.2 (swiftlang-6.4.2.1.9), target arm64-apple-macosx27.0.0 swift --version
macOS SDK 27.2 (MacOSX27.2.sdk) xcrun --sdk macosx --show-sdk-version with DEVELOPER_DIR pointing at Xcode
Deployment target macOS 15 (platforms: [.macOS(.v15)]) Packages/ORIXDocsKit/Package.swift
Signing identity Developer ID Application: Simon-Pierre Boucher (3YM54G49SN) present security find-identity -v -p codesigning (hash not recorded)
Notarization Existing notarytool keychain profile Stated in the brief; not verified (not queried, to avoid touching credentials)
Microsoft Word 16.115.1 Info.plist of /Applications/Microsoft Word.app
LibreOffice 26.8.2.2 (soffice) soffice --version
Apple Pages Present as Pages Creator Studio.app /Applications listing; version not read
pandoc 3.9.0.2 (upstream latest release is 3.14, 2026-11-12) pandoc --version; GitHub API
textutil /usr/bin/textutil which
pdffonts, pdftotext /opt/homebrew/bin (Poppler) which
veraPDF, qpdf Not installed which

Two environment facts matter later:

  • 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.
  • No PDF/A or PDF/UA validator is installed. Section 8 depends on one.

The 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.


# 1. Text layout and editing

# What was evaluated

Which 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.

# Options

  1. TextKit 2 — NSTextLayoutManager, NSTextContentStorage, NSTextLayoutFragment, viewport-based layout, used through NSTextView or a custom view.
  2. TextKit 1 — NSLayoutManager with an array of NSTextContainers, NSTextTable, NSTextView per container.
  3. Core Text — CTTypesetter, CTLine, CTRun, CTRunDelegate, with a custom pagination engine and a custom NSView that implements NSTextInputClient (architect's decision).

# Findings

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).

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.

TextKit 1 paginates, with limits. NSLayoutManager accepts many NSTextContainers 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).

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.

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.

# Assessment

Criterion TextKit 2 TextKit 1 Core Text + own engine
Functionality for pagination −− single container; no footnotes, table splitting, keeps − multi-container only; the rest must be built ++ whatever is implemented; nothing is free
Editing features for free (IME, selection, spelling, accessibility, Writing Tools) ++ ++ −− all by hand
Reliability + (Apple-maintained) + (mature) 0 depends entirely on own tests
Performance on long documents + viewport layout 0 full layout 0 own incremental layout required
Same layout for screen and PDF − printing path differs + ++ one renderer draws into any CGContext
License Apple SDK Apple SDK Apple SDK
Maintenance Apple Apple, in maintenance mode (not verified as an official statement) Own team, permanent
Security n/a n/a Own code parses nothing external at this layer
Apple silicon ++ ++ ++
Notarization ++ ++ ++
Offline ++ ++ ++

# Decision (architect) and rationale

Core 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).

The 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.

# Costs of the decision (must be budgeted, none is optional)

Area What NSTextView provides and the custom view must implement
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.
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).
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.
Spell and grammar checking NSSpellChecker requests, underline drawing, contextual menu, panels, autocorrection, text replacement, smart quotes/dashes (section 11).
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.
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.
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.
Undo Coalescing of typing, integration with NSDocument's UndoManager (the value-type model makes snapshots cheap, see overview.md).

# Risks and open questions

  • 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.
  • 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.
  • 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).
  • 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.

# 2. Document architecture

# What was evaluated

How the app owns files: open, save, autosave, versions, conflicts, windows and undo.

# Options

  1. NSDocument subclass hosting SwiftUI views through NSHostingController / NSHostingView (architect's decision).
  2. SwiftUI DocumentGroup with FileDocument (value type).
  3. SwiftUI DocumentGroup with ReferenceFileDocument (reference type with snapshots).

# Findings

  • 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(_:).
  • 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.
  • 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.

# Assessment

Criterion NSDocument + SwiftUI views DocumentGroup + FileDocument DocumentGroup + ReferenceFileDocument
Autosave in place ++ autosavesInPlace, explicit control of timing + automatic, not configurable + automatic, driven by undo registration
Versions browser ++ preservesVersions, browseVersions + inherited, not controllable (not verified) + same
Conflict detection / file coordination ++ NSFilePresenter callbacks can be overridden 0 handled internally, no hooks 0 same
Asynchronous saving ++ canAsynchronouslyWrite + unblockUserInteraction after taking a snapshot − fileWrapper is called with a value copy; large serialisations are opaque + snapshot then background serialisation
Custom window chrome, multiple windows per document, inspectors ++ NSWindowController − limited to scene modifiers − same
Control over undo ++ own UndoManager policy (snapshot stack of model values) − automatic, whole-value − must register every change
Import with warnings sheet, export accessory views, "Save As" type lists ++ prepareSavePanel, writableTypes(for:) − −
AppleScript document suite ++ built in −− not exposed −− not exposed
Reliability ++ 20+ years in production apps + +
License / notarization / Apple silicon / offline Apple SDK, no impact same same
Maintenance cost 0 more code, Objective-C-era callback APIs under Swift 6 strict concurrency ++ least code +

# Decision (architect) and rationale

NSDocument hosting SwiftUI. The research supports it: the product needs asynchronous saving of a ZIP container, an import path that reports FormatWarnings before the document becomes editable, a controlled undo stack, custom windows, and AppleScript; DocumentGroup hides each of these.

# Risks and open questions

  • 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.
  • Autosave cost. Autosave in place rewrites the whole .orixdoc (section 3). For documents with many images, measure before enabling autosavesInPlace unconditionally.
  • Not verified: exact behaviour of DocumentGroup regarding versions and conflict UI on macOS 15–27.

# 3. Native format .orixdoc

# What was evaluated

The on-disk format for native documents.

# Options

  1. Single-file ZIP container with a manifest, a SHA-256 per entry and a JSON model (architect's decision).
  2. Directory package (NSFileWrapper bundle with LSTypeIsPackage).
  3. SQLite database file.
  4. ODF (.odt) as the native format.
  5. DOCX as the native format.

# Assessment

Criterion ZIP + JSON Directory package SQLite ODF native DOCX native
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
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 ++ ++
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 ++ ++
Incremental save performance − whole archive rewritten on every save ++ only changed files rewritten ++ page-level writes − −
Inspectability / recoverability ++ unzip + JSON ++ 0 needs tooling + +
License Own Own Public domain OASIS standard, free to implement ECMA-376 / ISO 29500, free to implement
Maintenance + own schema with schemaVersion + 0 schema migrations −− tracks a 1 000-page standard −− tracks a 5 000-page standard plus Word behaviour
Security (hostile file) + small attack surface: own ZIP reader, JSONDecoder + path handling inside the package − SQLite on untrusted files needs defensive configuration − XML − XML
Apple silicon / notarization / offline No impact same same same same

# Decision (architect) and rationale

Single-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.

# Extension and type identifier

  • 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.
  • 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).
  • 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).

# Risks and open questions

  • 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.
  • 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.
  • 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).
  • Forward compatibility. FormatError.unsupportedVersion exists; decide now whether unknown JSON keys from a newer minor version are preserved or dropped on save.

# 4. ZIP implementation

# What was evaluated

How .orixdoc and .docx containers are read and written.

# Options

  1. 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).
  2. ZIPFoundation (https://github.com/weichsel/ZIPFoundation).
  3. libarchive (https://github.com/libarchive/libarchive), which also ships with macOS without public headers in the SDK (not verified).
  4. NSFileCoordinator with .forUploading, which makes the system zip a directory, and other tricks (/usr/bin/zip, ditto subprocesses).

# Library state (GitHub API, 2026-11-21)

Library Latest release License Last push Open issues + PRs Notes
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)
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)

# Assessment

Criterion Own reader/writer ZIPFoundation libarchive NSFileCoordinator / subprocess
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
Reliability 0 new code; depends on tests + widely used + very widely used − undocumented output details
Performance + in-memory, one-shot decode + streaming ++ −
License Own MIT BSD Apple
Maintenance 0 ~270 lines owned + upstream active + upstream active n/a
Security ++ limits are explicit and auditable; minimal surface 0 caller must add limits and name validation − large C surface, regular CVEs 0
Apple silicon / notarization ++ ++ pure Swift + must be built and signed ++
Offline ++ ++ ++ ++
Dependency policy ("no third-party dependency except SwiftMath") ++ − − ++

# Decision (architect) and rationale

Own 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.

# Security review of the current implementation

Read from ZipArchive.swift on 2026-11-21.

Threat Current behaviour Assessment
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.
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.
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.
Encrypted entries Rejected (general-purpose bit 0) Correct; state it in the UI ("password-protected documents are not supported").
Unsupported methods Only 0 and 8 accepted Correct.
ZIP64 Rejected when a size field is 0xFFFFFFFF; writer refuses to produce it Acceptable, with the risk below.
CRC CRC-32 verified on every read Good.
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).
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.
Multi-disk archives, EOCD in a comment, prepended data Not examined in this review Not verified. Add corpus tests.

# Risks and open questions

  • 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".
  • 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.
  • 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.

# 5. DOCX

# What was evaluated

How to read and write WordprocessingML (.docx) with tracked changes, comments, footnotes, tables, styles, numbering, fields, sections and images mapped to and from DocModel.

# Options surveyed

Option What it is State on 2026-11-21 License Fit
Own reader/writer (DocDOCX) Swift, over DocContainer and an XML parser Placeholder target Own Architect's decision
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
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)
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)
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)
Open XML SDK .NET library from Microsoft Not verified MIT (not verified) Requires a bundled .NET runtime
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
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
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

# Probe: what NSAttributedString keeps from a DOCX

A 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.

Feature in the source Result after reading
Body text, bold, italic Kept
Table Kept as NSTextTable blocks
Footnote Lost entirely (reference and text)
Hyperlink Text kept, link attribute lost (0 .link attributes)
Inline and display equations (OMML) Lost (the sentence reads "inline math ." with nothing in between)
Heading and title styles Lost: every run is Times 12 pt; no style names; only NSFont and NSParagraphStyle attributes
Numbered list Turned into bullets ("•")
Written back Archive contains document.xml, a theme and core/app properties; no styles.xml, numbering.xml, footnotes.xml or comments.xml

This confirms that the system reader is not a basis for a word processor. It remains useful as a last-resort text extractor.

# Assessment

Criterion Own reader/writer NSAttributedString LibreOfficeKit pandoc subprocess docx4j / python-docx Aspose
Functionality (maps to DocModel, tracked changes, comments, notes, fields) + what is implemented; explicit FormatWarnings for the rest −− + via an intermediate format; mapping to DocModel still required − 0 +
Reliability on real-world files 0 unproven until the corpus is large + never crashes, loses silently ++ + + ++ (vendor claim, not verified)
Performance ++ native, in-process ++ − process/library start-up, large memory − subprocess −− runtime start-up 0
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
Maintenance −− permanent, large ++ 0 track upstream 0 0 + vendor
Security + hostile-input rules applied in own code (section 13) + − very large C++ attack surface 0 0 0
Apple silicon ++ ++ + arm64 builds exist + + not verified
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
Offline ++ ++ ++ ++ ++ ++

# Decision (architect) and rationale

Own 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).

# Risks and open questions

  • 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 FormatWarnings prominently instead of presenting an import as faithful.
  • 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.
  • 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).
  • 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.
  • Not verified: licensing details of docx4j, Open XML SDK, Aspose and the individual LibreOffice components; python-docx's coverage of tracked changes.

# 6. Math

# What was evaluated

Typesetting of LaTeX math stored in the model (Equation), inline and display, drawn into the same Core Graphics context as the page (screen and PDF).

# Options and library state (GitHub API and repository contents, 2026-11-21)

Option Latest release License Activity Rendering Notes
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
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
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
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
Bundled TeX engine — LPPL / GPL / mixed — DVI/PDF Hundreds of MB for a usable distribution; subprocess; not evaluated in depth
Own implementation over the OpenType MATH table — Own — Core Text Full control; months of work to reach SwiftMath's current state

# SwiftMath in detail

Verified in the checkout used by the build (.build/checkouts/SwiftMath, revision fa8244e, tag 1.7.3) and against upstream main:

  • 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".
  • Environments found in the 1.7.3 source: matrix, pmatrix, bmatrix, Bmatrix, vmatrix, Vmatrix, eqalign, split, aligned, gather, displaylines, eqnarray, cases.
  • 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.
  • 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).
  • Still absent on main: \underbrace/\overbrace, \overset/\underset/\stackrel, \boxed, \cancel, \phantom, \xrightarrow, \tag, \newcommand, align, array.
  • 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.
  • 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.
  • 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).
  • 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.
  • Text in math: "no language support for other than west European languages and some Cyrillic characters" (README).

# Assessment

Criterion SwiftMath iosMath KaTeX / MathJax in WKWebView Bundled TeX Own MATH-table engine
Functionality (LaTeX coverage) 0 common school/undergraduate math; gaps listed above 0 similar ++ ++ 0 → + over time
Vector output in the page's CGContext (screen = PDF) ++ ++ −− web view; needs SVG-to-path conversion or bitmap snapshots + PDF fragments to embed ++
Reliability − reachable traps at the pinned version 0 + + 0
Performance ++ in-process ++ − web process, asynchronous −− subprocess ++
License MIT + font licenses to document MIT MIT / Apache-2.0 mixed, heavy Own
Maintenance 0 single maintainer; no release for 15 months despite 111 commits 0 ++ + −−
Security 0 parser of user-controlled strings with traps 0 + sandboxed web content process; JavaScript engine in the app − +
Apple silicon / notarization / offline ++ pure Swift, resources only + Objective-C + (bundled JS, no network) − many binaries ++

# Decision (architect) and rationale

SwiftMath, 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.

# Risks and open questions

  • 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.
  • 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.
  • 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.
  • 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).
  • Not verified: rendering equivalence with LaTeX ("rendered exactly as LaTeX would render them" is the README's claim, not a measured result).

# 7. Citations and bibliography

# What was evaluated

Parsing 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.

# Reference formats

Format What it expresses well Limits relevant to the importer
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
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
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
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

DocModel stores BibEntry values with PersonNames; 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.

# Formatting options and state (GitHub API, 2026-11-21)

Option State License Notes
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
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)
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
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
A Swift CSL processor None found — One web search returned only the Haskell library; the Swift Package Index was not searched exhaustively

The 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.

# Assessment

Criterion Own fixed-style formatter citeproc-js in JavaScriptCore pandoc/citeproc subprocess
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 ++
Reliability / correctness 0 correctness per style must be proven against the official manuals and the CSL test fixtures ++ reference implementation ++
Performance ++ + −
License ++ − CPAL attribution or AGPL − GPL (pandoc) / needs a Haskell binary
Maintenance − style manuals change (APA 7 → 8 one day) + upstream +
Security ++ 0 a JavaScript engine evaluating bundled code only 0
Apple silicon / notarization / offline ++ ++ +
Dependency policy ++ − −

# Decision (architect) and rationale

Own 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.

# Risks and open questions

  • 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.
  • "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.
  • 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).
  • 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.
  • Not verified: JavaScriptCore performance for citeproc-js; whether CPAL's attribution requirement is acceptable for this product.

# 8. PDF output

# What was evaluated

Producing PDF from the page renderer, with document outline, metadata, links, tagged structure, and the possibility of PDF/A and PDF/UA output.

# Approach (architect)

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.

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.

# What Core Graphics offers (macOS 27.2 SDK headers, plus a probe on macOS 27.0)

Capability API Availability Evidence and notes
Info dictionary (title, author, subject, keywords, creator) kCGPDFContextTitle, …Author, …Subject, …Keywords, …Creator macOS 10.4–10.5 SDK
XMP metadata CGPDFContextAddDocumentMetadata macOS 10.7 SDK
URL links CGPDFContextSetURLForRect (Swift: CGContext.setURL(_:for:)) macOS 10.4 SDK; Probe: produces a /URI action
Internal destinations and links CGPDFContextAddDestinationAtPoint, CGPDFContextSetDestinationForRect macOS 10.4 SDK; needed for cross-references, table of contents and footnote links
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.
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).
Linearization kCGPDFContextCreateLinearizedPDF macOS 11.0 SDK
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.
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.
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)
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).
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.
Lower-level hooks CGPDFContextSetParentTree, CGPDFContextSetIDTree, CGPDFContextSetPageTagStructureTree No availability annotation SDK; undocumented in the header; not verified

What 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.

# Validators

Validator License / cost What it checks State
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
Adobe Acrobat Pro Preflight Commercial PDF/A, PDF/X, PDF/UA syntax checks, fix-ups Not available on the build machine (not verified)
PAC (PDF Accessibility Checker) Free, Windows only (not verified) PDF/UA (Matterhorn Protocol) Not usable locally

A 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).

# Assessment

Criterion Core Graphics CGPDFContext + PDFKit Alternative: own PDF writer Alternative: print system (NSPrintOperation to PDF)
Functionality + vector text, fonts, images, links, tags; outline via PDFKit ++ full control of every object − no tags, no control of structure
Same renderer as the screen ++ − second backend +
Reliability ++ system PDF generator − new code ++
PDF/A 0 a flag exists; output unvalidated; header and metadata disagree on the level + possible with full control, large effort −
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) + −−
License / Apple silicon / notarization / offline Apple SDK Own Apple SDK
Maintenance + −− +

# Decision (architect) and rationale

Core 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.

# Requirements that follow from the findings

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. Install veraPDF on the build machine and add a script that validates exported samples; record its version in the environment table.

# Risks and open questions

  • 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.
  • Font embedding restrictions (fonts whose license forbids embedding), transparency and colour-space handling under PDF/A are not verified.
  • PDF outline creation through Core Graphics is undocumented in the SDK header.
  • 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.

# 9. Local AI

# What was evaluated

On-device text assistance (rewrite, summarise, proof-read suggestions presented as accept/reject changes) and classical language analysis, with no network use.

# Options

  1. Foundation Models framework (FoundationModels): SystemLanguageModel, LanguageModelSession, guided generation (@Generable, GenerationSchema), tools.
  2. NaturalLanguage framework: tokenisation, language identification, lemmatisation and part-of-speech tagging, named entities, word/sentence/contextual embeddings.
  3. Core ML with a bundled or downloaded model.
  4. MLX (ml-explore/mlx-swift) with optional downloadable models.

# Foundation Models: verified facts

Topic Fact Evidence
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)
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
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
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)
Token counting tokenCount(for:) exists only from macOS 26.4. SDK
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
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
Guided generation respond(to:generating:), GenerationSchema, @Generable, includeSchemaInPrompt; the schema consumes context tokens. SDK
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
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
Adapters SystemLanguageModel(adapter:) is deprecated in 26.4 and obsoleted in 27.0. Custom adapters are not an option. SDK
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)

# NaturalLanguage: verified on the build machine

For 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.

# Assessment

Criterion Foundation Models NaturalLanguage Core ML (bundled model) MLX (optional models)
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
Reliability / reproducibility − output changes with OS model versions; refusals ++ + fixed model + fixed model
Performance + system-managed, shared model ++ + + needs memory proportional to the model
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
Maintenance + Apple + − own model lifecycle − model downloads, updates
Security / privacy ++ on device (when SystemLanguageModel is used) ++ ++ + model files are downloaded data; verify hashes
Apple silicon Required Works on all Works on all Required
Notarization ++ ++ ++ + (Metal shaders, no JIT entitlement expected — not verified)
Offline ++ once the system model is present ++ ++ ++ after download; the download itself is a network operation
App size 0 0 −− hundreds of MB to GB 0 in the app; GB on disk per model

# Decision and rationale

  • Foundation Models (SystemLanguageModel only) for generative features, behind #available(macOS 26.0, *) and a run-time availability check.
  • NaturalLanguage for deterministic checks in DocAudit and for retrieval over long documents (chunk selection by embedding similarity).
  • 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.

# What must be disabled gracefully

Condition Required behaviour
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.
.deviceNotEligible Same, with the reason. No retry.
.appleIntelligenceNotEnabled Explain where to enable it; do not open System Settings without a user action.
.modelNotReady "The on-device model is being prepared"; observe availability and re-enable.
Unknown future reason Generic "not available" message.
Unsupported document or system language Disable per request with the reason (supportsLocale).
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.
Guardrail violation / refusal Show "the model declined this request"; leave the text untouched.
Every successful generation Present as a proposed change (the model already has tracked Revisions); never apply silently.

# Risks and open questions

  • 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.
  • The deployment target excludes AI on macOS 15. The feature list must say "on macOS 26 or later, on Macs that support Apple Intelligence".
  • 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.
  • Quality is not measured. No evaluation of the system model on proof-reading or academic rewriting was done; nothing may be claimed about it.
  • Non-determinism across OS updates makes snapshot tests of model output impossible; test the plumbing with a mock LanguageModel.
  • 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.

# 10. Automation and updates

# 10a. Automation

Option What it gives Cost and constraints Recommendation for v1.0
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.
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).
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.

These 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.

# 10b. Updates

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).

Sandbox 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.

Criterion Sparkle 2 No updater (manual download)
Functionality ++ check, download, verify, install, delta updates, release notes −− user must notice and reinstall
Reliability ++ de-facto standard outside the App Store n/a
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
License Permissive (attribution in acknowledgements) n/a
Maintenance + active; requires hosting an appcast and a release script ++ none
Apple silicon / notarization ++ universal; nested helpers must be signed (handled by Xcode archive/export; a manual codesign pipeline must sign inside-out) ++
Offline operation 0 the app works offline; the update check is the app's only network use and must be optional ++
Consistency with "local-first, no account, no network" 0 needs explicit disclosure and an off switch ++

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.

Reasons: (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 ; no document content, no identifiers".

Conditions: 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.


# 11. Spell checking, grammar, hyphenation, smart quotes

# Spell and grammar checking with a custom view

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.

Probe (macOS 27.0, French system locale):

  • 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.
  • 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.
  • 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.

What 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.

# Hyphenation

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).

Probe (macOS 27.0), 46 locales tested:

Hyphenation available (24) Not available (22)
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

For "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.

Criterion CFStringGetHyphenationLocationBeforeIndex Bundled TeX hyphenation patterns (own Liang implementation)
Functionality + 24 of 46 probed locales; one break point per call ++ 70+ languages (not verified count); all break points per word; user exceptions
Reliability / quality + system dictionaries; quality per language not verified + well-known patterns
License Apple SDK Per-language pattern licenses (mostly permissive; each must be checked)
Maintenance ++ none − pattern files to ship and credit
Offline / notarization / Apple silicon ++ ++

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.

# Risks and open questions

  • 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).
  • Non-Latin scripts without hyphenation (CJK, Thai) need dictionary- or rule-based line breaking that CTTypesetter provides, not verified for quality here.
  • Not verified: NSTextCheckingController behaviour with a non-NSTextView client on macOS 15–27; Writing Tools integration effort.

# 12. Distribution

# Current notarization requirements (Apple documentation, read 2026-11-21)

From "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):

Requirement Apple's wording or message
Valid code signature on all code "The signature of the binary is invalid." Verify with codesign -vvv --deep --strict.
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.
Secure timestamp "The signature does not include a secure timestamp." Requires --timestamp and internet access to timestamp.apple.com at signing time.
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.
SDK "notarization only works for binaries linked against macOS 10.9 or later."
Hardened runtime "To upload a macOS app to be notarized, you must enable the Hardened Runtime capability." (--options=runtime).
Entitlements format ASCII XML property list, no BOM, not binary plist.
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).
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).

Signing 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.

# App Sandbox for a Developer ID app

The 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:

Area Without sandbox With sandbox
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
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
Recent documents, window restoration Work Work (handled by NSDocumentController)
Fonts All installed fonts Same
Shortcuts / App Intents with file parameters Work Work; files are passed with access rights
AppleScript (being scripted) Works Works; sending Apple events to other apps needs entitlements
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.
Sparkle Works with default configuration Requires the installer XPC service and mach-lookup exceptions (section 10)
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
Foundation Models, NaturalLanguage, spell checker Work Work (not verified for every API)

# Decision and rationale

  • 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.
  • 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.

# Risks and open questions

  • The Sparkle private key and the notarization credentials are single points of failure for releases; document the recovery procedure.
  • A DMG downloaded by a browser is quarantined; first launch goes through Gatekeeper's check. Staple the ticket so the check works offline.
  • 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.

# 13. Security requirements for opening untrusted files

# Platform mechanisms

Mechanism What it does What the app must do
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.
Gatekeeper / notarization Verifies the app, not its documents. Section 12.
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.
App Sandbox Confines a compromised process. Section 12.

# Parser rules

Risk Rule Evidence / status
ZIP bombs, traversal, duplicate entries Section 4. Limits exist; duplicate-name rejection is missing. Code review
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.
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.
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
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.
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.
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).
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.
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.
LaTeX math strings Treated as hostile input to SwiftMath (section 6): length cap, pre-validation, no traps.
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.
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.
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.
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.

# Risks and open questions

  • The importers do not exist yet (placeholder targets); every rule above is a requirement, not a description of current behaviour.
  • SwiftMath is the one third-party parser in the process and has known input-triggered traps at the pinned version (section 6).
  • 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.

# Summary of decisions

# Decision Research verdict Most important risk
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
2 NSDocument hosting SwiftUI Supported Swift 6 concurrency around asynchronous saving
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
4 Own ZIP over the Compression framework Supported Duplicate entry names are accepted; ZIP64 files are refused
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
6 SwiftMath Supported with reservations Pinned release is 15 months old, lacks common commands and crash fixes that exist on main
7 Own formatter for six styles + four parsers Acceptable for v1.0 Six styles versus thousands in CSL; no reference-manager integration
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
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
10 CLI + small App Intents set + standard AppleScript suite; Sparkle 2 with opt-in checks Recommended Key custody and release pipeline
11 NSSpellChecker with custom view; CF hyphenation Supported Shallow system grammar checking; hyphenation for about half of the probed locales
12 Developer ID + hardened runtime + notarization; sandbox recommended for the GUI app Supported / open Sandbox decision not yet taken
13 Hostile-input rules for every importer Requirements defined Importers not yet written

# Claims not verified in this research

  • Existence and name of the notarytool keychain profile (not queried).
  • 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.
  • Effort to support Writing Tools in a custom view (NSWritingToolsCoordinator).
  • DocumentGroup internals and its versions/conflict behaviour.
  • Absence of .orixdoc in every file-extension registry; trademark implications of the name "ORIX"; absence of a registered application/vnd.…orixdoc type.
  • How common ZIP64 structures are in real-world DOCX files; reader behaviour on multi-disk archives and prepended data.
  • 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.
  • Licenses of eight of the twelve math fonts bundled with SwiftMath; SwiftMath's claim of rendering "exactly as LaTeX".
  • Count of CSL styles; JavaScriptCore performance with citeproc-js; non-existence of a Swift CSL processor beyond one search.
  • 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.
  • 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.
  • App Intents behaviour details; Sparkle appcast-signing feature; consequences of a leaked EdDSA key.
  • Hyphenation quality per language; number of languages covered by TeX patterns; NSTextCheckingController with a custom client.
  • 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.
  • OPC wording on DTDs; NSAttributedString(html:) network behaviour; PDFKit active-content handling; LSFileQuarantineEnabled effects.

# Sources

Primary, read on 2026-11-21:

Files main
Menu

Theme