@aotter/mantle 0.1.0-alpha.9 → 0.1.2-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/README.md +38 -38
  2. package/dist/cli/generate.d.ts +10 -1
  3. package/dist/cli/generate.d.ts.map +1 -1
  4. package/dist/cli/generate.js +49 -4
  5. package/dist/cli/generate.js.map +1 -1
  6. package/dist/cli/main.js +0 -8
  7. package/dist/cli/main.js.map +1 -1
  8. package/dist/codegen/emitMantleModule.js +8 -0
  9. package/dist/codegen/emitMantleModule.js.map +1 -1
  10. package/docs/adapter-guide.md +23 -26
  11. package/docs/adr/0008-structured-diagnostic-shape.md +7 -2
  12. package/docs/adr/0010-locale-and-translates.md +14 -16
  13. package/docs/adr/0011-adapter-port-spec.md +2 -1
  14. package/docs/adr/0014-auth-better-auth-and-multi-tenant-mcp.md +100 -0
  15. package/docs/adr/0018-core-starters-repository-boundary.md +3 -0
  16. package/docs/adr/0019-sealed-manifest-runtime-pipeline.md +38 -2
  17. package/docs/adr/0020-builtin-handler-contracts-and-matched-upsert.md +199 -0
  18. package/docs/adr/0021-retire-starter-scaffolding.md +30 -0
  19. package/docs/adr/0022-caller-observed-version-occ.md +212 -0
  20. package/docs/adr/0023-port-failure-contract.md +69 -0
  21. package/docs/adr/0024-manifest-native-schema-tables.md +260 -0
  22. package/docs/adr/README.md +19 -3
  23. package/docs/adr/adr-lite-803-request-diagnostics.md +38 -0
  24. package/docs/adr/adr-lite-808-route-readiness.md +47 -0
  25. package/docs/adr/adr-lite-809-bounded-public-content.md +71 -0
  26. package/docs/adr/adr-lite-812-native-parity.md +150 -0
  27. package/docs/adr/adr-lite-823-home-statistics.md +64 -0
  28. package/docs/adr/adr-lite-842-mcp-authoring.md +30 -0
  29. package/docs/adr/adr-lite-861-admin-webmcp.md +42 -0
  30. package/docs/adr/adr-lite-909-admin-ui-kit.md +37 -0
  31. package/docs/api-mcp-authorization.md +3 -664
  32. package/docs/auth-hosting-model.md +4 -4
  33. package/docs/cloudflare-low-level-composition.md +3 -104
  34. package/docs/deferred-lifecycle-queues.md +2 -243
  35. package/docs/design-atoms.md +16 -796
  36. package/docs/direct-authoring.md +5 -0
  37. package/docs/examples/minimal-worker/README.md +37 -0
  38. package/docs/examples/minimal-worker/manifests/site.yaml +25 -0
  39. package/docs/examples/minimal-worker/package.json +26 -0
  40. package/docs/examples/minimal-worker/smoke.mjs +23 -0
  41. package/docs/examples/minimal-worker/src/index.ts +4 -0
  42. package/docs/examples/minimal-worker/tsconfig.json +17 -0
  43. package/docs/examples/minimal-worker/wrangler.jsonc +22 -0
  44. package/docs/handbook/cloudflare/authentication.md +167 -0
  45. package/docs/handbook/cloudflare/bindings.md +236 -0
  46. package/docs/handbook/cloudflare/conventional-worker.md +162 -0
  47. package/docs/handbook/cloudflare/deferred-hooks-queues.md +171 -0
  48. package/docs/handbook/cloudflare/deploy-and-operate.md +105 -0
  49. package/docs/handbook/cloudflare/low-level-composition.md +169 -0
  50. package/docs/handbook/cloudflare/media-r2.md +216 -0
  51. package/docs/handbook/cloudflare/public-web.md +144 -0
  52. package/docs/handbook/concepts/authorization.md +116 -0
  53. package/docs/handbook/concepts/four-atoms.md +173 -0
  54. package/docs/handbook/concepts/lifecycle-and-locales.md +142 -0
  55. package/docs/handbook/concepts/mcp-and-agents.md +109 -0
  56. package/docs/handbook/concepts/procedures-and-triggers.md +221 -0
  57. package/docs/handbook/concepts/runtime-and-adapters.md +177 -0
  58. package/docs/handbook/concepts/views.md +191 -0
  59. package/docs/handbook/examples/commerce-transaction.md +813 -0
  60. package/docs/handbook/examples/guarded-api.md +427 -0
  61. package/docs/handbook/examples/intake-form.md +319 -0
  62. package/docs/handbook/examples/legal-documents.md +218 -0
  63. package/docs/handbook/examples/procurement-approvals.md +240 -0
  64. package/docs/handbook/examples/publication.md +240 -0
  65. package/docs/handbook/examples/reservation.md +220 -0
  66. package/docs/handbook/navigation.json +63 -0
  67. package/docs/handbook/reference/authorization.md +295 -0
  68. package/docs/handbook/reference/diagnostics.md +183 -0
  69. package/docs/handbook/reference/manifest.md +132 -0
  70. package/docs/handbook/reference/procedure.md +263 -0
  71. package/docs/handbook/reference/schema.md +250 -0
  72. package/docs/handbook/reference/site-config.md +233 -0
  73. package/docs/handbook/reference/surface.md +207 -0
  74. package/docs/handbook/reference/trigger.md +193 -0
  75. package/docs/handbook/reference/view.md +256 -0
  76. package/docs/handbook/start/project-and-cli.md +122 -0
  77. package/docs/handbook/start/quickstart-worker.md +193 -0
  78. package/docs/labels.md +3 -1
  79. package/docs/media-uploads.md +3 -184
  80. package/docs/migration-0.1.2.md +60 -3
  81. package/docs/performance-harness.md +127 -10
  82. package/docs/release-process.md +85 -231
  83. package/docs/schema-indexes.md +3 -180
  84. package/docs/sealed-pipeline-ownership.md +6 -5
  85. package/docs/spec-only-host-adoption.md +158 -0
  86. package/docs/transaction-patterns.md +5 -0
  87. package/package.json +21 -25
  88. package/skills/README.md +4 -4
  89. package/skills/develop/SKILL.md +23 -28
  90. package/skills/install/SKILL.md +55 -147
  91. package/skills/provision/SKILL.md +4 -3
  92. package/skills/theme/SKILL.md +6 -6
  93. package/skills/update/SKILL.md +32 -68
  94. package/dist/cli/create.d.ts +0 -2
  95. package/dist/cli/create.d.ts.map +0 -1
  96. package/dist/cli/create.js +0 -243
  97. package/dist/cli/create.js.map +0 -1
  98. package/dist/cli/update.d.ts +0 -2
  99. package/dist/cli/update.d.ts.map +0 -1
  100. package/dist/cli/update.js +0 -413
  101. package/dist/cli/update.js.map +0 -1
  102. package/dist/provision/renderProvisionBundle.d.ts +0 -70
  103. package/dist/provision/renderProvisionBundle.d.ts.map +0 -1
  104. package/dist/provision/renderProvisionBundle.js +0 -367
  105. package/dist/provision/renderProvisionBundle.js.map +0 -1
  106. package/dist/provision.d.ts +0 -2
  107. package/dist/provision.d.ts.map +0 -1
  108. package/dist/provision.js +0 -2
  109. package/dist/provision.js.map +0 -1
@@ -0,0 +1,142 @@
1
+ ---
2
+ description: Choose between publishing and operational Schemas, and understand how site locales, localized Schemas and translation children fit together.
3
+ ---
4
+ # Lifecycle and locales
5
+
6
+ Two per-Schema decisions shape how an entry behaves for its whole life: which state machine it follows, and whether it carries a locale. Both are declared on the [Schema](../reference/schema.md); neither is a site-wide setting.
7
+
8
+ ## Publishing versus operational
9
+
10
+ `spec.lifecycle` is `publishing` (the default) or `operational`. The modes mix freely inside one site.
11
+
12
+ **`publishing`** is for content a person stages and then releases: posts, pages, announcements, product copy. The point of the mode is that a draft exists and is not readable by the public until someone publishes it.
13
+
14
+ **`operational`** is for records written as a side effect rather than drafted: submissions, inquiries, orders, inventory snapshots, grant and audit rows. The point of the mode is that the row is real the moment it is created. Declare it on any Schema whose rows a human should inspect and correct, never stage and publish.
15
+
16
+ | `publishing` — from | To |
17
+ |---|---|
18
+ | `draft` | `published`, `archived` |
19
+ | `published` | `archived`, `draft` |
20
+ | `archived` | `draft` |
21
+
22
+ | `operational` | Behavior |
23
+ |---|---|
24
+ | On create | `status: published` immediately |
25
+ | Editing | In place, in any status |
26
+ | Transitions | None. Publish, unpublish and archive all reject. |
27
+
28
+ Any transition the machine does not allow returns `CONFLICT` (HTTP 409). That includes every transition request against an operational Schema, and deleting a `published` entry of a publishing Schema — unpublish it first. Operational entries can be deleted in any status. A builtin `archive` Procedure may only target a publishing Schema.
29
+
30
+ `status: published` on an operational row is not a grant of public read access. Reads are still authorized by the [View](./views.md) that exposes them.
31
+
32
+ ### What each surface shows
33
+
34
+ | Surface | `publishing` | `operational` |
35
+ |---|---|---|
36
+ | Admin | Draft and published buckets, publish and unpublish controls, archive | Flat list, no lifecycle chrome; `uiSchema.list` supplies the columns |
37
+ | Staff MCP | `create_draft_<schema>`, `update_draft_<schema>` | `create_record_<schema>`, `update_record_<schema>` |
38
+ | Staff MCP, both modes | `request_publish`, `unpublish_entry`, `archive_entry`, `delete_entry` | same generic lifecycle tools |
39
+
40
+ ### Procedure-managed collections
41
+
42
+ Root `schema.readOnly: true` marks a collection whose authority lives in its declared Procedures, not in generic authoring. Staff MCP emits no `create_*` or `update_*` tool for it, and Admin's generic create, update, status change and delete return `CONFLICT` with a message saying the Schema is read-only on generic authoring surfaces. Declared Views and Procedures keep working. Use it for operational mirrors, projections and audit rows.
43
+
44
+ ## Locales in three layers
45
+
46
+ Localization is not one switch. Three independent layers have to agree.
47
+
48
+ | Layer | Where | What it decides |
49
+ |---|---|---|
50
+ | `Schema.spec.localized` | Manifest | Whether rows of this collection may carry `data.locale` |
51
+ | `site_config.locales` | Adapter `siteDefaults.locales`, boot-synced into the `site_config` row | Which locale tags exist for this deployment; the first entry is the canonical locale |
52
+ | `data.locale` | The entry | Which locale this particular row is |
53
+
54
+ `siteDefaults.locales` is code-owned: Core rewrites the stored row at boot whenever the declared list differs, so the code stays canonical. Brand, title and description seed once and are then edited through site settings. See [Site defaults and site_config](../reference/site-config.md).
55
+
56
+ ### Canonical tags
57
+
58
+ Mantle accepts a deliberately narrow subset of BCP 47: a two- or three-letter language, plus an optional two-letter region. Mixed spellings are canonicalized, so `zh-tw`, `ZH_TW` and `zhTW` all become `zh-TW`, and the list is deduplicated in place. Anything else fails at boot with `InvalidSiteDefaultsError`.
59
+
60
+ > **Script subtags are unsupported**
61
+ > `zh-Hant`, `zh-Hans`, `sr-Latn` and `sr-Cyrl` are valid BCP 47 but rejected in this version. Use region tags: `zh-TW` for Traditional Chinese, `zh-CN` for Simplified.
62
+
63
+ ### The write-time gate
64
+
65
+ Every authoring path — Admin, Staff MCP and builtin Procedures — runs the same guard, per request, against the current site locales.
66
+
67
+ | Condition | Result |
68
+ |---|---|
69
+ | Non-localized Schema, `data.locale` present | `INPUT_VALIDATION_FAILED` |
70
+ | Localized Schema, `data.locale` missing or empty | `INPUT_VALIDATION_FAILED`, skipped for partial draft saves |
71
+ | Localized Schema, `data.locale` not in the site locales | `INPUT_VALIDATION_FAILED`, with the enabled locales as candidates |
72
+ | Site locales list is empty | Membership is not checked |
73
+
74
+ `locale` is a reserved data field. A non-localized Schema that declares it is rejected outright; when such a Schema genuinely needs a language value, name it after its domain meaning — `replyLocale` on a support ticket, `orderLocale` on an order — and validate it with an `enum` like any other field.
75
+
76
+ ### Boot checks versus per-request resolution
77
+
78
+ Boot validates shape only: the locale tags canonicalize, every `translates` reference resolves, and a `localized: true` Schema has at least one site locale (`SCHEMA_LOCALIZED_REQUIRES_SITE_LOCALES`). The active locale set is read from `site_config` per request, so changing the list does not require a redeploy of the manifest — but it does require the code-owned `siteDefaults` to agree, because boot resynchronizes the row.
79
+
80
+ ## Versions of one entity versus independent rows
81
+
82
+ Two shapes are legal, and the choice is about identity, not about language count.
83
+
84
+ **A standalone localized Schema** treats each locale row as an independent record. Use it when nothing is shared between languages except a naming convention. A blog whose translations are independent posts does this: one localized `posts` Schema with `uniqueIndexes: [[slug, locale]]`.
85
+
86
+ **A non-localized parent plus a localized `translates` child** treats locale rows as versions of one entity. Use it when several rows describe the same thing and editors need to see which languages are missing. Only this shape powers Admin's translation grouping and completeness; Admin renders the child as locale tabs inside the parent's editor rather than as its own collection.
87
+
88
+ ```yaml
89
+ apiVersion: cms.mantle.aotter.net/v1
90
+ kind: Schema
91
+ metadata:
92
+ name: products
93
+ spec:
94
+ title: Products
95
+ localized: false
96
+ lifecycle: publishing
97
+ uniqueIndexes: [[sku]]
98
+ schema:
99
+ type: object
100
+ additionalProperties: false
101
+ required: [sku, priceMinor]
102
+ properties:
103
+ sku: { type: string, pattern: "^[A-Z0-9-]+$" }
104
+ priceMinor: { type: integer, x-mcp-hint: money-minor }
105
+ ---
106
+ apiVersion: cms.mantle.aotter.net/v1
107
+ kind: Schema
108
+ metadata:
109
+ name: product-translations
110
+ spec:
111
+ title: Product translations
112
+ localized: true
113
+ translates: { parent: products, on: sku }
114
+ lifecycle: publishing
115
+ uniqueIndexes: [[sku, locale]]
116
+ indexes: [[locale, sku]]
117
+ schema:
118
+ type: object
119
+ additionalProperties: false
120
+ required: [sku, name]
121
+ properties:
122
+ sku: { type: string, pattern: "^[A-Z0-9-]+$" }
123
+ locale: { type: string }
124
+ name: { type: string, minLength: 1 }
125
+ summary: { type: string, x-mcp-hint: markdown }
126
+ ```
127
+
128
+ The parent holds what every language shares and stays non-localized. The child sets `localized: true`, declares `locale` without listing it in `required` — the write-time gate enforces presence — and owns at least one content field besides the join field and `locale`. A parent that is itself localized, a missing join field on either side, or a child with no content field are all rejected at parse or validate time; the codes are listed in the [Schema reference](../reference/schema.md#translates).
129
+
130
+ When you keep parallel locale rows in step, translate display strings only. Field names, option values, step identifiers and result keys must stay identical across locales, or the same View and the same MCP tool stop describing the same thing.
131
+
132
+ The full worked version of this pattern, with a locale-parameterized public View and its REST response, is [Publication](../examples/publication.md).
133
+
134
+ ## Source
135
+
136
+ - [`packages/mantle-spec/src/domain/service/LifecycleStateMachine.ts`](../../../packages/mantle-spec/src/domain/service/LifecycleStateMachine.ts)
137
+ - [`packages/mantle-spec/src/domain/service/LocaleCanonicalizer.ts`](../../../packages/mantle-spec/src/domain/service/LocaleCanonicalizer.ts)
138
+ - [`packages/mantle-spec/src/domain/service/SiteDefaultsValidator.ts`](../../../packages/mantle-spec/src/domain/service/SiteDefaultsValidator.ts)
139
+ - [`packages/mantle-spec/src/domain/model/SiteConfig.ts`](../../../packages/mantle-spec/src/domain/model/SiteConfig.ts)
140
+ - [`packages/mantle-runtime/src/domain/service/io/EntryWriteGuard.ts`](../../../packages/mantle-runtime/src/domain/service/io/EntryWriteGuard.ts)
141
+ - [`packages/mantle-runtime/src/infrastructure/mcp/McpToolCatalog.ts`](../../../packages/mantle-runtime/src/infrastructure/mcp/McpToolCatalog.ts)
142
+ - [`skills/develop/SKILL.md`](../../../skills/develop/SKILL.md)
@@ -0,0 +1,109 @@
1
+ ---
2
+ description: Mantle serves /mcp and /mcp/staff from the same Manifest — tool naming, the OAuth model, connecting a client, llms.txt, WebMCP and skills.
3
+ ---
4
+ # MCP and agents
5
+
6
+ Mantle is an MCP server out of the box. Nothing is registered, exported or annotated to make it one: the same compiled plan that produces REST and Admin also produces the tool catalog, so an agent and a browser reach identical behavior through different transports. This page covers the two surfaces, how tools are named, how a client authenticates, and the rest of the agent-facing surface area.
7
+
8
+ ## Two surfaces
9
+
10
+ | Mount | Caller | Exposes |
11
+ |---|---|---|
12
+ | `/mcp` | Any authenticated OAuth caller; anonymous requests get `401` | Views with `surface: public`, and Procedures reached by an MCP Trigger with `surface: public` |
13
+ | `/mcp/staff` | Authenticated caller holding a staff role | Views with `surface: staff`, the generic authoring tools (rank-gated at `tools/call`), Procedures reached by an MCP Trigger with `surface: staff` |
14
+
15
+ Both accept tokens for one canonical protected resource, `${PUBLIC_ORIGIN}/mcp`. `/mcp/staff` is a stricter server-side role projection, not a second OAuth audience.
16
+
17
+ ## Tool naming
18
+
19
+ A tool name is derived from a manifest name by `mcpToolNameSegment`: lowercased, with `-` replaced by `_`.
20
+
21
+ | Tool | Produced by | Surface |
22
+ |---|---|---|
23
+ | `query_view_<segment>` | Any View | The View's own `surface` |
24
+ | `create_draft_<schema>`, `update_draft_<schema>` | A Schema with `lifecycle: publishing` | Staff |
25
+ | `create_record_<schema>`, `update_record_<schema>` | A Schema with `lifecycle: operational` | Staff |
26
+ | `request_publish`, `unpublish_entry`, `archive_entry`, `delete_entry` | Present when an applicable Schema exists | Staff |
27
+ | `create_media_upload`, `commit_media_upload` | Media storage bound and at least one purpose declared | Staff |
28
+ | `<procedure segment>` | A Trigger with `source.kind: mcp` | The Trigger's `source.surface` |
29
+
30
+ A Schema whose root `schema` sets `readOnly: true` gets no authoring tools; its declared Procedures still work. Update tools add required `id` and `expected_version` arguments, and fields carrying `x-mantle-bind` are stripped from authoring tool schemas because the runtime stamps them. Those generic names and the `create_draft_`, `update_draft_`, `create_record_`, `update_record_` and `query_view_` prefixes are reserved; a collision is rejected at validation with `MCP_TOOL_NAME_COLLISION`.
31
+
32
+ Procedures are never exposed on their own. A Procedure becomes a tool only through a Trigger of `kind: mcp`, exactly as it becomes a route only through a Trigger of `kind: http`. Writing a Procedure with no Trigger gives you typed logic that nothing can call from outside — which is what a guard Procedure or a cron-invoked Procedure wants. See [Writes: Procedures, Triggers and hooks](./procedures-and-triggers.md).
33
+
34
+ ## The OAuth model
35
+
36
+ The Cloudflare adapter runs one Better Auth 1.7 instance for staff identity, authorization, consent, client registration and MCP resource verification. Client identity is CIMD-first — the MCP 2026-07-28 Client ID Metadata Document profile, which is why the Worker needs the `global_fetch_strictly_public` flag to fetch client metadata across the public Internet boundary — with unauthenticated legacy DCR kept only as a bounded compatibility path for older clients, on the previous provider's 90-day default lifetime. One non-colon scope, `mcp`, is advertised in `scopes_supported`, because clients such as claude.ai reject colon-shaped scopes; per-surface enforcement then happens server-side, not through scope strings. Authorization is session-bound: the JWT's originating Better Auth session must still exist and be unexpired, so signing out of Admin also ends that session's MCP access, and a refresh token is not an independent authorization. Unauthenticated requests to either mount answer `401` with a `WWW-Authenticate` challenge pointing at the RFC 9728 protected-resource metadata document served under the auth mount. Authorization endpoints live under `/api/auth/oauth2/*` and are discovered from the advertised metadata, never hard-coded.
37
+
38
+ ## Connecting a local client
39
+
40
+ Start the dev server and use the exact origin it prints. Before touching client configuration, confirm the endpoint is reachable and protected:
41
+
42
+ ```sh
43
+ curl -i http://localhost:8787/mcp
44
+ ```
45
+
46
+ An OAuth-protected endpoint answers `401` with a `WWW-Authenticate` resource-metadata challenge before sign-in. A `503 setup_incomplete` instead means Auth configuration is missing; see [Authentication](../cloudflare/authentication.md).
47
+
48
+ Prefer the client's native remote HTTP and OAuth support. Use a standard HTTP-to-stdio bridge only when the client accepts stdio MCP servers and cannot connect to remote HTTP directly:
49
+
50
+ ```sh
51
+ npx -y mcp-remote http://localhost:8787/mcp
52
+ ```
53
+
54
+ Mantle owns no local proxy and no auth-bypass mode. After connecting, inspect `tools/list`, then make one read-only `query_view_*` call before invoking any mutation — it proves the credential, the surface and the data path in one step that cannot damage anything. Use project-scoped client configuration where the client offers it, and never commit OAuth tokens or the bridge's token cache.
55
+
56
+ > **Discovery is not enforcement**
57
+ > `tools/list` filtering is UX. Every `tools/call` re-evaluates the manifest predicates and the guard through the same evaluator REST uses, so a guessed tool name gains nothing. See [Authorization](./authorization.md).
58
+
59
+ ## The agent-readable web surface
60
+
61
+ When a Worker mounts public pages, the same content is served in a form agents can read without parsing HTML:
62
+
63
+ - **Markdown mirrors.** Every entry page has a `.md` twin at the same path, and entry pages advertise it with `<link rel="alternate" type="text/markdown">`.
64
+ - **`llms.txt` indexes.** `GET /llms.txt` lists the site; `GET /:locale/llms.txt` lists one locale. Pages hold 50 entries, ordered `updatedAt DESC, id DESC`, with a forward `cursor`, a `Link: ...; rel="next"` header and a `## Continue` section.
65
+ - **Sitemap.** `GET /sitemap.xml` returns a urlset, or an index linking `/sitemap.xml?part=1&cursor=...` parts of up to 2,000 URLs each.
66
+
67
+ Only `status: published` entries appear anywhere in that set. Details are in [Public web, SEO and cache](../cloudflare/public-web.md).
68
+
69
+ ## WebMCP in the browser
70
+
71
+ `@aotter/mantle-web/webmcp` exposes public capabilities as tools inside a page, for browsers implementing the draft imperative WebMCP API. Importing the subpath has no side effect; registration starts only when `bindWebMcp()` is called.
72
+
73
+ ```ts
74
+ import { bindWebMcp } from "@aotter/mantle-web/webmcp";
75
+
76
+ const binding = await bindWebMcp();
77
+ // later, when the page or app scope ends
78
+ binding.dispose();
79
+ ```
80
+
81
+ It feature-detects `document.modelContext` and returns `{ supported: false }` on browsers without it. Only public capabilities are registered — staff capabilities never leave the server. Existing host tool names are inspected and skipped, never replaced. A server-backed page discovers the safe descriptors published at `GET /api/views` and calls the same-origin `GET /api/views/<name>` routes; a browser-local SPA passes `projectCallableCapabilities(plan, { surface: "public" })` and its own invoker. Procedure tools must still originate from an explicit public MCP Trigger, and invocation enters the runtime through that Trigger, so browser tools cannot bypass validation or authorization. See [Runtime pipeline and adapters](./runtime-and-adapters.md).
82
+
83
+ ## Skills for your coding agent
84
+
85
+ The installed SDK ships version-matched instructions for agents working on a Mantle project. Project them into the repository:
86
+
87
+ ```sh
88
+ pnpm exec mantle skills
89
+ pnpm exec mantle skills --check
90
+ ```
91
+
92
+ This copies every skill the installed package marks `projection: project` — the develop skill among them — into matching `.agents/skills/mantle-*` and `.claude/skills/mantle-*` paths. Both layouts receive identical bytes; `--check` detects drift without writing. Skills that act destructively or target one platform stay out of that set and are opt-in. Manifest generation never rewrites agent instructions.
93
+
94
+ For Claude Code, the same bundle is installable from the plugin marketplace at the exact installed version:
95
+
96
+ ```sh
97
+ /plugin marketplace add aotter/mantle@v<installed-version>
98
+ ```
99
+
100
+ Never point a versioned project at a mutable branch. See [Project layout and the CLI loop](../start/project-and-cli.md).
101
+
102
+ ## Source
103
+ - [`docs/adapter-guide.md`](../../../docs/adapter-guide.md)
104
+ - [`docs/adr/0014-auth-better-auth-and-multi-tenant-mcp.md`](../../../docs/adr/0014-auth-better-auth-and-multi-tenant-mcp.md)
105
+ - [`packages/mantle-spec/src/domain/service/McpToolNaming.ts`](../../../packages/mantle-spec/src/domain/service/McpToolNaming.ts)
106
+ - [`packages/mantle-web/README.md`](../../../packages/mantle-web/README.md)
107
+ - [`packages/mantle/README.md`](../../../packages/mantle/README.md)
108
+ - [`packages/adapters/cloudflare/README.md`](../../../packages/adapters/cloudflare/README.md)
109
+ - [`skills/develop/SKILL.md`](../../../skills/develop/SKILL.md)
@@ -0,0 +1,221 @@
1
+ ---
2
+ description: How writes work — typed Procedures with a code seam, the three Trigger kinds that bind them, builtin ops, lifecycle hooks and the HTTP envelope.
3
+ ---
4
+ # Writes: Procedures, Triggers and lifecycle hooks
5
+
6
+ Every write goes through a Procedure, and every Procedure that anything outside the runtime can reach has a Trigger. This page explains the split and the lifecycle hook contract. Field-level rules are in the [Procedure](../reference/procedure.md) and [Trigger](../reference/trigger.md) references.
7
+
8
+ ## A Procedure is a callable, not an endpoint
9
+
10
+ A Procedure declares typed `input`, typed `output`, optional `requires`, and one `handler`. It contains no path, no method and no tool name; it is transport-agnostic on purpose, so calling a Procedure name as a URL returns `404`. Exposing a write is a separate, explicit decision.
11
+
12
+ Invocation runs in a fixed order: static auth predicates, input validation, the optional guard Procedure, the handler, then output validation — which checks the returned value but does not strip extra fields.
13
+
14
+ The Procedure is also the only atom with a code seam. `handler: { kind: ref, ref: <key> }` names an opaque registration key — not a file path — that your project maps to a function in its `handlers` object. A key with no registered function fails at boot with `HANDLER_NOT_REGISTERED`.
15
+
16
+ ## A Trigger is the only binding
17
+
18
+ `Trigger.spec.target.procedure` names a declared Procedure; `spec.source` says what reaches it. There are three source kinds.
19
+
20
+ | `source.kind` | Binds to | Notes |
21
+ |---|---|---|
22
+ | `http` | `method` and `path` | `POST`, `PUT`, `PATCH`, `DELETE` only. `GET` is absent because reads belong to [Views](./views.md). The path must start `/api/`, must not collide with another Trigger or an adapter-reserved prefix, and may use OpenAPI `{param}` segments that auto-bind to same-named input fields. |
23
+ | `mcp` | `surface: public` or `staff` | The tool is named after the Procedure, lowercased with hyphens replaced by underscores. Surface controls discovery only; `requires` is re-evaluated on every `tools/call`. |
24
+ | `lifecycle` | `schema`, `on: [<hook>]`, optional `errorPolicy` | Fires around entry mutations. See [Lifecycle hooks](#lifecycle-hooks). |
25
+
26
+ One Procedure may carry several Triggers, and that is how the same handler becomes an HTTP endpoint, an MCP tool and a hook without duplicated logic. Adding a transport is additive: write another Trigger, leave the Procedure alone.
27
+
28
+ ## Builtin or `ref`
29
+
30
+ `handler.kind: builtin` is a thin shortcut over the storage adapter. The rule is simple: **use `builtin` when the body of the operation is "insert a row", "update a row" or "delete a row"; reach for `ref` when there is real business logic.** A guard Procedure can never be builtin.
31
+
32
+ | `op` | What it does | Input contract |
33
+ |---|---|---|
34
+ | `create` | Projects `input ∩ Schema.properties`, stamps `x-mantle-bind` fields, inserts. Status is `draft`, or `published` for an operational Schema. Returns the created `EntryRow`. | An object schema |
35
+ | `update` | Loads, merges the patch, bumps `version` under optimistic concurrency using the caller's observed `expectedVersion` (not `version+1`) | `id` (strict string) and `expectedVersion` (strict number), both required |
36
+ | `upsert` | With `match`, looks the row up by natural key: update with the caller token, or create when no row exists and no version was sent | `match` equals one `uniqueIndexes` tuple exactly, in order; no `id`; `expectedVersion` declared as strict number but not globally required |
37
+ | `delete` | Hard delete by id | `id` (strict string) required |
38
+ | `archive` | Transitions to `archived`, or `CONFLICT` if the machine disallows it | `id` required; publishing Schemas only |
39
+
40
+ `request_publish` and `publish` are deliberately not builtin ops. They are lifecycle operations, not CRUD primitives.
41
+
42
+ Every builtin write runs the same guards: locale gate, then a unique-index preflight. A race that slips past the preflight is caught by the database constraint and surfaces as `CONFLICT` (409) with no automatic retry.
43
+
44
+ ### Side-channel input fields
45
+
46
+ A Procedure's `input` is the contract with the caller, not with the Schema. It may declare fields the Schema does not — a Turnstile token, a honeypot value, a referrer. The builtin op projects `input ∩ Schema.properties` and silently drops the rest, so nothing extra is stored.
47
+
48
+ Those fields are still readable where it matters: a `before_create` or `before_update` hook receives the **original, pre-projection** input. Every `after_*` hook receives only the persisted `entry.data`. That asymmetry is why bot checks are `before_*` hooks and notifications are `after_*` hooks.
49
+
50
+ ## Lifecycle hooks
51
+
52
+ | Hook | Fires | Default `errorPolicy` |
53
+ |---|---|---|
54
+ | `before_create` | Before insert | `abort` |
55
+ | `after_create` | After insert | `continue` |
56
+ | `before_update` | Before an update, or a status transition whose target is not `published` | `abort` |
57
+ | `after_update` | After an update, or a status transition whose target is not `published` | `continue` |
58
+ | `before_delete` | Before delete | `abort` |
59
+ | `after_delete` | After delete | `continue` |
60
+ | `before_publish` | Before a transition to `published` | `abort` |
61
+ | `after_publish` | After a transition to `published` | `continue` |
62
+
63
+ > **Update hooks are not edit-only**
64
+ > There are no unpublish-specific or archive-specific hooks. `before_update` and `after_update` also fire for unpublish, archive and every other transition whose target is not `published`. A hook that assumes "the row was edited" will run on state changes you did not intend.
65
+
66
+ `abort` means a throwing handler cancels the surrounding mutation and the caller receives `LIFECYCLE_HOOK_REJECTED` (409). `continue` means the committed mutation stands: on the inline or `waitUntil` path the failure is logged and swallowed. Authors may set `errorPolicy` explicitly, but `abort` is rejected on a Trigger whose `on` list contains any `after_*` hook — a committed write cannot be un-committed.
67
+
68
+ Hooks are wired through the entry repository, so Admin, Staff MCP and builtin Procedures all fire the same hooks. When several lifecycle Triggers bind the same schema and hook, they fire **alphabetically by `Trigger.metadata.name`**; number them (`010-bot-check`, `020-rate-limit`) so the order is visible.
69
+
70
+ Handlers receive `ctx.event = { id, trigger, hook, schema, entry }`. `id` is stable across retries, `trigger` is the current Trigger name, and `entry` is `null` only for `before_create`; otherwise it is the pre-mutation row for `before_*` and the persisted row for `after_*`.
71
+
72
+ ### Deferred `after_*` delivery
73
+
74
+ With an optional `DeferredHookDispatcher`, `after_*` hooks leave the request path and run under the delivery adapter's at-least-once retry and dead-letter policy instead of being swallowed. Delivery is not transactional with the database and exactly-once is not promised, so handlers must be idempotent; the conventional key is `${ctx.event.id}:${ctx.event.trigger}`. Cloudflare wiring, the envelope and DLQ configuration are in [Deferred hooks with Queues](../cloudflare/deferred-hooks-queues.md).
75
+
76
+ ## The HTTP envelope
77
+
78
+ An HTTP Trigger wraps the handler's result as `{ "ok": true, "data": <result> }`, or returns the redacted diagnostic with the code's mapped status:
79
+
80
+ ```json
81
+ { "ok": false, "diagnostic": { "code": "INPUT_VALIDATION_FAILED", "path": "POST /api/contact#/name" } }
82
+ ```
83
+
84
+ For a builtin `create`, `data` is the whole `EntryRow`: `id`, `collection`, `status`, `version`, `data`, nullable `authorId`, millisecond `createdAt` and `updatedAt`, and `locale` on localized rows. Declare `spec.output` against that row, not against the envelope. The request body must be a JSON object; anything else is a 400, and an oversize body is a 413.
85
+
86
+ | Code | HTTP | When |
87
+ |---|---|---|
88
+ | `INPUT_VALIDATION_FAILED` | 400 | Input fails the converted schema, or the body is not a JSON object |
89
+ | `UNAUTHENTICATED` | 401 | No verified credential at all |
90
+ | `ENTITLEMENT_REQUIRED` | 402 | A guard Procedure denied the current business entitlement |
91
+ | `AUTH_DENIED` | 403 | Authenticated, but a `requires.auth` predicate was false |
92
+ | `NOT_FOUND` | 404 | Unknown entry id or View name |
93
+ | `CONFLICT` | 409 | Illegal lifecycle transition, or a unique-index collision |
94
+ | `LIFECYCLE_HOOK_REJECTED` | 409 | A `before_*` hook aborted the mutation |
95
+ | `OUTPUT_VALIDATION_FAILED` | 500 | The handler returned a value its `output` schema rejects |
96
+ | `HANDLER_NOT_REGISTERED` | 500 | A `ref` key has no registered function |
97
+ | `INTERNAL_ERROR` | 500 | Uncaught handler exception |
98
+
99
+ The full catalog is in [Diagnostic codes](../reference/diagnostics.md).
100
+
101
+ ## Worked example: a contact form
102
+
103
+ One builtin write, one `before_create` check that can abort it, one `after_create` notification that cannot.
104
+
105
+ ```yaml
106
+ apiVersion: cms.mantle.aotter.net/v1
107
+ kind: Schema
108
+ metadata:
109
+ name: contact-messages
110
+ spec:
111
+ title: Contact messages
112
+ lifecycle: operational
113
+ schema:
114
+ type: object
115
+ additionalProperties: false
116
+ required: [name, email, message]
117
+ properties:
118
+ name: { type: string, minLength: 1, maxLength: 80 }
119
+ email: { type: string, format: email }
120
+ message: { type: string, minLength: 1, maxLength: 4000 }
121
+ submittedAt: { type: integer, x-mcp-hint: timestamp-ms, x-mantle-bind: now }
122
+ ---
123
+ apiVersion: cms.mantle.aotter.net/v1
124
+ kind: Procedure
125
+ metadata:
126
+ name: send-contact-message
127
+ spec:
128
+ title: Send contact message
129
+ input:
130
+ type: object
131
+ additionalProperties: false
132
+ required: [name, email, message, botToken]
133
+ properties:
134
+ name: { type: string, minLength: 1, maxLength: 80 }
135
+ email: { type: string, format: email }
136
+ message: { type: string, minLength: 1, maxLength: 4000 }
137
+ botToken: { type: string, minLength: 1 }
138
+ output:
139
+ type: object
140
+ required: [id]
141
+ properties:
142
+ id: { type: string }
143
+ handler: { kind: builtin, op: create, schema: contact-messages }
144
+ ---
145
+ apiVersion: cms.mantle.aotter.net/v1
146
+ kind: Trigger
147
+ metadata:
148
+ name: contact-http
149
+ spec:
150
+ source: { kind: http, method: POST, path: /api/contact }
151
+ target: { procedure: send-contact-message }
152
+ ---
153
+ apiVersion: cms.mantle.aotter.net/v1
154
+ kind: Procedure
155
+ metadata:
156
+ name: check-contact-bot
157
+ spec:
158
+ input:
159
+ type: object
160
+ properties:
161
+ botToken: { type: string }
162
+ output: { type: object }
163
+ handler: { kind: ref, ref: check-contact-bot }
164
+ ---
165
+ apiVersion: cms.mantle.aotter.net/v1
166
+ kind: Trigger
167
+ metadata:
168
+ name: 010-contact-bot-check
169
+ spec:
170
+ source:
171
+ kind: lifecycle
172
+ schema: contact-messages
173
+ on: [before_create]
174
+ errorPolicy: abort
175
+ target: { procedure: check-contact-bot }
176
+ ---
177
+ apiVersion: cms.mantle.aotter.net/v1
178
+ kind: Procedure
179
+ metadata:
180
+ name: notify-contact-message
181
+ spec:
182
+ input:
183
+ type: object
184
+ properties:
185
+ name: { type: string }
186
+ email: { type: string }
187
+ message: { type: string }
188
+ output: { type: object }
189
+ handler: { kind: ref, ref: notify-contact-message }
190
+ ---
191
+ apiVersion: cms.mantle.aotter.net/v1
192
+ kind: Trigger
193
+ metadata:
194
+ name: 020-contact-notify
195
+ spec:
196
+ source:
197
+ kind: lifecycle
198
+ schema: contact-messages
199
+ on: [after_create]
200
+ errorPolicy: continue
201
+ target: { procedure: notify-contact-message }
202
+ ```
203
+
204
+ What each piece is doing:
205
+
206
+ - `botToken` is declared on the Procedure input but not on the Schema, so it is validated, read by the hook, and never stored.
207
+ - `010-contact-bot-check` runs first because Triggers on the same hook fire alphabetically. Throwing from its handler cancels the insert and the caller receives 409 `LIFECYCLE_HOOK_REJECTED`; nothing is written.
208
+ - `020-contact-notify` runs after the row exists and receives only `entry.data`. A failing mailer is logged, not fatal — the visitor's message is already saved.
209
+ - `submittedAt` is stamped by the runtime, so it is absent from the Procedure input and from Staff MCP authoring tools.
210
+ - Adding `{ kind: mcp, surface: public }` as a fourth Trigger would publish the same Procedure as an agent tool without touching a handler.
211
+
212
+ Register the two `ref` keys in the project's handlers map, then run the check loop from [Project layout and the CLI loop](../start/project-and-cli.md). The complete version with real Turnstile and email handlers is [Intake form](../examples/intake-form.md).
213
+
214
+ ## Source
215
+
216
+ - [`docs/adr/0001-four-atom-manifest-model.md`](../../../docs/adr/0001-four-atom-manifest-model.md)
217
+ - [`docs/deferred-lifecycle-queues.md`](../../../docs/deferred-lifecycle-queues.md)
218
+ - [`packages/mantle-spec/src/domain/model/ManifestGrammar.ts`](../../../packages/mantle-spec/src/domain/model/ManifestGrammar.ts)
219
+ - [`packages/mantle-runtime/src/domain/service/BuiltinProjector.ts`](../../../packages/mantle-runtime/src/domain/service/BuiltinProjector.ts)
220
+ - [`packages/mantle-runtime/src/infrastructure/http/createMantleRequestHandler.ts`](../../../packages/mantle-runtime/src/infrastructure/http/createMantleRequestHandler.ts)
221
+ - [`skills/develop/SKILL.md`](../../../skills/develop/SKILL.md)