# joggle

> Cross-file patterns and idioms for TypeScript, enforced like a linter.

`tsc` checks one program. `oxlint` checks one file. Neither answers whether
two functions in different modules are the same concept, whether a name means
something different here than it does there, or that a module is not shaped
like the other twelve modules of its kind.

joggle is the layer above both. It indexes the codebase into facts, generates
candidates cheaply and deterministically, and then asks narrow typed questions
about the candidates it cannot decide by looking. Answers come back as
probabilities, code keeps control of the thresholds, and the output is an
ordinary diagnostic -- so the same tool serves an editor, a pre-commit hook and
CI.

The design rule is one sentence: **be deterministic where you can prove, and
judge only where you must.** What the tool is for -- the entropy reverser, and
the three moves a finding can propose -- is [docs/thesis.md](./docs/thesis.md).

## Where it sits

| Tool | Unit | Question | Output |
| --- | --- | --- | --- |
| `tsc` / `tsgo` | the program | is this well-typed? | diagnostics |
| `oxlint` | the file and its AST | is this well-formed? | diagnostics |
| **joggle** | the codebase and its facts | is this the same thing as that? | diagnostics |

Because the output shape is identical, a host does not have to care which kind
of rule produced a finding. There is no separate report, no separate format,
and no separate gate.

## The shape of a rule

Every rule is a file with the same five moves.

```
find        deterministic, high recall, noise tolerated
  |
  v
evidence    the panel a reviewer would need in order to decide
  |
  v
questions   atomic, typed (Noul / Choice), all sent in one request
  |
  v
policy      weights and thresholds, imported from policy.ts
  |
  v
diagnose    span, message, help, confidence
```

A rule's deterministic half is its **candidate generation**: a predicate over the
facts, free and high-recall. The verdict is a question. Every rule in the set is
judged, because a check that is not a question belongs in the linter or the
typechecker, and a meta-rule rejects one.

![How joggle decides: the index feeds candidate generation (a predicate over the
facts), which becomes evidence, atomic questions in one request, gates, and one
diagnostic shape.](./docs/rule-anatomy.svg)

*The diagram is generated by `scripts/diagram-rules.mjs`.*

## Running it

```sh
pnpm install

pnpm joggle rules                              # what is enforced
pnpm joggle check src                          # analyse a directory
pnpm joggle check --typecheck                  # carry tsgo diagnostics too
pnpm joggle check --format github              # GitHub Actions annotations
pnpm joggle check --offline                    # replay from cache, no network
pnpm joggle check --rule joggle/naming-drift   # one rule
pnpm joggle check --max-warnings 0             # warnings fail the build
pnpm joggle check --since origin/main          # only what this branch changed
pnpm joggle check --pr                         # only what this branch's PR changed
pnpm joggle check --pr-number 123              # only what PR 123 changed
```

With no paths, joggle asks `tsgo --listFilesOnly` what the project is, so it
analyses exactly what the compiler sees rather than whatever is on disk. With
paths, it walks them itself.

### Installing the command

The simplest way to use joggle from another workspace is to put it on `PATH`
once:

```sh
cd path/to/joggle && pnpm install && pnpm build
ln -sf "$PWD/scripts/joggle.sh" ~/.local/bin/joggle
```

Then, from any checkout:

```sh
joggle check --since origin/main
```

The wrapper resolves its own checkout through the symlink and runs the build
(falling back to the source). It looks for the TypeSafe key in three places, in
order: the environment, a gitignored `.env.local` beside the wrapper, and
doppler. The doppler fetch runs from the joggle root, because doppler resolves a
project from the **working directory's** `doppler.yaml` and a sibling
repository's setup wins over explicit `--project`/`--config` (and over
`DOPPLER_PROJECT` / `DOPPLER_CONFIG`); it also restores `HOME` from the passwd
database, because a host such as pi can spawn the command with no `HOME` and
doppler needs it to find its own auth. `JOGGLE_DOPPLER_PROJECT` and
`JOGGLE_DOPPLER_CONFIG` override the defaults `joggle` and `dev`. Commands that
need no key (`rules`, help, `--offline`) skip the lookup entirely, and a key
that cannot be found degrades to unverified findings -- with a warning on
stderr, which the pi tools surface in their result -- rather than taking the
tool down.

### From another repository

joggle runs its source in development, and its build when installed. Build once,
then link it into the repository you are working in:

```sh
cd path/to/joggle && pnpm install && pnpm build

cd path/to/other-repo
pnpm add -D file:/absolute/path/to/joggle   # or: pnpm link /absolute/path/to/joggle

pnpm exec joggle check --pr                 # after cutting a PR
```

`file:` installs a copy of `dist/`, so nothing in the other repository has to
understand TypeScript. `pnpm link` symlinks the source, which works because the
symlink's real path sits outside `node_modules` -- but a `file:` install needs
`dist/`, and `pnpm build` is what makes it.

### Inspecting a checkout you do not want to touch

A repository is only modified if it is being onboarded. To analyse a sibling
checkout without writing anything into it:

```sh
pnpm joggle:elsewhere ../shakti-v2 --since origin/develop --offline
```

`scripts/joggle-elsewhere.sh` runs `check --cwd <path>` and sends the answer
cache to the machine cache **unless the target already has a committed
`.joggle/`**, in which case the repository's own cache is used so a replay still
works. Nothing else is written: the run cache, the parse cache and any type
trace already live under the machine cache, and the default run makes no network
call when there is no key.

### As a pi extension

The repository is also a [pi](https://pi.dev) package. Install it once and pi
gains two tools and a command in every repository it works in:

```sh
pi install /absolute/path/to/joggle    # or: pi -e /absolute/path/to/joggle
```

| Name | What it does |
| --- | --- |
| `joggle_check` | Run a scoped check and return the findings. Defaults to the changed scope, so it answers what the current batch of work introduced; `scope: "pr"` answers what a pull request introduced. Returns at most 50 findings; pass `limit` to change that, or `0` for all of them. |
| `joggle_rules` | List the rules a repository enforces. |
| `/joggle` | Run a check from the prompt line; arguments pass through, e.g. `/joggle --pr`. |

Both tools take a `cwd`, so a session in one repository can check a sibling:

```
joggle_check { cwd: "../shakti-v2", scope: "since", since: "origin/develop" }
```

`joggle_check` follows the same non-invasive cache rule as the script above: it
passes `--cache-dir` to the machine cache when the target has no `.joggle/`, and
uses the committed cache when it does. Pass an explicit `cacheDir` to override.
The extension is a shell over the CLI in this checkout (`dist/main.js`, falling
back to `src/main.ts`), and `JOGGLE_BIN` points it at a different build or a
wrapper.

Output formats follow oxlint, because oxlint already decided what a linter's
output should be and its decisions are worth copying:

| Format | Shape | For |
| --- | --- | --- |
| `text` (default) | `path:line:col: severity rule: message help: ...`, one line per problem | terminals and CI logs |
| `stylish` | grouped per file, aligned columns, colour on a TTY | reading by hand |
| `unix` | `path:line:col: message [Severity/rule]` plus a count | editors and scripts |
| `json` | everything, including per-answer confidence | another tool |
| `github` | Actions workflow commands | annotations |

A hand-rolled code frame was removed in favour of the compact default. On a
1,870-file codebase the frames made the report 8,083 lines; oxlint's shape
prints 343. A terminal and a CI log need different shapes.

| Flag | Meaning |
| --- | --- |
| `--rule <ids>` | comma-separated rule ids |
| `--format text\|stylish\|unix\|json\|github` | output format (see below) |
| `--max-warnings <n>` | fail when warnings exceed `n` (`-1` disables) |
| `--typecheck` | include tsgo diagnostics as `joggle/typecheck` |
| `--no-tsgo` | never invoke tsgo |
| `--run-external-code` | let `tsc` execute content-mapper packages declared in tsconfig (TypeScript 7.1+); off by default |
| `--offline` | answer only from the judgement cache |
| `--changed` | scope to what changed since the stored run |
| `--since <rev>` | scope to what changed since a git revision, working tree included |
| `--pr` | scope to the pull request for the current branch (resolved with `gh`) |
| `--pr-number <n\|url>` | scope to a specific pull request |
| `--cache-dir <path>` | where the answer cache lives: `<cwd>/.joggle` when it exists, else the machine cache |
| `--cwd <path>` | project root |

Content mappers are TypeScript 7.1's plugin point for `.vue`, `.svelte`, `.mdx`
and similar files. joggle does not run them unless `--run-external-code` (or
`"runExternalCode": true` in `joggle.config.json`) says so: a mapper is arbitrary
code named by the repository. Even with it on, joggle's own parser indexes only
TypeScript and Astro, so `check` reports a note naming every declared extension
it did not index. [docs/content-mappers.md](./docs/content-mappers.md) has the
full contract.

## CI and replay

A judgement is a network call, so the cache key is the contract:

```
question version + model + evidence + questions
```

It is serialised with sorted keys, so the same candidate produces the same key
on every machine — which means **run from the repository root**. Evidence
carries root-relative paths; running from a subdirectory changes the key and
misses every cached verdict. Successful judgements are written to a
write-through cache under `.joggle/cache/`, one sorted, line-oriented answer per
line. The reviewed `.joggle/answers.jsonl` (or sharded `answers/`) is the ledger
a person commits; a judged run reads it and never rewrites it, so CI replays it
with `--offline` and **no API key at all**. A line is the
key and the answer and nothing else, so two branches that judge different
candidates merge with git's built-in `merge=union` and the same answer merges to
one line rather than a copy; `joggle cache compact` and `cache prune --max-bytes`
keep the store from growing without a ceiling. A store large enough to make a whole-file rewrite or a
merge expensive can be sharded instead (`cache.layout: "sharded"`, or
`joggle cache migrate --layout sharded`); both layouts are read, and
`cache migrate` moves between them. The older `answers.json` object is read and
consolidated on the next write. The layouts and the deployment modes are in
[docs/artifacts.md](./docs/artifacts.md). Bump `policy.decisionVersion` when you
change a question's wording, and every cached answer for it is invalidated at
once instead of silently replayed against newer questions.

When the judge is unavailable, the rule's own `onUnavailable` decides, and a
repository may override it for the whole run with `unavailable`, or per rule with
`onUnavailable`:

| Answer | What happens |
| --- | --- |
| `report` (the default) | the rule still reports; each candidate is an unverified finding |
| `propagate` | the rule steps aside and the engine reports it as skipped |
| `count` | the candidates are counted in one note and not printed |

A repository that runs without a key in CI sets `"unavailable": "count"` once and
the whole judged layer becomes a count; a developer's machine with a key is
unaffected. Answers already cached and replayed with `--offline` are judgements,
so none of this applies to them. A missing key degrades the gate; it does not
disable it.

### Where the key goes

The key is read from the process environment only, so it never appears in the
repository or in any config file joggle owns.

Locally, use the secret manager the team already has:

```sh
doppler run -- pnpm joggle check src      # recommended
direnv allow                              # or a gitignored .envrc.local
```

In CI, add `TYPESAFE_API_KEY` as a repository secret and map it onto the step
that judges new candidates. The replay job needs no secret at all.

Two properties make this safe to live with:

* `.joggle/judgements.json` holds questions, evidence and answers. It never
  holds the key, so it is safe to commit and review.
* Because the cache is the replay path, **the judged run can be done by a
  person and the result handed to CI or to an agent**. Neither reads the
  credential; both work from the committed verdicts.

If the key is ever pasted into a file, into chat, or into a shell that gets
logged, rotate it in the TypeSafe console. This repository is private, so
GitHub's secret scanning will not catch it for you.

### What leaves the machine

The judged rules send the evidence panel -- including source excerpts of the
declarations being compared -- to `api.typesafe.ai`. Deterministic rules and
`--offline` send nothing.

Decide this per repository. For a client codebase, either point
`TYPESAFE_BASE_URL` at a deployment you control, or run the judged pass over
public and fixture code only and let the committed replay cache carry the
verdicts into the client's CI.

```sh
TYPESAFE_BASE_URL=https://typesafe.internal.example doppler run -- pnpm joggle check src
```

## The judgement

The evidence panel is the System One `state`; the questions are the typed
primitives. Everything the model returns is constrained to the options the rule
supplied, so nothing has to be recovered from generated prose.

- `Noul` -- the probability that a yes/no statement holds.
- `Choice` -- one option out of a set, with the full distribution and a
  confidence.

Thresholds live in `src/policy.ts` and nowhere else. When a verdict stops
matching what the team would decide, you change a weight, re-run, and see the
difference -- you do not rewrite a prompt.

### What the judge is actually for

Code finds; the model verifies. That reverses how joggle started, and the first
real measurements corrected it.

Findings were being produced two ways: exact shape equality (a fact, but
reported unverified) and a hand-tuned near-duplicate search that asked the model
to *discover*. Over 55 API calls that produced 5 findings, and the questions
could not have done better, because two of the four were constants:

* `same_behavior` was asked about pairs selected *because their text differs*.
  Of 49 real judgements, 40 came back below 0.25. The answer was decided by the
  candidate filter before the question was asked.
* `merge_changes_behavior` -- "would replacing one with the other change
  behaviour for some caller?" -- was made a hard veto at 0.4. Across 49
  judgements it never once fell below 0.4 (mean 0.64). Asked without any call
  sites in the state, the model answers "probably yes" every time. A question whose
  answer is fixed in advance measures nothing.

Both are gone. Behaviour is now asked about only where it is genuinely open,
and only in the band where the text actually differs.

The judge's job is intent, not behaviour. When two declarations are
syntactically identical, equivalence is already an AST fact; the only open
question is whether the repetition is redundancy or two things that merely look
alike. A perceptual question about names and purpose is what a calibrated model
answers; code decides what to do with the answer.

One policy rule has since been deleted for the same reason. It suppressed a
finding when the two declarations sat in different areas and neither was a
general-purpose utility. Over 500 verdicts that removed 284 candidates --
including a type named `GhostProjectSummary` declared once in the API and once
in the UI, where the model itself answered `sameName 0.97` and "keep left". The
gate inverted a correct judgement. **Locality is not intent**, and
`docs/reference/names.md` is the argument: one concept should have one name and one
declaration. The model may override the deterministic fact only when it
judges the two names to mean different things, or says confidently that both
should stay.

Below the judgement budget, candidates are still reported, marked unverified. A
budget must never silently delete a finding.

## Adding a rule

1. Add a `src/rules/<name>.ts` with the five moves above.
2. Register it in `src/rules/index.ts`.
3. Put every new threshold in `src/policy.ts`.
4. Test it twice: once with answers that should activate the policy, once with
   answers that should not.
5. Run `pnpm joggle check src` -- joggle is expected to pass its own rules.

## Why the next layer is types, not more AST

joggle reasons about syntax today: it parses with oxc, normalises a
declaration's text, and hashes it. That catches copy-pasted code -- on a
1,870-file codebase it found a `delay` helper copied into six files and one
type declared in 48 -- but 79% of what it reported were *type* declarations,
judged by text similarity. That is the wrong instrument, and the material in
`docs/` says why:

* `docs/reference/names.md` -- types are the one contract the compiler enforces, and a
  type name is a search term exactly like a function name. Every `any` leaves
  the compiler with nothing to say and the agent with nothing to search.
* `docs/reference/parse.md` -- the entire argument is that the type system is where a
  program makes illegal states unrepresentable, and that validation which
  discards what it learned is the anti-pattern.
* `docs/reference/something.md` -- the goal is a compiler on top of the codebase that can
  refuse a change because "this file is in the wrong relationship to that".
* `docs/new-passes.md` names four pillars: AST structure, dependency graph,
  **type resolution data**, and text analysis. joggle has the first, part of
  the second, and none of the third.

Types are the only layer whose answers are *provable*. Measured on that same codebase with `tsgo --generateTrace` -- 11.5s
and 301MB of type facts for 1,870 files:

```
User: 46 resolved entries across 24 declaring files, 3 distinct resolved shapes
      Object (x38), Any (x4), TypeParameter (x4)
```

One name, three meanings, and four of them are `any`. Text hashing cannot see
that. The checker resolves it exactly.

So the direction is: keep the AST as the index and the source of spans, and
move the *judgements* to the type graph.

The first type-aware rule should be **`joggle/one-concept-one-type`**: the same
declared name resolving to different types in different places. Divergence is a
correctness problem; provable identity is a collapse candidate. Neither is
reachable from text.

Two implementation notes, because a trace is a hack that works and not the
final shape:

* `--generateTrace` needs no fork and is read-only, but the join from a source
  declaration to its resolved type is not a plain name lookup -- aliases expand,
  and one name can appear as several entries. `CompanyType` did not appear at
  all under its own name. Solving that join is the first task.
* The eventual host is the checker itself, the way `Effect-TS/language-service`
  and `effect-ts/tsgo` do it: run inside the compiler and ask
  `getTypeAtLocation`. The trace route buys the same facts today without
  maintaining a fork.

Deliberately *not* next: widening AST coverage to class and object-literal
methods. That is more surface on a weaker signal. It comes after types.


### The committed cache has a size, and it is not free

Committing the answer cache buys keyless replay, and it costs bytes in every clone
and every CI checkout. GitHub warns above **50 MB per file** and refuses above
100 MB; a cache is worth nowhere near that.

- `joggle cache prune --max-bytes 4000000` caps the file, oldest first, on any store.
  `--max-age 90` needs ages, which only the machine cache records.
- A run says so when the store passes 8 MB, because a cache nobody measured is how
  a 0-byte ledger on the base branch becomes 55 MB at the top of a stack.
- **Build output is never source.** The directory walk skips `node_modules`, `dist`,
  `build`, `out`, `coverage`, `.next`, `.turbo`, `.vercel`, `.cache` and anything a
  `.gitignore` excludes, and the checker's file list (under `--types`) is filtered the same
  way. Without that, a tsconfig that includes `dist` made every declaration appear twice, and
  the report said "declared in two places" about a build artifact — 73 of 95 findings on one
  repository, present on a developer's machine and absent in CI because CI had never built.
- **The analysed set is machine-readable.** `--format json` carries a `discovery` block —
  files analysed, files and directories ignored, extensions skipped, whether the walk was
  truncated — and `--list-files` adds the paths. Two checkouts of one commit that report
  different findings differ either in that set or in its verdicts, and the JSON used to show
  neither: the census was prose and the list was never emitted.
- **A run says how it got its answers.** "N judgement(s) were asked of the model" means a
  key was present and this run judged for itself; "N judgement(s) were replayed" means no model
  was called. The two can name the same site differently, so a local report and a CI report at
  the same commit are only comparable when this line matches.
- **A check does not write the ledger at all.** `--read-only` (and any run `jig` starts,
  which exports `JIG_READ_ONLY=1` to every engine) answers from the cache and never writes
  it. This is not hygiene: a new answer *renames* the finding it verifies, so a check that
  judged and wrote would re-open identities the baseline already accepted, and the next run
  would fail on files the change never touched. One pull request's lint run appended 919
  answers that way and re-opened 91 findings in a rule whose ledger entries were intact.
  Warming the ledger is a deliberate act: `joggle check` on trunk, or `--update-baseline`.
- **A scoped run does not write the committed ledger.** `--since`, `--pr` and
  `--changed` answer into the machine cache unless `--cache-dir` names a store: a
  branch's verdicts are a cache, and committing them is what put 131,440 lines in
  every pull request of a stack instead of the 5,890 answers they held.
- **`joggle cache compact` repairs a duplicated ledger in place.** A line used to
  carry `writtenAt`, so the same answer serialised differently on every branch and
  `merge=union` kept both sides on every rebase. The line is now the key and the
  answer only, so merges collapse to one line; for a history that already grew,
  compact reads each key once and rewrites the set. No re-judging, no key needed.
- **Deduplicating an old ledger is safe on a keyless CI today**, so nobody has to wait
  for this version to shrink one: the stamps were never load-bearing for replay. A
  parked stack deduplicated by key in the old three-field format (keeping the newest
  stamp) went from 55.4 MB / 372,623 lines to 1.21 MB / 8,171 answers, and the
  keyless lint job stayed green on the same answers.
- **Compaction is a commit, so it re-dirties every child of a stack.** Compact
  bottom-up in one pass, or compact the base branch once after the stack merges —
  compacting a parent mid-stack costs one rebase per child for a diff nobody reads.

## Two committed artifacts, two machine artifacts

joggle's state is four files with four lifetimes. Two belong to the repository
and two belong to the machine.

| artifact | lives in | committed | what it is |
| --- | --- | --- | --- |
| `answers.jsonl` (or `answers/` when sharded) | `<root>/.joggle/answers*` reviewed · `<root>/.joggle/cache/answers*` write-through | **reviewed ledger yes** | one line per answer, sorted by key, keyed by the decision and the state it read. **The reviewed ledger is the replay path**: CI replays it with no API key and no tokens; a judged run writes only its cache. |
| `baseline/` | `<root>/.joggle/` | **yes** | the findings already accepted, one fragment per finding: the ratchet. |
| `wire.json` | `<machine cache>/joggle/<root>/` | no | every wire request's response, keyed by the request. A performance artifact, and far too large to commit: 11.5 megabytes on a 2,493-file repository. |
| `last-run.json` | `<machine cache>/joggle/<root>/` | no | a manifest and the last report. A performance artifact. |

The first two are decisions a person should be able to read in a diff, and they
are per-repository because the evidence is keyed on root-relative paths. The
others are the largest, churn on every edit, and are worthless to anyone else — so
it lives in `$XDG_CACHE_HOME` (or `~/Library/Caches` on macOS), keyed by the
analysed root. One machine cache serves every repository, and pointing joggle at
somebody else's checkout writes nothing into it.

### Running against a diff

```sh
joggle check --update-baseline .joggle/baseline   # on main: record what is accepted
joggle check --baseline .joggle/baseline          # on a branch: only what is new
joggle check                                       # nothing changed: the previous run
joggle cache prune --max-age 90                    # the cache is regenerable; keep it small
```

`--update-baseline` refuses while any candidate was not judged
(`unreadable`, `no_evidence`, or past a budget): a baseline is the record of
what a person reviewed, and one written over unjudged candidates ratifies what
nobody looked at. `--allow-unjudged-baseline` is the explicit override; `jig
init` passes it, because a ledger born on day one has no review to protect yet.

The reason an unjudged ledger is worse than an incomplete one: judgement is part of
the analysis, not a badge on it. Without a model key (`TYPESAFE_API_KEY` in the
run's environment) the same candidates are clustered and named from what the rules
could see alone, so one group can be one finding locally and three in CI. The two
runs are two analyses with two identity sets, and a ledger written by the unkeyed
one does not hold against the keyed one — locally green, red in CI, both "passing"
their own run. A CI ledger must be written by a run with the key; a local run
without one is for reading, and `jig baseline` refuses unverified findings for the
same reason. In a stack, seed a child from its parent instead of re-judging:
`git checkout <parent> -- .jig-baseline.json .joggle/answers.jsonl` reuses every
identity the branch inherits and asks only for the ones it adds.

In a stack the run that works is scoped, because a full-repository run has a
full-repository budget: at ~2.5k candidates a keyed run, a repository with 12k
unjudged candidates is a 25-minute run that still refuses to write.

```sh
# the gate: what this branch adds, judged
joggle check --types --no-replay --since origin/<parent> --baseline .joggle/baseline
```

**A scoped run is for the gate. Acceptance is a full-run act**, and the command
enforces it: `--update-baseline` refuses a scoped run unless
`--allow-scoped-baseline` says otherwise.

The reason is the fold. Two findings at the same site with the same move are folded
into the richer one, and which survivor wins depends on what ran: a scoped run sees
fewer candidates at that site than a full run does, so it can name the problem with
one rule where a full run names it with another. Identities are therefore not
scope-invariant, a scoped accept can miss exactly the identity CI fails on, and no
amount of `--merge-baseline` repairs a ledger that never saw it. (The fix is aliases
on a folded survivor, so the ledger can match any of them; until that lands, the
refusal is the honest state.) Accept with one full run at the head of a stack:

```sh
joggle check --types --no-replay \
  --baseline .joggle/baseline --update-baseline .joggle/baseline --merge-baseline
```

`--merge-baseline` keeps the identities already accepted and adds this run's, so
accepting at the head does not discard the stack's accepted set. `--allow-unjudged-baseline`
is not the shortcut here: it ratifies thousands nobody looked at, which is a commit
nobody can defend.

### The cascade, not the conflicts

In a deep stack the conflicts are the easy half. Every one of them is a committed
artifact — a baseline, an answer ledger, a generated catalog — so
`git rebase -X theirs <parent>` clears the text and the artifacts are rebuilt
rather than merged.

The hard half is ordering. Accepting an identity, or rebuilding a catalog, adds a
commit to the parent, and that commit re-dirties every child above it: with 21
children, one fix is 21 re-dirties, and a cascade run between fixes runs once per
fix. A 22-branch migration spent five cascades that way, not because any rebase
was hard, but because each pass moved the parent again.

So the recipe is three passes, not one per branch:

1. **Finish every accept and every rebuild first**, on every branch. Nothing is
   rebased until the artifacts have stopped moving.
2. **Then rebase bottom-up, once**, with `-X theirs` for the artifact conflicts.
3. **Then push once**, bottom-up, with `--force-with-lease`.

`gh stack rebase` and the stacked-PR bots do exactly these three steps in one pass,
which is why they exist. An interrupted rebase leaves `rebase-merge/` or
`index.lock` behind and the next branch fails with "there is already a rebase-merge
directory": `git rebase --abort` clears it, and a scripted cascade belongs in a
`trap` that aborts rather than in a run that stops half-rebased.

The baseline is by identity, not by line: rule, kept symbol and cluster
membership. Code moves constantly, and a baseline that reports every edit as a
new finding is a baseline nobody reads. A rename or a new member does change the
identity, which is correct — the finding is a different finding then.

It is stored as **fragments**: one file per accepted finding, named by the
identity's hash, under the target directory. A new acceptance is a new file, so
two branches that accept different findings cannot conflict. A target ending in
`.json` is still written as the old single file.

### Why an unchanged run costs nothing

`last-run.json` carries a manifest: a hash of `policy.analysisVersion`, the
question version, the model, the rule set, the analysed root, and the content of
every file. If it matches, the run ends after reading the files and before
parsing them. On a 1,870-file codebase:

```
cold, judgements cached    0 calls, 0 tokens, 3,718ms
again                      0 calls, 0 tokens,   325ms   (replayed)
```

The 325ms is file reads and hashing, which is what makes the check honest: it is
content, not mtimes. Add one file that duplicates nothing and the run is a full
analysis with zero calls; add the second copy and a new cluster exists, so
exactly that candidate is judged:

```
first copy of a new duplicate   0 calls,   0 tokens
second copy                     1 call,  846 tokens
nothing changed                 0 calls,   0 tokens, replayed
```

**`policy.analysisVersion` is the one thing that must be kept honest by hand.**
A candidate filter or a clustering rule can change every finding while leaving
every question byte-identical, and the manifest is what decides whether a stale
report gets replayed. Bump it when the rules move.


### Answering "what did this change introduce?"

Two scopes answer this. `--changed` compares against the last stored run, which
is machine-local and only exists once the repository has been analysed before:

```sh
joggle check --changed     # scope candidate generation to the changed declarations
```

`--since` and `--pr` answer the same question from git, so a fresh clone is
scoped on its first run. They include the working tree and untracked files, which
is what makes a second pass see the edit made after the first:

```sh
joggle check --since origin/main   # this branch against where it forked
joggle check --pr                  # the current branch's pull request
joggle check --pr-number 123       # a specific pull request
```

Both are sound because a change elsewhere cannot create a duplicate between two
declarations it did not touch: every *new* finding has at least one changed
member. Dependents come into scope only when a file's **exports** moved, because
only then can their type names resolve to something else — a refinement the
stored-run scope makes and the git scope does not.

A **pure rename** is not a content change, and a PR that moves files is mostly
renames. Both scopes split it out: `changed` is added, modified and
renamed-with-edits, and `moved` is a rename git is certain kept every byte
(`--changed` finds the same thing from matching content hashes). Content rules
read `changed` alone — a moved file's bytes are not new — while the graph rules
read the union, because the move itself can put a module on the wrong side of a
boundary it used to respect. The scope note says how many were set aside.

What neither does is report removals, and neither is a full report — so a scoped
run leaves the stored run alone rather than becoming the next comparison base,
and a git scope never replays the stored full report.

Measured on 1,870 files:

| | calls | tokens | wall clock |
| --- | --- | --- | --- |
| nothing changed | 0 | 0 | **488ms** (replayed) |
| body edit to a widely-imported file | 0 | 0 | 4,737ms |
| comment inside a duplicated declaration | 1 | 1,571 | 5,284ms |
| same edit seen again | 0 | 0 | ~0 (cached verdict) |
| a full analysis | 0 | 0 | ~15s |

The 4.7s is file reads and hashing — correctness needs content, not mtimes. What
remains after that is parsing every file; an incremental fact cache keyed on
content hash would remove it. The candidate generation is already scoped.

## One column, two nullabilities

A type whose nullability comes from outside TypeScript: the database.

`joggle/nullability-drift` reads a knex migration statically — `table.uuid('x')`
is nullable, `.notNullable()` is what makes it required — and compares it with a
schema field that names the column it reads:

```ts
export const PayrollCrewRowSchema = Schema.Struct({
  personId: Schema.NullOr(uuid).annotate({ sourceColumn: 'payroll_crew.shakti_user_id' }),
})
```

The mapping is an **annotation**, because it is not derivable: the field is
`personId`, the column is `shakti_user_id`, and that alias exists only in the SQL.
A repository opts in by annotating; a field with no `sourceColumn` is not
compared at all, and the rule's note says so rather than printing a clean zero.

The comparison is deterministic: a migration is a specification and
`Schema.NullOr` is a fact. What is a judgement is what the disagreement *means* --
a schema that should agree with the migration, a null that is data the adapter
handles, or an annotation that reads the wrong column -- and that is the question.
What it catches is the decode that fails the first time real data arrives: the
column can hold a null and the schema refuses it.

## A 5xx for a row that is not there

The amplifier the nullability work cannot see: the data is legitimately absent,
and the endpoint reports a server outage for it. One bad request becomes an
outage signal — pagers, error budgets, retries against a request that will never
succeed.

`joggle/data-error-as-outage` is judged, and the split is deliberate:

- **Candidate (deterministic, high recall):** any branch that could be about a
  row and answers a 5xx — a nullish guard (`!row`, `row == null`) with a 5xx
  inside, or a `try` whose `catch` answers a 5xx (`reply.code(500)`,
  `res.statusCode = 503`).
- **Questions (Jev), atomic, over the same handler source:**
  - `about_a_row` (Noul) — does the branch concern a row from a data store?
  - `verdict` (Choice) — is the absent row normal, or a broken invariant?
- **Composed in code:** report only when the branch IS about a row and the
  absence is normal. `row_absence_is_normal` reports; `row_absence_is_an_error`
  drops; a deliberate 5xx is pinned in `.joggle/answers/`.

A nullish guard with a 5xx inside is specific enough to report unverified when no
model is available; a bare `catch` is not — every ordinary error handler has one —
so a `catch` is reported only once the model confirms it is about a row.

The candidate does **not** decide what a row read is. An earlier version named it
in code (`find*`, `get*`, `load*`, `parse*`), and against a real repository it
missed a read inside a callback, a bare call, and a verb that was not on the list
— three false negatives no answer could recover, because a candidate that is
never sent cannot be judged. So the code finds the *shape* and asks the question
the names were guessing at: state, not a pre-decided classifier. Nothing here
knows Fastify, Express or a schema library.

## Not here yet

The honest list: **no type awareness** (see above -- it is the next layer), no
LSP, no `--fix`, no emission as an oxlint rule, and no
calibration harness. The calibration harness is the piece that has to exist
before any judged rule can move from `warn` to `error`.

## Layout

```
src/
  policy.ts                 every threshold and question version, one file
  schema.ts                 diagnostics, the System One contract, typed errors
  workspace.ts              oxc facts, normalisation, similarity
  typetrace.ts              tsgo --generateTrace reader, and the type facts cache
  tsgo.ts                   tsgo subprocess adapter
  decision.ts               System One client, with the wire and answer caches
  atoms.ts                  the run's shared facts, content-addressed
  plans.ts                  the plan engine: one request per run, cache per question
  rule.ts                   the Rule and PlannedRule vocabulary
  rules/                    one file per rule
  check.ts                  the two-phase analysis pass
  report.ts                 text / json / github
  main.ts                   CLI
extensions/
  joggle.ts                 the pi extension: tools and a command over the CLI
scripts/
  joggle.sh                 the global command: resolves the checkout, supplies the key
  joggle-elsewhere.sh       check another checkout without writing into it
tests/
  fixtures/corpus/          intentionally duplicated fixture project
```

`docs/` is the thinking that motivated this layer -- how agents navigate code,
why names are addresses, parse don't validate, incremental computation, the
deterministic harness. The previous implementation -- a Rust CLI of hand-written
heuristics -- has been removed; the ideas worth keeping are the rules here.
