Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
feat(reports): agent-written HTML reports per project (#570)
Ben Senescu99be193db70c
diff --git a/.agents/PAPERCUTS.md b/.agents/PAPERCUTS.mdindex c26058f5..8233f8ac 100644--- a/.agents/PAPERCUTS.md+++ b/.agents/PAPERCUTS.md@@ -10,6 +10,7 @@ data, or sensitive paths.## Open+- [ ] `2026-09-03T00:00:00Z` — `claude` — `pnpm ci:check` does not run `pnpm build`, so a route file that pulls `cloudflare:workers` into the client bundle passes every check and still breaks the build (hit on the dynamic-reports branch). Add a build step to `ci:check`, or document that `pnpm build` must be run separately before opening a PR.- [ ] `2026-09-11T00:13:05Z` — `codex` — The web-content review skill points to the removed `src/server/features/onboarding/openseo-fact-sheet.md`; the reference now lives at `src/server/features/sam/openseo-fact-sheet.md`. Update the skill's pointer so content reviews reach the current fact sheet.- `2026-09-05T23:52:53Z` — `codex` — After `pnpm build` ran alongside an active Vite dev server, browser navigation failed and server functions returned undefined. The server logged `Cannot read properties of undefined (reading 'map')` in `runInRunnerObject` / `loadEntries`. Restarting Vite restored the same dashboard without code changes. Stop and restart the dev server around production builds before browser QA; consider documenting or isolating the shared build/runtime state.diff --git a/.agents/skills/competitive-landscape/SKILL.md b/.agents/skills/competitive-landscape/SKILL.mdindex 0036b9d5..22f9a707 100644--- a/.agents/skills/competitive-landscape/SKILL.md+++ b/.agents/skills/competitive-landscape/SKILL.md@@ -27,6 +27,10 @@ The project-context tools are free and shared with the app and other agents.3. Before spending credits, check the research log. If the same research ran within the last 30 days, reuse that result and say so instead of re-buying it.4. On finish, write back what is durable with `update_project_context` — every confirmed competitor via `addCompetitors` with a short note on why they matter, plus `removeCompetitors` for entries you added that turned out irrelevant (leave rows the user added alone) — and append a research log entry: `{ appendResearchLog: { summary: "Competitive landscape: <market/query set>. Verdict: <conclusion>" } }`.+## Deliver as a report++Deliver through the `seo-report` skill, saving with `skill: "competitive-landscape"`. If that skill is not available, say so and stop before writing HTML.+## OpenSEO MCP tools- `research_keywords`: discover representative market queries.@@ -61,24 +65,16 @@ The project-context tools are free and shared with the app and other agents.## Output format-Start with the market read:--- Market leaders-- Most winnable opportunity area-- Biggest barrier to ranking--Then include:--| Domain | Type | Why they matter | Organic footprint | Winning themes | Weakness/gap |-| ------ | ---- | --------------- | ----------------- | -------------- | ------------ |+`h1`: the market or category.-Add:+Sections in this order:-- Query set used-- Content formats that are working-- Keyword/theme gaps-- Backlink or authority observations-- Recommended next workflows: competitor analysis, keyword clustering, or content brief+1. **The market read** — one or two opening sentences naming the leaders, the most winnable area, and the biggest barrier.+2. **Who is winning** — a table of domain, type, organic footprint, winning themes, and the gap. Label domain types explicitly.+3. **Why they win** — one finding per pattern, the Fix pointing at what the user should do instead.+4. **Gaps and openings** — a table of theme, demand, and who currently owns it, plus a bar chart when a handful of themes carry the demand.+5. **What to do next** — an ordered list ending in the next workflow to run: competitor analysis, keyword clustering, or a content brief.+6. **Method** — the query set used, and a note calling the read directional when the query set was small.## Guardrailsdiff --git a/.agents/skills/competitor-analysis/SKILL.md b/.agents/skills/competitor-analysis/SKILL.mdindex f84f5d78..e77bf8bc 100644--- a/.agents/skills/competitor-analysis/SKILL.md+++ b/.agents/skills/competitor-analysis/SKILL.md@@ -27,6 +27,10 @@ The project-context tools are free and shared with the app and other agents.3. Before spending credits, check the research log. If the same research ran within the last 30 days, reuse that result and say so instead of re-buying it.4. On finish, write back what is durable with `update_project_context` — an `addCompetitors` upsert for this domain with a short note on its strengths and where it is vulnerable — and append a research log entry: `{ appendResearchLog: { summary: "Competitor analysis: <domain>. Verdict: <conclusion>" } }`.+## Deliver as a report++Deliver through the `seo-report` skill, saving with `skill: "competitor-analysis"`. If that skill is not available, say so and stop before writing HTML.+## OpenSEO MCP tools- `get_domain_overview`: baseline organic traffic and keyword count.@@ -63,24 +67,17 @@ The project-context tools are free and shared with the app and other agents.## Output format-Start with:--- Competitor snapshot-- Biggest lesson-- Best opportunity to beat them--Then include:--| Area | Competitor pattern | Evidence | OpenSEO opportunity |-| ---- | ------------------ | -------- | ------------------- |+`h1`: the competitor domain.-Include sections for:+Sections in this order:-- Top keyword themes-- Content/page types working for them-- Backlink/authority notes-- Head-to-head SERP observations-- Priority actions for the user+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.+2. **The biggest lesson** — one finding.+3. **Where they are vulnerable** — one finding per opening, ordered by how winnable it is.+4. **Keyword themes** — a table of theme, example keywords, volume, and whether the user competes there. A bar chart when a few themes dominate the footprint.+5. **Content patterns and authority** — prose, with a note for anything inferred from keyword rows rather than seen on a page.+6. **What to do next** — an ordered list, shortest useful.+7. **Method** — which tools reported what, and what you checked yourself.## Guardrailsdiff --git a/.agents/skills/keyword-clustering/SKILL.md b/.agents/skills/keyword-clustering/SKILL.mdindex 84ac92b0..199d51d1 100644--- a/.agents/skills/keyword-clustering/SKILL.md+++ b/.agents/skills/keyword-clustering/SKILL.md@@ -26,6 +26,10 @@ The project-context tools are free and shared with the app and other agents.3. Before spending credits, check the research log. If the same research ran within the last 30 days, reuse that result and say so instead of re-buying it.4. On finish, write back what is durable with `update_project_context` — new or corrected `addKeyPages` entries with the topic each page now targets — and append a research log entry: `{ appendResearchLog: { summary: "Keyword clustering: <keyword set>. Verdict: <conclusion>" } }`.+## Deliver as a report++Deliver through the `seo-report` skill, saving with `skill: "keyword-clustering"`. If that skill is not available, say so and stop before writing HTML.+## OpenSEO MCP tools- `list_saved_keywords`: fetch an existing keyword set, optionally filtered by tags.@@ -57,25 +61,16 @@ The project-context tools are free and shared with the app and other agents.## Output format-Start with a short mapping summary:--- Number of clusters-- Pages to create-- Existing pages to update-- Cannibalization or consolidation issues--Then include:--| Cluster | Primary keyword | Secondary keywords | Intent | Target page | Priority | Notes |-| ------- | --------------- | ------------------ | ------ | ----------- | -------- | ----- |+`h1`: the site or keyword set.-For each cluster, include a recommended page brief:+Sections in this order:-- Page type-- Searcher problem-- Required sections-- Internal-link opportunities-- Save/tag suggestion+1. **The map** — one or two opening sentences: how many clusters, how many pages to create, how many to update, and any cannibalization found.+2. **Clusters** — a table of cluster, primary keyword, intent, target page, and priority. Keep secondary keywords in the per-cluster briefs, not in this table.+3. **Page briefs** — one finding per cluster: the page type and the searcher's problem, then the page to create or update. List required sections and internal links underneath.+4. **Cannibalization** — a table of the query, the competing URLs, and which one to keep, only when there is real evidence for it.+5. **What to do next** — an ordered list, including the tag suggestions and the explicit ask before applying them.+6. **Method** — where the keywords came from, and a note labelling target pages as proposed when no URL data was supplied.## Guardrailsdiff --git a/.agents/skills/keyword-research/SKILL.md b/.agents/skills/keyword-research/SKILL.mdindex 23918fc8..f65b5d48 100644--- a/.agents/skills/keyword-research/SKILL.md+++ b/.agents/skills/keyword-research/SKILL.md@@ -26,6 +26,10 @@ The project-context tools are free and shared with the app and other agents.3. Before spending credits, check the research log. If the same research ran within the last 30 days, reuse that result and say so instead of re-buying it.4. On finish, write back what is durable — a sharpened `business_overview` or `current_goal`, competitors that kept appearing in the SERPs via `addCompetitors`, pages the keywords should land on via `addKeyPages` — and append a research log entry: `{ appendResearchLog: { summary: "Keyword research: <seeds/market>. Verdict: <conclusion>" } }`.+## Deliver as a report++Deliver through the `seo-report` skill, saving with `skill: "keyword-research"`. If that skill is not available, say so and stop before writing HTML.+## OpenSEO MCP tools- `research_keywords`: primary discovery tool. Use 1-5 seeds per call and prefer 150 results unless the user asks for exhaustive research.@@ -58,19 +62,17 @@ The project-context tools are free and shared with the app and other agents.## Output format-Start with the highest-signal recommendation:--- Best opportunity theme-- Top keywords to target now-- Keywords to save-- Risks or SERP caveats--Then include a compact table:+`h1`: the site or topic.-| Keyword | Intent | Volume | KD | CPC | Priority | Notes |-| ------- | ------ | -----: | --: | --: | -------- | ----- |+Sections in this order:-End with next actions, including whether to run keyword clustering, create a content brief, or save the chosen keywords.+1. **The opportunity** — one or two opening sentences naming the best theme and why the site can win it now.+2. **Target these now** — a table of keyword, intent, volume, KD, CPC, and the page to make. Add a bar chart comparing the volumes of the shortlist.+3. **Why these** — one finding per keyword that needs justifying: the SERP or metric evidence, then the page to build.+4. **The longer opportunity list** — a second table, same columns.+5. **Risks and caveats** — notes: SERP intent that would change the recommendation, missing metrics written as `unknown`, close-variant volumes that are one bucket rather than several.+6. **What to do next** — an ordered list, including whether to run keyword clustering, write a content brief, or save the chosen keywords.+7. **Method** — which tools returned what.## Guardrailsdiff --git a/.agents/skills/link-prospecting/SKILL.md b/.agents/skills/link-prospecting/SKILL.mdindex 6858211c..463606e2 100644--- a/.agents/skills/link-prospecting/SKILL.md+++ b/.agents/skills/link-prospecting/SKILL.md@@ -26,6 +26,10 @@ The project-context tools are free and shared with the app and other agents.3. Before spending credits, check the research log. If the same research ran within the last 30 days, reuse that result and say so instead of re-buying it.4. On finish, write back what is durable — the linkable asset via `addKeyPages`, any competitor whose backlink profile proved useful via `addCompetitors` — and append a research log entry: `{ appendResearchLog: { summary: "Link prospecting: <asset/target page>. Verdict: <conclusion>" } }`.+## Deliver as a report++Deliver through the `seo-report` skill, saving with `skill: "link-prospecting"`. If that skill is not available, say so and stop before writing HTML.+## OpenSEO MCP tools- `get_serp_results`: find ranking articles, listicles, resource pages, comparisons, and topical publishers.@@ -90,22 +94,17 @@ Use `get_serp_results` in batches for the most relevant patterns. Send at most 1## Output format-Start with:--- Best outreach angle-- Highest-priority prospect type-- Any data limitations--Then include:--| Prospect URL | Site/domain | Source | Relevance | Suggested angle | Contact path | Priority |-| ------------ | ----------- | ------ | --------- | --------------- | ------------ | -------- |+`h1`: the linkable asset.-Then provide 2-3 reusable outreach drafts:+Sections in this order:-- Resource/list inclusion-- Article update/reference suggestion-- Competitor alternative/comparison angle+1. **The angle** — one or two opening sentences naming the best outreach angle and the prospect type to work first.+2. **Prospects** — a table of prospect URL, site, source, suggested angle, contact path, and priority. Keep it under about eight columns; drop the ones that add nothing for this run.+3. **Why these** — one finding per prospect worth explaining: the evidence that they link to things like this, then the exact ask.+4. **Outreach drafts** — the message text for each of two or three reusable angles: resource or list inclusion, an article update, and a comparison mention.+5. **Limitations** — notes: contact paths not found, prospects that are direct competitors or likely paid placements, and which source found each contact detail.+6. **What to do next** — an ordered list: who to send to first, and in what order.+7. **Method** — which tools returned prospects and which came from the web or the browser.## Guardrailsdiff --git a/.agents/skills/local-seo/SKILL.md b/.agents/skills/local-seo/SKILL.mdindex d74fae91..88e5f37d 100644--- a/.agents/skills/local-seo/SKILL.md+++ b/.agents/skills/local-seo/SKILL.md@@ -27,6 +27,10 @@ The project-context tools are free and shared with the app and other agents.3. Before spending credits, check the research log. If the same research ran within the last 30 days, reuse that result and say so instead of re-buying it.4. On finish, write back what is durable with `update_project_context` — local competitors that have a website via `addCompetitors` (competitor rows are keyed by domain, so skip listings without one), a corrected `business_overview` — and append a research log entry: `{ appendResearchLog: { summary: "Local SEO: <business> near <area>. Verdict: <conclusion>" } }`.+## Deliver as a report++Deliver through the `seo-report` skill, saving with `skill: "local-seo"`. If that skill is not available, say so and stop before writing HTML.+## OpenSEO MCP tools- `search_local_businesses`: nearby listings, filterable by `minRating`, `minReviews`, and `isClaimed` — use `isClaimed: false` to find unclaimed listings when prospecting. One call with the brand name as `query` and a wide radius returns category, rating, review count, claimed status, coordinates, and `cid` for every location of a chain — usually enough that per-location `get_business_profile` calls are unnecessary.@@ -58,18 +62,17 @@ Always build the profile snapshot table for the whole chain — one `search_loca## Output format-Start with:--- Profile snapshot (category, rating, reviews, claimed) — one row per location for chains-- Where visibility drops off, per the grid-- The one fix to do this week--Then include:+`h1`: the business name.-| Signal | This business | Best competitor | Gap | Action |-| ------ | ------------- | --------------- | --- | ------ |+Sections in this order:-Cover: categories, reviews (count, recency, owner replies), hours and profile completeness, listing website links, Maps coverage from the grid, Q&A and posting hygiene.+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.+2. **The one fix** — one finding. Category and claim problems outrank posting cadence every time.+3. **Head to head** — a table of signal, this business, the best competitor, and the gap. Cover categories, reviews (count, recency, owner replies), hours and profile completeness, and the listing's website link.+4. **Maps coverage** — what the grid shows, where visibility drops off, and who wins there. A bar chart of ranks by direction reads faster than a paragraph; label every value.+5. **Q&A and posting** — only when the basics are already competitive.+6. **What to do next** — an ordered list.+7. **Method** — which tools returned what, plus a note reading each missing grid rank against that point's `resultsCount` rather than calling it invisibility.## Guardrailsdiff --git a/.agents/skills/seo-audit/SKILL.md b/.agents/skills/seo-audit/SKILL.mdindex afe4a2ba..553d6ade 100644--- a/.agents/skills/seo-audit/SKILL.md+++ b/.agents/skills/seo-audit/SKILL.md@@ -25,6 +25,10 @@ The project-context tools are free and shared with the app and other agents.3. Before spending credits, check the research log. If the same research ran within the last 30 days, reuse that result and say so instead of re-buying it.4. On finish, write back what is durable — a corrected `business_overview`, the pages the report singles out via `addKeyPages` — and append a research log entry: `{ appendResearchLog: { summary: "Site audit: <domain>. Verdict: <conclusion>" } }`.+## Deliver as a report++Deliver through the `seo-report` skill, saving with `skill: "seo-audit"`. If that skill is not available, say so and stop before writing HTML.+## OpenSEO MCP tools- `whoami`: confirm connection and remaining credits before spending anything. If OpenSEO is not connected, stop and ask the user to connect it.@@ -49,18 +53,24 @@ Keep total spend modest: one audit, one backlinks overview, at most one domain o- Blocked or noindexed pages: remove the block.It must be doable this week by a non-technical person, with copy-paste-ready mechanics included.7. When the site is healthy, propose a starting focus area: run one `research_keywords` call seeded from the site's actual topic, then pick one theme and 3 to 5 specific, low-difficulty keywords the site can realistically rank for, each with the page or post to make. This is a starting direction, not a keyword strategy; point the user at the `keyword-research` skill for the full workflow. Skip this step entirely when the site is down — the one thing is all that matters there.-8. Write the report using `template.html` in this skill directory (see Output format).-9. Review before delivering: run an adversarial pass with a second agent or model if your environment has one, otherwise do a fresh self-review. Give the reviewer the verified facts and have it attack four things: claims beyond the facts, unglossed jargon, anything overwhelming for a beginner, and dramatic language. The reviewer may also flag true facts it was not given; check those against your evidence instead of "fixing" them.-10. Deliver the report: if your environment can publish or preview HTML (for example as an artifact), do that; otherwise save the HTML file and tell the user to open it in their browser.+8. Review before delivering: run an adversarial pass with a second agent or model if your environment has one, otherwise do a fresh self-review. Give the reviewer the verified facts and have it attack four things: claims beyond the facts, unglossed jargon, anything overwhelming for a beginner, and dramatic language. The reviewer may also flag true facts it was not given; check those against your evidence instead of "fixing" them.+9. Write and save the report through the `seo-report` skill (see Output format).## Output format-Use `template.html` next to this file. Fill in content; keep the CSS and structure as they are (light palette only, no dark mode).+`h1`: the domain. Then one or two opening sentences: the overall state and the one thing.++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.+2. **Top priority** — one finding, with copy-paste-ready mechanics.+3. **Small fixes** — one finding each, 5 to 10 max, ordered by impact. Each shows the exact evidence: a quoted tag, a number, or a URL.+4. **Where to focus first** (healthy sites only) — one sentence, then a table of 3 to 5 keywords with volume and difficulty and the page or post to make for each, plus a bar chart when the volumes are worth comparing. Omit the whole section when the site is down.+5. **What's working now** — a short list.+6. **What to do next** — an ordered list, the one thing first.+7. **Method** — what the tools reported and what you verified by hand.-- Header: domain as the title, the review date on its own line under it, then a 2-3 sentence summary of the whole report (overall state; the main gap and the one thing; what the report covers).-- Section order: verdict, the one thing, small fixes (5 to 10 max, ordered by impact), where to focus first (healthy sites only), already working, method footer.-- Each fix row shows the exact evidence (a quoted tag or number) and concrete steps a non-technical person can follow.-- "Where to focus first" names one topic area and 3 to 5 keywords, each with its search volume in plain words and the page or post to make. Omit the section when the site is down.+Use a note for anything you could not verify or where the site's goal makes a standard recommendation the wrong call.## Guardrailsdiff --git a/.agents/skills/seo-audit/template.html b/.agents/skills/seo-audit/template.htmldeleted file mode 100644index 933e897d..00000000--- a/.agents/skills/seo-audit/template.html+++ /dev/null@@ -1,136 +0,0 @@-<!-- SEO audit report template.- Replace ALL-CAPS placeholders and the example rows/items. Keep the CSS and structure.- If your agent publishes HTML through a pipeline that adds its own document wrapper- (for example an artifact viewer), strip this comment and the doctype/head/body tags;- as a standalone file opened in a browser, keep everything. -->-<!doctype html>-<html lang="en">-<head>-<meta charset="utf-8">-<meta name="viewport" content="width=device-width, initial-scale=1">-<title>DOMAIN SEO review</title>-<style>- :root {- --bg: #e2e9f3;- --ink: #122650;- --muted: #4f5f79;- --rule: #c2cddd;- --rule-strong: #122650;- }- html { background: var(--bg); color-scheme: light; }- body {- background: var(--bg); color: var(--ink);- font-family: Charter, Georgia, "Times New Roman", serif;- line-height: 1.55; margin: 0; padding: 3.5rem 1.5rem 5rem;- }- .page { max-width: 860px; margin: 0 auto; }- .mono {- font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;- font-size: 0.72rem; letter-spacing: 0.06em; text-transform: uppercase; color: var(--muted);- }- h1 {- font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;- font-weight: 700; font-size: 1.6rem; letter-spacing: -0.01em;- margin: 0.75rem 0 0.25rem; text-wrap: balance;- }- .subtitle { color: var(--muted); margin: 0 0 2.5rem; font-size: 1.02rem; max-width: 46rem; }- .dateline { color: var(--muted); font-size: 0.92rem; margin: 0 0 1.1rem; }- h2 {- font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;- font-weight: 700; font-size: 1.25rem; margin: 3rem 0 0.75rem;- }- .lede { font-size: 1.05rem; max-width: 46rem; }- section > p { max-width: 46rem; }- hr.heavy { border: 0; border-top: 2px solid var(--rule-strong); margin: 3rem 0 0; }- section .cols:first-of-type { border-top: 1px solid var(--rule); }- .cols {- display: grid; grid-template-columns: minmax(180px, 5fr) 8fr;- gap: 1.25rem; padding: 0.6rem 0; border-bottom: 1px solid var(--rule);- }- .row-title { font-size: 1.12rem; margin: 0; }- .row-title .tag { display: block; margin-top: 0.35rem; }- .cols > div p { margin: 0 0 0.6rem; color: var(--muted); font-size: 0.95rem; }- .cols > div p:last-child { margin-bottom: 0; }- .cols > div p.fix { color: var(--ink); }- .fix b { font-weight: 600; }- code {- font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;- font-size: 0.85em; word-break: break-word;- }- ol { padding-left: 1.3rem; max-width: 44rem; }- ol li { margin-bottom: 0.5rem; }- ul.plain { list-style: none; padding: 0; max-width: 46rem; }- ul.plain li { padding: 0.5rem 0; border-bottom: 1px solid var(--rule); font-size: 0.98rem; }- ul.plain li:first-child { border-top: 1px solid var(--rule); }- ul.plain .why { color: var(--muted); }- footer { margin-top: 4rem; color: var(--muted); font-size: 0.88rem; max-width: 46rem; }- @media (max-width: 620px) {- .cols { grid-template-columns: 1fr; gap: 0.4rem; }- }-</style>-</head>-<body>-<div class="page">- <header>- <h1>DOMAIN</h1>- <p class="dateline">DATE</p>- <p class="subtitle">SUMMARY: 2-3 sentences covering the whole report. Sentence 1: overall state of the site. Sentence 2: the main gap and the one thing. Sentence 3: what the report covers.</p>- </header>-- <section>- <h2>Where the site stands</h2>- <p class="lede">VERDICT-PARAGRAPH: what is working, in plain words.</p>- <p class="lede">VERDICT-PARAGRAPH-2: the main gap the one thing addresses.</p>- </section>-- <hr class="heavy">-- <section>- <h2>If you only do one thing</h2>- <p class="lede">THE-ONE-THING, one sentence.</p>- <p>WHY-IT-MATTERS, one or two sentences.</p>- <ol>- <li>STEP-1 (concrete, doable today).</li>- <li>STEP-2 (include any copy-paste message in <i>italics</i>).</li>- <li>STEP-3 (how to check it worked).</li>- </ol>- </section>-- <section>- <h2>Small fixes, in order</h2>- <!-- one .cols block per finding; 5-10 max; tag = severity word only where literally true -->- <div class="cols">- <div><p class="row-title">FINDING-TITLE <span class="mono tag">low</span></p></div>- <div>- <p>WHAT-WE-FOUND with the exact evidence, e.g. a quoted tag in <code>code</code>.</p>- <p class="fix"><b>Fix:</b> CONCRETE-STEPS a non-technical person can follow.</p>- </div>- </div>- </section>-- <section>- <h2>Where to focus first</h2>- <!-- healthy sites only: omit this whole section when the site is down -->- <p>FOCUS-INTRO: the one topic area to build toward and why it fits this site.</p>- <div class="cols">- <div><p class="row-title">KEYWORD <span class="mono tag">N searches/mo</span></p></div>- <div>- <p>WHY-THIS-KEYWORD: who searches it and how winnable it is, in plain words.</p>- <p class="fix"><b>Make:</b> WHAT-TO-CREATE, one page or post and its angle.</p>- </div>- </div>- </section>-- <section>- <h2>Already working</h2>- <ul class="plain">- <li>GOOD-THING. <span class="why">Why it matters, one clause.</span></li>- </ul>- </section>-- <footer>- <p>Reviewed DATE. DATA-SOURCES, e.g.: crawl and backlink data from OpenSEO; every page also fetched and reviewed individually.</p>- </footer>-</div>-</body>-</html>diff --git a/.agents/skills/seo-coach/SKILL.md b/.agents/skills/seo-coach/SKILL.mdindex 0da5cf8a..7f32639d 100644--- a/.agents/skills/seo-coach/SKILL.md+++ b/.agents/skills/seo-coach/SKILL.md@@ -55,6 +55,7 @@ Good starting points:- `competitor-analysis`: studies one competitor's keywords, content themes, backlink profile, and gaps.- `local-seo`: audits a Google Business Profile against local competitors and maps Maps visibility around a location.- `link-prospecting`: finds likely link opportunities, discovers contact paths, and drafts outreach.+- `seo-report`: the report-writing skill the workflows above deliver through. It carries the starter template and the save rules; users do not run it on its own.## Tool coaching@@ -64,8 +65,9 @@ Explain the difference between data sources:- Google Search Console (when connected on the project's Integrations page) is the user's own first-party data — real clicks, impressions, CTR, and position. Read it live with `get_search_console_performance` instead of asking for CSV exports. It's free (no credits) and the best starting point for "what already ranks" and near-ranking opportunities.- Web search can find current market context, recent pages, reviews, docs, social profiles, and contact paths outside OpenSEO.- Browser/page scraping can extract page copy, headings, author names, contact links, schema, and content structure.-- Project context (`get_project_context` / `update_project_context`) is the project's shared memory: business, goal, positioning, writing preferences, competitors, key pages, and a research log. It is free, every skill reads it, and the user can edit it on the project's Context settings page.-- Local files are for file work: GSC CSVs, crawls, drafts, briefs, and reports.+- Project context (`get_project_context` / `update_project_context`) is the project's shared memory: business, goal, positioning, writing preferences, competitors, key pages, and a research log. It is free, every skill reads it, and the user can edit it on the project's Context page (in the sidebar under AI).+- Local files are for file work: GSC CSVs, crawls, and drafts.+- Reports are where finished work lives: each workflow saves its deliverable to the project's Reports page as an HTML page anyone on the team can open and print. Before starting a workflow, call `list_reports` to see what already exists and point the user at it instead of re-running research they already paid for.Encourage the user to keep project knowledge in project context rather than in a local file, so it follows them across sessions and agents.diff --git a/.agents/skills/seo-project-setup/SKILL.md b/.agents/skills/seo-project-setup/SKILL.mdindex ce623924..8ef9b34a 100644--- a/.agents/skills/seo-project-setup/SKILL.md+++ b/.agents/skills/seo-project-setup/SKILL.md@@ -7,7 +7,7 @@ description: Populate a project's shared OpenSEO context — site scope, goals,## Goal-Interview the user once about one website or SEO project, and store the answers in that project's shared context in OpenSEO with `update_project_context`. That context is read by every other skill, by SAM in the app, and by the user on the project's Context settings page — so it survives new sessions, new machines, and new agents. This is a context setup workflow, not a full audit.+Interview the user once about one website or SEO project, and store the answers in that project's shared context in OpenSEO with `update_project_context`. That context is read by every other skill, by SAM in the app, and by the user on the project's Context page (in the sidebar under AI) — so it survives new sessions, new machines, and new agents. This is a context setup workflow, not a full audit.## Tone@@ -183,7 +183,7 @@ Then summarize:- Sections still missing from project context- Recommended next workflow-Tell the user they can read and edit everything saved here on the project's Context settings page.+Tell the user they can read and edit everything saved here on the project's Context page, in the sidebar under AI.## Guardrailsdiff --git a/.agents/skills/seo-report/SKILL.md b/.agents/skills/seo-report/SKILL.mdnew file mode 100644index 00000000..698a9fc1--- /dev/null+++ b/.agents/skills/seo-report/SKILL.md@@ -0,0 +1,221 @@+---+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."+---++# OpenSEO Report++## Goal++Turn finished research into one self-contained HTML page, saved to the project with `save_report`, so anyone on the team can open it in the app, read it on a phone, and print it to PDF.++Every OpenSEO skill that produces a recommendation delivers through this skill. Chat gets the link, the verdict, and the top action. The report gets everything else.++## Before you write++1. Call `list_reports` for the project. If a report already covers the same subject for the same period, you are correcting your own run: pass its `reportId` to `save_report` and replace it. A new month, a new competitor, or a different skill is a new report. Never save a near-duplicate.+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.++## 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.+- **Be specific and numeric.** "Position 4.6, one click on 1,085 impressions" beats "underperforming". Every claim carries the number, the quoted tag, or the URL that proves it.+- **Be honest about confidence.** Say which numbers came from a tool and which you verified yourself. When you could not check something, put it in a `.note` and say so.+- **Plain language.** Gloss every term of art on first use: canonical, meta description, crawler, 301, structured data. No drama words, no exclamation points, no filler.+- **One report, one spine.** Lead with the verdict, then the single most important action, then the supporting detail. A report with twenty findings has failed.+- **Print the numbers.** A chart never carries a value that is not also written out in text.++## Title and summary++- `title`: names the subject and the period, under 120 characters. "badseo.dev SEO audit, Sep 2026". Never "SEO Report" or "Analysis".+- `summary`: markdown under 2,500 characters, in this order — the verdict, the single top action, then the key numbers. This is what `list_reports` returns and what you or another agent read instead of the HTML, so write it for a reader who will never open the page.++## HTML constraints++These are enforced by the viewer, not by taste. A report that breaks them renders blank or broken.++- **No external resources of any kind.** No web fonts, no CDN scripts or stylesheets, no images by URL, no `fetch`. Every request from a saved report is blocked. Inline all CSS in one `<style>` block.+- **Links open in a new tab.** Write every link as `<a href="..." target="_blank" rel="noopener">`. A plain link would navigate the report frame itself, replacing the report with a broken copy of the target. The exception is an in-page anchor (`href="#id"`, as in the contents rail), which stays in the document.+- **No `<script>`.** Scripts are blocked outright. Anything interactive has to be static.+- **Charts are inline SVG or CSS bars**, with real `<text>` labels and a `viewBox`. Always print the numbers next to the chart too.+- **Aim under 80 KB.** The hard cap is 500,000 bytes, and the error says "the limit is 500 KB". Inlined images are the usual way people blow it. A filled report is normally 10-30 KB.+- **No backticks and no `${` anywhere in the HTML.** Codex passes the argument through a JavaScript template literal, where both are syntax. Use `<code>` for inline code and plain text everywhere else.+- **Finish the document.** The server rejects HTML that does not end with `</html>` as "stopped early". Write the whole page in one call rather than trailing off mid-section.+- **Keep the doctype, `<html>`, `<head>`, and `<title>`.** The app renders the whole document you save, not a fragment.++## After you save++- `save_report` returns `{ reportId, url, htmlBytes }`. The whole reply is at most three short bullets, then the link last on its own line as `Read the full report: <url>`. The bullets: the verdict, the top action, and anything the user has to act on (a project you created, a question you need answered). Nothing else: no account of the run, no reviewer notes, no list of what worked, no restating the report. The report is how they learn; chat only points at it.+- The skill you are running appends its own research-log line; add one only if it does not: `{ appendResearchLog: { summary: "Report: <title>. Verdict: <conclusion>" } }`.+- If the save fails, the error names the limit and the value. Fix that one thing and save again. Never paste the report into chat instead.++## Starter template++Copy this, keep the CSS as it is, and replace the ALL-CAPS placeholders. Each primitive shows one example row; repeat the ones you need and delete the ones you do not.++```html+<!doctype html>+<html lang="en"><head><meta charset="utf-8">+<meta name="viewport" content="width=device-width,initial-scale=1">+<title>DOMAIN — REPORT TITLE</title>+<style>+/* One light look, on screen and on paper. The report is read inside the app,+ which has its own theme toggle, and a saved document has no way to hear about+ it: a report that follows the OS scheme alone shows a black panel inside a+ light 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}+*{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;+ font-family:Geist,-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;-webkit-font-smoothing:antialiased}+.shell{max-width:1100px;margin:0 auto}+header{padding:40px 0 0;max-width:660px}+h1{font-size:clamp(34px,6vw,56px);font-weight:700;line-height:1.03;letter-spacing:-.035em;margin:0;text-wrap:balance}+.byline{margin:24px 0 0;font-size:16px;color:var(--fg-2)}+.body{display:grid;grid-template-columns:minmax(0,660px) 1fr;gap:0 64px;margin:48px 0 0}+/* Both explicitly in row 1: without it the rail auto-places into row 1 and+ pushes the article down a whole row, opening an empty band above the text. */+article{grid-column:1;grid-row:1;min-width:0}+.rail{grid-column:2;grid-row:1;font-size:14px;color:var(--fg-3);padding-top:6px}+.rail .sticky{position:sticky;top:40px}+.toc-label{font-size:12px;letter-spacing:.08em;text-transform:uppercase;color:var(--fg-3);margin:0 0 10px}+.toc ol{list-style:none;margin:0;padding:0}+.toc li{margin:0 0 7px}+.toc a{color:var(--fg-2);text-decoration:none}+.toc a:hover{color:var(--fg)}+/* Below 900px the rail is dropped rather than stacked: a contents list above+ the report is a wall to scroll past on a phone, not a shortcut. */+@media (max-width:900px){.body{grid-template-columns:1fr}.rail{display:none}}+article p{margin:0 0 26px;text-wrap:pretty}+h2{font-size:30px;font-weight:600;letter-spacing:-.025em;line-height:1.2;margin:60px 0 22px;text-wrap:balance}+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}+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}+ul,ol{margin:0 0 26px;padding-left:22px}li{margin:0 0 11px}li::marker{color:var(--fg-3)}+.note{border-left:2px solid var(--fg);padding:2px 0 2px 22px;margin:0 0 26px}+.note p{margin:0;color:var(--fg-2)}+.note p+p{margin-top:14px}+.tw{overflow-x:auto;margin:0 0 30px}+table{border-collapse:collapse;width:100%;font-size:15.5px;min-width:440px}+th{text-align:left;font-weight:500;color:var(--fg-3);padding:0 20px 10px 0;border-bottom:1px solid var(--rule-2);white-space:nowrap}+td{padding:13px 20px 13px 0;border-bottom:1px solid var(--rule);vertical-align:top;color:var(--fg-2)}+td:first-child{color:var(--fg)}+td.n,th.n{text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap}+td:last-child,th:last-child{padding-right:0}+tr:last-child td{border-bottom:none}+figure{margin:0 0 30px}+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 .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}+footer{max-width:660px;margin:64px 0 0;padding:26px 0 0;border-top:1px solid var(--rule);font-size:15px;color:var(--fg-3)}+@media print{+ /* A zero top margin hides the browser's own print header (date, tab title);+ the bottom margin holds a page counter instead of the browser's URL line.+ The body padding supplies the visible page margins. */+ @page{margin:0 0 12mm 0;@bottom-center{content:counter(page) " of " counter(pages);font:10px -apple-system,BlinkMacSystemFont,Helvetica,Arial,sans-serif;color:#8f8f8f}}+ body{background:#fff;color:#111;padding:14mm 16mm 6mm;font-size:11pt}+ .shell,.body{display:block;max-width:none}+ header{padding:0;max-width:none}+ h1{font-size:26pt}+ h2{font-size:15pt;margin:22pt 0 10pt}+ h3{font-size:12pt;margin:14pt 0 6pt}+ article,footer{max-width:none}+ .rail{display:none}+ h1,h2,h3{break-after:avoid}+ table,figure,.note,svg{break-inside:avoid}+ tr,td,th{break-inside:avoid}+ p,li{orphans:3;widows:3}+ thead{display:table-header-group}+ .tw{overflow:visible}+ table{font-size:10pt;min-width:0}+ .byline,footer,figcaption{font-size:9.5pt}+ svg,.bars .bar,.bars .track{-webkit-print-color-adjust:exact;print-color-adjust:exact}+ a{text-decoration:none}+}+</style></head>+<body><div class="shell">++<header>+ <h1>REPORT TITLE</h1>+ <p class="byline">Prepared for NAME · MONTH D, YYYY</p>+</header>++<div class="body">+ <aside class="rail"><div class="sticky">+ <p class="toc-label">Contents</p>+ <nav class="toc" aria-label="Contents">+ <ol>+ <li><a href="#section-heading">SECTION HEADING</a></li>+ <li><a href="#what-to-do-next">What to do next</a></li>+ </ol>+ </nav>+ </div></aside>+ <article>++ <p>One or two sentences: the state of things and the one action.</p>++ <h2 id="section-heading">SECTION HEADING</h2>++ <h3>FINDING TITLE</h3>+ <ul class="finding">+ <li><b>Status:</b> what is true, with the number or the quoted tag that proves it.</li>+ <li><b>Fix:</b> the concrete step, doable this week by a non-technical person.</li>+ </ul>++ <div class="note"><p>A caveat, a confidence note, or something you could not verify.</p></div>++ <div class="tw">+ <table>+ <thead><tr><th>Item</th><th class="n">Volume</th><th class="n">Difficulty</th></tr></thead>+ <tbody><tr><td>example keyword</td><td class="n">1,300</td><td class="n">4</td></tr></tbody>+ </table>+ </div>++ <figure>+ <div class="bars" role="img" aria-label="Monthly volume: alpha 1,300, beta 590">+ <span class="label">alpha</span><span class="track"><span class="bar" style="width:100%"></span></span><span class="value">1,300</span>+ <span class="label">beta</span><span class="track"><span class="bar" style="width:45%"></span></span><span class="value">590</span>+ </div>+ <figcaption>One row per item; the widest bar is 100% and the rest are scaled to it.</figcaption>+ </figure>++ <hr>+ <h2 id="what-to-do-next">What to do next</h2>+ <ol><li>The top priority, first.</li></ol>++ </article>+</div>++<footer>What the tools reported, and what was verified by hand.</footer>+</div></body></html>+```++## The primitives++- **Header** — `h1` (the report title) and `.byline` (who it is for and the date): "Prepared for badseo.dev · September 3, 2026".+- **`.rail` contents** — the table of contents, sticky to the right of the text on a wide screen, dropped on a phone and in print. Every `h2` has an id, and the contents list links to each one with a plain `href="#id"` — in-page anchors are the one kind of link that must **not** use `target="_blank"`. Ids are the kebab-case of the heading text.+- **`h2` / `h3`** — `h2` opens a section, `h3` names one finding. Do not skip levels.+- **Finding** — `h3`, then a `.finding` list: `<li><b>Status:</b> …</li>`, `<li><b>Fix:</b> …</li>`, and `<li><b>Why:</b> …</li>` only when the reason is not obvious. Each bullet is one or two sentences. This is the workhorse; most of a report is a run of these.+- **`.note`** — one left-ruled callout for a caveat, a confidence limit, or something you could not verify. Two or three in a report, never a row of them.+- **`.tw` table** — every numeric column gets `class="n"` on both the `th` and the `td` so the digits line up. Keep tables to five columns or fewer, put the long-text column last, and keep cell text short; a wide table scrolls on a phone and clips in print.+- **`figure` + `.bars`** — one small bar chart where a comparison reads faster than a sentence. One row per item: `.label`, a `.track` holding a `.bar` whose inline width is the value as a percentage of the largest, and `.value`. Inline SVG is fine for anything that is not a bar chart; give it a `viewBox` and real `<text>` labels.+- **`hr` then a closing `h2`** — the "What to do next" list, ordered, shortest useful.+- **`footer`** — what the tools reported and what you verified by hand.++## 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 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/CLAUDE.md b/CLAUDE.mdindex 14df5841..a0f27fca 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -11,6 +11,7 @@- Use idiomatic TypeScript. Use Zod to validate untrusted data and narrow runtime values at trust boundaries.- Prefer established project helpers and libraries over hand-rolled implementations.- Prefer idiomatic TanStack Query, Router, and Form patterns for server state, routing, and submitted forms.+- Specs under `specs/` are public design records: what a feature does, how it works, the alternatives considered and why they lost. No line numbers, migration mechanics, test plans, incidents, costs, or internal infrastructure details.## Testingdiff --git a/drizzle-pg/0025_reports.sql b/drizzle-pg/0025_reports.sqlnew file mode 100644index 00000000..ec152725--- /dev/null+++ b/drizzle-pg/0025_reports.sql@@ -0,0 +1,34 @@+CREATE TABLE "reports" (+ "id" text PRIMARY KEY NOT NULL,+ "project_id" text NOT NULL,+ "title" text NOT NULL,+ "summary" text NOT NULL,+ "html" text NOT NULL,+ "skill" text,+ "template_id" text,+ "created_by" text NOT NULL,+ "created_by_user_id" text NOT NULL,+ "size_bytes" integer NOT NULL,+ "share_token" text,+ "shared_at" text,+ "created_at" text DEFAULT to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') NOT NULL,+ "updated_at" text DEFAULT to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') NOT NULL+);+--> statement-breakpoint+CREATE TABLE "report_templates" (+ "id" text PRIMARY KEY NOT NULL,+ "project_id" text NOT NULL,+ "name" text NOT NULL,+ "description" text NOT NULL,+ "instructions" text NOT NULL,+ "created_by" text NOT NULL,+ "created_by_user_id" text NOT NULL,+ "created_at" text DEFAULT to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') NOT NULL,+ "updated_at" text DEFAULT to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') NOT NULL+);+--> statement-breakpoint+ALTER TABLE "reports" ADD CONSTRAINT "reports_project_id_projects_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."projects"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "report_templates" ADD CONSTRAINT "report_templates_project_id_projects_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."projects"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+CREATE INDEX "reports_project_updated_idx" ON "reports" USING btree ("project_id","updated_at","id","size_bytes");--> statement-breakpoint+CREATE UNIQUE INDEX "reports_share_token_idx" ON "reports" USING btree ("share_token");--> statement-breakpoint+CREATE UNIQUE INDEX "report_templates_project_name_idx" ON "report_templates" USING btree ("project_id","name");\ No newline at end of filediff --git a/drizzle-pg/meta/0025_snapshot.json b/drizzle-pg/meta/0025_snapshot.jsonnew file mode 100644index 00000000..122b6be0--- /dev/null+++ b/drizzle-pg/meta/0025_snapshot.json@@ -0,0 +1,4477 @@+{+ "id": "044a60be-0f23-487e-9c88-660fafb28e1d",+ "prevId": "a4f3d0e2-89b0-47ac-80d5-88c5f850523b",+ "version": "7",+ "dialect": "postgresql",+ "tables": {+ "public.backlink_snapshots": {+ "name": "backlink_snapshots",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "domain": {+ "name": "domain",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "rank": {+ "name": "rank",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "backlinks": {+ "name": "backlinks",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "referring_domains": {+ "name": "referring_domains",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "broken_backlinks": {+ "name": "broken_backlinks",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "new_backlinks": {+ "name": "new_backlinks",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "lost_backlinks": {+ "name": "lost_backlinks",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "new_referring_domains": {+ "name": "new_referring_domains",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "lost_referring_domains": {+ "name": "lost_referring_domains",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "captured_at": {+ "name": "captured_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "backlink_snapshots_project_captured_idx": {+ "name": "backlink_snapshots_project_captured_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "captured_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "backlink_snapshots_project_id_projects_id_fk": {+ "name": "backlink_snapshots_project_id_projects_id_fk",+ "tableFrom": "backlink_snapshots",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.dashboard_step_dismissals": {+ "name": "dashboard_step_dismissals",+ "schema": "",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "step": {+ "name": "step",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "dashboard_step_dismissals_project_idx": {+ "name": "dashboard_step_dismissals_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "dashboard_step_dismissals_user_id_user_id_fk": {+ "name": "dashboard_step_dismissals_user_id_user_id_fk",+ "tableFrom": "dashboard_step_dismissals",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "dashboard_step_dismissals_project_id_projects_id_fk": {+ "name": "dashboard_step_dismissals_project_id_projects_id_fk",+ "tableFrom": "dashboard_step_dismissals",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "dashboard_step_dismissals_user_id_project_id_step_pk": {+ "name": "dashboard_step_dismissals_user_id_project_id_step_pk",+ "columns": [+ "user_id",+ "project_id",+ "step"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.keyword_metrics": {+ "name": "keyword_metrics",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "keyword": {+ "name": "keyword",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "location_code": {+ "name": "location_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "language_code": {+ "name": "language_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'en'"+ },+ "search_volume": {+ "name": "search_volume",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "cpc": {+ "name": "cpc",+ "type": "real",+ "primaryKey": false,+ "notNull": false+ },+ "competition": {+ "name": "competition",+ "type": "real",+ "primaryKey": false,+ "notNull": false+ },+ "keyword_difficulty": {+ "name": "keyword_difficulty",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "intent": {+ "name": "intent",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "monthly_searches": {+ "name": "monthly_searches",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "fetched_at": {+ "name": "fetched_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "keyword_metrics_unique_project_keyword_location_language": {+ "name": "keyword_metrics_unique_project_keyword_location_language",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "keyword",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "location_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "language_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "keyword_metrics_lookup_idx": {+ "name": "keyword_metrics_lookup_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "keyword",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "location_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "language_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "fetched_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "keyword_metrics_project_id_projects_id_fk": {+ "name": "keyword_metrics_project_id_projects_id_fk",+ "tableFrom": "keyword_metrics",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.organization_activation_state": {+ "name": "organization_activation_state",+ "schema": "",+ "columns": {+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "first_mcp_authorized_at": {+ "name": "first_mcp_authorized_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "first_mcp_tool_call_at": {+ "name": "first_mcp_tool_call_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "organization_activation_state_organization_id_organization_id_fk": {+ "name": "organization_activation_state_organization_id_organization_id_fk",+ "tableFrom": "organization_activation_state",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_activation_state": {+ "name": "project_activation_state",+ "schema": "",+ "columns": {+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "competitor_step_clicked_at": {+ "name": "competitor_step_clicked_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "mcp_card_dismissed_at": {+ "name": "mcp_card_dismissed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "ga4_card_dismissed_at": {+ "name": "ga4_card_dismissed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "project_activation_state_project_id_projects_id_fk": {+ "name": "project_activation_state_project_id_projects_id_fk",+ "tableFrom": "project_activation_state",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.projects": {+ "name": "projects",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "domain": {+ "name": "domain",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "location_code": {+ "name": "location_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 2840+ },+ "language_code": {+ "name": "language_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'en'"+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "archived_at": {+ "name": "archived_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "projects_one_default_per_organization_idx": {+ "name": "projects_one_default_per_organization_idx",+ "columns": [+ {+ "expression": "organization_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"projects\".\"name\" = 'Default' AND \"projects\".\"domain\" IS NULL AND \"projects\".\"archived_at\" IS NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "projects_organization_id_idx": {+ "name": "projects_organization_id_idx",+ "columns": [+ {+ "expression": "organization_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "projects_organization_id_organization_id_fk": {+ "name": "projects_organization_id_organization_id_fk",+ "tableFrom": "projects",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.rank_check_runs": {+ "name": "rank_check_runs",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "config_id": {+ "name": "config_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "keywords_total": {+ "name": "keywords_total",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "keywords_checked": {+ "name": "keywords_checked",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "is_subset_run": {+ "name": "is_subset_run",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "error_message": {+ "name": "error_message",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "started_at": {+ "name": "started_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "completed_at": {+ "name": "completed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "rank_check_runs_config_idx": {+ "name": "rank_check_runs_config_idx",+ "columns": [+ {+ "expression": "config_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "started_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "rank_check_runs_project_idx": {+ "name": "rank_check_runs_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "started_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "rank_check_runs_one_active_per_config_idx": {+ "name": "rank_check_runs_one_active_per_config_idx",+ "columns": [+ {+ "expression": "config_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"rank_check_runs\".\"status\" IN ('pending', 'running')",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "rank_check_runs_config_id_rank_tracking_configs_id_fk": {+ "name": "rank_check_runs_config_id_rank_tracking_configs_id_fk",+ "tableFrom": "rank_check_runs",+ "tableTo": "rank_tracking_configs",+ "columnsFrom": [+ "config_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "rank_check_runs_project_id_projects_id_fk": {+ "name": "rank_check_runs_project_id_projects_id_fk",+ "tableFrom": "rank_check_runs",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.rank_snapshots": {+ "name": "rank_snapshots",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "run_id": {+ "name": "run_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "tracking_keyword_id": {+ "name": "tracking_keyword_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "keyword": {+ "name": "keyword",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "device": {+ "name": "device",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "serp_features": {+ "name": "serp_features",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "checked_at": {+ "name": "checked_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "rank_snapshots_keyword_device_idx": {+ "name": "rank_snapshots_keyword_device_idx",+ "columns": [+ {+ "expression": "tracking_keyword_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "device",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "checked_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "rank_snapshots_run_keyword_device_idx": {+ "name": "rank_snapshots_run_keyword_device_idx",+ "columns": [+ {+ "expression": "run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "tracking_keyword_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "device",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "rank_snapshots_run_id_rank_check_runs_id_fk": {+ "name": "rank_snapshots_run_id_rank_check_runs_id_fk",+ "tableFrom": "rank_snapshots",+ "tableTo": "rank_check_runs",+ "columnsFrom": [+ "run_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.rank_tracking_configs": {+ "name": "rank_tracking_configs",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "domain": {+ "name": "domain",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "location_code": {+ "name": "location_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 2840+ },+ "language_code": {+ "name": "language_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'en'"+ },+ "devices": {+ "name": "devices",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'both'"+ },+ "serp_depth": {+ "name": "serp_depth",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "schedule_interval": {+ "name": "schedule_interval",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'weekly'"+ },+ "location_name": {+ "name": "location_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "is_active": {+ "name": "is_active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "last_checked_at": {+ "name": "last_checked_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "next_check_at": {+ "name": "next_check_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "last_skip_reason": {+ "name": "last_skip_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "rank_tracking_configs_project_active_created_idx": {+ "name": "rank_tracking_configs_project_active_created_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "is_active",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "rank_tracking_configs_national_idx": {+ "name": "rank_tracking_configs_national_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "domain",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "location_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"rank_tracking_configs\".\"location_name\" IS NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "rank_tracking_configs_local_idx": {+ "name": "rank_tracking_configs_local_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "domain",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "location_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "location_name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"rank_tracking_configs\".\"location_name\" IS NOT NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "rank_tracking_configs_project_id_projects_id_fk": {+ "name": "rank_tracking_configs_project_id_projects_id_fk",+ "tableFrom": "rank_tracking_configs",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.rank_tracking_keywords": {+ "name": "rank_tracking_keywords",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "config_id": {+ "name": "config_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "keyword": {+ "name": "keyword",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "match_case": {+ "name": "match_case",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "search_volume": {+ "name": "search_volume",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "keyword_difficulty": {+ "name": "keyword_difficulty",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "cpc": {+ "name": "cpc",+ "type": "real",+ "primaryKey": false,+ "notNull": false+ },+ "metrics_fetched_at": {+ "name": "metrics_fetched_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "rank_tracking_keywords_config_keyword_idx": {+ "name": "rank_tracking_keywords_config_keyword_idx",+ "columns": [+ {+ "expression": "config_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "keyword",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "rank_tracking_keywords_config_id_rank_tracking_configs_id_fk": {+ "name": "rank_tracking_keywords_config_id_rank_tracking_configs_id_fk",+ "tableFrom": "rank_tracking_keywords",+ "tableTo": "rank_tracking_configs",+ "columnsFrom": [+ "config_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.saved_keyword_tag_assignments": {+ "name": "saved_keyword_tag_assignments",+ "schema": "",+ "columns": {+ "saved_keyword_id": {+ "name": "saved_keyword_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "tag_id": {+ "name": "tag_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "saved_keyword_tag_assignments_unique_idx": {+ "name": "saved_keyword_tag_assignments_unique_idx",+ "columns": [+ {+ "expression": "saved_keyword_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "tag_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "saved_keyword_tag_assignments_tag_idx": {+ "name": "saved_keyword_tag_assignments_tag_idx",+ "columns": [+ {+ "expression": "tag_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "saved_keyword_tag_assignments_saved_keyword_id_saved_keywords_id_fk": {+ "name": "saved_keyword_tag_assignments_saved_keyword_id_saved_keywords_id_fk",+ "tableFrom": "saved_keyword_tag_assignments",+ "tableTo": "saved_keywords",+ "columnsFrom": [+ "saved_keyword_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "saved_keyword_tag_assignments_tag_id_saved_keyword_tags_id_fk": {+ "name": "saved_keyword_tag_assignments_tag_id_saved_keyword_tags_id_fk",+ "tableFrom": "saved_keyword_tag_assignments",+ "tableTo": "saved_keyword_tags",+ "columnsFrom": [+ "tag_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.saved_keyword_tags": {+ "name": "saved_keyword_tags",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "normalized_name": {+ "name": "normalized_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "saved_keyword_tags_project_normalized_name_idx": {+ "name": "saved_keyword_tags_project_normalized_name_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "normalized_name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "saved_keyword_tags_project_name_idx": {+ "name": "saved_keyword_tags_project_name_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "saved_keyword_tags_project_id_projects_id_fk": {+ "name": "saved_keyword_tags_project_id_projects_id_fk",+ "tableFrom": "saved_keyword_tags",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.saved_keywords": {+ "name": "saved_keywords",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "keyword": {+ "name": "keyword",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "location_code": {+ "name": "location_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 2840+ },+ "language_code": {+ "name": "language_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'en'"+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "saved_keywords_unique_project_keyword_location_language": {+ "name": "saved_keywords_unique_project_keyword_location_language",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "keyword",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "location_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "language_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "saved_keywords_project_created_idx": {+ "name": "saved_keywords_project_created_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "saved_keywords_project_id_projects_id_fk": {+ "name": "saved_keywords_project_id_projects_id_fk",+ "tableFrom": "saved_keywords",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_onboarding_answers": {+ "name": "user_onboarding_answers",+ "schema": "",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "interested_features": {+ "name": "interested_features",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'"+ },+ "work_for": {+ "name": "work_for",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "client_website_count": {+ "name": "client_website_count",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "found_via": {+ "name": "found_via",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "mcp_setup_intent": {+ "name": "mcp_setup_intent",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "completed_at": {+ "name": "completed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "gsc_nudge_dismissed_at": {+ "name": "gsc_nudge_dismissed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "user_onboarding_answers_organization_idx": {+ "name": "user_onboarding_answers_organization_idx",+ "columns": [+ {+ "expression": "organization_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_onboarding_answers_user_id_user_id_fk": {+ "name": "user_onboarding_answers_user_id_user_id_fk",+ "tableFrom": "user_onboarding_answers",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "user_onboarding_answers_organization_id_organization_id_fk": {+ "name": "user_onboarding_answers_organization_id_organization_id_fk",+ "tableFrom": "user_onboarding_answers",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_competitors": {+ "name": "project_competitors",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "domain": {+ "name": "domain",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "notes": {+ "name": "notes",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "updated_by": {+ "name": "updated_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "project_competitors_project_domain_idx": {+ "name": "project_competitors_project_domain_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "domain",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_competitors_project_id_projects_id_fk": {+ "name": "project_competitors_project_id_projects_id_fk",+ "tableFrom": "project_competitors",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_context_sections": {+ "name": "project_context_sections",+ "schema": "",+ "columns": {+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "updated_by": {+ "name": "updated_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "project_context_sections_project_id_projects_id_fk": {+ "name": "project_context_sections_project_id_projects_id_fk",+ "tableFrom": "project_context_sections",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "project_context_sections_project_id_key_pk": {+ "name": "project_context_sections_project_id_key_pk",+ "columns": [+ "project_id",+ "key"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_key_pages": {+ "name": "project_key_pages",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "topic": {+ "name": "topic",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "notes": {+ "name": "notes",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "updated_by": {+ "name": "updated_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "project_key_pages_project_url_idx": {+ "name": "project_key_pages_project_url_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "url",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_key_pages_project_id_projects_id_fk": {+ "name": "project_key_pages_project_id_projects_id_fk",+ "tableFrom": "project_key_pages",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_research_log": {+ "name": "project_research_log",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "entry_date": {+ "name": "entry_date",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "summary": {+ "name": "summary",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "project_research_log_project_date_idx": {+ "name": "project_research_log_project_date_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "entry_date",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_research_log_project_id_projects_id_fk": {+ "name": "project_research_log_project_id_projects_id_fk",+ "tableFrom": "project_research_log",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.reports": {+ "name": "reports",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "summary": {+ "name": "summary",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "html": {+ "name": "html",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "skill": {+ "name": "skill",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "template_id": {+ "name": "template_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "size_bytes": {+ "name": "size_bytes",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "share_token": {+ "name": "share_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "shared_at": {+ "name": "shared_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "reports_project_updated_idx": {+ "name": "reports_project_updated_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "updated_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "size_bytes",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "reports_share_token_idx": {+ "name": "reports_share_token_idx",+ "columns": [+ {+ "expression": "share_token",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "reports_project_id_projects_id_fk": {+ "name": "reports_project_id_projects_id_fk",+ "tableFrom": "reports",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.report_templates": {+ "name": "report_templates",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "instructions": {+ "name": "instructions",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "report_templates_project_name_idx": {+ "name": "report_templates_project_name_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "report_templates_project_id_projects_id_fk": {+ "name": "report_templates_project_id_projects_id_fk",+ "tableFrom": "report_templates",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.audit_issues": {+ "name": "audit_issues",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "audit_id": {+ "name": "audit_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "page_id": {+ "name": "page_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "page_url": {+ "name": "page_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "issue_type": {+ "name": "issue_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "severity": {+ "name": "severity",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'info'"+ },+ "details_json": {+ "name": "details_json",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "audit_issues_audit_type_idx": {+ "name": "audit_issues_audit_type_idx",+ "columns": [+ {+ "expression": "audit_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "audit_issues_page_id_idx": {+ "name": "audit_issues_page_id_idx",+ "columns": [+ {+ "expression": "page_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "audit_issues_audit_id_audits_id_fk": {+ "name": "audit_issues_audit_id_audits_id_fk",+ "tableFrom": "audit_issues",+ "tableTo": "audits",+ "columnsFrom": [+ "audit_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "audit_issues_page_id_audit_pages_id_fk": {+ "name": "audit_issues_page_id_audit_pages_id_fk",+ "tableFrom": "audit_issues",+ "tableTo": "audit_pages",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.audit_lighthouse_results": {+ "name": "audit_lighthouse_results",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "audit_id": {+ "name": "audit_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "page_id": {+ "name": "page_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "strategy": {+ "name": "strategy",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "performance_score": {+ "name": "performance_score",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "accessibility_score": {+ "name": "accessibility_score",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "best_practices_score": {+ "name": "best_practices_score",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "seo_score": {+ "name": "seo_score",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "lcp_ms": {+ "name": "lcp_ms",+ "type": "real",+ "primaryKey": false,+ "notNull": false+ },+ "cls": {+ "name": "cls",+ "type": "real",+ "primaryKey": false,+ "notNull": false+ },+ "inp_ms": {+ "name": "inp_ms",+ "type": "real",+ "primaryKey": false,+ "notNull": false+ },+ "ttfb_ms": {+ "name": "ttfb_ms",+ "type": "real",+ "primaryKey": false,+ "notNull": false+ },+ "error_message": {+ "name": "error_message",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "r2_key": {+ "name": "r2_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "payload_size_bytes": {+ "name": "payload_size_bytes",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "audit_lighthouse_results_audit_id_idx": {+ "name": "audit_lighthouse_results_audit_id_idx",+ "columns": [+ {+ "expression": "audit_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "audit_lighthouse_results_page_id_idx": {+ "name": "audit_lighthouse_results_page_id_idx",+ "columns": [+ {+ "expression": "page_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "audit_lighthouse_results_audit_id_audits_id_fk": {+ "name": "audit_lighthouse_results_audit_id_audits_id_fk",+ "tableFrom": "audit_lighthouse_results",+ "tableTo": "audits",+ "columnsFrom": [+ "audit_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "audit_lighthouse_results_page_id_audit_pages_id_fk": {+ "name": "audit_lighthouse_results_page_id_audit_pages_id_fk",+ "tableFrom": "audit_lighthouse_results",+ "tableTo": "audit_pages",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.audit_pages": {+ "name": "audit_pages",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "audit_id": {+ "name": "audit_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status_code": {+ "name": "status_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "redirect_url": {+ "name": "redirect_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "meta_description": {+ "name": "meta_description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "canonical_url": {+ "name": "canonical_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "robots_meta": {+ "name": "robots_meta",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "og_title": {+ "name": "og_title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "og_description": {+ "name": "og_description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "og_image": {+ "name": "og_image",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "h1_count": {+ "name": "h1_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "h2_count": {+ "name": "h2_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "h3_count": {+ "name": "h3_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "h4_count": {+ "name": "h4_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "h5_count": {+ "name": "h5_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "h6_count": {+ "name": "h6_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "heading_order_json": {+ "name": "heading_order_json",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "word_count": {+ "name": "word_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "images_total": {+ "name": "images_total",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "images_missing_alt": {+ "name": "images_missing_alt",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "images_json": {+ "name": "images_json",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "internal_link_count": {+ "name": "internal_link_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "external_link_count": {+ "name": "external_link_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "has_structured_data": {+ "name": "has_structured_data",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "hreflang_tags_json": {+ "name": "hreflang_tags_json",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "is_indexable": {+ "name": "is_indexable",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "x_robots_tag": {+ "name": "x_robots_tag",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "header_canonical_url": {+ "name": "header_canonical_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "crawl_depth": {+ "name": "crawl_depth",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "in_sitemap": {+ "name": "in_sitemap",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "content_hash": {+ "name": "content_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "fetch_class": {+ "name": "fetch_class",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'ok'"+ },+ "response_time_ms": {+ "name": "response_time_ms",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "audit_pages_audit_url_idx": {+ "name": "audit_pages_audit_url_idx",+ "columns": [+ {+ "expression": "audit_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "url",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "audit_pages_audit_id_audits_id_fk": {+ "name": "audit_pages_audit_id_audits_id_fk",+ "tableFrom": "audit_pages",+ "tableTo": "audits",+ "columnsFrom": [+ "audit_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.audits": {+ "name": "audits",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "started_by_user_id": {+ "name": "started_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "start_url": {+ "name": "start_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'running'"+ },+ "workflow_instance_id": {+ "name": "workflow_instance_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "config": {+ "name": "config",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'"+ },+ "pages_crawled": {+ "name": "pages_crawled",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "pages_total": {+ "name": "pages_total",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "lighthouse_total": {+ "name": "lighthouse_total",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "lighthouse_completed": {+ "name": "lighthouse_completed",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "lighthouse_failed": {+ "name": "lighthouse_failed",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "current_phase": {+ "name": "current_phase",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "default": "'discovery'"+ },+ "error_code": {+ "name": "error_code",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "error_detail": {+ "name": "error_detail",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "failed_phase": {+ "name": "failed_phase",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "started_at": {+ "name": "started_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "completed_at": {+ "name": "completed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "audits_project_id_idx": {+ "name": "audits_project_id_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "audits_started_by_user_id_idx": {+ "name": "audits_started_by_user_id_idx",+ "columns": [+ {+ "expression": "started_by_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "audits_project_id_projects_id_fk": {+ "name": "audits_project_id_projects_id_fk",+ "tableFrom": "audits",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.sam_sessions": {+ "name": "sam_sessions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'New chat'"+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "archived_at": {+ "name": "archived_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "sam_sessions_project_updated_idx": {+ "name": "sam_sessions_project_updated_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "updated_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "sam_sessions_project_id_projects_id_fk": {+ "name": "sam_sessions_project_id_projects_id_fk",+ "tableFrom": "sam_sessions",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "sam_sessions_user_id_user_id_fk": {+ "name": "sam_sessions_user_id_user_id_fk",+ "tableFrom": "sam_sessions",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.account": {+ "name": "account",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "account_id": {+ "name": "account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "id_token": {+ "name": "id_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "access_token_expires_at": {+ "name": "access_token_expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_token_expires_at": {+ "name": "refresh_token_expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "password": {+ "name": "password",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "account_userId_idx": {+ "name": "account_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "account_accountId_providerId_idx": {+ "name": "account_accountId_providerId_idx",+ "columns": [+ {+ "expression": "account_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "account_user_id_user_id_fk": {+ "name": "account_user_id_user_id_fk",+ "tableFrom": "account",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.apikey": {+ "name": "apikey",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "config_id": {+ "name": "config_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'default'"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "start": {+ "name": "start",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "prefix": {+ "name": "prefix",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reference_id": {+ "name": "reference_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "refill_interval": {+ "name": "refill_interval",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "refill_amount": {+ "name": "refill_amount",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "last_refill_at": {+ "name": "last_refill_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "rate_limit_enabled": {+ "name": "rate_limit_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "rate_limit_time_window": {+ "name": "rate_limit_time_window",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 60000+ },+ "rate_limit_max": {+ "name": "rate_limit_max",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 120+ },+ "request_count": {+ "name": "request_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "remaining": {+ "name": "remaining",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "last_request": {+ "name": "last_request",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "permissions": {+ "name": "permissions",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "apikey_configId_idx": {+ "name": "apikey_configId_idx",+ "columns": [+ {+ "expression": "config_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "apikey_referenceId_idx": {+ "name": "apikey_referenceId_idx",+ "columns": [+ {+ "expression": "reference_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "apikey_key_idx": {+ "name": "apikey_key_idx",+ "columns": [+ {+ "expression": "key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.invitation": {+ "name": "invitation",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "inviter_id": {+ "name": "inviter_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "invitation_organizationId_idx": {+ "name": "invitation_organizationId_idx",+ "columns": [+ {+ "expression": "organization_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "invitation_email_idx": {+ "name": "invitation_email_idx",+ "columns": [+ {+ "expression": "email",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "invitation_organization_id_organization_id_fk": {+ "name": "invitation_organization_id_organization_id_fk",+ "tableFrom": "invitation",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "invitation_inviter_id_user_id_fk": {+ "name": "invitation_inviter_id_user_id_fk",+ "tableFrom": "invitation",+ "tableTo": "user",+ "columnsFrom": [+ "inviter_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.member": {+ "name": "member",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'member'"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "member_organizationId_idx": {+ "name": "member_organizationId_idx",+ "columns": [+ {+ "expression": "organization_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "member_userId_idx": {+ "name": "member_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "member_organizationId_userId_uidx": {+ "name": "member_organizationId_userId_uidx",+ "columns": [+ {+ "expression": "organization_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "member_organization_id_organization_id_fk": {+ "name": "member_organization_id_organization_id_fk",+ "tableFrom": "member",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "member_user_id_user_id_fk": {+ "name": "member_user_id_user_id_fk",+ "tableFrom": "member",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.organization": {+ "name": "organization",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "logo": {+ "name": "logo",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "organization_slug_uidx": {+ "name": "organization_slug_uidx",+ "columns": [+ {+ "expression": "slug",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "organization_slug_unique": {+ "name": "organization_slug_unique",+ "nullsNotDistinct": false,+ "columns": [+ "slug"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.session": {+ "name": "session",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "ip_address": {+ "name": "ip_address",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_agent": {+ "name": "user_agent",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "active_organization_id": {+ "name": "active_organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "session_userId_idx": {+ "name": "session_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "session_user_id_user_id_fk": {+ "name": "session_user_id_user_id_fk",+ "tableFrom": "session",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "session_token_unique": {+ "name": "session_token_unique",+ "nullsNotDistinct": false,+ "columns": [+ "token"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user": {+ "name": "user",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email_verified": {+ "name": "email_verified",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "image": {+ "name": "image",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "analytics_opted_out": {+ "name": "analytics_opted_out",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false+ },+ "last_active_organization_id": {+ "name": "last_active_organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_email_unique": {+ "name": "user_email_unique",+ "nullsNotDistinct": false,+ "columns": [+ "email"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.verification": {+ "name": "verification",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "identifier": {+ "name": "identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "verification_identifier_idx": {+ "name": "verification_identifier_idx",+ "columns": [+ {+ "expression": "identifier",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "verification_expiresAt_idx": {+ "name": "verification_expiresAt_idx",+ "columns": [+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.billing_customer_status": {+ "name": "billing_customer_status",+ "schema": "",+ "columns": {+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "is_paying": {+ "name": "is_paying",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "paid_plan_id": {+ "name": "paid_plan_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "paid_plan_status": {+ "name": "paid_plan_status",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "customer_json": {+ "name": "customer_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "synced_at": {+ "name": "synced_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "billing_customer_status_organization_id_organization_id_fk": {+ "name": "billing_customer_status_organization_id_organization_id_fk",+ "tableFrom": "billing_customer_status",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.ga4_connections": {+ "name": "ga4_connections",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "property_id": {+ "name": "property_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "property_display_name": {+ "name": "property_display_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "property_time_zone": {+ "name": "property_time_zone",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "property_currency_code": {+ "name": "property_currency_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "connected_by_user_id": {+ "name": "connected_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "ga4_account_id": {+ "name": "ga4_account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "connected_account_email": {+ "name": "connected_account_email",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "ga4_connections_project_idx": {+ "name": "ga4_connections_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "ga4_connections_organization_idx": {+ "name": "ga4_connections_organization_idx",+ "columns": [+ {+ "expression": "organization_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "ga4_connections_connector_idx": {+ "name": "ga4_connections_connector_idx",+ "columns": [+ {+ "expression": "connected_by_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "ga4_account_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "ga4_connections_project_id_projects_id_fk": {+ "name": "ga4_connections_project_id_projects_id_fk",+ "tableFrom": "ga4_connections",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "ga4_connections_organization_id_organization_id_fk": {+ "name": "ga4_connections_organization_id_organization_id_fk",+ "tableFrom": "ga4_connections",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.gsc_connections": {+ "name": "gsc_connections",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "site_url": {+ "name": "site_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "connected_by_user_id": {+ "name": "connected_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "gsc_account_id": {+ "name": "gsc_account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "connected_account_email": {+ "name": "connected_account_email",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')"+ }+ },+ "indexes": {+ "gsc_connections_project_idx": {+ "name": "gsc_connections_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "gsc_connections_organization_idx": {+ "name": "gsc_connections_organization_idx",+ "columns": [+ {+ "expression": "organization_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "gsc_connections_project_id_projects_id_fk": {+ "name": "gsc_connections_project_id_projects_id_fk",+ "tableFrom": "gsc_connections",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "gsc_connections_organization_id_organization_id_fk": {+ "name": "gsc_connections_organization_id_organization_id_fk",+ "tableFrom": "gsc_connections",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.telemetry_state": {+ "name": "telemetry_state",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "default": 1+ },+ "install_id": {+ "name": "install_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "installed_at": {+ "name": "installed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_heartbeat_at": {+ "name": "last_heartbeat_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_version": {+ "name": "last_version",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "mcp_tool_call_count": {+ "name": "mcp_tool_call_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ }+ },+ "enums": {},+ "schemas": {},+ "sequences": {},+ "roles": {},+ "policies": {},+ "views": {},+ "_meta": {+ "columns": {},+ "schemas": {},+ "tables": {}+ }+}\ No newline at end of filediff --git a/drizzle-pg/meta/_journal.json b/drizzle-pg/meta/_journal.jsonindex 407a0c1d..34561ccc 100644--- a/drizzle-pg/meta/_journal.json+++ b/drizzle-pg/meta/_journal.json@@ -176,6 +176,13 @@"when": 1788651419109,"tag": "0024_tense_echo","breakpoints": true+ },+ {+ "idx": 25,+ "version": "7",+ "when": 1789455137276,+ "tag": "0025_reports",+ "breakpoints": true}]}\ No newline at end of filediff --git a/drizzle/0047_reports.sql b/drizzle/0047_reports.sqlnew file mode 100644index 00000000..dda0a6e1--- /dev/null+++ b/drizzle/0047_reports.sql@@ -0,0 +1,34 @@+CREATE TABLE `reports` (+ `id` text PRIMARY KEY NOT NULL,+ `project_id` text NOT NULL,+ `title` text NOT NULL,+ `summary` text NOT NULL,+ `html` text NOT NULL,+ `skill` text,+ `template_id` text,+ `created_by` text NOT NULL,+ `created_by_user_id` text NOT NULL,+ `size_bytes` integer NOT NULL,+ `share_token` text,+ `shared_at` text,+ `created_at` text DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')) NOT NULL,+ `updated_at` text DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')) NOT NULL,+ FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade+);+--> statement-breakpoint+CREATE INDEX `reports_project_updated_idx` ON `reports` (`project_id`,`updated_at`,`id`,`size_bytes`);--> statement-breakpoint+CREATE UNIQUE INDEX `reports_share_token_idx` ON `reports` (`share_token`);--> statement-breakpoint+CREATE TABLE `report_templates` (+ `id` text PRIMARY KEY NOT NULL,+ `project_id` text NOT NULL,+ `name` text NOT NULL,+ `description` text NOT NULL,+ `instructions` text NOT NULL,+ `created_by` text NOT NULL,+ `created_by_user_id` text NOT NULL,+ `created_at` text DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')) NOT NULL,+ `updated_at` text DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')) NOT NULL,+ FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade+);+--> statement-breakpoint+CREATE UNIQUE INDEX `report_templates_project_name_idx` ON `report_templates` (`project_id`,`name`);\ No newline at end of filediff --git a/drizzle/meta/0047_snapshot.json b/drizzle/meta/0047_snapshot.jsonnew file mode 100644index 00000000..ee5291ed--- /dev/null+++ b/drizzle/meta/0047_snapshot.json@@ -0,0 +1,4070 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "1c9bbbf4-30c7-4625-94ca-6fa89e460d39",+ "prevId": "cfb3ee2c-43a2-413e-a538-ec7dfe0a7a6a",+ "tables": {+ "backlink_snapshots": {+ "name": "backlink_snapshots",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "domain": {+ "name": "domain",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "rank": {+ "name": "rank",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "backlinks": {+ "name": "backlinks",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "referring_domains": {+ "name": "referring_domains",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "broken_backlinks": {+ "name": "broken_backlinks",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "new_backlinks": {+ "name": "new_backlinks",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "lost_backlinks": {+ "name": "lost_backlinks",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "new_referring_domains": {+ "name": "new_referring_domains",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "lost_referring_domains": {+ "name": "lost_referring_domains",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "captured_at": {+ "name": "captured_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "backlink_snapshots_project_captured_idx": {+ "name": "backlink_snapshots_project_captured_idx",+ "columns": [+ "project_id",+ "captured_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "backlink_snapshots_project_id_projects_id_fk": {+ "name": "backlink_snapshots_project_id_projects_id_fk",+ "tableFrom": "backlink_snapshots",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "dashboard_step_dismissals": {+ "name": "dashboard_step_dismissals",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "step": {+ "name": "step",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "dashboard_step_dismissals_project_idx": {+ "name": "dashboard_step_dismissals_project_idx",+ "columns": [+ "project_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "dashboard_step_dismissals_user_id_user_id_fk": {+ "name": "dashboard_step_dismissals_user_id_user_id_fk",+ "tableFrom": "dashboard_step_dismissals",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "dashboard_step_dismissals_project_id_projects_id_fk": {+ "name": "dashboard_step_dismissals_project_id_projects_id_fk",+ "tableFrom": "dashboard_step_dismissals",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "dashboard_step_dismissals_user_id_project_id_step_pk": {+ "columns": [+ "user_id",+ "project_id",+ "step"+ ],+ "name": "dashboard_step_dismissals_user_id_project_id_step_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "keyword_metrics": {+ "name": "keyword_metrics",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "keyword": {+ "name": "keyword",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "location_code": {+ "name": "location_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "language_code": {+ "name": "language_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'en'"+ },+ "search_volume": {+ "name": "search_volume",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "cpc": {+ "name": "cpc",+ "type": "real",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "competition": {+ "name": "competition",+ "type": "real",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "keyword_difficulty": {+ "name": "keyword_difficulty",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "intent": {+ "name": "intent",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "monthly_searches": {+ "name": "monthly_searches",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "fetched_at": {+ "name": "fetched_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "keyword_metrics_unique_project_keyword_location_language": {+ "name": "keyword_metrics_unique_project_keyword_location_language",+ "columns": [+ "project_id",+ "keyword",+ "location_code",+ "language_code"+ ],+ "isUnique": true+ },+ "keyword_metrics_lookup_idx": {+ "name": "keyword_metrics_lookup_idx",+ "columns": [+ "project_id",+ "keyword",+ "location_code",+ "language_code",+ "fetched_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "keyword_metrics_project_id_projects_id_fk": {+ "name": "keyword_metrics_project_id_projects_id_fk",+ "tableFrom": "keyword_metrics",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "organization_activation_state": {+ "name": "organization_activation_state",+ "columns": {+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "first_mcp_authorized_at": {+ "name": "first_mcp_authorized_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "first_mcp_tool_call_at": {+ "name": "first_mcp_tool_call_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "organization_activation_state_organization_id_organization_id_fk": {+ "name": "organization_activation_state_organization_id_organization_id_fk",+ "tableFrom": "organization_activation_state",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "project_activation_state": {+ "name": "project_activation_state",+ "columns": {+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "competitor_step_clicked_at": {+ "name": "competitor_step_clicked_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "mcp_card_dismissed_at": {+ "name": "mcp_card_dismissed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "ga4_card_dismissed_at": {+ "name": "ga4_card_dismissed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "project_activation_state_project_id_projects_id_fk": {+ "name": "project_activation_state_project_id_projects_id_fk",+ "tableFrom": "project_activation_state",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "projects": {+ "name": "projects",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "domain": {+ "name": "domain",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "location_code": {+ "name": "location_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 2840+ },+ "language_code": {+ "name": "language_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'en'"+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "archived_at": {+ "name": "archived_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "projects_one_default_per_organization_idx": {+ "name": "projects_one_default_per_organization_idx",+ "columns": [+ "organization_id"+ ],+ "isUnique": true,+ "where": "\"projects\".\"name\" = 'Default' AND \"projects\".\"domain\" IS NULL AND \"projects\".\"archived_at\" IS NULL"+ },+ "projects_organization_id_idx": {+ "name": "projects_organization_id_idx",+ "columns": [+ "organization_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "projects_organization_id_organization_id_fk": {+ "name": "projects_organization_id_organization_id_fk",+ "tableFrom": "projects",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "rank_check_runs": {+ "name": "rank_check_runs",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "config_id": {+ "name": "config_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'pending'"+ },+ "keywords_total": {+ "name": "keywords_total",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "keywords_checked": {+ "name": "keywords_checked",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "is_subset_run": {+ "name": "is_subset_run",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "error_message": {+ "name": "error_message",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "started_at": {+ "name": "started_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "completed_at": {+ "name": "completed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "rank_check_runs_config_idx": {+ "name": "rank_check_runs_config_idx",+ "columns": [+ "config_id",+ "started_at"+ ],+ "isUnique": false+ },+ "rank_check_runs_project_idx": {+ "name": "rank_check_runs_project_idx",+ "columns": [+ "project_id",+ "started_at"+ ],+ "isUnique": false+ },+ "rank_check_runs_one_active_per_config_idx": {+ "name": "rank_check_runs_one_active_per_config_idx",+ "columns": [+ "config_id"+ ],+ "isUnique": true,+ "where": "\"rank_check_runs\".\"status\" IN ('pending', 'running')"+ }+ },+ "foreignKeys": {+ "rank_check_runs_config_id_rank_tracking_configs_id_fk": {+ "name": "rank_check_runs_config_id_rank_tracking_configs_id_fk",+ "tableFrom": "rank_check_runs",+ "tableTo": "rank_tracking_configs",+ "columnsFrom": [+ "config_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "rank_check_runs_project_id_projects_id_fk": {+ "name": "rank_check_runs_project_id_projects_id_fk",+ "tableFrom": "rank_check_runs",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "rank_snapshots": {+ "name": "rank_snapshots",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "run_id": {+ "name": "run_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "tracking_keyword_id": {+ "name": "tracking_keyword_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "keyword": {+ "name": "keyword",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "device": {+ "name": "device",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "serp_features": {+ "name": "serp_features",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "checked_at": {+ "name": "checked_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "rank_snapshots_keyword_device_idx": {+ "name": "rank_snapshots_keyword_device_idx",+ "columns": [+ "tracking_keyword_id",+ "device",+ "checked_at"+ ],+ "isUnique": false+ },+ "rank_snapshots_run_keyword_device_idx": {+ "name": "rank_snapshots_run_keyword_device_idx",+ "columns": [+ "run_id",+ "tracking_keyword_id",+ "device"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "rank_snapshots_run_id_rank_check_runs_id_fk": {+ "name": "rank_snapshots_run_id_rank_check_runs_id_fk",+ "tableFrom": "rank_snapshots",+ "tableTo": "rank_check_runs",+ "columnsFrom": [+ "run_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "rank_tracking_configs": {+ "name": "rank_tracking_configs",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "domain": {+ "name": "domain",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "location_code": {+ "name": "location_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 2840+ },+ "language_code": {+ "name": "language_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'en'"+ },+ "devices": {+ "name": "devices",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'both'"+ },+ "serp_depth": {+ "name": "serp_depth",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "schedule_interval": {+ "name": "schedule_interval",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'weekly'"+ },+ "location_name": {+ "name": "location_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "is_active": {+ "name": "is_active",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "last_checked_at": {+ "name": "last_checked_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "next_check_at": {+ "name": "next_check_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_skip_reason": {+ "name": "last_skip_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "rank_tracking_configs_project_active_created_idx": {+ "name": "rank_tracking_configs_project_active_created_idx",+ "columns": [+ "project_id",+ "is_active",+ "created_at"+ ],+ "isUnique": false+ },+ "rank_tracking_configs_national_idx": {+ "name": "rank_tracking_configs_national_idx",+ "columns": [+ "project_id",+ "domain",+ "location_code"+ ],+ "isUnique": true,+ "where": "\"rank_tracking_configs\".\"location_name\" IS NULL"+ },+ "rank_tracking_configs_local_idx": {+ "name": "rank_tracking_configs_local_idx",+ "columns": [+ "project_id",+ "domain",+ "location_code",+ "location_name"+ ],+ "isUnique": true,+ "where": "\"rank_tracking_configs\".\"location_name\" IS NOT NULL"+ }+ },+ "foreignKeys": {+ "rank_tracking_configs_project_id_projects_id_fk": {+ "name": "rank_tracking_configs_project_id_projects_id_fk",+ "tableFrom": "rank_tracking_configs",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "rank_tracking_keywords": {+ "name": "rank_tracking_keywords",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "config_id": {+ "name": "config_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "keyword": {+ "name": "keyword",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "match_case": {+ "name": "match_case",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "search_volume": {+ "name": "search_volume",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "keyword_difficulty": {+ "name": "keyword_difficulty",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "cpc": {+ "name": "cpc",+ "type": "real",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "metrics_fetched_at": {+ "name": "metrics_fetched_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "rank_tracking_keywords_config_keyword_idx": {+ "name": "rank_tracking_keywords_config_keyword_idx",+ "columns": [+ "config_id",+ "keyword"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "rank_tracking_keywords_config_id_rank_tracking_configs_id_fk": {+ "name": "rank_tracking_keywords_config_id_rank_tracking_configs_id_fk",+ "tableFrom": "rank_tracking_keywords",+ "tableTo": "rank_tracking_configs",+ "columnsFrom": [+ "config_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "saved_keyword_tag_assignments": {+ "name": "saved_keyword_tag_assignments",+ "columns": {+ "saved_keyword_id": {+ "name": "saved_keyword_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "tag_id": {+ "name": "tag_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "saved_keyword_tag_assignments_unique_idx": {+ "name": "saved_keyword_tag_assignments_unique_idx",+ "columns": [+ "saved_keyword_id",+ "tag_id"+ ],+ "isUnique": true+ },+ "saved_keyword_tag_assignments_tag_idx": {+ "name": "saved_keyword_tag_assignments_tag_idx",+ "columns": [+ "tag_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "saved_keyword_tag_assignments_saved_keyword_id_saved_keywords_id_fk": {+ "name": "saved_keyword_tag_assignments_saved_keyword_id_saved_keywords_id_fk",+ "tableFrom": "saved_keyword_tag_assignments",+ "tableTo": "saved_keywords",+ "columnsFrom": [+ "saved_keyword_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "saved_keyword_tag_assignments_tag_id_saved_keyword_tags_id_fk": {+ "name": "saved_keyword_tag_assignments_tag_id_saved_keyword_tags_id_fk",+ "tableFrom": "saved_keyword_tag_assignments",+ "tableTo": "saved_keyword_tags",+ "columnsFrom": [+ "tag_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "saved_keyword_tags": {+ "name": "saved_keyword_tags",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "normalized_name": {+ "name": "normalized_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "saved_keyword_tags_project_normalized_name_idx": {+ "name": "saved_keyword_tags_project_normalized_name_idx",+ "columns": [+ "project_id",+ "normalized_name"+ ],+ "isUnique": true+ },+ "saved_keyword_tags_project_name_idx": {+ "name": "saved_keyword_tags_project_name_idx",+ "columns": [+ "project_id",+ "name"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "saved_keyword_tags_project_id_projects_id_fk": {+ "name": "saved_keyword_tags_project_id_projects_id_fk",+ "tableFrom": "saved_keyword_tags",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "saved_keywords": {+ "name": "saved_keywords",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "keyword": {+ "name": "keyword",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "location_code": {+ "name": "location_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 2840+ },+ "language_code": {+ "name": "language_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'en'"+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "saved_keywords_unique_project_keyword_location_language": {+ "name": "saved_keywords_unique_project_keyword_location_language",+ "columns": [+ "project_id",+ "keyword",+ "location_code",+ "language_code"+ ],+ "isUnique": true+ },+ "saved_keywords_project_created_idx": {+ "name": "saved_keywords_project_created_idx",+ "columns": [+ "project_id",+ "created_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "saved_keywords_project_id_projects_id_fk": {+ "name": "saved_keywords_project_id_projects_id_fk",+ "tableFrom": "saved_keywords",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "user_onboarding_answers": {+ "name": "user_onboarding_answers",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "interested_features": {+ "name": "interested_features",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "work_for": {+ "name": "work_for",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "client_website_count": {+ "name": "client_website_count",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "found_via": {+ "name": "found_via",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "mcp_setup_intent": {+ "name": "mcp_setup_intent",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "completed_at": {+ "name": "completed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "gsc_nudge_dismissed_at": {+ "name": "gsc_nudge_dismissed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "user_onboarding_answers_organization_idx": {+ "name": "user_onboarding_answers_organization_idx",+ "columns": [+ "organization_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "user_onboarding_answers_user_id_user_id_fk": {+ "name": "user_onboarding_answers_user_id_user_id_fk",+ "tableFrom": "user_onboarding_answers",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "user_onboarding_answers_organization_id_organization_id_fk": {+ "name": "user_onboarding_answers_organization_id_organization_id_fk",+ "tableFrom": "user_onboarding_answers",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "project_competitors": {+ "name": "project_competitors",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "domain": {+ "name": "domain",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "notes": {+ "name": "notes",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "updated_by": {+ "name": "updated_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "project_competitors_project_domain_idx": {+ "name": "project_competitors_project_domain_idx",+ "columns": [+ "project_id",+ "domain"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "project_competitors_project_id_projects_id_fk": {+ "name": "project_competitors_project_id_projects_id_fk",+ "tableFrom": "project_competitors",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "project_context_sections": {+ "name": "project_context_sections",+ "columns": {+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "updated_by": {+ "name": "updated_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "project_context_sections_project_id_projects_id_fk": {+ "name": "project_context_sections_project_id_projects_id_fk",+ "tableFrom": "project_context_sections",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "project_context_sections_project_id_key_pk": {+ "columns": [+ "project_id",+ "key"+ ],+ "name": "project_context_sections_project_id_key_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "project_key_pages": {+ "name": "project_key_pages",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "topic": {+ "name": "topic",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "notes": {+ "name": "notes",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "updated_by": {+ "name": "updated_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "project_key_pages_project_url_idx": {+ "name": "project_key_pages_project_url_idx",+ "columns": [+ "project_id",+ "url"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "project_key_pages_project_id_projects_id_fk": {+ "name": "project_key_pages_project_id_projects_id_fk",+ "tableFrom": "project_key_pages",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "project_research_log": {+ "name": "project_research_log",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "entry_date": {+ "name": "entry_date",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "summary": {+ "name": "summary",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(strftime('%Y-%m-%dT%H:%M:%fZ','now'))"+ }+ },+ "indexes": {+ "project_research_log_project_date_idx": {+ "name": "project_research_log_project_date_idx",+ "columns": [+ "project_id",+ "entry_date"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "project_research_log_project_id_projects_id_fk": {+ "name": "project_research_log_project_id_projects_id_fk",+ "tableFrom": "project_research_log",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "reports": {+ "name": "reports",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "summary": {+ "name": "summary",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "html": {+ "name": "html",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "skill": {+ "name": "skill",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "template_id": {+ "name": "template_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "size_bytes": {+ "name": "size_bytes",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "share_token": {+ "name": "share_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "shared_at": {+ "name": "shared_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(strftime('%Y-%m-%dT%H:%M:%fZ','now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(strftime('%Y-%m-%dT%H:%M:%fZ','now'))"+ }+ },+ "indexes": {+ "reports_project_updated_idx": {+ "name": "reports_project_updated_idx",+ "columns": [+ "project_id",+ "updated_at",+ "id",+ "size_bytes"+ ],+ "isUnique": false+ },+ "reports_share_token_idx": {+ "name": "reports_share_token_idx",+ "columns": [+ "share_token"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "reports_project_id_projects_id_fk": {+ "name": "reports_project_id_projects_id_fk",+ "tableFrom": "reports",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "report_templates": {+ "name": "report_templates",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "instructions": {+ "name": "instructions",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(strftime('%Y-%m-%dT%H:%M:%fZ','now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(strftime('%Y-%m-%dT%H:%M:%fZ','now'))"+ }+ },+ "indexes": {+ "report_templates_project_name_idx": {+ "name": "report_templates_project_name_idx",+ "columns": [+ "project_id",+ "name"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "report_templates_project_id_projects_id_fk": {+ "name": "report_templates_project_id_projects_id_fk",+ "tableFrom": "report_templates",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "audit_issues": {+ "name": "audit_issues",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "audit_id": {+ "name": "audit_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "page_id": {+ "name": "page_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "page_url": {+ "name": "page_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "issue_type": {+ "name": "issue_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "severity": {+ "name": "severity",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'info'"+ },+ "details_json": {+ "name": "details_json",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "audit_issues_audit_type_idx": {+ "name": "audit_issues_audit_type_idx",+ "columns": [+ "audit_id",+ "issue_type"+ ],+ "isUnique": false+ },+ "audit_issues_page_id_idx": {+ "name": "audit_issues_page_id_idx",+ "columns": [+ "page_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "audit_issues_audit_id_audits_id_fk": {+ "name": "audit_issues_audit_id_audits_id_fk",+ "tableFrom": "audit_issues",+ "tableTo": "audits",+ "columnsFrom": [+ "audit_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "audit_issues_page_id_audit_pages_id_fk": {+ "name": "audit_issues_page_id_audit_pages_id_fk",+ "tableFrom": "audit_issues",+ "tableTo": "audit_pages",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "audit_lighthouse_results": {+ "name": "audit_lighthouse_results",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "audit_id": {+ "name": "audit_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "page_id": {+ "name": "page_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "strategy": {+ "name": "strategy",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "performance_score": {+ "name": "performance_score",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "accessibility_score": {+ "name": "accessibility_score",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "best_practices_score": {+ "name": "best_practices_score",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "seo_score": {+ "name": "seo_score",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "lcp_ms": {+ "name": "lcp_ms",+ "type": "real",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "cls": {+ "name": "cls",+ "type": "real",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "inp_ms": {+ "name": "inp_ms",+ "type": "real",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "ttfb_ms": {+ "name": "ttfb_ms",+ "type": "real",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "error_message": {+ "name": "error_message",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "r2_key": {+ "name": "r2_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "payload_size_bytes": {+ "name": "payload_size_bytes",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "audit_lighthouse_results_audit_id_idx": {+ "name": "audit_lighthouse_results_audit_id_idx",+ "columns": [+ "audit_id"+ ],+ "isUnique": false+ },+ "audit_lighthouse_results_page_id_idx": {+ "name": "audit_lighthouse_results_page_id_idx",+ "columns": [+ "page_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "audit_lighthouse_results_audit_id_audits_id_fk": {+ "name": "audit_lighthouse_results_audit_id_audits_id_fk",+ "tableFrom": "audit_lighthouse_results",+ "tableTo": "audits",+ "columnsFrom": [+ "audit_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "audit_lighthouse_results_page_id_audit_pages_id_fk": {+ "name": "audit_lighthouse_results_page_id_audit_pages_id_fk",+ "tableFrom": "audit_lighthouse_results",+ "tableTo": "audit_pages",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "audit_pages": {+ "name": "audit_pages",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "audit_id": {+ "name": "audit_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status_code": {+ "name": "status_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "redirect_url": {+ "name": "redirect_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "meta_description": {+ "name": "meta_description",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "canonical_url": {+ "name": "canonical_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "robots_meta": {+ "name": "robots_meta",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "og_title": {+ "name": "og_title",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "og_description": {+ "name": "og_description",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "og_image": {+ "name": "og_image",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "h1_count": {+ "name": "h1_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "h2_count": {+ "name": "h2_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "h3_count": {+ "name": "h3_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "h4_count": {+ "name": "h4_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "h5_count": {+ "name": "h5_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "h6_count": {+ "name": "h6_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "heading_order_json": {+ "name": "heading_order_json",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "word_count": {+ "name": "word_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "images_total": {+ "name": "images_total",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "images_missing_alt": {+ "name": "images_missing_alt",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "images_json": {+ "name": "images_json",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "internal_link_count": {+ "name": "internal_link_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "external_link_count": {+ "name": "external_link_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "has_structured_data": {+ "name": "has_structured_data",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "hreflang_tags_json": {+ "name": "hreflang_tags_json",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "is_indexable": {+ "name": "is_indexable",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "x_robots_tag": {+ "name": "x_robots_tag",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "header_canonical_url": {+ "name": "header_canonical_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "crawl_depth": {+ "name": "crawl_depth",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "in_sitemap": {+ "name": "in_sitemap",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "content_hash": {+ "name": "content_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "fetch_class": {+ "name": "fetch_class",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'ok'"+ },+ "response_time_ms": {+ "name": "response_time_ms",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "audit_pages_audit_url_idx": {+ "name": "audit_pages_audit_url_idx",+ "columns": [+ "audit_id",+ "url"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "audit_pages_audit_id_audits_id_fk": {+ "name": "audit_pages_audit_id_audits_id_fk",+ "tableFrom": "audit_pages",+ "tableTo": "audits",+ "columnsFrom": [+ "audit_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "audits": {+ "name": "audits",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "started_by_user_id": {+ "name": "started_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "start_url": {+ "name": "start_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'running'"+ },+ "workflow_instance_id": {+ "name": "workflow_instance_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "config": {+ "name": "config",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "pages_crawled": {+ "name": "pages_crawled",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "pages_total": {+ "name": "pages_total",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "lighthouse_total": {+ "name": "lighthouse_total",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "lighthouse_completed": {+ "name": "lighthouse_completed",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "lighthouse_failed": {+ "name": "lighthouse_failed",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "current_phase": {+ "name": "current_phase",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "'discovery'"+ },+ "error_code": {+ "name": "error_code",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "error_detail": {+ "name": "error_detail",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "failed_phase": {+ "name": "failed_phase",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "started_at": {+ "name": "started_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "completed_at": {+ "name": "completed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "audits_project_id_idx": {+ "name": "audits_project_id_idx",+ "columns": [+ "project_id"+ ],+ "isUnique": false+ },+ "audits_started_by_user_id_idx": {+ "name": "audits_started_by_user_id_idx",+ "columns": [+ "started_by_user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "audits_project_id_projects_id_fk": {+ "name": "audits_project_id_projects_id_fk",+ "tableFrom": "audits",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "sam_sessions": {+ "name": "sam_sessions",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'New chat'"+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "archived_at": {+ "name": "archived_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "sam_sessions_project_updated_idx": {+ "name": "sam_sessions_project_updated_idx",+ "columns": [+ "project_id",+ "updated_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "sam_sessions_project_id_projects_id_fk": {+ "name": "sam_sessions_project_id_projects_id_fk",+ "tableFrom": "sam_sessions",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "sam_sessions_user_id_user_id_fk": {+ "name": "sam_sessions_user_id_user_id_fk",+ "tableFrom": "sam_sessions",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "account": {+ "name": "account",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "account_id": {+ "name": "account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "id_token": {+ "name": "id_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "access_token_expires_at": {+ "name": "access_token_expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "refresh_token_expires_at": {+ "name": "refresh_token_expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "password": {+ "name": "password",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "account_userId_idx": {+ "name": "account_userId_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ },+ "account_accountId_providerId_idx": {+ "name": "account_accountId_providerId_idx",+ "columns": [+ "account_id",+ "provider_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "account_user_id_user_id_fk": {+ "name": "account_user_id_user_id_fk",+ "tableFrom": "account",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "apikey": {+ "name": "apikey",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "config_id": {+ "name": "config_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'default'"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "start": {+ "name": "start",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "prefix": {+ "name": "prefix",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "reference_id": {+ "name": "reference_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "refill_interval": {+ "name": "refill_interval",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "refill_amount": {+ "name": "refill_amount",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_refill_at": {+ "name": "last_refill_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "enabled": {+ "name": "enabled",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": true+ },+ "rate_limit_enabled": {+ "name": "rate_limit_enabled",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": true+ },+ "rate_limit_time_window": {+ "name": "rate_limit_time_window",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": 60000+ },+ "rate_limit_max": {+ "name": "rate_limit_max",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": 120+ },+ "request_count": {+ "name": "request_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": 0+ },+ "remaining": {+ "name": "remaining",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_request": {+ "name": "last_request",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "permissions": {+ "name": "permissions",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "apikey_configId_idx": {+ "name": "apikey_configId_idx",+ "columns": [+ "config_id"+ ],+ "isUnique": false+ },+ "apikey_referenceId_idx": {+ "name": "apikey_referenceId_idx",+ "columns": [+ "reference_id"+ ],+ "isUnique": false+ },+ "apikey_key_idx": {+ "name": "apikey_key_idx",+ "columns": [+ "key"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "invitation": {+ "name": "invitation",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'pending'"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"+ },+ "inviter_id": {+ "name": "inviter_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "invitation_organizationId_idx": {+ "name": "invitation_organizationId_idx",+ "columns": [+ "organization_id"+ ],+ "isUnique": false+ },+ "invitation_email_idx": {+ "name": "invitation_email_idx",+ "columns": [+ "email"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "invitation_organization_id_organization_id_fk": {+ "name": "invitation_organization_id_organization_id_fk",+ "tableFrom": "invitation",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "invitation_inviter_id_user_id_fk": {+ "name": "invitation_inviter_id_user_id_fk",+ "tableFrom": "invitation",+ "tableTo": "user",+ "columnsFrom": [+ "inviter_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "member": {+ "name": "member",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'member'"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "member_organizationId_idx": {+ "name": "member_organizationId_idx",+ "columns": [+ "organization_id"+ ],+ "isUnique": false+ },+ "member_userId_idx": {+ "name": "member_userId_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ },+ "member_organizationId_userId_uidx": {+ "name": "member_organizationId_userId_uidx",+ "columns": [+ "organization_id",+ "user_id"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "member_organization_id_organization_id_fk": {+ "name": "member_organization_id_organization_id_fk",+ "tableFrom": "member",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "member_user_id_user_id_fk": {+ "name": "member_user_id_user_id_fk",+ "tableFrom": "member",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "organization": {+ "name": "organization",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "logo": {+ "name": "logo",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "organization_slug_unique": {+ "name": "organization_slug_unique",+ "columns": [+ "slug"+ ],+ "isUnique": true+ },+ "organization_slug_uidx": {+ "name": "organization_slug_uidx",+ "columns": [+ "slug"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "session": {+ "name": "session",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ip_address": {+ "name": "ip_address",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "user_agent": {+ "name": "user_agent",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "active_organization_id": {+ "name": "active_organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "session_token_unique": {+ "name": "session_token_unique",+ "columns": [+ "token"+ ],+ "isUnique": true+ },+ "session_userId_idx": {+ "name": "session_userId_idx",+ "columns": [+ "user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "session_user_id_user_id_fk": {+ "name": "session_user_id_user_id_fk",+ "tableFrom": "session",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "user": {+ "name": "user",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "email_verified": {+ "name": "email_verified",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "image": {+ "name": "image",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"+ },+ "analytics_opted_out": {+ "name": "analytics_opted_out",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_active_organization_id": {+ "name": "last_active_organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "user_email_unique": {+ "name": "user_email_unique",+ "columns": [+ "email"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "verification": {+ "name": "verification",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "identifier": {+ "name": "identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"+ }+ },+ "indexes": {+ "verification_identifier_idx": {+ "name": "verification_identifier_idx",+ "columns": [+ "identifier"+ ],+ "isUnique": false+ },+ "verification_expiresAt_idx": {+ "name": "verification_expiresAt_idx",+ "columns": [+ "expires_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "billing_customer_status": {+ "name": "billing_customer_status",+ "columns": {+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "is_paying": {+ "name": "is_paying",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "paid_plan_id": {+ "name": "paid_plan_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "paid_plan_status": {+ "name": "paid_plan_status",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "customer_json": {+ "name": "customer_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "synced_at": {+ "name": "synced_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "billing_customer_status_organization_id_organization_id_fk": {+ "name": "billing_customer_status_organization_id_organization_id_fk",+ "tableFrom": "billing_customer_status",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "ga4_connections": {+ "name": "ga4_connections",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "property_id": {+ "name": "property_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "property_display_name": {+ "name": "property_display_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "property_time_zone": {+ "name": "property_time_zone",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "property_currency_code": {+ "name": "property_currency_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "connected_by_user_id": {+ "name": "connected_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ga4_account_id": {+ "name": "ga4_account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "connected_account_email": {+ "name": "connected_account_email",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "ga4_connections_project_idx": {+ "name": "ga4_connections_project_idx",+ "columns": [+ "project_id"+ ],+ "isUnique": true+ },+ "ga4_connections_organization_idx": {+ "name": "ga4_connections_organization_idx",+ "columns": [+ "organization_id"+ ],+ "isUnique": false+ },+ "ga4_connections_connector_idx": {+ "name": "ga4_connections_connector_idx",+ "columns": [+ "connected_by_user_id",+ "ga4_account_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "ga4_connections_project_id_projects_id_fk": {+ "name": "ga4_connections_project_id_projects_id_fk",+ "tableFrom": "ga4_connections",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "ga4_connections_organization_id_organization_id_fk": {+ "name": "ga4_connections_organization_id_organization_id_fk",+ "tableFrom": "ga4_connections",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "gsc_connections": {+ "name": "gsc_connections",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "site_url": {+ "name": "site_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "connected_by_user_id": {+ "name": "connected_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "gsc_account_id": {+ "name": "gsc_account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "connected_account_email": {+ "name": "connected_account_email",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(current_timestamp)"+ }+ },+ "indexes": {+ "gsc_connections_project_idx": {+ "name": "gsc_connections_project_idx",+ "columns": [+ "project_id"+ ],+ "isUnique": true+ },+ "gsc_connections_organization_idx": {+ "name": "gsc_connections_organization_idx",+ "columns": [+ "organization_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "gsc_connections_project_id_projects_id_fk": {+ "name": "gsc_connections_project_id_projects_id_fk",+ "tableFrom": "gsc_connections",+ "tableTo": "projects",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "gsc_connections_organization_id_organization_id_fk": {+ "name": "gsc_connections_organization_id_organization_id_fk",+ "tableFrom": "gsc_connections",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "telemetry_state": {+ "name": "telemetry_state",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false,+ "default": 1+ },+ "install_id": {+ "name": "install_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "installed_at": {+ "name": "installed_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_heartbeat_at": {+ "name": "last_heartbeat_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_version": {+ "name": "last_version",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "mcp_tool_call_count": {+ "name": "mcp_tool_call_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ }+ },+ "views": {},+ "enums": {},+ "_meta": {+ "schemas": {},+ "tables": {},+ "columns": {}+ },+ "internal": {+ "indexes": {}+ }+}\ No newline at end of filediff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.jsonindex 705de0a8..75785080 100644--- a/drizzle/meta/_journal.json+++ b/drizzle/meta/_journal.json@@ -330,6 +330,13 @@"when": 1788651415740,"tag": "0046_plain_the_watchers","breakpoints": true+ },+ {+ "idx": 47,+ "version": "6",+ "when": 1789455135151,+ "tag": "0047_reports",+ "breakpoints": true}]}\ No newline at end of filediff --git a/plugins/openseo/README.md b/plugins/openseo/README.mdindex 279d2af2..0db3d4f9 100644--- a/plugins/openseo/README.md+++ b/plugins/openseo/README.md@@ -13,7 +13,7 @@ OpenSEO gives your agent real SEO data and guided workflows, so its advice is gr- Track organic and Google Maps rankings- Work with Google Search Console and Analytics data-The plugin includes nine skills that guide Cursor through complete SEO workflows, plus the hosted OpenSEO MCP server for live data and project management.+The plugin includes ten skills that guide Cursor through complete SEO workflows, plus the hosted OpenSEO MCP server for live data and project management.## Connect@@ -40,6 +40,7 @@ You need an OpenSEO account. The plugin package is free and open source. Hosted- SEO audit- SEO coach- SEO project setup+- SEO report## Linksdiff --git a/plugins/openseo/skills/competitive-landscape/SKILL.md b/plugins/openseo/skills/competitive-landscape/SKILL.mdindex 0036b9d5..22f9a707 100644--- a/plugins/openseo/skills/competitive-landscape/SKILL.md+++ b/plugins/openseo/skills/competitive-landscape/SKILL.md@@ -27,6 +27,10 @@ The project-context tools are free and shared with the app and other agents.3. Before spending credits, check the research log. If the same research ran within the last 30 days, reuse that result and say so instead of re-buying it.4. On finish, write back what is durable with `update_project_context` — every confirmed competitor via `addCompetitors` with a short note on why they matter, plus `removeCompetitors` for entries you added that turned out irrelevant (leave rows the user added alone) — and append a research log entry: `{ appendResearchLog: { summary: "Competitive landscape: <market/query set>. Verdict: <conclusion>" } }`.+## Deliver as a report++Deliver through the `seo-report` skill, saving with `skill: "competitive-landscape"`. If that skill is not available, say so and stop before writing HTML.+## OpenSEO MCP tools- `research_keywords`: discover representative market queries.@@ -61,24 +65,16 @@ The project-context tools are free and shared with the app and other agents.## Output format-Start with the market read:--- Market leaders-- Most winnable opportunity area-- Biggest barrier to ranking--Then include:--| Domain | Type | Why they matter | Organic footprint | Winning themes | Weakness/gap |-| ------ | ---- | --------------- | ----------------- | -------------- | ------------ |+`h1`: the market or category.-Add:+Sections in this order:-- Query set used-- Content formats that are working-- Keyword/theme gaps-- Backlink or authority observations-- Recommended next workflows: competitor analysis, keyword clustering, or content brief+1. **The market read** — one or two opening sentences naming the leaders, the most winnable area, and the biggest barrier.+2. **Who is winning** — a table of domain, type, organic footprint, winning themes, and the gap. Label domain types explicitly.+3. **Why they win** — one finding per pattern, the Fix pointing at what the user should do instead.+4. **Gaps and openings** — a table of theme, demand, and who currently owns it, plus a bar chart when a handful of themes carry the demand.+5. **What to do next** — an ordered list ending in the next workflow to run: competitor analysis, keyword clustering, or a content brief.+6. **Method** — the query set used, and a note calling the read directional when the query set was small.## Guardrailsdiff --git a/plugins/openseo/skills/competitor-analysis/SKILL.md b/plugins/openseo/skills/competitor-analysis/SKILL.mdindex f84f5d78..e77bf8bc 100644--- a/plugins/openseo/skills/competitor-analysis/SKILL.md+++ b/plugins/openseo/skills/competitor-analysis/SKILL.md@@ -27,6 +27,10 @@ The project-context tools are free and shared with the app and other agents.3. Before spending credits, check the research log. If the same research ran within the last 30 days, reuse that result and say so instead of re-buying it.4. On finish, write back what is durable with `update_project_context` — an `addCompetitors` upsert for this domain with a short note on its strengths and where it is vulnerable — and append a research log entry: `{ appendResearchLog: { summary: "Competitor analysis: <domain>. Verdict: <conclusion>" } }`.+## Deliver as a report++Deliver through the `seo-report` skill, saving with `skill: "competitor-analysis"`. If that skill is not available, say so and stop before writing HTML.+## OpenSEO MCP tools- `get_domain_overview`: baseline organic traffic and keyword count.@@ -63,24 +67,17 @@ The project-context tools are free and shared with the app and other agents.## Output format-Start with:--- Competitor snapshot-- Biggest lesson-- Best opportunity to beat them--Then include:--| Area | Competitor pattern | Evidence | OpenSEO opportunity |-| ---- | ------------------ | -------- | ------------------- |+`h1`: the competitor domain.-Include sections for:+Sections in this order:-- Top keyword themes-- Content/page types working for them-- Backlink/authority notes-- Head-to-head SERP observations-- Priority actions for the user+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.+2. **The biggest lesson** — one finding.+3. **Where they are vulnerable** — one finding per opening, ordered by how winnable it is.+4. **Keyword themes** — a table of theme, example keywords, volume, and whether the user competes there. A bar chart when a few themes dominate the footprint.+5. **Content patterns and authority** — prose, with a note for anything inferred from keyword rows rather than seen on a page.+6. **What to do next** — an ordered list, shortest useful.+7. **Method** — which tools reported what, and what you checked yourself.## Guardrailsdiff --git a/plugins/openseo/skills/keyword-clustering/SKILL.md b/plugins/openseo/skills/keyword-clustering/SKILL.mdindex 84ac92b0..199d51d1 100644--- a/plugins/openseo/skills/keyword-clustering/SKILL.md+++ b/plugins/openseo/skills/keyword-clustering/SKILL.md@@ -26,6 +26,10 @@ The project-context tools are free and shared with the app and other agents.3. Before spending credits, check the research log. If the same research ran within the last 30 days, reuse that result and say so instead of re-buying it.4. On finish, write back what is durable with `update_project_context` — new or corrected `addKeyPages` entries with the topic each page now targets — and append a research log entry: `{ appendResearchLog: { summary: "Keyword clustering: <keyword set>. Verdict: <conclusion>" } }`.+## Deliver as a report++Deliver through the `seo-report` skill, saving with `skill: "keyword-clustering"`. If that skill is not available, say so and stop before writing HTML.+## OpenSEO MCP tools- `list_saved_keywords`: fetch an existing keyword set, optionally filtered by tags.@@ -57,25 +61,16 @@ The project-context tools are free and shared with the app and other agents.## Output format-Start with a short mapping summary:--- Number of clusters-- Pages to create-- Existing pages to update-- Cannibalization or consolidation issues--Then include:--| Cluster | Primary keyword | Secondary keywords | Intent | Target page | Priority | Notes |-| ------- | --------------- | ------------------ | ------ | ----------- | -------- | ----- |+`h1`: the site or keyword set.-For each cluster, include a recommended page brief:+Sections in this order:-- Page type-- Searcher problem-- Required sections-- Internal-link opportunities-- Save/tag suggestion+1. **The map** — one or two opening sentences: how many clusters, how many pages to create, how many to update, and any cannibalization found.+2. **Clusters** — a table of cluster, primary keyword, intent, target page, and priority. Keep secondary keywords in the per-cluster briefs, not in this table.+3. **Page briefs** — one finding per cluster: the page type and the searcher's problem, then the page to create or update. List required sections and internal links underneath.+4. **Cannibalization** — a table of the query, the competing URLs, and which one to keep, only when there is real evidence for it.+5. **What to do next** — an ordered list, including the tag suggestions and the explicit ask before applying them.+6. **Method** — where the keywords came from, and a note labelling target pages as proposed when no URL data was supplied.## Guardrailsdiff --git a/plugins/openseo/skills/keyword-research/SKILL.md b/plugins/openseo/skills/keyword-research/SKILL.mdindex 23918fc8..f65b5d48 100644--- a/plugins/openseo/skills/keyword-research/SKILL.md+++ b/plugins/openseo/skills/keyword-research/SKILL.md@@ -26,6 +26,10 @@ The project-context tools are free and shared with the app and other agents.3. Before spending credits, check the research log. If the same research ran within the last 30 days, reuse that result and say so instead of re-buying it.4. On finish, write back what is durable — a sharpened `business_overview` or `current_goal`, competitors that kept appearing in the SERPs via `addCompetitors`, pages the keywords should land on via `addKeyPages` — and append a research log entry: `{ appendResearchLog: { summary: "Keyword research: <seeds/market>. Verdict: <conclusion>" } }`.+## Deliver as a report++Deliver through the `seo-report` skill, saving with `skill: "keyword-research"`. If that skill is not available, say so and stop before writing HTML.+## OpenSEO MCP tools- `research_keywords`: primary discovery tool. Use 1-5 seeds per call and prefer 150 results unless the user asks for exhaustive research.@@ -58,19 +62,17 @@ The project-context tools are free and shared with the app and other agents.## Output format-Start with the highest-signal recommendation:--- Best opportunity theme-- Top keywords to target now-- Keywords to save-- Risks or SERP caveats--Then include a compact table:+`h1`: the site or topic.-| Keyword | Intent | Volume | KD | CPC | Priority | Notes |-| ------- | ------ | -----: | --: | --: | -------- | ----- |+Sections in this order:-End with next actions, including whether to run keyword clustering, create a content brief, or save the chosen keywords.+1. **The opportunity** — one or two opening sentences naming the best theme and why the site can win it now.+2. **Target these now** — a table of keyword, intent, volume, KD, CPC, and the page to make. Add a bar chart comparing the volumes of the shortlist.+3. **Why these** — one finding per keyword that needs justifying: the SERP or metric evidence, then the page to build.+4. **The longer opportunity list** — a second table, same columns.+5. **Risks and caveats** — notes: SERP intent that would change the recommendation, missing metrics written as `unknown`, close-variant volumes that are one bucket rather than several.+6. **What to do next** — an ordered list, including whether to run keyword clustering, write a content brief, or save the chosen keywords.+7. **Method** — which tools returned what.## Guardrailsdiff --git a/plugins/openseo/skills/link-prospecting/SKILL.md b/plugins/openseo/skills/link-prospecting/SKILL.mdindex 6858211c..463606e2 100644--- a/plugins/openseo/skills/link-prospecting/SKILL.md+++ b/plugins/openseo/skills/link-prospecting/SKILL.md@@ -26,6 +26,10 @@ The project-context tools are free and shared with the app and other agents.3. Before spending credits, check the research log. If the same research ran within the last 30 days, reuse that result and say so instead of re-buying it.4. On finish, write back what is durable — the linkable asset via `addKeyPages`, any competitor whose backlink profile proved useful via `addCompetitors` — and append a research log entry: `{ appendResearchLog: { summary: "Link prospecting: <asset/target page>. Verdict: <conclusion>" } }`.+## Deliver as a report++Deliver through the `seo-report` skill, saving with `skill: "link-prospecting"`. If that skill is not available, say so and stop before writing HTML.+## OpenSEO MCP tools- `get_serp_results`: find ranking articles, listicles, resource pages, comparisons, and topical publishers.@@ -90,22 +94,17 @@ Use `get_serp_results` in batches for the most relevant patterns. Send at most 1## Output format-Start with:--- Best outreach angle-- Highest-priority prospect type-- Any data limitations--Then include:--| Prospect URL | Site/domain | Source | Relevance | Suggested angle | Contact path | Priority |-| ------------ | ----------- | ------ | --------- | --------------- | ------------ | -------- |+`h1`: the linkable asset.-Then provide 2-3 reusable outreach drafts:+Sections in this order:-- Resource/list inclusion-- Article update/reference suggestion-- Competitor alternative/comparison angle+1. **The angle** — one or two opening sentences naming the best outreach angle and the prospect type to work first.+2. **Prospects** — a table of prospect URL, site, source, suggested angle, contact path, and priority. Keep it under about eight columns; drop the ones that add nothing for this run.+3. **Why these** — one finding per prospect worth explaining: the evidence that they link to things like this, then the exact ask.+4. **Outreach drafts** — the message text for each of two or three reusable angles: resource or list inclusion, an article update, and a comparison mention.+5. **Limitations** — notes: contact paths not found, prospects that are direct competitors or likely paid placements, and which source found each contact detail.+6. **What to do next** — an ordered list: who to send to first, and in what order.+7. **Method** — which tools returned prospects and which came from the web or the browser.## Guardrailsdiff --git a/plugins/openseo/skills/local-seo/SKILL.md b/plugins/openseo/skills/local-seo/SKILL.mdindex d74fae91..88e5f37d 100644--- a/plugins/openseo/skills/local-seo/SKILL.md+++ b/plugins/openseo/skills/local-seo/SKILL.md@@ -27,6 +27,10 @@ The project-context tools are free and shared with the app and other agents.3. Before spending credits, check the research log. If the same research ran within the last 30 days, reuse that result and say so instead of re-buying it.4. On finish, write back what is durable with `update_project_context` — local competitors that have a website via `addCompetitors` (competitor rows are keyed by domain, so skip listings without one), a corrected `business_overview` — and append a research log entry: `{ appendResearchLog: { summary: "Local SEO: <business> near <area>. Verdict: <conclusion>" } }`.+## Deliver as a report++Deliver through the `seo-report` skill, saving with `skill: "local-seo"`. If that skill is not available, say so and stop before writing HTML.+## OpenSEO MCP tools- `search_local_businesses`: nearby listings, filterable by `minRating`, `minReviews`, and `isClaimed` — use `isClaimed: false` to find unclaimed listings when prospecting. One call with the brand name as `query` and a wide radius returns category, rating, review count, claimed status, coordinates, and `cid` for every location of a chain — usually enough that per-location `get_business_profile` calls are unnecessary.@@ -58,18 +62,17 @@ Always build the profile snapshot table for the whole chain — one `search_loca## Output format-Start with:--- Profile snapshot (category, rating, reviews, claimed) — one row per location for chains-- Where visibility drops off, per the grid-- The one fix to do this week--Then include:+`h1`: the business name.-| Signal | This business | Best competitor | Gap | Action |-| ------ | ------------- | --------------- | --- | ------ |+Sections in this order:-Cover: categories, reviews (count, recency, owner replies), hours and profile completeness, listing website links, Maps coverage from the grid, Q&A and posting hygiene.+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.+2. **The one fix** — one finding. Category and claim problems outrank posting cadence every time.+3. **Head to head** — a table of signal, this business, the best competitor, and the gap. Cover categories, reviews (count, recency, owner replies), hours and profile completeness, and the listing's website link.+4. **Maps coverage** — what the grid shows, where visibility drops off, and who wins there. A bar chart of ranks by direction reads faster than a paragraph; label every value.+5. **Q&A and posting** — only when the basics are already competitive.+6. **What to do next** — an ordered list.+7. **Method** — which tools returned what, plus a note reading each missing grid rank against that point's `resultsCount` rather than calling it invisibility.## Guardrailsdiff --git a/plugins/openseo/skills/seo-audit/SKILL.md b/plugins/openseo/skills/seo-audit/SKILL.mdindex afe4a2ba..553d6ade 100644--- a/plugins/openseo/skills/seo-audit/SKILL.md+++ b/plugins/openseo/skills/seo-audit/SKILL.md@@ -25,6 +25,10 @@ The project-context tools are free and shared with the app and other agents.3. Before spending credits, check the research log. If the same research ran within the last 30 days, reuse that result and say so instead of re-buying it.4. On finish, write back what is durable — a corrected `business_overview`, the pages the report singles out via `addKeyPages` — and append a research log entry: `{ appendResearchLog: { summary: "Site audit: <domain>. Verdict: <conclusion>" } }`.+## Deliver as a report++Deliver through the `seo-report` skill, saving with `skill: "seo-audit"`. If that skill is not available, say so and stop before writing HTML.+## OpenSEO MCP tools- `whoami`: confirm connection and remaining credits before spending anything. If OpenSEO is not connected, stop and ask the user to connect it.@@ -49,18 +53,24 @@ Keep total spend modest: one audit, one backlinks overview, at most one domain o- Blocked or noindexed pages: remove the block.It must be doable this week by a non-technical person, with copy-paste-ready mechanics included.7. When the site is healthy, propose a starting focus area: run one `research_keywords` call seeded from the site's actual topic, then pick one theme and 3 to 5 specific, low-difficulty keywords the site can realistically rank for, each with the page or post to make. This is a starting direction, not a keyword strategy; point the user at the `keyword-research` skill for the full workflow. Skip this step entirely when the site is down — the one thing is all that matters there.-8. Write the report using `template.html` in this skill directory (see Output format).-9. Review before delivering: run an adversarial pass with a second agent or model if your environment has one, otherwise do a fresh self-review. Give the reviewer the verified facts and have it attack four things: claims beyond the facts, unglossed jargon, anything overwhelming for a beginner, and dramatic language. The reviewer may also flag true facts it was not given; check those against your evidence instead of "fixing" them.-10. Deliver the report: if your environment can publish or preview HTML (for example as an artifact), do that; otherwise save the HTML file and tell the user to open it in their browser.+8. Review before delivering: run an adversarial pass with a second agent or model if your environment has one, otherwise do a fresh self-review. Give the reviewer the verified facts and have it attack four things: claims beyond the facts, unglossed jargon, anything overwhelming for a beginner, and dramatic language. The reviewer may also flag true facts it was not given; check those against your evidence instead of "fixing" them.+9. Write and save the report through the `seo-report` skill (see Output format).## Output format-Use `template.html` next to this file. Fill in content; keep the CSS and structure as they are (light palette only, no dark mode).+`h1`: the domain. Then one or two opening sentences: the overall state and the one thing.++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.+2. **Top priority** — one finding, with copy-paste-ready mechanics.+3. **Small fixes** — one finding each, 5 to 10 max, ordered by impact. Each shows the exact evidence: a quoted tag, a number, or a URL.+4. **Where to focus first** (healthy sites only) — one sentence, then a table of 3 to 5 keywords with volume and difficulty and the page or post to make for each, plus a bar chart when the volumes are worth comparing. Omit the whole section when the site is down.+5. **What's working now** — a short list.+6. **What to do next** — an ordered list, the one thing first.+7. **Method** — what the tools reported and what you verified by hand.-- Header: domain as the title, the review date on its own line under it, then a 2-3 sentence summary of the whole report (overall state; the main gap and the one thing; what the report covers).-- Section order: verdict, the one thing, small fixes (5 to 10 max, ordered by impact), where to focus first (healthy sites only), already working, method footer.-- Each fix row shows the exact evidence (a quoted tag or number) and concrete steps a non-technical person can follow.-- "Where to focus first" names one topic area and 3 to 5 keywords, each with its search volume in plain words and the page or post to make. Omit the section when the site is down.+Use a note for anything you could not verify or where the site's goal makes a standard recommendation the wrong call.## Guardrailsdiff --git a/plugins/openseo/skills/seo-audit/template.html b/plugins/openseo/skills/seo-audit/template.htmldeleted file mode 100644index 933e897d..00000000--- a/plugins/openseo/skills/seo-audit/template.html+++ /dev/null@@ -1,136 +0,0 @@-<!-- SEO audit report template.- Replace ALL-CAPS placeholders and the example rows/items. Keep the CSS and structure.- If your agent publishes HTML through a pipeline that adds its own document wrapper- (for example an artifact viewer), strip this comment and the doctype/head/body tags;- as a standalone file opened in a browser, keep everything. -->-<!doctype html>-<html lang="en">-<head>-<meta charset="utf-8">-<meta name="viewport" content="width=device-width, initial-scale=1">-<title>DOMAIN SEO review</title>-<style>- :root {- --bg: #e2e9f3;- --ink: #122650;- --muted: #4f5f79;- --rule: #c2cddd;- --rule-strong: #122650;- }- html { background: var(--bg); color-scheme: light; }- body {- background: var(--bg); color: var(--ink);- font-family: Charter, Georgia, "Times New Roman", serif;- line-height: 1.55; margin: 0; padding: 3.5rem 1.5rem 5rem;- }- .page { max-width: 860px; margin: 0 auto; }- .mono {- font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;- font-size: 0.72rem; letter-spacing: 0.06em; text-transform: uppercase; color: var(--muted);- }- h1 {- font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;- font-weight: 700; font-size: 1.6rem; letter-spacing: -0.01em;- margin: 0.75rem 0 0.25rem; text-wrap: balance;- }- .subtitle { color: var(--muted); margin: 0 0 2.5rem; font-size: 1.02rem; max-width: 46rem; }- .dateline { color: var(--muted); font-size: 0.92rem; margin: 0 0 1.1rem; }- h2 {- font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;- font-weight: 700; font-size: 1.25rem; margin: 3rem 0 0.75rem;- }- .lede { font-size: 1.05rem; max-width: 46rem; }- section > p { max-width: 46rem; }- hr.heavy { border: 0; border-top: 2px solid var(--rule-strong); margin: 3rem 0 0; }- section .cols:first-of-type { border-top: 1px solid var(--rule); }- .cols {- display: grid; grid-template-columns: minmax(180px, 5fr) 8fr;- gap: 1.25rem; padding: 0.6rem 0; border-bottom: 1px solid var(--rule);- }- .row-title { font-size: 1.12rem; margin: 0; }- .row-title .tag { display: block; margin-top: 0.35rem; }- .cols > div p { margin: 0 0 0.6rem; color: var(--muted); font-size: 0.95rem; }- .cols > div p:last-child { margin-bottom: 0; }- .cols > div p.fix { color: var(--ink); }- .fix b { font-weight: 600; }- code {- font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;- font-size: 0.85em; word-break: break-word;- }- ol { padding-left: 1.3rem; max-width: 44rem; }- ol li { margin-bottom: 0.5rem; }- ul.plain { list-style: none; padding: 0; max-width: 46rem; }- ul.plain li { padding: 0.5rem 0; border-bottom: 1px solid var(--rule); font-size: 0.98rem; }- ul.plain li:first-child { border-top: 1px solid var(--rule); }- ul.plain .why { color: var(--muted); }- footer { margin-top: 4rem; color: var(--muted); font-size: 0.88rem; max-width: 46rem; }- @media (max-width: 620px) {- .cols { grid-template-columns: 1fr; gap: 0.4rem; }- }-</style>-</head>-<body>-<div class="page">- <header>- <h1>DOMAIN</h1>- <p class="dateline">DATE</p>- <p class="subtitle">SUMMARY: 2-3 sentences covering the whole report. Sentence 1: overall state of the site. Sentence 2: the main gap and the one thing. Sentence 3: what the report covers.</p>- </header>-- <section>- <h2>Where the site stands</h2>- <p class="lede">VERDICT-PARAGRAPH: what is working, in plain words.</p>- <p class="lede">VERDICT-PARAGRAPH-2: the main gap the one thing addresses.</p>- </section>-- <hr class="heavy">-- <section>- <h2>If you only do one thing</h2>- <p class="lede">THE-ONE-THING, one sentence.</p>- <p>WHY-IT-MATTERS, one or two sentences.</p>- <ol>- <li>STEP-1 (concrete, doable today).</li>- <li>STEP-2 (include any copy-paste message in <i>italics</i>).</li>- <li>STEP-3 (how to check it worked).</li>- </ol>- </section>-- <section>- <h2>Small fixes, in order</h2>- <!-- one .cols block per finding; 5-10 max; tag = severity word only where literally true -->- <div class="cols">- <div><p class="row-title">FINDING-TITLE <span class="mono tag">low</span></p></div>- <div>- <p>WHAT-WE-FOUND with the exact evidence, e.g. a quoted tag in <code>code</code>.</p>- <p class="fix"><b>Fix:</b> CONCRETE-STEPS a non-technical person can follow.</p>- </div>- </div>- </section>-- <section>- <h2>Where to focus first</h2>- <!-- healthy sites only: omit this whole section when the site is down -->- <p>FOCUS-INTRO: the one topic area to build toward and why it fits this site.</p>- <div class="cols">- <div><p class="row-title">KEYWORD <span class="mono tag">N searches/mo</span></p></div>- <div>- <p>WHY-THIS-KEYWORD: who searches it and how winnable it is, in plain words.</p>- <p class="fix"><b>Make:</b> WHAT-TO-CREATE, one page or post and its angle.</p>- </div>- </div>- </section>-- <section>- <h2>Already working</h2>- <ul class="plain">- <li>GOOD-THING. <span class="why">Why it matters, one clause.</span></li>- </ul>- </section>-- <footer>- <p>Reviewed DATE. DATA-SOURCES, e.g.: crawl and backlink data from OpenSEO; every page also fetched and reviewed individually.</p>- </footer>-</div>-</body>-</html>diff --git a/plugins/openseo/skills/seo-coach/SKILL.md b/plugins/openseo/skills/seo-coach/SKILL.mdindex 0da5cf8a..7f32639d 100644--- a/plugins/openseo/skills/seo-coach/SKILL.md+++ b/plugins/openseo/skills/seo-coach/SKILL.md@@ -55,6 +55,7 @@ Good starting points:- `competitor-analysis`: studies one competitor's keywords, content themes, backlink profile, and gaps.- `local-seo`: audits a Google Business Profile against local competitors and maps Maps visibility around a location.- `link-prospecting`: finds likely link opportunities, discovers contact paths, and drafts outreach.+- `seo-report`: the report-writing skill the workflows above deliver through. It carries the starter template and the save rules; users do not run it on its own.## Tool coaching@@ -64,8 +65,9 @@ Explain the difference between data sources:- Google Search Console (when connected on the project's Integrations page) is the user's own first-party data — real clicks, impressions, CTR, and position. Read it live with `get_search_console_performance` instead of asking for CSV exports. It's free (no credits) and the best starting point for "what already ranks" and near-ranking opportunities.- Web search can find current market context, recent pages, reviews, docs, social profiles, and contact paths outside OpenSEO.- Browser/page scraping can extract page copy, headings, author names, contact links, schema, and content structure.-- Project context (`get_project_context` / `update_project_context`) is the project's shared memory: business, goal, positioning, writing preferences, competitors, key pages, and a research log. It is free, every skill reads it, and the user can edit it on the project's Context settings page.-- Local files are for file work: GSC CSVs, crawls, drafts, briefs, and reports.+- Project context (`get_project_context` / `update_project_context`) is the project's shared memory: business, goal, positioning, writing preferences, competitors, key pages, and a research log. It is free, every skill reads it, and the user can edit it on the project's Context page (in the sidebar under AI).+- Local files are for file work: GSC CSVs, crawls, and drafts.+- Reports are where finished work lives: each workflow saves its deliverable to the project's Reports page as an HTML page anyone on the team can open and print. Before starting a workflow, call `list_reports` to see what already exists and point the user at it instead of re-running research they already paid for.Encourage the user to keep project knowledge in project context rather than in a local file, so it follows them across sessions and agents.diff --git a/plugins/openseo/skills/seo-project-setup/SKILL.md b/plugins/openseo/skills/seo-project-setup/SKILL.mdindex ce623924..8ef9b34a 100644--- a/plugins/openseo/skills/seo-project-setup/SKILL.md+++ b/plugins/openseo/skills/seo-project-setup/SKILL.md@@ -7,7 +7,7 @@ description: Populate a project's shared OpenSEO context — site scope, goals,## Goal-Interview the user once about one website or SEO project, and store the answers in that project's shared context in OpenSEO with `update_project_context`. That context is read by every other skill, by SAM in the app, and by the user on the project's Context settings page — so it survives new sessions, new machines, and new agents. This is a context setup workflow, not a full audit.+Interview the user once about one website or SEO project, and store the answers in that project's shared context in OpenSEO with `update_project_context`. That context is read by every other skill, by SAM in the app, and by the user on the project's Context page (in the sidebar under AI) — so it survives new sessions, new machines, and new agents. This is a context setup workflow, not a full audit.## Tone@@ -183,7 +183,7 @@ Then summarize:- Sections still missing from project context- Recommended next workflow-Tell the user they can read and edit everything saved here on the project's Context settings page.+Tell the user they can read and edit everything saved here on the project's Context page, in the sidebar under AI.## Guardrailsdiff --git a/plugins/openseo/skills/seo-report/SKILL.md b/plugins/openseo/skills/seo-report/SKILL.mdnew file mode 100644index 00000000..698a9fc1--- /dev/null+++ b/plugins/openseo/skills/seo-report/SKILL.md@@ -0,0 +1,221 @@+---+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."+---++# OpenSEO Report++## Goal++Turn finished research into one self-contained HTML page, saved to the project with `save_report`, so anyone on the team can open it in the app, read it on a phone, and print it to PDF.++Every OpenSEO skill that produces a recommendation delivers through this skill. Chat gets the link, the verdict, and the top action. The report gets everything else.++## Before you write++1. Call `list_reports` for the project. If a report already covers the same subject for the same period, you are correcting your own run: pass its `reportId` to `save_report` and replace it. A new month, a new competitor, or a different skill is a new report. Never save a near-duplicate.+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.++## 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.+- **Be specific and numeric.** "Position 4.6, one click on 1,085 impressions" beats "underperforming". Every claim carries the number, the quoted tag, or the URL that proves it.+- **Be honest about confidence.** Say which numbers came from a tool and which you verified yourself. When you could not check something, put it in a `.note` and say so.+- **Plain language.** Gloss every term of art on first use: canonical, meta description, crawler, 301, structured data. No drama words, no exclamation points, no filler.+- **One report, one spine.** Lead with the verdict, then the single most important action, then the supporting detail. A report with twenty findings has failed.+- **Print the numbers.** A chart never carries a value that is not also written out in text.++## Title and summary++- `title`: names the subject and the period, under 120 characters. "badseo.dev SEO audit, Sep 2026". Never "SEO Report" or "Analysis".+- `summary`: markdown under 2,500 characters, in this order — the verdict, the single top action, then the key numbers. This is what `list_reports` returns and what you or another agent read instead of the HTML, so write it for a reader who will never open the page.++## HTML constraints++These are enforced by the viewer, not by taste. A report that breaks them renders blank or broken.++- **No external resources of any kind.** No web fonts, no CDN scripts or stylesheets, no images by URL, no `fetch`. Every request from a saved report is blocked. Inline all CSS in one `<style>` block.+- **Links open in a new tab.** Write every link as `<a href="..." target="_blank" rel="noopener">`. A plain link would navigate the report frame itself, replacing the report with a broken copy of the target. The exception is an in-page anchor (`href="#id"`, as in the contents rail), which stays in the document.+- **No `<script>`.** Scripts are blocked outright. Anything interactive has to be static.+- **Charts are inline SVG or CSS bars**, with real `<text>` labels and a `viewBox`. Always print the numbers next to the chart too.+- **Aim under 80 KB.** The hard cap is 500,000 bytes, and the error says "the limit is 500 KB". Inlined images are the usual way people blow it. A filled report is normally 10-30 KB.+- **No backticks and no `${` anywhere in the HTML.** Codex passes the argument through a JavaScript template literal, where both are syntax. Use `<code>` for inline code and plain text everywhere else.+- **Finish the document.** The server rejects HTML that does not end with `</html>` as "stopped early". Write the whole page in one call rather than trailing off mid-section.+- **Keep the doctype, `<html>`, `<head>`, and `<title>`.** The app renders the whole document you save, not a fragment.++## After you save++- `save_report` returns `{ reportId, url, htmlBytes }`. The whole reply is at most three short bullets, then the link last on its own line as `Read the full report: <url>`. The bullets: the verdict, the top action, and anything the user has to act on (a project you created, a question you need answered). Nothing else: no account of the run, no reviewer notes, no list of what worked, no restating the report. The report is how they learn; chat only points at it.+- The skill you are running appends its own research-log line; add one only if it does not: `{ appendResearchLog: { summary: "Report: <title>. Verdict: <conclusion>" } }`.+- If the save fails, the error names the limit and the value. Fix that one thing and save again. Never paste the report into chat instead.++## Starter template++Copy this, keep the CSS as it is, and replace the ALL-CAPS placeholders. Each primitive shows one example row; repeat the ones you need and delete the ones you do not.++```html+<!doctype html>+<html lang="en"><head><meta charset="utf-8">+<meta name="viewport" content="width=device-width,initial-scale=1">+<title>DOMAIN — REPORT TITLE</title>+<style>+/* One light look, on screen and on paper. The report is read inside the app,+ which has its own theme toggle, and a saved document has no way to hear about+ it: a report that follows the OS scheme alone shows a black panel inside a+ light 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}+*{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;+ font-family:Geist,-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;-webkit-font-smoothing:antialiased}+.shell{max-width:1100px;margin:0 auto}+header{padding:40px 0 0;max-width:660px}+h1{font-size:clamp(34px,6vw,56px);font-weight:700;line-height:1.03;letter-spacing:-.035em;margin:0;text-wrap:balance}+.byline{margin:24px 0 0;font-size:16px;color:var(--fg-2)}+.body{display:grid;grid-template-columns:minmax(0,660px) 1fr;gap:0 64px;margin:48px 0 0}+/* Both explicitly in row 1: without it the rail auto-places into row 1 and+ pushes the article down a whole row, opening an empty band above the text. */+article{grid-column:1;grid-row:1;min-width:0}+.rail{grid-column:2;grid-row:1;font-size:14px;color:var(--fg-3);padding-top:6px}+.rail .sticky{position:sticky;top:40px}+.toc-label{font-size:12px;letter-spacing:.08em;text-transform:uppercase;color:var(--fg-3);margin:0 0 10px}+.toc ol{list-style:none;margin:0;padding:0}+.toc li{margin:0 0 7px}+.toc a{color:var(--fg-2);text-decoration:none}+.toc a:hover{color:var(--fg)}+/* Below 900px the rail is dropped rather than stacked: a contents list above+ the report is a wall to scroll past on a phone, not a shortcut. */+@media (max-width:900px){.body{grid-template-columns:1fr}.rail{display:none}}+article p{margin:0 0 26px;text-wrap:pretty}+h2{font-size:30px;font-weight:600;letter-spacing:-.025em;line-height:1.2;margin:60px 0 22px;text-wrap:balance}+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}+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}+ul,ol{margin:0 0 26px;padding-left:22px}li{margin:0 0 11px}li::marker{color:var(--fg-3)}+.note{border-left:2px solid var(--fg);padding:2px 0 2px 22px;margin:0 0 26px}+.note p{margin:0;color:var(--fg-2)}+.note p+p{margin-top:14px}+.tw{overflow-x:auto;margin:0 0 30px}+table{border-collapse:collapse;width:100%;font-size:15.5px;min-width:440px}+th{text-align:left;font-weight:500;color:var(--fg-3);padding:0 20px 10px 0;border-bottom:1px solid var(--rule-2);white-space:nowrap}+td{padding:13px 20px 13px 0;border-bottom:1px solid var(--rule);vertical-align:top;color:var(--fg-2)}+td:first-child{color:var(--fg)}+td.n,th.n{text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap}+td:last-child,th:last-child{padding-right:0}+tr:last-child td{border-bottom:none}+figure{margin:0 0 30px}+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 .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}+footer{max-width:660px;margin:64px 0 0;padding:26px 0 0;border-top:1px solid var(--rule);font-size:15px;color:var(--fg-3)}+@media print{+ /* A zero top margin hides the browser's own print header (date, tab title);+ the bottom margin holds a page counter instead of the browser's URL line.+ The body padding supplies the visible page margins. */+ @page{margin:0 0 12mm 0;@bottom-center{content:counter(page) " of " counter(pages);font:10px -apple-system,BlinkMacSystemFont,Helvetica,Arial,sans-serif;color:#8f8f8f}}+ body{background:#fff;color:#111;padding:14mm 16mm 6mm;font-size:11pt}+ .shell,.body{display:block;max-width:none}+ header{padding:0;max-width:none}+ h1{font-size:26pt}+ h2{font-size:15pt;margin:22pt 0 10pt}+ h3{font-size:12pt;margin:14pt 0 6pt}+ article,footer{max-width:none}+ .rail{display:none}+ h1,h2,h3{break-after:avoid}+ table,figure,.note,svg{break-inside:avoid}+ tr,td,th{break-inside:avoid}+ p,li{orphans:3;widows:3}+ thead{display:table-header-group}+ .tw{overflow:visible}+ table{font-size:10pt;min-width:0}+ .byline,footer,figcaption{font-size:9.5pt}+ svg,.bars .bar,.bars .track{-webkit-print-color-adjust:exact;print-color-adjust:exact}+ a{text-decoration:none}+}+</style></head>+<body><div class="shell">++<header>+ <h1>REPORT TITLE</h1>+ <p class="byline">Prepared for NAME · MONTH D, YYYY</p>+</header>++<div class="body">+ <aside class="rail"><div class="sticky">+ <p class="toc-label">Contents</p>+ <nav class="toc" aria-label="Contents">+ <ol>+ <li><a href="#section-heading">SECTION HEADING</a></li>+ <li><a href="#what-to-do-next">What to do next</a></li>+ </ol>+ </nav>+ </div></aside>+ <article>++ <p>One or two sentences: the state of things and the one action.</p>++ <h2 id="section-heading">SECTION HEADING</h2>++ <h3>FINDING TITLE</h3>+ <ul class="finding">+ <li><b>Status:</b> what is true, with the number or the quoted tag that proves it.</li>+ <li><b>Fix:</b> the concrete step, doable this week by a non-technical person.</li>+ </ul>++ <div class="note"><p>A caveat, a confidence note, or something you could not verify.</p></div>++ <div class="tw">+ <table>+ <thead><tr><th>Item</th><th class="n">Volume</th><th class="n">Difficulty</th></tr></thead>+ <tbody><tr><td>example keyword</td><td class="n">1,300</td><td class="n">4</td></tr></tbody>+ </table>+ </div>++ <figure>+ <div class="bars" role="img" aria-label="Monthly volume: alpha 1,300, beta 590">+ <span class="label">alpha</span><span class="track"><span class="bar" style="width:100%"></span></span><span class="value">1,300</span>+ <span class="label">beta</span><span class="track"><span class="bar" style="width:45%"></span></span><span class="value">590</span>+ </div>+ <figcaption>One row per item; the widest bar is 100% and the rest are scaled to it.</figcaption>+ </figure>++ <hr>+ <h2 id="what-to-do-next">What to do next</h2>+ <ol><li>The top priority, first.</li></ol>++ </article>+</div>++<footer>What the tools reported, and what was verified by hand.</footer>+</div></body></html>+```++## The primitives++- **Header** — `h1` (the report title) and `.byline` (who it is for and the date): "Prepared for badseo.dev · September 3, 2026".+- **`.rail` contents** — the table of contents, sticky to the right of the text on a wide screen, dropped on a phone and in print. Every `h2` has an id, and the contents list links to each one with a plain `href="#id"` — in-page anchors are the one kind of link that must **not** use `target="_blank"`. Ids are the kebab-case of the heading text.+- **`h2` / `h3`** — `h2` opens a section, `h3` names one finding. Do not skip levels.+- **Finding** — `h3`, then a `.finding` list: `<li><b>Status:</b> …</li>`, `<li><b>Fix:</b> …</li>`, and `<li><b>Why:</b> …</li>` only when the reason is not obvious. Each bullet is one or two sentences. This is the workhorse; most of a report is a run of these.+- **`.note`** — one left-ruled callout for a caveat, a confidence limit, or something you could not verify. Two or three in a report, never a row of them.+- **`.tw` table** — every numeric column gets `class="n"` on both the `th` and the `td` so the digits line up. Keep tables to five columns or fewer, put the long-text column last, and keep cell text short; a wide table scrolls on a phone and clips in print.+- **`figure` + `.bars`** — one small bar chart where a comparison reads faster than a sentence. One row per item: `.label`, a `.track` holding a `.bar` whose inline width is the value as a percentage of the largest, and `.value`. Inline SVG is fine for anything that is not a bar chart; give it a `viewBox` and real `<text>` labels.+- **`hr` then a closing `h2`** — the "What to do next" list, ordered, shortest useful.+- **`footer`** — what the tools reported and what you verified by hand.++## 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 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/scripts/erase-user-data.ts b/scripts/erase-user-data.tsindex b936b0fc..ecf4e075 100644--- a/scripts/erase-user-data.ts+++ b/scripts/erase-user-data.ts@@ -26,7 +26,7 @@ import {or,sql,} from "drizzle-orm";-import { alias } from "drizzle-orm/pg-core";+import { alias, type PgColumn, type PgTable } from "drizzle-orm/pg-core";import { drizzle } from "drizzle-orm/postgres-js";import postgres from "postgres";import { z } from "zod";@@ -254,7 +254,8 @@ async function buildInventory(db: Db, user: UserRow) {).orderBy(schema.rankCheckRuns.id);- const projectCount = async (table: typeof schema.savedKeywords) =>+ // Any table with a `project_id`: the counts differ only in which table.+ const projectCount = async (table: PgTable & { projectId: PgColumn }) =>projectIds.length === 0? 0: db.$count(table, inArray(table.projectId, projectIds));@@ -273,13 +274,7 @@ async function buildInventory(db: Db, user: UserRow) {),projects: projectIds.length,saved_keywords: await projectCount(schema.savedKeywords),- audits:- projectIds.length === 0- ? 0- : await db.$count(- schema.audits,- inArray(schema.audits.projectId, projectIds),- ),+ audits: await projectCount(schema.audits),rank_snapshots:projectIds.length === 0? 0@@ -297,6 +292,11 @@ async function buildInventory(db: Db, user: UserRow) {schema.audits,eq(schema.audits.startedByUserId, user.id),),+ reports: await projectCount(schema.reports),+ attributed_reports: await db.$count(+ schema.reports,+ eq(schema.reports.createdByUserId, user.id),+ ),gsc_connections: await db.$count(schema.gscConnections,eq(schema.gscConnections.connectedByUserId, user.id),@@ -498,6 +498,12 @@ async function erasePostgres(db: Db, user: UserRow, organizationIds: string[]) {.update(schema.audits).set({ startedByUserId: "gdpr-deleted-user" }).where(eq(schema.audits.startedByUserId, user.id));+ // reports.created_by_user_id has no FK either (same reason as audits), so a+ // surviving multi-member org keeps its reports with the attribution wiped.+ await tx+ .update(schema.reports)+ .set({ createdByUserId: "gdpr-deleted-user" })+ .where(eq(schema.reports.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/scripts/migrate-d1-to-postgres.ts b/scripts/migrate-d1-to-postgres.tsindex b6a5ba84..b16ffec6 100644--- a/scripts/migrate-d1-to-postgres.ts+++ b/scripts/migrate-d1-to-postgres.ts@@ -84,6 +84,10 @@ const args = parseArgs(process.argv.slice(2));const dryRun = args["dry-run"] === "true";const allowNonEmpty = args["allow-nonempty"] === "true";const pageSize = Number(args["page-size"]) || 5000;+// Tables whose rows are big enough that the default page size would build a+// multi-gigabyte D1 HTTP response and a multi-gigabyte INSERT. `reports.html`+// is capped at REPORT_MAX_HTML_BYTES (500 KB) per row.+const PAGE_SIZE_OVERRIDES: Record<string, number> = { reports: 20 };const updateMode = args["update"] === "true";const sinceHours = Number(args["since-hours"]) || 12;@@ -332,7 +336,11 @@ async function copyTable(// Keep each INSERT's bound-parameter count (rows × columns) well under// Postgres's 65535 limit.const colCount = Object.keys(getTableColumns(pgTable)).length;- const insertBatch = Math.max(1, Math.min(5000, Math.floor(50000 / colCount)));+ const tablePageSize = PAGE_SIZE_OVERRIDES[name] ?? pageSize;+ const insertBatch = Math.max(+ 1,+ Math.min(tablePageSize, Math.floor(50000 / colCount)),+ );const { target, set } = buildUpsert(pgTable,conflictArbiterNames(sqliteTable),@@ -346,7 +354,7 @@ async function copyTable(for (;;) {const page = await d1Query<Record<string, unknown>>(databaseId,- `SELECT * FROM "${name}" ${where}${orderBy} LIMIT ${pageSize} OFFSET ${offset}`,+ `SELECT * FROM "${name}" ${where}${orderBy} LIMIT ${tablePageSize} OFFSET ${offset}`,);if (page.length === 0) break;@@ -358,8 +366,8 @@ async function copyTable(: dest.insert(pgTable).values(chunk).onConflictDoNothing());}count += page.length;- offset += pageSize;- if (page.length < pageSize) break;+ offset += tablePageSize;+ if (page.length < tablePageSize) break;}return count;}diff --git a/scripts/sync-plugin-skills.mjs b/scripts/sync-plugin-skills.mjsindex bb1103a0..a86f320e 100644--- a/scripts/sync-plugin-skills.mjs+++ b/scripts/sync-plugin-skills.mjs@@ -21,6 +21,7 @@ const skills = ["seo-audit","seo-coach","seo-project-setup",+ "seo-report",];// Wipe and rebuild so a skill removed from the list above doesn't leave adiff --git a/specs/0012-dynamic-reports.md b/specs/0012-dynamic-reports.mdnew file mode 100644index 00000000..0e83892a--- /dev/null+++ b/specs/0012-dynamic-reports.md@@ -0,0 +1,53 @@+# Reports (agent-written HTML reports per project)++## Status++Accepted. Shipped in PR #570. Report templates (`specs/0013-report-templates.md`) and public share links (`specs/0014-public-share-links.md`) build on it.++## What it does++- When an agent finishes a workflow such as `seo-audit`, it writes the result as one self-contained HTML page and saves it to the project with the free MCP tool `save_report`. `list_reports` and `get_report` read them back. SAM, the in-app agent, does not get them.+- The project's Reports page lists them. A report page renders the document in a locked-down viewer, with Export (the browser's print dialog), full screen, open in a new tab, and delete.+- Saving with an existing report id replaces the content in place. There is no version history.+- A report can be up to 500 KB. Storage stops at 10,000 reports per project and 5 GB per organization, runaway guards rather than product limits.++## How it works++**Data.** One `reports` table: `id`, `project_id` (cascades from the project), `title`, `summary` (markdown, up to 2,500 characters), `html`, `skill` (the slug that wrote it), `created_by` (a client label such as "Claude Code"), `created_by_user_id`, `size_bytes`, timestamps, plus `template_id`, `share_token` and `shared_at` for the follow-up specs. One index on `(project_id, updated_at, id)` serves the list, newest first.++**Invariants.**++- Every query is scoped by project id. The one lookup by report id alone returns the owning project id, which the caller authorizes before any content is read.+- List queries never select `html`; only the render path reads the document. Worker memory, not storage, is the constraint.+- Attribution is stamped at create time from the session and the request's client identity, never from the model, and never re-stamped on update. Nothing authorizes or bills on the client label.+- The service validates before any write: title and summary length, UTF-8 byte size, and a cheap document-shape check (the HTML contains `<html` and ends with `</html>`), because a model that stops mid-document would otherwise overwrite the previous good report.+- Titles are unique within a project. The count cap is a guardrail, not a strict invariant: parallel saves can briefly exceed it, and the next save refuses.+- Error messages read as instructions, because agents see them verbatim.++**Rendering.** The stored document is served byte for byte on the app's own origin behind sign-in and project membership. The response carries a Content Security Policy with a `sandbox` directive, so the document has an opaque origin whether framed or opened as a top-level tab: no cookies, no storage, no session cookie on anything it issues. `default-src 'none'` blocks scripts, fetches, forms and external resources; inline styles and `data:` images and fonts are allowed. The only sandbox tokens granted let links open a new tab, with the opener severed so the popup cannot navigate the reader's tab. The in-app viewer is an iframe whose `sandbox` attribute carries exactly the header's token list; `allow-same-origin` is never added, because with scripts it lets a frame remove its own sandbox and alone it hands the frame the app's cookies. Print mode is hash-authorized: the one script the app ever appends is an attribute-free tag allowed by its hash, so the report's own scripts stay blocked.++Not signed in bounces to sign-in and back. An unknown report and another organization's report get the same 404. A report in an archived project answers 404 naming the project, since the viewer is already a member.++**Skills.** A new public skill, `seo-report`, owns the save rules (list first, reuse the id when redoing the same job, reply with the link and a verdict rather than the report), the writing rules (no external resources, no scripts, no backticks or `${` because some clients pass HTML through a template literal), and the single starter template with inline CSS and one light look on screen and paper. The seven workflow skills deliver through it.++Both self-host modes get reports with no new binding or store. Erasing a user re-attributes their reports and revokes links on them; deleting a project cascades. Saves, deletes and opens are counted in telemetry.++## Alternatives considered++- HTML in object storage instead of a text column: a second store that can half-fail on every update and a second thing to erase, for documents of tens of kilobytes.+- Immutable snapshots instead of update in place: more rows, a "which one is current" rule and a UI to browse them, for a deliverable agents redo rather than revise. The shape check is the price of update in place.+- Credits per report instead of free with caps: reports only touch the app database. The caps bound the one free surface that stores large blobs.+- Per-skill templates instead of one starter: one template gives every skill one thing to keep good.+- Allowing scripts in v1: blocking is the one-way door in the safe direction. Reports saved without scripts keep working after a later flip; the reverse is not true.+- A nonce instead of a hash for the print script: the tag is spliced into a document the app did not parse, and a dangling tag in the report could absorb the nonce.+- An injected print banner: the document it warns about could hide or fake it with CSS.+- Server-side PDF: the report is a real document with its own print CSS, so the browser prints it.+- A separate report domain: covered in `specs/0014-public-share-links.md`.++## Not in scope++Server-side PDF, version history, scheduled reports and email, `updated_by` attribution, list search and filters, keyset paging, a chunked save path.++## Later++Interactive charts via `allow-scripts` without `allow-same-origin`: the frame stays origin-less, so a chart can run but has no cookies, storage or network.diff --git a/src/client/components/ConfirmDeleteModal.tsx b/src/client/components/ConfirmDeleteModal.tsxnew file mode 100644index 00000000..f52b0033--- /dev/null+++ b/src/client/components/ConfirmDeleteModal.tsx@@ -0,0 +1,46 @@+import { Loader2 } from "lucide-react";+import { Modal } from "@/client/components/Modal";++/** Confirm-by-name modal for a delete with no undo. */+export function ConfirmDeleteModal({+ title,+ detail,+ confirmLabel,+ isPending,+ onClose,+ onConfirm,+}: {+ title: string;+ detail: string;+ confirmLabel: string;+ isPending: boolean;+ onClose: () => void;+ onConfirm: () => void;+}) {+ return (+ <Modal onClose={onClose} labelledBy="confirm-delete-title">+ <h3 id="confirm-delete-title" className="text-lg font-semibold">+ {title}+ </h3>+ <p className="text-sm text-base-content/70">{detail}</p>+ <div className="flex justify-end gap-2">+ <button+ type="button"+ className="btn btn-ghost btn-sm"+ onClick={onClose}+ >+ Cancel+ </button>+ <button+ type="button"+ className="btn btn-error btn-sm gap-1"+ onClick={onConfirm}+ disabled={isPending}+ >+ {isPending ? <Loader2 className="size-3 animate-spin" /> : null}+ {confirmLabel}+ </button>+ </div>+ </Modal>+ );+}diff --git a/src/client/components/Sidebar.tsx b/src/client/components/Sidebar.tsxindex e85b1407..0f87002b 100644--- a/src/client/components/Sidebar.tsx+++ b/src/client/components/Sidebar.tsx@@ -82,10 +82,9 @@ function SidebarNavLink({}export function Sidebar({ projectId, onNavigate, onClose }: SidebarProps) {- const navGroups = [- ...(projectId ? getProjectNavGroups(projectId) : []),- connectNavGroup,- ];+ const navGroups = projectId+ ? getProjectNavGroups(projectId)+ : [connectNavGroup];const navigate = useNavigate();const location = useLocation();const onSamRoute = location.pathname.includes("/sam");diff --git a/src/client/features/ai-mcp/AvailableTools.tsx b/src/client/features/ai-mcp/AvailableTools.tsxindex b6b2aee4..752e8c7b 100644--- a/src/client/features/ai-mcp/AvailableTools.tsx+++ b/src/client/features/ai-mcp/AvailableTools.tsx@@ -27,6 +27,27 @@ const toolCategories: ToolCategory[] = [},],},+ {+ label: "Reports",+ tools: [+ {+ name: "save_report",+ title: "Save a report",+ description:+ "Save an agent's finished HTML report to the project, or replace an existing one.",+ },+ {+ name: "list_reports",+ title: "List reports",+ description: "See the project's saved reports and their summaries.",+ },+ {+ name: "get_report",+ title: "Get a report",+ description: "Read one report's summary, and its HTML when needed.",+ },+ ],+ },{label: "Keywords",tools: [diff --git a/src/client/features/reports/ReportViewer.tsx b/src/client/features/reports/ReportViewer.tsxnew file mode 100644index 00000000..c3f00695--- /dev/null+++ b/src/client/features/reports/ReportViewer.tsx@@ -0,0 +1,30 @@+import { REPORT_IFRAME_SANDBOX } from "@/shared/report-sandbox";++/**+ * The only place the app renders model-written HTML. Everything that keeps it+ * safe is the `sandbox` attribute plus the CSP the document response sets; the+ * token list is shared with that header so a link behaves the same framed and+ * top-level, and `allow-same-origin` is never added.+ */+export function ReportViewer({+ src,+ title,+ className,+}: {+ src: string;+ title: string;+ className?: string;+}) {+ return (+ <iframe+ src={src}+ sandbox={REPORT_IFRAME_SANDBOX}+ referrerPolicy="no-referrer"+ title={title}+ className={+ className ??+ "h-full w-full rounded-lg border border-base-300 bg-base-100"+ }+ />+ );+}diff --git a/src/client/features/reports/ReportsList.tsx b/src/client/features/reports/ReportsList.tsxnew file mode 100644index 00000000..aac59fcf--- /dev/null+++ b/src/client/features/reports/ReportsList.tsx@@ -0,0 +1,91 @@+import { Link } from "@tanstack/react-router";+import { Trash2 } from "lucide-react";+import { PortalMenu } from "@/client/components/PortalMenu";+import {+ formatCreatedBy,+ formatRelativeTime,+} from "@/client/features/reports/shared";+import type { ReportListItem } from "@/serverFunctions/reports";+import { REPORT_APP_LIST_LIMIT } from "@/types/schemas/reports";++export function ReportsList({+ projectId,+ reports,+ onDelete,+}: {+ projectId: string;+ reports: ReportListItem[];+ onDelete: (report: ReportListItem) => void;+}) {+ if (reports.length === 0) {+ return (+ <p className="rounded-lg border border-dashed border-base-300 px-4 py-6 text-sm text-base-content/60">+ No reports yet. Run an OpenSEO skill such as seo-audit from Claude Code,+ Codex, or SAM and the report will appear here.+ </p>+ );+ }++ return (+ <div className="space-y-3">+ <div className="overflow-x-auto rounded-lg border border-base-300">+ <table className="table table-sm">+ <thead>+ <tr>+ <th>Title</th>+ <th>Created by</th>+ <th>Skill</th>+ <th>Updated</th>+ <th></th>+ </tr>+ </thead>+ <tbody>+ {reports.map((report) => (+ <tr key={report.id} className="hover:bg-base-200">+ <td className="max-w-[420px]">+ <Link+ to="/p/$projectId/reports/$reportId"+ params={{ projectId, reportId: report.id }}+ className="link link-hover font-medium"+ >+ {report.title}+ </Link>+ </td>+ <td className="text-base-content/70">+ {formatCreatedBy(report)}+ </td>+ <td className="text-base-content/70">{report.skill ?? "—"}</td>+ <td className="whitespace-nowrap text-base-content/70">+ {formatRelativeTime(report.updatedAt)}+ </td>+ <td className="w-10 text-right">+ <PortalMenu ariaLabel={`Actions for ${report.title}`}>+ {(close) => (+ <li>+ <button+ className="text-error"+ onClick={() => {+ close();+ onDelete(report);+ }}+ >+ <Trash2 className="size-3.5" />+ Delete+ </button>+ </li>+ )}+ </PortalMenu>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ {reports.length === REPORT_APP_LIST_LIMIT ? (+ <p className="text-xs text-base-content/60">+ Showing the {REPORT_APP_LIST_LIMIT} most recent reports.+ </p>+ ) : null}+ </div>+ );+}diff --git a/src/client/features/reports/shared.tsx b/src/client/features/reports/shared.tsxnew file mode 100644index 00000000..1dc9fb45--- /dev/null+++ b/src/client/features/reports/shared.tsx@@ -0,0 +1,104 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import { toast } from "sonner";+import { ConfirmDeleteModal } from "@/client/components/ConfirmDeleteModal";+import { getStandardErrorMessage } from "@/client/lib/error-messages";+import { captureClientEvent } from "@/client/lib/posthog";+import { deleteReport, type ReportListItem } from "@/serverFunctions/reports";++// Query keys for both reports pages. staleTime is 0 wherever these are used:+// the pages exist to inspect what an agent just wrote, so the app-wide+// five-minute staleTime would show a pre-save list as current.+export const reportsQueryKey = (projectId: string) =>+ ["reports", projectId] as const;++export const reportQueryKey = (projectId: string, reportId: string) =>+ ["report", projectId, reportId] as const;++const RELATIVE_UNITS: [Intl.RelativeTimeFormatUnit, number][] = [+ ["year", 365 * 24 * 60 * 60 * 1000],+ ["month", 30 * 24 * 60 * 60 * 1000],+ ["day", 24 * 60 * 60 * 1000],+ ["hour", 60 * 60 * 1000],+ ["minute", 60 * 1000],+];++/** "3 hours ago" for an ISO timestamp; "just now" under a minute. */+export function formatRelativeTime(iso: string): string {+ const then = new Date(iso).getTime();+ if (Number.isNaN(then)) return "";+ const diff = then - Date.now();+ const absolute = Math.abs(diff);+ const formatter = new Intl.RelativeTimeFormat("en-US", { numeric: "auto" });+ for (const [unit, ms] of RELATIVE_UNITS) {+ if (absolute >= ms) return formatter.format(Math.round(diff / ms), unit);+ }+ return "just now";+}++/**+ * "Ben · Claude Code". The person is the half that means something (it comes+ * from the session); the client half is a self-reported hint, so it stands+ * alone when the user cannot be resolved.+ */+export function formatCreatedBy(report: ReportListItem): string {+ return report.createdByName+ ? `${report.createdByName} · ${report.createdBy}`+ : report.createdBy;+}++/**+ * One delete flow for both the list row and the detail page, so the toast, the+ * event and the invalidation cannot drift apart.+ */+export function useDeleteReport(projectId: string, onDeleted?: () => void) {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: (reportId: string) =>+ deleteReport({ data: { projectId, reportId } }),+ onSuccess: (_result, reportId) => {+ captureClientEvent("report:deleted", {+ project_id: projectId,+ report_id: reportId,+ });+ toast.success("Report deleted");+ void queryClient.invalidateQueries({+ queryKey: reportsQueryKey(projectId),+ });+ // Drop the detail entry too, or a later visit to that URL renders the+ // deleted report from cache before the refetch turns it into a 404.+ queryClient.removeQueries({+ queryKey: reportQueryKey(projectId, reportId),+ });+ onDeleted?.();+ },+ onError: (error: Error) => {+ toast.error(+ getStandardErrorMessage(error, "Failed to delete the report"),+ );+ },+ });+}++/** Reports have no version history and no undo, so deletes are confirmed by name. */+export function DeleteReportModal({+ title,+ isPending,+ onClose,+ onConfirm,+}: {+ title: string;+ isPending: boolean;+ onClose: () => void;+ onConfirm: () => void;+}) {+ return (+ <ConfirmDeleteModal+ title={`Delete \u201c${title}\u201d?`}+ detail="This cannot be undone."+ confirmLabel="Delete report"+ isPending={isPending}+ onClose={onClose}+ onConfirm={onConfirm}+ />+ );+}diff --git a/src/client/features/sam/SamChat.tsx b/src/client/features/sam/SamChat.tsxindex bcede0e5..94519b94 100644--- a/src/client/features/sam/SamChat.tsx+++ b/src/client/features/sam/SamChat.tsx@@ -87,7 +87,7 @@ export function SamChat({{activeTitle ?? "Chat"}</span><Link- to="/p/$projectId/settings/context"+ to="/p/$projectId/context"params={{ projectId }}className="flex shrink-0 items-center gap-1.5 text-xs text-base-content/60 transition-colors hover:text-base-content">diff --git a/src/client/navigation/items.ts b/src/client/navigation/items.tsindex b27d53e8..221e78ba 100644--- a/src/client/navigation/items.ts+++ b/src/client/navigation/items.ts@@ -1,7 +1,9 @@import {Bookmark,Bot,+ Brain,ClipboardCheck,+ FileText,Globe,LayoutDashboard,Link2,@@ -67,17 +69,30 @@ const projectNavItems = [label: "Prompt Explorer",icon: MessageSquare,},+ {+ to: "/p/$projectId/reports" as const,+ label: "Reports",+ icon: FileText,+ },+ {+ to: "/p/$projectId/context" as const,+ label: "Context",+ icon: Brain,+ },] as const;+// Project-independent. Rendered inside the project "AI" group when a project+// is selected, and on its own (connectNavGroup) when none is.const aiNavItem = linkOptions({to: "/ai" as const,- label: "AI & MCP",+ label: "MCP setup",icon: Bot,});-// Always-visible sidebar group (not project-scoped, unlike the groups below).+// Shown only when no project is selected; with a project, MCP setup lives in+// the "AI" group below.export const connectNavGroup = {- label: "Connect",+ label: "AI",items: [aiNavItem],};@@ -103,6 +118,14 @@ export function getProjectNavGroups(projectId: string) {label: "Overview",items: [byPath("/p/$projectId")],},+ {+ label: "AI",+ items: [+ byPath("/p/$projectId/reports"),+ byPath("/p/$projectId/context"),+ aiNavItem,+ ],+ },{label: "Research",items: [diff --git a/src/db/d1/schema.ts b/src/db/d1/schema.tsindex 41f252a9..e5100dea 100644--- a/src/db/d1/schema.ts+++ b/src/db/d1/schema.ts@@ -3,6 +3,8 @@// SQLite tables regardless of DATABASE_PROVIDER.export * from "../app.schema";export * from "../project-context.schema";+export * from "../reports.schema";+export * from "../report-templates.schema";export * from "../audit.schema";export * from "../sam.schema";export * from "../better-auth-schema";diff --git a/src/db/pg/report-templates.schema.ts b/src/db/pg/report-templates.schema.tsnew file mode 100644index 00000000..bab7a45d--- /dev/null+++ b/src/db/pg/report-templates.schema.ts@@ -0,0 +1,32 @@+import { sql } from "drizzle-orm";+import { pgTable, text, uniqueIndex } from "drizzle-orm/pg-core";+import { projects } from "./app.schema";++// Timestamps are stored as *text* (same column shape as the SQLite schema); see+// the note in pg/app.schema.ts.+const isoNow = sql`to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`;++// Postgres mirror of the report_templates table. Column notes: see+// ../report-templates.schema.ts.+export const reportTemplates = pgTable(+ "report_templates",+ {+ id: text("id").primaryKey(),+ projectId: text("project_id")+ .notNull()+ .references(() => projects.id, { onDelete: "cascade" }),+ name: text("name").notNull(),+ description: text("description").notNull(),+ instructions: text("instructions").notNull(),+ createdBy: text("created_by").notNull(),+ createdByUserId: text("created_by_user_id").notNull(),+ createdAt: text("created_at").notNull().default(isoNow),+ updatedAt: text("updated_at").notNull().default(isoNow),+ },+ (table) => [+ uniqueIndex("report_templates_project_name_idx").on(+ table.projectId,+ table.name,+ ),+ ],+);diff --git a/src/db/pg/reports.schema.ts b/src/db/pg/reports.schema.tsnew file mode 100644index 00000000..c5bc2d9e--- /dev/null+++ b/src/db/pg/reports.schema.ts@@ -0,0 +1,46 @@+import { sql } from "drizzle-orm";+import {+ index,+ integer,+ pgTable,+ text,+ uniqueIndex,+} from "drizzle-orm/pg-core";+import { projects } from "./app.schema";++// Timestamps are stored as *text* (same column shape as the SQLite schema); see+// the note in pg/app.schema.ts. `isoNow` matches `new Date().toISOString()` so+// DB-defaulted and app-written values sort together lexicographically.+const isoNow = sql`to_char(now() AT TIME ZONE 'utc', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`;++// Postgres mirror of the reports table. Column notes: see ../reports.schema.ts.+export const reports = pgTable(+ "reports",+ {+ id: text("id").primaryKey(),+ projectId: text("project_id")+ .notNull()+ .references(() => projects.id, { onDelete: "cascade" }),+ title: text("title").notNull(),+ summary: text("summary").notNull(),+ html: text("html").notNull(),+ skill: text("skill"),+ templateId: text("template_id"),+ createdBy: text("created_by").notNull(),+ createdByUserId: text("created_by_user_id").notNull(),+ sizeBytes: integer("size_bytes").notNull(),+ shareToken: text("share_token"),+ sharedAt: text("shared_at"),+ createdAt: text("created_at").notNull().default(isoNow),+ updatedAt: text("updated_at").notNull().default(isoNow),+ },+ (table) => [+ index("reports_project_updated_idx").on(+ table.projectId,+ table.updatedAt,+ table.id,+ table.sizeBytes,+ ),+ uniqueIndex("reports_share_token_idx").on(table.shareToken),+ ],+);diff --git a/src/db/pg/schema.ts b/src/db/pg/schema.tsindex 5b74981a..05572ecd 100644--- a/src/db/pg/schema.ts+++ b/src/db/pg/schema.ts@@ -1,5 +1,7 @@export * from "./app.schema";export * from "./project-context.schema";+export * from "./reports.schema";+export * from "./report-templates.schema";export * from "./audit.schema";export * from "./sam.schema";export * from "./better-auth-schema";diff --git a/src/db/report-templates.schema.ts b/src/db/report-templates.schema.tsnew file mode 100644index 00000000..dc58c011--- /dev/null+++ b/src/db/report-templates.schema.ts@@ -0,0 +1,43 @@+import { sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";+import { sql } from "drizzle-orm";+import { projects } from "./app.schema";++// ============================================================================+// Report templates: named, reusable briefs for a kind of report. Instructions+// only — the agent still writes the document from the seo-report starter; a+// template replaces the calling skill's section list and tone, never the HTML+// constraints.+// ============================================================================++export const reportTemplates = sqliteTable(+ "report_templates",+ {+ id: text("id").primaryKey(),+ projectId: text("project_id")+ .notNull()+ .references(() => projects.id, { onDelete: "cascade" }),+ name: text("name").notNull(),+ // One line saying when to use it: what agents pick a template by in the+ // project-context digest.+ description: text("description").notNull(),+ // Markdown: audience, sections in order, tone, sign-off, accent color.+ instructions: text("instructions").notNull(),+ // Same two-column attribution as reports; see reports.schema.ts.+ createdBy: text("created_by").notNull(),+ createdByUserId: text("created_by_user_id").notNull(),+ createdAt: text("created_at")+ .notNull()+ .default(sql`(strftime('%Y-%m-%dT%H:%M:%fZ','now'))`),+ updatedAt: text("updated_at")+ .notNull()+ .default(sql`(strftime('%Y-%m-%dT%H:%M:%fZ','now'))`),+ },+ // Backstop for the service's case-insensitive duplicate-name check, and the+ // index the feature's one list query reads.+ (table) => [+ uniqueIndex("report_templates_project_name_idx").on(+ table.projectId,+ table.name,+ ),+ ],+);diff --git a/src/db/reports.schema.ts b/src/db/reports.schema.tsnew file mode 100644index 00000000..165cffe4--- /dev/null+++ b/src/db/reports.schema.ts@@ -0,0 +1,85 @@+import {+ index,+ integer,+ sqliteTable,+ text,+ uniqueIndex,+} from "drizzle-orm/sqlite-core";+import { sql } from "drizzle-orm";+import { projects } from "./app.schema";++// ============================================================================+// Reports: the HTML documents agents write for a project. One row is one whole+// self-contained document, replaced in place — there is no version history.+// ============================================================================++// `html` is a text column rather than an R2 object: the service caps it at+// REPORT_MAX_HTML_BYTES, well under D1's 2 MB per-row limit, and a single store+// keeps deletion to the projects cascade. Never `SELECT *` here — list reads+// take metadata columns only, and only getReportHtml touches `html`.+export const reports = sqliteTable(+ "reports",+ {+ id: text("id").primaryKey(),+ projectId: text("project_id")+ .notNull()+ .references(() => projects.id, { onDelete: "cascade" }),+ title: text("title").notNull(),+ // Markdown, capped at REPORT_MAX_SUMMARY_CHARS: what list reads return+ // instead of the document.+ summary: text("summary").notNull(),+ html: text("html").notNull(),+ // Agent-supplied slug of the skill that produced the report ("seo-audit").+ skill: text("skill"),+ // The report template the agent followed, when it followed one. No FK: a+ // deleted template must not delete or block the reports written from it,+ // and every read of the name is project-scoped anyway.+ templateId: text("template_id"),+ // The client half of attribution: free text ("Claude Code", "Codex", "SAM",+ // "API key", a sanitized UA token). Self-reported, so nothing authorizes,+ // filters or bills on it. Stamped at create and never re-stamped.+ createdBy: text("created_by").notNull(),+ // The identity half, from the authenticated session. No FK, mirroring+ // audits.started_by_user_id, so GDPR can re-attribute an erased user+ // without cascading a surviving organization's reports away.+ createdByUserId: text("created_by_user_id").notNull(),+ // UTF-8 byte length of `html`, so readers can detect a truncated read+ // without loading the document.+ sizeBytes: integer("size_bytes").notNull(),+ // Public share link. Null means not shared: the capability IS the token, so+ // nulling it is what revokes the link. 192 bits of base64url, stored in+ // plaintext — it is an unguessable URL, not a credential to compare against+ // a user, and the raw endpoint has to look a row up by it.+ shareToken: text("share_token"),+ // When the current token was minted. Re-sharing mints a new token and a new+ // stamp; content saves never touch either column.+ sharedAt: text("shared_at"),+ // Timestamps are text on both dialects and stamped by the repository. The+ // default emits ISO (unlike current_timestamp's space format) because the+ // list order is lexicographic against app-written ISO stamps.+ createdAt: text("created_at")+ .notNull()+ .default(sql`(strftime('%Y-%m-%dT%H:%M:%fZ','now'))`),+ updatedAt: text("updated_at")+ .notNull()+ .default(sql`(strftime('%Y-%m-%dT%H:%M:%fZ','now'))`),+ },+ // Serves the feature's one list query: a project's reports, newest update+ // first. `id` is in the key because same-second saves tie on updated_at.+ // Trailing `size_bytes` is what makes the org storage-ceiling SUM (run on+ // every save) an index-only read; without it the scan fetches every row and,+ // because `size_bytes` follows `html` in the record, walks each row's+ // overflow pages.+ (table) => [+ index("reports_project_updated_idx").on(+ table.projectId,+ table.updatedAt,+ table.id,+ table.sizeBytes,+ ),+ // The public read path: one lookup by token, with no project id to scope+ // it. Unique so a mint collision fails loudly instead of pointing one link+ // at two reports; nulls do not collide on either dialect.+ uniqueIndex("reports_share_token_idx").on(table.shareToken),+ ],+);diff --git a/src/db/schema-parity.test.ts b/src/db/schema-parity.test.tsindex b9c97d91..15fcc327 100644--- a/src/db/schema-parity.test.ts+++ b/src/db/schema-parity.test.ts@@ -7,6 +7,8 @@ import { sort } from "remeda";import { describe, expect, it } from "vitest";import * as sqliteApp from "./app.schema";import * as sqliteProjectContext from "./project-context.schema";+import * as sqliteReports from "./reports.schema";+import * as sqliteReportTemplates from "./report-templates.schema";import * as sqliteAudit from "./audit.schema";import * as sqliteSam from "./sam.schema";import * as sqliteAuth from "./better-auth-schema";@@ -16,6 +18,8 @@ import * as sqliteGsc from "./gsc.schema";import * as sqliteTelemetry from "./telemetry.schema";import * as pgApp from "./pg/app.schema";import * as pgProjectContext from "./pg/project-context.schema";+import * as pgReports from "./pg/reports.schema";+import * as pgReportTemplates from "./pg/report-templates.schema";import * as pgAudit from "./pg/audit.schema";import * as pgSam from "./pg/sam.schema";import * as pgAuth from "./pg/better-auth-schema";@@ -147,6 +151,8 @@ function checkNames(table: Table, dialect: Dialect): string[] {const sqliteAppTables = tablesFrom(sqliteApp,sqliteProjectContext,+ sqliteReports,+ sqliteReportTemplates,sqliteAudit,sqliteSam,sqliteBilling,@@ -157,6 +163,8 @@ const sqliteAppTables = tablesFrom(const pgAppTables = tablesFrom(pgApp,pgProjectContext,+ pgReports,+ pgReportTemplates,pgAudit,pgSam,pgBilling,diff --git a/src/db/schema.ts b/src/db/schema.tsindex 87107927..12b0d30d 100644--- a/src/db/schema.ts+++ b/src/db/schema.ts@@ -1,6 +1,8 @@import { getDatabaseProvider } from "./provider";import * as sqliteApp from "./app.schema";import * as sqliteProjectContext from "./project-context.schema";+import * as sqliteReports from "./reports.schema";+import * as sqliteReportTemplates from "./report-templates.schema";import * as sqliteAudit from "./audit.schema";import * as sqliteSam from "./sam.schema";import * as sqliteAuth from "./better-auth-schema";@@ -10,6 +12,8 @@ import * as sqliteGsc from "./gsc.schema";import * as sqliteTelemetry from "./telemetry.schema";import * as pgApp from "./pg/app.schema";import * as pgProjectContext from "./pg/project-context.schema";+import * as pgReports from "./pg/reports.schema";+import * as pgReportTemplates from "./pg/report-templates.schema";import * as pgAudit from "./pg/audit.schema";import * as pgSam from "./pg/sam.schema";import * as pgAuth from "./pg/better-auth-schema";@@ -30,6 +34,8 @@ import * as pgTelemetry from "./pg/telemetry.schema";// parity test is its drift guard.type AppSchema = typeof sqliteApp &typeof sqliteProjectContext &+ typeof sqliteReports &+ typeof sqliteReportTemplates &typeof sqliteAudit &typeof sqliteSam &typeof sqliteAuth &@@ -43,6 +49,8 @@ const runtimeSchema =? {...pgApp,...pgProjectContext,+ ...pgReports,+ ...pgReportTemplates,...pgAudit,...pgSam,...pgAuth,@@ -54,6 +62,8 @@ const runtimeSchema =: {...sqliteApp,...sqliteProjectContext,+ ...sqliteReports,+ ...sqliteReportTemplates,...sqliteAudit,...sqliteSam,...sqliteAuth,@@ -85,6 +95,8 @@ export const {projectCompetitors,projectKeyPages,projectResearchLog,+ reports,+ reportTemplates,audits,auditPages,auditIssues,diff --git a/src/lib/auth-redirect.ts b/src/lib/auth-redirect.tsindex ee3d0805..f1e83dd4 100644--- a/src/lib/auth-redirect.ts+++ b/src/lib/auth-redirect.ts@@ -73,6 +73,17 @@ export function getCurrentAuthRedirectFromHref(href: string) {return normalizeAuthRedirect(`${url.pathname}${url.search}${url.hash}`);}+/**+ * Routes served as a raw document by a server handler, with no client+ * component. They are still matchable in the generated client route tree, where+ * a route with no component renders an empty shell — so an SPA navigation to+ * one lands the user on a blank page. Navigate to these with a document load.+ */+export function isDocumentRoute(redirectTo: string) {+ // Every componentless server-handler route must reload; /r/ is the only one.+ return redirectTo.startsWith("/r/");+}+export function getSignInSearch(redirectTo: string) {return redirectTo === "/" ? {} : { redirect: redirectTo };}diff --git a/src/routeTree.gen.ts b/src/routeTree.gen.tsindex 7aeaa211..5dc10969 100644--- a/src/routeTree.gen.ts+++ b/src/routeTree.gen.ts@@ -18,6 +18,7 @@ import { Route as AuthRouteImport } from './routes/_auth'import { Route as ProjectRouteRouteImport } from './routes/_project/route'import { Route as AppRouteRouteImport } from './routes/_app/route'import { Route as AppIndexRouteImport } from './routes/_app/index'+import { Route as RReportIdRouteImport } from './routes/r/$reportId'import { Route as MockupsSignupRouteImport } from './routes/mockups.signup'import { Route as ApiHealthRouteImport } from './routes/api/health'import { Route as AcceptInvitationIdRouteImport } from './routes/accept-invitation.$id'@@ -51,14 +52,17 @@ import { Route as ProjectPProjectIdRankTrackingRouteImport } from './routes/_proimport { Route as ProjectPProjectIdPromptExplorerRouteImport } from './routes/_project/p/$projectId/prompt-explorer'import { Route as ProjectPProjectIdKeywordsRouteImport } from './routes/_project/p/$projectId/keywords'import { Route as ProjectPProjectIdDomainRouteImport } from './routes/_project/p/$projectId/domain'+import { Route as ProjectPProjectIdContextRouteImport } from './routes/_project/p/$projectId/context'import { Route as ProjectPProjectIdBrandLookupRouteImport } from './routes/_project/p/$projectId/brand-lookup'import { Route as ProjectPProjectIdBacklinksRouteImport } from './routes/_project/p/$projectId/backlinks'import { Route as ProjectPProjectIdAuditRouteImport } from './routes/_project/p/$projectId/audit'import { Route as ProjectPProjectIdSettingsIndexRouteImport } from './routes/_project/p/$projectId/settings/index'+import { Route as ProjectPProjectIdReportsIndexRouteImport } from './routes/_project/p/$projectId/reports/index'import { Route as ProjectPProjectIdRankTrackingIndexRouteImport } from './routes/_project/p/$projectId/rank-tracking/index'import { 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 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'@@ -103,6 +107,11 @@ const AppIndexRoute = AppIndexRouteImport.update({path: '/',getParentRoute: () => AppRouteRoute,} as any)+const RReportIdRoute = RReportIdRouteImport.update({+ id: '/r/$reportId',+ path: '/r/$reportId',+ getParentRoute: () => rootRouteImport,+} as any)const MockupsSignupRoute = MockupsSignupRouteImport.update({id: '/mockups/signup',path: '/mockups/signup',@@ -276,6 +285,12 @@ const ProjectPProjectIdDomainRoute = ProjectPProjectIdDomainRouteImport.update({path: '/domain',getParentRoute: () => ProjectPProjectIdRouteRoute,} as any)+const ProjectPProjectIdContextRoute =+ ProjectPProjectIdContextRouteImport.update({+ id: '/context',+ path: '/context',+ getParentRoute: () => ProjectPProjectIdRouteRoute,+ } as any)const ProjectPProjectIdBrandLookupRoute =ProjectPProjectIdBrandLookupRouteImport.update({id: '/brand-lookup',@@ -299,6 +314,12 @@ const ProjectPProjectIdSettingsIndexRoute =path: '/',getParentRoute: () => ProjectPProjectIdSettingsRoute,} as any)+const ProjectPProjectIdReportsIndexRoute =+ ProjectPProjectIdReportsIndexRouteImport.update({+ id: '/reports/',+ path: '/reports/',+ getParentRoute: () => ProjectPProjectIdRouteRoute,+ } as any)const ProjectPProjectIdRankTrackingIndexRoute =ProjectPProjectIdRankTrackingIndexRouteImport.update({id: '/',@@ -323,6 +344,12 @@ const ProjectPProjectIdSettingsContextRoute =path: '/context',getParentRoute: () => ProjectPProjectIdSettingsRoute,} as any)+const ProjectPProjectIdReportsReportIdRoute =+ ProjectPProjectIdReportsReportIdRouteImport.update({+ id: '/reports/$reportId',+ path: '/reports/$reportId',+ getParentRoute: () => ProjectPProjectIdRouteRoute,+ } as any)const ProjectPProjectIdRankTrackingConfigIdRoute =ProjectPProjectIdRankTrackingConfigIdRouteImport.update({id: '/$configId',@@ -356,6 +383,7 @@ export interface FileRoutesByFullPath {'/accept-invitation/$id': typeof AcceptInvitationIdRoute'/api/health': typeof ApiHealthRoute'/mockups/signup': typeof MockupsSignupRoute+ '/r/$reportId': typeof RReportIdRoute'/p/$projectId': typeof ProjectPProjectIdRouteRouteWithChildren'/help/dataforseo-api-key': typeof AppHelpDataforseoApiKeyRoute'/help/openrouter-api-key': typeof AppHelpOpenrouterApiKeyRoute@@ -367,6 +395,7 @@ export interface FileRoutesByFullPath {'/p/$projectId/audit': typeof ProjectPProjectIdAuditRouteWithChildren'/p/$projectId/backlinks': typeof ProjectPProjectIdBacklinksRoute'/p/$projectId/brand-lookup': typeof ProjectPProjectIdBrandLookupRoute+ '/p/$projectId/context': typeof ProjectPProjectIdContextRoute'/p/$projectId/domain': typeof ProjectPProjectIdDomainRoute'/p/$projectId/keywords': typeof ProjectPProjectIdKeywordsRoute'/p/$projectId/prompt-explorer': typeof ProjectPProjectIdPromptExplorerRoute@@ -379,10 +408,12 @@ export interface FileRoutesByFullPath {'/api/gsc/oauth/callback': typeof ApiGscOauthCallbackRoute'/p/$projectId/': typeof ProjectPProjectIdIndexRoute'/p/$projectId/rank-tracking/$configId': typeof ProjectPProjectIdRankTrackingConfigIdRoute+ '/p/$projectId/reports/$reportId': typeof ProjectPProjectIdReportsReportIdRoute'/p/$projectId/settings/context': typeof ProjectPProjectIdSettingsContextRoute'/p/$projectId/settings/integrations': typeof ProjectPProjectIdSettingsIntegrationsRoute'/p/$projectId/audit/': typeof ProjectPProjectIdAuditIndexRoute'/p/$projectId/rank-tracking/': typeof ProjectPProjectIdRankTrackingIndexRoute+ '/p/$projectId/reports/': typeof ProjectPProjectIdReportsIndexRoute'/p/$projectId/settings/': typeof ProjectPProjectIdSettingsIndexRoute'/p/$projectId/audit/issues/$resultId': typeof ProjectPProjectIdAuditIssuesResultIdRoute}@@ -405,6 +436,7 @@ export interface FileRoutesByTo {'/accept-invitation/$id': typeof AcceptInvitationIdRoute'/api/health': typeof ApiHealthRoute'/mockups/signup': typeof MockupsSignupRoute+ '/r/$reportId': typeof RReportIdRoute'/help/dataforseo-api-key': typeof AppHelpDataforseoApiKeyRoute'/help/openrouter-api-key': typeof AppHelpOpenrouterApiKeyRoute'/settings/organization': typeof AppSettingsOrganizationRoute@@ -414,6 +446,7 @@ export interface FileRoutesByTo {'/onboarding': typeof AuthenticatedOnboardingIndexRoute'/p/$projectId/backlinks': typeof ProjectPProjectIdBacklinksRoute'/p/$projectId/brand-lookup': typeof ProjectPProjectIdBrandLookupRoute+ '/p/$projectId/context': typeof ProjectPProjectIdContextRoute'/p/$projectId/domain': typeof ProjectPProjectIdDomainRoute'/p/$projectId/keywords': typeof ProjectPProjectIdKeywordsRoute'/p/$projectId/prompt-explorer': typeof ProjectPProjectIdPromptExplorerRoute@@ -424,10 +457,12 @@ export interface FileRoutesByTo {'/api/gsc/oauth/callback': typeof ApiGscOauthCallbackRoute'/p/$projectId': typeof ProjectPProjectIdIndexRoute'/p/$projectId/rank-tracking/$configId': typeof ProjectPProjectIdRankTrackingConfigIdRoute+ '/p/$projectId/reports/$reportId': typeof ProjectPProjectIdReportsReportIdRoute'/p/$projectId/settings/context': typeof ProjectPProjectIdSettingsContextRoute'/p/$projectId/settings/integrations': typeof ProjectPProjectIdSettingsIntegrationsRoute'/p/$projectId/audit': typeof ProjectPProjectIdAuditIndexRoute'/p/$projectId/rank-tracking': typeof ProjectPProjectIdRankTrackingIndexRoute+ '/p/$projectId/reports': typeof ProjectPProjectIdReportsIndexRoute'/p/$projectId/settings': typeof ProjectPProjectIdSettingsIndexRoute'/p/$projectId/audit/issues/$resultId': typeof ProjectPProjectIdAuditIssuesResultIdRoute}@@ -455,6 +490,7 @@ export interface FileRoutesById {'/accept-invitation/$id': typeof AcceptInvitationIdRoute'/api/health': typeof ApiHealthRoute'/mockups/signup': typeof MockupsSignupRoute+ '/r/$reportId': typeof RReportIdRoute'/_app/': typeof AppIndexRoute'/_project/p/$projectId': typeof ProjectPProjectIdRouteRouteWithChildren'/_app/help/dataforseo-api-key': typeof AppHelpDataforseoApiKeyRoute@@ -467,6 +503,7 @@ export interface FileRoutesById {'/_project/p/$projectId/audit': typeof ProjectPProjectIdAuditRouteWithChildren'/_project/p/$projectId/backlinks': typeof ProjectPProjectIdBacklinksRoute'/_project/p/$projectId/brand-lookup': typeof ProjectPProjectIdBrandLookupRoute+ '/_project/p/$projectId/context': typeof ProjectPProjectIdContextRoute'/_project/p/$projectId/domain': typeof ProjectPProjectIdDomainRoute'/_project/p/$projectId/keywords': typeof ProjectPProjectIdKeywordsRoute'/_project/p/$projectId/prompt-explorer': typeof ProjectPProjectIdPromptExplorerRoute@@ -479,10 +516,12 @@ export interface FileRoutesById {'/api/gsc/oauth/callback': typeof ApiGscOauthCallbackRoute'/_project/p/$projectId/': typeof ProjectPProjectIdIndexRoute'/_project/p/$projectId/rank-tracking/$configId': typeof ProjectPProjectIdRankTrackingConfigIdRoute+ '/_project/p/$projectId/reports/$reportId': typeof ProjectPProjectIdReportsReportIdRoute'/_project/p/$projectId/settings/context': typeof ProjectPProjectIdSettingsContextRoute'/_project/p/$projectId/settings/integrations': typeof ProjectPProjectIdSettingsIntegrationsRoute'/_project/p/$projectId/audit/': typeof ProjectPProjectIdAuditIndexRoute'/_project/p/$projectId/rank-tracking/': typeof ProjectPProjectIdRankTrackingIndexRoute+ '/_project/p/$projectId/reports/': typeof ProjectPProjectIdReportsIndexRoute'/_project/p/$projectId/settings/': typeof ProjectPProjectIdSettingsIndexRoute'/_project/p/$projectId/audit/issues/$resultId': typeof ProjectPProjectIdAuditIssuesResultIdRoute}@@ -508,6 +547,7 @@ export interface FileRouteTypes {| '/accept-invitation/$id'| '/api/health'| '/mockups/signup'+ | '/r/$reportId'| '/p/$projectId'| '/help/dataforseo-api-key'| '/help/openrouter-api-key'@@ -519,6 +559,7 @@ export interface FileRouteTypes {| '/p/$projectId/audit'| '/p/$projectId/backlinks'| '/p/$projectId/brand-lookup'+ | '/p/$projectId/context'| '/p/$projectId/domain'| '/p/$projectId/keywords'| '/p/$projectId/prompt-explorer'@@ -531,10 +572,12 @@ export interface FileRouteTypes {| '/api/gsc/oauth/callback'| '/p/$projectId/'| '/p/$projectId/rank-tracking/$configId'+ | '/p/$projectId/reports/$reportId'| '/p/$projectId/settings/context'| '/p/$projectId/settings/integrations'| '/p/$projectId/audit/'| '/p/$projectId/rank-tracking/'+ | '/p/$projectId/reports/'| '/p/$projectId/settings/'| '/p/$projectId/audit/issues/$resultId'fileRoutesByTo: FileRoutesByTo@@ -557,6 +600,7 @@ export interface FileRouteTypes {| '/accept-invitation/$id'| '/api/health'| '/mockups/signup'+ | '/r/$reportId'| '/help/dataforseo-api-key'| '/help/openrouter-api-key'| '/settings/organization'@@ -566,6 +610,7 @@ export interface FileRouteTypes {| '/onboarding'| '/p/$projectId/backlinks'| '/p/$projectId/brand-lookup'+ | '/p/$projectId/context'| '/p/$projectId/domain'| '/p/$projectId/keywords'| '/p/$projectId/prompt-explorer'@@ -576,10 +621,12 @@ export interface FileRouteTypes {| '/api/gsc/oauth/callback'| '/p/$projectId'| '/p/$projectId/rank-tracking/$configId'+ | '/p/$projectId/reports/$reportId'| '/p/$projectId/settings/context'| '/p/$projectId/settings/integrations'| '/p/$projectId/audit'| '/p/$projectId/rank-tracking'+ | '/p/$projectId/reports'| '/p/$projectId/settings'| '/p/$projectId/audit/issues/$resultId'id:@@ -606,6 +653,7 @@ export interface FileRouteTypes {| '/accept-invitation/$id'| '/api/health'| '/mockups/signup'+ | '/r/$reportId'| '/_app/'| '/_project/p/$projectId'| '/_app/help/dataforseo-api-key'@@ -618,6 +666,7 @@ export interface FileRouteTypes {| '/_project/p/$projectId/audit'| '/_project/p/$projectId/backlinks'| '/_project/p/$projectId/brand-lookup'+ | '/_project/p/$projectId/context'| '/_project/p/$projectId/domain'| '/_project/p/$projectId/keywords'| '/_project/p/$projectId/prompt-explorer'@@ -630,10 +679,12 @@ export interface FileRouteTypes {| '/api/gsc/oauth/callback'| '/_project/p/$projectId/'| '/_project/p/$projectId/rank-tracking/$configId'+ | '/_project/p/$projectId/reports/$reportId'| '/_project/p/$projectId/settings/context'| '/_project/p/$projectId/settings/integrations'| '/_project/p/$projectId/audit/'| '/_project/p/$projectId/rank-tracking/'+ | '/_project/p/$projectId/reports/'| '/_project/p/$projectId/settings/'| '/_project/p/$projectId/audit/issues/$resultId'fileRoutesById: FileRoutesById@@ -651,6 +702,7 @@ export interface RootRouteChildren {AcceptInvitationIdRoute: typeof AcceptInvitationIdRouteApiHealthRoute: typeof ApiHealthRouteMockupsSignupRoute: typeof MockupsSignupRoute+ RReportIdRoute: typeof RReportIdRouteApiAuthSplatRoute: typeof ApiAuthSplatRouteApiAutumnSplatRoute: typeof ApiAutumnSplatRouteApiGa4OauthCallbackRoute: typeof ApiGa4OauthCallbackRoute@@ -722,6 +774,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof AppIndexRouteImportparentRoute: typeof AppRouteRoute}+ '/r/$reportId': {+ id: '/r/$reportId'+ path: '/r/$reportId'+ fullPath: '/r/$reportId'+ preLoaderRoute: typeof RReportIdRouteImport+ parentRoute: typeof rootRouteImport+ }'/mockups/signup': {id: '/mockups/signup'path: '/mockups/signup'@@ -953,6 +1012,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof ProjectPProjectIdDomainRouteImportparentRoute: typeof ProjectPProjectIdRouteRoute}+ '/_project/p/$projectId/context': {+ id: '/_project/p/$projectId/context'+ path: '/context'+ fullPath: '/p/$projectId/context'+ preLoaderRoute: typeof ProjectPProjectIdContextRouteImport+ parentRoute: typeof ProjectPProjectIdRouteRoute+ }'/_project/p/$projectId/brand-lookup': {id: '/_project/p/$projectId/brand-lookup'path: '/brand-lookup'@@ -981,6 +1047,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof ProjectPProjectIdSettingsIndexRouteImportparentRoute: typeof ProjectPProjectIdSettingsRoute}+ '/_project/p/$projectId/reports/': {+ id: '/_project/p/$projectId/reports/'+ path: '/reports'+ fullPath: '/p/$projectId/reports/'+ preLoaderRoute: typeof ProjectPProjectIdReportsIndexRouteImport+ parentRoute: typeof ProjectPProjectIdRouteRoute+ }'/_project/p/$projectId/rank-tracking/': {id: '/_project/p/$projectId/rank-tracking/'path: '/'@@ -1009,6 +1082,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof ProjectPProjectIdSettingsContextRouteImportparentRoute: typeof ProjectPProjectIdSettingsRoute}+ '/_project/p/$projectId/reports/$reportId': {+ id: '/_project/p/$projectId/reports/$reportId'+ path: '/reports/$reportId'+ fullPath: '/p/$projectId/reports/$reportId'+ preLoaderRoute: typeof ProjectPProjectIdReportsReportIdRouteImport+ parentRoute: typeof ProjectPProjectIdRouteRoute+ }'/_project/p/$projectId/rank-tracking/$configId': {id: '/_project/p/$projectId/rank-tracking/$configId'path: '/$configId'@@ -1127,6 +1207,7 @@ interface ProjectPProjectIdRouteRouteChildren {ProjectPProjectIdAuditRoute: typeof ProjectPProjectIdAuditRouteWithChildrenProjectPProjectIdBacklinksRoute: typeof ProjectPProjectIdBacklinksRouteProjectPProjectIdBrandLookupRoute: typeof ProjectPProjectIdBrandLookupRoute+ ProjectPProjectIdContextRoute: typeof ProjectPProjectIdContextRouteProjectPProjectIdDomainRoute: typeof ProjectPProjectIdDomainRouteProjectPProjectIdKeywordsRoute: typeof ProjectPProjectIdKeywordsRouteProjectPProjectIdPromptExplorerRoute: typeof ProjectPProjectIdPromptExplorerRoute@@ -1136,6 +1217,8 @@ interface ProjectPProjectIdRouteRouteChildren {ProjectPProjectIdSearchPerformanceRoute: typeof ProjectPProjectIdSearchPerformanceRouteProjectPProjectIdSettingsRoute: typeof ProjectPProjectIdSettingsRouteWithChildrenProjectPProjectIdIndexRoute: typeof ProjectPProjectIdIndexRoute+ ProjectPProjectIdReportsReportIdRoute: typeof ProjectPProjectIdReportsReportIdRoute+ ProjectPProjectIdReportsIndexRoute: typeof ProjectPProjectIdReportsIndexRoute}const ProjectPProjectIdRouteRouteChildren: ProjectPProjectIdRouteRouteChildren =@@ -1143,6 +1226,7 @@ const ProjectPProjectIdRouteRouteChildren: ProjectPProjectIdRouteRouteChildren =ProjectPProjectIdAuditRoute: ProjectPProjectIdAuditRouteWithChildren,ProjectPProjectIdBacklinksRoute: ProjectPProjectIdBacklinksRoute,ProjectPProjectIdBrandLookupRoute: ProjectPProjectIdBrandLookupRoute,+ ProjectPProjectIdContextRoute: ProjectPProjectIdContextRoute,ProjectPProjectIdDomainRoute: ProjectPProjectIdDomainRoute,ProjectPProjectIdKeywordsRoute: ProjectPProjectIdKeywordsRoute,ProjectPProjectIdPromptExplorerRoute: ProjectPProjectIdPromptExplorerRoute,@@ -1154,6 +1238,9 @@ const ProjectPProjectIdRouteRouteChildren: ProjectPProjectIdRouteRouteChildren =ProjectPProjectIdSearchPerformanceRoute,ProjectPProjectIdSettingsRoute: ProjectPProjectIdSettingsRouteWithChildren,ProjectPProjectIdIndexRoute: ProjectPProjectIdIndexRoute,+ ProjectPProjectIdReportsReportIdRoute:+ ProjectPProjectIdReportsReportIdRoute,+ ProjectPProjectIdReportsIndexRoute: ProjectPProjectIdReportsIndexRoute,}const ProjectPProjectIdRouteRouteWithChildren =@@ -1215,6 +1302,7 @@ const rootRouteChildren: RootRouteChildren = {AcceptInvitationIdRoute: AcceptInvitationIdRoute,ApiHealthRoute: ApiHealthRoute,MockupsSignupRoute: MockupsSignupRoute,+ RReportIdRoute: RReportIdRoute,ApiAuthSplatRoute: ApiAuthSplatRoute,ApiAutumnSplatRoute: ApiAutumnSplatRoute,ApiGa4OauthCallbackRoute: ApiGa4OauthCallbackRoute,diff --git a/src/routes/_app/ai.tsx b/src/routes/_app/ai.tsxindex 819188a1..d6c7f2c9 100644--- a/src/routes/_app/ai.tsx+++ b/src/routes/_app/ai.tsx@@ -24,6 +24,10 @@ const SKILL_NAMES = ["link-prospecting","local-seo","seo-audit",+ // Listed so people know it installs, but the skills above deliver through it+ // — running it on its own gives it no research to write up, so it is labelled+ // in the list below rather than presented as something to type.+ "seo-report",];const SKILLS_INSTALL = `npx skills add every-app/open-seo`;const ALL_SKILLS_INSTALL = `npx skills add every-app/open-seo --skill '*'`;@@ -43,6 +47,27 @@ export const Route = createFileRoute("/_app/ai")({component: AiPage,});+function SkillList() {+ return (+ <ul className="mt-2 grid gap-1.5 text-sm text-base-content/70 sm:grid-cols-2">+ {SKILL_NAMES.map((skill) => (+ <li key={skill} className="flex gap-2">+ <span className="text-base-content/35">-</span>+ <span>+ {skill}+ {skill === "seo-report" ? (+ <span className="text-base-content/45">+ {" "}+ (used by the skills above)+ </span>+ ) : null}+ </span>+ </li>+ ))}+ </ul>+ );+}+function AiPage() {const mcpUrl =typeof window === "undefined"@@ -52,7 +77,7 @@ function AiPage() {return (<div className="h-full overflow-auto bg-base-100 px-4 py-12 md:px-6 md:py-16 pb-24 md:pb-12"><div className="mx-auto max-w-3xl">- <h1 className="text-2xl font-semibold">AI & MCP</h1>+ <h1 className="text-2xl font-semibold">MCP setup</h1><p className="mt-2 text-sm text-base-content/70 leading-relaxed">Connect your AI agent to OpenSEO. Run keyword research, SERP analysis,domain lookups, and backlink reviews from your editor or chat.@@ -284,14 +309,7 @@ function AiPage() {<p className="mt-4 text-xs font-medium uppercase tracking-wide text-base-content/50">Available skills</p>- <ul className="mt-2 grid gap-1.5 text-sm text-base-content/70 sm:grid-cols-2">- {SKILL_NAMES.map((skill) => (- <li key={skill} className="flex gap-2">- <span className="text-base-content/35">-</span>- <span>{skill}</span>- </li>- ))}- </ul>+ <SkillList /></div></section>diff --git a/src/routes/_auth.tsx b/src/routes/_auth.tsxindex fcbb4680..681c9a18 100644--- a/src/routes/_auth.tsx+++ b/src/routes/_auth.tsx@@ -6,7 +6,7 @@ import {} from "@/client/features/auth/AuthPage";import { useSession } from "@/lib/auth-client";import { isHostedClientAuthMode } from "@/lib/auth-mode";-import { getCurrentAuthRedirect } from "@/lib/auth-redirect";+import { getCurrentAuthRedirect, isDocumentRoute } from "@/lib/auth-redirect";export const Route = createFileRoute("/_auth")({validateSearch: authRedirectSearchSchema,@@ -28,7 +28,14 @@ function AuthPageLayout() {// Already authenticated: hand off to the destination. If the user is// unverified, that route's useHostedAuthRouteGuard bounces them to// /verify-email — this layout doesn't duplicate that rule.- void navigate({ href: redirectTo, replace: true });+ //+ // A document route (a report at /r/<id>) has no client component, so an SPA+ // navigation there would render an empty shell; ask for a real page load.+ void navigate({+ href: redirectTo,+ replace: true,+ reloadDocument: isDocumentRoute(redirectTo),+ });}, [navigate, redirectTo, session?.user?.id]);if (isHostedMode && (isPending || session?.user?.id)) {diff --git a/src/routes/_project/p/$projectId/context.tsx b/src/routes/_project/p/$projectId/context.tsxnew file mode 100644index 00000000..ea1cff27--- /dev/null+++ b/src/routes/_project/p/$projectId/context.tsx@@ -0,0 +1,30 @@+import { createFileRoute } from "@tanstack/react-router";+import { useQuery } from "@tanstack/react-query";+import { ProjectContextPage } from "@/client/features/projects/project-context/ProjectContextPage";+import { getProjects } from "@/serverFunctions/projects";++export const Route = createFileRoute("/_project/p/$projectId/context")({+ component: ProjectContextRoute,+});++function ProjectContextRoute() {+ const { projectId } = Route.useParams();+ const projectsQuery = useQuery({+ queryKey: ["projects"],+ queryFn: () => getProjects(),+ });+ const project = projectsQuery.data?.find((entry) => entry.id === projectId);++ return (+ <div className="h-full overflow-auto bg-base-100">+ <div className="mx-auto w-full max-w-2xl space-y-8 p-4 py-8 pb-24 sm:p-6 md:py-12 md:pb-12">+ <div>+ <h1 className="text-2xl font-bold tracking-tight">Context</h1>+ <p className="text-sm text-base-content/60">{project?.name ?? " "}</p>+ </div>++ <ProjectContextPage projectId={projectId} />+ </div>+ </div>+ );+}diff --git a/src/routes/_project/p/$projectId/reports/$reportId.tsx b/src/routes/_project/p/$projectId/reports/$reportId.tsxnew file mode 100644index 00000000..39b85afb--- /dev/null+++ b/src/routes/_project/p/$projectId/reports/$reportId.tsx@@ -0,0 +1,286 @@+import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";+import { useQuery } from "@tanstack/react-query";+import { useCallback, useEffect, useRef, useState } from "react";+import {+ ChevronLeft,+ ExternalLink,+ FileDown,+ Maximize2,+ Minimize2,+ MoreHorizontal,+ Trash2,+} from "lucide-react";+import { z } from "zod";+import { PortalMenu } from "@/client/components/PortalMenu";+import { ReportViewer } from "@/client/features/reports/ReportViewer";+import {+ DeleteReportModal,+ formatCreatedBy,+ formatRelativeTime,+ reportQueryKey,+ useDeleteReport,+} from "@/client/features/reports/shared";+import {+ getErrorCode,+ getStandardErrorMessage,+} from "@/client/lib/error-messages";+import { captureClientEvent } from "@/client/lib/posthog";+import { getReport } from "@/serverFunctions/reports";++// Expand lives in the URL, not in state, so a refresh (or a link someone+// pasted) comes back expanded.+const reportDetailSearchSchema = z.object({ full: z.boolean().optional() });++export const Route = createFileRoute(+ "/_project/p/$projectId/reports/$reportId",+)({+ validateSearch: reportDetailSearchSchema,+ component: ReportDetailPage,+});++function ReportDetailPage() {+ const { projectId, reportId } = Route.useParams();+ const { full } = Route.useSearch();+ const navigate = useNavigate({ from: Route.fullPath });+ const [showDelete, setShowDelete] = useState(false);+ const openedRef = useRef<string | null>(null);+ const exitRef = useRef<HTMLButtonElement>(null);++ const reportQuery = useQuery({+ queryKey: reportQueryKey(projectId, reportId),+ queryFn: () => getReport({ data: { projectId, reportId } }),+ // The report may have been replaced by an agent seconds ago; the app-wide+ // 5-minute staleTime would show the previous metadata as current.+ staleTime: 0,+ // A deleted report is a NOT_FOUND, not a flake; retrying it only delays the+ // not-found copy by several seconds.+ retry: false,+ });+ const report = reportQuery.data;++ const deleteMutation = useDeleteReport(projectId, () => {+ setShowDelete(false);+ // `replace`, so Back does not return to the deleted report's URL.+ void navigate({+ to: "/p/$projectId/reports",+ params: { projectId },+ replace: true,+ });+ });++ // useCallback so the Esc listener below is not re-registered every render.+ const setExpanded = useCallback(+ (expanded: boolean) => {+ void navigate({+ search: () => (expanded ? { full: true } : {}),+ replace: true,+ });+ },+ [navigate],+ );++ // One open event per report, once its metadata (and so its skill) is known.+ useEffect(() => {+ if (!report || openedRef.current === report.id) return;+ openedRef.current = report.id;+ captureClientEvent("report:opened", {+ project_id: projectId,+ report_id: report.id,+ skill: report.skill,+ });+ }, [projectId, report]);++ // Esc leaves the expanded view, the same key Modal.tsx uses to close. The+ // listener is on the parent window, and the expanded body is almost entirely+ // the sandboxed iframe: one click inside moves focus into the frame, which+ // has no scripts and so cannot forward the key. Focusing Exit on entry keeps+ // Esc working until the reader clicks into the report; Exit is the+ // guaranteed path.+ useEffect(() => {+ if (!full) return;+ exitRef.current?.focus();+ const handleKeyDown = (event: KeyboardEvent) => {+ if (event.key !== "Escape" || event.defaultPrevented) return;+ event.preventDefault();+ setExpanded(false);+ };+ window.addEventListener("keydown", handleKeyDown);+ return () => window.removeEventListener("keydown", handleKeyDown);+ }, [full, setExpanded]);++ if (reportQuery.isPending) {+ return (+ <div className="flex justify-center py-10">+ <span className="loading loading-spinner loading-md" />+ </div>+ );+ }++ if (reportQuery.isError || !report) {+ return (+ <div className="px-4 py-6 md:px-6">+ <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+ same 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."+ : getStandardErrorMessage(+ reportQuery.error,+ "Failed to load the report",+ )}+ </span>+ </div>+ <Link+ to="/p/$projectId/reports"+ params={{ projectId }}+ className="btn btn-ghost btn-sm"+ >+ ← Back to reports+ </Link>+ </div>+ </div>+ );+ }++ if (full) {+ return (+ <div className="fixed inset-0 z-50 flex flex-col bg-base-100">+ <div className="flex items-center justify-between gap-3 border-b border-base-300 px-4 py-2">+ <span className="truncate text-sm font-medium">{report.title}</span>+ <button+ type="button"+ ref={exitRef}+ className="btn btn-ghost btn-sm gap-1.5"+ onClick={() => setExpanded(false)}+ >+ <Minimize2 className="size-4" />+ Exit+ </button>+ </div>+ <div className="min-h-0 flex-1 p-2">+ <ReportViewer+ src={`/r/${report.id}`}+ title={report.title}+ className="h-full w-full bg-base-100"+ />+ </div>+ </div>+ );+ }++ return (+ <div className="flex h-full min-h-0 flex-col gap-3 px-4 py-4 md:px-6 md:py-6">+ <div className="space-y-3">+ <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 className="min-w-0">+ <h1 className="text-2xl font-semibold">{report.title}</h1>+ <dl className="mt-1.5 flex flex-wrap items-baseline gap-x-6 gap-y-1 text-sm">+ <div className="flex items-baseline gap-1.5">+ <dt className="text-base-content/50">Created by</dt>+ <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>+ </div>+ <div className="flex items-baseline gap-1.5">+ <dt className="text-base-content/50">Updated</dt>+ <dd title={new Date(report.updatedAt).toLocaleString()}>+ {formatRelativeTime(report.updatedAt)}+ </dd>+ </div>+ </dl>+ </div>+ <div className="flex shrink-0 items-center gap-2">+ <button+ type="button"+ className="btn btn-primary btn-sm gap-1.5"+ onClick={() => {+ captureClientEvent("report:exported_pdf", {+ project_id: projectId,+ report_id: report.id,+ });+ // `?print=1` serves the same document with a print() script+ // appended, so the new tab opens the print dialog itself.+ window.open(`/r/${report.id}?print=1`, "_blank", "noopener");+ }}+ >+ <FileDown className="size-4" />+ Export+ </button>+ <PortalMenu+ ariaLabel="Report actions"+ triggerClassName="btn btn-ghost btn-sm btn-square"+ triggerContent={<MoreHorizontal className="size-4" />}+ menuClassName="w-52"+ >+ {(close) => (+ <>+ <li>+ <button+ onClick={() => {+ close();+ setExpanded(true);+ }}+ >+ <Maximize2 className="size-4" />+ Full screen+ </button>+ </li>+ <li>+ <a+ href={`/r/${report.id}`}+ target="_blank"+ rel="noreferrer"+ onClick={close}+ >+ <ExternalLink className="size-4" />+ Open in new tab+ </a>+ </li>+ <li role="separator" className="mx-1 my-1 h-px bg-base-300" />+ <li>+ <button+ className="text-error"+ onClick={() => {+ close();+ setShowDelete(true);+ }}+ >+ <Trash2 className="size-4" />+ Delete+ </button>+ </li>+ </>+ )}+ </PortalMenu>+ </div>+ </div>+ </div>++ <div className="min-h-0 flex-1">+ <ReportViewer src={`/r/${report.id}`} title={report.title} />+ </div>++ {showDelete ? (+ <DeleteReportModal+ title={report.title}+ isPending={deleteMutation.isPending}+ onClose={() => setShowDelete(false)}+ onConfirm={() => deleteMutation.mutate(report.id)}+ />+ ) : null}+ </div>+ );+}diff --git a/src/routes/_project/p/$projectId/reports/index.tsx b/src/routes/_project/p/$projectId/reports/index.tsxnew file mode 100644index 00000000..58e38599--- /dev/null+++ b/src/routes/_project/p/$projectId/reports/index.tsx@@ -0,0 +1,79 @@+import { createFileRoute } from "@tanstack/react-router";+import { useQuery } from "@tanstack/react-query";+import { useState } from "react";+import { ReportsList } from "@/client/features/reports/ReportsList";+import {+ DeleteReportModal,+ reportsQueryKey,+ useDeleteReport,+} from "@/client/features/reports/shared";+import { getStandardErrorMessage } from "@/client/lib/error-messages";+import { listReports, type ReportListItem } from "@/serverFunctions/reports";+import { REPORT_APP_LIST_LIMIT } from "@/types/schemas/reports";++export const Route = createFileRoute("/_project/p/$projectId/reports/")({+ component: ReportsPage,+});++function ReportsPage() {+ const { projectId } = Route.useParams();+ const [pendingDelete, setPendingDelete] = useState<ReportListItem | null>(+ null,+ );++ const reportsQuery = useQuery({+ queryKey: reportsQueryKey(projectId),+ queryFn: () =>+ listReports({ data: { projectId, limit: REPORT_APP_LIST_LIMIT } }),+ // This page exists to inspect what an agent just wrote; the app-wide+ // 5-minute staleTime would show a pre-save list as current.+ staleTime: 0,+ });++ const deleteMutation = useDeleteReport(projectId, () =>+ setPendingDelete(null),+ );++ 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>++ {reportsQuery.isPending ? (+ <div className="flex justify-center py-10">+ <span className="loading loading-spinner loading-md" />+ </div>+ ) : reportsQuery.isError ? (+ <div className="alert alert-error">+ <span className="text-sm">+ {getStandardErrorMessage(+ reportsQuery.error,+ "Failed to load reports",+ )}+ </span>+ </div>+ ) : (+ <ReportsList+ projectId={projectId}+ reports={reportsQuery.data.reports}+ onDelete={setPendingDelete}+ />+ )}+ </div>++ {pendingDelete ? (+ <DeleteReportModal+ title={pendingDelete.title}+ isPending={deleteMutation.isPending}+ onClose={() => setPendingDelete(null)}+ onConfirm={() => deleteMutation.mutate(pendingDelete.id)}+ />+ ) : null}+ </div>+ );+}diff --git a/src/routes/_project/p/$projectId/settings.tsx b/src/routes/_project/p/$projectId/settings.tsxindex 4c6a51a5..e584b6a2 100644--- a/src/routes/_project/p/$projectId/settings.tsx+++ b/src/routes/_project/p/$projectId/settings.tsx@@ -9,7 +9,6 @@ export const Route = createFileRoute("/_project/p/$projectId/settings")({const tabs = [{ to: "/p/$projectId/settings" as const, label: "General", exact: true },- { to: "/p/$projectId/settings/context" as const, label: "Context" },{ to: "/p/$projectId/settings/integrations" as const, label: "Integrations" },];diff --git a/src/routes/_project/p/$projectId/settings/context.tsx b/src/routes/_project/p/$projectId/settings/context.tsxindex 7a18b82e..b488cdb0 100644--- a/src/routes/_project/p/$projectId/settings/context.tsx+++ b/src/routes/_project/p/$projectId/settings/context.tsx@@ -1,13 +1,15 @@-import { createFileRoute } from "@tanstack/react-router";-import { ProjectContextPage } from "@/client/features/projects/project-context/ProjectContextPage";+import { createFileRoute, redirect } from "@tanstack/react-router";+// Context moved out of settings to the project's AI group. Agents have already+// pasted this URL into transcripts, so it redirects rather than 404s.export const Route = createFileRoute("/_project/p/$projectId/settings/context")({- component: ProjectContextRoute,+ beforeLoad: ({ params }) => {+ throw redirect({+ to: "/p/$projectId/context",+ params: { projectId: params.projectId },+ replace: true,+ });+ },},);--function ProjectContextRoute() {- const { projectId } = Route.useParams();- return <ProjectContextPage projectId={projectId} />;-}diff --git a/src/routes/r/$reportId.ts b/src/routes/r/$reportId.tsnew file mode 100644index 00000000..e884414f--- /dev/null+++ b/src/routes/r/$reportId.ts@@ -0,0 +1,134 @@+import { env } from "cloudflare:workers";+import { createFileRoute } from "@tanstack/react-router";+import { isHostedAuthMode } from "@/lib/auth-mode";+import { resolveUserContextFromHeaders } from "@/middleware/ensure-user/resolve";+import { ProjectRepository } from "@/server/features/projects/repositories/ProjectRepository";+import { ReportRepository } from "@/server/features/reports/repositories/ReportRepository";+import { asAppError } from "@/server/lib/errors";+import { PRINT_SCRIPT, reportCsp, textResponse } from "@/shared/report-sandbox";++// The report viewer: the stored document, served byte for byte from the app's+// own origin and locked down by REPORT_CSP. A raw-Response route, so no React+// and no `_authenticated` guard runs — this handler does its own auth.++// One body for "no such report" and "another organization's report", so report+// ids cannot be probed for existence. An archived project of the reader's own+// organization gets its own message: the reader is already a member, so naming+// it leaks nothing and "does not exist" would send them hunting.+const NOT_FOUND_BODY =+ "This report does not exist or you do not have access to it.";++const reportNotFound = () => textResponse(NOT_FOUND_BODY, 404);++/**+ * Appends PRINT_SCRIPT to a stored document, last so it runs after the page.+ * The splice happens without parsing a document we did not write, so a report+ * ending in a dangling `<script src="…" ` absorbs whatever we put on our tag;+ * an attribute-free tag gives such a document nothing but a valueless+ * attribute name, and printing simply no-ops there.+ */+function withPrintScript(html: string): string {+ const tag = `<script>${PRINT_SCRIPT}</script>`;+ const bodyClose = html.lastIndexOf("</body>");+ if (bodyClose !== -1)+ return html.slice(0, bodyClose) + tag + html.slice(bodyClose);+ const htmlClose = html.lastIndexOf("</html>");+ if (htmlClose !== -1)+ return html.slice(0, htmlClose) + tag + html.slice(htmlClose);+ return html + tag;+}++async function handleReportRequest(+ reportId: string,+ request: Request,+): Promise<Response> {+ let context;+ try {+ context = await resolveUserContextFromHeaders(request.headers);+ } catch (error) {+ // Only a missing session is answered here, and only in hosted mode. A+ // config or session-store failure must not masquerade as "you are logged+ // out", and the self-hosted modes have no sign-in page to complete.+ if (asAppError(error)?.code !== "UNAUTHENTICATED") throw error;+ if (!isHostedAuthMode(env.AUTH_MODE)) {+ return textResponse("Sign in to read this report.", 401);+ }+ // The most likely real entry: someone opening a report link in a browser+ // whose session expired.+ const target = `/r/${encodeURIComponent(reportId)}`;+ return new Response(null, {+ status: 302,+ headers: {+ Location: `/sign-in?redirect=${encodeURIComponent(target)}`,+ "Cache-Control": "private, no-store",+ },+ });+ }++ // Reads go through the repository rather than ReportService: the service's+ // job is the save-time caps and refusal copy, and the only policy on a render+ // is the authorization below, which happens here. Authorize before touching+ // the `html` column, so an unauthorized request never pulls a document onto+ // the worker's heap.+ const projectId = await ReportRepository.getReportProjectId(reportId);+ if (!projectId) return reportNotFound();++ // The canonical project-access check — org ownership plus "not archived" —+ // the same one ensureUserMiddleware uses for server functions. Org ids are+ // never compared by hand.+ const project = await ProjectRepository.getProjectForOrganization(+ projectId,+ context.organizationId,+ );+ if (!project) {+ const archived = await ProjectRepository.getArchivedProjectForOrganization(+ projectId,+ context.organizationId,+ );+ if (!archived) return reportNotFound();+ return textResponse(+ `This project is archived, so its reports are hidden. Restore ${archived.name} to read them.`,+ 404,+ );+ }++ const html = await ReportRepository.getReportHtml(projectId, reportId);+ if (html === null) return reportNotFound();++ // Print mode. "Export" in the app opens `/r/<id>?print=1`, and the appended+ // script is the only thing that makes that a one-click path: the tab opens+ // the browser's print dialog itself.+ const print = new URL(request.url).searchParams.get("print") === "1";++ return new Response(print ? withPrintScript(html) : html, {+ status: 200,+ headers: {+ "Content-Type": "text/html; charset=utf-8",+ "Content-Security-Policy": reportCsp(print),+ // The sandbox allows popups to escape, so a link in a report opens a real+ // page that would otherwise keep a handle on this tab and be able to+ // navigate it. COOP severs that handle. Ignored when framed, which is+ // what the in-app viewer wants.+ "Cross-Origin-Opener-Policy": "same-origin",+ "Referrer-Policy": "no-referrer",+ "X-Content-Type-Options": "nosniff",+ "Cache-Control": "private, no-store",+ },+ });+}++// Handler only, and no `component` on purpose: a component would pull this file+// (and `cloudflare:workers` with it) into the client bundle. That leaves+// `/r/$reportId` matchable but componentless in the client route tree, so+// anything navigating to it client-side must hard-navigate — see+// isDocumentRoute in src/lib/auth-redirect.ts.+export const Route = createFileRoute("/r/$reportId")({+ server: {+ handlers: {+ GET: ({ params, request }) =>+ handleReportRequest(params.reportId, request),+ },+ },+});++export { handleReportRequest, NOT_FOUND_BODY };diff --git a/src/server/auth/repositories/AuthRepository.ts b/src/server/auth/repositories/AuthRepository.tsindex 64292f21..2f8e1e08 100644--- a/src/server/auth/repositories/AuthRepository.ts+++ b/src/server/auth/repositories/AuthRepository.ts@@ -5,6 +5,7 @@ import {desc,eq,gt,+ inArray,lt,notExists,sql,@@ -95,6 +96,15 @@ async function getHostedUser(userId: string) {});}+/** Names for a set of user ids in one query; missing ids are simply absent. */+async function getHostedUserNames(userIds: string[]) {+ if (userIds.length === 0) return [];+ return db+ .select({ id: authUser.id, name: authUser.name })+ .from(authUser)+ .where(inArray(authUser.id, userIds));+}+// The per-request membership check: session.activeOrganizationId is only an// identity hint, this row is the authorization fact. Returns null when the// user is not (or no longer) a member.@@ -184,5 +194,6 @@ export const AuthRepository = {getLastActiveOrganizationId,setLastActiveOrganization,getHostedUser,+ getHostedUserNames,hasPendingInvitationForEmail,} as const;diff --git a/src/server/features/projects/repositories/ProjectRepository.ts b/src/server/features/projects/repositories/ProjectRepository.tsindex 175c395d..0fe127ab 100644--- a/src/server/features/projects/repositories/ProjectRepository.ts+++ b/src/server/features/projects/repositories/ProjectRepository.ts@@ -44,6 +44,27 @@ async function getProjectForOrganization(return project ?? null;}+// The archived counterpart of getProjectForOrganization, for the surfaces that+// owe the reader "this project is archived" instead of a bare not-found. Still+// org-scoped, so it adds no cross-org existence oracle.+async function getArchivedProjectForOrganization(+ projectId: string,+ organizationId: string,+) {+ const [project] = await db+ .select()+ .from(projects)+ .where(+ and(+ eq(projects.id, projectId),+ eq(projects.organizationId, organizationId),+ isNotNull(projects.archivedAt),+ ),+ )+ .limit(1);+ return project ?? null;+}+// Look up a project by id alone (no org scoping). Only for trusted server// contexts that have already authorized access another way — e.g. the// SAM chat Durable Object, whose connections are authorized in the Worker@@ -193,6 +214,7 @@ export const ProjectRepository = {listArchivedProjects,countProjects,getProjectForOrganization,+ getArchivedProjectForOrganization,getProjectById,createProject,updateProject,diff --git a/src/server/features/reports/reportRoute.test.ts b/src/server/features/reports/reportRoute.test.tsnew file mode 100644index 00000000..64171943--- /dev/null+++ b/src/server/features/reports/reportRoute.test.ts@@ -0,0 +1,172 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { handleReportRequest, NOT_FOUND_BODY } from "@/routes/r/$reportId";+import { PRINT_SCRIPT, REPORT_CSP, reportCsp } from "@/shared/report-sandbox";++const mocks = vi.hoisted(() => ({+ resolveUserContextFromHeaders: vi.fn(),+ getProjectForOrganization: vi.fn(),+ getArchivedProjectForOrganization: vi.fn(),+ getReportProjectId: vi.fn(),+ getReportHtml: vi.fn(),+}));++vi.mock("cloudflare:workers", () => ({ env: { AUTH_MODE: "hosted" } }));+vi.mock("@/middleware/ensure-user/resolve", () => ({+ resolveUserContextFromHeaders: mocks.resolveUserContextFromHeaders,+}));+vi.mock("@/server/features/projects/repositories/ProjectRepository", () => ({+ ProjectRepository: {+ getProjectForOrganization: mocks.getProjectForOrganization,+ getArchivedProjectForOrganization: mocks.getArchivedProjectForOrganization,+ },+}));+vi.mock("@/server/features/reports/repositories/ReportRepository", () => ({+ ReportRepository: {+ getReportProjectId: mocks.getReportProjectId,+ getReportHtml: mocks.getReportHtml,+ },+}));++const HTML = "<!doctype html><html><body>report</body></html>";++const request = () => new Request("https://app.example.com/r/report-1");++beforeEach(() => {+ mocks.resolveUserContextFromHeaders.mockResolvedValue({+ userId: "user-1",+ userEmail: "[email protected]",+ emailVerified: true,+ organizationId: "org-1",+ role: "owner",+ });+ mocks.getReportProjectId.mockResolvedValue("project-1");+ mocks.getProjectForOrganization.mockResolvedValue({ id: "project-1" });+ mocks.getArchivedProjectForOrganization.mockResolvedValue(null);+ mocks.getReportHtml.mockResolvedValue(HTML);+});++describe("handleReportRequest", () => {+ it("serves the stored document with the sandbox headers", async () => {+ const response = await handleReportRequest("report-1", request());++ expect(response.status).toBe(200);+ expect(await response.text()).toBe(HTML);+ expect(Object.fromEntries(response.headers)).toEqual({+ "content-type": "text/html; charset=utf-8",+ "content-security-policy": REPORT_CSP,+ "cross-origin-opener-policy": "same-origin",+ "referrer-policy": "no-referrer",+ "x-content-type-options": "nosniff",+ "cache-control": "private, no-store",+ });+ // Authorized against the row's project before the document is read, so an+ // unauthorized request never pulls one onto the worker's heap.+ expect(mocks.getProjectForOrganization).toHaveBeenCalledWith(+ "project-1",+ "org-1",+ );+ });++ // "Export" is one click only because the served document prints itself; the+ // script-src hash is what lets that one script run while the report's own+ // scripts stay blocked.+ it("appends the print script and widens the sandbox in print mode", async () => {+ const response = await handleReportRequest(+ "report-1",+ new Request("https://app.example.com/r/report-1?print=1"),+ );++ expect(await response.text()).toBe(+ `<!doctype html><html><body>report<script>${PRINT_SCRIPT}</script></body></html>`,+ );+ expect(response.headers.get("content-security-policy")).toBe(+ reportCsp(true),+ );+ });++ // See withPrintScript: a dangling `<script src="…" ` absorbs any attribute on+ // the tag we splice in.+ it("gives a dangling script tag in the document no attribute to absorb", async () => {+ mocks.getReportHtml.mockResolvedValue(+ '<!doctype html><html><body><script src="https://evil.example/x.js" </body></html>',+ );++ const response = await handleReportRequest(+ "report-1",+ new Request("https://app.example.com/r/report-1?print=1"),+ );++ const body = await response.text();+ // The spliced tag carries no attributes, so the dangling tag absorbs+ // nothing but a valueless `<script` attribute name.+ expect(body).toBe(+ '<!doctype html><html><body><script src="https://evil.example/x.js" ' ++ `<script>${PRINT_SCRIPT}</script></body></html>`,+ );+ expect(response.headers.get("content-security-policy")).not.toContain(+ "'nonce-",+ );+ });++ it.each([+ [+ "an unknown report",+ () => mocks.getReportProjectId.mockResolvedValue(null),+ ],+ // Another organization's project is indistinguishable from one that does+ // not exist, on purpose.+ [+ "a project the viewer cannot access",+ () => mocks.getProjectForOrganization.mockResolvedValue(null),+ ],+ ])("answers the same 404 for %s", async (_case, arrange) => {+ arrange();++ const response = await handleReportRequest("report-1", request());++ expect(response.status).toBe(404);+ expect(await response.text()).toBe(NOT_FOUND_BODY);+ expect(mocks.getReportHtml).not.toHaveBeenCalled();+ });++ it("names an archived project of the viewer's own organization", async () => {+ mocks.getProjectForOrganization.mockResolvedValue(null);+ mocks.getArchivedProjectForOrganization.mockResolvedValue({+ id: "project-1",+ name: "badseo.dev",+ });++ const response = await handleReportRequest("report-1", request());++ expect(response.status).toBe(404);+ expect(await response.text()).toBe(+ "This project is archived, so its reports are hidden. Restore badseo.dev to read them.",+ );+ expect(mocks.getReportHtml).not.toHaveBeenCalled();+ });++ it("bounces an unauthenticated viewer to sign-in", async () => {+ mocks.resolveUserContextFromHeaders.mockRejectedValue(+ new Error("UNAUTHENTICATED"),+ );++ const response = await handleReportRequest("report-1", request());++ expect(response.status).toBe(302);+ expect(response.headers.get("location")).toBe(+ "/sign-in?redirect=%2Fr%2Freport-1",+ );+ });++ // A session-store or config failure must not read as "you are logged out" and+ // send the reader round a sign-in loop that cannot fix it.+ it("lets a non-auth failure escape instead of bouncing to sign-in", async () => {+ mocks.resolveUserContextFromHeaders.mockRejectedValue(+ new Error("AUTH_CONFIG_MISSING"),+ );++ await expect(handleReportRequest("report-1", request())).rejects.toThrow(+ "AUTH_CONFIG_MISSING",+ );+ });+});diff --git a/src/server/features/reports/repositories/ReportRepository.ts b/src/server/features/reports/repositories/ReportRepository.tsnew file mode 100644index 00000000..c4c36091--- /dev/null+++ b/src/server/features/reports/repositories/ReportRepository.ts@@ -0,0 +1,203 @@+import { and, count, desc, eq, sum } from "drizzle-orm";+import { db } from "@/db";+import { projects, reports } from "@/db/schema";+import type { ReportMetadata } from "@/types/schemas/reports";++// Backing store for reports. Every query filters on `project_id` as well as+// `id`: callers authorize the projectId they were given, not the child row, so+// a guessed id from another project must not resolve.+//+// `html` is never selected here except by getReportHtml — a list read that+// pulled documents would put megabytes on the app worker's heap.++const metadataColumns = {+ id: reports.id,+ projectId: reports.projectId,+ title: reports.title,+ summary: reports.summary,+ skill: reports.skill,+ createdBy: reports.createdBy,+ createdByUserId: reports.createdByUserId,+ sizeBytes: reports.sizeBytes,+ createdAt: reports.createdAt,+ updatedAt: reports.updatedAt,+};++async function listReports(params: {+ projectId: string;+ limit: number;+ offset: number;+}): Promise<ReportMetadata[]> {+ return (+ db+ .select(metadataColumns)+ .from(reports)+ .where(eq(reports.projectId, params.projectId))+ // Matches reports_project_updated_idx; `id` breaks same-timestamp ties so+ // the order is total.+ .orderBy(desc(reports.updatedAt), desc(reports.id))+ .limit(params.limit)+ .offset(params.offset)+ );+}++async function getReport(+ projectId: string,+ reportId: string,+): Promise<ReportMetadata | null> {+ const [row] = await db+ .select(metadataColumns)+ .from(reports)+ .where(and(eq(reports.id, reportId), eq(reports.projectId, projectId)))+ .limit(1);+ return row ?? null;+}++// The one query that is not project-scoped, and the only one allowed to be:+// the render route (/r/<reportId>) arrives with a report id and nothing else.+// It returns the owning project id alone — no content, no metadata — and the+// caller authorizes that project before reading anything else.+async function getReportProjectId(reportId: string): Promise<string | null> {+ const [row] = await db+ .select({ projectId: reports.projectId })+ .from(reports)+ .where(eq(reports.id, reportId))+ .limit(1);+ return row?.projectId ?? null;+}++async function getReportHtml(+ projectId: string,+ reportId: string,+): Promise<string | null> {+ const [row] = await db+ .select({ html: reports.html })+ .from(reports)+ .where(and(eq(reports.id, reportId), eq(reports.projectId, projectId)))+ .limit(1);+ return row?.html ?? null;+}++// Metadata and document in one read, for get_report's includeHtml path — the+// only caller that needs both, and the only reason to select `html` alongside+// the metadata columns.+async function getReportWithHtml(+ projectId: string,+ reportId: string,+): Promise<(ReportMetadata & { html: string }) | null> {+ const [row] = await db+ .select({ ...metadataColumns, html: reports.html })+ .from(reports)+ .where(and(eq(reports.id, reportId), eq(reports.projectId, projectId)))+ .limit(1);+ return row ?? null;+}++async function findReportByTitle(+ projectId: string,+ title: string,+): Promise<{ id: string; title: string } | null> {+ const [row] = await db+ .select({ id: reports.id, title: reports.title })+ .from(reports)+ .where(and(eq(reports.projectId, projectId), eq(reports.title, title)))+ .limit(1);+ return row ?? null;+}++async function countReports(projectId: string): Promise<number> {+ const [row] = await db+ .select({ value: count() })+ .from(reports)+ .where(eq(reports.projectId, projectId));+ return row?.value ?? 0;+}++// Stored bytes across every project the organization owns. SUM() comes back as+// a string on Postgres and a number on SQLite, and as null on an empty set.+async function sumReportBytesForOrganization(+ organizationId: string,+): Promise<number> {+ const [row] = await db+ .select({ value: sum(reports.sizeBytes) })+ .from(reports)+ .innerJoin(projects, eq(projects.id, reports.projectId))+ .where(eq(projects.organizationId, organizationId));+ return Number(row?.value ?? 0);+}++// createdAt/updatedAt are stamped here, not left to the column defaults: the+// two dialects' defaults render different formats and the list order is a+// lexicographic comparison against app-written ISO stamps.+async function insertReport(params: {+ id: string;+ projectId: string;+ title: string;+ summary: string;+ html: string;+ skill: string | null;+ createdBy: string;+ createdByUserId: string;+ sizeBytes: number;+}): Promise<void> {+ const now = new Date().toISOString();+ await db+ .insert(reports)+ .values({ ...params, createdAt: now, updatedAt: now });+}++// Content only: `created_by` and `created_by_user_id` are stamped at create and+// never re-stamped, so "created by" keeps meaning what it says after an agent+// replaces the body.+async function updateReportContent(params: {+ reportId: string;+ projectId: string;+ title: string;+ summary: string;+ html: string;+ skill: string | null;+ sizeBytes: number;+}): Promise<void> {+ await db+ .update(reports)+ .set({+ title: params.title,+ summary: params.summary,+ html: params.html,+ skill: params.skill,+ sizeBytes: params.sizeBytes,+ updatedAt: new Date().toISOString(),+ })+ .where(+ and(+ eq(reports.id, params.reportId),+ eq(reports.projectId, params.projectId),+ ),+ );+}++/** True when a row was deleted; false when the id is not in this project. */+async function deleteReport(+ projectId: string,+ reportId: string,+): Promise<boolean> {+ const deleted = await db+ .delete(reports)+ .where(and(eq(reports.id, reportId), eq(reports.projectId, projectId)))+ .returning({ id: reports.id });+ return deleted.length > 0;+}++export const ReportRepository = {+ listReports,+ getReport,+ getReportProjectId,+ getReportHtml,+ getReportWithHtml,+ findReportByTitle,+ countReports,+ sumReportBytesForOrganization,+ insertReport,+ updateReportContent,+ deleteReport,+} as const;diff --git a/src/server/features/reports/services/ReportService.test.ts b/src/server/features/reports/services/ReportService.test.tsnew file mode 100644index 00000000..1e3408b7--- /dev/null+++ b/src/server/features/reports/services/ReportService.test.ts@@ -0,0 +1,195 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { formatCount } from "@/shared/format";+import {+ REPORT_MAX_BYTES_PER_ORG,+ REPORT_MAX_PER_PROJECT,+} from "@/types/schemas/reports";+import { deleteReport, getReport, saveReport } from "./ReportService";++const mocks = vi.hoisted(() => ({+ listReports: vi.fn(),+ getReport: vi.fn(),+ findReportByTitle: vi.fn(),+ countReports: vi.fn(),+ sumReportBytesForOrganization: vi.fn(),+ insertReport: vi.fn(),+ updateReportContent: vi.fn(),+ deleteReport: vi.fn(),+}));++vi.mock("@/server/features/reports/repositories/ReportRepository", () => ({+ ReportRepository: mocks,+}));++const html = "<!doctype html><html><body>Hi</body></html>";++const save = (overrides: Partial<Parameters<typeof saveReport>[0]> = {}) =>+ saveReport({+ projectId: "project_1",+ organizationId: "org_1",+ title: "badseo.dev SEO audit, Sep 2026",+ summary: "One clear verdict.",+ html,+ createdBy: "Claude Code",+ createdByUserId: "user_1",+ ...overrides,+ });++const storedReport = {+ id: "report_1",+ projectId: "project_1",+ title: "badseo.dev SEO audit, Sep 2026",+ summary: "One clear verdict.",+ skill: "seo-audit",+ createdBy: "Codex",+ createdByUserId: "user_original",+ sizeBytes: 42,+ createdAt: "2026-09-01T10:00:00.000Z",+ updatedAt: "2026-09-01T10:00:00.000Z",+};++describe("saveReport", () => {+ beforeEach(() => {+ mocks.findReportByTitle.mockResolvedValue(null);+ mocks.countReports.mockResolvedValue(0);+ mocks.sumReportBytesForOrganization.mockResolvedValue(0);+ mocks.getReport.mockResolvedValue(storedReport);+ });++ it("updates in place, keeping the stored skill and attribution", async () => {+ const result = await save({ reportId: "report_1", title: "New title" });++ expect(result).toEqual({+ reportId: "report_1",+ title: "New title",+ created: false,+ htmlBytes: html.length,+ });+ expect(mocks.insertReport).not.toHaveBeenCalled();+ // Exact payload: the attribution columns are absent, so an overwrite keeps+ // the original saver, and an omitted `skill` keeps the stored slug rather+ // than clearing it.+ expect(mocks.updateReportContent).toHaveBeenCalledWith({+ reportId: "report_1",+ projectId: "project_1",+ title: "New title",+ summary: "One clear verdict.",+ html,+ skill: "seo-audit",+ sizeBytes: html.length,+ });+ });++ it("refuses an unknown reportId", async () => {+ mocks.getReport.mockResolvedValue(null);++ await expect(save({ reportId: "report_gone" })).rejects.toThrow(+ "No report report_gone in this project. Call list_reports, or omit reportId to create a new one.",+ );+ expect(mocks.updateReportContent).not.toHaveBeenCalled();+ });++ it("refuses an over-long title and writes nothing", async () => {+ await expect(save({ title: "T".repeat(143) })).rejects.toThrow(+ "Title is 143 characters; the limit is 120. Shorten it and save again.",+ );+ expect(mocks.insertReport).not.toHaveBeenCalled();+ });++ it("refuses an over-long summary", async () => {+ await expect(save({ summary: "s".repeat(2720) })).rejects.toThrow(+ "Summary is 2,720 characters; the limit is 2,500. Shorten it and save again.",+ );+ });++ it("measures the byte cap in UTF-8, not code units", async () => {+ // 320,000 two-byte characters: under the cap by String.length, over it by+ // the bytes that actually reach the column.+ await expect(save({ html: "é".repeat(320_000) })).rejects.toThrow(+ "Report is 640 KB; the limit is 500 KB. Inlined images are the usual cause. Remove them and save again.",+ );+ expect(mocks.insertReport).not.toHaveBeenCalled();+ });++ it("refuses a document that stopped mid-write", async () => {+ await expect(save({ html: "<html><body>half a repo" })).rejects.toThrow(+ "The HTML has no closing </html>; the model stopped early. On Codex, escape backticks and ${.",+ );+ });++ it("refuses a rename onto another report's title", async () => {+ mocks.findReportByTitle.mockResolvedValue({+ id: "report_2",+ title: "Taken",+ });++ await expect(+ save({ reportId: "report_1", title: "Taken" }),+ ).rejects.toThrow(+ "A report titled 'Taken' exists (id report_2). Pass reportId to update it, or change the title.",+ );+ expect(mocks.updateReportContent).not.toHaveBeenCalled();+ });++ it("refuses a create at the per-project cap", async () => {+ mocks.countReports.mockResolvedValue(REPORT_MAX_PER_PROJECT);++ await expect(save()).rejects.toThrow(+ `This project has ${formatCount(REPORT_MAX_PER_PROJECT)} reports, the limit. Delete one from the Reports page.`,+ );+ expect(mocks.insertReport).not.toHaveBeenCalled();+ });++ it("applies the cap to creates only, not updates", async () => {+ mocks.countReports.mockResolvedValue(REPORT_MAX_PER_PROJECT);++ await expect(save({ reportId: "report_1" })).resolves.toMatchObject({+ created: false,+ });+ });++ // The per-project cap bounds nothing on its own: projects are unlimited, and+ // save_report is free, so this is the guardrail on total storage.+ it("refuses a save that would push the organization over its byte ceiling", async () => {+ mocks.sumReportBytesForOrganization.mockResolvedValue(+ REPORT_MAX_BYTES_PER_ORG,+ );++ await expect(save()).rejects.toThrow(+ `This organization is storing ${formatCount(REPORT_MAX_BYTES_PER_ORG / 1_000_000)} MB of reports, the limit. Delete reports you no longer need from the Reports page.`,+ );+ expect(mocks.insertReport).not.toHaveBeenCalled();+ });++ it("counts an update against the ceiling net of the bytes it replaces", async () => {+ // At the ceiling, but the row being replaced is bigger than the new one.+ mocks.sumReportBytesForOrganization.mockResolvedValue(+ REPORT_MAX_BYTES_PER_ORG,+ );+ mocks.getReport.mockResolvedValue({ ...storedReport, sizeBytes: 1_000 });++ await expect(save({ reportId: "report_1" })).resolves.toMatchObject({+ created: false,+ });+ });+});++describe("reads and deletes", () => {+ it("scopes a read to the project and refuses an unknown id", async () => {+ mocks.getReport.mockResolvedValue(null);++ await expect(getReport("project_1", "report_gone")).rejects.toThrow(+ "No report report_gone in this project. Call list_reports to see what exists.",+ );+ expect(mocks.getReport).toHaveBeenCalledWith("project_1", "report_gone");+ });++ it("refuses a delete whose id is not in this project", async () => {+ mocks.deleteReport.mockResolvedValue(false);++ await expect(deleteReport("project_1", "report_gone")).rejects.toThrow(+ "No report report_gone in this project.",+ );+ expect(mocks.deleteReport).toHaveBeenCalledWith("project_1", "report_gone");+ });+});diff --git a/src/server/features/reports/services/ReportService.ts b/src/server/features/reports/services/ReportService.tsnew file mode 100644index 00000000..cca07e19--- /dev/null+++ b/src/server/features/reports/services/ReportService.ts@@ -0,0 +1,243 @@+import { ReportRepository } from "@/server/features/reports/repositories/ReportRepository";+import { AppError } from "@/server/lib/errors";+import { formatCount } from "@/shared/format";+import {+ REPORT_MAX_BYTES_PER_ORG,+ REPORT_MAX_HTML_BYTES,+ REPORT_MAX_PER_PROJECT,+ REPORT_MAX_SUMMARY_CHARS,+ REPORT_MAX_TITLE_CHARS,+ type ReportMetadata,+} from "@/types/schemas/reports";++// Reports: the HTML documents agents write for a project. 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` (ensureUserMiddleware for server functions,+// withMcpProjectAuth for MCP tools) and every query is scoped to it.++// The over-size refusal prints the actual size and the limit side by side, so+// they must never round to the same number: 499,900 bytes reading "500 KB; the+// limit is 500 KB" tells the agent to shrink by nothing. Round the actual size+// up and the limit down.+const kbUp = (bytes: number) => `${formatCount(Math.ceil(bytes / 1000))} KB`;+const kbDown = (bytes: number) => `${formatCount(Math.floor(bytes / 1000))} KB`;+const mb = (bytes: number) =>+ `${formatCount(Math.round(bytes / 1_000_000))} MB`;++const htmlBytes = (html: string) => new TextEncoder().encode(html).length;++type SaveReportParams = {+ projectId: string;+ /** The project's organization, for the workspace-wide storage ceiling. */+ organizationId: string;+ reportId?: string;+ title: string;+ summary: string;+ html: string;+ skill?: 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 report untouched — there is no+ * version history, and a half-written overwrite is unrecoverable.+ */+export async function saveReport(params: SaveReportParams): Promise<{+ reportId: string;+ title: string;+ created: boolean;+ htmlBytes: number;+}> {+ const { projectId, title, summary, html } = params;++ if (title.length > REPORT_MAX_TITLE_CHARS) {+ throw new AppError(+ "VALIDATION_ERROR",+ `Title is ${formatCount(title.length)} characters; the limit is ${formatCount(REPORT_MAX_TITLE_CHARS)}. Shorten it and save again.`,+ );+ }+ if (summary.length > REPORT_MAX_SUMMARY_CHARS) {+ throw new AppError(+ "VALIDATION_ERROR",+ `Summary is ${formatCount(summary.length)} characters; the limit is ${formatCount(REPORT_MAX_SUMMARY_CHARS)}. Shorten it and save again.`,+ );+ }+ // UTF-8 bytes, not code units: a `.length` check understates multi-byte+ // content and is what actually reaches the column and the worker's heap.+ const sizeBytes = htmlBytes(html);+ if (sizeBytes > REPORT_MAX_HTML_BYTES) {+ throw new AppError(+ "VALIDATION_ERROR",+ `Report is ${kbUp(sizeBytes)}; the limit is ${kbDown(REPORT_MAX_HTML_BYTES)}. Inlined images are the usual cause. Remove them and save again.`,+ );+ }+ // The cheap structural check, not an HTML parser: models have stopped+ // mid-document with no error, and update-in-place would silently destroy the+ // previous good report.+ const trimmed = html.trim().toLowerCase();+ if (!trimmed.includes("<html") || !trimmed.endsWith("</html>")) {+ throw new AppError(+ "VALIDATION_ERROR",+ "The HTML has no closing </html>; the model stopped early. On Codex, escape backticks and ${.",+ );+ }++ const existing = params.reportId+ ? await ReportRepository.getReport(projectId, params.reportId)+ : null;+ if (params.reportId && !existing) {+ throw new AppError(+ "NOT_FOUND",+ `No report ${params.reportId} in this project. Call list_reports, or omit reportId to create a new one.`,+ );+ }++ // Titles are unique within a project, which the skills state as a contract+ // and which keeps the duplicate pointer below unambiguous. A rename has to+ // clear the same bar as a create.+ const clash = await ReportRepository.findReportByTitle(projectId, title);+ if (clash && clash.id !== existing?.id) {+ throw new AppError(+ "VALIDATION_ERROR",+ // A same-title save without a reportId is almost always an agent that+ // forgot to list first; point it at the id it should have reused.+ `A report titled '${clash.title}' exists (id ${clash.id}). Pass reportId to update it, or change the title.`,+ );+ }++ if (!existing) {+ // Plain read-then-write: concurrent saves can both pass at 99, so a project+ // may briefly hold a few more than the cap. That is accepted — this is a+ // storage guardrail, not an invariant, and the next save refuses.+ const total = await ReportRepository.countReports(projectId);+ if (total >= REPORT_MAX_PER_PROJECT) {+ throw new AppError(+ "VALIDATION_ERROR",+ `This project has ${formatCount(REPORT_MAX_PER_PROJECT)} reports, the limit. Delete one from the Reports page.`,+ );+ }+ }++ // The workspace-wide ceiling, checked on updates as well as creates: projects+ // are unlimited, so the per-project cap on its own bounds nothing, and an+ // update that grows a report is the other way to add bytes.+ const orgBytes = await ReportRepository.sumReportBytesForOrganization(+ params.organizationId,+ );+ if (+ orgBytes - (existing?.sizeBytes ?? 0) + sizeBytes >+ REPORT_MAX_BYTES_PER_ORG+ ) {+ throw new AppError(+ "VALIDATION_ERROR",+ `This organization is storing ${mb(orgBytes)} of reports, the limit. Delete reports you no longer need from the Reports page.`,+ );+ }++ if (existing) {+ await ReportRepository.updateReportContent({+ reportId: existing.id,+ projectId,+ title,+ summary,+ 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.+ skill: params.skill ?? existing.skill,+ sizeBytes,+ });+ return {+ reportId: existing.id,+ title,+ created: false,+ htmlBytes: sizeBytes,+ };+ }++ const id = crypto.randomUUID();+ await ReportRepository.insertReport({+ id,+ projectId,+ title,+ summary,+ html,+ skill: params.skill ?? null,+ createdBy: params.createdBy,+ createdByUserId: params.createdByUserId,+ sizeBytes,+ });+ return { reportId: id, title, created: true, htmlBytes: sizeBytes };+}++/** Metadata only, newest update first. `remaining` is the room left under the cap. */+async function listReports(params: {+ projectId: string;+ limit: number;+ offset: number;+}): Promise<{+ reports: ReportMetadata[];+ totalCount: number;+ remaining: number;+}> {+ const [rows, totalCount] = await Promise.all([+ ReportRepository.listReports(params),+ ReportRepository.countReports(params.projectId),+ ]);+ return {+ reports: rows,+ totalCount,+ remaining: Math.max(0, REPORT_MAX_PER_PROJECT - totalCount),+ };+}++export async function getReport(+ projectId: string,+ reportId: string,+): Promise<ReportMetadata> {+ const report = await ReportRepository.getReport(projectId, reportId);+ if (!report) throw notFound(reportId);+ return report;+}++/** The only reader of the `html` column, and it reads the metadata with it. */+async function getReportWithHtml(+ projectId: string,+ reportId: string,+): Promise<{ report: ReportMetadata; html: string }> {+ const row = await ReportRepository.getReportWithHtml(projectId, reportId);+ if (!row) throw notFound(reportId);+ const { html, ...report } = row;+ return { report, html };+}++export async function deleteReport(+ projectId: string,+ reportId: string,+): Promise<void> {+ const deleted = await ReportRepository.deleteReport(projectId, reportId);+ if (!deleted) throw notFound(reportId);+}++// Shared by the reads and the delete, where `reportId` is a required argument —+// so no "omit reportId" hint here; that one belongs to save_report, which has+// its own message above.+function notFound(reportId: string) {+ return new AppError(+ "NOT_FOUND",+ `No report ${reportId} in this project. Call list_reports to see what exists.`,+ );+}++export const ReportService = {+ saveReport,+ listReports,+ getReport,+ getReportWithHtml,+ deleteReport,+} as const;diff --git a/src/server/features/sam/openseo-fact-sheet.md b/src/server/features/sam/openseo-fact-sheet.mdindex ac7e5845..41e3958a 100644--- a/src/server/features/sam/openseo-fact-sheet.md+++ b/src/server/features/sam/openseo-fact-sheet.md@@ -131,6 +131,7 @@ OpenSEO's app includes these practical workflows:- Rank tracking: track keyword positions over time.- Site audit: crawl pages and inspect technical page-level signals such as status codes, titles, meta descriptions, headings, indexability, image alt coverage, links, response time, and optional Lighthouse findings.- Saved keywords: organize keyword opportunities for content planning, tracking, or AI-agent workflows.+- Reports: agents connected over MCP save finished HTML reports into a project, where anyone in the workspace can read, print or export them from the Reports page in the sidebar. You cannot save reports yourself. Reports use no credits, and each project holds up to 100.- AI and MCP setup: connect OpenSEO to agents and install OpenSEO skills.## What users can do after subscribingdiff --git a/src/server/features/sam/samSkills.ts b/src/server/features/sam/samSkills.tsindex 4f99f35f..7e3ff344 100644--- a/src/server/features/sam/samSkills.ts+++ b/src/server/features/sam/samSkills.ts@@ -22,16 +22,15 @@ const skillFiles = import.meta.glob<string>("/.agents/skills/*/SKILL.md", {const SAM_SURFACE_NOTE = `> Surface note: you are SAM, running inside the OpenSEO app. You are already> authenticated and scoped to the user's current project — skip any "verify the> MCP connection", "choose a project", or skill-install steps. You have no-> local filesystem: skip local-folder and file steps, and store durable-> outputs in project context instead (sections, competitors, key pages,-> research log).+> local filesystem: skip local-folder and file steps.>> Your project context is already in your system prompt — read it there; there-> is no get_project_context tool here. Write changes with-> update_project_context. If a skill step needs a tool you don't have (e.g.-> project creation), say so and point the user at the app page rather than-> improvising. Keep SAM's chat voice: a skill's output format is a-> checklist of what to cover, not a document template to fill.`;+> is no get_project_context tool here. Write durable facts about the business+> back with update_project_context. You have no report tools: skip any step+> that says to deliver through the seo-report skill or to save a report, and+> give the findings in chat, short and scannable.+> If a skill step needs a tool you don't have (e.g. project creation), say so+> and point the user at the app page rather than improvising.`;type SamSkill = { name: string; description: string; body: string };@@ -53,6 +52,8 @@ function parseSkill(path: string, raw: string): SamSkill | null {// Public for `npx skills add` users but not an in-app workflow: it drafts// GitHub issues for contributors, which SAM has no surface for.if (frontmatter.name === "simple-issue-description") return null;+ // SAM has no report tools, so the report-writing skill has nothing to drive.+ if (frontmatter.name === "seo-report") return null;return {name: frontmatter.name,description: frontmatter.description,diff --git a/src/server/mcp/client-label.ts b/src/server/mcp/client-label.tsnew file mode 100644index 00000000..34d4a527--- /dev/null+++ b/src/server/mcp/client-label.ts@@ -0,0 +1,57 @@+// Which client made this call, as a display label. It is a self-reported hint,+// never an identity: nothing authorizes, filters or bills on it, and the only+// value nothing outside the server can influence is the user id on the auth+// context. Kept a pure function in a leaf module so it is testable without the+// transport.+//+// Both signals are attacker-controlled, so the fallback is stripped to a safe+// character set and truncated.++/**+ * Cap on the stored client label. The label is derived from a fully+ * attacker-controlled `User-Agent` (or client-supplied client info), and an+ * unbounded one would land in the table, the app's list column and every+ * list_reports text block.+ */+const REPORT_MAX_CREATED_BY_CHARS = 60;++/** Verified User-Agent strings: `claude-code/2.1.259 (sdk-cli)`, `codex-mcp-client/0.149.1`. */+const KNOWN_CLIENTS: [RegExp, string][] = [+ [/^claude-code\//i, "Claude Code"],+ [/^codex-mcp-client\//i, "Codex"],+];++/**+ * What a call with no usable User-Agent and no client info is labelled. API-key+ * calls are the realistic case: they reach the same entry point as every other+ * request, carrying whatever (or no) User-Agent the caller sent.+ */+export const DEFAULT_CLIENT_LABEL = "API key";++/** Spaces are kept so a client title like "VS Code" survives; everything else is dropped. */+function sanitizeLabel(value: string): string {+ return value+ .replace(/[^A-Za-z0-9._+\- ]/g, "")+ .replace(/\s+/g, " ")+ .trim()+ .slice(0, REPORT_MAX_CREATED_BY_CHARS)+ .trim();+}++export function resolveClientLabel(input: {+ userAgent?: string | null;+ /** The reserved clientInfo envelope key's `title`, when the client sends one. */+ clientTitle?: string | null;+}): string {+ const userAgent = input.userAgent?.trim() ?? "";+ for (const [pattern, label] of KNOWN_CLIENTS) {+ if (pattern.test(userAgent)) return label;+ }++ const title = sanitizeLabel(input.clientTitle ?? "");+ if (title) return title;++ // The product token only: "curl/8.4.0" is a client, "8.4.0" is noise.+ const productToken = sanitizeLabel(userAgent.split(/[\s/]/)[0] ?? "");+ return productToken || DEFAULT_CLIENT_LABEL;+}diff --git a/src/server/mcp/context.ts b/src/server/mcp/context.tsindex 2df60c8d..875df96a 100644--- a/src/server/mcp/context.ts+++ b/src/server/mcp/context.ts@@ -1,6 +1,10 @@-import type { ServerContext } from "@modelcontextprotocol/server";+import {+ CLIENT_INFO_META_KEY,+ type ServerContext,+} from "@modelcontextprotocol/server";import { z } from "zod";import type { BillingCustomerContext } from "@/server/billing/subscription";+import { resolveClientLabel } from "@/server/mcp/client-label";import { buildDashboardUrl } from "@/server/mcp/urls";export type ToolAuthContext = {@@ -23,6 +27,12 @@ export type ToolAuthContext = {scopes: string[];clientId: string | null;baseUrl: string;+ // Which client made the call ("Claude Code", "Codex", "API key", …), for+ // display only — a self-reported hint, never an identity. Reports stamp it+ // into `created_by`; nothing authorizes, filters or bills on it. Always set+ // on the MCP path; absent on hand-built contexts (SAM), which name+ // themselves at the tool instead.+ clientLabel?: string;};export type ToolContext = {@@ -55,6 +65,11 @@ const applicationAuthContextSchema = z.object({// clientId/scopes in transport.ts from authInfo instead of props.clientId: z.string().min(1).nullable().optional(),scopes: z.array(z.string()).optional(),+ // Raw request User-Agent, stamped per request by the transport. The only+ // client signal present on every call: initialize's clientInfo is not+ // visible on a later tools/call, and this transport never populates+ // ServerContext.http.req.+ userAgent: z.string().optional(),});type ApplicationAuthContext = z.infer<typeof applicationAuthContextSchema>;@@ -83,8 +98,28 @@ export function createWorkersOAuthMcpProps(};}+// Clients on the 2026-07-28 protocol may carry their identity per request in+// the reserved clientInfo key, which the SDK lifts out of `_meta` into+// `mcpReq.envelope` before any handler runs — so the envelope is the only place+// to look. It is client-supplied and typed as an open envelope, so parse it+// rather than reaching into it.+const clientInfoMetaSchema = z.object({+ [CLIENT_INFO_META_KEY]: z.object({ title: z.string().optional() }).optional(),+});++// Not named McpRequestContext: the SDK exports a type by that name. `mcpReq`+// is optional so the two auth-fallback tests do not have to build a request+// fixture.+type ToolCallContext = Pick<ServerContext, "http"> &+ Partial<Pick<ServerContext, "mcpReq">>;++function readClientTitle(context: ToolCallContext): string | undefined {+ const parsed = clientInfoMetaSchema.safeParse(context.mcpReq?.envelope);+ return parsed.success ? parsed.data[CLIENT_INFO_META_KEY]?.title : undefined;+}+export function createMcpToolContext(- context: Pick<ServerContext, "http">,+ context: ToolCallContext,props: McpProps,): ToolContext {const result = workersOAuthMcpPropsSchema.safeParse(props);@@ -117,6 +152,10 @@ export function createMcpToolContext(orgScope,clientId,scopes,+ clientLabel: resolveClientLabel({+ userAgent: applicationAuth.userAgent,+ clientTitle: readClientTitle(context),+ }),},};}diff --git a/src/server/mcp/formatters.ts b/src/server/mcp/formatters.tsindex b3bd2047..bf3646ec 100644--- a/src/server/mcp/formatters.ts+++ b/src/server/mcp/formatters.ts@@ -52,3 +52,13 @@ export function mcpResponse(opts: {}return result;}++/**+ * A short preview of a long text field for a list response. mcpResponse puts+ * `text` AND `structuredContent` on the wire and clients count both, so a list+ * page carries every preview twice — full summaries or instructions at their+ * caps would be tens of KB on the one call every agent is told to make first.+ * The single-item read is where the whole field is returned.+ */+export const truncatePreview = (value: string, max = 300) =>+ value.length <= max ? value : `${value.slice(0, max).trimEnd()}…`;diff --git a/src/server/mcp/server.ts b/src/server/mcp/server.tsindex fa6b4442..1956aa68 100644--- a/src/server/mcp/server.ts+++ b/src/server/mcp/server.ts@@ -57,6 +57,11 @@ import {getLocalRankGridTool,listBusinessCategoriesTool,} from "@/server/mcp/tools/local-seo-tools";+import {+ getReportTool,+ listReportsTool,+ saveReportTool,+} from "@/server/mcp/tools/report-tools";import { researchKeywordsTool } from "@/server/mcp/tools/research-keywords";import { saveKeywordsTool } from "@/server/mcp/tools/save-keywords";import {@@ -205,6 +210,9 @@ export function createOpenSeoMcpServer(authProps: McpProps) {register(getAuditStatusTool);register(getAuditIssuesTool);register(getAuditPagesTool);+ register(saveReportTool);+ register(listReportsTool);+ register(getReportTool);return server;}diff --git a/src/server/mcp/tools/meta-only-response.test.ts b/src/server/mcp/tools/meta-only-response.test.tsindex 58125b78..3e6ffc8e 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 reportTools from "./report-tools";import * as researchKeywords from "./research-keywords";import * as runRankTracker from "./run-rank-tracker";import * as saveKeywords from "./save-keywords";@@ -53,6 +54,7 @@ const toolExports: Record<string, unknown> = {...localSeoTools,...projectContext,...removeRankTrackingKeywords,+ ...reportTools,...researchKeywords,...runRankTracker,...saveKeywords,@@ -78,14 +80,20 @@ function isToolDefinition(value: unknown): value is ToolDefinition {const TOOLS_DIR = join(import.meta.dirname, ".");-/** Every `export const <name>Tool = {` in a tools file, with the character- * offset where that tool's source begins. */+/** Every tool's source start in a tools file: `export const <name>Tool =`, and+ * the `export function build<Name>Tool(` factories, whose handler body sits+ * before the `export const` that calls them (update_project_context). */function toolSpans(source: string): { exportName: string; start: number }[] {const spans: { exportName: string; start: number }[] = [];- const pattern = /export const (\w+Tool)\s*=/g;+ const pattern =+ /export (?:const (\w+Tool)\s*=|function build(\w+Tool)\s*\()/g;let match: RegExpExecArray | null;while ((match = pattern.exec(source)) !== null) {- spans.push({ exportName: match[1], start: match.index });+ const built = match[2];+ spans.push({+ exportName: match[1] ?? `${built[0].toLowerCase()}${built.slice(1)}`,+ start: match.index,+ });}return spans;}@@ -153,8 +161,8 @@ function toolsReturningMetaOnly(): string[] {* output schema that accepts a meta-only payload.** Asserting the reverse (that *every* tool tolerates a meta-only payload) would- * be wrong: 43 of the 46 tools legitimately require output fields they always- * populate, and loosening those would forfeit real validation.+ * be wrong: most of the 50 registered tools legitimately require output fields+ * they always populate, and loosening those would forfeit real validation.*/describe("tools that answer with meta but no structured content", () => {it("declare an output schema that accepts a meta-only response", async () => {diff --git a/src/server/mcp/tools/project-context.ts b/src/server/mcp/tools/project-context.tsindex 805b3631..c8f59830 100644--- a/src/server/mcp/tools/project-context.ts+++ b/src/server/mcp/tools/project-context.ts@@ -26,7 +26,7 @@ const contextOutputSchema = {...optionalMetaOutputSchema,} as const;-const contextPath = (projectId: string) => `/p/${projectId}/settings/context`;+const contextPath = (projectId: string) => `/p/${projectId}/context`;const getInputSchema = { projectId: projectIdSchema } as const;diff --git a/src/server/mcp/tools/report-tools.test.ts b/src/server/mcp/tools/report-tools.test.tsnew file mode 100644index 00000000..0f98593a--- /dev/null+++ b/src/server/mcp/tools/report-tools.test.ts@@ -0,0 +1,197 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { REPORT_MAX_PER_PROJECT } from "@/types/schemas/reports";+import { getReportTool, listReportsTool, saveReportTool } from "./report-tools";+import { makeToolContext, textContent } from "./tool-test-support";++// Mocked at the repository seam, not the service: the tools' contract is that a+// save reaches storage with the right attribution and reads back through the+// real caps and the real refusal copy.+const mocks = vi.hoisted(() => ({+ getProjectForOrganization: vi.fn(),+ listReports: vi.fn(),+ getReport: vi.fn(),+ getReportWithHtml: vi.fn(),+ findReportByTitle: vi.fn(),+ countReports: vi.fn(),+ sumReportBytesForOrganization: vi.fn(),+ insertReport: vi.fn(),+ updateReportContent: vi.fn(),+ captureServerEvent: vi.fn(),+}));++vi.mock("cloudflare:workers", () => ({ env: {} }));+vi.mock("@/server/features/projects/services/ProjectService", () => ({+ ProjectService: {+ getProjectForOrganization: mocks.getProjectForOrganization,+ },+}));+vi.mock("@/server/features/reports/repositories/ReportRepository", () => ({+ ReportRepository: mocks,+}));+vi.mock("@/server/lib/posthog", () => ({+ captureServerEvent: mocks.captureServerEvent,+}));++const projectId = "project_1";+const reportId = "report_1";+const html = "<!doctype html><html><body><h1>Audit</h1></body></html>";++const storedReport = (overrides: Record<string, unknown> = {}) => ({+ id: reportId,+ projectId,+ title: "badseo.dev SEO audit, Sep 2026",+ summary: "Verdict: titles are the problem.",+ skill: "seo-audit",+ createdBy: "Claude Code",+ createdByUserId: "user_123",+ sizeBytes: 15_517,+ createdAt: "2026-09-01T10:00:00.000Z",+ updatedAt: "2026-09-01T10:00:00.000Z",+ ...overrides,+});++beforeEach(() => {+ mocks.getProjectForOrganization.mockResolvedValue({ id: projectId });+ mocks.countReports.mockResolvedValue(3);+ mocks.sumReportBytesForOrganization.mockResolvedValue(0);+ mocks.findReportByTitle.mockResolvedValue(null);+ mocks.captureServerEvent.mockResolvedValue(undefined);+});++const toolContext = makeToolContext({ clientLabel: "Claude Code" });++describe("save_report", () => {+ it("creates a report attributed to the client and answers with its app URL", async () => {+ const result = await saveReportTool.handler(+ {+ projectId,+ title: "badseo.dev SEO audit, Sep 2026",+ summary: "Verdict: titles are the problem.",+ html,+ skill: "seo-audit",+ },+ toolContext,+ );++ expect(mocks.insertReport).toHaveBeenCalledWith(+ expect.objectContaining({+ projectId,+ skill: "seo-audit",+ createdBy: "Claude Code",+ createdByUserId: "user_123",+ }),+ );+ const saved = result.structuredContent;+ expect(saved.created).toBe(true);+ expect(saved.url).toBe(+ `https://open-seo.test/p/${projectId}/reports/${saved.reportId}`,+ );+ expect(textContent(result)).toContain(saved.url);+ expect(mocks.captureServerEvent).toHaveBeenCalledWith(+ expect.objectContaining({+ event: "report:saved",+ properties: {+ project_id: projectId,+ skill: "seo-audit",+ size_bytes: new TextEncoder().encode(html).length,+ client: "Claude Code",+ is_update: false,+ source: "mcp",+ },+ }),+ );+ });++ it("replaces the existing report when a reportId is passed, keeping its attribution", async () => {+ mocks.getReport.mockResolvedValue(storedReport());++ const result = await saveReportTool.handler(+ {+ projectId,+ reportId,+ title: "badseo.dev SEO audit, Sep 2026",+ summary: "Verdict: titles are still the problem.",+ html,+ },+ toolContext,+ );++ expect(mocks.insertReport).not.toHaveBeenCalled();+ expect(mocks.updateReportContent).toHaveBeenCalledWith(+ expect.objectContaining({ reportId, projectId }),+ );+ expect(result.structuredContent.created).toBe(false);+ });++ it("passes a service refusal through with its message", async () => {+ mocks.findReportByTitle.mockResolvedValue({+ id: reportId,+ title: "badseo.dev SEO audit, Sep 2026",+ });++ await expect(+ saveReportTool.handler(+ {+ projectId,+ title: "badseo.dev SEO audit, Sep 2026",+ summary: "Verdict.",+ html,+ },+ toolContext,+ ),+ ).rejects.toThrow(/Pass reportId to update it/);+ expect(mocks.insertReport).not.toHaveBeenCalled();+ });+});++describe("list_reports", () => {+ it("truncates the summary in both the text block and the structured rows", async () => {+ const longSummary = "x".repeat(400);+ mocks.listReports.mockResolvedValue([+ storedReport({ summary: longSummary }),+ ]);+ mocks.countReports.mockResolvedValue(1);++ const result = await listReportsTool.handler({ projectId }, toolContext);++ expect(mocks.listReports).toHaveBeenCalledWith({+ projectId,+ limit: 20,+ offset: 0,+ });+ const rows = result.structuredContent.reports;+ expect(rows[0].summary).toBe(`${"x".repeat(300)}…`);+ expect(result.structuredContent).toMatchObject({+ totalCount: 1,+ rowCount: 1,+ remaining: REPORT_MAX_PER_PROJECT - 1,+ });+ const text = textContent(result);+ expect(text).toContain(`${"x".repeat(300)}…`);+ expect(text).not.toContain("x".repeat(301));+ expect(text).toContain("1 reports.");+ });+});++describe("get_report", () => {+ it("returns the summary without the document, and the document on request", async () => {+ mocks.getReport.mockResolvedValue(storedReport());+ mocks.getReportWithHtml.mockResolvedValue({ ...storedReport(), html });++ const metadataOnly = await getReportTool.handler(+ { projectId, reportId },+ toolContext,+ );+ expect(mocks.getReportWithHtml).not.toHaveBeenCalled();+ expect(textContent(metadataOnly)).not.toContain(html);+ expect(metadataOnly.structuredContent.report).toMatchObject({+ htmlBytes: 15_517,+ });++ const withHtml = await getReportTool.handler(+ { projectId, reportId, includeHtml: true },+ toolContext,+ );+ expect(textContent(withHtml)).toContain(html);+ });+});diff --git a/src/server/mcp/tools/report-tools.ts b/src/server/mcp/tools/report-tools.tsnew file mode 100644index 00000000..0307947c--- /dev/null+++ b/src/server/mcp/tools/report-tools.ts@@ -0,0 +1,334 @@+import { z } from "zod";+import { ReportService } from "@/server/features/reports/services/ReportService";+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_DEFAULT_LIST_LIMIT,+ REPORT_MAX_HTML_BYTES,+ REPORT_MAX_LIST_LIMIT,+ REPORT_MAX_SKILL_CHARS,+ REPORT_MAX_SUMMARY_CHARS,+ REPORT_MAX_TITLE_CHARS,+ type ReportMetadata,+} from "@/types/schemas/reports";++// The three report tools. All free (they touch only the app DB), all wrapped in+// withMcpProjectAuth, and all answering with the in-app report URL so an agent+// can hand back a link instead of pasting a document into chat.++const reportPath = (projectId: string, reportId: string) =>+ `/p/${projectId}/reports/${reportId}`;++// Small reports are real (a one-page summary is a few hundred bytes), and+// rounding those to "0 KB" reads like a failed save.+const size = (bytes: number) =>+ bytes < 1000+ ? `${formatCount(bytes)} bytes`+ : `${formatCount(Math.round(bytes / 1000))} KB`;++const metaLine = (report: ReportMetadata) =>+ [+ report.skill ?? "no skill",+ report.createdBy,+ `updated ${report.updatedAt.slice(0, 10)}`,+ size(report.sizeBytes),+ ].join(" · ");++// ---------------------------------------------------------------- save_report++const saveInputSchema = {+ projectId: projectIdSchema,+ title: z+ .string()+ .min(1)+ .describe(+ `Specific title shown in the report list, e.g. "badseo.dev SEO audit, Sep 2026". Never a generic label like "SEO Report". Max ${REPORT_MAX_TITLE_CHARS} characters.`,+ ),+ summary: z+ .string()+ .min(1)+ .describe(+ `Markdown, under ${formatCount(REPORT_MAX_SUMMARY_CHARS)} characters: the verdict, the single top action, and the key numbers. This is what list_reports returns and what you or another agent read instead of the HTML.`,+ ),+ html: z+ .string()+ .min(1)+ .describe(+ `The complete self-contained HTML document. Inline all CSS; no external requests of any kind (no CDNs, no web fonts, no images by URL, no fetch) — they are blocked when the report renders, and scripts are blocked too. No backticks and no \${ anywhere, including inside CSS content strings: some clients (Codex) pass this argument through a JavaScript template literal and either sequence corrupts the document. It must be a whole document, ending in </html>: a save that stops mid-document is refused, because there is no version history to fall back on. Aim under 80 KB so the report can be read back whole in one call; the hard limit is ${formatCount(REPORT_MAX_HTML_BYTES)} bytes. Use the seo-report skill's starter template when you have it; otherwise a plain semantic document — heading, short sections, one table — reads fine.`,+ ),+ reportId: z+ .string()+ .min(1)+ .optional()+ .describe(+ "Omit to create a new report. Pass an id from list_reports to replace that report in place — there is no version history and the old content is gone.",+ ),+ skill: z+ .string()+ .max(REPORT_MAX_SKILL_CHARS)+ .optional()+ .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 "—".',+ ),+} as const;++const saveOutputSchema = {+ reportId: z.string(),+ title: z.string(),+ created: z.boolean(),+ htmlBytes: z.number(),+ url: z.string(),+ ...optionalMetaOutputSchema,+} as const;++export const saveReportTool = {+ name: "save_report",+ config: {+ title: "Save report",+ description:+ "Saves a finished HTML report to this project, where anyone in the workspace can read and print it. Uses no credits. Call list_reports first and pass the matching reportId to replace that report instead of creating a near-duplicate — a save whose title already exists in the project is refused. Give the report a specific title (the subject and the period), a summary carrying the verdict, the top action and the key numbers, and the skill slug you are running. Then reply with the returned url, a one-line verdict and the single top action; do not paste the report into chat.",+ inputSchema: saveInputSchema,+ outputSchema: saveOutputSchema,+ annotations: {+ readOnlyHint: false,+ openWorldHint: false,+ // A save with a reportId overwrites the stored document, with no undo.+ destructiveHint: true,+ },+ },+ handler: withMcpProjectAuth(+ async (args: z.infer<z.ZodObject<typeof saveInputSchema>>, context) => {+ const saved = await ReportService.saveReport({+ projectId: args.projectId,+ organizationId: context.auth.organizationId,+ reportId: args.reportId,+ title: args.title,+ summary: args.summary,+ html: args.html,+ skill: args.skill,+ // Never taken from the model: the label the transport derived from the+ // request.+ createdBy: context.auth.clientLabel ?? DEFAULT_CLIENT_LABEL,+ createdByUserId: context.auth.userId,+ });++ const path = reportPath(args.projectId, saved.reportId);+ const url = buildDashboardUrl(context.baseUrl, path);++ await captureServerEvent({+ distinctId: context.auth.userId,+ event: "report:saved",+ organizationId: context.auth.organizationId,+ properties: {+ project_id: args.projectId,+ skill: args.skill,+ size_bytes: saved.htmlBytes,+ client: context.auth.clientLabel,+ is_update: !saved.created,+ source: "mcp",+ },+ });++ return mcpResponse({+ text: `${saved.created ? "Saved" : "Replaced"} report "${saved.title}" (${size(saved.htmlBytes)}). Open it at ${url}. Reply with this link, a one-line verdict, and the single top action — do not paste the report into chat.`,+ meta: buildProjectMeta(context, args.projectId, path),+ structuredContent: {+ reportId: saved.reportId,+ title: saved.title,+ created: saved.created,+ htmlBytes: saved.htmlBytes,+ url,+ },+ });+ },+ ),+};++// --------------------------------------------------------------- list_reports++const listInputSchema = {+ projectId: projectIdSchema,+ limit: z+ .number()+ .int()+ .min(1)+ .max(REPORT_MAX_LIST_LIMIT)+ .optional()+ .describe(+ `Reports per page, newest update first. Default ${REPORT_DEFAULT_LIST_LIMIT}, max ${REPORT_MAX_LIST_LIMIT}.`,+ ),+ offset: z+ .number()+ .int()+ .min(0)+ .optional()+ .describe("Rows to skip. Omit for the first page."),+} as const;++const listOutputSchema = {+ reports: z.array(looseObjectOutputSchema),+ totalCount: z.number(),+ rowCount: z.number(),+ remaining: z.number(),+ ...optionalMetaOutputSchema,+} as const;++export const listReportsTool = {+ name: "list_reports",+ config: {+ title: "List reports",+ description:+ "Lists this project's saved reports, newest update first: id, title, skill, who saved it, when, and a short summary preview. Uses no credits. Call this before save_report and reuse the id of the report you are redoing, so the project collects one good report per job instead of near-duplicates. Read the full summary with get_report; the HTML is only worth fetching to edit a specific passage.",+ inputSchema: listInputSchema,+ outputSchema: listOutputSchema,+ annotations: {+ readOnlyHint: true,+ openWorldHint: false,+ destructiveHint: false,+ },+ },+ handler: withMcpProjectAuth(+ async (args: z.infer<z.ZodObject<typeof listInputSchema>>, context) => {+ const limit = args.limit ?? REPORT_DEFAULT_LIST_LIMIT;+ const offset = args.offset ?? 0;+ const { reports, totalCount, remaining } =+ await ReportService.listReports({+ projectId: args.projectId,+ limit,+ offset,+ });++ const rows = reports.map((report) => ({+ ...report,+ summary: truncatePreview(report.summary),+ }));++ const blocks = rows.map((report) =>+ [+ `${report.id} ${report.title}`,+ ` ${metaLine(report)}`,+ ` ${report.summary}`,+ ].join("\n"),+ );+ const shownEnd = offset + rows.length;+ const more =+ shownEnd < totalCount+ ? `${rows.length} shown, more available — pass offset ${shownEnd} for the next page.`+ : `${rows.length} shown.`;++ return mcpResponse({+ text: [+ rows.length > 0+ ? blocks.join("\n\n")+ : "No reports saved for this project yet.",+ "",+ `${formatCount(totalCount)} reports. ${more}`,+ ].join("\n"),+ meta: buildProjectMeta(+ context,+ args.projectId,+ `/p/${args.projectId}/reports`,+ ),+ structuredContent: {+ reports: rows,+ totalCount,+ rowCount: rows.length,+ remaining,+ },+ });+ },+ ),+};++// ----------------------------------------------------------------- get_report++const getInputSchema = {+ projectId: projectIdSchema,+ reportId: z+ .string()+ .min(1)+ .describe("Report id from list_reports or save_report."),+ includeHtml: z+ .boolean()+ .optional()+ .describe(+ "Include the full HTML document. Leave it off unless you need to edit a specific passage: an 80 KB report is roughly 20,000 tokens, and a larger one is truncated by many clients. When you do fetch it, compare new TextEncoder().encode(html).length against the returned htmlBytes — if it is smaller your client truncated the read, so send the user to the app instead of saving the short version back over the good report.",+ ),+} as const;++const getOutputSchema = {+ report: looseObjectOutputSchema,+ ...optionalMetaOutputSchema,+} as const;++export const getReportTool = {+ name: "get_report",+ config: {+ title: "Get report",+ description:+ "Reads one saved report: title, skill, attribution, size, and the full summary. Uses no credits. This is the cheap way to see what a report already says before you revise it — pass includeHtml only when you need the document itself.",+ inputSchema: getInputSchema,+ outputSchema: getOutputSchema,+ annotations: {+ readOnlyHint: true,+ openWorldHint: false,+ destructiveHint: false,+ },+ },+ handler: withMcpProjectAuth(+ async (args: z.infer<z.ZodObject<typeof getInputSchema>>, context) => {+ // One read either way: includeHtml pulls the metadata and the document+ // together rather than selecting the same row twice.+ const { report, html } = args.includeHtml+ ? await ReportService.getReportWithHtml(args.projectId, args.reportId)+ : {+ report: await ReportService.getReport(+ args.projectId,+ args.reportId,+ ),+ html: null,+ };++ const path = reportPath(args.projectId, report.id);+ const url = buildDashboardUrl(context.baseUrl, path);++ return mcpResponse({+ // The document goes in `text` only. It is what the agent actually+ // reads, and repeating it in structuredContent would double a payload+ // that is already the largest thing these tools return.+ text: [+ `${report.title} (${report.id})`,+ metaLine(report),+ url,+ "",+ report.summary,+ ...(html+ ? [+ "",+ `HTML (${formatCount(report.sizeBytes)} bytes as stored — if what you received is shorter, your client truncated it and you must not save it back):`,+ html,+ ]+ : []),+ ].join("\n"),+ meta: buildProjectMeta(context, args.projectId, path),+ structuredContent: {+ report: {+ ...report,+ htmlBytes: report.sizeBytes,+ url,+ },+ },+ });+ },+ ),+};diff --git a/src/server/mcp/transport.ts b/src/server/mcp/transport.tsindex cc8ebbd6..b59f61f0 100644--- a/src/server/mcp/transport.ts+++ b/src/server/mcp/transport.ts@@ -220,6 +220,10 @@ export async function handleAuthenticatedOpenSeoMcpRequest(organizationId: organization.organizationId,role: organization.role,orgScope: "user",+ // The only per-request client signal that reaches a tools/call: initialize's+ // clientInfo is long gone by then and this transport never populates+ // ServerContext.http.req. Display only (report attribution).+ userAgent: request.headers.get("user-agent") ?? undefined,});return createRequestHandler(requestProps, [hostedUrl.hostname,@@ -247,6 +251,7 @@ export async function handleSelfHostedOpenSeoMcpRequest(userEmail: identity.userEmail,organizationId: identity.organizationId,baseUrl: getPublicOrigin(request),+ userAgent: request.headers.get("user-agent") ?? undefined,});return createRequestHandler(props)(request, env, ctx);diff --git a/src/serverFunctions/reports.ts b/src/serverFunctions/reports.tsnew file mode 100644index 00000000..0eb5bedc--- /dev/null+++ b/src/serverFunctions/reports.ts@@ -0,0 +1,91 @@+import { createServerFn } from "@tanstack/react-start";+import { omit } from "remeda";+import { z } from "zod";+import { AuthRepository } from "@/server/auth/repositories/AuthRepository";+import { ReportService } from "@/server/features/reports/services/ReportService";+import { requireProjectContext } from "@/serverFunctions/middleware";+import {+ REPORT_APP_LIST_LIMIT,+ REPORT_DEFAULT_LIST_LIMIT,+ type ReportMetadata,+} from "@/types/schemas/reports";++// Reports read path for the app. The `projectId` field in each validator is+// what triggers project authorization (ADR 0001); the service never authorizes.+// The stored `html` is deliberately unreachable from here — the /r/<id> render+// route is its only reader, so no server function can pull documents into the+// app worker's heap.++const listReportsSchema = z.object({+ projectId: z.string().min(1),+ limit: z.number().int().min(1).max(REPORT_APP_LIST_LIMIT).optional(),+ offset: z.number().int().min(0).optional(),+});++const reportRefSchema = z.object({+ projectId: z.string().min(1),+ reportId: z.string().min(1),+});++/**+ * `summary` is dropped on the way out: it is written for agents, the app never+ * renders it, and it is the one field here big enough to matter on the wire.+ * MCP and the share page still read it.+ */+export type ReportListItem = Omit<ReportMetadata, "summary"> & {+ /**+ * Display name behind `createdByUserId`, or null when the user is gone+ * (GDPR re-attribution) or has no name. The UI falls back to the client+ * label alone.+ */+ createdByName: string | null;+};++// One lookup for all savers, not one per row.+async function withCreatorNames(+ reports: ReportMetadata[],+): Promise<ReportListItem[]> {+ const userIds = [...new Set(reports.map((report) => report.createdByUserId))];+ const users = await AuthRepository.getHostedUserNames(userIds);+ const names = new Map(users.map((user) => [user.id, user.name]));+ return reports.map((report) => ({+ ...omit(report, ["summary"]),+ createdByName: names.get(report.createdByUserId) ?? null,+ }));+}++export const listReports = createServerFn({ method: "POST" })+ .middleware(requireProjectContext)+ .validator(listReportsSchema)+ .handler(async ({ data, context }) => {+ const result = await ReportService.listReports({+ projectId: context.projectId,+ limit: data.limit ?? REPORT_DEFAULT_LIST_LIMIT,+ offset: data.offset ?? 0,+ });+ // 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) };+ });++/** Metadata only. The document itself is served by /r/<reportId>. */+export const getReport = createServerFn({ method: "POST" })+ .middleware(requireProjectContext)+ .validator(reportRefSchema)+ .handler(async ({ data, context }) => {+ const report = await ReportService.getReport(+ context.projectId,+ data.reportId,+ );+ const [withName] = await withCreatorNames([report]);+ return withName;+ });++export const deleteReport = createServerFn({ method: "POST" })+ .middleware(requireProjectContext)+ .validator(reportRefSchema)+ .handler(async ({ data, context }) => {+ await ReportService.deleteReport(context.projectId, data.reportId);+ return { reportId: data.reportId };+ });diff --git a/src/shared/format.ts b/src/shared/format.tsnew file mode 100644index 00000000..bf243ac1--- /dev/null+++ b/src/shared/format.ts@@ -0,0 +1,2 @@+/** Thousands separators for a count in server copy: "500,000". */+export const formatCount = (n: number) => n.toLocaleString("en-US");diff --git a/src/shared/report-sandbox.test.ts b/src/shared/report-sandbox.test.tsnew file mode 100644index 00000000..61d849ba--- /dev/null+++ b/src/shared/report-sandbox.test.ts@@ -0,0 +1,18 @@+import { describe, expect, it } from "vitest";+import { PRINT_SCRIPT, PRINT_SCRIPT_SHA256, reportCsp } from "./report-sandbox";++describe("report-sandbox", () => {+ // The hash is hardcoded because the CSP needs it synchronously, so editing+ // PRINT_SCRIPT without editing the constant would block the print script and+ // silently break "Export". This is what catches that.+ it("authorizes the print script by the digest of its own text", async () => {+ const digest = await crypto.subtle.digest(+ "SHA-256",+ new TextEncoder().encode(PRINT_SCRIPT),+ );+ const base64 = btoa(String.fromCharCode(...new Uint8Array(digest)));++ expect(base64).toBe(PRINT_SCRIPT_SHA256);+ expect(reportCsp(true)).toContain(`script-src 'sha256-${base64}'`);+ });+});diff --git a/src/shared/report-sandbox.ts b/src/shared/report-sandbox.tsnew file mode 100644index 00000000..c62a058d--- /dev/null+++ b/src/shared/report-sandbox.ts@@ -0,0 +1,82 @@+// The report sandbox lives here so the two halves cannot drift: the header+// `/r/<reportId>` serves, and the `sandbox` attribute the in-app viewer puts on+// the iframe pointing at that same document. A report is a full HTML document+// written by a model from attacker-influenceable inputs (crawled pages, SERP+// titles, GSC queries), so it is treated as hostile in both cases.+//+// The `sandbox` directive is what makes the open-in-a-tab case safe: a+// top-level document has no iframe attribute, and the directive gives it an+// opaque origin anyway — no cookies, no localStorage, no same-origin access to+// the app.++/**+ * The iframe's `sandbox` attribute value, matching the CSP's sandbox+ * directive. `allow-popups` plus `allow-popups-to-escape-sandbox` let a+ * report's `target="_blank"` links open normally (the audited site, a+ * reference); everything else stays restricted. The attribute must always be+ * present — an absent `sandbox` attribute is no sandbox at all — and+ * `allow-same-origin` is never added: it would hand the frame the app's cookies+ * and, with scripts, let the frame remove its own sandbox.+ */+export const REPORT_IFRAME_SANDBOX =+ "allow-popups allow-popups-to-escape-sandbox";++const CSP_TAIL =+ "default-src 'none'; style-src 'unsafe-inline'; img-src data:; font-src data:; connect-src 'none'; form-action 'none'; base-uri 'none'; object-src 'none'; frame-ancestors 'self'";++// The report's own JavaScript is blocked, and there is no `script-src`:+// `default-src 'none'` already blocks every script. One flip turns it on, in+// three places: add `allow-scripts` to the sandbox directive below, add it to+// REPORT_IFRAME_SANDBOX, and add `script-src 'unsafe-inline'` here. Reports+// saved while JS is blocked keep working after the flip; the reverse is not+// true, which is why blocking is the V1 default.+export const REPORT_CSP = `sandbox ${REPORT_IFRAME_SANDBOX}; ${CSP_TAIL}`;++/**+ * The script print mode appends, and the only script authorized to run in a+ * report. A small delay after `load`, so fonts and images settle before the+ * dialog snapshots the page. It is injected with no attributes at all — see+ * withPrintScript.+ */+export const PRINT_SCRIPT =+ 'addEventListener("load",()=>{setTimeout(()=>print(),150)})';++/**+ * Base64 SHA-256 of PRINT_SCRIPT, for the `script-src` hash source. Hardcoded+ * rather than computed at module load: the digest is needed synchronously and+ * Web Crypto is async. report-sandbox.test.ts recomputes it from PRINT_SCRIPT,+ * so editing the script without editing this constant fails the suite instead+ * of silently breaking printing.+ */+export const PRINT_SCRIPT_SHA256 =+ "thhppZwgMkIvdqds8iPeCMHMT5bX6Wi4nx2PdnxB36w=";++/**+ * The policy for one response. Outside print mode it is REPORT_CSP, byte for+ * byte.+ *+ * Print mode (`/r/<id>?print=1`) is the one case the app appends a script of+ * its own — a `print()` call, so "Export" lands in the browser's print dialog+ * instead of asking the reader to find it. That needs `allow-scripts` (and+ * `allow-modals`, since `print()` is a modal in a sandbox) plus a `script-src`+ * naming the hash of that one script, which is also what keeps the report's own+ * scripts blocked — see withPrintScript.+ */+export function reportCsp(print?: boolean): string {+ if (!print) return REPORT_CSP;+ return `sandbox ${REPORT_IFRAME_SANDBOX} allow-scripts allow-modals; script-src 'sha256-${PRINT_SCRIPT_SHA256}'; ${CSP_TAIL}`;+}++/**+ * The plain-text response both report routes answer errors with: the sandbox+ * headers belong to the document, and these bodies are ours.+ */+export function textResponse(body: string, status: number): Response {+ return new Response(body, {+ status,+ headers: {+ "Content-Type": "text/plain; charset=utf-8",+ "Cache-Control": "private, no-store",+ },+ });+}diff --git a/src/types/schemas/reports.ts b/src/types/schemas/reports.tsnew file mode 100644index 00000000..8f8214a9--- /dev/null+++ b/src/types/schemas/reports.ts@@ -0,0 +1,59 @@+// Shared vocabulary for reports. The MCP tools, the server functions and the+// app all import these constants and this type, so the caps and the wire shape+// of a save are defined once.++/**+ * UTF-8 byte cap on a stored document, measured with TextEncoder (not+ * `String.length`, which counts UTF-16 code units and understates multi-byte+ * content). Chosen for the app worker's heap, not for storage: a save is parsed+ * out of JSON-RPC, copied by TextEncoder and bound into a statement on a worker+ * whose P90 heap already sits near its limit. Reports should aim well under+ * 80,000 bytes; this is the refusal line, not the target.+ */+export const REPORT_MAX_HTML_BYTES = 500_000;+/**+ * Runaway-storage guard per project, enforced on create only. It is not a+ * product limit: no real project writes ten thousand reports, so the number a+ * user hits is a loop that got stuck, not a workflow.+ */+export const REPORT_MAX_PER_PROJECT = 10_000;+/**+ * Runaway-storage guard for a whole organization, across every project it+ * owns. Projects are unlimited, so the per-project guard bounds nothing on its+ * own; this is the line that actually bounds free, unmetered writes. Set at+ * the per-project guard times the 500 KB per-report cap, which no workspace+ * writing reports by hand will approach.+ */+export const REPORT_MAX_BYTES_PER_ORG = 5_000_000_000;+/** Page size for a list read when the caller does not ask for one. */+export const REPORT_DEFAULT_LIST_LIMIT = 20;+/** Ceiling on a single list page, for the MCP tool's payload budget. */+export const REPORT_MAX_LIST_LIMIT = 50;+/** The Reports page shows the most recent 100. */+export const REPORT_APP_LIST_LIMIT = 100;+export const REPORT_MAX_TITLE_CHARS = 120;+/** A skill slug is a directory name; anything longer is not one. */+export const REPORT_MAX_SKILL_CHARS = 60;+export const REPORT_MAX_SUMMARY_CHARS = 2_500;++/**+ * Everything a list or detail read returns. `html` is deliberately absent: it+ * is read only by getReportHtml, so no list path can pull documents into the+ * worker's heap.+ *+ * A plain type, not a Zod schema: these rows are built by the repository from+ * its own column selection, so there is no trust boundary here to validate.+ */+export type ReportMetadata = {+ id: string;+ projectId: string;+ title: string;+ summary: string;+ skill: string | null;+ createdBy: string;+ createdByUserId: string;+ /** UTF-8 byte length of the stored document. */+ sizeBytes: number;+ createdAt: string;+ updatedAt: string;+};diff --git a/web/content/blogs/how-to-prompt-claude-code-for-seo.md b/web/content/blogs/how-to-prompt-claude-code-for-seo.mdindex 74bb7b0c..8484bd29 100644--- a/web/content/blogs/how-to-prompt-claude-code-for-seo.md+++ b/web/content/blogs/how-to-prompt-claude-code-for-seo.md@@ -96,7 +96,7 @@ That works with or without OpenSEO connected. With it, the answers come with rea## What each SEO skill does-If you ran the two plugin commands above, you already have all nine skills, and the Codex plugin installs the same set. Anywhere else, [connect MCP](/docs/mcp) first and then [add the skill files](/docs/skills/setup).+If you ran the two plugin commands above, you already have all ten skills, and the Codex plugin installs the same set. Anywhere else, [connect MCP](/docs/mcp) first and then [add the skill files](/docs/skills/setup).Each skill hands Claude a complete workflow. The ones you'll reach for most:diff --git a/web/content/docs/claude-code-plugin.md b/web/content/docs/claude-code-plugin.mdindex 153f5f18..ea03ed96 100644--- a/web/content/docs/claude-code-plugin.md+++ b/web/content/docs/claude-code-plugin.md@@ -16,7 +16,7 @@ Run these two commands in Claude Code:If the install summary says `Run /reload-plugins to activate.`, run that command.-Claude Code connects OpenSEO MCP at `https://app.openseo.so/mcp` and enables nine skills:+Claude Code connects OpenSEO MCP at `https://app.openseo.so/mcp` and enables ten skills:- SEO Project Setup- SEO Coach@@ -27,6 +27,7 @@ Claude Code connects OpenSEO MCP at `https://app.openseo.so/mcp` and enables nin- Competitor Analysis- Local SEO- Link Prospecting+- SEO Report## Finish the logindiff --git a/web/content/docs/codex-plugin.md b/web/content/docs/codex-plugin.mdindex fb3f5568..66f39a82 100644--- a/web/content/docs/codex-plugin.md+++ b/web/content/docs/codex-plugin.md@@ -17,7 +17,7 @@ codex mcp login openseo`codex mcp login` opens a browser to approve the OpenSEO connection. If it reports that `openseo` isn't found, restart Codex first — bundled MCP servers only register after a restart, not immediately after install — then run `codex mcp login openseo` again.-Codex connects OpenSEO MCP at `https://app.openseo.so/mcp` and enables nine skills:+Codex connects OpenSEO MCP at `https://app.openseo.so/mcp` and enables ten skills:- SEO Project Setup- SEO Coach@@ -28,6 +28,7 @@ Codex connects OpenSEO MCP at `https://app.openseo.so/mcp` and enables nine skil- Competitor Analysis- Local SEO- Link Prospecting+- SEO Report## Run a skilldiff --git a/web/content/docs/mcp.md b/web/content/docs/mcp.mdindex c17b6993..36555d65 100644--- a/web/content/docs/mcp.md+++ b/web/content/docs/mcp.md@@ -13,7 +13,7 @@ https://app.openseo.so/mcpThe first connection sends you through OpenSEO login. After authorization, your MCP client can call OpenSEO tools with the project context and account scopes you approved. For headless environments and CI, [connect with an API key](#connect-with-an-api-key) instead.-For the most current setup UI and a copyable endpoint, open [AI & MCP in OpenSEO](https://app.openseo.so/ai).+For the most current setup UI and a copyable endpoint, open [MCP setup in OpenSEO](https://app.openseo.so/ai).## Claude Codediff --git a/web/content/docs/skills/index.md b/web/content/docs/skills/index.mdindex fde49238..f1ef4845 100644--- a/web/content/docs/skills/index.md+++ b/web/content/docs/skills/index.md@@ -7,7 +7,7 @@ OpenSEO Agent Skills let you hand repeatable SEO workflows to your AI agent.Run a slash command when you need keyword research, clustering, competitor analysis, link prospecting, or project setup. The skill gives your agent the workflow instructions.-You stay in charge of strategy. Your agent uses OpenSEO data and the skill instructions to return a recommendation, plan, or shortlist.+You stay in charge of strategy. Your agent uses OpenSEO data and the skill instructions to research the answer, then saves the result as a report in your project.## Set up OpenSEO Agent Skills@@ -39,6 +39,10 @@ MCP connects your agent to OpenSEO data. Skills tell your agent which SEO workfl- [Link Prospecting](/docs/skills/link-prospecting): find qualified outreach prospects and the angle that makes each one relevant.+## How the results reach you++- [SEO Report](/docs/skills/seo-report): the shared report-writing skill every workflow above delivers through. Your agent writes one self-contained HTML page and saves it to your project's Reports page, where anyone can read or print it.+## Learn more about skillsOpenSEO uses the same `SKILL.md` pattern supported by modern AI agents. To learn how skills work in your agent, read:diff --git a/web/content/docs/skills/meta.json b/web/content/docs/skills/meta.jsonindex 182f4e43..680c171e 100644--- a/web/content/docs/skills/meta.json+++ b/web/content/docs/skills/meta.json@@ -11,6 +11,7 @@"[Competitive Landscape](/docs/skills/competitive-landscape)","[Competitor Analysis](/docs/skills/competitor-analysis)","[Local SEO](/docs/skills/local-seo)",- "[Link Prospecting](/docs/skills/link-prospecting)"+ "[Link Prospecting](/docs/skills/link-prospecting)",+ "[SEO Report](/docs/skills/seo-report)"]}diff --git a/web/content/docs/skills/seo-audit.mdx b/web/content/docs/skills/seo-audit.mdxindex f4770ddd..e6358fe0 100644--- a/web/content/docs/skills/seo-audit.mdx+++ b/web/content/docs/skills/seo-audit.mdx@@ -9,7 +9,7 @@ The SEO Audit Agent Skill audits a site and writes a one-page HTML report that aYour agent runs an OpenSEO site audit, pulls backlink and traffic-estimate data, and re-checks every finding against the live pages before reporting it. The report is built around one action the site owner can take this week, with the exact message or steps included, followed by a short list of small fixes and a section on what already works.-The skill is plain `SKILL.md` instructions plus an HTML template, so it runs in Claude Code, Codex, or any agent that supports the skills format. If your agent can publish or preview HTML it will use that; otherwise it saves the report as a file for you to open in your browser.+The skill is plain `SKILL.md` instructions, so it runs in Claude Code, Codex, or any agent that supports the skills format. It delivers through the [SEO Report skill](/docs/skills/seo-report): the finished page is saved to your OpenSEO project and appears on the project's Reports page, where anyone on your team can open it or print it to PDF.## What this skill helps your agent do@@ -19,7 +19,7 @@ The skill is plain `SKILL.md` instructions plus an HTML template, so it runs in- Pick one do-this-week action and include the copy-paste mechanics for it.- Propose a starting focus area: a handful of specific, winnable keywords and what to make for each.- Explain every technical term in plain English the first time it appears.-- Deliver the result as a single HTML page you can send to anyone.+- Save the result to your project as a single HTML page anyone on your team can open or print.## When to use it@@ -29,7 +29,7 @@ It handles broken sites honestly. If the domain is down or half-crawled, the age## What you get back-One HTML page: a three-sentence summary, the single action to take this week with concrete steps, five to ten small fixes with the exact evidence for each, a starting focus area with three to five keyword ideas (healthy sites only), a list of what already works, and a note on how the review was done.+One report on your project's Reports page: a three-sentence summary, the single action to take this week with concrete steps, five to ten small fixes with the exact evidence for each, a starting focus area with three to five keyword ideas (healthy sites only), a list of what already works, and a note on how the review was done. In chat you get the link, the verdict, and the one thing to do.## How to get the best result@@ -50,6 +50,7 @@ The source `SKILL.md` lives on GitHub:## Related skills+- [SEO Report](/docs/skills/seo-report), the shared skill that writes and saves the report.- [SEO Coach](/docs/skills/seo-coach) if you are not sure this is the right workflow to run first.- [Keyword Research](/docs/skills/keyword-research) to go deeper than the report's starting keywords.- [Link Prospecting](/docs/skills/link-prospecting) when the report's one thing is links and you want to go beyond the first outreach batch.diff --git a/web/content/docs/skills/seo-project-setup.mdx b/web/content/docs/skills/seo-project-setup.mdxindex 81c87b9c..ef2b6855 100644--- a/web/content/docs/skills/seo-project-setup.mdx+++ b/web/content/docs/skills/seo-project-setup.mdx@@ -9,7 +9,7 @@ The SEO Project Setup Agent Skill gives your agent the context it needs before dYour agent asks about the website, goals, positioning, competitors, and key pages once, then saves the answers to your project's context in OpenSEO.-Every other skill reads that context, so does SAM in the app, and you can edit it yourself on the project's Context settings page. It carries across sessions, machines, and agents.+Every other skill reads that context, so does SAM in the app, and you can edit it yourself on the project's Context page, in the sidebar under AI. It carries across sessions, machines, and agents.## What this skill helps your agent dodiff --git a/web/content/docs/skills/seo-report.mdx b/web/content/docs/skills/seo-report.mdxnew file mode 100644index 00000000..6ce9d9bf--- /dev/null+++ b/web/content/docs/skills/seo-report.mdx@@ -0,0 +1,42 @@+---+title: "SEO Report Agent Skill"+description: "The report-writing skill every OpenSEO workflow delivers through: one self-contained HTML page, saved to your project, readable and printable by anyone."+---++The SEO Report Agent Skill is how the other OpenSEO workflows hand you their finished work.++You do not run it on its own. When your agent finishes an audit, a keyword study, or a competitor analysis, this skill tells it how to write the result as one self-contained HTML page and save it to your project. The page shows up on the project's Reports page in OpenSEO, where anyone on your team can open it, read it on a phone, and print it to PDF.++## What this skill helps your agent do++- Write one HTML page instead of a wall of chat text, using a shared starter template so every report looks the same.+- Save it to the project with `save_report`, so it is tied to the site it is about and findable tomorrow.+- Check `list_reports` first and update the existing report when it is correcting its own run, instead of leaving you with three near-identical copies.+- Keep the report self-contained: all the styling is inside the file, nothing is fetched from the web, and it prints correctly with no network at all.+- Write a short summary alongside the page, so the agent, or the next agent, can pick the work back up without re-reading the whole report.+- Reply in chat with the link, the verdict, and the top action, and leave the tables where they belong.++## What you get back++A report page in your project with a title that names the subject and the period, like "badseo.dev SEO audit, Sep 2026". Open it from the Reports page in the sidebar, then click Export to save a PDF. The menu beside it opens the report full screen or in its own tab.++Reports are free. They do not spend credits, and there is no practical limit on how many a project holds. The Reports page shows the 100 most recent.++## How to get the best result++- Ask for a workflow, not for a report: "audit badseo.dev" produces one on its own.+- If you want the report corrected rather than duplicated, say so, and the agent will update the same page.+- 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.++## Read the actual skill++The source `SKILL.md`, including the starter template, lives on GitHub:++- [SEO Report skill](https://github.com/every-app/open-seo/tree/main/.agents/skills/seo-report)++## Related skills++- [SEO Audit](/docs/skills/seo-audit), the workflow most people meet this skill through.+- [Competitor Analysis](/docs/skills/competitor-analysis) and [Keyword Research](/docs/skills/keyword-research), which deliver the same way.+- [SEO Coach](/docs/skills/seo-coach) if you are not sure which workflow to run first.