diff options
Diffstat (limited to 'claude-templates')
| -rw-r--r-- | claude-templates/.ai/protocols.org | 6 | ||||
| -rw-r--r-- | claude-templates/.ai/references/calendar-reference.org | 66 | ||||
| -rwxr-xr-x | claude-templates/.ai/scripts/sync-templates | 131 | ||||
| -rw-r--r-- | claude-templates/.ai/scripts/tests/sync-templates.bats | 319 | ||||
| -rw-r--r-- | claude-templates/.ai/scripts/tests/test-todo-cleanup.el | 2 | ||||
| -rw-r--r-- | claude-templates/.ai/scripts/todo-cleanup.el | 2 | ||||
| -rw-r--r-- | claude-templates/.ai/workflows/code-quality.org | 2 | ||||
| -rw-r--r-- | claude-templates/.ai/workflows/daily-prep.org | 32 | ||||
| -rw-r--r-- | claude-templates/.ai/workflows/helper-mode.org | 29 | ||||
| -rw-r--r-- | claude-templates/.ai/workflows/no-approvals.org | 4 | ||||
| -rw-r--r-- | claude-templates/.ai/workflows/sentry.org | 68 | ||||
| -rw-r--r-- | claude-templates/.ai/workflows/startup.org | 43 | ||||
| -rw-r--r-- | claude-templates/.ai/workflows/triage-intake.telegram.org | 141 | ||||
| -rw-r--r-- | claude-templates/.ai/workflows/work-the-backlog.org | 5 | ||||
| -rw-r--r-- | claude-templates/.ai/workflows/wrap-it-up.org | 34 | ||||
| -rwxr-xr-x | claude-templates/bin/ai | 209 |
16 files changed, 918 insertions, 175 deletions
diff --git a/claude-templates/.ai/protocols.org b/claude-templates/.ai/protocols.org index f4eefed..b291d9e 100644 --- a/claude-templates/.ai/protocols.org +++ b/claude-templates/.ai/protocols.org @@ -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 diff --git a/claude-templates/.ai/references/calendar-reference.org b/claude-templates/.ai/references/calendar-reference.org deleted file mode 100644 index 5791b08..0000000 --- a/claude-templates/.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/claude-templates/.ai/scripts/sync-templates b/claude-templates/.ai/scripts/sync-templates new file mode 100755 index 0000000..b9769f3 --- /dev/null +++ b/claude-templates/.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/claude-templates/.ai/scripts/tests/sync-templates.bats b/claude-templates/.ai/scripts/tests/sync-templates.bats new file mode 100644 index 0000000..6651c99 --- /dev/null +++ b/claude-templates/.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/claude-templates/.ai/scripts/tests/test-todo-cleanup.el b/claude-templates/.ai/scripts/tests/test-todo-cleanup.el index a92d238..1e964b3 100644 --- a/claude-templates/.ai/scripts/tests/test-todo-cleanup.el +++ b/claude-templates/.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/claude-templates/.ai/scripts/todo-cleanup.el b/claude-templates/.ai/scripts/todo-cleanup.el index cb333e2..516e9b1 100644 --- a/claude-templates/.ai/scripts/todo-cleanup.el +++ b/claude-templates/.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/claude-templates/.ai/workflows/code-quality.org b/claude-templates/.ai/workflows/code-quality.org index 0481166..3c4ed8f 100644 --- a/claude-templates/.ai/workflows/code-quality.org +++ b/claude-templates/.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/claude-templates/.ai/workflows/daily-prep.org b/claude-templates/.ai/workflows/daily-prep.org index 3f21214..9f706d1 100644 --- a/claude-templates/.ai/workflows/daily-prep.org +++ b/claude-templates/.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/claude-templates/.ai/workflows/helper-mode.org b/claude-templates/.ai/workflows/helper-mode.org index a6acfa7..b32d574 100644 --- a/claude-templates/.ai/workflows/helper-mode.org +++ b/claude-templates/.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/claude-templates/.ai/workflows/no-approvals.org b/claude-templates/.ai/workflows/no-approvals.org index b4c7fcf..6b5c7fa 100644 --- a/claude-templates/.ai/workflows/no-approvals.org +++ b/claude-templates/.ai/workflows/no-approvals.org @@ -46,7 +46,7 @@ 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 the =publish= skill, Step 0. @@ -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/claude-templates/.ai/workflows/sentry.org b/claude-templates/.ai/workflows/sentry.org index e25ca39..b25fc14 100644 --- a/claude-templates/.ai/workflows/sentry.org +++ b/claude-templates/.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/claude-templates/.ai/workflows/startup.org b/claude-templates/.ai/workflows/startup.org index 2262eea..bc89256 100644 --- a/claude-templates/.ai/workflows/startup.org +++ b/claude-templates/.ai/workflows/startup.org @@ -137,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). @@ -213,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/claude-templates/.ai/workflows/triage-intake.telegram.org b/claude-templates/.ai/workflows/triage-intake.telegram.org index 5039a8b..1319da5 100644 --- a/claude-templates/.ai/workflows/triage-intake.telegram.org +++ b/claude-templates/.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/claude-templates/.ai/workflows/work-the-backlog.org b/claude-templates/.ai/workflows/work-the-backlog.org index a0b24a8..ea3f402 100644 --- a/claude-templates/.ai/workflows/work-the-backlog.org +++ b/claude-templates/.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/claude-templates/.ai/workflows/wrap-it-up.org b/claude-templates/.ai/workflows/wrap-it-up.org index d212195..ecd3d22 100644 --- a/claude-templates/.ai/workflows/wrap-it-up.org +++ b/claude-templates/.ai/workflows/wrap-it-up.org @@ -29,6 +29,8 @@ The wrap-up is complete when: 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 diff --git a/claude-templates/bin/ai b/claude-templates/bin/ai index 65d0ab7..3440ee2 100755 --- a/claude-templates/bin/ai +++ b/claude-templates/bin/ai @@ -18,6 +18,17 @@ # ollama; model per AI_LOCAL_MODEL, default gpt-oss:120b). # Also settable via AI_RUNTIME. # +# ai --helper <dir> Open a SECOND session in a project that already has a +# live one, under the helper-mode.org role contract: reads +# freely, makes only scoped edits, never mutates git, and +# skips git prep because the primary owns pulls. Runs +# agent-roster first — with no other agent live it warns +# and falls back to a normal primary launch (which does +# run git prep). Run it from a terminal of your own: the +# roster excludes its caller's own process ancestry, so +# invoking it from inside an agent session hides that +# session and silently downgrades to a primary launch. +# # ai --attach Attach to the existing 'ai' session without changes. # # ai -h | --help Show this help. @@ -110,8 +121,18 @@ build_instructions() { printf 'This is %s %s project. Follow all instructions in .ai/protocols.org.' "$(uname -n)" "$name" } +# The opening line for a helper session. Deliberately does NOT name +# protocols.org: a helper must not run normal startup (pulls, rsync, inbox +# processing all belong to the primary), and helper-mode.org sends it to +# protocols.org itself once the role contract is loaded. +build_helper_instructions() { + local name="$1" + printf 'This is %s %s project. You are a helper session: another agent is already live here. Read and follow .ai/workflows/helper-mode.org — it is your role contract. Do not run the normal startup workflow.' \ + "$(uname -n)" "$name" +} + usage() { - sed -n '2,23p' "$0" | sed 's|^# \?||' + sed -n '2,34p' "$0" | sed 's|^# \?||' exit 0 } @@ -146,14 +167,92 @@ _git_prep_action() { fi } +# Decide what a `--helper` launch actually becomes, from the roster's verdict. +# Input is agent-roster's exit status — 0 alone, 1 others live, 2 unavailable — +# or the literal "absent" when no roster script is installed. Echoes one of: +# helper — confirmed: another agent is live here +# primary — refuted: nobody else is here, so --helper is a no-op +# helper-unverified — the roster couldn't answer +# Unverifiable resolves toward helper on purpose. `--helper` is the operator +# asserting a primary is live, and helper mode is the strictly less destructive +# guess: 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. +_helper_launch_mode() { + case "$1" in + 1) echo helper ;; + 0) echo primary ;; + *) echo helper-unverified ;; + esac +} + +# A helper's agent id: helper-<rand4>, per helper-mode.org's identity rule. +# Four hex digits is enough — the id only has to be unique among the agents +# live in one project at one moment, and the archived session file carries the +# date and time as well. Two draws because bash's RANDOM is 15-bit, so a single +# one would never set the top bit and the first hex digit would always be 0-7. +_helper_id() { + printf 'helper-%04x\n' $(( ((RANDOM << 1) ^ RANDOM) & 0xffff )) +} + +# Reduce an id to the characters session-context-path keeps, so the launcher and +# the path resolver agree on what a given id means. This is also a safety fix, +# not just tidiness: the id is interpolated into the command line typed into the +# pane, so an id carrying a space or a ';' would split the assignment off from +# the command and run something else instead of launching the helper. +# printf without a newline on purpose: tr -c would translate a trailing newline +# into an underscore too, silently appending one to every sanitized id. +_sanitize_agent_id() { + printf '%s' "$1" | tr -c 'A-Za-z0-9._-' '_' + printf '\n' +} + +# Resolve the id for a helper launch: an explicitly-exported one when it is +# free, otherwise a fresh one. +# +# The reuse check is the load-bearing part. A helper's own pane exports +# AI_AGENT_ID, so `ai --helper` invoked from inside a helper inherits its +# parent's id rather than being given one deliberately. Honoring that blindly +# points two live agents at one .ai/session-context.d/<id>.org, which is the +# lost-update collision the whole helper contract exists to avoid. +_resolve_helper_id() { + local dir="$1" + local want="${AI_AGENT_ID:-}" + local tries=0 + + if [ -n "$want" ]; then + want="$(_sanitize_agent_id "$want")" + if [ ! -e "$dir/.ai/session-context.d/$want.org" ]; then + printf '%s\n' "$want" + return + fi + echo "ai: agent id '$want' is already live in $(basename "$dir") — assigning a fresh one" >&2 + fi + + # A minted id gets the same free-anchor check as a supplied one. The odds of + # a chance collision are small, but a guard that only covers the path the + # caller controls leaves the collision it exists to prevent reachable. + # Bounded so a full or unreadable directory can't spin here. + while [ "$tries" -lt 8 ]; do + want="$(_helper_id)" + [ -e "$dir/.ai/session-context.d/$want.org" ] || break + tries=$((tries + 1)) + done + printf '%s\n' "$want" +} + # Re-order "name<TAB>wid" lines (stdin) into the launcher's window order: # non-project windows alphabetically, then project windows alphabetically. # $1 is a newline-separated list of project window names. +# +# A helper window is named "<project>:<agent-id>", so it matches on the prefix +# before the first colon rather than on the whole name. That keeps it sorted +# next to the project it helps instead of landing among the unrelated windows. _order_windows() { local project_names="$1" wname wid others="" projects="" while IFS=$'\t' read -r wname wid; do [ -z "$wname" ] && continue - if printf '%s\n' "$project_names" | grep -qxF "$wname"; then + if printf '%s\n' "$project_names" | grep -qxF "$wname" || + printf '%s\n' "$project_names" | grep -qxF "${wname%%:*}"; then projects+="${wname}"$'\t'"${wid}"$'\n' else others+="${wname}"$'\t'"${wid}"$'\n' @@ -394,6 +493,36 @@ prep_git_single() { esac } +# Run the project's agent-roster and turn its verdict into a launch decision. +# The decision is the only thing on stdout; warnings go to stderr so callers +# can capture one without the other. +_resolve_helper_launch() { + # Two statements on purpose: a name assigned in a `local` is not yet visible + # to a later assignment in that same `local`, so building the roster path in + # this line would read the CALLER's $dir — right only by coincidence. + local dir="$1" + local roster="$dir/.ai/scripts/agent-roster" rc decision + if [ -x "$roster" ]; then + # The roster prints the other agents it found; only its exit code matters + # here, and its stdout must not reach a --print-launch caller's output. + "$roster" "$dir" >/dev/null 2>&1 + rc=$? + else + rc=absent + fi + + decision="$(_helper_launch_mode "$rc")" + case "$decision" in + primary) + echo "ai: --helper found no other agent live in $(basename "$dir") — opening a normal primary session instead" >&2 + ;; + helper-unverified) + echo "ai: could not verify another agent is live in $(basename "$dir") — roster unavailable; opening a helper anyway" >&2 + ;; + esac + echo "$decision" +} + # ---------- modes ---------- attach_mode() { @@ -447,6 +576,55 @@ single_mode() { attach_session } +# Open a helper session: a second agent in a project that already has a live +# one. Two deliberate differences from single_mode. It never focuses an +# existing window — a second session is the entire 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, because every pull belongs to the primary under the +# helper contract. +helper_mode() { + local arg="$1" dir name id wid wname decision instructions + dir="$(cd "$arg" 2>/dev/null && pwd)" || { + echo "ai: cannot access '$arg'" >&2 + return 1 + } + + if [ ! -f "$dir/.ai/protocols.org" ]; then + echo "ai: $dir has no .ai/protocols.org — not an agent-template project" >&2 + return 1 + fi + + name="$(basename "$dir")" + + # Nobody else is here, so there is nothing to be a helper to. Fall through to + # the normal launch rather than opening a crippled session. + decision="$(_resolve_helper_launch "$dir")" + if [ "$decision" = primary ]; then + single_mode "$arg" + return $? + fi + + id="$(_resolve_helper_id "$dir")" + wname="$name:$id" + instructions=$(build_helper_instructions "$name") + + if tmux has-session -t "$SESSION" 2>/dev/null; then + wid=$(tmux new-window -a -t "$SESSION:{end}" -n "$wname" -c "$dir" -P -F '#{window_id}') + sleep 0.1 + else + wid=$(tmux new-session -d -s "$SESSION" -n "$wname" -c "$dir" -P -F '#{window_id}') + fi + + # The id rides in the launched process's environment, which is what + # session-context-path reads to resolve .ai/session-context.d/<id>.org. + tmux send-keys -t "$wid" \ + "${LAUNCH_PREFIX}AI_AGENT_ID=$id AI_HELPER=1 $AGENT_CMD \"$instructions\"" Enter + + sort_windows + tmux select-window -t "$wid" + attach_session +} + # Multi-select via fzf (the original aix flow). multi_mode() { local filtered=() selections first_wid="" @@ -537,6 +715,15 @@ print_launch_mode() { exit 1 fi name="$(basename "$dir")" + + # The roster runs here too, so the printed line reflects the decision a real + # run would make — including the downgrade to a primary launch. + if [ -n "$HELPER_MODE" ] && [ "$(_resolve_helper_launch "$dir")" != primary ]; then + printf 'AI_AGENT_ID=%s AI_HELPER=1 %s "%s"\n' \ + "$(_resolve_helper_id "$dir")" "$AGENT_CMD" "$(build_helper_instructions "$name")" + exit 0 + fi + printf '%s "%s"\n' "$AGENT_CMD" "$(build_instructions "$name")" exit 0 } @@ -549,12 +736,17 @@ print_launch_mode() { # dispatch runs exactly as before; when sourced, it's skipped. main() { print_launch="" + HELPER_MODE="" runtime_explicit="${AI_RUNTIME:+1}" while [ $# -gt 0 ]; do case "$1" in -h | --help) usage ;; + --helper) + HELPER_MODE=1 + shift + ;; --runtime) [ -z "${2:-}" ] && { echo "ai: --runtime needs a value — valid runtimes: claude, codex, local" >&2 @@ -585,6 +777,13 @@ main() { resolve_agent_cmd + # A helper is always scoped to one named project. There is no roster to check + # and no primary to help without one, so this can't fall back to the picker. + if [ -n "$HELPER_MODE" ] && [ -z "${1:-}" ]; then + echo "ai: --helper needs a project directory" >&2 + exit 2 + fi + if [ -n "$print_launch" ]; then [ $# -eq 0 ] && { echo "ai: --print-launch needs a project directory" >&2 @@ -610,7 +809,11 @@ main() { *) check_deps for arg in "$@"; do - single_mode "$arg" + if [ -n "$HELPER_MODE" ]; then + helper_mode "$arg" + else + single_mode "$arg" + fi done ;; esac |
