# Templates

Templates are workflows curated by Adlass (routines + workflow + questions). Installing one copies
its routines and workflow into a Space of the caller's tenant, filled with the user's own answers;
the copy belongs to the tenant and can be edited. Nothing runs or sends before the user activates it.

`templates.*` catalog and install operations answer only while the marketplace platform switch is
on; off, the catalog is empty and a template reads as not found. Installations already made keep
working either way. `templates.list` returns `enabled` (the switch; added 2026-09-27, tech lead
decision): `true` with empty `items` means the marketplace is on but nothing is published yet.

Install, step by step:
1. `templates.list`, then `templates.get`: what the template does, what it needs (providers, plan
   features), what it creates, the permissions in plain language and every parameter with its
   `value_schema`, group and order.
2. Collect answers group by group. Pickers come from `templates.parameter_options` (Slack users,
   connections, folders, record types, options): never type an id. A `record_type` parameter with
   a packaged definition creates that record type when left blank or sent as `{mode: "create"}`;
   `{mode: "pick", record_type_id}` uses a published one of the Space instead.
   A definition may pin the record type's `key` (scripts name record types by key): create mode then
   always uses that key whatever name the person types, and `{mode: "pick"}` accepts only a type
   with that key, every packaged field with the same type, the same `unique` flags and the same
   select options; otherwise the plan answers `record_type_contract_mismatch` with the missing
   pieces in `gaps`. A script that merges on fields which are not unique fields (or exactly one
   unique key) of a packaged type is refused when the package is validated
   (`script_merge_on_not_unique`).
   A routine whose entry is a pinned script may call a provider API directly (Level 4) when its
   integration requirement declares `direct_http.paths`, a list of `{method, prefix}` (for example
   `{"method": "POST", "prefix": "/invoices"}`), and `requirements.capabilities` lists `direct_http`.
   The template's scripts reach only those methods and paths, whatever the grant allows: Adlass checks
   every direct HTTP call of a template script against the installed package (`direct_http_path_denied`).
   The plan's capability summary shows the paths. Such scripts write only with a `business_key`, never with
   `force` (static rule S-13 and the review check it; the platform refuses it at run time).
   Writing Shopify order tags: the script adds them with the GraphQL `tagsAdd` mutation through
   `http.request` (never `http.graphql`, which is read-only), so the package declares
   `{"method": "POST", "prefix": "/graphql.json"}` and the store's app needs `write_orders`. Tags are only
   added: `tagsRemove`, `orderUpdate` with `tags` and PUT/PATCH on an order fail static rule S-14. Copy the
   canonical snippet `shopify_order_tags` (read_docs("scripts")) and give each tag its own `business_key`. The
   `/graphql.json` path does not tell mutations apart: any mutation of the script goes through it, so the
   review checks the GraphQL documents of the source.
   Missing paths are `direct_http_paths_required`, a bad entry `direct_http_path_invalid`; direct
   HTTP for a routine run by its agent stays `capability_forbidden`.
   A `boolean` parameter is a switch. With `consent` the plan lists one `required_acknowledgements`
   entry of `kind: "consent"` (`operations: []`, `text`) while the value is being turned on, and
   only a person confirms it. With `admin_only` only an organization admin can turn it on
   (`admin_required` in the plan, `template_parameter_admin_required` on install, update,
   reconfigure and undo); anyone can turn it off. A boolean reaches a script only as a whole value
   of `entry.parameters` (`"[[param:timbrar]]"`).
3. Call `templates.install_plan` with the answers so far, as often as needed; it creates nothing.
   Each parameter has a `status` and a plain message; every pending item is an `actions` entry with
   the operation and arguments that fix it. A template that needs to write through a read-only Space
   grant comes back with `grant_read_only`; a person opens the grant and decides, nothing changes it
   silently.
4. `templates.install` when the plan is ready (a person confirms). The workflow is installed paused
   and a verification run of every routine starts; follow it with `templates.installations.get`.
5. When the installation is `READY`: `templates.installations.try` runs the try branch once with the
   installer as recipient, then `templates.installations.activate` switches the schedule on.
   A template's pages are app pages, packaged as `{ref, name, source, manifest, settings}`
   (read_docs("pages"), HTML source without `adlass-document:` images); install publishes them, and `activate` gives each one public link. Their
   manifest names tables and fields by key, so nothing is rewritten, and declares no `downloads`
   (`page_downloads_forbidden`; a manifest that does not parse is `page_manifest_invalid`). A later
   update publishes a new version; existing links move to it only when a person runs the update.

Human steps (agents never do them):
- Consents travel in the separate `acknowledged` argument, exactly as the plan's
  `required_acknowledgements` list them (operations and contract digest). Only a person gives them:
  in the web app wizard, or through the in-app assistant with the user's approval.
- Install, update, reconfigure, undo, uninstall, activate, try and reverify need a person's
  confirmation. External agents over MCP save a wizard draft (`templates.drafts.save`) and hand the
  user its `wizard_url` instead.

Actions the plan can ask for:
- `connect_provider`: connect the provider in the web app, then plan again.
- `reconnect_provider`: the connection lost access or misses a scope; reconnect it.
- `complete_connection_setup`: finish the connection setup (for Slack, choose the users who may
  send documents).
- `add_to_scope_group`: the chosen person is not in the connection's group (for Slack, the users
  who may send documents); add them to the connection.
- `open_grant`: open the Space grant. It answers the issue `grant_read_only`: the template needs to
  write, the grant is read only, and only a person may change that.
- `upgrade_plan`: the tenant's plan lacks a feature the template needs.
- `top_up_credits`: verification runs are billed to the tenant; add credits.
- `open_verification`: open the failed verification run to see what went wrong.

After install:
- `templates.reconfigure` changes answers (send only changed keys; the Configure form prefills the
  current values). `templates.update_plan` + `templates.update` move to a newer version; edited
  routines or workflow need a keep or take choice. Every change can be undone with
  `templates.installations.undo` (see `templates.installations.revisions`).
- Update, reconfigure and undo start a new verification round. An active installation is paused
  until that round passes and then switches itself back on; when the round fails it stays paused
  and needs `templates.installations.activate` again. Until a round passed, and once Adlass revoked
  the version, the installation's routines and workflow run through no path at all (runs, enable,
  triggers): `template_verification_required` or `template_version_revoked`.
- `templates.uninstall` with `preview: true` lists what happens; uninstall archives what the template
  created (routines, the workflow, pages: their public links are revoked), never deletes folders,
  record types or documents. Uninstall also deletes the provider webhook subscriptions that the
  installation's workflows created (for example Shopify's). The deletion is asynchronous. When one
  cannot be deleted, an alert lists the ones that remained so you can delete them by hand at the
  provider; nothing is left silently. `templates.installations.detach` keeps everything and
  forgets the template link.
- `templates.installations.for_object` tells whether a routine or workflow came from a template.

Queues in a package (M-16): a template may declare up to 5 `queues`, each consumed by the pinned script
entry of one of its routines, for example
`{"ref": "pedidos", "slug": "maqui-pedidos", "skill_ref": "facturar", "entry": {"alias": "cobrar"},
"ordered_by_key": true, "batch_size": 10, "webhook": {"grant_param": "shopify", "events": ["orders/paid"],
"keys": {"orders/paid": {"dedupe": "id", "order_key": "id", "order_key_prefix": "shopify:order:"}}}}`.
- `keys.<event>.dedupe` and `order_key` are dotted paths into the delivery body; `order_key_prefix` goes in
  front of the value (`shopify:order:5678`), so webhooks, scripts and reconciliation share one key shape.
  An ordered queue needs an order key for every event (`queue_keys_missing`); a delivery whose path does
  not resolve is stored dead (`order_key_missing`) and alerts the Adlass team. An ordered queue takes at
  most 10 items per batch.
- The install creates the queue (run as the installer) and its sources inactive: it never adopts an
  existing queue (`queue_slug_taken`), the webhook grant must belong to the installer
  (`queue_webhook_grant_not_owned`) and the slug of an installed queue cannot change (`queue_slug_immutable`).
- The provider subscriptions are created when the installation is activated; pause stops intake and
  batches but keeps the subscriptions. A queue the platform paused (`paused_reason` other than manual)
  blocks activation until its cause is fixed.
- Uninstall (or a version that drops the queue) leaves the queue paused with all its items and removes
  its sources; reinstalling needs the old queue deleted first. Undoing an update does not revert the
  settings of a queue.
- Reconciliation (M-20): an ordered queue with a webhook may add `"reconcile": {"alias": "conciliar",
  "hourly": true, "nightly": true, "grace_minutes": 15, "parameters": {...}, "guard": {"record_type_param":
  "documentos", "order_field": "pedido", "state_field": "estado_dian", "blocked_values": ["rechazado"]}}`.
  `alias` is a second script of the queue's routine, pinned in `definition.scripts` (`queue_reconcile_invalid`);
  the queue must be ordered (`queue_reconcile_requires_order_key`); `guard.record_type_param` names a
  `record_type` parameter whose `order_field` is a text field and `state_field` a text or single_select field
  (`queue_reconcile_guard_invalid`). The platform runs the script hourly (from the last complete run minus 24 h)
  and nightly (31 days); the installation date is the lower bound of every reconciliation and never moves.
  An order whose document the guard finds in a blocked state is never re-enqueued. The install fails with
  `template_install_failed` (cause `queue_reconcile_guard_unresolved`) when the guard's record type is not
  resolved. Nothing runs until the platform switch `ADLASS_RECONCILE_ENABLED` is on.

Platform operators only (REST from the web app session, never MCP or API keys): the button "Publicar en marketplace" on a
published workflow opens the authoring wizard (`/templates/authoring/<template_id>`): questions (curate the detected
values), QA data, verification (QA installation, approval) and publish. The operations behind it are
`templates.admin.export`, `templates.admin.get`, `templates.admin.save`, `templates.admin.parameter_options` and
`templates.admin.qa_plan` (pickers and plan over the draft, no published version needed), `templates.admin.submit`,
`templates.admin.qa_install` (`space_id`: the QA Space, chosen per call, that you manage and can install in),
`templates.admin.approve` (the exact candidate with a READY QA installation), `templates.admin.publish` (QA READY and
approved), `templates.admin.update_listing` (the catalog name, summary and category of the published version, without a
new version; the next publish replaces them with that version's metadata) and `templates.admin.deprecate`;
`templates.admin.revoke` (the first call requests, the next confirms) stays
in the operations console. One operator may do every step; nothing else is configured.

Authoring source: export needs a published workflow, and publishing the source workflow turns its schedule on,
so the source itself starts running at its next fire time. Keep it idle with `workflows.set_enabled`
(`enabled: false`) once it is published; export works on a disabled workflow. While the source is enabled
with an active schedule, `templates.admin.export` returns a `source_schedule_active` entry in `warnings`.
The exported schedule parameter proposes the source schedule as its `default` (a rule or cron only).
The queues of the source Space whose consumer is a packaged routine travel with it: script entry, batch size and
attempts within the package limits, a provider webhook whose subscription Adlass manages (its grant becomes the
provider's grant parameter, the subscription operations included) and a platform event. An agent entry, another
webhook, an event bound to one object or filtered by severity and a reconciliation stay out with an open note.
Published app pages of the source Space that read a record type of a packaged routine's scope travel as packaged
pages; their upload folder becomes a folder question, and a page with download slots gets the note
`page_downloads_forbidden` until the slots leave its manifest, a page with `adlass-document:` images
`page_documents_forbidden` until the source uses public image URLs instead. Every field of a script's
`entry.parameters` (routine or queue) becomes a question in its place (`entry_parameter`): text, a whole number or a
switch (a switch keeps the source value as default); lists, objects and decimals are notes. Mark a question
optional when the script has its own default: an unanswered optional question reaches the script as `null`.
