Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
feat(reports): report templates per project (#615)
Ben Senescu6e834a5622b4
diff --git a/.agents/skills/competitive-landscape/SKILL.md b/.agents/skills/competitive-landscape/SKILL.mdindex 22f9a707..5714761c 100644--- a/.agents/skills/competitive-landscape/SKILL.md+++ b/.agents/skills/competitive-landscape/SKILL.md@@ -67,6 +67,8 @@ Deliver through the `seo-report` skill, saving with `skill: "competitive-landsca`h1`: the market or category.+If a report template applies (see `seo-report`), its sections and tone replace this list.+Sections in this order:1. **The market read** — one or two opening sentences naming the leaders, the most winnable area, and the biggest barrier.diff --git a/.agents/skills/competitor-analysis/SKILL.md b/.agents/skills/competitor-analysis/SKILL.mdindex e77bf8bc..a6d00ef9 100644--- a/.agents/skills/competitor-analysis/SKILL.md+++ b/.agents/skills/competitor-analysis/SKILL.md@@ -69,6 +69,8 @@ Deliver through the `seo-report` skill, saving with `skill: "competitor-analysis`h1`: the competitor domain.+If a report template applies (see `seo-report`), its sections and tone replace this list.+Sections in this order:1. **Snapshot** — one or two opening sentences, then a table of the competitor's organic footprint (traffic estimate, keyword count, referring domains). Add the user's domain as a second row when comparing.diff --git a/.agents/skills/keyword-clustering/SKILL.md b/.agents/skills/keyword-clustering/SKILL.mdindex 199d51d1..9ed4e4d5 100644--- a/.agents/skills/keyword-clustering/SKILL.md+++ b/.agents/skills/keyword-clustering/SKILL.md@@ -63,6 +63,8 @@ Deliver through the `seo-report` skill, saving with `skill: "keyword-clustering"`h1`: the site or keyword set.+If a report template applies (see `seo-report`), its sections and tone replace this list.+Sections in this order:1. **The map** — one or two opening sentences: how many clusters, how many pages to create, how many to update, and any cannibalization found.diff --git a/.agents/skills/keyword-research/SKILL.md b/.agents/skills/keyword-research/SKILL.mdindex f65b5d48..b1d99b65 100644--- a/.agents/skills/keyword-research/SKILL.md+++ b/.agents/skills/keyword-research/SKILL.md@@ -64,6 +64,8 @@ Deliver through the `seo-report` skill, saving with `skill: "keyword-research"`.`h1`: the site or topic.+If a report template applies (see `seo-report`), its sections and tone replace this list.+Sections in this order:1. **The opportunity** — one or two opening sentences naming the best theme and why the site can win it now.diff --git a/.agents/skills/link-prospecting/SKILL.md b/.agents/skills/link-prospecting/SKILL.mdindex 463606e2..ec1248e3 100644--- a/.agents/skills/link-prospecting/SKILL.md+++ b/.agents/skills/link-prospecting/SKILL.md@@ -96,6 +96,8 @@ Use `get_serp_results` in batches for the most relevant patterns. Send at most 1`h1`: the linkable asset.+If a report template applies (see `seo-report`), its sections and tone replace this list.+Sections in this order:1. **The angle** — one or two opening sentences naming the best outreach angle and the prospect type to work first.diff --git a/.agents/skills/local-seo/SKILL.md b/.agents/skills/local-seo/SKILL.mdindex 88e5f37d..59dd9c36 100644--- a/.agents/skills/local-seo/SKILL.md+++ b/.agents/skills/local-seo/SKILL.md@@ -64,6 +64,8 @@ Always build the profile snapshot table for the whole chain — one `search_loca`h1`: the business name.+If a report template applies (see `seo-report`), its sections and tone replace this list.+Sections in this order:1. **Snapshot** — one or two opening sentences, then a table of category, rating, review count, and claimed status. One row per location for a chain.diff --git a/.agents/skills/seo-audit/SKILL.md b/.agents/skills/seo-audit/SKILL.mdindex 553d6ade..275e6217 100644--- a/.agents/skills/seo-audit/SKILL.md+++ b/.agents/skills/seo-audit/SKILL.md@@ -60,6 +60,8 @@ Keep total spend modest: one audit, one backlinks overview, at most one domain o`h1`: the domain. Then one or two opening sentences: the overall state and the one thing.+If a report template applies (see `seo-report`), its sections and tone replace this list.+Sections in this order:1. **Verdict** — three to five bullets, one line each: the state of the site, the numbers that matter (pages crawled and indexable, search terms and estimated visits, linking sites), and the biggest gap. No prose.diff --git a/.agents/skills/seo-report/SKILL.md b/.agents/skills/seo-report/SKILL.mdindex 698a9fc1..969af63f 100644--- a/.agents/skills/seo-report/SKILL.md+++ b/.agents/skills/seo-report/SKILL.md@@ -1,6 +1,6 @@---name: seo-report-description: "Write an OpenSEO report as one self-contained HTML page and save it to the project with save_report. Use whenever a skill has finished its research and owes the user a deliverable."+description: "Write and save an OpenSEO report as one self-contained HTML page. Use when a skill has finished its research, and whenever the user asks for a report, check-in, or summary, or names a report template."---# OpenSEO Report@@ -17,6 +17,12 @@ Every OpenSEO skill that produces a recommendation delivers through this skill.2. Titles are unique within a project. Saving a second report under an existing title with no `reportId` is rejected, so either pass the `reportId` of the report you are replacing or change the title to name the new subject or period.3. To revise an existing report, work from its summary. `get_report` returns the HTML only with `includeHtml: true`, and an 80 KB report is roughly 20,000 tokens, which most clients truncate. Fetch the HTML only when you need to edit a specific passage, and if what comes back looks cut off, send the user to the app instead of saving over it.+## Following a template++A project can carry report templates: named, reusable briefs saying who a report is for, which sections it has in what order, how it should sound, and how to sign off. They are listed in project context, and `list_report_templates` returns the full instructions for each one. Templates belong to a project. To reuse one in another project, list it there and save a copy here.++Use a template only when the user names it, or asks for the kind of report a template's name or description names. A plain skill run ("audit this site") uses the skill's default format. If two match, ask in one line. A template's sections, audience and tone replace the skill's Output format list; the HTML constraints and writing rules never change. Project writing_preferences always apply; a template's tone wins only where they conflict. Pass its `templateId` to `save_report`.+## Writing rules- **Write notes, not essays.** The reader scans. A finding is a heading and two or three short bullets: Status (what is true, with the number), Fix (the step), and Why only when it is not obvious. No paragraph runs past two sentences. A section opens with one sentence or none. A summary section (a verdict, a snapshot, a market read) is a bullet list, one fact per line, never prose. How the data was gathered goes in the footer, not in the section.@@ -64,7 +70,10 @@ Copy this, keep the CSS as it is, and replace the ALL-CAPS placeholders. Each prwhich has its own theme toggle, and a saved document has no way to hear aboutit: a report that follows the OS scheme alone shows a black panel inside alight app for anyone whose two settings disagree. */-:root{--bg:#fff;--fg:#0a0a0a;--fg-2:#454545;--fg-3:#8f8f8f;--rule:#ebebeb;--rule-2:#dcdcdc;--sunk:#fafafa}+:root{--bg:#fff;--fg:#0a0a0a;--fg-2:#454545;--fg-3:#8f8f8f;--rule:#ebebeb;--rule-2:#dcdcdc;--sunk:#fafafa;+ /* The one token a report template may change. Left as the text color, so a+ report with no template looks exactly as it did before. */+ --accent:var(--fg)}*{box-sizing:border-box}html{-webkit-text-size-adjust:100%}body{background:var(--bg);color:var(--fg);margin:0;padding:0 24px 120px;font-size:18px;line-height:1.65;letter-spacing:-.003em;@@ -92,7 +101,7 @@ h2{font-size:30px;font-weight:600;letter-spacing:-.025em;line-height:1.2;margin:h3{font-size:20px;font-weight:600;letter-spacing:-.015em;margin:38px 0 14px}.finding{list-style:none;padding:0;margin:0 0 26px}.finding li{margin:0 0 8px;color:var(--fg-2)}-.finding b{color:var(--fg);font-weight:600}+.finding b{color:var(--accent);font-weight:600}a{color:var(--fg);text-decoration:underline;text-underline-offset:3px;text-decoration-color:var(--rule-2)}strong{font-weight:600}code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.86em;background:var(--sunk);border:1px solid var(--rule);padding:1px 5px;border-radius:4px}@@ -113,7 +122,7 @@ figcaption{font-size:14px;color:var(--fg-3);margin-top:8px}.bars{display:grid;grid-template-columns:minmax(90px,170px) 1fr auto;gap:10px 12px;align-items:center;font-size:14px}.bars .label{color:var(--fg-2);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.bars .track{display:block;height:20px;background:var(--sunk)}-.bars .bar{display:block;height:100%;background:var(--fg);opacity:.16}+.bars .bar{display:block;height:100%;background:var(--accent);opacity:.16}.bars .value{font-variant-numeric:tabular-nums;min-width:3ch;text-align:right}svg{display:block;max-width:100%;height:auto}hr{border:none;border-top:1px solid var(--rule);margin:60px 0}@@ -215,7 +224,7 @@ footer{max-width:660px;margin:64px 0 0;padding:26px 0 0;border-top:1px solid var## Guardrails- Do not narrate the run in chat. Three bullets and the link is the ceiling, not the floor.-- Do not restyle the template per report. One look, kept good, is the point.+- Do not restyle the template per report. One look, kept good, is the point. A report template may set `--accent`, the byline (for example `Prepared for NAME` or a `Prepared by` sign-off), and the footer; nothing else in the CSS changes.- Do not paste the report body into chat, and do not offer to write it to a local file instead. The report lives in the project.- Do not save a report into a project you were not asked about. `save_report` takes the `projectId` the skill is already working in.- Do not invent a number to fill a table cell. Write `unknown` and say why in a `.note`.diff --git a/plugins/openseo/skills/competitive-landscape/SKILL.md b/plugins/openseo/skills/competitive-landscape/SKILL.mdindex 22f9a707..5714761c 100644--- a/plugins/openseo/skills/competitive-landscape/SKILL.md+++ b/plugins/openseo/skills/competitive-landscape/SKILL.md@@ -67,6 +67,8 @@ Deliver through the `seo-report` skill, saving with `skill: "competitive-landsca`h1`: the market or category.+If a report template applies (see `seo-report`), its sections and tone replace this list.+Sections in this order:1. **The market read** — one or two opening sentences naming the leaders, the most winnable area, and the biggest barrier.diff --git a/plugins/openseo/skills/competitor-analysis/SKILL.md b/plugins/openseo/skills/competitor-analysis/SKILL.mdindex e77bf8bc..a6d00ef9 100644--- a/plugins/openseo/skills/competitor-analysis/SKILL.md+++ b/plugins/openseo/skills/competitor-analysis/SKILL.md@@ -69,6 +69,8 @@ Deliver through the `seo-report` skill, saving with `skill: "competitor-analysis`h1`: the competitor domain.+If a report template applies (see `seo-report`), its sections and tone replace this list.+Sections in this order:1. **Snapshot** — one or two opening sentences, then a table of the competitor's organic footprint (traffic estimate, keyword count, referring domains). Add the user's domain as a second row when comparing.diff --git a/plugins/openseo/skills/keyword-clustering/SKILL.md b/plugins/openseo/skills/keyword-clustering/SKILL.mdindex 199d51d1..9ed4e4d5 100644--- a/plugins/openseo/skills/keyword-clustering/SKILL.md+++ b/plugins/openseo/skills/keyword-clustering/SKILL.md@@ -63,6 +63,8 @@ Deliver through the `seo-report` skill, saving with `skill: "keyword-clustering"`h1`: the site or keyword set.+If a report template applies (see `seo-report`), its sections and tone replace this list.+Sections in this order:1. **The map** — one or two opening sentences: how many clusters, how many pages to create, how many to update, and any cannibalization found.diff --git a/plugins/openseo/skills/keyword-research/SKILL.md b/plugins/openseo/skills/keyword-research/SKILL.mdindex f65b5d48..b1d99b65 100644--- a/plugins/openseo/skills/keyword-research/SKILL.md+++ b/plugins/openseo/skills/keyword-research/SKILL.md@@ -64,6 +64,8 @@ Deliver through the `seo-report` skill, saving with `skill: "keyword-research"`.`h1`: the site or topic.+If a report template applies (see `seo-report`), its sections and tone replace this list.+Sections in this order:1. **The opportunity** — one or two opening sentences naming the best theme and why the site can win it now.diff --git a/plugins/openseo/skills/link-prospecting/SKILL.md b/plugins/openseo/skills/link-prospecting/SKILL.mdindex 463606e2..ec1248e3 100644--- a/plugins/openseo/skills/link-prospecting/SKILL.md+++ b/plugins/openseo/skills/link-prospecting/SKILL.md@@ -96,6 +96,8 @@ Use `get_serp_results` in batches for the most relevant patterns. Send at most 1`h1`: the linkable asset.+If a report template applies (see `seo-report`), its sections and tone replace this list.+Sections in this order:1. **The angle** — one or two opening sentences naming the best outreach angle and the prospect type to work first.diff --git a/plugins/openseo/skills/local-seo/SKILL.md b/plugins/openseo/skills/local-seo/SKILL.mdindex 88e5f37d..59dd9c36 100644--- a/plugins/openseo/skills/local-seo/SKILL.md+++ b/plugins/openseo/skills/local-seo/SKILL.md@@ -64,6 +64,8 @@ Always build the profile snapshot table for the whole chain — one `search_loca`h1`: the business name.+If a report template applies (see `seo-report`), its sections and tone replace this list.+Sections in this order:1. **Snapshot** — one or two opening sentences, then a table of category, rating, review count, and claimed status. One row per location for a chain.diff --git a/plugins/openseo/skills/seo-audit/SKILL.md b/plugins/openseo/skills/seo-audit/SKILL.mdindex 553d6ade..275e6217 100644--- a/plugins/openseo/skills/seo-audit/SKILL.md+++ b/plugins/openseo/skills/seo-audit/SKILL.md@@ -60,6 +60,8 @@ Keep total spend modest: one audit, one backlinks overview, at most one domain o`h1`: the domain. Then one or two opening sentences: the overall state and the one thing.+If a report template applies (see `seo-report`), its sections and tone replace this list.+Sections in this order:1. **Verdict** — three to five bullets, one line each: the state of the site, the numbers that matter (pages crawled and indexable, search terms and estimated visits, linking sites), and the biggest gap. No prose.diff --git a/plugins/openseo/skills/seo-report/SKILL.md b/plugins/openseo/skills/seo-report/SKILL.mdindex 698a9fc1..969af63f 100644--- a/plugins/openseo/skills/seo-report/SKILL.md+++ b/plugins/openseo/skills/seo-report/SKILL.md@@ -1,6 +1,6 @@---name: seo-report-description: "Write an OpenSEO report as one self-contained HTML page and save it to the project with save_report. Use whenever a skill has finished its research and owes the user a deliverable."+description: "Write and save an OpenSEO report as one self-contained HTML page. Use when a skill has finished its research, and whenever the user asks for a report, check-in, or summary, or names a report template."---# OpenSEO Report@@ -17,6 +17,12 @@ Every OpenSEO skill that produces a recommendation delivers through this skill.2. Titles are unique within a project. Saving a second report under an existing title with no `reportId` is rejected, so either pass the `reportId` of the report you are replacing or change the title to name the new subject or period.3. To revise an existing report, work from its summary. `get_report` returns the HTML only with `includeHtml: true`, and an 80 KB report is roughly 20,000 tokens, which most clients truncate. Fetch the HTML only when you need to edit a specific passage, and if what comes back looks cut off, send the user to the app instead of saving over it.+## Following a template++A project can carry report templates: named, reusable briefs saying who a report is for, which sections it has in what order, how it should sound, and how to sign off. They are listed in project context, and `list_report_templates` returns the full instructions for each one. Templates belong to a project. To reuse one in another project, list it there and save a copy here.++Use a template only when the user names it, or asks for the kind of report a template's name or description names. A plain skill run ("audit this site") uses the skill's default format. If two match, ask in one line. A template's sections, audience and tone replace the skill's Output format list; the HTML constraints and writing rules never change. Project writing_preferences always apply; a template's tone wins only where they conflict. Pass its `templateId` to `save_report`.+## Writing rules- **Write notes, not essays.** The reader scans. A finding is a heading and two or three short bullets: Status (what is true, with the number), Fix (the step), and Why only when it is not obvious. No paragraph runs past two sentences. A section opens with one sentence or none. A summary section (a verdict, a snapshot, a market read) is a bullet list, one fact per line, never prose. How the data was gathered goes in the footer, not in the section.@@ -64,7 +70,10 @@ Copy this, keep the CSS as it is, and replace the ALL-CAPS placeholders. Each prwhich has its own theme toggle, and a saved document has no way to hear aboutit: a report that follows the OS scheme alone shows a black panel inside alight app for anyone whose two settings disagree. */-:root{--bg:#fff;--fg:#0a0a0a;--fg-2:#454545;--fg-3:#8f8f8f;--rule:#ebebeb;--rule-2:#dcdcdc;--sunk:#fafafa}+:root{--bg:#fff;--fg:#0a0a0a;--fg-2:#454545;--fg-3:#8f8f8f;--rule:#ebebeb;--rule-2:#dcdcdc;--sunk:#fafafa;+ /* The one token a report template may change. Left as the text color, so a+ report with no template looks exactly as it did before. */+ --accent:var(--fg)}*{box-sizing:border-box}html{-webkit-text-size-adjust:100%}body{background:var(--bg);color:var(--fg);margin:0;padding:0 24px 120px;font-size:18px;line-height:1.65;letter-spacing:-.003em;@@ -92,7 +101,7 @@ h2{font-size:30px;font-weight:600;letter-spacing:-.025em;line-height:1.2;margin:h3{font-size:20px;font-weight:600;letter-spacing:-.015em;margin:38px 0 14px}.finding{list-style:none;padding:0;margin:0 0 26px}.finding li{margin:0 0 8px;color:var(--fg-2)}-.finding b{color:var(--fg);font-weight:600}+.finding b{color:var(--accent);font-weight:600}a{color:var(--fg);text-decoration:underline;text-underline-offset:3px;text-decoration-color:var(--rule-2)}strong{font-weight:600}code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.86em;background:var(--sunk);border:1px solid var(--rule);padding:1px 5px;border-radius:4px}@@ -113,7 +122,7 @@ figcaption{font-size:14px;color:var(--fg-3);margin-top:8px}.bars{display:grid;grid-template-columns:minmax(90px,170px) 1fr auto;gap:10px 12px;align-items:center;font-size:14px}.bars .label{color:var(--fg-2);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.bars .track{display:block;height:20px;background:var(--sunk)}-.bars .bar{display:block;height:100%;background:var(--fg);opacity:.16}+.bars .bar{display:block;height:100%;background:var(--accent);opacity:.16}.bars .value{font-variant-numeric:tabular-nums;min-width:3ch;text-align:right}svg{display:block;max-width:100%;height:auto}hr{border:none;border-top:1px solid var(--rule);margin:60px 0}@@ -215,7 +224,7 @@ footer{max-width:660px;margin:64px 0 0;padding:26px 0 0;border-top:1px solid var## Guardrails- Do not narrate the run in chat. Three bullets and the link is the ceiling, not the floor.-- Do not restyle the template per report. One look, kept good, is the point.+- Do not restyle the template per report. One look, kept good, is the point. A report template may set `--accent`, the byline (for example `Prepared for NAME` or a `Prepared by` sign-off), and the footer; nothing else in the CSS changes.- Do not paste the report body into chat, and do not offer to write it to a local file instead. The report lives in the project.- Do not save a report into a project you were not asked about. `save_report` takes the `projectId` the skill is already working in.- Do not invent a number to fill a table cell. Write `unknown` and say why in a `.note`.diff --git a/runbooks/gdpr-erasure.md b/runbooks/gdpr-erasure.mdindex d55c2383..c043fecb 100644--- a/runbooks/gdpr-erasure.md+++ b/runbooks/gdpr-erasure.md@@ -78,6 +78,13 @@ The execution order is designed for safe retries:3. Delete the organizations and user in one Postgres transaction, relying onforeign-key cascades for project data, then verify the root rows are gone.+Two classes are re-attributed rather than deleted, because they have no user+foreign key and a surviving multi-member organization keeps them: `reports` and+`report_templates` (both `created_by_user_id` becomes `gdpr-deleted-user`). The+dry run counts them as `attributed_reports` and `attributed_report_templates`,+alongside the `reports` and `report_templates` in the target's projects — those+cascade away with the project when its organization is deleted.+If a step fails, fix the reported credential or service error and run the samecommand again. Vendor absence and already-finished Workflows are treated assuccessful no-ops.diff --git a/scripts/erase-user-data.ts b/scripts/erase-user-data.tsindex ecf4e075..343acbe3 100644--- a/scripts/erase-user-data.ts+++ b/scripts/erase-user-data.ts@@ -297,6 +297,11 @@ async function buildInventory(db: Db, user: UserRow) {schema.reports,eq(schema.reports.createdByUserId, user.id),),+ report_templates: await projectCount(schema.reportTemplates),+ attributed_report_templates: await db.$count(+ schema.reportTemplates,+ eq(schema.reportTemplates.createdByUserId, user.id),+ ),gsc_connections: await db.$count(schema.gscConnections,eq(schema.gscConnections.connectedByUserId, user.id),@@ -504,6 +509,10 @@ async function erasePostgres(db: Db, user: UserRow, organizationIds: string[]) {.update(schema.reports).set({ createdByUserId: "gdpr-deleted-user" }).where(eq(schema.reports.createdByUserId, user.id));+ await tx+ .update(schema.reportTemplates)+ .set({ createdByUserId: "gdpr-deleted-user" })+ .where(eq(schema.reportTemplates.createdByUserId, user.id));if (organizationIds.length > 0) {// Re-assert the solo-membership guard at delete time: anyone who// accepted an invite after the inventory was taken must abort thediff --git a/specs/0013-report-templates.md b/specs/0013-report-templates.mdnew file mode 100644index 00000000..cd7e8823--- /dev/null+++ b/specs/0013-report-templates.md@@ -0,0 +1,45 @@+# Report templates (reusable report briefs per project)++## Status++Accepted. Shipped in PR #615, on top of reports (`specs/0012-dynamic-reports.md`).++## What it does++- A template is a reusable brief for a kind of report: who it is for, which sections it has and in what order, how it sounds, how it signs off, and an accent color. It is instructions, not a document; the agent still writes the HTML from the `seo-report` starter.+- Templates belong to a project, up to 10 each. The Templates page, reached from Reports, holds the table, the form and delete.+- Agents see a project's templates in project context and follow one when the user names it or asks for the kind of report it describes. A plain skill run keeps the skill's own format.+- Two free MCP tools, `list_report_templates` and `save_report_template` (create or update); SAM, the in-app agent, does not get them. `save_report` accepts an optional template id, and the reports list shows the template name as the report's type.++## How it works++**Data.** One `report_templates` table: `id`, `project_id` (cascades from the project), `name` (up to 80 characters, unique per project), `description` (one line, up to 200 characters), `instructions` (markdown, up to 3,000 characters), `created_by`, `created_by_user_id`, timestamps. The uniqueness check is case-insensitive in the service, with the unique index as the backstop, because "use the monthly check-in template" must never be ambiguous.++`reports.template_id` is nullable with no foreign key: deleting a template neither deletes nor blocks the reports written from it, and the name is resolved by a project-scoped read that shows nothing for a dangling id.++**Invariants.**++- Every template query is scoped by project id, including updates, deletes, the template check on `save_report` and the name resolution on the reports list. A template id from another project reads exactly like a deleted one.+- Reuse across projects is a copy, not a shared row: list the template in one project, save it in the other.+- A template replaces the section list, audience and tone. It never changes the HTML constraints, so the report still prints and still opens on a phone.++**Discovery.** The project-context digest that every skill reads first, and that SAM sees every turn, gains a "Report templates" section listing name and description, omitted when there are none. The `seo-report` skill carries the opt-in rule. The starter CSS gains an accent variable used by bar fills and finding labels; a template may set that, the byline and the footer, and nothing else in the CSS.++Template saves are counted in telemetry. Erasing a user re-attributes the templates they created.++## Alternatives considered++- A prose list of templates in project context instead of a table: custom sections are free text, so renames and caps would be policed by hand, and a caller could not address a template by id. What that option got right, discovery in the context agents already read, is kept.+- Organization-wide templates as a scope on the row: built, then removed. It needed a cross-scope name rule, an immutable scope, a who-can-edit rule and two caps, for a reuse case that copying already covers.+- Stored starter HTML per template instead of instructions only: a second thing to keep in sync with the skill's starter, for a benefit the accent, byline and footer hooks already deliver.+- A foreign key on `reports.template_id`: it would delete or block reports when their template goes.+- A delete tool: the app page owns deletion, and an agent has no reason to remove a brief the user wrote.+- A default template applied without asking: it would silently change every report a skill produces.++## Not in scope++Organization-wide templates, a template picker in the app, a default template, stored starter HTML, deleting templates from an agent.++## Later++Seeing every template across the organization and cloning one into a project. Stored starter HTML would arrive as an additive column.diff --git a/src/client/features/ai-mcp/AvailableTools.tsx b/src/client/features/ai-mcp/AvailableTools.tsxindex 752e8c7b..108aaeea 100644--- a/src/client/features/ai-mcp/AvailableTools.tsx+++ b/src/client/features/ai-mcp/AvailableTools.tsx@@ -46,6 +46,17 @@ const toolCategories: ToolCategory[] = [title: "Get a report",description: "Read one report's summary, and its HTML when needed.",},+ {+ name: "list_report_templates",+ title: "List report templates",+ description:+ "See this project's report templates, and the brief each one carries.",+ },+ {+ name: "save_report_template",+ title: "Save a report template",+ description: "Save a reusable report brief to this project.",+ },],},{diff --git a/src/client/features/reports/ReportTemplateForm.tsx b/src/client/features/reports/ReportTemplateForm.tsxnew file mode 100644index 00000000..95ef412e--- /dev/null+++ b/src/client/features/reports/ReportTemplateForm.tsx@@ -0,0 +1,194 @@+import { useForm } from "@tanstack/react-form";+import { useMutation } from "@tanstack/react-query";+import { Loader2 } from "lucide-react";+import { z } from "zod";+import { Modal } from "@/client/components/Modal";+import { getStandardErrorMessage } from "@/client/lib/error-messages";+import { getFieldError } from "@/client/lib/forms";+import { captureClientEvent } from "@/client/lib/posthog";+import { saveReportTemplate } from "@/serverFunctions/reportTemplates";+import type { ReportTemplate } from "@/types/schemas/report-templates";++// One form for create and edit. Shape only, as at every other boundary: the+// caps come back from the service with their copy and show in the alert.+const formSchema = z.object({+ name: z.string().trim().min(1, "Give the template a name."),+ description: z+ .string()+ .trim()+ .min(1, "Say in one line when to use this template."),+ instructions: z+ .string()+ .trim()+ .min(1, "Say who the report is for and which sections it has."),+});++const INSTRUCTIONS_PLACEHOLDER = `Audience: the client's marketing lead, not technical.+Sections, in order: Where we are / What we did this month / What moved / What to expect next.+Tone: plain and confident. Gloss every SEO term. No exclamation points.+Sign off as: Acme SEO+Accent: #1C4ED8`;++export function ReportTemplateForm({+ projectId,+ template,+ onClose,+ onSaved,+}: {+ projectId: string;+ /** The template being edited, or undefined when creating one. */+ template?: ReportTemplate;+ onClose: () => void;+ onSaved: () => void;+}) {+ const saveMutation = useMutation({+ // A refusal (duplicate name, the cap) comes back as `{ ok: false }` rather+ // than an error, because thrown errors reach the client stripped to their+ // code. Rethrowing it here gives the form one error branch.+ mutationFn: async (values: z.infer<typeof formSchema>) => {+ const result = await saveReportTemplate({+ data: { projectId, templateId: template?.id, ...values },+ });+ if (!result.ok) throw new Error(result.message);+ return result;+ },+ onSuccess: (result) => {+ captureClientEvent("report_template:saved", {+ project_id: projectId,+ is_update: !result.created,+ source: "app",+ });+ onSaved();+ },+ });++ const error = saveMutation.error+ ? getStandardErrorMessage(saveMutation.error, "Failed to save the template")+ : null;++ const form = useForm({+ defaultValues: {+ name: template?.name ?? "",+ description: template?.description ?? "",+ instructions: template?.instructions ?? "",+ },+ validators: { onSubmit: formSchema },+ onSubmit: ({ value }) => saveMutation.mutate(value),+ });++ return (+ <Modal maxWidth="max-w-2xl" onClose={onClose} labelledBy="template-title">+ <h3 id="template-title" className="text-lg font-semibold">+ {template ? "Edit template" : "New template"}+ </h3>++ <form+ className="space-y-4"+ onSubmit={(event) => {+ event.preventDefault();+ void form.handleSubmit();+ }}+ >+ <form.Field name="name">+ {(field) => (+ <Labelled+ label="Name"+ error={getFieldError(field.state.meta.errors)}+ >+ <input+ type="text"+ className="input input-bordered w-full"+ placeholder="Monthly client check-in"+ value={field.state.value}+ onChange={(event) => field.handleChange(event.target.value)}+ />+ </Labelled>+ )}+ </form.Field>++ <form.Field name="description">+ {(field) => (+ <Labelled+ label="Description"+ hint="One line saying when to use it. This is what an agent reads to decide."+ error={getFieldError(field.state.meta.errors)}+ >+ <input+ type="text"+ className="input input-bordered w-full"+ placeholder="The monthly update we send retainer clients."+ value={field.state.value}+ onChange={(event) => field.handleChange(event.target.value)}+ />+ </Labelled>+ )}+ </form.Field>++ <form.Field name="instructions">+ {(field) => (+ <Labelled+ label="Instructions"+ hint="Brand voice for the whole project lives in Context › Writing preferences."+ error={getFieldError(field.state.meta.errors)}+ >+ <textarea+ className="textarea textarea-bordered h-56 w-full font-mono text-xs leading-relaxed"+ placeholder={INSTRUCTIONS_PLACEHOLDER}+ value={field.state.value}+ onChange={(event) => field.handleChange(event.target.value)}+ />+ </Labelled>+ )}+ </form.Field>++ {error ? (+ <div className="alert alert-error">+ <span className="text-sm">{error}</span>+ </div>+ ) : null}++ <div className="flex justify-end gap-2">+ <button+ type="button"+ className="btn btn-ghost btn-sm"+ onClick={onClose}+ >+ Cancel+ </button>+ <button+ type="submit"+ className="btn btn-primary btn-sm gap-1"+ disabled={saveMutation.isPending}+ >+ {saveMutation.isPending ? (+ <Loader2 className="size-3 animate-spin" />+ ) : null}+ {template ? "Save changes" : "Create template"}+ </button>+ </div>+ </form>+ </Modal>+ );+}++function Labelled({+ label,+ hint,+ error,+ children,+}: {+ label: string;+ hint?: string;+ error: string | null;+ children: React.ReactNode;+}) {+ return (+ // The wrapping label associates the text with the control, so no id plumbing.+ <label className="block space-y-1.5">+ <span className="block text-sm font-medium">{label}</span>+ {children}+ {hint ? <p className="text-xs text-base-content/60">{hint}</p> : null}+ {error ? <p className="text-sm text-error">{error}</p> : null}+ </label>+ );+}diff --git a/src/client/features/reports/ReportTemplatesList.tsx b/src/client/features/reports/ReportTemplatesList.tsxnew file mode 100644index 00000000..dfc28355--- /dev/null+++ b/src/client/features/reports/ReportTemplatesList.tsx@@ -0,0 +1,82 @@+import { Pencil, Trash2 } from "lucide-react";+import { PortalMenu } from "@/client/components/PortalMenu";+import { formatRelativeTime } from "@/client/features/reports/shared";+import type { ReportTemplate } from "@/types/schemas/report-templates";++export function ReportTemplatesList({+ templates,+ onEdit,+ onDelete,+}: {+ templates: ReportTemplate[];+ onEdit: (template: ReportTemplate) => void;+ onDelete: (template: ReportTemplate) => void;+}) {+ if (templates.length === 0) {+ return (+ <p className="rounded-lg border border-dashed border-base-300 px-4 py-6 text-sm text-base-content/60">+ No templates yet. A template is a reusable brief for a kind of report:+ who it is for, which sections it has, how it sounds.+ </p>+ );+ }++ return (+ <div className="overflow-x-auto rounded-lg border border-base-300">+ <table className="table table-sm">+ <thead>+ <tr>+ <th>Name</th>+ <th>Description</th>+ <th>Updated</th>+ <th></th>+ </tr>+ </thead>+ <tbody>+ {templates.map((template) => (+ <tr key={template.id}>+ <td className="font-medium">{template.name}</td>+ <td className="max-w-[420px] text-base-content/70">+ {template.description}+ </td>+ <td className="whitespace-nowrap text-base-content/70">+ {formatRelativeTime(template.updatedAt)}+ </td>+ <td className="w-10 text-right">+ <PortalMenu ariaLabel={`Actions for ${template.name}`}>+ {(close) => (+ <>+ <li>+ <button+ onClick={() => {+ close();+ onEdit(template);+ }}+ >+ <Pencil className="size-3.5" />+ Edit+ </button>+ </li>+ <li>+ <button+ className="text-error"+ onClick={() => {+ close();+ onDelete(template);+ }}+ >+ <Trash2 className="size-3.5" />+ Delete+ </button>+ </li>+ </>+ )}+ </PortalMenu>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+}diff --git a/src/client/features/reports/ReportsList.tsx b/src/client/features/reports/ReportsList.tsxindex aac59fcf..9b0b0ee3 100644--- a/src/client/features/reports/ReportsList.tsx+++ b/src/client/features/reports/ReportsList.tsx@@ -34,7 +34,7 @@ export function ReportsList({<tr><th>Title</th><th>Created by</th>- <th>Skill</th>+ <th>Type</th><th>Updated</th><th></th></tr>@@ -54,7 +54,12 @@ export function ReportsList({<td className="text-base-content/70">{formatCreatedBy(report)}</td>- <td className="text-base-content/70">{report.skill ?? "—"}</td>+ {/* The template the report was written from, else the skill+ that produced it: what a reader needs to tell two reports+ on the same site apart. */}+ <td className="text-base-content/70">+ {report.templateName ?? report.skill ?? "—"}+ </td><td className="whitespace-nowrap text-base-content/70">{formatRelativeTime(report.updatedAt)}</td>diff --git a/src/routeTree.gen.ts b/src/routeTree.gen.tsindex 5dc10969..0e6f565a 100644--- a/src/routeTree.gen.ts+++ b/src/routeTree.gen.ts@@ -62,6 +62,7 @@ import { Route as ProjectPProjectIdRankTrackingIndexRouteImport } from './routesimport { Route as ProjectPProjectIdAuditIndexRouteImport } from './routes/_project/p/$projectId/audit/index'import { Route as ProjectPProjectIdSettingsIntegrationsRouteImport } from './routes/_project/p/$projectId/settings/integrations'import { Route as ProjectPProjectIdSettingsContextRouteImport } from './routes/_project/p/$projectId/settings/context'+import { Route as ProjectPProjectIdReportsTemplatesRouteImport } from './routes/_project/p/$projectId/reports/templates'import { Route as ProjectPProjectIdReportsReportIdRouteImport } from './routes/_project/p/$projectId/reports/$reportId'import { Route as ProjectPProjectIdRankTrackingConfigIdRouteImport } from './routes/_project/p/$projectId/rank-tracking/$configId'import { Route as ProjectPProjectIdAuditIssuesResultIdRouteImport } from './routes/_project/p/$projectId/audit/issues/$resultId'@@ -344,6 +345,12 @@ const ProjectPProjectIdSettingsContextRoute =path: '/context',getParentRoute: () => ProjectPProjectIdSettingsRoute,} as any)+const ProjectPProjectIdReportsTemplatesRoute =+ ProjectPProjectIdReportsTemplatesRouteImport.update({+ id: '/reports/templates',+ path: '/reports/templates',+ getParentRoute: () => ProjectPProjectIdRouteRoute,+ } as any)const ProjectPProjectIdReportsReportIdRoute =ProjectPProjectIdReportsReportIdRouteImport.update({id: '/reports/$reportId',@@ -409,6 +416,7 @@ export interface FileRoutesByFullPath {'/p/$projectId/': typeof ProjectPProjectIdIndexRoute'/p/$projectId/rank-tracking/$configId': typeof ProjectPProjectIdRankTrackingConfigIdRoute'/p/$projectId/reports/$reportId': typeof ProjectPProjectIdReportsReportIdRoute+ '/p/$projectId/reports/templates': typeof ProjectPProjectIdReportsTemplatesRoute'/p/$projectId/settings/context': typeof ProjectPProjectIdSettingsContextRoute'/p/$projectId/settings/integrations': typeof ProjectPProjectIdSettingsIntegrationsRoute'/p/$projectId/audit/': typeof ProjectPProjectIdAuditIndexRoute@@ -458,6 +466,7 @@ export interface FileRoutesByTo {'/p/$projectId': typeof ProjectPProjectIdIndexRoute'/p/$projectId/rank-tracking/$configId': typeof ProjectPProjectIdRankTrackingConfigIdRoute'/p/$projectId/reports/$reportId': typeof ProjectPProjectIdReportsReportIdRoute+ '/p/$projectId/reports/templates': typeof ProjectPProjectIdReportsTemplatesRoute'/p/$projectId/settings/context': typeof ProjectPProjectIdSettingsContextRoute'/p/$projectId/settings/integrations': typeof ProjectPProjectIdSettingsIntegrationsRoute'/p/$projectId/audit': typeof ProjectPProjectIdAuditIndexRoute@@ -517,6 +526,7 @@ export interface FileRoutesById {'/_project/p/$projectId/': typeof ProjectPProjectIdIndexRoute'/_project/p/$projectId/rank-tracking/$configId': typeof ProjectPProjectIdRankTrackingConfigIdRoute'/_project/p/$projectId/reports/$reportId': typeof ProjectPProjectIdReportsReportIdRoute+ '/_project/p/$projectId/reports/templates': typeof ProjectPProjectIdReportsTemplatesRoute'/_project/p/$projectId/settings/context': typeof ProjectPProjectIdSettingsContextRoute'/_project/p/$projectId/settings/integrations': typeof ProjectPProjectIdSettingsIntegrationsRoute'/_project/p/$projectId/audit/': typeof ProjectPProjectIdAuditIndexRoute@@ -573,6 +583,7 @@ export interface FileRouteTypes {| '/p/$projectId/'| '/p/$projectId/rank-tracking/$configId'| '/p/$projectId/reports/$reportId'+ | '/p/$projectId/reports/templates'| '/p/$projectId/settings/context'| '/p/$projectId/settings/integrations'| '/p/$projectId/audit/'@@ -622,6 +633,7 @@ export interface FileRouteTypes {| '/p/$projectId'| '/p/$projectId/rank-tracking/$configId'| '/p/$projectId/reports/$reportId'+ | '/p/$projectId/reports/templates'| '/p/$projectId/settings/context'| '/p/$projectId/settings/integrations'| '/p/$projectId/audit'@@ -680,6 +692,7 @@ export interface FileRouteTypes {| '/_project/p/$projectId/'| '/_project/p/$projectId/rank-tracking/$configId'| '/_project/p/$projectId/reports/$reportId'+ | '/_project/p/$projectId/reports/templates'| '/_project/p/$projectId/settings/context'| '/_project/p/$projectId/settings/integrations'| '/_project/p/$projectId/audit/'@@ -1082,6 +1095,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof ProjectPProjectIdSettingsContextRouteImportparentRoute: typeof ProjectPProjectIdSettingsRoute}+ '/_project/p/$projectId/reports/templates': {+ id: '/_project/p/$projectId/reports/templates'+ path: '/reports/templates'+ fullPath: '/p/$projectId/reports/templates'+ preLoaderRoute: typeof ProjectPProjectIdReportsTemplatesRouteImport+ parentRoute: typeof ProjectPProjectIdRouteRoute+ }'/_project/p/$projectId/reports/$reportId': {id: '/_project/p/$projectId/reports/$reportId'path: '/reports/$reportId'@@ -1218,6 +1238,7 @@ interface ProjectPProjectIdRouteRouteChildren {ProjectPProjectIdSettingsRoute: typeof ProjectPProjectIdSettingsRouteWithChildrenProjectPProjectIdIndexRoute: typeof ProjectPProjectIdIndexRouteProjectPProjectIdReportsReportIdRoute: typeof ProjectPProjectIdReportsReportIdRoute+ ProjectPProjectIdReportsTemplatesRoute: typeof ProjectPProjectIdReportsTemplatesRouteProjectPProjectIdReportsIndexRoute: typeof ProjectPProjectIdReportsIndexRoute}@@ -1240,6 +1261,8 @@ const ProjectPProjectIdRouteRouteChildren: ProjectPProjectIdRouteRouteChildren =ProjectPProjectIdIndexRoute: ProjectPProjectIdIndexRoute,ProjectPProjectIdReportsReportIdRoute:ProjectPProjectIdReportsReportIdRoute,+ ProjectPProjectIdReportsTemplatesRoute:+ ProjectPProjectIdReportsTemplatesRoute,ProjectPProjectIdReportsIndexRoute: ProjectPProjectIdReportsIndexRoute,}diff --git a/src/routes/_project/p/$projectId/reports/$reportId.tsx b/src/routes/_project/p/$projectId/reports/$reportId.tsxindex 39b85afb..0203a030 100644--- a/src/routes/_project/p/$projectId/reports/$reportId.tsx+++ b/src/routes/_project/p/$projectId/reports/$reportId.tsx@@ -122,7 +122,7 @@ function ReportDetailPage() {<div className="mx-auto max-w-3xl space-y-4"><div className="alert alert-error"><span className="text-sm">- {/* A deleted report and another organization's report are the+ {/* A deleted report and another project's report are thesame answer on purpose, so ids cannot be probed. */}{getErrorCode(reportQuery.error) === "NOT_FOUND"? "This report does not exist or you do not have access to it."@@ -190,9 +190,10 @@ function ReportDetailPage() {<dd>{formatCreatedBy(report)}</dd></div><div className="flex items-baseline gap-1.5">- <dt className="text-base-content/50">Skill</dt>- {/* An em dash, as in the list column: the label explains it. */}- <dd>{report.skill ?? "—"}</dd>+ <dt className="text-base-content/50">Type</dt>+ {/* As in the list's Type column: the template name when the+ report followed one, else the skill, else an em dash. */}+ <dd>{report.templateName ?? report.skill ?? "—"}</dd></div><div className="flex items-baseline gap-1.5"><dt className="text-base-content/50">Updated</dt>diff --git a/src/routes/_project/p/$projectId/reports/index.tsx b/src/routes/_project/p/$projectId/reports/index.tsxindex 58e38599..269bbc0a 100644--- a/src/routes/_project/p/$projectId/reports/index.tsx+++ b/src/routes/_project/p/$projectId/reports/index.tsx@@ -1,4 +1,4 @@-import { createFileRoute } from "@tanstack/react-router";+import { createFileRoute, Link } from "@tanstack/react-router";import { useQuery } from "@tanstack/react-query";import { useState } from "react";import { ReportsList } from "@/client/features/reports/ReportsList";@@ -37,11 +37,20 @@ function ReportsPage() {return (<div className="overflow-auto px-4 py-4 pb-24 md:px-6 md:py-6 md:pb-8"><div className="mx-auto max-w-5xl space-y-4">- <div>- <h1 className="text-2xl font-semibold">Reports</h1>- <p className="text-sm text-base-content/70">- HTML reports your agents saved to this project.- </p>+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div>+ <h1 className="text-2xl font-semibold">Reports</h1>+ <p className="text-sm text-base-content/70">+ HTML reports your agents saved to this project.+ </p>+ </div>+ <Link+ to="/p/$projectId/reports/templates"+ params={{ projectId }}+ className="btn btn-ghost btn-sm"+ >+ Templates+ </Link></div>{reportsQuery.isPending ? (diff --git a/src/routes/_project/p/$projectId/reports/templates.tsx b/src/routes/_project/p/$projectId/reports/templates.tsxnew file mode 100644index 00000000..1a9cc3ea--- /dev/null+++ b/src/routes/_project/p/$projectId/reports/templates.tsx@@ -0,0 +1,146 @@+import { createFileRoute, Link } from "@tanstack/react-router";+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { useState } from "react";+import { ChevronLeft, Plus } from "lucide-react";+import { toast } from "sonner";+import { ConfirmDeleteModal } from "@/client/components/ConfirmDeleteModal";+import { ReportTemplateForm } from "@/client/features/reports/ReportTemplateForm";+import { ReportTemplatesList } from "@/client/features/reports/ReportTemplatesList";+import { reportsQueryKey } from "@/client/features/reports/shared";+import { getStandardErrorMessage } from "@/client/lib/error-messages";+import { captureClientEvent } from "@/client/lib/posthog";+import {+ deleteReportTemplate,+ listReportTemplates,+} from "@/serverFunctions/reportTemplates";+import type { ReportTemplate } from "@/types/schemas/report-templates";++export const Route = createFileRoute(+ "/_project/p/$projectId/reports/templates",+)({+ component: ReportTemplatesPage,+});++const templatesQueryKey = (projectId: string) =>+ ["report-templates", projectId] as const;++function ReportTemplatesPage() {+ const { projectId } = Route.useParams();+ const queryClient = useQueryClient();+ // `{}` opens the form for a new template; `{ template }` opens it for an edit.+ const [form, setForm] = useState<{ template?: ReportTemplate } | null>(null);+ const [pendingDelete, setPendingDelete] = useState<ReportTemplate | null>(+ null,+ );++ const templatesQuery = useQuery({+ queryKey: templatesQueryKey(projectId),+ queryFn: () => listReportTemplates({ data: { projectId } }),+ });++ const invalidate = () => {+ void queryClient.invalidateQueries({+ queryKey: templatesQueryKey(projectId),+ });+ // The reports list renders the template name in its Type column.+ void queryClient.invalidateQueries({+ queryKey: reportsQueryKey(projectId),+ });+ };++ const deleteMutation = useMutation({+ mutationFn: (templateId: string) =>+ deleteReportTemplate({ data: { projectId, templateId } }),+ onSuccess: (_result, templateId) => {+ captureClientEvent("report_template:deleted", {+ project_id: projectId,+ template_id: templateId,+ });+ toast.success("Template deleted");+ setPendingDelete(null);+ invalidate();+ },+ onError: (error: Error) => {+ toast.error(+ getStandardErrorMessage(error, "Failed to delete the template"),+ );+ },+ });++ return (+ <div className="overflow-auto px-4 py-4 pb-24 md:px-6 md:py-6 md:pb-8">+ <div className="mx-auto max-w-5xl space-y-4">+ <Link+ to="/p/$projectId/reports"+ params={{ projectId }}+ className="inline-flex items-center gap-1 text-sm text-base-content/60 transition-colors hover:text-base-content"+ >+ <ChevronLeft className="size-4" />+ Reports+ </Link>++ <div className="flex flex-wrap items-start justify-between gap-3">+ <div>+ <h1 className="text-2xl font-semibold">Report templates</h1>+ <p className="text-sm text-base-content/70">+ Reusable briefs your agents follow when they write a report: who+ it is for, which sections it has, and how it should sound.+ </p>+ </div>+ <button+ type="button"+ className="btn btn-primary btn-sm gap-1.5"+ onClick={() => setForm({})}+ >+ <Plus className="size-4" />+ New template+ </button>+ </div>++ {templatesQuery.isPending ? (+ <div className="flex justify-center py-10">+ <span className="loading loading-spinner loading-md" />+ </div>+ ) : templatesQuery.isError ? (+ <div className="alert alert-error">+ <span className="text-sm">+ {getStandardErrorMessage(+ templatesQuery.error,+ "Failed to load templates",+ )}+ </span>+ </div>+ ) : (+ <ReportTemplatesList+ templates={templatesQuery.data.templates}+ onEdit={(template) => setForm({ template })}+ onDelete={setPendingDelete}+ />+ )}+ </div>++ {form ? (+ <ReportTemplateForm+ projectId={projectId}+ template={form.template}+ onClose={() => setForm(null)}+ onSaved={() => {+ setForm(null);+ invalidate();+ }}+ />+ ) : null}++ {pendingDelete ? (+ <ConfirmDeleteModal+ title={`Delete \u201c${pendingDelete.name}\u201d?`}+ detail="Reports already written from it are not affected."+ confirmLabel="Delete template"+ isPending={deleteMutation.isPending}+ onClose={() => setPendingDelete(null)}+ onConfirm={() => deleteMutation.mutate(pendingDelete.id)}+ />+ ) : null}+ </div>+ );+}diff --git a/src/server/features/project-context/services/ProjectContextService.test.ts b/src/server/features/project-context/services/ProjectContextService.test.tsindex a6a8562f..5b1a0720 100644--- a/src/server/features/project-context/services/ProjectContextService.test.ts+++ b/src/server/features/project-context/services/ProjectContextService.test.ts@@ -18,6 +18,7 @@ const mocks = vi.hoisted(() => ({listResearchLog: vi.fn(),appendResearchLogEntry: vi.fn(),pruneResearchLogBefore: vi.fn(),+ listTemplates: vi.fn(),}));vi.mock(@@ -25,6 +26,13 @@ vi.mock(() => ({ ProjectContextRepository: mocks }),);+vi.mock(+ "@/server/features/reports/repositories/ReportTemplateRepository",+ () => ({+ ReportTemplateRepository: mocks,+ }),+);+// The real runBatch needs a Workers runtime; executing the built statements// directly preserves what the tests assert on (which repository writes ran).const runBatch = vi.hoisted(() =>@@ -53,6 +61,7 @@ describe("project context service", () => {mocks.listCompetitors.mockResolvedValue([]);mocks.listKeyPages.mockResolvedValue([]);mocks.listResearchLog.mockResolvedValue([]);+ mocks.listTemplates.mockResolvedValue([]);});it("splits typed from custom sections and reports the empty typed ones", async () => {@@ -320,6 +329,7 @@ describe("project context service", () => {competitors: [],keyPages: [],researchLog: [],+ reportTemplates: [],});expect(markdown).toContain("## Business overview\n\nWe sell paint.");@@ -339,6 +349,7 @@ describe("project context service", () => {customSections: [],competitors: [],keyPages: [],+ reportTemplates: [],researchLog: Array.from({ length: entryCount }, (_, index) => ({id: `log_${index}`,entryDate: "2026-08-15",diff --git a/src/server/features/project-context/services/ProjectContextService.ts b/src/server/features/project-context/services/ProjectContextService.tsindex c48a5afa..15d30fe6 100644--- a/src/server/features/project-context/services/ProjectContextService.ts+++ b/src/server/features/project-context/services/ProjectContextService.ts@@ -1,6 +1,7 @@import { runBatch } from "@/db/runBatch";import { ProjectContextRepository } from "@/server/features/project-context/repositories/ProjectContextRepository";import { resolveContextUpdates } from "@/server/features/project-context/services/contextUpdateOps";+import { ReportTemplateRepository } from "@/server/features/reports/repositories/ReportTemplateRepository";import {CUSTOM_SECTION_KEY_PREFIX,PROJECT_CONTEXT_SECTION_KEYS,@@ -10,7 +11,6 @@ import {type ProjectContextSectionKey,type ProjectContextUpdate,} from "@/types/schemas/projectContext";-// Project memory: the qualitative context SAM, MCP clients and the settings UI// share. Reading, writing and rendering it all go through here; the per-op// caps and normalization live in contextUpdateOps.@@ -56,17 +56,25 @@ type ProjectContext = {summary: string;createdBy: ContextAuthor;}[];+ /**+ * The project's report templates. They belong to the reports feature, but+ * this digest is the one block every skill already reads, so it is where+ * agents discover them.+ */+ reportTemplates: { name: string; description: string }[];};export async function getProjectContext(projectId: string,): Promise<ProjectContext> {- const [sectionRows, competitors, keyPages, researchLog] = await Promise.all([- ProjectContextRepository.listSections(projectId),- ProjectContextRepository.listCompetitors(projectId),- ProjectContextRepository.listKeyPages(projectId),- ProjectContextRepository.listResearchLog(projectId, RESEARCH_LOG_LIMIT),- ]);+ const [sectionRows, competitors, keyPages, researchLog, reportTemplates] =+ await Promise.all([+ ProjectContextRepository.listSections(projectId),+ ProjectContextRepository.listCompetitors(projectId),+ ProjectContextRepository.listKeyPages(projectId),+ ProjectContextRepository.listResearchLog(projectId, RESEARCH_LOG_LIMIT),+ ReportTemplateRepository.listTemplates(projectId),+ ]);const stored = new Map(sectionRows.map((row) => [row.key, row]));// Typed sections keep their declared order, which is also the order the@@ -107,6 +115,10 @@ export async function getProjectContext(summary: row.summary,createdBy: row.createdBy,})),+ reportTemplates: reportTemplates.map((template) => ({+ name: template.name,+ description: template.description,+ })),};}@@ -229,6 +241,9 @@ function pushSection(lines: string[], heading: string, body: string[]) {* `text` payload and for SAM's read-only context block. Typed sections are* always listed — an empty one shows up as missing, which is the signal agents* use to offer setup.+ *+ * The report-templates section is omitted entirely when there are none, so a+ * project with no templates reads exactly as it did before.*/export function renderProjectContextMarkdown(context: ProjectContext): string {const lines = ["# Project context", ""];@@ -293,6 +308,16 @@ export function renderProjectContextMarkdown(context: ProjectContext): string {],);+ if (context.reportTemplates.length > 0) {+ pushSection(+ lines,+ "Report templates",+ context.reportTemplates.map(+ (template) => `- ${template.name}: ${template.description}`,+ ),+ );+ }+lines.push(context.missingSections.length > 0? `Missing sections: ${context.missingSections.join(", ")}`diff --git a/src/server/features/reports/repositories/ReportRepository.ts b/src/server/features/reports/repositories/ReportRepository.tsindex c4c36091..51ff80c8 100644--- a/src/server/features/reports/repositories/ReportRepository.ts+++ b/src/server/features/reports/repositories/ReportRepository.ts@@ -16,6 +16,7 @@ const metadataColumns = {title: reports.title,summary: reports.summary,skill: reports.skill,+ templateId: reports.templateId,createdBy: reports.createdBy,createdByUserId: reports.createdByUserId,sizeBytes: reports.sizeBytes,@@ -136,6 +137,7 @@ async function insertReport(params: {summary: string;html: string;skill: string | null;+ templateId: string | null;createdBy: string;createdByUserId: string;sizeBytes: number;@@ -156,6 +158,7 @@ async function updateReportContent(params: {summary: string;html: string;skill: string | null;+ templateId: string | null;sizeBytes: number;}): Promise<void> {await db@@ -165,6 +168,7 @@ async function updateReportContent(params: {summary: params.summary,html: params.html,skill: params.skill,+ templateId: params.templateId,sizeBytes: params.sizeBytes,updatedAt: new Date().toISOString(),})diff --git a/src/server/features/reports/repositories/ReportTemplateRepository.ts b/src/server/features/reports/repositories/ReportTemplateRepository.tsnew file mode 100644index 00000000..f491feb8--- /dev/null+++ b/src/server/features/reports/repositories/ReportTemplateRepository.ts@@ -0,0 +1,113 @@+import { and, asc, eq } from "drizzle-orm";+import { db } from "@/db";+import { reportTemplates } from "@/db/schema";+import type { ReportTemplate } from "@/types/schemas/report-templates";++// Backing store for report templates. Every query filters on `project_id` as+// well as `id` — never a bare `WHERE id = ?` — because callers authorize the+// projectId they were given, not the child row, so a guessed id from another+// project must not resolve.++const columns = {+ id: reportTemplates.id,+ projectId: reportTemplates.projectId,+ name: reportTemplates.name,+ description: reportTemplates.description,+ instructions: reportTemplates.instructions,+ createdBy: reportTemplates.createdBy,+ createdByUserId: reportTemplates.createdByUserId,+ createdAt: reportTemplates.createdAt,+ updatedAt: reportTemplates.updatedAt,+};++async function listTemplates(projectId: string): Promise<ReportTemplate[]> {+ return db+ .select(columns)+ .from(reportTemplates)+ .where(eq(reportTemplates.projectId, projectId))+ .orderBy(asc(reportTemplates.name), asc(reportTemplates.id));+}++async function getTemplate(+ projectId: string,+ templateId: string,+): Promise<ReportTemplate | null> {+ const [row] = await db+ .select(columns)+ .from(reportTemplates)+ .where(+ and(+ eq(reportTemplates.id, templateId),+ eq(reportTemplates.projectId, projectId),+ ),+ )+ .limit(1);+ return row ?? null;+}++// createdAt/updatedAt are stamped here, not left to the column defaults: the+// two dialects' defaults render different formats.+async function insertTemplate(params: {+ id: string;+ projectId: string;+ name: string;+ description: string;+ instructions: string;+ createdBy: string;+ createdByUserId: string;+}): Promise<void> {+ const now = new Date().toISOString();+ await db+ .insert(reportTemplates)+ .values({ ...params, createdAt: now, updatedAt: now });+}++// Content only: the attribution columns are stamped at create and never+// re-stamped, so "created by" keeps meaning what it says after an edit.+async function updateTemplate(params: {+ templateId: string;+ projectId: string;+ name: string;+ description: string;+ instructions: string;+}): Promise<void> {+ await db+ .update(reportTemplates)+ .set({+ name: params.name,+ description: params.description,+ instructions: params.instructions,+ updatedAt: new Date().toISOString(),+ })+ .where(+ and(+ eq(reportTemplates.id, params.templateId),+ eq(reportTemplates.projectId, params.projectId),+ ),+ );+}++/** True when a row was deleted; false when the id is not in this project. */+async function deleteTemplate(+ projectId: string,+ templateId: string,+): Promise<boolean> {+ const deleted = await db+ .delete(reportTemplates)+ .where(+ and(+ eq(reportTemplates.id, templateId),+ eq(reportTemplates.projectId, projectId),+ ),+ )+ .returning({ id: reportTemplates.id });+ return deleted.length > 0;+}++export const ReportTemplateRepository = {+ listTemplates,+ getTemplate,+ insertTemplate,+ updateTemplate,+ deleteTemplate,+} as const;diff --git a/src/server/features/reports/services/ReportService.ts b/src/server/features/reports/services/ReportService.tsindex cca07e19..315005c1 100644--- a/src/server/features/reports/services/ReportService.ts+++ b/src/server/features/reports/services/ReportService.ts@@ -36,6 +36,8 @@ type SaveReportParams = {summary: string;html: string;skill?: string;+ /** Validated against the project by the caller, not here. */+ templateId?: string;/** Client label, stamped by the server. Never taken from the model. */createdBy: string;/** From the authenticated context, and nowhere else. */@@ -148,8 +150,10 @@ export async function saveReport(params: SaveReportParams): Promise<{html,// An update that omits the slug keeps the stored one: `skill` is// optional on save_report, and clearing it would drop the report out of- // the list's Skill column for no reason the caller asked for.+ // the list's Type column for no reason the caller asked for.skill: params.skill ?? existing.skill,+ // Same rule for the template the report was written from.+ templateId: params.templateId ?? existing.templateId,sizeBytes,});return {@@ -168,6 +172,7 @@ export async function saveReport(params: SaveReportParams): Promise<{summary,html,skill: params.skill ?? null,+ templateId: params.templateId ?? null,createdBy: params.createdBy,createdByUserId: params.createdByUserId,sizeBytes,diff --git a/src/server/features/reports/services/ReportTemplateService.test.ts b/src/server/features/reports/services/ReportTemplateService.test.tsnew file mode 100644index 00000000..de1b0755--- /dev/null+++ b/src/server/features/reports/services/ReportTemplateService.test.ts@@ -0,0 +1,125 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ deleteReportTemplate,+ saveReportTemplate,+} from "./ReportTemplateService";+import {+ REPORT_TEMPLATE_MAX_PER_PROJECT,+ type ReportTemplate,+} from "@/types/schemas/report-templates";++const mocks = vi.hoisted(() => ({+ listTemplates: vi.fn(),+ getTemplate: vi.fn(),+ insertTemplate: vi.fn(),+ updateTemplate: vi.fn(),+ deleteTemplate: vi.fn(),+}));++vi.mock(+ "@/server/features/reports/repositories/ReportTemplateRepository",+ () => ({ ReportTemplateRepository: mocks }),+);++const stored = (overrides: Partial<ReportTemplate> = {}): ReportTemplate => ({+ id: "template_1",+ projectId: "project_1",+ name: "Client-ready audit summary",+ description: "For the site owner, non-technical.",+ instructions: "Audience: the site owner. Sections: what we found.",+ createdBy: "Claude Code",+ createdByUserId: "user_1",+ createdAt: "2026-09-01T10:00:00.000Z",+ updatedAt: "2026-09-01T10:00:00.000Z",+ ...overrides,+});++const save = (+ overrides: Partial<Parameters<typeof saveReportTemplate>[0]> = {},+) =>+ saveReportTemplate({+ projectId: "project_1",+ name: "Client-ready audit summary",+ description: "For the site owner, non-technical.",+ instructions: "Audience: the site owner. Sections: what we found.",+ createdBy: "Claude Code",+ createdByUserId: "user_1",+ ...overrides,+ });++beforeEach(() => {+ mocks.listTemplates.mockResolvedValue([]);+});++describe("saveReportTemplate", () => {+ it("creates a template in the project", async () => {+ const result = await save();++ expect(result.created).toBe(true);+ expect(mocks.insertTemplate).toHaveBeenCalledWith(+ expect.objectContaining({ projectId: "project_1" }),+ );+ });++ it("updates by id instead of inserting", async () => {+ mocks.listTemplates.mockResolvedValue([stored()]);++ const result = await save({ templateId: "template_1", name: "Renamed" });++ expect(result).toEqual({+ templateId: "template_1",+ name: "Renamed",+ created: false,+ });+ expect(mocks.insertTemplate).not.toHaveBeenCalled();+ expect(mocks.updateTemplate).toHaveBeenCalledWith(+ expect.objectContaining({+ templateId: "template_1",+ projectId: "project_1",+ name: "Renamed",+ }),+ );+ });++ it("refuses an unknown templateId", async () => {+ await expect(save({ templateId: "template_other" })).rejects.toThrow(+ /No report template template_other/,+ );+ });++ it("refuses a name another template in the project already uses, ignoring case", async () => {+ mocks.listTemplates.mockResolvedValue([+ stored({ id: "template_other", name: "client-ready AUDIT summary" }),+ ]);++ await expect(save()).rejects.toThrow(+ /exists in this project \(id template_other\)/,+ );+ expect(mocks.insertTemplate).not.toHaveBeenCalled();+ });++ it("refuses a create at the per-project cap", async () => {+ mocks.listTemplates.mockResolvedValue(+ Array.from({ length: REPORT_TEMPLATE_MAX_PER_PROJECT }, (_, index) =>+ stored({ id: `template_${index}`, name: `Template ${index}` }),+ ),+ );++ await expect(save()).rejects.toThrow(/report templates, the limit/);+ expect(mocks.insertTemplate).not.toHaveBeenCalled();+ });+});++describe("deleteReportTemplate", () => {+ it("refuses a template that does not resolve in this project", async () => {+ mocks.deleteTemplate.mockResolvedValue(false);++ await expect(+ deleteReportTemplate("project_1", "template_x"),+ ).rejects.toThrow(/No report template template_x/);+ expect(mocks.deleteTemplate).toHaveBeenCalledWith(+ "project_1",+ "template_x",+ );+ });+});diff --git a/src/server/features/reports/services/ReportTemplateService.ts b/src/server/features/reports/services/ReportTemplateService.tsnew file mode 100644index 00000000..2a6278e4--- /dev/null+++ b/src/server/features/reports/services/ReportTemplateService.ts@@ -0,0 +1,184 @@+import { ReportTemplateRepository } from "@/server/features/reports/repositories/ReportTemplateRepository";+import { AppError } from "@/server/lib/errors";+import { formatCount } from "@/shared/format";+import {+ REPORT_TEMPLATE_MAX_DESCRIPTION_CHARS,+ REPORT_TEMPLATE_MAX_INSTRUCTIONS_CHARS,+ REPORT_TEMPLATE_MAX_NAME_CHARS,+ REPORT_TEMPLATE_MAX_PER_PROJECT,+ type ReportTemplate,+} from "@/types/schemas/report-templates";++// Report templates: the named briefs agents follow when writing a report.+// Every caller (server function, MCP tool, SAM) comes through here, so the caps+// and the refusal copy exist once. Authorization is NOT done here — the caller+// has already authorized `projectId` and every query is scoped to it.++/** This project's templates, and the room left under the cap. */+async function listReportTemplates(projectId: string): Promise<{+ templates: ReportTemplate[];+ remaining: number;+}> {+ const templates = await ReportTemplateRepository.listTemplates(projectId);+ return {+ templates,+ remaining: Math.max(0, REPORT_TEMPLATE_MAX_PER_PROJECT - templates.length),+ };+}++async function getReportTemplate(+ projectId: string,+ templateId: string,+): Promise<ReportTemplate> {+ const template = await ReportTemplateRepository.getTemplate(+ projectId,+ templateId,+ );+ if (!template) throw notFound(templateId);+ return template;+}++function notFound(templateId: string) {+ return new AppError(+ "NOT_FOUND",+ `No report template ${templateId} in this project. Call list_report_templates to see what exists.`,+ );+}++type SaveParams = {+ projectId: string;+ templateId?: string;+ name: string;+ description: string;+ instructions: string;+ /** Client label, stamped by the server. Never taken from the model. */+ createdBy: string;+ /** From the authenticated context, and nowhere else. */+ createdByUserId: string;+};++/**+ * Create-or-update in one call. Everything is validated before anything is+ * written, so a rejected save leaves the stored template untouched.+ */+export async function saveReportTemplate(params: SaveParams): Promise<{+ templateId: string;+ name: string;+ created: boolean;+}> {+ const name = params.name.trim();+ const description = params.description.trim();+ const instructions = params.instructions.trim();++ if (name.length === 0) {+ throw new AppError("VALIDATION_ERROR", "Give the template a name.");+ }+ if (name.length > REPORT_TEMPLATE_MAX_NAME_CHARS) {+ throw new AppError(+ "VALIDATION_ERROR",+ `Name is ${formatCount(name.length)} characters; the limit is ${formatCount(REPORT_TEMPLATE_MAX_NAME_CHARS)}. Shorten it and save again.`,+ );+ }+ if (description.length === 0) {+ throw new AppError(+ "VALIDATION_ERROR",+ "Add a one-line description saying when to use this template. It is what an agent reads to decide.",+ );+ }+ if (description.length > REPORT_TEMPLATE_MAX_DESCRIPTION_CHARS) {+ throw new AppError(+ "VALIDATION_ERROR",+ `Description is ${formatCount(description.length)} characters; the limit is ${formatCount(REPORT_TEMPLATE_MAX_DESCRIPTION_CHARS)}. It is one line saying when to use the template — move the detail into the instructions.`,+ );+ }+ if (instructions.length === 0) {+ throw new AppError(+ "VALIDATION_ERROR",+ "Add instructions: the audience, the sections in order, the tone, and the sign-off.",+ );+ }+ if (instructions.length > REPORT_TEMPLATE_MAX_INSTRUCTIONS_CHARS) {+ throw new AppError(+ "VALIDATION_ERROR",+ `Instructions are ${formatCount(instructions.length)} characters; the limit is ${formatCount(REPORT_TEMPLATE_MAX_INSTRUCTIONS_CHARS)}. A template is a brief, not the report — say the audience, the sections in order, the tone and the sign-off, and cut the rest.`,+ );+ }++ // One read serves the existence check, the duplicate-name check and the cap.+ const templates = await ReportTemplateRepository.listTemplates(+ params.projectId,+ );+ const existing = params.templateId+ ? templates.find((template) => template.id === params.templateId)+ : undefined;+ if (params.templateId && !existing) {+ throw new AppError(+ "NOT_FOUND",+ `No report template ${params.templateId} in this project. Call list_report_templates, or omit templateId to create a new one.`,+ );+ }++ // A name that appears twice in a project makes "use the monthly check-in+ // template" ambiguous, so a rename clears the same bar as a create.+ const lowerName = name.toLowerCase();+ const clash = templates.find(+ (template) =>+ template.name.toLowerCase() === lowerName && template.id !== existing?.id,+ );+ if (clash) {+ throw new AppError(+ "VALIDATION_ERROR",+ `A template named "${clash.name}" exists in this project (id ${clash.id}). Pass its templateId to update it, or choose another name.`,+ );+ }++ if (existing) {+ await ReportTemplateRepository.updateTemplate({+ templateId: existing.id,+ projectId: params.projectId,+ name,+ description,+ instructions,+ });+ return { templateId: existing.id, name, created: false };+ }++ // Plain read-then-write: concurrent saves can both pass at the cap, which is+ // accepted — this is a guardrail, not an invariant, and the next save refuses.+ if (templates.length >= REPORT_TEMPLATE_MAX_PER_PROJECT) {+ throw new AppError(+ "VALIDATION_ERROR",+ `This project has ${formatCount(REPORT_TEMPLATE_MAX_PER_PROJECT)} report templates, the limit. Delete one from the Templates page.`,+ );+ }++ const id = crypto.randomUUID();+ await ReportTemplateRepository.insertTemplate({+ id,+ projectId: params.projectId,+ name,+ description,+ instructions,+ createdBy: params.createdBy,+ createdByUserId: params.createdByUserId,+ });+ return { templateId: id, name, created: true };+}++export async function deleteReportTemplate(+ projectId: string,+ templateId: string,+): Promise<void> {+ const deleted = await ReportTemplateRepository.deleteTemplate(+ projectId,+ templateId,+ );+ if (!deleted) throw notFound(templateId);+}++export const ReportTemplateService = {+ listReportTemplates,+ getReportTemplate,+ saveReportTemplate,+ deleteReportTemplate,+} as const;diff --git a/src/server/mcp/server.ts b/src/server/mcp/server.tsindex 1956aa68..cd5018ab 100644--- a/src/server/mcp/server.ts+++ b/src/server/mcp/server.ts@@ -62,6 +62,10 @@ import {listReportsTool,saveReportTool,} from "@/server/mcp/tools/report-tools";+import {+ listReportTemplatesTool,+ saveReportTemplateTool,+} from "@/server/mcp/tools/report-template-tools";import { researchKeywordsTool } from "@/server/mcp/tools/research-keywords";import { saveKeywordsTool } from "@/server/mcp/tools/save-keywords";import {@@ -213,6 +217,8 @@ export function createOpenSeoMcpServer(authProps: McpProps) {register(saveReportTool);register(listReportsTool);register(getReportTool);+ register(listReportTemplatesTool);+ register(saveReportTemplateTool);return server;}diff --git a/src/server/mcp/tools/meta-only-response.test.ts b/src/server/mcp/tools/meta-only-response.test.tsindex 3e6ffc8e..cc2decff 100644--- a/src/server/mcp/tools/meta-only-response.test.ts+++ b/src/server/mcp/tools/meta-only-response.test.ts@@ -28,6 +28,7 @@ import * as listSavedKeywords from "./list-saved-keywords";import * as localSeoTools from "./local-seo-tools";import * as projectContext from "./project-context";import * as removeRankTrackingKeywords from "./remove-rank-tracking-keywords";+import * as reportTemplateTools from "./report-template-tools";import * as reportTools from "./report-tools";import * as researchKeywords from "./research-keywords";import * as runRankTracker from "./run-rank-tracker";@@ -54,6 +55,7 @@ const toolExports: Record<string, unknown> = {...localSeoTools,...projectContext,...removeRankTrackingKeywords,+ ...reportTemplateTools,...reportTools,...researchKeywords,...runRankTracker,diff --git a/src/server/mcp/tools/project-context.test.ts b/src/server/mcp/tools/project-context.test.tsindex 85bdd4e3..dec3c4ee 100644--- a/src/server/mcp/tools/project-context.test.ts+++ b/src/server/mcp/tools/project-context.test.ts@@ -1,5 +1,8 @@import { beforeEach, describe, expect, it, vi } from "vitest";-import { updateProjectContextTool } from "./project-context";+import {+ getProjectContextTool,+ updateProjectContextTool,+} from "./project-context";import { makeToolContext, textContent } from "./tool-test-support";// The repository is the seam, not the service: the tool's contract is that an@@ -12,6 +15,7 @@ const mocks = vi.hoisted(() => ({listCompetitors: vi.fn(),listKeyPages: vi.fn(),listResearchLog: vi.fn(),+ listTemplates: vi.fn(),}));vi.mock("cloudflare:workers", () => ({ env: {} }));@@ -30,6 +34,12 @@ vi.mock("@/server/features/project-context/repositories/ProjectContextRepository",() => ({ ProjectContextRepository: mocks }),);+// The digest lists the project's report templates, which live in the reports+// feature's own store.+vi.mock(+ "@/server/features/reports/repositories/ReportTemplateRepository",+ () => ({ ReportTemplateRepository: mocks }),+);beforeEach(() => {mocks.getProjectForOrganization.mockResolvedValue({ id: "project_1" });@@ -37,6 +47,7 @@ beforeEach(() => {mocks.listCompetitors.mockResolvedValue([]);mocks.listKeyPages.mockResolvedValue([]);mocks.listResearchLog.mockResolvedValue([]);+ mocks.listTemplates.mockResolvedValue([]);});describe("update_project_context", () => {@@ -77,3 +88,33 @@ describe("update_project_context", () => {expect(textContent(result)).toContain("Grow signups");});});++describe("get_project_context", () => {+ // Templates are discovered through the digest and nowhere else, so an agent+ // that cannot read the menu here will never follow a template.+ it("lists the project's report templates", async () => {+ mocks.listTemplates.mockResolvedValue([+ {+ id: "template_1",+ projectId: "project_1",+ name: "Monthly client check-in",+ description: "The monthly update we send retainer clients.",+ instructions: "Audience: the client's marketing lead.",+ createdBy: "OpenSEO app",+ createdByUserId: "user_1",+ createdAt: "2026-09-01T10:00:00.000Z",+ updatedAt: "2026-09-01T10:00:00.000Z",+ },+ ]);++ const result = await getProjectContextTool.handler(+ { projectId: "project_1" },+ makeToolContext(),+ );++ expect(textContent(result)).toContain("## Report templates");+ expect(textContent(result)).toContain(+ "- Monthly client check-in: The monthly update we send retainer clients.",+ );+ });+});diff --git a/src/server/mcp/tools/project-context.ts b/src/server/mcp/tools/project-context.tsindex c8f59830..6d72b6ad 100644--- a/src/server/mcp/tools/project-context.ts+++ b/src/server/mcp/tools/project-context.ts@@ -23,6 +23,7 @@ const contextOutputSchema = {competitors: z.array(looseObjectOutputSchema),keyPages: z.array(looseObjectOutputSchema),researchLog: z.array(looseObjectOutputSchema),+ reportTemplates: z.array(looseObjectOutputSchema),...optionalMetaOutputSchema,} as const;diff --git a/src/server/mcp/tools/report-template-tools.ts b/src/server/mcp/tools/report-template-tools.tsnew file mode 100644index 00000000..c9721a3e--- /dev/null+++ b/src/server/mcp/tools/report-template-tools.ts@@ -0,0 +1,179 @@+import { z } from "zod";+import { ReportTemplateService } from "@/server/features/reports/services/ReportTemplateService";+import { captureServerEvent } from "@/server/lib/posthog";+import { DEFAULT_CLIENT_LABEL } from "@/server/mcp/client-label";+import { buildProjectMeta } from "@/server/mcp/context";+import { mcpResponse, truncatePreview } from "@/server/mcp/formatters";+import {+ looseObjectOutputSchema,+ optionalMetaOutputSchema,+} from "@/server/mcp/output-schemas";+import { withMcpProjectAuth } from "@/server/mcp/project-auth";+import { projectIdSchema } from "@/server/mcp/schemas";+import { buildDashboardUrl } from "@/server/mcp/urls";+import { formatCount } from "@/shared/format";+import {+ REPORT_TEMPLATE_MAX_DESCRIPTION_CHARS,+ REPORT_TEMPLATE_MAX_INSTRUCTIONS_CHARS,+ REPORT_TEMPLATE_MAX_NAME_CHARS,+} from "@/types/schemas/report-templates";++// The two report-template tools. Both free (they touch only the app DB), both+// wrapped in withMcpProjectAuth, and both scoped to the authorized project — a+// template id from another project never resolves.++const templatesPath = (projectId: string) =>+ `/p/${projectId}/reports/templates`;++// ------------------------------------------------- list_report_templates++const listInputSchema = { projectId: projectIdSchema } as const;++const listOutputSchema = {+ templates: z.array(looseObjectOutputSchema),+ remaining: z.number(),+ ...optionalMetaOutputSchema,+} as const;++export const listReportTemplatesTool = {+ name: "list_report_templates",+ config: {+ title: "List report templates",+ description:+ "Lists this project's report templates. Uses no credits. A template is a reusable brief — audience, sections in order, tone, sign-off — that replaces a skill's default report format. Read one only when the user names it or asks for the kind of report it describes; a plain skill run uses the skill's own format. Pass the template's id to save_report as templateId. To reuse one in another project, list it there and save it here.",+ inputSchema: listInputSchema,+ outputSchema: listOutputSchema,+ annotations: {+ readOnlyHint: true,+ openWorldHint: false,+ destructiveHint: false,+ },+ },+ handler: withMcpProjectAuth(+ async (args: z.infer<z.ZodObject<typeof listInputSchema>>, context) => {+ const { templates, remaining } =+ await ReportTemplateService.listReportTemplates(args.projectId);++ const blocks = templates.map((template) =>+ [+ `${template.id} ${template.name}`,+ ` ${template.description}`,+ "",+ template.instructions,+ ].join("\n"),+ );++ return mcpResponse({+ text:+ templates.length > 0+ ? blocks.join("\n\n---\n\n")+ : "This project has no report templates. Reports use the running skill's own format.",+ meta: buildProjectMeta(+ context,+ args.projectId,+ templatesPath(args.projectId),+ ),+ structuredContent: {+ templates: templates.map((template) => ({+ id: template.id,+ name: template.name,+ description: template.description,+ instructionsPreview: truncatePreview(template.instructions),+ updatedAt: template.updatedAt,+ })),+ remaining,+ },+ });+ },+ ),+};++// ------------------------------------------------- save_report_template++const saveInputSchema = {+ projectId: projectIdSchema,+ templateId: z+ .string()+ .min(1)+ .optional()+ .describe(+ "Omit to create a new template. Pass an id from list_report_templates to replace that template's name, description and instructions in place.",+ ),+ name: z+ .string()+ .min(1)+ .describe(+ `What the user will ask for by name, e.g. "Client-ready audit summary". Max ${REPORT_TEMPLATE_MAX_NAME_CHARS} characters.`,+ ),+ description: z+ .string()+ .min(1)+ .describe(+ `One line saying when to use this template. Agents read this to decide whether it applies, so name the occasion, not the format. Max ${REPORT_TEMPLATE_MAX_DESCRIPTION_CHARS} characters.`,+ ),+ instructions: z+ .string()+ .min(1)+ .describe(+ `Markdown, max ${formatCount(REPORT_TEMPLATE_MAX_INSTRUCTIONS_CHARS)} characters: the audience, the sections in order, the tone, the sign-off, and optionally an accent color as "accent: #1C4ED8". This replaces the skill's default section list and tone — never the seo-report HTML constraints, which always apply.`,+ ),+} as const;++const saveOutputSchema = {+ templateId: z.string(),+ name: z.string(),+ created: z.boolean(),+ url: z.string(),+ ...optionalMetaOutputSchema,+} as const;++export const saveReportTemplateTool = {+ name: "save_report_template",+ config: {+ title: "Save report template",+ description:+ "Saves a reusable report brief to this project. Uses no credits. Only do this when the user asks for a template, or agrees to one — a one-off report needs no template. Call list_report_templates first and pass the matching templateId to edit an existing template rather than creating a near-duplicate; a name already used in this project is refused.",+ inputSchema: saveInputSchema,+ outputSchema: saveOutputSchema,+ annotations: {+ readOnlyHint: false,+ openWorldHint: false,+ // A save with a templateId overwrites the stored brief.+ destructiveHint: true,+ },+ },+ handler: withMcpProjectAuth(+ async (args: z.infer<z.ZodObject<typeof saveInputSchema>>, context) => {+ const { templateId, name, created } =+ await ReportTemplateService.saveReportTemplate({+ projectId: args.projectId,+ templateId: args.templateId,+ name: args.name,+ description: args.description,+ instructions: args.instructions,+ createdBy: context.auth.clientLabel ?? DEFAULT_CLIENT_LABEL,+ createdByUserId: context.auth.userId,+ });++ const path = templatesPath(args.projectId);+ const url = buildDashboardUrl(context.baseUrl, path);++ await captureServerEvent({+ distinctId: context.auth.userId,+ event: "report_template:saved",+ organizationId: context.auth.organizationId,+ properties: {+ project_id: args.projectId,+ is_update: !created,+ source: "mcp",+ },+ });++ return mcpResponse({+ text: `${created ? "Saved" : "Updated"} report template "${name}" (id ${templateId}) in this project. Pass templateId: "${templateId}" to save_report when you write a report from it. Manage templates at ${url}.`,+ meta: buildProjectMeta(context, args.projectId, path),+ structuredContent: { templateId, name, created, url },+ });+ },+ ),+};diff --git a/src/server/mcp/tools/report-tools.test.ts b/src/server/mcp/tools/report-tools.test.tsindex 0f98593a..02c56ed2 100644--- a/src/server/mcp/tools/report-tools.test.ts+++ b/src/server/mcp/tools/report-tools.test.ts@@ -16,6 +16,7 @@ const mocks = vi.hoisted(() => ({sumReportBytesForOrganization: vi.fn(),insertReport: vi.fn(),updateReportContent: vi.fn(),+ getTemplate: vi.fn(),captureServerEvent: vi.fn(),}));@@ -28,6 +29,10 @@ vi.mock("@/server/features/projects/services/ProjectService", () => ({vi.mock("@/server/features/reports/repositories/ReportRepository", () => ({ReportRepository: mocks,}));+vi.mock(+ "@/server/features/reports/repositories/ReportTemplateRepository",+ () => ({ ReportTemplateRepository: mocks }),+);vi.mock("@/server/lib/posthog", () => ({captureServerEvent: mocks.captureServerEvent,}));@@ -55,6 +60,7 @@ beforeEach(() => {mocks.countReports.mockResolvedValue(3);mocks.sumReportBytesForOrganization.mockResolvedValue(0);mocks.findReportByTitle.mockResolvedValue(null);+ mocks.getTemplate.mockResolvedValue(null);mocks.captureServerEvent.mockResolvedValue(undefined);});@@ -93,6 +99,7 @@ describe("save_report", () => {properties: {project_id: projectId,skill: "seo-audit",+ used_template: false,size_bytes: new TextEncoder().encode(html).length,client: "Claude Code",is_update: false,@@ -123,6 +130,24 @@ describe("save_report", () => {expect(result.structuredContent.created).toBe(false);});+ it("refuses a templateId that does not resolve in this project", async () => {+ // The template lookup is project-scoped, so another project's template+ // reads exactly like a deleted one.+ await expect(+ saveReportTool.handler(+ {+ projectId,+ title: "badseo.dev SEO audit, Sep 2026",+ summary: "Verdict: titles are the problem.",+ html,+ templateId: "template_other_project",+ },+ toolContext,+ ),+ ).rejects.toThrow(/No report template template_other_project/);+ expect(mocks.insertReport).not.toHaveBeenCalled();+ });+it("passes a service refusal through with its message", async () => {mocks.findReportByTitle.mockResolvedValue({id: reportId,diff --git a/src/server/mcp/tools/report-tools.ts b/src/server/mcp/tools/report-tools.tsindex 0307947c..799b7090 100644--- a/src/server/mcp/tools/report-tools.ts+++ b/src/server/mcp/tools/report-tools.ts@@ -1,5 +1,6 @@import { z } from "zod";import { ReportService } from "@/server/features/reports/services/ReportService";+import { ReportTemplateService } from "@/server/features/reports/services/ReportTemplateService";import { captureServerEvent } from "@/server/lib/posthog";import { DEFAULT_CLIENT_LABEL } from "@/server/mcp/client-label";import { buildProjectMeta } from "@/server/mcp/context";@@ -80,6 +81,13 @@ const saveInputSchema = {.describe('The slug of the skill that produced this report — the name of the SKILL.md you are running, e.g. "seo-audit". The report list keys on it, so a save without it shows "—".',),+ templateId: z+ .string()+ .min(1)+ .optional()+ .describe(+ "The id of the report template you followed, from list_report_templates or the project context. Pass it only when you actually followed that template; it is what the report list and the report page show instead of the skill slug.",+ ),} as const;const saveOutputSchema = {@@ -108,6 +116,15 @@ export const saveReportTool = {},handler: withMcpProjectAuth(async (args: z.infer<z.ZodObject<typeof saveInputSchema>>, context) => {+ // Resolved against the authorized project before the save: an id from+ // another project must not be stored, and a dangling one would render+ // as no template at all.+ if (args.templateId) {+ await ReportTemplateService.getReportTemplate(+ args.projectId,+ args.templateId,+ );+ }const saved = await ReportService.saveReport({projectId: args.projectId,organizationId: context.auth.organizationId,@@ -116,6 +133,7 @@ export const saveReportTool = {summary: args.summary,html: args.html,skill: args.skill,+ templateId: args.templateId,// Never taken from the model: the label the transport derived from the// request.createdBy: context.auth.clientLabel ?? DEFAULT_CLIENT_LABEL,@@ -132,6 +150,7 @@ export const saveReportTool = {properties: {project_id: args.projectId,skill: args.skill,+ used_template: Boolean(args.templateId),size_bytes: saved.htmlBytes,client: context.auth.clientLabel,is_update: !saved.created,diff --git a/src/serverFunctions/reportTemplates.ts b/src/serverFunctions/reportTemplates.tsnew file mode 100644index 00000000..c6a6afea--- /dev/null+++ b/src/serverFunctions/reportTemplates.ts@@ -0,0 +1,69 @@+import { createServerFn } from "@tanstack/react-start";+import { z } from "zod";+import { ReportTemplateService } from "@/server/features/reports/services/ReportTemplateService";+import { AppError } from "@/server/lib/errors";+import { requireProjectContext } from "@/serverFunctions/middleware";++// Report templates for the app. The `projectId` field in each validator is what+// triggers project authorization (ADR 0001); the service never authorizes.++const projectScopeSchema = z.object({ projectId: z.string().min(1) });++// Shape only; the service owns the caps and the refusal copy.+const saveSchema = z.object({+ projectId: z.string().min(1),+ templateId: z.string().min(1).optional(),+ name: z.string().min(1),+ description: z.string().min(1),+ instructions: z.string().min(1),+});++const templateRefSchema = z.object({+ projectId: z.string().min(1),+ templateId: z.string().min(1),+});++export const listReportTemplates = createServerFn({ method: "POST" })+ .middleware(requireProjectContext)+ .validator(projectScopeSchema)+ .handler(async ({ context }) =>+ ReportTemplateService.listReportTemplates(context.projectId),+ );++export const saveReportTemplate = createServerFn({ method: "POST" })+ .middleware(requireProjectContext)+ .validator(saveSchema)+ .handler(async ({ data, context }) => {+ try {+ const { templateId, created } =+ await ReportTemplateService.saveReportTemplate({+ projectId: context.projectId,+ templateId: data.templateId,+ name: data.name,+ description: data.description,+ instructions: data.instructions,+ // The client label for a template made in the app, not through MCP.+ createdBy: "OpenSEO app",+ createdByUserId: context.userId,+ });+ return { ok: true as const, templateId, created };+ } catch (error) {+ // A refusal (duplicate name, the cap) is the answer the form shows, and+ // thrown errors reach the client stripped to their code.+ if (error instanceof AppError && error.code === "VALIDATION_ERROR") {+ return { ok: false as const, message: error.message };+ }+ throw error;+ }+ });++export const deleteReportTemplate = createServerFn({ method: "POST" })+ .middleware(requireProjectContext)+ .validator(templateRefSchema)+ .handler(async ({ data, context }) => {+ await ReportTemplateService.deleteReportTemplate(+ context.projectId,+ data.templateId,+ );+ return { templateId: data.templateId };+ });diff --git a/src/serverFunctions/reports.ts b/src/serverFunctions/reports.tsindex 0eb5bedc..d4336ebf 100644--- a/src/serverFunctions/reports.ts+++ b/src/serverFunctions/reports.ts@@ -3,6 +3,7 @@ import { omit } from "remeda";import { z } from "zod";import { AuthRepository } from "@/server/auth/repositories/AuthRepository";import { ReportService } from "@/server/features/reports/services/ReportService";+import { ReportTemplateService } from "@/server/features/reports/services/ReportTemplateService";import { requireProjectContext } from "@/serverFunctions/middleware";import {REPORT_APP_LIST_LIMIT,@@ -39,18 +40,29 @@ export type ReportListItem = Omit<ReportMetadata, "summary"> & {* label alone.*/createdByName: string | null;+ /** The template's name, or null when the report followed none or its id no longer resolves in this project. */+ templateName: string | null;};-// One lookup for all savers, not one per row.-async function withCreatorNames(+// One lookup for all savers and one for all templates, not one per row. The+// project's whole template list is the name lookup: it is capped at ten rows.+async function withDisplayNames(reports: ReportMetadata[],+ projectId: string,): Promise<ReportListItem[]> {const userIds = [...new Set(reports.map((report) => report.createdByUserId))];- const users = await AuthRepository.getHostedUserNames(userIds);+ const [users, { templates }] = await Promise.all([+ AuthRepository.getHostedUserNames(userIds),+ ReportTemplateService.listReportTemplates(projectId),+ ]);const names = new Map(users.map((user) => [user.id, user.name]));+ const templateNames = new Map(templates.map((t) => [t.id, t.name]));return reports.map((report) => ({...omit(report, ["summary"]),createdByName: names.get(report.createdByUserId) ?? null,+ templateName: report.templateId+ ? (templateNames.get(report.templateId) ?? null)+ : null,}));}@@ -66,7 +78,9 @@ export const listReports = createServerFn({ method: "POST" })// Neither `remaining` nor `totalCount` is returned: the page shows the// most recent REPORT_APP_LIST_LIMIT reports and says so when it is full,// and the caps are runaway guards nobody needs a running tally against.- return { reports: await withCreatorNames(result.reports) };+ return {+ reports: await withDisplayNames(result.reports, context.projectId),+ };});/** Metadata only. The document itself is served by /r/<reportId>. */@@ -78,8 +92,8 @@ export const getReport = createServerFn({ method: "POST" })context.projectId,data.reportId,);- const [withName] = await withCreatorNames([report]);- return withName;+ const [withNames] = await withDisplayNames([report], context.projectId);+ return withNames;});export const deleteReport = createServerFn({ method: "POST" })diff --git a/src/types/schemas/report-templates.ts b/src/types/schemas/report-templates.tsnew file mode 100644index 00000000..9c80f3c8--- /dev/null+++ b/src/types/schemas/report-templates.ts@@ -0,0 +1,26 @@+// Shared vocabulary for report templates. The caps are enforced in+// ReportTemplateService with actionable copy; Zod at each boundary validates+// shape only.++/**+ * Small on purpose: the list is read by agents inside the project-context+ * digest, and a long menu of near-identical formats makes the choice worse.+ */+export const REPORT_TEMPLATE_MAX_PER_PROJECT = 10;+export const REPORT_TEMPLATE_MAX_NAME_CHARS = 80;+export const REPORT_TEMPLATE_MAX_DESCRIPTION_CHARS = 200;+/** A brief, not a document. Ten at the cap is the 30 KB list_report_templates worst case. */+export const REPORT_TEMPLATE_MAX_INSTRUCTIONS_CHARS = 3_000;++/** A stored template. A plain type, as ReportMetadata: rows come from the repository's own column selection. */+export type ReportTemplate = {+ id: string;+ projectId: string;+ name: string;+ description: string;+ instructions: string;+ createdBy: string;+ createdByUserId: string;+ createdAt: string;+ updatedAt: string;+};diff --git a/src/types/schemas/reports.ts b/src/types/schemas/reports.tsindex 8f8214a9..86cd9ee9 100644--- a/src/types/schemas/reports.ts+++ b/src/types/schemas/reports.ts@@ -50,6 +50,9 @@ export type ReportMetadata = {title: string;summary: string;skill: string | null;+ /** The report template the agent followed, or null. Unresolved: the name is+ * looked up project-scoped by the reader that needs it. */+ templateId: string | null;createdBy: string;createdByUserId: string;/** UTF-8 byte length of the stored document. */diff --git a/web/content/docs/mcp.md b/web/content/docs/mcp.mdindex 36555d65..43d32094 100644--- a/web/content/docs/mcp.md+++ b/web/content/docs/mcp.md@@ -133,6 +133,8 @@ OpenSEO MCP exposes tools for SEO research workflows:- Read first-party Google Search Console performance (clicks, impressions, CTR, position).- Inspect index status, crawl, and canonical for specific URLs (up to 10 per call).- Read and update a project's shared context: business, goal, positioning, writing preferences, competitors, key pages, and a research log (free, no credits).+- Save and read HTML reports on a project (free, no credits).+- List a project's report templates, and save a reusable report brief to the project (free, no credits).## What to do after setupdiff --git a/web/content/docs/skills/seo-report.mdx b/web/content/docs/skills/seo-report.mdxindex 6ce9d9bf..683c9080 100644--- a/web/content/docs/skills/seo-report.mdx+++ b/web/content/docs/skills/seo-report.mdx@@ -29,6 +29,12 @@ Reports are free. They do not spend credits, and there is no practical limit on- Say who the report is for. The agent puts it in the byline and pitches the language to match.- Reports have no version history and no undo, so a correction overwrites what was there.+## Report templates++A template is a reusable brief for a kind of report: who it is for, which sections it has and in what order, how it should sound, and how to sign off. Create one on the Templates page, reached from the Reports page in your project. Templates belong to a project; to reuse one somewhere else, ask your agent to list it in the first project and save a copy in the second.++Your agent sees a project's templates and follows one when you name it, or when you ask for the kind of report it describes ("write the client-ready audit summary for badseo.dev"). A plain "audit this site" still uses the skill's own format. The template replaces the sections and the tone; it never changes how the page is built, so the report still prints and still opens on a phone.+## Read the actual skillThe source `SKILL.md`, including the starter template, lives on GitHub: