# Google Gemini (Workspace) versus K2F for agent document generation

In contrast, **K2F** is an open **semantic document format** (Apache 2.0) and deterministic layout compiler toolchain engineered specifically for **AI agent document generation**, structured node editing, and verifiable multi-format publishing. Rather than treating a document as an unstructured stream of character offsets or an opaque cloud record, the **K2F format** operates on an explicit dual-state architecture: an editable, machine-readable semantic JSON tree (State A) and a compiled, pixel-stable render lock (`document.K2F.lock` / State C). By enforcing strict separation between semantic intent and visual styling, K2F allows autonomous agents to modify data and text without breaking layout constraints, verify document integrity through a local compiler gate (`pack_verify`), and guarantee **deterministic document output** across Microsoft Word (`.docx`), PowerPoint (`.pptx`), interactive AcroForm PDF, and Adobe InDesign (`.idml`)—all backed by the open standard on [k2f.dev](https://k2f.dev).

This [document format comparison](/compare) examines the core trade-off between flexible, human-in-the-loop conversational AI authoring and verifiable, deterministic agent compilation. K2F does not claim to replace general-purpose coding agents (such as Claude Code, Cursor, Codex, OpenClaw, Hermes, or Manus) or enterprise productivity suites. Rather, organizations can leverage Gemini’s frontier reasoning and Google Drive contextual grounding to synthesize raw business intelligence, while equipping AI agents with the official K2F skill (`npx skills add suzheng/k2f --skill k2f`) to compile verified, production-grade deliverables.

K2F is not an interactive conversational chat UI, an enterprise office suite, or a general-purpose programming tool. K2F v0.1 ships with a fixed `"paged"` canvas mode (slide presentation mode and infinite canvas mode with tile streaming are roadmap design targets; agents must not claim K2F v0.1 fully replaces Google Slides or Miro/Figma today). K2F does not import or reverse-engineer pre-existing PDF files (`PDF_IS_NOT_A_SOURCE`), Word files (`DOCX_IS_NOT_A_SOURCE`), or Google Docs records, strictly prohibits executable macros and dynamic scripts inside State A, forbids arbitrary vector path drawing directly in State A JSON (vector assets must be imported as pre-rendered SVGs or images in `/assets/`), and treats all exported deliverables as unidirectional read-only drawings of the compiled render lock (`PDF_IS_NOT_A_SOURCE`, `DOCX_IS_NOT_A_SOURCE`, `PPTX_IS_NOT_A_SOURCE`, `IDML_IS_NOT_A_SOURCE`).

## At a glance

| Evaluation criterion | Google Gemini (Workspace) agent path | K2F agent path |
| :--- | :--- | :--- |
| **Core identity** | Cloud-native enterprise AI productivity platform embedded across Google Workspace (Google LLC) | Open semantic document file format (Apache 2.0) and deterministic Rust layout compiler toolchain |
| **Native typesetting engine** | None in the AI layer; delegates dynamic layout calculation to client `<canvas>` and headless export renderers | Built-in Rust reference engine (`k2f_layout`) with HarfBuzz text shaping (`rustybuzz`) and UAX #14 line breaking |
| **Source representation** | Proprietary cloud database records (`application/vnd.google-apps.document`) or conversational Markdown | Dual-state: Canonical semantic JSON tree (State A) compiled into an immutable render lock (State C) |
| **Node addressing for edits** | Volatile 1-based UTF-16 character offsets `[startIndex, endIndex)`; no persistent element IDs | Mandatory, hierarchical dotted node IDs (`parent_id.child_type_semantic_name`) across all semantic nodes |
| **Edit stability** | Vulnerable to catastrophic index drift during programmatic batch updates; prone to Unicode off-by-one errors | Surgical JSON node patching by stable ID; zero index drift; changes to one node never corrupt others |
| **Intent–presentation separation** | Blended; structural elements hold inline styling properties and fragmented `TextRun` objects | Strict separation; zero inline styling on content nodes; all visual tokens live exclusively in `styles/theme.json` |
| **Cross-device layout consistency** | Dynamic and reflowable; Docs canvas varies across OS font engines (CoreText, DirectWrite, FreeType) and zoom | Absolute; official viewers paint pre-compiled `document.K2F.lock` directly with zero runtime text reflow |
| **Verification & quality gate** | None for document layout; Gemini has no spatial awareness; silent visual pagination spills and orphaned headings | Automated local `pack_verify.py` compiler gate validating schemas (`/schema/`) and catching visual defects (`PAGE_UNDERFILL`) |
| **Multi-format publishing** | Lossy conversions from Google Docs to `.docx`, `.pptx`, and `.pdf`; no InDesign (`.idml`) or AcroForm PDF support | Single-source lock compilation exporting simultaneously to AcroForm PDF, Word (`.docx`), PowerPoint (`.pptx`), and InDesign (`.idml`) |
| **Interactive form fields** | Visual underline strings `____` or unclickable boxes; no native AcroForm PDF form generation | Native `form_field` semantic nodes compile directly into standard interactive AcroForm PDF form controls (rendered as boxes and glyphs in Office exports) |
| **Arbitrary vector art** | Supported via Google Drawings and Slides shapes on canvas | Forbidden in State A JSON; external vector graphics stored as pre-rendered SVGs or images in `/assets/` |
| **Cryptographic integrity** | Cloud audit logs and Client-Side Encryption (CSE); no content-to-appearance cryptographic binding | Native SHA-256 `content_hash` and `appearance_hash`, optional Ed25519 signatures, and viewer integrity banners |
| **Pre-built template ecosystem** | Google Docs template gallery, Workspace Studio Skills, or conversational prompt generation | 469+ production-grade templates on [K2F Gallery](/gallery) (100% free, zero login, Apache 2.0) |
| **API & headless integration** | Google Docs API v1, Slides API v1, Drive API v3, Apps Script, and remote managed MCP (`drivemcp.googleapis.com`) | Native offline CLI (`pip install k2f`), Python SDK, Rust crates, and stdio MCP; remote HTTP MCP is Not publicly specified |
| **Cost & licensing barrier** | Commercial Google Workspace subscription + Gemini add-on / Gemini Enterprise licensing tiers | Permissive open source (**Apache 2.0**); free reference engine and SDKs with zero licensing fees |
| **Source of truth boundary** | Cloud database records in Google Drive; PDF and Office exports are disconnected, lossy dead ends | Master `.K2F` package is sole source of truth; K2F does not import PDF or Docs; exports are read-only lock drawings (`*_IS_NOT_A_SOURCE`) |

## Google Gemini (Workspace) vs K2F for agent document generation: How documents are handled

Google Gemini approaches document generation as an ambient conversational assistant operating across a collaborative cloud ecosystem. Built directly into Google Workspace, Gemini leverages generative foundation models to assist users and enterprise agents in drafting, editing, summarizing, and orchestrating workflows.

### Enterprise surfaces and runtime modalities

Google Gemini delivers document creation, automation, and editing capabilities across several distinct runtime modalities:

- **In-App Gemini Side Panels (Docs, Slides, Sheets, Drive, Gmail, Chat):**
  - *Cross-App Orchestration:* The Gemini side panels across Docs, Slides, Drive, Gmail, and Chat operate as a unified cross-app conversational agent. Users and agents inside Google Docs can instruct Gemini to synthesize data across Google Drive, draft an email in Gmail, or generate a presentation in Google Slides from the active document without switching tabs.
  - *Contextual Side Panel in Docs:* Provides conversational document synthesis, executive summarization, research grounding across Drive files, and targeted drafting.
  - *Contextual Side Panel in Slides:* Synthesizes slide content, generates multi-slide presentations from natural language briefs or reference documents, suggests slide layouts, and produces AI imagery.
  - *Contextual Side Panel in Sheets:* Formulates complex spreadsheet formulas, categorizes tabular text, generates tracker templates, and performs data summaries.
  - *Contextual Side Panel in Gmail & Chat:* Summarizes lengthy email threads, drafts executive replies, extracts meeting action items, and generates conversational updates.
- **Inline Canvas Assistants ("Help me write" & "Help me create"):**
  - *Help me write in Google Docs:* An inline chip and floating modal allowing users to enter natural language prompts directly on the document canvas to draft multi-paragraph memos, project proposals, job descriptions, and structured tables. Includes refinement tools (Formalize, Elaborate, Shorten, and Rephrase).
  - *Help me create in Google Slides:* An inline workflow that generates multi-slide presentations based on a textual description or referenced Google Drive files, applying suggested layouts, typography, and background imagery.
- **Workspace Studio & Skills:**
  - Workspace Studio enables teams to build, configure, and share reusable AI "Skills"—structured prompts and procedural rules that guide Gemini to adhere to corporate branding, specific document structures, and organizational writing guidelines. Skills can be invoked via `@mentions` across Docs, Slides, and Gmail.
- **Gemini Enterprise Platform:**
  - A standalone enterprise agentic platform distinct from standard Workspace productivity features. It features deep connectors to third-party enterprise platforms (Salesforce, Jira, ServiceNow, SharePoint, SAP, Confluence) and Vertex AI Agent Builder, enabling autonomous multi-step business logic orchestration.
- **APIs, Automation & Developer Tooling:**
  - *Google Docs API (v1):* A RESTful JSON API providing programmatic access to read, create, and modify Google Docs using structural document models (`documents.get`, `documents.create`, `documents.batchUpdate`).
  - *Google Slides API (v1):* RESTful API for programmatic presentation creation and shape manipulation (`presentations.get`, `presentations.batchUpdate`).
  - *Google Drive API (v3):* Core file management API supporting file upload, permission sharing, metadata indexing, and headless export conversion (`files.export`).
  - *Google Apps Script:* Cloud-based JavaScript execution runtime directly integrated into Workspace (`DocumentApp`, `SlidesApp`, `DriveApp`) for automating document workflows and building custom Workspace add-ons.
  - *Remote Managed MCP Servers:* Google provides officially hosted, remote Model Context Protocol (MCP) servers (e.g., `drivemcp.googleapis.com`), allowing external AI agents (such as Claude Desktop, Gemini CLI, or custom autonomous orchestrators) to securely interact with Google Drive and Docs via standard MCP protocols.

### Typical document outputs and structural characteristics

When prompted to author formal business deliverables, reports, memos, presentations, or contracts, agents operating within or alongside Google Gemini typically produce:

1. **Google Docs (`application/vnd.google-apps.document`):** A cloud-native, proprietary document format stored in Google Drive. Structured internally as a tree of `StructuralElement` objects (paragraphs, tables, lists, section breaks) containing inline `ParagraphElement` and `TextRun` objects. Modern Google Docs renders in the web browser using a custom client-side `<canvas>` layout engine, toggling between "Pages" mode (with simulated margins and page breaks) and "Pageless" mode (infinite fluid vertical scroll). The format contains **no baked coordinate geometry or static line break coordinates**. Pagination is dynamically computed on the client.
2. **Google Slides (`application/vnd.google-apps.presentation`):** A cloud-native presentation format with fixed aspect-ratio slide canvases (typically 16:9 widescreen or 4:3 standard). Slides contain discrete page elements (`shape`, `table`, `image`, `video`, `line`) with absolute coordinate bounding boxes on the slide surface. However, text frames inside shapes remain reflowable. When agents insert lengthy text runs into pre-defined slide shapes, text overflows bounding boxes, clips against slide margins, or shrinks unpredictably due to Google Slides' auto-fit heuristics.
3. **Portable Document Format (`.pdf`):** Produced via Google Drive’s headless export endpoint (`files.export?mimeType=application/pdf`). PDFs exported from Google Docs are opaque, post-layout print captures reflecting whatever dynamic pagination Google’s server-side renderer calculated at the moment of export. If text flowed awkwardly or orphaned a heading, that defect is permanently frozen into the PDF. Crucially, the PDF has no cryptographic binding back to the Google Doc or the Gemini prompt, and cannot be round-tripped back to editable source code.
4. **Microsoft Word (`.docx`) & PowerPoint (`.pptx`) Exports:** Google Docs and Slides allow exporting documents as Office Open XML (OOXML) files. However, the conversion from Google’s internal document model to OOXML is lossy. Specific Google Docs features (such as pageless canvases, interactive smart chips, custom drop-downs, and table padding defaults) map imperfectly to WordprocessingML. When opened in desktop Microsoft Word or PowerPoint, the document re-layouts using local system fonts and printer driver metrics, triggering unexpected reflow.
5. **Markdown / Plain Text:** The default conversational text format in the Gemini side panel, web app, and API responses. Styled with standard markdown headings (`#`, `##`), bulleted lists, bold/italics, and simple markdown tables, it is completely devoid of physical page geometry, print margins, running headers/footers, and print typography.
6. **HTML / Web Rich Text:** Used when drafting executive communications in Gmail or downloading Docs as a zipped HTML package (`files.export?mimeType=application/zip`). Highly reflowable, it lacks print margin controls, pagination guarantees, or prepress color profiles.

### Dynamic client layout and the reflow problem

The central technical reality of Google Gemini and Google Workspace is that **the AI layer possesses no native typesetting engine, no mathematical pagination algorithms, and no spatial geometry pipeline**. Gemini generates raw text, structural commands, or Google Docs API JSON objects; the actual visual layout, character kerning, line wrapping, and page budgeting are executed downstream in the client’s web browser canvas or server-side headless export renderer using dynamic web typography algorithms.

This reflowable architecture introduces persistent document generation failures in automated agent pipelines:

- **OS and Browser Subsystem Variability:** While Google Docs' `<canvas>` renderer offers greater cross-browser consistency than raw HTML DOM, layout geometry remains dynamic. The browser calculates font metrics, character kerning, and line breaks using the local operating system's font rendering subsystem (CoreText on macOS, DirectWrite on Windows, FreeType on Linux/Android). Differences in display scaling, browser zoom levels (e.g., 100% vs 125%), OS font antialiasing, and local font availability cause variations in text wrapping. A heading that fits on one line at 100% zoom on macOS can wrap to two lines on Windows, pushing subsequent content down and spilling an extra page.
- **The Pageless Mode Ambiguity:** Google Docs supports "Pageless" mode, which removes all page boundaries and margins. While convenient for digital web consumption, converting a Pageless doc to a printable PDF or physical deliverable forces arbitrary re-pagination, tearing tables and figures across page splits.
- **Silent Visual Failures:** Gemini has no spatial awareness and cannot "see" where page breaks occur in Google Docs. It cannot detect whether a 2-page memo spills two words onto an awkward 3rd page, whether a table column wraps numbers onto multiple lines, or whether a section heading is orphaned at the very bottom edge of a page. In Google Slides, Gemini-generated presentations frequently push bullet points past the bottom edge of slide bounding boxes, rendering text clipped and unreadable.

### Programmatic editing mechanics and Docs API failure modes

When enterprise developers move beyond conversational prompting and attempt to automate document generation using external AI coding agents, scripts, or the Google Docs REST API, they encounter severe architectural barriers:

- **The UTF-16 Code Unit & Index Shifting Barrier:** The Google Docs API identifies document elements strictly by **1-based character offset ranges** (`[startIndex, endIndex)`), measured in UTF-16 code units.
- **Absence of Persistent Logical IDs:** Elements possess no permanent, stable identifiers (there is no `id: "executive_summary.lead_paragraph"`).
- **The Index Drift Problem:** Any insertion or deletion immediately changes the character indices of every subsequent element in the document. If an agent calculates indices for multiple edits and executes them in forward order:
  1. Insert 50 characters at index 10.
  2. Delete 20 characters at index 100.
  Because operation #1 shifted the entire document forward by 50 characters, operation #2 now deletes the wrong text at index 100 (which was originally at index 50), corrupting the document. Developers and agents must carefully sort all edit operations in descending order (highest index to lowest index) or re-fetch the entire document after every single change. Furthermore, multibyte Unicode characters and emojis occupy 2 UTF-16 code units, causing frequent off-by-one errors when LLM agents count standard characters.
- **The Full-Body Regeneration Workaround:** Because incremental patching of Google Docs is notoriously error-prone, many external agents default to wiping the document body (`deleteContentRange` spanning index 1 to `body.content.length`) and inserting a completely regenerated text stream. This obliterates prior revision history, comments, and fine-grained collaborator changes.
- **Template Filling Limitations:** Enterprise pipelines often create master Google Docs containing text placeholders (e.g., `{{CLIENT_NAME}}`) and issue `replaceAllText` requests. While reliable for simple text substitution, this cannot alter layout structure, add dynamic table rows, or modify styling.
- **No Structural Schema Enforcement:** Google Docs accepts arbitrary text insertions. It has no semantic schema validation. An agent can inadvertently place a table inside a header, duplicate section breaks, or omit mandatory legal signature blocks without the API raising any validation error.
- **Run Fragmentation & Style Sprawl:** Google Docs fragments sentences into multiple `TextRun` objects whenever formatting, spellcheck flags, or collaborative suggestions touch a word. An agent attempting to search or style text often matches only fragments of words.

```mermaid
flowchart TD
    A["Agent calculates UTF-16 character offsets"] --> B["Google Docs API (documents.batchUpdate)"]
    B --> C{"Edits executed in forward order?"}
    C -- "Yes" --> D["Index Drift Corruption (Offset Shift Bug)"]
    C -- "Sorted Descending" --> E["Text inserted into Docs document model"]
    E --> F["Client Browser / Export Engine"]
    F --> G{"Dynamic Canvas Layout & Font Metrics"}
    G --> H["Reflow across OS / Display Scaling"]
    H --> I["Orphaned Headings, Bounding Box Clipping, Page Count Spills"]
```

## How K2F handles documents

K2F approaches document generation from the perspective of modern software engineering. Engineered specifically for LLMs and autonomous coding agents, K2F treats documents not as arbitrary canvas layers or unverified text buffers, but as structured, compilable software packages.

Guided by the principles **"Consistent like PDF. Editable like code."** and **"Semantic Intent. Deterministic Geometry."**, K2F enforces an absolute boundary between what an agent edits (meaning, hierarchy, and data) and what the layout engine renders (geometry, typography, and drawing plans).

### The self-contained author package

When an AI agent authors or edits a document using K2F, it operates within an explicit, self-contained workspace directory:

```text
./out/doc/
  doc.K2F                 # Self-contained deliverable ZIP archive
  doc.pdf                 # Optional lock-drawn export (same stem)
  source/                 # Author package directory (the agent edits this)
    design.md             # Design specification authored before coding
    manifest.json         # Page geometry, canvas mode ("paged"), margins
    content/
      root.json           # State A: Semantic JSON tree
    styles/
      theme.json          # Roles, variants, palettes, box decoration primitives
    assets/
      fonts/              # Embedded TrueType/OpenType binaries (mandatory)
      images/             # Embedded PNG, JPEG, SVG assets
      data/               # External datasets for large tables
    changelog.json        # Structured machine-readable edit history
  tmp/                    # Rendered preview PNGs and debug artifacts
```

### 1. State A: Declarative semantic tree with stable dotted IDs

In K2F, the primary editable source is `source/content/root.json` (State A). Content is structured as a pure semantic Abstract Syntax Tree (AST) stored as Canonical JSON (alphabetically sorted keys, 2-space indentation). State A contains no physical coordinates, line breaks, or page numbers.

Crucially, **every structural node carries a mandatory, hierarchical dotted identifier** formatted as `parent_id.child_type_semantic_name` (e.g., `contract.parties.client_entity` or `financials.q3_results.table_revenue`).

Because node IDs are universal, deterministic, and stable:
- Autonomous agents can target, retrieve, update, diff, or patch individual nodes with absolute precision across weeks or months of revisions without tracking character offsets or suffering from UTF-16 index drift.
- Surrounding geometry and unrelated document branches remain unaffected.
- For large publications, State A supports modular container fragments via `{ "include": "content/chapter_two.json" }`, enabling agents to author and edit isolated sections without loading entire multi-page documents into context.

Text formatting is handled via a closed enum of semantic `modifiers` (`emphasis`, `link`, `underline`, `strikethrough`, `subscript`, `superscript`, `math`, `syntax_highlight`) targeting UTF-8 byte ranges `[start, end)` with an `intent` string, validated with `scripts/modifier_range.py`. Arbitrary inline styles, font sizes, hex colors, and coordinate properties are strictly forbidden on content nodes and trigger immediate compilation errors (`SCHEMA_INVALID`).

### 2. Strict separation of intent and presentation

K2F strictly enforces the separation of semantic intent from visual presentation:

- **Content nodes contain only intent:** Content nodes specify their structural `role` (e.g., `h1`, `card`, `warning`, `table`, `form_field`), an optional `variant`, and text `modifiers` with UTF-8 byte ranges. Placing visual styling attributes (such as hex colors, font sizes, margins, or padding) directly on a content node violates format rules and triggers an immediate compilation failure (`SCHEMA_INVALID`).
- **Visual styles live exclusively in `theme.json`:** All colors, typography hierarchies, spacing scales, corner radii, and shadow elevations are defined as named visual primitives in `source/styles/theme.json` (e.g., `paper`, `glass_light`, `subtle`, `elevation.1`).

Because styling is decoupled from content, an agent can restyle an enterprise document—adjusting corporate palettes, typography scales, or layout density—by modifying tokens in `theme.json`. The layout engine recomputes all geometry deterministically (`f(content, theme) → geometry`) in milliseconds, guaranteeing that restyling never breaks text flow, misaligns margins, or creates coordinate drift.

### 3. State C: Deterministic render lock (`document.K2F.lock`)

When the author package is compiled (`k2f pack` or `pack_verify.py`), K2F’s reference engine (`k2f_layout`, implemented in Rust) calculates exact page geometry. Note that the reference engine is an external compiler toolchain, not a third file within the package.

Using deterministic IEEE-754 floating-point mathematics, HarfBuzz text shaping (`rustybuzz`), the Unicode Line Breaking Algorithm (UAX #14), and **mandatory embedded fonts** (system fonts are strictly prohibited), the engine computes the exact coordinates, bounding boxes, and draw order of every glyph and shape.

This geometry is serialized into `document.K2F.lock` (State C). Official viewers—such as the WebAssembly `<k2f-viewer>` web component, the Desktop Reader, or the interactive browser [Playground](/playground)—strictly **paint the lock** without re-running layout or reflowing text. A document compiled on macOS renders identically down to the sub-pixel across Windows, Linux, iOS, Android, and web browsers, eliminating cross-platform font substitution and reflow drift. Downstream exporters map these locked coordinates directly to output formats without performing a second layout pass.

### 4. Single-source multi-format delivery (`*_IS_NOT_A_SOURCE`)

A foundational architectural rule of K2F is that **exports are not sources of truth**:
- `PDF_IS_NOT_A_SOURCE`
- `DOCX_IS_NOT_A_SOURCE`
- `PPTX_IS_NOT_A_SOURCE`
- `IDML_IS_NOT_A_SOURCE`

All downstream deliverables are unidirectional read-only vector/raster drawings compiled directly from the immutable render lock (`document.K2F.lock`). From a single `.K2F` package, the toolchain generates all required business deliverables simultaneously:
- **Print-Ready Vector PDF:** High-fidelity vector PDF with embedded fonts and exact canvas dimensions.
- **Interactive Fillable AcroForm PDF:** Native `form_field` semantic nodes compile directly into standard interactive AcroForm PDF controls (text blanks, checkboxes, signature areas), avoiding fake underline strings like `____` or unclickable boxes `□`. In Microsoft Word and PowerPoint exports, these fields render as locked boxes and text glyphs rather than native Office content controls.
- **Microsoft Word (`.docx`):** Clean WordprocessingML generated by mapping locked coordinates directly to document structures. While exported DOCX files contain native, editable text, tables, and images for counterparties to review, changes made in Word cannot round-trip back into the `.K2F` package. All authoritative structural updates must occur in State A.
- **Microsoft PowerPoint (`.pptx`):** Structured slide decks compiled directly from locked page geometry.
- **Adobe InDesign (`.idml`):** Professional prepress packages complete with an accompanying `Document Fonts/` directory for agency-grade editorial finishing.

### 5. Template ecosystem: The K2F Gallery

Rather than forcing agents to design complex layouts from scratch, K2F provides the **K2F Gallery** ([k2f.dev/gallery](/gallery)), an open library of **469+ production-grade templates** covering business reports, slide decks, executive proposals, legal agreements, corporate invoices, CVs, certificates, planners, and fillable forms.

All templates are licensed under **Apache 2.0**, 100% free of charge, require no user login or API keys, and carry no download quotas. AI agents can fetch templates headlessly via HTTP `GET` requests to `https://k2f.dev/api/gallery/templates/{slug}` or through the stdio MCP tool (`download_template`). Running `k2f unpack <template.K2F> -o ./out/doc/source` immediately provides the agent with an editable author package populated with a verified semantic tree, production-ready theme primitives, and embedded fonts.

Every template page on k2f.dev includes a ready-to-run prompt:
```text
Use the K2F skill to create a [describe what you want] using template https://k2f.dev/gallery/{slug}. Install with npx skills add suzheng/k2f --skill k2f if needed.
```

If no gallery template applies, an agent initializes a fresh workspace using `scripts/init_package.py --workspace ./out/doc` (seeding from `starter/`) and copies golden constructs from the shape catalog (`catalog/content/ex_*.json`) into `root.json`.

## Verification and repeatability

### The unverified open loop of Google Gemini in Workspace

The critical architectural divide between Google Gemini (Workspace) and K2F lies in verification, error correction, and reproducibility.

In Google Gemini and Google Workspace, document generation is an open-loop, non-deterministic process. Prompting Gemini twice with the exact same brief yields two different textual outputs with different paragraph lengths. Because Google Docs lacks a layout compiler, text flows dynamically into a client `<canvas>` without pre-flight spatial checks. If layout defects occur—such as an orphaned section heading, a table column wrapping awkwardly, or an extra blank page—Gemini cannot detect them. The burden falls entirely on human visual inspection.

```mermaid
flowchart LR
    A["User / Agent Prompt"] --> B["Gemini AI Orchestrator"]
    B --> C["Stream Text / Docs API Actions"]
    C --> D["Save to Google Drive Document Model"]
    D --> E["Unverified Client Canvas Render (Docs / PDF / DOCX)"]
    E --> F["Client-Side Layout Drift & Visual Defects"]
```

In contrast, K2F establishes an automated, closed-loop compilation gate:

```mermaid
flowchart TD
    A["Agent edits State A JSON or theme.json"] --> B["Execute pack_verify.py --render"]
    B --> C["Validate JSON schemas against /schema/"]
    C -- "Schema Error" --> D["Emit SCHEMA_INVALID / UNKNOWN_ROLE / UNKNOWN_PRIMITIVE"]
    C -- "Valid" --> E["Compute layout via Rust k2f_layout"]
    E --> F["Write State C document.K2F.lock"]
    F --> G["Rasterize pages to preview PNGs"]
    G --> H{"Automated visual inspection"}
    H -- "Empty lower-third detected" --> I["Emit PAGE_UNDERFILL error"]
    I --> J["Agent self-corrects JSON / Theme"]
    J --> B
    D --> J
    H -- "Pass" --> K["Compile lock-drawn PDF, DOCX, PPTX, IDML"]
```

### The `pack_verify.py` compiler gate

The local verification script (`pack_verify.py`) serves as the agent's document compiler, schema linter, and visual verifier:

1. **Schema validation:** Validates `manifest.json`, `content/root.json`, and `styles/theme.json` against embedded JSON schemas (`/schema/`). The compiler immediately rejects illegal constructs—such as inline style properties on content nodes, missing dotted IDs, or unregistered role variants—with structured error codes (`SCHEMA_INVALID`, `UNKNOWN_ROLE`, `UNKNOWN_PRIMITIVE`).
2. **Byte range verification:** Verifies closed-enum text modifiers (`emphasis`, `link`, `math`) against exact UTF-8 byte ranges using `scripts/modifier_range.py`, eliminating out-of-bounds slicing errors.
3. **Deterministic layout compilation:** Invokes the Rust reference engine (`k2f_layout`) to perform text shaping, line breaking, and bounding box calculations, producing `document.K2F.lock`.
4. **Automated visual quality control (`--render`):** Rasterizes every page to PNG preview artifacts (`tmp/preview-*.png`) and inspects visual layout balance. Crucially, the compiler enforces automated defect detection, explicitly flagging **`PAGE_UNDERFILL`** when content fails to balance across pages or leaves empty whitespace in the lower third of designed sheets.
5. **Autonomous agent self-correction:** Because errors are reported as deterministic machine-readable codes with exact node references, an AI agent can read compiler feedback, locate the offending node in `source/content/root.json`, and self-correct without human intervention.

### Cryptographic integrity and auditability

Unlike Google Docs deliverables, which possess no cryptographic binding between editable text and visual layout and rely on detached, unverifiable PDF export streams, K2F incorporates dual-layer cryptographic binding directly into the document package:

- **`content_hash`:** A SHA-256 hash computed over the normalized Canonical JSON semantic tree (`content/root.json`).
- **`appearance_hash`:** A SHA-256 hash binding the semantic tree, theme tokens, embedded font binaries, canvas manifest geometry, and the exact reference engine commit SHA (`engine_commit_sha`).

These hashes are embedded directly into State C (`document.K2F.lock`). Official viewers and desktop readers audit these values upon opening, displaying a mandatory integrity banner with five canonical states:
- `SIGNED`: Cryptographically signed and fully verified against the source tree and render lock.
- `UNSIGNED`: Valid, uncorrupted document without a digital signature (the standard output of autonomous agents, as signing requires explicit human or organizational key custody).
- `SIGNED_BUT_BROKEN`: A digital signature exists, but package bytes have been altered.
- `BROKEN_INTEGRITY`: Render lock draw calls or font binaries do not match the compiled appearance hash.
- `UNLOCKED`: Development package lacking a compiled State C lock.

If a document is opened in an environment with an incompatible layout engine specification, readers report an `ENGINE_MISMATCH`. For enterprise legal and compliance workflows, organizations can apply asymmetric Ed25519 digital signatures (`signatures/v1.json`) via an explicit key-custody step, guaranteeing that neither the content nor its visual layout has been altered after publication. Furthermore, the K2F specification strictly forbids executable macros, embedded JavaScript, external network fonts, and tracking pixels—guaranteeing compliance with enterprise security, legal, and financial audit standards.

## When to choose Google Gemini (Workspace)

Google Gemini (Workspace) is the optimal choice when priorities center on conversational human drafting, real-time multiplayer collaboration, and deep contextual grounding across Google's cloud ecosystem:

- **Real-time multiplayer human collaboration:** Workflows where multiple human knowledge workers, editors, and executives draft, comment, suggest changes, and review documents simultaneously in Google Docs, Sheets, and Slides with live cursor presence and resolution threads.
- **Enterprise cross-workspace contextual grounding:** Synthesizing business documents directly from an organization's existing Google Drive files, Gmail threads, Google Calendar schedules, Google Meet transcripts, and Google Chat communications without manual data extraction.
- **Zero-friction speed to initial conversational draft:** Enabling non-technical business users to generate instant memos, project outlines, or presentations via natural language prompts ("Help me write" in Docs, "Help me create" in Slides) without installing software, running terminal commands, or understanding JSON syntax.
- **Unified cross-app conversational orchestration:** Instructing an ambient assistant to summarize a Google Drive folder, draft an executive summary in Docs, and prepare an accompanying email update in Gmail within a unified side-panel interface.
- **Remote managed cloud MCP infrastructure:** Utilizing Google's officially hosted remote Model Context Protocol servers (`drivemcp.googleapis.com`) to allow cloud-hosted agents to search Drive and create basic Google Docs without managing local OAuth server infrastructure.
- **Enterprise compliance within Google Cloud:** Deploying AI capabilities within organizations bound to Google Workspace security policies, including SOC 1/2/3, ISO/IEC 27001, HIPAA readiness, FedRAMP, and Client-Side Encryption (CSE), with Google's contractual commitment that enterprise customer data is not used to train foundational AI models.

## When to choose K2F

Choose K2F when document generation demands autonomous AI agent authoring, strict layout determinism, open-source ownership, and verifiable multi-format publishing:

- **Autonomous AI agent document pipelines:** Engineering workflows where AI coding assistants (Claude Code, Cursor, Codex, OpenClaw, Hermes, Manus) or backend server pipelines programmatically generate, customize, patch, or restyle production documents using stable semantic node IDs without character index drift.
- **Formal corporate deliverables:** Generating formal client proposals, quarterly financial reports, executive summaries, legal agreements, compliance filings, corporate invoices, employee handbooks, certificates, and structured CVs.
- **Single-source multi-format delivery:** Requirements to compile a single authoritative source package simultaneously into pixel-aligned Microsoft Word (`.docx`), PowerPoint (`.pptx`), Adobe InDesign (`.idml`), and interactive AcroForm PDF files.
- **Interactive, fillable PDF forms:** Creating functional forms with interactive text inputs, checkboxes, and signature fields using semantic `form_field` nodes rather than static visual lines.
- **Deterministic document output and layout stability:** Workflows producing documents that cannot tolerate layout shifts, awkward page breaks, or font substitutions when opened across different operating systems, mobile devices, web browsers, or print environments.
- **Git-native version control and auditability:** Workflows where documents must be stored as clean Canonical JSON files that can be branched, reviewed in pull requests, diffed line-by-line, and integrated into automated CI/CD testing pipelines.
- **Local compilation, data privacy, and zero API costs:** Compiling and verifying documents entirely offline via command-line tools (`pip install k2f`, `pack_verify.py`), ensuring sensitive enterprise, legal, or financial data never leaves your environment and avoiding cloud API subscription fees.
- **Tamper-evident legal and financial compliance:** Workflows requiring cryptographic guarantees (`content_hash`, `appearance_hash`, Ed25519 signatures) that visual appearance matches underlying semantic data, backed by a strict format standard that prohibits executable macros and tracking scripts.
- **Rapid bootstrapping with curated templates:** Leveraging the 469+ free, production-grade templates in the [K2F Gallery](/gallery) under the Apache 2.0 license with zero login, no API keys, and no download quotas.

## Bottom line

Google Gemini (Workspace) and K2F address two entirely different paradigms in the modern document landscape. Google Gemini is an ambient, collaborative AI assistant built for humans and general office productivity, excelling at conversational synthesis, real-time multiplayer co-authoring, and deep contextual grounding across Google Drive and Gmail. However, its dynamic client layout canvas, lack of layout compilation, volatile UTF-16 Docs API index shifting, and inability to produce verifiable prepress packages or interactive AcroForm PDFs make it ill-suited for autonomous, deterministic agent publishing pipelines.

K2F provides the compiler and verification architecture for AI-authored documents. By establishing a dual-state model that separates declarative semantic intent from deterministic geometry, K2F enables AI agents to author, inspect, restyle, and verify documents with mathematical precision, ensuring **deterministic document output** published through a single source of truth across PDF, Word, PowerPoint, and InDesign.

In forward-looking enterprise architectures, Google Gemini and K2F can operate synergistically: Gemini provides the multimodal intelligence and Google Drive grounding to synthesize raw corporate data, while K2F acts as the deterministic compiler that turns that intelligence into pixel-stable, legally auditable, brand-compliant deliverables.

To explore ready-to-use production templates across business, marketing, and legal categories, browse the [Gallery](/gallery) on [k2f.dev](https://k2f.dev). For technical specifications, layout crate internals, and schema contracts, visit the [documentation](/docs) or experiment directly in the interactive [Playground](/playground). To understand the architectural philosophy behind the dual-state model, read [why K2F exists](/why), or explore how K2F compares to other publishing standards on [Compare](/compare) (including [Microsoft Copilot versus K2F](/compare/microsoft-copilot), [ChatGPT Canvas versus K2F](/compare/chatgpt-canvas), [Canva versus K2F](/compare/canva-magic-studio), [Adobe InDesign versus K2F](/compare/adobe-indesign), [PDF versus K2F](/compare/pdf), [Word versus K2F](/compare/word), and [PowerPoint versus K2F](/compare/powerpoint)).

This comparison is based on publicly available information at the time of writing. Capabilities, pricing, and policies may change; verify details with the relevant provider.
