# Scripts and coding agents

The voice is for people. The same commands work for a script, a CI job or a coding agent, with JSON in place of the text a person reads, and no jokes in it. Every JSON document has a `schemaVersion`, which changes only when a field is removed or changes meaning.

`ssqch build --format json` prints one report on standard output, whether the build worked or not (the exit code is 0 or 1 as usual):

```sh
ssqch build --format json
```

```json
{
  "schemaVersion": 1,
  "ok": false,
  "environment": "production",
  "output": "dist",
  "warnings": [
    {
      "code": "schema",
      "message": "src/guides/pine.md: `lvl` isn't a field of this schema (did you mean `level`?) (schema `guides`)",
      "file": "src/guides/pine.md",
      "line": 3,
      "field": "lvl"
    }
  ],
  "aliases": [],
  "errors": [
    {
      "code": "template",
      "message": "rendering index.edge with `edge`: index.edge:7: Cannot read properties of undefined (reading 'toUpperCase') in `guide.data.name`",
      "file": "src/index.edge",
      "line": 7
    }
  ]
}
```

- **Each warning and error** has a `code` and the `message` a person would have read. `file` (from the project root) is there when the problem is in a file that exists, `line` when the line is known, `field` for a [schema](https://sitesquatch.dev/docs/content-schemas/index.md) problem, and `url` for a problem in a written page, like a broken link.
- **`line` is a line of the file**, counted from its first line with the front matter included, and it's the number in the message too (`index.edge:7`).
- **`aliases`** lists the words from another generator that the build took as ssqch's (`pathPrefix` for `base`): each one's `word`, its `kind`, ssqch's name for it (`use`), `alias`, the generators it comes `from` and where to read `more`. In the terminal, each is the `note: pathPrefix works; ssqch calls it base` line, said once.
- **The codes:** `config`, `data`, `front-matter`, `template`, `schema`, `conflict` (two pages write the same file), `links`, `images`, `assets`, `fetch`, `passthrough`, `last-modified`, `hook`, `console` (`console.warn` in a config), `template-formats` (files in a template language the site doesn't list), `other-generator`, `foreign-key` and `foreign-global` (another generator's config, front matter or template data), `over-budget` (a [footprint budget](https://sitesquatch.dev/docs/footprint/index.md)), `slow-call` (a filter, transform or collection of the site's that took a second or more in one call: [Where the time went](https://sitesquatch.dev/docs/build-summary/index.md#where-the-time-went)), `missing-asset` (from `ssqch serve`), and `build` for anything else.
- **A build that works** also has `durationMs`, `pages` (`written`, `templates`, `bytes`, and `new` and `gone` since the last build to that folder, or `null` when there wasn't one), `copied`, `removed`, `drafts` (the `draft: true` pages a production build left out), `written` (each page's file, from the output folder), `summary` (the lines plugins add to the [build summary](https://sitesquatch.dev/docs/build-summary/index.md)) and `timings`.
- **Standard output is only the report.** The lines a person would have read (an image's `[ssqch] Encoded ...`, and with `--verbose`, `[ssqch] Writing ...` for each page), `console.log` from your config and the output of `beforeBuild` commands go to standard error; `--quiet` leaves the progress lines out.

`ssqch capabilities --format json` says what the installed ssqch supports, so nothing has to be guessed from the documentation of another version: its `version`, `commands`, `json` (every command that prints JSON with `--format json`, and `serve --ready-file`), `features` (`avif`, `fetch`, `sass` and each template language, listed only when this build can do them), `templateLanguages` with their extensions, `configFiles`, `configOptions`, `defaults` (the template formats and engines a config that says nothing gets), `frontMatter` and `dataFiles` (the formats each can be written in), the built-in `modules` with what each exports, `templateFunctions` (the built-in ones, and each plugin's), `nodeModules` (Node's built-in modules), `globals`, `imageFormats`, `starters` and `starterEngines` (what `ssqch init` can write), and `importers` (the generators `ssqch scout` reads). Without `--format json` it prints the same as text, under "What's in the pack".

`ssqch docs` is this documentation, from the package, so it matches the version that's installed and works without the network. Alone, it lists every command, config option, template function and module export with one line each. `ssqch docs base` (or `imagePlugin`, `toc`, `serve`) prints what these docs say about that name and which other sections mention it, `ssqch docs "content schemas"` prints a section, `ssqch docs "On a host > Netlify"` a section inside another (for a title two pages share; a section's list of what's in it writes them that way), and other words search the text. `--all` prints a section with every section under it (`ssqch docs "Configuring a site" --all`), and alone, the whole documentation as one text, to read or to save beside a site. Another generator's word gets ssqch's (`ssqch docs pathPrefix`), and `ssqch docs --from eleventy` lists that generator's words with ssqch's for each, then its trailhead. `--format json` has the same, with each answer's `names`, `section` and `also`.

`ssqch init` writes an `AGENTS.md` for coding agents, with a one-line `CLAUDE.md` that imports it: what each file is, and the commands above for looking a name up, checking a change and comparing builds. It's about 1 KB, since an agent carries it through a whole session, and `init` never replaces one a site already has. For a site that doesn't have one, `ssqch docs agents > AGENTS.md` writes it, or `ssqch init` in the site's folder: beside a config of the site's own, it writes `AGENTS.md`, `CLAUDE.md` and the editor types and leaves the starter's pages out (`left out the starter's 17 files in src/: they need the starter's config, and ssqch.config.js is this site's own`), since they'd need the starter's config to build.

`ssqch serve --ready-file <file>` writes a file once the first build is done and the site is being served, so a script can wait for the file instead of reading the server's output or sleeping:

```sh
ssqch serve --port 0 --ready-file .cache/ready.json &
```

```json
{
  "schemaVersion": 1,
  "url": "http://localhost:60768/",
  "port": 60768,
  "base": "",
  "output": "/home/sam/site/dist",
  "pid": 39675,
  "ok": true
}
```

`ok` is whether that first build worked (the server keeps running either way, and rebuilds when a file changes). The file is deleted when the server starts, so one from an earlier run never counts, and it's written again when a changed config loads, since `output` and `base` can change with it.

The other commands with JSON are [`ssqch trace --format json`](https://sitesquatch.dev/docs/where-values-come-from/index.md) (where a page's data came from), [`ssqch diff --format json`](https://sitesquatch.dev/docs/comparing-builds/index.md) (what a change did to the output; it exits with 0, 1 or 2 like `diff`), [`ssqch footprint --format json`](https://sitesquatch.dev/docs/footprint/index.md) (what the build weighs), [`ssqch patrol --format json`](https://sitesquatch.dev/docs/patrol/index.md) (what agents and crawlers find in it), `ssqch new --format json` (the file it made), `ssqch scout --format json` (what a move takes) and `ssqch docs --format json`. `ssqch capabilities --format json` lists them all as `json`.

## Moving a site with an agent

Every move from another generator so far ran the same loop: build the old site, build the new one, compare, fix the biggest group of differences, repeat. It's a loop an agent can run, as long as each step has an answer it can read:

1. **Reference builds you can trust.** `ssqch baseline "<old build command>"` builds the old site with its own generator three times, each in a fresh copy with every file's time pinned and `TZ=UTC`, into `.cache/ssqch/baseline/ref-1` to `-3`, and names what changes by itself (the build's time, ids from `Math.random()`): pin it, or note an `--ignore` pattern for it, before anything else. After the move's first commit, build the commit before it: `--commit <rev>`. When builds vary, run more of them (`--runs 20`): the summary counts how many builds agree on each file and names the one most like the others, and `.cache/ssqch/baseline/ref-common` has each file's most common version, which is the one to compare with. A commit that needs a fix to build at all takes `--patch fix.patch`; a tool that won't follow a link out of its folder (Hugo's `js.Build`) takes `--copy-installs` (a `hugo` command gets it by itself). Watch the first build's warnings: GitHub Pages' placeholder `github.com/pages/...` URLs mean the reference build is wrong on every page.
2. **What the move takes.** `ssqch scout` finds the old generator and lists what the site uses that needs doing, each with its file and line and ssqch's way to do it (or "not in ssqch yet"), with the `ssqch baseline` command for step 1; `--format json` has it as data. `--write-draft` writes the config draft and the other new files, and `--patch move.patch` writes the mechanical edits as a patch to read and `git apply`. Run it again at any point to see what's left. `ssqch docs --from <generator>` has that generator's words with ssqch's for each, and its trailhead.
3. **A build that works.** Build into an empty folder (files an earlier build left count as differences): `rm -rf dist && TZ=UTC ssqch build --format json`, until `ok` is true. Each error has a `code`, a `file` and a `line`.
4. **The biggest group first.** `ssqch diff .cache/ssqch/baseline/ref-1 dist --format json --lines 0` lists the changes on more than one file as `groups`, the most files first. One cause (a filter that formats dates another way, a layout that lost a `<meta>`) is often hundreds of pages, and fixing it shows what's under it. Each change on a page says which heading it's under (`@ under #its-id`, or `at` in the JSON), to find it in the source, and the notes call out what moves a reader: a changed `<title>`, canonical link or redirect, ids that links point at, and a feed's entries. Build and compare again after each fix. What browsers read the same (attribute order, quotes, entities, percent-encoding in URLs, `<br/>`), fingerprints and image ids don't count, so what's left is a real difference.
5. **Done is a decision.** Stop at `No differences`, or when what's left is on purpose: write each one down with why (an `--ignore` pattern with a comment, or a line in the move's notes). `ssqch diff --exact` shows the bytes that still differ, such as a minifier's.
6. **Then ssqch's own features,** one at a time (its Markdown, highlighting, minifying, `toc()`), with a diff after each, so every change in the output has one cause.

### When the reference isn't what it seems

A reference build that's quietly different from the site's real one costs more than any other step: every difference after it is chased in the wrong place. The moves so far met these, each without a word from the old generator:

- **Dates from git.** `baseline` builds copies of the files git would commit, without their history, so a generator that reads git (Docusaurus's "Last updated", Eleventy's `git Last Modified`) has none to read and leaves the dates out. Build the commit instead: `--commit HEAD` copies it with its history.
- **An install below the root.** `node_modules` beside the root's `package.json` is linked into each copy; one in a folder below it (a docs site in `website/`) isn't. Install there in each copy as part of the command (`"cd website && npm ci && npm run build"`), or link it with `--link website/node_modules`.
- **Bundlers and linked installs.** webpack and rspack (Docusaurus, Gatsby, Next.js) name CSS modules' classes and chunks by each file's real path, and a linked `node_modules` is somewhere else: every class on every page differs from the site's own build, and the copies agree with each other. `--copy-installs` copies the installs in instead, and a warm cache (`node_modules/.cache`) left from another build makes a run faster than it'll be in CI.
- **pnpm and a linked `node_modules`.** pnpm 11 checks the install before `pnpm run` and tries to install again when it's linked. Call the tool itself in the command: `node_modules/.bin/docusaurus build`.
- **A fetch at build time.** A build that downloads content (other repositories' docs, an API) builds whatever is there that day. Pin it in the command, as the site allows (`DOCS_REF=v5.0.0 npm run build`), or save what it fetched and point the build at the copy.
- **"The same" isn't byte for byte.** `baseline` says builds are the same as `ssqch diff` would: attribute order and whitespace between tags aside. `ssqch diff --exact .cache/ssqch/baseline/ref-1 .cache/ssqch/baseline/ref-2` shows the bytes that differ.
- **Check run 1 against the site's own.** When the site was built in place before (its `build/` or `public/`), `ssqch diff --exact <that folder> .cache/ssqch/baseline/ref-1` should say `No differences`, or only what varies by itself. A difference there is the reference's, not ssqch's.

Two things a move often needs at the end: an exact comparison with fingerprinted names left out, `ssqch diff ref dist --exact --ignore '\.[0-9a-f]{8}\.(?:css|js)'`, and a patch of everything the move added, new files too, `git add -N . && git diff --binary > move.patch`.

### A move, step by step

A small Eleventy blog (three posts, an About page, a feed from `@11ty/eleventy-plugin-rss`, a `posts` collection and two date filters) moved with the loop above, with each command's real output, trimmed. The site is in git, and each step is a commit an agent can go back to.

**1. Scout it.** In the old site's folder, before changing anything:

```text
$ ssqch scout
Scouting the Eleventy site in . (found eleventy.config.js)

4 to do: 4 ssqch does.

Reference build
  ssqch baseline "npm run build"

To do (4)
  package-lock.json: run `npm install` to update it for ssqch
  eleventy.config.js:8: addCollection("posts") -> `collections: { posts: (pages) => ... }`: getAll() is pages.all(), getFilteredByTag is pages.byTag, getFilteredByGlob is pages.byGlob
  eleventy.config.js:9: addPlugin(feedPlugin) (from @11ty/eleventy-plugin-rss) -> see its package below
  eleventy.config.js: @11ty/eleventy-plugin-rss -> `rssPlugin()` from "ssqch/rss" for a feed template's filters, or its `feedPlugin({ url })` for the feed itself (...)

Draft (1 to write): --write-draft writes them, and never overwrites a file
  ssqch.config.js (a first draft, from eleventy.config.js)

Edits (1): --patch <file> writes them as a patch to review, and changes nothing
  package.json: @11ty/eleventy -> ssqch 0.17.0 in devDependencies, scripts: eleventy -> ssqch build, eleventy --serve -> ssqch serve
```

**2. Build the reference.** The command is the one scout found. After the move has started, `--commit HEAD` (or the commit before the move) builds the old site and not the working tree, whose `npm run build` is ssqch's by then:

```text
$ ssqch baseline "npm run build" --commit HEAD
Base camp is set: .cache/ssqch/baseline/ref-1, .cache/ssqch/baseline/ref-2 and .cache/ssqch/baseline/ref-3, built from ... with TZ=UTC, SOURCE_DATE_EPOCH and every file's time pinned; ...
Every build is the same: 5 pages and 2 other files. The tracks match every time.
```

When the builds don't agree, it says what varies before anything is compared. With a random `?v=` on the stylesheet's link, and `--runs 5`:

```text
Varies (4)
  The same difference on more than one file, the most files first (--ungrouped lists each file with all of it):
  ~ 4 pages, the same but for attribute values: /, /posts/cedar-trail-reopens/, /posts/footprints-at-the-stump/ and 1 more
      - <link href="/style.css?v=p3eijx" rel="stylesheet">
      + <link href="/style.css?v=8fvwrb" rel="stylesheet">

The eyewitness accounts differ: 4 files vary between builds made the same way; 0 pages and 2 other files are the same in all of them. Pin what changes (the build's time, random ids) before comparing another build with these, or leave it out with --ignore.
4 files have no most common version: each build has its own. More builds (--runs 20) show whether one is usual.
Wrote .cache/ssqch/baseline/ref-common: each file's most common version of the 5 builds, to compare ssqch's with.
```

Pin it in the old site if you can (a fixed value, or one from the commit). If not, leave it out of every comparison: `ssqch diff .cache/ssqch/baseline/ref-common dist --ignore '\?v=\w+'`. Compare with `ref-common` whenever builds vary: it's each file's version that most builds wrote, where `ref-1` is one build's luck. A file with no most common version (each build its own, as here) is what `--ignore` is for.

**3. The draft and the patch.** `ssqch scout --write-draft --patch move.patch` writes `ssqch.config.js` (the old config's directories, engines, passthrough copies and self-contained filters, as written) and the patch, which changes only `package.json` here. Read it, then `git apply move.patch` and `npm install`. The draft ends with what it couldn't carry over:

```js
// To port from eleventy.config.js:
//   collections: posts
```

**4. Build, and compare.** Into an empty folder, so nothing an earlier build left looks like a difference:

```text
$ rm -rf _site && TZ=UTC ssqch build
$ ssqch diff .cache/ssqch/baseline/ref-1 _site
Removed (1)
  - /feed.xml

Changed (1)
  ~ /  (text and markup)
      the same lines, in another order
      - <a href="/posts/pine-cone-count/">
      + <a href="/posts/cedar-trail-reopens/">
      ...
```

The two differences are the two to-dos: the home page lists the posts oldest first without the `posts` collection, and there's no feed without a feed plugin. Port the collection (`posts: (pages) => pages.byGlob("src/posts/*.md").reverse()`), build and compare again, and the home page is the same.

**5. Scout again, halfway.** It reads the config the move has written so far, and what's done is off the list:

```text
$ ssqch scout
Scouting the Eleventy site in . (found eleventy.config.js): a move under way, with ssqch.config.js

3 to do: 3 ssqch does.
1 done already: ssqch.config.js has `collections.posts`.
```

**6. The next group.** After `feedPlugin({ url: "https://example.com", limit: 10, author: "A Ranger" })` from `ssqch/rss`, a change on the About page says which heading it's under, to find it in the template:

```text
Changed (1)
  ~ /about/  (markup)
      @ under #trails
      - <a href="/maps/#old-growth-and-cedar">
      + <a href="/maps/#old-growth-cedar">
```

Eleventy's `slugify` spells out `&` as `and`, and ssqch's drops it; `slugify({ ascii: true })` spells it out too (other symbols as the `slugify` package does, which isn't always as Eleventy's `slugify` does: `ssqch docs --from eleventy`). With that in the template, every page is the same.

**7. Done is a decision.** What's left is the feed, and it's on purpose: Eleventy's listed the posts oldest first (the plugin reverses the collection, which this site had already put newest first) and its subtitle was the plugin's placeholder (`This is a longer description about your blog.`), and ssqch's is newest first, which is what feed readers expect, with the site's `description` as the subtitle. Its picture is a generated copy (`/img/uAgOSjhLVO-4.png`), as `feedHtml()` writes one. Each goes in the move's notes with why, and scout's last to-do is `npm install`.

**An agent's loop, as data.** Each step has a JSON answer, so an agent can run the loop without reading prose:

- `ssqch scout --format json`: `todo` (each with `code`, `at` and `what`), `done`, `summary` (`ssqch`, `option`, `notYet`, `site` and `done` counts) and `build.baseline` (the command for step 2). The move is finished when `todo` is empty or each one left is written down.
- `rm -rf dist && TZ=UTC ssqch build --format json`: `ok`, and `errors`, each with `code`, `file` and `line`. Fix until `ok` is true.
- `ssqch diff <reference> dist --format json --lines 0`: `groups` (changes on more than one file, the most files first: fix the first), then `changed` (each file's `hunks`, with `at`, the heading a change is under), `added` and `removed`. `summary` says how many are left, which is the loop's measure of progress.

## Examples to copy

Every example site the docs link to comes with the package, in `node_modules/ssqch/bundled/examples/<name>/` (each is its source: no build, no installs), so an agent in a site's folder can read one or copy it without leaving the project: `cp -R node_modules/ssqch/bundled/examples/islands/src/elements src/`. They're small, complete sites, each written against a feature: `blog-tags` and `blog-categories` (tags, categories, feeds), `docs-sidebar`, `glossary-docs` and `versioned-docs` (docs sites, Pagefind search), `component-docs` (Edge components, Sass), `islands` (custom elements that load only where they're used), `jekyll-guides` (a Jekyll site's layout), `reference-pages` (one page per option, from a JSON schema), `searchable-directory` (a page per record from a data file, with filters), `multilingual` (a language per folder, hreflang) and `company-site` (a marketing site: products from checked data, pricing, forms, careers). The [list](https://github.com/reverentgeek/sitesquatch/tree/main/examples/sites/) says what each shows, and each is on sitesquatch.dev/examples/.
