# 🕸️ Site Diff Engine - Whole-Site Change Detection (`that_red_bird/site-diff-engine`) Actor

🕸️ Crawls an entire site and diffs it run over run: pages ADDED, REMOVED, CHANGED (structural vs body) or UNCHANGED. ✅ Canonical URL handling collapses /page, /page/ and ?utm\_source=x into one page, and flags near-duplicate templated pages within a run.

- **URL**: https://apify.com/that\_red\_bird/site-diff-engine.md
- **Developed by:** [mohamed alaya](https://apify.com/that_red_bird) (community)
- **Categories:** SEO tools, Developer tools
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per event

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/platform/actors/running/actors-in-store#pay-per-event

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

## Site Diff Engine

Most "change monitors" watch one page. This one watches a whole **site** and tells you what
actually moved between two runs — pages that appeared, pages that vanished, and pages whose
content or SEO surface really changed. Timestamps, tokens and view counters never trigger a
false alert, and neither does a trailing slash.

### How it works

1. **Discover** every page via `sitemap.xml` / `sitemap_index.xml`, same-site link-following, or
   both (`crawlMode: "auto"`), capped by `maxPages`.
2. **Canonicalize** every URL so `/page`, `/page/`, `/page/index.html` and
   `/page?utm_source=x&ref=y` all collapse to the exact same page identity — a page's own
   `<link rel="canonical">` wins when present. This is the single most important correctness
   detail: without it, every run reports phantom adds and removes.
3. **Fingerprint** each page's cleaned main content (nav/ads/footers stripped, then timestamps,
   CSRF tokens, session ids and view counters stripped) separately from its title / H1 / meta
   description — so a copy edit and an SEO-relevant change never look the same.
4. **Diff** this run's site snapshot against the last one: `ADDED`, `REMOVED`, `CHANGED`
   (`changeCategory`: `STRUCTURAL`, `BODY` or `BOTH`), `UNCHANGED`.
5. **Flag near-duplicates** within the same run — thin category pages, boilerplate legal pages,
   auto-generated tag pages — via word-shingle Jaccard similarity.

The first run on a site only records a baseline (`status: "BASELINE"`) — it never reports the
whole site as "changed" just because nothing existed before.

### Input

```json
{
  "startUrl": "https://example.com/",
  "maxPages": 200,
  "crawlMode": "auto",
  "urlExcludePatterns": ["/(cart|checkout|login)(/|$)"],
  "onlyChanges": true
}
```

### Output

One dataset row per page:

| field | meaning |
|---|---|
| `status` | `BASELINE` · `ADDED` · `REMOVED` · `CHANGED` · `UNCHANGED` |
| `changeCategory` | `STRUCTURAL` (title/H1/meta), `BODY`, `BOTH`, or `null` |
| `title` / `h1` / `metaDescription` | current values (null for `REMOVED`) |
| `previousTitle` / `previousH1` / `previousMetaDescription` | prior run's values |
| `nearDuplicateOf` | canonical URLs of pages this one is near-identical to |

`SUMMARY` in the key-value store gives run-level counts (added/removed/changed/unchanged,
structural vs body change counts, near-duplicate page count).

### Honest limits

- **No JavaScript rendering.** Pages that build their body client-side (SPA shells) will
  fingerprint as near-empty. Server-rendered and static sites work well.
- **State is deliberately lean.** Only fingerprints and the small structural fields (title/H1/
  meta) are persisted between runs, not full page bodies — so a `CHANGED` body row tells you a
  page changed, not a word-level diff of what changed.
- **Near-duplicate detection is O(n²)** over the pages in one run. Fine at the `maxPages` scale
  this Actor targets; keep `maxPages` sane on very large sites.
- **`robots.txt` is not consulted.** Use `urlExcludePatterns` to keep the crawl off pages you
  don't want touched.
- Canonicalization is URL-rule + `<link rel="canonical">` based. Sites with exotic session-based
  URL schemes (path-embedded session ids, etc.) may need `urlExcludePatterns` to avoid crawl
  explosion.

### Schedule it

Run daily or weekly depending on how often the site changes. Point it at the same
`stateStoreName` every run so the diff has something to compare against.

# Actor input Schema

## `startUrl` (type: `string`):

The root URL of the site to crawl, e.g. https://example.com. The crawl stays on this origin only.

## `maxPages` (type: `integer`):

Hard cap on how many pages this run will crawl and fingerprint. Keep this reasonable — near-duplicate detection compares every page against every other page in the run. Kept small by default so a first run finishes quickly; raise it once you know the site's crawl time.

## `crawlMode` (type: `string`):

sitemap = read sitemap.xml/sitemap\_index.xml only · links = follow same-site links from the start URL only · auto = try the sitemap first and also follow links, so nothing sitemap-less gets missed.

## `urlExcludePatterns` (type: `array`):

Regex patterns. Any discovered URL matching one of these is never crawled — useful for /search, /cart, /login, paginated archives, etc.

## `excludeSelectors` (type: `array`):

CSS selectors removed from a page's content before fingerprinting — cookie banners, ads, chat widgets, related-content carousels. The single best fix for false CHANGED rows.

## `nearDuplicateThreshold` (type: `integer`):

Two pages in the same run with word-shingle similarity at or above this percentage are flagged as near-duplicate/templated content.

## `shingleSize` (type: `integer`):

Word-sequence length used for near-duplicate comparison. Smaller catches more overlap but is noisier; larger is stricter.

## `onlyChanges` (type: `boolean`):

Push only ADDED / REMOVED / CHANGED rows (skip UNCHANGED). Recommended once you're past the first baseline run.

## `resetBaseline` (type: `boolean`):

Forget the stored site snapshot and start fresh. Use after you change excludeSelectors or urlExcludePatterns.

## `stateStoreName` (type: `string`):

Named key-value store holding the previous run's site snapshot. Use different names to track multiple sites separately.

## `concurrency` (type: `integer`):

How many pages to fetch in parallel while crawling.

## `requestTimeoutSecs` (type: `integer`):

How long to wait for each page before giving up on it.

## `customHeaders` (type: `object`):

Extra request headers sent with every page fetch, e.g. a Cookie or Authorization header for a staging site behind auth.

## `proxyConfiguration` (type: `object`):

Optional Apify proxy configuration for sites that block datacenter traffic.

## Actor input object example

```json
{
  "startUrl": "https://books.toscrape.com/",
  "maxPages": 20,
  "crawlMode": "auto",
  "urlExcludePatterns": [
    "\\?",
    "/(cart|checkout|login|search)(/|$)"
  ],
  "excludeSelectors": [
    ".cookie-banner",
    "#ads",
    ".chat-widget"
  ],
  "nearDuplicateThreshold": 85,
  "shingleSize": 6,
  "onlyChanges": false,
  "resetBaseline": false,
  "stateStoreName": "site-diff-engine-state",
  "concurrency": 5,
  "requestTimeoutSecs": 30
}
```

# Actor output Schema

## `siteDiff` (type: `string`):

No description

## `downloadCsv` (type: `string`):

No description

## `summary` (type: `string`):

No description

## `pagesCrawled` (type: `string`):

No description

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "startUrl": "https://books.toscrape.com/",
    "urlExcludePatterns": [
        "\\?",
        "/(cart|checkout|login|search)(/|$)"
    ],
    "excludeSelectors": [
        ".cookie-banner",
        "#ads",
        ".chat-widget"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("that_red_bird/site-diff-engine").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "startUrl": "https://books.toscrape.com/",
    "urlExcludePatterns": [
        "\\?",
        "/(cart|checkout|login|search)(/|$)",
    ],
    "excludeSelectors": [
        ".cookie-banner",
        "#ads",
        ".chat-widget",
    ],
}

# Run the Actor and wait for it to finish
run = client.actor("that_red_bird/site-diff-engine").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "startUrl": "https://books.toscrape.com/",
  "urlExcludePatterns": [
    "\\\\?",
    "/(cart|checkout|login|search)(/|$)"
  ],
  "excludeSelectors": [
    ".cookie-banner",
    "#ads",
    ".chat-widget"
  ]
}' |
apify call that_red_bird/site-diff-engine --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,that_red_bird/site-diff-engine"
        }
    }
}

```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/xTdA9C0MvgSvCmv8V/builds/ECv17zJWBs9bLuIn9/openapi.json
