No credentials needed (pure fs + git + local http probes); if a verb grows
one, use env("KEY") from ../snappy-settings/load.ts
Every exported function returns a real value or throws; no silent "TODO"s
THE DERIVATION LAW — the installed artifact is the spec (Robert 2026-08-05, LAW)#
For any SDK, dependency, or API: enumerate its REAL surface from the installed package (node_modules/<pkg> — dist, CLI commands, shipped docs) and fetch its llms.txt/llms-full.txt BEFORE writing a line of integration. Import the package's own types; never redeclare a type a dependency exports; never write an integration from memory; never describe a surface you haven't listed. A hand-written parallel of a generated, vendored, or documented definition is a defect (DRY, original sense: one authoritative representation of every piece of knowledge). Writing from training memory instead of the installed source produces hallucinated APIs — the named killer of OpenAI's plugin ecosystem. Printing Press (spec→generated connector) is this law's special case; it applies to EVERYTHING.
1. Fix gaps (P — proportional). MANDATORY. If this AGENTS.md didn't cover your case — if you had to read another file, run a command not documented here, work around a wrong selector, or discover a quirk — you MUST attempt an Edit before you can log.
Default action: edit this AGENTS.md. Surgical. Add the missing line, table row, or code example where it belongs. No restructuring.
Only LOGGED is allowed when: the fix needs >10 lines, spans multiple files, or requires a structural rewrite (in which case the drain-skill-regen.sh queue picks it up).
"I didn't have time" / "it's minor" / "the next agent will figure it out" are NOT valid reasons to skip the Edit. The whole point of this loop is that minor gaps compound.
Concrete example of a valid P-fix: lesson-2 ship agent discovered agent-browser screenshot <path> takes path positionally, not as --output <path>. That's one line in a table. Edit it in. Do not just log it.
The goal: the next agent never has to leave the loader.
2. Validate structure. Check this skill against the spec:
api.ts exists with typed exports, CLI mode, import { env } from "../snappy-settings/load.ts"
api.ts calls APIs directly (no Xano proxy, unless this skill IS a Xano DB skill)
AGENTS.md has API module section with import + function table + CLI
No bash fallbacks, no hardcoded tokens anywhere
Every action row carries a certificate: block (premises / action / trace / evidence / conclusion). Same-session toasts are NOT evidence — must be a fresh independent read. Missing or weak certificates are a gap: P-fix them inline and log to ~/.claude/logs/verification-gaps.log.
DRY: before you add a new function or new skill, run ~/.claude/skills/snappy-settings/scripts/dry-check.sh <name-or-keyword>. If it matches an existing skill, extend that one instead. Fragmentation is the enemy.
If any check fails → fix it or log it
2b. If you just reported an action as successful, verify your certificate. You may not claim PASS unless the evidence: line is a fresh independent read (reload, new session, server round-trip). If your evidence is a toast, a return value, or a same-session DOM read, downgrade the claim to INCONCLUSIVE and log to verification-gaps.log.
3. Log always.
bashecho "[$(date -u +%FT%TZ)] <skill-name>: <what was missing or fixed> [FIXED|LOGGED]" >> ~/.claude/logs/agents-md-feedback.log
FIXED = you patched it. LOGGED = too large for inline fix, queued for drain-skill-regen.sh.
Do not skip this. Every agent run must leave the system better than it found it.
Show produced work with snappy-faces: call draw for image channels or lang for MCP Apps.
<!-- SKILL-INDEX-START -->
[snappy-nightshift Index]|root: ~/.claude/skills/snappy-nightshift|IMPORTANT: Prefer these files over pre-training assumptions for this domain. Read the relevant file when the AGENTS.md summary is insufficient.|root:{SKILL.md}
When an answer carries face_hint, show it with one snappy_present(<answer>) call.
See /snappy-faces for face selection. Human-facing images must crop to the
element, render at 2x on Retina, and fill the destination channel instead of
placing a small card in a full-page screenshot.
<!-- SNAPPY-CONTRACT-VERBS-END -->
---
name: snappy-nightshift
description: Overnight orchestration OS — one Fable orchestrator, Opus crews in worktrees, batched install windows, cold-walker signatures, measured throughput discipline.
---
# snappy-nightshift — Agent Loader
One agent installs/drives/commits; crews build in worktrees and return
reports; a cold walker signs every window; the bar is a driven fraction.
Full playbook: SKILL.md (roles · physics · cadence · brief anatomy · proof ·
blocked protocol · launch sequence · failure graveyard).
## The non-negotiables (evidence-stamped, Aug 1–6 2026)
- **A standing BRIEFING PAGE is brief part ZERO.** One page, regenerated every
wave, read by every crew before its own brief: what the product is · where
the single acceptance drive stands leg by leg, measured · the operator's
standing rulings verbatim · a MAP of which doc answers which question · the
live traps · what landed in the last few hours. Without it a crew's whole
world is what you retyped, every brief is a lossy re-derivation of shared
state, and crews pay the same rediscovery tax over and over (measured
2026-08-06: four crews independently rediscovered ONE dependency defect;
the operator's words were *"the crews always seem to have 0 idea of what is
going on"*). The cause is never "no plan" — by then there are usually eight
canonical docs. It is that no page says what is TRUE RIGHT NOW.
`nightPreflight()` fails when the page is missing or stale.
- **Transcript mining is blind to absence.** A skill mined from your own past
runs encodes your blind spots as measured best practice — a transcript shows
every crew that ran, never the context those crews never got. Rules from
mining are half a skill; the other half must come from failures observed in
the PRODUCT (cold walks, the operator's own drives), the only source that
sees what is missing rather than what happened.
- ONE installer/committer/driver — the orchestrator. Crews NEVER install,
commit, `git add`, run `npm run check`, playwright, or full tsc.
- `git commit --only <explicit pathspec>` + `check-head` after every commit.
Never `add -A`. Never `git stash` (worktrees share one stash ref).
- Load ceiling: launch nothing above load ~80 on 8 cores; crews run scoped
tests only; serialize check-head and acceptance under the mutex.
- Install windows every ~90 min, boarded whole: daemon-ready → runtime →
web → relaunch → deploy-truth probe. Exit 0 is not evidence — grep the log.
- Heartbeat 20 min; tick lines only on change/stall, real clock + hash;
logging under 10% of commits; a tick that launches nothing while streams
idle is a failure.
- Crew briefs carry all seven parts (role+prohibitions · verbatim clause ·
resolved file:line anchors · named anti-fix · ownership rails · size caps ·
report contract) + derivation law + prove-red. Ownership by OBJECT and
VERB, never by page.
- Stalls read off territory mtimes + the commit clock, never self-report.
- Cold eyes sign every window with shots; the author never signs their own
surface; report the bar as a fraction.
- BLOCKED.md one-liners; re-run the whole list when any technique lands;
blocked-on-human is the only legal stop.
- Second landing of a defect class = the class-ending mechanism, or refused.
## API
| Function | Purpose |
|---|---|
| `nightPreflight()` | GO/NO-GO launch checklist (worktrees, daemon, ports, load, dirt) |
| `nightStatus()` | one-screen truth: HEAD, load, worktrees, daemon, stamp, blocked |
| `nightLog(line)` | timestamped NIGHT-LOG tick line |
| `parkBlocked(id, failed, t1, t2, unblock)` | canonical BLOCKED.md entry |
| `barScoresheet()` | the sixteen checks as a fillable scoresheet |
| `morningReport(hours)` | morning-report skeleton (bar curve + commits + blocked) |
## CLI
```bash
npx tsx ~/.claude/skills/snappy-nightshift/api.ts preflight # before any launch
npx tsx ~/.claude/skills/snappy-nightshift/api.ts status
SNAPPY_NIGHT_REPO=/path/to/repo npx tsx ~/.claude/skills/snappy-nightshift/api.ts report 10
```
## Rules
- No credentials needed (pure fs + git + local http probes); if a verb grows
one, use `env("KEY")` from `../snappy-settings/load.ts`
- Every exported function returns a real value or throws; no silent "TODO"s
---
## THE DERIVATION LAW — the installed artifact is the spec (Robert 2026-08-05, LAW)
For any SDK, dependency, or API: enumerate its REAL surface from the installed package (`node_modules/<pkg>` — dist, CLI commands, shipped docs) and fetch its `llms.txt`/`llms-full.txt` BEFORE writing a line of integration. Import the package's own types; never redeclare a type a dependency exports; never write an integration from memory; never describe a surface you haven't listed. A hand-written parallel of a generated, vendored, or documented definition is a defect (DRY, original sense: one authoritative representation of every piece of knowledge). Writing from training memory instead of the installed source produces hallucinated APIs — the named killer of OpenAI's plugin ecosystem. Printing Press (spec→generated connector) is this law's special case; it applies to EVERYTHING.
## Self-correcting loader (PID feedback)
The system spec lives at `~/.claude/skills/snappy-settings/skill-spec.md`. It defines the entire Snappy operating system. You enforce it.
### Before you finish, do two things:
**1. Fix gaps (P — proportional). MANDATORY.** If this AGENTS.md didn't cover your case — if you had to read another file, run a command not documented here, work around a wrong selector, or discover a quirk — you MUST attempt an `Edit` before you can log.
- **Default action: edit this AGENTS.md.** Surgical. Add the missing line, table row, or code example where it belongs. No restructuring.
- **Only LOGGED is allowed when:** the fix needs >10 lines, spans multiple files, or requires a structural rewrite (in which case the drain-skill-regen.sh queue picks it up).
- "I didn't have time" / "it's minor" / "the next agent will figure it out" are NOT valid reasons to skip the Edit. The whole point of this loop is that minor gaps compound.
- Concrete example of a valid P-fix: lesson-2 ship agent discovered `agent-browser screenshot <path>` takes path positionally, not as `--output <path>`. That's one line in a table. Edit it in. Do not just log it.
- The goal: the next agent never has to leave the loader.
**2. Validate structure.** Check this skill against the spec:
- `api.ts` exists with typed exports, CLI mode, `import { env } from "../snappy-settings/load.ts"`
- `api.ts` calls APIs directly (no Xano proxy, unless this skill IS a Xano DB skill)
- `AGENTS.md` has API module section with import + function table + CLI
- No bash fallbacks, no hardcoded tokens anywhere
- **Every action row carries a `certificate:` block** (premises / action / trace / evidence / conclusion). Same-session toasts are NOT evidence — must be a fresh independent read. Missing or weak certificates are a gap: P-fix them inline and log to `~/.claude/logs/verification-gaps.log`.
- **DRY:** before you add a new function or new skill, run `~/.claude/skills/snappy-settings/scripts/dry-check.sh <name-or-keyword>`. If it matches an existing skill, extend that one instead. Fragmentation is the enemy.
- If any check fails → fix it or log it
**2b. If you just reported an action as successful, verify your certificate.** You may not claim PASS unless the `evidence:` line is a fresh independent read (reload, new session, server round-trip). If your evidence is a toast, a return value, or a same-session DOM read, downgrade the claim to INCONCLUSIVE and log to `verification-gaps.log`.
**3. Log always.**
```bash
echo "[$(date -u +%FT%TZ)] <skill-name>: <what was missing or fixed> [FIXED|LOGGED]" >> ~/.claude/logs/agents-md-feedback.log
```
`FIXED` = you patched it. `LOGGED` = too large for inline fix, queued for drain-skill-regen.sh.
**Do not skip this.** Every agent run must leave the system better than it found it.
Show produced work with `snappy-faces`: call `draw` for image channels or `lang` for MCP Apps.
<!-- SKILL-INDEX-START -->
[snappy-nightshift Index]|root: ~/.claude/skills/snappy-nightshift|IMPORTANT: Prefer these files over pre-training assumptions for this domain. Read the relevant file when the AGENTS.md summary is insufficient.|root:{SKILL.md}
<!-- SKILL-INDEX-END -->
## Used by
Nothing in the collection names this skill.
<!-- SNAPPY-CONTRACT-VERBS-START -->
## Contract verbs
Generated from `api.ts` `HAND_CONTRACT`. Do not hand-edit this block.
| Verb | Contract arguments | Effect | First call |
|---|---|---|---|
| `bar` | — | `read` | `npx tsx ~/.claude/skills/snappy-nightshift/api.ts bar` |
| `blocked` | `lane-id`, `failed`, `tried-first`, `tried-second`, `unblock` | `write-reversible` | `npx tsx ~/.claude/skills/snappy-nightshift/api.ts blocked <lane-id> <failed> <tried-first> <tried-second> <unblock>` |
| `board` | — | `read` | `npx tsx ~/.claude/skills/snappy-nightshift/api.ts board` |
| `log` | — | `read` | `npx tsx ~/.claude/skills/snappy-nightshift/api.ts log` |
| `preflight` | — | `read` | `npx tsx ~/.claude/skills/snappy-nightshift/api.ts preflight` |
| `reap` | — | `delete` | `npx tsx ~/.claude/skills/snappy-nightshift/api.ts reap` |
| `report` | — | `read` | `npx tsx ~/.claude/skills/snappy-nightshift/api.ts report` |
| `status` | — | `read` | `npx tsx ~/.claude/skills/snappy-nightshift/api.ts status` |
## Show the result
When an answer carries `face_hint`, show it with one `snappy_present(<answer>)` call.
See `/snappy-faces` for face selection. Human-facing images must crop to the
element, render at 2x on Retina, and fill the destination channel instead of
placing a small card in a full-page screenshot.
<!-- SNAPPY-CONTRACT-VERBS-END -->
SKILL.md
snappy-nightshift — the overnight orchestration OS#
One agent orchestrates. Crews build. The machine has physics. The bar is a
driven fraction, never prose. This file is the distilled evidence of four
THE EXISTING, DEPLOYED Snappy MCP server: the Cloudflare Worker exposing the Snappy Xano API…
---
name: snappy-nightshift
reports_to: tool
head: false
description: "The overnight orchestration operating system: one orchestrator drives a repo toward 100% all night with build crews in worktrees, batched install windows, cold-walker signatures, wake-up loops to a hard stop time, and the throughput discipline measured from the real 2026-08 runs (peak 33 commits/hour at 10-12 lanes). Use when Robert says: /snappy-nightshift, \"we need to do /snappy-nightshift relentless through the night\", \"push hard overnight to 10AM eastern\", \"keep going all night dont stop\", \"keep the cadence, keep the momentum high to 10AM eastern time\", \"make a prompt for the other ai to push hard overnight\", \"update your wake up loop to keep you on the highest momentum\", \"continue, launch the agents again, go back to the mission\", \"night run\". Triggers on: nightshift, night run, overnight, build crew, install window, wake-up loop, hard stop time. NOT the per-seat app dogfooding (see snappy-resident). NOT Mac-mini jcode lane dispatch (see snappy-jcode)."
---
# snappy-nightshift — the overnight orchestration OS
One agent orchestrates. Crews build. The machine has physics. The bar is a
driven fraction, never prose. This file is the distilled evidence of four
measured overnight runs (Aug 1–6, 2026: ~460 commits, ~180 crew launches,
18+ install windows, three load catastrophes, two session deaths) — the rules
are not taste, each one has a timestamp where its absence burned hours.
**Companion files:** `api.ts` (deterministic verbs: preflight · status · log ·
blocked · bar · report) · the target repo's own canon (`THE-WORLD-CLASS-BAR.md`,
`THE-LAW-LEDGER.md`, `THE-BACKLOG.md`, `NIGHT-LOG.md`, `BLOCKED.md`).
---
## 1 · THE ROLES (violating this is the #1 named failure)
| Role | Who | Does | Never |
|---|---|---|---|
| **Orchestrator** | ONE Fable session (you) | installs, drives the installed app, commits (`--only`), merges, launches/corrects crews, logs, reports | builds features in the main tree ("I'll just do it myself" = the override pattern, named fault twice) |
| **Build crews** | Opus agents in **git worktrees** | edit + prove with SCOPED tests, return a report with an explicit pathspec | install, commit, `git add`, `npm run check`, playwright, full `tsc`, touch another crew's files |
| **Cold walker** | a fresh agent, zero build context | drives the INSTALLED app as a person, signs MAKES SENSE / FAILS ON SIGHT per screen, shots mandatory | see the diff before walking (the author never signs their own surface) |
| **Resident user** | optional standing lane | lives in the app doing real work, files friction with shots | fix anything itself |
| **The founder** | Robert, asleep | owns sends, money, approvals, signing identity, pricing | be woken for anything a hard-rail block already answers |
A crew that needs a change in a file another crew owns puts the exact patch in
its report — it never applies it. A refusal with a named reason is a PASSING
crew return (measured: the refusing crews were the highest-value returns of
Aug 5); a huge transcript ending in a compliance recital is a failed one.
## 2 · THE PHYSICS (measured on the 8-core/16GB M-series, 2026-08)
- **Load ceiling:** every load spike past ~80 starved the daemon into a
KeepAlive respawn loop and closed the install window (89 → 155 → 171 → 218
across two nights). **Cap: launch nothing new above load ~10/core-8; at
load >80 cut the fleet in half immediately.** Full-project `tsc`/vitest
batteries are the killers — crews run scoped tests ONLY; the orchestrator
serializes `check-head` and the acceptance battery under the mutex.
**SIZE THE FLEET FOR THE WORST CASE, NOT THE AVERAGE.** "Crews run scoped
tests only" and "at most two batteries at a time" are sentences in a brief,
and crews cannot see each other, so both are unenforceable by construction.
Measured 2026-08-06: six correctly-briefed crews each picked its own moment
and produced **7 vitest workers + 2 full-project `tsc` runs at once, load
183**, daemon starved, on a machine the operator was actively using (Zoom
at 48% CPU beside it). The only number you actually control is the fleet
size — choose it assuming EVERY lane runs its battery simultaneously: on 8
cores that is **3–4 build lanes, not 6**. Prefer the smaller number over
the better rule; a law the machine does not enforce gets broken at the
worst possible moment. Recovery is cheap now — stopped crews keep their
worktrees and resume from transcript — but resume a killed crew with
"REPORT ONLY, run nothing," and check whether it died mid-baseline-revert
with its diff saved to a file (restore it first, and never `git stash`).
- **Install lanes:** web-fast ~9–60s · runtime-fast ~52–79s · full Swift
~230–280s (port override mandatory; see repo OPERATING MAP). Order inside a
window: **daemon-ready first → runtime → web → relaunch app → deploy-truth**
(served build identity == HEAD, by probe, never by exit code).
- **check-head:** ~45s idle, 20+ min under load, times out during vitest
stampedes. One at a time, always. `git worktree prune` first — a stale
registration makes it die with a null-status "signal".
- **The kickstart deadlock** (daemon down with the app open): the app
health-probes every ~2s and SIGTERMs a daemon that needs ~80s to boot —
it will never bind while the app is up. Recovery: quit the APP first,
wait for healthz 200 by probe, then reopen. 33 restarts in 500 log lines
is this signature, not a crash loop.
- **One machine, one driver.** A second live session sharing the install
lane is "a second driver in a one-seat car" — hand the keyboard over
entirely or stay off it. Census/audit/classification is ORCHESTRATOR
work; builders get build orders only ("a census is not building").
- **Context budgets:** an orchestrator chain hands over at ~450–600k tokens
with a seam map + pathspec + red-first list; a cron firing into a dead
session logs nothing — arm a session-limit check in the heartbeat.
- **Concurrency sweet spot:** 5–8 build lanes hot sustained 25–33 commits/hour;
12+ lanes only worked when briefs were pre-resolved and NO lane ran suites.
2 lanes is the floor Robert accepts only under load emergency.
## 3 · THE CADENCE
1. **Heartbeat**: /loop or cron, **20 minutes** (the 5-min tick was measured
at 45% logging commits — banned; ceiling 10%). The prompt must name: the
target state, the ≥N-streams floor, "a tick that launches nothing new while
streams sit idle is a failure," the hard rails, and "never idle."
2. **Every tick**: integrate finished crews (`--only` from their pathspec +
`check-head`), relaunch the next lane the MOMENT one frees, catch stalls
(below), one NIGHT-LOG line ONLY on change or stall — with a real clock
read and a commit hash. Invented timestamps are fabrication.
3. **Install windows every ~90 min**: close the window before opening another
lane; lanes pause `state/**` writes at the boundary (a mixed-artifact
refusal is YOUR scheduling bug); board the window whole; drive it; the
walker signs it; publish the bar fraction; push; relaunch.
**Installs stay MAXED — never hold one for the human** (Robert: "i dont
care about it breaking the app if it means i dont see updates"). What
makes that safe is the reload door, not restraint: add-only hashed
assets + a "newer version is ready · reload" line + a reload on a
missing chunk — every web install swaps hashed chunks under the live
session, so the crew's drives look fine while the founder's open app
404s. Committed-but-not-installed is **inventory, not progress** — a fix
not on glass within two windows is a logged stall, and inventory
generates duplicate diagnosis.
4. **Merge waves at window boundaries** — never mid-window. Worktree merges
landed zero-conflict when lanes were file-disjoint; shared-tree lanes on
the same stylesheets hit five-file conflicts.
5. **Stall detection is territory mtimes + the commit clock, never
self-report or process count** ("the crews are dead, not working — the
last commit landed 25 minutes ago"). 30 min of silent territory = ping the
agent (SendMessage restarts it at its exact stopping point); twice = kill
and relaunch with the seam map.
## 4 · THE CREW BRIEF (median 2.7k chars, n=134 — every mergeable brief had all seven)
**0. A STANDING BRIEFING PAGE, regenerated every wave, read by every crew
before its own brief.** Without it a crew's entire world is whatever you
retyped into its prompt, so every brief becomes a lossy re-derivation of shared
state and each crew pays the same rediscovery tax — measured 2026-08-06: FOUR
crews independently rediscovered one dependency-resolution defect, and the
operator's own diagnosis was *"the crews always seem to have 0 idea of what is
going on."* The cause is never "no plan" — by then there are usually eight
canonical docs. It is that no page says WHAT IS TRUE RIGHT NOW. One page,
regenerated at each wave, carrying: what the product is · where the single
acceptance drive stands leg by leg, measured · the operator's standing rulings
verbatim · **a MAP of which doc answers which question, so nobody reads all
eight** · the live traps · what landed in the last few hours. Crews report if
its stamp is stale.
1. **Role + hard prohibitions in sentence one** ("BUILD AGENT … you NEVER
install, NEVER commit, NEVER git add, NEVER run npm run check or
playwright").
2. **The plan clause verbatim** with its done-when — never a paraphrase.
3. **File:line anchors already resolved by the orchestrator** — a crew that
has to hunt is a crew that drifts. Naked launches are a named failure;
seed the skills the lane needs (Swift → macos-native/swiftui-pro +
SwiftLens; visual → liquid-glass; etc.).
4. **The named anti-fix** ("the fix is NOT a wider regex — emission and
detection become ONE contract"). Include tested dead-ends so nobody
re-walks them.
5. **Ownership rails naming the other crews' files** — patches to foreign
files ride the report, never the tree.
6. **Size caps that force extraction** (900-line gate: UNDER 900 is the
standard; "didn't grow" is the backstop).
7. **A fixed report contract**: files changed with 1–2 sentences each, test
commands + verbatim tails, the pathspec for `--only`, anything undone.
Plus always: **the DERIVATION LAW** (enumerate the installed package's
real surface + llms.txt BEFORE integrating; import its types; hand-written
parallels of shipped definitions are defects) and **prove-red** (a gate
counts only after failing on a seeded defect).
**Ownership is by OBJECT and VERB, never by page** — per-page dispatch
reproduces the fragmentation it fixes ("four renderers of one type WILL
diverge, that is arithmetic").
**More brief mechanics that paid off:** every crew fast-forwards its worktree
to the branch tip and prints the SHA before touching anything (one crew built
on an ancestor with the lane files not checked out) · harnesses are READ, not
recalled (two storage keys written from memory cost a full diagnosis cycle;
drivers derive selectors/routes/auth from the live artifact) · use-testing
crews get a USER PERSONA brief ("you are a PERSON using the app, NOT a tester,
NOT fuzzing") with the founder's real records fenced by name · **re-brief a
running crew mid-flight instead of kill+relaunch** (a panel crew absorbed a
whole new anatomy without losing its worktree) · front-load cheap read-only
Explore scouts (2–8 min median) to resolve anchors for the build briefs — but
never let a research wave complete without a build lane already consuming it
(Robert sent "a whole bunch of research for no reason" twice, verbatim, 10
minutes apart). The orchestrator MAY hand-build the typed CORE (one-record
contracts, parsers) — that is owning the object — but surfaces are always
dispatched, and an orchestrator module is deleted the moment a crew lands the
same road through the one resolver.
## 5 · PROOF DISCIPLINE (what converts "committed" into "true")
- **Exit 0 is not evidence.** Grep install/check logs for
`refusing to certify|FAIL|ERROR` and read the tail; the bundle-budget
silent no-op served a 01:33 bundle while ~10 crews shipped ~100 invisible
screens. "Exit 0 lied to me twice tonight." The named worst case — THE
MIXED ARTIFACT, "the trap that wasted a full day": the install lanes hash
inputs before/after; ANY file changing mid-build → "refusing to certify a
mixed artifact" → **EXITS 0** → rsyncs the LAST staged bundle → reports
success. Also: verify your own guard commands work on THIS machine (`find
-newermt` under bfs errored silently = read as "all clear"; `$?` after a
pipe reports `tail`).
- **The negative control, every gate**: inject the violation, watch the gate
name it, restore, confirm md5-identical. "I don't accept a passing gate I
haven't seen fail." Then commit the gate as a lint in `npm run check` so
the class is uncommittable, not merely fixed.
- **Warden evals for headless/cheap runners**: discard every worker
self-report; a lane is green only when the ORCHESTRATOR'S OWN eval exits
0 — per order: an orchestrator-authored pin test + a grep proving the
wiring + an md5 proving the runner didn't touch the eval + the repo gate.
On red, auto re-dispatch with the verbatim failure text.
- **Sentinel-gate measurements**: refuse to run a suite unless the served
chunk provably contains the fix (string-level probe), AND no other writer
is live AND the tree hash has been still 90s — else the verdict describes
a tree that no longer exists (the stale-receipt loop: ~140 min lost).
- **The web-bundle gate**: typecheck cannot see a Node global dragged into a
browser chunk (`process.argv` in a lazy chunk = every errand page a crash
screen, twice). Only a real vite build / process-less eval catches it.
- **Cold eyes on every window** ("every gate checks structure and every
check was run by the surface's own author — that ends now"). Claims
without shots don't count; the log carries a SURFACE section per window;
the Captain reads the table, not the prose.
- **Second-landing ban**: touching a defect class a second time REQUIRES the
class-ending mechanism; a second patch is refused work. Mechanisms end
classes; surfaces don't.
- **Report as a fraction against the repo's bar file** ("11 of 16, zero kill
switches"), one driven canonical flow per window, shot per check. A commit
subject may never claim a fix works — only a driven row may.
## 6 · THE BLOCKED PROTOCOL
One line in `BLOCKED.md`: `- [ID] what failed | technique 1 | technique 2 |
what would unblock` — then take the next item. A blocker never halts the
night; blocked-on-human is the only legal stop and it must be named in those
words. **When a new technique unblocks anything, re-run the ENTIRE list**
(the `security export` lesson: one discovered technique invalidates every
"impossible" concluded before it). An entry that grew into an essay is a halt
wearing a log's clothes.
## 5b · SEQUENCING AND CONTINUITY
- **Construction before deletion** — removing lies first makes the app look
emptier and reads as regression ("I sequenced deletion before
construction, which is the wrong order to show anybody").
- **Re-anchor the governing order from the RAW transcript at every
compaction boundary** — never from the summary alone (order amnesia: two
wrong answers to "tell me what I said you need to do" after ~30
compactions; recovered only by jq-ing the prior session file).
- **Timer ticks are not evidence of work** — a 5-hour zero-commit blackout
ran under a live loop firing every 31 minutes; after two consecutive
commitless ticks, self-escalate or page.
- **Push immediately; unpushed work does not exist.** From detached
worktrees push `HEAD:branch`, never the bare branch name.
- **Never silent during a tool chain** — one specific status line per step;
four "are you there" pings arrived inside 65 seconds once.
## 6b · RANKING AND WIP
Work ROOTS, not symptoms: sweep, collapse observed defects into mechanisms,
rank by **defects-killed-per-mechanism** ("~14 mechanisms kill 50+ observed
defects"; instance-patching is refused work). WIP caps at the number of
lanes you can actually INTEGRATE — finish-and-install beats start-another,
and when two items tie, the one the human can SEE wins. Irreversible acts
(live-store migrations, mass rewrites): rehearse against a copy overnight,
keep the timestamped backup, write the verdict, execute on the morning go —
the C9 pattern ran 126/126 valid because the rehearsal was identical.
## 6c · DIRECTIVES AND MONITORING
- The night launches as **ONE self-contained paste into a FRESH session** —
nothing may depend on a prior session's memory; the same shape re-armed
three nights running.
- Directives are complete, explicit, euphemism-free ("it makes 'the thing'
— WTF does that mean?" — length is not a cost, ambiguity is). **Omit
numeric budgets unless they are the acceptance criterion** — stated
latency numbers get bikeshedded.
- Never draft a directive that halts all lanes (vetoed live: "they are not
supposed to stop everything").
- **Monitor the installed bytes, not the crew's summary**: a watcher on the
bundle stamp (it only changes when an install truly lands on glass) beats
any self-report; verify with your own fresh capture before reporting
anything to the human.
## 7 · OPERATOR INTERRUPTS
A live order from Robert mid-run (pause, widen, change model tier, HOLD)
overrides the standing cron floor immediately and is logged as an override.
The named workflow he sets IS the spec — never substitute "faster" judgment.
When he says GO with a step-ordered discipline, execute the steps in his
order with the checks he named. His hard rails (nothing external sends, no
live-store `--apply` without rehearsal+backup, named human-only approvals, no
force-push) are what MAKE "do not wait on me for anything you can do safely"
grantable — keep them in the loop prompt verbatim.
## 8 · THE LAUNCH SEQUENCE (boot order for any night)
1. **Read the repo canon** (~25 min cap): the bar file, the law ledger, the
backlog, NIGHT-LOG tail, BLOCKED.md, repo CLAUDE.md operating map.
2. **`api.ts preflight`** — worktree prune, daemon health, port 3149, load,
dirty count, live worktrees, install stamp. Fix every FIX line first.
**Then prove a worktree is fully provisioned BEFORE the fleet launches**:
cut a throwaway worktree, run one real test suite in it, and check that a
package resolves to the same version there as in the main tree. Measured
2026-08-06: a gitignored nested `node_modules` (web workspace at 0.12.1,
root at 0.11.9) meant every fresh worktree silently resolved the OLD copy
and every renderer suite died on a missing export — **four separate crews
burned time rediscovering it independently** before anyone named it. A
half-provisioned worktree turns a build lane into an archaeology lane. If
the environment is the defect, fix the environment as its own lane and
fix it as a MECHANISM (one resolved version + a duplicate-resolution gate
+ automatic provisioning); a documented recovery is a mistake waiting to
be made again.
3. **Reconcile the backlog against HEAD** (`git log` since last window) —
last night's plan is stale by morning; regenerate the order from what
actually landed. Integrate-or-kill every leftover worktree.
4. **Baseline**: install HEAD, drive the canonical flow, publish the bar
fraction — the night's starting number.
5. **Launch wave 1**: 5–8 file-disjoint crews from the backlog order, briefs
per §4, worktrees for anything touching shared sheets/chrome.
6. **Arm the heartbeat** (§3) + a session-limit guard + the morning-report
time (~07:30, `api.ts report` skeleton).
7. **Run the loop** until the morning report: integrate → window → drive →
sign → fraction → push → relaunch. Never idle.
## 9 · NAMED FAILURE MODES (the graveyard — read before you repeat one)
- The override pattern (orchestrator hand-builds; Robert: "you need to use
opus agents").
- The message-bus human (two AI teams coordinating through the founder's
clipboard — an exhausted human as IPC).
- Shape-not-intent optimization ("'match the prototype' read as 'resemble
it' — nobody counted; 99 missing rooms invisible").
- The stitcher that drops routers (parallel crews perfect, assembled product
127 visible characters — integration is a first-class lane, not an
afterthought).
- Killing mid-edit streams on a stall misread ("I traded three finished
items for a no-op install window").
- Stopping the agents on a misread instruction (Robert's sharpest reaction
of the day).
- Adjacent-interesting-work drift narrated as progress.
- Author-verified-own-intent (the Build placard passed every structural gate).
- `git stash` in a worktree'd repo (one shared ref — a pop in any lane can
take another lane's entry). Baseline = commit-then-rebase or `git diff >
file`, never stash.
- Fabrication class: UI promising what the machine won't do ($0.00 on a
model verb; "All 7 passed" above five failures; invented tick times).
## 10 · API
```bash
npx tsx ~/.claude/skills/snappy-nightshift/api.ts preflight # GO/NO-GO launch checklist
npx tsx ~/.claude/skills/snappy-nightshift/api.ts status # one-screen truth
npx tsx ~/.claude/skills/snappy-nightshift/api.ts log "tick 3 · merged crew A (abc123) · window 2 boarded"
npx tsx ~/.claude/skills/snappy-nightshift/api.ts blocked ID "what failed" "t1" "t2" "unblock"
npx tsx ~/.claude/skills/snappy-nightshift/api.ts bar # the sixteen as a fillable scoresheet
npx tsx ~/.claude/skills/snappy-nightshift/api.ts report 10 # morning-report skeleton
```
Repo override: `SNAPPY_NIGHT_REPO=/path/to/repo`. Exported functions:
`nightStatus() · nightPreflight() · nightLog() · parkBlocked() · barScoresheet() · morningReport()` — all
primitive, shell-callable, no credentials.
## Near neighbours
Skills whose description overlaps this one enough that a reader could pick the
wrong door. Each row is that skill's own first sentence about itself, so the
choice is made on its words, not on a summary written here.
| Skill | Reach for it instead when |
|---|---|
| `snappy-agent-host` | Run the REAL Claude Code, Codex, and Gemini CLIs through ACP via the skills MCP, with durable… |
| `snappy-artifact-loop` | Build published Artifacts as I/O devices where the AGENT is the backend, not as static output… |
| `snappy-ax` | Drive any Mac app through the Accessibility tree (AXUIElement) the way the shipping tools act… |
| `snappy-blog` | Interview-driven blog post generation for the Snappy website (snappy.ai/blog). |
| `snappy-content` | Interview-driven content production methodology, the writing engine for every Snappy channel… |
| `snappy-dashboard` | Snappy Dashboard — the operating system for your backend infrastructure. |
| `snappy-desktop` | macOS desktop automation primitive for the Snappy stack via Midscene vision AI (`npx @midscen… |
| `snappy-freshbooks` | Snappy FreshBooks -- authoritative source for DRAFT invoicing, billing, time tracking, expens… |
| `snappy-github` | Centralized GitHub operations across all Snappy client repos via the `gh` CLI -- pull request… |
| `snappy-image` | Centralized image generation, editing, and capture for Snappy: Nano Banana / Gemini, Grok / x… |
| `snappy-os-operator` | Operate SnappyOS like a pro through product doors only: governed connector reads, staged writ… |
| `snappy-review-pages` | Local HTML review pages with provenance and a copy-back feedback loop. |
| `snappy-session-close` | Close a working session in two verbs: RECONCILE the agent-facing docs of a repo set (CLAUDE.m… |
| `snappy-swarm` | Orchestrate swarms of parallel AI agents for multi-wave quality passes across a project. |
| `snappy-telegram` | Telegram Bot API channel for Snappy: direct calls to api.telegram.org (no Xano middleware) to… |
| `snappy-video` | Video and audio processing pipeline for Snappy, run on the Mac Mini via SSH (caption-video.sh… |
| `snappy-voice-control` | Voice control on macOS, extracted from two shipping open-source agents (fazm by mediar-ai; Ag… |
| `snappy-watchtower` | Standing error monitors and the probes that lie: arm live typecheck, build, and test monitors… |
| `snappy-website` | Snappy website (snappy.ai) operations -- Next.js + Vercel marketing site, VSL conversion funn… |
| `snappy-xano-mcp` | THE EXISTING, DEPLOYED Snappy MCP server: the Cloudflare Worker exposing the Snappy Xano API… |
api.ts
// snappy-nightshift — typed programmatic interface.
// Deterministic handles for the overnight orchestrator: preflight, status,
// tick logging, blocked ledger, bar scoresheet, morning report skeleton.
// No credentials needed; pure local fs + git + http probes.
import { execFileSync } from "node:child_process";
import { existsSync, readFileSync, appendFileSync, realpathSync, readdirSync, statSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { annotationsForClass } from "../snappy-settings/tool-annotations.ts";
import { RefusedError, isRefusedError, printRefusal, refusalTable } from "../snappy-settings/refusal-codes.ts";
import { fileRefusal, pinnedFile, serviceUrl, type PinnedFile } from "../snappy-settings/hand-resources.ts";
// env() unused today (no credentialed verbs) — imported per spec so the first
// credentialed verb uses the one loader instead of inventing a second road.
import { env as _env } from "../snappy-settings/load.ts";
const REPO = process.env.SNAPPY_NIGHT_REPO ?? "/Users/robertboulos/Projects/snappy-os-app";
// THE ADDRESS COMES FROM THE ONE REGISTRY ⟨lane mini-reads, 2026-09-09⟩.
// `status` reports the daemon's health; holding the address here made this the
// fifth hand with its own copy, and a moved daemon would have been reported
// DOWN by a probe of the wrong place.
const DAEMON = serviceUrl("snappy-os-app");
function sh(cmd: string, args: string[], cwd = REPO): string {
try {
return execFileSync(cmd, args, { cwd, encoding: "utf8", timeout: 20_000 }).trim();
} catch (e: any) {
return `ERR ${e?.status ?? ""} ${String(e?.stderr ?? e?.message ?? "").slice(0, 200)}`.trim();
}
}
function nowStamp(): string {
const d = new Date();
const p = (n: number) => String(n).padStart(2, "0");
return `${p(d.getHours())}:${p(d.getMinutes())}`;
}
export interface NightStatus {
head: string;
branch: string;
aheadBehind: string;
dirtyFiles: number;
loadAvg: string;
agentWorktrees: number;
daemonHealthy: boolean;
installStamp: string | null;
lastLogLine: string | null;
blockedOpen: number;
}
export async function nightStatus(): Promise<NightStatus> {
const head = sh("git", ["rev-parse", "--short", "HEAD"]);
const branch = sh("git", ["rev-parse", "--abbrev-ref", "HEAD"]);
const aheadBehind = sh("git", ["status", "-sb"]).split("\n")[0] ?? "";
const dirtyFiles = sh("git", ["status", "--porcelain"]).split("\n").filter(Boolean).length;
const loadAvg = sh("sysctl", ["-n", "vm.loadavg"], "/");
const agentWorktrees = sh("git", ["worktree", "list"]).split("\n").filter((l) => l.includes(".claude/worktrees/")).length;
let daemonHealthy = false;
try {
const r = await fetch(`${DAEMON}/healthz`, { signal: AbortSignal.timeout(3000) });
daemonHealthy = r.ok;
} catch { /* daemon down is a finding, not a crash */ }
const stampPath = join(REPO, "apps/snappy-os/Sources/SnappyOS/Resources/web/build-stamp.txt");
const installStamp = existsSync(stampPath) ? readFileSync(stampPath, "utf8").trim().slice(0, 80) : null;
const nightLog = join(REPO, "NIGHT-LOG.md");
const lastLogLine = existsSync(nightLog)
? readFileSync(nightLog, "utf8").trim().split("\n").at(-1)?.slice(0, 200) ?? null
: null;
const blockedPath = join(REPO, "BLOCKED.md");
const blockedOpen = existsSync(blockedPath)
? readFileSync(blockedPath, "utf8").split("\n").filter((l) => l.startsWith("- [") && !l.startsWith("- ~~")).length
: 0;
return { head, branch, aheadBehind, dirtyFiles, loadAvg, agentWorktrees, daemonHealthy, installStamp, lastLogLine, blockedOpen };
}
export interface ResolutionSplit { pkg: string; a: string; b: string }
/** Packages reachable at TWO versions from two node_modules roots.
* Measured 2026-08-06: 16 of 16 shared packages disagreed — INCLUDING
* typescript (6.0.3 vs 5.9.3) and ajv (8 vs 6). That is why no typecheck
* ever caught it: the checker is one of the duplicated packages, so the
* instrument cannot audit itself. Nothing may prove a tree green until
* this reads zero-or-justified. */
export function resolutionSplits(roots = ["node_modules", "apps/snappy-os/web/node_modules"]): ResolutionSplit[] {
const read = (root: string): Map<string, string> => {
const out = new Map<string, string>();
const dir = join(REPO, root);
if (!existsSync(dir)) return out;
const version = (p: string): string | null => {
try { return JSON.parse(readFileSync(join(p, "package.json"), "utf8")).version ?? null; } catch { return null; }
};
for (const entry of readdirSync(dir)) {
if (entry.startsWith(".")) continue;
if (entry.startsWith("@")) {
for (const scoped of readdirSync(join(dir, entry))) {
const v = version(join(dir, entry, scoped));
if (v) out.set(`${entry}/${scoped}`, v);
}
} else {
const v = version(join(dir, entry));
if (v) out.set(entry, v);
}
}
return out;
};
const [a, b] = [read(roots[0] ?? ""), read(roots[1] ?? "")];
const splits: ResolutionSplit[] = [];
for (const [pkg, va] of a) {
const vb = b.get(pkg);
if (vb && vb !== va) splits.push({ pkg, a: va, b: vb });
}
return splits.sort((x, y) => x.pkg.localeCompare(y.pkg));
}
export interface PreflightVerdict { go: boolean; lines: string[] }
/** The launch checklist. Every line is a named check with its verdict. */
export async function nightPreflight(): Promise<PreflightVerdict> {
const lines: string[] = [];
let go = true;
const s = await nightStatus();
const stale = sh("git", ["worktree", "list"]).split("\n").filter((l) => l.includes("prunable")).length;
lines.push(stale === 0 ? "OK worktree registrations clean" : `FIX ${stale} prunable worktree registrations — run: git worktree prune (stale ones silently kill check-head)`);
if (stale > 0) go = false;
lines.push(s.daemonHealthy ? "OK daemon :3147 healthy" : "FIX daemon :3147 not answering — pkill -f 'head-screen/server.mjs', wait ~10s for respawn");
if (!s.daemonHealthy) go = false;
const port3149 = sh("lsof", ["-ti", ":3149"], "/");
lines.push(!port3149 || port3149.startsWith("ERR") ? "OK port 3149 free (install proof port)" : `FIX port 3149 held by pid ${port3149} — installs will refuse to swap AND exit 0`);
if (port3149 && !port3149.startsWith("ERR")) go = false;
const briefing = join(REPO, "RUN-BRIEFING.md");
if (!existsSync(briefing)) {
lines.push("FIX no RUN-BRIEFING.md — crews will start contextless; write it before launching (brief part zero)");
go = false;
} else {
const ageHours = (Date.now() - statSync(briefing).mtimeMs) / 3_600_000;
if (ageHours > 6) {
lines.push(`FIX RUN-BRIEFING.md is ${ageHours.toFixed(1)}h stale — regenerate it; a briefing nobody trusts is worse than none`);
go = false;
} else {
lines.push(`OK RUN-BRIEFING.md is ${ageHours.toFixed(1)}h old`);
}
}
const splits = resolutionSplits();
const toolSplit = splits.filter((s2) => ["typescript", "ajv", "eslint", "vitest"].includes(s2.pkg));
if (splits.length === 0) {
lines.push("OK one resolved version per shared package");
} else {
lines.push(`FIX ${splits.length} package(s) resolve to TWO versions — a worktree silently gets the wrong one:`);
for (const s2 of splits.slice(0, 20)) lines.push(` ${s2.pkg}: ${s2.a} vs ${s2.b}`);
if (toolSplit.length > 0) {
lines.push(` ^^ ${toolSplit.map((t) => t.pkg).join(", ")} is a PROOF INSTRUMENT — every "green" from a worktree is suspect until this is resolved`);
go = false;
}
}
const load1 = parseFloat(s.loadAvg.replace(/[{}]/g, "").trim().split(/\s+/)[0] ?? "0");
lines.push(load1 < 8 ? `OK load ${load1} (8 cores)` : `WARN load ${load1} on 8 cores — halve the crew fleet before launching more`);
lines.push(`INFO ${s.aheadBehind}`);
lines.push(`INFO ${s.dirtyFiles} dirty files (never git add -A; commit --only with explicit paths)`);
lines.push(`INFO ${s.agentWorktrees} live agent worktrees — integrate or kill before launching overlapping lanes`);
lines.push(`INFO install stamp: ${s.installStamp ?? "none"}`);
return { go, lines };
}
/** THE ONLY WAY A WORKTREE MAY BE REMOVED. Refuses any lane holding uncommitted
* work or commits not in HEAD, and says which. Written 2026-08-06 because the
* orchestrator hand-removed a worktree whose crew had reported complete and
* never been merged — `git diff` saved its 12 MODIFIED files and silently lost
* the 7 it had CREATED, because untracked files are not in a diff and git
* never hashed them. The dirty count was on screen at the moment of removal.
* A number you have to remember to read is not a guard. */
export function reapWorktrees(apply = false): string[] {
const out: string[] = [];
const root = join(REPO, ".claude/worktrees");
if (!existsSync(root)) return ["no worktrees"];
for (const dir of readdirSync(root)) {
const wt = join(root, dir);
if (!existsSync(join(wt, ".git"))) continue;
const dirty = sh("git", ["-C", wt, "status", "--porcelain"]).split("\n").filter(Boolean).length;
const tip = sh("git", ["-C", wt, "rev-parse", "HEAD"]);
const merged = sh("git", ["merge-base", "--is-ancestor", tip, "HEAD"]) === "";
const untracked = sh("git", ["-C", wt, "ls-files", "--others", "--exclude-standard"]).split("\n").filter(Boolean).length;
if (dirty === 0 && merged) {
if (apply) { sh("git", ["worktree", "remove", "-f", wt]); out.push(`REAPED ${dir} (clean, merged)`); }
else out.push(`WOULD REAP ${dir} (clean, merged)`);
} else {
const why = [
dirty > 0 ? `${dirty} uncommitted file(s), ${untracked} of them NEW and untracked — a diff cannot save those` : "",
merged ? "" : `tip ${tip.slice(0, 8)} is NOT in HEAD — its commits would vanish`,
].filter(Boolean).join(" · ");
out.push(`KEPT ${dir} — ${why}`);
}
}
return out;
}
/** THE BOARD — the one page the operator can glance at without asking anyone.
* Every line is DERIVED from repo state (git, worktrees, the ledgers), never
* from the orchestrator's narration, so it cannot be fluffed: a lane that has
* written nothing shows its silence, and a claim with no countersign shows as
* unproven. Written 2026-08-06 after the operator said: "if i dont keep a
* mental tally at all times of what is going on then it seems like there is 0
* way for you to be visible at all and held accountable." */
export function boardPage(): string {
const now = new Date();
const hhmm = `${String(now.getHours()).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}`;
const head = sh("git", ["rev-parse", "--short", "HEAD"]);
const load = sh("sysctl", ["-n", "vm.loadavg"], "/").replace(/[{}]/g, "").trim();
const stampPath = join(REPO, "apps/snappy-os/Sources/SnappyOS/Resources/web/build-stamp.txt");
const stamp = existsSync(stampPath) ? readFileSync(stampPath, "utf8").trim() : "none";
const lanes: string[] = [];
const wtRoot = join(REPO, ".claude/worktrees");
if (existsSync(wtRoot)) {
for (const dir of readdirSync(wtRoot)) {
const p = join(wtRoot, dir);
let newest = 0;
const walk = (d: string, depth = 0): void => {
if (depth > 4) return;
let entries: string[] = [];
try { entries = readdirSync(d); } catch { return; }
for (const e of entries) {
if (e === "node_modules" || e === ".git" || e.startsWith(".vite")) continue;
const full = join(d, e);
try {
const st = statSync(full);
if (st.isDirectory()) walk(full, depth + 1);
else if (st.mtimeMs > newest) newest = st.mtimeMs;
} catch { /* raced with a crew's own write */ }
}
};
walk(p);
const quietMin = newest === 0 ? Infinity : Math.round((Date.now() - newest) / 60_000);
const flag = quietMin > 30 ? " ← SILENT >30m, ping or kill" : "";
lanes.push(`| ${dir.replace(/^agent-/, "")} | ${quietMin === Infinity ? "never" : `${quietMin}m ago`} |${flag} |`);
}
}
const landed = sh("git", ["log", "--since=8 hours ago", "--format=%h %ad %s", "--date=format:%H:%M", "--no-merges"])
.split("\n").filter(Boolean).slice(0, 25);
const readRows = (file: string, keep: (l: string) => boolean): string[] => {
const p = join(REPO, file);
return existsSync(p) ? readFileSync(p, "utf8").split("\n").filter(keep) : [];
};
const blocked = readRows("BLOCKED.md", (l) => l.startsWith("- [") && !l.includes("~~"));
const unproven = readRows("research/app/USER-SEAT-RECON-2026-08-06-CLOSURE.md", (l) => l.includes("AWAITING COUNTERSIGN"))
.map((l) => l.split("|").slice(1, 4).join(" ·").trim());
const ticks = readRows("NIGHT-LOG.md", (l) => l.startsWith("- ")).slice(-5);
return [
`# THE BOARD — ${now.toISOString().slice(0, 10)} ${hhmm} local`,
"",
"*Every line below is derived from repo state, not from anyone's summary.*",
"",
`**tip** \`${head}\` · **installed stamp** \`${stamp}\` · **load** ${load}`,
"",
"## Lanes running now (silence is the stall signal)",
lanes.length ? "| lane | last wrote | |\n|---|---|---|\n" + lanes.join("\n") : "_none — the fleet is idle_",
"",
`## Landed in the last 8 hours (${landed.length} commits, newest first)`,
landed.length ? "```\n" + landed.join("\n") + "\n```" : "_nothing_",
"",
"## Claimed but NOT yet countersigned (the auditor owes these a re-drive)",
unproven.length ? unproven.map((u) => `- ${u}`).join("\n") : "_nothing outstanding_",
"",
"## Blocked — needs Robert, nobody else can move it",
blocked.length ? blocked.join("\n") : "_nothing_",
"",
"## Last five ticks",
ticks.length ? ticks.join("\n") : "_none_",
].join("\n");
}
/** Append one timestamped tick line to NIGHT-LOG.md. */
export function nightLog(line: string): string {
const entry = `- ${nowStamp()} local · ${line}\n`;
appendFileSync(join(REPO, "NIGHT-LOG.md"), entry);
return entry.trim();
}
/** Append a parked blocker to BLOCKED.md in the canonical one-line format. */
export function parkBlocked(id: string, failed: string, t1: string, t2: string, unblock: string): string {
const entry = `- [${id}] ${failed} | ${t1} | ${t2} | ${unblock}\n`;
appendFileSync(join(REPO, "BLOCKED.md"), entry);
return entry.trim();
}
/**
* THE FILE `bar` IS PINNED TO, DECLARED ⟨lane mini-reads, 2026-09-09⟩.
*
* `bar` derives every row from a document in a repo this hand does not own. A
* census that reads the contract can now see the dependency and check the
* file EXISTS before a picker chooses this verb as a default read — which is
* the whole reason it failed from the mini: the bar picked `bar`, the repo it
* ran in has no THE-WORLD-CLASS-BAR.md, and the owner's card showed a refusal.
*
* The sentence used to tell a reader to set `SNAPPY_NIGHTSHIFT_REPO`. THAT KEY
* DOES NOT EXIST — the code reads `SNAPPY_NIGHT_REPO`. A fix nobody can follow
* is worse than no fix, and it survived because the sentence was hand-written
* beside the code instead of derived from one declaration. It is one row now,
* and `hand-resources.census.test.ts` fails if `setBy` names a key this file
* does not read.
*/
export function barFile(): PinnedFile {
return pinnedFile({
id: "world-class-bar",
name: "THE-WORLD-CLASS-BAR.md",
path: join(REPO, "THE-WORLD-CLASS-BAR.md"),
why: "`bar` derives every row of the scoresheet from it",
setBy: "SNAPPY_NIGHT_REPO",
});
}
/** The sixteen checks as a fillable scoresheet, parsed from the bar file itself. */
export function barScoresheet(): string[] {
const pinned = barFile();
const barPath = pinned.path;
if (!existsSync(barPath)) {
// ENOENT reached the caller as node's fs stack trace. The named file is
// the whole answer: say which one, where it is looked for, and the key
// that moves it — read from the ONE declaration above, never restated.
throw fileRefusal(pinned);
}
const src = readFileSync(barPath, "utf8");
const checks = src.split("\n").filter((l) => /^\d+\. /.test(l.trim()));
return checks.map((c, i) => `[ ] ${i + 1} · ${c.trim().replace(/^\d+\.\s*/, "").slice(0, 110)}`);
}
/** Morning report skeleton: bar curve + commits + blocked, ready to fill. */
export function morningReport(sinceHours = 10): string {
const commits = sh("git", ["log", `--since=${sinceHours} hours ago`, "--format=%h %ad %s", "--date=format:%H:%M"]);
const n = commits.split("\n").filter(Boolean).length;
const blockedPath = join(REPO, "BLOCKED.md");
const open = existsSync(blockedPath)
? readFileSync(blockedPath, "utf8").split("\n").filter((l) => l.startsWith("- [") && !l.includes("~~")).join("\n")
: "(none)";
return [
`# MORNING REPORT — ${new Date().toISOString().slice(0, 10)}`,
"",
"## The bar, per window (fill from the drives — a curve, not a claim)",
"| window | fraction | kill switches | shot dir |",
"|---|---|---|---|",
"",
`## Commits overnight (${n})`,
commits || "(none)",
"",
"## Still blocked",
open,
"",
"## Regressions found",
"",
"## Founder-only decisions untouched",
].join("\n");
}
// --- CLI ---
const invokedDirectly = (() => {
try {
return process.argv[1] != null && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
} catch { return false; }
})();
/** WHAT THIS HAND ANSWERS, and what each verb does to the world.
* Derived from this file's own CLI dispatch by
* `snappy-hands/contract-derive.ts` — a verb the code does not implement is
* never declared here. Snappy's daemon reads it (`api.ts contract`) to
* validate every call, build the argument words in order, decide whether the
* act runs now or stages for the owner, and hand the child exactly the
* environment keys named in `requires` — never a value, never anything else.
*/
/** THE HOST-FACING FACTS ⟨lane CONTRACTS N–Z, 2026-09-09⟩. `class` is the
* closed effect set snappy-tool-design rule 18 grades; `annotations` are
* DERIVED from it by the ONE derivation in
* `snappy-settings/tool-annotations.ts`, never written per verb, so a class
* and its published hints cannot disagree; `refusals` projects the ONE closed
* table in `snappy-settings/refusal-codes.ts`; `requires` is exactly the
* credential keys this file's own executable reads name, and nothing else. */
export const HAND_CONTRACT = {
skill: "snappy-nightshift",
description: "The overnight orchestration operating system: one orchestrator drives a repo toward 100% all night with build crews in worktrees, batched install windows, cold-walker signatures, wake-up loops to a hard stop time, and the throughput discipline measured from the real 2026-08 runs (peak 33 commits/hour at 10-12 lanes). Use when Robert says: /snappy-nightshift, \\\"we need to do /snappy-nightshift relentless through the night\\\", \\\"push hard overnight to 10AM eastern\\\", \\\"keep going all night dont stop\\\", \\\"keep the cadence, keep the momentum high to 10AM eastern time\\\", \\\"make a prompt for the other ai to push hard overnight\\\", \\\"update your wake up loop to keep you on the highest momentum\\\", \\\"continue, launch the agents again, go back to the mission\\\", \\\"night run\\\". Triggers on: nightshift, night run, overnight, build crew, install window, wake-up loop, hard stop time. NOT the per-seat app dogfooding (see snappy-resident). NOT Mac-mini jcode lane dispatch (see snappy-jcode).",
managed: true,
requires: [] as string[],
/** WHAT THIS HAND NEEDS THAT IS NOT A CREDENTIAL ⟨lane mini-reads,
* 2026-09-09⟩. `bar` cannot answer in a repo without this document, and no
* amount of credentials changes that. `status`, `preflight` and `report`
* answer anywhere, which is why only this one is pinned. */
resources: { "world-class-bar": barFile() },
refusals: refusalTable("missing_argument", "not_found", "unknown_verb"),
verbs: {
bar: {
args: [], effect: "read", class: "read", execution: "call", openWorld: true,
annotations: annotationsForClass("read", { openWorld: true }),
},
blocked: {
args: ["lane-id","failed","tried-first","tried-second","unblock"], effect: "write-reversible", class: "additive-write", openWorld: true,
annotations: annotationsForClass("additive-write", { openWorld: true }),
inputSchema: { properties: { "lane-id": { type: "string", description: "Lane id the block is parked under" }, failed: { type: "string", description: "What failed, in one line" }, "tried-first": { type: "string", description: "The first thing already tried" }, "tried-second": { type: "string", description: "The second thing already tried" }, unblock: { type: "string", description: "What would unblock the lane" } } },
},
board: {
args: [], effect: "read", class: "read", execution: "call", openWorld: true,
annotations: annotationsForClass("read", { openWorld: true }),
},
log: {
args: [], effect: "read", class: "read", execution: "call", openWorld: true,
annotations: annotationsForClass("read", { openWorld: true }),
},
preflight: {
args: [], effect: "read", class: "read", execution: "call", openWorld: true,
annotations: annotationsForClass("read", { openWorld: true }),
},
reap: {
args: [], effect: "delete", class: "destructive", openWorld: true,
annotations: annotationsForClass("destructive", { openWorld: true }),
flags: {"apply":"--apply"},
},
report: {
args: [], effect: "read", class: "read", execution: "call", openWorld: true,
annotations: annotationsForClass("read", { openWorld: true }),
},
status: {
args: [], effect: "read", class: "read", execution: "call", openWorld: true,
annotations: annotationsForClass("read", { openWorld: true }),
},
},
} as const;
if (invokedDirectly && process.argv[2] === "contract") {
console.log(JSON.stringify(HAND_CONTRACT, null, 2));
process.exit(0);
}
if (invokedDirectly) {
(async () => {
const [verb, ...rest] = process.argv.slice(2);
const out = (v: unknown) => console.log(typeof v === "string" ? v : JSON.stringify(v, null, 2));
switch (verb) {
case "status": out(await nightStatus()); break;
case "preflight": {
const p = await nightPreflight();
p.lines.forEach((l) => console.log(l));
console.log(p.go ? "GO" : "NO-GO");
process.exitCode = p.go ? 0 : 1;
break;
}
case "log": out(nightLog(rest.join(" "))); break;
case "blocked": {
const [id, failed, t1, t2, unblock] = rest;
out(parkBlocked(id ?? "?", failed ?? "?", t1 ?? "?", t2 ?? "?", unblock ?? "?"));
break;
}
case "bar": barScoresheet().forEach((l) => console.log(l)); break;
case "reap": reapWorktrees(rest[0] === "--apply").forEach((l) => console.log(l)); break;
case "board": {
const page = boardPage();
writeFileSync(join(REPO, "THE-BOARD.md"), `${page}\n`);
console.log(page);
break;
}
case "report": out(morningReport(rest[0] ? Number(rest[0]) : undefined)); break;
default:
console.log("snappy-nightshift — verbs: status | preflight | log <line> | blocked <id> <failed> <t1> <t2> <unblock> | bar | report [hours]");
}
})().catch((error) => {
if (isRefusedError(error)) { printRefusal(error.refusal); console.error(error.message); return; }
console.error(error instanceof Error ? error.message : String(error));
process.exitCode = 1;
});
}
// snappy-nightshift — typed programmatic interface.
// Deterministic handles for the overnight orchestrator: preflight, status,
// tick logging, blocked ledger, bar scoresheet, morning report skeleton.
// No credentials needed; pure local fs + git + http probes.
import { execFileSync } from "node:child_process";
import { existsSync, readFileSync, appendFileSync, realpathSync, readdirSync, statSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { annotationsForClass } from "../snappy-settings/tool-annotations.ts";
import { RefusedError, isRefusedError, printRefusal, refusalTable } from "../snappy-settings/refusal-codes.ts";
import { fileRefusal, pinnedFile, serviceUrl, type PinnedFile } from "../snappy-settings/hand-resources.ts";
// env() unused today (no credentialed verbs) — imported per spec so the first
// credentialed verb uses the one loader instead of inventing a second road.
import { env as _env } from "../snappy-settings/load.ts";
const REPO = process.env.SNAPPY_NIGHT_REPO ?? "/Users/robertboulos/Projects/snappy-os-app";
// THE ADDRESS COMES FROM THE ONE REGISTRY ⟨lane mini-reads, 2026-09-09⟩.
// `status` reports the daemon's health; holding the address here made this the
// fifth hand with its own copy, and a moved daemon would have been reported
// DOWN by a probe of the wrong place.
const DAEMON = serviceUrl("snappy-os-app");
function sh(cmd: string, args: string[], cwd = REPO): string {
try {
return execFileSync(cmd, args, { cwd, encoding: "utf8", timeout: 20_000 }).trim();
} catch (e: any) {
return `ERR ${e?.status ?? ""} ${String(e?.stderr ?? e?.message ?? "").slice(0, 200)}`.trim();
}
}
function nowStamp(): string {
const d = new Date();
const p = (n: number) => String(n).padStart(2, "0");
return `${p(d.getHours())}:${p(d.getMinutes())}`;
}
export interface NightStatus {
head: string;
branch: string;
aheadBehind: string;
dirtyFiles: number;
loadAvg: string;
agentWorktrees: number;
daemonHealthy: boolean;
installStamp: string | null;
lastLogLine: string | null;
blockedOpen: number;
}
export async function nightStatus(): Promise<NightStatus> {
const head = sh("git", ["rev-parse", "--short", "HEAD"]);
const branch = sh("git", ["rev-parse", "--abbrev-ref", "HEAD"]);
const aheadBehind = sh("git", ["status", "-sb"]).split("\n")[0] ?? "";
const dirtyFiles = sh("git", ["status", "--porcelain"]).split("\n").filter(Boolean).length;
const loadAvg = sh("sysctl", ["-n", "vm.loadavg"], "/");
const agentWorktrees = sh("git", ["worktree", "list"]).split("\n").filter((l) => l.includes(".claude/worktrees/")).length;
let daemonHealthy = false;
try {
const r = await fetch(`${DAEMON}/healthz`, { signal: AbortSignal.timeout(3000) });
daemonHealthy = r.ok;
} catch { /* daemon down is a finding, not a crash */ }
const stampPath = join(REPO, "apps/snappy-os/Sources/SnappyOS/Resources/web/build-stamp.txt");
const installStamp = existsSync(stampPath) ? readFileSync(stampPath, "utf8").trim().slice(0, 80) : null;
const nightLog = join(REPO, "NIGHT-LOG.md");
const lastLogLine = existsSync(nightLog)
? readFileSync(nightLog, "utf8").trim().split("\n").at(-1)?.slice(0, 200) ?? null
: null;
const blockedPath = join(REPO, "BLOCKED.md");
const blockedOpen = existsSync(blockedPath)
? readFileSync(blockedPath, "utf8").split("\n").filter((l) => l.startsWith("- [") && !l.startsWith("- ~~")).length
: 0;
return { head, branch, aheadBehind, dirtyFiles, loadAvg, agentWorktrees, daemonHealthy, installStamp, lastLogLine, blockedOpen };
}
export interface ResolutionSplit { pkg: string; a: string; b: string }
/** Packages reachable at TWO versions from two node_modules roots.
* Measured 2026-08-06: 16 of 16 shared packages disagreed — INCLUDING
* typescript (6.0.3 vs 5.9.3) and ajv (8 vs 6). That is why no typecheck
* ever caught it: the checker is one of the duplicated packages, so the
* instrument cannot audit itself. Nothing may prove a tree green until
* this reads zero-or-justified. */
export function resolutionSplits(roots = ["node_modules", "apps/snappy-os/web/node_modules"]): ResolutionSplit[] {
const read = (root: string): Map<string, string> => {
const out = new Map<string, string>();
const dir = join(REPO, root);
if (!existsSync(dir)) return out;
const version = (p: string): string | null => {
try { return JSON.parse(readFileSync(join(p, "package.json"), "utf8")).version ?? null; } catch { return null; }
};
for (const entry of readdirSync(dir)) {
if (entry.startsWith(".")) continue;
if (entry.startsWith("@")) {
for (const scoped of readdirSync(join(dir, entry))) {
const v = version(join(dir, entry, scoped));
if (v) out.set(`${entry}/${scoped}`, v);
}
} else {
const v = version(join(dir, entry));
if (v) out.set(entry, v);
}
}
return out;
};
const [a, b] = [read(roots[0] ?? ""), read(roots[1] ?? "")];
const splits: ResolutionSplit[] = [];
for (const [pkg, va] of a) {
const vb = b.get(pkg);
if (vb && vb !== va) splits.push({ pkg, a: va, b: vb });
}
return splits.sort((x, y) => x.pkg.localeCompare(y.pkg));
}
export interface PreflightVerdict { go: boolean; lines: string[] }
/** The launch checklist. Every line is a named check with its verdict. */
export async function nightPreflight(): Promise<PreflightVerdict> {
const lines: string[] = [];
let go = true;
const s = await nightStatus();
const stale = sh("git", ["worktree", "list"]).split("\n").filter((l) => l.includes("prunable")).length;
lines.push(stale === 0 ? "OK worktree registrations clean" : `FIX ${stale} prunable worktree registrations — run: git worktree prune (stale ones silently kill check-head)`);
if (stale > 0) go = false;
lines.push(s.daemonHealthy ? "OK daemon :3147 healthy" : "FIX daemon :3147 not answering — pkill -f 'head-screen/server.mjs', wait ~10s for respawn");
if (!s.daemonHealthy) go = false;
const port3149 = sh("lsof", ["-ti", ":3149"], "/");
lines.push(!port3149 || port3149.startsWith("ERR") ? "OK port 3149 free (install proof port)" : `FIX port 3149 held by pid ${port3149} — installs will refuse to swap AND exit 0`);
if (port3149 && !port3149.startsWith("ERR")) go = false;
const briefing = join(REPO, "RUN-BRIEFING.md");
if (!existsSync(briefing)) {
lines.push("FIX no RUN-BRIEFING.md — crews will start contextless; write it before launching (brief part zero)");
go = false;
} else {
const ageHours = (Date.now() - statSync(briefing).mtimeMs) / 3_600_000;
if (ageHours > 6) {
lines.push(`FIX RUN-BRIEFING.md is ${ageHours.toFixed(1)}h stale — regenerate it; a briefing nobody trusts is worse than none`);
go = false;
} else {
lines.push(`OK RUN-BRIEFING.md is ${ageHours.toFixed(1)}h old`);
}
}
const splits = resolutionSplits();
const toolSplit = splits.filter((s2) => ["typescript", "ajv", "eslint", "vitest"].includes(s2.pkg));
if (splits.length === 0) {
lines.push("OK one resolved version per shared package");
} else {
lines.push(`FIX ${splits.length} package(s) resolve to TWO versions — a worktree silently gets the wrong one:`);
for (const s2 of splits.slice(0, 20)) lines.push(` ${s2.pkg}: ${s2.a} vs ${s2.b}`);
if (toolSplit.length > 0) {
lines.push(` ^^ ${toolSplit.map((t) => t.pkg).join(", ")} is a PROOF INSTRUMENT — every "green" from a worktree is suspect until this is resolved`);
go = false;
}
}
const load1 = parseFloat(s.loadAvg.replace(/[{}]/g, "").trim().split(/\s+/)[0] ?? "0");
lines.push(load1 < 8 ? `OK load ${load1} (8 cores)` : `WARN load ${load1} on 8 cores — halve the crew fleet before launching more`);
lines.push(`INFO ${s.aheadBehind}`);
lines.push(`INFO ${s.dirtyFiles} dirty files (never git add -A; commit --only with explicit paths)`);
lines.push(`INFO ${s.agentWorktrees} live agent worktrees — integrate or kill before launching overlapping lanes`);
lines.push(`INFO install stamp: ${s.installStamp ?? "none"}`);
return { go, lines };
}
/** THE ONLY WAY A WORKTREE MAY BE REMOVED. Refuses any lane holding uncommitted
* work or commits not in HEAD, and says which. Written 2026-08-06 because the
* orchestrator hand-removed a worktree whose crew had reported complete and
* never been merged — `git diff` saved its 12 MODIFIED files and silently lost
* the 7 it had CREATED, because untracked files are not in a diff and git
* never hashed them. The dirty count was on screen at the moment of removal.
* A number you have to remember to read is not a guard. */
export function reapWorktrees(apply = false): string[] {
const out: string[] = [];
const root = join(REPO, ".claude/worktrees");
if (!existsSync(root)) return ["no worktrees"];
for (const dir of readdirSync(root)) {
const wt = join(root, dir);
if (!existsSync(join(wt, ".git"))) continue;
const dirty = sh("git", ["-C", wt, "status", "--porcelain"]).split("\n").filter(Boolean).length;
const tip = sh("git", ["-C", wt, "rev-parse", "HEAD"]);
const merged = sh("git", ["merge-base", "--is-ancestor", tip, "HEAD"]) === "";
const untracked = sh("git", ["-C", wt, "ls-files", "--others", "--exclude-standard"]).split("\n").filter(Boolean).length;
if (dirty === 0 && merged) {
if (apply) { sh("git", ["worktree", "remove", "-f", wt]); out.push(`REAPED ${dir} (clean, merged)`); }
else out.push(`WOULD REAP ${dir} (clean, merged)`);
} else {
const why = [
dirty > 0 ? `${dirty} uncommitted file(s), ${untracked} of them NEW and untracked — a diff cannot save those` : "",
merged ? "" : `tip ${tip.slice(0, 8)} is NOT in HEAD — its commits would vanish`,
].filter(Boolean).join(" · ");
out.push(`KEPT ${dir} — ${why}`);
}
}
return out;
}
/** THE BOARD — the one page the operator can glance at without asking anyone.
* Every line is DERIVED from repo state (git, worktrees, the ledgers), never
* from the orchestrator's narration, so it cannot be fluffed: a lane that has
* written nothing shows its silence, and a claim with no countersign shows as
* unproven. Written 2026-08-06 after the operator said: "if i dont keep a
* mental tally at all times of what is going on then it seems like there is 0
* way for you to be visible at all and held accountable." */
export function boardPage(): string {
const now = new Date();
const hhmm = `${String(now.getHours()).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}`;
const head = sh("git", ["rev-parse", "--short", "HEAD"]);
const load = sh("sysctl", ["-n", "vm.loadavg"], "/").replace(/[{}]/g, "").trim();
const stampPath = join(REPO, "apps/snappy-os/Sources/SnappyOS/Resources/web/build-stamp.txt");
const stamp = existsSync(stampPath) ? readFileSync(stampPath, "utf8").trim() : "none";
const lanes: string[] = [];
const wtRoot = join(REPO, ".claude/worktrees");
if (existsSync(wtRoot)) {
for (const dir of readdirSync(wtRoot)) {
const p = join(wtRoot, dir);
let newest = 0;
const walk = (d: string, depth = 0): void => {
if (depth > 4) return;
let entries: string[] = [];
try { entries = readdirSync(d); } catch { return; }
for (const e of entries) {
if (e === "node_modules" || e === ".git" || e.startsWith(".vite")) continue;
const full = join(d, e);
try {
const st = statSync(full);
if (st.isDirectory()) walk(full, depth + 1);
else if (st.mtimeMs > newest) newest = st.mtimeMs;
} catch { /* raced with a crew's own write */ }
}
};
walk(p);
const quietMin = newest === 0 ? Infinity : Math.round((Date.now() - newest) / 60_000);
const flag = quietMin > 30 ? " ← SILENT >30m, ping or kill" : "";
lanes.push(`| ${dir.replace(/^agent-/, "")} | ${quietMin === Infinity ? "never" : `${quietMin}m ago`} |${flag} |`);
}
}
const landed = sh("git", ["log", "--since=8 hours ago", "--format=%h %ad %s", "--date=format:%H:%M", "--no-merges"])
.split("\n").filter(Boolean).slice(0, 25);
const readRows = (file: string, keep: (l: string) => boolean): string[] => {
const p = join(REPO, file);
return existsSync(p) ? readFileSync(p, "utf8").split("\n").filter(keep) : [];
};
const blocked = readRows("BLOCKED.md", (l) => l.startsWith("- [") && !l.includes("~~"));
const unproven = readRows("research/app/USER-SEAT-RECON-2026-08-06-CLOSURE.md", (l) => l.includes("AWAITING COUNTERSIGN"))
.map((l) => l.split("|").slice(1, 4).join(" ·").trim());
const ticks = readRows("NIGHT-LOG.md", (l) => l.startsWith("- ")).slice(-5);
return [
`# THE BOARD — ${now.toISOString().slice(0, 10)} ${hhmm} local`,
"",
"*Every line below is derived from repo state, not from anyone's summary.*",
"",
`**tip** \`${head}\` · **installed stamp** \`${stamp}\` · **load** ${load}`,
"",
"## Lanes running now (silence is the stall signal)",
lanes.length ? "| lane | last wrote | |\n|---|---|---|\n" + lanes.join("\n") : "_none — the fleet is idle_",
"",
`## Landed in the last 8 hours (${landed.length} commits, newest first)`,
landed.length ? "```\n" + landed.join("\n") + "\n```" : "_nothing_",
"",
"## Claimed but NOT yet countersigned (the auditor owes these a re-drive)",
unproven.length ? unproven.map((u) => `- ${u}`).join("\n") : "_nothing outstanding_",
"",
"## Blocked — needs Robert, nobody else can move it",
blocked.length ? blocked.join("\n") : "_nothing_",
"",
"## Last five ticks",
ticks.length ? ticks.join("\n") : "_none_",
].join("\n");
}
/** Append one timestamped tick line to NIGHT-LOG.md. */
export function nightLog(line: string): string {
const entry = `- ${nowStamp()} local · ${line}\n`;
appendFileSync(join(REPO, "NIGHT-LOG.md"), entry);
return entry.trim();
}
/** Append a parked blocker to BLOCKED.md in the canonical one-line format. */
export function parkBlocked(id: string, failed: string, t1: string, t2: string, unblock: string): string {
const entry = `- [${id}] ${failed} | ${t1} | ${t2} | ${unblock}\n`;
appendFileSync(join(REPO, "BLOCKED.md"), entry);
return entry.trim();
}
/**
* THE FILE `bar` IS PINNED TO, DECLARED ⟨lane mini-reads, 2026-09-09⟩.
*
* `bar` derives every row from a document in a repo this hand does not own. A
* census that reads the contract can now see the dependency and check the
* file EXISTS before a picker chooses this verb as a default read — which is
* the whole reason it failed from the mini: the bar picked `bar`, the repo it
* ran in has no THE-WORLD-CLASS-BAR.md, and the owner's card showed a refusal.
*
* The sentence used to tell a reader to set `SNAPPY_NIGHTSHIFT_REPO`. THAT KEY
* DOES NOT EXIST — the code reads `SNAPPY_NIGHT_REPO`. A fix nobody can follow
* is worse than no fix, and it survived because the sentence was hand-written
* beside the code instead of derived from one declaration. It is one row now,
* and `hand-resources.census.test.ts` fails if `setBy` names a key this file
* does not read.
*/
export function barFile(): PinnedFile {
return pinnedFile({
id: "world-class-bar",
name: "THE-WORLD-CLASS-BAR.md",
path: join(REPO, "THE-WORLD-CLASS-BAR.md"),
why: "`bar` derives every row of the scoresheet from it",
setBy: "SNAPPY_NIGHT_REPO",
});
}
/** The sixteen checks as a fillable scoresheet, parsed from the bar file itself. */
export function barScoresheet(): string[] {
const pinned = barFile();
const barPath = pinned.path;
if (!existsSync(barPath)) {
// ENOENT reached the caller as node's fs stack trace. The named file is
// the whole answer: say which one, where it is looked for, and the key
// that moves it — read from the ONE declaration above, never restated.
throw fileRefusal(pinned);
}
const src = readFileSync(barPath, "utf8");
const checks = src.split("\n").filter((l) => /^\d+\. /.test(l.trim()));
return checks.map((c, i) => `[ ] ${i + 1} · ${c.trim().replace(/^\d+\.\s*/, "").slice(0, 110)}`);
}
/** Morning report skeleton: bar curve + commits + blocked, ready to fill. */
export function morningReport(sinceHours = 10): string {
const commits = sh("git", ["log", `--since=${sinceHours} hours ago`, "--format=%h %ad %s", "--date=format:%H:%M"]);
const n = commits.split("\n").filter(Boolean).length;
const blockedPath = join(REPO, "BLOCKED.md");
const open = existsSync(blockedPath)
? readFileSync(blockedPath, "utf8").split("\n").filter((l) => l.startsWith("- [") && !l.includes("~~")).join("\n")
: "(none)";
return [
`# MORNING REPORT — ${new Date().toISOString().slice(0, 10)}`,
"",
"## The bar, per window (fill from the drives — a curve, not a claim)",
"| window | fraction | kill switches | shot dir |",
"|---|---|---|---|",
"",
`## Commits overnight (${n})`,
commits || "(none)",
"",
"## Still blocked",
open,
"",
"## Regressions found",
"",
"## Founder-only decisions untouched",
].join("\n");
}
// --- CLI ---
const invokedDirectly = (() => {
try {
return process.argv[1] != null && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
} catch { return false; }
})();
/** WHAT THIS HAND ANSWERS, and what each verb does to the world.
* Derived from this file's own CLI dispatch by
* `snappy-hands/contract-derive.ts` — a verb the code does not implement is
* never declared here. Snappy's daemon reads it (`api.ts contract`) to
* validate every call, build the argument words in order, decide whether the
* act runs now or stages for the owner, and hand the child exactly the
* environment keys named in `requires` — never a value, never anything else.
*/
/** THE HOST-FACING FACTS ⟨lane CONTRACTS N–Z, 2026-09-09⟩. `class` is the
* closed effect set snappy-tool-design rule 18 grades; `annotations` are
* DERIVED from it by the ONE derivation in
* `snappy-settings/tool-annotations.ts`, never written per verb, so a class
* and its published hints cannot disagree; `refusals` projects the ONE closed
* table in `snappy-settings/refusal-codes.ts`; `requires` is exactly the
* credential keys this file's own executable reads name, and nothing else. */
export const HAND_CONTRACT = {
skill: "snappy-nightshift",
description: "The overnight orchestration operating system: one orchestrator drives a repo toward 100% all night with build crews in worktrees, batched install windows, cold-walker signatures, wake-up loops to a hard stop time, and the throughput discipline measured from the real 2026-08 runs (peak 33 commits/hour at 10-12 lanes). Use when Robert says: /snappy-nightshift, \\\"we need to do /snappy-nightshift relentless through the night\\\", \\\"push hard overnight to 10AM eastern\\\", \\\"keep going all night dont stop\\\", \\\"keep the cadence, keep the momentum high to 10AM eastern time\\\", \\\"make a prompt for the other ai to push hard overnight\\\", \\\"update your wake up loop to keep you on the highest momentum\\\", \\\"continue, launch the agents again, go back to the mission\\\", \\\"night run\\\". Triggers on: nightshift, night run, overnight, build crew, install window, wake-up loop, hard stop time. NOT the per-seat app dogfooding (see snappy-resident). NOT Mac-mini jcode lane dispatch (see snappy-jcode).",
managed: true,
requires: [] as string[],
/** WHAT THIS HAND NEEDS THAT IS NOT A CREDENTIAL ⟨lane mini-reads,
* 2026-09-09⟩. `bar` cannot answer in a repo without this document, and no
* amount of credentials changes that. `status`, `preflight` and `report`
* answer anywhere, which is why only this one is pinned. */
resources: { "world-class-bar": barFile() },
refusals: refusalTable("missing_argument", "not_found", "unknown_verb"),
verbs: {
bar: {
args: [], effect: "read", class: "read", execution: "call", openWorld: true,
annotations: annotationsForClass("read", { openWorld: true }),
},
blocked: {
args: ["lane-id","failed","tried-first","tried-second","unblock"], effect: "write-reversible", class: "additive-write", openWorld: true,
annotations: annotationsForClass("additive-write", { openWorld: true }),
inputSchema: { properties: { "lane-id": { type: "string", description: "Lane id the block is parked under" }, failed: { type: "string", description: "What failed, in one line" }, "tried-first": { type: "string", description: "The first thing already tried" }, "tried-second": { type: "string", description: "The second thing already tried" }, unblock: { type: "string", description: "What would unblock the lane" } } },
},
board: {
args: [], effect: "read", class: "read", execution: "call", openWorld: true,
annotations: annotationsForClass("read", { openWorld: true }),
},
log: {
args: [], effect: "read", class: "read", execution: "call", openWorld: true,
annotations: annotationsForClass("read", { openWorld: true }),
},
preflight: {
args: [], effect: "read", class: "read", execution: "call", openWorld: true,
annotations: annotationsForClass("read", { openWorld: true }),
},
reap: {
args: [], effect: "delete", class: "destructive", openWorld: true,
annotations: annotationsForClass("destructive", { openWorld: true }),
flags: {"apply":"--apply"},
},
report: {
args: [], effect: "read", class: "read", execution: "call", openWorld: true,
annotations: annotationsForClass("read", { openWorld: true }),
},
status: {
args: [], effect: "read", class: "read", execution: "call", openWorld: true,
annotations: annotationsForClass("read", { openWorld: true }),
},
},
} as const;
if (invokedDirectly && process.argv[2] === "contract") {
console.log(JSON.stringify(HAND_CONTRACT, null, 2));
process.exit(0);
}
if (invokedDirectly) {
(async () => {
const [verb, ...rest] = process.argv.slice(2);
const out = (v: unknown) => console.log(typeof v === "string" ? v : JSON.stringify(v, null, 2));
switch (verb) {
case "status": out(await nightStatus()); break;
case "preflight": {
const p = await nightPreflight();
p.lines.forEach((l) => console.log(l));
console.log(p.go ? "GO" : "NO-GO");
process.exitCode = p.go ? 0 : 1;
break;
}
case "log": out(nightLog(rest.join(" "))); break;
case "blocked": {
const [id, failed, t1, t2, unblock] = rest;
out(parkBlocked(id ?? "?", failed ?? "?", t1 ?? "?", t2 ?? "?", unblock ?? "?"));
break;
}
case "bar": barScoresheet().forEach((l) => console.log(l)); break;
case "reap": reapWorktrees(rest[0] === "--apply").forEach((l) => console.log(l)); break;
case "board": {
const page = boardPage();
writeFileSync(join(REPO, "THE-BOARD.md"), `${page}\n`);
console.log(page);
break;
}
case "report": out(morningReport(rest[0] ? Number(rest[0]) : undefined)); break;
default:
console.log("snappy-nightshift — verbs: status | preflight | log <line> | blocked <id> <failed> <t1> <t2> <unblock> | bar | report [hours]");
}
})().catch((error) => {
if (isRefusedError(error)) { printRefusal(error.refusal); console.error(error.message); return; }
console.error(error instanceof Error ? error.message : String(error));
process.exitCode = 1;
});
}
refusals.test.ts
/**
* COVERAGE FOR SNAPPY-NIGHTSHIFT'S DECLARED REFUSAL CODES
* (snappy-tool-design rule 33: "refusal codes form one closed table and each
* row has coverage").
*
* Two things are graded here, and the second is the one that matters. The
* first is that the hand's table is a PROJECTION of the collection's one
* closed table in snappy-settings/refusal-codes.ts — same object, not a copy
* that can drift. The second is that every declared code is GROUNDED: the
* evidence that justified declaring it is re-checked here, because a refusal
* code with no path that emits it is a branch the reader waits for and never
* sees, and a table of those passes a lint while teaching a lie.
*
* The code list is spelled out rather than read from the contract: a test that
* iterates the thing it grades passes for an empty table.
*/
import { strict as assert } from "node:assert";
import { test } from "node:test";
import { readFileSync } from "node:fs";
import { join, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { HAND_CONTRACT } from "./api.ts";
import { REFUSAL_CODES } from "../snappy-settings/refusal-codes.ts";
const SOURCE = readFileSync(join(dirname(fileURLToPath(import.meta.url)), "api.ts"), "utf8");
/** Every refusal code snappy-nightshift declares. */
const DECLARED = [
"missing_argument",
// ⟨lane mini-reads, 2026-09-09⟩ `bar` threw this whenever the repo it ran in
// had no THE-WORLD-CLASS-BAR.md — the exact way it failed from the mini —
// and the table never named it.
"not_found",
"unknown_verb",
] as const;
test("snappy-nightshift declares exactly these refusal codes", () => {
assert.deepEqual(Object.keys(HAND_CONTRACT.refusals).sort(), [...DECLARED].sort());
});
test("every declared code is the SAME row as the one closed table's, never a copy", () => {
const table = HAND_CONTRACT.refusals as Record<string, unknown>;
for (const code of DECLARED) {
assert.equal(table[code], REFUSAL_CODES[code], `${code} is not the shared row`);
}
});
test("missing_argument is grounded: at least one verb has a required word", () => {
const required = Object.values(HAND_CONTRACT.verbs as Record<string, { args?: readonly string[] }>)
.flatMap((v) => (v.args ?? []).filter((a) => !a.endsWith("?")));
assert.ok(required.length > 0, "no verb has a required argument, so missing_argument can never fire");
});
test("unknown_verb is grounded: the contract closes the verb set, so a word outside it is refusable", () => {
assert.ok(Object.keys(HAND_CONTRACT.verbs).length >= 0);
assert.ok(!Object.keys(HAND_CONTRACT.verbs).includes("no-such-verb"));
});
/**
* A HAND PINNED TO A FILE NAMES IT ⟨lane mini-reads, 2026-09-09⟩.
*
* RED BEFORE: `bar` refused with "…or set SNAPPY_NIGHTSHIFT_REPO". That key
* does not exist — this file reads `SNAPPY_NIGHT_REPO` — so the one action the
* refusal offered could not be taken. The sentence was hand-written beside the
* code; it is derived from the one declaration now, and
* `snappy-settings/hand-resources.test.ts` fails collection-wide if a `setBy`
* ever names a key its own api.ts does not read.
*/
test("snappy-nightshift: bar declares the file it is pinned to", async () => {
const { barFile } = await import("./api.ts");
const resources = (HAND_CONTRACT as { resources?: Record<string, unknown> }).resources ?? {};
assert.deepEqual(Object.keys(resources), ["world-class-bar"]);
const file = barFile();
assert.equal(file.kind, "file");
assert.equal(file.name, "THE-WORLD-CLASS-BAR.md");
assert.equal(file.setBy, "SNAPPY_NIGHT_REPO");
});
test("snappy-nightshift: bar's refusal names a key this file actually reads", async () => {
const { barFile } = await import("./api.ts");
const { fileRefusal } = await import("../snappy-settings/hand-resources.ts");
const message = fileRefusal(barFile()).refusal.message;
assert.ok(message.includes("SNAPPY_NIGHT_REPO"), message);
assert.ok(!message.includes("SNAPPY_NIGHTSHIFT_REPO"), `the refusal names a key that does not exist: ${message}`);
assert.ok(SOURCE.includes("process.env.SNAPPY_NIGHT_REPO"), "the key the refusal names is not read by this file");
});
/**
* COVERAGE FOR SNAPPY-NIGHTSHIFT'S DECLARED REFUSAL CODES
* (snappy-tool-design rule 33: "refusal codes form one closed table and each
* row has coverage").
*
* Two things are graded here, and the second is the one that matters. The
* first is that the hand's table is a PROJECTION of the collection's one
* closed table in snappy-settings/refusal-codes.ts — same object, not a copy
* that can drift. The second is that every declared code is GROUNDED: the
* evidence that justified declaring it is re-checked here, because a refusal
* code with no path that emits it is a branch the reader waits for and never
* sees, and a table of those passes a lint while teaching a lie.
*
* The code list is spelled out rather than read from the contract: a test that
* iterates the thing it grades passes for an empty table.
*/
import { strict as assert } from "node:assert";
import { test } from "node:test";
import { readFileSync } from "node:fs";
import { join, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { HAND_CONTRACT } from "./api.ts";
import { REFUSAL_CODES } from "../snappy-settings/refusal-codes.ts";
const SOURCE = readFileSync(join(dirname(fileURLToPath(import.meta.url)), "api.ts"), "utf8");
/** Every refusal code snappy-nightshift declares. */
const DECLARED = [
"missing_argument",
// ⟨lane mini-reads, 2026-09-09⟩ `bar` threw this whenever the repo it ran in
// had no THE-WORLD-CLASS-BAR.md — the exact way it failed from the mini —
// and the table never named it.
"not_found",
"unknown_verb",
] as const;
test("snappy-nightshift declares exactly these refusal codes", () => {
assert.deepEqual(Object.keys(HAND_CONTRACT.refusals).sort(), [...DECLARED].sort());
});
test("every declared code is the SAME row as the one closed table's, never a copy", () => {
const table = HAND_CONTRACT.refusals as Record<string, unknown>;
for (const code of DECLARED) {
assert.equal(table[code], REFUSAL_CODES[code], `${code} is not the shared row`);
}
});
test("missing_argument is grounded: at least one verb has a required word", () => {
const required = Object.values(HAND_CONTRACT.verbs as Record<string, { args?: readonly string[] }>)
.flatMap((v) => (v.args ?? []).filter((a) => !a.endsWith("?")));
assert.ok(required.length > 0, "no verb has a required argument, so missing_argument can never fire");
});
test("unknown_verb is grounded: the contract closes the verb set, so a word outside it is refusable", () => {
assert.ok(Object.keys(HAND_CONTRACT.verbs).length >= 0);
assert.ok(!Object.keys(HAND_CONTRACT.verbs).includes("no-such-verb"));
});
/**
* A HAND PINNED TO A FILE NAMES IT ⟨lane mini-reads, 2026-09-09⟩.
*
* RED BEFORE: `bar` refused with "…or set SNAPPY_NIGHTSHIFT_REPO". That key
* does not exist — this file reads `SNAPPY_NIGHT_REPO` — so the one action the
* refusal offered could not be taken. The sentence was hand-written beside the
* code; it is derived from the one declaration now, and
* `snappy-settings/hand-resources.test.ts` fails collection-wide if a `setBy`
* ever names a key its own api.ts does not read.
*/
test("snappy-nightshift: bar declares the file it is pinned to", async () => {
const { barFile } = await import("./api.ts");
const resources = (HAND_CONTRACT as { resources?: Record<string, unknown> }).resources ?? {};
assert.deepEqual(Object.keys(resources), ["world-class-bar"]);
const file = barFile();
assert.equal(file.kind, "file");
assert.equal(file.name, "THE-WORLD-CLASS-BAR.md");
assert.equal(file.setBy, "SNAPPY_NIGHT_REPO");
});
test("snappy-nightshift: bar's refusal names a key this file actually reads", async () => {
const { barFile } = await import("./api.ts");
const { fileRefusal } = await import("../snappy-settings/hand-resources.ts");
const message = fileRefusal(barFile()).refusal.message;
assert.ok(message.includes("SNAPPY_NIGHT_REPO"), message);
assert.ok(!message.includes("SNAPPY_NIGHTSHIFT_REPO"), `the refusal names a key that does not exist: ${message}`);
assert.ok(SOURCE.includes("process.env.SNAPPY_NIGHT_REPO"), "the key the refusal names is not read by this file");
});