Repository Public
1<!--2ORIX Docs3File: docs/development/automation.md4Author: Simon-Pierre Boucher5Contact: contact@spboucher.ai6-->7# Automation89ORIX Docs can be driven without its windows in three ways, all on the same engine (`Packages/ORIXDocsKit/Sources/DocAutomation`):1011| Surface | Where | For |12|---|---|---|13| Workflows | the **Workflows…** command in the app, `orixdocs workflow run` | Repeatable sequences of document operations, on one document or a batch |14| `orixdocs` | the package's executable target | Scripts, CI, the terminal |15| Shortcuts actions | App Intents in the app | Shortcuts, Spotlight, Siri |1617Everything runs on this Mac. No step, command or action opens a network connection, runs a script or starts another program.1819## Workflows2021A workflow is a name and an ordered list of steps. `WorkflowRunner` executes it on one input (`run`) or on many files with bounded concurrency (`runBatch`).22Each execution produces a `WorkflowRun` record: start and end, the outcome, duration and detail of every step, the warnings of the converters (tagged with their step), the files written, the audit summary and, on failure, a structured error naming the step and the file.2324* **Progress.** A callback receives, per step, the index, the plain-language name and the fraction done; a batch also reports which file.25* **Cancellation** is cooperative: the task's cancellation is checked before every step and before every new file of a batch. A step in progress finishes; nothing is left half-written (files are written atomically).26* **Failures in a batch** do not stop the other files. Every input gets a record, in input order.27* **Existing files** are never overwritten unless asked: the runner's policy is `fail` (default; used by the tool), `rename` (“name 2.pdf”; used by the app) or `overwrite` (`--force`, “Replace files that already exist”). A workflow can never replace its own input file.28* **History.** Runs are appended to `~/Library/Application Support/ORIX Docs/Automation/history.json` (newest first, the 200 most recent). `ORIX_AUTOMATION_HOME` moves that folder (tests, CI).29* **Saved workflows** are JSON files in `~/Library/Application Support/ORIX Docs/Automation/Workflows/`. The sheet's *Add Workflow File…* validates a file and copies it there.3031### JSON format3233```json34{35 "name": "Thesis to PDF",36 "summary": "House style for theses.",37 "steps": [38 { "type": "import" },39 { "type": "applyTemplateStyles", "template": "thesis" },40 { "type": "setPageSetup", "paper": "a4", "margins": 72, "marginLeft": 90 },41 { "type": "acceptAllChanges" },42 { "type": "removeComments" },43 { "type": "tableOfContents", "maxLevel": 2 },44 { "type": "setCitationStyle", "style": "apa" },45 { "type": "insertBibliography" },46 { "type": "audit", "profile": "academic", "failOnErrors": true },47 { "type": "export", "format": "pdf", "fileName": "pdf/{name}.pdf", "pdf": { "outline": true, "tagged": true } },48 { "type": "writeAuditReport", "format": "json" }49 ]50}51```5253`name` and `steps` are required; `id` (defaults to a slug of the name) and `summary` are optional. The file must be smaller than 1 MB.5455### Step catalogue5657| `type` | Keys | What it does |58|---|---|---|59| `import` | `path` (optional) | Reads the document. Without `path`, takes the input of the run (a file of the batch, or the open document). Any readable format: `orixdoc`, `docx`, `rtf`, `txt`, `md`, `html`, `pdf` (text). Import warnings are recorded. |60| `applyTheme` | `theme` | Re-derives the built-in styles from a theme: ORIX, Classic, Modern, Academic, Editorial, Technical. |61| `applyTemplateStyles` | `template` | Replaces the style sheet with a template's (`blank`, `business-letter`, `academic-paper`, `research-report`, `thesis`, `proposal`, `financial-report`, `legal-memorandum`, `meeting-minutes`, `resume`, `cover-letter`, `technical-manual`, `book-manuscript`, `project-report`, `invoice`, `newsletter`). Paragraphs keep their style id, so a Heading 1 takes the template's Heading 1; styles the template does not define are carried over. |62| `setPageSetup` | `paper`, `orientation`, `margins`, `marginTop`, `marginBottom`, `marginLeft`, `marginRight` | Applies to every section. Paper: `a4`, `letter`, `legal`, `a5`, `b5`, `tabloid`, `trade`. Orientation: `portrait` or `landscape`. Margins in points (0–1000). Absent keys are left alone. |63| `acceptAllChanges` / `rejectAllChanges` | — | Resolves every tracked change. Skipped when there is none. |64| `removeComments` | — | Removes all comments and their anchors. |65| `tableOfContents` | `title`, `maxLevel` (1–9, default 3) | Inserts a table of contents after the title block when the document has headings and no contents; an existing one gets `maxLevel` (and `title` when given). |66| `insertBibliography` | `title` | Appends the bibliography when the document cites sources and has none. Cited keys without a reference are reported as a warning. |67| `setCitationStyle` | `style` | `apa`, `chicago-author-date`, `mla`, `ieee`, `numeric`, `vancouver`. |68| `recalculateTables` | — | Recalculates every table formula. |69| `setMetadata` | `title`, `author`, `subject`, `keywords`, `language` | Sets the given document properties. |70| `audit` | `profile` (`standard`, `academic`, `business`, `minimal`), `failOnErrors` | Runs the document auditor with the facts of a real pagination. With `failOnErrors`, a finding of severity `error` stops the workflow. |71| `export` | `format`, `fileName`, `pdf` | Writes the document into the output folder. `format`: `orixdoc`, `docx`, `pdf`, `rtf`, `markdown`, `html`, `txt`. `fileName` may contain `{name}` (the input name) and subfolders; default `{name}.<ext>`. `pdf`: `outline`, `tagged`, `cropMarks`, `bleed`, `firstPage`, `lastPage`. Export warnings are recorded. |72| `writeAuditReport` | `format` (`md` by default, `json`, or any export format), `fileName` | Writes the findings of the last `audit` step next to the output (default `{name}-audit.<ext>`). Skipped when no audit ran. |7374A step that has nothing to do (no tracked changes, no citations…) is recorded as *skipped*, not failed.7576### Built-in workflows7778| Id | Steps |79|---|---|80| `docx-to-styled-pdf` | import, apply the ORIX theme, contents, audit, export PDF |81| `markdown-to-pdf` | import, styles of the Research Report template, A4 with 72 pt margins, contents, bibliography, export PDF |82| `clean-review-copy` | import, accept all changes, remove comments, recalculate tables, export `{name}-clean.docx` |83| `audit-only` | import, audit, write the report as Markdown and as JSON |8485## Security8687* **No script execution.** The step types above are the whole vocabulary. A workflow file with any other `type` (`shell`, `runScript`, …) is rejected when it is loaded, before any input is read. The engine contains no process spawning, no AppleScript and no network code; a test (`OnDeviceOnlyTests.noNetworkCodeInAutomationOrIntelligence`) scans the sources for those APIs.88* **Path confinement.** Output names are relative to the output folder. A name that is absolute, starts with `~`, or contains `..`, `.` or empty components is rejected at load time (`pathEscapesOutputFolder`). At run time the destination is resolved again, symbolic links included, and refused if it lands outside the folder; `{name}` is sanitised so an input name cannot carry a path.89* **Reading.** `import` with a `path` reads that file and nothing else; Markdown and HTML may load images only from the folder of the source file, and never from the network (`DocumentConverter`).90* **Hostile input.** Importers treat files as untrusted (size limits, defensive ZIP reader); a damaged file fails its own run only.91* **Values are validated before anything runs**: unknown theme, template, paper, citation style, audit profile or export format, and out-of-range margins or levels.9293## Command-line tool9495`orixdocs` is the executable target of the package (`swift build --product orixdocs`). It needs no window server beyond what Core Text and Core Graphics use.9697```98orixdocs convert <input> <output> [--theme <name>] [--paper <size>] [--accept-changes] [--force]99orixdocs audit <input> [--profile standard|academic|business|minimal] [--json] [--fail-on-error]100orixdocs stats <input> [--json]101orixdocs compare <original> <revised> [--report <out.md>] [--merged <out.orixdoc>] [--force]102orixdocs workflow run <workflow.json|builtin-name> <inputs…> --out <dir> [--jobs <n>] [--force] [--quiet]103orixdocs workflow list [--json]104orixdocs formats105orixdocs --version106orixdocs <command> --help107```108109Results (paths written, reports, JSON) go to standard output; errors, warnings and progress go to standard error, prefixed with `orixdocs:` for errors.110111| Exit code | Meaning |112|---|---|113| 0 | Success |114| 1 | The operation failed: unreadable or damaged input, conversion or I/O error, invalid workflow file |115| 2 | Bad command line: unknown command or option, missing argument, unknown theme, paper, profile or format |116| 3 | An output file already exists and `--force` was not given (nothing was written) |117| 4 | A batch finished, but at least one input failed |118| 5 | `audit --fail-on-error` found at least one finding of severity `error` |119| 130 | Interrupted (Ctrl-C): the step in progress finished, the remaining files were not processed |120121Examples:122123```sh124orixdocs convert report.docx report.pdf --theme Academic --paper a4125orixdocs convert draft.docx clean.docx --accept-changes126orixdocs audit thesis.orixdoc --profile academic --json > findings.json127orixdocs audit thesis.orixdoc --fail-on-error || echo "errors remain"128orixdocs stats chapter.md --json129orixdocs compare v1.docx v2.docx --report changes.md --merged merged.orixdoc130orixdocs workflow run docx-to-styled-pdf inbox/*.docx --out published --jobs 8131orixdocs workflow run house-style.json chapter-*.md --out build --force132```133134`workflow run` prints one output path per line and, on standard error, one line per finished file and a final summary (`3 succeeded, 1 failed, 0 cancelled in 0.41 s`). `--jobs` defaults to the number of cores, at most 8.135136## Shortcuts actions137138Four App Intents (`App/Sources/Automation/DocumentIntents.swift`), listed by `ORIXDocsShortcuts`:139140| Action | Input | Output |141|---|---|---|142| **Convert Document** | a file, a format, “Accept Tracked Changes” | the converted file |143| **Export as PDF** | a file | a PDF |144| **Audit Document** | a file, a profile, Text or JSON | the findings as text |145| **Document Statistics** | a file, Text or JSON | the statistics as text |146147They take the file's bytes (`IntentFile`), call the same engine as the tool off the main actor, and return a value; `openAppWhenRun` is false and they create no document or window themselves.148149Status: the actions compile and their engine paths are the tested ones, but **they have not been run from the Shortcuts app** (that cannot be scripted from a terminal session).150One point must be settled first in the application delegate, which this work does not own: when macOS launches the app in the background to run an action, `applicationDidFinishLaunching` activates the app and the untitled-document path shows the template chooser. Launches made for an intent must skip both.151152## AppleScript: deferred153154Not shipped in this version, deliberately.155156* The standard suite needs a scripting definition (`.sdef`), `NSAppleScriptEnabled` and `OSAScriptingDefinition` in the Info.plist, and a model exposed through key-value coding. `NSDocument` would give `open`, `close`, `save`, `print` and `count documents` almost for free, but `save … as` only reaches the types the document class can write, which is the native format alone (other formats go through export). The one command people script a word processor for — “export this document as PDF” — would need a custom command, and `text of document` a text suite over a value-type model.157* A dictionary that advertises the standard suite and then fails on `save as PDF` or returns nothing for `text` is the half-working dictionary this project does not ship.158* The same needs are covered today: batch conversion and auditing by `orixdocs`, user-facing automation by the Shortcuts actions (which AppleScript and Automator can call through `shortcuts run`).159160If it is added later, the minimal honest scope is: standard suite on `document` (name, path, modified; open, close, save in the native format, print) plus one custom `export` command with a format parameter, implemented on `DocumentConverter`, with tests that drive it through `osascript`.161162## Measured timings163164Machine: Mac Studio, Apple M5 Max (18 cores), macOS 27.0; `orixdocs` built with `-c release`.165Batch: 76 DOCX files (the 19 documents of the import corpus × 4 copies, 656 KB in total; short documents of one to three pages), workflow `docx-to-styled-pdf` (import, theme, contents, audit with pagination, tagged PDF with outline).166167| `--jobs` | Wall time | Per document |168|---|---|---|169| 1 | 0.96 s | 12.6 ms |170| 4 | 0.44 s | 5.8 ms |171| 8 | 0.65 s | 8.6 ms |172173One run each, measured on 2026-11-21 with `time`, while the machine was busy with other builds and tests (load average 28 on 18 cores): the figures are indicative, and the slower result at 8 jobs than at 4 is within that noise. All 76 files succeeded in every run. The corpus documents are small; process start-up and font loading are a visible share of these times, so they say little about long documents.174175In the app, the same workflow on the open Research Report template (5 pages) took 0.4 s, and on the Thesis template (14 pages) 0.4 s, in a debug build.176177## Known limits178179* **PDF outline.** Written by the publisher with `CGPDFContextSetOutline` (an earlier PDFKit-based pass did not persist on macOS 27.0 and was replaced); `Tests/DocLayoutTests/PDFTests.swift` (`outlineMirrorsTheHeadings`) checks it. The automation tests themselves do not assert on the outline.180* Two inputs with the same base name in one batch write to the same output name: with `fail` the second one is refused, with `overwrite` the last one wins.181* Workflows have no conditions or loops, by design.182* The history keeps paths and step details, not document content.183