ADL 39 · Part V — Execution, presentation, and integration

0.5.1 baseline + 0.6 edition note

Templates and documents

ADL 0.6.0 reference · Review draft 1 · November 14, 2026.

Contents · Source map · Evidence

The 0.6 edition note

This chapter retains the detailed language contract and its source-specific observations. Its chapter number and numbered sections remain stable. The 0.6 additions do not by themselves change this subject’s defaults or supply fresh execution evidence for it.

Reverification should cover template inputs, render failures, and disclosure in generated documents. Use the original examples and evidence links below to recover the earlier test context. The new edition’s source map records this chapter as inherited detail; the current draft does not claim those historical tests were rerun.

Retained reference detail

The numbered sections below are carried from 39-templates-and-documents.md. Their original baseline and evidence remain attached to the source. Statements about “current” or “checked” behavior in this retained text refer to those original observations unless the edition note explicitly updates them. This is a consolidated draft, not a claim of complete re-verification.

39.1 Scope and edition boundary

A template generates a document from a record and additional context. It can run on a declared event or through its generation endpoint, save an output file, record document metadata, and attempt to attach the document ID to a resource field. This chapter owns those author-visible behaviors. ADL 24 owns history captures, ADL 35 owns notification delivery, and the platform book owns file-provider deployment.

The inherited chapter (v0.5.0, retired) remains the baseline. Current-source checks distinguish actual Markdown/HTML output, PDF/DOCX downgrade, metadata inconsistencies, event-worker behavior, and recovery limits. Template declaration, successful generation, readable file, record attachment, and notification delivery are separate observations.

39.2 Template grammar and placement

domain.templates maps names to template definitions. The complete examples include ordinary Ticket resources and disposable document storage. This fragment illustrates their manual receipt template:

# Domain fragment from markdown.yaml.
templates:
  receipt:
    trigger:
      manual: true
      resource: Ticket
    format: markdown
    filename: Receipt-{id}.md
    body: |
      # {title}

      Amount {amount | money}; actor {$actor.name}.
    permissions:
      generate: [writer]
      view: [reader]
    attachTo:
      resource: Ticket
      recordId: $record.id
      field: document
KeyCurrent shape and default
descriptionString, empty
triggermanual, or an object with resource/event/transition/manual
conditionAEL expression, empty; used in event subscription
formatString, default html
filenamePlaceholder-bearing string, default <templateName>.html
bodyTemplate text, empty
permissions.generate, .viewIndependent role arrays
parametersArray of name/type/required/default/label declarations
dataNamed data-source mapping, described in §39.3
layoutPage/layout metadata, described in §39.5
attachToResource, record-ID expression/convention, and field
notificationNotification configuration connected through generated history

Setting only format: markdown does not automatically change the parser’s default .html filename. Authors should supply a filename appropriate to the requested format; binary downgrade is the separate exception that renames it. The current native parser does not reject every unrecognized format or unused option. The xlsx.yaml input demonstrates unsupported format acceptance rather than spreadsheet generation.

39.3 Input record, parameters, and named data sources

Manual generation takes the template name from the path and other request fields as parameters. A body recordId, with either the template’s declared resource or a request resource, lets the engine load $record context from that resource’s table. A missing row falls back to an empty record; it does not necessarily fail generation. This lookup uses direct SQL, not resource get RBAC.

Parameter declarations default type to string and required to true. The current generation handler copies supplied values but does not enforce the full parameter schema or apply declaration defaults. The checked required note with a default is omitted successfully and renders empty. Request fields resource and recordId also remain visible in the copied parameter object.

Record fields first populate the flat context. Explicit data names then override matching context keys:

Data declarationAssembled value
ticket: $recordThe loaded/trigger record under ticket
fixed: {static: {site: Demo}}Object whose configured values are strings, with environment expansion
rows: {source: Ticket, filter: ..., single: false}Direct source-table query, filtered in memory
total: {computed: ...}AEL against record/parameters; failures become null
past: {history: true, limit: 100}Best-effort trigger-resource history query

Query filters have $record for the triggering record and $row/$this for the candidate row, plus parameters and bare-field fallback. The template engine does not install a general cross-resource AEL query service in computed data sources. Source-query sort is parsed but not applied by the current loop; single selects its first returned row. The data-order.yaml example compares a declared descending order with the actual generated sequence.

History data reads use the trigger resource and record ID. The current query orders by at, while the checked history table uses createdAt; the example therefore renders no history entries despite existing history rows. The probe records this boundary instead of interpreting empty output as absence of history. Direct queries also bypass resource scopes, field filtering, and ordinary soft-delete handling. A template’s own permissions are the access boundary at its API, not a promise to inherit every source resource’s read policy.

39.4 Interpolation and event context

Body placeholders support dotted context lookup, formats, system values, and iteration:

FormMeaning
{title}, {ticket.title}Flat or dotted context value
`{amountmoney}`
{$actor.id}, {$actor.name}Available requesting/trigger actor attributes
{$params.note}Supplied generation parameter
{$date}, {$datetime}Current system date/time
{#each rows}…{/each}Repeat over an array; access the current item as rows
{$index} inside eachZero-based item index

For example, {#each rows}{$index}:{rows.title};{/each} produces 0:A;1:B; for two rows. A bare {title} inside that block still refers to the outer context. $item is a workflow convention, not the template loop’s item name. Missing placeholders render empty. Format helpers include money, integer, decimal2, percentage, date, datetime, duration, and boolean; unsupported labels fall back to ordinary value text. Their numerical conversion is observable: 0.125 with percentage formatting produces 0.1%, not a multiplication by 100.

Filename interpolation has context/system placeholders but no loop expansion or supplied actor/parameter object. A filename may therefore resolve differently from the body even when its braces look similar.

Event templates subscribe to history topics. event: create, update, and delete map to history names created, updated, and deleted. Other event names are used directly. For event: transition, the current convention appends d to a transition name that does not already end in d; it is not a general English past-tense converter. The corresponding history event must exist and actually be published.

The subscriber extracts captured data, supplies the envelope record ID when needed, evaluates condition, and enqueues a generation job. Condition runs before full-record loading. A condition on an uncaptured amount can suppress an event template even when the stored amount is positive. The paired fixture records that behavior.

The worker subsequently loads the current record and overlays the captures, preserving captured values over current ones. Unlike ordinary notifications, event templates can therefore obtain uncaptured fields from storage. The example captures title but renders amount from the full row. This differs from the inherited statement that templates can only render captured fields. Actor metadata is best-effort; the checked event path renders an empty actor name while manual generation renders the supplied username.

39.5 Output formats, layout, and downgrade

Requested formatChecked output without a registered document renderer
markdownInterpolated Markdown bytes
htmlMarkdown converted to HTML by the native helper
pdf, docxInterpolated Markdown, renamed to .md, with a downgrade notice
Other string, such as xlsxNative fallback writes text; no format-specific renderer or rejection

PDF/DOCX generation checks an optional document-renderer interface. The chapter’s build has no registered renderer. A successful downgraded generation response includes documentId, template, actual filename, format: md, requestedFormat, formatDowngraded: true, and a notice. This proves the fallback response, not PDF or DOCX production.

The later document record and download have a discrepancy: they retain the requested format. The checked PDF example downloads Receipt-t1.md with Markdown content but a format: pdf member. A client cannot treat that member alone as the actual content type. The arbitrary xlsx case has no equivalent downgrade flag, and the independent modeller rejects that format.

Layout parses pageSize (default letter), orientation (portrait), margins, header/footer, watermark text, and font: {family, size} (Helvetica/10 by default). It would be supplied to a registered binary renderer. It is not consumed by the Markdown/HTML/fallback paths. Flat fontFamily/fontSize examples in older descriptions are not the builder’s nested font shape.

39.6 Storage, references, and generated history

domain.documentStorage accepts provider (default filesystem), basePath, structure (default {domain}/{resource}/{year}/{month}/), and S3-related bucket/region/prefix metadata. Current storage writes files under the configured base and expanded structure. The storage-provider.yaml example selects s3 but still writes a local file; a provider string does not activate S3 storage. The platform book owns any actual storage-provider implementation.

Generation creates a document UUID and stores metadata identifying the template, resource/record, filename, path, size, generating user, time, and format. A write failure returns STORAGE_FAILED; the disposable invalid-directory example checks the resulting HTTP 500 and absence of a document record.

Filename uniqueness is the author’s concern in the checked implementation. Opening a reused filename truncates its existing contents. The duplicate-filename example generates two document IDs into the same path; downloading the first ID then returns the second generation’s contents. A new metadata ID does not make the underlying file immutable or versioned.

attachTo attempts an internal resource update with the new document ID. It uses the trusted __system__ identity and admin role. The record-ID resolver supports literal IDs and $record/$record.<path> conventions; it is not a general AEL expression evaluator. Attachment failure does not fail generation. The examples compare a successful attachment with a nonexistent destination field and verify the stored record separately.

Generation can fire the resource’s trigger: template history events. It adds documentId to the event context; a template-level notification is desugared through that generated history path. The event-driven example waits for both the stored document and the resulting local notification log. This establishes that chain, not a general email-attachment protocol or binary attachment delivery.

The worker queue is in memory and bounded at 1024 jobs; a full queue drops the new job with a warning. Deferred generation cannot change the triggering write’s response. Stored files, document metadata, record attachment, and history are not one rollback transaction. Queue durability across process termination and retry of failed jobs are not implemented by these declarations.

39.7 Permissions, endpoints, and recovery

Template generate and view permission arrays are independent. Empty arrays mean admin/administrator only; *, authenticated, and concrete roles have explicit matching behavior. Nonempty permission arrays do not automatically let an administrator bypass the listed grants. Catalog/detail visibility admits a caller allowed to generate or view; document download requires view. The checked writer can generate and is denied download, while reader can download.

Routes under /api/v1/{domain} are:

MethodSuffixPurpose
GET/templates, /templates/{name}Definitions visible to the caller
POST/templates/{name}/generateManual generation
GET/documentsBounded document metadata list
GET/documents/{id}JSON content and document metadata
GET/documents/{id}/metadataMetadata without content

Unknown templates/documents return NOT_FOUND; missing document IDs use VALIDATION_ERROR; denied operations use FORBIDDEN. A generation handler can return GENERATION_FAILED or STORAGE_FAILED. Downloads here are JSON responses containing a content string, not a binary streaming endpoint.

Document authorization resolves the document’s current template definition. If that definition is absent, the handlers skip its permission check. The missing-template-access probe simulates that state in the disposable metadata table and tests anonymous download. Removing a definition therefore requires separate access/recovery consideration; it does not safely archive its documents. List filtering happens after the bounded database query, so returned count is not a complete count of all accessible documents.

The manual handler does not apply the event subscription’s condition check; the manual-condition fixture successfully generates despite condition: false. Generation permission, source record selection, event eligibility, and document view permission must be considered independently.

Model export can succeed while dropping templates and documentStorage entirely. The checked ordinary template loses them on export and source-free registry restoration. A template that desugars a notification instead reaches the exporter’s subsystem rejection. Source-backed restoration retains the definitions. The evidence records both paths and the modeller’s separate diagnostics, including its rejection of captured generated documentId as an undeclared resource field.

The verification record identifies source hashes, actual files, responses, event observations, and focused tests. These checks do not assert PDF/DOCX rendering, remote storage, an external provider, a browser layout, or durable queue recovery.