Skip to content

Open-source SEO, GEO, and marketing skills for AI agents.

chore: remove legacy OpenClaw surface

Tong3c73078b24b9
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index 5f0fe03e..ea85e705 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -5,14 +5,14 @@
},
"metadata": {
"description": "The official Google Ads + Meta Ads + SEO + GEO plugin from NotFair. SEO, GEO, Google Ads, and Meta Ads skills for Claude Code.",
- "version": "0.25.2"
+ "version": "0.25.3"
},
"plugins": [
{
"name": "notfair",
"source": "./",
- "description": "The official Google Ads + Meta Ads + SEO + GEO plugin from NotFair. SEO analysis, Google Ads management, Meta (Facebook + Instagram) Ads management, GSC-driven content planning + local calendar viewer, opt-in OpenClaw cron publisher to a NotFair webhook, keyword research, content optimization, schema markup, meta tags optimization, broken link checker, single-page deep audit, and Generative Engine Optimization for AI search.",
- "version": "0.25.2",
+ "description": "The official Google Ads + Meta Ads + SEO + GEO plugin from NotFair. SEO analysis, Google Ads management, Meta (Facebook + Instagram) Ads management, GSC-driven content planning + local calendar viewer, keyword research, content optimization, schema markup, meta tags optimization, broken link checker, single-page deep audit, and Generative Engine Optimization for AI search.",
+ "version": "0.25.3",
"author": {
"name": "NotFair",
"url": "https://notfair.co"
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 2d34a3b3..c0a017d7 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "notfair",
- "version": "0.25.2",
+ "version": "0.25.3",
"description": "The official Google Ads + Meta Ads + SEO + GEO plugin from NotFair. SEO analysis, Google Ads management, Meta (Facebook + Instagram) Ads management, keyword research, content optimization, schema markup tools, broken link checker, single-page deep audit, and Generative Engine Optimization (GEO) for AI search engines — powered by Google Search Console, Google Ads, and Meta Marketing APIs.",
"author": {
"name": "NotFair",
@@ -24,7 +24,6 @@
"./seo/broken-link-checker",
"./seo/geo-optimizer",
"./notfair-upgrade-skill",
- "./notfair-cmo-skill",
"./gemini"
]
}
diff --git a/AGENTS.md b/AGENTS.md
index e5bd0b6d..7d1c17e3 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,6 +1,6 @@
# NotFair — Skill Resolver for AI Agents
-**This file is the universal entry point.** Any AI coding agent (Claude Code, OpenClaw, Codex, Hermes, Cursor, etc.) reads this to know which NotFair skill to run for which user intent.
+**This file is the universal entry point.** Any AI coding agent (Claude Code, Codex, Hermes, Cursor, etc.) reads this to know which NotFair skill to run for which user intent.
If you are an agent and a user mentions Google Ads, Meta Ads, SEO, GEO, or anything in the tables below, route to the named skill.
@@ -12,7 +12,7 @@ If you are an agent and a user mentions Google Ads, Meta Ads, SEO, GEO, or anyth
2. **Read the named skill's `SKILL.md`** from the path shown.
3. **Follow the procedure** in that SKILL.md exactly.
-Skills under `seo/`, `google-ads/`, `meta-ads/`, `gemini/`, and `notfair-upgrade-skill/` are **host-agnostic** — they work the same on every agent host. The skills under `openclaw/skills/` are **OpenClaw-only orchestrators** that compose the host-agnostic skills into multi-site adaptive workflows; only invoke them inside an OpenClaw workspace.
+Skills under `seo/`, `google-ads/`, `meta-ads/`, `gemini/`, and `notfair-upgrade-skill/` are **host-agnostic** — they work the same on every supported agent host.
---
@@ -58,25 +58,6 @@ Skills under `seo/`, `google-ads/`, `meta-ads/`, `gemini/`, and `notfair-upgrade
| Intent | Skill | Path |
|---|---|---|
| Upgrade NotFair to the latest version | `upgrade` | `notfair-upgrade-skill/SKILL.md` |
-| Open the local NotFair CMO portal (browser UI for marketing agents) | `cmo` | `notfair-cmo-skill/SKILL.md` |
-
----
-
-## OpenClaw multi-site orchestrators
-
-These skills only apply inside an OpenClaw workspace that has been initialized via `./openclaw/install/install.sh`. They compose the host-agnostic SEO skills above into closed-loop, multi-site workflows with persisted artifacts under `~/.toprank/openclaw/` (path retained from the toprank → notfair rename to preserve existing portfolio state; see CHANGELOG 0.24.0).
-
-| Intent | Skill | Path |
-|---|---|---|
-| Register a new site in the portfolio | `notfair-site-onboard` | `openclaw/skills/notfair-site-onboard/SKILL.md` |
-| Pick which site in the portfolio deserves attention next | `notfair-portfolio-review` | `openclaw/skills/notfair-portfolio-review/SKILL.md` |
-| Weekly SEO review for one registered site | `notfair-weekly-review` | `openclaw/skills/notfair-weekly-review/SKILL.md` |
-| Improve one URL inside a registered site | `notfair-improve-page` | `openclaw/skills/notfair-improve-page/SKILL.md` |
-| Investigate an organic traffic drop on a registered site | `notfair-investigate-drop` | `openclaw/skills/notfair-investigate-drop/SKILL.md` |
-
-If the user mentions multi-site work, portfolio, scheduled follow-ups, or "the next best action across my sites," prefer an OpenClaw orchestrator. For single ad-hoc requests on one site, use the canonical SEO skill directly.
-
----
## External dependencies
@@ -91,7 +72,7 @@ Skills check for missing credentials at startup and walk the user through setup.
## Conventions for installers (managed-block fences)
-Any installer that writes into a file the user also edits (e.g., a user's workspace `AGENTS.md`, `CLAUDE.md`, or `~/.openclaw/AGENTS.md`) MUST wrap its inserted content in a fence:
+Any installer that writes into a file the user also edits (e.g., a user's workspace `AGENTS.md`, `CLAUDE.md`, or host config) MUST wrap its inserted content in a fence:
```
<!-- notfair:managed -->
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b09da940..98e253d6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,19 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
---
+## [0.25.3] — 2026-05-28
+
+### Removed
+
+- Removed the legacy OpenClaw adaptive layer, including repo-local orchestrator skills, cron/install scripts, schemas, examples, runtime helpers, and OpenClaw-specific tests.
+- Removed the OpenClaw-backed `/notfair:cmo` launch skill from the Claude Code plugin manifest and public resolver.
+
+### Changed
+
+- Updated public install and resolver docs to describe the remaining host-agnostic NotFair skill surface for Claude Code, Codex, and Hermes.
+
+---
+
## [0.25.2] — 2026-05-24
### Fixed
diff --git a/CLAUDE.md b/CLAUDE.md
index 17e79ac3..8250080d 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1,8 +1,8 @@
-# NotFair — Public AI-Agent Plugin (Claude Code, OpenClaw, Codex, Hermes)
+# NotFair — Public AI-Agent Plugin (Claude Code, Codex, Hermes)
**This is the public, open-source repository that ships to all customers and the community.**
-NotFair is a host-agnostic plugin providing SEO, Google Ads, and Meta Ads skills for AI coding agents. It is distributed via the `nowork-studio` Claude Code marketplace and via direct agent install on OpenClaw, Codex, and Hermes. Every change here is user-facing.
+NotFair is a host-agnostic plugin providing SEO, Google Ads, and Meta Ads skills for AI coding agents. It is distributed via the `nowork-studio` Claude Code marketplace and via direct agent install on Codex and Hermes. Every change here is user-facing.
## Engineering Execution Standard
@@ -36,7 +36,6 @@ This code ships to real users. Sycophancy and rubber-stamping cost us credibilit
- Home of the `notfair` plugin — the public artifact customers install.
- Contains host-agnostic skills under `google-ads/`, `seo/`, `meta-ads/`, `gemini/`, and `notfair-upgrade-skill/`.
-- Contains OpenClaw-specific multi-site orchestrators under `openclaw/skills/` that compose the host-agnostic skills above.
- Registered via `.claude-plugin/plugin.json` + `.claude-plugin/marketplace.json` (Claude Code) and `AGENTS.md` (every other host).
- Paired with the NotFair-GoogleAds and NotFair-MetaAds MCP servers (OAuth at notfair.co) for ad-platform writes, and Google Search Console for SEO reads.
@@ -53,7 +52,7 @@ The product is **NotFair**. All user-facing text, documentation, skill descripti
## When adding or modifying a skill
1. Create/edit the skill directory under the appropriate category (`google-ads/`, `seo/`, etc.) with a `SKILL.md` containing valid frontmatter.
-2. **Register it in `AGENTS.md`** under the matching intent table. A skill that isn't in `AGENTS.md` is invisible to OpenClaw, Codex, Hermes, and any non-Claude host.
+2. **Register it in `AGENTS.md`** under the matching intent table. A skill that isn't in `AGENTS.md` is invisible to Codex, Hermes, and any non-Claude host.
3. **Register it in `.claude-plugin/plugin.json`** under the `skills` array. A skill that exists on disk but isn't listed here will NOT appear in the installed Claude Code plugin — this has already bitten us once with `ads-landing`.
4. Bump the version in three places so upgrades propagate:
- `.claude-plugin/plugin.json` → `version`
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index a2b00508..edb5892e 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -22,17 +22,6 @@ Each skill lives in its own folder under a category directory (e.g., `seo/`, `go
* `VERSION`
6. **Update Changelog**: Add a brief description of your new skill to `CHANGELOG.md`.
-
-### 1A. OpenClaw adaptive layer
-
-The repo also ships an OpenClaw-specific surface under `openclaw/`.
-
-- Keep the existing `seo/` and `google-ads/` skills canonical.
-- Add runtime-specific wrappers under `openclaw/skills/` instead of duplicating skill logic.
-- Put schemas under `openclaw/artifacts/schemas/` and shared docs under `openclaw/shared/`.
-- **Do not register OpenClaw wrapper skills in `.claude-plugin/plugin.json`** — they are not part of the Claude plugin surface.
-- Runtime state belongs under `~/.toprank/openclaw`, not in git.
-
### 2. Improving Existing Skills
* Refine prompts in `SKILL.md` for better accuracy.
diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.md
index 546e1ecb..58479e18 100644
--- a/INSTALL_FOR_AGENTS.md
+++ b/INSTALL_FOR_AGENTS.md
@@ -1,6 +1,6 @@
# Install NotFair — for AI Agents
-You are an AI coding agent (Claude Code, OpenClaw, Codex, Hermes, Cursor, or similar). The user has asked you to install or set up NotFair. Follow this document end-to-end.
+You are an AI coding agent (Claude Code, Codex, Hermes, Cursor, or similar). The user has asked you to install or set up NotFair. Follow this document end-to-end.
**Single paste line for users (give them this if they ask how to install):**
@@ -16,10 +16,9 @@ https://raw.githubusercontent.com/nowork-studio/notfair/main/INSTALL_FOR_AGENTS.
Determine which agent runtime you are running inside. Check, in order:
1. Are you Claude Code (file system has `~/.claude/` or `.claude/` in the project) → **host = `claude-code`**
-2. Are you in an OpenClaw workspace (env `OPENCLAW_WORKSPACE` is set, or `~/.openclaw/` exists) → **host = `openclaw`**
-3. Are you Codex (env `CODEX_HOME` is set, or running under the OpenAI Codex CLI) → **host = `codex`**
-4. Are you Hermes Agent → **host = `hermes`**
-5. Otherwise → **host = `generic`**
+2. Are you Codex (env `CODEX_HOME` is set, or running under the OpenAI Codex CLI) → **host = `codex`**
+3. Are you Hermes Agent → **host = `hermes`**
+4. Otherwise → **host = `generic`**
If you cannot determine the host, ask the user once and proceed.
@@ -51,29 +50,6 @@ NotFair is published as a Claude Code plugin via the `nowork-studio` marketplace
Then verify by listing installed plugins. No further action required — Claude Code reads `.claude-plugin/plugin.json` directly.
-### host = `openclaw`
-
-Run from the repo root:
-
-```bash
-./openclaw/install/install.sh
-```
-
-This script:
-1. Creates `~/.toprank/openclaw/` runtime state (or `$TOPRANK_OPENCLAW_HOME` if set). Path retained from the toprank → notfair rename to preserve existing portfolio state — see CHANGELOG 0.24.0.
-2. Bootstraps `portfolio.json` and `schedule.json`.
-3. Copies the OpenClaw orchestrator skills from `openclaw/skills/` into `~/.openclaw/skills/`.
-4. Symlinks `openclaw/shared`, `openclaw/bin`, and `seo/` to stable paths so wrappers resolve.
-
-Verify:
-
-```bash
-openclaw skills check | grep -i notfair
-python3 -m pytest -q openclaw/tests
-```
-
-Read `AGENTS.md` at the repo root to learn the skill resolver.
-
### host = `codex`
Codex reads `AGENTS.md` natively. From the repo root:
@@ -121,14 +97,13 @@ Do **not** invent credentials. If a skill needs auth that isn't present, surface
1. Confirm `AGENTS.md` is readable from the working directory.
2. Confirm at least one canonical skill (e.g., `seo/seo-analysis/SKILL.md`) is readable.
-3. For OpenClaw: confirm `openclaw skills check` lists at least one `notfair-*` skill.
-4. Tell the user: "NotFair is installed. Try `/notfair:google-ads-audit` for ads or `/notfair:seo-analysis` for SEO."
+3. Tell the user: "NotFair is installed. Try `/notfair:google-ads-audit` for ads or `/notfair:seo-analysis` for SEO."
---
## Notes for agents
- **Read `AGENTS.md` first** for any user intent. It is the resolver.
-- **Skills are host-agnostic.** A `SKILL.md` under `seo/`, `google-ads/`, `meta-ads/`, `gemini/` works identically on every host. The `openclaw/skills/` orchestrators are the only host-specific layer.
+- **Skills are host-agnostic.** A `SKILL.md` under `seo/`, `google-ads/`, `meta-ads/`, `gemini/` works identically on every supported host.
- **If you write into a user-edited file** (e.g., their workspace `AGENTS.md`), wrap your insertions in `<!-- notfair:managed -->` ... `<!-- /notfair:managed -->` fences so re-runs are idempotent and hand-edits survive.
- **Do not duplicate skills** when adding new host adapters. Add a thin install adapter under `install/<host>/` that points the host at the existing skill files.
diff --git a/README.md b/README.md
index efb005b0..2de94f40 100644
--- a/README.md
+++ b/README.md
@@ -16,50 +16,6 @@ The NotFair plugin is the CLI side — the skills that run inside Claude Code (a
Free, open-source. Install in 30 seconds.
-### Or run it as a local app — [`notfair-cmo/`](notfair-cmo/)
-
-Prefer a local UI over the CLI? **[notfair-cmo](notfair-cmo/)** is a Node app that runs entirely on your machine and orchestrates the same NotFair skills as specialist agents (CMO, Google Ads, SEO) per project. Chat with them, schedule their recurring work, watch tool calls stream inline. Bring your own LLM credentials and your own ad-platform OAuth — nothing leaves your machine.
-
-#### Prerequisites
-
-- **[OpenClaw](https://docs.openclaw.ai/install)** installed and the gateway running on this machine (`openclaw gateway`).
-- **Node 20+** (Node 24 recommended).
-- An LLM provider configured in your OpenClaw config (e.g. an `OPENAI_API_KEY` env var or `agents.defaults.model` entry).
-
-#### Run it
-
-From inside Claude Code, if you have the plugin installed:
-
-```
-/notfair:cmo
-```
-
-The skill probes whether the portal is already running, runs `notfair-cmo doctor` to verify your environment, then launches the server in the background and opens `http://127.0.0.1:3000/` in your browser.
-
-Or from your shell directly:
-
-```bash
-# One-shot, no install:
-npx notfair-cmo@latest doctor # verify env (Node, OpenClaw, LLM, data dir, port)
-npx notfair-cmo@latest # launch UI on http://127.0.0.1:3000
-
-# Or install globally:
-npm install -g notfair-cmo
-notfair-cmo
-```
-
-#### What you get
-
-- Per-project specialist agents (CMO, Google Ads, SEO) auto-provisioned in isolated OpenClaw workspaces.
-- A chat UI scoped to each project with inline streaming of tool calls and MCP invocations.
-- A **Crons** tab (calendar + list) that groups OpenClaw's scheduled jobs by project + agent.
-- **Connections** — one-click PKCE OAuth to bring Google Ads (and other NotFair MCP servers) into the agents' toolbox.
-- An append-only **Activity log** of every autonomous decision and scheduled run.
-
-See [`notfair-cmo/README.md`](notfair-cmo/README.md) for full docs.
-
----
-
## See It Work
### Google Ads
@@ -204,27 +160,6 @@ The plugin was renamed `toprank` → `notfair` in v0.24.0. If you previously ins
Your data is preserved — the runtime state directory (`~/.toprank/`, holding portfolio state, change logs, business-context cache, audit history) is intentionally retained under its original name for this release. See `CHANGELOG.md` for details.
----
-
-## 🤖 The Fully-Automated SEO Agent (OpenClaw / Hermes)
-
-Instead of manually running single SEO skills, the future of NotFair is the **Fully-Automated SEO Agent**.
-
-By leveraging the **OpenClaw adaptive layer** under [`openclaw/`](openclaw/), you can instruct OpenClaw or Hermes to automatically set up a persistent SEO agent for your project. This isn't just a set of tools—it's a background worker that configures cron jobs, continually monitors your site, runs SEO audits, and autonomously makes improvements over time.
-
-Features of the SEO Agent:
-- **Zero-Touch Setup:** Simply give the repo to OpenClaw or Hermes, and they will follow the instructions to spin up the agent for you.
-- **Always-On Automation:** Automatically schedules and runs SEO tasks via cron.
-- **Self-Improving:** Continuously monitors Search Console data, ships page optimizations, rewrites meta tags, and adds structured data without manual intervention.
-- **Multi-Site Portfolio:** Maintains portfolio state, a per-site work folder, OpenClaw wrapper skills, and structured JSON artifacts for reviews, plans, and feedback.
-
-Start building your agent here:
-
-- [`openclaw/README.md`](openclaw/README.md)
-- [`docs/openclaw-adaptive-layer.md`](docs/openclaw-adaptive-layer.md)
-
----
-
## Skills
### Google Ads
@@ -297,7 +232,6 @@ notfair/
│ ├── geo-optimizer/ <- GEO for AI search engines
│ └── setup-cms/ <- CMS connector
├── gemini/ <- cross-model review via Gemini CLI
-├── openclaw/ <- OpenClaw adaptive layer (multi-site wrappers, artifacts, installers)
├── notfair-upgrade-skill/ <- self-updater
├── test/ <- unit + LLM-judge eval tests
└── VERSION
diff --git a/VERSION b/VERSION
index 166c9e29..3d9dcb1b 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.25.2
+0.25.3
diff --git a/docs/openclaw-adaptive-layer.md b/docs/openclaw-adaptive-layer.md
deleted file mode 100644
index fed29bf6..00000000
--- a/docs/openclaw-adaptive-layer.md
+++ /dev/null
@@ -1,192 +0,0 @@
-# OpenClaw Adaptive Layer (MVP)
-
-NotFair's OpenClaw surface is a thin adaptive layer that sits on top of the existing open-source SEO skills. It does **not** replace `seo/` or `google-ads/`. It adds multi-site state, scheduled review loops, artifact writing, and policy gates so an operator can manage a portfolio of websites from one OpenClaw workspace.
-
-## Product definition
-
-**Goal:** maximize qualified organic growth across a portfolio of websites, subject to explicit safety and approval rules.
-
-**Core idea:** the existing NotFair skills are capability modules; the OpenClaw layer is the operator.
-
-## Operating model
-
-The layer runs two loops:
-
-1. **Portfolio loop** — look across all registered sites, rank urgency and opportunity, decide where attention should go next.
-2. **Site loop** — observe a single site, diagnose the highest-leverage issue, propose or draft the next action, verify it, and schedule a later feedback check.
-
-## MVP scope
-
-The MVP deliberately stays narrow.
-
-### Supported actions
-- title/meta rewrite proposals
-- schema proposals
-- internal-link recommendations
-- page improvement proposals
-- traffic-drop investigation plans
-- weekly review prioritization
-
-### Not in MVP
-- automatic publishing to CMS
-- autonomous mass rewrites
-- automatic redirect sweeps
-- cross-site learned priors driving writes without approval
-
-## Multi-site workspace layout
-
-Runtime state lives **outside the repo** under `~/.toprank/openclaw` by default.
-
-```text
-~/.toprank/openclaw/
-├── portfolio.json
-├── schedule.json
-└── sites/
- ├── example.com/
- │ ├── site-profile.json
- │ ├── goals.json
- │ ├── latest-state.json
- │ ├── learned-patterns.json
- │ ├── queue/
- │ ├── proposals/
- │ ├── runs/
- │ └── feedback/
- └── example-service.com/
- └── ...
-```
-
-The repo contains the shared layer under `openclaw/`:
-
-```text
-openclaw/
-├── README.md
-├── artifacts/
-│ ├── examples/
-│ └── schemas/
-├── bin/
-├── install/
-├── shared/
-└── skills/
-```
-
-## JSON file catalog
-
-### Portfolio-level
-
-- `portfolio.json` — the registry of all sites, their business weight, cadence, and status.
-- `schedule.json` — upcoming recurring checks and feedback follow-ups.
-
-### Per-site core files
-
-- `site-profile.json` — domain, canonical URL, brand terms, CMS, primary business context.
-- `goals.json` — one or more active SEO goals for the site.
-- `latest-state.json` — the last summarized state snapshot used for quick loading.
-- `learned-patterns.json` — site-local observations about what interventions have worked or failed.
-
-### Per-site work folders
-
-- `queue/` — pending work items the layer should revisit.
-- `proposals/` — generated proposals and patch candidates waiting for review or approval.
-- `runs/` — immutable run artifacts grouped by timestamp.
-- `feedback/` — post-action outcome reviews.
-
-### Per-run files
-
-Each run directory under `sites/<site_id>/runs/<timestamp>/` can contain:
-
-- `trigger.json`
-- `state-snapshot.json`
-- `audit.json`
-- `action-plan.json`
-- `proposal.json`
-- `patch-set.json`
-- `verification.json`
-- `feedback.json`
-- `learning-log.json`
-
-The MVP requires at least:
-- `audit.json`
-- `action-plan.json`
-- `verification.json`
-
-## Policy model
-
-### Auto-safe
-- run audits
-- write local artifacts
-- update queue items
-- generate proposals and drafts
-
-### Approval-required
-- edit website repo files
-- write to a CMS
-- open a PR
-- publish content or metadata
-
-### Blocked from auto
-- delete content in production
-- deploy bulk redirect changes
-- perform irreversible public changes without approval
-
-## Wrapper skills
-
-The MVP ships five OpenClaw-facing wrapper skills:
-
-- `notfair-site-onboard`
-- `notfair-portfolio-review`
-- `notfair-weekly-review`
-- `notfair-improve-page`
-- `notfair-investigate-drop`
-
-These wrappers keep the existing `seo/` skills as the source of truth. The wrapper adds:
-
-- site selection
-- multi-site state loading
-- artifact writing
-- policy gating
-- follow-up scheduling
-
-## Recommended cadence
-
-- **daily** — lightweight portfolio health scan
-- **weekly** — portfolio review + top site deep review
-- **14/28 day** — feedback checks on prior actions
-
-## Success criteria for MVP
-
-The MVP is working if an OpenClaw operator can:
-
-1. register multiple websites,
-2. keep a separate work folder for each site,
-3. run a portfolio review to decide where to focus,
-4. run a site review that produces structured artifacts,
-5. draft one safe next action,
-6. schedule and record a follow-up result.
-
-## Working implementation status
-
-The current MVP includes these concrete helper flows:
-
-- `openclaw/bin/onboard_site.py` — creates or updates the site work folder, portfolio entry, and initial goal.
-- `openclaw/bin/weekly_review.py` — runs or reads Search Console analysis, builds the weekly review payload automatically, persists the run, and seeds baseline metrics for follow-up scoring.
-- `openclaw/bin/persist_run.py` — takes a structured review payload and writes a timestamped run with `audit.json`, `action-plan.json`, `verification.json`, and optional queue items.
-- `openclaw/bin/portfolio_review.py` — ranks active sites using business weight, open issues, and active goals, then writes a portfolio review snapshot.
-- `openclaw/bin/improve_page.py` — persists a page-improvement proposal, optional patch-set, and feedback follow-up.
-- `openclaw/bin/investigate_drop.py` — persists a traffic-drop investigation, ranked recovery actions, and optional page-improvement follow-up.
-- `openclaw/bin/followups_due.py` — lists scheduled follow-up items that are due, making the schedule actionable.
-- `openclaw/bin/run_scheduler.py` — processes due schedule entries, auto-materializes feedback-check runs, and surfaces manual-attention items.
-- `openclaw/bin/record_followup_metrics.py` and `openclaw/bin/score_feedback.py` — let the operator attach observed metrics to a follow-up and score it as a win / neutral / loss / inconclusive.
-- `openclaw/bin/hydrate_followup_gsc.py` — can populate observed metrics from real Google Search Console data when a site has a GSC property or canonical URL configured.
-
-This means the adaptive layer can already persist real onboarding, automated weekly-review state, page-improvement proposals, drop investigations, due follow-up discovery, simple autonomous schedule processing, first-pass feedback scoring, and site-local learned priors even before the higher-level wrappers become fully autonomous.
-
-## Priority adaptation
-
-The weekly review runner now reads `learned-patterns.json` before ranking actions.
-
-That means the same site can evolve different preferences over time:
-- if `meta_tags` repeatedly improves `non_brand_clicks_28d`, weekly review boosts it,
-- if `page_improvement` repeatedly loses on the same metric, weekly review discounts it,
-- if no prior exists, the runner falls back to raw severity and opportunity heuristics.
-
-This is the first real behavior change driven by past outcomes.
diff --git a/install/README.md b/install/README.md
index 16b28ff9..458d5b3d 100644
--- a/install/README.md
+++ b/install/README.md
@@ -7,7 +7,6 @@ This directory is the home for **thin install adapters** that wire NotFair into
NotFair ships one source of truth for skills. Different agent hosts expect skills in different places:
- **Claude Code** — reads `.claude-plugin/plugin.json` directly from the repo. No adapter needed; the manifest at the repo root *is* the adapter.
-- **OpenClaw** — expects skills under `~/.openclaw/skills/`. The adapter lives at `../openclaw/install/install.sh` (kept there for back-compat). Future relocations will preserve a stub here.
- **Codex** — reads `AGENTS.md` at the workspace root. No filesystem install yet; workspace-local usage is the supported path. A future `install/codex/` adapter can register skills into Codex's global skill directory.
- **Hermes** — reads `AGENTS.md` at the workspace root. Same shape as Codex.
@@ -16,7 +15,7 @@ NotFair ships one source of truth for skills. Different agent hosts expect skill
1. Create `install/<host>/install.sh` (or `.py`, or whatever the host prefers).
2. The adapter should:
- Read skills from their canonical location (`seo/`, `google-ads/`, etc.) — do not copy them into per-host directories unless the host's loader requires it.
- - If the host requires copying (e.g., OpenClaw rejects symlinks that escape its skill root), copy the minimum needed and link the rest.
+ - If the host requires copying, copy the minimum needed and link the rest.
- Write any host-specific configuration with **managed-block fences** (see below).
3. Add a "host = `<host>`" branch to `../INSTALL_FOR_AGENTS.md` describing how the agent should invoke the adapter.
4. Update `../AGENTS.md` if the host introduces new orchestrator skills (most hosts will not — they will route to the same canonical skills).
@@ -36,5 +35,4 @@ Re-running the installer rewrites only inside the fence. Anything the user wrote
## What not to put here
- **Skill source code.** Skills belong in `seo/`, `google-ads/`, `meta-ads/`, `gemini/`. Adapters point at them; adapters do not own them.
-- **Host-specific orchestrators.** Those go alongside the host (e.g., `openclaw/skills/`), not under `install/`.
- **Runtime state.** Use `~/.toprank/<host>/` (path retained from the toprank → notfair rename; see CHANGELOG 0.24.0) or the host's standard runtime directory.
diff --git a/notfair-cmo-skill/SKILL.md b/notfair-cmo-skill/SKILL.md
deleted file mode 100644
index 6769cdfc..00000000
--- a/notfair-cmo-skill/SKILL.md
+++ /dev/null
@@ -1,138 +0,0 @@
----
-name: cmo
-argument-hint: "<or just run '/notfair:cmo'>"
-description: >
- Launch the local NotFair CMO portal (a browser UI for specialist marketing agents)
- on this machine and open it in the browser. Use when the user asks to "open notfair-cmo",
- "launch the CMO", "open the marketing portal", "start the local CMO", or any phrasing
- that implies they want the local web UI for NotFair's marketing agents instead of the
- Claude Code CLI flow. The portal source lives at `notfair-cmo/` in this repo and is
- published to npm as `notfair-cmo`.
-allowed-tools:
- - Bash
- - Read
- - AskUserQuestion
----
-
-# /notfair:cmo
-
-Open the local NotFair CMO portal in the user's browser.
-
-The portal is a Node app (`notfair-cmo`) that runs on `http://127.0.0.1:3327` and lets the user chat with specialist marketing agents (CMO, Google Ads, SEO), schedule recurring work, and watch tool calls stream inline. Source: [`notfair-cmo/`](../notfair-cmo/). Distributed via `npx notfair-cmo@latest`.
-
-This skill **does not implement the portal** — it only launches it. If you need to change portal behavior, edit `notfair-cmo/` and ship via its own npm release.
-
----
-
-## Default port
-
-`3327` unless the user specifies otherwise (`--port`). If 3327 is busy, the portal's CLI auto-probes the next 5 ports. (The dev server uses `3326`; the published portal uses `3327`.)
-
----
-
-## Step 0: Check for NotFair updates
-
-Run this **before anything else** — the skill's own steps (ports, flags) ship with the plugin, so a stale plugin runs stale instructions.
-
-```bash
-_UPD_BIN=$(ls ~/.claude/plugins/cache/nowork-studio/notfair/*/bin/notfair-update-check 2>/dev/null | head -1)
-[ -n "$_UPD_BIN" ] && _UPD=$("$_UPD_BIN" 2>/dev/null || true) || _UPD=""
-[ -n "$_UPD" ] && echo "$_UPD" || true
-```
-
-If the output contains `UPGRADE_AVAILABLE <old> <new>`: immediately follow the inline upgrade flow in the `/notfair:upgrade` skill (Step 1 onward) to auto-upgrade. After the upgrade completes, **re-read this `/notfair:cmo` skill from the new plugin cache and restart from Step 1** (the upgrade check itself doesn't need to run again) — the refreshed skill may use a different default port.
-
-If the output contains `JUST_UPGRADED <old> <new>`: mention "NotFair upgraded from v{old} to v{new}" briefly, then continue to Step 1.
-
-If neither: continue to Step 1 silently.
-
----
-
-## Step 1: Probe — is it already running?
-
-```bash
-PORT=3327
-if curl -fsS --max-time 1 -o /dev/null "http://127.0.0.1:$PORT/" 2>/dev/null; then
- echo "RUNNING"
-else
- echo "NOT_RUNNING"
-fi
-```
-
-- If `RUNNING` → skip to **Step 4 (open browser)**.
-- If `NOT_RUNNING` → continue to Step 2.
-
----
-
-## Step 2: Preflight — run `notfair-cmo doctor`
-
-The portal ships a `doctor` command that checks Node ≥ 20, `openclaw` on PATH, OpenClaw gateway reachable, an LLM provider configured, writable data dir, and a free port. It exits non-zero with `Fix:` lines on failure.
-
-```bash
-npx -y notfair-cmo@latest doctor 2>&1
-```
-
-- Exit 0 → continue to Step 3.
-- Exit non-zero → **stop**. Surface the doctor output verbatim (it contains the `Fix:` instructions). Do not attempt to launch.
-
-If `npx` itself is missing (no Node installed), surface: *"Node 20+ is required. Install from https://nodejs.org or via `nvm install 20`, then re-run `/notfair:cmo`."*
-
----
-
-## Step 3: Launch the portal (detached)
-
-Background it so the skill returns control. The portal opens the browser itself via its `open` dependency, but we double-tap in Step 4 in case it's already running headlessly.
-
-```bash
-LOG=$(mktemp -t notfair-cmo.XXXXXX.log)
-nohup npx -y notfair-cmo@latest start --no-open > "$LOG" 2>&1 &
-echo "Launched notfair-cmo (PID $!), log: $LOG"
-```
-
-Wait for the port to respond (up to 30s):
-
-```bash
-for i in $(seq 1 30); do
- if curl -fsS --max-time 1 -o /dev/null "http://127.0.0.1:$PORT/" 2>/dev/null; then
- echo "READY"
- break
- fi
- sleep 1
-done
-```
-
-If after 30s the port still doesn't respond, surface the last 40 lines of `$LOG` and stop.
-
----
-
-## Step 4: Open the browser
-
-```bash
-URL="http://127.0.0.1:$PORT/"
-if command -v open >/dev/null 2>&1; then
- open "$URL"
-elif command -v xdg-open >/dev/null 2>&1; then
- xdg-open "$URL"
-elif command -v wslview >/dev/null 2>&1; then
- wslview "$URL"
-else
- echo "Could not auto-open a browser. Visit: $URL"
-fi
-echo "NotFair CMO is open at $URL"
-```
-
----
-
-## Arguments
-
-If the user passes a port (`/notfair:cmo --port 4001` or just `/notfair:cmo 4001`), substitute it for `PORT` above and pass `--port <n>` to `notfair-cmo start`.
-
----
-
-## What this skill does *not* do
-
-- It does not configure LLM providers — that's OpenClaw's `agents.defaults.model`. The doctor surfaces the right error if missing.
-- It does not install OpenClaw. If `openclaw` isn't on PATH, the doctor's `Fix:` line names the install command.
-- It does not create projects or run agents — the user does that from the browser UI.
-
-If the user wants to see project source / open issues, point them at `notfair-cmo/` in this repo.
diff --git a/openclaw/README.md b/openclaw/README.md
deleted file mode 100644
index 217fe967..00000000
--- a/openclaw/README.md
+++ /dev/null
@@ -1,290 +0,0 @@
-# OpenClaw surface for NotFair
-
-NotFair + OpenClaw is now a **closed-loop SEO operator**.
-
-It does not just run one-off audits. It can now:
-- pull real SEO signals from Google Search Console,
-- diagnose opportunities,
-- prioritize the next action using learned history,
-- persist proposals and safe operational steps,
-- schedule follow-up checks,
-- score whether changes worked,
-- update learned priors,
-- and keep going.
-
-This directory adds that multi-site adaptive layer for OpenClaw **without replacing the existing NotFair skills**.
-
-## The new power
-
-**SEO becomes a continuous system instead of a manual project.**
-
-```text
-signals -> diagnosis -> action -> follow-up measurement -> scoring -> learned priors -> better next action
-```
-
-![Continuous SEO Improvement Loop](artifacts/visuals/continuous-seo-improvement-loop.jpg)
-
-In practice, this means OpenClaw can continuously work a portfolio of sites by reading live data, generating the next best move, revisiting outcomes later, and getting smarter from the result.
-
-## What it is
-
-- `skills/` — OpenClaw wrapper skills
-- `shared/` — adapter rules, artifact contract, policy, and trigger docs
-- `artifacts/schemas/` — JSON schemas for runtime artifacts
-- `bin/` — small helper scripts for multi-site workspace bootstrapping
-- `install/` — installers/bootstrap helpers
-
-## What it is not
-
-- not a second copy of the SEO skill library
-- not a replacement for the Claude plugin surface
-- **not an auto-publisher by default** — publishing is an explicit opt-in. The
- base install is read-only / advisory. If you want OpenClaw to POST ready
- blog posts to a NotFair Next.js webhook on a cron, pass
- `--enable-publisher` to `install-openclaw-cron.sh` and export
- `NOTFAIR_PUBLISH_TOKEN` in the cron environment. The publisher only fires
- for content-calendar entries the user has explicitly flipped to
- `status: "ready_to_publish"`. Contract: `openclaw/install/notfair-publisher.md`.
-
-## Runtime state
-
-The adaptive layer writes runtime state outside the repo by default:
-
-```
-~/.toprank/openclaw
-```
-
-Override with:
-
-```
-export TOPRANK_OPENCLAW_HOME=/custom/path
-```
-
-## Install
-
-Run from the NotFair repo root:
-
-```bash
-./openclaw/install/install.sh
-```
-
-That script:
-
-1. creates `~/.toprank/openclaw/` if needed,
-2. bootstraps `portfolio.json` and `schedule.json`,
-3. copies all OpenClaw wrapper skills into `~/.openclaw/skills/`,
-4. links support paths so the wrappers can still resolve this repo's canonical `seo/` skills.
-
-Why copy instead of symlink wrapper skills directly? OpenClaw skill discovery intentionally rejects symlinks that escape the configured skill root. The installer copies wrappers into the OpenClaw skill root and uses stable support links for repo-relative files.
-
-Verify:
-
-```bash
-openclaw skills check | grep -i notfair
-python3 -m pytest -q openclaw/tests
-```
-
-## Paste this into OpenClaw
-
-Use this as the setup prompt for a fresh machine or a new OpenClaw instance. Replace the placeholders before pasting.
-
-```text
-Set up the NotFair OpenClaw SEO Operator on this machine.
-
-Repo:
-- If the NotFair repo already exists locally, use it; do not reclone.
-- Otherwise clone https://github.com/nowork-studio/notfair and cd into the repo root.
-
-Install:
-1. Run: ./openclaw/install/install.sh
-2. Verify NotFair skills are discoverable: openclaw skills check | grep -i notfair
-3. Run tests: python3 -m pytest -q openclaw/tests
-
-Sites:
-- Register these sites if they are not already in ~/.toprank/openclaw/portfolio.json:
- - <site_id_1> with GSC property <gsc_property_1>
- - <site_id_2> with GSC property <gsc_property_2>
-- If GSC properties are unknown, run:
- python3 seo/seo-analysis/scripts/list_gsc_sites.py
- Then update each site's ~/.toprank/openclaw/sites/<site_id>/site-profile.json with "gsc_property".
-
-Background wiring:
-- Install OpenClaw cron jobs with:
- ./openclaw/install/install-openclaw-cron.sh --to "<delivery_destination>" --channel "<channel>" --thread-id "<optional_thread_id>"
-- If there is no chat delivery target, omit --to; the jobs should be installed with --no-deliver.
-- Do not pass --model unless you first verify the model is accepted by this OpenClaw instance's model allowlist.
-
-Smoke test:
-1. Run the scheduler once:
- TOPRANK_OPENCLAW_HOME="$HOME/.toprank/openclaw" python3 openclaw/bin/run_scheduler.py
-2. Run one weekly review:
- TOPRANK_OPENCLAW_HOME="$HOME/.toprank/openclaw" python3 openclaw/bin/weekly_review.py "<site_id_1>"
-3. Confirm the review wrote audit.json, action-plan.json, and verification.json under ~/.toprank/openclaw/sites/<site_id>/runs/.
-4. Confirm openclaw cron list shows NotFair OpenClaw Scheduler and one NotFair Weekly Review job per active site.
-
-Policy:
-- This is an SEO operator loop, not an auto-publisher.
-- Do not edit websites, CMS content, repos, or publish changes without explicit approval.
-- Weekly review jobs may propose actions and write artifacts only.
-
-Report back with:
-- installed skill names,
-- active sites and GSC properties,
-- cron job ids/schedules,
-- smoke-test artifact path,
-- any blockers.
-```
-
-## Bootstrap a site work folder
-
-```bash
-./openclaw/install/bootstrap-site.sh https://example.com
-```
-
-That creates:
-
-```text
-~/.toprank/openclaw/sites/example.com/
-├── site-profile.json
-├── goals.json
-├── latest-state.json
-├── learned-patterns.json
-├── queue/
-├── proposals/
-├── runs/
-└── feedback/
-```
-
-## Why this matters
-
-Before this layer, NotFair had strong point skills.
-
-Now it has memory and recurrence:
-- **real signal ingestion** via GSC analysis,
-- **persistent state** per website,
-- **scheduled follow-ups** instead of forgotten recommendations,
-- **feedback scoring** instead of vague “seems better”,
-- **learned priors** so future prioritization adapts.
-
-That is the step from “SEO assistant” to “SEO operating loop”.
-
-## Working helper scripts
-
-- `python3 openclaw/bin/onboard_site.py <url> ...` — updates `portfolio.json`, `site-profile.json`, and `goals.json`
-- `python3 openclaw/bin/persist_run.py <site> --payload-file payload.json` — writes review artifacts into a timestamped run folder and refreshes `latest-state.json`
-- `python3 openclaw/bin/portfolio_review.py` — ranks active sites and writes a portfolio review snapshot
-- `python3 openclaw/bin/weekly_review.py <site>` — generates a real weekly review payload from GSC analysis, persists artifacts, and creates a scored follow-up baseline
-- `python3 openclaw/bin/improve_page.py <site> --url <url> ...` — persists a page-improvement proposal and follow-up task
-- `python3 openclaw/bin/investigate_drop.py <site> --summary "..." ...` — persists a drop investigation and recovery plan
-- `python3 openclaw/bin/followups_due.py` — shows which scheduled follow-up items are due now
-- `python3 openclaw/bin/run_scheduler.py` — processes due schedule items, materializes follow-up review artifacts, and surfaces manual-attention work
-- `python3 openclaw/bin/record_followup_metrics.py <site> <item_id> ...` — records observed metrics on a queued follow-up
-- `python3 openclaw/bin/hydrate_followup_gsc.py <site> <item_id> ...` — pulls real GSC metrics into a queued follow-up using the existing `seo-analysis` scripts (uses `site-profile.json` `gsc_property` when present, otherwise falls back to `canonical_url`)
-- `python3 openclaw/bin/score_feedback.py --item-file <queue-item.json>` — scores a follow-up as win / neutral / loss / inconclusive
-
-Use these example payloads and flows as templates:
-
-- `openclaw/artifacts/examples/weekly-review-payload.json`
-- `openclaw/artifacts/examples/gsc-analysis-sample.json`
-- `openclaw/artifacts/examples/improve-page-payload.json`
-- `openclaw/artifacts/examples/investigate-drop-payload.json`
-- `openclaw/artifacts/examples/scored-feedback-item.json`
-
-## Wrapper skills
-
-- `notfair-site-onboard` — register a site and initialize its work folder
-- `notfair-portfolio-review` — rank all active sites by urgency/opportunity
-- `notfair-weekly-review` — review one site and propose the next best action
-- `notfair-improve-page` — improve one URL on a site
-- `notfair-investigate-drop` — traffic-drop recovery workflow
-
-## Autonomous loop building blocks
-
-The closed loop is now made of three concrete runtime pieces:
-
-1. **Weekly review from real data**
- - `weekly_review.py` runs or reads GSC analysis
- - generates `audit.json`, `action-plan.json`, `verification.json`
- - seeds `baseline_metrics` for later scoring
-
-2. **Scheduled follow-up evaluation**
- - `run_scheduler.py` revisits due `feedback_check` items
- - `hydrate_followup_gsc.py` can pull fresh observed metrics
- - `score_feedback.py` classifies `win` / `neutral` / `loss` / `inconclusive`
-
-3. **Learning from outcomes**
- - `learned-patterns.json` stores site-level priors
- - weekly review uses those priors to bias future action ranking
-
-## Automated weekly review
-
-The OpenClaw layer now has a real weekly review runner:
-
-```bash
-python3 openclaw/bin/weekly_review.py example.com
-```
-
-Useful flags:
-- `--gsc-property sc-domain:example.com`
-- `--analysis-file openclaw/artifacts/examples/gsc-analysis-sample.json`
-
-This runner:
-- runs or reads GSC analysis,
-- builds `audit.json`, `action-plan.json`, and `verification.json`,
-- inherits baseline metrics into the follow-up queue item,
-- uses `learned-patterns.json` to bias action ranking,
-- turns raw signals into a concrete next action plus a measurable follow-up.
-
-## Scheduler runner
-
-The MVP now includes a simple runner for automation:
-
-```bash
-python3 openclaw/bin/run_scheduler.py
-# or
-./openclaw/install/run-scheduler.sh
-```
-
-What it does today:
-- processes due `feedback_check` items automatically,
-- scores them as `win`, `neutral`, `loss`, or `inconclusive` when metric snapshots exist,
-- writes follow-up run artifacts,
-- marks processed schedule items,
-- updates `learned-patterns.json` with outcome priors,
-- surfaces unsupported due items as `ready_for_attention`.
-
-Install it with OpenClaw cron:
-
-```bash
-# With chat delivery for useful weekly-review summaries:
-./openclaw/install/install-openclaw-cron.sh \
- --to "<delivery_destination>" \
- --channel telegram \
- --thread-id "<optional_thread_id>"
-
-# Without chat delivery:
-./openclaw/install/install-openclaw-cron.sh
-```
-
-The OpenClaw cron installer creates:
-
-- `NotFair OpenClaw Scheduler` — hourly follow-up processor
-- `NotFair Weekly Review — <site>` — one weekly review per active portfolio site
-
-It intentionally does not set a model by default. If you want a model override, pass `--model <provider/model>` only after confirming the local OpenClaw model allowlist accepts it.
-
-macOS `launchd` is still available as a lower-level alternative:
-
-```bash
-./openclaw/install/install-launchd.sh --write-only
-# inspect the plist, then load it for real:
-./openclaw/install/install-launchd.sh
-```
-
-Or use the system cron example at `openclaw/install/notfair-openclaw.cron.example`.
-
-This is now the core of a real autonomous operator loop.
-
-## Design principle
-
-The OpenClaw surface is an **adapter layer**. The existing NotFair skill folders remain canonical. The OpenClaw wrappers add persistent state, portfolio awareness, artifact writing, and policy gates.
diff --git a/openclaw/artifacts/examples/action-plan.json b/openclaw/artifacts/examples/action-plan.json
deleted file mode 100644
index 37f61a11..00000000
--- a/openclaw/artifacts/examples/action-plan.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "site_id": "example.com",
- "generated_at": "2026-04-29T22:00:00Z",
- "goal_id": "goal_example_001",
- "actions": [
- {
- "action_id": "action_001",
- "title": "Rewrite the homepage title and meta description to match high-impression queries.",
- "type": "meta_tags",
- "priority_score": 0.87,
- "expected_impact": "Improve CTR on a high-impression page.",
- "requires_approval": true,
- "reversibility": "high",
- "owner": "operator"
- }
- ]
-}
diff --git a/openclaw/artifacts/examples/business-context.json b/openclaw/artifacts/examples/business-context.json
deleted file mode 100644
index 5e436b26..00000000
--- a/openclaw/artifacts/examples/business-context.json
+++ /dev/null
@@ -1,56 +0,0 @@
-{
- "site_id": "example.com",
- "site_stage": "harvest",
- "service_value_weights": {
- "emergency roof repair": 1.6,
- "roof replacement": 1.4,
- "roof repair cost": 0.8
- },
- "target_customer_priority": {
- "primary": ["local homeowners ready to book or request a quote"],
- "deprioritized": ["national informational readers outside service area"]
- },
- "location_priorities": {
- "Portland": { "priority": "high", "notes": "High-margin service area with capacity." }
- },
- "conversion_events": [
- {
- "name": "quote_request",
- "weight": 1.5,
- "paths": ["/contact", "/quote", "/roof-repair"],
- "intent_terms": ["near me", "quote", "emergency"]
- },
- {
- "name": "phone_call",
- "weight": 1.3,
- "intent_terms": ["call", "open now", "emergency"]
- }
- ],
- "booking_intent_hierarchy": {
- "highest_priority": ["emergency roof repair portland", "roof repair near me"],
- "supporting_only": ["how much does roof repair cost", "roof repair cost"]
- },
- "local_proof_points": ["same-day inspection", "licensed local team", "transparent price ranges"],
- "serp_competitor_positioning": {
- "roof repair near me": ["map pack", "Angi", "Yelp", "local contractors"]
- },
- "page_role_map": {
- "/roof-repair": "transactional local landing page",
- "/roof-repair-prices": "local commercial-research page",
- "/blog/roof-repair-cost": "supporting informational page"
- },
- "internal_link_sources": {
- "/roof-repair-prices": {
- "hub_pages": ["/services"],
- "adjacent_commercial_pages": ["/roof-repair"],
- "support_pages": ["/blog/roof-repair-cost"]
- }
- },
- "retired_or_cannibal_pages": [
- {
- "url": "/old-roof-repair-pricing",
- "desired_state": "redirected and absent from sitemap/internal links",
- "canonical_owner": "/roof-repair-prices"
- }
- ]
-}
diff --git a/openclaw/artifacts/examples/goal.json b/openclaw/artifacts/examples/goal.json
deleted file mode 100644
index 1c29e2f5..00000000
--- a/openclaw/artifacts/examples/goal.json
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- "goal_id": "goal_example_001",
- "site_id": "example.com",
- "type": "grow_non_brand_clicks",
- "primary_metric": "non_brand_clicks_28d",
- "target_delta": 0.2,
- "status": "active"
-}
diff --git a/openclaw/artifacts/examples/gsc-analysis-sample.json b/openclaw/artifacts/examples/gsc-analysis-sample.json
deleted file mode 100644
index 215ff82e..00000000
--- a/openclaw/artifacts/examples/gsc-analysis-sample.json
+++ /dev/null
@@ -1,69 +0,0 @@
-{
- "site": "sc-domain:example.com",
- "period": {
- "start": "2026-04-01",
- "end": "2026-04-28",
- "days": 28
- },
- "summary": {
- "clicks": 150,
- "impressions": 5200,
- "ctr": 2.88,
- "position": 10.7
- },
- "ctr_gaps_by_page": [
- {
- "page": "https://example.com/services/roof-repair",
- "clicks": 20,
- "impressions": 1200,
- "ctr": 1.67,
- "position": 7.4
- }
- ],
- "ctr_opportunities": [
- {
- "query": "roof repair local",
- "clicks": 12,
- "impressions": 900,
- "ctr": 1.33,
- "position": 6.9
- }
- ],
- "cannibalization": [
- {
- "query": "roof repair pricing",
- "winner_page": "https://example.com/services/roof-repair",
- "loser_pages": [
- "https://example.com/pricing"
- ]
- }
- ],
- "comparison": {
- "declining_pages": [
- {
- "page": "https://example.com/services/roof-repair",
- "change_pct": -35.0,
- "clicks_now": 18,
- "clicks_prev": 28
- }
- ],
- "declining_queries": [
- {
- "query": "emergency roof repair",
- "change_pct": -28.0,
- "clicks_now": 9,
- "clicks_prev": 13
- }
- ]
- },
- "branded_split": {
- "branded": {
- "clicks": 40,
- "impressions": 1000
- },
- "non_branded": {
- "clicks": 110,
- "impressions": 4200
- }
- }
-}
diff --git a/openclaw/artifacts/examples/improve-page-payload.json b/openclaw/artifacts/examples/improve-page-payload.json
deleted file mode 100644
index 7f270e51..00000000
--- a/openclaw/artifacts/examples/improve-page-payload.json
+++ /dev/null
@@ -1,53 +0,0 @@
-{
- "generated_at": "2026-04-29T22:00:00Z",
- "trigger": {
- "type": "improve_page",
- "target": "https://example.com/services/roof-repair",
- "notes": "Improve a service page with weak CTR and missing schema."
- },
- "audit": {
- "summary": "The service page has good impressions but weak CTR and limited structured context.",
- "issues": [
- {
- "title": "Title and meta description do not match top service-intent queries.",
- "severity": "warning",
- "confidence": 0.79,
- "evidence": [
- "Page receives impressions but CTR is below site baseline.",
- "Current title misses the city + service modifier."
- ],
- "recommended_action_type": "meta_tags"
- }
- ]
- },
- "action_plan": {
- "actions": [
- {
- "action_id": "action_001",
- "title": "Draft new title/meta and local-service schema for the page.",
- "type": "page_improvement",
- "priority_score": 0.84,
- "expected_impact": "Improve CTR and clarify page relevance.",
- "requires_approval": true,
- "reversibility": "high",
- "owner": "operator"
- }
- ]
- },
- "proposal": {
- "proposal_type": "page_improvement",
- "target": "https://example.com/services/roof-repair",
- "summary": "Generate 3 title/meta candidates and add schema markup recommendations.",
- "requires_approval": true
- },
- "verification": {
- "checks": [
- {
- "name": "proposal persisted",
- "status": "pass",
- "notes": "Proposal artifact stored."
- }
- ],
- "follow_up_due": "2026-05-13T22:00:00Z"
- }
-}
diff --git a/openclaw/artifacts/examples/investigate-drop-payload.json b/openclaw/artifacts/examples/investigate-drop-payload.json
deleted file mode 100644
index 3ec1f39c..00000000
--- a/openclaw/artifacts/examples/investigate-drop-payload.json
+++ /dev/null
@@ -1,55 +0,0 @@
-{
- "generated_at": "2026-04-29T22:00:00Z",
- "trigger": {
- "type": "traffic_drop_detected",
- "notes": "Organic clicks fell 28% week over week on the primary service cluster."
- },
- "audit": {
- "summary": "Traffic drop investigation identified one likely technical issue and one likely intent/CTR issue.",
- "issues": [
- {
- "title": "A high-value service page may have fallen out of the index.",
- "severity": "critical",
- "confidence": 0.82,
- "evidence": [
- "Primary service page lost impressions sharply.",
- "Recent crawl reported inconsistent indexation."
- ],
- "recommended_action_type": "drop_recovery"
- },
- {
- "title": "Homepage CTR declined after a recent copy change.",
- "severity": "warning",
- "confidence": 0.68,
- "evidence": [
- "CTR down on high-impression brand-adjacent queries."
- ],
- "recommended_action_type": "drop_recovery"
- }
- ]
- },
- "action_plan": {
- "actions": [
- {
- "action_id": "action_001",
- "title": "Investigate indexation and request recrawl if needed.",
- "type": "drop_recovery",
- "priority_score": 0.92,
- "expected_impact": "Recover lost visibility from a likely indexation issue.",
- "requires_approval": true,
- "reversibility": "high",
- "owner": "operator"
- }
- ]
- },
- "verification": {
- "checks": [
- {
- "name": "drop investigation persisted",
- "status": "pass",
- "notes": "Recovery plan stored."
- }
- ],
- "follow_up_due": "2026-05-06T22:00:00Z"
- }
-}
diff --git a/openclaw/artifacts/examples/portfolio.json b/openclaw/artifacts/examples/portfolio.json
deleted file mode 100644
index 674d24ea..00000000
--- a/openclaw/artifacts/examples/portfolio.json
+++ /dev/null
@@ -1,13 +0,0 @@
-{
- "schema_version": "1",
- "portfolio_id": "default",
- "sites": [
- {
- "site_id": "example.com",
- "display_name": "Example",
- "business_weight": 1.0,
- "cadence": "weekly",
- "status": "active"
- }
- ]
-}
diff --git a/openclaw/artifacts/examples/scored-feedback-item.json b/openclaw/artifacts/examples/scored-feedback-item.json
deleted file mode 100644
index 4e583ade..00000000
--- a/openclaw/artifacts/examples/scored-feedback-item.json
+++ /dev/null
@@ -1,26 +0,0 @@
-{
- "item_id": "followup_example_homepage_ctr_14d",
- "site_id": "example.com",
- "type": "feedback_check",
- "status": "pending",
- "due_at": "2026-05-13T22:00:00Z",
- "notes": "Review homepage CTR after approved metadata changes.",
- "primary_metric": "organic_clicks_28d",
- "primary_direction": "higher_better",
- "success_threshold_pct": 0.1,
- "baseline_metrics": {
- "organic_clicks_28d": 100,
- "conversions_28d": 10
- },
- "observed_metrics": {
- "organic_clicks_28d": 121,
- "conversions_28d": 11
- },
- "guardrail_metrics": [
- {
- "metric": "conversions_28d",
- "direction": "higher_better",
- "max_worsen_pct": 0.05
- }
- ]
-}
diff --git a/openclaw/artifacts/examples/site-profile.json b/openclaw/artifacts/examples/site-profile.json
deleted file mode 100644
index 1082f60a..00000000
--- a/openclaw/artifacts/examples/site-profile.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "schema_version": "1",
- "site_id": "example.com",
- "canonical_url": "https://example.com",
- "display_name": "Example",
- "brand_terms": [
- "Example"
- ],
- "cms": "nextjs",
- "business_context": "Demo site profile for the OpenClaw adaptive layer.",
- "status": "active"
-}
diff --git a/openclaw/artifacts/examples/weekly-review-payload.json b/openclaw/artifacts/examples/weekly-review-payload.json
deleted file mode 100644
index 8aafe5d9..00000000
--- a/openclaw/artifacts/examples/weekly-review-payload.json
+++ /dev/null
@@ -1,79 +0,0 @@
-{
- "generated_at": "2026-04-29T22:00:00Z",
- "trigger": {
- "type": "weekly_review",
- "notes": "Scheduled weekly review for example.com."
- },
- "state_snapshot": {
- "summary": "Homepage CTR is lagging and one service page has indexation risk.",
- "open_issues": [
- {
- "title": "Homepage CTR lag",
- "severity": "warning",
- "confidence": 0.78
- },
- {
- "title": "Service page not consistently indexed",
- "severity": "warning",
- "confidence": 0.66
- }
- ],
- "recent_actions": [],
- "metrics": {
- "organic_clicks_28d": 100,
- "organic_impressions_28d": 4000,
- "organic_ctr_28d": 2.5,
- "avg_position_28d": 11.2,
- "non_brand_clicks_28d": 72,
- "branded_clicks_28d": 28
- }
- },
- "audit": {
- "summary": "Two high-leverage SEO issues were identified during the weekly review.",
- "issues": [
- {
- "title": "Homepage title does not align with top impression queries.",
- "severity": "warning",
- "confidence": 0.81,
- "evidence": [
- "High impressions with below-baseline CTR.",
- "Current title misses the primary service term."
- ],
- "recommended_action_type": "meta_tags"
- }
- ]
- },
- "action_plan": {
- "actions": [
- {
- "action_id": "action_001",
- "title": "Draft three homepage title/meta variants for approval.",
- "type": "meta_tags",
- "priority_score": 0.87,
- "expected_impact": "Improve CTR on the site's highest-impression page.",
- "requires_approval": true,
- "reversibility": "high",
- "owner": "operator"
- }
- ]
- },
- "verification": {
- "checks": [
- {
- "name": "artifact completeness",
- "status": "pass",
- "notes": "Audit, action plan, and verification artifacts were written."
- }
- ],
- "follow_up_due": "2026-05-13T22:00:00Z"
- },
- "queue_items": [
- {
- "item_id": "followup_example_homepage_ctr_14d",
- "type": "feedback_check",
- "status": "pending",
- "due_at": "2026-05-13T22:00:00Z",
- "notes": "Re-check homepage CTR after any approved metadata update."
- }
- ]
-}
diff --git a/openclaw/artifacts/schemas/action-plan.schema.json b/openclaw/artifacts/schemas/action-plan.schema.json
deleted file mode 100644
index 9c15642a..00000000
--- a/openclaw/artifacts/schemas/action-plan.schema.json
+++ /dev/null
@@ -1,73 +0,0 @@
-{
- "$schema": "https://json-schema.org/draft/2020-12/schema",
- "title": "NotFair OpenClaw Action Plan",
- "type": "object",
- "properties": {
- "site_id": {
- "type": "string"
- },
- "generated_at": {
- "type": "string"
- },
- "goal_id": {
- "type": [
- "string",
- "null"
- ]
- },
- "actions": {
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "action_id": {
- "type": "string"
- },
- "title": {
- "type": "string"
- },
- "type": {
- "type": "string"
- },
- "priority_score": {
- "type": "number"
- },
- "expected_impact": {
- "type": "string"
- },
- "requires_approval": {
- "type": "boolean"
- },
- "reversibility": {
- "type": "string",
- "enum": [
- "high",
- "medium",
- "low"
- ]
- },
- "owner": {
- "type": [
- "string",
- "null"
- ]
- }
- },
- "required": [
- "action_id",
- "title",
- "type",
- "priority_score",
- "requires_approval"
- ],
- "additionalProperties": true
- }
- }
- },
- "required": [
- "site_id",
- "generated_at",
- "actions"
- ],
- "additionalProperties": true
-}
diff --git a/openclaw/artifacts/schemas/audit.schema.json b/openclaw/artifacts/schemas/audit.schema.json
deleted file mode 100644
index 8cf10ebf..00000000
--- a/openclaw/artifacts/schemas/audit.schema.json
+++ /dev/null
@@ -1,63 +0,0 @@
-{
- "$schema": "https://json-schema.org/draft/2020-12/schema",
- "title": "NotFair OpenClaw Audit",
- "type": "object",
- "properties": {
- "site_id": {
- "type": "string"
- },
- "generated_at": {
- "type": "string"
- },
- "summary": {
- "type": "string"
- },
- "issues": {
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "title": {
- "type": "string"
- },
- "severity": {
- "type": "string",
- "enum": [
- "critical",
- "warning",
- "info"
- ]
- },
- "confidence": {
- "type": "number"
- },
- "evidence": {
- "type": "array",
- "items": {
- "type": "string"
- }
- },
- "recommended_action_type": {
- "type": [
- "string",
- "null"
- ]
- }
- },
- "required": [
- "title",
- "severity",
- "evidence"
- ],
- "additionalProperties": true
- }
- }
- },
- "required": [
- "site_id",
- "generated_at",
- "summary",
- "issues"
- ],
- "additionalProperties": true
-}
diff --git a/openclaw/artifacts/schemas/business-context.schema.json b/openclaw/artifacts/schemas/business-context.schema.json
deleted file mode 100644
index 92634278..00000000
--- a/openclaw/artifacts/schemas/business-context.schema.json
+++ /dev/null
@@ -1,60 +0,0 @@
-{
- "$schema": "https://json-schema.org/draft/2020-12/schema",
- "title": "NotFair OpenClaw Business Impact Context",
- "type": "object",
- "properties": {
- "site_id": { "type": "string" },
- "site_stage": {
- "type": "string",
- "enum": ["seed", "harvest", "defend", "recover"]
- },
- "service_value_weights": {
- "description": "Relative revenue/margin weights by service, product, query theme, or page family. 1.0 = neutral; >1 = more valuable.",
- "oneOf": [
- { "type": "object", "additionalProperties": { "type": "number" } },
- {
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "term": { "type": "string" },
- "service": { "type": "string" },
- "product": { "type": "string" },
- "weight": { "type": "number" }
- },
- "additionalProperties": true
- }
- }
- ]
- },
- "target_customer_priority": {
- "description": "Priority and deprioritized customer segments for qualified organic growth."
- },
- "location_priorities": {
- "description": "Market/service-area priorities, capacity, and margin context."
- },
- "conversion_events": {
- "description": "Organic conversion events or funnel signals with optional value weights and URL/query matches."
- },
- "booking_intent_hierarchy": {
- "description": "Highest-priority vs supporting-only query intents."
- },
- "local_proof_points": {
- "description": "Proof points snippets/content should emphasize."
- },
- "serp_competitor_positioning": {
- "description": "Competitors/directories/SERP modules that affect priority queries."
- },
- "page_role_map": {
- "description": "Mapping from URL/path to transactional, commercial, local, support, informational, or docs role."
- },
- "internal_link_sources": {
- "description": "Known hub/category, adjacent commercial/service, and support/blog/docs pages that should link to priority SEO targets."
- },
- "retired_or_cannibal_pages": {
- "description": "URLs that should be noindex, redirected, canonicalized, removed from sitemap, or removed from internal links."
- }
- },
- "required": ["site_id"],
- "additionalProperties": true
-}
diff --git a/openclaw/artifacts/schemas/feedback.schema.json b/openclaw/artifacts/schemas/feedback.schema.json
deleted file mode 100644
index 9797956c..00000000
--- a/openclaw/artifacts/schemas/feedback.schema.json
+++ /dev/null
@@ -1,40 +0,0 @@
-{
- "$schema": "https://json-schema.org/draft/2020-12/schema",
- "title": "NotFair OpenClaw Feedback",
- "type": "object",
- "properties": {
- "site_id": {
- "type": "string"
- },
- "generated_at": {
- "type": "string"
- },
- "action_id": {
- "type": "string"
- },
- "window_days": {
- "type": "integer"
- },
- "outcome": {
- "type": "string",
- "enum": [
- "win",
- "neutral",
- "loss",
- "inconclusive"
- ]
- },
- "summary": {
- "type": "string"
- }
- },
- "required": [
- "site_id",
- "generated_at",
- "action_id",
- "window_days",
- "outcome",
- "summary"
- ],
- "additionalProperties": true
-}
diff --git a/openclaw/artifacts/schemas/goal.schema.json b/openclaw/artifacts/schemas/goal.schema.json
deleted file mode 100644
index affb59f4..00000000
--- a/openclaw/artifacts/schemas/goal.schema.json
+++ /dev/null
@@ -1,41 +0,0 @@
-{
- "$schema": "https://json-schema.org/draft/2020-12/schema",
- "title": "NotFair OpenClaw Goal",
- "type": "object",
- "properties": {
- "goal_id": {
- "type": "string"
- },
- "site_id": {
- "type": "string"
- },
- "type": {
- "type": "string"
- },
- "primary_metric": {
- "type": "string"
- },
- "target_delta": {
- "type": [
- "number",
- "null"
- ]
- },
- "status": {
- "type": "string",
- "enum": [
- "active",
- "paused",
- "archived"
- ]
- }
- },
- "required": [
- "goal_id",
- "site_id",
- "type",
- "primary_metric",
- "status"
- ],
- "additionalProperties": true
-}
diff --git a/openclaw/artifacts/schemas/learning-log.schema.json b/openclaw/artifacts/schemas/learning-log.schema.json
deleted file mode 100644
index 09efe36e..00000000
--- a/openclaw/artifacts/schemas/learning-log.schema.json
+++ /dev/null
@@ -1,42 +0,0 @@
-{
- "$schema": "https://json-schema.org/draft/2020-12/schema",
- "title": "NotFair OpenClaw Learning Log",
- "type": "object",
- "properties": {
- "site_id": {
- "type": "string"
- },
- "generated_at": {
- "type": "string"
- },
- "observations": {
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "pattern": {
- "type": "string"
- },
- "confidence": {
- "type": "number"
- },
- "notes": {
- "type": "string"
- }
- },
- "required": [
- "pattern",
- "confidence",
- "notes"
- ],
- "additionalProperties": true
- }
- }
- },
- "required": [
- "site_id",
- "generated_at",
- "observations"
- ],
- "additionalProperties": true
-}
diff --git a/openclaw/artifacts/schemas/patch-set.schema.json b/openclaw/artifacts/schemas/patch-set.schema.json
deleted file mode 100644
index 74a5e229..00000000
--- a/openclaw/artifacts/schemas/patch-set.schema.json
+++ /dev/null
@@ -1,42 +0,0 @@
-{
- "$schema": "https://json-schema.org/draft/2020-12/schema",
- "title": "NotFair OpenClaw Patch Set",
- "type": "object",
- "properties": {
- "site_id": {
- "type": "string"
- },
- "generated_at": {
- "type": "string"
- },
- "patches": {
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "path": {
- "type": "string"
- },
- "change_type": {
- "type": "string"
- },
- "summary": {
- "type": "string"
- }
- },
- "required": [
- "path",
- "change_type",
- "summary"
- ],
- "additionalProperties": true
- }
- }
- },
- "required": [
- "site_id",
- "generated_at",
- "patches"
- ],
- "additionalProperties": true
-}
diff --git a/openclaw/artifacts/schemas/portfolio.schema.json b/openclaw/artifacts/schemas/portfolio.schema.json
deleted file mode 100644
index 66436c36..00000000
--- a/openclaw/artifacts/schemas/portfolio.schema.json
+++ /dev/null
@@ -1,60 +0,0 @@
-{
- "$schema": "https://json-schema.org/draft/2020-12/schema",
- "title": "NotFair OpenClaw Portfolio",
- "type": "object",
- "properties": {
- "schema_version": {
- "type": "string"
- },
- "portfolio_id": {
- "type": "string"
- },
- "sites": {
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "site_id": {
- "type": "string"
- },
- "display_name": {
- "type": "string"
- },
- "business_weight": {
- "type": "number"
- },
- "cadence": {
- "type": "string",
- "enum": [
- "daily",
- "weekly",
- "monthly",
- "on_demand"
- ]
- },
- "status": {
- "type": "string",
- "enum": [
- "active",
- "paused",
- "archived"
- ]
- }
- },
- "required": [
- "site_id",
- "business_weight",
- "cadence",
- "status"
- ],
- "additionalProperties": true
- }
- }
- },
- "required": [
- "schema_version",
- "portfolio_id",
- "sites"
- ],
- "additionalProperties": true
-}
diff --git a/openclaw/artifacts/schemas/proposal.schema.json b/openclaw/artifacts/schemas/proposal.schema.json
deleted file mode 100644
index 6412db48..00000000
--- a/openclaw/artifacts/schemas/proposal.schema.json
+++ /dev/null
@@ -1,34 +0,0 @@
-{
- "$schema": "https://json-schema.org/draft/2020-12/schema",
- "title": "NotFair OpenClaw Proposal",
- "type": "object",
- "properties": {
- "site_id": {
- "type": "string"
- },
- "generated_at": {
- "type": "string"
- },
- "proposal_type": {
- "type": "string"
- },
- "target": {
- "type": "string"
- },
- "summary": {
- "type": "string"
- },
- "requires_approval": {
- "type": "boolean"
- }
- },
- "required": [
- "site_id",
- "generated_at",
- "proposal_type",
- "target",
- "summary",
- "requires_approval"
- ],
- "additionalProperties": true
-}
diff --git a/openclaw/artifacts/schemas/queue-item.schema.json b/openclaw/artifacts/schemas/queue-item.schema.json
deleted file mode 100644
index 48d3f697..00000000
--- a/openclaw/artifacts/schemas/queue-item.schema.json
+++ /dev/null
@@ -1,46 +0,0 @@
-{
- "$schema": "https://json-schema.org/draft/2020-12/schema",
- "title": "NotFair OpenClaw Queue Item",
- "type": "object",
- "properties": {
- "item_id": {
- "type": "string"
- },
- "site_id": {
- "type": "string"
- },
- "type": {
- "type": "string"
- },
- "status": {
- "type": "string",
- "enum": [
- "pending",
- "in_progress",
- "ready_for_attention",
- "blocked",
- "done",
- "processed"
- ]
- },
- "due_at": {
- "type": [
- "string",
- "null"
- ]
- },
- "notes": {
- "type": [
- "string",
- "null"
- ]
- }
- },
- "required": [
- "item_id",
- "site_id",
- "type",
- "status"
- ],
- "additionalProperties": true
-}
diff --git a/openclaw/artifacts/schemas/site-profile.schema.json b/openclaw/artifacts/schemas/site-profile.schema.json
deleted file mode 100644
index cf039a2c..00000000
--- a/openclaw/artifacts/schemas/site-profile.schema.json
+++ /dev/null
@@ -1,53 +0,0 @@
-{
- "$schema": "https://json-schema.org/draft/2020-12/schema",
- "title": "NotFair OpenClaw Site Profile",
- "type": "object",
- "properties": {
- "schema_version": {
- "type": "string"
- },
- "site_id": {
- "type": "string"
- },
- "canonical_url": {
- "type": "string"
- },
- "display_name": {
- "type": "string"
- },
- "brand_terms": {
- "type": "array",
- "items": {
- "type": "string"
- }
- },
- "cms": {
- "type": [
- "string",
- "null"
- ]
- },
- "business_context": {
- "type": [
- "string",
- "null"
- ]
- },
- "status": {
- "type": "string",
- "enum": [
- "active",
- "paused",
- "archived"
- ]
- }
- },
- "required": [
- "schema_version",
- "site_id",
- "canonical_url",
- "brand_terms",
- "status"
- ],
- "additionalProperties": true
-}
diff --git a/openclaw/artifacts/schemas/state-snapshot.schema.json b/openclaw/artifacts/schemas/state-snapshot.schema.json
deleted file mode 100644
index 95a9a3c9..00000000
--- a/openclaw/artifacts/schemas/state-snapshot.schema.json
+++ /dev/null
@@ -1,37 +0,0 @@
-{
- "$schema": "https://json-schema.org/draft/2020-12/schema",
- "title": "NotFair OpenClaw State Snapshot",
- "type": "object",
- "properties": {
- "site_id": {
- "type": "string"
- },
- "generated_at": {
- "type": "string"
- },
- "trigger": {
- "type": "string"
- },
- "summary": {
- "type": "string"
- },
- "open_issues": {
- "type": "array",
- "items": {
- "type": "object"
- }
- },
- "recent_actions": {
- "type": "array",
- "items": {
- "type": "object"
- }
- }
- },
- "required": [
- "site_id",
- "generated_at",
- "summary"
- ],
- "additionalProperties": true
-}
diff --git a/openclaw/artifacts/schemas/verification.schema.json b/openclaw/artifacts/schemas/verification.schema.json
deleted file mode 100644
index 13d124d5..00000000
--- a/openclaw/artifacts/schemas/verification.schema.json
+++ /dev/null
@@ -1,56 +0,0 @@
-{
- "$schema": "https://json-schema.org/draft/2020-12/schema",
- "title": "NotFair OpenClaw Verification",
- "type": "object",
- "properties": {
- "site_id": {
- "type": "string"
- },
- "generated_at": {
- "type": "string"
- },
- "checks": {
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "name": {
- "type": "string"
- },
- "status": {
- "type": "string",
- "enum": [
- "pass",
- "warning",
- "fail",
- "not_run"
- ]
- },
- "notes": {
- "type": [
- "string",
- "null"
- ]
- }
- },
- "required": [
- "name",
- "status"
- ],
- "additionalProperties": true
- }
- },
- "follow_up_due": {
- "type": [
- "string",
- "null"
- ]
- }
- },
- "required": [
- "site_id",
- "generated_at",
- "checks"
- ],
- "additionalProperties": true
-}
diff --git a/openclaw/artifacts/visuals/continuous-seo-improvement-loop.jpg b/openclaw/artifacts/visuals/continuous-seo-improvement-loop.jpg
deleted file mode 100644
index 3148a0fc..00000000
Binary files a/openclaw/artifacts/visuals/continuous-seo-improvement-loop.jpg and /dev/null differ
diff --git a/openclaw/bin/bootstrap_site.py b/openclaw/bin/bootstrap_site.py
deleted file mode 100755
index 23fcda49..00000000
--- a/openclaw/bin/bootstrap_site.py
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/usr/bin/env python3
-"""Initialize a per-site work folder inside the NotFair OpenClaw runtime workspace."""
-
-from __future__ import annotations
-
-import sys
-from pathlib import Path
-
-CURRENT_DIR = Path(__file__).resolve().parent
-if str(CURRENT_DIR) not in sys.path:
- sys.path.insert(0, str(CURRENT_DIR))
-
-from runtime import bootstrap_workspace, ensure_site_dirs, load_json, save_json, workspace_root
-from site_id import normalize_site_id
-
-
-def bootstrap_site(site_input: str, root: Path | None = None) -> Path:
- site_id = normalize_site_id(site_input)
- root = bootstrap_workspace(root or workspace_root())
- site_root = ensure_site_dirs(site_id, root)
-
- profile = site_root / "site-profile.json"
- goals = site_root / "goals.json"
- latest = site_root / "latest-state.json"
- learned = site_root / "learned-patterns.json"
-
- if not profile.exists():
- save_json(
- profile,
- {
- "schema_version": "1",
- "site_id": site_id,
- "canonical_url": site_input if "://" in site_input else f"https://{site_id}",
- "display_name": site_id,
- "brand_terms": [],
- "cms": None,
- "business_context": None,
- "status": "active",
- },
- )
-
- if not goals.exists():
- save_json(goals, {"active": [], "archived": []})
-
- if not latest.exists():
- save_json(
- latest,
- {
- "site_id": site_id,
- "summary": "bootstrap complete",
- "open_issues": [],
- "recent_actions": [],
- },
- )
-
- if not learned.exists():
- save_json(learned, {"site_id": site_id, "observations": []})
-
- return site_root
-
-
-def main(argv: list[str]) -> int:
- if len(argv) != 2:
- print("usage: bootstrap_site.py <url-or-domain>", file=sys.stderr)
- return 1
- print(bootstrap_site(argv[1]))
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main(sys.argv))
diff --git a/openclaw/bin/bootstrap_workspace.py b/openclaw/bin/bootstrap_workspace.py
deleted file mode 100755
index 4cd1f4f1..00000000
--- a/openclaw/bin/bootstrap_workspace.py
+++ /dev/null
@@ -1,10 +0,0 @@
-#!/usr/bin/env python3
-"""Create the NotFair OpenClaw runtime workspace if it does not exist."""
-
-from __future__ import annotations
-
-from runtime import bootstrap_workspace
-
-
-if __name__ == "__main__":
- print(bootstrap_workspace())
diff --git a/openclaw/bin/followups_due.py b/openclaw/bin/followups_due.py
deleted file mode 100755
index e7039b39..00000000
--- a/openclaw/bin/followups_due.py
+++ /dev/null
@@ -1,67 +0,0 @@
-#!/usr/bin/env python3
-"""List due or upcoming follow-up items from the NotFair OpenClaw schedule."""
-
-from __future__ import annotations
-
-import argparse
-import json
-import sys
-from datetime import datetime, timezone
-from pathlib import Path
-
-CURRENT_DIR = Path(__file__).resolve().parent
-if str(CURRENT_DIR) not in sys.path:
- sys.path.insert(0, str(CURRENT_DIR))
-
-from runtime import bootstrap_workspace, load_json, now_iso, reconcile_schedule_from_queue, save_json, workspace_root
-
-
-def parse_iso(value: str | None) -> datetime:
- if not value:
- return datetime.max.replace(tzinfo=timezone.utc)
- normalized = value.replace("Z", "+00:00")
- parsed = datetime.fromisoformat(normalized)
- if parsed.tzinfo is None:
- return parsed.replace(tzinfo=timezone.utc)
- return parsed
-
-
-def main(argv: list[str]) -> int:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--site")
- parser.add_argument("--include-future", action="store_true")
- parser.add_argument("--as-of", default=now_iso())
- args = parser.parse_args(argv[1:])
-
- root = bootstrap_workspace(workspace_root())
- schedule_path = root / "schedule.json"
- schedule = load_json(schedule_path, {"upcoming": []})
- schedule, restored_from_queue = reconcile_schedule_from_queue(root, schedule)
- save_json(schedule_path, schedule)
- cutoff = parse_iso(args.as_of)
-
- items = []
- for item in schedule.get("upcoming", []):
- if item.get("status") in {"done", "processed"}:
- continue
- if args.site and item.get("site_id") != args.site:
- continue
- due_at = parse_iso(item.get("due_at"))
- if args.include_future or due_at <= cutoff:
- items.append(item)
-
- items.sort(key=lambda item: item.get("due_at") or "")
- result = {
- "generated_at": now_iso(),
- "as_of": args.as_of,
- "site_filter": args.site,
- "count": len(items),
- "items": items,
- "restored_from_queue": restored_from_queue,
- }
- print(json.dumps(result, indent=2))
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main(sys.argv))
diff --git a/openclaw/bin/hydrate_followup_gsc.py b/openclaw/bin/hydrate_followup_gsc.py
deleted file mode 100755
index 5538b9fb..00000000
--- a/openclaw/bin/hydrate_followup_gsc.py
+++ /dev/null
@@ -1,117 +0,0 @@
-#!/usr/bin/env python3
-"""Fetch real GSC metrics for a follow-up item and attach them as observed metrics."""
-
-from __future__ import annotations
-
-import argparse
-import json
-import subprocess
-import sys
-import tempfile
-from pathlib import Path
-
-CURRENT_DIR = Path(__file__).resolve().parent
-if str(CURRENT_DIR) not in sys.path:
- sys.path.insert(0, str(CURRENT_DIR))
-
-from runtime import bootstrap_workspace, load_json, workspace_root
-
-ANALYZE_GSC = Path(__file__).resolve().parents[2] / "seo" / "seo-analysis" / "scripts" / "analyze_gsc.py"
-
-
-def infer_days(primary_metric: str | None, fallback: int = 28) -> int:
- if not primary_metric:
- return fallback
- for part in primary_metric.split("_"):
- if part.endswith("d") and part[:-1].isdigit():
- return int(part[:-1])
- return fallback
-
-
-def metric_suffix(days: int) -> str:
- return f"_{days}d"
-
-
-def extract_metrics(data: dict, days: int) -> dict[str, float]:
- suffix = metric_suffix(days)
- summary = data.get("summary", {})
- metrics: dict[str, float] = {}
- if summary:
- metrics[f"organic_clicks{suffix}"] = float(summary.get("clicks", 0))
- metrics[f"organic_impressions{suffix}"] = float(summary.get("impressions", 0))
- metrics[f"organic_ctr{suffix}"] = float(summary.get("ctr", 0))
- metrics[f"avg_position{suffix}"] = float(summary.get("position", 0))
- branded_split = data.get("branded_split") or {}
- branded = branded_split.get("branded") or {}
- non_branded = branded_split.get("non_branded") or {}
- if branded or non_branded:
- metrics[f"branded_clicks{suffix}"] = float(branded.get("clicks", 0))
- metrics[f"non_brand_clicks{suffix}"] = float(non_branded.get("clicks", 0))
- metrics[f"branded_impressions{suffix}"] = float(branded.get("impressions", 0))
- metrics[f"non_brand_impressions{suffix}"] = float(non_branded.get("impressions", 0))
- return metrics
-
-
-def main(argv: list[str]) -> int:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("site_id")
- parser.add_argument("item_id")
- parser.add_argument("--gsc-property")
- parser.add_argument("--brand-terms")
- parser.add_argument("--days", type=int)
- parser.add_argument("--analysis-file")
- args = parser.parse_args(argv[1:])
-
- root = bootstrap_workspace(workspace_root())
- site_root = root / "sites" / args.site_id
- queue_path = site_root / "queue" / f"{args.item_id}.json"
- if not queue_path.exists():
- raise SystemExit(f"queue item not found: {queue_path}")
- queue_item = load_json(queue_path, {})
- profile = load_json(site_root / "site-profile.json", {})
-
- primary_metric = queue_item.get("primary_metric")
- days = args.days or infer_days(primary_metric, 28)
- gsc_property = args.gsc_property or profile.get("gsc_property") or profile.get("canonical_url")
- if not gsc_property:
- raise SystemExit("No GSC property or canonical_url available for this site.")
-
- brand_terms = args.brand_terms or ",".join(profile.get("brand_terms", []))
-
- if args.analysis_file:
- data = json.loads(Path(args.analysis_file).read_text())
- else:
- with tempfile.NamedTemporaryFile(prefix="notfair_gsc_", suffix=".json", delete=False) as tmp:
- output_path = Path(tmp.name)
-
- cmd = [sys.executable, str(ANALYZE_GSC), "--site", gsc_property, "--days", str(days), "--output", str(output_path)]
- if brand_terms:
- cmd.extend(["--brand-terms", brand_terms])
- subprocess.run(cmd, check=True)
-
- data = json.loads(output_path.read_text())
- observed_metrics = extract_metrics(data, days)
- queue_item.setdefault("observed_metrics", {})
- queue_item["observed_metrics"].update(observed_metrics)
- queue_path.write_text(json.dumps(queue_item, indent=2, ensure_ascii=False) + "\n")
-
- schedule_path = root / "schedule.json"
- schedule = load_json(schedule_path, {"schema_version": "1", "upcoming": []})
- for item in schedule.get("upcoming", []):
- if item.get("item_id") == args.item_id and item.get("site_id") == args.site_id:
- item.setdefault("observed_metrics", {})
- item["observed_metrics"].update(observed_metrics)
- break
- schedule_path.write_text(json.dumps(schedule, indent=2, ensure_ascii=False) + "\n")
-
- print(json.dumps({
- "queue_path": str(queue_path),
- "gsc_property": gsc_property,
- "days": days,
- "observed_metrics": observed_metrics,
- }, indent=2))
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main(sys.argv))
diff --git a/openclaw/bin/improve_page.py b/openclaw/bin/improve_page.py
deleted file mode 100755
index a2f0882e..00000000
--- a/openclaw/bin/improve_page.py
+++ /dev/null
@@ -1,171 +0,0 @@
-#!/usr/bin/env python3
-"""Create and persist a page-improvement proposal for a site."""
-
-from __future__ import annotations
-
-import argparse
-import json
-import sys
-from datetime import datetime, timedelta, timezone
-from pathlib import Path
-
-CURRENT_DIR = Path(__file__).resolve().parent
-if str(CURRENT_DIR) not in sys.path:
- sys.path.insert(0, str(CURRENT_DIR))
-
-from persist_run import persist_payload
-from runtime import now_iso, workspace_root
-from site_id import normalize_site_id
-
-
-def future_iso(days: int) -> str:
- return (datetime.now(timezone.utc) + timedelta(days=days)).replace(microsecond=0).isoformat().replace("+00:00", "Z")
-
-
-def main(argv: list[str]) -> int:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("site")
- parser.add_argument("--url", required=True)
- parser.add_argument("--issue-summary", required=True)
- parser.add_argument("--proposal-summary", required=True)
- parser.add_argument("--action-type", default="page_improvement")
- parser.add_argument("--expected-impact", default="Improve organic performance for the target page.")
- parser.add_argument("--requires-approval", dest="requires_approval", action="store_true", default=True)
- parser.add_argument("--auto-safe", dest="requires_approval", action="store_false")
- parser.add_argument("--follow-up-days", type=int, default=14)
- parser.add_argument("--primary-metric", default="organic_clicks_28d")
- parser.add_argument("--success-threshold-pct", type=float, default=0.1)
- parser.add_argument("--baseline-metric", action="append", default=[])
- parser.add_argument("--guardrail-metric", action="append", default=[], help="metric:direction:max_worsen_pct")
- parser.add_argument("--patch-path", action="append", default=[])
- parser.add_argument("--patch-summary", action="append", default=[])
- args = parser.parse_args(argv[1:])
-
- site_id = normalize_site_id(args.site)
- generated_at = now_iso()
- follow_up_due = future_iso(args.follow_up_days)
-
- baseline_metrics = {}
- for raw in args.baseline_metric:
- if "=" not in raw:
- raise SystemExit(f"baseline metric must look like name=value, got: {raw}")
- name, value = raw.split("=", 1)
- baseline_metrics[name.strip()] = float(value)
-
- guardrail_metrics = []
- for raw in args.guardrail_metric:
- metric, direction, max_worsen = raw.split(":", 2)
- guardrail_metrics.append({"metric": metric, "direction": direction, "max_worsen_pct": float(max_worsen)})
-
- proposal = {
- "site_id": site_id,
- "generated_at": generated_at,
- "proposal_type": args.action_type,
- "target": args.url,
- "summary": args.proposal_summary,
- "requires_approval": args.requires_approval,
- }
-
- payload: dict = {
- "generated_at": generated_at,
- "trigger": {
- "type": "improve_page",
- "target": args.url,
- "notes": f"Improve page workflow for {args.url}.",
- },
- "state_snapshot": {
- "site_id": site_id,
- "generated_at": generated_at,
- "summary": f"Page improvement requested for {args.url}.",
- "open_issues": [
- {
- "title": args.issue_summary,
- "severity": "warning",
- "confidence": 0.75,
- }
- ],
- "recent_actions": [],
- },
- "audit": {
- "site_id": site_id,
- "generated_at": generated_at,
- "summary": f"Focused page review for {args.url}.",
- "issues": [
- {
- "title": args.issue_summary,
- "severity": "warning",
- "confidence": 0.75,
- "evidence": [f"Target URL: {args.url}"],
- "recommended_action_type": args.action_type,
- }
- ],
- },
- "action_plan": {
- "site_id": site_id,
- "generated_at": generated_at,
- "actions": [
- {
- "action_id": f"improve_page_{site_id}_{generated_at.replace(':', '-')}",
- "title": args.proposal_summary,
- "type": args.action_type,
- "priority_score": 0.82,
- "expected_impact": args.expected_impact,
- "requires_approval": args.requires_approval,
- "reversibility": "high",
- "owner": "operator",
- }
- ],
- },
- "proposal": proposal,
- "verification": {
- "site_id": site_id,
- "generated_at": generated_at,
- "checks": [
- {
- "name": "proposal persisted",
- "status": "pass",
- "notes": f"Stored proposal artifact for {args.url}.",
- },
- {
- "name": "approval gate",
- "status": "warning" if args.requires_approval else "pass",
- "notes": "External or production writes still require approval." if args.requires_approval else "No external write requested yet.",
- },
- ],
- "follow_up_due": follow_up_due,
- },
- "queue_items": [
- {
- "item_id": f"followup_{site_id}_{generated_at.replace(':', '-')}",
- "type": "feedback_check",
- "status": "pending",
- "due_at": follow_up_due,
- "notes": f"Review impact of page improvement for {args.url}.",
- "action_type": args.action_type,
- "primary_metric": args.primary_metric,
- "primary_direction": "higher_better",
- "success_threshold_pct": args.success_threshold_pct,
- "baseline_metrics": baseline_metrics,
- "guardrail_metrics": guardrail_metrics,
- }
- ],
- }
-
- if args.patch_path:
- patches = []
- for index, path in enumerate(args.patch_path):
- summary = args.patch_summary[index] if index < len(args.patch_summary) else f"Patch proposal for {path}"
- patches.append({"path": path, "change_type": args.action_type, "summary": summary})
- payload["patch_set"] = {
- "site_id": site_id,
- "generated_at": generated_at,
- "patches": patches,
- }
-
- result = persist_payload(args.site, payload, root=workspace_root())
- print(json.dumps(result, indent=2))
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main(sys.argv))
diff --git a/openclaw/bin/investigate_drop.py b/openclaw/bin/investigate_drop.py
deleted file mode 100755
index 635e772c..00000000
--- a/openclaw/bin/investigate_drop.py
+++ /dev/null
@@ -1,165 +0,0 @@
-#!/usr/bin/env python3
-"""Create and persist a traffic-drop investigation for a site."""
-
-from __future__ import annotations
-
-import argparse
-import json
-import sys
-from datetime import datetime, timedelta, timezone
-from pathlib import Path
-
-CURRENT_DIR = Path(__file__).resolve().parent
-if str(CURRENT_DIR) not in sys.path:
- sys.path.insert(0, str(CURRENT_DIR))
-
-from persist_run import persist_payload
-from runtime import now_iso, workspace_root
-from site_id import normalize_site_id
-
-
-def future_iso(days: int) -> str:
- return (datetime.now(timezone.utc) + timedelta(days=days)).replace(microsecond=0).isoformat().replace("+00:00", "Z")
-
-
-def main(argv: list[str]) -> int:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("site")
- parser.add_argument("--summary", required=True)
- parser.add_argument("--likely-cause", action="append", default=[])
- parser.add_argument("--target-url")
- parser.add_argument("--follow-up-days", type=int, default=7)
- parser.add_argument("--primary-metric", default="organic_clicks_7d")
- parser.add_argument("--success-threshold-pct", type=float, default=0.1)
- parser.add_argument("--baseline-metric", action="append", default=[])
- parser.add_argument("--guardrail-metric", action="append", default=[], help="metric:direction:max_worsen_pct")
- args = parser.parse_args(argv[1:])
-
- site_id = normalize_site_id(args.site)
- generated_at = now_iso()
- follow_up_due = future_iso(args.follow_up_days)
- causes = args.likely_cause or ["Investigate ranking, indexation, and CTR changes."]
-
- baseline_metrics = {}
- for raw in args.baseline_metric:
- if "=" not in raw:
- raise SystemExit(f"baseline metric must look like name=value, got: {raw}")
- name, value = raw.split("=", 1)
- baseline_metrics[name.strip()] = float(value)
-
- guardrail_metrics = []
- for raw in args.guardrail_metric:
- metric, direction, max_worsen = raw.split(":", 2)
- guardrail_metrics.append({"metric": metric, "direction": direction, "max_worsen_pct": float(max_worsen)})
-
- issues = []
- actions = []
- for index, cause in enumerate(causes, start=1):
- issues.append(
- {
- "title": cause,
- "severity": "warning" if index > 1 else "critical",
- "confidence": max(0.45, 0.8 - ((index - 1) * 0.1)),
- "evidence": [args.summary],
- "recommended_action_type": "drop_recovery",
- }
- )
- actions.append(
- {
- "action_id": f"drop_recovery_{index:02d}",
- "title": f"Investigate and mitigate: {cause}",
- "type": "drop_recovery",
- "priority_score": round(0.92 - ((index - 1) * 0.08), 2),
- "expected_impact": "Recover lost visibility or conversions from the reported drop.",
- "requires_approval": index == 1,
- "reversibility": "high",
- "owner": "operator",
- }
- )
-
- queue_items = [
- {
- "item_id": f"drop_followup_{site_id}_{generated_at.replace(':', '-')}",
- "type": "feedback_check",
- "status": "pending",
- "due_at": follow_up_due,
- "notes": "Reassess the traffic drop after mitigation work or more data.",
- "action_type": "drop_recovery",
- "primary_metric": args.primary_metric,
- "primary_direction": "higher_better",
- "success_threshold_pct": args.success_threshold_pct,
- "baseline_metrics": baseline_metrics,
- "guardrail_metrics": guardrail_metrics,
- }
- ]
-
- if args.target_url:
- queue_items.append(
- {
- "item_id": f"improve_page_{site_id}_{generated_at.replace(':', '-')}",
- "type": "improve_page",
- "status": "pending",
- "notes": f"Run a focused page improvement workflow for {args.target_url}.",
- "target": args.target_url,
- }
- )
-
- payload = {
- "generated_at": generated_at,
- "trigger": {
- "type": "traffic_drop_detected",
- "notes": args.summary,
- "target": args.target_url,
- },
- "state_snapshot": {
- "site_id": site_id,
- "generated_at": generated_at,
- "summary": args.summary,
- "open_issues": [
- {
- "title": issue["title"],
- "severity": issue["severity"],
- "confidence": issue["confidence"],
- }
- for issue in issues
- ],
- "recent_actions": [],
- },
- "audit": {
- "site_id": site_id,
- "generated_at": generated_at,
- "summary": args.summary,
- "issues": issues,
- },
- "action_plan": {
- "site_id": site_id,
- "generated_at": generated_at,
- "actions": actions,
- },
- "verification": {
- "site_id": site_id,
- "generated_at": generated_at,
- "checks": [
- {
- "name": "drop investigation persisted",
- "status": "pass",
- "notes": "Stored ranked recovery actions for the reported drop.",
- },
- {
- "name": "follow-up scheduled",
- "status": "pass",
- "notes": f"Feedback check scheduled for {follow_up_due}.",
- },
- ],
- "follow_up_due": follow_up_due,
- },
- "queue_items": queue_items,
- }
-
- result = persist_payload(args.site, payload, root=workspace_root())
- print(json.dumps(result, indent=2))
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main(sys.argv))
diff --git a/openclaw/bin/onboard_site.py b/openclaw/bin/onboard_site.py
deleted file mode 100755
index ea6270f6..00000000
--- a/openclaw/bin/onboard_site.py
+++ /dev/null
@@ -1,132 +0,0 @@
-#!/usr/bin/env python3
-"""Register or update a site in the NotFair OpenClaw portfolio."""
-
-from __future__ import annotations
-
-import argparse
-import sys
-from pathlib import Path
-
-CURRENT_DIR = Path(__file__).resolve().parent
-if str(CURRENT_DIR) not in sys.path:
- sys.path.insert(0, str(CURRENT_DIR))
-
-from bootstrap_site import bootstrap_site
-from runtime import load_json, now_iso, save_json, upsert_portfolio_site, workspace_root
-from site_id import normalize_site_id
-
-
-def parse_brand_terms(raw: str | None) -> list[str]:
- if not raw:
- return []
- return [item.strip() for item in raw.split(",") if item.strip()]
-
-
-def next_goal_id(active: list[dict], site_id: str) -> str:
- return f"goal_{site_id.replace('.', '_')}_{len(active) + 1:03d}"
-
-
-def main(argv: list[str]) -> int:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("site")
- parser.add_argument("--display-name")
- parser.add_argument("--brand-terms", help="Comma-separated brand terms")
- parser.add_argument("--cms")
- parser.add_argument("--business-context")
- parser.add_argument("--business-weight", type=float, default=1.0)
- parser.add_argument("--cadence", default="weekly", choices=["daily", "weekly", "monthly", "on_demand"])
- parser.add_argument("--goal-type", default="grow_non_brand_clicks")
- parser.add_argument("--primary-metric", default="non_brand_clicks_28d")
- parser.add_argument("--target-delta", type=float)
- parser.add_argument("--skip-goal", action="store_true")
- args = parser.parse_args(argv[1:])
-
- root = workspace_root()
- site_id = normalize_site_id(args.site)
- site_path = bootstrap_site(args.site, root)
-
- profile_path = site_path / "site-profile.json"
- goals_path = site_path / "goals.json"
- latest_path = site_path / "latest-state.json"
-
- profile = load_json(profile_path, {})
- profile.update(
- {
- "schema_version": "1",
- "site_id": site_id,
- "canonical_url": args.site if "://" in args.site else f"https://{site_id}",
- "display_name": args.display_name or profile.get("display_name") or site_id,
- "brand_terms": parse_brand_terms(args.brand_terms) or profile.get("brand_terms") or [],
- "cms": args.cms if args.cms is not None else profile.get("cms"),
- "business_context": args.business_context if args.business_context is not None else profile.get("business_context"),
- "status": profile.get("status", "active"),
- }
- )
- save_json(profile_path, profile)
-
- portfolio_site = upsert_portfolio_site(
- site_id,
- display_name=profile["display_name"],
- business_weight=args.business_weight,
- cadence=args.cadence,
- status=profile["status"],
- root=root,
- )
-
- goals = load_json(goals_path, {"active": [], "archived": []})
- created_goal = None
- if not args.skip_goal:
- active = goals.setdefault("active", [])
- existing = next(
- (
- goal
- for goal in active
- if goal.get("type") == args.goal_type and goal.get("primary_metric") == args.primary_metric and goal.get("status") == "active"
- ),
- None,
- )
- if existing is None:
- created_goal = {
- "goal_id": next_goal_id(active, site_id),
- "site_id": site_id,
- "type": args.goal_type,
- "primary_metric": args.primary_metric,
- "target_delta": args.target_delta,
- "status": "active",
- "created_at": now_iso(),
- }
- active.append(created_goal)
- save_json(goals_path, goals)
- else:
- created_goal = existing
-
- latest = load_json(latest_path, {"site_id": site_id})
- latest.update(
- {
- "site_id": site_id,
- "generated_at": now_iso(),
- "summary": f"Onboarded {profile['display_name']} into the OpenClaw portfolio.",
- "open_issues": latest.get("open_issues", []),
- "recent_actions": [
- {
- "type": "site_onboard",
- "at": now_iso(),
- "notes": f"Initialized work folder for {site_id}.",
- }
- ],
- }
- )
- save_json(latest_path, latest)
-
- result = {
- "site_id": site_id,
- "site_path": str(site_path),
- "portfolio_site": portfolio_site,
- "goal": created_goal,
- }
- print(__import__("json").dumps(result, indent=2))
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main(sys.argv))
diff --git a/openclaw/bin/persist_run.py b/openclaw/bin/persist_run.py
deleted file mode 100755
index 00470628..00000000
--- a/openclaw/bin/persist_run.py
+++ /dev/null
@@ -1,237 +0,0 @@
-#!/usr/bin/env python3
-"""Persist OpenClaw run artifacts for a site review or follow-up."""
-
-from __future__ import annotations
-
-import argparse
-import json
-import sys
-from pathlib import Path
-
-CURRENT_DIR = Path(__file__).resolve().parent
-if str(CURRENT_DIR) not in sys.path:
- sys.path.insert(0, str(CURRENT_DIR))
-
-from bootstrap_site import bootstrap_site
-from runtime import ensure_site_dirs, load_json, now_iso, save_json, timestamp_slug, upsert_schedule_items, workspace_root
-from site_id import normalize_site_id
-
-ARTIFACT_KEYS = {
- "trigger": "trigger.json",
- "state_snapshot": "state-snapshot.json",
- "audit": "audit.json",
- "action_plan": "action-plan.json",
- "proposal": "proposal.json",
- "patch_set": "patch-set.json",
- "verification": "verification.json",
- "feedback": "feedback.json",
- "learning_log": "learning-log.json",
-}
-
-
-REQUIRED_KEYS = ["audit", "action_plan", "verification"]
-
-
-def metric_direction(metric_name: str | None) -> str:
- if not metric_name:
- return "higher_better"
- return "lower_better" if "position" in metric_name.lower() else "higher_better"
-
-
-def extract_metric_snapshot(payload: dict) -> dict:
- for source_key in ["state_snapshot", "audit", "proposal", "feedback"]:
- source = payload.get(source_key)
- if isinstance(source, dict) and isinstance(source.get("metrics"), dict):
- return dict(source["metrics"])
- return {}
-
-
-def enrich_queue_items(payload: dict) -> None:
- queue_items = payload.get("queue_items")
- if not isinstance(queue_items, list):
- return
- metric_snapshot = extract_metric_snapshot(payload)
- first_action = None
- actions = payload.get("action_plan", {}).get("actions", []) if isinstance(payload.get("action_plan"), dict) else []
- if actions:
- first_action = actions[0]
- proposal = payload.get("proposal") if isinstance(payload.get("proposal"), dict) else {}
- trigger = payload.get("trigger") if isinstance(payload.get("trigger"), dict) else {}
-
- for item in queue_items:
- if not isinstance(item, dict):
- continue
- if item.get("type") != "feedback_check":
- continue
- if first_action and not item.get("action_type"):
- item["action_type"] = first_action.get("type")
- if proposal.get("target") and not item.get("target"):
- item["target"] = proposal.get("target")
- elif trigger.get("target") and not item.get("target"):
- item["target"] = trigger.get("target")
- if metric_snapshot and not item.get("baseline_metrics"):
- item["baseline_metrics"] = dict(metric_snapshot)
- if not item.get("primary_metric") and metric_snapshot:
- preferred = [
- key
- for key in [
- "non_brand_clicks_28d",
- "organic_clicks_28d",
- "organic_clicks_7d",
- "organic_impressions_28d",
- "organic_ctr_28d",
- "avg_position_28d",
- ]
- if key in metric_snapshot
- ]
- item["primary_metric"] = preferred[0] if preferred else next(iter(metric_snapshot.keys()), None)
- if item.get("primary_metric") and not item.get("primary_direction"):
- item["primary_direction"] = metric_direction(item.get("primary_metric"))
- if "success_threshold_pct" not in item:
- item["success_threshold_pct"] = 0.1
- if "guardrail_metrics" not in item:
- item["guardrail_metrics"] = []
-
-
-def with_defaults(payload: dict, site_id: str) -> dict:
- generated_at = payload.get("generated_at") or now_iso()
- payload["generated_at"] = generated_at
- for key in REQUIRED_KEYS:
- if key not in payload:
- raise ValueError(f"payload missing required key: {key}")
- enrich_queue_items(payload)
- for key in ["state_snapshot", "audit", "action_plan", "proposal", "patch_set", "verification", "feedback", "learning_log"]:
- if key in payload and isinstance(payload[key], dict):
- payload[key].setdefault("site_id", site_id)
- payload[key].setdefault("generated_at", generated_at)
- if "trigger" not in payload:
- payload["trigger"] = {"site_id": site_id, "generated_at": generated_at, "type": "manual_request"}
- else:
- payload["trigger"].setdefault("site_id", site_id)
- payload["trigger"].setdefault("generated_at", generated_at)
- return payload
-
-
-def persist_queue_items(site_path: Path, queue_items: list[dict], site_id: str) -> tuple[list[str], list[dict]]:
- queue_dir = site_path / "queue"
- queue_dir.mkdir(parents=True, exist_ok=True)
- written = []
- normalized = []
- for index, item in enumerate(queue_items, start=1):
- item_id = item.get("item_id") or f"queue_{timestamp_slug()}_{index:02d}"
- item.setdefault("site_id", site_id)
- item.setdefault("status", "pending")
- item.setdefault("created_at", now_iso())
- item["item_id"] = item_id
- path = queue_dir / f"{item_id}.json"
- save_json(path, item)
- written.append(str(path))
- normalized.append(item)
- return written, normalized
-
-
-def derive_latest_state(payload: dict, site_id: str) -> dict:
- if isinstance(payload.get("state_snapshot"), dict):
- latest = dict(payload["state_snapshot"])
- latest.setdefault("site_id", site_id)
- latest.setdefault("generated_at", payload["generated_at"])
- return latest
-
- audit = payload["audit"]
- actions = payload["action_plan"].get("actions", [])
- summary = audit.get("summary") or "Weekly review complete."
- open_issues = []
- for issue in audit.get("issues", [])[:5]:
- open_issues.append(
- {
- "title": issue.get("title"),
- "severity": issue.get("severity", "warning"),
- "confidence": issue.get("confidence"),
- }
- )
- recent_actions = []
- for action in actions[:3]:
- recent_actions.append(
- {
- "type": action.get("type"),
- "title": action.get("title"),
- "requires_approval": action.get("requires_approval", True),
- }
- )
- return {
- "site_id": site_id,
- "generated_at": payload["generated_at"],
- "summary": summary,
- "open_issues": open_issues,
- "recent_actions": recent_actions,
- }
-
-
-def next_run_dir(site_path: Path) -> Path:
- base = timestamp_slug()
- candidate = site_path / "runs" / base
- if not candidate.exists():
- return candidate
- counter = 2
- while True:
- candidate = site_path / "runs" / f"{base}-{counter:02d}"
- if not candidate.exists():
- return candidate
- counter += 1
-
-
-def persist_payload(site_input: str, payload: dict, *, root: Path | None = None) -> dict:
- root = root or workspace_root()
- site_id = normalize_site_id(site_input)
- site_path = ensure_site_dirs(site_id, root)
- if not (site_path / "site-profile.json").exists():
- bootstrap_site(site_input, root)
-
- payload = with_defaults(payload, site_id)
-
- run_dir = next_run_dir(site_path)
- run_dir.mkdir(parents=True, exist_ok=False)
-
- written = []
- for key, filename in ARTIFACT_KEYS.items():
- data = payload.get(key)
- if data is None:
- continue
- path = run_dir / filename
- save_json(path, data)
- written.append(str(path))
-
- latest_state = derive_latest_state(payload, site_id)
- save_json(site_path / "latest-state.json", latest_state)
-
- queue_paths = []
- schedule_items_written = []
- if isinstance(payload.get("queue_items"), list):
- queue_paths, normalized_queue = persist_queue_items(site_path, payload["queue_items"], site_id)
- schedule_candidates = [item for item in normalized_queue if item.get("due_at")]
- if schedule_candidates:
- schedule_items_written = upsert_schedule_items(schedule_candidates, root)
-
- return {
- "site_id": site_id,
- "run_dir": str(run_dir),
- "artifacts_written": written,
- "queue_items_written": queue_paths,
- "schedule_items_written": schedule_items_written,
- }
-
-
-def main(argv: list[str]) -> int:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("site")
- parser.add_argument("--payload-file", required=True)
- args = parser.parse_args(argv[1:])
-
- payload = json.loads(Path(args.payload_file).read_text())
- result = persist_payload(args.site, payload)
- print(json.dumps(result, indent=2))
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main(sys.argv))
diff --git a/openclaw/bin/portfolio_review.py b/openclaw/bin/portfolio_review.py
deleted file mode 100755
index 9591aba6..00000000
--- a/openclaw/bin/portfolio_review.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/env python3
-"""Rank active sites in the NotFair OpenClaw portfolio by urgency and upside."""
-
-from __future__ import annotations
-
-import json
-import sys
-from pathlib import Path
-
-CURRENT_DIR = Path(__file__).resolve().parent
-if str(CURRENT_DIR) not in sys.path:
- sys.path.insert(0, str(CURRENT_DIR))
-
-from runtime import bootstrap_workspace, load_json, now_iso, save_json, timestamp_slug, workspace_root
-
-SEVERITY_WEIGHTS = {
- "critical": 3.0,
- "warning": 1.5,
- "info": 0.5,
-}
-
-
-def site_priority(record: dict, latest_state: dict, goals: dict) -> tuple[float, dict]:
- open_issues = latest_state.get("open_issues", [])
- urgency = sum(SEVERITY_WEIGHTS.get(issue.get("severity", "warning"), 1.0) for issue in open_issues) or 0.5
- active_goals = len(goals.get("active", [])) or 1
- business_weight = float(record.get("business_weight", 1.0))
- opportunity = 1.0 + (0.25 * min(active_goals, 4))
- score = round(business_weight * urgency * opportunity, 3)
- summary = latest_state.get("summary") or "No recent state summary."
- return score, {
- "site_id": record["site_id"],
- "display_name": record.get("display_name") or record["site_id"],
- "score": score,
- "business_weight": business_weight,
- "open_issue_count": len(open_issues),
- "active_goal_count": len(goals.get("active", [])),
- "summary": summary,
- "top_issue": open_issues[0]["title"] if open_issues else None,
- }
-
-
-def main(argv: list[str]) -> int:
- root = bootstrap_workspace(workspace_root())
- portfolio = load_json(root / "portfolio.json", {"sites": []})
- active_sites = [site for site in portfolio.get("sites", []) if site.get("status", "active") == "active"]
-
- rankings = []
- for record in active_sites:
- site_root = root / "sites" / record["site_id"]
- latest_state = load_json(site_root / "latest-state.json", {"summary": "No state yet.", "open_issues": []})
- goals = load_json(site_root / "goals.json", {"active": [], "archived": []})
- score, site_summary = site_priority(record, latest_state, goals)
- rankings.append(site_summary)
-
- rankings.sort(key=lambda item: item["score"], reverse=True)
- result = {
- "generated_at": now_iso(),
- "site_count": len(rankings),
- "rankings": rankings,
- "recommended_focus_site": rankings[0]["site_id"] if rankings else None,
- }
-
- output_dir = root / "portfolio-reviews"
- output_dir.mkdir(parents=True, exist_ok=True)
- save_json(output_dir / f"{timestamp_slug()}.json", result)
- print(json.dumps(result, indent=2))
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main(sys.argv))
diff --git a/openclaw/bin/publish_pending.py b/openclaw/bin/publish_pending.py
deleted file mode 100755
index b1c838f8..00000000
--- a/openclaw/bin/publish_pending.py
+++ /dev/null
@@ -1,299 +0,0 @@
-#!/usr/bin/env python3
-"""publish_pending.py — publish ready blog posts from a NotFair content calendar.
-
-Reads content-calendar.json, finds entries marked status: "ready_to_publish"
-that have a `bodyPath` pointing at a written file, POSTs each to the configured
-NotFair Next.js webhook, and updates the entry to status: "published" or
-"failed" based on the response.
-
-Designed to run as an OpenClaw cron job. Safe by default:
-
-- Dry-run unless --commit is passed (or OPENCLAW_PUBLISH_COMMIT=1)
-- Stops cleanly when the calendar is missing or has nothing ready
-- 2xx → entry becomes status: "published", publishedAt + response stored
-- 4xx → entry becomes status: "failed", lastError stored (non-retryable)
-- 5xx → entry stays "ready_to_publish", lastError stored, exit non-zero
-- Network err → entry stays "ready_to_publish", lastError stored, exit non-zero
-
-Environment:
- NOTFAIR_PUBLISH_URL webhook URL (default: https://notfair.co/api/blog/publish)
- NOTFAIR_PUBLISH_TOKEN Bearer token; required in --commit mode
- OPENCLAW_PUBLISH_COMMIT "1" → write mode without passing --commit
- OPENCLAW_PUBLISH_CALENDAR explicit calendar path
-
-Webhook contract: see openclaw/install/notfair-publisher.md.
-"""
-from __future__ import annotations
-
-import argparse
-import json
-import os
-import sys
-import urllib.error
-import urllib.request
-from datetime import datetime, timezone
-from pathlib import Path
-from typing import Any
-
-DEFAULT_WEBHOOK = "https://notfair.co/api/blog/publish"
-DEFAULT_TIMEOUT_SECS = 30
-READY_STATUS = "ready_to_publish"
-PUBLISHED_STATUS = "published"
-FAILED_STATUS = "failed"
-
-
-def now_iso() -> str:
- return (
- datetime.now(timezone.utc)
- .replace(microsecond=0)
- .isoformat()
- .replace("+00:00", "Z")
- )
-
-
-def resolve_calendar_path(explicit: str | None) -> Path:
- if explicit:
- return Path(explicit).expanduser().resolve()
- env = os.environ.get("OPENCLAW_PUBLISH_CALENDAR")
- if env:
- return Path(env).expanduser().resolve()
- project = Path.cwd() / ".notfair" / "content-calendar.json"
- if project.is_file():
- return project
- return Path.home() / ".notfair" / "content-calendar.json"
-
-
-def load_calendar(path: Path) -> dict | None:
- if not path.is_file():
- return None
- return json.loads(path.read_text(encoding="utf-8"))
-
-
-def save_calendar(path: Path, calendar: dict) -> None:
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(
- json.dumps(calendar, indent=2, ensure_ascii=False) + "\n",
- encoding="utf-8",
- )
-
-
-def read_body(body_path: str, calendar_dir: Path) -> str:
- p = Path(body_path).expanduser()
- if not p.is_absolute():
- p = (calendar_dir / p).resolve()
- return p.read_text(encoding="utf-8")
-
-
-def build_payload(entry: dict, body: str) -> dict[str, Any]:
- """Map a calendar entry to the webhook payload.
-
- The Next.js endpoint contract is documented in
- openclaw/install/notfair-publisher.md — keep them in sync.
- """
- return {
- "schemaVersion": "1",
- "slug": entry.get("id"),
- "title": entry.get("title"),
- "primaryKeyword": entry.get("primaryKeyword"),
- "secondaryKeywords": entry.get("secondaryKeywords") or [],
- "intent": entry.get("intent"),
- "type": entry.get("type", "blog"),
- "metaDescription": entry.get("metaDescription"),
- "body": body,
- "bodyFormat": entry.get("bodyFormat", "markdown"),
- "featuredImage": entry.get("featuredImage"),
- "inlineImages": entry.get("inlineImages") or [],
- "structuredData": entry.get("structuredData"),
- "scheduledAt": entry.get("scheduledDate"),
- "source": {"tool": "notfair", "skill": "content-planner", "version": "1"},
- }
-
-
-def post_to_webhook(
- url: str, token: str, payload: dict, timeout: int = DEFAULT_TIMEOUT_SECS
-) -> tuple[int, dict | str]:
- """POST payload to the webhook. Returns (status_code, parsed_body_or_text)."""
- data = json.dumps(payload).encode("utf-8")
- req = urllib.request.Request(
- url,
- data=data,
- method="POST",
- headers={
- "Content-Type": "application/json",
- "Accept": "application/json",
- "Authorization": f"Bearer {token}",
- "User-Agent": "notfair-publisher/1",
- },
- )
- try:
- with urllib.request.urlopen(req, timeout=timeout) as resp:
- raw = resp.read().decode("utf-8", errors="replace")
- return resp.status, _try_parse(raw)
- except urllib.error.HTTPError as exc:
- raw = exc.read().decode("utf-8", errors="replace") if hasattr(exc, "read") else str(exc)
- return exc.code, _try_parse(raw)
-
-
-def _try_parse(raw: str) -> dict | str:
- try:
- return json.loads(raw)
- except (json.JSONDecodeError, ValueError):
- return raw
-
-
-def ready_entries(calendar: dict, site_filter: str | None) -> list[dict]:
- out = []
- for entry in calendar.get("topics") or []:
- if entry.get("status") != READY_STATUS:
- continue
- if not entry.get("bodyPath"):
- continue
- if site_filter and entry.get("site") != site_filter:
- continue
- out.append(entry)
- return out
-
-
-def publish_one(
- entry: dict,
- *,
- webhook: str,
- token: str,
- calendar_dir: Path,
- dry_run: bool,
-) -> dict:
- body_path = entry["bodyPath"]
- try:
- body = read_body(body_path, calendar_dir)
- except OSError as exc:
- entry["status"] = FAILED_STATUS
- entry["lastError"] = f"could not read bodyPath '{body_path}': {exc}"
- entry["lastAttemptAt"] = now_iso()
- return {"id": entry.get("id"), "outcome": "skipped", "reason": "body unreadable"}
-
- payload = build_payload(entry, body)
-
- if dry_run:
- return {
- "id": entry.get("id"),
- "outcome": "dry-run",
- "would_post_to": webhook,
- "payload_bytes": len(json.dumps(payload)),
- }
-
- try:
- status, body_resp = post_to_webhook(webhook, token, payload)
- except (urllib.error.URLError, TimeoutError, OSError) as exc:
- entry["lastError"] = f"network: {exc}"
- entry["lastAttemptAt"] = now_iso()
- return {"id": entry.get("id"), "outcome": "network-error", "error": str(exc)}
-
- entry["lastAttemptAt"] = now_iso()
-
- if 200 <= status < 300:
- entry["status"] = PUBLISHED_STATUS
- entry["publishedAt"] = now_iso()
- if isinstance(body_resp, dict):
- url = body_resp.get("url") or body_resp.get("publishedUrl")
- if url:
- entry["publishedUrl"] = url
- entry["response"] = body_resp
- entry.pop("lastError", None)
- return {"id": entry.get("id"), "outcome": "published", "status": status}
-
- if 400 <= status < 500:
- entry["status"] = FAILED_STATUS
- entry["lastError"] = f"HTTP {status}: {body_resp}"
- return {"id": entry.get("id"), "outcome": "failed", "status": status}
-
- entry["lastError"] = f"HTTP {status}: {body_resp}"
- return {"id": entry.get("id"), "outcome": "retry", "status": status}
-
-
-def run(
- *,
- calendar_path: Path,
- webhook: str,
- token: str | None,
- dry_run: bool,
- site_filter: str | None,
-) -> dict:
- calendar = load_calendar(calendar_path)
- if calendar is None:
- return {"ok": True, "processed": [], "note": f"no calendar at {calendar_path}"}
-
- candidates = ready_entries(calendar, site_filter)
- if not candidates:
- return {"ok": True, "processed": [], "note": "no entries ready_to_publish"}
-
- if not token and not dry_run:
- return {
- "ok": False,
- "processed": [],
- "error": "NOTFAIR_PUBLISH_TOKEN is unset; refusing to publish. Set the env var or pass --dry-run.",
- }
-
- processed = []
- any_retry_or_network = False
-
- for entry in candidates:
- result = publish_one(
- entry,
- webhook=webhook,
- token=token or "",
- calendar_dir=calendar_path.parent,
- dry_run=dry_run,
- )
- processed.append(result)
- if result["outcome"] in ("retry", "network-error"):
- any_retry_or_network = True
-
- if not dry_run:
- save_calendar(calendar_path, calendar)
-
- return {
- "ok": not any_retry_or_network,
- "processed": processed,
- "calendar": str(calendar_path),
- "dryRun": dry_run,
- }
-
-
-def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
- p = argparse.ArgumentParser(prog="publish_pending")
- p.add_argument("--calendar", default=None,
- help="Path to content-calendar.json (default: ./.notfair/... → ~/.notfair/...)")
- p.add_argument("--site", default=None,
- help="Only publish entries matching this site id")
- p.add_argument("--webhook", default=None,
- help=f"Webhook URL (default: $NOTFAIR_PUBLISH_URL or {DEFAULT_WEBHOOK})")
- p.add_argument("--commit", action="store_true",
- help="Actually POST. Default is dry-run.")
- p.add_argument("--dry-run", action="store_true",
- help="Force dry-run even if OPENCLAW_PUBLISH_COMMIT=1.")
- return p.parse_args(argv)
-
-
-def main(argv: list[str] | None = None) -> int:
- args = parse_args(argv)
-
- commit_env = os.environ.get("OPENCLAW_PUBLISH_COMMIT") == "1"
- dry_run = args.dry_run or not (args.commit or commit_env)
-
- calendar_path = resolve_calendar_path(args.calendar)
- webhook = args.webhook or os.environ.get("NOTFAIR_PUBLISH_URL") or DEFAULT_WEBHOOK
- token = os.environ.get("NOTFAIR_PUBLISH_TOKEN")
-
- result = run(
- calendar_path=calendar_path,
- webhook=webhook,
- token=token,
- dry_run=dry_run,
- site_filter=args.site,
- )
- print(json.dumps(result, indent=2, ensure_ascii=False))
- return 0 if result.get("ok") else 1
-
-
-if __name__ == "__main__":
- sys.exit(main())
diff --git a/openclaw/bin/record_followup_metrics.py b/openclaw/bin/record_followup_metrics.py
deleted file mode 100755
index 5f438541..00000000
--- a/openclaw/bin/record_followup_metrics.py
+++ /dev/null
@@ -1,85 +0,0 @@
-#!/usr/bin/env python3
-"""Attach observed metric values to a queued follow-up item and matching schedule entry."""
-
-from __future__ import annotations
-
-import argparse
-import json
-import sys
-from pathlib import Path
-
-CURRENT_DIR = Path(__file__).resolve().parent
-if str(CURRENT_DIR) not in sys.path:
- sys.path.insert(0, str(CURRENT_DIR))
-
-from runtime import bootstrap_workspace, load_json, save_json, workspace_root
-
-
-def parse_metric_pairs(values: list[str]) -> dict[str, float]:
- metrics: dict[str, float] = {}
- for raw in values:
- if "=" not in raw:
- raise ValueError(f"metric must look like name=value, got: {raw}")
- name, value = raw.split("=", 1)
- metrics[name.strip()] = float(value)
- return metrics
-
-
-def update_item(payload: dict, args: argparse.Namespace) -> dict:
- if args.primary_metric:
- payload["primary_metric"] = args.primary_metric
- if args.primary_direction:
- payload["primary_direction"] = args.primary_direction
- if args.success_threshold_pct is not None:
- payload["success_threshold_pct"] = args.success_threshold_pct
- if args.baseline_metric:
- payload["baseline_metrics"] = {**payload.get("baseline_metrics", {}), **parse_metric_pairs(args.baseline_metric)}
- if args.observed_metric:
- payload["observed_metrics"] = {**payload.get("observed_metrics", {}), **parse_metric_pairs(args.observed_metric)}
- if args.guardrail_metric:
- guardrails = payload.get("guardrail_metrics", [])
- for raw in args.guardrail_metric:
- metric, direction, max_worsen = raw.split(":", 2)
- guardrails.append({"metric": metric, "direction": direction, "max_worsen_pct": float(max_worsen)})
- payload["guardrail_metrics"] = guardrails
- if args.notes:
- payload["notes"] = args.notes
- return payload
-
-
-def main(argv: list[str]) -> int:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("site_id")
- parser.add_argument("item_id")
- parser.add_argument("--primary-metric")
- parser.add_argument("--primary-direction", choices=["higher_better", "lower_better"])
- parser.add_argument("--success-threshold-pct", type=float)
- parser.add_argument("--baseline-metric", action="append", default=[])
- parser.add_argument("--observed-metric", action="append", default=[])
- parser.add_argument("--guardrail-metric", action="append", default=[], help="metric:direction:max_worsen_pct")
- parser.add_argument("--notes")
- args = parser.parse_args(argv[1:])
-
- root = bootstrap_workspace(workspace_root())
- queue_path = root / "sites" / args.site_id / "queue" / f"{args.item_id}.json"
- if not queue_path.exists():
- raise SystemExit(f"queue item not found: {queue_path}")
-
- queue_payload = load_json(queue_path, {})
- queue_payload = update_item(queue_payload, args)
- save_json(queue_path, queue_payload)
-
- schedule_path = root / "schedule.json"
- schedule = load_json(schedule_path, {"schema_version": "1", "upcoming": []})
- for item in schedule.get("upcoming", []):
- if item.get("item_id") == args.item_id and item.get("site_id") == args.site_id:
- item.update(queue_payload)
- break
- save_json(schedule_path, schedule)
-
- print(json.dumps({"queue_path": str(queue_path), "updated_item": queue_payload}, indent=2))
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main(sys.argv))
diff --git a/openclaw/bin/run_scheduler.py b/openclaw/bin/run_scheduler.py
deleted file mode 100755
index 1770bdaf..00000000
--- a/openclaw/bin/run_scheduler.py
+++ /dev/null
@@ -1,252 +0,0 @@
-#!/usr/bin/env python3
-"""Process due items from the NotFair OpenClaw schedule."""
-
-from __future__ import annotations
-
-import argparse
-import json
-import sys
-from datetime import datetime, timezone
-from pathlib import Path
-
-CURRENT_DIR = Path(__file__).resolve().parent
-if str(CURRENT_DIR) not in sys.path:
- sys.path.insert(0, str(CURRENT_DIR))
-
-from persist_run import persist_payload
-from runtime import bootstrap_workspace, load_json, now_iso, reconcile_schedule_from_queue, save_json, update_learned_patterns, workspace_root
-from score_feedback import score_item
-
-
-def parse_iso(value: str | None) -> datetime:
- if not value:
- return datetime.max.replace(tzinfo=timezone.utc)
- parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
- if parsed.tzinfo is None:
- return parsed.replace(tzinfo=timezone.utc)
- return parsed
-
-
-def update_queue_file(root: Path, item: dict, **updates) -> str | None:
- item_id = item.get("item_id")
- site_id = item.get("site_id")
- if not item_id or not site_id:
- return None
- queue_path = root / "sites" / site_id / "queue" / f"{item_id}.json"
- if not queue_path.exists():
- return None
- payload = load_json(queue_path, {})
- payload.update(updates)
- save_json(queue_path, payload)
- return str(queue_path)
-
-
-def build_feedback_payload(item: dict, root: Path, score: dict | None = None) -> dict:
- site_id = item["site_id"]
- latest = load_json(root / "sites" / site_id / "latest-state.json", {"summary": "No recent state summary.", "open_issues": []})
- summary = item.get("notes") or latest.get("summary") or "Scheduled follow-up review."
- action_id = item.get("item_id", "feedback_check")
- score = score or score_item(item)
- outcome = score.get("outcome", "inconclusive")
- reason = score.get("reason", "no scoring reason available")
- score_summary = f"Feedback outcome: {outcome}. Reason: {reason}."
- if score.get("primary_metric"):
- score_summary += f" Primary metric `{score['primary_metric']}` changed {score.get('primary_change', 0):+.1%}."
- return {
- "trigger": {
- "type": "scheduled_followup",
- "notes": summary,
- "source_item_id": action_id,
- },
- "state_snapshot": {
- "site_id": site_id,
- "summary": f"Follow-up checkpoint due for {site_id}. {score_summary}",
- "open_issues": latest.get("open_issues", []),
- "recent_actions": latest.get("recent_actions", []),
- },
- "audit": {
- "site_id": site_id,
- "summary": f"Scheduled feedback review for {site_id}. {score_summary}",
- "issues": [
- {
- "title": "A scheduled follow-up reached its review window.",
- "severity": "info" if outcome in {"win", "neutral", "inconclusive"} else "warning",
- "confidence": score.get("confidence", 0.6),
- "evidence": [summary, score_summary],
- "recommended_action_type": "feedback_review",
- }
- ],
- },
- "action_plan": {
- "site_id": site_id,
- "actions": [
- {
- "action_id": f"feedback_review_{action_id}",
- "title": "Review post-change performance and decide whether to continue, revise, or stop the intervention.",
- "type": "feedback_review",
- "priority_score": 0.7,
- "expected_impact": "Turns a pending follow-up into a concrete review task.",
- "requires_approval": False,
- "reversibility": "high",
- "owner": "operator",
- }
- ],
- },
- "feedback": {
- "site_id": site_id,
- "action_id": action_id,
- "window_days": 14,
- "outcome": outcome,
- "summary": score_summary,
- "score": score,
- },
- "learning_log": {
- "site_id": site_id,
- "observations": [
- {
- "pattern": f"followup_{outcome}",
- "confidence": score.get("confidence", 0.55),
- "notes": score_summary,
- }
- ],
- },
- "verification": {
- "site_id": site_id,
- "checks": [
- {
- "name": "follow-up materialized",
- "status": "pass",
- "notes": "A scheduled follow-up run artifact was created.",
- },
- {
- "name": "outcome available",
- "status": "pass" if outcome != "inconclusive" else "warning",
- "notes": score_summary if outcome != "inconclusive" else "Metric data is still incomplete, so the follow-up remains inconclusive.",
- },
- ],
- "follow_up_due": None,
- },
- }
-
-
-def mark_for_attention(root: Path, item: dict, reason: str) -> dict:
- item["status"] = "ready_for_attention"
- item["surfaced_at"] = now_iso()
- item["attention_reason"] = reason
- update_queue_file(
- root,
- item,
- status="ready_for_attention",
- surfaced_at=item["surfaced_at"],
- attention_reason=reason,
- )
- return {
- "item_id": item.get("item_id"),
- "site_id": item.get("site_id"),
- "type": item.get("type"),
- "reason": reason,
- }
-
-
-def main(argv: list[str]) -> int:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--site")
- parser.add_argument("--as-of", default=now_iso())
- parser.add_argument("--dry-run", action="store_true")
- args = parser.parse_args(argv[1:])
-
- root = bootstrap_workspace(workspace_root())
- schedule_path = root / "schedule.json"
- schedule = load_json(schedule_path, {"schema_version": "1", "upcoming": []})
- schedule, restored_from_queue = reconcile_schedule_from_queue(root, schedule)
- upcoming = schedule.setdefault("upcoming", [])
- as_of_dt = parse_iso(args.as_of)
-
- processed = []
- manual_attention = []
-
- for item in upcoming:
- if item.get("status", "pending") not in {"pending", "ready_for_attention"}:
- continue
- if args.site and item.get("site_id") != args.site:
- continue
- if parse_iso(item.get("due_at")) > as_of_dt:
- continue
-
- if item.get("type") == "feedback_check":
- if args.dry_run:
- score = score_item(item)
- if score.get("outcome") == "inconclusive":
- manual_attention.append(
- {
- "item_id": item.get("item_id"),
- "site_id": item.get("site_id"),
- "type": item.get("type"),
- "reason": score.get("reason", "feedback scoring was inconclusive"),
- "dry_run": True,
- }
- )
- else:
- processed.append(
- {
- "item_id": item.get("item_id"),
- "site_id": item.get("site_id"),
- "outcome": score.get("outcome"),
- "dry_run": True,
- }
- )
- continue
- score = score_item(item)
- if score.get("outcome") == "inconclusive":
- manual_attention.append(mark_for_attention(root, item, score.get("reason", "feedback scoring was inconclusive")))
- continue
- payload = build_feedback_payload(item, root, score)
- result = persist_payload(item["site_id"], payload, root=root)
- feedback_outcome = payload.get("feedback", {}).get("outcome", "inconclusive")
- item["status"] = "processed"
- item["processed_at"] = now_iso()
- item["result_run_dir"] = result["run_dir"]
- update_queue_file(root, item, status="done", processed_at=item["processed_at"], result_run_dir=result["run_dir"])
-
- feedback_path = root / "sites" / item["site_id"] / "feedback" / f"{item['item_id']}.json"
- feedback_payload = {
- "site_id": item["site_id"],
- "item_id": item["item_id"],
- "processed_at": item["processed_at"],
- "result_run_dir": result["run_dir"],
- "status": feedback_outcome,
- "notes": payload.get("feedback", {}).get("summary") or item.get("notes"),
- "score": payload.get("feedback", {}).get("score"),
- }
- save_json(feedback_path, feedback_payload)
- update_learned_patterns(
- item["site_id"],
- action_type=item.get("action_type"),
- primary_metric=payload.get("feedback", {}).get("score", {}).get("primary_metric"),
- outcome=feedback_outcome,
- primary_change=payload.get("feedback", {}).get("score", {}).get("primary_change"),
- confidence=payload.get("feedback", {}).get("score", {}).get("confidence"),
- notes=payload.get("feedback", {}).get("summary") or item.get("notes"),
- root=root,
- )
- processed.append({"item_id": item.get("item_id"), "site_id": item.get("site_id"), "result_run_dir": result["run_dir"], "outcome": feedback_outcome})
- else:
- manual_attention.append(mark_for_attention(root, item, f"unsupported schedule item type: {item.get('type')}"))
-
- if not args.dry_run:
- save_json(schedule_path, schedule)
-
- result = {
- "generated_at": now_iso(),
- "as_of": args.as_of,
- "processed": processed,
- "manual_attention": manual_attention,
- "restored_from_queue": restored_from_queue,
- "dry_run": args.dry_run,
- }
- print(json.dumps(result, indent=2))
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main(sys.argv))
diff --git a/openclaw/bin/runtime.py b/openclaw/bin/runtime.py
deleted file mode 100755
index 68835340..00000000
--- a/openclaw/bin/runtime.py
+++ /dev/null
@@ -1,251 +0,0 @@
-#!/usr/bin/env python3
-"""Shared helpers for the NotFair OpenClaw runtime workspace."""
-
-from __future__ import annotations
-
-import json
-import os
-from datetime import datetime, timezone
-from pathlib import Path
-from typing import Any
-
-TERMINAL_QUEUE_STATUSES = {"done", "processed"}
-
-
-def workspace_root() -> Path:
- configured = os.environ.get("TOPRANK_OPENCLAW_HOME")
- return Path(configured or (Path.home() / ".toprank" / "openclaw")).expanduser()
-
-
-def now_iso() -> str:
- return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
-
-
-def timestamp_slug() -> str:
- return now_iso().replace(":", "-")
-
-
-def load_json(path: Path, default: Any) -> Any:
- if not path.exists():
- return default
- return json.loads(path.read_text())
-
-
-def save_json(path: Path, payload: Any) -> None:
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n")
-
-
-def bootstrap_workspace(root: Path | None = None) -> Path:
- root = (root or workspace_root()).expanduser()
- (root / "sites").mkdir(parents=True, exist_ok=True)
-
- portfolio = root / "portfolio.json"
- schedule = root / "schedule.json"
-
- if not portfolio.exists():
- save_json(portfolio, {"schema_version": "1", "portfolio_id": "default", "sites": []})
- if not schedule.exists():
- save_json(schedule, {"schema_version": "1", "upcoming": []})
- return root
-
-
-def site_root(site_id: str, root: Path | None = None) -> Path:
- root = bootstrap_workspace(root)
- return root / "sites" / site_id
-
-
-def ensure_site_dirs(site_id: str, root: Path | None = None) -> Path:
- site = site_root(site_id, root)
- for subdir in ["queue", "proposals", "runs", "feedback"]:
- (site / subdir).mkdir(parents=True, exist_ok=True)
- return site
-
-
-def update_learned_patterns(
- site_id: str,
- *,
- action_type: str | None,
- primary_metric: str | None,
- outcome: str,
- primary_change: float | None,
- confidence: float | None,
- notes: str | None = None,
- root: Path | None = None,
-) -> dict[str, Any]:
- site = ensure_site_dirs(site_id, root)
- path = site / "learned-patterns.json"
- payload = load_json(path, {"site_id": site_id, "observations": [], "priors": {}})
- payload.setdefault("site_id", site_id)
- payload.setdefault("observations", [])
- priors = payload.setdefault("priors", {})
-
- key = f"{action_type or 'unknown'}::{primary_metric or 'unknown'}"
- prior = priors.setdefault(
- key,
- {
- "action_type": action_type or "unknown",
- "primary_metric": primary_metric or "unknown",
- "sample_size": 0,
- "wins": 0,
- "neutral": 0,
- "losses": 0,
- "inconclusive": 0,
- "avg_primary_change": 0.0,
- "confidence": 0.0,
- "last_outcome": None,
- "last_updated_at": None,
- },
- )
-
- prior["sample_size"] += 1
- if outcome == "win":
- prior["wins"] += 1
- elif outcome == "loss":
- prior["losses"] += 1
- elif outcome == "neutral":
- prior["neutral"] += 1
- else:
- prior["inconclusive"] += 1
-
- if primary_change is not None:
- previous_count = prior["sample_size"] - 1
- previous_avg = float(prior.get("avg_primary_change", 0.0))
- prior["avg_primary_change"] = round(((previous_avg * previous_count) + float(primary_change)) / max(prior["sample_size"], 1), 4)
- if confidence is not None:
- previous_count = prior["sample_size"] - 1
- previous_conf = float(prior.get("confidence", 0.0))
- prior["confidence"] = round(((previous_conf * previous_count) + float(confidence)) / max(prior["sample_size"], 1), 4)
-
- prior["last_outcome"] = outcome
- prior["last_updated_at"] = now_iso()
-
- payload["observations"].append(
- {
- "generated_at": now_iso(),
- "action_type": action_type or "unknown",
- "primary_metric": primary_metric or "unknown",
- "outcome": outcome,
- "primary_change": primary_change,
- "confidence": confidence,
- "notes": notes,
- }
- )
- save_json(path, payload)
- return payload
-
-
-def upsert_schedule_items(items: list[dict[str, Any]], root: Path | None = None) -> list[dict[str, Any]]:
- root = bootstrap_workspace(root)
- schedule_path = root / "schedule.json"
- schedule = load_json(schedule_path, {"schema_version": "1", "upcoming": []})
- upcoming = schedule.setdefault("upcoming", [])
- written: list[dict[str, Any]] = []
-
- for item in items:
- item_id = item.get("item_id")
- if not item_id:
- continue
- site_id = item.get("site_id")
- existing = next(
- (
- entry
- for entry in upcoming
- if entry.get("item_id") == item_id and (site_id is None or entry.get("site_id") == site_id)
- ),
- None,
- )
- if existing is None:
- upcoming.append(item)
- written.append(item)
- else:
- existing.update(item)
- written.append(existing)
-
- save_json(schedule_path, schedule)
- return written
-
-
-def reconcile_schedule_from_queue(root: Path | None = None, schedule: dict[str, Any] | None = None) -> tuple[dict[str, Any], list[dict[str, Any]]]:
- """Restore scheduled work from per-site queue files.
-
- Queue files are the durable per-site task records. `schedule.json` is an
- index used by the runner, so a missing schedule entry should not make a
- pending queue item disappear from backend processing.
- """
- root = bootstrap_workspace(root)
- if schedule is None:
- schedule = load_json(root / "schedule.json", {"schema_version": "1", "upcoming": []})
- upcoming = schedule.setdefault("upcoming", [])
- restored: list[dict[str, Any]] = []
-
- existing_by_key = {
- (entry.get("site_id"), entry.get("item_id")): entry
- for entry in upcoming
- if entry.get("site_id") and entry.get("item_id")
- }
-
- sites_dir = root / "sites"
- if not sites_dir.exists():
- return schedule, restored
-
- for queue_path in sites_dir.glob("*/queue/*.json"):
- try:
- item = load_json(queue_path, {})
- except json.JSONDecodeError:
- continue
- if not isinstance(item, dict):
- continue
- if not item.get("due_at"):
- continue
- status = item.get("status", "pending")
- if status in TERMINAL_QUEUE_STATUSES:
- continue
-
- site_id = item.get("site_id") or queue_path.parents[1].name
- item_id = item.get("item_id") or queue_path.stem
- item["site_id"] = site_id
- item["item_id"] = item_id
- key = (site_id, item_id)
- existing = existing_by_key.get(key)
- if existing is None:
- upcoming.append(dict(item))
- existing_by_key[key] = upcoming[-1]
- restored.append(upcoming[-1])
- elif existing.get("status") not in TERMINAL_QUEUE_STATUSES:
- existing.update(item)
-
- return schedule, restored
-
-
-def upsert_portfolio_site(
- site_id: str,
- *,
- display_name: str | None = None,
- business_weight: float = 1.0,
- cadence: str = "weekly",
- status: str = "active",
- root: Path | None = None,
-) -> dict[str, Any]:
- root = bootstrap_workspace(root)
- portfolio_path = root / "portfolio.json"
- portfolio = load_json(portfolio_path, {"schema_version": "1", "portfolio_id": "default", "sites": []})
- sites = portfolio.setdefault("sites", [])
-
- existing = next((item for item in sites if item.get("site_id") == site_id), None)
- record = {
- "site_id": site_id,
- "display_name": display_name or site_id,
- "business_weight": business_weight,
- "cadence": cadence,
- "status": status,
- }
-
- if existing is None:
- sites.append(record)
- else:
- existing.update(record)
- record = existing
-
- save_json(portfolio_path, portfolio)
- return record
diff --git a/openclaw/bin/score_feedback.py b/openclaw/bin/score_feedback.py
deleted file mode 100755
index 259d8835..00000000
--- a/openclaw/bin/score_feedback.py
+++ /dev/null
@@ -1,119 +0,0 @@
-#!/usr/bin/env python3
-"""Score a follow-up outcome from before/after metrics."""
-
-from __future__ import annotations
-
-import argparse
-import json
-import sys
-from pathlib import Path
-from typing import Any
-
-DIRECTION_HIGHER = "higher_better"
-DIRECTION_LOWER = "lower_better"
-VALID_DIRECTIONS = {DIRECTION_HIGHER, DIRECTION_LOWER}
-
-
-def normalized_change(before: float, after: float, direction: str) -> float:
- if before == 0:
- if after == 0:
- return 0.0
- raw = 1.0
- else:
- raw = (after - before) / abs(before)
- if direction == DIRECTION_LOWER:
- return -raw
- return raw
-
-
-def score_item(item: dict[str, Any]) -> dict[str, Any]:
- baseline = item.get("baseline_metrics") or {}
- observed = item.get("observed_metrics") or {}
- primary_metric = item.get("primary_metric")
- primary_direction = item.get("primary_direction", DIRECTION_HIGHER)
- threshold = float(item.get("success_threshold_pct", 0.1))
- guardrails = item.get("guardrail_metrics") or []
-
- if primary_direction not in VALID_DIRECTIONS:
- raise ValueError(f"invalid primary_direction: {primary_direction}")
- if not primary_metric:
- return {"outcome": "inconclusive", "reason": "missing primary_metric"}
- if primary_metric not in baseline or primary_metric not in observed:
- return {"outcome": "inconclusive", "reason": f"missing metric data for {primary_metric}"}
-
- before = float(baseline[primary_metric])
- after = float(observed[primary_metric])
- primary_change = normalized_change(before, after, primary_direction)
-
- metric_deltas: dict[str, dict[str, float | str]] = {}
- for metric in set(baseline) & set(observed):
- direction = DIRECTION_HIGHER
- if metric == primary_metric:
- direction = primary_direction
- for guardrail in guardrails:
- if guardrail.get("metric") == metric:
- direction = guardrail.get("direction", direction)
- break
- metric_deltas[metric] = {
- "before": float(baseline[metric]),
- "after": float(observed[metric]),
- "normalized_change": round(normalized_change(float(baseline[metric]), float(observed[metric]), direction), 4),
- "direction": direction,
- }
-
- guardrail_failures = []
- for guardrail in guardrails:
- metric = guardrail.get("metric")
- if metric not in baseline or metric not in observed:
- continue
- direction = guardrail.get("direction", DIRECTION_HIGHER)
- max_worsen_pct = float(guardrail.get("max_worsen_pct", 0.05))
- delta = normalized_change(float(baseline[metric]), float(observed[metric]), direction)
- if delta < -max_worsen_pct:
- guardrail_failures.append(
- {
- "metric": metric,
- "normalized_change": round(delta, 4),
- "max_worsen_pct": max_worsen_pct,
- }
- )
-
- if guardrail_failures:
- outcome = "loss"
- reason = "guardrail failure"
- elif primary_change >= threshold:
- outcome = "win"
- reason = "primary metric improved"
- elif primary_change <= -threshold:
- outcome = "loss"
- reason = "primary metric worsened"
- else:
- outcome = "neutral"
- reason = "change stayed within the neutral band"
-
- confidence = min(0.95, round(0.55 + min(abs(primary_change), 1.0) * 0.35 + min(len(guardrails), 2) * 0.03, 2))
-
- return {
- "outcome": outcome,
- "reason": reason,
- "primary_metric": primary_metric,
- "primary_direction": primary_direction,
- "primary_change": round(primary_change, 4),
- "success_threshold_pct": threshold,
- "guardrail_failures": guardrail_failures,
- "metric_deltas": metric_deltas,
- "confidence": confidence,
- }
-
-
-def main(argv: list[str]) -> int:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--item-file", required=True)
- args = parser.parse_args(argv[1:])
- item = json.loads(Path(args.item_file).read_text())
- print(json.dumps(score_item(item), indent=2))
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main(sys.argv))
diff --git a/openclaw/bin/site_id.py b/openclaw/bin/site_id.py
deleted file mode 100755
index 86dd99a9..00000000
--- a/openclaw/bin/site_id.py
+++ /dev/null
@@ -1,36 +0,0 @@
-#!/usr/bin/env python3
-"""Normalize a URL or hostname into a stable site_id."""
-
-from __future__ import annotations
-
-import sys
-from urllib.parse import urlparse
-
-
-def normalize_site_id(value: str) -> str:
- raw = (value or '').strip().lower()
- if not raw:
- raise ValueError('site input is required')
- parsed = urlparse(raw if '://' in raw else f'https://{raw}')
- host = (parsed.hostname or parsed.path or '').strip().lower()
- if host.startswith('www.'):
- host = host[4:]
- if not host:
- raise ValueError(f'could not derive site id from: {value!r}')
- return host
-
-
-def main(argv: list[str]) -> int:
- if len(argv) != 2:
- print('usage: site_id.py <url-or-domain>', file=sys.stderr)
- return 1
- try:
- print(normalize_site_id(argv[1]))
- except ValueError as exc:
- print(str(exc), file=sys.stderr)
- return 1
- return 0
-
-
-if __name__ == '__main__':
- raise SystemExit(main(sys.argv))
diff --git a/openclaw/bin/weekly_review.py b/openclaw/bin/weekly_review.py
deleted file mode 100755
index 9b6b2eb9..00000000
--- a/openclaw/bin/weekly_review.py
+++ /dev/null
@@ -1,2468 +0,0 @@
-#!/usr/bin/env python3
-"""Run an automated weekly review for a site using GSC analysis output."""
-
-from __future__ import annotations
-
-import argparse
-import html
-from html.parser import HTMLParser
-import json
-import math
-import os
-import re
-import subprocess
-import sys
-import tempfile
-from urllib.error import HTTPError, URLError
-from urllib.parse import parse_qsl, quote_plus, unquote, urlencode, urlparse, urlunparse
-from urllib.request import Request, urlopen
-from datetime import datetime, timedelta, timezone
-from pathlib import Path
-from typing import Any
-
-CURRENT_DIR = Path(__file__).resolve().parent
-if str(CURRENT_DIR) not in sys.path:
- sys.path.insert(0, str(CURRENT_DIR))
-
-from persist_run import persist_payload
-from runtime import load_json, workspace_root
-from site_id import normalize_site_id
-
-ANALYZE_GSC = Path(__file__).resolve().parents[2] / "seo" / "seo-analysis" / "scripts" / "analyze_gsc.py"
-DEFAULT_PRIMARY_METRIC = "non_brand_clicks_28d"
-
-
-SEO_BEST_PRACTICE_REFERENCE = "seo/shared/seo-best-practices.md"
-SEO_BEST_PRACTICE_AREAS: dict[str, dict[str, Any]] = {
- "search_eligibility_indexability": {
- "label": "Search eligibility & indexability",
- "resources": [
- "Google Search Essentials",
- "Google Search Central SEO Starter Guide",
- ],
- "why": "Google must be able to discover, crawl, render, canonicalize, and index the right URL before content changes can work.",
- },
- "demand_intent_targeting": {
- "label": "Demand & intent targeting",
- "resources": [
- "Ahrefs Beginner’s Guide to SEO",
- "Moz Beginner’s Guide to SEO",
- "Google helpful content guidance",
- ],
- "why": "The operator should first choose the valuable search demand and map each query intent to the page that should own it.",
- },
- "content_usefulness_trust": {
- "label": "Content usefulness & trust",
- "resources": [
- "Google helpful, reliable, people-first content guidance",
- "Google Search Quality concepts: E-E-A-T",
- ],
- "why": "Pages need original, complete, trustworthy information that satisfies the searcher, not just search-engine-first copy.",
- },
- "on_page_relevance_serp_packaging": {
- "label": "On-page relevance & SERP packaging",
- "resources": [
- "Google Search Central SEO Starter Guide",
- "Google structured data documentation",
- "Moz Beginner’s Guide to SEO",
- ],
- "why": "Titles, headings, snippets, structured data, and above-the-fold packaging help users and search engines understand why the page is the right result.",
- },
- "technical_ux_page_experience": {
- "label": "Technical UX & page experience",
- "resources": [
- "Google page experience documentation",
- "Google Core Web Vitals guidance",
- ],
- "why": "Fast, secure, mobile-friendly, non-intrusive pages support better user outcomes and can contribute when helpful content is otherwise competitive.",
- },
- "authority_distribution": {
- "label": "Authority & distribution",
- "resources": [
- "Ahrefs link building guidance",
- "Moz link building guidance",
- "Google Search Essentials promotion guidance",
- ],
- "why": "Competitive topics often need internal link equity, citations, mentions, or other legitimate reputation signals beyond page-level copy.",
- },
- "local_presence_reputation": {
- "label": "Local presence & reputation",
- "resources": [
- "Google Business Profile local ranking guidance",
- "Ahrefs local SEO guidance",
- ],
- "why": "Local rankings depend on relevance, distance, and prominence, including complete business information, reviews, photos, and locally specific proof.",
- },
- "measurement_prioritization_experimentation": {
- "label": "Measurement, prioritization & experimentation",
- "resources": [
- "Google Search Central measurement guidance",
- SEO_BEST_PRACTICE_REFERENCE,
- ],
- "why": "SEO work should be prioritized by expected business impact, measured against baselines, and followed up after enough data matures.",
- },
-}
-
-ACTION_BEST_PRACTICE_AREAS = {
- "canonical_or_tracking_investigation": "search_eligibility_indexability",
- "demand_seed_content": "demand_intent_targeting",
- "query_intent_mapping": "demand_intent_targeting",
- "local_intent_ownership": "demand_intent_targeting",
- "content_refresh": "content_usefulness_trust",
- "page_improvement": "content_usefulness_trust",
- "meta_tags": "on_page_relevance_serp_packaging",
- "snippet_content_packaging": "on_page_relevance_serp_packaging",
- "internal_links": "authority_distribution",
- "technical_index_sitemap": "search_eligibility_indexability",
- "conversion_path_optimization": "measurement_prioritization_experimentation",
- "manual_review": "measurement_prioritization_experimentation",
-}
-
-
-def future_iso(days: int) -> str:
- return (datetime.now(timezone.utc) + timedelta(days=days)).replace(microsecond=0).isoformat().replace("+00:00", "Z")
-
-
-def metric_snapshot_from_analysis(data: dict[str, Any]) -> dict[str, float]:
- period_days = int((data.get("period") or {}).get("days") or 28)
- suffix = f"_{period_days}d"
- summary = data.get("summary") or {}
- branded_split = data.get("branded_split") or {}
- branded = branded_split.get("branded") or {}
- non_branded = branded_split.get("non_branded") or {}
- snapshot: dict[str, float] = {
- f"organic_clicks{suffix}": float(summary.get("clicks", 0)),
- f"organic_impressions{suffix}": float(summary.get("impressions", 0)),
- f"organic_ctr{suffix}": float(summary.get("ctr", 0)),
- f"avg_position{suffix}": float(summary.get("position", 0)),
- }
- if branded_split:
- snapshot[f"non_brand_clicks{suffix}"] = float(non_branded.get("clicks", 0))
- snapshot[f"branded_clicks{suffix}"] = float(branded.get("clicks", 0))
- snapshot[f"non_brand_impressions{suffix}"] = float(non_branded.get("impressions", 0))
- snapshot[f"branded_impressions{suffix}"] = float(branded.get("impressions", 0))
- return snapshot
-
-
-def learned_multiplier(learned: dict[str, Any], action_type: str, primary_metric: str) -> float:
- priors = (learned or {}).get("priors") or {}
- prior = priors.get(f"{action_type}::{primary_metric}")
- if not prior:
- return 1.0
- sample_size = max(int(prior.get("sample_size", 0)), 1)
- wins = int(prior.get("wins", 0))
- losses = int(prior.get("losses", 0))
- neutral = int(prior.get("neutral", 0))
- avg_change = float(prior.get("avg_primary_change", 0.0))
- confidence = float(prior.get("confidence", 0.0))
- win_rate = wins / sample_size
- loss_rate = losses / sample_size
- neutral_rate = neutral / sample_size
- raw = 1.0 + (win_rate * 0.25) - (loss_rate * 0.2) + (avg_change * 0.5) + (confidence * 0.1) + (neutral_rate * 0.02)
- return max(0.7, min(1.5, round(raw, 3)))
-
-
-TRACKING_PARAM_NAMES = {
- "fbclid",
- "gclid",
- "gbraid",
- "wbraid",
- "mc_cid",
- "mc_eid",
- "msclkid",
-}
-TRACKING_PARAM_PREFIXES = ("utm_",)
-
-
-def clamp(value: float, low: float, high: float) -> float:
- return max(low, min(high, value))
-
-
-def expected_ctr_for_position(position: float | None) -> float:
- """Return a conservative expected CTR percentage for a rough SERP position."""
- if position is None or position <= 0:
- return 1.0
- if position <= 1.5:
- return 18.0
- if position <= 3:
- return 10.0
- if position <= 5:
- return 6.0
- if position <= 10:
- return 3.0
- if position <= 20:
- return 1.5
- return 0.5
-
-
-def sample_confidence(clicks: float = 0, impressions: float = 0) -> float:
- """Soft confidence curve: larger samples earn more trust without a hard cutoff."""
- click_component = 1 - math.exp(-max(clicks, 0) / 35)
- impression_component = 1 - math.exp(-max(impressions, 0) / 1200)
- return round(clamp(0.25 + (click_component * 0.45) + (impression_component * 0.3), 0.25, 1.0), 3)
-
-
-def url_context(url: str | None) -> dict[str, Any]:
- if not url:
- return {
- "raw_target": None,
- "canonical_target": None,
- "url_quality_score": 0.8,
- "has_tracking_params": False,
- "operator_judgment_notes": [],
- }
-
- parsed = urlparse(url)
- query_pairs = parse_qsl(parsed.query, keep_blank_values=True)
- tracking_keys = [key for key, _ in query_pairs if key in TRACKING_PARAM_NAMES or key.startswith(TRACKING_PARAM_PREFIXES)]
- remaining_pairs = [(key, value) for key, value in query_pairs if key not in TRACKING_PARAM_NAMES and not key.startswith(TRACKING_PARAM_PREFIXES)]
- canonical_path = parsed.path or "/"
- canonical_query = urlencode(remaining_pairs, doseq=True)
- canonical = urlunparse((parsed.scheme, parsed.netloc, canonical_path, "", canonical_query, ""))
-
- notes = []
- if tracking_keys:
- notes.append(f"tracking URL variant ({', '.join(sorted(set(tracking_keys)))})")
- if query_pairs and not remaining_pairs:
- notes.append("canonical target removes query parameters")
-
- if tracking_keys and not remaining_pairs:
- url_quality = 0.45
- elif tracking_keys:
- url_quality = 0.65
- elif query_pairs:
- url_quality = 0.8
- else:
- url_quality = 1.0
-
- return {
- "raw_target": url,
- "canonical_target": canonical,
- "url_quality_score": url_quality,
- "has_tracking_params": bool(tracking_keys),
- "operator_judgment_notes": notes,
- }
-
-
-def severity_from_score(score: float) -> str:
- if score >= 1.4:
- return "critical"
- if score >= 0.65:
- return "warning"
- return "info"
-
-
-def total_declining_click_loss(analysis: dict[str, Any]) -> float:
- comparison = analysis.get("comparison") or {}
- page_loss = 0.0
- query_loss = 0.0
- for page in comparison.get("declining_pages") or []:
- page_loss += max(float(page.get("clicks_prev") or 0) - float(page.get("clicks_now") or 0), 0.0)
- for query in comparison.get("declining_queries") or []:
- query_loss += max(float(query.get("clicks_prev") or 0) - float(query.get("clicks_now") or 0), 0.0)
- # Page and query declines are different slices of the same GSC clicks. Summing
- # them double-counts the same traffic loss and can falsely trigger recovery mode.
- return round(max(page_loss, query_loss), 1)
-
-
-def infer_site_stage(analysis: dict[str, Any], metrics: dict[str, float], business_context: dict[str, Any] | None = None) -> dict[str, Any]:
- """Classify the SEO operating mode so the weekly review picks the right playbook.
-
- Seed-stage sites should not be told "manual review only" just because GSC is
- sparse. Harvest/recover/defend sites have enough signal for GSC-led actions.
- """
- configured = (business_context or {}).get("site_stage") or (business_context or {}).get("seo_stage")
- valid = {"seed", "harvest", "defend", "recover"}
- if isinstance(configured, str) and configured.lower() in valid:
- return {
- "stage": configured.lower(),
- "source": "business_context",
- "reason": f"Business context explicitly sets SEO stage to {configured.lower()}.",
- }
-
- period_days = int((analysis.get("period") or {}).get("days") or 28)
- suffix = f"_{period_days}d"
- organic_clicks = float(metrics.get(f"organic_clicks{suffix}", 0.0))
- organic_impressions = float(metrics.get(f"organic_impressions{suffix}", 0.0))
- non_brand_clicks = float(metrics.get(f"non_brand_clicks{suffix}", 0.0))
- non_brand_impressions = float(metrics.get(f"non_brand_impressions{suffix}", 0.0))
- branded_clicks = float(metrics.get(f"branded_clicks{suffix}", 0.0))
- lost_clicks = total_declining_click_loss(analysis)
-
- signals = {
- "organic_clicks": organic_clicks,
- "organic_impressions": organic_impressions,
- "non_brand_clicks": non_brand_clicks,
- "non_brand_impressions": non_brand_impressions,
- "branded_clicks": branded_clicks,
- "declining_click_loss": lost_clicks,
- "period_days": period_days,
- }
- if lost_clicks >= 25:
- return {"stage": "recover", "source": "heuristic", "reason": f"Meaningful recent organic loss detected (~{lost_clicks:g} lost clicks).", "signals": signals}
- if organic_impressions < 1000 or organic_clicks < 50:
- return {"stage": "seed", "source": "heuristic", "reason": "GSC volume is too sparse for harvest-mode optimization; create demand-capture assets first.", "signals": signals}
- if non_brand_impressions >= 1000 or organic_impressions >= 5000:
- return {"stage": "harvest", "source": "heuristic", "reason": "Enough impression volume exists to harvest CTR/ranking/internal-link opportunities.", "signals": signals}
- return {"stage": "defend", "source": "heuristic", "reason": "Moderate organic presence; protect brand/service coverage while looking for qualified expansion bets.", "signals": signals}
-
-
-def make_issue(
- title: str,
- severity: str,
- confidence: float,
- evidence: list[str],
- action_type: str,
- target: str | None = None,
- base_priority: float = 0.5,
- **extra: Any,
-) -> dict[str, Any]:
- context = url_context(target)
- issue = {
- "title": title,
- "severity": severity,
- "confidence": round(confidence, 2),
- "evidence": evidence,
- "recommended_action_type": action_type,
- "base_priority": round(base_priority, 3),
- "operator_judgment_notes": extra.pop("operator_judgment_notes", []) + context["operator_judgment_notes"],
- "score_components": extra.pop("score_components", {}),
- "raw_target": context["raw_target"],
- "canonical_target": context["canonical_target"],
- }
- if target:
- issue["target"] = context["canonical_target"] or target
- issue.update(extra)
- return issue
-
-
-def best_practice_alignment_for_issue(issue: dict[str, Any]) -> dict[str, Any]:
- """Attach the primary MECE SEO best-practice lane for operator review."""
- action_type = str(issue.get("recommended_action_type") or "manual_review")
- area_key = ACTION_BEST_PRACTICE_AREAS.get(action_type)
- if area_key is None:
- return {
- "reference": SEO_BEST_PRACTICE_REFERENCE,
- "primary_area": "unmapped",
- "primary_area_label": "Unmapped SEO action type",
- "resources": [SEO_BEST_PRACTICE_REFERENCE],
- "notes": [
- f"Action type '{action_type}' is not mapped to a MECE SEO best-practice lane.",
- "Downgrade to investigation/manual review or update ACTION_BEST_PRACTICE_AREAS before treating this as an approved recommendation.",
- ],
- }
-
- area = SEO_BEST_PRACTICE_AREAS[area_key]
- notes = [area["why"]]
-
- if action_type == "content_refresh":
- notes.append("Content has lost ranking position; refresh with current data, intent alignment, and competitive comparison before republishing.")
- elif action_type in {"meta_tags", "snippet_content_packaging"}:
- notes.append("Validate the query/page/SERP fit before treating low CTR as a title or meta-description problem.")
- elif action_type in {"query_intent_mapping", "local_intent_ownership"}:
- notes.append("Resolve search intent ownership before changing content, redirects, canonicals, or metadata.")
- elif action_type == "page_improvement":
- notes.append("A regression is a diagnosis trigger; inspect content usefulness, SERP changes, and technical access before publishing edits.")
- elif action_type == "internal_links":
- notes.append("Use relevant internal links to clarify page ownership and distribute authority; do not jump straight to redirects.")
- elif action_type == "canonical_or_tracking_investigation":
- notes.append("Canonical/tracking variants should be investigated as URL hygiene before editing page copy.")
- elif action_type == "technical_index_sitemap":
- notes.append("Resolve noindex, sitemap, redirect, canonical, and internal-link inconsistencies before asking content changes to perform.")
- elif action_type == "conversion_path_optimization":
- notes.append("Organic traffic should route to a measurable qualified action; check CTA friction and conversion instrumentation before chasing clicks.")
-
- return {
- "reference": SEO_BEST_PRACTICE_REFERENCE,
- "primary_area": area_key,
- "primary_area_label": area["label"],
- "resources": area["resources"],
- "notes": notes,
- }
-
-
-
-LOCAL_INTENT_TERMS = {
- "near me",
- "nearby",
- "local",
- "open now",
-}
-COMMERCIAL_SERVICE_TERMS = {
- "service",
- "services",
- "repair",
- "installation",
- "contractor",
- "company",
- "provider",
- "appointment",
- "booking",
- "quote",
- "consultation",
-}
-INFORMATIONAL_SERP_TERMS = {
- "how much",
- "average",
- "cost",
- "price",
- "prices",
- "per day",
- "per night",
- "for a week",
-}
-
-
-def business_intent_for_query(query: str | None) -> tuple[float, str, list[str]]:
- """Estimate whether click upside is likely to map to revenue, not just visits.
-
- This is deliberately a soft judgment lever, not a hard rule. Informational
- price queries can be valuable, but they often have zero-click SERPs and need
- content/CTA packaging, not metadata-only edits.
- """
- if not query:
- return 0.7, "unknown", ["query intent unknown; validate before editing metadata"]
-
- q = query.lower()
- has_local = any(term in q for term in LOCAL_INTENT_TERMS)
- has_service = any(term in q for term in COMMERCIAL_SERVICE_TERMS)
- has_info = any(term in q for term in INFORMATIONAL_SERP_TERMS)
-
- if has_local and has_service:
- return 1.0, "local_commercial", []
- if "near me" in q:
- return 0.95, "local_commercial", []
- if has_service and not has_info:
- return 0.85, "commercial", []
- if has_info and has_service:
- return 0.7, "commercial_research", [
- "commercial research query; metadata alone is unproven",
- "possible zero-click/SERP-answer behavior; inspect SERP before assuming CTR lift",
- ]
- if has_info:
- return 0.55, "informational", [
- "informational query; click upside may not convert",
- "possible zero-click/SERP-answer behavior; inspect SERP before assuming CTR lift",
- ]
- return 0.75, "mixed", ["mixed intent; validate business value before content edits"]
-
-
-def zero_click_risk_for_query(query: str | None, intent_class: str | None = None) -> tuple[str, list[str]]:
- q = (query or "").lower()
- notes = []
- risk_score = 0
- if intent_class in {"commercial_research", "informational"}:
- risk_score += 1
- notes.append(f"{intent_class} intent often gets answered directly on the SERP")
- if any(term in q for term in INFORMATIONAL_SERP_TERMS):
- risk_score += 1
- notes.append("price/how-much wording can trigger answer boxes or calculator-style snippets")
- if any(term in q for term in LOCAL_INTENT_TERMS):
- risk_score -= 1
- notes.append("local modifier increases booking intent and reduces pure zero-click risk")
- if risk_score >= 2:
- return "high", notes
- if risk_score == 1:
- return "medium", notes
- return "low", notes or ["query does not look primarily answer-box driven"]
-
-
-def is_branded_query(query: str | None, brand_terms: list[str] | None) -> bool:
- if not query or not brand_terms:
- return False
- q = query.lower()
- return any(term and term.lower() in q for term in brand_terms)
-
-
-GENERIC_BRAND_STOPWORDS = {"the", "a", "an", "inc", "llc", "ltd", "co", "company", "official", "website"}
-GENERIC_BRAND_SERVICE_TERMS = {"boarding", "board", "daycare", "grooming", "groom", "training", "sitting", "sitter", "pet", "dog", "cat"}
-
-
-def is_generic_branded_query(query: str | None, brand_terms: list[str] | None) -> bool:
- """True for pure navigational brand searches like "paws vip".
-
- Branded service searches ("paws vip dog boarding", "example grooming seattle")
- can still be business-relevant for service pages, but pure brand navigational
- searches usually belong to the homepage / GBP / directory SERP, so low CTR on
- a secondary service page is not an actionable snippet opportunity.
- """
- if not is_branded_query(query, brand_terms):
- return False
- normalized = re.sub(r"[^a-z0-9]+", " ", (query or "").lower()).strip()
- for term in sorted((brand_terms or []), key=len, reverse=True):
- term_norm = re.sub(r"[^a-z0-9]+", " ", term.lower()).strip()
- if term_norm:
- normalized = re.sub(rf"\b{re.escape(term_norm)}\b", " ", normalized)
- residual = " ".join(token for token in normalized.split() if token not in GENERIC_BRAND_STOPWORDS)
- if not residual:
- return True
- action_terms = LOCAL_INTENT_TERMS | COMMERCIAL_SERVICE_TERMS | INFORMATIONAL_SERP_TERMS | GENERIC_BRAND_SERVICE_TERMS
- return not any(term in residual for term in action_terms)
-
-
-SERVICE_PAGE_PATTERNS = re.compile(r"/(?:locations?|services?|pricing|booking|book|reserve|contact|about|faq|gallery|rates?|review|team|careers?|apply|shop|products?|dogs?-(?:boarding?|daycare|sitting?|grooming|training)|pet-(?:boarding?|daycare|sitting?|grooming|training))")
-
-
-def is_service_page(url: str | None) -> bool:
- """True if the URL looks like a service/business page, not a blog or content article."""
- if not url:
- return False
- path = urlparse(url).path.rstrip("/") or "/"
- if re.search(r"/(?:blogs?|blog|news|articles?|posts?|journal|category|tag/|author/)", path):
- return False
- if bool(SERVICE_PAGE_PATTERNS.search(path)):
- return True
- # Short paths with no subdirectory are likely service pages (e.g. /dog-boarding, /)
- return path.count("/") <= 2
-
-
-def goal_alignment_for_query(query: str | None, brand_terms: list[str] | None) -> tuple[float, list[str]]:
- if is_branded_query(query, brand_terms):
- return 0.35, ["branded/navigational query; lower priority for non-brand growth"]
- return 1.0, []
-
-
-def classify_regression_pattern(top_query: dict[str, Any]) -> tuple[str, str, list[str]]:
- """Classify a losing query into an action type and best-practice area.
-
- Examines which metric moved first to determine the root cause:
-
- - Position drop + impression drop + CTR ~stable → ranking loss → content_refresh
- - CTR drop + position stable + impressions ~stable → SERP displacement → snippet_content_packaging
- - Impression drop + position stable + CTR stable → demand fade → query_intent_mapping
- - Mixed/ambiguous → page_improvement (defer to operator)
- """
- pos_now = top_query.get("position_now")
- pos_prev = top_query.get("position_prev")
- pos_delta = None
- if pos_now is not None and pos_prev is not None:
- pos_delta = pos_now - pos_prev # positive = rank dropped (higher number = worse)
-
- ctr_now = top_query.get("ctr_now") or 0
- ctr_prev = top_query.get("ctr_prev") or 0
- ctr_delta = ctr_now - ctr_prev
-
- impr_now = top_query.get("impressions_now", 0)
- impr_prev = top_query.get("impressions_prev", 0)
- impr_delta = impr_now - impr_prev
- impr_decline_pct = (impr_delta / max(impr_prev, 1)) * 100 if impr_prev > 0 else 0
-
- notes = []
-
- # Rank position drop is the strongest signal
- if pos_delta is not None and pos_delta >= 1.5:
- notes.append(f"Position dropped {pos_delta:+.1f} positions; likely ranking loss or competitive displacement")
- return "content_refresh", "content_usefulness_trust", notes
-
- if pos_delta is not None and pos_delta >= 0.5:
- notes.append(f"Position drifted {pos_delta:+.1f} positions; mild ranking regression")
- return "content_refresh", "content_usefulness_trust", notes
-
- # CTR drop with stable position → SERP displacement
- if ctr_delta < -2.0 and impr_decline_pct > -30:
- notes.append(f"CTR dropped {ctr_delta:+.1f}% while position held; likely SERP feature displacement")
- return "snippet_content_packaging", "on_page_relevance_serp_packaging", notes
-
- if ctr_delta < -1.0 and pos_delta is not None and abs(pos_delta) < 0.5:
- notes.append(f"Mild CTR decline {ctr_delta:+.1f}% with stable position; possible SERP layout change")
- return "snippet_content_packaging", "on_page_relevance_serp_packaging", notes
-
- # Impression drop without position or CTR change → demand fade / intent shift
- if impr_decline_pct < -40 and ctr_delta > -1.0 and (pos_delta is None or abs(pos_delta) < 0.5):
- notes.append(f"Impressions declined {impr_decline_pct:.0f}% without ranking or CTR change; possible intent shift or demand fade")
- return "query_intent_mapping", "demand_intent_targeting", notes
-
- # Mixed signals — keep as page_improvement
- notes.append("Mixed or ambiguous regression signals; operator investigation required")
- return "page_improvement", "content_usefulness_trust", notes
-
-
-def decline_issue(page: dict[str, Any]) -> dict[str, Any]:
- raw_target = page.get("page")
- context = url_context(raw_target)
- clicks_now = float(page.get("clicks_now") or 0)
- clicks_prev = float(page.get("clicks_prev") or 0)
- lost_clicks = max(clicks_prev - clicks_now, 0.0)
- change_pct = float(page.get("change_pct") or 0)
- confidence = sample_confidence(clicks=clicks_prev + clicks_now)
- impact_score = clamp(lost_clicks / 50, 0.05, 2.0)
- actionability_score = 0.75
- action_type = "page_improvement"
- title_target = raw_target
- notes = []
-
- # Decompose with top-losing-queries from query-page GSC data
- top_losing_queries = page.get("top_losing_queries", [])
- if top_losing_queries:
- top_losing_queries = [q for q in top_losing_queries if q.get("absolute_click_loss", 0) > 0]
-
- primary_query: str | None = None
- diagnostic_query: str | None = None
- query_decomposition: dict[str, Any] | None = None
- approval_blockers: list[str] = []
- if top_losing_queries:
- top = top_losing_queries[0]
- total_lost = top.get("absolute_click_loss", 0)
- share_of_loss = total_lost / max(lost_clicks, 1)
- top_name = top.get("query", "")
- diagnostic_query = top_name or None
- explained_loss = sum(float(q.get("absolute_click_loss") or 0) for q in top_losing_queries[:5])
- explained_loss_share = explained_loss / max(lost_clicks, 1)
- query_decomposition = {
- "top_query_loss_share": round(share_of_loss, 3),
- "top_5_explained_loss_share": round(explained_loss_share, 3),
- "top_5_explained_lost_clicks": round(explained_loss, 1),
- "is_distributed": share_of_loss < 0.3,
- }
-
- if share_of_loss >= 0.3:
- # Dominant losing query — reclassify action type based on regression pattern
- primary_query = top_name
- classified_type, classified_area, classify_notes = classify_regression_pattern(top)
- action_type = classified_type
- notes.extend(classify_notes)
- notes.append(f"Top query '{primary_query}' drives {share_of_loss:.0%} of lost clicks ({total_lost:g} of {lost_clicks:g})")
- else:
- # Distributed across queries — keep page_improvement but attach context
- notes.append(f"Top query '{top_name}' drives {share_of_loss:.0%} of lost clicks; decline is distributed")
- notes.append("Distributed decline; diagnose SERP changes and content freshness across multiple queries")
- actionability_score = 0.35 if explained_loss_share >= 0.5 else 0.2
- notes.append("No dominant losing query; this is a diagnostic signal, not an approval-ready edit")
- approval_blockers.append("distributed regression has no dominant primary query")
-
- if context["has_tracking_params"]:
- action_type = "canonical_or_tracking_investigation"
- actionability_score = 0.45
- notes.append("treat as attribution/canonical investigation before editing page content")
- title_target = context["canonical_target"] or raw_target
- if lost_clicks < 25:
- notes.append("low absolute click loss; percentage drop may overstate impact")
-
- url_quality = float(context["url_quality_score"])
- score = impact_score * confidence * actionability_score * url_quality
-
- extra_kwargs: dict[str, Any] = {
- "target": raw_target,
- "base_priority": impact_score,
- "expected_click_delta": round(-lost_clicks, 1),
- "priority_score": round(score, 3),
- "score_components": {
- "expected_impact": round(impact_score, 3),
- "confidence_score": confidence,
- "goal_alignment_score": 1.0,
- "actionability_score": actionability_score,
- "url_quality_score": url_quality,
- },
- "operator_judgment_notes": notes,
- "top_losing_queries": top_losing_queries,
- }
- if primary_query:
- extra_kwargs["primary_query"] = primary_query
- if diagnostic_query and diagnostic_query != primary_query:
- extra_kwargs["diagnostic_query"] = diagnostic_query
- if query_decomposition:
- extra_kwargs["query_decomposition"] = query_decomposition
- if approval_blockers:
- extra_kwargs["approval_blockers"] = approval_blockers
-
- return make_issue(
- f"Traffic dropped on {title_target}",
- severity_from_score(score),
- confidence,
- [
- f"Clicks changed {change_pct}% vs prior period.",
- f"Current clicks: {clicks_now:g} | previous clicks: {clicks_prev:g} | lost clicks: {lost_clicks:g}",
- ],
- action_type,
- **extra_kwargs,
- )
-
-
-def ctr_gap_issue(gap: dict[str, Any], brand_terms: list[str] | None = None) -> dict[str, Any]:
- raw_target = gap.get("page")
- clicks = float(gap.get("clicks") or 0)
- impressions = float(gap.get("impressions") or 0)
- ctr = float(gap.get("ctr") or 0)
- position = float(gap.get("position") or 0)
- expected_ctr = expected_ctr_for_position(position)
- incremental_clicks = max(impressions * ((expected_ctr - ctr) / 100), 0.0)
- impact_score = clamp(incremental_clicks / 50, 0.05, 2.0)
- confidence = sample_confidence(clicks=clicks, impressions=impressions)
- query = gap.get("query")
- business_intent_score, intent_class, intent_notes = business_intent_for_query(query)
- actionability_score = 0.95
- action_type = "meta_tags"
- action_notes = ["clear snippet/title lever with measurable upside"]
- if intent_class in {"commercial_research", "informational", "mixed", "unknown"}:
- action_type = "snippet_content_packaging"
- actionability_score = 0.75
- action_notes = [
- "low CTR is a hypothesis, not proof of bad metadata",
- "recommend SERP + snippet + above-the-fold content diagnosis before editing",
- ]
- url_quality = float(url_context(raw_target)["url_quality_score"])
- # For service pages, goal_alignment considers the page's role, not just the top
- # underperforming query. Branded service searches ("example boarding") can be
- # valuable; pure brand navigational searches ("example") should not become
- # secondary-page CTR edit proposals.
- generic_branded_service_gap = is_service_page(raw_target) and is_generic_branded_query(query, brand_terms)
- approval_blockers: list[str] = []
- if generic_branded_service_gap:
- goal_alignment_score = 0.35
- actionability_score = min(actionability_score, 0.35)
- goal_notes = [
- "generic branded query; low CTR on a secondary service page is usually navigational SERP behavior, not a snippet/content fix",
- ]
- approval_blockers.append("generic branded query needs SERP ownership diagnosis, not a page edit")
- elif is_service_page(raw_target) and is_branded_query(query, brand_terms):
- goal_alignment_score = 1.0
- goal_notes = ["service page; goal alignment based on page role, not gap query"]
- else:
- goal_alignment_score, goal_notes = goal_alignment_for_query(query, brand_terms)
- score = impact_score * confidence * goal_alignment_score * actionability_score * url_quality * business_intent_score
- evidence = [
- f"{impressions:g} impressions with CTR {ctr}%.",
- f"Average position {position:g}; conservative expected CTR {expected_ctr}% suggests ~{incremental_clicks:.0f} incremental-click upside before intent/zero-click discount.",
- f"Query intent classified as {intent_class} with business intent score {business_intent_score:g}.",
- ]
- if query:
- evidence.append(f"Underperforming query: {query}")
- return make_issue(
- f"High-impression page with low CTR: {raw_target}",
- severity_from_score(score),
- confidence,
- evidence,
- action_type,
- target=raw_target,
- base_priority=impact_score,
- expected_click_delta=round(incremental_clicks * business_intent_score, 1),
- priority_score=round(score, 3),
- primary_query=query,
- intent_class=intent_class,
- score_components={
- "expected_impact": round(impact_score, 3),
- "confidence_score": confidence,
- "goal_alignment_score": goal_alignment_score,
- "business_intent_score": business_intent_score,
- "actionability_score": actionability_score,
- "url_quality_score": url_quality,
- **({"generic_brand_discount": 0.35} if generic_branded_service_gap else {}),
- },
- operator_judgment_notes=[*action_notes, *intent_notes, *goal_notes],
- approval_blockers=approval_blockers,
- )
-
-
-def approval_readiness_for_issue(issue: dict[str, Any]) -> dict[str, Any]:
- blockers = [str(blocker) for blocker in issue.get("approval_blockers", []) if blocker]
- if issue.get("recommended_action_type") == "manual_review":
- blockers.append("manual review only")
- actionability = (issue.get("score_components") or {}).get("actionability_score")
- if isinstance(actionability, (int, float)) and actionability < 0.5:
- blockers.append("actionability below approval threshold")
- if issue.get("recommended_action_type") == "page_improvement" and issue.get("diagnostic_query") and not issue.get("primary_query"):
- blocker = "diagnostic query is only a fallback; no primary query owns the loss"
- if blocker not in blockers:
- blockers.append(blocker)
- deduped = list(dict.fromkeys(blockers))
- return {"approval_ready": not deduped, "approval_blockers": deduped}
-
-
-def cannibalization_issue(cannibal: dict[str, Any], brand_terms: list[str] | None = None) -> dict[str, Any]:
- raw_target = cannibal.get("winner_page")
- impressions = float(cannibal.get("total_impressions") or 0)
- clicks = float(cannibal.get("total_clicks") or 0)
- impact_score = clamp(impressions / 5000, 0.05, 1.4)
- confidence = sample_confidence(clicks=clicks, impressions=impressions)
- actionability_score = 0.65
- url_quality = float(url_context(raw_target)["url_quality_score"])
- goal_alignment_score, goal_notes = goal_alignment_for_query(cannibal.get("query"), brand_terms)
- score = impact_score * confidence * goal_alignment_score * actionability_score * url_quality
- loser_pages = cannibal.get("loser_pages", [])
- return make_issue(
- f"Cannibalization on query '{cannibal.get('query')}'",
- severity_from_score(score),
- confidence,
- [
- f"Winner page: {raw_target}",
- f"Competing pages: {', '.join(loser_pages[:8])}{'...' if len(loser_pages) > 8 else ''}",
- f"Affected query set: {impressions:g} impressions and {clicks:g} clicks.",
- ],
- "internal_links",
- target=raw_target,
- base_priority=impact_score,
- expected_click_delta=None,
- priority_score=round(score, 3),
- winner_page=raw_target,
- loser_pages=loser_pages,
- competing_pages=cannibal.get("competing_pages", []),
- source_recommended_action=cannibal.get("recommended_action"),
- score_components={
- "expected_impact": round(impact_score, 3),
- "confidence_score": confidence,
- "goal_alignment_score": goal_alignment_score,
- "actionability_score": actionability_score,
- "url_quality_score": url_quality,
- },
- operator_judgment_notes=["needs intent review before redirects/canonicals", *goal_notes],
- )
-
-
-def technical_consistency_findings(data: dict[str, Any]) -> list[dict[str, Any]]:
- """Extract index/sitemap/canonical/link findings from analyzer or crawler output.
-
- NotFair does not assume one crawler schema. Site-specific analyzers can pass a
- compact `index_sitemap_consistency` block, or nest the same block under
- `technical_seo` / `technical_audit`.
- """
- sources = [
- data.get("index_sitemap_consistency"),
- (data.get("technical_seo") or {}).get("index_sitemap_consistency") if isinstance(data.get("technical_seo"), dict) else None,
- (data.get("technical_audit") or {}).get("index_sitemap_consistency") if isinstance(data.get("technical_audit"), dict) else None,
- ]
- field_labels = {
- "noindex_in_sitemap": "noindex URL is present in sitemap",
- "noindex_urls_in_sitemap": "noindex URL is present in sitemap",
- "redirect_in_sitemap": "redirecting URL is present in sitemap",
- "redirects_in_sitemap": "redirecting URL is present in sitemap",
- "internal_links_to_redirects": "internal links still point at redirected URLs",
- "internal_links_to_noindex": "internal links point at noindex URLs",
- "canonical_mismatches": "canonical target does not match the URL being promoted",
- }
- findings: list[dict[str, Any]] = []
- for source in sources:
- if not isinstance(source, dict):
- continue
- for field, label in field_labels.items():
- values = source.get(field) or []
- if isinstance(values, dict):
- values = [values]
- if isinstance(values, str):
- values = [{"url": values}]
- for item in values:
- if isinstance(item, str):
- item = {"url": item}
- if not isinstance(item, dict):
- continue
- url = item.get("url") or item.get("page") or item.get("source_url") or item.get("from")
- if not url:
- continue
- findings.append({
- "type": field,
- "label": label,
- "url": url,
- "canonical_url": item.get("canonical_url") or item.get("canonical") or item.get("target"),
- "redirect_target": item.get("redirect_target") or item.get("to") or item.get("destination"),
- "source_urls": item.get("source_urls") or item.get("linked_from") or item.get("referrers") or [],
- "raw": item,
- })
- return findings
-
-
-def technical_consistency_issue(finding: dict[str, Any]) -> dict[str, Any]:
- target = finding.get("url")
- label = finding.get("label", "technical consistency issue")
- source_urls = finding.get("source_urls") or []
- if isinstance(source_urls, str):
- source_urls = [source_urls]
- evidence = [label, f"URL: {target}"]
- if finding.get("canonical_url"):
- evidence.append(f"Canonical target: {finding['canonical_url']}")
- if finding.get("redirect_target"):
- evidence.append(f"Redirect target: {finding['redirect_target']}")
- if source_urls:
- evidence.append(f"Linked from: {', '.join(str(url) for url in source_urls[:5])}")
- return make_issue(
- f"Fix index/sitemap consistency: {target}",
- "warning",
- 0.8,
- evidence,
- "technical_index_sitemap",
- target=target,
- base_priority=0.9,
- expected_click_delta=None,
- priority_score=0.72,
- technical_consistency_finding=finding,
- score_components={
- "expected_impact": 0.9,
- "confidence_score": 0.8,
- "goal_alignment_score": 1.0,
- "actionability_score": 0.95,
- "url_quality_score": float(url_context(target)["url_quality_score"]),
- },
- operator_judgment_notes=[
- "noindex URLs must be absent from sitemaps",
- "redirected URLs should be removed from sitemaps and internal links should point to canonical destinations",
- "fix eligibility/indexing hygiene before content or metadata edits",
- ],
- )
-
-
-def query_ctr_issue(opp: dict[str, Any], brand_terms: list[str] | None = None) -> dict[str, Any]:
- impressions = float(opp.get("impressions") or 0)
- clicks = float(opp.get("clicks") or 0)
- ctr = float(opp.get("ctr") or 0)
- position = float(opp.get("position") or 0)
- expected_ctr = expected_ctr_for_position(position)
- incremental_clicks = max(impressions * ((expected_ctr - ctr) / 100), 0.0)
- impact_score = clamp(incremental_clicks / 65, 0.05, 1.3)
- confidence = sample_confidence(clicks=clicks, impressions=impressions)
- actionability_score = 0.55 # Query-only; needs page mapping before editing.
- query = opp.get("query")
- business_intent_score, intent_class, intent_notes = business_intent_for_query(query)
- goal_alignment_score, goal_notes = goal_alignment_for_query(query, brand_terms)
- score = impact_score * confidence * goal_alignment_score * actionability_score * business_intent_score
- return make_issue(
- f"Query-level CTR opportunity: {query}",
- severity_from_score(score),
- confidence,
- [
- f"{impressions:g} impressions with CTR {ctr}%.",
- f"Average position {position:g}; conservative expected CTR {expected_ctr}% suggests ~{incremental_clicks:.0f} incremental-click upside before intent/zero-click discount.",
- f"Query intent classified as {intent_class} with business intent score {business_intent_score:g}.",
- ],
- "query_intent_mapping",
- base_priority=impact_score,
- expected_click_delta=round(incremental_clicks * business_intent_score, 1),
- priority_score=round(score, 3),
- primary_query=query,
- intent_class=intent_class,
- score_components={
- "expected_impact": round(impact_score, 3),
- "confidence_score": confidence,
- "goal_alignment_score": goal_alignment_score,
- "business_intent_score": business_intent_score,
- "actionability_score": actionability_score,
- "url_quality_score": 1.0,
- },
- operator_judgment_notes=["query-level signal; map to a concrete page before editing", *intent_notes, *goal_notes],
- )
-
-
-def declining_query_issue(query: dict[str, Any], brand_terms: list[str] | None = None) -> dict[str, Any]:
- clicks_now = float(query.get("clicks_now") or 0)
- clicks_prev = float(query.get("clicks_prev") or 0)
- lost_clicks = max(clicks_prev - clicks_now, 0.0)
- confidence = sample_confidence(clicks=clicks_prev + clicks_now)
- impact_score = clamp(lost_clicks / 50, 0.05, 1.0)
- actionability_score = 0.5
- goal_alignment_score, goal_notes = goal_alignment_for_query(query.get("query"), brand_terms)
- score = impact_score * confidence * goal_alignment_score * actionability_score
- return make_issue(
- f"Query demand fell for '{query.get('query')}'",
- severity_from_score(score),
- confidence,
- [
- f"Clicks changed {query.get('change_pct')}% vs prior period.",
- f"Current clicks: {clicks_now:g} | previous clicks: {clicks_prev:g} | lost clicks: {lost_clicks:g}",
- ],
- "content_refresh",
- base_priority=impact_score,
- expected_click_delta=round(-lost_clicks, 1),
- priority_score=round(score, 3),
- score_components={
- "expected_impact": round(impact_score, 3),
- "confidence_score": confidence,
- "goal_alignment_score": goal_alignment_score,
- "actionability_score": actionability_score,
- "url_quality_score": 1.0,
- },
- operator_judgment_notes=["query-level regression; needs SERP/page diagnosis before editing", *goal_notes],
- )
-
-
-def dedupe_candidates(candidates: list[dict[str, Any]]) -> list[dict[str, Any]]:
- by_key: dict[str, dict[str, Any]] = {}
- for candidate in candidates:
- key = candidate.get("canonical_target") or candidate.get("title")
- existing = by_key.get(key)
- if not existing or candidate.get("priority_score", 0) > existing.get("priority_score", 0):
- by_key[key] = candidate
- elif existing:
- existing.setdefault("operator_judgment_notes", []).append(f"Also saw signal: {candidate['title']}")
- return list(by_key.values())
-
-
-def derive_candidate_issues(data: dict[str, Any]) -> list[dict[str, Any]]:
- issues: list[dict[str, Any]] = []
- comparison = data.get("comparison") or {}
- ctr_gaps = data.get("ctr_gaps_by_page") or []
- cannibalization = data.get("cannibalization") or []
- ctr_opps = data.get("ctr_opportunities") or []
- declining_pages = comparison.get("declining_pages") or []
- declining_queries = comparison.get("declining_queries") or []
- brand_terms = data.get("_brand_terms") or []
-
- # Build lookup for query-page decompositions (from GSC comparison analysis)
- page_query_lookup: dict[str, list[dict[str, Any]]] = {}
- for decomp in (comparison.get("page_query_decompositions") or []):
- page_url = decomp.get("page", "")
- losing_queries = decomp.get("top_losing_queries", [])
- if page_url and losing_queries:
- page_query_lookup[page_url] = losing_queries
-
- for page in declining_pages[:8]:
- page_url = page.get("page", "")
- top_losing = page_query_lookup.get(page_url, [])
- page["top_losing_queries"] = top_losing
- issues.extend([decline_issue(page)])
- issues.extend(technical_consistency_issue(finding) for finding in technical_consistency_findings(data)[:8])
- issues.extend(ctr_gap_issue(gap, brand_terms) for gap in ctr_gaps[:8])
- issues.extend(cannibalization_issue(cannibal, brand_terms) for cannibal in cannibalization[:5])
- issues.extend(query_ctr_issue(opp, brand_terms) for opp in ctr_opps[:5])
- issues.extend(declining_query_issue(query, brand_terms) for query in declining_queries[:5])
-
- return dedupe_candidates(issues)
-
-
-def apply_prioritization(candidates: list[dict[str, Any]], learned: dict[str, Any], primary_metric: str) -> list[dict[str, Any]]:
- ranked = []
- for item in candidates:
- multiplier = learned_multiplier(learned, item["recommended_action_type"], primary_metric)
- score = float(item.get("priority_score", item.get("base_priority", 0.5))) * multiplier
- enriched = dict(item)
- enriched["priority_score"] = round(score, 3)
- enriched["learned_multiplier"] = multiplier
- enriched["severity"] = severity_from_score(score)
- ranked.append(enriched)
- ranked.sort(key=lambda issue: issue["priority_score"], reverse=True)
- return ranked
-
-
-
-class PageSnapshotParser(HTMLParser):
- def __init__(self) -> None:
- super().__init__()
- self.title = ""
- self.meta_description = ""
- self.h1 = ""
- self._tag_stack: list[str] = []
- self._capture_title = False
- self._capture_h1 = False
- self._skip_depth = 0
- self.body_chunks: list[str] = []
- self.cta_texts: list[str] = []
-
- def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
- attrs_dict = {key.lower(): value or "" for key, value in attrs}
- tag = tag.lower()
- self._tag_stack.append(tag)
- if tag in {"script", "style", "noscript", "svg"}:
- self._skip_depth += 1
- if tag == "title":
- self._capture_title = True
- if tag == "h1" and not self.h1:
- self._capture_h1 = True
- if tag == "meta" and attrs_dict.get("name", "").lower() == "description":
- self.meta_description = attrs_dict.get("content", "").strip()
- if tag in {"a", "button"}:
- aria = attrs_dict.get("aria-label", "").strip()
- if aria:
- self.cta_texts.append(aria)
-
- def handle_endtag(self, tag: str) -> None:
- tag = tag.lower()
- if tag == "title":
- self._capture_title = False
- if tag == "h1":
- self._capture_h1 = False
- if tag in {"script", "style", "noscript", "svg"} and self._skip_depth:
- self._skip_depth -= 1
- if self._tag_stack:
- self._tag_stack.pop()
-
- def handle_data(self, data: str) -> None:
- text = re.sub(r"\s+", " ", data).strip()
- if not text:
- return
- if self._capture_title:
- self.title = (self.title + " " + text).strip()
- if self._capture_h1 and not self.h1:
- self.h1 = (self.h1 + " " + text).strip()
- if self._skip_depth == 0:
- self.body_chunks.append(text)
- if self._tag_stack and self._tag_stack[-1] in {"a", "button"}:
- self.cta_texts.append(text)
-
-
-def live_fetch_headers(site_profile: dict[str, Any] | None = None) -> dict[str, str]:
- headers = {
- "User-Agent": "Mozilla/5.0 (compatible; NotFairOpenClawSEOOperator/1.0; +https://openclaw.ai)",
- "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
- }
- profile = site_profile or {}
- for name, value in (profile.get("live_fetch_headers") or {}).items():
- if value:
- headers[str(name)] = str(value)
- for name, env_name in (profile.get("live_fetch_header_env") or {}).items():
- value = os.environ.get(str(env_name))
- if value:
- headers[str(name)] = value
-
- bypass_env_names = [
- profile.get("vercel_protection_bypass_env"),
- "TOPRANK_VERCEL_PROTECTION_BYPASS",
- "VERCEL_PROTECTION_BYPASS",
- "VERCEL_AUTOMATION_BYPASS_SECRET",
- ]
- for env_name in bypass_env_names:
- if env_name and os.environ.get(str(env_name)):
- headers["x-vercel-protection-bypass"] = os.environ[str(env_name)]
- break
- return headers
-
-
-def fetch_url_text(url: str, timeout: int = 12, site_profile: dict[str, Any] | None = None) -> tuple[str | None, dict[str, Any]]:
- request = Request(url, headers=live_fetch_headers(site_profile))
- try:
- with urlopen(request, timeout=timeout) as response:
- content_type = response.headers.get("content-type", "")
- raw = response.read(750_000)
- return raw.decode("utf-8", "ignore"), {"status": "ok", "http_status": response.status, "content_type": content_type}
- except HTTPError as exc:
- body = ""
- try:
- body = exc.read(80_000).decode("utf-8", "ignore")
- except Exception:
- body = ""
- mitigated = "vercel" in body.lower() and ("security checkpoint" in body.lower() or "challenge" in body.lower())
- return None, {"status": "blocked", "http_status": exc.code, "reason": "vercel_security_checkpoint" if mitigated else str(exc)}
- except (TimeoutError, URLError) as exc:
- return None, {"status": "error", "reason": str(exc)}
-
-
-def parse_html_snapshot(raw_html: str, source: str) -> dict[str, Any]:
- parser = PageSnapshotParser()
- parser.feed(raw_html)
- body = "\n".join(parser.body_chunks)
- body = re.sub(r"\s+", " ", html.unescape(body)).strip()
- return {
- "source": source,
- "status": "ok",
- "title": html.unescape(parser.title).strip(),
- "meta_description": html.unescape(parser.meta_description).strip(),
- "h1": html.unescape(parser.h1).strip(),
- "above_the_fold_text": body[:1800],
- "content_word_count": len(re.findall(r"\b\w+\b", body)),
- "cta_texts": sorted({text.strip() for text in parser.cta_texts if text.strip()})[:12],
- }
-
-
-def parse_frontmatter_snapshot(markdown: str, source_path: Path) -> dict[str, Any]:
- frontmatter: dict[str, Any] = {}
- body = markdown
- if markdown.startswith("---"):
- parts = markdown.split("---", 2)
- if len(parts) >= 3:
- body = parts[2]
- for line in parts[1].splitlines():
- if ":" not in line or line.strip().startswith("[") or line.strip().startswith("]"):
- continue
- key, value = line.split(":", 1)
- value = value.strip().strip('"').strip("'")
- if value:
- frontmatter[key.strip()] = value
- heading = ""
- for line in body.splitlines():
- stripped = line.strip()
- if stripped.startswith("# "):
- heading = stripped[2:].strip()
- break
- plain = re.sub(r"```.*?```", " ", body, flags=re.S)
- plain = re.sub(r"!\[[^\]]*\]\([^)]*\)", " ", plain)
- plain = re.sub(r"\[[^\]]+\]\([^)]*\)", lambda m: m.group(0).split("]", 1)[0].lstrip("["), plain)
- plain = re.sub(r"[#*_>`-]+", " ", plain)
- plain = re.sub(r"\s+", " ", plain).strip()
- return {
- "source": "local_source",
- "source_path": str(source_path),
- "status": "ok",
- "title": frontmatter.get("title", ""),
- "meta_description": frontmatter.get("description", ""),
- "h1": heading or frontmatter.get("title", ""),
- "above_the_fold_text": plain[:1800],
- "content_word_count": len(re.findall(r"\b\w+\b", plain)),
- "cta_texts": sorted(set(re.findall(r"(?i)\b(book now|book|reserve|call|schedule|request quote|get quote)\b", plain[:2500])))[:12],
- }
-
-
-def discover_local_source(url: str | None, site_profile: dict[str, Any] | None = None) -> Path | None:
- if not url:
- return None
- parsed = urlparse(url)
- slug = Path(parsed.path).name
- if not slug:
- return None
- profile = site_profile or {}
- configured_roots = [Path(root).expanduser() for root in profile.get("source_roots", [])]
- project_root = profile.get("local_project_root")
- if project_root:
- configured_roots.append(Path(project_root).expanduser())
- search_roots = configured_roots or list((Path.home() / "Documents" / "Projects").glob("*"))
- candidates: list[Path] = []
- common_rel_paths = [
- Path("content/blogs") / f"{slug}.mdx",
- Path("content/blogs") / f"{slug}.md",
- Path("src/content/blogs") / f"{slug}.mdx",
- Path("app") / parsed.path.strip("/") / "page.tsx",
- Path("pages") / f"{slug}.tsx",
- ]
- for root in search_roots[:80]:
- if not root.exists() or not root.is_dir():
- continue
- for rel in common_rel_paths:
- path = root / rel
- if path.exists() and path.is_file():
- candidates.append(path)
- return candidates[0] if len(candidates) == 1 else None
-
-
-def page_snapshot_for_url(url: str | None, site_profile: dict[str, Any] | None = None, live: bool = False) -> dict[str, Any]:
- source_path = discover_local_source(url, site_profile)
- if source_path:
- return parse_frontmatter_snapshot(source_path.read_text(errors="ignore"), source_path)
- if live and url:
- raw_html, meta = fetch_url_text(url, site_profile=site_profile)
- if raw_html:
- return parse_html_snapshot(raw_html, "live_fetch")
- return {"source": "live_fetch", **meta}
- return {"source": "none", "status": "unavailable", "reason": "no local source mapping and live fetch disabled"}
-
-
-def parse_duckduckgo_results(raw_html: str) -> list[dict[str, str]]:
- results: list[dict[str, str]] = []
- for match in re.finditer(r'<a[^>]+class="result__a"[^>]+href="([^"]+)"[^>]*>(.*?)</a>', raw_html, re.S):
- href = html.unescape(match.group(1))
- parsed_href = urlparse(href)
- if parsed_href.path.startswith("/l/"):
- params = dict(parse_qsl(parsed_href.query))
- href = unquote(params.get("uddg", href))
- elif href.startswith("//duckduckgo.com/l/"):
- params = dict(parse_qsl(urlparse("https:" + href).query))
- href = unquote(params.get("uddg", href))
- title = re.sub(r"<.*?>", "", match.group(2), flags=re.S)
- block = raw_html[match.end(): match.end() + 2500]
- snippet_match = re.search(r'class="result__snippet"[^>]*>(.*?)</(?:a|div)>', block, re.S)
- snippet_raw = snippet_match.group(1) if snippet_match else ""
- snippet = re.sub(r"<.*?>", "", snippet_raw, flags=re.S)
- domain = urlparse(href).netloc.lower().removeprefix("www.")
- if not domain:
- continue
- results.append({
- "title": html.unescape(re.sub(r"\s+", " ", title)).strip(),
- "url": href,
- "snippet": html.unescape(re.sub(r"\s+", " ", snippet)).strip(),
- "domain": domain,
- })
- if len(results) >= 8:
- break
- return results
-
-def serp_snapshot_for_query(query: str | None, site_id: str, live: bool = False) -> dict[str, Any]:
- if not query:
- return {"source": "none", "status": "skipped", "reason": "no query available"}
- if not live:
- return {"source": "duckduckgo_html", "status": "skipped", "reason": "live SERP disabled"}
- url = "https://duckduckgo.com/html/?q=" + quote_plus(query)
- raw_html, meta = fetch_url_text(url)
- if not raw_html:
- return {"source": "duckduckgo_html", **meta}
- results = parse_duckduckgo_results(raw_html)
- if not results:
- return {"source": "duckduckgo_html", "status": "no_results_parsed", "query": query, "results": []}
- site_domain = site_id.lower().removeprefix("www.")
- own_positions = [idx + 1 for idx, result in enumerate(results) if site_domain in result.get("domain", "")]
- answer_like = any(re.search(r"\$\d|\b\d+\s*(?:-|to)\s*\$?\d+|per night|per day|average", " ".join([r.get("title", ""), r.get("snippet", "")]), re.I) for r in results[:5])
- return {
- "source": "duckduckgo_html",
- "status": "ok",
- "query": query,
- "results": results[:5],
- "own_domain_positions": own_positions,
- "answer_like_serp": answer_like,
- "competitor_domains": [r["domain"] for r in results[:5] if r.get("domain") and site_domain not in r["domain"]],
- }
-
-
-def analyze_page_packaging(page_snapshot: dict[str, Any], query: str | None) -> dict[str, Any]:
- text = (page_snapshot.get("above_the_fold_text") or "").lower()
- title = (page_snapshot.get("title") or "").lower()
- description = (page_snapshot.get("meta_description") or "").lower()
- q = (query or "").lower()
- wants_price = any(term in q for term in INFORMATIONAL_SERP_TERMS)
- price_answer = bool(re.search(r"\$\d|\b\d+\s*(?:-|to)\s*\$?\d+|per night|per day", text[:1400], re.I))
- cta = bool(re.search(r"\b(book|reserve|call|schedule|get quote|request quote)\b", text[:1600], re.I)) or bool(page_snapshot.get("cta_texts"))
- query_terms = [term for term in re.findall(r"[a-z]{4,}", q) if term not in {"much", "does", "cost", "board", "with", "what"}]
- missing_terms = [term for term in query_terms if term not in title and term not in description and term not in text[:1400]]
- observations = []
- if wants_price and not price_answer:
- observations.append("above-the-fold text does not give a fast price/range answer")
- if not cta:
- observations.append("no obvious booking/call CTA detected above the fold")
- if missing_terms:
- observations.append(f"query terms not visible early: {', '.join(missing_terms[:5])}")
- if page_snapshot.get("status") != "ok":
- observations.append(f"page snapshot unavailable: {page_snapshot.get('reason') or page_snapshot.get('status')}")
- return {
- "status": "ok" if page_snapshot.get("status") == "ok" else "partial",
- "has_fast_price_answer_above_fold": price_answer if wants_price else None,
- "has_booking_cta_above_fold": cta,
- "missing_query_terms_above_fold": missing_terms[:8],
- "observations": observations or ["no obvious above-the-fold packaging issue detected by static analysis"],
- }
-
-
-def matching_serp_result(serp: dict[str, Any], target: str | None) -> dict[str, Any] | None:
- if not target:
- return None
- parsed_target = urlparse(target)
- target_domain = parsed_target.netloc.lower().removeprefix("www.")
- target_path = parsed_target.path.rstrip("/")
- for result in serp.get("results") or []:
- parsed_result = urlparse(result.get("url") or "")
- result_domain = parsed_result.netloc.lower().removeprefix("www.")
- result_path = parsed_result.path.rstrip("/")
- if target_domain and target_domain == result_domain and target_path == result_path:
- return result
- return None
-
-
-def deep_dive_diagnostic(issue: dict[str, Any], site_id: str, site_profile: dict[str, Any] | None = None, live: bool = False) -> dict[str, Any]:
- query = issue.get("primary_query") or issue.get("diagnostic_query")
- query_source = "primary_query" if issue.get("primary_query") else ("diagnostic_query" if issue.get("diagnostic_query") else None)
- intent_class = issue.get("intent_class")
- target = issue.get("target") or issue.get("canonical_target") or issue.get("raw_target")
- if isinstance(target, str) and target.startswith("/"):
- target = f"https://www.{site_id}{target}"
- serp = serp_snapshot_for_query(query, site_id, live=live)
- page_snapshot = page_snapshot_for_url(target, site_profile, live=live)
- serp_result = matching_serp_result(serp, target)
- snippet_snapshot = page_snapshot
- if page_snapshot.get("status") != "ok" and serp_result:
- snippet_snapshot = {
- "source": "serp_result",
- "status": "ok",
- "title": serp_result.get("title"),
- "meta_description": serp_result.get("snippet"),
- "h1": None,
- }
- packaging = analyze_page_packaging(page_snapshot, query)
- depth = content_depth_score(page_snapshot, issue)
- zero_click_risk, zero_click_notes = zero_click_risk_for_query(query, intent_class)
- checks = {
- "serp_inspected": serp.get("status") == "ok" and bool(serp.get("results")),
- "current_snippet_inspected": snippet_snapshot.get("status") == "ok",
- "above_the_fold_inspected": packaging.get("status") == "ok",
- "zero_click_risk_accounted_for": True,
- }
- return {
- "status": "completed" if all(checks.values()) else "partial",
- "query": query,
- "query_source": query_source,
- "target": target,
- "checks": checks,
- "serp": serp,
- "current_snippet": {
- "source": snippet_snapshot.get("source"),
- "source_path": snippet_snapshot.get("source_path"),
- "status": snippet_snapshot.get("status"),
- "title": snippet_snapshot.get("title"),
- "meta_description": snippet_snapshot.get("meta_description"),
- "h1": snippet_snapshot.get("h1"),
- },
- "above_the_fold": packaging,
- "content_depth": depth,
- "zero_click_risk": {"level": zero_click_risk, "notes": zero_click_notes},
- }
-
-
-def add_deep_dive_diagnostics(issues: list[dict[str, Any]], site_id: str, site_profile: dict[str, Any] | None = None, live: bool = False) -> list[dict[str, Any]]:
- enriched = []
- for issue in issues:
- updated = dict(issue)
- if issue.get("recommended_action_type") in {"snippet_content_packaging", "meta_tags", "page_improvement", "query_intent_mapping", "local_intent_ownership", "content_refresh"}:
- updated["deep_dive"] = deep_dive_diagnostic(issue, site_id, site_profile, live=live)
- enriched.append(updated)
- return enriched
-
-
-def gate_result(name: str, status: str, notes: list[str] | str, **extra: Any) -> dict[str, Any]:
- return {
- "name": name,
- "status": status,
- "notes": notes if isinstance(notes, list) else [notes],
- **extra,
- }
-
-
-def gate_rollup(gates: list[dict[str, Any]]) -> str:
- statuses = {gate.get("status") for gate in gates}
- if "blocked" in statuses:
- return "blocked"
- if "warning" in statuses:
- return "warning"
- return "pass"
-
-
-def content_depth_score(page_snapshot: dict[str, Any], issue: dict[str, Any]) -> dict[str, Any]:
- text = (page_snapshot.get("above_the_fold_text") or "").lower()
- action_type = issue.get("recommended_action_type")
- word_count = int(page_snapshot.get("content_word_count") or 0)
- required_words = 700 if action_type in {"content_refresh", "page_improvement", "snippet_content_packaging"} else 300
- markers = {
- "use_cases": bool(re.search(r"\b(use case|for teams|for agencies|for owners|scenario|when to)\b", text)),
- "workflows": bool(re.search(r"\b(workflow|process|steps|how it works|approval|setup)\b", text)),
- "examples": bool(re.search(r"\b(example|sample|template|case study)\b", text)),
- "faqs": bool(re.search(r"\b(faq|questions?|asked)\b", text)),
- "differentiation": bool(re.search(r"\b(why us|different|unlike|advantage|proof|reviews?|licensed|certified|integrat)\b", text)),
- }
- marker_hits = sum(1 for present in markers.values() if present)
- score = round(clamp((word_count / max(required_words, 1)) * 0.55 + (marker_hits / len(markers)) * 0.45, 0.0, 1.0), 3)
- return {
- "score": score,
- "word_count": word_count,
- "required_words": required_words,
- "markers": markers,
- "marker_hits": marker_hits,
- }
-
-
-def cannibalization_gate(issue: dict[str, Any], business_context: dict[str, Any] | None) -> dict[str, Any]:
- if issue.get("recommended_action_type") not in {"internal_links", "local_intent_ownership"} and not issue.get("loser_pages"):
- return gate_result("cannibalization intent safety", "pass", "No competing-page signal on this action.")
- winner = issue.get("winner_page") or issue.get("target") or issue.get("canonical_target")
- loser_pages = [str(page) for page in issue.get("loser_pages") or []]
- page_roles = (business_context or {}).get("page_role_map") or {}
- winner_role = matching_page_role(winner, page_roles)
- loser_roles = {page: matching_page_role(page, page_roles) for page in loser_pages}
- supporting_losers = [page for page, role in loser_roles.items() if any(token in role for token in ["support", "informational", "noindex", "redirect", "canonical"])]
- if loser_pages and not winner_role:
- return gate_result(
- "cannibalization intent safety",
- "warning",
- "Competing pages exist; declare the canonical/intended owner and loser roles before redirect/canonical/internal-link changes.",
- winner_page=winner,
- loser_pages=loser_pages,
- loser_roles=loser_roles,
- )
- if loser_pages and len(supporting_losers) < len(loser_pages):
- return gate_result(
- "cannibalization intent safety",
- "warning",
- "Some competing pages are not marked as supporting/noindex/redirect/canonical; avoid consolidating until page roles are explicit.",
- winner_page=winner,
- winner_role=winner_role,
- loser_roles=loser_roles,
- )
- return gate_result(
- "cannibalization intent safety",
- "pass",
- "Canonical owner and supporting/retired competitors are explicit enough for approval review.",
- winner_page=winner,
- winner_role=winner_role,
- loser_roles=loser_roles,
- )
-
-
-def internal_link_graph_gate(issue: dict[str, Any], business_context: dict[str, Any] | None) -> dict[str, Any]:
- if issue.get("recommended_action_type") not in {"internal_links", "local_intent_ownership", "demand_seed_content", "content_refresh", "page_improvement", "snippet_content_packaging"}:
- return gate_result("internal link graph", "pass", "No internal-link plan required for this action type.")
- target = issue.get("target") or issue.get("canonical_target")
- source_target = issue.get("source_target")
- requirements = [
- "links from hub/category pages",
- "links from adjacent commercial/service pages",
- "links from relevant support/blog/docs pages",
- "remove links pointing to retired, redirected, noindex, or cannibal pages",
- ]
- if source_target:
- requirements.append("source support page links clearly to the preferred owner")
- context_has_roles = bool(page_role_entries(business_context))
- context_has_link_sources = bool((business_context or {}).get("internal_link_sources"))
- status = "pass" if issue.get("internal_link_plan") or context_has_link_sources or context_has_roles else "warning"
- notes = "Internal-link requirements are explicit; use them when drafting the approved patch." if status == "pass" else "No page-role map/internal-link plan is attached; approval should require link sources before publishing."
- return gate_result(
- "internal link graph",
- status,
- notes,
- target=target,
- source_target=source_target,
- required_links=requirements,
- configured_link_sources=(business_context or {}).get("internal_link_sources"),
- retired_or_cannibal_pages=(business_context or {}).get("retired_or_cannibal_pages"),
- )
-
-
-def content_depth_gate(issue: dict[str, Any]) -> dict[str, Any]:
- action_type = issue.get("recommended_action_type")
- if action_type not in {"demand_seed_content", "content_refresh", "page_improvement", "snippet_content_packaging"}:
- return gate_result("content depth", "pass", "No content-depth gate required for this action type.")
- if action_type == "demand_seed_content":
- deliverable = issue.get("recommended_deliverable") or {}
- required = deliverable.get("required_fields_per_bet") or []
- status = "pass" if {"slug", "target_query_cluster", "intent", "conversion_event", "CTA", "measurement_plan"}.issubset(set(required)) else "warning"
- return gate_result(
- "content depth",
- status,
- "Seed content brief requires concrete use cases, intent, CTA, and measurement fields before new pages are approved.",
- required_fields_per_bet=required,
- )
- depth = (issue.get("deep_dive") or {}).get("content_depth")
- if not depth:
- depth = {
- "score": 0.0,
- "word_count": 0,
- "required_words": 700,
- "markers": {},
- "marker_hits": 0,
- }
- status = "pass" if depth["score"] >= 0.7 else "warning"
- return gate_result(
- "content depth",
- status,
- "Content is deep enough for approval review." if status == "pass" else "Do not ship thin SEO copy; add workflows, examples, FAQs, and differentiating proof before publishing.",
- depth_score=depth,
- )
-
-
-def conversion_path_gate(issue: dict[str, Any], business_context: dict[str, Any] | None) -> dict[str, Any]:
- action_type = issue.get("recommended_action_type")
- if action_type == "technical_index_sitemap":
- return gate_result("conversion path", "pass", "Technical hygiene action does not need a conversion-path rewrite.")
- conversion = issue.get("conversion_opportunity") or {}
- context_events = context_values((business_context or {}).get("conversion_events"))
- deep_dive = issue.get("deep_dive") or {}
- cta_seen = ((deep_dive.get("above_the_fold") or {}).get("has_booking_cta_above_fold") is True)
- if conversion.get("matched_conversion_event") or cta_seen:
- return gate_result("conversion path", "pass", "Action has either a mapped conversion event or an above-the-fold CTA.", conversion_opportunity=conversion)
- notes = "Conversion events exist, but this action is not mapped to one yet." if context_events else "Business context is missing conversion events; approval should keep `complete_business_context` as a precondition."
- return gate_result("conversion path", "warning", notes, conversion_opportunity=conversion)
-
-
-def technical_index_gate(issue: dict[str, Any]) -> dict[str, Any]:
- finding = issue.get("technical_consistency_finding")
- if finding:
- return gate_result(
- "index/sitemap consistency",
- "blocked" if issue.get("recommended_action_type") != "technical_index_sitemap" else "pass",
- "Noindex/sitemap/redirect/internal-link inconsistency is explicit and actionable.",
- finding=finding,
- )
- return gate_result("index/sitemap consistency", "pass", "No sitemap/indexing conflict attached to this action.")
-
-
-def no_ship_review_gate(issue: dict[str, Any], prior_gates: list[dict[str, Any]]) -> dict[str, Any]:
- notes = []
- if any(gate.get("status") == "blocked" for gate in prior_gates):
- notes.append("blocked prerequisite gate exists")
- if cannibalization := next((gate for gate in prior_gates if gate.get("name") == "cannibalization intent safety"), None):
- if cannibalization.get("status") == "warning":
- notes.append("cannibalization ownership is not explicit")
- conversion = next((gate for gate in prior_gates if gate.get("name") == "conversion path"), None)
- if conversion and conversion.get("status") != "pass":
- notes.append("conversion path is weak or unmapped")
- public_text = json.dumps({
- "title": issue.get("title"),
- "notes": issue.get("operator_judgment_notes"),
- "deliverable": issue.get("recommended_deliverable"),
- }, default=str).lower()
- if re.search(r"\b(secret|private strategy|internal-only|do not disclose|confidential)\b", public_text):
- notes.append("possible public strategy/confidentiality leakage in proposed copy/brief")
- status = "blocked" if any("blocked prerequisite" in note or "confidentiality" in note for note in notes) else ("warning" if notes else "pass")
- return gate_result(
- "Gemini NO-SHIP review",
- status,
- notes or "NO-SHIP checks passed: no public strategy leakage, unresolved cannibalization blocker, CTA friction blocker, or technical SEO conflict detected.",
- template_checks=[
- "public strategy leakage",
- "cannibalization/intent ownership",
- "CTA and conversion friction",
- "index/sitemap/canonical/internal-link consistency",
- ],
- )
-
-
-def add_seo_review_gates(issues: list[dict[str, Any]], business_context: dict[str, Any] | None = None) -> list[dict[str, Any]]:
- enriched = []
- for issue in issues:
- updated = dict(issue)
- gates = [
- technical_index_gate(updated),
- cannibalization_gate(updated, business_context),
- internal_link_graph_gate(updated, business_context),
- content_depth_gate(updated),
- conversion_path_gate(updated, business_context),
- ]
- gates.append(no_ship_review_gate(updated, gates))
- updated["seo_review_gates"] = gates
- updated["seo_review_gate_status"] = gate_rollup(gates)
- if updated["seo_review_gate_status"] == "blocked":
- blockers = list(updated.get("approval_blockers") or [])
- blockers.append("SEO review gates blocked approval")
- updated["approval_blockers"] = list(dict.fromkeys(blockers))
- enriched.append(updated)
- return enriched
-
-
-def context_values(value: Any) -> list[Any]:
- if value is None or value == "":
- return []
- if isinstance(value, (list, dict)) and not value:
- return []
- if isinstance(value, list):
- return [item for nested in value for item in context_values(nested)]
- if isinstance(value, dict):
- return [item for nested in value.values() for item in context_values(nested)]
- return [value]
-
-
-def context_text(value: Any) -> str:
- return " ".join(str(item).lower() for item in context_values(value))
-
-
-def page_role_entries(business_context: dict[str, Any] | None) -> list[tuple[str, str]]:
- page_roles = (business_context or {}).get("page_role_map") or {}
- entries: list[tuple[str, str]] = []
- if isinstance(page_roles, dict):
- for locator, role in page_roles.items():
- entries.append((str(locator), context_text(role)))
- elif isinstance(page_roles, list):
- for item in page_roles:
- if isinstance(item, dict):
- locator = item.get("url") or item.get("path") or item.get("page") or item.get("target")
- role = item.get("role") or item.get("page_role") or item.get("type") or item
- if locator:
- entries.append((str(locator), context_text(role)))
- else:
- entries.append((str(item), str(item).lower()))
- return entries
-
-
-def matching_page_role(reference_url: str | None, page_roles: Any) -> str:
- if not reference_url:
- return ""
- parsed = urlparse(reference_url)
- target_path = parsed.path.rstrip("/") or "/"
- target_url = reference_url.rstrip("/")
- pseudo_context = {"page_role_map": page_roles}
- for locator, role_text in page_role_entries(pseudo_context):
- locator_url = url_for_context_path(reference_url, locator).rstrip("/")
- locator_path = urlparse(locator_url).path.rstrip("/") or "/"
- if locator_url == target_url or locator_path == target_path:
- return role_text
- return ""
-
-
-def business_context_local_label(business_context: dict[str, Any] | None) -> str:
- context = business_context or {}
- geography = str(context.get("primary_geography") or "").strip()
- if geography:
- return geography
- location_priorities = context.get("location_priorities")
- if isinstance(location_priorities, dict):
- priority_order = {"high": 0, "medium": 1, "low": 2}
- ranked_locations = sorted(
- location_priorities.items(),
- key=lambda item: priority_order.get(str((item[1] or {}).get("priority", "") if isinstance(item[1], dict) else "").lower(), 3),
- )
- if ranked_locations:
- return "/".join(str(location) for location, _details in ranked_locations[:3])
- locations = context.get("target_locations") or context.get("locations") or location_priorities or []
- values = context_values(locations)
- if values:
- return "/".join(str(value) for value in values[:3])
- return "local"
-
-def url_for_context_path(reference_url: str | None, path: str) -> str:
- if path.startswith("http://") or path.startswith("https://"):
- return path
- parsed = urlparse(reference_url or "")
- scheme = parsed.scheme or "https"
- netloc = parsed.netloc
- if not netloc:
- return path
- return urlunparse((scheme, netloc, path if path.startswith("/") else f"/{path}", "", "", ""))
-
-
-def query_matches_any(query: str | None, terms: Any) -> bool:
- q = (query or "").lower()
- if not q:
- return False
- return any(str(term).lower() in q for term in context_values(terms) if term)
-
-
-def context_page_candidates(business_context: dict[str, Any] | None, reference_url: str | None) -> dict[str, str | None]:
- local_research = None
- transactional = None
- support = None
- for locator, role_text in page_role_entries(business_context):
- url = url_for_context_path(reference_url, locator)
- if local_research is None and "local" in role_text and any(term in role_text for term in ["commercial", "research", "price", "cost"]):
- local_research = url
- if transactional is None and "transactional" in role_text:
- transactional = url
- if support is None and ("support" in role_text or "informational" in role_text):
- support = url
- return {"local_research": local_research, "transactional": transactional, "support": support}
-
-
-def business_context_says_national_deprioritized(business_context: dict[str, Any] | None) -> bool:
- priority = (business_context or {}).get("target_customer_priority") or {}
- deprioritized = priority.get("deprioritized", []) if isinstance(priority, dict) else []
- text = context_text(deprioritized)
- return "national" in text or "outside service area" in text or "non-local" in text
-
-
-def booking_intent_terms(hierarchy: Any) -> tuple[list[Any], list[Any]]:
- if isinstance(hierarchy, dict):
- return context_values(hierarchy.get("highest_priority", [])), context_values(hierarchy.get("supporting_only", []))
- ordered = context_values(hierarchy)
- if not ordered:
- return [], []
- high_priority = ordered[:1]
- supporting = ordered[1:]
- informational_markers = ("cost", "price", "how much", "average", "guide", "research", "compare")
- for term in ordered:
- if any(marker in str(term).lower() for marker in informational_markers) and term not in supporting:
- supporting.append(term)
- return high_priority, supporting
-
-
-def weighted_terms_match_score(text: str, weighted_terms: Any, default: float = 1.0) -> tuple[float, str | None]:
- """Return the strongest business value weight whose term appears in text.
-
- Supports either {"term": 1.4} or [{"term": "x", "weight": 1.4}].
- """
- haystack = (text or "").lower()
- best = (default, None)
- if isinstance(weighted_terms, dict):
- iterable = weighted_terms.items()
- elif isinstance(weighted_terms, list):
- iterable = []
- for item in weighted_terms:
- if isinstance(item, dict):
- term = item.get("term") or item.get("service") or item.get("product") or item.get("query")
- weight = item.get("weight") or item.get("value") or item.get("score")
- iterable.append((term, weight))
- else:
- iterable.append((item, default))
- else:
- iterable = []
- for term, raw_weight in iterable:
- if not term:
- continue
- try:
- weight = float(raw_weight)
- except (TypeError, ValueError):
- weight = default
- if str(term).lower() in haystack and weight > best[0]:
- best = (weight, str(term))
- return best
-
-
-def conversion_event_weight_for_issue(issue: dict[str, Any], business_context: dict[str, Any] | None) -> tuple[float, str | None]:
- events = (business_context or {}).get("conversion_events") or []
- target = str(issue.get("target") or issue.get("canonical_target") or issue.get("raw_target") or "").lower()
- query = str(issue.get("primary_query") or issue.get("diagnostic_query") or "").lower()
- title = str(issue.get("title") or "").lower()
- text = " ".join([target, query, title])
- best_weight = 1.0
- best_event = None
- iterable = events.values() if isinstance(events, dict) else events
- for event in iterable:
- if isinstance(event, str):
- event = {"name": event}
- if not isinstance(event, dict):
- continue
- name = str(event.get("name") or event.get("event") or event.get("id") or "conversion")
- paths = context_values(event.get("paths") or event.get("page_paths") or event.get("landing_pages") or event.get("targets") or [])
- terms = context_values(event.get("queries") or event.get("intent_terms") or event.get("terms") or [])
- target_path = urlparse(target).path.rstrip("/") or "/"
- path_match = False
- for path in paths:
- if not path:
- continue
- raw_path = str(path).lower().rstrip("/") or "/"
- parsed_path = urlparse(raw_path).path.rstrip("/") or raw_path
- if target_path == parsed_path or target.endswith(raw_path):
- path_match = True
- break
- match = path_match or any(str(term).lower() in text for term in terms if term)
- if not match and not paths and not terms:
- match = any(token in text for token in ["book", "quote", "contact", "signup", "connect", "demo"])
- if not match:
- continue
- try:
- weight = float(event.get("weight") or event.get("value_weight") or event.get("business_value") or 1.15)
- except (TypeError, ValueError):
- weight = 1.15
- if weight > best_weight:
- best_weight = weight
- best_event = name
- return best_weight, best_event
-
-
-def page_role_conversion_weight(issue: dict[str, Any], business_context: dict[str, Any] | None) -> tuple[float, str]:
- target = issue.get("target") or issue.get("canonical_target") or issue.get("raw_target")
- role = matching_page_role(target, (business_context or {}).get("page_role_map") or {})
- target_path = urlparse(target or "").path.rstrip("/") or "/"
- if not role and target_path != "/" and is_service_page(target):
- role = "service/transactional page inferred from URL"
- role_text = role.lower()
- if any(token in role_text for token in ["transactional", "booking", "signup", "quote", "lead", "conversion"]):
- return 1.35, role or "transactional page"
- if any(token in role_text for token in ["local", "commercial", "service", "pricing"]):
- return 1.15, role or "commercial page"
- if any(token in role_text for token in ["support", "informational", "blog", "guide", "docs"]):
- return 0.7, role or "supporting informational page"
- return 1.0, role or "unknown"
-
-
-def stage_conversion_multiplier(site_stage: dict[str, Any], issue: dict[str, Any]) -> tuple[float, list[str]]:
- stage = (site_stage or {}).get("stage")
- action_type = issue.get("recommended_action_type")
- notes: list[str] = []
- if stage == "seed":
- if action_type == "demand_seed_content":
- notes.append("seed-stage site: prioritize creating qualified demand-capture assets before optimizing sparse GSC noise")
- return 1.25, notes
- notes.append("seed-stage site: GSC evidence is sparse, so require external demand validation")
- return 0.85, notes
- if stage == "recover" and action_type in {"content_refresh", "page_improvement", "snippet_content_packaging"}:
- notes.append("recover-stage site: recent losses get extra priority")
- return 1.15, notes
- if stage == "harvest" and action_type in {"meta_tags", "snippet_content_packaging", "internal_links", "local_intent_ownership"}:
- notes.append("harvest-stage site: enough impressions exist to optimize existing qualified demand")
- return 1.1, notes
- return 1.0, notes
-
-
-def conversion_opportunity_for_issue(issue: dict[str, Any], business_context: dict[str, Any] | None, site_stage: dict[str, Any]) -> dict[str, Any]:
- query = str(issue.get("primary_query") or issue.get("diagnostic_query") or "")
- target = str(issue.get("target") or issue.get("canonical_target") or issue.get("raw_target") or "")
- title = str(issue.get("title") or "")
- combined = " ".join([query, target, title])
- service_weight, matched_service = weighted_terms_match_score(combined, (business_context or {}).get("service_value_weights"), default=1.0)
- role_weight, role = page_role_conversion_weight(issue, business_context)
- event_weight, matched_event = conversion_event_weight_for_issue(issue, business_context)
- intent_weight = float((issue.get("score_components") or {}).get("business_intent_score") or 1.0)
- if is_branded_query(query, (business_context or {}).get("brand_terms") or []):
- intent_weight = min(intent_weight, 0.85)
- stage_weight, stage_notes = stage_conversion_multiplier(site_stage, issue)
- has_context = bool(business_context)
- context_weight = 1.0 if has_context else 0.95
- multiplier = clamp(service_weight * role_weight * event_weight * intent_weight * stage_weight * context_weight, 0.35, 2.25)
- notes = []
- if matched_service:
- notes.append(f"matched high-value service/product: {matched_service}")
- if matched_event:
- notes.append(f"maps to conversion event: {matched_event}")
- if role != "unknown":
- notes.append(f"page role: {role}")
- if not has_context:
- notes.append("business context missing; conversion weighting is conservative")
- notes.extend(stage_notes)
- return {
- "multiplier": round(multiplier, 3),
- "service_value_weight": round(service_weight, 3),
- "matched_service": matched_service,
- "page_role_weight": round(role_weight, 3),
- "page_role": role,
- "conversion_event_weight": round(event_weight, 3),
- "matched_conversion_event": matched_event,
- "intent_weight": round(intent_weight, 3),
- "stage_weight": round(stage_weight, 3),
- "stage": (site_stage or {}).get("stage"),
- "notes": notes,
- }
-
-
-def apply_conversion_weighting(candidates: list[dict[str, Any]], business_context: dict[str, Any] | None, site_stage: dict[str, Any]) -> list[dict[str, Any]]:
- weighted = []
- for candidate in candidates:
- updated = dict(candidate)
- opportunity = conversion_opportunity_for_issue(updated, business_context, site_stage)
- raw_priority = float(updated.get("priority_score", updated.get("base_priority", 0.5)))
- updated["raw_priority_score"] = round(raw_priority, 3)
- updated["conversion_opportunity"] = opportunity
- updated["priority_score"] = round(raw_priority * float(opportunity["multiplier"]), 3)
- score_components = dict(updated.get("score_components") or {})
- score_components["conversion_multiplier"] = opportunity["multiplier"]
- score_components["conversion_weighted_priority_score"] = updated["priority_score"]
- updated["score_components"] = score_components
- notes = list(updated.get("operator_judgment_notes") or [])
- notes.extend(opportunity.get("notes") or [])
- updated["operator_judgment_notes"] = list(dict.fromkeys(notes))
- weighted.append(updated)
- return weighted
-
-
-def seed_demand_issue(site_id: str, analysis: dict[str, Any], site_profile: dict[str, Any] | None, business_context: dict[str, Any] | None, site_stage: dict[str, Any]) -> dict[str, Any]:
- summary = analysis.get("summary") or {}
- top_pages = analysis.get("top_pages") or []
- top_queries = analysis.get("top_queries") or []
- canonical = (site_profile or {}).get("canonical_url") or f"https://{site_id}"
- visible_pages = [str(page.get("page")) for page in top_pages[:5] if page.get("page")]
- visible_queries = [str(query.get("query")) for query in top_queries[:8] if query.get("query")]
- context = business_context or {}
- conversion_events = context_values(context.get("conversion_events"))[:5]
- recommended_deliverable = {
- "artifact_type": "seed_content_portfolio_brief",
- "goal": "Create qualified organic demand where GSC does not yet have enough data to optimize.",
- "minimum_bets": 3,
- "demand_sources": [
- "Google Ads/search-term data",
- "Keyword Planner",
- "competitor SERPs",
- "customer/sales language",
- "existing product/integration docs",
- ],
- "page_bet_types": [
- "high-intent integration/setup page",
- "comparison or alternative page",
- "use-case landing page",
- "problem/solution page with conversion CTA",
- ],
- "required_fields_per_bet": ["slug", "target_query_cluster", "intent", "conversion_event", "title", "h1", "CTA", "measurement_plan"],
- "known_gsc_pages": visible_pages,
- "visible_gsc_queries": visible_queries,
- "known_conversion_events": conversion_events,
- "success_metric": "qualified organic impressions/clicks plus mapped conversion events by landing page",
- }
- return make_issue(
- f"Seed qualified organic demand for {site_id}",
- "warning",
- 0.62,
- [
- f"Only {summary.get('clicks', 0):g} clicks and {summary.get('impressions', 0):g} impressions in the current GSC window.",
- "Sparse GSC means the operator should generate validated demand-capture bets instead of reporting no issue.",
- ],
- "demand_seed_content",
- target=canonical,
- base_priority=0.55,
- priority_score=0.55,
- expected_click_delta=None,
- expected_impact="Prepare an approval-ready portfolio of 3–5 high-intent organic landing/content bets, then measure first impressions/clicks/conversions.",
- approval_artifact_type="seed_content_portfolio_brief",
- recommended_deliverable=recommended_deliverable,
- site_stage=site_stage,
- score_components={
- "expected_impact": 0.55,
- "confidence_score": 0.62,
- "goal_alignment_score": 1.0,
- "actionability_score": 0.85,
- "url_quality_score": 1.0,
- },
- operator_judgment_notes=[
- "seed mode: use external demand sources because GSC has too little volume",
- "human approval is still required before publishing new pages or content",
- ],
- )
-
-def apply_business_context_to_issue(issue: dict[str, Any], business_context: dict[str, Any] | None, site_id: str | None = None) -> dict[str, Any]:
- if not business_context:
- return issue
- query = issue.get("primary_query")
- hierarchy = business_context.get("booking_intent_hierarchy") or {}
- high_priority_terms, supporting_terms = booking_intent_terms(hierarchy)
- page_roles = business_context.get("page_role_map") or {}
- target = issue.get("target") or issue.get("canonical_target") or issue.get("raw_target")
- reference_url = target or (business_context or {}).get("target_url") or (f"https://www.{site_id}" if site_id else None)
- role_text = matching_page_role(target, page_roles)
- is_support_query = query_matches_any(query, supporting_terms)
- is_high_priority_query = query_matches_any(query, high_priority_terms)
- is_support_page = "support" in role_text or "informational" in role_text
- national_deprioritized = business_context_says_national_deprioritized(business_context)
- candidates = context_page_candidates(business_context, reference_url)
- context_support_page = candidates.get("support")
-
- if issue.get("recommended_action_type") in {"snippet_content_packaging", "meta_tags", "query_intent_mapping"} and is_support_query and not is_high_priority_query and (is_support_page or context_support_page or national_deprioritized):
- source_support_page = target or context_support_page or reference_url
- preferred_owner = candidates.get("local_research") or candidates.get("transactional") or source_support_page
- updated = dict(issue)
- updated["recommended_action_type"] = "local_intent_ownership"
- locality = business_context_local_label(business_context)
- updated["title"] = f"Resolve {locality} intent ownership for '{query}'"
- updated["target"] = preferred_owner
- updated["canonical_target"] = preferred_owner
- updated["source_target"] = source_support_page
- updated["consolidation_targets"] = {
- "source_support_page": source_support_page,
- "preferred_local_owner": preferred_owner,
- "conversion_target": candidates.get("transactional"),
- }
- updated["expected_click_delta"] = None
- updated["expected_impact"] = f"Clarify which {locality} page should own this intent; optimize for qualified local outcomes, not raw support-page CTR."
- updated.setdefault("operator_judgment_notes", [])
- ownership_notes = [
- "supporting intent should route qualified demand to the best local owner",
- "decide whether to consolidate, canonicalize, redirect, or internally link from the support page to the local owner",
- ]
- if national_deprioritized:
- ownership_notes = [
- "business context deprioritizes national informational clicks",
- "do not optimize the support page for broad national CTR unless it routes qualified local intent",
- *ownership_notes,
- ]
- updated["operator_judgment_notes"] = [*updated["operator_judgment_notes"], *ownership_notes]
- score_components = dict(updated.get("score_components", {}))
- score_components["business_context_goal_score"] = 1.0
- if national_deprioritized:
- score_components["national_click_discount"] = 0.25
- updated["score_components"] = score_components
- updated["business_context_adjustment"] = {
- "from_action_type": issue.get("recommended_action_type"),
- "reason": f"supporting query is not the direct business goal; prioritize {locality} ownership",
- "preferred_local_owner": preferred_owner,
- "source_support_page": source_support_page,
- }
- raw_priority = float(issue.get("priority_score", 0))
- if national_deprioritized:
- updated["priority_score"] = round(raw_priority * score_components["national_click_discount"], 3)
- return updated
- return issue
-
-
-def apply_business_context(candidates: list[dict[str, Any]], business_context: dict[str, Any] | None, site_id: str | None = None) -> list[dict[str, Any]]:
- return [apply_business_context_to_issue(candidate, business_context, site_id=site_id) for candidate in candidates]
-
-
-BUSINESS_IMPACT_CONTEXT_FIELDS = {
- "service_value_weights": "Relative revenue/margin value by service or product line",
- "target_customer_priority": "Priority customer segments (local buyers, high-margin segments, urgent-need customers, recurring customers, etc.)",
- "location_priorities": "Location-level priority/capacity/margin context",
- "conversion_events": "Organic conversion events or booking funnel signals",
- "booking_intent_hierarchy": "Which query intents are most likely to become bookings",
- "local_proof_points": "Local differentiators to use in snippets/content",
- "serp_competitor_positioning": "Competitor/SERP positioning for priority queries",
- "page_role_map": "Transactional vs informational role for important pages",
-}
-
-
-def business_context_gaps(business_context: dict[str, Any] | None) -> list[dict[str, str]]:
- context = business_context or {}
- gaps = []
- for field, reason in BUSINESS_IMPACT_CONTEXT_FIELDS.items():
- value = context.get(field)
- if value in (None, "", [], {}):
- gaps.append({"field": field, "why_it_matters": reason})
- return gaps
-
-
-def business_context_questions(gaps: list[dict[str, str]]) -> list[str]:
- wanted = {gap["field"] for gap in gaps}
- questions = []
- if "service_value_weights" in wanted:
- questions.append("Rank services or product lines by business value/margin.")
- if "target_customer_priority" in wanted:
- questions.append("Which customer segments matter most: local buyers, high-margin services, recurring customers, urgent-need customers, enterprise accounts, etc.?")
- if "location_priorities" in wanted:
- questions.append("Which markets or service areas should SEO prioritize right now, and are any capacity-constrained?")
- if "conversion_events" in wanted:
- questions.append("What organic conversion signals should count: form starts, completed purchases/bookings, calls, quote requests, CRM events, GA4 events?")
- if "booking_intent_hierarchy" in wanted:
- questions.append("Give a rough intent ranking: e.g. high-intent local/service query > category query > cost/research query > broad informational query.")
- if "local_proof_points" in wanted:
- questions.append("What proof points should snippets emphasize: response time, certifications, warranty, reviews, pricing transparency, local coverage, multi-location coverage?")
- if "serp_competitor_positioning" in wanted:
- questions.append("For priority queries, who must we beat or differentiate from: direct competitors, marketplaces/directories, map-pack results, review sites, or national brands?")
- if "page_role_map" in wanted:
- questions.append("Which pages are transactional landing pages vs informational support pages?")
- return questions
-
-
-def context_quality_check(business_context: dict[str, Any] | None) -> dict[str, Any]:
- gaps = business_context_gaps(business_context)
- missing = len(gaps)
- total = len(BUSINESS_IMPACT_CONTEXT_FIELDS)
- score = round((total - missing) / total, 3)
- status = "pass" if score >= 0.75 else "warning"
- return {
- "score": score,
- "status": status,
- "missing_fields": gaps,
- "questions": business_context_questions(gaps),
- }
-
-
-def build_business_context_request(site_id: str, context_check: dict[str, Any]) -> dict[str, Any] | None:
- if context_check["score"] >= 0.75:
- return None
- return {
- "item_id": f"context_request_{site_id}_business_impact",
- "type": "business_context_request",
- "status": "pending_input",
- "priority": "high",
- "notes": "Complete business-impact context before approving SEO content, snippet, metadata, redirect, or internal-link actions.",
- "business_context_score": context_check["score"],
- "business_context_gaps": context_check["missing_fields"],
- "business_context_questions": context_check["questions"],
- "output_path": f"~/.toprank/business-context/{site_id}.json",
- "blocks_auto_approval": True,
- }
-
-
-def build_payload(
- site_id: str,
- analysis: dict[str, Any],
- learned: dict[str, Any],
- goal: dict[str, Any] | None,
- business_context: dict[str, Any] | None = None,
- site_profile: dict[str, Any] | None = None,
- live_diagnostics: bool = False,
-) -> dict[str, Any]:
- metrics = metric_snapshot_from_analysis(analysis)
- primary_metric = None
- if goal and goal.get("primary_metric"):
- primary_metric = goal["primary_metric"]
- if not primary_metric:
- primary_metric = DEFAULT_PRIMARY_METRIC if DEFAULT_PRIMARY_METRIC in metrics else next(iter(metrics.keys()), DEFAULT_PRIMARY_METRIC)
-
- context_check = context_quality_check(business_context)
- site_stage = infer_site_stage(analysis, metrics, business_context)
- candidates = dedupe_candidates(apply_business_context(derive_candidate_issues(analysis), business_context, site_id=site_id))
- candidates = apply_conversion_weighting(candidates, business_context, site_stage)
- ranked = apply_prioritization(candidates, learned, primary_metric)
- if site_stage.get("stage") == "seed":
- # Sparse-GSC sites need demand creation first. Keep noisy GSC-derived items as
- # supporting diagnostics, but do not let a single low-volume CTR gap become
- # the approval proposal ahead of the seed content portfolio.
- seed_issue = seed_demand_issue(site_id, analysis, site_profile, business_context, site_stage)
- seed_ranked = apply_prioritization(apply_conversion_weighting([seed_issue], business_context, site_stage), learned, primary_metric)
- top_issues = [*seed_ranked, *ranked[:2]]
- elif ranked:
- top_issues = ranked[:3]
- else:
- top_issues = [
- make_issue(
- "No major issue surfaced from the automated weekly review.",
- "info",
- 0.5,
- ["Use the canonical seo-analysis skill for deeper manual diagnosis if needed."],
- "manual_review",
- base_priority=0.3,
- )
- ]
- top_issues = [
- {
- **issue,
- "priority_score": issue.get("priority_score", round(issue.get("base_priority", 0.3), 3)),
- "learned_multiplier": issue.get("learned_multiplier", 1.0),
- "best_practice_alignment": best_practice_alignment_for_issue(issue),
- }
- for issue in top_issues
- ]
- top_issues = add_deep_dive_diagnostics(top_issues, site_id, site_profile, live=live_diagnostics)
- top_issues = add_seo_review_gates(top_issues, business_context)
-
- summary = analysis.get("summary") or {}
- non_brand_clicks = metrics.get(primary_metric)
- action_entries = []
- queue_items = []
- context_request = build_business_context_request(site_id, context_check)
- if context_request:
- queue_items.append(context_request)
- proposal_written = False
- for idx, issue in enumerate(top_issues, start=1):
- action_id = f"weekly_action_{idx:02d}"
- action_type = issue["recommended_action_type"]
- readiness = approval_readiness_for_issue(issue)
- issue["approval_ready"] = readiness["approval_ready"]
- issue["approval_blockers"] = readiness["approval_blockers"]
- expected_delta = issue.get("expected_click_delta")
- expected_impact = issue.get("expected_impact") or f"Address {action_type.replace('_', ' ')} opportunity surfaced in the weekly review."
- if isinstance(expected_delta, (int, float)) and expected_delta > 0:
- expected_impact = f"Estimated upside: ~{expected_delta:g} incremental clicks if the opportunity is fixed."
- elif isinstance(expected_delta, (int, float)) and expected_delta < 0:
- expected_impact = f"Regression signal: ~{abs(expected_delta):g} lost clicks vs prior period; investigate before changing content."
- action_entries.append(
- {
- "action_id": action_id,
- "title": issue["title"],
- "type": action_type,
- "priority_score": issue["priority_score"],
- "expected_impact": expected_impact,
- "requires_approval": action_type not in {"manual_review"},
- "reversibility": "high",
- "owner": "operator",
- "target": issue.get("target"),
- "raw_target": issue.get("raw_target"),
- "canonical_target": issue.get("canonical_target"),
- "score_components": issue.get("score_components", {}),
- "operator_judgment_notes": issue.get("operator_judgment_notes", []),
- "deep_dive": issue.get("deep_dive"),
- "business_context_adjustment": issue.get("business_context_adjustment"),
- "conversion_opportunity": issue.get("conversion_opportunity"),
- "raw_priority_score": issue.get("raw_priority_score"),
- "site_stage": site_stage,
- "best_practice_alignment": issue.get("best_practice_alignment"),
- "seo_review_gates": issue.get("seo_review_gates", []),
- "seo_review_gate_status": issue.get("seo_review_gate_status"),
- "primary_query": issue.get("primary_query"),
- "diagnostic_query": issue.get("diagnostic_query"),
- "query_decomposition": issue.get("query_decomposition"),
- "top_losing_queries": issue.get("top_losing_queries", []),
- "approval_ready": issue.get("approval_ready", False),
- "approval_blockers": issue.get("approval_blockers", []),
- "consolidation_targets": issue.get("consolidation_targets"),
- "source_target": issue.get("source_target"),
- "approval_artifact_type": issue.get("approval_artifact_type"),
- "recommended_deliverable": issue.get("recommended_deliverable"),
- "needs_business_context": context_check["score"] < 0.75,
- "learned_multiplier": issue.get("learned_multiplier", 1.0),
- }
- )
- if not proposal_written and issue.get("approval_ready") and action_type != "manual_review":
- proposal_written = True
- queue_items.append(
- {
- "item_id": f"proposal_{site_id}_{action_type}_{analysis['period']['days']}d",
- "type": "action_proposal",
- "status": "pending_approval",
- "notes": f"Approve, reject, or revise the weekly action: {issue['title']}",
- "action_id": action_id,
- "action_type": action_type,
- "target": issue.get("target"),
- "raw_target": issue.get("raw_target"),
- "canonical_target": issue.get("canonical_target"),
- "primary_metric": primary_metric,
- "primary_direction": "higher_better" if "position" not in primary_metric else "lower_better",
- "success_threshold_pct": 0.1,
- "baseline_metrics": metrics,
- "guardrail_metrics": [],
- "follow_up_after_approval_days": 14,
- "approval_required": True,
- "score_components": issue.get("score_components", {}),
- "operator_judgment_notes": issue.get("operator_judgment_notes", []),
- "deep_dive": issue.get("deep_dive"),
- "business_context_adjustment": issue.get("business_context_adjustment"),
- "conversion_opportunity": issue.get("conversion_opportunity"),
- "raw_priority_score": issue.get("raw_priority_score"),
- "site_stage": site_stage,
- "best_practice_alignment": issue.get("best_practice_alignment"),
- "seo_review_gates": issue.get("seo_review_gates", []),
- "seo_review_gate_status": issue.get("seo_review_gate_status"),
- "primary_query": issue.get("primary_query"),
- "diagnostic_query": issue.get("diagnostic_query"),
- "query_decomposition": issue.get("query_decomposition"),
- "top_losing_queries": issue.get("top_losing_queries", []),
- "approval_ready": issue.get("approval_ready", False),
- "approval_blockers": issue.get("approval_blockers", []),
- "consolidation_targets": issue.get("consolidation_targets"),
- "source_target": issue.get("source_target"),
- "approval_artifact_type": issue.get("approval_artifact_type"),
- "recommended_deliverable": issue.get("recommended_deliverable"),
- "business_context_score": context_check["score"],
- "business_context_gaps": context_check["missing_fields"],
- "business_context_questions": context_check["questions"],
- "approval_preconditions": ["complete_business_context"] if context_check["score"] < 0.75 else [],
- }
- )
-
- return {
- "trigger": {
- "type": "weekly_review",
- "notes": f"Automated weekly review for {site_id}.",
- },
- "state_snapshot": {
- "site_id": site_id,
- "summary": f"{summary.get('clicks', 0)} clicks, {summary.get('impressions', 0)} impressions, CTR {summary.get('ctr', 0)}%, position {summary.get('position', 0)}.",
- "open_issues": [
- {
- "title": issue["title"],
- "severity": issue["severity"],
- "confidence": issue["confidence"],
- }
- for issue in top_issues
- ],
- "recent_actions": [],
- "metrics": metrics,
- "site_stage": site_stage,
- },
- "audit": {
- "site_id": site_id,
- "summary": f"Automated weekly review surfaced {len(top_issues)} prioritized issue(s).",
- "issues": top_issues,
- "metrics": metrics,
- "site_stage": site_stage,
- },
- "action_plan": {
- "site_id": site_id,
- "goal_id": goal.get("goal_id") if goal else None,
- "site_stage": site_stage,
- "actions": action_entries,
- },
- "verification": {
- "site_id": site_id,
- "checks": [
- {"name": "gsc analysis available", "status": "pass", "notes": "Weekly review generated from Search Console data."},
- {"name": "action plan generated", "status": "pass", "notes": f"Primary metric for follow-up scoring: {primary_metric}."},
- {"name": "site stage playbook", "status": "pass", "notes": site_stage.get("reason", "Site stage inferred."), "site_stage": site_stage},
- {
- "name": "recommendation quality gate",
- "status": "pass" if top_issues[0].get("approval_ready") else "warning",
- "notes": "; ".join(top_issues[0].get("approval_blockers") or top_issues[0].get("operator_judgment_notes", [])) or "Top action has explicit score components for operator review.",
- },
- {
- "name": "deep dive diagnostics",
- "status": "pass" if top_issues[0].get("deep_dive", {}).get("status") == "completed" else "warning",
- "notes": "Top recommendation includes SERP, snippet, above-the-fold, and zero-click diagnostics before edit approval." if top_issues[0].get("deep_dive") else "No deep dive was needed for the top recommendation.",
- "deep_dive_status": top_issues[0].get("deep_dive", {}).get("status"),
- "checks": top_issues[0].get("deep_dive", {}).get("checks", {}),
- },
- {
- "name": "best practice alignment",
- "status": "pass" if top_issues[0].get("best_practice_alignment", {}).get("primary_area") not in {None, "", "unmapped"} else "warning",
- "notes": top_issues[0].get("best_practice_alignment", {}).get("primary_area_label", "Top recommendation is not mapped to a MECE SEO best-practice lane."),
- "reference": SEO_BEST_PRACTICE_REFERENCE,
- "alignment": top_issues[0].get("best_practice_alignment", {}),
- },
- {
- "name": "SEO review gates",
- "status": "pass" if top_issues[0].get("seo_review_gate_status") == "pass" else "warning",
- "notes": f"Gate rollup: {top_issues[0].get('seo_review_gate_status') or 'unknown'}.",
- "gates": top_issues[0].get("seo_review_gates", []),
- },
- {
- "name": "business impact context",
- "status": context_check["status"],
- "notes": f"Business-impact context completeness: {context_check['score']:.0%}. Missing: {', '.join(gap['field'] for gap in context_check['missing_fields']) or 'none'}.",
- "questions": context_check["questions"],
- },
- ],
- "follow_up_due": None,
- },
- "queue_items": queue_items,
- }
-
-
-def run_analysis(site_property: str, days: int, brand_terms: str | None) -> dict[str, Any]:
- with tempfile.NamedTemporaryFile(prefix="notfair_weekly_review_", suffix=".json", delete=False) as tmp:
- output_path = Path(tmp.name)
- cmd = [sys.executable, str(ANALYZE_GSC), "--site", site_property, "--days", str(days), "--output", str(output_path)]
- if brand_terms:
- cmd.extend(["--brand-terms", brand_terms])
- completed = subprocess.run(cmd, check=True, text=True, capture_output=True)
- if completed.stdout:
- print(completed.stdout, file=sys.stderr, end="")
- if completed.stderr:
- print(completed.stderr, file=sys.stderr, end="")
- return json.loads(output_path.read_text())
-
-
-def build_user_message(site_id: str, result: dict[str, Any], payload: dict[str, Any], context_request: dict[str, Any] | None) -> str:
- summary = payload.get("state_snapshot", {}).get("summary") or "Weekly review complete."
- actions = (payload.get("action_plan") or {}).get("actions") or []
- top_action = actions[0] if actions else {}
- queue_items = result.get("queue_items_written") or []
- proposal_path = next((path for path in queue_items if "/proposal_" in path), None)
- site_stage = (payload.get("action_plan") or {}).get("site_stage") or {}
- lines = [
- f"Weekly SEO review complete for `{site_id}`.",
- "",
- f"Run: `{result.get('run_dir')}`",
- f"Summary: {summary}",
- ]
- if site_stage:
- lines.append(f"Stage: `{site_stage.get('stage')}` — {site_stage.get('reason')}")
- if top_action:
- lines.extend([
- "",
- "Top proposed next action:",
- f"- Type: `{top_action.get('type')}`",
- f"- Target: `{top_action.get('target')}`",
- f"- Why: {top_action.get('expected_impact')}",
- f"- Best-practice lane: `{(top_action.get('best_practice_alignment') or {}).get('primary_area_label', 'not mapped')}`",
- f"- Requires approval: {'yes' if top_action.get('requires_approval') else 'no'}",
- ])
- conversion = top_action.get("conversion_opportunity") or {}
- if conversion:
- lines.append(f"- Conversion weighting: {conversion.get('multiplier')}× ({'; '.join(conversion.get('notes') or []) or 'no notes'})")
- if top_action.get("approval_artifact_type"):
- lines.append(f"- Approval artifact: `{top_action.get('approval_artifact_type')}`")
- if top_action.get("approval_ready") is False:
- blockers = top_action.get("approval_blockers") or []
- lines.append(f"- Approval-ready: no{'; ' + '; '.join(blockers) if blockers else ''}")
- deep_dive = top_action.get("deep_dive") or {}
- checks = deep_dive.get("checks") or {}
- if deep_dive:
- lines.append(
- f"- Deep dive: {deep_dive.get('status')} "
- f"(SERP {'yes' if checks.get('serp_inspected') else 'no'}, "
- f"snippet {'yes' if checks.get('current_snippet_inspected') else 'no'}, "
- f"above-fold {'yes' if checks.get('above_the_fold_inspected') else 'no'})"
- )
- # Surface top-losing-query decomposition if available
- top_losing = top_action.get("top_losing_queries", [])
- if top_losing:
- top_query = top_losing[0]
- lines.append(
- f"- Top losing query: `{top_query.get('query', '?')}` "
- f"(lost {top_query.get('absolute_click_loss', 0):g} clicks, "
- f"pos {top_query.get('position_prev', '?')}→{top_query.get('position_now', '?')}, "
- f"CTR {top_query.get('ctr_prev', '?')}%→{top_query.get('ctr_now', '?')}%)"
- )
- if proposal_path:
- lines.extend(["", f"Proposal file: `{proposal_path}`"])
- elif top_action:
- lines.extend(["", "No approval proposal was queued; the review surfaced diagnostics only."])
- if context_request:
- questions = context_request.get("business_context_questions") or []
- score = context_request.get("business_context_score")
- percent = round(float(score or 0) * 100)
- lines.extend([
- "",
- f"Before I can recommend/approve edits, business context is only {percent}% complete. Please answer these, roughly is fine:",
- ])
- lines.extend(f"{idx}. {question}" for idx, question in enumerate(questions, start=1))
- return "\n".join(lines)
-
-
-def main(argv: list[str]) -> int:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("site")
- parser.add_argument("--analysis-file")
- parser.add_argument("--gsc-property")
- parser.add_argument("--brand-terms")
- parser.add_argument("--days", type=int, default=28)
- args = parser.parse_args(argv[1:])
-
- root = workspace_root()
- site_id = normalize_site_id(args.site)
- site_root = root / "sites" / site_id
- profile = load_json(site_root / "site-profile.json", {})
- goals = load_json(site_root / "goals.json", {"active": [], "archived": []})
- learned = load_json(site_root / "learned-patterns.json", {"site_id": site_id, "observations": [], "priors": {}})
- active_goal = goals.get("active", [None])[0] if goals.get("active") else None
-
- if args.analysis_file:
- analysis = json.loads(Path(args.analysis_file).read_text())
- else:
- site_property = args.gsc_property or profile.get("gsc_property") or profile.get("canonical_url")
- if not site_property:
- raise SystemExit("No GSC property or canonical_url found for this site. Provide --gsc-property or update site-profile.json.")
- brand_terms = args.brand_terms if args.brand_terms is not None else ",".join(profile.get("brand_terms", []))
- analysis = run_analysis(site_property, args.days, brand_terms)
-
- analysis["_brand_terms"] = profile.get("brand_terms", [])
- business_context_path = Path.home() / ".toprank" / "business-context" / f"{site_id}.json"
- business_context = load_json(business_context_path, {})
- payload = build_payload(site_id, analysis, learned, active_goal, business_context, profile, live_diagnostics=True)
- result = persist_payload(args.site, payload, root=root)
- metric_item = next((item for item in payload.get("queue_items", []) if item.get("primary_metric")), None)
- result["primary_metric"] = metric_item["primary_metric"] if metric_item else None
- context_request = next((item for item in payload.get("queue_items", []) if item.get("type") == "business_context_request"), None)
- if context_request:
- result["business_context_request"] = {
- "status": context_request["status"],
- "business_context_score": context_request["business_context_score"],
- "output_path": context_request["output_path"],
- "questions": context_request["business_context_questions"],
- }
- result["user_message"] = build_user_message(site_id, result, payload, context_request)
- print(json.dumps(result, indent=2))
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main(sys.argv))
diff --git a/openclaw/install/bootstrap-site.sh b/openclaw/install/bootstrap-site.sh
deleted file mode 100755
index 24014566..00000000
--- a/openclaw/install/bootstrap-site.sh
+++ /dev/null
@@ -1,9 +0,0 @@
-#!/usr/bin/env bash
-set -euo pipefail
-
-REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
-if [ "$#" -ne 1 ]; then
- echo "usage: $0 <url-or-domain>" >&2
- exit 1
-fi
-python3 "$REPO_ROOT/openclaw/bin/bootstrap_site.py" "$1"
diff --git a/openclaw/install/install-launchd.sh b/openclaw/install/install-launchd.sh
deleted file mode 100755
index 752cb264..00000000
--- a/openclaw/install/install-launchd.sh
+++ /dev/null
@@ -1,89 +0,0 @@
-#!/usr/bin/env bash
-set -euo pipefail
-
-REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
-PYTHON_BIN="$(command -v python3)"
-LABEL="com.noworkstudio.toprank.openclaw.scheduler"
-INTERVAL=3600
-OUTPUT_DIR="${HOME}/Library/LaunchAgents"
-WRITE_ONLY=0
-RUNTIME_HOME="${TOPRANK_OPENCLAW_HOME:-$HOME/.toprank/openclaw}"
-
-while [[ $# -gt 0 ]]; do
- case "$1" in
- --label)
- LABEL="$2"
- shift 2
- ;;
- --interval)
- INTERVAL="$2"
- shift 2
- ;;
- --output-dir)
- OUTPUT_DIR="$2"
- shift 2
- ;;
- --runtime-home)
- RUNTIME_HOME="$2"
- shift 2
- ;;
- --write-only)
- WRITE_ONLY=1
- shift
- ;;
- *)
- echo "Unknown argument: $1" >&2
- exit 1
- ;;
- esac
-done
-
-mkdir -p "$OUTPUT_DIR"
-PLIST_PATH="$OUTPUT_DIR/${LABEL}.plist"
-STDOUT_LOG="${RUNTIME_HOME}/logs/scheduler.stdout.log"
-STDERR_LOG="${RUNTIME_HOME}/logs/scheduler.stderr.log"
-mkdir -p "$(dirname "$STDOUT_LOG")"
-
-cat > "$PLIST_PATH" <<PLIST
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<plist version="1.0">
- <dict>
- <key>Label</key>
- <string>${LABEL}</string>
- <key>ProgramArguments</key>
- <array>
- <string>${PYTHON_BIN}</string>
- <string>${REPO_ROOT}/openclaw/bin/run_scheduler.py</string>
- </array>
- <key>EnvironmentVariables</key>
- <dict>
- <key>TOPRANK_OPENCLAW_HOME</key>
- <string>${RUNTIME_HOME}</string>
- </dict>
- <key>StartInterval</key>
- <integer>${INTERVAL}</integer>
- <key>RunAtLoad</key>
- <true/>
- <key>StandardOutPath</key>
- <string>${STDOUT_LOG}</string>
- <key>StandardErrorPath</key>
- <string>${STDERR_LOG}</string>
- </dict>
-</plist>
-PLIST
-
-plutil -lint "$PLIST_PATH" >/dev/null
-
-echo "Wrote $PLIST_PATH"
-
-if [[ "$WRITE_ONLY" == "1" ]]; then
- echo "Skipped launchctl load (--write-only)."
- exit 0
-fi
-
-launchctl bootout "gui/${UID}" "$PLIST_PATH" >/dev/null 2>&1 || true
-launchctl bootstrap "gui/${UID}" "$PLIST_PATH"
-launchctl enable "gui/${UID}/${LABEL}" >/dev/null 2>&1 || true
-
-echo "Loaded ${LABEL}"
diff --git a/openclaw/install/install-openclaw-cron.sh b/openclaw/install/install-openclaw-cron.sh
deleted file mode 100755
index 4509b321..00000000
--- a/openclaw/install/install-openclaw-cron.sh
+++ /dev/null
@@ -1,218 +0,0 @@
-#!/usr/bin/env bash
-set -euo pipefail
-
-usage() {
- cat <<'USAGE'
-Install OpenClaw cron wiring for the NotFair OpenClaw SEO Operator.
-
-Usage:
- ./openclaw/install/install-openclaw-cron.sh [options]
-
-Options:
- --to <dest> Delivery destination, e.g. Telegram chat id. If omitted, jobs use --no-deliver.
- --channel <channel> Delivery channel for --to. Default: telegram.
- --thread-id <id> Optional Telegram forum topic/thread id.
- --account <id> Optional channel account id.
- --model <model> Optional OpenClaw model override. Omit unless you know the allowlist accepts it.
- --timezone <tz> Cron timezone. Default: America/Los_Angeles.
- --weekly-time <HH:MM> Local time for weekly reviews. Default: 06:30.
- --scheduler-every <dur> Scheduler interval. Default: 1h.
- --sites <csv> Comma-separated sites. Default: active sites from ~/.toprank/openclaw/portfolio.json.
- --runtime-home <path> NotFair runtime home. Default: ~/.toprank/openclaw.
- --repo-root <path> NotFair repo root. Default: auto-detected from this script.
-
-Publisher (opt-in; off by default — see openclaw/install/notfair-publisher.md):
- --enable-publisher Register a recurring publisher job that POSTs ready
- blog posts to NotFair. Requires NOTFAIR_PUBLISH_TOKEN
- in the cron environment.
- --publisher-every <dur> Publisher interval. Default: 15m.
- --publisher-calendar <p> Explicit calendar path passed to publish_pending.py
- (default: auto-resolve to ./.notfair/... → ~/.notfair/...).
-
- -h, --help Show this help.
-
-Examples:
- ./openclaw/install/install-openclaw-cron.sh --to "-1001234567890" --thread-id 28
- ./openclaw/install/install-openclaw-cron.sh --no-deliver is not needed; omit --to instead.
-USAGE
-}
-
-SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
-REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
-RUNTIME_HOME="${TOPRANK_OPENCLAW_HOME:-$HOME/.toprank/openclaw}"
-CHANNEL="telegram"
-TO=""
-THREAD_ID=""
-ACCOUNT=""
-MODEL=""
-TIMEZONE="America/Los_Angeles"
-WEEKLY_TIME="06:30"
-SCHEDULER_EVERY="1h"
-SITES_CSV=""
-ENABLE_PUBLISHER=0
-PUBLISHER_EVERY="15m"
-PUBLISHER_CALENDAR=""
-
-while [[ $# -gt 0 ]]; do
- case "$1" in
- --to) TO="$2"; shift 2 ;;
- --channel) CHANNEL="$2"; shift 2 ;;
- --thread-id) THREAD_ID="$2"; shift 2 ;;
- --account) ACCOUNT="$2"; shift 2 ;;
- --model) MODEL="$2"; shift 2 ;;
- --timezone|--tz) TIMEZONE="$2"; shift 2 ;;
- --weekly-time) WEEKLY_TIME="$2"; shift 2 ;;
- --scheduler-every) SCHEDULER_EVERY="$2"; shift 2 ;;
- --sites) SITES_CSV="$2"; shift 2 ;;
- --runtime-home) RUNTIME_HOME="$2"; shift 2 ;;
- --repo-root) REPO_ROOT="$2"; shift 2 ;;
- --enable-publisher) ENABLE_PUBLISHER=1; shift ;;
- --publisher-every) PUBLISHER_EVERY="$2"; shift 2 ;;
- --publisher-calendar) PUBLISHER_CALENDAR="$2"; shift 2 ;;
- -h|--help) usage; exit 0 ;;
- *) echo "Unknown argument: $1" >&2; usage >&2; exit 1 ;;
- esac
-done
-
-if ! command -v openclaw >/dev/null 2>&1; then
- echo "ERROR: openclaw CLI not found in PATH." >&2
- exit 1
-fi
-
-if [[ ! -x "$REPO_ROOT/openclaw/bin/run_scheduler.py" ]]; then
- echo "ERROR: NotFair repo root looks wrong: $REPO_ROOT" >&2
- exit 1
-fi
-
-if [[ ! "$WEEKLY_TIME" =~ ^([01][0-9]|2[0-3]):[0-5][0-9]$ ]]; then
- echo "ERROR: --weekly-time must be HH:MM, got $WEEKLY_TIME" >&2
- exit 1
-fi
-
-minute="${WEEKLY_TIME#*:}"
-hour="${WEEKLY_TIME%:*}"
-hour="$((10#$hour))"
-minute="$((10#$minute))"
-
-delivery_args=()
-if [[ -n "$TO" ]]; then
- delivery_args=(--announce --channel "$CHANNEL" --to "$TO" --best-effort-deliver)
- [[ -n "$THREAD_ID" ]] && delivery_args+=(--thread-id "$THREAD_ID")
- [[ -n "$ACCOUNT" ]] && delivery_args+=(--account "$ACCOUNT")
-else
- delivery_args=(--no-deliver)
-fi
-
-read_sites() {
- if [[ -n "$SITES_CSV" ]]; then
- tr ',' '\n' <<<"$SITES_CSV" | sed 's/^ *//;s/ *$//' | grep -v '^$'
- return 0
- fi
- python3 - "$RUNTIME_HOME/portfolio.json" <<'PY'
-import json, sys
-from pathlib import Path
-path = Path(sys.argv[1]).expanduser()
-if not path.exists():
- raise SystemExit(f"portfolio.json not found: {path}")
-data = json.loads(path.read_text())
-for site in data.get("sites", []):
- site_id = site.get("site_id")
- if site_id and site.get("status", "active") == "active" and site_id != "example.com":
- print(site_id)
-PY
-}
-
-job_exists() {
- local name="$1"
- openclaw cron list --json 2>/dev/null | python3 -c 'import json, sys; name = sys.argv[1]; data = json.load(sys.stdin); raise SystemExit(0 if any(job.get("name") == name for job in data.get("jobs", [])) else 1)' "$name"
-}
-
-add_job_if_missing() {
- local name="$1"
- shift
- if job_exists "$name"; then
- echo "exists: $name"
- return 0
- fi
- openclaw cron add --name "$name" "$@"
-}
-
-scheduler_msg="Run the NotFair OpenClaw scheduler. Execute exactly: TOPRANK_OPENCLAW_HOME=\"$RUNTIME_HOME\" python3 \"$REPO_ROOT/openclaw/bin/run_scheduler.py\". Parse the JSON. If processed, manual_attention, and restored_from_queue are all empty, reply exactly NO_REPLY. If any are non-empty, summarize what changed and include any item_id/site_id that needs attention. If the command fails, report the blocker."
-
-scheduler_args=(
- --every "$SCHEDULER_EVERY"
- --session isolated
- --light-context
- --message "$scheduler_msg"
- --tools exec
-)
-[[ -n "$MODEL" ]] && scheduler_args+=(--model "$MODEL")
-scheduler_args+=("${delivery_args[@]}")
-
-add_job_if_missing "NotFair OpenClaw Scheduler" "${scheduler_args[@]}"
-
-sites=()
-while IFS= read -r site; do
- sites+=("$site")
-done < <(read_sites)
-if [[ ${#sites[@]} -eq 0 ]]; then
- echo "No active sites found. Add sites with openclaw/bin/onboard_site.py, or pass --sites." >&2
- exit 1
-fi
-
-for i in "${!sites[@]}"; do
- site="${sites[$i]}"
- # Cron day-of-week: 1=Monday. Spread sites across weekdays, then wrap.
- dow=$(( (i % 5) + 1 ))
- cron_expr="$minute $hour * * $dow"
- weekly_msg="Run the automated NotFair weekly SEO review for $site. Execute exactly: TOPRANK_OPENCLAW_HOME=\"$RUNTIME_HOME\" python3 \"$REPO_ROOT/openclaw/bin/weekly_review.py\" \"$site\". Parse the JSON stdout. If it contains user_message, send that user_message to the user as the main visible update. If business_context_request is present, explicitly ask those questions; do not bury them behind artifact paths. Otherwise summarize the top issue, proposed next action, whether it requires approval, and the artifact path. Do not edit websites, CMS, repos, or publish anything. If the command fails, report the blocker."
-
- weekly_args=(
- --cron "$cron_expr"
- --tz "$TIMEZONE"
- --exact
- --session isolated
- --light-context
- --message "$weekly_msg"
- --tools exec
- )
- [[ -n "$MODEL" ]] && weekly_args+=(--model "$MODEL")
- weekly_args+=("${delivery_args[@]}")
-
- add_job_if_missing "NotFair Weekly Review — $site" "${weekly_args[@]}"
-done
-
-if [[ "$ENABLE_PUBLISHER" -eq 1 ]]; then
- if [[ ! -x "$REPO_ROOT/openclaw/bin/publish_pending.py" ]]; then
- echo "ERROR: --enable-publisher set but $REPO_ROOT/openclaw/bin/publish_pending.py is missing" >&2
- exit 1
- fi
- publisher_cmd="OPENCLAW_PUBLISH_COMMIT=1 TOPRANK_OPENCLAW_HOME=\"$RUNTIME_HOME\" python3 \"$REPO_ROOT/openclaw/bin/publish_pending.py\" --commit"
- if [[ -n "$PUBLISHER_CALENDAR" ]]; then
- publisher_cmd+=" --calendar \"$PUBLISHER_CALENDAR\""
- fi
- publisher_msg="Run the NotFair publisher. Execute exactly: $publisher_cmd. Parse the JSON stdout. If processed is empty, reply exactly NO_REPLY. Otherwise summarize: how many published, how many failed (with reasons), how many retried. If the command exits non-zero, report the blocker. Do not retry the publisher in this turn — the next cron pass picks up retryable failures."
-
- publisher_args=(
- --every "$PUBLISHER_EVERY"
- --session isolated
- --light-context
- --message "$publisher_msg"
- --tools exec
- )
- [[ -n "$MODEL" ]] && publisher_args+=(--model "$MODEL")
- publisher_args+=("${delivery_args[@]}")
-
- add_job_if_missing "NotFair NotFair Publisher" "${publisher_args[@]}"
-
- if [[ -z "${NOTFAIR_PUBLISH_TOKEN:-}" ]]; then
- echo
- echo "WARNING: NOTFAIR_PUBLISH_TOKEN is not set in your environment."
- echo "The publisher cron job is registered but will fail until the token is exported"
- echo "in the cron environment. See openclaw/install/notfair-publisher.md."
- fi
-fi
-
-echo
-echo "Installed/verified NotFair OpenClaw cron jobs:"
-openclaw cron list | grep -i 'NotFair' || true
diff --git a/openclaw/install/install.sh b/openclaw/install/install.sh
deleted file mode 100755
index d3d62759..00000000
--- a/openclaw/install/install.sh
+++ /dev/null
@@ -1,41 +0,0 @@
-#!/usr/bin/env bash
-set -euo pipefail
-
-REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
-OPENCLAW_HOME="${OPENCLAW_HOME:-$HOME/.openclaw}"
-SKILL_TARGET_DIR="${OPENCLAW_SKILLS_DIR:-$OPENCLAW_HOME/skills}"
-
-link_or_warn() {
- local src="$1"
- local dest="$2"
- if [[ -e "$dest" && ! -L "$dest" ]]; then
- echo "warning: $dest exists and is not a symlink; leaving it unchanged" >&2
- return 0
- fi
- ln -sfn "$src" "$dest"
-}
-
-mkdir -p "$SKILL_TARGET_DIR"
-python3 "$REPO_ROOT/openclaw/bin/bootstrap_workspace.py" >/dev/null
-
-for skill_dir in "$REPO_ROOT"/openclaw/skills/*; do
- name="$(basename "$skill_dir")"
- target="$SKILL_TARGET_DIR/$name"
- rm -rf "$target"
- mkdir -p "$target"
- cp -R "$skill_dir"/. "$target"/
- echo "copied $name -> $target"
-done
-
-# OpenClaw skill discovery rejects symlinks that escape ~/.openclaw/skills.
-# The wrapper skills are copied above, then their repo-relative support paths are
-# preserved with stable links for `{baseDir}/../../shared`, `{baseDir}/../../bin`,
-# and `{baseDir}/../../../seo`.
-link_or_warn "$REPO_ROOT/openclaw/shared" "$OPENCLAW_HOME/shared"
-link_or_warn "$REPO_ROOT/openclaw/bin" "$OPENCLAW_HOME/bin"
-link_or_warn "$REPO_ROOT/seo" "$HOME/seo"
-
-echo
-echo "OpenClaw skills installed."
-echo "Runtime home: ${TOPRANK_OPENCLAW_HOME:-$HOME/.toprank/openclaw}"
-echo "Skills dir: $SKILL_TARGET_DIR"
diff --git a/openclaw/install/notfair-openclaw.cron.example b/openclaw/install/notfair-openclaw.cron.example
deleted file mode 100644
index 1de85cd0..00000000
--- a/openclaw/install/notfair-openclaw.cron.example
+++ /dev/null
@@ -1,6 +0,0 @@
-# Run the NotFair OpenClaw scheduler every hour.
-# Edit TOPRANK_OPENCLAW_HOME if you keep runtime state elsewhere (env var
-# name retained from the toprank → notfair rename to preserve existing
-# config; see CHANGELOG 0.24.0).
-
-0 * * * * TOPRANK_OPENCLAW_HOME="$HOME/.toprank/openclaw" /usr/bin/env python3 /ABSOLUTE/PATH/TO/notfair/openclaw/bin/run_scheduler.py >> "$HOME/.toprank/openclaw/logs/cron.log" 2>&1
diff --git a/openclaw/install/notfair-publisher.md b/openclaw/install/notfair-publisher.md
deleted file mode 100644
index 6dfc2ec5..00000000
--- a/openclaw/install/notfair-publisher.md
+++ /dev/null
@@ -1,145 +0,0 @@
-# NotFair Publisher — Webhook Contract
-
-`openclaw/bin/publish_pending.py` POSTs ready blog posts from a NotFair content
-calendar to a NotFair-hosted Next.js webhook. This file is the contract: the
-Next.js handler on `notfair.co` must accept exactly this shape.
-
-If you change either side, update this file in the same commit. Keep the
-publisher and the handler in lockstep.
-
----
-
-## Endpoint
-
-```
-POST https://notfair.co/api/blog/publish
-```
-
-Configurable via `NOTFAIR_PUBLISH_URL`. For local Next.js dev, point at
-`http://localhost:3000/api/blog/publish`.
-
-## Auth
-
-```
-Authorization: Bearer <NOTFAIR_PUBLISH_TOKEN>
-```
-
-The token is a long-lived secret the user provisions in the NotFair admin and
-exports as `NOTFAIR_PUBLISH_TOKEN` in their OpenClaw cron environment. The
-handler MUST reject requests without a valid Bearer token (401).
-
-There is no HMAC signing in v1. If you need request integrity, add an
-`X-NotFair-Signature` header in a future version and bump `schemaVersion`.
-
-## Request body
-
-`Content-Type: application/json`
-
-```json
-{
- "schemaVersion": "1",
- "slug": "facebook-seo-optimization",
- "title": "Facebook SEO Optimization: 7 Tactics That Actually Move Pipeline",
- "primaryKeyword": "facebook seo optimization",
- "secondaryKeywords": ["facebook page seo", "facebook search ranking"],
- "intent": "informational",
- "type": "blog",
- "metaDescription": "...",
- "body": "# ...\n\nMarkdown body of the post.",
- "bodyFormat": "markdown",
- "featuredImage": {
- "url": "https://cdn.notfair.co/blog/facebook-seo/featured.webp",
- "alt": "...",
- "width": 1200,
- "height": 1200
- },
- "inlineImages": [
- { "url": "...", "alt": "...", "placement": "after-h2-1" }
- ],
- "structuredData": { "@context": "https://schema.org", "@type": "BlogPosting", "...": "..." },
- "scheduledAt": "2026-05-22",
- "source": { "tool": "notfair", "skill": "content-planner", "version": "1" }
-}
-```
-
-**Field notes:**
-
-- `slug` (required) — used as the URL slug. Must be stable; re-publishing the
- same slug is treated as an update by the Next.js side.
-- `body` (required) — Markdown. The Next.js handler is responsible for
- rendering to HTML, sanitization, and CMS persistence.
-- `bodyFormat` — currently always `"markdown"`. Reserved for future `"html"`
- or `"mdx"` values.
-- `featuredImage` — may be `null` if the planner couldn't generate one;
- handler should reject with 400 if your site requires it.
-- `inlineImages` — array; `placement` is an opaque hint ("after-h2-1",
- "after-h2-2", etc.) the handler can use to position images.
-- `structuredData` — JSON-LD object; handler should embed verbatim in `<head>`.
-
-## Response — 2xx (success)
-
-```json
-{
- "ok": true,
- "url": "https://notfair.co/blog/facebook-seo-optimization",
- "publishedAt": "2026-05-22T14:30:00Z"
-}
-```
-
-The publisher reads `url` (or `publishedUrl`) and stores it on the calendar
-entry as `publishedUrl`. The full response body is stored under
-`entry.response` for audit.
-
-## Response — 4xx (non-retryable failure)
-
-```json
-{
- "ok": false,
- "error": "invalid slug",
- "code": "slug_collision"
-}
-```
-
-The publisher marks the calendar entry as `status: "failed"` and stores the
-response body in `entry.lastError`. The cron will **not** retry. The user must
-fix the entry (rename slug, add missing fields, etc.) and flip status back to
-`ready_to_publish` to try again.
-
-Common 4xx cases the handler should map:
-- `400` — schema validation failure (missing required field, bad format)
-- `401` — missing or invalid Bearer token
-- `409` — slug collision with an existing post
-- `413` — body too large
-
-## Response — 5xx (retryable failure)
-
-The publisher leaves the entry as `ready_to_publish` and stores the response
-body in `entry.lastError`. The cron will retry on its next pass.
-
-The handler should return 5xx **only for transient failures** — DB unavailable,
-upstream timeout, etc. Return 4xx for permanent errors so the publisher stops
-hammering.
-
-## Idempotency
-
-The handler MUST tolerate the same `slug` being submitted more than once:
-
-- If the previous publish succeeded and the cron retries (e.g. response was
- lost mid-flight), the handler returns 2xx with the same `url`.
-- If the body has changed, treat as an update — overwrite the existing post.
-
-The publisher does not currently send an idempotency key; rely on `slug`.
-
-## Rate
-
-The cron runs at the interval configured via `--scheduler-every` (default 1h
-for the OpenClaw scheduler; the publisher job defaults to every 15 min — see
-`install-openclaw-cron.sh --enable-publisher`). A single run POSTs once per
-ready entry, sequentially, with no concurrency. No backoff between requests.
-
-## Versioning
-
-Bump `schemaVersion` when adding required fields or changing semantics. The
-handler should accept `schemaVersion: "1"` for the foreseeable future; minor
-field additions are backward-compatible. Drop support only after every
-deployed publisher has rolled forward.
diff --git a/openclaw/install/run-scheduler.sh b/openclaw/install/run-scheduler.sh
deleted file mode 100755
index f05b6b11..00000000
--- a/openclaw/install/run-scheduler.sh
+++ /dev/null
@@ -1,5 +0,0 @@
-#!/usr/bin/env bash
-set -euo pipefail
-
-REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
-python3 "$REPO_ROOT/openclaw/bin/run_scheduler.py" "$@"
diff --git a/openclaw/shared/adapter-rules.md b/openclaw/shared/adapter-rules.md
deleted file mode 100644
index 37ba4a56..00000000
--- a/openclaw/shared/adapter-rules.md
+++ /dev/null
@@ -1,79 +0,0 @@
-# Adapter Rules
-
-These rules apply to every `openclaw/skills/*` wrapper.
-
-## 1. Preserve the canonical skills
-
-The existing NotFair skills under `seo/` and `google-ads/` remain the source of truth for domain expertise. Do not fork or silently rewrite them inside the OpenClaw surface.
-
-## 2. Treat OpenClaw as the operator layer
-
-The wrapper is responsible for:
-
-- selecting the right site,
-- loading persistent state,
-- deciding whether to run at the portfolio or site level,
-- writing structured artifacts,
-- applying policy gates,
-- scheduling follow-up work.
-
-## 3. Runtime home
-
-Use:
-
-```bash
-TOPRANK_OPENCLAW_HOME="${TOPRANK_OPENCLAW_HOME:-$HOME/.toprank/openclaw}"
-```
-
-Never write live operator state into this git repo.
-
-## 4. Site selection
-
-Every wrapper must resolve a `site_id` before acting. Use the helper:
-
-```bash
-python3 {baseDir}/../../bin/site_id.py https://example.com
-```
-
-If the user did not specify a site and multiple sites are active, either:
-
-- run `notfair-portfolio-review`, or
-- ask the user which site they mean.
-
-## 5. Required artifacts
-
-Every non-trivial run should write at least:
-
-- `audit.json`
-- `action-plan.json`
-- `verification.json`
-
-under:
-
-```text
-$TOPRANK_OPENCLAW_HOME/sites/<site_id>/runs/<timestamp>/
-```
-
-## 6. Approval boundaries
-
-Wrappers may automatically:
-
-- read site state,
-- run analysis,
-- update queue items,
-- generate proposals and drafts.
-
-Wrappers must ask first before:
-
-- editing website repo files,
-- writing to a CMS,
-- opening a PR,
-- publishing or deploying changes.
-
-## 7. Multi-site first
-
-Assume the operator owns multiple websites. State must stay isolated by site. Never mix artifacts from two sites in the same run folder.
-
-## 8. Feedback discipline
-
-If a wrapper proposes or drafts an action, it should also write a queue or schedule entry for a future outcome check when the action is time-based.
diff --git a/openclaw/shared/artifact-contract.md b/openclaw/shared/artifact-contract.md
deleted file mode 100644
index 7a6a0e58..00000000
--- a/openclaw/shared/artifact-contract.md
+++ /dev/null
@@ -1,64 +0,0 @@
-# Artifact Contract
-
-The OpenClaw adaptive layer is artifact-first. Runs should leave behind structured JSON that another agent turn can resume from.
-
-## Portfolio files
-
-- `portfolio.json` — registry of sites, business weights, cadence, and status
-- `schedule.json` — future recurring checks and follow-up tasks
-
-## Per-site files
-
-- `site-profile.json` — stable description of the website
-- `goals.json` — active and archived SEO goals
-- `latest-state.json` — compact snapshot used for fast re-entry
-- `learned-patterns.json` — site-local lessons with confidence
-
-## Per-run files
-
-Each run lives under:
-
-```text
-sites/<site_id>/runs/<timestamp>/
-```
-
-Recommended files:
-
-- `trigger.json`
-- `state-snapshot.json`
-- `audit.json`
-- `action-plan.json`
-- `proposal.json`
-- `patch-set.json`
-- `verification.json`
-- `feedback.json`
-- `learning-log.json`
-
-## Minimal required shape
-
-### audit.json
-Must answer:
-- what problem was found?
-- what evidence supports it?
-- how severe is it?
-
-### action-plan.json
-Must answer:
-- what should happen next?
-- what is the expected impact?
-- does it require approval?
-
-### verification.json
-Must answer:
-- what was checked?
-- what is safe/unsafe?
-- what follow-up is required?
-
-## Queue items
-
-Queue files under `sites/<site_id>/queue/` represent deferred work. Typical items:
-
-- weekly review
-- feedback check in 14 days
-- page improvement pending approval
-- revisit indexing issue after deploy
diff --git a/openclaw/shared/policy.md b/openclaw/shared/policy.md
deleted file mode 100644
index 6875ac30..00000000
--- a/openclaw/shared/policy.md
+++ /dev/null
@@ -1,33 +0,0 @@
-# Policy
-
-## Default operating mode
-
-Use **operator mode** by default:
-
-- generate drafts and proposals automatically,
-- ask before any external or production write.
-
-## Safety classes
-
-### Auto-safe
-- local audits
-- artifact writes
-- queue updates
-- proposal generation
-- internal prioritization
-
-### Approval-required
-- repo file edits for the target website
-- CMS writes
-- PR creation
-- content publication
-- production metadata changes
-
-### Blocked from auto
-- destructive mass changes
-- irreversible public actions
-- bulk redirects without review
-
-## Business weighting
-
-Use the `business_weight` in `portfolio.json` when ranking sites. Important sites should receive more attention, but active regressions may still preempt lower-value growth work.
diff --git a/openclaw/shared/recommendation-quality.md b/openclaw/shared/recommendation-quality.md
deleted file mode 100644
index 6d6cfd00..00000000
--- a/openclaw/shared/recommendation-quality.md
+++ /dev/null
@@ -1,63 +0,0 @@
-# Recommendation Quality
-
-The OpenClaw SEO operator should behave like an analyst, not an alert router.
-
-## Principle
-
-Prefer recommendations with clear expected upside, enough evidence, and an obvious next lever. Avoid ranking noisy metric movement above actionable opportunities just because the percentage change is large.
-
-Use `seo/shared/seo-best-practices.md` as the durable reference. Every top recommendation should map to exactly one primary MECE best-practice lane so the operator knows whether the right next action is eligibility/indexing, intent targeting, content usefulness, SERP packaging, technical UX, authority, local presence, or measurement.
-
-## Judgment levers
-
-Each recommendation should expose the inputs that drove ranking:
-
-- `expected_impact` — estimated click upside or click loss, using absolute impact when possible
-- `confidence_score` — sample size and signal stability
-- `goal_alignment_score` — whether the signal supports the active goal, especially non-brand growth
-- `actionability_score` — whether there is a clear SEO lever vs a vague investigation
-- `business_intent_score` — whether the query likely maps to revenue, not just informational visits
-- `business_context_goal_score` — whether the opportunity matches the site-specific business goal, e.g. local qualified outcomes over national informational traffic
-- `url_quality_score` — whether the URL is canonical/actionable or a tracking/parameter variant
-- `learned_multiplier` — site-local prior from previous outcomes
-- `best_practice_alignment` — the primary SEO best-practice lane, source references, and why the action belongs there
-- `seo_review_gates` — explicit pre-approval checks for index/sitemap consistency, cannibalization ownership, internal-link graph, content depth, conversion path, and NO-SHIP risks
-- `seo_review_gate_status` — rollup status for those gates: `pass`, `warning`, or `blocked`
-
-These are not hard approval rules. They are decision levers for the operator and the human reviewer.
-
-## Common false positives
-
-- Tiny-denominator drops, e.g. 13 clicks to 3 clicks, especially when ranked by percent change
-- Tracking URLs and UTM variants treated as standalone strategic pages
-- Branded/navigational query noise outranking non-brand growth opportunities
-- Cannibalization reports where the “winner” is not actually the intended page
-- Cannibalization fixes that redirect/canonicalize pages before declaring the canonical owner and support/retired page roles
-- Noindex pages left in XML sitemaps, redirected URLs left in sitemaps, or internal links still pointing to retired URLs
-- Thin SEO pages that have a query target but no real workflows, examples, FAQs, differentiating proof, or conversion path
-- Query-level opportunities that have not been mapped to a concrete page
-- Treating high-impression informational/price queries as metadata-only wins without checking zero-click SERP behavior
-
-## Preferred behavior
-
-- Preserve the raw signal in evidence.
-- Canonicalize the action target when the raw URL is a tracking variant.
-- Reclassify tracking-param traffic drops as investigation work instead of content/page edits.
-- Let high-impression, high-position, low-CTR opportunities outrank low-volume noisy regressions only when business intent, site-specific business context, and actionability are also strong.
-- For informational price queries, classify the action as snippet/content packaging or query-intent mapping unless a SERP diagnosis proves metadata is the main lever.
-- Explain why the top action is actionable and what would make it unsafe or low-confidence.
-- Attach `best_practice_alignment` to proposals and action-plan entries. If an action cannot be mapped to one primary best-practice lane, downgrade it to investigation/manual review.
-- Before proposing an edit for CTR/snippet/content opportunities, automatically run a deep-dive diagnostic: SERP snapshot, current title/meta/H1, above-the-fold content packaging, CTA/price-answer check, and zero-click risk classification.
-- Attach SEO review gates to every action/proposal. At minimum, the operator should report:
- - index/sitemap consistency: noindex URLs absent from sitemap, redirected URLs absent from sitemap, internal links point at canonical destinations
- - cannibalization intent safety: one intended owner, other pages clearly supporting/noindex/redirect/canonical
- - internal link graph: hub/category links, adjacent commercial/service links, relevant support/blog/docs links, and cleanup of links to retired/cannibal pages
- - content depth: no thin SEO pages; require use cases, workflows/process detail, examples, FAQs, and differentiating proof where content changes are proposed
- - conversion path: mapped qualified action or visible CTA; do not optimize only for raw clicks
- - Gemini NO-SHIP review: check public strategy leakage, unresolved cannibalization, CTA friction, and technical SEO conflicts
-- If business context deprioritizes a traffic class, reframe the recommendation instead of chasing raw clicks. Example: for a local service business that only values local qualified outcomes, broad national cost-query CTR should become a local intent ownership / consolidation proposal, not a national blog CTR optimization.
-- If business-impact context is incomplete, create an explicit `business_context_request` queue item and surface the questions in the runner result instead of burying them in verification warnings. Missing business context blocks approval/editing, but should not block the diagnostic deep dive.
-
-## Approval boundary
-
-A high score means “worth proposing,” not “safe to publish.” Repo edits, CMS writes, PRs, redirects, canonical changes, and production metadata changes still require explicit approval.
diff --git a/openclaw/shared/triggers.md b/openclaw/shared/triggers.md
deleted file mode 100644
index 3368803e..00000000
--- a/openclaw/shared/triggers.md
+++ /dev/null
@@ -1,21 +0,0 @@
-# Triggers
-
-The adaptive layer can wake up from three kinds of triggers.
-
-## Scheduled
-- `daily_health_check`
-- `weekly_review`
-- `monthly_strategy_refresh`
-
-## Event-driven
-- `traffic_drop_detected`
-- `indexing_regression`
-- `post_deploy_check`
-- `important_page_changed`
-
-## Manual
-- `manual_request`
-- `improve_this_page`
-- `investigate_drop`
-
-For the MVP, scheduled and manual triggers are enough. Event-driven triggers can be represented as queue items or future integrations.
diff --git a/openclaw/skills/notfair-improve-page/SKILL.md b/openclaw/skills/notfair-improve-page/SKILL.md
deleted file mode 100644
index 5c7c5350..00000000
--- a/openclaw/skills/notfair-improve-page/SKILL.md
+++ /dev/null
@@ -1,29 +0,0 @@
----
-name: notfair-improve-page
-description: Improve one URL inside a registered site by producing a focused diagnosis, proposal, and verification artifact.
-metadata: { "openclaw": { "emoji": "🧱", "homepage": "https://github.com/nowork-studio/notfair", "requires": { "bins": ["python3"] } } }
----
-
-# NotFair Improve Page
-
-1. Read `{baseDir}/../../shared/adapter-rules.md`.
-2. Read `{baseDir}/../../shared/artifact-contract.md`.
-3. Read `{baseDir}/../../shared/policy.md`.
-4. Load the site work folder, then focus on the target URL and choose the canonical page-level skills that best fit the issue.
-5. Read and follow the canonical NotFair skill at `{baseDir}/../../../seo/seo-page/SKILL.md`.
-6. Convert the page diagnosis into a structured proposal using `python3 {baseDir}/../../bin/improve_page.py <site> --url <url> --issue-summary "..." --proposal-summary "..."`.
-7. If you also have file-level edits to suggest, include `--patch-path` and `--patch-summary` so a `patch-set.json` artifact is written.
-8. Verify that the run wrote `proposal.json` and `verification.json`, plus `patch-set.json` when relevant.
-9. If the next action requires editing a site repo, CMS, publishing content, or opening a PR, stop and ask for approval before doing it.
-
-## Wrapper job
-
-Use this when the operator wants a single page improved.
-
-Typical combinations:
-- `seo-page` for diagnosis,
-- `meta-tags-optimizer` for title/meta candidates,
-- `schema-markup-generator` for structured data proposals,
-- `content-writer` for a content brief or rewrite draft.
-
-Write at least `proposal.json` and `verification.json`. If you generate patches or file-level changes, also write `patch-set.json`.
diff --git a/openclaw/skills/notfair-investigate-drop/SKILL.md b/openclaw/skills/notfair-investigate-drop/SKILL.md
deleted file mode 100644
index 1a50d1d9..00000000
--- a/openclaw/skills/notfair-investigate-drop/SKILL.md
+++ /dev/null
@@ -1,29 +0,0 @@
----
-name: notfair-investigate-drop
-description: Investigate an organic traffic drop for one registered site and produce a ranked recovery plan with artifacts.
-metadata: { "openclaw": { "emoji": "🚨", "homepage": "https://github.com/nowork-studio/notfair", "requires": { "bins": ["python3"] } } }
----
-
-# NotFair Investigate Drop
-
-1. Read `{baseDir}/../../shared/adapter-rules.md`.
-2. Read `{baseDir}/../../shared/artifact-contract.md`.
-3. Read `{baseDir}/../../shared/policy.md`.
-4. Resolve the target site, load prior audits and latest state, then compare the current problem against the site's recent history before choosing the next recovery action.
-5. Read and follow the canonical NotFair skill at `{baseDir}/../../../seo/seo-analysis/SKILL.md`.
-6. Convert the investigation into a structured recovery run using `python3 {baseDir}/../../bin/investigate_drop.py <site> --summary "..." --likely-cause "..."`.
-7. If the drop points to a specific URL, include `--target-url <url>` so the adaptive layer queues a follow-up page-improvement task.
-8. Verify that the run wrote `audit.json`, `action-plan.json`, and `verification.json`, plus any follow-up queue items.
-9. If the next action requires editing a site repo, CMS, publishing content, or opening a PR, stop and ask for approval before doing it.
-
-## Wrapper job
-
-Use this when the operator reports a traffic loss or ranking decline.
-
-Your job:
-- identify likely causes,
-- separate technical issues from content/intent issues,
-- rank the fastest and safest recovery actions,
-- write `audit.json`, `action-plan.json`, and `verification.json`.
-
-If the drop investigation suggests a page-level fix, queue a follow-up `notfair-improve-page` task.
diff --git a/openclaw/skills/notfair-portfolio-review/SKILL.md b/openclaw/skills/notfair-portfolio-review/SKILL.md
deleted file mode 100644
index d06988f5..00000000
--- a/openclaw/skills/notfair-portfolio-review/SKILL.md
+++ /dev/null
@@ -1,27 +0,0 @@
----
-name: notfair-portfolio-review
-description: Review all registered websites in the NotFair OpenClaw portfolio and rank which site deserves attention next.
-metadata: { "openclaw": { "emoji": "📊", "homepage": "https://github.com/nowork-studio/notfair", "requires": { "bins": ["python3"] } } }
----
-
-# NotFair Portfolio Review
-
-1. Read `{baseDir}/../../shared/adapter-rules.md`.
-2. Read `{baseDir}/../../shared/artifact-contract.md`.
-3. Read `{baseDir}/../../shared/policy.md`.
-4. Load `portfolio.json` and each active site's `latest-state.json` from the OpenClaw runtime home.
-5. Run `python3 {baseDir}/../../bin/portfolio_review.py` to get the current ranked site list and write a portfolio review artifact.
-6. Read and follow the canonical NotFair skill at `{baseDir}/../../../seo/seo-analysis/SKILL.md` only for the top-ranked site(s) if you need deeper analysis.
-7. If the top site needs deeper work, either launch `notfair-weekly-review` for that site or ask the operator which site to dive into.
-
-## Wrapper job
-
-Use this when the operator owns multiple websites and needs portfolio-level prioritization.
-
-Your job:
-- scan all active sites,
-- rank them by urgency and upside,
-- name the one or two sites that deserve attention now,
-- create queue items or follow-up tasks for deeper site reviews.
-
-Use business weight, visible regressions, and opportunity size when ranking the sites.
diff --git a/openclaw/skills/notfair-site-onboard/SKILL.md b/openclaw/skills/notfair-site-onboard/SKILL.md
deleted file mode 100644
index be286e69..00000000
--- a/openclaw/skills/notfair-site-onboard/SKILL.md
+++ /dev/null
@@ -1,29 +0,0 @@
----
-name: notfair-site-onboard
-description: Register a website in NotFair's OpenClaw adaptive layer and initialize its per-site work folder.
-metadata: { "openclaw": { "emoji": "🧭", "homepage": "https://github.com/nowork-studio/notfair", "requires": { "bins": ["python3"] } } }
----
-
-# NotFair Site Onboard
-
-1. Read `{baseDir}/../../shared/adapter-rules.md`.
-2. Read `{baseDir}/../../shared/artifact-contract.md`.
-3. Read `{baseDir}/../../shared/policy.md`.
-4. Gather the site URL, display name, brand terms, business weight, cadence, and one initial SEO goal.
-5. Run:
- - `python3 {baseDir}/../../bin/bootstrap_workspace.py`
- - `python3 {baseDir}/../../bin/onboard_site.py <url> --display-name "..." --brand-terms "A,B" --business-weight 1.0 --cadence weekly --goal-type grow_non_brand_clicks --primary-metric non_brand_clicks_28d`
-6. Read and follow the canonical NotFair skill at `{baseDir}/../../../seo/seo-analysis/SKILL.md` only if you need deeper site understanding during onboarding.
-7. Confirm that `site-profile.json`, `goals.json`, and `portfolio.json` were updated.
-
-## Wrapper job
-
-Use this when the operator is adding a new website.
-
-Your job:
-- create or update the portfolio registry,
-- initialize the site work folder,
-- capture brand terms, business weight, cadence, and one initial SEO goal,
-- write `site-profile.json` and `goals.json`.
-
-If the user already has multiple sites, keep this site's state isolated under its own folder.
diff --git a/openclaw/skills/notfair-weekly-review/SKILL.md b/openclaw/skills/notfair-weekly-review/SKILL.md
deleted file mode 100644
index 53428947..00000000
--- a/openclaw/skills/notfair-weekly-review/SKILL.md
+++ /dev/null
@@ -1,36 +0,0 @@
----
-name: notfair-weekly-review
-description: Run a weekly SEO review for one registered website, write audit artifacts, and choose the next best safe action.
-metadata: { "openclaw": { "emoji": "📈", "homepage": "https://github.com/nowork-studio/notfair", "requires": { "bins": ["python3"] } } }
----
-
-# NotFair Weekly Review
-
-1. Read `{baseDir}/../../shared/adapter-rules.md`.
-2. Read `{baseDir}/../../shared/artifact-contract.md`.
-3. Read `{baseDir}/../../shared/policy.md`.
-4. Read `{baseDir}/../../shared/recommendation-quality.md`.
-5. Read `{baseDir}/../../../seo/shared/seo-best-practices.md` and use its MECE lanes to explain why the top action is the right kind of SEO work.
-6. Resolve the target `site_id`; if no site was specified and multiple sites are active, run portfolio review first or ask the user which site to review.
-7. Read and follow the canonical NotFair skill at `{baseDir}/../../../seo/seo-analysis/SKILL.md`.
-8. Prefer the automated runner:
- - `python3 {baseDir}/../../bin/weekly_review.py <site_id-or-url>`
- - add `--gsc-property` if the site profile does not already contain one
- - add `--analysis-file` when testing against a saved GSC analysis JSON fixture
-9. The runner will generate and persist the review artifacts automatically, including automatic deep-dive diagnostics for the top CTR/snippet/content opportunity when applicable.
-10. Verify that the run wrote `audit.json`, `action-plan.json`, and `verification.json`, refreshed `latest-state.json`, and created queue items. The top proposal should include `best_practice_alignment` plus `deep_dive` with SERP, current snippet, above-the-fold, and zero-click checks before approval.
-11. If runner stdout includes `user_message`, use it as the user-facing summary. If it includes `business_context_request`, explicitly ask those questions in chat; do not just report artifact paths or say business context is incomplete.
-12. If the next action requires editing a site repo, CMS, publishing content, or opening a PR, stop and ask for approval before doing it. Missing business context blocks approval/editing, not investigation.
-
-## Wrapper job
-
-Use this as the default weekly loop for a single site.
-
-Your job:
-- load the site profile, goals, and latest state,
-- run a fresh review using the canonical SEO analysis skill,
-- identify the top three issues,
-- prioritize exactly one next best action,
-- write `audit.json`, `action-plan.json`, and `verification.json`.
-
-When possible, also create a queue item for a 14-day or 28-day follow-up check.
diff --git a/openclaw/tests/test_publish_pending.py b/openclaw/tests/test_publish_pending.py
deleted file mode 100644
index fde2e160..00000000
--- a/openclaw/tests/test_publish_pending.py
+++ /dev/null
@@ -1,360 +0,0 @@
-"""Tests for openclaw/bin/publish_pending.py."""
-from __future__ import annotations
-
-import contextlib
-import io
-import json
-import os
-import sys
-import tempfile
-import unittest
-import urllib.error
-from pathlib import Path
-from unittest import mock
-
-BIN_DIR = Path(__file__).resolve().parents[1] / "bin"
-if str(BIN_DIR) not in sys.path:
- sys.path.insert(0, str(BIN_DIR))
-
-import publish_pending as pp
-
-
-def _calendar_with(entries):
- return {
- "schema_version": "1",
- "generated": "2026-05-15T00:00:00Z",
- "site": "https://example.com",
- "topics": entries,
- "warnings": [],
- }
-
-
-def _ready_entry(idx=1, body="# Hello\n\nBody.", with_body_path=True, **overrides):
- """Return (entry, body_path) — body_path is None if with_body_path is False."""
- return {
- "id": f"post-{idx}",
- "title": "Hook-Driven Title",
- "primaryKeyword": "test keyword",
- "secondaryKeywords": ["k1", "k2"],
- "intent": "informational",
- "type": "blog",
- "metaDescription": "meta",
- "scheduledDate": "2026-05-22",
- "status": "ready_to_publish",
- "priority": "P0",
- "bodyPath": f"bodies/post-{idx}.md" if with_body_path else None,
- **overrides,
- }
-
-
-class PublishPendingTest(unittest.TestCase):
- def setUp(self):
- self.tmp = tempfile.TemporaryDirectory()
- self.root = Path(self.tmp.name)
- self.calendar_path = self.root / "content-calendar.json"
- (self.root / "bodies").mkdir()
-
- def tearDown(self):
- self.tmp.cleanup()
-
- def _write_calendar(self, entries):
- pp.save_calendar(self.calendar_path, _calendar_with(entries))
-
- def _write_body(self, idx, body="# Hello\n\nBody."):
- (self.root / "bodies" / f"post-{idx}.md").write_text(body)
-
- # ── Calendar resolution / empty cases ───────────────────────────────
-
- def test_missing_calendar_returns_ok_no_processing(self):
- result = pp.run(
- calendar_path=self.root / "nope.json",
- webhook="https://x",
- token="t",
- dry_run=False,
- site_filter=None,
- )
- self.assertTrue(result["ok"])
- self.assertEqual(result["processed"], [])
- self.assertIn("no calendar at", result["note"])
-
- def test_calendar_with_no_ready_entries_is_a_noop(self):
- self._write_calendar([
- {"id": "planned-1", "status": "planned", "bodyPath": "bodies/planned-1.md"},
- {"id": "published-1", "status": "published", "bodyPath": "bodies/x.md"},
- ])
- result = pp.run(
- calendar_path=self.calendar_path, webhook="https://x", token="t",
- dry_run=False, site_filter=None,
- )
- self.assertTrue(result["ok"])
- self.assertEqual(result["processed"], [])
- self.assertEqual(result["note"], "no entries ready_to_publish")
-
- def test_ready_entry_without_body_path_is_skipped(self):
- self._write_calendar([_ready_entry(1, with_body_path=False)])
- result = pp.run(
- calendar_path=self.calendar_path, webhook="https://x", token="t",
- dry_run=False, site_filter=None,
- )
- self.assertEqual(result["processed"], [])
-
- # ── Safety / commit gating ──────────────────────────────────────────
-
- def test_commit_mode_without_token_refuses(self):
- self._write_calendar([_ready_entry(1)])
- self._write_body(1)
- result = pp.run(
- calendar_path=self.calendar_path, webhook="https://x", token=None,
- dry_run=False, site_filter=None,
- )
- self.assertFalse(result["ok"])
- self.assertIn("NOTFAIR_PUBLISH_TOKEN", result["error"])
-
- cal = pp.load_calendar(self.calendar_path)
- self.assertEqual(cal["topics"][0]["status"], "ready_to_publish")
-
- def test_dry_run_does_not_post_and_does_not_mutate(self):
- self._write_calendar([_ready_entry(1)])
- self._write_body(1)
- with mock.patch.object(pp, "post_to_webhook") as mocked:
- result = pp.run(
- calendar_path=self.calendar_path, webhook="https://x", token=None,
- dry_run=True, site_filter=None,
- )
- mocked.assert_not_called()
- self.assertTrue(result["ok"])
- self.assertEqual(result["processed"][0]["outcome"], "dry-run")
-
- cal = pp.load_calendar(self.calendar_path)
- self.assertEqual(cal["topics"][0]["status"], "ready_to_publish")
- self.assertNotIn("publishedAt", cal["topics"][0])
-
- # ── Success path ───────────────────────────────────────────────────
-
- def test_2xx_marks_published_and_stores_url(self):
- self._write_calendar([_ready_entry(1)])
- self._write_body(1)
- with mock.patch.object(
- pp, "post_to_webhook",
- return_value=(201, {"ok": True, "url": "https://notfair.co/blog/post-1"}),
- ):
- result = pp.run(
- calendar_path=self.calendar_path, webhook="https://x", token="t",
- dry_run=False, site_filter=None,
- )
- self.assertTrue(result["ok"])
- self.assertEqual(result["processed"][0]["outcome"], "published")
-
- cal = pp.load_calendar(self.calendar_path)
- entry = cal["topics"][0]
- self.assertEqual(entry["status"], "published")
- self.assertEqual(entry["publishedUrl"], "https://notfair.co/blog/post-1")
- self.assertIn("publishedAt", entry)
- self.assertEqual(entry["response"]["ok"], True)
-
- # ── 4xx / failed ───────────────────────────────────────────────────
-
- def test_400_marks_failed_and_records_error(self):
- self._write_calendar([_ready_entry(1)])
- self._write_body(1)
- with mock.patch.object(
- pp, "post_to_webhook",
- return_value=(400, {"ok": False, "error": "invalid slug"}),
- ):
- result = pp.run(
- calendar_path=self.calendar_path, webhook="https://x", token="t",
- dry_run=False, site_filter=None,
- )
- # 4xx is non-retryable but not a "system" failure for the publisher,
- # so the run is still ok (the entry is marked failed for the user).
- self.assertTrue(result["ok"])
- self.assertEqual(result["processed"][0]["outcome"], "failed")
- self.assertEqual(result["processed"][0]["status"], 400)
-
- cal = pp.load_calendar(self.calendar_path)
- entry = cal["topics"][0]
- self.assertEqual(entry["status"], "failed")
- self.assertIn("HTTP 400", entry["lastError"])
-
- # ── 5xx / retry ────────────────────────────────────────────────────
-
- def test_5xx_leaves_entry_ready_and_exits_non_ok(self):
- self._write_calendar([_ready_entry(1)])
- self._write_body(1)
- with mock.patch.object(
- pp, "post_to_webhook",
- return_value=(503, "service unavailable"),
- ):
- result = pp.run(
- calendar_path=self.calendar_path, webhook="https://x", token="t",
- dry_run=False, site_filter=None,
- )
- self.assertFalse(result["ok"])
- self.assertEqual(result["processed"][0]["outcome"], "retry")
-
- cal = pp.load_calendar(self.calendar_path)
- entry = cal["topics"][0]
- self.assertEqual(entry["status"], "ready_to_publish")
- self.assertIn("HTTP 503", entry["lastError"])
-
- # ── Network error ──────────────────────────────────────────────────
-
- def test_network_error_leaves_entry_ready_and_exits_non_ok(self):
- self._write_calendar([_ready_entry(1)])
- self._write_body(1)
- with mock.patch.object(
- pp, "post_to_webhook",
- side_effect=urllib.error.URLError("connection refused"),
- ):
- result = pp.run(
- calendar_path=self.calendar_path, webhook="https://x", token="t",
- dry_run=False, site_filter=None,
- )
- self.assertFalse(result["ok"])
- self.assertEqual(result["processed"][0]["outcome"], "network-error")
-
- cal = pp.load_calendar(self.calendar_path)
- entry = cal["topics"][0]
- self.assertEqual(entry["status"], "ready_to_publish")
- self.assertIn("network:", entry["lastError"])
-
- # ── Body unreadable ────────────────────────────────────────────────
-
- def test_missing_body_file_marks_failed(self):
- # Calendar references body but file isn't created
- self._write_calendar([_ready_entry(1)])
- # No _write_body call
- with mock.patch.object(pp, "post_to_webhook") as mocked:
- result = pp.run(
- calendar_path=self.calendar_path, webhook="https://x", token="t",
- dry_run=False, site_filter=None,
- )
- mocked.assert_not_called()
- self.assertEqual(result["processed"][0]["outcome"], "skipped")
-
- cal = pp.load_calendar(self.calendar_path)
- entry = cal["topics"][0]
- self.assertEqual(entry["status"], "failed")
- self.assertIn("could not read bodyPath", entry["lastError"])
-
- # ── Multiple entries ───────────────────────────────────────────────
-
- def test_multiple_entries_processed_independently(self):
- self._write_calendar([
- _ready_entry(1),
- _ready_entry(2),
- {"id": "planned", "status": "planned", "bodyPath": "bodies/x.md"}, # not ready
- ])
- self._write_body(1)
- self._write_body(2)
-
- def fake_post(url, token, payload, timeout=30):
- if payload["slug"] == "post-1":
- return 201, {"ok": True, "url": "https://notfair.co/blog/post-1"}
- return 400, {"error": "nope"}
-
- with mock.patch.object(pp, "post_to_webhook", side_effect=fake_post):
- result = pp.run(
- calendar_path=self.calendar_path, webhook="https://x", token="t",
- dry_run=False, site_filter=None,
- )
-
- outcomes = {r["id"]: r["outcome"] for r in result["processed"]}
- self.assertEqual(outcomes, {"post-1": "published", "post-2": "failed"})
-
- cal = pp.load_calendar(self.calendar_path)
- statuses = {t["id"]: t["status"] for t in cal["topics"]}
- self.assertEqual(
- statuses,
- {"post-1": "published", "post-2": "failed", "planned": "planned"},
- )
-
- # ── Site filter ────────────────────────────────────────────────────
-
- def test_site_filter_only_publishes_matching_entries(self):
- self._write_calendar([
- _ready_entry(1, site="a.com"),
- _ready_entry(2, site="b.com"),
- ])
- self._write_body(1)
- self._write_body(2)
- with mock.patch.object(
- pp, "post_to_webhook", return_value=(200, {"ok": True, "url": "x"}),
- ) as mocked:
- result = pp.run(
- calendar_path=self.calendar_path, webhook="https://x", token="t",
- dry_run=False, site_filter="a.com",
- )
- self.assertEqual(len(result["processed"]), 1)
- self.assertEqual(result["processed"][0]["id"], "post-1")
- mocked.assert_called_once()
-
- # ── Payload shape ──────────────────────────────────────────────────
-
- def test_payload_includes_required_fields(self):
- self._write_calendar([_ready_entry(1, featuredImage={"url": "https://x/img.png", "alt": "a"})])
- self._write_body(1, body="# Body\n\nText.")
- captured = {}
-
- def capture(url, token, payload, timeout=30):
- captured["payload"] = payload
- captured["token"] = token
- captured["url"] = url
- return 200, {"ok": True, "url": "https://x/published"}
-
- with mock.patch.object(pp, "post_to_webhook", side_effect=capture):
- pp.run(
- calendar_path=self.calendar_path, webhook="https://hook.example",
- token="secret-token", dry_run=False, site_filter=None,
- )
-
- p = captured["payload"]
- self.assertEqual(p["schemaVersion"], "1")
- self.assertEqual(p["slug"], "post-1")
- self.assertEqual(p["title"], "Hook-Driven Title")
- self.assertEqual(p["primaryKeyword"], "test keyword")
- self.assertEqual(p["body"], "# Body\n\nText.")
- self.assertEqual(p["bodyFormat"], "markdown")
- self.assertEqual(p["featuredImage"], {"url": "https://x/img.png", "alt": "a"})
- self.assertEqual(p["source"], {"tool": "notfair", "skill": "content-planner", "version": "1"})
- self.assertEqual(captured["token"], "secret-token")
- self.assertEqual(captured["url"], "https://hook.example")
-
- # ── CLI / main ──────────────────────────────────────────────────────
-
- def test_main_dry_run_default_when_no_flags(self):
- self._write_calendar([_ready_entry(1)])
- self._write_body(1)
- with mock.patch.object(pp, "post_to_webhook") as mocked, \
- mock.patch.dict(os.environ, {}, clear=False):
- os.environ.pop("OPENCLAW_PUBLISH_COMMIT", None)
- os.environ.pop("NOTFAIR_PUBLISH_TOKEN", None)
- buf = io.StringIO()
- with contextlib.redirect_stdout(buf):
- rc = pp.main(["--calendar", str(self.calendar_path)])
- mocked.assert_not_called()
- self.assertEqual(rc, 0)
- out = json.loads(buf.getvalue())
- self.assertTrue(out["dryRun"])
-
- def test_main_commit_via_env_var(self):
- self._write_calendar([_ready_entry(1)])
- self._write_body(1)
- with mock.patch.object(
- pp, "post_to_webhook", return_value=(200, {"ok": True, "url": "x"}),
- ) as mocked, mock.patch.dict(
- os.environ,
- {"OPENCLAW_PUBLISH_COMMIT": "1", "NOTFAIR_PUBLISH_TOKEN": "tok"},
- clear=False,
- ):
- buf = io.StringIO()
- with contextlib.redirect_stdout(buf):
- rc = pp.main(["--calendar", str(self.calendar_path)])
- mocked.assert_called_once()
- self.assertEqual(rc, 0)
- out = json.loads(buf.getvalue())
- self.assertFalse(out["dryRun"])
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/openclaw/tests/test_scheduler.py b/openclaw/tests/test_scheduler.py
deleted file mode 100644
index f343cff1..00000000
--- a/openclaw/tests/test_scheduler.py
+++ /dev/null
@@ -1,166 +0,0 @@
-import contextlib
-import io
-import json
-import os
-import sys
-import tempfile
-import unittest
-from pathlib import Path
-
-BIN_DIR = Path(__file__).resolve().parents[1] / "bin"
-if str(BIN_DIR) not in sys.path:
- sys.path.insert(0, str(BIN_DIR))
-
-import run_scheduler
-from runtime import bootstrap_workspace, load_json, reconcile_schedule_from_queue, save_json, upsert_schedule_items
-
-
-class OpenClawSchedulerTest(unittest.TestCase):
- def setUp(self) -> None:
- self.tempdir = tempfile.TemporaryDirectory()
- self.root = Path(self.tempdir.name)
- self.previous_home = os.environ.get("TOPRANK_OPENCLAW_HOME")
- os.environ["TOPRANK_OPENCLAW_HOME"] = str(self.root)
- bootstrap_workspace(self.root)
-
- def tearDown(self) -> None:
- if self.previous_home is None:
- os.environ.pop("TOPRANK_OPENCLAW_HOME", None)
- else:
- os.environ["TOPRANK_OPENCLAW_HOME"] = self.previous_home
- self.tempdir.cleanup()
-
- def write_queue_item(self, site_id: str, item: dict) -> Path:
- queue_path = self.root / "sites" / site_id / "queue" / f"{item['item_id']}.json"
- save_json(queue_path, {"site_id": site_id, **item})
- return queue_path
-
- def run_scheduler(self, *args: str) -> dict:
- output = io.StringIO()
- with contextlib.redirect_stdout(output):
- code = run_scheduler.main(["run_scheduler.py", *args])
- self.assertEqual(code, 0)
- return json.loads(output.getvalue())
-
- def test_upsert_schedule_items_uses_site_and_item_id(self) -> None:
- upsert_schedule_items(
- [
- {"site_id": "a.com", "item_id": "same", "type": "feedback_check", "status": "pending", "due_at": "2026-01-01T00:00:00Z"},
- {"site_id": "b.com", "item_id": "same", "type": "feedback_check", "status": "pending", "due_at": "2026-01-01T00:00:00Z"},
- ],
- self.root,
- )
-
- schedule = load_json(self.root / "schedule.json", {})
- self.assertEqual(len(schedule["upcoming"]), 2)
- self.assertEqual({item["site_id"] for item in schedule["upcoming"]}, {"a.com", "b.com"})
-
- def test_reconcile_restores_pending_queue_item_missing_from_schedule(self) -> None:
- self.write_queue_item(
- "example.com",
- {
- "item_id": "orphaned_followup",
- "type": "feedback_check",
- "status": "pending",
- "due_at": "2026-01-01T00:00:00Z",
- },
- )
-
- schedule, restored = reconcile_schedule_from_queue(self.root)
-
- self.assertEqual(len(restored), 1)
- self.assertEqual(schedule["upcoming"][0]["item_id"], "orphaned_followup")
-
- def test_scheduler_accepts_naive_due_timestamps(self) -> None:
- self.write_queue_item(
- "example.com",
- {
- "item_id": "naive_due_followup",
- "type": "feedback_check",
- "status": "pending",
- "due_at": "2026-01-01T00:00:00",
- "primary_metric": "organic_clicks_7d",
- "baseline_metrics": {"organic_clicks_7d": 10.0},
- },
- )
-
- result = self.run_scheduler("--dry-run", "--as-of", "2026-01-02T00:00:00Z")
-
- self.assertEqual(result["manual_attention"][0]["item_id"], "naive_due_followup")
-
- def test_inconclusive_feedback_is_not_marked_done(self) -> None:
- queue_path = self.write_queue_item(
- "example.com",
- {
- "item_id": "missing_metrics_followup",
- "type": "feedback_check",
- "status": "pending",
- "due_at": "2026-01-01T00:00:00Z",
- "primary_metric": "organic_clicks_7d",
- "baseline_metrics": {"organic_clicks_7d": 10.0},
- },
- )
-
- result = self.run_scheduler("--as-of", "2026-01-02T00:00:00Z")
- queue_item = load_json(queue_path, {})
- schedule = load_json(self.root / "schedule.json", {})
-
- self.assertEqual(result["processed"], [])
- self.assertEqual(result["manual_attention"][0]["item_id"], "missing_metrics_followup")
- self.assertIn("missing metric data", result["manual_attention"][0]["reason"])
- self.assertEqual(queue_item["status"], "ready_for_attention")
- self.assertEqual(schedule["upcoming"][0]["status"], "ready_for_attention")
- self.assertFalse((self.root / "sites" / "example.com" / "feedback" / "missing_metrics_followup.json").exists())
-
- def test_dry_run_reports_inconclusive_feedback_as_manual_attention(self) -> None:
- queue_path = self.write_queue_item(
- "example.com",
- {
- "item_id": "dry_run_missing_metrics",
- "type": "feedback_check",
- "status": "pending",
- "due_at": "2026-01-01T00:00:00Z",
- "primary_metric": "organic_clicks_7d",
- "baseline_metrics": {"organic_clicks_7d": 10.0},
- },
- )
-
- result = self.run_scheduler("--dry-run", "--as-of", "2026-01-02T00:00:00Z")
- queue_item = load_json(queue_path, {})
-
- self.assertEqual(result["processed"], [])
- self.assertEqual(result["manual_attention"][0]["item_id"], "dry_run_missing_metrics")
- self.assertTrue(result["manual_attention"][0]["dry_run"])
- self.assertEqual(queue_item["status"], "pending")
-
- def test_feedback_with_observed_metrics_is_processed(self) -> None:
- queue_path = self.write_queue_item(
- "example.com",
- {
- "item_id": "scored_followup",
- "type": "feedback_check",
- "status": "pending",
- "due_at": "2026-01-01T00:00:00Z",
- "notes": "Re-check organic clicks.",
- "action_type": "page_improvement",
- "primary_metric": "organic_clicks_7d",
- "primary_direction": "higher_better",
- "success_threshold_pct": 0.1,
- "baseline_metrics": {"organic_clicks_7d": 10.0},
- "observed_metrics": {"organic_clicks_7d": 12.0},
- "guardrail_metrics": [],
- },
- )
-
- result = self.run_scheduler("--as-of", "2026-01-02T00:00:00Z")
- queue_item = load_json(queue_path, {})
- feedback = load_json(self.root / "sites" / "example.com" / "feedback" / "scored_followup.json", {})
-
- self.assertEqual(result["manual_attention"], [])
- self.assertEqual(result["processed"][0]["outcome"], "win")
- self.assertEqual(queue_item["status"], "done")
- self.assertEqual(feedback["status"], "win")
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/openclaw/tests/test_weekly_review_scoring.py b/openclaw/tests/test_weekly_review_scoring.py
deleted file mode 100644
index 193ad12c..00000000
--- a/openclaw/tests/test_weekly_review_scoring.py
+++ /dev/null
@@ -1,1108 +0,0 @@
-import os
-import sys
-import tempfile
-import unittest
-from pathlib import Path
-
-BIN_DIR = Path(__file__).resolve().parents[1] / "bin"
-if str(BIN_DIR) not in sys.path:
- sys.path.insert(0, str(BIN_DIR))
-
-import weekly_review
-
-
-class WeeklyReviewScoringTest(unittest.TestCase):
- def base_analysis(self) -> dict:
- return {
- "site": "sc-domain:example.com",
- "period": {"start": "2026-04-01", "end": "2026-04-28", "days": 28},
- "summary": {"clicks": 2000, "impressions": 200000, "ctr": 1.0, "position": 8.0},
- "branded_split": {
- "branded": {"clicks": 800, "impressions": 10000},
- "non_branded": {"clicks": 350, "impressions": 20000},
- },
- "comparison": {"declining_pages": [], "declining_queries": []},
- "ctr_gaps_by_page": [],
- "ctr_opportunities": [],
- "cannibalization": [],
- }
-
- def test_high_impression_ctr_gap_beats_low_volume_utm_drop(self) -> None:
- analysis = self.base_analysis()
- analysis["comparison"]["declining_pages"] = [
- {
- "page": "https://www.example.com/?utm_source=google_map",
- "clicks_now": 3,
- "clicks_prev": 13,
- "change_pct": -76.9,
- }
- ]
- analysis["ctr_gaps_by_page"] = [
- {
- "query": "roof repair cost",
- "page": "https://www.example.com/blog/roof-repair-cost",
- "clicks": 2,
- "impressions": 1681,
- "ctr": 0.12,
- "position": 2.8,
- }
- ]
-
- payload = weekly_review.build_payload("example.com", analysis, {"priors": {}}, None)
- top_action = payload["action_plan"]["actions"][0]
- issues = payload["audit"]["issues"]
-
- self.assertEqual(top_action["type"], "snippet_content_packaging")
- self.assertEqual(top_action["target"], "https://www.example.com/blog/roof-repair-cost")
- self.assertIn("business_intent_score", top_action["score_components"])
- self.assertGreater(issues[0]["priority_score"], issues[1]["priority_score"])
- self.assertIn("score_components", issues[0])
- context_request = next(item for item in payload["queue_items"] if item["type"] == "business_context_request")
- proposal = next(item for item in payload["queue_items"] if item["type"] == "action_proposal")
- self.assertEqual(context_request["status"], "pending_input")
- self.assertTrue(context_request["business_context_questions"])
- self.assertEqual(proposal["status"], "pending_approval")
- self.assertIn("complete_business_context", proposal["approval_preconditions"])
- self.assertNotIn("due_at", proposal)
-
- def test_tracking_url_decline_keeps_raw_target_but_canonicalizes_action_target(self) -> None:
- issue = weekly_review.decline_issue(
- {
- "page": "https://www.example.com/?utm_source=google_map&utm_medium=business_profile",
- "clicks_now": 3,
- "clicks_prev": 13,
- "change_pct": -76.9,
- }
- )
-
- self.assertEqual(issue["recommended_action_type"], "canonical_or_tracking_investigation")
- self.assertEqual(issue["raw_target"], "https://www.example.com/?utm_source=google_map&utm_medium=business_profile")
- self.assertEqual(issue["target"], "https://www.example.com/")
- self.assertLess(issue["score_components"]["url_quality_score"], 1.0)
- self.assertTrue(any("tracking" in note for note in issue["operator_judgment_notes"]))
-
- def test_absolute_loss_decline_beats_tiny_percent_drop(self) -> None:
- analysis = self.base_analysis()
- analysis["comparison"]["declining_pages"] = [
- {
- "page": "https://www.example.com/?utm_source=google_map",
- "clicks_now": 3,
- "clicks_prev": 13,
- "change_pct": -76.9,
- },
- {
- "page": "https://www.example.com/blog/roof-repair-costs",
- "clicks_now": 58,
- "clicks_prev": 103,
- "change_pct": -43.7,
- },
- ]
-
- payload = weekly_review.build_payload("example.com", analysis, {"priors": {}}, None)
- top_action = payload["action_plan"]["actions"][0]
-
- self.assertEqual(top_action["target"], "https://www.example.com/blog/roof-repair-costs")
- self.assertEqual(top_action["type"], "page_improvement")
- self.assertIn("45", top_action["expected_impact"])
-
- def test_local_commercial_ctr_gap_can_stay_metadata_action(self) -> None:
- issue = weekly_review.ctr_gap_issue(
- {
- "query": "roof repair near me",
- "page": "https://www.example.com/roof-repair",
- "clicks": 13,
- "impressions": 664,
- "ctr": 1.96,
- "position": 10.7,
- },
- [],
- )
-
- self.assertEqual(issue["recommended_action_type"], "meta_tags")
- self.assertEqual(issue["score_components"]["business_intent_score"], 1.0)
- self.assertFalse(any("metadata alone is unproven" in note for note in issue["operator_judgment_notes"]))
-
- def test_branded_gap_on_service_page_keeps_page_aligned(self) -> None:
- issue = weekly_review.ctr_gap_issue(
- {
- "query": "example boarding",
- "page": "https://www.example.com/dog-boarding",
- "clicks": 91,
- "impressions": 943,
- "ctr": 9.65,
- "position": 1.2,
- },
- ["example"],
- )
-
- self.assertEqual(issue["score_components"]["goal_alignment_score"], 1.0)
- self.assertTrue(any("service page" in note for note in issue["operator_judgment_notes"]))
-
- def test_generic_branded_gap_on_service_page_is_not_approval_ready(self) -> None:
- issue = weekly_review.ctr_gap_issue(
- {
- "query": "example",
- "page": "https://www.example.com/dog-boarding",
- "clicks": 17,
- "impressions": 941,
- "ctr": 1.81,
- "position": 1.2,
- },
- ["example"],
- )
- readiness = weekly_review.approval_readiness_for_issue(issue)
-
- self.assertLess(issue["score_components"]["goal_alignment_score"], 1.0)
- self.assertLess(issue["score_components"]["actionability_score"], 0.5)
- self.assertFalse(readiness["approval_ready"])
- self.assertTrue(any("generic branded" in note for note in issue["operator_judgment_notes"]))
-
- def test_branded_gap_on_blog_stays_lower_priority(self) -> None:
- issue = weekly_review.ctr_gap_issue(
- {
- "query": "example boarding",
- "page": "https://www.example.com/blog/dog-boarding-guide",
- "clicks": 91,
- "impressions": 943,
- "ctr": 9.65,
- "position": 1.2,
- },
- ["example"],
- )
-
- self.assertLess(issue["score_components"]["goal_alignment_score"], 1.0)
- self.assertTrue(any("branded/navigational" in note for note in issue["operator_judgment_notes"]))
-
- def test_informational_ctr_gap_is_not_metadata_only(self) -> None:
- issue = weekly_review.ctr_gap_issue(
- {
- "query": "how much does roof repair cost",
- "page": "https://www.example.com/blog/roof-repair-cost",
- "clicks": 2,
- "impressions": 1681,
- "ctr": 0.12,
- "position": 2.8,
- },
- [],
- )
-
- self.assertEqual(issue["recommended_action_type"], "snippet_content_packaging")
- self.assertLess(issue["score_components"]["business_intent_score"], 1.0)
- self.assertTrue(any("metadata alone is unproven" in note for note in issue["operator_judgment_notes"]))
-
- def test_query_only_ctr_gap_is_mapping_not_metadata_action(self) -> None:
- issue = weekly_review.query_ctr_issue(
- {
- "query": "how much does roof repair cost",
- "clicks": 2,
- "impressions": 1804,
- "ctr": 0.11,
- "position": 3.5,
- },
- [],
- )
-
- self.assertEqual(issue["recommended_action_type"], "query_intent_mapping")
- self.assertIn("business_intent_score", issue["score_components"])
- self.assertTrue(any("concrete page" in note for note in issue["operator_judgment_notes"]))
-
- def test_business_context_reframes_national_cost_ctr_as_local_intent_ownership(self) -> None:
- analysis = self.base_analysis()
- analysis["ctr_gaps_by_page"] = [
- {
- "query": "how much does roof repair cost",
- "page": "https://www.example.com/blog/roof-repair-cost",
- "clicks": 2,
- "impressions": 1681,
- "ctr": 0.12,
- "position": 2.8,
- }
- ]
- business_context = {
- "target_customer_priority": {
- "primary": ["local homeowners"],
- "deprioritized": ["national informational readers outside service area"],
- },
- "booking_intent_hierarchy": {
- "highest_priority": ["emergency roof repair portland", "roof repair near me"],
- "supporting_only": ["how much does roof repair cost", "roof repair cost"],
- },
- "page_role_map": {
- "/blog/roof-repair-cost": "supporting informational page",
- "/blog/roof-repair-prices-portland": "local commercial-research page",
- "/emergency-roof-repair-portland": "transactional local landing page",
- },
- }
-
- payload = weekly_review.build_payload("example.com", analysis, {"priors": {}}, None, business_context)
- top_action = payload["action_plan"]["actions"][0]
- proposal = next(item for item in payload["queue_items"] if item["type"] == "action_proposal")
-
- self.assertEqual(top_action["type"], "local_intent_ownership")
- self.assertEqual(top_action["target"], "https://www.example.com/blog/roof-repair-prices-portland")
- self.assertEqual(top_action["source_target"], "https://www.example.com/blog/roof-repair-cost")
- self.assertEqual(proposal["action_type"], "local_intent_ownership")
- self.assertIn("national_click_discount", proposal["score_components"])
- self.assertEqual(proposal["consolidation_targets"]["conversion_target"], "https://www.example.com/emergency-roof-repair-portland")
- self.assertTrue(any("national informational" in note for note in top_action["operator_judgment_notes"]))
-
-
- def test_priority_list_does_not_mean_national_is_deprioritized(self) -> None:
- issue = {
- "recommended_action_type": "snippet_content_packaging",
- "primary_query": "how much does roof repair cost",
- "target": "https://www.example.com/blog/roof-repair-cost",
- "canonical_target": "https://www.example.com/blog/roof-repair-cost",
- "priority_score": 0.6,
- "score_components": {},
- "operator_judgment_notes": [],
- }
- business_context = {
- "target_customer_priority": ["national customers", "local customers"],
- "booking_intent_hierarchy": {"supporting_only": ["how much does roof repair cost"]},
- }
-
- updated = weekly_review.apply_business_context_to_issue(issue, business_context, site_id="example.com")
-
- self.assertEqual(updated["recommended_action_type"], "snippet_content_packaging")
- self.assertNotIn("national_click_discount", updated.get("score_components", {}))
-
- def test_support_page_retargeting_without_national_deprioritization_keeps_score(self) -> None:
- issue = {
- "recommended_action_type": "snippet_content_packaging",
- "primary_query": "how much does roof repair cost",
- "target": "https://www.example.com/blog/roof-repair-cost",
- "canonical_target": "https://www.example.com/blog/roof-repair-cost",
- "priority_score": 0.6,
- "score_components": {},
- "operator_judgment_notes": [],
- }
- business_context = {
- "target_customer_priority": ["local homeowners", "researchers"],
- "booking_intent_hierarchy": {"supporting_only": ["how much does roof repair cost"]},
- "page_role_map": {
- "/blog/roof-repair-cost": "supporting informational page",
- "/roof-repair-prices": "local commercial-research page",
- },
- }
-
- updated = weekly_review.apply_business_context_to_issue(issue, business_context, site_id="example.com")
-
- self.assertEqual(updated["recommended_action_type"], "local_intent_ownership")
- self.assertEqual(updated["priority_score"], 0.6)
- self.assertNotIn("national_click_discount", updated.get("score_components", {}))
- self.assertFalse(any("national informational" in note for note in updated["operator_judgment_notes"]))
-
- def test_query_only_retargeting_uses_context_support_page_as_source(self) -> None:
- issue = {
- "recommended_action_type": "query_intent_mapping",
- "primary_query": "how much does roof repair cost",
- "priority_score": 0.6,
- "score_components": {},
- "operator_judgment_notes": [],
- }
- business_context = {
- "target_customer_priority": {"deprioritized": ["national informational readers outside service area"]},
- "booking_intent_hierarchy": {"supporting_only": ["how much does roof repair cost"]},
- "page_role_map": [
- {"path": "/blog/roof-repair-cost", "role": "supporting informational page"},
- {"path": "/roof-repair-prices", "role": "local commercial-research page"},
- ],
- }
-
- updated = weekly_review.apply_business_context_to_issue(issue, business_context, site_id="example.com")
-
- self.assertEqual(updated["recommended_action_type"], "local_intent_ownership")
- self.assertEqual(updated["source_target"], "https://www.example.com/blog/roof-repair-cost")
- self.assertEqual(updated["consolidation_targets"]["source_support_page"], "https://www.example.com/blog/roof-repair-cost")
- self.assertEqual(updated["target"], "https://www.example.com/roof-repair-prices")
-
- def test_live_fetch_headers_include_vercel_bypass_from_env(self) -> None:
- previous = os.environ.get("TOPRANK_VERCEL_PROTECTION_BYPASS")
- os.environ["TOPRANK_VERCEL_PROTECTION_BYPASS"] = "test-bypass-secret"
- try:
- headers = weekly_review.live_fetch_headers()
- finally:
- if previous is None:
- os.environ.pop("TOPRANK_VERCEL_PROTECTION_BYPASS", None)
- else:
- os.environ["TOPRANK_VERCEL_PROTECTION_BYPASS"] = previous
-
- self.assertEqual(headers["x-vercel-protection-bypass"], "test-bypass-secret")
-
- def test_live_fetch_headers_support_site_profile_header_env(self) -> None:
- previous = os.environ.get("CUSTOM_FETCH_TOKEN")
- os.environ["CUSTOM_FETCH_TOKEN"] = "custom-token"
- try:
- headers = weekly_review.live_fetch_headers({"live_fetch_header_env": {"x-custom-token": "CUSTOM_FETCH_TOKEN"}})
- finally:
- if previous is None:
- os.environ.pop("CUSTOM_FETCH_TOKEN", None)
- else:
- os.environ["CUSTOM_FETCH_TOKEN"] = previous
-
- self.assertEqual(headers["x-custom-token"], "custom-token")
-
- def test_national_click_discount_demotes_ranking_score_without_floor_boost(self) -> None:
- issue = {
- "recommended_action_type": "snippet_content_packaging",
- "primary_query": "how much does roof repair cost",
- "target": "https://www.example.com/blog/roof-repair-cost",
- "canonical_target": "https://www.example.com/blog/roof-repair-cost",
- "priority_score": 0.007,
- "score_components": {},
- "operator_judgment_notes": [],
- }
- business_context = {
- "target_customer_priority": {"deprioritized": ["national informational readers outside service area"]},
- "booking_intent_hierarchy": {"supporting_only": ["how much does roof repair cost"]},
- "page_role_map": {
- "/blog/roof-repair-cost": "supporting informational page",
- "/roof-repair-prices": "local commercial-research page",
- },
- }
-
- updated = weekly_review.apply_business_context_to_issue(issue, business_context, site_id="example.com")
-
- self.assertEqual(updated["recommended_action_type"], "local_intent_ownership")
- self.assertEqual(updated["score_components"]["national_click_discount"], 0.25)
- self.assertEqual(updated["priority_score"], 0.002)
-
- def test_discounted_support_query_does_not_outrank_local_candidate(self) -> None:
- candidates = [
- {
- "recommended_action_type": "snippet_content_packaging",
- "primary_query": "how much does roof repair cost",
- "target": "https://www.example.com/blog/roof-repair-cost",
- "canonical_target": "https://www.example.com/blog/roof-repair-cost",
- "priority_score": 0.8,
- "score_components": {},
- "operator_judgment_notes": [],
- },
- {
- "recommended_action_type": "meta_tags",
- "primary_query": "roof repair near me",
- "target": "https://www.example.com/roof-repair",
- "canonical_target": "https://www.example.com/roof-repair",
- "priority_score": 0.3,
- "score_components": {},
- "operator_judgment_notes": [],
- },
- ]
- business_context = {
- "target_customer_priority": {"deprioritized": ["national informational readers outside service area"]},
- "booking_intent_hierarchy": {
- "highest_priority": ["roof repair near me"],
- "supporting_only": ["how much does roof repair cost"],
- },
- "page_role_map": {
- "/blog/roof-repair-cost": "supporting informational page",
- "/roof-repair-prices": "local commercial-research page",
- "/roof-repair": "transactional local landing page",
- },
- }
-
- adjusted = weekly_review.dedupe_candidates(weekly_review.apply_business_context(candidates, business_context, site_id="example.com"))
- ranked = weekly_review.apply_prioritization(adjusted, {"priors": {}}, "non_brand_clicks_28d")
-
- self.assertEqual(ranked[0]["primary_query"], "roof repair near me")
- self.assertEqual(ranked[1]["recommended_action_type"], "local_intent_ownership")
-
- def test_retargeted_business_context_issues_are_deduped(self) -> None:
- candidates = [
- {
- "recommended_action_type": "snippet_content_packaging",
- "primary_query": "how much does roof repair cost",
- "target": "https://www.example.com/blog/roof-repair-cost",
- "canonical_target": "https://www.example.com/blog/roof-repair-cost",
- "priority_score": 0.6,
- "score_components": {},
- "operator_judgment_notes": [],
- "title": "Support query A",
- },
- {
- "recommended_action_type": "query_intent_mapping",
- "primary_query": "roof repair cost",
- "target": "https://www.example.com/blog/roof-repair-pricing",
- "canonical_target": "https://www.example.com/blog/roof-repair-pricing",
- "priority_score": 0.5,
- "score_components": {},
- "operator_judgment_notes": [],
- "title": "Support query B",
- },
- ]
- business_context = {
- "target_customer_priority": {"deprioritized": ["national informational readers outside service area"]},
- "booking_intent_hierarchy": {"supporting_only": ["how much does roof repair cost", "roof repair cost"]},
- "page_role_map": [
- {"path": "/blog/roof-repair-cost", "role": "supporting informational page"},
- {"path": "/blog/roof-repair-pricing", "role": "supporting informational page"},
- {"path": "/roof-repair-prices", "role": "local commercial-research page"},
- ],
- }
-
- adjusted = weekly_review.apply_business_context(candidates, business_context, site_id="example.com")
- deduped = weekly_review.dedupe_candidates(adjusted)
-
- self.assertEqual(len(deduped), 1)
- self.assertEqual(deduped[0]["canonical_target"], "https://www.example.com/roof-repair-prices")
-
- def test_action_proposal_includes_deep_dive_diagnostics_before_approval(self) -> None:
- analysis = self.base_analysis()
- analysis["ctr_gaps_by_page"] = [
- {
- "query": "how much does roof repair cost",
- "page": "https://www.example.com/blog/roof-repair-cost",
- "clicks": 2,
- "impressions": 1681,
- "ctr": 0.12,
- "position": 2.8,
- }
- ]
- with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
- source = root / "content" / "blogs"
- source.mkdir(parents=True)
- (source / "roof-repair-cost.mdx").write_text(
- "---\n"
- "title: \"Roof Repair Cost in 2026\"\n"
- "description: \"Compare roof repair prices and hidden fees.\"\n"
- "---\n\n"
- "# Roof Repair Cost in 2026\n\n"
- "This guide explains fees first. Request a repair quote when ready.\n\n"
- "Prices are $55-$90 per project in the local market.\n",
- encoding="utf-8",
- )
- original = weekly_review.serp_snapshot_for_query
- weekly_review.serp_snapshot_for_query = lambda query, site_id, live=False: {
- "source": "test_serp",
- "status": "ok",
- "query": query,
- "results": [{"title": "Roof Repair Cost", "domain": "example.com", "snippet": "$55-$90 per project"}],
- "answer_like_serp": True,
- }
- try:
- payload = weekly_review.build_payload(
- "example.com",
- analysis,
- {"priors": {}},
- None,
- site_profile={"source_roots": [str(root)]},
- live_diagnostics=True,
- )
- finally:
- weekly_review.serp_snapshot_for_query = original
-
- proposal = next(item for item in payload["queue_items"] if item["type"] == "action_proposal")
- deep_dive = proposal["deep_dive"]
- self.assertEqual(deep_dive["status"], "completed")
- self.assertTrue(deep_dive["checks"]["serp_inspected"])
- self.assertTrue(deep_dive["checks"]["current_snippet_inspected"])
- self.assertTrue(deep_dive["checks"]["above_the_fold_inspected"])
- self.assertTrue(deep_dive["checks"]["zero_click_risk_accounted_for"])
- self.assertEqual(deep_dive["current_snippet"]["title"], "Roof Repair Cost in 2026")
- self.assertTrue(deep_dive["above_the_fold"]["has_fast_price_answer_above_fold"])
- self.assertIn("complete_business_context", proposal["approval_preconditions"])
-
- def test_action_proposal_surfaces_business_context_gaps(self) -> None:
- analysis = self.base_analysis()
- analysis["ctr_gaps_by_page"] = [
- {
- "query": "roof repair cost",
- "page": "https://www.example.com/blog/roof-repair-cost",
- "clicks": 2,
- "impressions": 1681,
- "ctr": 0.12,
- "position": 2.8,
- }
- ]
-
- payload = weekly_review.build_payload("example.com", analysis, {"priors": {}}, None, {"business_name": "Example"})
- context_request = next(item for item in payload["queue_items"] if item["type"] == "business_context_request")
- queue_item = next(item for item in payload["queue_items"] if item["type"] == "action_proposal")
- context_check = next(check for check in payload["verification"]["checks"] if check["name"] == "business impact context")
-
- self.assertEqual(context_check["status"], "warning")
- self.assertEqual(context_request["status"], "pending_input")
- self.assertEqual(context_request["output_path"], "~/.toprank/business-context/example.com.json")
- self.assertLess(queue_item["business_context_score"], 0.75)
- self.assertIn("complete_business_context", queue_item["approval_preconditions"])
- self.assertTrue(any(gap["field"] == "service_value_weights" for gap in context_request["business_context_gaps"]))
- self.assertTrue(context_request["business_context_questions"])
-
- def test_seed_stage_generates_demand_seed_action_instead_of_manual_review(self) -> None:
- analysis = {
- "site": "sc-domain:newco.com",
- "period": {"start": "2026-04-01", "end": "2026-04-28", "days": 28},
- "summary": {"clicks": 9, "impressions": 44, "ctr": 20.45, "position": 4.1},
- "branded_split": {},
- "comparison": {"declining_pages": [], "declining_queries": []},
- "ctr_gaps_by_page": [],
- "ctr_opportunities": [],
- "cannibalization": [],
- "top_pages": [{"page": "https://newco.com/setup-guide", "clicks": 0, "impressions": 6}],
- "top_queries": [{"query": "newco setup", "clicks": 0, "impressions": 1}],
- }
-
- payload = weekly_review.build_payload("newco.com", analysis, {"priors": {}}, None, site_profile={"canonical_url": "https://newco.com"})
- top_action = payload["action_plan"]["actions"][0]
- proposal = next(item for item in payload["queue_items"] if item["type"] == "action_proposal")
- stage_check = next(item for item in payload["verification"]["checks"] if item["name"] == "site stage playbook")
-
- self.assertEqual(payload["action_plan"]["site_stage"]["stage"], "seed")
- self.assertEqual(top_action["type"], "demand_seed_content")
- self.assertNotEqual(top_action["type"], "manual_review")
- self.assertEqual(top_action["approval_artifact_type"], "seed_content_portfolio_brief")
- self.assertIn("Google Ads/search-term data", top_action["recommended_deliverable"]["demand_sources"])
- self.assertEqual(proposal["action_type"], "demand_seed_content")
- self.assertEqual(stage_check["site_stage"]["stage"], "seed")
-
- def test_seed_stage_prioritizes_seed_portfolio_over_sparse_ctr_noise(self) -> None:
- analysis = {
- "site": "sc-domain:newco.com",
- "period": {"start": "2026-04-01", "end": "2026-04-28", "days": 28},
- "summary": {"clicks": 20, "impressions": 900, "ctr": 2.2, "position": 4.0},
- "branded_split": {},
- "comparison": {"declining_pages": [], "declining_queries": []},
- "ctr_gaps_by_page": [
- {
- "query": "emergency roof repair near me",
- "page": "https://newco.com/roof-repair",
- "clicks": 1,
- "impressions": 900,
- "ctr": 0.11,
- "position": 3.0,
- }
- ],
- "ctr_opportunities": [],
- "cannibalization": [],
- "top_pages": [],
- "top_queries": [],
- }
-
- payload = weekly_review.build_payload("newco.com", analysis, {"priors": {}}, None, site_profile={"canonical_url": "https://newco.com"})
- top_action = payload["action_plan"]["actions"][0]
- proposal = next(item for item in payload["queue_items"] if item["type"] == "action_proposal")
-
- self.assertEqual(payload["action_plan"]["site_stage"]["stage"], "seed")
- self.assertEqual(top_action["type"], "demand_seed_content")
- self.assertEqual(proposal["action_type"], "demand_seed_content")
- self.assertTrue(any(action["type"] == "meta_tags" for action in payload["action_plan"]["actions"][1:]))
-
- def test_declining_click_loss_uses_max_slice_not_page_plus_query_sum(self) -> None:
- analysis = {
- "comparison": {
- "declining_pages": [{"clicks_prev": 100, "clicks_now": 80}],
- "declining_queries": [{"clicks_prev": 95, "clicks_now": 75}],
- }
- }
-
- self.assertEqual(weekly_review.total_declining_click_loss(analysis), 20.0)
-
- def test_conversion_weighting_promotes_transactional_high_value_candidate(self) -> None:
- analysis = self.base_analysis()
- analysis["ctr_gaps_by_page"] = [
- {
- "query": "roof repair cost",
- "page": "https://www.example.com/blog/roof-repair-cost",
- "clicks": 2,
- "impressions": 5000,
- "ctr": 0.1,
- "position": 3.0,
- },
- {
- "query": "emergency roof repair near me",
- "page": "https://www.example.com/roof-repair",
- "clicks": 8,
- "impressions": 900,
- "ctr": 0.89,
- "position": 8.0,
- },
- ]
- business_context = {
- "site_stage": "harvest",
- "service_value_weights": {"emergency roof repair": 1.8, "roof repair cost": 0.6},
- "conversion_events": [
- {"name": "quote_request", "weight": 1.5, "paths": ["/roof-repair"], "intent_terms": ["near me", "emergency"]}
- ],
- "page_role_map": {
- "/roof-repair": "transactional quote landing page",
- "/blog/roof-repair-cost": "supporting informational page",
- },
- }
-
- payload = weekly_review.build_payload("example.com", analysis, {"priors": {}}, None, business_context)
- top_action = payload["action_plan"]["actions"][0]
-
- self.assertEqual(top_action["target"], "https://www.example.com/roof-repair")
- self.assertEqual(top_action["conversion_opportunity"]["matched_service"], "emergency roof repair")
- self.assertEqual(top_action["conversion_opportunity"]["matched_conversion_event"], "quote_request")
- self.assertGreater(top_action["priority_score"], top_action["raw_priority_score"])
-
- def test_action_proposal_includes_best_practice_alignment(self) -> None:
- analysis = self.base_analysis()
- analysis["ctr_gaps_by_page"] = [
- {
- "query": "roof repair cost",
- "page": "https://www.example.com/blog/roof-repair-cost",
- "clicks": 2,
- "impressions": 1681,
- "ctr": 0.12,
- "position": 2.8,
- }
- ]
-
- payload = weekly_review.build_payload("example.com", analysis, {"priors": {}}, None)
- proposal = next(item for item in payload["queue_items"] if item["type"] == "action_proposal")
- action = payload["action_plan"]["actions"][0]
- check = next(item for item in payload["verification"]["checks"] if item["name"] == "best practice alignment")
-
- self.assertEqual(check["status"], "pass")
- self.assertEqual(proposal["best_practice_alignment"]["reference"], "seo/shared/seo-best-practices.md")
- self.assertEqual(action["best_practice_alignment"]["primary_area"], "on_page_relevance_serp_packaging")
- self.assertTrue(proposal["best_practice_alignment"]["resources"])
-
- def test_all_current_action_types_have_best_practice_mapping(self) -> None:
- expected_action_types = {
- "canonical_or_tracking_investigation",
- "demand_seed_content",
- "query_intent_mapping",
- "local_intent_ownership",
- "content_refresh",
- "page_improvement",
- "meta_tags",
- "snippet_content_packaging",
- "internal_links",
- "technical_index_sitemap",
- "conversion_path_optimization",
- "manual_review",
- }
-
- self.assertEqual(set(weekly_review.ACTION_BEST_PRACTICE_AREAS), expected_action_types)
- for action_type, area in weekly_review.ACTION_BEST_PRACTICE_AREAS.items():
- with self.subTest(action_type=action_type):
- self.assertIn(area, weekly_review.SEO_BEST_PRACTICE_AREAS)
- alignment = weekly_review.best_practice_alignment_for_issue({"recommended_action_type": action_type})
- self.assertEqual(alignment["primary_area"], area)
- self.assertNotEqual(alignment["primary_area"], "unmapped")
-
- def test_classify_ranking_loss_pattern(self) -> None:
- """Position drop ≥1.5 → content_refresh, content_usefulness_trust."""
- top_query = {
- "query": "dog sitting seattle",
- "position_now": 8.5,
- "position_prev": 5.2,
- "ctr_now": 3.0,
- "ctr_prev": 5.0,
- "impressions_now": 500,
- "impressions_prev": 1200,
- }
- action_type, area, notes = weekly_review.classify_regression_pattern(top_query)
- self.assertEqual(action_type, "content_refresh")
- self.assertEqual(area, "content_usefulness_trust")
- self.assertTrue(any("dropped" in n for n in notes))
-
- def test_classify_serp_displacement_pattern(self) -> None:
- """CTR drop with stable position → snippet_content_packaging."""
- top_query = {
- "query": "dog sitting seattle",
- "position_now": 3.5,
- "position_prev": 3.2,
- "ctr_now": 2.0,
- "ctr_prev": 6.0,
- "impressions_now": 1200,
- "impressions_prev": 1100,
- }
- action_type, area, notes = weekly_review.classify_regression_pattern(top_query)
- self.assertEqual(action_type, "snippet_content_packaging")
- self.assertEqual(area, "on_page_relevance_serp_packaging")
- self.assertTrue(any("displacement" in n for n in notes))
-
- def test_classify_demand_fade_pattern(self) -> None:
- """Impression drop without position/CTR change → query_intent_mapping."""
- top_query = {
- "query": "dog sitting seattle",
- "position_now": 4.5,
- "position_prev": 4.2,
- "ctr_now": 5.0,
- "ctr_prev": 5.5,
- "impressions_now": 200,
- "impressions_prev": 800,
- }
- action_type, area, notes = weekly_review.classify_regression_pattern(top_query)
- self.assertEqual(action_type, "query_intent_mapping")
- self.assertEqual(area, "demand_intent_targeting")
- self.assertTrue(any("intent" in n or "demand" in n for n in notes))
-
- def test_classify_mixed_pattern(self) -> None:
- """Small changes across metrics → page_improvement."""
- top_query = {
- "query": "dog sitting seattle",
- "position_now": 4.5,
- "position_prev": 4.3,
- "ctr_now": 4.8,
- "ctr_prev": 5.0,
- "impressions_now": 800,
- "impressions_prev": 850,
- }
- action_type, area, notes = weekly_review.classify_regression_pattern(top_query)
- self.assertEqual(action_type, "page_improvement")
- self.assertTrue(any("Mixed" in n for n in notes))
-
- def test_classify_no_position_data(self) -> None:
- """Missing position data → fall through to other signals."""
- top_query = {
- "query": "dog sitting",
- "ctr_now": 2.0,
- "ctr_prev": 6.0,
- "impressions_now": 500,
- "impressions_prev": 520,
- }
- action_type, area, notes = weekly_review.classify_regression_pattern(top_query)
- self.assertEqual(action_type, "snippet_content_packaging")
-
- def test_decline_issue_uses_top_losing_query_ranking_loss(self) -> None:
- """decline_issue should set primary_query and reclassify to content_refresh when a top query shows ranking loss."""
- page = {
- "page": "https://example.com/dog-sitting-seattle",
- "clicks_now": 50,
- "clicks_prev": 100,
- "change_pct": -50.0,
- "top_losing_queries": [
- {
- "query": "dog sitting seattle",
- "clicks_now": 30,
- "clicks_prev": 70,
- "absolute_click_loss": 40,
- "change_pct": -57.1,
- "position_now": 7.5,
- "position_prev": 4.0,
- "ctr_now": 3.0,
- "ctr_prev": 5.0,
- "impressions_now": 600,
- "impressions_prev": 1400,
- }
- ],
- }
- issue = weekly_review.decline_issue(page)
- self.assertEqual(issue["primary_query"], "dog sitting seattle")
- self.assertEqual(issue["recommended_action_type"], "content_refresh")
- self.assertIn("top_losing_queries", issue)
- self.assertEqual(len(issue["top_losing_queries"]), 1)
-
- def test_decline_issue_uses_top_losing_query_serp_displacement(self) -> None:
- """decline_issue should reclassify to snippet_content_packaging when CTR drops with stable position."""
- page = {
- "page": "https://example.com/dog-sitting-seattle",
- "clicks_now": 60,
- "clicks_prev": 100,
- "change_pct": -40.0,
- "top_losing_queries": [
- {
- "query": "dog sitting seattle",
- "clicks_now": 35,
- "clicks_prev": 65,
- "absolute_click_loss": 30,
- "change_pct": -46.2,
- "position_now": 3.5,
- "position_prev": 3.2,
- "ctr_now": 2.0,
- "ctr_prev": 6.0,
- "impressions_now": 1200,
- "impressions_prev": 1100,
- }
- ],
- }
- issue = weekly_review.decline_issue(page)
- self.assertEqual(issue["recommended_action_type"], "snippet_content_packaging")
- self.assertEqual(issue["primary_query"], "dog sitting seattle")
-
- def test_decline_issue_distributed_no_primary_query(self) -> None:
- """When top query drives <30% of lost clicks, don't set primary_query or reclassify."""
- page = {
- "page": "https://example.com/dog-sitting-seattle",
- "clicks_now": 80,
- "clicks_prev": 100,
- "change_pct": -20.0,
- "top_losing_queries": [
- {
- "query": "dog sitting seattle",
- "clicks_now": 45,
- "clicks_prev": 50,
- "absolute_click_loss": 5,
- "change_pct": -10.0,
- "position_now": 3.5,
- "position_prev": 3.2,
- "ctr_now": 4.0,
- "ctr_prev": 4.5,
- "impressions_now": 1100,
- "impressions_prev": 1150,
- }
- ],
- }
- issue = weekly_review.decline_issue(page)
- # share_of_loss = 5/20 = 25% < 30%, so the query is only a diagnostic fallback.
- self.assertNotIn("primary_query", issue)
- self.assertEqual(issue["diagnostic_query"], "dog sitting seattle")
- self.assertEqual(issue["recommended_action_type"], "page_improvement")
- self.assertLess(issue["score_components"]["actionability_score"], 0.5)
- self.assertFalse(weekly_review.approval_readiness_for_issue(issue)["approval_ready"])
-
- def test_non_actionable_top_issues_do_not_queue_approval_proposal(self) -> None:
- analysis = self.base_analysis()
- analysis["_brand_terms"] = ["example"]
- analysis["comparison"]["declining_pages"] = [
- {
- "page": "https://www.example.com/blog/dog-boarding-cost",
- "clicks_now": 173,
- "clicks_prev": 247,
- "change_pct": -30.0,
- }
- ]
- analysis["comparison"]["page_query_decompositions"] = [
- {
- "page": "https://www.example.com/blog/dog-boarding-cost",
- "top_losing_queries": [
- {"query": "average cost to board a dog", "absolute_click_loss": 1, "clicks_now": 2, "clicks_prev": 3}
- ],
- }
- ]
- analysis["ctr_gaps_by_page"] = [
- {
- "query": "example",
- "page": "https://www.example.com/dog-boarding",
- "clicks": 17,
- "impressions": 941,
- "ctr": 1.81,
- "position": 1.2,
- }
- ]
-
- payload = weekly_review.build_payload("example.com", analysis, {"priors": {}}, None)
- proposals = [item for item in payload["queue_items"] if item["type"] == "action_proposal"]
-
- self.assertEqual(proposals, [])
- self.assertFalse(payload["action_plan"]["actions"][0]["approval_ready"])
- quality_gate = next(item for item in payload["verification"]["checks"] if item["name"] == "recommendation quality gate")
- self.assertEqual(quality_gate["status"], "warning")
-
- def test_unknown_action_type_warns_as_unmapped(self) -> None:
- alignment = weekly_review.best_practice_alignment_for_issue({"recommended_action_type": "core_web_vitals"})
-
- self.assertEqual(alignment["primary_area"], "unmapped")
- self.assertEqual(alignment["primary_area_label"], "Unmapped SEO action type")
- self.assertTrue(any("core_web_vitals" in note for note in alignment["notes"]))
-
- analysis = self.base_analysis()
- original = weekly_review.derive_candidate_issues
- weekly_review.derive_candidate_issues = lambda _analysis: [
- {
- "title": "Future action",
- "severity": "info",
- "confidence": 0.5,
- "evidence": ["synthetic"],
- "recommended_action_type": "core_web_vitals",
- "base_priority": 0.5,
- "priority_score": 0.5,
- "operator_judgment_notes": [],
- "score_components": {},
- "raw_target": None,
- "canonical_target": None,
- }
- ]
- try:
- payload = weekly_review.build_payload("example.com", analysis, {"priors": {}}, None)
- finally:
- weekly_review.derive_candidate_issues = original
-
- check = next(item for item in payload["verification"]["checks"] if item["name"] == "best practice alignment")
- action = payload["action_plan"]["actions"][0]
- self.assertEqual(check["status"], "warning")
- self.assertEqual(action["best_practice_alignment"]["primary_area"], "unmapped")
-
- def test_index_sitemap_consistency_creates_technical_issue(self) -> None:
- analysis = self.base_analysis()
- analysis["index_sitemap_consistency"] = {
- "noindex_in_sitemap": [
- {
- "url": "https://www.example.com/internal-thank-you",
- "canonical": "https://www.example.com/internal-thank-you",
- }
- ],
- "internal_links_to_redirects": [
- {
- "from": "https://www.example.com/old-roof-repair",
- "to": "https://www.example.com/roof-repair",
- "source_urls": ["https://www.example.com/services"],
- }
- ],
- }
-
- payload = weekly_review.build_payload(
- "example.com",
- analysis,
- {"priors": {}},
- None,
- {
- "site_stage": "harvest",
- "service_value_weights": {"roof repair": 1.0},
- "target_customer_priority": ["local homeowners"],
- "location_priorities": {"Portland": {"priority": "high"}},
- "conversion_events": [{"name": "quote_request", "paths": ["/roof-repair"]}],
- "booking_intent_hierarchy": {"highest_priority": ["roof repair"]},
- "local_proof_points": ["licensed team"],
- "serp_competitor_positioning": {"roof repair": ["Angi"]},
- "page_role_map": {"/roof-repair": "transactional quote landing page"},
- },
- )
- top_action = payload["action_plan"]["actions"][0]
- proposal = next(item for item in payload["queue_items"] if item["type"] == "action_proposal")
- gate_check = next(item for item in payload["verification"]["checks"] if item["name"] == "SEO review gates")
-
- self.assertEqual(top_action["type"], "technical_index_sitemap")
- self.assertEqual(top_action["best_practice_alignment"]["primary_area"], "search_eligibility_indexability")
- self.assertEqual(top_action["seo_review_gate_status"], "pass")
- self.assertEqual(proposal["action_type"], "technical_index_sitemap")
- self.assertEqual(gate_check["status"], "pass")
-
- def test_cannibalization_gate_requires_explicit_page_roles(self) -> None:
- analysis = self.base_analysis()
- analysis["cannibalization"] = [
- {
- "query": "roof repair pricing",
- "winner_page": "https://www.example.com/roof-repair",
- "loser_pages": ["https://www.example.com/blog/roof-repair-cost"],
- "competing_pages": [
- {"page": "https://www.example.com/roof-repair", "position": 4.0, "clicks": 8},
- {"page": "https://www.example.com/blog/roof-repair-cost", "position": 5.2, "clicks": 6},
- ],
- "total_impressions": 2500,
- "total_clicks": 14,
- }
- ]
-
- payload = weekly_review.build_payload(
- "example.com",
- analysis,
- {"priors": {}},
- None,
- {
- "site_stage": "harvest",
- "service_value_weights": {"roof repair": 1.0},
- "target_customer_priority": ["local homeowners"],
- "location_priorities": {"Portland": {"priority": "high"}},
- "conversion_events": [{"name": "quote_request", "paths": ["/roof-repair"]}],
- "booking_intent_hierarchy": {"highest_priority": ["roof repair pricing"]},
- "local_proof_points": ["licensed team"],
- "serp_competitor_positioning": {"roof repair pricing": ["Angi"]},
- },
- )
- action = payload["action_plan"]["actions"][0]
- cannibal_gate = next(gate for gate in action["seo_review_gates"] if gate["name"] == "cannibalization intent safety")
- no_ship_gate = next(gate for gate in action["seo_review_gates"] if gate["name"] == "Gemini NO-SHIP review")
-
- self.assertEqual(action["type"], "internal_links")
- self.assertEqual(cannibal_gate["status"], "warning")
- self.assertEqual(no_ship_gate["status"], "warning")
- self.assertEqual(action["seo_review_gate_status"], "warning")
-
- def test_cannibalization_gate_passes_with_winner_and_support_roles(self) -> None:
- analysis = self.base_analysis()
- analysis["cannibalization"] = [
- {
- "query": "roof repair pricing",
- "winner_page": "https://www.example.com/roof-repair",
- "loser_pages": ["https://www.example.com/blog/roof-repair-cost"],
- "total_impressions": 2500,
- "total_clicks": 14,
- }
- ]
- business_context = {
- "site_stage": "harvest",
- "service_value_weights": {"roof repair": 1.0},
- "target_customer_priority": ["local homeowners"],
- "location_priorities": {"Portland": {"priority": "high"}},
- "conversion_events": [{"name": "quote_request", "paths": ["/roof-repair"]}],
- "booking_intent_hierarchy": {"highest_priority": ["roof repair pricing"]},
- "local_proof_points": ["licensed team"],
- "serp_competitor_positioning": {"roof repair pricing": ["Angi"]},
- "page_role_map": {
- "/roof-repair": "transactional quote landing page",
- "/blog/roof-repair-cost": "supporting informational page",
- },
- }
-
- payload = weekly_review.build_payload("example.com", analysis, {"priors": {}}, None, business_context)
- action = payload["action_plan"]["actions"][0]
- cannibal_gate = next(gate for gate in action["seo_review_gates"] if gate["name"] == "cannibalization intent safety")
-
- self.assertEqual(cannibal_gate["status"], "pass")
- self.assertEqual(action["seo_review_gate_status"], "pass")
- self.assertEqual(next(item for item in payload["queue_items"] if item["type"] == "action_proposal")["seo_review_gate_status"], "pass")
-
- def test_content_depth_gate_flags_thin_page_before_approval_review(self) -> None:
- analysis = self.base_analysis()
- analysis["ctr_gaps_by_page"] = [
- {
- "query": "roof repair cost",
- "page": "https://www.example.com/blog/roof-repair-cost",
- "clicks": 2,
- "impressions": 1681,
- "ctr": 0.12,
- "position": 2.8,
- }
- ]
- with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
- source = root / "content" / "blogs"
- source.mkdir(parents=True)
- (source / "roof-repair-cost.mdx").write_text(
- "---\n"
- "title: \"Roof Repair Cost\"\n"
- "description: \"Roof repair cost.\"\n"
- "---\n\n"
- "# Roof Repair Cost\n\n"
- "Prices vary. Request quote.\n",
- encoding="utf-8",
- )
- original = weekly_review.serp_snapshot_for_query
- weekly_review.serp_snapshot_for_query = lambda query, site_id, live=False: {
- "source": "test_serp",
- "status": "ok",
- "query": query,
- "results": [{"title": "Roof Repair Cost", "domain": "example.com", "snippet": "$55-$90"}],
- "answer_like_serp": True,
- }
- try:
- payload = weekly_review.build_payload(
- "example.com",
- analysis,
- {"priors": {}},
- None,
- {
- "site_stage": "harvest",
- "service_value_weights": {"roof repair": 1.0},
- "target_customer_priority": ["local homeowners"],
- "location_priorities": {"Portland": {"priority": "high"}},
- "conversion_events": [{"name": "quote_request", "paths": ["/blog/roof-repair-cost"]}],
- "booking_intent_hierarchy": {"highest_priority": ["roof repair cost"]},
- "local_proof_points": ["licensed team"],
- "serp_competitor_positioning": {"roof repair cost": ["Angi"]},
- "page_role_map": {"/blog/roof-repair-cost": "supporting informational page"},
- },
- site_profile={"source_roots": [str(root)]},
- live_diagnostics=True,
- )
- finally:
- weekly_review.serp_snapshot_for_query = original
-
- action = payload["action_plan"]["actions"][0]
- depth_gate = next(gate for gate in action["seo_review_gates"] if gate["name"] == "content depth")
-
- self.assertEqual(depth_gate["status"], "warning")
- self.assertLess(depth_gate["depth_score"]["score"], 0.7)
- self.assertEqual(action["seo_review_gate_status"], "warning")
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/openclaw/workspace-template/README.md b/openclaw/workspace-template/README.md
deleted file mode 100644
index 783dd818..00000000
--- a/openclaw/workspace-template/README.md
+++ /dev/null
@@ -1,5 +0,0 @@
-# Workspace Template
-
-This directory documents the runtime layout created under `~/.toprank/openclaw`.
-
-The files here are templates and examples only. Do not store live operator data in the git repo.
diff --git a/openclaw/workspace-template/portfolio.json b/openclaw/workspace-template/portfolio.json
deleted file mode 100644
index 6938c73d..00000000
--- a/openclaw/workspace-template/portfolio.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "schema_version": "1",
- "portfolio_id": "default",
- "sites": []
-}
diff --git a/openclaw/workspace-template/schedule.json b/openclaw/workspace-template/schedule.json
deleted file mode 100644
index 34003973..00000000
--- a/openclaw/workspace-template/schedule.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "schema_version": "1",
- "upcoming": []
-}
diff --git a/seo/content-planner/SKILL.md b/seo/content-planner/SKILL.md
index ebe8c33d..26d7d323 100644
--- a/seo/content-planner/SKILL.md
+++ b/seo/content-planner/SKILL.md
@@ -165,8 +165,7 @@ Schedule one post per week, P0s first. Format every entry against this schema:
| `published` | publisher POSTed to the webhook with 2xx | `publish_pending.py` |
| `failed` | publisher got 4xx; needs user fix | `publish_pending.py` |
-The publisher (`openclaw/bin/publish_pending.py`, opt-in via OpenClaw cron)
-only picks up entries with `status === "ready_to_publish"` AND a non-empty
+A publisher should only pick up entries with `status === "ready_to_publish"` AND a non-empty
`bodyPath`. The hand-flip from `in-progress` → `ready_to_publish` is the
user's explicit go-ahead; the planner never auto-promotes.
diff --git a/test/openclaw/test_launchd_install.py b/test/openclaw/test_launchd_install.py
deleted file mode 100644
index 4d7f53f2..00000000
--- a/test/openclaw/test_launchd_install.py
+++ /dev/null
@@ -1,24 +0,0 @@
-import os
-import subprocess
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-
-
-def test_install_launchd_script_writes_valid_plist(tmp_path):
- output_dir = tmp_path / 'LaunchAgents'
- runtime_home = tmp_path / 'runtime'
- script = REPO_ROOT / 'openclaw' / 'install' / 'install-launchd.sh'
- env = os.environ.copy()
- env['TOPRANK_OPENCLAW_HOME'] = str(runtime_home)
- subprocess.run(
- [str(script), '--write-only', '--output-dir', str(output_dir), '--interval', '1800'],
- check=True,
- env=env,
- )
- plists = list(output_dir.glob('*.plist'))
- assert len(plists) == 1
- contents = plists[0].read_text()
- assert 'run_scheduler.py' in contents
- assert '1800' in contents
diff --git a/test/openclaw/test_openclaw_mvp.py b/test/openclaw/test_openclaw_mvp.py
deleted file mode 100644
index 24a93dff..00000000
--- a/test/openclaw/test_openclaw_mvp.py
+++ /dev/null
@@ -1,483 +0,0 @@
-import json
-import os
-import subprocess
-import sys
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-
-
-def test_all_schema_files_are_valid_json():
- schema_dir = REPO_ROOT / 'openclaw' / 'artifacts' / 'schemas'
- for path in schema_dir.glob('*.json'):
- data = json.loads(path.read_text())
- assert data['type'] == 'object'
- assert '$schema' in data
-
-
-def test_example_action_plan_has_expected_shape():
- path = REPO_ROOT / 'openclaw' / 'artifacts' / 'examples' / 'action-plan.json'
- data = json.loads(path.read_text())
- assert data['site_id'] == 'example.com'
- assert data['actions']
- assert data['actions'][0]['requires_approval'] is True
-
-
-def test_bootstrap_workspace_and_site(tmp_path):
- env = os.environ.copy()
- env['TOPRANK_OPENCLAW_HOME'] = str(tmp_path / 'runtime')
- subprocess.run([sys.executable, str(REPO_ROOT / 'openclaw' / 'bin' / 'bootstrap_workspace.py')], check=True, env=env)
- subprocess.run([sys.executable, str(REPO_ROOT / 'openclaw' / 'bin' / 'bootstrap_site.py'), 'https://Example.com'], check=True, env=env)
- site_root = tmp_path / 'runtime' / 'sites' / 'example.com'
- assert (tmp_path / 'runtime' / 'portfolio.json').exists()
- assert (site_root / 'site-profile.json').exists()
- assert (site_root / 'queue').is_dir()
- profile = json.loads((site_root / 'site-profile.json').read_text())
- assert profile['site_id'] == 'example.com'
-
-
-def test_onboard_site_updates_portfolio_and_goal(tmp_path):
- env = os.environ.copy()
- env['TOPRANK_OPENCLAW_HOME'] = str(tmp_path / 'runtime')
- subprocess.run(
- [
- sys.executable,
- str(REPO_ROOT / 'openclaw' / 'bin' / 'onboard_site.py'),
- 'https://example.com',
- '--display-name',
- 'Example Site',
- '--brand-terms',
- 'Example,Example Site',
- '--business-weight',
- '0.8',
- '--cadence',
- 'weekly',
- '--goal-type',
- 'grow_non_brand_clicks',
- '--primary-metric',
- 'non_brand_clicks_28d',
- ],
- check=True,
- env=env,
- )
- portfolio = json.loads((tmp_path / 'runtime' / 'portfolio.json').read_text())
- assert portfolio['sites'][0]['site_id'] == 'example.com'
- assert portfolio['sites'][0]['business_weight'] == 0.8
- site_root = tmp_path / 'runtime' / 'sites' / 'example.com'
- profile = json.loads((site_root / 'site-profile.json').read_text())
- assert profile['display_name'] == 'Example Site'
- assert profile['brand_terms'] == ['Example', 'Example Site']
- goals = json.loads((site_root / 'goals.json').read_text())
- assert goals['active']
- assert goals['active'][0]['primary_metric'] == 'non_brand_clicks_28d'
-
-
-def test_persist_run_writes_artifacts_and_queue(tmp_path):
- env = os.environ.copy()
- env['TOPRANK_OPENCLAW_HOME'] = str(tmp_path / 'runtime')
- subprocess.run([sys.executable, str(REPO_ROOT / 'openclaw' / 'bin' / 'bootstrap_site.py'), 'example.com'], check=True, env=env)
- payload_path = tmp_path / 'payload.json'
- payload_path.write_text((REPO_ROOT / 'openclaw' / 'artifacts' / 'examples' / 'weekly-review-payload.json').read_text())
- subprocess.run(
- [
- sys.executable,
- str(REPO_ROOT / 'openclaw' / 'bin' / 'persist_run.py'),
- 'example.com',
- '--payload-file',
- str(payload_path),
- ],
- check=True,
- env=env,
- )
- runs_dir = tmp_path / 'runtime' / 'sites' / 'example.com' / 'runs'
- run_dirs = [path for path in runs_dir.iterdir() if path.is_dir()]
- assert len(run_dirs) == 1
- run_dir = run_dirs[0]
- assert (run_dir / 'audit.json').exists()
- assert (run_dir / 'action-plan.json').exists()
- assert (run_dir / 'verification.json').exists()
- latest = json.loads((tmp_path / 'runtime' / 'sites' / 'example.com' / 'latest-state.json').read_text())
- assert 'Homepage CTR' in latest['summary']
- queue_dir = tmp_path / 'runtime' / 'sites' / 'example.com' / 'queue'
- queue_files = list(queue_dir.glob('*.json'))
- assert len(queue_files) == 1
- queue_item = json.loads(queue_files[0].read_text())
- assert queue_item['type'] == 'feedback_check'
- assert queue_item['baseline_metrics']['organic_clicks_28d'] == 100
- assert queue_item['primary_metric'] == 'non_brand_clicks_28d'
- assert queue_item['action_type'] == 'meta_tags'
- schedule = json.loads((tmp_path / 'runtime' / 'schedule.json').read_text())
- assert schedule['upcoming']
- assert schedule['upcoming'][0]['item_id'] == queue_item['item_id']
-
-
-def test_improve_page_persists_proposal_and_patch_set(tmp_path):
- env = os.environ.copy()
- env['TOPRANK_OPENCLAW_HOME'] = str(tmp_path / 'runtime')
- subprocess.run([sys.executable, str(REPO_ROOT / 'openclaw' / 'bin' / 'bootstrap_site.py'), 'example.com'], check=True, env=env)
- subprocess.run(
- [
- sys.executable,
- str(REPO_ROOT / 'openclaw' / 'bin' / 'improve_page.py'),
- 'example.com',
- '--url',
- 'https://example.com/services/roof-repair',
- '--issue-summary',
- 'Service page CTR is low and schema is missing.',
- '--proposal-summary',
- 'Draft new title/meta candidates and add LocalBusiness schema.',
- '--patch-path',
- 'pages/services/roof-repair.tsx',
- '--patch-summary',
- 'Add schema and update metadata fields.',
- ],
- check=True,
- env=env,
- )
- run_dirs = list((tmp_path / 'runtime' / 'sites' / 'example.com' / 'runs').iterdir())
- assert len(run_dirs) == 1
- run_dir = run_dirs[0]
- assert (run_dir / 'proposal.json').exists()
- assert (run_dir / 'patch-set.json').exists()
- proposal = json.loads((run_dir / 'proposal.json').read_text())
- assert proposal['target'] == 'https://example.com/services/roof-repair'
- patch_set = json.loads((run_dir / 'patch-set.json').read_text())
- assert patch_set['patches'][0]['path'] == 'pages/services/roof-repair.tsx'
-
-
-def test_investigate_drop_creates_recovery_plan_and_followups(tmp_path):
- env = os.environ.copy()
- env['TOPRANK_OPENCLAW_HOME'] = str(tmp_path / 'runtime')
- subprocess.run([sys.executable, str(REPO_ROOT / 'openclaw' / 'bin' / 'bootstrap_site.py'), 'example.com'], check=True, env=env)
- subprocess.run(
- [
- sys.executable,
- str(REPO_ROOT / 'openclaw' / 'bin' / 'investigate_drop.py'),
- 'example.com',
- '--summary',
- 'Organic clicks fell sharply on the primary service cluster.',
- '--likely-cause',
- 'A service page may have fallen out of the index.',
- '--likely-cause',
- 'Homepage CTR declined after a copy update.',
- '--target-url',
- 'https://example.com/services/roof-repair',
- ],
- check=True,
- env=env,
- )
- run_dirs = list((tmp_path / 'runtime' / 'sites' / 'example.com' / 'runs').iterdir())
- assert len(run_dirs) == 1
- run_dir = run_dirs[0]
- audit = json.loads((run_dir / 'audit.json').read_text())
- assert len(audit['issues']) == 2
- queue_files = list((tmp_path / 'runtime' / 'sites' / 'example.com' / 'queue').glob('*.json'))
- queue_types = {json.loads(path.read_text())['type'] for path in queue_files}
- assert 'feedback_check' in queue_types
- assert 'improve_page' in queue_types
-
-
-def test_followups_due_lists_due_items(tmp_path):
- env = os.environ.copy()
- env['TOPRANK_OPENCLAW_HOME'] = str(tmp_path / 'runtime')
- subprocess.run([sys.executable, str(REPO_ROOT / 'openclaw' / 'bin' / 'bootstrap_site.py'), 'example.com'], check=True, env=env)
- payload_path = tmp_path / 'payload.json'
- payload = json.loads((REPO_ROOT / 'openclaw' / 'artifacts' / 'examples' / 'weekly-review-payload.json').read_text())
- payload['queue_items'][0]['due_at'] = '2026-04-01T00:00:00Z'
- payload_path.write_text(json.dumps(payload, indent=2) + '\n')
- subprocess.run(
- [
- sys.executable,
- str(REPO_ROOT / 'openclaw' / 'bin' / 'persist_run.py'),
- 'example.com',
- '--payload-file',
- str(payload_path),
- ],
- check=True,
- env=env,
- )
- result = subprocess.run(
- [
- sys.executable,
- str(REPO_ROOT / 'openclaw' / 'bin' / 'followups_due.py'),
- '--as-of',
- '2026-04-15T00:00:00Z',
- ],
- check=True,
- env=env,
- capture_output=True,
- text=True,
- )
- data = json.loads(result.stdout)
- assert data['count'] == 1
- assert data['items'][0]['type'] == 'feedback_check'
-
-
-def test_hydrate_followup_gsc_updates_observed_metrics(tmp_path):
- env = os.environ.copy()
- env['TOPRANK_OPENCLAW_HOME'] = str(tmp_path / 'runtime')
- subprocess.run([sys.executable, str(REPO_ROOT / 'openclaw' / 'bin' / 'bootstrap_site.py'), 'example.com'], check=True, env=env)
- payload_path = tmp_path / 'payload.json'
- payload = json.loads((REPO_ROOT / 'openclaw' / 'artifacts' / 'examples' / 'weekly-review-payload.json').read_text())
- payload_path.write_text(json.dumps(payload, indent=2) + '\n')
- subprocess.run(
- [sys.executable, str(REPO_ROOT / 'openclaw' / 'bin' / 'persist_run.py'), 'example.com', '--payload-file', str(payload_path)],
- check=True,
- env=env,
- )
- subprocess.run(
- [
- sys.executable,
- str(REPO_ROOT / 'openclaw' / 'bin' / 'hydrate_followup_gsc.py'),
- 'example.com',
- 'followup_example_homepage_ctr_14d',
- '--analysis-file',
- str(REPO_ROOT / 'openclaw' / 'artifacts' / 'examples' / 'gsc-analysis-sample.json'),
- ],
- check=True,
- env=env,
- )
- queue_path = tmp_path / 'runtime' / 'sites' / 'example.com' / 'queue' / 'followup_example_homepage_ctr_14d.json'
- queue_item = json.loads(queue_path.read_text())
- assert queue_item['observed_metrics']['non_brand_clicks_28d'] == 110.0
- assert queue_item['observed_metrics']['organic_clicks_28d'] == 150.0
-
-
-def test_record_followup_metrics_and_score_script(tmp_path):
- env = os.environ.copy()
- env['TOPRANK_OPENCLAW_HOME'] = str(tmp_path / 'runtime')
- subprocess.run([sys.executable, str(REPO_ROOT / 'openclaw' / 'bin' / 'bootstrap_site.py'), 'example.com'], check=True, env=env)
- payload_path = tmp_path / 'payload.json'
- payload = json.loads((REPO_ROOT / 'openclaw' / 'artifacts' / 'examples' / 'weekly-review-payload.json').read_text())
- payload['queue_items'][0]['due_at'] = '2026-04-01T00:00:00Z'
- payload['queue_items'][0]['baseline_metrics'] = {'organic_clicks_28d': 100, 'conversions_28d': 10}
- payload['queue_items'][0]['primary_metric'] = 'organic_clicks_28d'
- payload['queue_items'][0]['success_threshold_pct'] = 0.1
- payload['queue_items'][0]['guardrail_metrics'] = [{'metric': 'conversions_28d', 'direction': 'higher_better', 'max_worsen_pct': 0.05}]
- payload_path.write_text(json.dumps(payload, indent=2) + '\n')
- subprocess.run(
- [sys.executable, str(REPO_ROOT / 'openclaw' / 'bin' / 'persist_run.py'), 'example.com', '--payload-file', str(payload_path)],
- check=True,
- env=env,
- )
- item_id = payload['queue_items'][0]['item_id']
- subprocess.run(
- [
- sys.executable,
- str(REPO_ROOT / 'openclaw' / 'bin' / 'record_followup_metrics.py'),
- 'example.com',
- item_id,
- '--observed-metric',
- 'organic_clicks_28d=125',
- '--observed-metric',
- 'conversions_28d=11',
- ],
- check=True,
- env=env,
- )
- queue_path = tmp_path / 'runtime' / 'sites' / 'example.com' / 'queue' / f'{item_id}.json'
- score_result = subprocess.run(
- [sys.executable, str(REPO_ROOT / 'openclaw' / 'bin' / 'score_feedback.py'), '--item-file', str(queue_path)],
- check=True,
- env=env,
- capture_output=True,
- text=True,
- )
- score = json.loads(score_result.stdout)
- assert score['outcome'] == 'win'
- assert score['primary_metric'] == 'organic_clicks_28d'
-
-
-def test_run_scheduler_processes_due_feedback_checks(tmp_path):
- env = os.environ.copy()
- env['TOPRANK_OPENCLAW_HOME'] = str(tmp_path / 'runtime')
- subprocess.run([sys.executable, str(REPO_ROOT / 'openclaw' / 'bin' / 'bootstrap_site.py'), 'example.com'], check=True, env=env)
- payload_path = tmp_path / 'payload.json'
- payload = json.loads((REPO_ROOT / 'openclaw' / 'artifacts' / 'examples' / 'weekly-review-payload.json').read_text())
- payload['queue_items'][0]['due_at'] = '2026-04-01T00:00:00Z'
- payload['queue_items'][0]['baseline_metrics'] = {'organic_clicks_28d': 100}
- payload['queue_items'][0]['observed_metrics'] = {'organic_clicks_28d': 120}
- payload['queue_items'][0]['primary_metric'] = 'organic_clicks_28d'
- payload['queue_items'][0]['success_threshold_pct'] = 0.1
- payload_path.write_text(json.dumps(payload, indent=2) + '\n')
- subprocess.run(
- [sys.executable, str(REPO_ROOT / 'openclaw' / 'bin' / 'persist_run.py'), 'example.com', '--payload-file', str(payload_path)],
- check=True,
- env=env,
- )
- result = subprocess.run(
- [sys.executable, str(REPO_ROOT / 'openclaw' / 'bin' / 'run_scheduler.py'), '--as-of', '2026-04-15T00:00:00Z'],
- check=True,
- env=env,
- capture_output=True,
- text=True,
- )
- data = json.loads(result.stdout)
- assert len(data['processed']) == 1
- schedule = json.loads((tmp_path / 'runtime' / 'schedule.json').read_text())
- assert schedule['upcoming'][0]['status'] == 'processed'
- feedback_dir = tmp_path / 'runtime' / 'sites' / 'example.com' / 'feedback'
- feedback_files = list(feedback_dir.glob('*.json'))
- assert len(feedback_files) == 1
- feedback = json.loads(feedback_files[0].read_text())
- assert feedback['status'] == 'win'
- learned = json.loads((tmp_path / 'runtime' / 'sites' / 'example.com' / 'learned-patterns.json').read_text())
- assert learned['priors']['meta_tags::organic_clicks_28d']['wins'] == 1
-
-
-def test_run_scheduler_surfaces_manual_attention_items(tmp_path):
- env = os.environ.copy()
- env['TOPRANK_OPENCLAW_HOME'] = str(tmp_path / 'runtime')
- subprocess.run([sys.executable, str(REPO_ROOT / 'openclaw' / 'bin' / 'bootstrap_site.py'), 'example.com'], check=True, env=env)
- schedule_path = tmp_path / 'runtime' / 'schedule.json'
- schedule = {'schema_version': '1', 'upcoming': [{'item_id': 'manual_001', 'site_id': 'example.com', 'type': 'improve_page', 'status': 'pending', 'due_at': '2026-04-01T00:00:00Z'}]}
- schedule_path.write_text(json.dumps(schedule, indent=2) + '\n')
- queue_path = tmp_path / 'runtime' / 'sites' / 'example.com' / 'queue' / 'manual_001.json'
- queue_path.write_text(json.dumps(schedule['upcoming'][0], indent=2) + '\n')
- result = subprocess.run(
- [sys.executable, str(REPO_ROOT / 'openclaw' / 'bin' / 'run_scheduler.py'), '--as-of', '2026-04-15T00:00:00Z'],
- check=True,
- env=env,
- capture_output=True,
- text=True,
- )
- data = json.loads(result.stdout)
- assert len(data['manual_attention']) == 1
- updated_schedule = json.loads(schedule_path.read_text())
- assert updated_schedule['upcoming'][0]['status'] == 'ready_for_attention'
-
-
-def test_weekly_review_uses_learned_priors_and_seeds_followup(tmp_path):
- env = os.environ.copy()
- env['TOPRANK_OPENCLAW_HOME'] = str(tmp_path / 'runtime')
- subprocess.run(
- [
- sys.executable,
- str(REPO_ROOT / 'openclaw' / 'bin' / 'onboard_site.py'),
- 'https://example.com',
- '--display-name',
- 'Example',
- '--goal-type',
- 'grow_non_brand_clicks',
- '--primary-metric',
- 'non_brand_clicks_28d',
- ],
- check=True,
- env=env,
- )
- learned_path = tmp_path / 'runtime' / 'sites' / 'example.com' / 'learned-patterns.json'
- learned_path.write_text(json.dumps({
- 'site_id': 'example.com',
- 'observations': [],
- 'priors': {
- 'meta_tags::non_brand_clicks_28d': {
- 'action_type': 'meta_tags',
- 'primary_metric': 'non_brand_clicks_28d',
- 'sample_size': 3,
- 'wins': 2,
- 'neutral': 1,
- 'losses': 0,
- 'inconclusive': 0,
- 'avg_primary_change': 0.18,
- 'confidence': 0.72,
- 'last_outcome': 'win',
- 'last_updated_at': '2026-04-01T00:00:00Z'
- },
- 'page_improvement::non_brand_clicks_28d': {
- 'action_type': 'page_improvement',
- 'primary_metric': 'non_brand_clicks_28d',
- 'sample_size': 2,
- 'wins': 0,
- 'neutral': 0,
- 'losses': 2,
- 'inconclusive': 0,
- 'avg_primary_change': -0.15,
- 'confidence': 0.8,
- 'last_outcome': 'loss',
- 'last_updated_at': '2026-04-01T00:00:00Z'
- }
- }
- }, indent=2) + '\n')
- subprocess.run(
- [
- sys.executable,
- str(REPO_ROOT / 'openclaw' / 'bin' / 'weekly_review.py'),
- 'example.com',
- '--analysis-file',
- str(REPO_ROOT / 'openclaw' / 'artifacts' / 'examples' / 'gsc-analysis-sample.json'),
- ],
- check=True,
- env=env,
- )
- run_dirs = sorted((tmp_path / 'runtime' / 'sites' / 'example.com' / 'runs').iterdir())
- run_dir = run_dirs[-1]
- action_plan = json.loads((run_dir / 'action-plan.json').read_text())
- assert action_plan['actions'][0]['type'] == 'snippet_content_packaging'
- queue_files = list((tmp_path / 'runtime' / 'sites' / 'example.com' / 'queue').glob('*.json'))
- queue_items = [json.loads(path.read_text()) for path in queue_files]
- queue_by_type = {item['type']: item for item in queue_items}
- assert set(queue_by_type) == {'business_context_request', 'action_proposal'}
- assert queue_by_type['business_context_request']['status'] == 'pending_input'
- assert queue_by_type['business_context_request']['business_context_questions']
- queue_item = queue_by_type['action_proposal']
- assert queue_item['baseline_metrics']['non_brand_clicks_28d'] == 110.0
- assert queue_item['primary_metric'] == 'non_brand_clicks_28d'
- assert queue_item['action_type'] == 'snippet_content_packaging'
- assert 'complete_business_context' in queue_item['approval_preconditions']
-
-
-def test_portfolio_review_ranks_sites(tmp_path):
- env = os.environ.copy()
- env['TOPRANK_OPENCLAW_HOME'] = str(tmp_path / 'runtime')
- subprocess.run(
- [
- sys.executable,
- str(REPO_ROOT / 'openclaw' / 'bin' / 'onboard_site.py'),
- 'https://alpha.example',
- '--display-name',
- 'Alpha',
- '--business-weight',
- '1.0',
- ],
- check=True,
- env=env,
- )
- subprocess.run(
- [
- sys.executable,
- str(REPO_ROOT / 'openclaw' / 'bin' / 'onboard_site.py'),
- 'https://beta.example',
- '--display-name',
- 'Beta',
- '--business-weight',
- '0.5',
- ],
- check=True,
- env=env,
- )
- latest_alpha = tmp_path / 'runtime' / 'sites' / 'alpha.example' / 'latest-state.json'
- latest_beta = tmp_path / 'runtime' / 'sites' / 'beta.example' / 'latest-state.json'
- latest_alpha.write_text(json.dumps({
- 'site_id': 'alpha.example',
- 'summary': 'Alpha has a critical indexing regression.',
- 'open_issues': [{'title': 'Critical indexing regression', 'severity': 'critical'}],
- 'recent_actions': []
- }, indent=2) + '\n')
- latest_beta.write_text(json.dumps({
- 'site_id': 'beta.example',
- 'summary': 'Beta is stable.',
- 'open_issues': [],
- 'recent_actions': []
- }, indent=2) + '\n')
- result = subprocess.run(
- [sys.executable, str(REPO_ROOT / 'openclaw' / 'bin' / 'portfolio_review.py')],
- check=True,
- env=env,
- capture_output=True,
- text=True,
- )
- data = json.loads(result.stdout)
- assert data['recommended_focus_site'] == 'alpha.example'
- review_dir = tmp_path / 'runtime' / 'portfolio-reviews'
- assert any(review_dir.glob('*.json'))