aboutsummaryrefslogtreecommitdiff
path: root/.ai
diff options
context:
space:
mode:
Diffstat (limited to '.ai')
-rw-r--r--.ai/notes.org4
-rw-r--r--.ai/protocols.org29
-rw-r--r--.ai/references/calendar-reference.org66
-rwxr-xr-x.ai/scripts/sync-templates131
-rw-r--r--.ai/scripts/tests/sync-templates.bats319
-rw-r--r--.ai/scripts/tests/test-todo-cleanup.el2
-rw-r--r--.ai/scripts/todo-cleanup.el2
-rw-r--r--.ai/sessions/2026-07-25-15-34-clean-wrap-and-inbox-safe-sync.org85
-rw-r--r--.ai/sessions/2026-07-27-17-02-context-engineering-rightsizing.org176
-rw-r--r--.ai/sessions/2026-07-29-06-36-adversarial-review-flow-and-telegram-fixes.org514
-rw-r--r--.ai/sessions/2026-07-29-14-29-helper-1055-launch-pilot-idle.org62
-rw-r--r--.ai/sessions/2026-07-31-06-32-helper-agents-mcp-scoping-and-sync-extraction.org656
-rw-r--r--.ai/sessions/2026-07-31-22-43-sync-guard-narrowing-and-standup-scripts.org142
-rw-r--r--.ai/workflows/code-quality.org2
-rw-r--r--.ai/workflows/daily-prep.org32
-rw-r--r--.ai/workflows/helper-mode.org29
-rw-r--r--.ai/workflows/inbox.org2
-rw-r--r--.ai/workflows/no-approvals.org8
-rw-r--r--.ai/workflows/sentry.org68
-rw-r--r--.ai/workflows/startup.org74
-rw-r--r--.ai/workflows/triage-intake.telegram.org141
-rw-r--r--.ai/workflows/work-the-backlog.org5
-rw-r--r--.ai/workflows/wrap-it-up.org94
23 files changed, 2434 insertions, 209 deletions
diff --git a/.ai/notes.org b/.ai/notes.org
index d53f8e0..b6c85f8 100644
--- a/.ai/notes.org
+++ b/.ai/notes.org
@@ -61,6 +61,8 @@ This section tracks decisions that need Craig's input before work can proceed.
** Current Reminders
+- =[2026-07-27]= Finish the context-engineering rightsizing — Craig's explicit ask at wrap. Surface is 57,800 → 28,949 tokens; the remaining work needs *his decisions*, not execution: =verification.md= (C1 — its honesty core vs the Opus 5 over-verification warning), =interaction.md= (3,828 tok, largest remaining), the TDD rationalization table (cut or keep), and D3 the gate separation (which approval gates are preference vs guardrail). Task: "Finish context-engineering rightsizing" in todo.org. Docs in =working/context-engineering-rightsizing/= are one commit behind — reconcile them first.
+
- =[2026-07-14]= Review the sentry spec (docs/specs/2026-07-14-sentry-workflow-spec.org) — Craig's explicit ask at wrap: strongly suggest he reviews it before ending the next session. All 12 review findings and 10 decisions are resolved and folded in; the spec is open in his Emacs; the READY flip and the [#B] build task both wait on his deep read.
** Instructions for This Section
@@ -83,6 +85,6 @@ Format:
Markers maintained by workflows to record when they last ran. Read by other workflows that gate their behavior on freshness.
:LAST_AUDIT: 2026-07-20 (open set current — this session's shipped work (working/temp, triage-source-activation, silent-until-signal, suspend detach) closed as it went; sentry cluster consolidated (merged the /schedule tasks, added cross-host-coordination); nothing shipped-but-open per git reconcile. Live finding: the Polyglot + Subprojects scouting tasks are SCHEDULED 2026-07-20 and due.)
-:LAST_INBOX_PROCESS: 2026-07-20 (morning sentry review + build session: triage migration confirmations from home + work processed; earlier 2026-07-18 pass folded in)
+:LAST_INBOX_PROCESS: 2026-07-31 (four work handoffs: standup-scripts proposal accepted with four changes and shipped as a212eeb; voice pattern #48 filed [#B], then its interaction.md mirror folded in on Craig's approval; a correction FYI acknowledged — my project-workflows fork claim was wrong, Phase 11 composes rather than shadows)
Format: one =:MARKER: YYYY-MM-DD= line per workflow. Workflows overwrite their own marker on completion.
diff --git a/.ai/protocols.org b/.ai/protocols.org
index 3cd02ef..b291d9e 100644
--- a/.ai/protocols.org
+++ b/.ai/protocols.org
@@ -84,7 +84,7 @@ Do NOT estimate, guess, or rely on memory. Just run the command. It takes one se
Every session pulls rulesets first, then the local project repo. Rulesets carries the canonical behavioral rules and =.ai/= templates (the old =claude-templates= repo is folded in as a subtree at =rulesets/claude-templates/=); the project pull lands commits pushed from other machines or teammates since the last session.
-Resolve any dirty-tree or merge issue at each step before moving on. Both pulls run as =git pull --ff-only= (or =git merge --ff-only= against the fetched upstream), so anything non-trivial — non-fast-forward history, dirty working tree, diverged branches — aborts. Surface the state and stop. Never auto-stash, auto-merge, or auto-rebase; the user resolves the conflict before further work.
+Resolve any sync-blocking tree or merge issue at each step before moving on. The shared =git-worktree-gate sync-safe= policy permits untracked deliveries beneath =inbox/= so receiving a handoff never prevents another project from refreshing rulesets; every staged or tracked change, dirty submodule, Git operation in progress, or untracked path outside =inbox/= blocks. Both pulls run as =git pull --ff-only= (or =git merge --ff-only= against the fetched upstream), so non-fast-forward history and diverged branches also abort. Surface the state and stop. Never auto-stash, auto-merge, or auto-rebase; the user resolves the conflict before further work.
Mechanics live in =startup.org= Phase A.0. The rule lives here because it governs the very first action of every session: load the freshest behavioral rules and templates before anything else runs.
@@ -106,7 +106,7 @@ The epoch is baked into the id by the spawner, never minted inside =session-cont
Resolve the path with =.ai/scripts/session-context-path= rather than hardcoding =.ai/session-context.org=; it prints the right path for the current =AI_AGENT_ID=. Fall back to =.ai/session-context.org= if the script isn't present (older checkouts mid-sync). Everything below — the record/recovery purpose, the update triggers, the startup existence check, the wrap-up rename — operates on that resolved path. The prose says "session-context.org" as the default name; read it as "the resolved active path" when =AI_AGENT_ID= is set.
-A helper instance (a second agent running in this project while a primary session is live) follows a different contract: it skips the pulls and rsync, makes only scoped single-heading edits to shared files, leaves all git mutation to the primary, and wraps up by archiving its own context file without committing. The full rules — read/write tiers, data-integrity, light startup, helper wrap-up — live in [[file:workflows/helper-mode.org][workflows/helper-mode.org]]. A session is a helper only when something routes it there (the =ai --helper= launcher, startup's roster check, or an explicit "you are a helper" instruction); the routing itself ships behind the helper-instance feature gate and isn't live yet.
+A helper instance (a second agent running in this project while a primary session is live) follows a different contract: it skips the pulls and rsync, makes only scoped single-heading edits to shared files, leaves all git mutation to the primary, and wraps up by archiving its own context file without committing. The full rules — read/write tiers, data-integrity, light startup, helper wrap-up — live in [[file:workflows/helper-mode.org][workflows/helper-mode.org]]. A session is a helper only when something routes it there: the =ai --helper= launcher (live — it checks the roster, assigns the id, and opens the helper in its own tmux window) or an explicit "you are a helper" instruction. Startup's roster check is *not* built, so a bare =claude= launched into a project that already has a live session will run full primary startup regardless. Launch helpers with =ai --helper=.
This file serves two purposes with one mechanism:
1. *Crash recovery* — if the session dies mid-work, the live file is all that's left. On 2026-01-22 a session crashed during a 20-minute design discussion and all context was lost because this file wasn't being updated.
@@ -270,7 +270,9 @@ The queue lives in the session anchor (=.ai/session-context.org=) under a =* Bef
Three ways to access Craig's calendars: Google Calendar MCP (preferred, both personal + work accounts), gcalcli (fallback, personal only), Emacs org files (read-only viewer).
-For tool recipes, authentication details, and credentials, see [[file:references/calendar-reference.org][calendar-reference.org]].
+For tool recipes and account details, read the calendar workflows in =.ai/workflows/=: =add-calendar-event.org=, =edit-calendar-event.org=, =delete-calendar-event.org=, =read-calendar-events.org=. They carry the MCP tool names, both account ids, the gcalcli fallback, and the conflict-check discipline.
+
+Credentials are needed only for a re-auth Craig performs himself. The MCP bundle's =mcp/README.org= in the rulesets repo is the authority: =gcp-oauth.keys.json= is gitignored and regenerated at install from a base64 var in the bundle, never committed. Named in prose rather than linked, because that path isn't synced into consuming projects.
** GPG Keys
@@ -374,9 +376,19 @@ Craig runs a pure Wayland setup (Hyprland) and avoids XWayland/Xorg apps.
- Clipboard: Use =wl-copy= and =wl-paste= (NOT =xclip= or =xsel=)
- Window management: Use Hyprland commands (NOT =xkill=, =xdotool=, etc.)
- Prefer Wayland-native tools over X11 equivalents
-- Open URLs in browser: Use =google-chrome-stable "URL" &>/dev/null &=
- - The =&>/dev/null &= is required to detach the process and suppress output
- - Without it, the command may appear to hang or produce no result
+- Open URLs in browser: invoke Chrome directly — never =xdg-open=, which returned success in a home session on 2026-07-26 while no tab appeared.
+
+ Chrome is normally already running, and in that case it hands the URL to the live session and exits immediately (rc 0), printing =Opening in existing browser session.= on *stdout*. So run it in the foreground and read that line as the confirmation the tab actually opened:
+
+ #+begin_src bash
+ google-chrome-stable --new-tab "URL"
+ #+end_src
+
+ Don't redirect stdout away while checking for that line — verified 2026-07-27 on ratio: with =2>/dev/null= the message still appears (it isn't stderr), and with =>/dev/null= it vanishes.
+
+ Several URLs in one invocation open as separate tabs (=google-chrome-stable --new-tab "URL1" "URL2"=). Pass them as separate words or an array — the Bash tool runs zsh, which does not word-split an unquoted =$urls= variable, so a space-joined string arrives as one malformed argument (see the zsh note below).
+
+ *Cold start.* If Chrome is *not* already running, the command becomes the browser process and blocks. Detach that case with =&>/dev/null &=, accepting that the confirmation line is discarded — there is no session to confirm into. Don't apply the detach form unconditionally: it suppresses the very output the warm path is verified by.
*** Shell aliases (=ls= → =exa=)
Craig's shell aliases =ls= to =exa=, which prints nothing to non-TTY pipes (e.g. when capturing =ls= output in a Bash tool call). The result looks like the directory is empty when it isn't.
@@ -567,12 +579,13 @@ When monitoring a long-running process (rsync, large downloads, builds, VM tests
** "Wrap it up" / "That's a wrap" / "Let's call it a wrap"
-When Craig says any of these phrases (or variations), execute the wrap-up workflow: [[file:workflows/wrap-it-up.org][wrap-it-up.org]]. Four steps:
+When Craig says any of these phrases (or variations), execute the wrap-up workflow: [[file:workflows/wrap-it-up.org][wrap-it-up.org]]. Five load-bearing steps:
1. *Finalize the Summary* in =.ai/session-context.org= (populate the 5 subsections from the Session Log)
2. *Rename* =.ai/session-context.org= → =.ai/sessions/YYYY-MM-DD-HH-MM-description.org=
3. *Git commit + push* to all remotes (see Git Commit Requirements)
-4. *Valediction* — brief, warm, specific closing
+4. *Certify the clean tree* with =git-worktree-gate certify=. Any remaining staged, unstaged, untracked, submodule, or in-progress-operation state blocks wrap entirely; report each path and the exact decision needed. There is no dirty-file deferral.
+5. *Valediction* — brief, warm, specific closing, reachable only after certification
The absence of =.ai/session-context.org= after wrap-up is the signal that the session ended cleanly. If the file is still there at the next session start, the previous session was interrupted.
diff --git a/.ai/references/calendar-reference.org b/.ai/references/calendar-reference.org
deleted file mode 100644
index 5791b08..0000000
--- a/.ai/references/calendar-reference.org
+++ /dev/null
@@ -1,66 +0,0 @@
-#+TITLE: Calendar Reference
-#+AUTHOR: Craig Jennings
-
-Tool recipes, authentication, and credentials for Craig's calendar
-setup. Three access methods, in order of preference.
-
-* Google Calendar MCP Server (preferred for all calendar operations)
-
-Craig has the =@cocal/google-calendar-mcp= MCP server configured at user scope (=~/.claude.json=). It provides full read/write access to Google Calendar via MCP tools.
-
-Two accounts are authenticated:
-- *personal* — craigmartinjennings@gmail.com (primary: "Craig Google")
-- *work* — craig.jennings@deepsat.com (primary: "Craig Deepsat")
-
-MCP tools available:
-- =list-events=, =search-events=, =get-event= — read events
-- =create-event=, =create-events= — add events
-- =update-event= — modify events
-- =delete-event= — remove events
-- =list-calendars=, =list-colors= — calendar metadata
-- =get-freebusy= — check availability
-- =manage-accounts= — add/remove/list authenticated accounts
-- =respond-to-event= — accept/decline invitations
-- =get-current-time= — current time in any timezone
-
-Use =account_id: "personal"= or =account_id: "work"= to specify which account.
-
-Default calendar for adding events: "Craig Google" (personal account).
-
-Calendar workflows are available alongside this reference: add-calendar-event, edit-calendar-event, delete-calendar-event, read-calendar-events.
-
-If re-authentication is needed:
-- Use the =manage-accounts= MCP tool with =action: "add"= and the account nickname
-- OAuth credentials: =~/projects/homelab/assets/gcp-oauth.keys.json=
-- Google Cloud app is in production mode (tokens don't expire after 7 days)
-- See =~/projects/homelab/.ai/gcalcli-setup.org= for Google Cloud project details
-
-* gcalcli (fallback for personal account only)
-
-Craig has =gcalcli= installed via pipx, authenticated to his personal Google account only.
-
-#+begin_src bash
-gcalcli agenda # upcoming events
-gcalcli calw # weekly view
-gcalcli add --title "..." --when "..." --duration "60" # add event
-gcalcli search "..." # search events
-gcalcli delete "..." # delete event
-#+end_src
-
-Use =--calendar "Craig Google"= when adding events.
-
-gcalcli does NOT have access to the work (DeepSat) calendar. Use the MCP server for work calendar operations.
-
-If gcalcli needs re-authentication, credentials are stored in the homelab project: =~/projects/homelab/assets/gcalcli-client-secret.json.gpg= (GPG encrypted).
-
-* Emacs org files (read-only, for viewing schedules)
-
-Craig's calendars are at: =~/.emacs.d/data/*cal.org= (gcal.org, dcal.org, pcal.org)
-
-These files are **READ-ONLY** — NEVER add anything to them.
-
-Use this to:
-- Check meeting times and schedules
-- Verify when events occurred
-- See what's upcoming
-- Note: only updated periodically when Emacs is running — may be stale
diff --git a/.ai/scripts/sync-templates b/.ai/scripts/sync-templates
new file mode 100755
index 0000000..b9769f3
--- /dev/null
+++ b/.ai/scripts/sync-templates
@@ -0,0 +1,131 @@
+#!/usr/bin/env bash
+# sync-templates — copy rulesets' canonical .ai/ templates into this project.
+#
+# Extracted verbatim from startup.org Phase A step 3 (2026-07-31). This is the
+# mechanism that distributes every workflow, protocol and script change to every
+# project, and until the extraction it was untested inline bash running in every
+# session. The extraction exists so the guard changes that follow can be tested
+# before they reach a file whose failure mode is "no project starts".
+#
+# Behavior is deliberately identical to the inline block it replaces, including
+# its rough edges. Anything that looks like a defect here is characterized by a
+# test rather than fixed in passing — a change of behavior belongs in its own
+# commit, not smuggled into an extraction.
+#
+# Usage: sync-templates [project-root] (default: $PWD)
+# Output: one line naming the outcome, matching the previous inline wording
+# Exit: 0 always, as the inline block did — the outcome is on stdout
+#
+# Two guards, and they work differently. One withholds files; the other skips
+# the whole run:
+#
+# Rulesets dirty under the synced paths → withhold exactly those files.
+# rsync -a --delete copies the working tree by disk presence, so an in-flight
+# edit in rulesets would otherwise land downstream as drift the project never
+# authored. Each dirty path becomes an --exclude, which rsync honors on both
+# sides: the file is neither overwritten nor deleted downstream, and every
+# clean file still propagates. This was a global skip until 2026-07-31, which
+# meant one uncommitted file in rulesets froze every template for every
+# project until it was committed.
+#
+# Project branch behind its upstream → skip the whole sync. Syncing onto a
+# stale committed .ai/ baseline measures the diff against old content, so it
+# comes out huge and conflicts once the branch reconciles to an upstream that
+# already carries the newer templates. This one stays all-or-nothing because
+# the staleness is in the destination, not in any particular source file.
+#
+# The rulesets location is injectable (SYNC_RULESETS_DIR) so the guards can be
+# exercised against a fixture instead of the real checkout.
+
+rs="${SYNC_RULESETS_DIR:-$HOME/code/rulesets}"
+proj="${1:-$PWD}"
+
+cd "$proj" || {
+ echo "sync-templates: cannot enter '$proj'" >&2
+ exit 0
+}
+
+# The dirty set under the synced paths, one repo-relative path per line.
+# core.quotePath=false keeps a non-ASCII filename literal instead of \xNN-escaped,
+# so the path we build an --exclude from is the path on disk.
+synced_dirty=$(cd "$rs" && git -c core.quotePath=false status --porcelain -- \
+ claude-templates/.ai/protocols.org \
+ claude-templates/.ai/workflows/ \
+ claude-templates/.ai/scripts/ 2>/dev/null)
+
+# Turn that set into per-rsync --exclude flags rather than a global skip. An
+# excluded path is neither overwritten nor deleted on the receiving side, so an
+# in-flight edit stays in-flight while every file it doesn't touch propagates
+# normally. The all-or-nothing skip this replaces is what caused the 2026-07-30
+# outage: one uncommitted workflow file withheld every template from every
+# project for a full day.
+protocols_dirty=0
+wf_excludes=()
+sc_excludes=()
+withheld=()
+
+while IFS= read -r line; do
+ [ -z "$line" ] && continue
+ path="${line:3}"
+ # A rename reports "old -> new". Withhold both sides: the new name is
+ # half-landed, and sweeping the old copy downstream would delete a file the
+ # project still runs while the rename sits uncommitted.
+ if [[ "$path" == *" -> "* ]]; then
+ paths=("${path%% -> *}" "${path##* -> }")
+ else
+ paths=("$path")
+ fi
+ for p in "${paths[@]}"; do
+ p="${p%\"}"; p="${p#\"}"
+ case "$p" in
+ claude-templates/.ai/protocols.org)
+ # A single-file rsync has nothing to exclude within, so this one
+ # transfer is skipped outright while the other two still run.
+ protocols_dirty=1
+ withheld+=("$p")
+ ;;
+ claude-templates/.ai/workflows/*)
+ # Leading / anchors the pattern to the transfer root, so a dirty
+ # workflows/foo.org can't also suppress scripts/tests/foo.org.
+ wf_excludes+=("--exclude=/${p#claude-templates/.ai/workflows/}")
+ withheld+=("$p")
+ ;;
+ claude-templates/.ai/scripts/*)
+ sc_excludes+=("--exclude=/${p#claude-templates/.ai/scripts/}")
+ withheld+=("$p")
+ ;;
+ esac
+ done
+done <<< "$synced_dirty"
+
+# behind==0 (up-to-date or ahead-only) means HEAD contains all of upstream, so
+# the baseline is current. No upstream (new/unpushed branch) → rev-list fails →
+# proj_behind stays 0 → the sync runs.
+proj_behind=0
+if [ -d .git ]; then
+ counts=$(git rev-list --left-right --count '@{u}...HEAD' 2>/dev/null) \
+ && [ "$(printf '%s' "$counts" | cut -f1)" -gt 0 ] 2>/dev/null \
+ && proj_behind=1
+fi
+
+if [ "$proj_behind" -eq 1 ]; then
+ echo "project branch is behind upstream — skipping .ai/ sync this session (templates never land on a stale baseline; the sync runs once the branch is current)"
+else
+ [ "$protocols_dirty" -eq 0 ] && rsync -a "$rs/claude-templates/.ai/protocols.org" .ai/protocols.org
+ rsync -a --delete "${wf_excludes[@]}" "$rs/claude-templates/.ai/workflows/" .ai/workflows/
+ # Running rulesets' own pytest leaves these in the canonical scripts/tests/,
+ # and rsync -a copies by disk presence regardless of .gitignore, so without
+ # the excludes every project's tree collects machine-specific cache files.
+ rsync -a --delete --exclude='__pycache__' --exclude='.pytest_cache' --exclude='*.pyc' \
+ "${sc_excludes[@]}" "$rs/claude-templates/.ai/scripts/" .ai/scripts/
+ # Known false-success path, inherited and characterized rather than fixed
+ # here: this line prints unconditionally, so a run where all three rsyncs
+ # failed (an absent canonical source, say) still reports a successful sync.
+ # A last-synced manifest must not be written from this branch as it stands —
+ # it would stamp success onto a sync that did nothing.
+ echo ".ai/ synced from templates"
+ if [ ${#withheld[@]} -gt 0 ]; then
+ echo " withheld — uncommitted in rulesets, lands once committed:"
+ printf ' %s\n' "${withheld[@]}"
+ fi
+fi
diff --git a/.ai/scripts/tests/sync-templates.bats b/.ai/scripts/tests/sync-templates.bats
new file mode 100644
index 0000000..6651c99
--- /dev/null
+++ b/.ai/scripts/tests/sync-templates.bats
@@ -0,0 +1,319 @@
+#!/usr/bin/env bats
+# Characterization tests for sync-templates — the mechanism that distributes
+# every template change to every project.
+#
+# These pin CURRENT behavior (record-not-spec) ahead of the guard changes the
+# 2026-07-30 propagation incident calls for. That incident is what these exist
+# for: an uncommitted edit in rulesets silently blocked all three rsyncs for a
+# whole day, and five workflow files went stale in one downstream project alone
+# with nothing anywhere reporting it. Any change to this script's guards has to
+# come with a red test here first.
+#
+# Everything runs against fixture directories via SYNC_RULESETS_DIR, so no test
+# touches the real rulesets checkout or any real project.
+
+setup() {
+ # This suite lives beside the script it tests and travels with it, so it
+ # resolves the script relative to itself rather than to a repo root.
+ SYNC="$(cd "$(dirname "$BATS_TEST_FILENAME")/.." && pwd)/sync-templates"
+ WORK="$(mktemp -d)"
+ RS="$WORK/rulesets"
+ PROJ="$WORK/proj"
+ export SYNC_RULESETS_DIR="$RS"
+
+ # A minimal rulesets fixture: a git repo with the three synced source paths.
+ mkdir -p "$RS/claude-templates/.ai/workflows" "$RS/claude-templates/.ai/scripts"
+ printf 'canonical protocols\n' > "$RS/claude-templates/.ai/protocols.org"
+ printf 'canonical startup\n' > "$RS/claude-templates/.ai/workflows/startup.org"
+ printf 'canonical helper\n' > "$RS/claude-templates/.ai/scripts/helper"
+ # Real rulesets gitignores the python cache paths, so they never make the
+ # tree dirty. Without this the fixture diverges from production in a way
+ # that silently disarms the exclusion test: the cache files read as
+ # untracked, guard one fires, the sync never runs, and assertions that the
+ # cache did NOT arrive pass because nothing arrived at all.
+ printf '__pycache__/\n.pytest_cache/\n*.pyc\n' > "$RS/.gitignore"
+ _mk_repo "$RS"
+
+ # A consuming project with the destination dirs.
+ mkdir -p "$PROJ/.ai/workflows" "$PROJ/.ai/scripts"
+}
+
+teardown() { rm -rf "$WORK"; }
+
+_mk_repo() {
+ local d="$1"
+ git init -q "$d"
+ git -C "$d" config user.email t@example.com
+ git -C "$d" config user.name tester
+ git -C "$d" config commit.gpgsign false
+ git -C "$d" config gc.auto 0
+ git -C "$d" config maintenance.auto false
+ git -C "$d" add -A
+ # --allow-empty: the project fixture holds only empty directories, which git
+ # has nothing to commit, and these tests need it to be a repo with a HEAD.
+ git -C "$d" commit -q --allow-empty -m init
+}
+
+# --- the happy path ------------------------------------------------------------
+
+@test "clean rulesets and a non-git project: syncs all three paths" {
+ run bash "$SYNC" "$PROJ"
+ [ "$status" -eq 0 ]
+ [[ "$output" == *"synced from templates"* ]]
+ [ "$(cat "$PROJ/.ai/protocols.org")" = "canonical protocols" ]
+ [ "$(cat "$PROJ/.ai/workflows/startup.org")" = "canonical startup" ]
+ [ "$(cat "$PROJ/.ai/scripts/helper")" = "canonical helper" ]
+}
+
+@test "--delete removes a retired template file from the project" {
+ printf 'retired\n' > "$PROJ/.ai/workflows/gone.org"
+ run bash "$SYNC" "$PROJ"
+ [ "$status" -eq 0 ]
+ [[ "$output" == *"synced from templates"* ]]
+ [ ! -e "$PROJ/.ai/workflows/gone.org" ]
+}
+
+@test "the scripts sync excludes python cache artifacts" {
+ mkdir -p "$RS/claude-templates/.ai/scripts/__pycache__" \
+ "$RS/claude-templates/.ai/scripts/.pytest_cache"
+ printf 'junk\n' > "$RS/claude-templates/.ai/scripts/__pycache__/x.pyc"
+ printf 'junk\n' > "$RS/claude-templates/.ai/scripts/.pytest_cache/y"
+ printf 'junk\n' > "$RS/claude-templates/.ai/scripts/stray.pyc"
+ run bash "$SYNC" "$PROJ"
+ [ "$status" -eq 0 ]
+ # Assert the sync RAN before asserting what it didn't copy. Without this the
+ # absences below are satisfied by a skipped sync, and the whole test passes
+ # with every --exclude flag deleted from the script.
+ [[ "$output" == *"synced from templates"* ]]
+ [ -e "$PROJ/.ai/scripts/helper" ]
+ [ ! -e "$PROJ/.ai/scripts/__pycache__" ]
+ [ ! -e "$PROJ/.ai/scripts/.pytest_cache" ]
+ [ ! -e "$PROJ/.ai/scripts/stray.pyc" ]
+}
+
+@test "project-owned directories are never touched by the sync" {
+ mkdir -p "$PROJ/.ai/project-workflows" "$PROJ/.ai/project-scripts"
+ printf 'mine\n' > "$PROJ/.ai/project-workflows/local.org"
+ printf 'mine\n' > "$PROJ/.ai/project-scripts/local.py"
+ run bash "$SYNC" "$PROJ"
+ [ "$status" -eq 0 ]
+ [[ "$output" == *"synced from templates"* ]]
+ [ "$(cat "$PROJ/.ai/project-workflows/local.org")" = "mine" ]
+ [ "$(cat "$PROJ/.ai/project-scripts/local.py")" = "mine" ]
+}
+
+# --- guard one: rulesets dirty under the synced paths --------------------------
+
+@test "a dirty file is withheld from the sync and named in the output" {
+ printf 'in-flight edit\n' >> "$RS/claude-templates/.ai/workflows/startup.org"
+ printf 'stale\n' > "$PROJ/.ai/workflows/startup.org"
+ run bash "$SYNC" "$PROJ"
+ [ "$status" -eq 0 ]
+ [[ "$output" == *"withheld"* ]]
+ [[ "$output" == *"startup.org"* ]]
+ # The in-flight edit still must not land downstream.
+ [ "$(cat "$PROJ/.ai/workflows/startup.org")" = "stale" ]
+}
+
+@test "ONE dirty file no longer blocks the other two rsyncs" {
+ # The 2026-07-30 incident, inverted. An edit to a workflow file used to
+ # withhold protocols.org and every script for every project; now it withholds
+ # only itself.
+ printf 'in-flight edit\n' >> "$RS/claude-templates/.ai/workflows/startup.org"
+ printf 'stale protocols\n' > "$PROJ/.ai/protocols.org"
+ printf 'stale helper\n' > "$PROJ/.ai/scripts/helper"
+ run bash "$SYNC" "$PROJ"
+ [ "$status" -eq 0 ]
+ [ "$(cat "$PROJ/.ai/protocols.org")" = "canonical protocols" ]
+ [ "$(cat "$PROJ/.ai/scripts/helper")" = "canonical helper" ]
+}
+
+@test "a dirty file's clean siblings under the SAME path still sync" {
+ printf 'canonical wrap\n' > "$RS/claude-templates/.ai/workflows/wrap.org"
+ git -C "$RS" add -A && git -C "$RS" commit -q -m 'add wrap'
+ printf 'in-flight edit\n' >> "$RS/claude-templates/.ai/workflows/startup.org"
+ printf 'stale wrap\n' > "$PROJ/.ai/workflows/wrap.org"
+ run bash "$SYNC" "$PROJ"
+ [ "$status" -eq 0 ]
+ # The narrowing is per-file, not per-directory: only startup.org is held back.
+ [ "$(cat "$PROJ/.ai/workflows/wrap.org")" = "canonical wrap" ]
+}
+
+@test "an excluded file is not deleted by --delete either" {
+ # rsync honors --exclude on both sides, so a withheld file that exists
+ # downstream must survive the run rather than being swept as a stray.
+ printf 'in-flight edit\n' >> "$RS/claude-templates/.ai/workflows/startup.org"
+ printf 'project copy\n' > "$PROJ/.ai/workflows/startup.org"
+ run bash "$SYNC" "$PROJ"
+ [ "$status" -eq 0 ]
+ [ -e "$PROJ/.ai/workflows/startup.org" ]
+ [ "$(cat "$PROJ/.ai/workflows/startup.org")" = "project copy" ]
+}
+
+@test "a dirty protocols.org withholds only itself; workflows and scripts sync" {
+ printf 'in-flight edit\n' >> "$RS/claude-templates/.ai/protocols.org"
+ printf 'stale protocols\n' > "$PROJ/.ai/protocols.org"
+ printf 'stale startup\n' > "$PROJ/.ai/workflows/startup.org"
+ printf 'stale helper\n' > "$PROJ/.ai/scripts/helper"
+ run bash "$SYNC" "$PROJ"
+ [ "$status" -eq 0 ]
+ [ "$(cat "$PROJ/.ai/protocols.org")" = "stale protocols" ]
+ [ "$(cat "$PROJ/.ai/workflows/startup.org")" = "canonical startup" ]
+ [ "$(cat "$PROJ/.ai/scripts/helper")" = "canonical helper" ]
+}
+
+@test "dirty files across two synced paths withhold both, sync the third" {
+ printf 'in-flight\n' >> "$RS/claude-templates/.ai/workflows/startup.org"
+ printf 'in-flight\n' >> "$RS/claude-templates/.ai/scripts/helper"
+ printf 'stale startup\n' > "$PROJ/.ai/workflows/startup.org"
+ printf 'stale helper\n' > "$PROJ/.ai/scripts/helper"
+ printf 'stale protocols\n' > "$PROJ/.ai/protocols.org"
+ run bash "$SYNC" "$PROJ"
+ [ "$status" -eq 0 ]
+ [ "$(cat "$PROJ/.ai/workflows/startup.org")" = "stale startup" ]
+ [ "$(cat "$PROJ/.ai/scripts/helper")" = "stale helper" ]
+ [ "$(cat "$PROJ/.ai/protocols.org")" = "canonical protocols" ]
+}
+
+@test "an untracked file under a synced path is withheld, not blocking" {
+ printf 'new template\n' > "$RS/claude-templates/.ai/workflows/brand-new.org"
+ printf 'stale protocols\n' > "$PROJ/.ai/protocols.org"
+ run bash "$SYNC" "$PROJ"
+ [ "$status" -eq 0 ]
+ [[ "$output" == *"withheld"* ]]
+ # An unfinished new template must not ship half-written...
+ [ ! -e "$PROJ/.ai/workflows/brand-new.org" ]
+ # ...and must not hold back everything else.
+ [ "$(cat "$PROJ/.ai/protocols.org")" = "canonical protocols" ]
+}
+
+@test "an untracked DIRECTORY under a synced path is withheld whole" {
+ # git collapses an untracked dir to one porcelain line with a trailing slash
+ # ("?? .../plugins/"), so the exclude has to match the directory rather than
+ # the files inside it. A half-written plugin dir must not ship.
+ mkdir -p "$RS/claude-templates/.ai/workflows/plugins"
+ printf 'half written\n' > "$RS/claude-templates/.ai/workflows/plugins/new.org"
+ printf 'stale protocols\n' > "$PROJ/.ai/protocols.org"
+ run bash "$SYNC" "$PROJ"
+ [ "$status" -eq 0 ]
+ [ ! -e "$PROJ/.ai/workflows/plugins" ]
+ [ "$(cat "$PROJ/.ai/protocols.org")" = "canonical protocols" ]
+}
+
+@test "a file dirty in the index (staged, uncommitted) is withheld too" {
+ printf 'staged edit\n' >> "$RS/claude-templates/.ai/workflows/startup.org"
+ git -C "$RS" add claude-templates/.ai/workflows/startup.org
+ printf 'stale\n' > "$PROJ/.ai/workflows/startup.org"
+ run bash "$SYNC" "$PROJ"
+ [ "$status" -eq 0 ]
+ [ "$(cat "$PROJ/.ai/workflows/startup.org")" = "stale" ]
+}
+
+@test "a renamed template withholds both the old and the new path" {
+ git -C "$RS" mv claude-templates/.ai/workflows/startup.org \
+ claude-templates/.ai/workflows/renamed.org
+ printf 'stale startup\n' > "$PROJ/.ai/workflows/startup.org"
+ run bash "$SYNC" "$PROJ"
+ [ "$status" -eq 0 ]
+ # The new name must not ship mid-rename, and the old copy must not be swept
+ # while the rename is still uncommitted.
+ [ ! -e "$PROJ/.ai/workflows/renamed.org" ]
+ [ "$(cat "$PROJ/.ai/workflows/startup.org")" = "stale startup" ]
+}
+
+@test "rulesets dirt OUTSIDE the synced paths does not block the sync" {
+ printf 'scratch\n' > "$RS/scratch.txt"
+ printf 'edit\n' >> "$RS/claude-templates/bin-ish.txt"
+ run bash "$SYNC" "$PROJ"
+ [ "$status" -eq 0 ]
+ [[ "$output" == *"synced from templates"* ]]
+}
+
+# --- guard two: the project branch is behind its upstream ----------------------
+
+@test "a project behind its upstream skips the sync" {
+ _mk_repo "$PROJ"
+ git init -q --bare "$WORK/remote"
+ git -C "$PROJ" remote add origin "$WORK/remote"
+ git -C "$PROJ" push -q -u origin HEAD
+ git -C "$PROJ" commit -q --allow-empty -m ahead
+ git -C "$PROJ" push -q origin HEAD
+ git -C "$PROJ" reset -q --hard HEAD~1
+ printf 'stale\n' > "$PROJ/.ai/workflows/startup.org"
+
+ run bash "$SYNC" "$PROJ"
+ [ "$status" -eq 0 ]
+ [[ "$output" == *"behind upstream"* ]]
+ [ "$(cat "$PROJ/.ai/workflows/startup.org")" = "stale" ]
+}
+
+@test "a project AHEAD of its upstream still syncs" {
+ _mk_repo "$PROJ"
+ git init -q --bare "$WORK/remote"
+ git -C "$PROJ" remote add origin "$WORK/remote"
+ git -C "$PROJ" push -q -u origin HEAD
+ git -C "$PROJ" commit -q --allow-empty -m ahead
+ run bash "$SYNC" "$PROJ"
+ [ "$status" -eq 0 ]
+ [[ "$output" == *"synced from templates"* ]]
+}
+
+@test "a git project with no upstream syncs (rev-list fails, guard stays off)" {
+ _mk_repo "$PROJ"
+ run bash "$SYNC" "$PROJ"
+ [ "$status" -eq 0 ]
+ [[ "$output" == *"synced from templates"* ]]
+}
+
+# --- edges ---------------------------------------------------------------------
+
+@test "a nonexistent project directory reports and exits 0 without syncing" {
+ run bash "$SYNC" "$WORK/does-not-exist"
+ [ "$status" -eq 0 ]
+ [[ "$output" == *"cannot enter"* ]]
+ [[ "$output" != *"synced from templates"* ]]
+ [ ! -e "$WORK/does-not-exist" ]
+}
+
+@test "the sync is idempotent — a second run changes nothing" {
+ bash "$SYNC" "$PROJ"
+ first="$(find "$PROJ/.ai" -type f -exec sha256sum {} + | sort)"
+ run bash "$SYNC" "$PROJ"
+ [ "$status" -eq 0 ]
+ [[ "$output" == *"synced from templates"* ]]
+ second="$(find "$PROJ/.ai" -type f -exec sha256sum {} + | sort)"
+ [ "$first" = "$second" ]
+}
+
+@test "a missing canonical source still reports success — the false-success path" {
+ # Faithfully inherited from the inline block, and pinned here because the
+ # manifest step depends on it: a last-synced record written after this
+ # branch would stamp a successful sync onto one where all three rsyncs
+ # failed. The guard work has to fix this before it can trust the record.
+ # Point at a rulesets that isn't there at all, rather than deleting the
+ # canonical subtree inside a live repo — that would show up as staged
+ # deletions and trip guard one, which is a different path entirely.
+ SYNC_RULESETS_DIR="$WORK/no-such-rulesets" run bash "$SYNC" "$PROJ"
+ [ "$status" -eq 0 ]
+ [[ "$output" == *"synced from templates"* ]]
+ # Nothing arrived, and the success line says otherwise. Asserted against a
+ # file that DOES arrive on a real sync — protocols.org is absent before any
+ # sync too, so its absence alone would prove nothing.
+ [ ! -e "$PROJ/.ai/scripts/helper" ]
+}
+
+@test "a locally-edited template is silently overwritten, with no record kept" {
+ # Work's 2026-07-30 regression, pinned: a project patches a rulesets-owned
+ # file, the next sync reverts it to canonical, and nothing anywhere says so.
+ # The output is indistinguishable from an ordinary successful sync.
+ bash "$SYNC" "$PROJ"
+ printf 'local fix for a real bug\n' > "$PROJ/.ai/workflows/startup.org"
+ run bash "$SYNC" "$PROJ"
+ [ "$status" -eq 0 ]
+ [ "$(cat "$PROJ/.ai/workflows/startup.org")" = "canonical startup" ]
+ [[ "$output" == *"synced from templates"* ]]
+ # No warning, no backup, no manifest — the loss leaves no trace at all.
+ [[ "$output" != *"overwrote"* ]]
+ [[ "$output" != *"local edit"* ]]
+ [ ! -d "$PROJ/.ai/.sync-backups" ]
+}
diff --git a/.ai/scripts/tests/test-todo-cleanup.el b/.ai/scripts/tests/test-todo-cleanup.el
index a92d238..1e964b3 100644
--- a/.ai/scripts/tests/test-todo-cleanup.el
+++ b/.ai/scripts/tests/test-todo-cleanup.el
@@ -1086,7 +1086,7 @@ line) is left untouched — the strip stops at the first non-planning line."
;;
;; todo-cleanup rewrites todo.org in place and left no copy behind, while both
;; sibling org-mutators back up to /tmp first. It is also the one that runs most
-;; often (every wrap, every sentry fire). Emacs's own backup does not fire under
+;; often (every wrap, every sentry cycle). Emacs's own backup does not fire under
;; --batch -q, so there was genuinely no undo short of git.
(ert-deftest tc-backup-written-before-a-real-mutation ()
diff --git a/.ai/scripts/todo-cleanup.el b/.ai/scripts/todo-cleanup.el
index cb333e2..516e9b1 100644
--- a/.ai/scripts/todo-cleanup.el
+++ b/.ai/scripts/todo-cleanup.el
@@ -843,7 +843,7 @@ event-log entry, pulling the timestamp from its CLOSED cookie. Honors
Matches `lint-org.el' and `wrap-org-table.el', the other tools that rewrite
these org files. todo-cleanup runs the most often of the three (every wrap,
-every sentry fire), and Emacs's own backup does not fire under --batch -q, so
+every sentry cycle), and Emacs's own backup does not fire under --batch -q, so
without this a mechanical rewrite has no undo short of git — which recovers
only to the last commit and loses intra-session work."
(let* ((base (format "%s%s.before-todo-cleanup.%s"
diff --git a/.ai/sessions/2026-07-25-15-34-clean-wrap-and-inbox-safe-sync.org b/.ai/sessions/2026-07-25-15-34-clean-wrap-and-inbox-safe-sync.org
new file mode 100644
index 0000000..737b1c5
--- /dev/null
+++ b/.ai/sessions/2026-07-25-15-34-clean-wrap-and-inbox-safe-sync.org
@@ -0,0 +1,85 @@
+#+TITLE: Session Context — 2026-07-25
+#+AUTHOR: Craig Jennings
+
+* Summary
+
+** Active Goal
+
+Guarantee that rulesets can only report a successful wrap with a completely clean Git worktree, while allowing other projects to refresh rulesets when its only residue is untracked inbox deliveries. Implemented, reviewed, fully tested, and prepared for a strict self-hosted wrap.
+
+** Decisions
+
+- One executable, =git-worktree-gate=, owns both repository-state policies. =strict= means no staged, unstaged, untracked, dirty-submodule, or in-progress-operation state; =sync-safe= permits only untracked paths beneath =inbox/=.
+- Cleanup failure is not a degraded wrap. It leaves the session open and must report each path, its Git state, why it cannot be resolved safely, and the decision Craig needs. Dirty-file deferrals, valediction, and teardown are forbidden in that state.
+- Final wrap verification is a HEAD-bound certificate stored in the Git directory and freshly rechecked inside the existing teardown hook. Integrating the check avoids the concurrent-hook race documented by Codex.
+- Another project's structured Edit/Write call may not resolve through an installed symlink into rulesets. The runtime hook denies it and points the sender to =inbox-send rulesets=.
+- The two MCP-registry handoffs were consolidated into one parked =[#B]= specification decision. The memory auditor remains separate; no machine-owned MCP configuration was promoted into canonical rulesets.
+
+** Data Collected / Findings
+
+- The prior rulesets archive completed at 09:24; the inherited three tracked changes were written at 10:27. The repository was dirtied after wrap through a later write path, which is why wrap certification alone needed the symlink-aware boundary guard.
+- The previous wrap prose contradicted itself: clean Git state was an exit criterion, but the leftover and inbox sections allowed explicit deferral. The teardown hook checked only the sentinel.
+- Adversarial review found a fail-open process-substitution edge: a low-level =git status= failure could appear as an empty stream. The gate now captures status and its exit code in Git-directory temporary files and blocks on failure.
+- Current Codex hooks support Stop blocking with =continue=false= and run matching commands concurrently. A user-level =hooks.json= is installed; a new Codex session must complete the normal hook review/trust step.
+- Full =make test= passed twice on the implementation. The final run includes 436 core Python tests, 72 hook tests, language suites, ERT suites, and all Bats suites. Focused additions cover inbox-only pulls, staged/unstaged/untracked/submodule/operation states, status failure, certificate/HEAD drift, Claude and Codex Stop outputs, installation, and realpath-based write denial.
+- The wrap roam sweep found Craig's 120-column table question. It was already enforced by =org-tables.md=, =lint-org='s =org-table-standard= judgment, and =wrap-org-table.el=; the live lint pass flagged the existing over-wide table. Removed the duplicate capture and synced roam.
+
+** Files Modified
+
+- =claude-templates/bin/git-worktree-gate= — shared strict/sync-safe classifier plus certificate/verify modes.
+- Startup protocol/workflow mirrors and =claude-templates/bin/ai= — inbox-only state remains visible but no longer blocks fast-forward refresh.
+- Wrap protocol/workflow mirrors and =hooks/ai-wrap-teardown.sh= — no deferral escape, actionable hard blocker, final certificate, fresh teardown verification.
+- =hooks/rulesets-write-boundary.py=, Claude/Codex hook configuration, cross-project rule, Makefile, and hook documentation — prevent structured writes through installed symlinks and install the enforcement on both runtimes.
+- Bats and pytest suites — repository-state, launcher, teardown, installer, and cross-project boundary regressions.
+- =todo.org= and workflow state — parked the consolidated MCP registry spec decision and recorded inbox processing.
+- Three inherited backlog files — retain the post-09:24 definition that speedrunnable means =:solo:=.
+
+** Next Steps
+
+- Start a new Codex session and review/trust the new user-level hooks when =/hooks= prompts; Claude already reads the linked hook configuration.
+- Say "spec the MCP registry sync" when ready to design the separate host-level registry reconciler.
+- The existing =inbox/lint-followups.org= pipeline retains its 14 current judgment items, including the over-wide table and older missing review stamps/links; they do not represent uncommitted work after this wrap.
+
+KB: promoted 0 / consulted no
+
+* Session Log
+
+** Startup and clean-worktree investigation
+
+Ran the required startup workflow. The canonical rulesets pull and template sync were blocked by three tracked modifications; two untracked inbox handoffs were also pending. Read the project and global behavioral rules, recent session archive, wrap workflow, relevant hook and launcher code, and the current Codex MCP and hook documentation needed to evaluate the inbox proposals.
+
+Investigated Craig's requirement that rulesets finish with an absolutely clean worktree while still allowing downstream projects to sync when rulesets has received inbox deliveries. The current wrap workflow states a clean exit criterion but later permits explicitly deferred dirty files, and its teardown hook checks only the wrap sentinel rather than Git state. The startup shell's tracked-change check already ignores untracked inbox files, but the general launcher dirty check does not distinguish inbox deliveries from other untracked residue.
+
+The three tracked files now dirty were written at 10:27, after the latest archived rulesets session wrapped at 09:24. That establishes a post-wrap write path: a strict wrap gate can guarantee the state at completion, but preventing later contamination also needs a realpath-aware cross-project write guard because globally installed rules and workflows are symlinks into this repository.
+
+The proposed design is one shared repository-state classifier with two policies. Strict wrap requires no staged, unstaged, or untracked entries and no dirty submodules. Inbox-safe sync permits an otherwise clean tracked/index state with untracked entries only below =inbox/=; those deliveries do not block pull or template sync. The strict check should run after the final push and again inside the ordered teardown hook, tied to the checked HEAD, while the inbox-safe policy should drive both startup and the =ai= launcher. Tests should cover every Git state, unusual path names, inbox-only sync, hook behavior, and the canonical/template mirrors.
+
+Two pending inbox handoffs both propose a shared Claude-to-Codex MCP registry mirror. They pass the value gate but overlap. The recommendation is to consolidate them into one =[#B]= specification with Codex-only entries preserved, atomic and redacted updates, dependency and health checks, both-machine verification, and the Claude-memory audit split into a separate task. No inbox disposition or project implementation has been applied.
+
+Completed the investigation plan without changing product code. The worktree proposal is ready for Craig's approval; implementation, tests, and inbox filing remain deliberately pending.
+
+** Clean-wrap invariant clarified
+
+Craig confirmed that cleanup failure must prevent wrap-up entirely. The agent must keep the session open and report exactly what remains in the Git worktree, why it could not resolve each item safely, and the specific action or decision Craig needs to supply. A warning, deferred-file exception, valediction, archived-as-complete status, or teardown is not an acceptable substitute for a clean tree.
+
+** Clean-wrap enforcement implemented
+
+Craig approved implementation and asked for a full wrap when it is done. Added =git-worktree-gate= as the single policy executable: strict mode rejects every staged, unstaged, untracked, dirty-submodule, and in-progress-operation state; sync-safe mode permits only untracked =inbox/= deliveries. Certificate and verify modes bind the final clean check to HEAD inside the Git directory.
+
+Wired sync-safe behavior into both startup workflow copies and the =ai= launcher. The picker labels inbox-only state distinctly and now fast-forwards a behind repository with inbox deliveries present while refusing other untracked residue.
+
+Made wrap cleanup fail closed: removed every dirty-file and inbox deferral escape, added the post-push clean certificate as a hard prerequisite to valediction, and required an exact path/state/needed-decision report when cleanup cannot finish. The existing teardown hook now freshly verifies the certificate and HEAD before consuming either sentinel, emits the runtime-appropriate Claude or Codex Stop blocker, and leaves the sentinel/session intact on failure. Added global Codex hook configuration and installed its symlink; Codex will require its normal hook review/trust on a new session.
+
+Added =rulesets-write-boundary.py= and configured Claude and Codex Edit/Write hooks. It resolves targets through symlinks and denies another project's write when the real path lands in rulesets, directing the proposal through =inbox-send rulesets=. The cross-project rule now states the installed-symlink case explicitly.
+
+Focused verification is green: 10 state-gate Bats cases, 13 teardown-hook cases including dirty/changed-HEAD/missing-certificate and both runtime outputs, 36 launcher cases including inbox-only pull, 5 installer cases, and 5 Python write-boundary cases.
+
+** Inbox — MCP registry proposals consolidated
+
+Processed the two pending 2026-07-25 handoffs from work and home. They were duplicate evidence for a host-level Claude-to-Codex MCP registry reconciler, not project-level implementation requests. Filed one =[#B]= parked specification decision in =todo.org= with preservation, redaction, atomicity, transport, health-check, two-machine, malformed-input, and token-rotation gates; split the memory auditor into separate future work. Deleted both inbound handoffs, stamped =:LAST_INBOX_PROCESS:=, sent acknowledgements to both source projects, and verified zero pending project handoffs.
+
+** Review, full verification, and wrap cleanup
+
+The first full =make test= run passed. Adversarial self-review then found the Git-status process-substitution fail-open and a path-resolution fail-open in the cross-project hook; fixed both, added status-error and sequencer regressions, aligned =protocols.org= with the new policies, and reran the complete suite successfully.
+
+Executed wrap cleanup: no sentry lock, todo hygiene/convert/archive/priority passes made no changes, lint-org applied zero mechanical changes and refreshed the 14-item judgment pipeline, project inbox remained at zero, route-batch had no candidates, and 30-day staleness was zero. The shared roam inbox held one rulesets capture about 120-column tables; verified the enforcement already exists in three layers, removed the duplicate, and pushed the roam update with the repository's sync helper.
diff --git a/.ai/sessions/2026-07-27-17-02-context-engineering-rightsizing.org b/.ai/sessions/2026-07-27-17-02-context-engineering-rightsizing.org
new file mode 100644
index 0000000..54020e4
--- /dev/null
+++ b/.ai/sessions/2026-07-27-17-02-context-engineering-rightsizing.org
@@ -0,0 +1,176 @@
+* Summary
+
+** Active Goal
+
+Review three Anthropic posts on context engineering against what this repo ships downstream, then act on the findings. Ended with the always-loaded rules surface cut from ~57,800 tokens to ~28,949 (plus 13,461 path-scoped), two mechanisms proven in a live session, and two of my own bugs found and fixed — one of which had killed Craig's work session.
+
+** Decisions
+
+- *Split rules by blast radius, not by size.* What must hold whether or not you're publishing, and where a violation is permanent and reaches other people, stays always-loaded. Everything recoverable can ride a trigger. That's what let =commits.md= and =testing.md= ship without waiting on any pilot.
+- *Goal is output quality first, tokens second* (Craig's correction). Anthropic's 80% was a finding, not a target. P4/Phase 8 (effort reduction) dropped outright for trading quality for cost; P5 (positive framing over prohibition) promoted as the lever that actually targets guardrails working against output.
+- *Don't apply the posts additively.* The harness system prompt already carries most of what the Opus 5 guide recommends adding, near-verbatim. Adding it to =claude-rules/= would worsen the duplicate-and-conflict problem the first post opens with. The posts' value here is subtractive.
+- *Everything authored in or about the repo is first person* (Craig's instruction), with one carve-out: a comment describing what the code does stays third person, since there the code is the actor.
+- *No unmerging home.* Its domains are already separated by tag (24 finances, 18 kit, 17 jrestate). The real problem is a tag namespace flattening four orthogonal axes, and cross-domain priority is a judgment no scheme can make — splitting projects hides the question rather than answering it.
+
+** Data Collected / Findings
+
+- *Path-scoping works at user level*, confirmed by =/context= in a live work session: 17 generic rules listed, the three path-scoped ones absent. Deterministic glob match, so no trial needed for that tier.
+- *User-level and project-level rules both load, project wins.* work and =.emacs.d= carried 19 byte-identical duplicates, and a stale project copy silently overrode the fresh global rule.
+- *My token estimates were 45% low.* Real ratio 2.28 tok/word. =commits.md= was 12,800 tokens, not the ~7,000 I claimed. =/context= reported the true per-file numbers the whole time and I used a word-count estimate because it was easier to compute from inside the repo.
+- *Two loading paths, not one.* Memory files arrive via the harness; =protocols.org= and the workflows are read by startup and land in Messages. They shrink by editing the workflow, not by scoping a rule.
+- *41 execution/hygiene workflows against 6 discovery/design.* The system is heavily built on the half of the problem that got easier.
+- *The instructions don't practice what they demand:* =commits.md= argued terseness at 5,561 words, =interaction.md= bans bold while the rules carry 591 bold markers, =testing.md= argues TDD across eight more rows of rationalizations.
+- *Two of my own mechanical guards failed the same day, both certifying success while doing damage.* =wrap-org-table.el= reflowed a table into a worse shape and =lint-org= then passed it; the wrap-teardown hook consumed a two-hour-old sentinel and killed Craig's live work session.
+
+** Files Modified
+
+Seven commits, all pushed, velox synced throughout. =6c1ea8b= peer-reasoning rule + Chrome convention + KB probe fix. =0adcb1a= =paths:= frontmatter on the three file-type rules + the lint checker that catches prose/frontmatter mismatch. =7ea1d7b= generic rules no longer ship per project, sweep + gitignored session anchor. =79ed3b0= the three rightsizing docs. =2c664cb= =hooks/session-start-disarm.sh= for the sentinel bug. =d74d98d= docs corrected against live measurements. =931f364= =commits.md= → invariant core + =publish= skill. =2f45b6e= =testing.md= → directive core + =testing-standards= skill, approval-gate signal fixed, first-person directive.
+
+** Next Steps
+
+Everything remaining needs Craig's decisions rather than execution — see the =[#B] Finish context-engineering rightsizing= task and the =[2026-07-27]= reminder. In order: reconcile the three working docs (one commit behind), then C1 (=verification.md='s honesty core vs the over-verification warning), =interaction.md=, the TDD rationalization table, and D3 (which approval gates are preference vs guardrail).
+
+Also open: the work sentry triage split and the recurring-loop proposal, both filed =[#B]= with their reviews. The sentry spec review is still waiting, now two weeks old.
+
+KB: promoted 2 / consulted no
+
+* Session Log
+
+** Startup — 2026-07-27 10:25 CDT
+
+Ran startup. Rulesets already current; =make install= had nothing new to link; project repo clean at f2609d9 with no upstream drift. =.ai/= synced from templates (no churn — the sync is a no-op mirror refresh in this repo). Previous session wrapped cleanly (no session-context anchor present).
+
+Startup signals: 6 top-level tasks unreviewed for >7 days; roam inbox empty; KB at 106 =:agent:= nodes but the best-practices node path resolved empty (=rg -l 'agent-kb-best-practices'= found nothing — worth checking whether that node exists); no spec-sort or host-identity flags; language-bundle sync silent.
+
+Five new inbox handoffs arrived since the last wrap. Read all five and ran the skeptical review on each before surfacing dispositions.
+
+Disposed of one without asking: home's 07-26 10:21 file was a pure FYI acknowledging that the parked MCP-registry spec decision and the separate memory-auditor track matched its handoff. It asked for nothing, so it needed no reply and no approval — deleted it. Four remain, all shared-asset or convention changes, all waiting on Craig's approval per the inbox engine's core §2.
+
+Skeptical-review conclusions on the four pending:
+
+- *archsetup publish-lock* — design sound, acceptance checks testable. Three gaps: TTL sizing has to survive an indefinite human approval wait (refresh-on-re-entry covers the agent, not a Craig who steps away); the blocked second session's behavior (wait / defer / stop) is unspecified; and it's a real build, not a quick edit. Recommend filing =[#B] :feature:=.
+- *home Chrome convention* — protocols.org already prefers google-chrome-stable over xdg-open, so the new parts are =--new-tab=, multi-URL, and the confirmation line. The confirmation half contradicts the existing =&>/dev/null &= form, which discards exactly the message to be verified. Recommend applying with a foreground-when-running / background-on-cold-start reconciliation.
+- *work sentry triage correction* — Craig's 07-27 correction supersedes his 07-21 ruling; today's work fire missed a Hayk DM and a Kostya PR-review request. The gap is that the current rule excludes by category (mail / messenger) and the new split is work-vs-personal, which category can't express. Shipping plugins: cmail, personal-gmail, personal-calendar, telegram, github-prs — no general work-mail plugin, so work's source is project-specific. A denylist of personal plugin names fails open on the next personal source added; a per-plugin eligibility declaration is the durable shape, and that's a design call. Recommend filing =[#B] :bug:= (Major × most-users-frequently = P2).
+- *work peer-reasoning rule* — approved exact text, well-formed. Two notes: it's a reasoning contract in a file scoped to communication style (the framing line should widen), and "process serves the outcome" sits one reading away from licensing deviation from the mandatory gates. Its own wording says surface-before-proceeding, so no edit needed, but that's the line to watch. Recommend installing as written.
+
+** Inbox pass applied — commit 6c1ea8b
+
+Craig approved all four dispositions plus the probe fix. Two corrections from him along the way: I had inverted the render-merge guard (numerals belong to the options list, dashes to every other enumeration in the same message — I did the reverse), and processed items shouldn't be left sitting in =inbox/=.
+
+Shipped: the peer-reasoning section at the top of =claude-rules/interaction.md= with the file's framing line widened; the Chrome convention rewritten in canonical =protocols.org=; the KB best-practices probe switched from a content grep to a filename =find=. Filed two =[#B]= tasks (sentry triage split, repository publish-lock), both stamped =:LAST_REVIEWED: 2026-07-27=. Swept the 40-file =PROCESSED-*= backlog out of =inbox/= along with the four handoffs; =inbox-status= now reports 0. Replies sent to archsetup, home, and work.
+
+*The review caught my own error.* I had written that Chrome's confirmation line prints to stderr and told every project to capture it with =2>&1=. It prints to *stdout*; stderr is empty. Verified both directions on ratio before correcting. An agent following the original text would have captured stderr, seen nothing, and concluded the tab failed to open — the exact silent-failure shape as the KB probe it shipped alongside. I asserted a stream rather than checking it, inside the same change that told others to verify. Side effect: four =about:blank= tabs opened in Craig's live browser during the check.
+
+Deliberate departure recorded: =route_recommend= returned =work strong= for the sentry task, but the work happens in rulesets' canonical =sentry.org=, so it's a local keeper and I left it unstamped rather than letting the wrap router offer to ship it away.
+
+Possible KB promotion at wrap: an identifier that lives only in a filename is invisible to a content search, and the lookup fails *silently* rather than erroring. Adjacent to the existing enumerate-vs-discover node but a distinct failure surface. Two instances in one commit (the KB probe, the Chrome stream) argue it generalizes.
+
+Startup-workflow bug found while checking the KB nudge: Phase A resolves the best-practices node with =rg -l 'agent-kb-best-practices' "$ra"=, which greps file *content*. The node's slug lives in its filename, so the probe returns empty and the contribute nudge points at nothing — in every project, every session. The node exists at =~/org/roam/agents/20260620232112-agent-kb-best-practices.org=. Synced-workflow change, so it waits on approval too.
+
+** Pushed and synced velox
+
+Pushed 6c1ea8b to origin/main (ahead-only, reconciled immediately before). On ratio, so velox needed the pull: it fast-forwarded and =make install= linked three things it had been missing since 2026-07-25 — the Codex =hooks.json=, =rulesets-write-boundary.py=, and =git-worktree-gate=. That drift is exactly the one-time-setup case =daily-drivers.md= names: the files traveled with the pull, but nothing re-runs the installer, so the symlinks only land where someone runs it. A new Codex session on velox will now hit the hook review/trust prompt, which was already on the 2026-07-25 next-steps list.
+
+** Context-engineering rightsizing — analysis and rollout plan
+
+Craig supplied three Anthropic posts (the 2026-07-24 Claude 5 context-engineering post, the Opus 5 prompting guide, the 2026-07-06 Fable field guide) and asked for a review, proposals, and a consistency audit of what this repo ships downstream. Then he reframed twice, and both reframes were better than the question I'd been answering.
+
+*First reframe:* consider the files as *his prompts*, not my context. That changed the finding. My first pass measured the always-loaded surface (32,123 words — =claude-rules/= 25,386 + =protocols.org= 6,620 + CLAUDE.md 117, roughly 40k tokens before the user's first word) and proposed shrinking it. Read as a map he hands every project, the finding is different: 41 execution/hygiene workflows against 6 discovery/design, seven to one. That ratio was right when the risk was the model doing things wrong. The field guide's claim is the bottleneck moved to the human's ability to clarify unknowns, so the system is heavily built on the half that got easier.
+
+*Second reframe:* metrics per claim, not one go/no-go. Turns the rollout into a set of separable testable claims rather than one bet.
+
+Three checkable "doesn't practice what it demands" findings: =commits.md= argues terseness at 5,561 words (longest file in the set); =interaction.md= bans bold in chat while the rules carry 591 bold markers; =testing.md= mandates TDD then argues eight more rows against rationalizations.
+
+*The finding that changed the plan:* the harness system prompt already carries most of what the Opus 5 guide recommends adding — its task-scope block, correction-narration block, and subagent cap are present nearly verbatim, and post 1's replacement comment guidance is present as the post's own new wording. So applying the posts additively would make the duplicate-and-conflict problem worse. The posts' value here is subtractive. It also exposes a third dedup axis nobody has audited: =claude-rules/= against the harness prompt, invisible from inside the repo.
+
+*Pilot selection rule* (the part that matters more than the list): the six pilot files were chosen because a silent miss is *detectable*, not because they're small. Four have a mechanical checker (=lint-org= =org-table-standard=, spec-board grep, =spec-review=), two produce an error Craig sees in seconds. =daily-drivers.md= and =emacs.md= were considered and held back — low risk, but a miss surfaces too slowly to learn from inside the trial window.
+
+Artifacts in =working/context-engineering-rightsizing/=: =proposals.org= (P1-P6, conflicts C1-C2, the from-your-side-of-the-desk section), =rollout.org= (Phases 0-8, decisions D1-D7, target trajectory), =metrics.org= (claim-by-claim testability, pilot go/no-go with the denominator rule, turn-back vs abandon triggers).
+
+Two honesty notes carried into the docs: I have a stake in arguing my own instructions should be shorter, so the plan weights mechanical detectors over my self-report; and about half the posts' claims aren't testable here without an eval harness, so those are labelled judgment rather than measurement so a future session doesn't mistake an adopted opinion for a tested result.
+
+Not started. Awaiting D1 (confirm pilot set) and D2 (skill index in the core).
+
+** Path-scoping shipped (0adcb1a) and work pre-synced
+
+The session's biggest finding: Claude Code scopes a rule by a =paths:= field in YAML frontmatter, and none of the 20 rules had one — even though three already declared a file-type scope in their =Applies to:= prose line. So =todo-format.md= (4,494), =org-tables.md= (464), and =emacs.md= (923) loaded into every session in every project, contradicting their own first line. 5,896 words. Fixed by adding the frontmatter, plus a =lint.sh= checker that warns when prose names a concrete extension without matching frontmatter (flags exactly those three, nothing else), plus teaching the heading check to skip a frontmatter block. Always-loaded rules surface: 25,386 → 19,505.
+
+Also confirmed from the docs: user-level and project-level rules *both* load, and project rules take priority. So work and =.emacs.d= carry 19 byte-identical duplicate copies, and a stale project copy overrides a fresh global one — which is exactly what was happening to work's =interaction.md= between this morning's commit and its next startup.
+
+Pre-synced work via =scripts/sync-language-bundle.sh ~/projects/work= (rulesets' own installer, run early rather than waiting for work's startup) so Craig's next work session is a valid test rather than one running the set it loaded before the sync. Verified: all four files now match canonical, frontmatter present, and work's =.claude/= is gitignored there so nothing was dirtied.
+
+Open question the next session answers: does =paths:= frontmatter apply to *user-level* rules or project-level only? The docs don't draw the distinction. =/context= in a fresh session settles it — if =todo-format.md= is absent from Memory files until an org file is opened, it works. If it's listed, the frontmatter is inert (no harm) and semantic skills are the only route.
+
+Not done: the double-load fix. Removing the 19 duplicates means changing what =install-lang= pushes into projects, and there may be a teammate-facing reason for them. Surfaced as Craig's call, not urgent — wasteful, not harmful.
+
+** De-duplicated the rules layer, unblocked sync (7ea1d7b, 79ed3b0)
+
+Craig confirmed no teammates depend on the per-project rule copies, so I removed them. =install-lang.sh= no longer copies the generic rules; =sync-language-bundle.sh= sweeps the ones earlier installs left, guarded on the global rule existing so a machine mid-bootstrap isn't stranded with none. Swept 20 files each from work and =.emacs.d=, leaving only their language rules plus work's =publishing.md= overlay. Three existing tests encoded the old contract and were rewritten; the generic-drift test now asserts sweep-not-repair, which is the stronger fix since the drifted copy outranked the global rule while it existed. Four new tests cover the sweep, the two keep-cases, and the no-global-rule guard.
+
+Also gitignored =.ai/session-context.org= and =.ai/session-context.d/=. This repo tracks =.ai/=, so the live anchor read as untracked all session and =git-worktree-gate= reported rulesets sync-blocked — meaning every other project skipped its rulesets pull until wrap, every session. Craig spotted the blocked state and inferred it was why I pre-synced work; it wasn't (rules load at launch, before the startup sync runs, which was the real reason), but chasing his inference found the anchor problem, which was the better bug.
+
+Corrections from Craig this stretch: the goal is output quality first, token reduction second — my docs led with the wrong number and P4 (effort reduction) should be demoted or dropped since it trades quality for cost. And all authored prose goes first person; I amended the first commit rather than leaving it. Code comments stay third-person by agreement, since they describe what the code does for the next reader.
+
+Docs not yet updated for either the goal reordering or the last two hours of findings (path-scoping, the double-load, the harness overlap). That's the next task.
+
+** Inbox: archsetup ack
+
+archsetup acknowledged the publish-lock acceptance and the three implementation gaps, confirming the decision stays closed on its side. Pure FYI, nothing asked, no reply owed. Deleted it. Inbox back to zero.
+
+** Killed Craig's work session with my own hook, then fixed it (2c664cb)
+
+Craig's 13:20 work session was blocked repeatedly and then had its terminal closed under it. The cause was mine, from Saturday's clean-wrap work.
+
+=wrap-it-up= drops =/tmp/ai-wrap-teardown-<project>= so the =Stop= hook tears down once the wrap certifies clean. I deliberately made a failed certification *preserve* the sentinel, so a wrap blocked by a dirty tree could retry on a later stop. I never bounded that retry to the session. work's 11:37 wrap left an uncertified sentinel armed; the 13:20 session's stops were all blocked by it failing certification; then startup's two commits (task filing, template sync) made the tree clean, the next stop certified, and =cj/ai-term-quit= killed the tmux session mid-work.
+
+Two others were armed and dangerous at the same moment: archsetup's since Saturday 15:02 on a live attached terminal, and home's from 13:21 on a live session. Disarmed all three by hand (backed up to =/tmp/disarmed-sentinels=) before writing any fix, since both were minutes from the same fate.
+
+Fix: =hooks/session-start-disarm.sh= clears the project's sentinels at =SessionStart= — a new session means the wrap that armed one is gone. Within-session retry is untouched (the hook only runs at session start) and a test pins that so the deliberate behavior isn't lost to the fix. Four tests on the disarm including project-scoping, one on the retry. Wired into =.claude/settings.json=, installed on both machines, =wrap-it-up.org= documents the session-scoping with the worked failure.
+
+Diagnostic note worth keeping: I found it by reading work's own crashed session anchor, which showed startup completing normally and then stopping dead, plus its git log showing two commits at 13:21 — the exact moment the tree went clean. The anchor being left behind by the interrupted session is what made the timeline reconstructable. That's the crash-recovery purpose earning itself.
+
+** /context settled both open questions; docs corrected (d74d98d)
+
+Craig ran =/context= in work. Memory files lists 17 generic rules; =todo-format.md=, =org-tables.md=, and =emacs.md= are absent, and only =python-testing.md= and =publishing.md= come from the project's own rules dir. So *path-scoping works at user level* and *the de-duplication holds*. Both were open.
+
+Three corrections the live numbers forced:
+
+1. *My token figures were low by ~45%.* Real ratio is 2.28 tok/word, not the ~1.3 I assumed. =commits.md= is 12,800 tokens (I said ~7,000); =claude-rules/= was ~57,800/session before today, now 44,410, with 13,390 path-scoped out. Worth naming the actual error: =/context= reports per-file token counts and I used a word-count estimate instead because it was easier to compute from inside the repo. The instrument existed the whole time.
+2. *Two loading paths, not one.* Memory files arrive via the harness at session start. =protocols.org= and the workflows are *read by startup*, so they land in Messages and never appear under Memory files. They shrink by editing the workflow, not by scoping a rule. My "always-loaded surface" number conflated them.
+3. *The harness's own suggestion* names =commits.md=, =testing.md=, =MEMORY.md= as the top three to prune — independently the same Phase 4 list I'd proposed.
+
+Because a glob match is deterministic, the remaining work splits: path-scopable rules ship with no trial (=docs-lifecycle.md= on =docs/**= is next), and only semantic-condition rules need the skills route and the stop conditions. =commits.md= is the real test there — largest single item, and almost all publish machinery that only applies when a commit is in play.
+
+Recorded a caution the confirmation doesn't cover: path-scoping fires on a *read* of a matching file, so creating a new org file from scratch never triggers =todo-format.md=. Edits are safe (Edit requires a prior read).
+
+Also folded in Craig's goal correction (quality first, tokens second): P4/Phase 8 dropped outright since lowering effort trades quality for cost, P5 promoted since positive-framing-over-prohibition is what targets guardrails working against output.
+
+** Split commits.md: 12,800 tokens → 2,342 always-loaded (931f364)
+
+Craig picked the commits.md split over docs-lifecycle after I checked the latter and found I'd overstated it — =docs-lifecycle.md= scopes to "any project carrying a docs/ tree," a *project-level* condition a glob can't express, and 2 of its 6 trigger points are creation cases a read-triggered path rule misses. Only three rules ever named a concrete extension and all three are already converted, so there is no other clean path-scope candidate.
+
+The split line is *blast radius*, not size. Stayed always-loaded (1,027 words / ~2,342 tokens): author identity, the no-AI-attribution ban, the generated-document byline rule, the public-artifact content-scope rules, and "If You Catch Yourself." Moved to =publish/SKILL.md= (4,871 words): message format, Voice and Focus, PR description structure, Review and Publish Steps 0-2, the three review shapes, hook authorization, merge strategy, the pre-commit checklist.
+
+Why that line: if the skill fails to trigger I don't know the flow and have to be told — visible and recoverable. I don't silently commit with AI attribution, because that guard never moved. Only the recoverable half rides the skill-triggering bet, which is what let this ship without waiting on the pilot.
+
+*Verified by using it.* The skill registered mid-session and I invoked =/publish= to publish its own commit; it loaded with the full flow present. Content conserved and checked rather than assumed: 5,561 words in, 5,898 across both files (delta = frontmatter + the pointer added to the core). Repointed five cross-references in =voice=, =review-code=, =inbox.org=, and =no-approvals.org= that named moved sections.
+
+Always-loaded rules surface: 44,410 → ~33,950 tokens. Started the day at ~57,800.
+
+Noted and deliberately not done: =publish/SKILL.md= is a single 4,871-word blob, and both posts argue a long skill should use progressive disclosure internally. It loads on demand now, which is the win worth taking; splitting it further is its own change.
+
+Also surfaced: the Step 2 =.ai=-tracking heuristic misfires here. It reads tracked =.ai/= as "shared team repo → skip the approval gate," but rulesets tracks =.ai/= as a committed mirror while being a private single-user repo. I kept asking rather than skipping, and flagged it to Craig.
+
+** testing.md split, gate fixed, first-person directive added (2f45b6e)
+
+Three changes. *testing.md split* the same way as commits.md — by what has to be resident, not by size. Core keeps TDD-is-default and the three-category requirement (347 words), because those fire *before* any code is written, which is exactly when no skill has been summoned. Everything else → =testing-standards= skill (2,903 words): characterization recipes, per-category detail, property/mutation testing, pyramid, integration rules, naming, test-quality and mocking rules, coverage targets, spike exception, anti-patterns.
+
+*Approval-gate fix.* The publish flow decided whether to ask by checking whether =.ai/= is tracked, as a proxy for "team repo." Wrong in the direction that matters: rulesets, home, and work all track =.ai/= and all three are private single-user repos, so the rule skipped the gate on Craig's three most-used projects. Now checks whether any remote is on a host other than cjennings.net. Verified both directions including a synthetic GitHub remote. Every current project → gate applies, which matches how the flow has actually been run all session.
+
+*First-person directive* added to the always-loaded core, at Craig's instruction. One existed for commit bodies/PR prose but it moved into the publish skill, and it never covered code comments at all. Now: everything authored in or about the repo is first person, with one carve-out — a comment describing what the code *does* stays third person, since there the code is the actor.
+
+Also split =publish/SKILL.md= internally: PR descriptions + the three review shapes → =references/pull-requests.md=, since a plain commit never needs them. SKILL.md 5,012 → 3,888 words.
+
+*Surface: ~57,800 tokens this morning → ~28,949 always-loaded now* (plus 13,461 path-scoped). Largest remaining: =interaction.md= 3,828, =verification.md= 3,388, =commits.md= core 2,804, =subagents.md= 2,373, =cross-project.md= 2,305.
+
+Risk recorded rather than buried: testing.md's margin is thinner than commits.md's. If =testing-standards= fails to trigger mid-test-writing I lose the mocking-boundary rules — a quality regression, visible in review, but a real bet where commits.md's moved half was purely procedural. Also moved the TDD rationalization table rather than cutting it; the posts say that kind of over-argument is counterproductive now, but deleting Craig's defense against me skipping TDD is his call.
diff --git a/.ai/sessions/2026-07-29-06-36-adversarial-review-flow-and-telegram-fixes.org b/.ai/sessions/2026-07-29-06-36-adversarial-review-flow-and-telegram-fixes.org
new file mode 100644
index 0000000..12cbe3d
--- /dev/null
+++ b/.ai/sessions/2026-07-29-06-36-adversarial-review-flow-and-telegram-fixes.org
@@ -0,0 +1,514 @@
+#+TITLE: Session Context — 2026-07-28
+#+AUTHOR: Craig Jennings
+#+DATE: 2026-07-28
+
+* Summary
+
+** Active Goal
+
+Started as inbox triage on a telegram-plugin bug report and became two things: shipping the cross-project fixes that arrived overnight, then designing and dogfooding a mandatory isolated adversarial review before every commit — which immediately found real defects in its own design and in everything filed afterward.
+
+** Decisions
+
+- *Merge colliding fixes rather than sequence them.* The parked down-is-launch diff still carried the bad =loadChats= call and cited the segfault gotcha the other fix rewrites. Applying either alone would have shipped a file arguing against itself.
+- *"Adversarial", not "hostile"* (Craig). An agent told to attack manufactures findings, so the stance carries a substantiation floor: a finding not substantiated against the diff is dropped.
+- *Re-review until the reviewer approves* (Craig's addition, the thing I had missed). Same reviewer continued, not a fresh one — a fresh reviewer can't tell an addressed finding from one that never existed. Bounded at three rounds or first recurrence.
+- *Dispatch on every commit*, with the reviewer's own Phase 0 ruling triviality. A floor written as "small" or "mechanical" puts the judgment back with the author, whose judgment is the thing being checked.
+- *Pass the requirement source, withhold the rationale.* A ticket is not the author's model; it was written first and by someone else, so it's the only input that can contradict the author's claim.
+- *=cycle=, not =pass=, for one sentry loop* (Craig). home proposed =pass=; =sentry.org= already uses it as a numbered noun for the eleven hygiene passes, so =Pass 11= would have collided with =pass 12=.
+- *Drop the =references/= link rather than sync the directory.* The four calendar workflows already travel and already carry the recipes.
+- *Strip the wrap-org-table task to Verified / Open questions* after its review loop bounded out. The measurements were never what failed.
+
+** Data Collected / Findings
+
+- *The telegram bug.* =(telega--loadChats 'main)= sends a bare symbol on the wire; =tdat_plist_value= (=telega-dat.c=) accepts only =(=, =[=, ="=, =-=, digit, =t=, =:=, =n= and calls =assert(false)= on =m=. Verified against telega's source at four points rather than trusting the handoff. Exposure was manual triage only — sentry excludes messengers, so home's eleven overnight cycles never loaded the plugin.
+- *=wrap-org-table.el= splits logical rows*, and =lint-org= doesn't merely miss it — it *causes* it. =lint-org.el:424= calls the same broken predicate, so it reports the tool's own correct output as "missing rule between rows — wrap-org-table.el reflows it" when nothing is missing, then reports the corrupted result clean. Idempotence is broken: the tool corrupts its own output on a second run.
+- *The isolated reviewer earned its keep on its first four uses*, finding: that withholding the ticket made my claim self-certifying; that my =subagents.md= override reaffirmed the Prompt Contract field that would destroy the isolation; a fourth verdict (=Needs Discussion=) I'd asserted didn't exist; and four successive wrong root-cause analyses on the table bug.
+- *rulesets is itself exposed* to the table bug: =todo.org='s four-row attachment-sanitization table. Don't reflow until fixed.
+- *Seven =../../= link sites* across four synced workflows resolve only in rulesets. =scripts/lint.sh='s =check_md_links= was built for that class and misses them because it matches markdown syntax only.
+
+** Files Modified
+
+Seven commits, all pushed, velox synced after each. =bff0138= merged telegram fixes. =43a4cf7= post-load liveness check. =614e3b1= removed finished working dirs. =ca508a1= filed three handoff findings. =f3f5bfd= the =fire= → =cycle= rename (72 sites plus three that had leaked outside =sentry.org=). =3a933a2= the =references/= analysis. =5999f88= dropped the dead link and deleted the stale file behind it. =ecd5d7b= filed the wrap-org-table bug.
+
+Rules changed: =publish/SKILL.md= Step 1 rewritten (dispatch contract, four defined verdicts, the loop, bounds), =review-code/SKILL.md= (two levels of dispatch, adversarial contract, re-review mode), =claude-rules/subagents.md= (Isolation Override; Prompt Contract field 2 inverts), and the three unattended callers taught to park.
+
+** Next Steps
+
+- *Three of the four items Craig queued are untouched*: the winvm =[#C]= lint defects, the context-engineering rightsizing (needs his four decisions), and the sentry spec deep read (two weeks old).
+- *Rule gap found by using the rule*: =Needs Discussion= exits to the user, but nothing says what happens after the user answers — whether the round counter resets. I treated it as a fresh review; that judgment isn't written down.
+- *Item 2 is now qualified*: its fix says "run =wrap-org-table.el=", and that tool has a live corruption bug. The specific table is safe, but verify the output rather than trust it.
+- Four =[#B]= bugs filed tonight and unstarted: the table splitter, the =../../= links, plus the two carried in.
+
+KB: promoted 1 / consulted no
+
+* Session Log
+
+** 11:55 — Startup
+
+Ran startup. Rulesets already current, project repo clean and current, =make
+install= had nothing new to link, =.ai/= synced from templates. No crash anchor
+— previous session (context-engineering rightsizing, 2026-07-27 17:02) wrapped
+cleanly.
+
+Findings: 6 tasks unreviewed >7 days; roam inbox holds 4 items; KB at 108
+=:agent:= nodes with nothing matching this project. Spec-sort and host-identity
+probes silent. Language-bundle check silent.
+
+** 12:05 — Inbox: the telegram segfault root cause
+
+Four new inbox files from =.emacs.d=, two pairs: a 06:15 intro note + plugin
+file, then a 07:21 correction + superseding plugin file. The correction retracts
+one secondary claim from the 06:15 write-up (that the "19 of ~50 chats" reading
+was truncation caused by the bug — it wasn't; 19 is the real account size,
+measured by work at the wire level). Root cause and fix unchanged.
+
+The proposal: =triage-intake.telegram.org= Step 1 calls =(telega--loadChats
+'main)=, and that bare symbol kills =telega-server= outright.
+
+I verified the whole chain against telega's own source rather than taking the
+handoff's word for it (=elpa/telega-20260706.2147/=):
+
+- =telega--loadChats= (telega-tdlib.el:2190) drops its argument straight into
+ the request as =:chat_list= with no conversion. Confirmed.
+- The C parser =tdat_plist_value= (server/telega-dat.c:466) accepts only =(=,
+ =[=, ="=, =-=, a digit, =t=, =:=, or =n= to start a value; anything else
+ prints "Unexpected char '%c' in plist value" and calls =assert(false)=.
+ =main= starts with =m=. Confirmed, and the accepted-char list in the handoff
+ is exactly right.
+- telega's own callers all pass the object: telega.el:290, telega.el:295,
+ telega-tdlib-events.el:516. Confirmed.
+- The symbol shorthand lives in a different layer — telega-filter.el:472 and
+ telega-folders.el:99 convert =(eq cl-fspec 'main)= to ='(:@type
+ "chatListMain")=. Confirmed.
+
+Every claim holds. Grepped all workflows for other bare-symbol arguments to
+=telega--*= wrappers: only the two sites this diff already fixes.
+
+*The complication I found.* There is already a parked =[#B]= VERIFY (todo.org:136,
+from =.emacs.d= 2026-07-24) proposing a different fix to this same file — the
+down-is-launch fix, with a prepared diff in
+=working/triage-telegram-down-launch/=. Its proposed file still carries the bad
+=loadChats= call at its lines 52 and 122, and its third hunk adds prose citing
+"tdlib segfaults in native mode (SEGFAULT gotcha below)" — pointing at the very
+section this new handoff rewrites to say the crashes were our bug, not tdlib's.
+Applying either one alone leaves the file half-right. They need merging, not
+sequencing.
+
+Also: home and work both declare =telegram= in =:TRIAGE_SOURCES:=, so both have
+been killing telega-server on every sweep. Work already patched locally and
+verified at the wire level. Home has not been told.
+
+** 11:58 — Staged the batch, closed the loops
+
+The Stop hook counted the four files still sitting in =inbox/=. The triage was
+done; what remained was Craig's merge decision, not mine. So I staged all four
+into =working/triage-telegram-segfault-rootcause/= (the 07:21 pair as
+=.proposed= + correction note, the 06:15 pair kept as superseded context — its
+blast-radius and follow-up sections aren't repeated in the correction). Inbox
+back to clean, =inbox-status= rc=0.
+
+Left =working/triage-telegram-down-launch/= untouched: the parked VERIFY's body
+links its =proposed.diff= by path, and moving it would break the link before
+Craig has decided anything. If he takes the merge, that consolidates then.
+
+Replied to =.emacs.d= — confirmed the verification, and told them the one thing
+they couldn't see: their own 2026-07-24 parked diff collides with this, both in
+the stale =loadChats= call it still carries and in the native-mode prose it adds
+citing the gotcha this rewrites. Also declined their suggested bare-symbol lint:
+one consumer file, two call sites both fixed, so the stated rule is cheaper than
+a checker with a single input.
+
+Notified home directly with the mechanism and the two-site fix, told it to patch
+locally rather than wait on the canonical, and carried the correction forward
+explicitly so it doesn't inherit the retracted truncation story.
+
+Nothing applied to the canonical. That still waits on Craig.
+
+** 12:10 — Craig picked the merge. Applied and committed.
+
+Merged both fixes into one version rather than sequencing them. Base was the
+segfault-corrected file, then the three parked hunks on top: the down-is-launch
+directive, the SCAN-FAILED-only-after-launch-attempted rewording, and =(setq
+telega-use-docker t)= restored to the Step 1 code block.
+
+The reconcile that made merging worth doing. The parked hunk's new comment said
+"tdlib segfaults in native mode (SEGFAULT gotcha below)", pointing at the
+section the other fix rewrites to say those deaths were our own bad argument.
+Left alone the file would have argued against itself. I changed the Step 1
+comment to state plainly that the two are separate concerns (the deaths happened
+*in* docker mode, so docker mode is neither a defense against the loadChats bug
+nor evidence for itself), and reworded the Quick Reference line from "tdlib
+segfaults outside docker mode" to "crashed in native mode (2026-06-09)" with the
+same disambiguation.
+
+That reword also removed a host-identity violation I hadn't gone looking for.
+The original asserted "Craig's daemon currently has telega-use-docker nil" — a
+mutable machine fact stated as fixed in a synced doc. I checked the actual
+default (=telega-customize.el:514=, =defcustom telega-use-docker nil=) and wrote
+the durable claim instead.
+
+Verified: both live call sites use the TL object, the two remaining ='main=
+occurrences are inside the gotcha prose describing the bug, lint-org clean on the
+changed file, mirror synced, =make test= green before (exit 0) and after (exit
+0).
+
+todo.org: closed the parked =**= VERIFY as =DONE= + =CLOSED:= per todo-format.md
+with the merge rationale in the body. Promoted its =***= engine child (SCAN
+FAILED must not advance the sentinel) to top-level =**= VERIFY so it doesn't get
+buried under a DONE parent. Kept its =:LAST_REVIEWED: 2026-07-24= rather than
+stamping today — I moved it and judged it separate, but nobody re-derived its
+content, so the older date keeps it honest.
+
+Review: Approve, no Critical or Important. Two Minor, both surfaced rather than
+fixed. The gotcha now advises a post-load =(process-live-p ...)= check that the
+Step 1 recipe doesn't actually do, and adding it would extend the recipe past the
+two fixes Craig approved.
+
+Committed =bff0138=. Not pushed — that's a separate confirmation.
+
+** 12:20 — home replied, and corrected my urgency read
+
+home accepted, patched both call sites locally, and re-verified the diagnosis
+independently rather than trusting it. Useful correction back: home declares
+telegram in =:TRIAGE_SOURCES:=, but sentry excludes messengers from triage
+intake, so the plugin never loaded on a sentry fire. Eleven overnight fires ran
+clean against the broken file. I had assumed the sweeps were affected; the real
+exposure is manual triage intake only.
+
+Told home its stopgap won't be reverted into a broken state — the next rsync
+replaces it with canonical content carrying the same fix. On this machine that
+lands as soon as its next startup runs, since the rsync reads the local rulesets
+working tree. velox needs the push.
+
+Inbox back to zero.
+
+** 14:10 — Pushed, and closed the velox gap
+
+Pushed =1675613..bff0138= to origin after the pre-push reconcile (still 1 ahead,
+0 behind).
+
+=.emacs.d= replied while the push was in flight. It had already verified bff0138
+here, re-run its own workflows rsync, and confirmed the corrected form landed.
+It withdrew the bare-symbol lint suggestion, conceded the home omission, and
+flagged one real gap: bff0138 was committed but not pushed, so velox stayed
+exposed. That was true when written and stale by the time it arrived.
+
+Checked velox over tailscale (this host is ratio, per =uname -n=). It was 1
+behind / 0 ahead and sync-safe, so I fast-forwarded it through the same
+=git-worktree-gate sync-safe= check startup uses. Velox is now at bff0138 and its
+workflow file carries the corrected call, with the only bare ='main= occurrences
+inside the gotcha prose. Both daily drivers covered.
+
+Corrected read carried into both replies: the exposure was manual triage intake
+only, not the automated sweeps, because sentry excludes messengers.
+
+** Open follow-ups (surfaced to Craig, not acted on)
+
+1. The gotcha tells callers to check =(process-live-p (telega-server--proc))=
+ after a load, but the Step 1 recipe doesn't do it. Now that the corrected call
+ shouldn't kill the server, that check is what would catch a regression. Left
+ out deliberately as scope creep past the two approved fixes.
+2. Both =working/triage-telegram-*= dirs are completed-task artifacts and want
+ filing per working-files.md. Revised read after checking: delete both
+ outright. Every file is tracked (=b19d420= and =bff0138=), so git holds them
+ permanently and a copy in =assets/= would only duplicate history. Nothing
+ links to them.
+
+** 15:00 — Second inbox round: .emacs.d self-correction + winvm lint findings
+
+=.emacs.d= wrote back to say it had overcorrected on home: it accepted "home was
+in the blast radius" and then recorded that home "had been killing telega-server
+on every sweep too", which home's own sentry data refutes. It fixed its task
+record rather than leaving it. I told it the pattern wasn't one-sided — I made
+the same move this morning, estimating home's blast radius instead of measuring
+it, and home's data is what corrected me. It also offered the emacs-side half of
+a completed-vs-truncated signal, which it has filed as =[#C]=, if the
+=process-live-p= recipe change lands.
+
+=winvm= sent a link-integrity pass with three findings, all reproduced against
+the rulesets source rather than only its local copy. I verified all three:
+
+1. =protocols.org:273= links =references/calendar-reference.org=, but the rsync
+ set is only =protocols.org=, =workflows/=, =scripts/=. Dead link in every
+ consuming project. home and =.emacs.d= have no =.ai/references/= at all.
+2. =retrospectives/PRINCIPLES.org:38= violates the org-table standard.
+ =lint-org= confirms, checker =org-table-standard=.
+3. =protocols.org= lints 8 mechanical + 19 judgment =misplaced-heading=, all
+ from Markdown =**bold**= in an org file. 48 bold spans, 14 line-initial.
+
+The check winvm couldn't run: adding =references/= to the sync brings =--delete=
+with it, which would destroy project-owned files there. work is the only project
+with a =.ai/references/= and its copy is byte-identical to the source, so nothing
+would be lost. That clears the path to sync-it over drop-the-link.
+
+One refinement back to winvm on finding 3: the 8 mechanical hits are would-fix,
+and the 14 line-initial bold spans are exactly what =lint-org --fix= would
+rewrite without knowing they're emphasis rather than headings. So that half is
+not safe to run mechanically even though the count suggests it is.
+
+Filed as =[#B] :bug:= (the dead link, Minor x every-project-every-sync = P2) and
+=[#C] :chore:= (the two cosmetic defects, P3), both stamped =:LAST_REVIEWED:=
+today since I graded them today. Verified todo.org's lint counts are unchanged
+from the pre-edit baseline (mechanical=2, judgment=12, both pre-existing and
+already in =inbox/lint-followups.org=).
+
+Inbox back to zero. todo.org is left uncommitted deliberately — Craig has a
+pending decision that will likely touch it again, so batching beats a churn
+commit.
+
+** 18:45 — Craig took both follow-ups. Liveness check staged.
+
+Added the liveness check to the Step 1 load call. It now returns ='server-died=
+instead of an unconditional ='loaded=, and new prose routes that into the
+existing SCAN FAILED definition rather than inventing a category: a server that
+dies during load leaves a thin hash, which reads exactly like a quiet account,
+which is the same false all-clear the down/not-loaded rule already prevents.
+
+Self-review caught a real defect in my own first draft. I called
+=(telega-server-live-p)= bare, but Step 0 guards the same predicate with
+=fboundp= because telega may not be loaded. A launch that failed outright would
+have signalled void-function instead of returning the clean contract. Added the
+guard, matching Step 0's idiom. Verified the predicate is exactly the
+=process-live-p= expression the gotcha names (=telega-server.el:221=).
+
+Verified: parens balance at depth 0, lint-org 0/0, mirror identical, =make test=
+green (exit 0) on the final state.
+
+Not committed — waiting on the approval gate.
+
+** 18:48 — Third inbox round
+
+=.emacs.d= sent a closing FYI marked no-action, agreeing my framing of the shared
+failure (blast radius estimated rather than measured) named the trigger rather
+than the failure. Deleted without reply, since replying to "nothing owed back"
+is noise.
+
+home proposed renaming sentry.org's noun-sense "fire" to "pass", after Craig read
+its "nine fires" as nine emergencies: "I assume you mean nine crises, not nine
+loop cycles and I begin to get scared." The problem is real, well-evidenced, and
+reaches Craig directly through digest headings.
+
+But the proposed term is wrong, and the reason home gave for it is the
+disqualifier. =sentry.org= already uses "pass" as a precise numbered noun — the
+pass list, the Pass Runner, "eleven finding/hygiene passes", "pass 12". With
+exactly eleven hygiene passes, home's proposed =** Pass 11= heading collides with
+an existing referent. That trades a term Craig misreads as urgent for one that is
+genuinely ambiguous.
+
+Counter-proposed *cycle*: zero occurrences in the file, and Craig's own word in
+the quote home cited. Checked and rejected "sweep" (3 uses) and "run" (used as a
+noun). Filed =[#C] :chore:= with the grading and the collision analysis; replied
+to home with the counter-proposal.
+
+** 18:50 — Three commits, and the collision confirmed from live evidence
+
+Craig approved both follow-ups and the =cycle= term. Three commits:
+
+- =43a4cf7= the liveness check.
+- =614e3b1= removed both telegram working dirs. Filing by deletion, since every
+ file was already in git via =b19d420= and =bff0138= and an =assets/= copy would
+ only duplicate history.
+- =ca508a1= filed the three handoff findings with their gradings.
+
+home wrote back confirming the "pass" collision was real, and that it had already
+walked into it: its anchor now carries =** Pass 11= meaning the eleventh cycle,
+three lines from =pass 12 (solo-task implementation)= meaning the twelfth item in
+the pass list. Same file, two referents, introduced by its own normalization an
+hour earlier. It found that in live evidence faster than reading the file would
+have caught it.
+
+It was blocked on Craig's confirmation and had written a memory saying "pass", so
+I sent the confirmation immediately. The memory was the urgent half — a stale one
+teaches every future home session the ambiguity, where the anchor is one file.
+
+Recording Craig's approval flipped the sentry task to =:solo:=. The term was the
+only judgment it carried, and the completion check is objective, so it can ride a
+backlog run rather than waiting for someone to touch =sentry.org=.
+
+Pushed =bff0138..ca508a1=, velox fast-forwarded to match.
+
+** 19:45 — The cycle rename, and the leak home's scope missed
+
+home did its side first: renormalized its anchor by restoring the
+pre-normalization backup and re-running fire→cycle from clean, rather than
+reverse-mapping pass→cycle. That was the right call — reverse-mapping would have
+needed a judgment on every instance to separate its own conversions from genuine
+pass-list references, where re-running from clean makes it structural. It also
+corrected its memory and handed the canonical back.
+
+Did the canonical rename with a script rather than by eye: protect the verb sites
+by explicit pattern, assert zero unclassified =-ed/-ing= forms survive, then
+substitute. 72 noun instances converted, 4 verb sites untouched (=/loop= fires
+again, two "fires on approval", "record of what fired").
+
+*The leak home's scope missed.* The term wasn't confined to =sentry.org=.
+=wrap-it-up.org= said "a crashed fire", and =todo-cleanup.el= and its test both
+said "every sentry fire" — all three naming a sentry cycle. Renaming only
+=sentry.org= would have split the vocabulary across files. Found by grepping
+every file that mentions sentry, then re-grepping without a context window after
+the first pass truncated short-line matches and hid them.
+
+Verified: exactly 3 verb instances left in sentry.org, no placeholder leaked, the
+digest commit template now reads =<date> <time> cycle=, capitalized plurals
+handled, lint 0/0 on sentry.org, suite green (exit 0 — load-bearing here, since
+=todo-cleanup.el= and its test are under test). The two =wrap-it-up.org= lint
+findings are pre-existing and identical at HEAD.
+
+Committed =f3f5bfd=, pushed, velox fast-forwarded and verified. Notified home
+(with the leak it hadn't seen) and =.emacs.d=. Closed the task =DONE=.
+
+Four commits this session, all pushed, both daily drivers current, inbox at zero.
+
+** 20:00 — Roam inbox zero, then the adversarial-review design
+
+Roam scan: 3 items, 1 claimed (=rulesets:= prefix), 2 unowned gear links left
+for Craig. Filed the claimed one, removed it from roam under capture-guard +
+roam-write lock, triggered =roam-sync=. A local =.emacs.d= FYI also cleared.
+
+The claimed item: "code reviews must occur before every commit an agent does,
+and they should be hostile reviews from a subagent without the agent's context."
+
+Craig's decisions: *adversarial* rather than hostile (he took my push-back that
+an agent told to attack manufactures findings), plus a requirement I had missed —
+a re-review loop that runs until the reviewer approves — and that the rules must
+not contradict afterward. Unopposed recommendations I proceeded on: dispatch on
+every commit with the reviewer's own gate deciding triviality, and the flow lands
+in the =publish= skill.
+
+Wrote it into three files: =publish/SKILL.md= Step 1 (dispatch contract,
+adversarial-with-substantiation, the loop, bounds), =review-code/SKILL.md= (the
+two levels of dispatch, the adversarial contract, re-review mode), and
+=claude-rules/subagents.md= (a new Isolation Override section, since three
+separate size rules there said don't dispatch small work).
+
+** 20:30 — Dogfooded it, and the reviewer found nine things
+
+Ran the new flow on its own diff: dispatched an isolated adversarial reviewer
+with the diff plus a one-line claim, withholding everything else. It returned
+REQUEST CHANGES with seven Important and two Minor, every one substantiated. I
+checked each against the files rather than accepting them, and all nine were
+real:
+
+1. =Skipped= from Phase 0 is not =Approve=, so trivial diffs dead-ended at a gate
+ with no defined pass.
+2. =no-approvals.org= line 73 (the actual execution step) still described the old
+ inline unbounded flow; I had only updated the preamble at line 49.
+3. =work-the-backlog.org= and =sentry.org= — the unattended callers — had no
+ receiver for "stop and surface to the user". The speedrun routes to
+ work-the-backlog, not the file I updated.
+4. The Step 2 exception still said the review runs "when it applies", which my
+ rewrite had made false.
+5. *The sharpest one.* Withholding the ticket/plan makes the author's claim
+ self-certifying and strands =review-code='s Intent-vs-Delivery criterion — the
+ one aimed at exactly the inherited-scope error this gate exists to catch. A
+ ticket is not the author's model; it is the independent record of what was
+ asked. I had not considered this.
+6. The loop turned on the verdict token, so a single Minor could burn all three
+ rounds and escalate.
+7. My override said it "doesn't relax the Prompt Contract" while field 2 of that
+ contract says paste your context verbatim — which would destroy the isolation
+ the whole change is built on.
+8. todo.org carried an unrelated =references/= rewrite, and the new task body
+ listed as open the questions the same commit answered.
+9. =subagents.md= still says subagent output is a claim to verify, unreconciled
+ with "approval is the reviewer's to give".
+
+All nine fixed. The =references/= hunk is split out as =3a933a2=. Round 2 sent
+back to the same reviewer, which is the loop working as designed.
+
+** 21:30 — The loop closed at three rounds
+
+Round 2 (three findings): =review-code='s adversarial contract still said two
+inputs, so the round-1 fix landed in =publish= but not in the text the reviewer
+reads — the two files disagreed at the one seam the change was about. A
+count/list regression my own fix introduced ("exactly two things" over a
+three-item list). And a fourth verdict I had missed entirely: =review-code=
+emits =Needs Discussion=, which is exactly what an adversarial reviewer reaches
+for on an architectural objection, and the flow had no handling for it.
+
+Fixing =Needs Discussion= reproduced round 1's finding 3 one level down, which I
+caught myself: all four unattended parking clauses keyed on "the loop hits its
+bound", and a first-round =Needs Discussion= is not a bound hit. Rewrote all four
+to trigger on "the review can't reach approval" with the three causes named, and
+asked the reviewer to verify that independently rather than take it from me.
+
+Round 3: APPROVE, with one Minor — a recurrence of the count/list mismatch, since
+my fourth-verdict fix left the lead-in saying "three outcomes" above four
+bullets. Fixed the numeral. The committed diff therefore differs from the
+approved one by exactly that word, which the flow's own Minor-only rule permits
+rather than spending a fourth round.
+
+The reviewer also verified things I had not asked about and would not have
+checked: that =failed= is already a legal outcome slug in work-the-backlog's
+metrics table, that the three workflow mirrors carry identical blob hashes rather
+than merely similar text, and that no fifth verdict token exists anywhere in
+=review-code=. It filed one follow-up correctly rather than fixing it in-diff —
+=start-work.md= Phase 7 still summarizes the publish flow instead of pointing at
+it, and was stale before today. Filed =[#C] :chore:solo:=.
+
+Convergence shape across the three rounds: nine findings, three, one Minor. The
+residue in later rounds was integration error from the previous round's fixes
+rather than new design problems, which is the shape the bound is calibrated for.
+
+Committed =8062460=, pushed, velox fast-forwarded and verified.
+
+Six commits this session, all pushed, both daily drivers current, inbox at zero,
+tree clean.
+
+** 2026-07-29 — Walking the remaining items, and a long lesson
+
+*Item 1, the =references/= dead link* (=5999f88=). Craig picked drop-the-link.
+The adversarial review returned =Needs Discussion= — the fourth verdict, on its
+first real use — and widened the fix twice, both correctly. My replacement prose
+said credentials "live in the rulesets repo" without naming a file, which would
+have sent readers to =calendar-reference.org=, whose three paths had been dead
+since May. Now names =mcp/README.org=. And the file itself was orphaned by the
+link removal, so both copies and the empty =references/= dirs are gone. Round 2
+approved with three Low findings, all against the task record: my count was wrong
+(seven sites, not five) and =scripts/lint.sh='s =check_md_links= already exists
+for that class, missing them only because it matches markdown syntax.
+
+*Rule gap found by using the rule.* =Needs Discussion= exits to the user, but I
+never wrote what happens after the user answers. Treated it as a fresh review on
+the reasoning that Craig adjudicated and the scope changed. Flagged to Craig; not
+yet written into the skill.
+
+*The wrap-org-table bug* (=ecd5d7b=). work reported that the tool splits a logical
+row and lint passes the result. Everything I *measured* held. Everything I
+*inferred* on top was refuted, four times:
+
+1. Root cause "absence of rules in the input" — refuted by the double-run repro
+ (the tool corrupts its own correct, rule-delimited output).
+2. "Tested and killed the empty-cell hypothesis" — the fixture was confounded.
+ With no hlines the code short-circuits at =:184= before the predicate is
+ reached, so I varied the empty cell while the path that reads it was switched
+ off, got a negative, and wrote it down as settled.
+3. "The reporter's row-below observation discriminates between the paths" — it
+ doesn't; both produce that signature. Claimed twice.
+4. "A static scan can't see primary-path exposure, needs simulation" — wrong, and
+ worse, I sent it to work, who built on it. Then my *corrected* advice (run the
+ predicate over rule-delimited groups) was also wrong: work implemented it and
+ showed it can't discriminate at any threshold, with worked examples where the
+ same structural signature has opposite correct verdicts.
+
+Three corrections sent to work, plus a fourth acknowledging their disproof. The
+review loop *bounded out* at three rounds — the first bound-out under the new
+rule, working as designed. Craig adjudicated by stripping the task to Verified /
+Two-fixes-that-work / Open-questions, which is the right shape: the measurements
+were never the problem.
+
+The fix that survived is work's read, not mine: check idempotence (reflow twice,
+diff) rather than build a detector. It's true by construction and needs nobody to
+decide what a group means.
+
+*The lesson, stated plainly.* Every refutation across three rounds landed on
+inference, never on a measurement. I ran experiments and then over-read them,
+repeatedly, at full confidence. work — after I'd sent them three wrong analyses —
+labelled their own uncertain number as a floor on a population they couldn't
+cleanly define, unprompted. That discipline is the thing to copy.
+
+I also found the 2026-07-27 note where I'd already observed this exact failure
+and left it in a session summary instead of filing it. work's framing: a correct
+observation recorded and then read as fine is the same failure as a green check
+on a corrupted table.
diff --git a/.ai/sessions/2026-07-29-14-29-helper-1055-launch-pilot-idle.org b/.ai/sessions/2026-07-29-14-29-helper-1055-launch-pilot-idle.org
new file mode 100644
index 0000000..76e856b
--- /dev/null
+++ b/.ai/sessions/2026-07-29-14-29-helper-1055-launch-pilot-idle.org
@@ -0,0 +1,62 @@
+helper-1055
+#+TITLE: Helper Session — helper-1055
+#+AUTHOR: Craig Jennings
+#+DATE: 2026-07-29
+
+* Summary
+
+Closed out by the primary session on 2026-07-31 at Craig's direction, rather
+than by this helper itself. It was launched as the live pilot of =ai --helper=,
+was never given work, and idled from 14:29 on 2026-07-29 onward.
+
+** Active Goal
+
+Serve as the first live helper instance in rulesets, validating the =ai --helper=
+launch path end to end against a running primary.
+
+** Decisions
+
+None. This session made no decisions and was asked for none.
+
+** Data Collected / Findings
+
+The helper launch path works. Every step of the contract's light startup
+executed as designed: the launcher-exported =AI_AGENT_ID=helper-1055= was
+adopted rather than self-assigned, =helper-mode.org= was read as the role
+contract, and every primary-only action was skipped — no Phase A.0 pulls, no
+=make install=, no =.ai/= rsync, no inbox processing, no git mutation.
+
+The roster resolved correctly from inside the helper: one other live agent (pid
+3707800) in the same project. Anchors did not collide — the primary stayed on
+the unscoped =session-context.org= while this session created
+=.ai/session-context.d/= and wrote here.
+
+** Files Modified
+
+Only this file. The helper touched nothing else, which is itself the finding:
+the contract's read/write tiers held with no enforcement beyond the instruction.
+
+** Next Steps
+
+None for this session. The unbuilt pieces it surfaced — startup's roster check
+and the live-helper gate on file-wide hygiene passes — are recorded in
+=helper-mode.org='s Status section and in the primary's session record.
+
+KB: promoted 0 / consulted no
+
+* Session Log
+
+** 2026-07-29 Wed @ 14:29 CDT — Helper light startup
+
+Launched as a helper into rulesets with =AI_AGENT_ID=helper-1055= already
+exported, so I adopted that id rather than self-assigning. Read
+=.ai/workflows/helper-mode.org= (the role contract) and =.ai/protocols.org=.
+Skipped everything primary-only: no Phase A.0 pulls, no =make install=, no
+=.ai/= rsync, no inbox processing, no git mutation.
+
+Roster confirms I am not alone — one other live agent, pid 3707800, cwd
+=/home/cjennings/code/rulesets=. That primary is anchored on the unscoped
+=.ai/session-context.org= (last written 10:46 today), so our anchors don't
+collide. =.ai/session-context.d/= didn't exist; I created it for this file.
+
+Awaiting the work Craig spawned this helper for.
diff --git a/.ai/sessions/2026-07-31-06-32-helper-agents-mcp-scoping-and-sync-extraction.org b/.ai/sessions/2026-07-31-06-32-helper-agents-mcp-scoping-and-sync-extraction.org
new file mode 100644
index 0000000..e2c5903
--- /dev/null
+++ b/.ai/sessions/2026-07-31-06-32-helper-agents-mcp-scoping-and-sync-extraction.org
@@ -0,0 +1,656 @@
+#+TITLE: Session Context — 2026-07-29
+#+AUTHOR: Craig Jennings
+
+* Summary
+
+** Active Goal
+
+Started as Craig's question about running a second helper agent in one project
+for "dogpiling" bugs, and became four arcs: building and piloting the helper
+launcher, prototyping worktree-based branch isolation, an MCP account-binding
+and CUI investigation, and finally a propagation incident that my own
+uncommitted file had been causing all day.
+
+** Decisions
+
+- *Linked worktrees, not bare, and the writer gets the isolation.* A bare layout
+ moves the path that project discovery, the roster's cwd match, =inbox-send=
+ resolution and =make install= all key on. Craig's framing pinned the diagnoser
+ to main; inverted it, because the read-only agent needs no isolation and the
+ committer does.
+- *Port work's sentry corrections rather than apply their file.* Both copies
+ predated =f3f5bfd= and would have reverted the =fire= → =cycle= rename the day
+ after it landed.
+- *Hold sentry's pass 3 at the mail/messenger exclusion* rather than take the
+ read-everything change. The =[#A]= account-binding guard is still an unapplied
+ prepared diff, and a category exclusion is the only thing keeping that hazard
+ unreachable meanwhile. Craig then reframed it further: each project declares
+ its own channels, so a blanket rule in either direction is the wrong shape.
+- *Extraction before guard changes.* The sync is untested inline bash running in
+ every project's every session, and both intended fixes modify exactly that.
+- *=--force= and a cache caveat on the recovery command*, after the reviewer
+ checked =audit.sh= and found it skips dirty tracked projects and carries none
+ of the =--exclude= flags.
+
+** Data Collected / Findings
+
+- *=ai --helper= shipped and piloted live* (=84bd121=). The roster excludes its
+ caller's own ancestry, so it must be run from a separate terminal — from
+ inside an agent session it silently downgrades to a second primary.
+- *=google-keep= was broken, not absent.* keep-mcp 0.3.1 imports FastMCP from
+ =mcp.server.fastmcp=, which =mcp= 2.0.0 removed, so the server died at import
+ and every client saw connected-with-no-tools. Pinned =mcp<2=; 23 tools
+ including =pin_note= and =set_note_color=, so the whole nag-note spec
+ automates and home's manual workaround is unnecessary.
+- *Every MCP server is registered globally*, so =slack-deepsat=,
+ =google-docs-work= and =linear= are callable from every project. The
+ =:TRIAGE_SOURCES:= declaration governs one consumer while the exposure sits at
+ the registry.
+- *The claude.ai connectors were live despite being "disabled"*, and probing
+ showed them bound to the *personal* account — which contradicts the =[#A]=
+ task's premise that =mcp__claude_ai_Gmail= is work-bound. I carried home's
+ binding claim forward without checking it, the same error I had caught work
+ making that morning.
+- *My uncommitted =sentry.org= blocked template propagation for a full day.*
+ Five workflow files went stale in =.emacs.d= alone; two were my own commits
+ from that morning. Then I re-created the identical condition six hours after
+ diagnosing it, which is the argument that the guard punishes ordinary WIP with
+ a silent project-wide outage.
+- *Two review rounds each found a real defect in my own work*: an =AI_AGENT_ID=
+ interpolated unquoted into the pane's command line, and a characterization
+ test that provably tested nothing (mutation-proven — deleting the flags it
+ guarded left the suite green).
+
+** Files Modified
+
+- =84bd121= =feat(ai): add --helper for a second session in a live project= —
+ launcher, wrap-up Step 0 helper branch, doc corrections, 30 tests. Pushed.
+- =f571057= =refactor(startup): extract the template sync into a tested script= —
+ =sync-templates= plus 15 characterization tests. Pushed.
+- =~/.claude.json=: =google-keep= re-registered with =mcp<2= (ratio only; velox
+ has no entry at all).
+- =stash@{0}=: the sentry CronCreate port, held pending the declaration spec.
+- =working/=: four parked handoff sets (sentry arming, triage declaration, sync
+ model, nag-event vocabulary).
+- Worktree =~/code/rulesets-wrap-org-table= on =fix/wrap-org-table=, with a
+ fixer session live in it.
+
+** Next Steps
+
+Sentry: the stashed port, the per-project declaration model for both channels
+and passes (Craig's reframe — work skips personal, home skips work, =.emacs.d=
+skips both), the pass inventory and its gaps, and the "one more thing" he
+mentioned and never got to say.
+
+Sync: steps 2 through 4 — narrow the dirty guard per path, add the last-synced
+manifest, and write work's line into =cross-project.md=. The manifest is the
+primary fix, not the narrowing: =.emacs.d='s five-file measurement showed silent
+drift is the ordinary case and the loud failure the exception.
+
+Also open: scope the five work-bound MCP servers to work-local; velox needs the
+Keep token and the same scoping; home needs telling their Keep caveat was wrong;
+the nag-event rule needs its corrections before landing; and the =[#A]=
+account-binding task may rest on a wrong premise.
+
+KB: promoted 0 / consulted no
+
+* Session Log
+
+** 2026-07-29 10:25 — Startup
+
+Ran startup.org. rulesets already current, project tree clean at 73e8c01, .ai/
+synced from templates, nothing new to link, no language-bundle drift. No
+session-context.org present, so the 06:36 session wrapped cleanly. Inbox has 0
+pending handoffs (lint-followups.org is the standing lint queue, refreshed by
+last night's commit — 16 judgment items). Roam inbox 2 items, both unrelated
+product captures. Staleness: 6 top-level tasks unreviewed >7 days. Surfaced the
+two active reminders (context-engineering rightsizing; the two-week-old sentry
+spec read).
+
+** 2026-07-29 10:30 — Helper-agent question: what's actually live
+
+Craig asked whether a second helper agent in the same project is in place, for a
+dogpile scenario: one agent reads code on main, diagnoses, files Linear bugs;
+the other branches, fixes, and queues PRs.
+
+Investigated rather than answering from the todo body. Findings:
+
+- Shipped and working: =.ai/scripts/agent-roster= (detection), =helper-mode.org=
+ (the role contract), and the =AI_AGENT_ID= + =session-context.d/= split.
+- Not shipped: =ai --helper=. Verified directly — the launcher's option parser
+ handles only =-h/--help=, =--runtime=, =--print-launch=, =--print-runtimes=,
+ =--attach=. No helper flag exists.
+- Also not shipped: startup's roster auto-routing branch, the wrap-it-up helper
+ branch, the hygiene-pass live-helper gate. helper-mode.org's own Status
+ section says the wiring is behind the three-ring gate and not yet live; the
+ manual "you are a helper" instruction is the only live adoption path.
+
+The more important finding is that Craig's scenario doesn't fit helper mode as
+designed, for a reason orthogonal to the missing wiring: two sessions in one
+clone share one working tree and one HEAD. The diagnoser cannot read main while
+the fixer works a branch — checkout is global to the clone. Helper mode's
+concurrency design is about two Edit writers on one shared org file, not about
+branch isolation. Separately, helper-mode.org bans all git mutation for the
+helper, which does map his roles correctly (fixer = primary, diagnoser =
+helper), but only after the branch problem is solved.
+
+The unbuilt =[#B] Repository publish-lock for two sessions sharing one clone=
+task (todo.org:210) is the same collision from the index side.
+
+Craig picked: finish the helper wiring first (launcher + wrap-up branch, pilot,
+then decide on the startup net), then design the worktree split. He'll keep the
+diagnosing agent read-only on code, which closes the write-collision half. I
+noted that read-only doesn't make it read =main= — it reads whatever branch the
+clone has checked out — and that's what the worktree work fixes.
+
+** 2026-07-29 11:05 — Slice A + B built: ai --helper and the wrap-up branch
+
+Green baseline first: =make test= exit 0 before touching anything.
+
+TDD throughout. Wrote =scripts/tests/ai-launcher-helper.bats= (23 tests) red,
+then built against it. The Makefile glob-discovers =scripts/tests/*.bats=, so
+the new file is actually covered rather than silently skipped.
+
+Launcher (=claude-templates/bin/ai=): =--helper <dir>= flag, =_helper_launch_mode=
+pure core, =_helper_id= (=helper-<rand4>=), =build_helper_instructions=,
+=_resolve_helper_launch= (runs the project's =agent-roster=), and =helper_mode=.
+Two deliberate departures from =single_mode=: it never focuses an existing
+window (a second session is the whole point, and focusing the primary's window
+is the one outcome that can't be what was asked for), and it never runs git prep
+(pulls are primary-only). =_order_windows= now matches a =<project>:<id>= helper
+window on its colon prefix so it sorts beside its project.
+
+Roster verdict → decision: exit 1 (others live) → helper; exit 0 (alone) →
+warn and fall through to a normal primary launch; exit 2 or script absent →
+warn and launch a helper anyway. Unverifiable resolves toward helper on purpose:
+a helper that turns out to be alone merely does less, while a primary that turns
+out not to be alone runs pulls and rsync under a live session.
+
+*Real bug caught by shellcheck, not by my tests.* =_resolve_helper_launch= built
+the roster path in the same =local= statement that assigned =dir=, which bash
+does not support — verified directly: =local a="$1" b="$a/x"= yields =b=/x=.
+Every one of my tests passed anyway, because both production callers happen to
+have their own =$dir= holding the same value, so the wrong lookup returned the
+right answer. Split into two =local= statements and added a test that calls the
+function with no =dir= in scope; confirmed it fails against the one-local form
+and passes against the fix.
+
+Wrap-up: new Step 0 helper branch in =wrap-it-up.org= (the old sentry guard
+became Step 0.5 — no live cross-references to renumber, checked). A helper
+re-runs the roster: primary live → archive its own context file to
+=sessions/...-<id>-<description>.org= and stop, no commit/push/hygiene;
+orphaned → full wrap, the git ban lifts; roster unavailable → archive-only,
+because leaving work uncommitted is recoverable and committing under a live
+primary is not. Exit Criteria gained the helper's shorter list.
+
+Corrected two docs that claimed this doesn't exist: =helper-mode.org='s Status
+section and the =protocols.org= helper paragraph. Both now name what is live and
+— more usefully — what isn't: startup has no roster check, so a bare =claude= in
+a project that already has a session still runs full primary startup; and the
+live-helper gate on file-wide hygiene passes is unbuilt, so a primary's
+=todo-cleanup=/=lint-org= run can still clobber a helper's scoped edit.
+
+Verified: =make test= exit 0, 529 passing. =shellcheck= clean on =bin/ai=.
+=sync-check.sh= clean (canonical and mirror both updated). Uncommitted.
+
+** 2026-07-29 14:30 — Live pilot passed; a helper is running now
+
+Craig ran =ai --helper ~/code/rulesets= from his own terminal. Everything the
+slice was supposed to do, it did: roster found this session (pid 3707800) and
+returned the helper verdict, id =helper-1055= assigned and exported alongside
+=AI_HELPER=1=, window opened as =rulesets:helper-1055= in the =ai= tmux session,
+and the helper opener landed verbatim — the helper read =helper-mode.org= as its
+first action rather than running startup.
+
+Two things checked before calling it a pass, because both looked like defects in
+the screenshot and neither was:
+
+- =.ai/session-context.d/= did not exist when the helper first looked. That's
+ correct — =session-context-path= is a pure resolver and never mkdirs; creating
+ the file is step 1 of the helper's own light startup. It had already created
+ =helper-1055.org= (965 bytes) by the time I checked.
+- The helper's first Bash call exited 2. Its own =&&= chain broke on the missing
+ directory; not a wiring fault.
+
+The helper's anchor is gitignored (=.gitignore:30= =.ai/session-context.d/=), so
+a live helper doesn't dirty my tree. My =git status= still shows exactly the
+eight files this session changed.
+
+*Standing constraint while the helper is live:* I must not run any file-wide
+hygiene pass — =todo-cleanup.el=, =lint-org.el=, =wrap-org-table.el=. Nothing
+enforces that yet (the live-helper gate is the unbuilt piece), so it's on me,
+and it matters most at wrap time when the hygiene step runs by default.
+
+** 2026-07-29 14:45 — Worktree prototype: the fixer checkout
+
+Craig's design question: bare worktree so each agent gets its own branch?
+Recommended linked worktrees off the existing clone, not bare — a bare layout
+moves the path that =ai='s project discovery, =agent-roster='s cwd match,
+=inbox-send='s basename resolution, and =make install= all key on, and buys
+nothing over a linked worktree. Also recommended inverting his role assignment:
+the *writer* needs the isolation, not the reader, so the read-only diagnoser
+stays here as the helper and the fixer gets the worktree.
+
+Created =~/code/rulesets-wrap-org-table= on branch =fix/wrap-org-table= off
+73e8c01. My eight uncommitted files stay in this checkout, which is what a fix
+branch should look like.
+
+Verified in the worktree: =.ai/protocols.org= and =.ai/scripts/= present (this
+project tracks =.ai/= — 192 files), no session anchor (gitignored, so the fixer
+gets a fresh one), the launcher accepts it as a project, HEAD on the new branch,
+clean status.
+
+*Correction to what I told Craig.* I said the worktree's =inbox/= would be empty
+because handoffs are untracked. Wrong mechanism: =inbox/lint-followups.org= is
+tracked (73e8c01 committed it), so it *does* appear in the worktree. The
+conclusion holds for a different reason — =inbox-status= reports 0 pending in
+both checkouts, so neither session tries to process it.
+
+*Scope limit worth naming:* rulesets has no Linear and no GitHub remote, so this
+prototype exercises the two-agents-two-branches mechanics but not the
+file-a-Linear-bug or open-a-PR half of the scenario. Those live in the work
+project.
+
+** 2026-07-30 — Publish flow: the isolated review earned its keep again
+
+Step 0 reconcile clean (0/0). Remote is =cjennings.net= only, so the approval
+gate applies. Staged eight files and dispatched the adversarial reviewer with
+the diff, a one-line claim, and the todo.org task body as the requirement
+source — withholding my reasoning, per the Isolation Override.
+
+Verdict: *Request Changes*, three Important. All three were real, and the first
+is the kind of defect the isolation exists to catch — it was invisible in my own
+model because I wrote the snippet believing it did what I meant.
+
+1. *The roster call in my new Step 0 omitted the project root.* =agent-roster=
+ defaults to =$PWD= and keeps only agents at or inside that root, so a helper
+ whose shell sits in a subdirectory would not see a primary at the root. That
+ reports "alone", which my own bullet list reads as *orphaned* — the one
+ branch that commits and pushes. I had written the sentence calling that the
+ unrecoverable outcome, and then wrote the call that produces it. Verified
+ empirically: from =scripts/= the old form was worse than the reviewer said —
+ the =[ -x .ai/scripts/agent-roster ]= test itself fails there, so it never ran
+ the roster at all and =$?= was the failed test's 1. Now resolves the root with
+ =git rev-parse --show-toplevel= and captures rc inside the branch.
+2. *helper-mode.org still listed startup's roster check as a live route* in
+ "When to Use This Workflow" while my new Status block said it doesn't exist.
+ The stale claim sat above the fold, in the section a session reads to decide
+ whether it is a helper. Now two routes, with the gap stated inline.
+3. *=AI_AGENT_ID= was honored unvalidated and interpolated unquoted* into the
+ command typed into the pane, so an id carrying =;= or a space would run
+ something else instead of launching the helper. Worse, the override is
+ *inherited*: a helper's pane exports the id, so =ai --helper= from inside a
+ helper reuses the parent's — two agents on one context file, the exact
+ lost-update shape the contract exists to prevent. Added =_sanitize_agent_id=
+ and =_resolve_helper_id= (sanitize, then mint fresh when that id's context
+ file already exists) plus four tests.
+
+Plus four cheap Minors: the help text claimed the fallback skips git prep (it
+doesn't), the rc capture above, =$((RANDOM % 65536))= was a no-op on bash's
+15-bit RANDOM, and the help now warns that the roster excludes its caller's
+ancestry.
+
+*My own fix had a bug my own test passed anyway.* The first =_sanitize_agent_id=
+used =printf '%s\n'= before =tr -c=, so tr translated the trailing newline into
+an underscore and every id gained a trailing =_=. The space test asserted a
+substring, which "helper_beef_" satisfies. Caught it only because two other
+tests failed. Fixed both the sanitizer and the assertion, which is now anchored
+on the following space.
+
+=make test= exit 0, 532 passing. shellcheck clean. sync-check clean. Sent back
+to the same reviewer for round 2; not committed.
+
+Deliberately not fixed: finding 8, a parked
+=working/working-dir-orphan-check/wrap-it-up.org.proposed= still carrying the
+old "Step 0: Refuse if sentry is live". Pre-existing, and applying it later
+would silently revert this work — surfacing to Craig rather than editing a
+parked proposal.
+
+** 2026-07-30 — Committed 84bd121
+
+Craig approved the drafted message. Committed =84bd121= on main, 8 files, 646
+insertions. Author =Craig Jennings <c@cjennings.net>=, no attribution. The
+pre-commit hook's sync-check passed, so canonical and mirror agree. Tracked tree
+clean; the two work handoffs remain as untracked inbox deliveries. Unpushed —
+push is its own confirmation.
+
+** 2026-07-31 — Extraction committed; propagation unblocked
+
+Committed the extraction after two review rounds. Synced paths verified clean,
+so template propagation is unblocked for every project's next startup.
+
+*Round 1 found a test of mine that provably tested nothing.* The pycache
+exclusion test's fixture had no =.gitignore=, so the cache files read as
+untracked, guard one fired, the sync never ran, and every "this didn't arrive"
+assertion was satisfied by nothing arriving. The reviewer proved it by deleting
+all three =--exclude= flags and watching the suite stay green. Fixed by
+committing a =.gitignore= into the fixture and asserting the sync *ran* before
+asserting what it skipped; re-ran the mutation both ways to confirm it now
+bites.
+
+It also caught my fallback naming a remedy that cannot happen ("the next
+successful sync installs it" — the fallback runs *instead of* the sync, so there
+is no next one) and found the real out-of-band recovery in =audit.sh=, which I
+had not looked for.
+
+*My own fix for the third finding was wrong on the first attempt.* The
+false-success test deleted the canonical inside the live fixture repo, which
+registered as staged deletions and tripped guard one — so it exercised the skip
+path while claiming to test false success. It failed, which is how I caught it.
+Now points =SYNC_RULESETS_DIR= at a nonexistent path.
+
+Round 2: Approve. The reviewer re-ran the 16-scenario differential
+independently, killed every mutant it aimed at the suite including round 1's
+survivor, and verified the =audit.sh --apply --force= recovery command actually
+does what the message claims. Three Minors, all closed: =--force= added (audit
+skips a dirty tracked project without it), the pycache caveat on that recovery
+path documented, and the false-success test's negative assertion moved onto a
+file that does arrive on a real sync.
+
+=make test= exit 0, 551 passing. Left uncommitted on purpose: the four parked
+handoff directories under =working/=, which want their own commit and do not
+block the sync guard.
+
+** 2026-07-31 — Step one: sync extracted from startup.org and characterized
+
+Green baseline first (536, exit 0), then extracted the Phase A sync block into
+=claude-templates/.ai/scripts/sync-templates=. Faithful extraction — the rough
+edges are preserved and characterized rather than fixed in passing, because a
+behavior change smuggled into an extraction is unreviewable.
+
+Proved it faithful *differentially* rather than by reading: ran the old inline
+block and the new script against identical fixtures, clean and dirty, and
+compared both stdout and a hash of the resulting tree. Byte-identical in both
+cases.
+
+14 characterization tests in =scripts/tests/sync-templates.bats=, glob-discovered
+so the gate actually sees them. Two of them pin the incident directly:
+
+- "ONE dirty file blocks ALL THREE rsyncs" — the 2026-07-30 blast radius in one
+ assertion. The narrowing change lands by making this test fail on purpose.
+- "a locally-edited template is silently overwritten, with no record kept" —
+ work's regression, pinned. Asserts the output is indistinguishable from an
+ ordinary sync, that no backup exists, and that nothing anywhere says a local
+ fix was destroyed.
+
+=startup.org= now calls the script, with a fallback that *announces* a skip
+rather than performing a silent one. First draft of that fallback's prose was
+wrong — I wrote that a pre-extraction project "cannot sync itself out of that
+state", which is false: the old inline block delivers both the script and the
+new startup.org together, so the ordinary rollout never hits the fallback. It
+covers only a split rsync. Corrected before it shipped.
+
+Verified: =make test= exit 0, 550 passing (536 + 14). sync-check clean, exec bit
+preserved in the mirror. shellcheck flags one SC2001 style note on the =sed= —
+inherited verbatim from the inline block, deliberately not "fixed", since that
+would be a behavior-adjacent edit inside an extraction commit.
+
+*And I immediately re-created today's incident.* =startup.org= is now modified
+under the synced paths, so template propagation is blocked again as of this
+moment. Same shape as the edit that cost a day, six hours after diagnosing it.
+The lesson isn't "remember to commit" — it's that the guard punishes an ordinary
+work-in-progress state with a silent, project-wide outage, which is the design
+flaw the narrowing fixes. Flagged to Craig rather than left sitting.
+
+** 2026-07-30 18:35 — My dirty tree was blocking template sync for every project
+
+Three handoffs: =.emacs.d= at 18:20, work at 18:29, =.emacs.d= again at 18:32
+correcting and escalating its own first framing. Craig is seeing "telega server
+died" on every triage run, eight =telega-server= SIGSEGVs on ratio today.
+
+*My fault, and it ran all day.* The startup guard skips all three rsyncs when
+anything under the synced template paths is dirty. My uncommitted =sentry.org=
+port sat there through the whole sentry discussion, so *no project received any
+template update today* — including home, which started fresh at 08:09 after the
+telega fix landed and still didn't get it. Verified: =MM
+claude-templates/.ai/workflows/sentry.org= was the only dirty synced path.
+Stashed it (=stash@{0}=, named), synced paths now clean, propagation unblocked.
+
+Holding a synced-path edit uncommitted has a cost I did not price. The
+discussion was worth having; leaving the file dirty across it was not.
+
+*The canonical itself is fine* — =.emacs.d= said so and I confirmed: the
+=loadChats= fix is in (=(telega--loadChats '(:@type "chatListMain"))=), the
+=telega-server-live-p= dead-server signal is present (8 sites), and the
+truncation claim work asked about is *already retracted* at :246-251, crediting
+work's own 2026-07-28 wire-level disproof. Both of work's content asks were
+already satisfied.
+
+*The systemic finding, which is the real one and is in my area.* Two failure
+modes, and the second is worse:
+
+1. (=.emacs.d='s first framing) A correctness fix to a synced file has no path
+ to a running session — sync is startup-only.
+2. (work's, from experience) The rsync runs =--delete=, so a local patch to a
+ rulesets-owned file is *silently reverted* at the next startup by whatever
+ the canonical held at that moment. A project that did everything right —
+ hit the bug, diagnosed it, patched locally, logged the patch, restarted —
+ comes back running the broken version with its log still asserting it was
+ fixed. That is what happened to work, and it is why three projects believed
+ this was handled for two days.
+
+=.emacs.d= is right that a freshness check addresses only its own version.
+Nothing currently notices the loss at the moment it happens, because that moment
+looks routine and successful.
+
+=84bd121= still unpushed, so velox will not see the helper work.
+
+** 2026-07-30 17:35 — The CUI exposure is at the MCP registry, not the declaration
+
+Work replied to the =:TRIAGE_SOURCES:= defect: fixed their side (cmail dropped
+with the reason written in, telegram kept deliberately because Kostya and Vrezh
+carry real work traffic there, personal-calendar under review for conflict
+checks), and widened the requirement with Craig's words — with CUI in play,
+work email, calendar and the rest are off limits to *every other* project. The
+reverse direction is the one carrying compliance weight: a personal or tooling
+project reading work channels is an exposure question, not a tidiness one.
+
+They also hit the run-time-read trap the hard way: an auto-triage cron armed
+twenty minutes earlier had the source list baked into its prompt, so correcting
+the declaration did nothing until they re-armed it. Both their spec suggestions
+accepted — deny-by-default for work-account sources, and read the declaration at
+run time rather than caching it.
+
+*Then the sweep turned up something bigger than their note assumed.* Every MCP
+server is registered *globally*, with no project scoping anywhere:
+=slack-deepsat=, =google-docs-work= and =linear= are directly callable from
+home, =.emacs.d=, =.dotfiles=, rulesets, and every other project. This session,
+in rulesets, has all three available right now.
+
+So =:TRIAGE_SOURCES:= governs one consumer — which plugins the triage engine
+loads — while the exposure sits at the registry. A correct declaration in every
+project would not close it. Any deny-by-default rule for work sources has to
+reach the MCP registration layer or it is a rule about the front door written
+while the side door stands open.
+
+Not proposing the fix: project-scoping those servers is a real change with real
+tradeoffs (several are useful outside work, and the calendar server manages both
+accounts in one place). Craig's call, and bigger than the declaration spec.
+Replied to work with the sweep and credited the finding to their handoff.
+
+** 2026-07-30 — google-keep MCP was broken, not absent; fixed on ratio
+
+Home's handoff claimed the google-keep MCP "shows as a connected server but
+exposes no tools", so a note cannot be created, coloured or pinned
+programmatically, and recorded a manual wl-copy workaround in the vocabulary
+rule. Craig pushed back: he and home were writing to each other through Keep
+notes on vacation last month. He was right.
+
+*Root cause.* The server is registered globally in =~/.claude.json= as =uvx
+--from keep-mcp python -m server.cli=, credentials present. It crashes at import
+with =ModuleNotFoundError: No module named 'mcp.server.fastmcp'=. keep-mcp 0.3.1
+imports FastMCP from there; uvx resolves =mcp= to 2.0.0, which dropped that
+module (confirmed by listing =mcp.server='s submodules — no =fastmcp=). The
+process dies instantly, so a client sees connected-with-no-tools. Not a missing
+integration; a dependency regression from =mcp= going 2.0.
+
+*Fix, applied and verified on ratio.* Pin to =mcp<2=. Re-registered through
+=claude mcp remove= / =add --scope user= rather than hand-editing
+=~/.claude.json=, because the live session owns that file and would clobber a
+manual edit. =claude mcp list= now reports =✔ Connected= where it previously
+reported =Failed to connect — Connection closed=. Config backed up first.
+
+*The capability is fuller than the rule assumed.* 23 tools, including
+=create_note=, =update_note=, =find=, =pin_note= and =set_note_color=. So the
+entire nag-note spec automates — colour and pin included, the two things home
+said had to be handed to Craig by hand. The manual workaround comes out of the
+rule.
+
+*Colour caveat.* Keep has 12 fixed colours: White Red Orange Yellow Green Teal
+Blue DarkBlue Purple Pink Brown Gray. There is no "burnt orange" — =Orange= is
+the match (Keep's Orange swatch renders burnt).
+
+*Not done, and why.* MCP servers load at session start, so the tools are not
+callable in this session — a restart is needed before any note can be written.
+And velox has *no* google-keep entry at all, not a broken one, so it needs
+first-time registration including the master token. That is a credential moving
+between machines, so I stopped and asked rather than pushing it over tailscale.
+
+The pin is a stopgap. Upstream keep-mcp needs =mcp= 2.x support, worth filing so
+the pin does not become permanent and unexplained.
+
+** 2026-07-30 — Review of the sentry port: Request Changes, two for Craig
+
+The isolated reviewer returned *Request Changes* on the port. Verified every
+factual anchor myself before surfacing, and all of them hold.
+
+Fixed (my own defects, both in the paragraph whose subject is a mis-stated
+mechanism, which is its own lesson):
+
+- *I fabricated this file's history.* My line 92 said "an earlier version of this
+ file claimed a detached schedule hits a headless-auth wall". It never did —
+ =git log -S'headless'= over both copies returns zero commits. I carried work's
+ self-description across without checking it against the file it was going
+ into, which is precisely the error I told work they had made. Now says the
+ file prescribed =/loop= without stating why, and points at
+ =triage-intake.org=, where the reasoning actually lives.
+- Line 89 claimed the first three constraints "were wrong in this file". Two
+ were simply absent. Now "none of them were recorded here before 2026-07-30".
+- Incomplete rename at :61 and :127, which still called sentry's mechanism a
+ loop after the diff purged that word everywhere else.
+
+Two that need Craig, both real:
+
+1. *Sequencing hazard (Critical).* The new pass 3 turns on unattended mail
+ hygiene — mark-read, star, trash — across every channel. The =[#A]=
+ account-binding guard that exists because of the 2026-07-23 wrong-inbox
+ incident is still a *parked* prepared diff:
+ =working/triage-account-guard/proposed.diff=, and
+ =triage-intake.personal-gmail.org= has zero account checks. That incident is
+ exactly this: a sentry triage cycle bound to the work Gmail account instead
+ of personal, 201 messages, graded =[#A]= on severity alone. Commit =33949c5=
+ ("exclude mail and messengers") is what made it structurally unreachable, and
+ this diff removes that protection while the deliberate replacement sits
+ unapplied.
+2. *A third ruling nobody reconciled.* =todo.org:198= records Craig's
+ *2026-07-27* correction — scan DeepSat work mail and every messenger,
+ *excluding only personal email*. Work's 2026-07-30 note reverses to "read
+ everything" and never mentions 07-27. So there are three rulings, and the
+ newest may have been given without the middle one in view.
+
+Not committed. Staged and held.
+
+** 2026-07-30 — Ported work's sentry corrections; inbox cleared
+
+Craig confirmed he gave work the pass-3 ruling and asked to see the port before
+it lands. Ported rather than applied either file, since both reverted yesterday's
+=fire= → =cycle= rename (=f3f5bfd=).
+
+Six changes to =sentry.org=: overview and interval trigger off the loop
+language; step 7 rewritten for =CronCreate= with both shapes; Stop Sentry to
+=CronList= / =CronDelete=; the lock model noting overlap can't arise under
+self-rescheduling; pass 3 to "read everything, send nothing".
+
+Three things beyond a straight port. Work's constraint list had three items; I
+made it five, adding two facts from =CronCreate='s own docs that neither copy
+carried — jobs fire only while the session is idle and never mid-query (so a
+long cycle delays its own successor without the lock), and the scheduler's
+jitter (up to 10% of period, capped 15 min, so an hourly sentry can land six
+minutes late and that is not a stall). Also noted =durable= has no effect, since
+someone will reach for it on reading that jobs die with the session.
+
+And I fixed a real defect from yesterday's rename: canonical pass 3 ended "they
+never cycle unattended", which had been "never fire unattended" — the rename
+caught the verb. Checked the whole file; it was the only one.
+
+Verified: lint-org 0 mechanical / 0 judgment, sync-check clean, 80 "cycle" and
+zero "fire" as a noun. Uncommitted, awaiting Craig.
+
+Inbox dispositioned per =inbox.org= park: all four handoffs moved to
+=working/sentry-arming-correction/= alongside the prepared diff. Inbox back to
+zero.
+
+** 2026-07-30 07:43 — Work's 07:39 correction: pass 3 is about sending, not reading
+
+Work sent a second pair at 07:39, three minutes after the first and before my
+07:40 reply landed. The correction: Craig told them this morning that the
+2026-07-21 pass-3 ruling was that sentry must never *send* via mail or
+messenger, never about reading. Their revised pass 3 is "read everything, send
+nothing" — full triage across every source, with local-state mail hygiene
+(mark-read, star, trash) allowed because it emits nothing, and anything outbound
+(a send, a Slack or Signal message, a ticket comment or state move, a posted PR
+review, a calendar RSVP) queued for morning approval.
+
+The framing is good and the outbound/local-state line is the right one. But it
+is a policy reversal on a synced shared asset, resting on a ruling given in a
+session I was not in and cannot verify from here. Asking Craig directly rather
+than applying it.
+
+The rename conflict persists in the corrected copy: 84 "fire" against 1 "cycle".
+They sent before my 07:40 reply, so they had not seen it. Replied acknowledging
+the supersession, restating the rename finding, and stating both files are held.
+
+Net: =CronCreate= substance accepted and verified, pass 3 waiting on Craig,
+neither file applied.
+
+** 2026-07-30 07:40 — Inbox: work's sentry.org arming correction
+
+Two handoffs from work at 07:36: a prose note plus an edited =sentry.org=,
+arguing the arming mechanism was documented wrong (=/loop=, justified by a
+headless-auth wall) and should be =CronCreate=.
+
+Shared-asset proposal, so skeptical review rather than silent application.
+
+*Substance verified and correct.* Checked all three claims against
+=CronCreate='s own tool documentation: jobs are session-only and in-memory and
+die with the session; recurring jobs auto-expire after seven days with one
+final fire; fires run inside the arming session, hence inherited MCP auth.
+Their overnight 2026-07-28/29 evidence matches. The off-minute guidance they
+added is verbatim from the tool docs, which is a good sign they wrote from the
+source rather than from memory.
+
+*The file is the problem.* Their copy predates =f3f5bfd= (2026-07-29,
+"refactor(sentry): call one loop cycle a cycle, not a fire") — Craig's decision,
+72 sites. Their version uses "fire" 85 times and "cycle" once; the canonical is
+the inverse. Applying it wholesale reverts yesterday's rename the day it landed.
+So: port their step 7, Stop Sentry, and overview changes into the canonical's
+=cycle= vocabulary. Parked pending Craig — sentry.org is synced to every
+project.
+
+Two facts from the tool docs neither version carries, worth adding in the port:
+jobs fire only while the REPL is idle, never mid-query, so a long cycle delays
+its successor on its own; and the scheduler adds jitter (up to 10% of period,
+capped at 15 min).
+
+Agreed with their pass-3 catch — they nearly overturned Craig's 2026-07-21
+mail/messenger exclusion by inferring a technical cause for a policy ruling, and
+caught themselves. Left as his call.
+
+Disagreed with their companion note. =triage-intake.org:210= says auth is
+inherited because the sweep runs in the live session, and that the wall applies
+to a *detached* cron run — still true of a system cron. Narrower than sentry's
+claim was, so not wrong, though it does prescribe =/loop= where =CronCreate=
+would also work. Smaller follow-up, not folded in.
+
+Replied to work with all of the above. Not applied.
+
+** Pilot prerequisites (recorded 14:30)
+
+Prerequisites for the pilot, learned by testing rather than assuming: the roster
+excludes its caller's own process ancestry, so =ai --helper= must be run from a
+separate terminal — from inside this session (or via =!=) it can't see me and
+silently downgrades to a second primary. And the =ai= script uses a tmux session
+named =ai= while Craig's live agents run in =aiv-<project>= from ai-term.el, so
+the helper opens in a different session and switches his client. Pre-existing
+launcher behavior; the Emacs surface is a separate handoff to =.emacs.d= per the
+task.
diff --git a/.ai/sessions/2026-07-31-22-43-sync-guard-narrowing-and-standup-scripts.org b/.ai/sessions/2026-07-31-22-43-sync-guard-narrowing-and-standup-scripts.org
new file mode 100644
index 0000000..8714a49
--- /dev/null
+++ b/.ai/sessions/2026-07-31-22-43-sync-guard-narrowing-and-standup-scripts.org
@@ -0,0 +1,142 @@
+#+TITLE: Session Context — 2026-07-31
+#+AUTHOR: Craig Jennings
+
+* Summary
+
+** Active Goal
+
+Answer the propagation question from the 2026-07-30 outage — how do I work in
+rulesets without blocking every other project's template sync — then build the
+answer. Four inbound handoffs from work preempted it mid-session and were
+processed inline before the build resumed.
+
+** Decisions
+
+- *Narrowing first, manifest second.* The per-path =--exclude= narrowing is the
+ direct answer to the question and cost ~60 lines. The last-synced manifest is
+ the larger fix behind it and stays unbuilt.
+- *Withhold rather than block, per file.* A dirty path is excluded from its own
+ rsync instead of skipping all three for every project. Verified empirically
+ before building: rsync honors =--exclude= on both sides, so a withheld file is
+ neither overwritten nor deleted downstream.
+- *The behind-upstream guard stays all-or-nothing.* That staleness lives in the
+ destination, so there is no single source file to narrow to.
+- *Accepted work's standup-script proposal with four changes*, the load-bearing
+ one being that the script is a draft Craig edits at the gate. A topic list
+ fails safe by forcing him to compose; a wrong script reads fluently enough to
+ be spoken unchanged. Work agreed this was better than what they sent.
+
+** Data Collected / Findings
+
+*The narrowing, shipped as =f69dc22=.* Each dirty path under the synced roots
+becomes an =--exclude= on its own rsync. A dirty =protocols.org= skips only its
+own single-file transfer. A rename withholds both names, since sweeping the old
+copy would delete a file the project still runs mid-rename. The run now names
+what it held back. Suite went 15 → 22 tests; six were written red on purpose to
+invert the "ONE dirty file blocks ALL THREE rsyncs" characterization.
+
+*Verified end-to-end against the live checkout*, which is the strongest evidence
+here: mid-change, rulesets had two dirty files under the synced paths. The run
+propagated 48 workflows and withheld exactly those two, naming them. The same
+run under the old guard would have synced nothing.
+
+*I was wrong about project-workflows shadowing.* I told work their
+=.ai/project-workflows/daily-prep.org= would shadow the synced copy and starve
+them of updates. Phase 11 says the project file runs as *additional* steps
+appended, "not a replacement" — daily-prep composes both. I had generalized from
+=protocols.org='s workflow-selection rule, which governs dispatching a *named*
+workflow. Their duplication concern was real by a different route and they
+handled it with a marked stopgap carrying an explicit delete condition.
+
+*Known false-success path, still open and still load-bearing:* the success line
+prints unconditionally, so a run whose rsyncs all failed still reports a clean
+sync. The manifest must not be written from that branch as it stands.
+
+** Files Modified
+
+- =claude-templates/.ai/workflows/daily-prep.org= (=a212eeb=) — standup scripts,
+ Phase 8 blocking gate, generalized worked example.
+- =claude-templates/.ai/scripts/sync-templates= + its bats suite (=f69dc22=) —
+ the narrowing.
+- =todo.org=, =.ai/notes.org= (=cb31fd2=) — voice pattern #48 filed, inbox marker.
+- =working/sync-model-revert/= (=1c222cb=) — the parked .emacs.d handoff, which
+ had been sitting untracked against the working-files rule.
+
+KB: promoted 0 / consulted no
+
+** Next Steps
+
+1. *Build the last-synced manifest* — the other half of the propagation fix, and
+ the one .emacs.d's measurement said matters more, since silent drift is the
+ ordinary case and the loud crash the exception. Its design constraint is in
+ =working/sync-model-revert/=: the report must carry the *diff*, not just a
+ backup path, so a reader can tell in one look whether the canonical already
+ contains their patch or whether their change was thrown away. Fix the
+ unconditional success line first or the manifest will stamp success onto a
+ sync that did nothing.
+2. *Voice pattern #48* is filed =[#B]= and fully specified — Craig approved the
+ =interaction.md= mirror, so both homes get the rule with a cross-reference
+ line in each, plus #48 into the attestation high-recurrence set. Work's
+ suggested text needs its em-dashes stripped before it lands.
+3. *Process note worth fixing:* every pre-commit review this session ran inline
+ rather than in an isolated subagent, because of the session's no-Agent-tool
+ directive. It caught real defects both times, but a self-review is weaker
+ evidence than an isolated one, and =subagents.md= names this as the standing
+ isolation-override case.
+
+Longer queue, unchanged: sentry's stashed =CronCreate= port and the per-project
+declaration model, the MCP scoping of five work-bound servers, velox's Keep
+token, the nag-event rule corrections, and the =[#A]= account-binding task whose
+premise may be wrong.
+
+* Session Log
+
+** 2026-07-31 Fri @ 11:24:43 -0500 — flushed
+
+Craig returned after the 06:32 wrap and asked to flush before taking the
+propagation outage. In flight: nothing on disk, tree clean at =cbcd972=. The
+work ahead is a design answer, not an edit, so nothing is half-finished. Read
+=.emacs.d='s 08:16 handoff and folded its diff-in-the-report point into the
+Findings above before clearing, since it changes the manifest design and would
+otherwise have to be re-read.
+
+** 2026-07-31 Fri @ 13:22 -0500 — inbox processed, standup-scripts shipped
+
+Three handoffs from work arrived mid-session and preempted the sync question.
+
+Accepted work's standup-brief proposal with four changes and shipped it as
+=a212eeb=: generalized their worked example (it carried real names, an
+=AWS Secrets Manager= detail, an investor demo and a specific bug into a file
+that syncs everywhere), dropped their "exactly None." punctuation change (it
+contradicted the Standups section, which already mandates =Blockers: None=),
+scoped the gate to *each* standup rather than the day (their phrasing would
+have passed the same text under both headers), and added the clause that the
+script is a draft I edit at the gate. That last one is the real finding: a
+topic list fails safe by forcing me to compose, where a wrong script reads
+fluently enough to be spoken unchanged. Work agreed it was better than what
+they sent.
+
+*I was wrong about the fork.* I told work their =.ai/project-workflows/daily-prep.org=
+would shadow the synced copy and silently starve them of updates. Phase 11 of
+the template says the project file runs as *additional* steps appended, "not a
+replacement" — daily-prep composes both, and there is no shadowing. I
+generalized from =protocols.org='s workflow-selection rule, which governs
+dispatching a *named* workflow, not this composition. Their duplication concern
+was real by a different route and they handled it with a marked stopgap
+carrying an explicit delete condition.
+
+Voice pattern #48 (corrective antithesis, "X rather than Y") filed =[#B]=. Two
+additions on the task: it belongs in the attestation high-recurrence set
+immediately, and the frequency cap needs mirroring into =interaction.md=,
+because Craig noticed the pattern in *conversation* and the voice skill only
+runs on publish artifacts.
+
+*Process note:* the Step 1 pre-commit review ran inline rather than in an
+isolated subagent, because this session's directive is not to call the Agent
+tool unattended. It caught two real defects (a self-contradicting Blockers rule
+and an example that undercut it), but a self-review is weaker evidence than an
+isolated one.
+
+*Still open and unanswered:* the sync-narrowing question from the top of the
+session. Options and recommendation are in the Summary above; nothing has been
+built.
diff --git a/.ai/workflows/code-quality.org b/.ai/workflows/code-quality.org
index 0481166..3c4ed8f 100644
--- a/.ai/workflows/code-quality.org
+++ b/.ai/workflows/code-quality.org
@@ -12,7 +12,7 @@ workflow only sequences them and collects the residue.
*Behavior-preserving rests on a test net.* The passes below claim to preserve
behavior, but a refactor on untested code is a guess, not a preservation. Where
the scope has no tests, bring it under a characterization net first
-(Normal/Boundary/Error per unit, per =testing.md='s "Adding Tests to Existing
+(Normal/Boundary/Error per unit, per the =testing-standards= skill's "Adding Tests to Existing
Untested Code") — that net is what turns "behavior-preserving" from an assertion
into something the green suite actually verifies across each pass.
diff --git a/.ai/workflows/daily-prep.org b/.ai/workflows/daily-prep.org
index 3f21214..9f706d1 100644
--- a/.ai/workflows/daily-prep.org
+++ b/.ai/workflows/daily-prep.org
@@ -130,12 +130,33 @@ Morning Prep is where Craig reads the prep doc, mentally walks the schedule, and
The Yesterday / Today / Blockers brief nests *directly under the standup meeting it's reported in* — never in a separate section. Plain section labels, no parenthetical questions in the rendered doc.
-- *Blockers is always present.* When there are none, write =Blockers: None= explicitly — silence is ambiguous.
+*The brief is a script, not a topic list.* The lines under each label are the words Craig says — complete first-person spoken sentences. Not fragments, not noun phrases, not a "bring these up" list. A topic list makes him compose the sentence live from a cue he wrote the night before and has since forgotten the shape of; a script is readable as-is. "Brief" invites bullets and bullets decay into topics, which is exactly the failure this rule exists to prevent.
+
+The script is a *draft for Craig to edit at the Phase 8 gate*, never words put in his mouth. That cuts both ways: a topic list forces him to compose and so fails safe, while a wrong script reads fluently enough to be spoken unchanged. So it gets the same gate scrutiny as the priorities.
+
+- *Blockers is always present.* A real blocker is stated as a full sentence, not a noun phrase. When there are none, write =Blockers: None= explicitly — silence is ambiguous.
- *Outcomes, not attendance.* Never "met with <person>" — instead what came out of it: "<person> finished the branch CI/CD work." Never "went to the managers' meeting" — instead the development from it that affects this audience.
- *No recurring 1:1s or ceremonies* in briefs — they're not news.
- *Match the standup's altitude.* An engineering standup gets engineering-goal material only: what moved the platform or the demo forward — architecture docs, PRs, tracker tickets, partner meetings with use-case implications, integration discussions, security findings, dataset discoveries. It does NOT get: 1:1s, attending other standups, personal-tooling maintenance, profile updates, sending messages or email, meeting prep, booking travel, or interviews with non-engineering candidates. The three questions are really: (a) how have I moved us closer to the engineering goals, (b) what will I work on that moves us closer, (c) what information do I have that might impact the team or its goals.
- A business-level (general) standup is different: features finished that leadership wanted, vacation/travel that affects availability or velocity, conference learnings, partner/customer decisions, cross-functional confusion worth clearing up. *Exclude routine maintenance and operational items — PR reviews don't belong here.* Foundational or strategic engineering work does; operations don't.
+Worked contrast — the same day's material, written both ways:
+
+#+begin_example
+Topics (the failure mode — a cue list, not a brief):
+ Bring: the freeze status, since Monday-or-later is the current answer.
+ The blocked review. The access request.
+
+Script (what belongs in the doc):
+ Yesterday: I fixed the bug where the selected region stayed editable
+ after an edit, and that's up for review along with the dependency
+ migration.
+ Today: I'm holding merges to development until the demo actually
+ happens, which now looks like Monday or later.
+ Blockers: None — the access request I raised Monday sits with the
+ platform team now, so it's slowing them rather than me.
+#+end_example
+
(Drafting rules — first-person, deadline precision, recurring-meeting filters, the team-visible test — are in Phase 6.)
*** Meetings
@@ -315,7 +336,9 @@ Combine session history + the sweep + Day's Priorities + WAITING items into Yest
- *Today*: 2-3 items max, from Day's Priorities. Include non-recurring meetings regardless of response status.
- *Blockers*: the bar is "did this actually stop me from making progress?" — not "is someone else involved?" Default to under-reporting; Craig adds borderline items at the gate. FYIs come after blockers and stay loose.
- *Team-visible filter*: only work that left Craig's local environment — pushed, shared, posted, changed in the tracker, or shifts what the team believes or plans. "If I didn't mention this, would someone make a worse decision or duplicate work?" If no, cut it.
-- Readable aloud in under 60 seconds.
+- *Write the words, not the topics.* Every line is a complete first-person sentence Craig can read aloud unchanged — see the worked contrast in the template's Standups section. No bare noun phrases, no "bring up X", and no identifier he wouldn't actually say out loud (a ticket key is fine where the team speaks in ticket keys, and wrong where they don't).
+- Readable aloud in under 60 seconds — roughly 120-150 words across the three sections. Over budget means cut an item, not compress a sentence back into a fragment.
+- *One script per standup.* Two standups on the same day get two separately-drafted scripts, because the altitude rules above admit different material to each. The same text under both headers is a defect, not a shortcut.
*** Step 3: Capture learnings
@@ -331,6 +354,8 @@ Also assemble the end-of-day block's upcoming-deadlines list: =DEADLINE:= entrie
Present the assembled doc and ask whether Craig agrees with the Day's Priorities. If not, work with him to add / remove / substitute priorities and blocks until he confirms. Surface here, in one pass: meeting-goal questions, decline candidates, look-ahead flags, carry-forward decisions, and proposed schedule adjustments.
+*Standup-script check (blocking).* The prep is not complete until every standup on that day's calendar carries its own script under its header, in the Phase 6 shape — spoken sentences, =Blockers:= present, altitude-matched. Check each standup individually and present the scripts at this gate for Craig to edit. Vacuous on a day with no standup, which is the common case in projects that hold none. This check exists because Phase 6's prose alone did not hold: on 2026-07-31 a prep wrote topic lists under both standup headers while every rule requiring a script was already on the page. Adding more prose to Phase 6 would not have caught that — the prose is what got skipped, so the requirement has to sit on a gate that blocks.
+
If the gate produces substantive rework, say so plainly: that's a =todo.org= staleness signal — the file should make Craig's current priorities obvious. Offer a task review.
Update mode replaces the gate with a delta summary: what changed and why.
@@ -448,3 +473,6 @@ The prep doc is born in =daily-prep/YYYY-MM-DD-daily-prep.org= and never moves;
*** 2026-06-11: Full template rewrite — strict three-section doc, two run modes, mandatory priorities gate
From Craig's instructive template spec (written 2026-06-10 evening, after reviewing generated preps) plus four refinements from his review of the first new-format prep. The doc is now exactly =* Heads-Up= / =* Day's Priorities= / =* Meetings / Focus Blocks=. Retired: the separate =* Standup Briefs= and =* Upcoming Deadlines= sections (briefs nest under their standup meeting; deadlines live in the end-of-day block), the =* [Day]'s Anchor Tasks= handoff (carry-forward lands directly in the next day's priorities, which are being built in the same sitting), the thin-link convention (entries mirror their todo.org task's heading and carry their own context — links in the body, never the heading), and standup-only mode (a brief refresh is an Update-mode run). New: two run modes (Create, with a MANDATORY end-of-flow priorities review gate whose disagreement signals todo.org staleness; Update, for when the world moves) both preceded by a triage-intake freshness check (no run in the last hour → run one first); event headers are the exact calendar title with ALL content nested under the event; per-event-type content rules (Morning Prep conflict-resolution strategy with drafts pre-written in the doc ready to send, standup altitude matching with =Blockers: None= explicit and operations excluded from business-level briefs, meetings carrying contribute/get/likely-questions with day-before prep blocks for "I don't know" answers and prep docs always =file:=-linked — the lesson of a prep that existed but couldn't be found in the minutes before a meeting that mattered, focus blocks as linked menus created day-before and marked free, lunch floor, the end-of-day "What Kind of Day Has It Been?" block carrying the deadlines list and generating tomorrow's prep); the look-ahead renders one day per line (=Fri 12:= …) with clear days marked =clear=; a requested-metrics Heads-Up slot rendered only when a metric is active (none yet); meetings verified against the live calendar at build and update time.
+
+*** 2026-07-31: Standup briefs are verbatim scripts, enforced at the Phase 8 gate
+A prep wrote =Bring:= topic lists under both standup headers while every rule requiring a Yesterday/Today/Blockers brief was already on the page. The rule existed and was skipped, so the fix is a gate rather than more prose: Phase 8 now blocks until every standup on the day's calendar carries its own script, and the Standups section says plainly that the lines are the words Craig speaks — complete first-person sentences, one script per standup since the altitude rules admit different material to each, roughly 120-150 words for the under-60-seconds target. A worked topics-vs-script contrast sits with the shape rules, because prose decays back into bullets and an example doesn't. The script is a draft Craig edits at the gate, never words put in his mouth: a topic list fails safe by forcing him to compose, where a wrong script reads fluently enough to be spoken unchanged.
diff --git a/.ai/workflows/helper-mode.org b/.ai/workflows/helper-mode.org
index a6acfa7..b32d574 100644
--- a/.ai/workflows/helper-mode.org
+++ b/.ai/workflows/helper-mode.org
@@ -12,13 +12,14 @@ The governing fact behind every rule below: the session-context split isolates e
* When to Use This Workflow
-No operator trigger phrase. A helper reaches this contract one of three ways:
+No operator trigger phrase. A helper reaches this contract one of two ways:
- The =ai --helper= launcher routes here after the roster confirms a live agent (the deterministic path).
-- Startup's roster check finds the session is not alone and routes here instead of running normal startup (the safety net for a raw =claude= launch).
- An explicit "you are a helper, follow helper-mode.org" instruction (the manual fallback).
-If none of those applies — the roster shows the session is alone — this is a primary session. Run normal [[file:startup.org][startup.org]], not this.
+There is deliberately no third way, and the gap matters: *startup does not check the roster*. A bare =claude= launched into a project that already has a live session runs full primary startup — pulls, rsync, inbox processing — without ever reaching this file. That safety net is designed (see Status below) but unbuilt, so nothing catches a raw launch. Use =ai --helper=.
+
+If neither route applies, this is a primary session. Run normal [[file:startup.org][startup.org]], not this.
* Identity
@@ -92,10 +93,28 @@ A helper does not run normal startup. It runs a light version:
When the helper's work is done:
-1. Re-run the roster (=.ai/scripts/agent-roster=) to learn whether a primary is still live.
+1. Re-run the roster to learn whether a primary is still live. Pass the project root explicitly — =agent-roster= defaults to =$PWD= and keeps only agents at or inside that root, so calling it from a subdirectory hides a primary sitting at the root and reports "alone":
+
+ #+begin_src bash
+ root="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
+ if [ -x "$root/.ai/scripts/agent-roster" ]; then
+ "$root/.ai/scripts/agent-roster" "$root"; rc=$?
+ else
+ rc=2
+ fi
+ echo "roster rc=$rc"
+ #+end_src
+
+ Read rc as =wrap-it-up.org= Step 0 does: 1 means a primary is still live, 0 means this helper is orphaned, and 2 (or an absent script) means unavailable — which takes the same archive-only path as 1, because leaving work uncommitted is recoverable and committing under a live primary is not.
2. *Primary still live (the normal case):* finalize the Summary in the helper's own =.ai/session-context.d/<id>.org=, archive it to =.ai/sessions/YYYY-MM-DD-HH-MM-<id>-<description>.org=, and stop. Do NOT commit, push, or run hygiene — the primary's next commit picks up the archived file and any scoped edits the helper left in the tree.
3. *Orphaned helper (roster shows the helper is now alone):* the primary already exited, so the helper assumes full closing duties — the git ban lifts because the concurrency that justified it is gone. Commit and push the tree (including the helper's own edits, which would otherwise strand as a dirty tree), per the normal wrap-up flow in [[file:wrap-it-up.org][wrap-it-up.org]].
* Status
-Phase 1.5 of the generic-agent-runtime spec. This contract is the canonical home; the spawn paths (=ai --helper=, startup's roster branch) and the [[file:wrap-it-up.org][wrap-it-up.org]] helper branch route here. Those wiring pieces ship behind the spec's bats-then-drills-then-pilot gate and are not yet live; until then, the manual "you are a helper" instruction is how a session adopts this contract.
+Phase 1.5 of the generic-agent-runtime spec. This contract is the canonical home; the spawn paths and the [[file:wrap-it-up.org][wrap-it-up.org]] helper branch route here.
+
+Live now: =ai --helper <project>= (roster check, id assignment, helper opener, its own tmux window), the explicit "you are a helper" instruction, and the wrap-it-up.org Step 0 helper branch.
+
+Not built yet, and worth knowing because it is the gap you can fall into: *startup has no roster check*. A second session launched as a bare =claude= in a project that already has one runs full primary startup — pulls, rsync, inbox processing — with no idea another agent is live. Until that safety net exists, =ai --helper= is not merely the preferred path, it is the only one that makes a helper without being told.
+
+Also unbuilt: the live-helper gate that pauses a primary's file-wide hygiene passes (=todo-cleanup.el=, =lint-org.el=, =wrap-org-table.el=) while a helper is mid-edit. Data-integrity rule 1 above describes the intended behavior; nothing enforces it yet, so a primary running hygiene can still clobber a helper's just-written scoped edit.
diff --git a/.ai/workflows/inbox.org b/.ai/workflows/inbox.org
index fc8091b..6faa20f 100644
--- a/.ai/workflows/inbox.org
+++ b/.ai/workflows/inbox.org
@@ -346,7 +346,7 @@ When Craig has put the session in no-approvals mode, an accepted item may be imp
2. *Quick* — the whole implementation, including verification, is under ~15 minutes.
3. *Solo* — you can carry it end to end without a decision from Craig. Manual verification you perform yourself is fine; needing Craig to choose an option, approve a design, or resolve an ambiguity is not.
-All three → implement it, verify, then commit and push at the end of that item (the Step 0 reconcile and pre-push check from =commits.md= still run). Miss any one and it doesn't self-apply: a shared-asset or convention change needs Craig's decision, so it fails *solo* and routes to the defer-and-stage park (core §2 / core §3); an oversized item fails *quick* and gets filed.
+All three → implement it, verify, then commit and push at the end of that item (the Step 0 reconcile and pre-push check from the =publish= skill still run). Miss any one and it doesn't self-apply: a shared-asset or convention change needs Craig's decision, so it fails *solo* and routes to the defer-and-stage park (core §2 / core §3); an oversized item fails *quick* and gets filed.
** Replying to handoffs
diff --git a/.ai/workflows/no-approvals.org b/.ai/workflows/no-approvals.org
index 5f54b96..6b5c7fa 100644
--- a/.ai/workflows/no-approvals.org
+++ b/.ai/workflows/no-approvals.org
@@ -35,7 +35,7 @@ Mode resets when:
The interaction gates that step the workflow back to Craig for an "OK to proceed?" check:
-- The commit-message gate in =commits.md= Step 2. Print the final commit message inline, then commit immediately. No "approve / request changes / open in editor" prompt.
+- The commit-message gate in the =publish= skill, Step 2. Print the final commit message inline, then commit immediately. No "approve / request changes / open in editor" prompt.
- The PR-description gate. Print the final body, then create the PR.
- The PR-review-reply gate. Print the final reply, then post.
- "Ready to start?" / "Plan looks like X, proceed?" gates before implementation work begins.
@@ -46,10 +46,10 @@ The interaction gates that step the workflow back to Craig for an "OK to proceed
The engineering-discipline gates protect quality, not Craig's interaction time. They remain in force:
-- =/review-code= against the staged diff before every commit. Critical and Important findings still block. Minor findings still surface. No "proceed anyway" override unless Craig has given it explicitly for this batch.
+- =/review-code= against the staged diff before every commit, dispatched as an isolated adversarial reviewer per the =publish= skill's Step 1 — no-approvals removes *interaction* gates, never the isolation. Critical and Important findings still block, and the re-review loop still runs to approval. Minor findings still surface. No "proceed anyway" override unless Craig has given it explicitly for this batch. If the review can't reach approval — three rounds, a recurring finding, or a =Needs Discussion= verdict — that is a genuine question: park the item per step 4 and move to the next one rather than committing past a standing finding.
- =/voice personal= on every publish artifact (commit messages, PR titles + bodies, PR review comments). The full pattern walk happens. The printed result just doesn't wait for approval.
- The full test suite + lint + compile before commit (per =verification.md=).
-- Fetch-and-reconcile in =commits.md= Step 0.
+- Fetch-and-reconcile in the =publish= skill, Step 0.
- Session Log updates per =protocols.org=. Every state-mutating turn writes to =.ai/session-context.org= before the closing message. The log is the crash-recovery anchor while Craig is away. Missing entries lose work.
- Subagent review-gate cadence (=subagents.md=). Review each subagent's output before the next dispatch.
- Destructive or irreversible operations per =CLAUDE.md='s "Executing actions with care": force-push, =rm -rf=, dropping a column, dropping a branch, package removal. These need explicit consent regardless of mode. No-approvals is for *interaction* gates, not destructive-action consent.
@@ -70,7 +70,7 @@ For each item:
- Do the work.
- Update the Session Log per the rules in =protocols.org=.
-- Before any commit: run =/review-code= against the staged diff. Surface Critical and Important findings inline; fix them and re-review until clean. Minor findings show but don't block.
+- Before any commit: dispatch the isolated adversarial reviewer per the =publish= skill's Step 1 — never review your own staged diff inline. Surface Critical and Important findings; fix them and send the updated diff back to the *same* reviewer until it approves. Minor findings show but don't block and never earn another round. If the review can't reach approval — three rounds, a finding that recurs after being reported fixed, or a =Needs Discussion= verdict — park the item per step 4 with the standing findings and move on; don't commit past a blocking finding.
- Draft the commit message. Run =/voice personal= (the skill, or walk the patterns inline if unavailable). Print the final message inline before committing so the log shows it.
- Commit and push.
- One-line status between items ("Task X done, on to Y.") so Craig knows what's happening when he checks back in.
diff --git a/.ai/workflows/sentry.org b/.ai/workflows/sentry.org
index e25ca39..b25fc14 100644
--- a/.ai/workflows/sentry.org
+++ b/.ai/workflows/sentry.org
@@ -4,11 +4,11 @@
* Overview
-Sentry is an interval loop that keeps a project's hygiene current while Craig is away. Each fire walks a fixed list of passes — roam pull, inbox zero, triage (no mail or messengers), todo cleanup, task audit, working-files hygiene, spec board, link integrity, git health, prep freshness, bug and refactor finding, and (opt-in) solo-task implementation — and commits each pass's writing to a throwaway daily branch. Nothing pushes. In the morning Craig reviews the branch, squash-merges what he wants, and deletes it.
+Sentry is an interval loop that keeps a project's hygiene current while Craig is away. Each cycle walks a fixed list of passes — roam pull, inbox zero, triage (no mail or messengers), todo cleanup, task audit, working-files hygiene, spec board, link integrity, git health, prep freshness, bug and refactor finding, and (opt-in) solo-task implementation — and commits each pass's writing to a throwaway daily branch. Nothing pushes. In the morning Craig reviews the branch, squash-merges what he wants, and deletes it.
The design goal is a project that greets the morning already tidy, with every judgment call and every destructive action parked in an approval queue rather than executed unattended. Sentry does the mechanical sweeping; Craig does the deciding.
-This file is the engine. It owns the entry gates, the branch mechanics, the lock model, the per-fire pass runner, the digest and approval queue, the skip semantics, and the stop-sentry shutdown. The =agent-lock= helper (=.ai/scripts/agent-lock=) provides the locks. The passes reuse existing workflows (=inbox.org=, =triage-intake.org=, =clean-todo.org=, =task-audit.org=) under sentry's unattended contract.
+This file is the engine. It owns the entry gates, the branch mechanics, the lock model, the per-cycle pass runner, the digest and approval queue, the skip semantics, and the stop-sentry shutdown. The =agent-lock= helper (=.ai/scripts/agent-lock=) provides the locks. The passes reuse existing workflows (=inbox.org=, =triage-intake.org=, =clean-todo.org=, =task-audit.org=) under sentry's unattended contract.
* When to Use This Workflow
@@ -58,7 +58,7 @@ Craig types the sentry trigger, so the first moves run with him at the terminal.
Wait for an answer. Sentry can't start unattended from a dirty state; that's the point.
-3. *Green-suite gate.* Run the project's full suite (=make test=, or the project's equivalent — detect it). Read the output. If anything is red, describe the failures and offer to investigate before arming. The loop starts only on a green baseline, because every unattended fire measures itself against "did I break this?" and a pre-existing red poisons that check.
+3. *Green-suite gate.* Run the project's full suite (=make test=, or the project's equivalent — detect it). Read the output. If anything is red, describe the failures and offer to investigate before arming. The loop starts only on a green baseline, because every unattended cycle measures itself against "did I break this?" and a pre-existing red poisons that check.
4. *Prior sentry branch.* =git branch --list 'sentry/*'=. An unmerged =sentry/*= branch from a previous night means the morning review didn't happen. Surface it and offer to squash-merge or delete it now (Craig is present); don't stack a second sentry branch on the first.
@@ -75,53 +75,53 @@ Craig types the sentry trigger, so the first moves run with him at the terminal.
The host suffix (=uname -n=) stops a same-date collision between the two daily drivers. The working tree now sits on this branch overnight — the launch hands the repo to sentry until the morning merge. Reclaiming it mid-night means stopping sentry first (see Stop Sentry). Note the Emacs buffer-revert caveat to Craig if he has the repo open: files change on disk under him overnight, so buffers want reverting after the morning merge (see =emacs.md=).
-7. *Arm the loop.* Start =/loop= at the interval (default hourly; Craig's "every <interval>" phrase overrides) with the per-fire body being one sentry fire (the Pass Runner below). Confirm the arming in one line: interval, branch name, project.
+7. *Arm the loop.* Start =/loop= at the interval (default hourly; Craig's "every <interval>" phrase overrides) with the per-cycle body being one sentry cycle (the Pass Runner below). Confirm the arming in one line: interval, branch name, project.
* The lock model
Two locks, both served by =.ai/scripts/agent-lock= (names only; the helper owns the paths, which live on tmpfs under =$XDG_RUNTIME_DIR/agent-locks/=, host-local and cleared on reboot).
-*Single-runner lock* (=sentry-<project>=, where =<project>= is the repo-root basename: =basename "$(git rev-parse --show-toplevel)"= — the same derivation =wrap-it-up.org='s guard uses, so the two agree on the lock name). Each fire acquires it at fire start and releases it at fire end, and refreshes it between passes (the heartbeat, so a live fire's lock never ages past one pass). If =/loop= fires again while a previous fire still holds it, the new fire's acquire fails and the fire skips with one digest line — no two fires run at once. The bounded wait is short (a few seconds); a live fire means defer, not queue.
+*Single-runner lock* (=sentry-<project>=, where =<project>= is the repo-root basename: =basename "$(git rev-parse --show-toplevel)"= — the same derivation =wrap-it-up.org='s guard uses, so the two agree on the lock name). Each cycle acquires it at cycle start and releases it at cycle end, and refreshes it between passes (the heartbeat, so a live cycle's lock never ages past one pass). If =/loop= fires again while a previous cycle still holds it, the new cycle's acquire fails and the cycle skips with one digest line — no two cycles run at once. The bounded wait is short (a few seconds); a live cycle means defer, not queue.
*Roam-write lock* (=roam-write=). A pass that edits a file under =~/org/roam= acquires it, runs =capture-guard --wait= (the human-capture layer stays underneath), edits the working tree, triggers =systemctl --user start roam-sync.service=, and releases. The lock spans only edit-plus-trigger. Sentry never runs =git= against =~/org/roam= — roam-sync stays the repo's only committer (the 2026-06-24 one-git-owner rule). Pass 1's =pull --ff-only= is the sole, read-only exception.
-Every reclaim of a stale lock surfaces in the digest — the helper prints the reclaim note, and the fire records it. A reclaim during a genuinely slow pass is possible, so it's never silent.
+Every reclaim of a stale lock surfaces in the digest — the helper prints the reclaim note, and the cycle records it. A reclaim during a genuinely slow pass is possible, so it's never silent.
* The Pass Runner — one contract per pass
-Each fire, after acquiring the single-runner lock and verifying branch state (below), walks the pass list in order. Every pass follows the same four-step contract:
+Each cycle, after acquiring the single-runner lock and verifying branch state (below), walks the pass list in order. Every pass follows the same four-step contract:
1. *Probe* — a cheap existence check for the pass's target (named per pass below). Absent → the pass is one skip line in the digest and nothing more. This is what makes the pass list portable: passes self-activate where their target exists and stay silent elsewhere, with zero per-project configuration.
2. *Work* — run the pass under the unattended contract. Quick, solo, already-agreed mechanical actions execute. Anything destructive or requiring judgment does *not* execute — it appends to the morning-approval queue (what, why, the exact command or edit that fires on approval). A pass runs fully or not at all; there is no reduced-form pass.
-3. *Session-context entry* — a pass that does or queues work appends its digest line to the =session-context.org= Session Log (path resolved via =.ai/scripts/session-context-path=) before its commit, so a crash between them still leaves the trail. Per-pass lines for an all-quiet fire (every pass probe-skipped or no-op) are not written one by one — the fire collapses to a single heartbeat at fire-end (below), so an idle fire doesn't spray one skip line per pass.
+3. *Session-context entry* — a pass that does or queues work appends its digest line to the =session-context.org= Session Log (path resolved via =.ai/scripts/session-context-path=) before its commit, so a crash between them still leaves the trail. Per-pass lines for an all-quiet cycle (every pass probe-skipped or no-op) are not written one by one — the cycle collapses to a single heartbeat at cycle-end (below), so an idle cycle doesn't spray one skip line per pass.
4. *Commit* — if the pass wrote to disk, commit it: =chore(sentry): <pass> — <what changed>=. One commit per writing pass. A probe-skip or a no-op pass writes nothing and commits nothing.
Between passes, refresh the single-runner lock (=agent-lock refresh sentry-<project>=) — the heartbeat.
-** Branch-state verification (fire start, before the passes)
+** Branch-state verification (cycle start, before the passes)
-After acquiring the lock, confirm the fire is safe to run:
+After acquiring the lock, confirm the cycle is safe to run:
-- *On the right branch* — HEAD is =sentry/<today>-<host>=. If the loop was armed on a prior day and crossed midnight, the branch keeps the arming date; that's fine, morning teardown handles it. If HEAD is somehow *not* a sentry branch (an interrupted stop, a manual checkout), skip the whole fire with a digest line rather than committing onto main.
-- *Clean of foreign changes* — =git diff --quiet HEAD= excluding the spine set (=session-context.org= / =session-context.d/=, resolved via =session-context-path=). Sentry's own spine writes must not trip this; a genuinely unexpected dirty tree (something outside the spine changed and wasn't committed by a prior pass) poisons the fire — skip it with a digest line, the next fire retries.
+- *On the right branch* — HEAD is =sentry/<today>-<host>=. If the loop was armed on a prior day and crossed midnight, the branch keeps the arming date; that's fine, morning teardown handles it. If HEAD is somehow *not* a sentry branch (an interrupted stop, a manual checkout), skip the whole cycle with a digest line rather than committing onto main.
+- *Clean of foreign changes* — =git diff --quiet HEAD= excluding the spine set (=session-context.org= / =session-context.d/=, resolved via =session-context-path=). Sentry's own spine writes must not trip this; a genuinely unexpected dirty tree (something outside the spine changed and wasn't committed by a prior pass) poisons the cycle — skip it with a digest line, the next cycle retries.
* Unattended safety — skip, never degrade
-With no one at the terminal, any unsafe state makes the affected scope skip with one digest line, and the next fire retries. Unsafe states and their scope:
+With no one at the terminal, any unsafe state makes the affected scope skip with one digest line, and the next cycle retries. Unsafe states and their scope:
-- *Unexpected dirty tree* (non-spine) → skip the whole fire.
-- *Lost or un-acquirable single-runner lock* → skip the fire (another fire holds it, or the helper is missing).
+- *Unexpected dirty tree* (non-spine) → skip the whole cycle.
+- *Lost or un-acquirable single-runner lock* → skip the cycle (another cycle holds it, or the helper is missing).
- *A pass's own precondition unmet* (its probe fails, or a dependency is dirty) → skip that pass only.
-- *Red suite at fire-end* (see below) → the commits stay on the branch, flagged in the digest for morning review; the fire doesn't roll back.
+- *Red suite at cycle-end* (see below) → the commits stay on the branch, flagged in the digest for morning review; the cycle doesn't roll back.
-Skips are never silent and never partial. Inside a *working* fire, a pass line means the pass fully ran and a skip line names why it didn't. An *all-quiet* fire is not a silent skip either: its single =sentry at HH:MM: nothing= heartbeat is the explicit record that every pass found nothing, standing in for a wall of identical skip lines. The anti-silence rule targets a pass that hides work it should have surfaced; a quiet fire has surfaced that there was none.
+Skips are never silent and never partial. Inside a *working* cycle, a pass line means the pass fully ran and a skip line names why it didn't. An *all-quiet* cycle is not a silent skip either: its single =sentry at HH:MM: nothing= heartbeat is the explicit record that every pass found nothing, standing in for a wall of identical skip lines. The anti-silence rule targets a pass that hides work it should have surfaced; a quiet cycle has surfaced that there was none.
** Multi-day stall notification
-An unmerged prior =sentry/*= branch at fire start (the morning review never happened) skips the fire. After the *second consecutive* fire skipped for this reason, send one persistent desktop notification naming the project and branch:
+An unmerged prior =sentry/*= branch at cycle start (the morning review never happened) skips the cycle. After the *second consecutive* cycle skipped for this reason, send one persistent desktop notification naming the project and branch:
: sentry stalled: <branch> unmerged — merge or delete to resume
@@ -135,11 +135,11 @@ In order. Each names its detection probe. A pass whose probe fails is one skip l
2. *Inbox zero* — run =inbox.org= roam mode under the no-approvals contract: quick+solo+agreed items execute, shared-asset and convention proposals park (prepared diff, =VERIFY= task, sender reply) in the approval queue. Edits to =~/org/roam/inbox.org= take the roam-write lock + =capture-guard=. Probe: the roam clone or a project =inbox/= exists. Tidying the shared roam inbox is allowed from *any* project session, work included — it's housekeeping on a shared resource, not a durable KB-node write, so the work-denylist doesn't gate it (=knowledge-base.md=). Never park it as a cross-project boundary crossing.
-3. *Triage intake — mail and messenger sources excluded.* Run =triage-intake.org=, loading only its non-mail, non-messenger source plugins (calendar, PR/ticketing). The mail and messenger plugins — cmail, any Gmail variant, Telegram, Signal, chat DMs — are never loaded by a sentry fire: Craig ruled 2026-07-21 that sentry doesn't check email or messengers. A manual "triage intake" still scans everything. Probe: the project has at least one *active* triage source that survives that exclusion — a project-specific plugin (=.ai/project-workflows/triage-intake.*.org=), or a non-empty =:TRIAGE_SOURCES:= declaration naming general plugins that exist. Mere presence of the template-synced general plugins does *not* activate the pass; a project that declares no sources, or whose only declared sources are mail or messengers, probe-skips (see =docs/specs/2026-07-20-triage-source-activation-spec.org=). Destructive actions (deleting, archiving, sending) queue; they never fire unattended.
+3. *Triage intake — mail and messenger sources excluded.* Run =triage-intake.org=, loading only its non-mail, non-messenger source plugins (calendar, PR/ticketing). The mail and messenger plugins — cmail, any Gmail variant, Telegram, Signal, chat DMs — are never loaded by a sentry cycle: Craig ruled 2026-07-21 that sentry doesn't check email or messengers. A manual "triage intake" still scans everything. Probe: the project has at least one *active* triage source that survives that exclusion — a project-specific plugin (=.ai/project-workflows/triage-intake.*.org=), or a non-empty =:TRIAGE_SOURCES:= declaration naming general plugins that exist. Mere presence of the template-synced general plugins does *not* activate the pass; a project that declares no sources, or whose only declared sources are mail or messengers, probe-skips (see =docs/specs/2026-07-20-triage-source-activation-spec.org=). Destructive actions (deleting, archiving, sending) queue; they never cycle unattended.
-4. *Todo cleanup* — the =clean-todo.org= mechanics (hygiene pass + =--archive-done= + =--convert-subtasks=). Probe: a root =todo.org=. Note that =--archive-done= is not purely an org-file pass on its first run in a project: it creates =archive/task-archive.org= and appends a =.gitignore= entry, so it produces a real tracked-file commit and correctly trips the fire-end conditional suite. (archangel, first live run 2026-07-21.)
+4. *Todo cleanup* — the =clean-todo.org= mechanics (hygiene pass + =--archive-done= + =--convert-subtasks=). Probe: a root =todo.org=. Note that =--archive-done= is not purely an org-file pass on its first run in a project: it creates =archive/task-archive.org= and appends a =.gitignore= entry, so it produces a real tracked-file commit and correctly trips the cycle-end conditional suite. (archangel, first live run 2026-07-21.)
-5. *Task audit* — the *mechanical subset* of =task-audit.org= hourly (staleness counts, structural checks, cookie recomputation); the judgment half (priority regrades, consolidations, merge candidates) runs *once per night* and queues its findings rather than repeating them every fire. Probe: a root =todo.org=. A full audit every hour is too heavy and re-surfaces the same judgment calls all night. (takuzu, first live run 2026-07-21.) Factual staleness fixes that are unambiguous still execute.
+5. *Task audit* — the *mechanical subset* of =task-audit.org= hourly (staleness counts, structural checks, cookie recomputation); the judgment half (priority regrades, consolidations, merge candidates) runs *once per night* and queues its findings rather than repeating them every cycle. Probe: a root =todo.org=. A full audit every hour is too heavy and re-surfaces the same judgment calls all night. (takuzu, first live run 2026-07-21.) Factual staleness fixes that are unambiguous still execute.
6. *Working-files hygiene* — flag =working/<slug>/= directories whose backing task is closed (a filing candidate per =working-files.md=). Probe: a =working/= directory exists. The filing itself queues (it's a judgment move).
@@ -151,25 +151,25 @@ In order. Each names its detection probe. A pass whose probe fails is one skip l
10. *Prep + symlink freshness* — stale daily-prep docs, broken symlinks. Probe: the prep dir / symlinks exist (work and home only, in practice).
-11. *Bug and refactor finding* — hunt for real bugs and worthwhile refactoring opportunities in the project's codebase: static analysis (=shellcheck= for shell, the project's own linters for its languages), config sanity checks, plus one targeted code-reading area per fire. Rotate the area across fires and name it in the digest, so coverage accumulates over a night instead of re-reading the same corner. Randomized property sweeps (generate-and-verify against an engine's own invariants) are good quiet-fire work here, reaching past a frozen test corpus. Expect the pass to go honestly quiet after the first few fires find the standing defects; a quiet hunt is a result, not a failure. (takuzu, first live run 2026-07-21: three real fixes in the first four fires, then quiet.) This pass does *not* run the test suite — the entry baseline already ran it, and re-running it hourly is anti-pattern 5; read the entry result instead. Probe: the project carries a codebase — source under version control beyond its org and tooling files. File each verified bug as a graded task in =todo.org= per the severity × frequency matrix (=todo-format.md=), and each refactoring opportunity as a =:refactor:= task, deduped against existing tasks; an unverifiable suspicion is a digest line, not a task. *Find, never fix in this pass* — the finding files a task and stops. A fix happens only in the opt-in implementation pass below, and only after the finding is a filed task that pass then re-verifies from scratch (see the premise rule there). A freshly-found "bug" can be a misread — one was filed and retracted two fires apart on 2026-07-23 — so the file-then-verify-then-fix pipeline is deliberate: the task is the checkpoint, not a same-breath fix. (Added at Craig's order 2026-07-21, first dogfooded in dotfiles; refactor-finding added 2026-07-24.)
+11. *Bug and refactor finding* — hunt for real bugs and worthwhile refactoring opportunities in the project's codebase: static analysis (=shellcheck= for shell, the project's own linters for its languages), config sanity checks, plus one targeted code-reading area per cycle. Rotate the area across cycles and name it in the digest, so coverage accumulates over a night instead of re-reading the same corner. Randomized property sweeps (generate-and-verify against an engine's own invariants) are good quiet-cycle work here, reaching past a frozen test corpus. Expect the pass to go honestly quiet after the first few cycles find the standing defects; a quiet hunt is a result, not a failure. (takuzu, first live run 2026-07-21: three real fixes in the first four cycles, then quiet.) This pass does *not* run the test suite — the entry baseline already ran it, and re-running it hourly is anti-pattern 5; read the entry result instead. Probe: the project carries a codebase — source under version control beyond its org and tooling files. File each verified bug as a graded task in =todo.org= per the severity × frequency matrix (=todo-format.md=), and each refactoring opportunity as a =:refactor:= task, deduped against existing tasks; an unverifiable suspicion is a digest line, not a task. *Find, never fix in this pass* — the finding files a task and stops. A fix happens only in the opt-in implementation pass below, and only after the finding is a filed task that pass then re-verifies from scratch (see the premise rule there). A freshly-found "bug" can be a misread — one was filed and retracted two cycles apart on 2026-07-23 — so the file-then-verify-then-fix pipeline is deliberate: the task is the checkpoint, not a same-breath fix. (Added at Craig's order 2026-07-21, first dogfooded in dotfiles; refactor-finding added 2026-07-24.)
-12. *Solo-task implementation (opt-in — =:SENTRY_MAY_IMPLEMENT:=)* — work the backlog's solo, decision-free tasks on the branch. Probe: =.ai/notes.org= Workflow State carries =:SENTRY_MAY_IMPLEMENT: yes= *and* the project holds =:COMMIT_AUTONOMY:= (the implement pass commits). Absent the marker, skip — this pass is off by default, because it turns the morning from a two-minute merge into a code review, and that's the project owner's call. When on: invoke =work-the-backlog.org= under its unattended-loop contract (no pre-flight Q&A — there's no Craig overnight), eligibility =TODO= + =:solo:=, with the defer checklist deciding act-vs-file. The overnight-only tightening: only the *ready* bucket implements (clears every checklist item with zero open decisions); a task needing even one quick decision defers to a =VERIFY= rather than guessing, exactly as the loop caller already does. Commit each logical change to the sentry branch; *never push* — the morning review and merge is the gate, same as every other pass. The full quality bar holds (TDD, suite green before each commit, =/review-code=, =/voice=), and =/review-code= here runs the *premise check first*: reproduce the bug or confirm the problem is real before judging the diff. The review is the fact-checker that a filed claim never got, and it is what makes fixing-on-a-branch safe (Craig, 2026-07-24). A task that fails its premise check is not implemented — the finding was wrong, and that outcome is a digest line, not a commit. (Added at Craig's direction 2026-07-24: overnight implement-on-branch, gated and never-pushed.)
+12. *Solo-task implementation (opt-in — =:SENTRY_MAY_IMPLEMENT:=)* — work the backlog's solo, decision-free tasks on the branch. Probe: =.ai/notes.org= Workflow State carries =:SENTRY_MAY_IMPLEMENT: yes= *and* the project holds =:COMMIT_AUTONOMY:= (the implement pass commits). Absent the marker, skip — this pass is off by default, because it turns the morning from a two-minute merge into a code review, and that's the project owner's call. When on: invoke =work-the-backlog.org= under its unattended-loop contract (no pre-flight Q&A — there's no Craig overnight), eligibility =TODO= + =:solo:=, with the defer checklist deciding act-vs-file. The overnight-only tightening: only the *ready* bucket implements (clears every checklist item with zero open decisions); a task needing even one quick decision defers to a =VERIFY= rather than guessing, exactly as the loop caller already does. Commit each logical change to the sentry branch; *never push* — the morning review and merge is the gate, same as every other pass. The full quality bar holds (TDD, suite green before each commit, the isolated adversarial review per =publish= Step 1 with its re-review loop, =/voice=), and the review here runs the *premise check first*: reproduce the bug or confirm the problem is real before judging the diff. The review is the fact-checker that a filed claim never got, and it is what makes fixing-on-a-branch safe (Craig, 2026-07-24). A task that fails its premise check is not implemented — the finding was wrong, and that outcome is a digest line, not a commit. A task whose review never reaches approval — three rounds, a recurring finding, or a =Needs Discussion= verdict — is the same shape: no commit, and a digest line naming the standing findings, so the morning review sees what the reviewer would not pass rather than finding the task silently absent. (Added at Craig's direction 2026-07-24: overnight implement-on-branch, gated and never-pushed.)
(KB lesson promotion — the pass the original proposal listed eleventh — is deferred to vNext. An unattended judgment pass writing to the shared knowledge base waits until sentry has quiet weeks behind it and a designed detection heuristic. See the filed lesson-detection-heuristic task.)
-* Fire-end — conditional suite, then the digest commit
+* Cycle-end — conditional suite, then the digest commit
After the passes:
-1. *Conditional suite run.* If any pass this fire modified files *outside* the org/spine set (a code-touching pass, rare but possible via fixtures), run the full suite once. A green run confirms the fire's commits are safe; a red run flags the digest for morning review — the commits stay on the branch (nothing is pushed, so the morning gate catches it). No per-pass suite runs: the entry run is the green baseline, and hourly per-commit runs would turn a seconds-long fire into minutes all night. Fires that only touched org/spine files skip this.
+1. *Conditional suite run.* If any pass this cycle modified files *outside* the org/spine set (a code-touching pass, rare but possible via fixtures), run the full suite once. A green run confirms the cycle's commits are safe; a red run flags the digest for morning review — the commits stay on the branch (nothing is pushed, so the morning gate catches it). No per-pass suite runs: the entry run is the green baseline, and hourly per-commit runs would turn a seconds-long cycle into minutes all night. Cycles that only touched org/spine files skip this.
-2. *Heartbeat or digest, then commit.* Decide quiet vs working. A *quiet* fire — every pass probe-skipped or no-op, nothing added to the approval queue — writes a single heartbeat line to the Session Log, =sentry at HH:MM: nothing= (HH:MM local, from =date=), and no per-pass digest block. A *working* fire — any pass ran, wrote, or queued — writes its full per-pass digest block. Then commit any accumulated spine writes in one sweep: =chore(sentry): digest — <date> <time> fire= for a working fire, =chore(sentry): heartbeat — <date> <time>= for a quiet one, so even a quiet fire leaves a clean tree for the next branch-state check (where the spine is untracked, the mirror-only case, there is nothing to commit and the heartbeat line stays in the working-tree anchor). This is the silent-until-signal policy (see =docs/specs/2026-07-20-silent-until-signal-monitors-spec.org=): an all-quiet night collapses from a wall of no-op digests to a list of one-line heartbeats, while a fire that actually did or queued something still writes the full record.
+2. *Heartbeat or digest, then commit.* Decide quiet vs working. A *quiet* cycle — every pass probe-skipped or no-op, nothing added to the approval queue — writes a single heartbeat line to the Session Log, =sentry at HH:MM: nothing= (HH:MM local, from =date=), and no per-pass digest block. A *working* cycle — any pass ran, wrote, or queued — writes its full per-pass digest block. Then commit any accumulated spine writes in one sweep: =chore(sentry): digest — <date> <time> cycle= for a working cycle, =chore(sentry): heartbeat — <date> <time>= for a quiet one, so even a quiet cycle leaves a clean tree for the next branch-state check (where the spine is untracked, the mirror-only case, there is nothing to commit and the heartbeat line stays in the working-tree anchor). This is the silent-until-signal policy (see =docs/specs/2026-07-20-silent-until-signal-monitors-spec.org=): an all-quiet night collapses from a wall of no-op digests to a list of one-line heartbeats, while a cycle that actually did or queued something still writes the full record.
3. *Release the single-runner lock.*
* The digest and the approval queue
-*Digest.* A *working* fire appends its block to the =session-context.org= Session Log (the spine the fire already writes), so it survives a crash, rides the session archive, and is on screen in the running session. One block per working fire: the timestamp, then one line per pass (ran + what, or skipped + why), plus any lock reclaim notes. A *quiet* fire (nothing done or queued) writes no block — just the one heartbeat line =sentry at HH:MM: nothing= (the silent-until-signal policy). The per-pass block is a working-fire artifact; it still carries one line per pass so a real skip inside a working fire is never hidden.
+*Digest.* A *working* cycle appends its block to the =session-context.org= Session Log (the spine the cycle already writes), so it survives a crash, rides the session archive, and is on screen in the running session. One block per working cycle: the timestamp, then one line per pass (ran + what, or skipped + why), plus any lock reclaim notes. A *quiet* cycle (nothing done or queued) writes no block — just the one heartbeat line =sentry at HH:MM: nothing= (the silent-until-signal policy). The per-pass block is a working-cycle artifact; it still carries one line per pass so a real skip inside a working cycle is never hidden.
*Approval queue.* Destructive and judgment actions accumulate under one heading in the same file — =* Sentry approval queue (<date>)= — newest last. Each item carries three things: *what* (the action), *why* (what triggered it), and the *exact command or edit* that fires on approval. The morning review is Craig reading this heading top to bottom and running or discarding each item.
@@ -186,13 +186,13 @@ Sentry never merges its own branch. In the morning Craig:
A bad night is discarded by deleting one branch — nothing reached main, nothing was pushed.
-In a project that gitignores =.ai/=, the whole spine is untracked, so quiet fires produce no commits at all and =git log main..sentry/<date>-<host>= understates the night's activity. There the anchor's heartbeat list is the only record of what fired. Read the anchor, not just the log. (archangel, first live run 2026-07-21.)
+In a project that gitignores =.ai/=, the whole spine is untracked, so quiet cycles produce no commits at all and =git log main..sentry/<date>-<host>= understates the night's activity. There the anchor's heartbeat list is the only record of what fired. Read the anchor, not just the log. (archangel, first live run 2026-07-21.)
* Stop Sentry
Trigger: "stop sentry" (and synonyms above). Sentry owns its own shutdown:
-1. *Cancel the loop* — stop the =/loop= (=ScheduleWakeup= stop / the loop's stop path). No further fires.
+1. *Cancel the loop* — stop the =/loop= (=ScheduleWakeup= stop / the loop's stop path). No further cycles.
2. *Release the single-runner lock* if this context holds it.
3. *Branch disposition* — offer, inline-numbered:
1. Squash-merge the day's branch into main now (walk the morning teardown steps 3-5 interactively)
@@ -208,14 +208,14 @@ Stopping sentry is the only way to reclaim the working tree mid-night. The entry
* Common Mistakes
1. *Running without the =:COMMIT_AUTONOMY:= grant* — sentry commits unattended; the marker is the entry ticket, and its absence is a hard stop, not a degrade.
-2. *Starting from a dirty or red tree* — the entry gates exist because an unattended fire can't tell Craig's in-progress work from a regression. Answer the gate; don't bypass it.
-3. *Committing onto main* — every writing pass commits to the daily =sentry/*= branch. A fire that finds HEAD off the sentry branch skips rather than commits.
+2. *Starting from a dirty or red tree* — the entry gates exist because an unattended cycle can't tell Craig's in-progress work from a regression. Answer the gate; don't bypass it.
+3. *Committing onto main* — every writing pass commits to the daily =sentry/*= branch. A cycle that finds HEAD off the sentry branch skips rather than commits.
4. *Running a =git= write against =~/org/roam=* — roam-sync is the only committer. Sentry edits the tree under the roam-write lock and triggers the sync; it never commits or pushes roam.
-5. *A per-pass suite run* — the suite runs at entry (baseline) and conditionally at fire-end (only when a pass touched non-org files). Hourly per-commit runs all night is the anti-pattern the suite policy exists to prevent.
+5. *A per-pass suite run* — the suite runs at entry (baseline) and conditionally at cycle-end (only when a pass touched non-org files). Hourly per-commit runs all night is the anti-pattern the suite policy exists to prevent.
6. *Executing a judgment or destructive action unattended* — those queue for the morning with their exact command. The pass did its detection; Craig makes the call. The one sanctioned exception is pass 12's solo-task implementation, and only because it inherits work-the-backlog's full defer checklist (data-loss and irreversible actions defer, never execute) plus a premise-verifying review, and it commits to the branch rather than acting on anything live.
-7. *A silent skip* — inside a working fire, every skip writes a digest line naming why; a missing pass with no line reads as "ran clean" when it didn't. The one exception is not a violation: an all-quiet fire collapses to a single =sentry at HH:MM: nothing= heartbeat instead of one skip line per pass — the heartbeat is the explicit "nothing to do" record, per the silent-until-signal policy.
+7. *A silent skip* — inside a working cycle, every skip writes a digest line naming why; a missing pass with no line reads as "ran clean" when it didn't. The one exception is not a violation: an all-quiet cycle collapses to a single =sentry at HH:MM: nothing= heartbeat instead of one skip line per pass — the heartbeat is the explicit "nothing to do" record, per the silent-until-signal policy.
8. *Degrading a pass to a reduced form* — a pass runs fully or skips. No half-passes.
-9. *Letting an unmerged branch stall silently* — after two consecutive unmerged-branch skips, the persistent desktop notify fires. Don't suppress it.
+9. *Letting an unmerged branch stall silently* — after two consecutive unmerged-branch skips, the persistent desktop notify cycles. Don't suppress it.
10. *Merging sentry's branch automatically* — the morning teardown is Craig's. Sentry creates and commits; it never merges or deletes its own branch.
* Living Document
diff --git a/.ai/workflows/startup.org b/.ai/workflows/startup.org
index 929d482..bc89256 100644
--- a/.ai/workflows/startup.org
+++ b/.ai/workflows/startup.org
@@ -29,10 +29,16 @@ Inside a rulesets session, the project-repo refresh below covers this — the ru
#+begin_src bash
rs="$HOME/code/rulesets"
if [ -d "$rs/.git" ]; then
- if (cd "$rs" && git diff --quiet --ignore-submodules HEAD -- 2>/dev/null); then
+ gate="$rs/claude-templates/bin/git-worktree-gate"
+ if [ -x "$gate" ] && "$gate" sync-safe "$rs"; then
+ (cd "$rs" && git pull --ff-only origin main 2>&1) | tail -3
+ elif [ ! -x "$gate" ] \
+ && (cd "$rs" && git diff --quiet --ignore-submodules HEAD -- 2>/dev/null); then
+ # Bootstrap fallback for a checkout old enough not to have the shared
+ # gate yet. The pull that follows installs it for subsequent starts.
(cd "$rs" && git pull --ff-only origin main 2>&1) | tail -3
else
- echo "rulesets: dirty working tree — using as-is, skipping pull"
+ echo "rulesets: changes beyond untracked inbox deliveries — using as-is, skipping pull"
fi
else
echo "rulesets: not a git checkout — skipping"
@@ -40,11 +46,11 @@ fi
#+end_src
Behavior:
-- *Clean working tree* → fast-forward pull. =git pull --ff-only= refuses any merge or rebase, so the operation is either a no-op (already current) or a clean advance.
-- *Dirty working tree* → skip the pull. Don't auto-stash and don't auto-merge — those would either lose work or invite conflicts at the worst possible moment (session start).
+- *Clean working tree, or untracked deliveries only beneath =inbox/=* → fast-forward pull. =git pull --ff-only= refuses any merge or rebase, so the operation is either a no-op (already current) or a clean advance. Inbox files are queue input, not source-tree work, and do not block other projects from receiving rulesets updates.
+- *Any staged or tracked change, dirty submodule, Git operation in progress, or untracked file outside =inbox/=* → skip the pull. Don't auto-stash and don't auto-merge — those would either lose work or invite conflicts at the worst possible moment (session start).
- *Non-fast-forward history* → =--ff-only= aborts with an error. Surface that to the user; the rsync still proceeds against the working tree as-is.
-*Template-freshness policy (applies to every dirty-check in the synced workflows).* "Dirty" means *tracked modifications only*. Untracked and gitignored files — an inbox drop, a file left in the tree to read, scratch output — never block a template pull, a fast-forward, or a monitoring gate. Projects were falling behind on templates because somebody sent them a task; that's the failure this policy closes. The checks here already comply (=git diff --quiet HEAD= sees only tracked changes; the ff gate uses =--untracked-files=no=), and any dirty-check added to a synced workflow follows the same rule. One deliberate exception: the rsync WIP-guard below counts untracked files *within rulesets' own synced source paths*, because an untracked half-written template is exactly the WIP it exists to hold back — that guard is about rulesets' outbound content, not the consuming project's local state.
+*Template-freshness policy (applies to every dirty-check in the synced workflows).* The shared =git-worktree-gate sync-safe= policy is the source of truth: untracked files beneath =inbox/= and gitignored files do not block a pull, fast-forward, or monitoring gate; every other staged, tracked, untracked, submodule, or in-progress-operation state does. Projects must not fall behind merely because somebody sent them a task, but an arbitrary scratch file is not silently treated as safe. One deliberate exception remains: the rsync WIP-guard below is narrower than the repository gate and counts untracked files within rulesets' own synced source paths, because an untracked half-written template is exactly the WIP it exists to hold back.
*** Install rulesets symlinks into ~/.claude (idempotent)
@@ -74,8 +80,11 @@ if [ -d .git ]; then
current=$(git symbolic-ref --short HEAD 2>/dev/null)
dirty=0
- if ! git diff --quiet --ignore-submodules HEAD -- 2>/dev/null \
- || [ -n "$(git status --porcelain --untracked-files=no)" ]; then
+ gate="$HOME/code/rulesets/claude-templates/bin/git-worktree-gate"
+ if [ -x "$gate" ]; then
+ "$gate" sync-safe "$PWD" >/dev/null 2>&1 || dirty=1
+ elif ! git diff --quiet --ignore-submodules HEAD -- 2>/dev/null \
+ || [ -n "$(git status --porcelain --untracked-files=no)" ]; then
dirty=1
fi
@@ -107,8 +116,8 @@ fi
#+end_src
Behavior, per branch:
-- *Behind only, current branch, clean tree* → =git merge --ff-only= advances HEAD.
-- *Behind only, current branch, dirty tree* → fetched but not advanced. Surface so Craig can ff manually after dealing with the dirty state.
+- *Behind only, current branch, sync-safe tree* → =git merge --ff-only= advances HEAD. An untracked =inbox/= delivery is sync-safe.
+- *Behind only, current branch, sync-blocking tree* → fetched but not advanced. Surface so Craig can ff manually after dealing with the reported state.
- *Behind only, non-checkout branch* → =git fetch . upstream:branch= advances the ref without touching the working tree.
- *Diverged* (ahead and behind) → leave alone. Surface for Craig to resolve. Don't auto-rebase or auto-merge.
- *Ahead only* or *up to date* → silent no-op.
@@ -128,39 +137,24 @@ These calls have no dependencies on each other. Issue them all together in one m
#+end_src
3. *Sync =.ai/= from templates — but only when the synced source paths in rulesets are clean.* Guard the three rsyncs behind a check that =claude-templates/.ai/{protocols.org,workflows/,scripts/}= have no uncommitted changes. Otherwise Phase A copies in-flight rulesets WIP (tracked edits or new untracked files) into this project's =.ai/workflows/= and =.ai/scripts/=, where it shows up as drift the user didn't author. Skipping once is cheap — the next session with rulesets clean catches up. The check is scoped to the synced paths, so unrelated rulesets dirt (a stray =session-context.org=, scratch files) doesn't needlessly block the sync. A second guard skips the same rsyncs when the *project* branch is behind its upstream (=git rev-list --left-right --count @{u}...HEAD= with =behind > 0=): syncing templates onto a stale committed =.ai/= baseline measures the diff against old content, so it comes out huge and conflicts when the branch later reconciles to upstream, whose history already carries the newer templates. It composes with the rulesets-clean guard — a stable rulesets source and a current project branch are both required before the sync runs.
- #+begin_src bash
- rs="$HOME/code/rulesets"
- synced_dirty=$(cd "$rs" && git status --porcelain -- \
- claude-templates/.ai/protocols.org \
- claude-templates/.ai/workflows/ \
- claude-templates/.ai/scripts/ 2>/dev/null)
- # Skip the sync when the project branch hasn't reached its upstream. Syncing
- # templates onto a behind baseline measures the diff against stale committed
- # .ai/, producing confusing drift that conflicts when the branch reconciles —
- # the newer .ai/ is already in upstream. behind==0 (up-to-date or ahead-only)
- # means HEAD contains all of upstream, so the baseline is current. No upstream
- # (new/unpushed branch) → rev-list fails → proj_behind stays 0, sync runs.
- proj_behind=0
- if [ -d .git ]; then
- counts=$(git rev-list --left-right --count '@{u}...HEAD' 2>/dev/null) \
- && [ "$(printf '%s' "$counts" | cut -f1)" -gt 0 ] 2>/dev/null \
- && proj_behind=1
- fi
+ The logic lives in =.ai/scripts/sync-templates=, not inline here. It was extracted 2026-07-31 after an uncommitted edit in rulesets silently blocked all three rsyncs for a full day — five workflow files went stale in one downstream project alone, with nothing anywhere reporting it. A mechanism that distributes correctness fixes to every project needs tests, and inline bash in an org file cannot have them. The behavior is unchanged by the extraction (verified differentially, output and resulting tree both byte-identical); the guards it applies are described below.
- if [ -n "$synced_dirty" ]; then
- echo "rulesets has uncommitted changes under the synced template paths — skipping .ai/ sync this session (catches up when rulesets is clean):"
- echo "$synced_dirty" | sed 's/^/ /'
- elif [ "$proj_behind" -eq 1 ]; then
- echo "project branch is behind upstream — skipping .ai/ sync this session (templates never land on a stale baseline; the sync runs once the branch is current)"
+ #+begin_src bash
+ if [ -x .ai/scripts/sync-templates ]; then
+ .ai/scripts/sync-templates
else
- rsync -a "$rs/claude-templates/.ai/protocols.org" .ai/protocols.org
- rsync -a --delete "$rs/claude-templates/.ai/workflows/" .ai/workflows/
- rsync -a --delete --exclude='__pycache__' --exclude='.pytest_cache' --exclude='*.pyc' \
- "$rs/claude-templates/.ai/scripts/" .ai/scripts/
- echo ".ai/ synced from templates"
+ echo "sync-templates not present — .ai/ sync SKIPPED and cannot self-heal; recover with: bash ~/code/rulesets/scripts/audit.sh --apply --force"
fi
#+end_src
+ The fallback should never fire in the ordinary rollout. A project still on the pre-extraction startup.org runs the old inline block this session, which delivers both the script and this file together, and the next session finds the script in place. It covers only the split case — the =workflows/= rsync landing while the =scripts/= one didn't — where a project would otherwise hold this file with no script to call.
+
+ *That state does not self-heal, which is why the message names a command.* The fallback runs /instead of/ the sync, so there is no later sync to deliver the missing script: the project would announce one line per session forever while its templates froze. Recovery is out-of-band, via =scripts/audit.sh --apply --force= in rulesets, which rsyncs =scripts/= directly. =--force= is there because audit skips a tracked project holding uncommitted =.ai/= changes, which a project wedged across several sessions is likely to be.
+
+ One caveat on that recovery, worth knowing before running it: audit's =scripts/= rsync carries none of the =__pycache__= / =.pytest_cache= / =*.pyc= excludes this sync does, so it can deposit python cache artifacts that then need removing by hand. Tracked separately; it is a pre-existing gap in audit rather than something this path introduced.
+
+ Announcing the skip loudly with its remedy is the point; a silent skip is the exact failure this extraction exists to stop.
+
4. =\ls -t .ai/sessions/ 2>/dev/null | head -5= — list 5 most recent session files. The backslash bypasses any =ls= alias in the user's profile. Without it, bare =ls -t= silently returns no output under =exa= (a common =ls= replacement) — which makes a sessions directory full of files look empty, and the agent then skips Phase B step 2.
5. =\ls -la inbox/ 2>/dev/null= — inventory the inbox. Same reason for the backslash escape, applied uniformly across the Phase A =ls= calls.
6. Read =.ai/notes.org= — Project-Specific Context, Active Reminders, Pending Decisions sections (skip About This File).
@@ -170,12 +164,14 @@ These calls have no dependencies on each other. Issue them all together in one m
10. =[ -f "$HOME/org/roam/inbox.org" ] && grep -cE '^\*\* ' "$HOME/org/roam/inbox.org" || true= — count items in the roam global inbox (=~/org/roam/inbox.org=), the roam-mode startup nudge. Silent if the roam clone isn't on this machine. Phase C reads the file when the count is non-zero, splits total vs items related to this project, and surfaces the offer (see =inbox.org= roam mode). Read-only; never files at startup.
11. KB surface prep (the read + contribute startup nudges; see =docs/specs/2026-06-16-encourage-kb-contribution-spec.org=). Gated on the agent KB clone. Counts =:agent:= nodes, lists up to 5 whose content matches the current project basename (titles only; a few most-recent nodes as a fallback when nothing matches), and resolves the best-practices node path. Read-only; silent when the clone is absent. Phase C surfaces the relevant titles (consult) and the best-practices link (contribute).
+ The best-practices lookup matches the node's *filename*, not its content. A roam node's slug lives only in its filename, so the earlier content-grep (=rg -l 'agent-kb-best-practices'=) matched nothing and the contribute nudge silently pointed at an empty path in every project, every session, for as long as it shipped. =find= rather than a glob keeps the probe identical under bash and zsh (zsh aborts on an unmatched glob) — the same reason the spec-sort probe below uses =find=.
+
#+begin_src bash
ra="$HOME/org/roam/agents"
if [ -d "$ra" ]; then
proj=$(basename "$PWD")
echo "kb-total: $(rg -l '#\+filetags:.*:agent:' "$ra" 2>/dev/null | wc -l)"
- echo "kb-bestpractices: $(rg -l 'agent-kb-best-practices' "$ra" 2>/dev/null | head -1)"
+ echo "kb-bestpractices: $(find "$ra" -maxdepth 1 -name '*agent-kb-best-practices*.org' -print -quit 2>/dev/null)"
matches=$(rg -il "$proj" "$ra" 2>/dev/null | head -5)
[ -z "$matches" ] && matches=$(\ls -t "$ra"/*.org 2>/dev/null | head -3)
echo "kb-relevant-titles:"
@@ -202,7 +198,7 @@ These calls have no dependencies on each other. Issue them all together in one m
Fleet descriptions ("the fleet is ratio and velox") and runtime derivations ("run =uname -n= to find the hostname") don't match — only current-identity assertions do. Fixture-verified under bash and zsh.
-Notes on the rsync commands:
+Notes on what =sync-templates= does (the rsync behavior it carries):
- Trailing slashes on both source and destination matter — they tell rsync to sync /contents/ rather than nest a directory inside.
- =--delete= on the directory syncs lets retired template files actually disappear from each project on next startup.
- protocols.org is a single file, no =--delete= needed.
diff --git a/.ai/workflows/triage-intake.telegram.org b/.ai/workflows/triage-intake.telegram.org
index 5039a8b..1319da5 100644
--- a/.ai/workflows/triage-intake.telegram.org
+++ b/.ai/workflows/triage-intake.telegram.org
@@ -30,12 +30,27 @@ Telega does not autostart with the Emacs daemon. "Down" is its normal state
unless Craig has Telegram open in Emacs. The scan therefore runs the full
lifecycle every time, never skips because the server is down:
+⚠ *DOWN / not-loaded is the TRIGGER to launch, never a reason to skip or fail.*
+This is the exact mistake two projects (work + home, 2026-07-24) made: they
+probed telega, saw =(telega-server-live-p)= nil or telega not =featurep=, and
+reported =SCAN FAILED: telegram — not loaded= or a silent SKIP — a *blind*
+sweep — instead of running Step 1 to start it. A down or unloaded telega is the
+normal entry state; =(telega t)= both LOADS the package and STARTS the docker
+server (work confirmed: down → =(telega t)= → Ready, 18 chats). So the plugin
+MUST run Step 1's launch whenever telega is down/unloaded, wait for Ready, then
+scan. =SCAN FAILED= is reserved for a launch that was actually ATTEMPTED and did
+not reach Ready (image missing, server crash on start, daemon unreachable) —
+never for the pre-launch down state itself. The =:ENABLED:= guard above tests
+whether telega is INSTALLED (=fboundp=), not whether the server is up; a down
+server never disables the source.
+
1. Record prior state: TELEGA_WAS_RUNNING via (telega-server-live-p).
2. Launch (only if not running):
emacsclient -e "(progn (setq telega-use-docker t) (telega t) 'started)"
- The setq is mandatory defense: tdlib segfaults outside docker mode
- (2026-06-09), and Craig's daemon currently has telega-use-docker nil.
- Wait ~2s for Ready, then (telega--loadChats 'main) until telega--chats
+ The setq is mandatory defense: tdlib crashed in native mode when this was
+ set up (2026-06-09) — a separate matter from the SEGFAULT gotcha, which is
+ about the loadChats argument — and Craig's daemon defaults to nil.
+ Wait ~2s for Ready, then (telega--loadChats '(:@type "chatListMain")) until telega--chats
is populated.
3. Check messages: the maphash unread scan in ** Scan Step 2 (filters the
messageContactRegistered join-notice noise).
@@ -48,10 +63,13 @@ lifecycle every time, never skips because the server is down:
Verify: telega-server-live-p → nil, no zevlg/telega-server container in
docker ps. If Craig had it running, leave it untouched.
-If any lifecycle step fails (docker image missing, server crash, daemon
-unreachable), the sweep reports it as SCAN FAILED at the top of the summary
-per the engine's failure rule — never as a silent skip. Craig gets real
-traffic here.
+If any lifecycle step fails *after the launch was attempted* (docker image
+missing, server crash on start, daemon unreachable, Ready never reached), the
+sweep reports it as SCAN FAILED at the top of the summary per the engine's
+failure rule — never as a silent skip. This does NOT cover the ordinary
+pre-launch down state: a down server means "run Step 1," not "SCAN FAILED."
+Craig gets real traffic here, so a blind sweep that skipped the launch is worse
+than a clean failure — it hides real unread messages behind a false all-clear.
** Scan
@@ -85,22 +103,58 @@ TELEGA_WAS_RUNNING=$(emacsclient -e "(and (fboundp 'telega-server-live-p) (teleg
*** Step 1 — start (docker mode) if not already running, wait for Ready
#+begin_src bash
-# `(telega t)` starts without popping the root buffer. Docker mode (the stable
-# path — see the SEGFAULT gotcha) reconnects the persisted ~/.telega session in
-# ~2s. Then load the main chat list so telega--chats populates.
+# `(telega t)` starts without popping the root buffer. Docker mode reconnects the
+# persisted ~/.telega session in ~2s. Then load the main chat list so
+# telega--chats populates.
+#
+# The `(setq telega-use-docker t)` is mandatory and must come BEFORE `(telega t)`:
+# tdlib crashed in native mode when this was first set up (2026-06-09), and the
+# daemon's default is nil unless something (e.g. an Emacs-config :custom) has
+# already forced it. It was missing here while the Quick Reference required it —
+# a session that started telega without it on a native-mode daemon would take the
+# untested path. Match the Quick Reference exactly.
+#
+# Note this is a SEPARATE concern from the SEGFAULT gotcha below: that gotcha is
+# about the `loadChats` argument, and the deaths it explains happened in docker
+# mode. Docker mode is not a defense against it, and it is not evidence for
+# docker mode. Keep both.
emacsclient -e "(progn
+ (setq telega-use-docker t)
(unless (and (fboundp 'telega-server-live-p) (telega-server-live-p)) (telega t))
'started)"
# Poll until Ready with chats synced, or a crash/timeout. Background this with an
# until-loop so the wait doesn't block; exit on Ready-with-chats OR an abnormal
# server exit. Then force a chat-list load if the hash is thin:
-emacsclient -e "(progn (ignore-errors (telega--loadChats 'main)) (ignore-errors (telega--loadChats 'main)) 'loaded)"
+# NOTE: the chat-list argument must be a TL object, not the symbol 'main.
+# `telega--loadChats' puts it straight into the request as :chat_list, and a
+# bare symbol kills the server outright (see the SEGFAULT gotcha below).
+#
+# The liveness check on the tail is the load's only failure signal. `ignore-errors'
+# catches nothing here, because a bad argument kills the server process rather than
+# signalling in elisp, so without this the call returns 'loaded either way.
+# The `fboundp' guard matches Step 0: if the launch failed outright telega is not
+# loaded, and that should read as 'server-died like any other failure rather than
+# signalling void-function.
+emacsclient -e "(progn (ignore-errors (telega--loadChats '(:@type \"chatListMain\"))) (ignore-errors (telega--loadChats '(:@type \"chatListMain\"))) (if (and (fboundp 'telega-server-live-p) (telega-server-live-p)) 'loaded 'server-died))"
#+end_src
On a persisted session telega reaches status "Ready" within ~2s; the chat list
loads over a few more. If =(hash-table-count telega--chats)= is 0 or thin,
re-issue =telega--loadChats= and poll until it stabilizes.
+⚠ *=server-died= is SCAN FAILED, never a quiet account.* A server that dies
+during the load leaves a thin =telega--chats= hash, and a thin hash reads exactly
+like an account with little unread. That is the same false all-clear the
+down/not-loaded rule exists to prevent, arriving one step later in the lifecycle.
+It also fits the SCAN FAILED definition above: the launch was attempted and did
+not hold. So on =server-died=, report SCAN FAILED rather than scanning, and never
+report a low unread count from that run.
+
+This is the independent evidence the SEGFAULT gotcha asks for when it says to
+treat a short chat list as a real short list. Without the check there is no way
+to tell the two apart, which is how the =loadChats= crash stayed invisible
+through two investigations.
+
*** Step 2 — read unread, classified by last-message type
The single most important filter: =messageContactRegistered=. Telegram counts a
@@ -157,24 +211,61 @@ stays non-nil). =telega-server-kill= is what actually stops the server. Call
left in =docker ps=. Skipping this whole branch when =TELEGA_WAS_RUNNING= is t is
the point of Step 0: never tear down a session Craig is actively using.
-⚠ *SEGFAULT GOTCHA — crashes are spontaneous; treat server death as routine.*
-The dockerized =telega-server= (=zevlg/telega-server:latest=, image built
-2026-06-04, tdlib 1.8.64) SIGSEGVs (exit 139) *on its own*, minutes-to-hours
-into a session — 11 host coredumps between 2026-06-09 and 2026-06-11, several at
-times when no triage verb was running. The 2026-06-11 investigation reproduced
-the crash-free verbs and the spontaneous deaths side by side: coredump
-backtraces show a corrupted stack (memory corruption in the musl build), and
-no newer image exists upstream. Earlier theories — "native mode is the trigger",
-"toggle-read is the trigger" — were timing coincidences; the verbs are sound.
+⚠ *SEGFAULT GOTCHA — this was our bug, not tdlib's. Root-caused 2026-07-28.*
+=telega-server= dies with =Unexpected char 'm' in plist value= followed by
+=Assertion failed: false (telega-dat.c: tdat_plist_value: 500)=. The cause was
+this workflow: Step 1 called =(telega--loadChats 'main)=.
+
+The chain. =telega--loadChats= is a raw TL wrapper — it drops its argument into
+the request as =:chat_list= with no conversion. =telega-server--send= then
+=prin1='s the whole plist, and =telega--tl-pack= passes atoms through untouched,
+so the symbol goes out on the wire bare as =main=. The C parser
+(=server/telega-dat.c=, =tdat_plist_value=) accepts only =(=, =[=, ="=, =-=, a
+digit, =t=, =:=, or =n= to start a value. It hits =m=, prints that line, and
+calls =assert(false)=, which aborts the process. The =m= in the error is
+literally the first character of =main=.
+
+The symbol shorthand is real but belongs to a different layer:
+=telega-filter.el= and =telega-folders.el= convert =(eq cl-fspec 'main)= into
+='(:@type "chatListMain")=. The raw TL layer never does. telega's own callers
+always pass the object (=telega.el:290=, =telega-tdlib-events.el:516=).
+
+Proved by experiment, not inference (2026-07-28): from a live Ready server,
+=(telega--loadChats 'main)= killed it within seconds and added one coredump,
+with that exact assertion; a restart plus =(telega--loadChats '(:@type
+"chatListMain"))= survived three consecutive calls with no new coredump and no
+assertion.
+
+*The previous entry here was wrong and cost real time.* It recorded the deaths
+as spontaneous musl memory corruption and declared "the verbs are sound", which
+sent later investigations at the docker image and tdlib versions instead of at
+this file. The corrupted stack in the backtraces is what an =assert= abort looks
+like, not independent evidence of a memory bug. If crashes are ever seen again
+with *no* triage verb running, that is a genuinely separate cause and needs its
+own investigation — do not reuse the old spontaneous-crash story to explain it.
+
+*This crash kills a scan; it does not silently shorten one.* An earlier draft of
+this section claimed the reported "19 chats of ~50" was truncation caused by the
+bad call. That was wrong, and work disproved it at the wire level on 2026-07-28:
+with the corrected call their count is 19 before the first load and 19 after five
+(four on =chatListMain=, one on =chatListArchive=). Nineteen is the real size of
+that account. The same reading here — 19 stable across three corrected loads —
+was already sitting in the evidence and should have retired the claim before it
+was written down. Treat a short chat list as a real short list unless something
+independently shows the server died mid-sync.
+
+=ignore-errors= around the call never helped — the failure is the server process
+dying, not an elisp signal, so there is nothing for it to catch. That is why the
+death is easy to miss from inside elisp, and why a caller should check
+=(process-live-p (telega-server--proc))= after a load rather than trusting a
+returned value.
Operationally: docker mode stays mandatory (=telega-use-docker= = t; the setq
before =(telega t)= is still the right defense), and *every action batch checks
the server first* — =(process-live-p (telega-server--proc))= — restarting via
-=(telega t)= when dead and re-checking Ready before firing verbs. A mid-sweep
-death is recoverable, not an abort: restart, confirm Ready, resume. Durable-fix
-candidates if the crashing gets worse: pin a pre-2026-06 image digest, build
-=telega-server= natively against tdlib, or report upstream to zevlg with the
-coredumps (=coredumpctl list /usr/bin/telega-server=).
+=(telega t)= when dead and re-checking Ready before firing verbs. Any argument
+handed to a =telega--*= TL wrapper must be a TL object or a plain
+string/number/list, never a bare symbol.
Defense in depth: even if the server does die, the scan still works because it
reads the cached =telega--chats= hash, not a live query. A dead server is
diff --git a/.ai/workflows/work-the-backlog.org b/.ai/workflows/work-the-backlog.org
index a0b24a8..ea3f402 100644
--- a/.ai/workflows/work-the-backlog.org
+++ b/.ai/workflows/work-the-backlog.org
@@ -54,7 +54,7 @@ For the task set, in order, until the run cap is hit:
1. *Eligibility gate* (below). Ineligible → record =skipped-ineligible=, next task.
2. *Scope read* of the relevant code. Cheap; just enough to run the defer checklist.
3. *Defer checklist* (below). Any hit → defer: file the =VERIFY= naming the gap and record =deferred-VERIFY= (or, under the speedrun preset, route a quick-question gap to the pre-flight Q&A), next task.
-4. *Implement* under the project's commit discipline: TDD red→green→refactor, then =/review-code --staged=, fix all Critical/Important findings, then close the task per =todo-format.md='s completion rules. Decompose into as many logical commits as the change needs — size is not capped. If implementation fails partway, leave the tree working, record =failed=, surface it, and continue to the next task.
+4. *Implement* under the project's commit discipline: TDD red→green→refactor, then the isolated adversarial review (=publish= Step 1) with its re-review loop, fix all Critical/Important findings, then close the task per =todo-format.md='s completion rules. Decompose into as many logical commits as the change needs — size is not capped. If implementation fails partway, leave the tree working, record =failed=, surface it, and continue to the next task.
5. *Commit autonomy branch:*
- =file-only= → surface the diff, do *not* commit. Record =implemented-diff-surfaced=.
- =autonomous-commit= → =/voice personal= on the message, commit individually, push per the project's flow. Record =implemented-committed=.
@@ -110,7 +110,8 @@ Autonomy changes who approves, not what quality means. Per task, non-negotiable:
- *TDD* per =testing.md=: red first, green, refactor. The keystone checklist item already proved the failing test is writable.
- *Verification* per =verification.md=: fresh evidence, full suite green before any commit.
-- *=/review-code --staged=* before every commit; Critical and Important findings block until fixed.
+- *Isolated adversarial review* before every commit, dispatched per the =publish= skill's Step 1 — never an inline self-review, however small the diff. Critical and Important findings block until fixed, and each fix goes back to the *same* reviewer until it approves. Minor findings never earn another round.
+ - *When the review can't reach approval* — three rounds without it, a finding that recurs after being reported fixed, or a =Needs Discussion= verdict — the unattended run has no one to ask. Record the task =failed= with the standing findings in its result, leave the tree working, and continue to the next task. Never commit past a blocking finding because nobody is awake to adjudicate — an unreviewed commit landing overnight is the outcome this gate exists to prevent.
- *=/voice personal=* on every commit message on the =autonomous-commit= path (or the patterns walked inline if the skill is unavailable), message printed inline so the log shows what landed.
- *Task closure* per =todo-format.md=: depth-based completion (keyword + =CLOSED:= at level 2, dated rewrite at level 3+).
- *One logical change per commit.* A large task becomes several commits, not one omnibus.
diff --git a/.ai/workflows/wrap-it-up.org b/.ai/workflows/wrap-it-up.org
index 103e225..ecd3d22 100644
--- a/.ai/workflows/wrap-it-up.org
+++ b/.ai/workflows/wrap-it-up.org
@@ -24,11 +24,13 @@ The wrap-up is complete when:
2. *File is archived.* =.ai/session-context.org= has been renamed to =.ai/sessions/YYYY-MM-DD-HH-MM-description.org=. The old path no longer exists.
3. *todo.org is clean.* Cleanup script ran. Any auto-fixes are staged for the wrap-up commit. Orphan planning lines surfaced for manual fix if there are any.
4. *Linear board is honest* (skip if project doesn't use Linear). Any Dev-Review ticket whose PR has merged was moved to Done or PM Acceptance per the classification rule.
-5. *Git state is clean.* All changes committed + pushed to all remotes. Working tree clean.
+5. *Git state is certified clean.* All changes are committed + pushed to all remotes, =git-worktree-gate certify= succeeded at the current HEAD, and the working tree has no staged, unstaged, untracked, submodule, or in-progress-operation state.
6. *Valediction delivered.* Brief, warm closing with key accomplishments and reminders, ending with =session wrapped.= on its own line as the signoff marker.
The absence of =.ai/session-context.org= is the signal that the last session wrapped up cleanly. Its presence at session start means the previous session was interrupted.
+*A helper session meets a shorter list.* Criteria 1 and 2 apply to its own context file (archived under =.ai/sessions/YYYY-MM-DD-HH-MM-<id>-<description>.org=), and 6 applies. Criteria 3, 4, and 5 do not: hygiene, the Linear pass, and all git mutation belong to the primary, so a helper that satisfied criterion 5 would have violated its contract to get there. Step 0 routes this.
+
* Teardown mode (set from the trigger phrase)
The wrap itself — Steps 1 through 5 — is identical in every mode. The trigger phrase only decides what Step 6 does once commit + push and the valediction are done. Resolve the mode from the phrase before starting:
@@ -43,7 +45,35 @@ This depends on three functions in =.emacs.d/modules/ai-term.el= (=cj/ai-term-qu
* The Workflow
-** Step 0: Refuse if sentry is live
+** Step 0: Helper branch — a helper wraps only itself
+
+Resolve first whether this session is a helper, because a helper's wrap is a different and much shorter workflow. Everything from Step 1 down — the hygiene passes, the inbox check, the commit, the push, the clean-tree certificate — is primary-only under the role contract in [[file:helper-mode.org][helper-mode.org]], and running any of it from a helper is exactly the concurrency failure that contract exists to prevent.
+
+A session is a helper when =AI_HELPER=1= in its environment (=ai --helper= sets it) or when it adopted helper-mode.org this session by instruction. If neither holds, this is a primary: skip to Step 0.5 and wrap normally.
+
+#+begin_src bash
+echo "AI_HELPER=${AI_HELPER:-unset} AI_AGENT_ID=${AI_AGENT_ID:-unset}"
+#+end_src
+
+For a helper, re-run the roster — the answer decides which wrap applies:
+
+#+begin_src bash
+root="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
+if [ -x "$root/.ai/scripts/agent-roster" ]; then
+ "$root/.ai/scripts/agent-roster" "$root"; rc=$?
+else
+ rc=2
+fi
+echo "roster rc=$rc"
+#+end_src
+
+Pass the project root explicitly. =agent-roster= defaults to =$PWD= and keeps only agents whose cwd is at or inside that root, so running it from a subdirectory hides a primary sitting at the root — and the "alone" that produces is read below as *orphaned*, which is the one branch that commits and pushes. Capture =rc= inside the branch too: =[ -x … ] && …; echo $?= reports the status of the whole list, so an absent script reads as 1 (others live) rather than 2 (unavailable).
+
+- *Primary still live (rc 1)* — the normal case. Finalize the =* Summary= in the helper's own context file — same contract as Step 1, KB receipt line included (resolve it with =AI_AGENT_ID=<id> .ai/scripts/session-context-path=), archive it to =.ai/sessions/YYYY-MM-DD-HH-MM-<id>-<description>.org= so it can't collide with the primary's archive name, deliver the valediction, and stop. Do NOT commit, push, or run any hygiene pass. The helper's scoped edits stay in the tree and the primary's next commit carries them along with the archived file — say so in the valediction, so Craig knows the work is real but not yet pushed.
+- *Alone (rc 0) — orphaned helper* — the primary exited first, so the git ban lifts: the concurrency that justified it is gone, and stopping here would strand the helper's edits as a dirty tree nobody owns. Run the full wrap below starting at Step 0.5, exactly as a primary would.
+- *Roster unavailable (rc 2, or the script absent)* — take the archive-only path, the same as primary-still-live. Leaving work for the next session to commit is recoverable; guessing "orphaned" and committing underneath a live primary is not.
+
+** Step 0.5: Refuse if sentry is live
Before anything else, check whether sentry is running in this project. Sentry holds the working tree on its =sentry/<date>-<host>= branch and commits unattended; wrapping underneath it would archive the session anchor and tear down the buffer while the loop is still firing into it. If sentry's single-runner lock is held, stop and point at the shutdown path:
@@ -55,7 +85,7 @@ if [ -x .ai/scripts/agent-lock ] && .ai/scripts/agent-lock status "sentry-$proj"
fi
#+end_src
-The stop-sentry operation (defined in =sentry.org=) owns the shutdown: it cancels the loop, disposes of the branch, and walks the approval queue. Wrap-up carries only this one guard; a =stale= lock (a crashed fire) doesn't block — only a live =held= lock does.
+The stop-sentry operation (defined in =sentry.org=) owns the shutdown: it cancels the loop, disposes of the branch, and walks the approval queue. Wrap-up carries only this one guard; a =stale= lock (a crashed cycle) doesn't block — only a live =held= lock does.
** Step 1: Finalize the Summary
@@ -273,7 +303,7 @@ For an interactive walk of the judgments mid-day, run =/lint-org todo.org=.
*** Inbox sanity check (surface unprocessed handoffs)
-If the project has an =inbox/= directory, verify it holds nothing but =.gitkeep=, =lint-followups.org= (the lint-org pipeline file the next morning's daily-prep consumes), and any explicitly-deferred =PROCESSED-*= files before the wrap completes. An inbox that arrived at session start with handoffs from other projects, or that received handoffs mid-session, needs =inbox.org= process mode to run and apply its value-gate dispositions. Wrapping with a dirty inbox silently defers the work to next session and accumulates handoff debt that the sender can't see.
+If the project has an =inbox/= directory, verify it holds nothing but =.gitkeep=, =lint-followups.org= (the lint-org pipeline file the next morning's daily-prep consumes), and =PROCESSED-*= files before the wrap completes. An inbox that arrived at session start with handoffs from other projects, or that received handoffs mid-session, needs =inbox.org= process mode to run and apply its value-gate dispositions. Wrapping with an unprocessed inbox silently defers the work to next session and accumulates handoff debt that the sender can't see.
#+begin_src bash
unprocessed=$(find inbox -maxdepth 1 -type f \
@@ -282,7 +312,7 @@ unprocessed=$(find inbox -maxdepth 1 -type f \
! -name 'PROCESSED-*' \
2>/dev/null | wc -l)
if [ "$unprocessed" -gt 0 ]; then
- echo "wrap-up: inbox/ has $unprocessed unprocessed item(s). Run inbox.org process mode before wrapping, or explicitly defer each item with a one-line reason in the valediction."
+ echo "wrap-up blocked: inbox/ has $unprocessed unprocessed item(s). Run inbox.org process mode before wrapping."
find inbox -maxdepth 1 -type f \
! -name '.gitkeep' \
! -name 'lint-followups.org' \
@@ -291,7 +321,7 @@ if [ "$unprocessed" -gt 0 ]; then
fi
#+end_src
-If the count is zero or the project has no =inbox/= directory, the check is a silent no-op. If non-zero, the wrap is incomplete by default. The user resolves each item (process now, defer with reason in the valediction, or delete with rationale) before the validation checklist passes.
+If the count is zero or the project has no =inbox/= directory, the check is a silent no-op. If non-zero, the wrap is blocked. Process each item through its value-gate disposition, or delete it only when that workflow's rationale authorizes deletion, before continuing.
The check exempts =lint-followups.org= explicitly because lint-org runs earlier in the same wrap-up workflow and writes its judgment items to that file in =inbox/= by design. The file is a pipeline artifact for the next morning's =daily-prep=, not a handoff that needs the value gate.
@@ -501,17 +531,17 @@ Behavior:
git status --short
#+end_src
-*Default policy: end every session with an empty =git status=.* The wrap is incomplete while anything remains dirty. There is no "leave it alone" default — every leftover gets an active resolution. The only way for a file to stay dirty across the wrap is the user explicitly saying "defer this one, leave it dirty." Surface each leftover with a concrete recommendation; the user has to actively opt out for the dirt to persist.
+*Hard policy: end every session with an empty =git status=.* The wrap is incomplete while anything remains dirty. There is no deferral exception and no "wrapped with known changes" state: unresolved dirt means the session remains open and wrap-up does not occur.
This inverts the older "intentional carryover" default, which let pre-existing dirty state accumulate across sessions silently. Carryover that lives for days or weeks is almost always one of: a forgotten commit from a prior wrap, a stale change that should be discarded, or genuine in-flight work that needs an explicit stash/branch home. None of those should default to "leave it dirty."
**** Three kinds of leftover
-| Pattern | What it is | Recommended action (apply unless user defers) |
+| Pattern | What it is | Recommended action |
|---+---+---|
| Generated, runtime, or lock files that no human edits — e.g., =.claude/scheduled_tasks.lock=, =.pytest_cache/=, build outputs, IDE state, editor swap files | *Runtime artifact* — created by tooling or the harness, not by the user, and shouldn't be tracked | Add the matching pattern to =.gitignore= (project-level, not =~/.gitignore_global=). For tracked files, =git rm --cached <path>=. Stage =.gitignore= and any =rm --cached= changes in *one* follow-up commit (=chore: gitignore X=), push. Re-run =git status= to confirm clean. |
| Modified or created during the session but not staged into the wrap-up commit | *Forgotten change* — real session work that should have been in the wrap commit but missed it | Stage and create a follow-up commit. Don't =--amend= the wrap-up commit once pushed (diverging history without a clear win). Push the follow-up to all remotes. |
-| Was dirty at session start and still dirty at session end — work this session deliberately didn't touch | *Pre-existing dirt that needs a decision* — could be a missed commit from a prior wrap, stale abandoned work, or real in-flight work without a home | Investigate (show diff + check the originating session). Recommend one of: (a) commit now if the work is complete, (b) stash with a descriptive message if it's genuine WIP, (c) =git checkout -- <path>= / =git clean -f <path>= if stale and unwanted, (d) move to a feature branch if it's longer-running, (e) user explicitly defers and accepts the dirt. Do not silently leave dirty. |
+| Was dirty at session start and still dirty at session end — work this session deliberately didn't touch | *Pre-existing dirt that needs a decision* — could be a missed commit from a prior wrap, stale abandoned work, or real in-flight work without a home | Investigate (show diff + check the originating session). Recommend one of: (a) commit now if the work is complete, (b) stash with a descriptive message if it's genuine WIP, (c) =git checkout -- <path>= / =git clean -f <path>= if stale and unwanted, or (d) move to a feature branch if it's longer-running. Do not silently leave dirty. |
**** Per-file flow
@@ -519,18 +549,40 @@ For each leftover line in =git status --short=:
1. Identify which of the three kinds above it matches.
2. State what the file is (one line) and the recommended action.
-3. Apply the action unless the user explicitly defers.
-4. Re-run =git status --short= after each follow-up commit until empty (or until every remaining line is an explicit user-deferred entry).
+3. Apply the action when it is safe and authorized.
+4. Re-run =git status --short= after each follow-up commit until empty.
The pre-existing-dirt case (third row) is the one this rule most cares about. Treat each pre-existing-dirty file as a question that must get an answer this session, not as "carryover that's fine to inherit." A file that was dirty for a week before this session probably isn't going to get cleaner by waiting another week. Look at the diff, check the originating session's notes, and recommend a real resolution.
-**** When the user defers
+**** When cleanup cannot be completed
+
+Stop the wrap. Do not deliver the valediction, print =session wrapped.=, drop a teardown/shutdown sentinel, or describe the session as complete. Report:
+
+1. Every remaining path and its exact Git state.
+2. What the file is and why the agent cannot safely resolve it alone.
+3. The concrete action or decision Craig needs to provide to make the tree clean.
+
+An explicit decision to keep a file dirty changes the outcome from "wrapping" to "leaving the session interrupted." It never satisfies this workflow.
+
+*** Final clean-tree certificate — hard gate
-If the user does say "leave this one dirty for now" after seeing the recommendation, that is fine — log the deferral in the valediction so the next session knows it was an explicit choice, not a miss. Format: "Deferred (per Craig's decision today): =path/to/file= — <one-line reason>". Without that note, the next session can't distinguish "we agreed to defer" from "we forgot again."
+After all commits are pushed and every leftover appears resolved, run the shared gate:
+
+#+begin_src bash
+gate="$(command -v git-worktree-gate 2>/dev/null || true)"
+[ -n "$gate" ] || gate="$HOME/code/rulesets/claude-templates/bin/git-worktree-gate"
+if [ ! -x "$gate" ]; then
+ echo "wrap blocked: git-worktree-gate is unavailable; install rulesets tooling and retry"
+ exit 1
+fi
+"$gate" certify "$PWD"
+#+end_src
+
+The certificate lives inside the Git directory, so it does not dirty the worktree. It records the exact verified HEAD. A non-zero result is a hard stop governed by "When cleanup cannot be completed" above. Step 5 is unreachable until certification succeeds.
** Step 5: Valediction
-Brief, warm closing. 3-4 sentences max.
+Only after the final clean-tree certificate succeeds, deliver a brief, warm closing. 3-4 sentences max.
Include:
- What was accomplished (specific, not generic)
@@ -567,7 +619,7 @@ Do nothing. The buffer, the =aiv-<project>= tmux session, and =claude= all stay
*** Teardown mode (default)
-Confirm commit + push succeeded (Exit Criteria 5 — never tear down over unpushed work), then drop the sentinel:
+Confirm commit + push and the final clean-tree certificate succeeded (Exit Criteria 5 — never tear down over unpushed or dirty work), then drop the sentinel:
#+begin_src bash
touch "/tmp/ai-wrap-teardown-$(basename "$PWD")"
@@ -575,6 +627,8 @@ touch "/tmp/ai-wrap-teardown-$(basename "$PWD")"
That is the whole step. Don't run any =tmux kill-session=, =emacsclient=, or buffer kill inline — the =Stop= hook reads the sentinel when this response ends and runs =cj/ai-term-quit=, which kills the =aiv-<project>= session (taking =claude= with it), kills the vterm buffer, and restores geometry. The basename of =$PWD= is the key the hook matches, so the sentinel names the session it tears down.
+*The sentinel is session-scoped.* If certification fails, the =Stop= hook blocks and leaves the sentinel armed on purpose, so a wrap blocked by a dirty tree retries on a later stop without re-running this workflow. It does *not* survive the session: =session-start-disarm.sh= clears it at =SessionStart=, because a wrap that never certified is not a pending teardown once its session is gone. Before that hook existed, an uncertified sentinel sat armed indefinitely and fired in whatever session next reached a clean tree — work's 2026-07-27 11:37 wrap killed the 13:20 session mid-work, and archsetup's sat armed on a live terminal for two days. If teardown is still wanted in a new session, run this workflow again.
+
*** Shutdown mode
Confirm commit + push succeeded, then evaluate the safety gate *before* committing to the shutdown — never power the box off out from under another live session:
@@ -605,7 +659,8 @@ If =emacsclient= isn't resolvable or the daemon is down, the gate can't run —
7. *Leaving =.ai/session-context.org= in place* — its presence means "interrupted session", confuses next startup
8. *Long preachy valediction* — brief beats thorough
9. *Leaving runtime/generated files dirty without gitignoring them* — pollutes every future =git status= and erodes trust in "working tree clean" as a signal. Fix =.gitignore= during the wrap, not later.
-10. *Treating "was dirty at session start, still dirty now" as fine by default* — that's how a forgotten commit from two sessions ago turns into "carryover" for two weeks. Every pre-existing dirty file needs an active resolution recommendation this session. Deferral is allowed only with an explicit user choice, logged in the valediction.
+10. *Treating "was dirty at session start, still dirty now" as fine* — that's how a forgotten commit from two sessions ago turns into "carryover" for two weeks. Every pre-existing dirty file must be resolved or the wrap remains blocked.
+11. *Calling a blocked cleanup a wrap* — if the strict gate fails, report the paths and needed decisions; do not valedict, certify completion, or tear down.
* Validation Checklist
@@ -618,19 +673,20 @@ Before considering wrap-up complete:
- [ ] =todo-cleanup.el= ran — hygiene pass + =--convert-subtasks= + =--archive-done= + =--sync-child-priority= (if =todo.org= exists at project root)
- [ ] =lint-org.el= ran on =todo.org= — mechanical fixes applied, judgments appended to follow-ups file (if =todo.org= exists)
- [ ] Any orphan-planning-line warnings reviewed (fix or accept)
-- [ ] Inbox carries nothing but expected pipeline artifacts (=.gitkeep=, =lint-followups.org=, =PROCESSED-*= prefixes), OR each remaining handoff has an explicit deferral logged in the valediction
+- [ ] Inbox carries nothing but expected committed or ignored pipeline artifacts (=.gitkeep=, =lint-followups.org=, =PROCESSED-*= prefixes); any untracked inbox delivery was processed before wrap
- [ ] Linear Dev-Review sweep ran; any merged-PR tickets moved to Done or PM Acceptance (skip if project doesn't use Linear)
- [ ] Template-sync churn committed as its own =chore: sync .ai tooling from templates= (consuming projects only; skipped in rulesets), or surfaced if a synced path didn't match canonical
-- [ ] After wrap-up commit + push, =git status --short= is empty OR every remaining line has an explicit user-deferred decision logged in the valediction
+- [ ] After wrap-up commit + push, =git-worktree-gate certify "$PWD"= succeeded at the current HEAD
- [ ] Each leftover was investigated and the user saw a concrete resolution recommendation
- [ ] Runtime artifacts added to =.gitignore=, follow-up commit pushed, =git status= re-verified
- [ ] Forgotten changes committed in a follow-up and pushed
-- [ ] Pre-existing dirty files resolved (committed / stashed / discarded / moved to a feature branch) or explicitly deferred with a one-line reason in the valediction
+- [ ] Pre-existing dirty files resolved (committed / stashed / discarded / moved to a feature branch); otherwise wrap stopped with an actionable blocker report
- [ ] Current branch pushed to ALL remotes (verified with =git remote -v=)
- [ ] All other local branches with a tracking upstream pushed to their remote
- [ ] Any untracked-upstream branches surfaced for manual =git push -u=
- [ ] Step 6 teardown matches the trigger phrase: no-teardown leaves the buffer; teardown drops only =/tmp/ai-wrap-teardown-<project>=; shutdown gates on =cj/ai-term-live-count= = 1 and drops only =/tmp/ai-wrap-shutdown-<project>=
- [ ] No teardown/shutdown sentinel was dropped before commit + push was verified
+- [ ] The teardown hook can re-verify the clean-tree certificate before consuming a sentinel
- [ ] Shutdown aborted (fell back to normal wrap, logged in the valediction) when another =aiv-*= session was live or the gate couldn't run
- [ ] Commit message follows format (no =session:=, no Claude attribution)
- [ ] Valediction delivered (brief, specific, warm)