Skip to main content

ADR-007: Document Generation Architecture

  • Status: Accepted
  • Date: 2026-04-16
  • Author: CTO Agent (KALA-135)

Context

Client workflows need repeatable document generation for proposals, letters, contracts, invoices, and custom forms. Generated documents should be reviewable, downloadable, and optionally reusable by the RAG system after creation.

The platform already has namespaces, department-scoped knowledge bases, document ingestion, and audit-friendly API routes. The document generator had to fit those primitives rather than become a separate storage system.

Decision

Use a two-step model:

DocumentTemplate -> DocumentGeneration -> optional KnowledgeBase Document

DocumentTemplate stores the reusable spec: namespace, category, template body, variables, and default output format.

DocumentGeneration stores each render attempt: user, input, output, status, error, and optional outputFileId.

When a non-preview generation is saved, the rendered output becomes a normal Document in a knowledge base. This lets generated documents use existing download, ingestion, chunking, embedding, and RAG retrieval flows.

Alternatives Considered

Store generated files outside the knowledge base

Rejected. Separate storage would need its own download, retention, and access rules and would not participate in RAG.

Generate only transient previews

Rejected. Legal and sales workflows need durable generation history and downloadable outputs.

Build a full office-document templating engine first

Rejected. Handlebars over Markdown/HTML/DOCX text covers current needs and is much easier to audit. Rich binary templates can be added later.

Consequences

Positive

  • Generation history is queryable.
  • Preview and saved generation share the same rendering path.
  • Saved outputs become knowledge documents and can be retrieved by RAG.
  • Department scope is inherited from namespace and knowledge base checks.

Negative

  • DOCX export is currently text-block based, not a full styled template engine.
  • PDF is reserved but not implemented.
  • RAG variable quality depends on the quality of source documents and queries.

Implementation Notes

  • src/documents/generator.ts owns variable parsing, resolution, rendering, and export metadata.
  • src/routes/document-templates.ts owns CRUD, generate, and generation history endpoints.
  • Variables can come from user, rag, or contractor_api.
  • Required missing variables fail the generation and store the error on the generation row.