From 5951bf67cbdfbe5a53d154fa39796066ae38c353 Mon Sep 17 00:00:00 2001 From: Alex Wegener Date: Sun, 15 Nov 2026 14:39:38 +0100 Subject: [PATCH 01/25] feat: standing entries end by until, until-check or a closing entry; check key (#73, #74) yt_standing skips entries whose until passed and entries of kind end; yt_standing_fields and yt_standing_lines expose every key and filter by role; yt_session_home is the per-session state both hooks and the Bash tool find. ytstack-check --standing validates until, until-condition, until-check, check and kind. Co-Authored-By: Claude Opus 5.5 --- bin/ytstack-check | 25 +++++++++ hooks/lib/git-ctx.sh | 103 +++++++++++++++++++++++++++++++----- tests/git-ctx.test.sh | 20 +++++++ tests/ytstack-check.test.sh | 26 +++++++++ 4 files changed, 161 insertions(+), 13 deletions(-) diff --git a/bin/ytstack-check b/bin/ytstack-check index 48cf6438..66456cb8 100755 --- a/bin/ytstack-check +++ b/bin/ytstack-check @@ -824,6 +824,31 @@ def check_standing(yt_dir): fails.append(f"{rel}: scope is empty (where the instruction applies)") if not body.strip(): fails.append(f"{rel}: no instruction below the frontmatter") + # Optional keys (issues #73, #74): until is a real ISO UTC time after + # given; until-condition, until-check and check are one line each when + # present (until-check may stand alone: the command is the condition); + # kind is empty or `end`, and an `end` names the entry it closes. + until = _fm_scalar(fm, "until") + if until is None: + fails.append(f"{rel}: until is one time, not a list") + elif until and "until" in fm: + um = _STANDING_GIVEN.match(until) + if not um: + fails.append(f"{rel}: until '{until}' is not an ISO UTC time (YYYY-MM-DDTHH:MMZ or with seconds)") + elif _standing_time(um.groups()) is None: + fails.append(f"{rel}: until {until} is not a real UTC date and time") + elif gm and _standing_time(gm.groups()) is not None and _standing_time(um.groups()) <= _standing_time(gm.groups()): + fails.append(f"{rel}: until {until} is not after given {given}") + for k in ("until-condition", "until-check", "check"): + if k in fm: + v = _fm_scalar(fm, k) + if v is None or not v or "\n" in v: + fails.append(f"{rel}: {k} is empty or not one line (leave the key out when there is none)") + kind = _fm_scalar(fm, "kind") + if kind not in ("", "end"): + fails.append(f"{rel}: kind '{kind}' is not 'end' (leave the key out for an instruction)") + elif kind == "end" and _fm_scalar(fm, "supersedes") in ("", "none", "None", "-", None): + fails.append(f"{rel}: kind end closes an entry, but supersedes names none") for name, (rel, fm, key) in sorted(entries.items()): sup = _fm_scalar(fm, "supersedes") if sup is None: diff --git a/hooks/lib/git-ctx.sh b/hooks/lib/git-ctx.sh index 8498424d..8b9bb264 100644 --- a/hooks/lib/git-ctx.sh +++ b/hooks/lib/git-ctx.sh @@ -640,42 +640,119 @@ yt_find_artifacts() { return 0 } -# ---- standing instructions, one file per entry (issue #57) -------------------- +# ---- standing instructions, one file per entry (issues #57, #72, #73, #74) ------ # yt_standing -> the standing entries in force, newest first, one per # line: TAB TAB . Entries live in # /standing/-.md (docs/ux/coordinator-format.md); # the time in the name orders them (missing seconds count as 00). An entry that another entry names in `supersedes` -# is skipped. Prints nothing when the directory does not exist; STANDING.md -# is read by the caller as before. +# is skipped, so is an entry whose `until` has passed and an entry of +# `kind: end` (it only closes another one). Prints nothing when the directory +# does not exist; STANDING.md is read by the caller as before. yt_standing() { - local sd="$1/standing" names + yt_standing_fields "$1" | awk -F '\t' '$9 == "active" { print $1 "\t" $2 "\t" ($3 == "-" ? "" : $3) }' + return 0 +} + +# yt_standing_fields [] -> every entry no +# other entry supersedes and not of kind end, newest first, TAB separated: +# name given scope until until-condition until-check check summary state +# An empty value is "-". summary is the first sentence of the body (at most 160 +# characters). state is "expired" when `until` is at or before now, else +# "active". Files only: no command of an entry runs here (bin/ytstack-standing +# list runs until-check and check). +yt_standing_fields() { + local sd="$1/standing" names now="${2:-}" [ -n "$1" ] && [ -d "$sd" ] || return 0 + [ -n "$now" ] || now=$(date -u +%Y%m%d%H%M%S) names=$(ls "$sd" 2>/dev/null | grep -E '^[0-9]{8}T[0-9]{4}([0-9]{2})?Z-[A-Za-z0-9._-]+\.md$') [ -n "$names" ] || return 0 # shellcheck disable=SC2086 # the names match the pattern above: no spaces ( cd "$sd" && awk -v q="'" ' function clean(v, f) { - gsub(/^[ \t]+|[ \t]+$/, "", v) + gsub(/\t/, " ", v); gsub(/^[ \t]+|[ \t]+$/, "", v) f = substr(v, 1, 1) if (length(v) >= 2 && (f == q || f == "\"") && substr(v, length(v)) == f) v = substr(v, 2, length(v) - 2) return v } + function d(v) { return v == "" ? "-" : v } + function val(key) { return clean(substr($0, length(key) + 2)) } # Sort key YYYYMMDDHHMMSS: a name without seconds counts as :00, so that # 20261114T1225Z sorts before 20261114T122530Z. - function out( k) { k = substr(fn, 1, 8) substr(fn, 10, 4) (substr(fn, 14, 1) == "Z" ? "00" : substr(fn, 14, 2)); print k "\t" fn "\t" g "\t" s "\t" u } - FNR == 1 { if (fn != "") out(); fn = FILENAME; infm = ($0 == "---"); g = ""; s = ""; u = ""; next } + function out( k) { + k = substr(fn, 1, 8) substr(fn, 10, 4) (substr(fn, 14, 1) == "Z" ? "00" : substr(fn, 14, 2)) + print k "\t" fn "\t" d(g) "\t" d(s) "\t" d(u) "\t" d(un) "\t" d(uc) "\t" d(uk) "\t" d(ck) "\t" d(kd) "\t" d(sm) + } + FNR == 1 { if (fn != "") out(); fn = FILENAME; infm = ($0 == "---"); g = s = u = un = uc = uk = ck = kd = sm = ""; next } infm && /^---[ \t]*$/ { infm = 0; next } - infm && /^given:/ { g = clean(substr($0, 7)) } - infm && /^scope:/ { s = clean(substr($0, 7)) } - infm && /^supersedes:/ { u = clean(substr($0, 12)); sub(/\.md$/, "", u) } + infm && /^given:/ { g = val("given") } + infm && /^scope:/ { s = val("scope") } + infm && /^supersedes:/ { u = val("supersedes"); sub(/\.md$/, "", u) } + infm && /^until:/ { un = val("until") } + infm && /^until-condition:/ { uc = val("until-condition") } + infm && /^until-check:/ { uk = val("until-check") } + infm && /^check:/ { ck = val("check") } + infm && /^kind:/ { kd = val("kind") } + !infm && sm == "" && NF { + sm = $0; gsub(/\t/, " ", sm); sub(/^[ ]*([-*#>]+[ ]+)?/, "", sm) + if (match(sm, /[.!?]( |$)/)) sm = substr(sm, 1, RSTART) + if (length(sm) > 160) sm = substr(sm, 1, 157) "..." + } END { if (fn != "") out() } - ' $names ) | sort -r | awk -F '\t' ' - { n[NR] = $2; l[NR] = $2 "\t" $3 "\t" $4; if ($5 != "" && $5 != "none" && $5 != "None" && $5 != "-") sup[$5] = 1 } - END { for (i = 1; i <= NR; i++) { b = n[i]; sub(/\.md$/, "", b); if (!(b in sup)) print l[i] } } + ' $names ) | sort -r | awk -F '\t' -v now="$now" ' + function key(t) { gsub(/[^0-9]/, "", t); return length(t) == 12 ? t "00" : t } + { r[NR] = $0; n[NR] = $2; if ($5 != "-" && $5 != "none" && $5 != "None") sup[$5] = 1 } + END { + for (i = 1; i <= NR; i++) { + split(r[i], f, "\t"); b = n[i]; sub(/\.md$/, "", b) + if ((b in sup) || f[10] == "end") continue + st = (f[6] != "-" && length(key(f[6])) == 14 && key(f[6]) <= now) ? "expired" : "active" + print f[2] "\t" f[3] "\t" f[4] "\t" f[6] "\t" f[7] "\t" f[8] "\t" f[9] "\t" f[11] "\t" st + } + } ' return 0 } +# yt_standing_lines [] -> the active entries that +# apply to as "- (): ", newest first; past +# one line "- ... more: bin/ytstack-standing list". Roles +# (docs/ux/coordinator-format.md, "Scope and roles"): coordinator gets every +# entry; lane and reviewer get the entries whose scope names their role or no +# role at all. Role words in the scope: coordinator(s); lane(s), worker(s), +# implementer(s); reviewer(s), review(s). +yt_standing_lines() { + yt_standing_fields "$1" | awk -F '\t' -v role="${2:-coordinator}" -v max="${3:-0}" ' + function roles(s, t, r) { + t = " " tolower(s) " "; gsub(/[^a-z]+/, " ", t); r = "" + if (t ~ / (coordinator|coordinators)( |$)/) r = r "c" + if (t ~ / (lane|lanes|worker|workers|implementer|implementers)( |$)/) r = r "l" + if (t ~ / (reviewer|reviewers|review|reviews)( |$)/) r = r "r" + return r + } + $9 != "active" { next } + { rs = roles($3) } + role != "coordinator" && rs != "" && index(rs, substr(role, 1, 1)) == 0 { next } + { n++; if (max > 0 && n > max) { more++; next } + b = $1; sub(/\.md$/, "", b) + print "- " b " (" $3 "): " ($8 == "-" ? "(no text)" : $8) } + END { if (more) print "- ... " more " more: bin/ytstack-standing list" } + ' + return 0 +} + +# yt_session_home -> the directory of per-session state that a hook and the +# Bash tool of the same session both find: ${XDG_STATE_HOME:-~/.local/state}/ +# ytstack/sessions. Not yt_state_base: Claude Code sets CLAUDE_PLUGIN_DATA for +# hooks only, never for commands of the Bash tool. Files under +# //: `coordinate` (written by the coordinate preamble: the +# YT_DIR on line 1), `prompts` (hooks/standing-prompt: one epoch per human +# prompt), `standing-flags` (epoch TAB YYYYMMDDHHMM TAB ISO TAB excerpt per +# prompt that looks like a standing instruction), `standing-stop` (hooks/stop: +# the epoch up to which flags were handled). +yt_session_home() { + printf '%s' "${XDG_STATE_HOME:-$HOME/.local/state}/ytstack/sessions" +} + # ---- factory tools that are off (M031-S03, issues #54 and #61) ----------------- # yt_mtime -> seconds since epoch of the last change ("" when unreadable). # GNU and BusyBox take -c; BSD stat rejects -c and takes -f. diff --git a/tests/git-ctx.test.sh b/tests/git-ctx.test.sh index 9b98e063..c3566077 100644 --- a/tests/git-ctx.test.sh +++ b/tests/git-ctx.test.sh @@ -395,6 +395,26 @@ ST2="$TMP/st2/.ytstack"; mkdir -p "$ST2/standing" printf -- '---\ngiven: 2026-11-14T12:25:00Z\nscope: x\nsupersedes:\n---\n\nOld.\n' > "$ST2/standing/20261114T1225Z-old.md" printf -- '---\ngiven: 2026-11-14T12:25:30Z\nscope: x\nsupersedes:\n---\n\nNew.\n' > "$ST2/standing/20261114T122530Z-new.md" eq "standing: optional seconds sort as :00 (12:25:30 before 12:25)" "20261114T122530Z-new.md 20261114T1225Z-old.md" "$(st "$ST2" | cut -f1 | tr '\n' ' ' | sed 's/ $//')" +# until, kind end, the fields and the role filter (issues #73, #74) +ST3="$TMP/st3/.ytstack"; mkdir -p "$ST3/standing" +printf -- '---\ngiven: 2026-11-14T10:00:00Z\nscope: every lane\nsupersedes:\nuntil: 2026-11-14T12:37Z\n---\n\nHold merges. Until the test ends.\n' > "$ST3/standing/20261114T1000Z-hold.md" +printf -- '---\ngiven: 2026-11-14T10:10:00Z\nscope: the coordinator\nsupersedes:\nuntil-condition: PR 1879 merged\ncheck: test -f LANES.md\n---\n\n- Keep LANES.md current!\n' > "$ST3/standing/20261114T1010Z-lanes.md" +printf -- '---\ngiven: 2026-11-14T10:20:00Z\nscope: every reviewer\nsupersedes:\n---\n\nName the commit.\n' > "$ST3/standing/20261114T1020Z-commit.md" +printf -- '---\ngiven: 2026-11-14T10:30:00Z\nscope: every reviewer\nsupersedes: 20261114T1020Z-commit\nkind: end\n---\n\nEnded: x.\n' > "$ST3/standing/20261114T1030Z-end-commit.md" +printf -- '---\ngiven: 2026-11-14T10:40:00Z\nscope: this project\nsupersedes:\n---\n\nEnglish in code.\n' > "$ST3/standing/20261114T1040Z-english.md" +sf() { ( . "$LIB"; yt_standing_fields "$@" ); } +eq "standing fields: before until -> active, end entry and its target gone" \ + "20261114T1040Z-english.md|20261114T1010Z-lanes.md|20261114T1000Z-hold.md" "$(sf "$ST3" 20261114120000 | cut -f1 | tr '\n' '|' | sed 's/|$//')" +eq "standing fields: until passed -> expired" "expired" "$(sf "$ST3" 20261114130000 | awk -F '\t' '$1 ~ /hold/ { print $9 }')" +eq "standing fields: until exactly now -> expired" "expired" "$(sf "$ST3" 20261114123700 | awk -F '\t' '$1 ~ /hold/ { print $9 }')" +eq "standing fields: the keys and the first sentence" "the coordinator|-|PR 1879 merged|-|test -f LANES.md|Keep LANES.md current!|active" \ + "$(sf "$ST3" 20261114120000 | awk -F '\t' '$1 ~ /lanes/ { print $3 "|" $4 "|" $5 "|" $6 "|" $7 "|" $8 "|" $9 }')" +eq "standing: yt_standing skips the expired entry" "20261114T1040Z-english.md 20261114T1010Z-lanes.md" "$(st "$ST3" | cut -f1 | tr '\n' ' ' | sed 's/ $//')" +sl() { ( . "$LIB"; yt_standing_lines "$@" ); } +eq "standing lines: coordinator sees all active" 2 "$(sl "$ST3" coordinator | grep -c .)" +eq "standing lines: lane sees the role-free entry only" "- 20261114T1040Z-english (this project): English in code." "$(sl "$ST3" lane)" +eq "standing lines: the cap leaves a pointer" "- ... 1 more: bin/ytstack-standing list" "$(sl "$ST3" coordinator 1 | sed -n 2p)" +eq "session home follows XDG_STATE_HOME" "/x/ytstack/sessions" "$( . "$LIB"; XDG_STATE_HOME=/x yt_session_home )" echo echo "$PASS passed, $FAIL failed" diff --git a/tests/ytstack-check.test.sh b/tests/ytstack-check.test.sh index a1101aac..1d894ef4 100644 --- a/tests/ytstack-check.test.sh +++ b/tests/ytstack-check.test.sh @@ -391,6 +391,32 @@ eq "time: 29 February of a common year -> FAIL" 1 "$(printf '%s' "$OUT" | grep - eq "time: 31 November -> FAIL" 1 "$(printf '%s' "$OUT" | grep -c "november-31.md: the time in the name is not a real")" eq "time: second 60 in given -> FAIL" 1 "$(printf '%s' "$OUT" | grep -c "bad-given-seconds.md: given 2026-11-14T23:59:60Z is not a real")" rm -f "$SD"/*.md +# temporary and conditional entries, checks, end entries (issues #73, #74) +xentry() { # xentry [supersedes] + printf -- '---\ngiven: %s\nscope: x\nsupersedes: %s\n%b---\n\nAn instruction.\n' "$2" "${4:-}" "$3" > "$SD/$1.md" +} +xentry 20261114T1000Z-window 2026-11-14T10:00:00Z 'until: 2026-11-14T12:37Z\n' +xentry 20261114T1010Z-cond 2026-11-14T10:10:00Z 'until-condition: PR #1879 merged\nuntil-check: gh pr view 1879 --json state -q .state | grep -qx MERGED\n' +xentry 20261114T1020Z-check-alone 2026-11-14T10:20:00Z 'until-check: test -f done\ncheck: test -f LANES.md\n' +xentry 20261114T1030Z-end-window 2026-11-14T10:30:00Z 'kind: end\n' 20261114T1000Z-window +OUT=$("$CHECK" --standing "$PRJ" 2>&1); EC=$? +eq "until, until-condition, until-check, check, kind end: well-formed -> exit 0" 0 "$EC" +xentry 20261114T1100Z-until-bad 2026-11-14T11:00:00Z 'until: tomorrow\n' +xentry 20261114T1110Z-until-early 2026-11-14T11:10:00Z 'until: 2026-11-14T11:00Z\n' +xentry 20261114T1120Z-until-unreal 2026-11-14T11:20:00Z 'until: 2026-11-31T11:00Z\n' +xentry 20261114T1130Z-kind-bad 2026-11-14T11:30:00Z 'kind: note\n' +xentry 20261114T1140Z-end-nothing 2026-11-14T11:40:00Z 'kind: end\n' +xentry 20261114T1150Z-check-empty 2026-11-14T11:50:00Z 'check: ""\n' +OUT=$("$CHECK" --standing "$PRJ" 2>&1); EC=$? +eq "broken optional keys -> exit 1" 1 "$EC" +eq "until not ISO -> FAIL" 1 "$(printf '%s' "$OUT" | grep -c "1100Z-until-bad.md: until 'tomorrow' is not an ISO UTC time")" +eq "until before given -> FAIL" 1 "$(printf '%s' "$OUT" | grep -c "1110Z-until-early.md: until 2026-11-14T11:00Z is not after given")" +eq "until not a real time -> FAIL" 1 "$(printf '%s' "$OUT" | grep -c "1120Z-until-unreal.md: until 2026-11-31T11:00Z is not a real")" +eq "kind other than end -> FAIL" 1 "$(printf '%s' "$OUT" | grep -c "1130Z-kind-bad.md: kind 'note' is not 'end'")" +eq "kind end without supersedes -> FAIL" 1 "$(printf '%s' "$OUT" | grep -c "1140Z-end-nothing.md: kind end closes an entry, but supersedes names none")" +eq "an empty check -> FAIL" 1 "$(printf '%s' "$OUT" | grep -c "1150Z-check-empty.md: check is empty")" +eq "the well-formed optional keys stay quiet" 0 "$(printf '%s' "$OUT" | grep -c "1000Z-window\|1010Z-cond\|1020Z-check-alone\|1030Z-end-window")" +rm -f "$SD"/*.md # user scope: no .ytstack in the repository, the entries under ~/.ytstack/projects/ UREPO="$TMP/userscope"; mkdir -p "$UREPO" "$TMP/home" ( cd "$UREPO" && git init -q ) >/dev/null 2>&1 From 239e297f9cd04286c24293901318b2bca8fab7f5 Mon Sep 17 00:00:00 2001 From: Alex Wegener Date: Sun, 15 Nov 2026 14:39:52 +0100 Subject: [PATCH 02/25] feat: bin/ytstack-standing: add, end and list standing entries (#72, #73) add writes one entry in its own worktree on standing/, commits, pushes and opens or updates one pull request per UTC day (ytstack-pr-watch create with the PR watch on); --here and user scope write in place. end closes an entry with a kind-end entry. list prints active, pending, ended, to-check and failed-check entries and the prompts since the newest one; until-check and check run only here, bounded by a timeout. Co-Authored-By: Claude Opus 5.5 --- bin/ytstack-standing | 328 +++++++++++++++++++++++++++++++++ tests/ytstack-standing.test.sh | 228 +++++++++++++++++++++++ 2 files changed, 556 insertions(+) create mode 100755 bin/ytstack-standing create mode 100644 tests/ytstack-standing.test.sh diff --git a/bin/ytstack-standing b/bin/ytstack-standing new file mode 100755 index 00000000..1b955313 --- /dev/null +++ b/bin/ytstack-standing @@ -0,0 +1,328 @@ +#!/usr/bin/env bash +# ytstack standing: write and read the standing instructions in one command. +# Format: docs/ux/coordinator-format.md ("standing/"). +# +# ytstack-standing [-C DIR] add TEXT --scope SCOPE [--supersedes ENTRY] [--until ISO_UTC] +# [--until-condition SENTENCE] [--until-check CMD] [--check CMD] [--slug SLUG] [--here] +# ytstack-standing [-C DIR] end ENTRY --reason TEXT [--here] +# ytstack-standing [-C DIR] list [--no-checks] +# +# add writes .ytstack/standing/-.md (UTC now) with +# given, scope, supersedes and the optional keys, TEXT as its body. By +# default it writes in a dedicated worktree outside the checkout +# (/repos//standing-worktree) on the branch +# standing/, commits, pushes, and opens one pull request per UTC day +# or adds to the open one: through bin/ytstack-pr-watch create when +# ~/.ytstack/config has pr_watch=on and the session has an id, else gh pr +# create. --here writes into the resolved .ytstack/standing/ of DIR and +# commits nothing (user scope always does this: it is outside the repository). +# end writes the entry that closes ENTRY: kind end, supersedes ENTRY, its +# scope, the body "Ended: TEXT". +# +# list prints the active entries (the working tree, plus entries on the +# branches standing/* and origin/standing/* not merged yet, marked pending), +# then the ones that ended (until passed, or until-check exited 0), the +# conditions to check now (until-condition without until-check) and the +# failed checks (check exited non-zero). It runs until-check and check: each +# with bash -c in the checkout's toplevel, stdin closed, at most +# YTSTACK_STANDING_TIMEOUT seconds (default 5) and at most 10 commands per +# call. --no-checks runs none. No hook runs these commands. The first line +# names the newest entry, its age and the human prompts this session sent +# since (counted by hooks/standing-prompt once the coordinate preamble ran). +# +# Exit codes +# add, end 0 written (and pushed, PR opened or updated); 1 no .ytstack, +# invalid entry, unknown ENTRY or a git step failed; 3 committed +# in the worktree but the push or the PR failed (the message says +# which; the next add pushes both); 64 usage +# list 0; 1 no .ytstack + +set -uo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +. "$ROOT/hooks/lib/git-ctx.sh" + +DIR="$PWD" +if [ "${1:-}" = "-C" ]; then DIR="${2:-}"; shift 2 || true; fi +CMD="${1:-}"; [ $# -gt 0 ] && shift + +usage() { sed -n '5,8p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; } +die() { echo "ytstack-standing: $*" >&2; exit 1; } +case "$CMD" in add|end|list) ;; -h|--help|help) usage; exit 0 ;; *) usage >&2; exit 64 ;; esac +[ -d "$DIR" ] || { echo "ytstack-standing: -C '$DIR' is not a directory" >&2; exit 64; } + +yt_git_ctx "$DIR" +yt_resolve_yt_dir >/dev/null +[ -n "${YT_DIR:-}" ] || die "no .ytstack directory for $DIR" +TOP="$YT_TOPLEVEL" +oneline() { printf '%s' "$1" | tr '\n\r\t' ' ' | sed 's/ */ /g; s/^ //; s/ $//'; } + +# ---- the merged view: working tree plus pending branches ------------------------ +# view : copies every entry into ; PENDING gets " " per +# entry that exists only on a standing branch. +PENDING="" +view() { + local out="$1" rel ref p b + mkdir -p "$out" + for p in "$YT_DIR"/standing/*.md; do [ -f "$p" ] && cp "$p" "$out/"; done + [ "$YT_IS_GIT" = yes ] || return 0 + case "$YT_DIR" in "$TOP"/*) rel="${YT_DIR#"$TOP"/}" ;; *) return 0 ;; esac + for ref in $(git -C "$TOP" for-each-ref --format='%(refname)' refs/heads/standing refs/remotes/origin/standing 2>/dev/null); do + for p in $(git -C "$TOP" ls-tree --name-only "$ref" -- "$rel/standing/" 2>/dev/null); do + b=$(basename "$p") + case "$b" in *.md) ;; *) continue ;; esac + [ ! -e "$out/$b" ] || continue + git -C "$TOP" show "$ref:$p" > "$out/$b" 2>/dev/null || { rm -f "$out/$b"; continue; } + PENDING="$PENDING$b ${ref#refs/*/} +" + done + done +} + +# ---- bounded run of an entry's command ---------------------------------------------- +RUNS=0 +# bounded : RC (124 on timeout) and LINE (first non-empty output line). +bounded() { + local t="${YTSTACK_STANDING_TIMEOUT:-5}" out pid w + case "$t" in ''|*[!0-9]*) t=5 ;; esac + out=$(mktemp "${TMPDIR:-/tmp}/ytstd.XXXXXX") + ( cd "$TOP" && exec bash -c "$1" ) "$out" 2>&1 & + pid=$! + ( sleep "$t"; kill -TERM "$pid"; sleep 1; kill -KILL "$pid" ) >/dev/null 2>&1 & + w=$! + wait "$pid"; RC=$? + kill "$w" 2>/dev/null; wait "$w" 2>/dev/null + if [ "$RC" -eq 143 ] || [ "$RC" -eq 137 ]; then RC=124; fi + LINE=$(sed '/^[[:space:]]*$/d' "$out" | head -1 | cut -c1-200) + rm -f "$out" +} 2>/dev/null + +age() { # age -> "2 h 14 min" / "5 min" + local s="$1" + if [ "$s" -ge 86400 ]; then echo "$((s / 86400)) d $((s % 86400 / 3600)) h" + elif [ "$s" -ge 3600 ]; then echo "$((s / 3600)) h $((s % 3600 / 60)) min" + else echo "$((s / 60)) min"; fi +} + +# ---- list ---------------------------------------------------------------------------- +cmd_list() { + local checks=yes tmp newest e now cnt sd sid name given scope until ucond ucheck check summary state pend + local active="" ended="" tocheck="" failed="" na=0 ne=0 nt=0 nf=0 + [ $# -eq 0 ] || { [ "$1" = --no-checks ] && [ $# -eq 1 ]; } || { usage >&2; return 64; } + [ $# -eq 0 ] || checks=no + tmp=$(mktemp -d "${TMPDIR:-/tmp}/ytstl.XXXXXX") + view "$tmp/standing" + now=$(date +%s) + + newest=$(ls "$tmp/standing" 2>/dev/null | grep -E '^[0-9]{8}T[0-9]{4}([0-9]{2})?Z-' | sort -r | head -1) + sid="${CLAUDE_CODE_SESSION_ID:-${CODEX_THREAD_ID:-}}" + case "$sid" in *[!A-Za-z0-9._-]*) sid="" ;; esac + sd="$(yt_session_home)/${sid:-none}" + if [ -z "$newest" ]; then + printf 'newest entry: none' + else + e=$(yt_epoch "$(printf '%s' "$newest" | sed -E 's/^([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2})([0-9]{2})([0-9]{2})?Z.*/\1-\2-\3T\4:\5:\6Z/; s/:Z$/:00Z/')") + printf 'newest entry: %s (%s ago)' "${newest%.md}" "$(age $(( now - ${e:-$now} )))" + fi + if [ -n "$sid" ] && [ -f "$sd/coordinate" ]; then + cnt=$(awk -v e="${e:-0}" '$1 + 0 > e + 0 { n++ } END { print n + 0 }' "$sd/prompts" 2>/dev/null) + printf '; human prompts since: %s\n' "${cnt:-0}" + else + printf '; human prompts since: not counted (no coordinate session marker; the coordinate preamble writes it)\n' + fi + + while IFS="$(printf '\t')" read -r name given scope until ucond ucheck check summary state; do + [ -n "$name" ] || continue + pend=$(printf '%s' "$PENDING" | awk -v n="$name" '$1 == n { print " (pending: " $2 ")" }') + if [ "$state" = active ] && [ "$ucheck" != - ]; then + if [ "$checks" = yes ] && [ "$RUNS" -lt 10 ]; then + RUNS=$((RUNS + 1)); bounded "$ucheck" + if [ "$RC" -eq 0 ]; then state=ended-check + elif [ "$RC" -eq 124 ]; then summary="$summary [until-check timed out]" + fi + else + summary="$summary [until-check not run]" + fi + fi + case "$state" in + expired) ne=$((ne + 1)); ended="$ended- ${name%.md}: until $until passed$pend +"; continue ;; + ended-check) ne=$((ne + 1)); ended="$ended- ${name%.md}: until-check exited 0 ($ucheck)$pend +"; continue ;; + esac + na=$((na + 1)) + active="$active- ${name%.md} ($scope): $summary$( [ "$until" = - ] || printf ' [until %s]' "$until")$pend +" + if [ "$ucond" != - ] && [ "$ucheck" = - ]; then + nt=$((nt + 1)); tocheck="$tocheck- ${name%.md}: $ucond +" + fi + if [ "$check" != - ]; then + if [ "$checks" = yes ] && [ "$RUNS" -lt 10 ]; then + RUNS=$((RUNS + 1)); bounded "$check" + if [ "$RC" -ne 0 ]; then + nf=$((nf + 1)); failed="$failed- ${name%.md}: $( [ "$RC" -eq 124 ] && echo "timed out" || echo "exit $RC")${LINE:+: $LINE} ($check) +" + fi + fi + fi + done < --reason ""\n%s' "$ne" "$ended" + [ "$nt" -eq 0 ] || printf 'condition to check now (%d): met -> ytstack-standing end ; not met -> it holds\n%s' "$nt" "$tocheck" + [ "$nf" -eq 0 ] || printf 'check failed (%d): the instruction is not kept\n%s' "$nf" "$failed" + [ "$checks" = yes ] || echo "(until-check and check not run: --no-checks)" + return 0 +} + +# ---- add / end ----------------------------------------------------------------------- +# entry_text: the file content from the A_* values. +entry_text() { + printf -- '---\ngiven: %s\nscope: %s\nsupersedes: %s\n' "$A_GIVEN" "$A_SCOPE" "$A_SUP" + [ -z "$A_UNTIL" ] || printf 'until: %s\n' "$A_UNTIL" + [ -z "$A_UCOND" ] || printf 'until-condition: %s\n' "$A_UCOND" + [ -z "$A_UCHECK" ] || printf 'until-check: %s\n' "$A_UCHECK" + [ -z "$A_CHECK" ] || printf 'check: %s\n' "$A_CHECK" + [ -z "$A_KIND" ] || printf 'kind: %s\n' "$A_KIND" + printf -- '---\n\n%s\n' "$A_TEXT" +} + +# write : the entry file in that directory; sets A_FILE. +write_entry() { + local sd="$1" base n=2 + mkdir -p "$sd" || die "cannot create $sd" + base="$A_STAMP-$A_SLUG"; A_FILE="$sd/$base.md" + while [ -e "$A_FILE" ]; do A_FILE="$sd/$base-$n.md"; n=$((n + 1)); done + entry_text > "$A_FILE" || die "cannot write $A_FILE" +} + +# validate <.ytstack dir>: ytstack-check --standing; on a problem the new file goes. +validate() { + local out py + py=$(yt_python); [ -n "$py" ] || die "python3 is needed for ytstack-check --standing" + out=$("$py" "$ROOT/bin/ytstack-check" --standing "$1" 2>&1) && return 0 + rm -f "$A_FILE" + printf '%s\n' "$out" | grep '\[fail\]' >&2 + die "the entry did not pass ytstack-check --standing; nothing was written" +} + +# repo_slug: OWNER/REPO from the configured origin URL (before insteadOf). +repo_slug() { + git -C "$TOP" config --get remote.origin.url 2>/dev/null | sed -E 's#\.git$##; s#/+$##; s#^.*[:/]([^/:]+/[^/:]+)$#\1#' +} + +publish() { + local wt rel day br base start repo n title body url + case "$YT_DIR" in "$TOP"/*) rel="${YT_DIR#"$TOP"/}" ;; *) die "the .ytstack directory $YT_DIR is outside the checkout; use --here" ;; esac + [ -n "$(git -C "$TOP" remote 2>/dev/null | head -1)" ] || die "no remote: use --here, or add origin" + day=$(date -u +%Y%m%d); br="standing/$day" + base="${A_BASE:-}" + [ -n "$base" ] || base=$(git -C "$TOP" symbolic-ref --short refs/remotes/origin/HEAD 2>/dev/null | sed 's#^origin/##') + [ -n "$base" ] || base=main + git -C "$TOP" fetch -q origin "$base" 2>/dev/null || echo "ytstack-standing: fetch failed, using the local refs" >&2 + git -C "$TOP" fetch -q origin "$br:refs/remotes/origin/$br" 2>/dev/null || true + yt_state_wt_dir >/dev/null + wt="$(yt_state_base)/repos/$YT_REPO_KEY/standing-worktree" + if ! git -C "$wt" rev-parse --is-inside-work-tree >/dev/null 2>&1; then + git -C "$TOP" worktree prune 2>/dev/null + mkdir -p "$(dirname "$wt")" || die "cannot create $(dirname "$wt")" + git -C "$TOP" worktree add -q --detach "$wt" 2>/dev/null || die "cannot add the worktree $wt" + fi + [ -z "$(git -C "$wt" status --porcelain 2>/dev/null)" ] || die "the standing worktree $wt has uncommitted changes; commit or remove them first" + if [ "$(git -C "$wt" branch --show-current)" != "$br" ]; then + if git -C "$TOP" rev-parse -q --verify "refs/heads/$br" >/dev/null; then + git -C "$wt" switch -q "$br" 2>/dev/null || die "cannot switch $wt to $br (checked out elsewhere?)" + else + start="origin/$br" + git -C "$TOP" rev-parse -q --verify "refs/remotes/$start" >/dev/null || start="origin/$base" + git -C "$TOP" rev-parse -q --verify "refs/remotes/$start" >/dev/null || start="$base" + git -C "$wt" switch -q -c "$br" "$start" 2>/dev/null || die "cannot create $br from $start in $wt" + fi + fi + ! git -C "$TOP" rev-parse -q --verify "refs/remotes/origin/$br" >/dev/null || git -C "$wt" merge -q --ff-only "origin/$br" 2>/dev/null || true + write_entry "$wt/$rel/standing" + validate "$wt/$rel" + git -C "$wt" add -- "$A_FILE" && git -C "$wt" commit -q -m "chore: standing: $(basename "$A_FILE" .md)" -- "$A_FILE" \ + || { rm -f "$A_FILE"; git -C "$wt" reset -q -- "$A_FILE" 2>/dev/null; die "the commit in $wt failed (signing?); nothing was committed"; } + echo "$A_FILE" + echo "committed on $br in $wt" + git -C "$wt" push -q -u origin "$br" 2>/dev/null || { echo "ytstack-standing: push of $br failed; the commit stays in $wt, the next add pushes it" >&2; exit 3; } + repo=$(repo_slug) + n=$(gh pr list --repo "$repo" --head "$br" --state open --json number --jq '.[0].number // empty' 2>/dev/null) \ + || { echo "ytstack-standing: pushed $br, but the open pull requests could not be read: open one for $br by hand" >&2; exit 3; } + if [ -n "$n" ]; then echo "standing PR #$n updated"; return 0; fi + title="chore: standing instructions $(date -u +%Y-%m-%d)" + body="Standing instructions recorded with bin/ytstack-standing on $(date -u +%Y-%m-%d) (one pull request per UTC day; docs/ux/coordinator-format.md, standing/). A change under .ytstack/standing/ goes to a person." + if grep -Eq '^[[:space:]]*pr_watch[[:space:]]*=[[:space:]]*on[[:space:]]*$' "${HOME:-/nonexistent}/.ytstack/config" 2>/dev/null \ + && [ -n "${CODEX_THREAD_ID:-}${CLAUDE_CODE_SESSION_ID:-}" ]; then + url=$(bash "$ROOT/bin/ytstack-pr-watch" create --repo "$repo" --cwd "$wt" -- --base "$base" --title "$title" --body "$body" 2>&1) + else + url=$(cd "$wt" && gh pr create --repo "$repo" --base "$base" --head "$br" --title "$title" --body "$body" 2>&1) + fi || { echo "ytstack-standing: pushed $br, but the pull request failed: $url" >&2; exit 3; } + echo "standing PR opened: $(printf '%s\n' "$url" | tail -1)" +} + +cmd_add() { + local here=no + A_TEXT=""; A_SCOPE=""; A_SUP=""; A_UNTIL=""; A_UCOND=""; A_UCHECK=""; A_CHECK=""; A_KIND=""; A_SLUG="" + if [ "$CMD" = end ]; then + [ $# -ge 1 ] || { usage >&2; return 64; } + A_SUP="${1%.md}"; shift + else + [ $# -ge 1 ] || { usage >&2; return 64; } + A_TEXT=$(oneline "$1"); shift + fi + while [ $# -gt 0 ]; do + case "$1" in + --here) here=yes; shift; continue ;; + esac + [ $# -ge 2 ] || { usage >&2; return 64; } + case "$CMD:$1" in + add:--scope) A_SCOPE=$(oneline "$2") ;; + add:--supersedes) A_SUP="${2%.md}" ;; + add:--until) A_UNTIL="$2" ;; + add:--until-condition) A_UCOND=$(oneline "$2") ;; + add:--until-check) A_UCHECK=$(oneline "$2") ;; + add:--check) A_CHECK=$(oneline "$2") ;; + add:--slug) A_SLUG="$2" ;; + end:--reason) A_TEXT="Ended: $(oneline "$2")" ;; + *:--base) A_BASE="$2" ;; + *) usage >&2; return 64 ;; + esac + shift 2 + done + if [ "$CMD" = end ]; then + [ -n "$A_TEXT" ] || { usage >&2; return 64; } + local tmp f + tmp=$(mktemp -d "${TMPDIR:-/tmp}/ytste.XXXXXX"); view "$tmp/standing" + f="$tmp/standing/$A_SUP.md" + [ -f "$f" ] || { rm -rf "$tmp"; die "no entry $A_SUP in $YT_DIR/standing/ or on a standing branch"; } + A_SCOPE=$(awk 'NR == 1 { next } /^---/ { exit } /^scope:/ { sub(/^scope:[ \t]*/, ""); print; exit }' "$f") + rm -rf "$tmp" + A_KIND=end; A_SLUG="end-$(printf '%s' "$A_SUP" | sed -E 's/^[0-9]{8}T[0-9]{4}([0-9]{2})?Z-//')" + case "$A_TEXT" in *[.!?]) ;; *) A_TEXT="$A_TEXT." ;; esac + fi + [ -n "$A_TEXT" ] && [ -n "$A_SCOPE" ] || { usage >&2; return 64; } + [ -n "$A_SLUG" ] || A_SLUG=$(printf '%s' "$A_TEXT" | LC_ALL=C tr '[:upper:]' '[:lower:]' | LC_ALL=C tr -c 'a-z0-9' ' ' | awk '{ for (i = 1; i <= NF && i <= 5; i++) printf "%s%s", (i > 1 ? "-" : ""), $i }' | cut -c1-40 | sed 's/-$//') + A_SLUG=$(printf '%s' "$A_SLUG" | LC_ALL=C tr '[:upper:]' '[:lower:]' | LC_ALL=C tr -c 'a-z0-9-' '-' | sed 's/--*/-/g; s/^-//' | cut -c1-48 | sed 's/-$//') + [ -n "$A_SLUG" ] || A_SLUG=instruction + A_STAMP=$(date -u +%Y%m%dT%H%MZ) + A_GIVEN=$(printf '%s' "$A_STAMP" | sed -E 's/^([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2})([0-9]{2})Z$/\1-\2-\3T\4:\5:00Z/') + case "$YT_DIR" in "$TOP"/*) ;; *) here=yes ;; esac + [ "$YT_IS_GIT" = yes ] || here=yes + if [ "$here" = yes ]; then + write_entry "$YT_DIR/standing" + validate "$YT_DIR" + echo "$A_FILE" + return 0 + fi + publish +} + +case "$CMD" in + list) cmd_list "$@" ;; + add|end) cmd_add "$@" ;; +esac diff --git a/tests/ytstack-standing.test.sh b/tests/ytstack-standing.test.sh new file mode 100644 index 00000000..25cbec6b --- /dev/null +++ b/tests/ytstack-standing.test.sh @@ -0,0 +1,228 @@ +#!/usr/bin/env bash +# Tests for bin/ytstack-standing: the write and read path of the standing +# instructions (.ytstack/standing/, docs/ux/coordinator-format.md; issues +# #72, #73, #74). +# +# Contract: +# add --here one entry file in the resolved .ytstack/standing/, name from +# UTC now and a slug, given/scope/supersedes and the optional +# keys, the text as body; ytstack-check --standing must pass, +# else nothing is written (exit 1); user scope is always --here +# add in a dedicated worktree outside the checkout on +# standing/: commit, push, one PR per day (gh pr +# create, or ytstack-pr-watch create with pr_watch=on), a second +# add the same day updates it; the checkout stays unchanged; +# push failure -> exit 3 with the commit kept +# end a kind-end entry that supersedes the one it closes, with its scope +# list active entries (pending ones from standing branches marked), +# ended ones (until passed, until-check exit 0), conditions to +# check, failed checks; commands are bounded by +# YTSTACK_STANDING_TIMEOUT; --no-checks runs none; the first line +# counts the session's human prompts since the newest entry +# +# Run: /bin/bash tests/ytstack-standing.test.sh (exit 0 = all pass; macOS bash 3.2) + +set -uo pipefail + +ROOT="$(cd "$(dirname "$0")/.." && pwd -P)" +BIN="$ROOT/bin/ytstack-standing" + +PASS=0; FAIL=0 +ok() { PASS=$((PASS+1)); echo " ok - $1"; } +bad() { FAIL=$((FAIL+1)); echo " FAIL - $1${2:+ ($2)}"; } +eq() { if [ "$2" = "$3" ]; then ok "$1"; else bad "$1" "expected '$2' got '$3'"; fi; } +has() { case "$3" in *"$2"*) ok "$1" ;; *) bad "$1" "no '$2' in: $3" ;; esac; } +hasnt() { case "$3" in *"$2"*) bad "$1" "unexpected '$2' in: $3" ;; *) ok "$1" ;; esac; } +grep_q() { grep "$@" >/dev/null; } + +if [ ! -x "$BIN" ]; then + bad "bin/ytstack-standing exists and is executable" + echo "$PASS passed, $FAIL failed" + exit 1 +fi + +TMP=$(mktemp -d "${TMPDIR:-/tmp}/ytstanding.XXXXXX"); TMP=$(cd "$TMP" && pwd -P) +trap 'rm -rf "$TMP"' EXIT +# A version-manager shim needs the real HOME: pick the binaries before HOME moves. +PY=$( . "$ROOT/hooks/lib/git-ctx.sh"; yt_python ) +[ -n "$PY" ] || { echo "FATAL: python3 not found"; exit 2; } +export YTSTACK_PYTHON="$PY" +export HOME="$TMP/home" XDG_STATE_HOME="$TMP/state" +mkdir -p "$HOME" +unset CLAUDE_CODE_SESSION_ID CODEX_THREAD_ID CLAUDE_PLUGIN_DATA PLUGIN_DATA 2>/dev/null +export GIT_CONFIG_NOSYSTEM=1 +git config --global user.email t@t.t; git config --global user.name t +git config --global commit.gpgsign false; git config --global init.defaultBranch main + +# ---- the fake host --------------------------------------------------------------- +FAKE="$TMP/fakebin"; GH_FIX="$TMP/host"; mkdir -p "$FAKE" "$GH_FIX" +cat > "$FAKE/gh" <<'GH' +#!/usr/bin/env bash +printf '%s\n' "$*" >> "$GH_FIX/log" +case "${1:-} ${2:-}" in + "pr list") [ ! -f "$GH_FIX/list.out" ] || cat "$GH_FIX/list.out" ;; + "pr create") [ ! -f "$GH_FIX/create.fail" ] || exit 1; echo "https://github.com/acme/demo/pull/5" ;; + "api repos/acme/demo/pulls/5") echo '{"number": 5}' ;; + *) echo "fake gh: unexpected call: $*" >&2; exit 1 ;; +esac +GH +chmod +x "$FAKE/gh" +export PATH="$FAKE:$PATH" GH_FIX + +# run : sets OUT (stdout + stderr) and EC +run() { local d="$1"; shift; OUT=$(bash "$BIN" -C "$d" "$@" 2>&1); EC=$?; } +NAME_RE='^[0-9]{8}T[0-9]{4}Z-[a-z0-9-]+\.md$' + +# ---- 1. --here: write, validate ---------------------------------------------------- +echo "# add --here" +P="$TMP/p"; mkdir -p "$P/.ytstack"; ( cd "$P" && git init -q ) || exit 2 +run "$P" add "Merge green pull requests promptly. Ask first for anything red." --scope "the coordinator" --here +eq "add --here: exit 0" 0 "$EC" +F=$(ls "$P/.ytstack/standing" | head -1) +if printf '%s\n' "$F" | grep -Eq "$NAME_RE"; then ok "name -.md ($F)"; else bad "name pattern" "$F"; fi +has "slug from the first words" "merge-green-pull-requests-promptly" "$F" +C=$(cat "$P/.ytstack/standing/$F") +has "given in the minute of the name" "given: $(printf '%s' "$F" | sed -E 's/^([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2})([0-9]{2})Z.*/\1-\2-\3T\4:\5:00Z/')" "$C" +has "scope" "scope: the coordinator" "$C" +has "empty supersedes" "supersedes: " "$C" +has "the text is the body" "Merge green pull requests promptly." "$C" +hasnt "no optional key when not given" "until" "$C" +eq "the entry passes ytstack-check --standing" 0 "$("$PY" "$ROOT/bin/ytstack-check" --standing "$P" >/dev/null 2>&1; echo $?)" + +run "$P" add "Hold merges" --scope "every lane" --until 2020-01-01T00:00Z --here +eq "until before given: exit 1" 1 "$EC"; has "names the problem" "not after given" "$OUT" +run "$P" add "Hold merges" --scope "every lane" --until tomorrow --here +eq "until not ISO: exit 1" 1 "$EC" +eq "nothing written by the refused adds" 1 "$(ls "$P/.ytstack/standing" | grep -c .)" +run "$P" add "No scope" --here; eq "add without --scope: exit 64" 64 "$EC" +run "$P" add "Hold" --scope x --supersedes 20200101T0000Z-nothing --here +eq "supersedes an unknown entry: exit 1" 1 "$EC" + +# ---- 2. list: active, ended, to check, failed checks --------------------------------- +echo "# list" +L="$TMP/l"; SD="$L/.ytstack/standing"; mkdir -p "$SD"; ( cd "$L" && git init -q ) || exit 2 +w() { printf -- '---\ngiven: %s\nscope: %s\nsupersedes:\n%b---\n\n%s\n' "$2" "$3" "$4" "$5" > "$SD/$1.md"; } +w 20261101T1000Z-old-window 2026-11-01T10:00:00Z "every lane" 'until: 2026-11-01T12:37Z\n' "Hold merges until the measurement ends." +w 20261101T1100Z-pr-hold 2026-11-01T11:00:00Z "every lane" 'until-condition: PR #1879 merged\n' "Do not touch PR 1336 while the v2 plan runs." +w 20261101T1200Z-done-by-check 2026-11-01T12:00:00Z "the coordinator" 'until-check: exit 0\n' "Raise the PR limit during the load test." +w 20261101T1300Z-lanes-file 2026-11-01T13:00:00Z "the coordinator" 'check: echo "LANES.md last changed 14 h ago"; exit 1\n' "Lanes are tracked in LANES.md at all times." +w 20261101T1400Z-slow 2026-11-01T14:00:00Z "the coordinator" 'until-check: sleep 30\n' "A slow condition." +w 20261101T1500Z-plain 2026-11-01T15:00:00Z "every reviewer" '' "Every review names the reviewed commit." +start=$(date +%s) +OUT=$(YTSTACK_STANDING_TIMEOUT=1 bash "$BIN" -C "$L" list 2>&1); EC=$? +took=$(( $(date +%s) - start )) +eq "list: exit 0" 0 "$EC" +has "first line names the newest entry" "newest entry: 20261101T1500Z-plain (" "$OUT" +has "no session -> prompts not counted" "human prompts since: not counted" "$OUT" +has "active section counts" "active (4):" "$OUT" +has "an active entry with scope and first sentence" "- 20261101T1500Z-plain (every reviewer): Every review names the reviewed commit." "$OUT" +has "until passed -> ended" "- 20261101T1000Z-old-window: until 2026-11-01T12:37Z passed" "$OUT" +has "until-check exit 0 -> ended" "- 20261101T1200Z-done-by-check: until-check exited 0" "$OUT" +has "until-condition -> to check" "- 20261101T1100Z-pr-hold: PR #1879 merged" "$OUT" +has "a failed check is shown with its output" "- 20261101T1300Z-lanes-file: exit 1: LANES.md last changed 14 h ago" "$OUT" +has "a slow until-check times out and stays active" "A slow condition. [until-check timed out]" "$OUT" +if [ "$took" -le 4 ]; then ok "the timeout bounds the run ($took s)"; else bad "the timeout bounds the run" "$took s"; fi +OUT=$(bash "$BIN" -C "$L" list --no-checks 2>&1) +hasnt "--no-checks: no until-check runs" "until-check exited 0" "$OUT" +hasnt "--no-checks: no check runs" "check failed" "$OUT" +has "--no-checks says so" "not run: --no-checks" "$OUT" +has "--no-checks: time-based expiry still applies" "until 2026-11-01T12:37Z passed" "$OUT" + +# ---- 3. end --------------------------------------------------------------------------- +echo "# end" +run "$L" end 20261101T1100Z-pr-hold --reason "PR #1879 merged at 2026-11-02T09:00Z" --here +eq "end: exit 0" 0 "$EC" +E=$(ls "$SD" | grep end-pr-hold) +C=$(cat "$SD/$E" 2>/dev/null) +has "end entry: kind end" "kind: end" "$C" +has "end entry: supersedes the closed one" "supersedes: 20261101T1100Z-pr-hold" "$C" +has "end entry: copies the scope" "scope: every lane" "$C" +has "end entry: body names the reason" "Ended: PR #1879 merged at 2026-11-02T09:00Z." "$C" +OUT=$(bash "$BIN" -C "$L" list --no-checks 2>&1) +hasnt "the closed entry is gone from the list" "- 20261101T1100Z-pr-hold" "$OUT" +hasnt "the end entry is no instruction" "Ended:" "$OUT" +eq "ytstack-check --standing accepts the end entry" 0 "$("$PY" "$ROOT/bin/ytstack-check" --standing "$L" >/dev/null 2>&1; echo $?)" +run "$L" end 20200101T0000Z-nothing --reason x --here; eq "end of an unknown entry: exit 1" 1 "$EC" + +# ---- 4. prompt counter ---------------------------------------------------------------- +echo "# prompts since the newest entry" +SESS="$XDG_STATE_HOME/ytstack/sessions/sess-1"; mkdir -p "$SESS" +printf '%s\n' "$L/.ytstack" > "$SESS/coordinate" +printf '%s\n%s\n%s\n' 1000 "$(date +%s)" "$(date +%s)" > "$SESS/prompts" +OUT=$(CLAUDE_CODE_SESSION_ID=sess-1 bash "$BIN" -C "$L" list --no-checks 2>&1) +has "two prompts after the newest entry are counted" "human prompts since: 2" "$OUT" + +# ---- 5. user scope is always --here ---------------------------------------------------- +echo "# user scope" +U="$TMP/u"; mkdir -p "$U"; ( cd "$U" && git init -q && git commit -q --allow-empty -m seed ) || exit 2 +KEY=$( . "$ROOT/hooks/lib/git-ctx.sh"; yt_git_ctx "$U"; printf '%s' "$YT_REPO_KEY" ) +mkdir -p "$HOME/.ytstack/projects/$KEY" +run "$U" add "Status only at slice boundaries." --scope "this project" +eq "user scope add: exit 0" 0 "$EC" +eq "written into the user-scope directory" 1 "$(ls "$HOME/.ytstack/projects/$KEY/standing" 2>/dev/null | grep -c .)" +eq "nothing in the checkout" "" "$(git -C "$U" status --porcelain)" + +# ---- 6. default: dedicated worktree, one PR per day ------------------------------------ +echo "# add: worktree, commit, push, PR" +BARE="$TMP/remote.git"; git init -q --bare "$BARE" +M="$TMP/m"; git init -q "$M" +( cd "$M" || exit 2 + git config url."$BARE".insteadOf https://github.com/acme/demo.git + git remote add origin https://github.com/acme/demo.git + mkdir .ytstack && printf 'x\n' > .ytstack/STATE.md && git add -A && git commit -qm seed && git push -q -u origin main + git remote set-head origin main ) >/dev/null 2>&1 || { echo "FATAL fixture"; exit 2; } +DAY=$(date -u +%Y%m%d) +rm -f "$GH_FIX/log" +run "$M" add "Never merge a red main." --scope "every lane" +eq "add: exit 0" 0 "$EC" +has "names the branch of the day" "committed on standing/$DAY" "$OUT" +has "a new PR is opened" "standing PR opened: https://github.com/acme/demo/pull/5" "$OUT" +LOG=$(cat "$GH_FIX/log" 2>/dev/null) +has "gh pr create on the day branch against main" "pr create --repo acme/demo --base main --head standing/$DAY" "$LOG" +eq "the checkout is unchanged" "" "$(git -C "$M" status --porcelain)" +[ ! -d "$M/.ytstack/standing" ] && ok "no entry in the checkout's tree" || bad "no entry in the checkout's tree" +REMOTE_FILES=$(git --git-dir="$BARE" ls-tree --name-only "standing/$DAY" -- .ytstack/standing/ 2>/dev/null) +has "pushed: the remote branch has the entry" "never-merge-a-red-main" "$REMOTE_FILES" +WT="$XDG_STATE_HOME/ytstack/repos" +case "$OUT" in *"$TMP/state/ytstack/repos/"*standing-worktree*) ok "the worktree is outside the checkout" ;; *) bad "the worktree is outside the checkout" "$OUT" ;; esac +SUBJ=$(git --git-dir="$BARE" log -1 --format=%s "standing/$DAY") +has "commit subject" "chore: standing: " "$SUBJ" + +echo 7 > "$GH_FIX/list.out"; rm -f "$GH_FIX/log" +run "$M" add "Status only at slice boundaries." --scope "this project" +eq "second add: exit 0" 0 "$EC" +has "the open PR of the day is updated" "standing PR #7 updated" "$OUT" +hasnt "no second PR" "pr create" "$(cat "$GH_FIX/log" 2>/dev/null)" +eq "two commits on the day branch" 2 "$(git --git-dir="$BARE" rev-list --count "main..standing/$DAY")" + +OUT=$(bash "$BIN" -C "$M" list --no-checks 2>&1) +has "list in the checkout shows the unmerged entries as pending" "(pending: standing/$DAY)" "$OUT" +has "both pending entries are active" "active (2):" "$OUT" + +echo "# push failure" +rm -f "$GH_FIX/list.out" +git -C "$M" config url."$TMP/nowhere.git".insteadOf https://github.com/acme/demo.git +git -C "$M" config --unset url."$BARE".insteadOf +run "$M" add "Keep the PR limit at 15." --scope "the coordinator" +eq "push fails: exit 3" 3 "$EC" +has "says the commit stays" "the commit stays" "$OUT" +git -C "$M" config --unset url."$TMP/nowhere.git".insteadOf +git -C "$M" config url."$BARE".insteadOf https://github.com/acme/demo.git + +echo "# pr-watch create when the PR watch is on" +# ytstack-pr-watch create reads `git remote get-url origin`, which applies +# insteadOf: keep the GitHub URL for fetch (refused at once, no network) and +# push to the bare repository. +git -C "$M" config --unset url."$BARE".insteadOf +git -C "$M" config remote.origin.pushurl "$BARE" +mkdir -p "$HOME/.ytstack"; printf 'pr_watch=on\n' > "$HOME/.ytstack/config" +rm -f "$GH_FIX/list.out" "$GH_FIX/log" +OUT=$(GIT_ALLOW_PROTOCOL=file CLAUDE_CODE_SESSION_ID=sess-1 YTSTACK_PR_WATCH_HOME="$TMP/prw" bash "$BIN" -C "$M" add "Review every push once." --scope "every reviewer" 2>&1); EC=$? +eq "add with pr_watch=on: exit 0" 0 "$EC" +has "the PR comes from ytstack-pr-watch create" "monitor registered" "$OUT" +has "and gh created it" "pr create --repo acme/demo" "$(cat "$GH_FIX/log" 2>/dev/null)" +eq "the push of the earlier failed commit went out too" 4 "$(git --git-dir="$BARE" rev-list --count "main..standing/$DAY")" + +echo +echo "$PASS passed, $FAIL failed" +[ "$FAIL" -eq 0 ] From 3d8046221374d7582ba9b03b3ff1733ccbe58b0e Mon Sep 17 00:00:00 2001 From: Alex Wegener Date: Sun, 15 Nov 2026 14:39:52 +0100 Subject: [PATCH 03/25] feat: standing-prompt hook flags standing instructions; stop blocks once when unrecorded (#72) Active only with the coordinate session marker. The prompt hook counts human prompts and flags ones that read like standing instructions; the Stop hook blocks once when flagged prompts got no entry in the working tree or on any local ref since. Co-Authored-By: Claude Opus 5.5 --- hooks/hooks.json | 13 +++- hooks/standing-prompt | 79 +++++++++++++++++++++++ hooks/stop | 110 +++++++++++++++++++++++--------- tests/hooks-json.test.sh | 2 + tests/hooks-standing.test.sh | 117 +++++++++++++++++++++++++++++++++++ 5 files changed, 291 insertions(+), 30 deletions(-) create mode 100644 hooks/standing-prompt create mode 100644 tests/hooks-standing.test.sh diff --git a/hooks/hooks.json b/hooks/hooks.json index 19f47a3f..50843c4c 100644 --- a/hooks/hooks.json +++ b/hooks/hooks.json @@ -1,5 +1,5 @@ { - "description": "ytstack lifecycle hooks: inject project state at session boundaries, persist volatile session state OUT OF TREE on compaction and end-of-session, link commits to tasks. All hooks resolve the checkout from the payload cwd via hooks/lib/git-ctx.sh (never CLAUDE_PROJECT_DIR) and fail open (no onFailure: block). SessionEnd hooks get a 1.5 s default budget from Claude Code; the hook runs in ~0.3-0.5 s. hooks/version-notice (UserPromptSubmit) says once when the installed plugin is newer than the one the session loaded. hooks/pr-watch (SessionStart, UserPromptSubmit, PreToolUse and PostToolUse on Bash or an MCP create_pull_request) is the opt-in PR watch: it exits at once unless ~/.ytstack/config has pr_watch=on (docs/pr-watch.md).", + "description": "ytstack lifecycle hooks: inject project state at session boundaries, persist volatile session state OUT OF TREE on compaction and end-of-session, link commits to tasks. All hooks resolve the checkout from the payload cwd via hooks/lib/git-ctx.sh (never CLAUDE_PROJECT_DIR) and fail open (no onFailure: block). SessionEnd hooks get a 1.5 s default budget from Claude Code; the hook runs in ~0.3-0.5 s. hooks/version-notice (UserPromptSubmit) says once when the installed plugin is newer than the one the session loaded. hooks/standing-prompt (UserPromptSubmit) acts only in a coordinate session (the marker the coordinate preamble writes): it counts human prompts and flags one that reads like a standing instruction, and hooks/stop then blocks once when no standing entry was written since. hooks/pr-watch (SessionStart, UserPromptSubmit, PreToolUse and PostToolUse on Bash or an MCP create_pull_request) is the opt-in PR watch: it exits at once unless ~/.ytstack/config has pr_watch=on (docs/pr-watch.md).", "hooks": { "SessionStart": [ { @@ -39,6 +39,17 @@ } ] }, + { + "hooks": [ + { + "type": "command", + "shell": "bash", + "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/standing-prompt\"", + "async": false, + "timeout": 5 + } + ] + }, { "hooks": [ { diff --git a/hooks/standing-prompt b/hooks/standing-prompt new file mode 100644 index 00000000..a06e08e7 --- /dev/null +++ b/hooks/standing-prompt @@ -0,0 +1,79 @@ +#!/usr/bin/env bash +# ytstack UserPromptSubmit hook: standing instructions in a coordinator session +# (issue #72). Active only in coordinate mode: the coordinate preamble writes +# the marker //coordinate (yt_session_home in +# hooks/lib/git-ctx.sh; DECISIONS 2026-11-15 "coordinate mode is a session +# marker"). Without it the hook ends at once, without reading git. +# +# In coordinate mode, per human prompt: +# 1. appends the epoch to /prompts (the coordinate preamble +# counts the prompts since the newest standing entry); +# 2. when the prompt reads like a standing instruction (always, never, from +# now on, until, while, prioritise, don't touch, remember; German: immer, +# nie, ab jetzt, bis, waehrend, priorisiere, fass ... nicht an, denk dran), +# appends it to /standing-flags for hooks/stop and injects +# one line: record it under .ytstack/standing/ before the next dispatch. +# A prompt that starts with "<" (a task notification, a system message) is no +# human prompt and is skipped. +# +# Files and grep only; no command of a standing entry runs here. Fail open: +# any problem ends silent with exit 0. Output: the UserPromptSubmit +# additionalContext JSON; YTSTACK_HOOK_FORMAT=plain prints the text. + +set -uo pipefail +trap '' PIPE + +. "$(cd "$(dirname "$0")" && pwd)/lib/git-ctx.sh" + +yt_read_stdin +SID="${YT_SESSION_ID:-}" +case "$SID" in ''|.|..|*[!A-Za-z0-9._-]*) exit 0 ;; esac +SD="$(yt_session_home)/$SID" +[ -f "$SD/coordinate" ] || exit 0 + +JQ=$(yt_jq) +if [ -n "$JQ" ]; then + PROMPT=$(printf '%s' "$YT_STDIN" | "$JQ" -r '.prompt | if type == "string" then . elif type == "array" then map(.text? // "") | join(" ") else "" end' 2>/dev/null) || exit 0 +elif [ -n "$(yt_python)" ]; then + PROMPT=$(printf '%s' "$YT_STDIN" | "$(yt_python)" -I -c ' +import json, sys +try: + p = json.load(sys.stdin).get("prompt", "") +except Exception: + p = "" +if isinstance(p, list): + p = " ".join(str(i.get("text", "")) for i in p if isinstance(i, dict)) +print(p if isinstance(p, str) else "") +' 2>/dev/null) || exit 0 +else + exit 0 +fi +PROMPT="${PROMPT:0:4000}" +case "${PROMPT#"${PROMPT%%[![:space:]]*}"}" in ''|'<'*) exit 0 ;; esac + +NOW=$(date +%s) +printf '%s\n' "$NOW" >> "$SD/prompts" 2>/dev/null || exit 0 + +# Word boundaries without \b (BSD and BusyBox grep differ): a non-letter or the +# line edge on both sides. LC_ALL=C keeps the umlaut bytes out of [:alnum:]. +B='(^|[^[:alnum:]])' +E='([^[:alnum:]]|$)' +EN="always|never|from now on|going forward|from here on|until|while|whenever|as long as|prioriti[sz]e|prioriti[sz]ing|don'?t touch|do not touch|hands off|leave [^.!?]{1,60} alone|remember to|keep in mind|no more" +DE="immer|nie|niemals|ab jetzt|ab sofort|von jetzt an|ab heute|k(ue|ü)nftig|in zukunft|bis|w(ae|ä)hrend|solange|sobald|priorisier[a-z]*|fass[^.!?]{1,60}nicht an|nicht anfassen|denk dran|denk daran|merk dir|grunds(ae|ä)tzlich" +HIT=$(printf '%s' "$PROMPT" | tr '\n\r' ' ' | LC_ALL=C tr '[:upper:]' '[:lower:]' | LC_ALL=C grep -Eo "$B($EN|$DE)$E" 2>/dev/null | head -1 | LC_ALL=C sed 's/^[^[:alnum:]]*//; s/[^[:alnum:]]*$//') +[ -n "$HIT" ] || exit 0 + +EXCERPT=$(printf '%s' "$PROMPT" | tr '\n\r\t' ' ' | cut -c1-100) +printf '%s\t%s\t%s\t%s\n' "$NOW" "$(date -u +%Y%m%d%H%M)" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$EXCERPT" >> "$SD/standing-flags" 2>/dev/null || exit 0 + +ROOT="${CLAUDE_PLUGIN_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}" +TEXT="ytstack: this prompt reads like a standing instruction (\"$HIT\"). If it holds beyond the task at hand, record it before the next dispatch, in your own words: bash \"$ROOT/bin/ytstack-standing\" add \"\" --scope \"\" (add --until or --until-condition \"\" when it ends). Agent memory is no substitute: a successor and other hosts read only .ytstack/standing/. If it is not one, go on." + +if [ "${YTSTACK_HOOK_FORMAT:-json}" = plain ]; then + printf '%s\n' "$TEXT" +elif [ -n "$JQ" ]; then + printf '%s' "$TEXT" | "$JQ" -Rs '{hookSpecificOutput: {hookEventName: "UserPromptSubmit", additionalContext: .}}' 2>/dev/null +elif [ -n "$(yt_python)" ]; then + printf '%s' "$TEXT" | "$(yt_python)" -I -c 'import sys, json; print(json.dumps({"hookSpecificOutput": {"hookEventName": "UserPromptSubmit", "additionalContext": sys.stdin.read()}}))' 2>/dev/null +fi +exit 0 diff --git a/hooks/stop b/hooks/stop index cc06df42..e5d9be2b 100644 --- a/hooks/stop +++ b/hooks/stop @@ -1,10 +1,22 @@ #!/usr/bin/env bash -# ytstack Stop hook (advisory, M019) +# ytstack Stop hook (M019, issue #72) # -# Fires when the main agent is about to stop. If STATE.md still points at an -# active task whose SUMMARY is missing or a draft stub, surface a one-line -# reminder to the user via `systemMessage`. Never blocks (exit 0, no -# `decision: block`): the user may well be stopping on purpose. +# Fires when the main agent is about to stop. +# +# 1. Task reminder (advisory): if STATE.md still points at an active task +# whose SUMMARY is missing or a draft stub, surface a one-line reminder +# via `systemMessage`. Never blocks for this: the user may well be +# stopping on purpose. +# 2. Standing instructions (coordinate mode only, the session marker of +# hooks/standing-prompt): when hooks/standing-prompt flagged human +# prompts that were not handled yet and no standing entry was written +# since the first of them, block the stop ONCE with the list +# (`decision: block`). An entry counts when its name time is in or after +# the minute of that prompt and it is in the working tree's standing/, +# or any ref of the repository (local branches, and the remote-tracking +# branch of a pushed standing PR) added it after that prompt. Local git +# only, no network. Afterwards the flags count as handled +# (/standing-stop), so the same prompts never block twice. # # Resolution: payload `cwd` via hooks/lib/git-ctx.sh (never CLAUDE_PROJECT_DIR). # Respects `stop_hook_active` (set when a previous Stop hook already continued @@ -16,38 +28,78 @@ trap '' PIPE . "$(cd "$(dirname "$0")" && pwd)/lib/git-ctx.sh" yt_read_stdin +JQ=$(yt_jq) # stop_hook_active: do nothing when we are inside a hook-continued turn -if [ -n "${YT_STDIN:-}" ]; then - JQ=$(yt_jq) - if [ -n "$JQ" ] && [ "$(printf '%s' "$YT_STDIN" | "$JQ" -r '.stop_hook_active // false' 2>/dev/null)" = true ]; then - exit 0 - fi +if [ -n "${YT_STDIN:-}" ] && [ -n "$JQ" ] && [ "$(printf '%s' "$YT_STDIN" | "$JQ" -r '.stop_hook_active // false' 2>/dev/null)" = true ]; then + exit 0 fi -yt_git_ctx "${YT_CWD:-$PWD}" -YT_DIR=$(yt_resolve_yt_dir) -[ -z "$YT_DIR" ] && exit 0 -STATE_FILE="$YT_DIR/STATE.md" -[ -f "$STATE_FILE" ] || exit 0 +# ---- 2. standing instructions (coordinate mode) ---------------------------------- +standing_block() { + local sid="${YT_SESSION_ID:-}" sd ytd done_at first_m first_iso last_e n f list + case "$sid" in ''|.|..|*[!A-Za-z0-9._-]*) return 0 ;; esac + sd="$(yt_session_home)/$sid" + [ -f "$sd/coordinate" ] && [ -s "$sd/standing-flags" ] || return 0 + ytd=$(sed -n 1p "$sd/coordinate" 2>/dev/null) + [ -n "$ytd" ] && [ -d "$ytd" ] || return 0 + done_at=$(sed -n 1p "$sd/standing-stop" 2>/dev/null); case "$done_at" in ''|*[!0-9]*) done_at=0 ;; esac + list=$(awk -F '\t' -v d="$done_at" '$1 + 0 > d + 0' "$sd/standing-flags" 2>/dev/null) + [ -n "$list" ] || return 0 + first_m=$(printf '%s\n' "$list" | awk -F '\t' 'NR == 1 { print $2 }') + first_iso=$(printf '%s\n' "$list" | awk -F '\t' 'NR == 1 { print $3 }') + last_e=$(printf '%s\n' "$list" | awk -F '\t' 'END { print $1 }') + printf '%s\n' "$last_e" > "$sd/standing-stop" 2>/dev/null || return 0 -get_field() { sed -n "s/^$1: *//p" "$STATE_FILE" 2>/dev/null | head -1; } -M=$(get_field current_milestone); S=$(get_field active_slice); T=$(get_field active_task) -case "$T" in ""|none|all) exit 0 ;; esac -case "$S" in ""|none|all) exit 0 ;; esac -case "$M" in ""|none) exit 0 ;; esac + # An entry since the first flagged prompt? Name time YYYYMMDDHHMM >= its minute. + newer() { awk -v m="$first_m" '{ b = $0; sub(/.*\//, "", b); k = substr(b, 1, 8) substr(b, 10, 4) } k ~ /^[0-9]+$/ && k >= m { f = 1 } END { exit !f }'; } + for f in "$ytd"/standing/*.md; do [ -f "$f" ] && printf '%s\n' "$f"; done | newer && return 0 + if [ "$(git -C "$ytd" rev-parse --is-inside-work-tree 2>/dev/null)" = true ]; then + git -C "$ytd" log --all --since="$first_iso" --diff-filter=A --name-only --format= -- standing/ 2>/dev/null | newer && return 0 + fi + n=$(printf '%s\n' "$list" | grep -c .) + BLOCK_REASON="ytstack: $n human prompt(s) in this coordinator session read like standing instructions, and no standing entry was written since $first_iso: +$(printf '%s\n' "$list" | awk -F '\t' '{ print "- " $3 ": \"" $4 "\"" }') +Record each one that holds beyond the task at hand, in your own words: bash \"${CLAUDE_PLUGIN_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}/bin/ytstack-standing\" add \"\" --scope \"\" (ytstack:coordinate Step 9). If none of them is one, say so in one line and stop. This check blocks once for these prompts." +} +BLOCK_REASON="" +standing_block -SUMMARY="$YT_DIR/$M-$S-$T-SUMMARY.md" +# ---- 1. task reminder -------------------------------------------------------------- +task_msg() { + local ytd state m s t summary + yt_git_ctx "${YT_CWD:-$PWD}" + ytd=$(yt_resolve_yt_dir) + [ -n "$ytd" ] && [ -f "$ytd/STATE.md" ] || return 0 + state="$ytd/STATE.md" + get_field() { sed -n "s/^$1: *//p" "$state" 2>/dev/null | head -1; } + m=$(get_field current_milestone); s=$(get_field active_slice); t=$(get_field active_task) + case "$t" in ""|none|all) return 0 ;; esac + case "$s" in ""|none|all) return 0 ;; esac + case "$m" in ""|none) return 0 ;; esac + summary="$ytd/$m-$s-$t-SUMMARY.md" + if [ ! -f "$summary" ]; then + MSG="ytstack: $m-$s-$t is still the active task and has no summary. If the work is done, run /ytstack:summarize-task; if you are pausing, /ytstack:handoff-session keeps the thread." + elif [ "$(sed -n 's/^closed: *//p' "$summary" | head -1)" = draft ]; then + MSG="ytstack: $m-$s-$t has only a draft summary stub. Run /ytstack:summarize-task to close it, or /ytstack:handoff-session if you are pausing." + fi +} MSG="" -if [ ! -f "$SUMMARY" ]; then - MSG="ytstack: $M-$S-$T is still the active task and has no summary. If the work is done, run /ytstack:summarize-task; if you are pausing, /ytstack:handoff-session keeps the thread." -elif [ "$(sed -n 's/^closed: *//p' "$SUMMARY" | head -1)" = draft ]; then - MSG="ytstack: $M-$S-$T has only a draft summary stub. Run /ytstack:summarize-task to close it, or /ytstack:handoff-session if you are pausing." -fi -[ -z "$MSG" ] && exit 0 +task_msg -JQ=$(yt_jq) +[ -n "$MSG$BLOCK_REASON" ] || exit 0 if [ -n "$JQ" ]; then - printf '%s' "$MSG" | "$JQ" -Rs '{systemMessage: .}' + "$JQ" -n --arg m "$MSG" --arg r "$BLOCK_REASON" \ + '(if $r != "" then {decision: "block", reason: $r} else {} end) + (if $m != "" then {systemMessage: $m} else {} end)' +elif [ -n "$(yt_python)" ]; then + "$(yt_python)" -I -c ' +import json, sys +m, r = sys.argv[1], sys.argv[2] +o = {} +if r: + o.update(decision="block", reason=r) +if m: + o["systemMessage"] = m +print(json.dumps(o))' "$MSG" "$BLOCK_REASON" else printf '{"systemMessage":"%s"}\n' "$(printf '%s' "$MSG" | sed 's/"/\\"/g')" fi diff --git a/tests/hooks-json.test.sh b/tests/hooks-json.test.sh index 758eed63..176f9324 100644 --- a/tests/hooks-json.test.sh +++ b/tests/hooks-json.test.sh @@ -38,6 +38,8 @@ eq "pr-watch timeouts are 15 s" "15" \ "$(jq -r --arg c "$PW" '[.hooks[][].hooks[] | select(.command == $c) | .timeout] | unique | join(",")' "$J")" eq "version-notice is the first UserPromptSubmit entry, 5 s" 'bash "${CLAUDE_PLUGIN_ROOT}/hooks/version-notice"|5' \ "$(jq -r '.hooks.UserPromptSubmit[0].hooks[0] | "\(.command)|\(.timeout)"' "$J")" +eq "standing-prompt is the second UserPromptSubmit entry, 5 s (issue #72)" 'bash "${CLAUDE_PLUGIN_ROOT}/hooks/standing-prompt"|5' \ + "$(jq -r '.hooks.UserPromptSubmit[1].hooks[0] | "\(.command)|\(.timeout)"' "$J")" eq "session-start stays the first SessionStart entry" 'bash "${CLAUDE_PLUGIN_ROOT}/hooks/session-start"' \ "$(jq -r '.hooks.SessionStart[0].hooks[0].command' "$J")" diff --git a/tests/hooks-standing.test.sh b/tests/hooks-standing.test.sh new file mode 100644 index 00000000..eed78a95 --- /dev/null +++ b/tests/hooks-standing.test.sh @@ -0,0 +1,117 @@ +#!/usr/bin/env bash +# Tests for the standing-instruction hooks of a coordinator session (issue #72). +# +# hooks/standing-prompt (UserPromptSubmit) +# - no coordinate marker -> silent, writes nothing +# - marker: every human prompt is counted (/prompts) +# - a prompt that reads like a standing instruction (English and German) +# is flagged and gets the record instruction as additionalContext +# - a plain prompt is counted, not flagged; a "" is neither +# hooks/stop +# - flagged prompt, no entry since -> decision block once, with the list +# - the next stop with the same flags -> no block (handled) +# - an entry in the working tree since the prompt -> no block +# - an entry only on a branch since the prompt -> no block +# - stop_hook_active -> silent; the task reminder still works beside a block +# +# Run: /bin/bash tests/hooks-standing.test.sh (exit 0 = all pass) + +set -uo pipefail +ROOT="$(cd "$(dirname "$0")/.." && pwd -P)" +HP="$ROOT/hooks/standing-prompt"; HS="$ROOT/hooks/stop" + +PASS=0; FAIL=0 +ok() { PASS=$((PASS+1)); echo " ok - $1"; } +bad() { FAIL=$((FAIL+1)); echo " FAIL - $1${2:+ ($2)}"; } +eq() { if [ "$2" = "$3" ]; then ok "$1"; else bad "$1" "expected '$2' got '$3'"; fi; } +has() { case "$2" in *"$3"*) ok "$1";; *) bad "$1" "missing '$3' in: $2";; esac; } +hasnt() { case "$2" in *"$3"*) bad "$1" "unexpected '$3'";; *) ok "$1";; esac; } + +JQ=""; for c in /usr/bin/jq /opt/homebrew/bin/jq /usr/local/bin/jq; do [ -x "$c" ] && { JQ="$c"; break; }; done +[ -n "$JQ" ] || JQ=$(command -v jq) +[ -n "$JQ" ] || { echo "FATAL: jq needed"; exit 2; } + +TMP=$(mktemp -d "${TMPDIR:-/tmp}/ytstdhook.XXXXXX"); TMP=$(cd "$TMP" && pwd -P) +trap 'rm -rf "$TMP"' EXIT +export XDG_STATE_HOME="$TMP/state" +unset CLAUDE_PLUGIN_DATA PLUGIN_DATA 2>/dev/null +SD="$XDG_STATE_HOME/ytstack/sessions/s1" + +P="$TMP/p"; mkdir -p "$P/.ytstack" +( cd "$P" || exit 2; git init -q && git config user.email t@t.t && git config user.name t && git config commit.gpgsign false + printf 'x\n' > .ytstack/STATE.md; git add -A; git commit -qm seed ) >/dev/null 2>&1 || { echo FATAL fixture; exit 2; } + +prompt() { # prompt -> OUT + OUT=$("$JQ" -n --arg p "$1" --arg c "$P" '{session_id: "s1", cwd: $c, hook_event_name: "UserPromptSubmit", prompt: $p}' | bash "$HP" 2>&1) +} +stop() { # stop [extra jq object] -> OUT + local extra="${1:-}"; [ -n "$extra" ] || extra='{}' + OUT=$("$JQ" -n --arg c "$P" '{session_id: "s1", cwd: $c, hook_event_name: "Stop"}' | "$JQ" -c ". + $extra" | bash "$HS" 2>&1) +} +lines() { [ -f "$1" ] && grep -c . "$1" || echo 0; } + +echo "# no coordinate marker" +prompt "From now on always merge green pull requests." +eq "silent without the marker" "" "$OUT" +[ -e "$SD" ] && bad "writes nothing without the marker" || ok "writes nothing without the marker" + +echo "# coordinate marker" +mkdir -p "$SD"; printf '%s\n' "$P/.ytstack" > "$SD/coordinate" +prompt "What is the state of lane S02?" +eq "plain prompt: silent" "" "$OUT" +eq "plain prompt: counted" 1 "$(lines "$SD/prompts")" +eq "plain prompt: not flagged" 0 "$(lines "$SD/standing-flags")" +prompt "agent done, never mind" +eq "task notification: silent" "" "$OUT" +eq "task notification: not counted" 1 "$(lines "$SD/prompts")" +prompt "From now on merge green PRs promptly." +has "English standing phrase -> instruction injected" "$OUT" "reads like a standing instruction" +has "names the command" "$OUT" "bin/ytstack-standing\\\" add" +has "says memory is no substitute" "$OUT" "Agent memory is no substitute" +if printf '%s' "$OUT" | "$JQ" -e '.hookSpecificOutput.additionalContext' >/dev/null 2>&1; then ok "UserPromptSubmit JSON"; else bad "UserPromptSubmit JSON" "$OUT"; fi +for p in "Bitte priorisiere M004 vor M005." "Fass PR 1336 nicht an, solange der Plan laeuft." "Denk dran: immer erst den Review." "Never touch the release branch." "Don't touch PR 12 while the load test runs." "Hold merges until 12:37 UTC."; do + prompt "$p"; has "flagged: $p" "$OUT" "standing instruction" +done +eq "all seven flagged" 7 "$(lines "$SD/standing-flags")" +eq "eight prompts counted" 8 "$(lines "$SD/prompts")" +prompt "Kein Problem, danke."; eq "German plain prompt: silent" "" "$OUT" +prompt "The pipeline is evergreen and nobody minds."; eq "no match inside a word (evergreen, nobody)" "" "$OUT" + +echo "# stop: block once" +stop +eq "block decision" block "$(printf '%s' "$OUT" | "$JQ" -r '.decision // empty' 2>/dev/null)" +R=$(printf '%s' "$OUT" | "$JQ" -r '.reason // empty' 2>/dev/null) +has "reason counts the prompts" "$R" "7 human prompt(s)" +has "reason lists a prompt" "$R" "Bitte priorisiere M004" +has "reason names the command" "$R" "bin/ytstack-standing\" add" +stop; eq "second stop, same flags: silent" "" "$OUT" +eq "git status of the project stays clean" "" "$(git -C "$P" status --porcelain)" + +echo "# stop: an entry since the prompt counts" +# A flag in the same second as the last stop counts as handled: wait one. +sleep 1; prompt "Always ask before a production deploy." +mkdir -p "$P/.ytstack/standing" +printf -- '---\ngiven: x\nscope: y\nsupersedes:\n---\n\nAsk first.\n' > "$P/.ytstack/standing/$(date -u +%Y%m%dT%H%MZ)-ask-first.md" +stop; eq "entry in the working tree -> no block" "" "$OUT" +rm -rf "$P/.ytstack/standing" + +sleep 1; prompt "Never merge on Fridays." +( cd "$P" || exit 2; git switch -q -c standing/x && mkdir -p .ytstack/standing \ + && printf 'e\n' > ".ytstack/standing/$(date -u +%Y%m%dT%H%MZ)-no-fridays.md" && git add -A && git commit -qm entry && git switch -q main ) >/dev/null 2>&1 +[ ! -d "$P/.ytstack/standing" ] && ok "fixture: entry only on the branch" || bad "fixture: entry only on the branch" +stop; eq "entry on a local branch -> no block" "" "$OUT" + +echo "# stop: guards and the task reminder" +sleep 1; prompt "Never deploy without a watch." +stop '{"stop_hook_active": true}'; eq "stop_hook_active -> silent" "" "$OUT" +printf 'current_milestone: M042\nactive_slice: S03\nactive_task: T07\n' > "$P/.ytstack/STATE.md" +stop +eq "block and task reminder together: block" block "$(printf '%s' "$OUT" | "$JQ" -r '.decision // empty')" +has "block and task reminder together: reminder" "$(printf '%s' "$OUT" | "$JQ" -r '.systemMessage // empty')" "M042-S03-T07" +rm -f "$SD/coordinate" +prompt "Never again."; stop +hasnt "marker gone: no block" "$OUT" '"decision"' + +echo +echo "$PASS passed, $FAIL failed" +[ "$FAIL" -eq 0 ] From 26611817cc478a88ec13e004b2ecdebecf2eb985 Mon Sep 17 00:00:00 2001 From: Alex Wegener Date: Sun, 15 Nov 2026 14:39:52 +0100 Subject: [PATCH 04/25] feat: inject standing entries at session start and into lane briefs (#74) session-start injects the active entries for the session's role (coordinator with the marker, else lane), files only, cut last for the cap; ytstack-brief render adds the entries for lanes or reviewers. Co-Authored-By: Claude Opus 5.5 --- bin/ytstack-brief | 7 ++- hooks/session-start | 43 +++++++++++++++++++ skills/spawn-milestone-team/SKILL.md | 2 +- skills/spawn-milestone-team/brief-template.md | 8 +++- tests/hooks-readonly.test.sh | 26 +++++++++++ tests/ytstack-brief.test.sh | 23 ++++++++++ 6 files changed, 106 insertions(+), 3 deletions(-) diff --git a/bin/ytstack-brief b/bin/ytstack-brief index 65773a48..bb422c2a 100755 --- a/bin/ytstack-brief +++ b/bin/ytstack-brief @@ -300,6 +300,11 @@ EOF B_CONTEXT="$B_CONTEXT$NL- \`$(rel "$YT_DIR/KNOWLEDGE.md")\`" fi + # The standing instructions for this kind of lane (issue #74): the active + # entries whose scope names lanes (a review: reviewers) or no role at all. + x=lane; [ "$lane" != review ] || x=reviewer + B_STANDING=$(yt_standing_lines "$YT_DIR" "$x") + # What the worker may do: the kind's fixed sentences, then its commit rule, # which the Git section repeats. The inserted values are a validated # reference and hex digits, so no character of them is special to the @@ -344,7 +349,7 @@ EOF # shortcut: values travel through the environment, so one value is limited to # what the OS allows per variable (about 128 KB on Linux); upgrade to # temporary files if a plan section ever gets that long. - export B_REF B_PROJECT B_OUTCOME B_KIND B_LENS B_FILES B_CONTEXT B_VERIFICATION B_SPEC_IMPACT B_GATES B_BRANCH B_BASE B_COMMIT_RULE B_CONTRACT + export B_REF B_PROJECT B_OUTCOME B_KIND B_LENS B_FILES B_CONTEXT B_STANDING B_VERIFICATION B_SPEC_IMPACT B_GATES B_BRANCH B_BASE B_COMMIT_RULE B_CONTRACT awk ' function flush() { if (!drop) printf "%s", buf; buf = ""; drop = 0 } /^ - + @@ -58,6 +58,12 @@ Anything outside these files is reported as a blocker, not changed. Other plans, summaries and the history in STATE.md are not needed for this task. +## Standing instructions + +{{STANDING}} + +The human gave these once and for all; they override the defaults of this brief. The full text of each is its file in `.ytstack/standing/`. + ## Verification {{VERIFICATION}} diff --git a/tests/hooks-readonly.test.sh b/tests/hooks-readonly.test.sh index 3bf2f053..7c7b9a12 100644 --- a/tests/hooks-readonly.test.sh +++ b/tests/hooks-readonly.test.sh @@ -120,6 +120,32 @@ lacks "ss-main: long next action -> not dropped" "$CTX" "(omitted: see if [ "${#CTX}" -le 9500 ]; then ok "ss-main: cut injection fits the guard (${#CTX})"; else bad "ss-main: cut injection fits the guard" "${#CTX}"; fi cp "$TMP/state.good" "$MAIN/.ytstack/STATE.md" +# ---- 1e2. session-start: standing entries in force, filtered by role (issue #74) +SDIR="$MAIN/.ytstack/standing"; mkdir -p "$SDIR" +sw() { printf -- '---\ngiven: %s\nscope: %s\nsupersedes: %s\n%b---\n\n%s\n' "$2" "$3" "$4" "$5" "$6" > "$SDIR/$1.md"; } +sw 20261101T1000Z-old 2026-11-01T10:00:00Z "every lane" "" "" "Old rule." +sw 20261101T1100Z-new 2026-11-01T11:00:00Z "every lane" 20261101T1000Z-old "" "Lanes run their own tests. Second sentence." +sw 20261101T1200Z-coord 2026-11-01T12:00:00Z "the coordinator" "" "" "Lanes are tracked in LANES.md at all times." +sw 20261101T1300Z-window 2026-11-01T13:00:00Z "everyone" "" 'until: 2026-11-01T14:00Z\n' "Hold merges until the measurement ends." +sw 20261101T1400Z-all 2026-11-01T14:00:00Z "this project" "" 'check: false\nuntil-check: touch $HOME/RAN\n' "Status only at slice boundaries." +run session-start "{\"session_id\":\"s1st\",\"cwd\":$(jstr "$MAIN"),\"source\":\"compact\"}" HOME="$TMP/h" +CTX=$(printf '%s' "$OUT" | jq -r '.hookSpecificOutput.additionalContext // empty' 2>/dev/null) +has "ss-standing: block names the role (lane without marker)" "$CTX" "Standing instructions in force (role: lane" +has "ss-standing: entry with scope and first sentence" "$CTX" "- 20261101T1100Z-new (every lane): Lanes run their own tests." +lacks "ss-standing: superseded entry skipped" "$CTX" "20261101T1000Z-old" +lacks "ss-standing: expired entry skipped" "$CTX" "20261101T1300Z-window" +lacks "ss-standing: coordinator entry not for a lane" "$CTX" "20261101T1200Z-coord" +has "ss-standing: entry naming no role is for everyone" "$CTX" "20261101T1400Z-all" +[ ! -e "$TMP/h/RAN" ] && ok "ss-standing: no until-check runs in the hook" || bad "ss-standing: no until-check runs in the hook" +mkdir -p "$TMP/xdg/ytstack/sessions/s1co"; printf '%s\n' "$MAIN/.ytstack" > "$TMP/xdg/ytstack/sessions/s1co/coordinate" +run session-start "{\"session_id\":\"s1co\",\"cwd\":$(jstr "$MAIN"),\"source\":\"compact\"}" XDG_STATE_HOME="$TMP/xdg" +CTX=$(printf '%s' "$OUT" | jq -r '.hookSpecificOutput.additionalContext // empty' 2>/dev/null) +has "ss-standing: coordinate marker -> role coordinator" "$CTX" "(role: coordinator" +has "ss-standing: coordinator sees its entry" "$CTX" "20261101T1200Z-coord (the coordinator)" +if [ "${#CTX}" -le 9500 ]; then ok "ss-standing: injection fits the guard (${#CTX})"; else bad "ss-standing: injection fits the guard" "${#CTX}"; fi +eq "ss-standing: git status shows only the fixture entries" "?? .ytstack/standing/" "$(git -C "$MAIN" status --porcelain)" +rm -rf "$SDIR" "$TMP/xdg" + # ---- 1f. session-start: no roadmap in progress -> clean count, no stderr noise run session-start "{\"session_id\":\"s1j\",\"cwd\":$(jstr "$MAIN")}" eq "ss-main: no in-progress roadmap -> no 'integer expression' error on stderr" 0 "$(grep -c 'integer expression' "$ERR")" diff --git a/tests/ytstack-brief.test.sh b/tests/ytstack-brief.test.sh index 9fbda42e..d994b24f 100644 --- a/tests/ytstack-brief.test.sh +++ b/tests/ytstack-brief.test.sh @@ -264,6 +264,29 @@ has "prepare with --branch: the checkout stays" "git checkout -B work main" "$G" has "prepare with --branch: the commit sentence is replaced" "Commit nothing. Do not merge or push." "$G" hasnt "prepare: no commit prefix anywhere" "Commit each task" "$OUT" +# ---- 3b. standing instructions in the brief (issue #74) ------------------------ +echo "# render: standing instructions" +SDIR="$R/.ytstack/standing"; mkdir -p "$SDIR" +printf -- '---\ngiven: 2026-11-01T10:00:00Z\nscope: every lane\nsupersedes:\n---\n\nRun the full suite before the report.\n' > "$SDIR/20261101T1000Z-full-suite.md" +printf -- '---\ngiven: 2026-11-01T11:00:00Z\nscope: the coordinator\nsupersedes:\n---\n\nTrack lanes in LANES.md.\n' > "$SDIR/20261101T1100Z-lanes.md" +printf -- '---\ngiven: 2026-11-01T12:00:00Z\nscope: every reviewer\nsupersedes:\n---\n\nName the reviewed commit.\n' > "$SDIR/20261101T1200Z-commit.md" +printf -- '---\ngiven: 2026-11-01T13:00:00Z\nscope: this project\nsupersedes:\n---\n\nEnglish in code and commits.\n' > "$SDIR/20261101T1300Z-english.md" +run "$R" render --task M001-S01-T01 +eq "with entries: a Standing instructions section after Read for context" "Outcome,Kind,Scope,Read for context,Standing instructions,Verification,Spec impact,Work contract,Report," \ + "$(printf '%s\n' "$OUT" | sed -n 's/^## //p' | tr '\n' ',')" +SI=$(part "Standing instructions") +has "implement: the lane entry" "- 20261101T1000Z-full-suite (every lane): Run the full suite before the report." "$SI" +has "implement: the entry naming no role" "20261101T1300Z-english (this project)" "$SI" +hasnt "implement: no coordinator entry" "20261101T1100Z-lanes" "$SI" +hasnt "implement: no reviewer entry" "20261101T1200Z-commit" "$SI" +run "$R" render --task M001-S01-T01 --kind review --head abc1234 +SI=$(part "Standing instructions") +has "review: the reviewer entry" "20261101T1200Z-commit (every reviewer)" "$SI" +hasnt "review: no lane entry" "20261101T1000Z-full-suite" "$SI" +rm -rf "$SDIR" +run "$R" render --task M001-S01-T01 +hasnt "no entries: no section" "## Standing instructions" "$OUT" + # ---- 4. render --lens --------------------------------------------------------- echo "# render --lens" # A policy with a visual lens, a lens without evidence that names a skill, and From 75bbab03e8bd0a94f56339bda34a1a7a2624ca7e Mon Sep 17 00:00:00 2001 From: Alex Wegener Date: Sun, 15 Nov 2026 14:39:52 +0100 Subject: [PATCH 05/25] feat: coordinate records standing entries with ytstack-standing and lists them (#72, #73, #74) The preamble writes the coordinate session marker and prints ytstack-standing list; Step 9 uses ytstack-standing add and says agent memory is no substitute; Step 3 acts on ended entries, conditions and failed checks. Co-Authored-By: Claude Opus 5.5 --- skills/coordinate/SKILL.md | 30 +++++++++++++++++++++++------- tests/skill-preambles.test.sh | 18 +++++++++++++----- 2 files changed, 36 insertions(+), 12 deletions(-) diff --git a/skills/coordinate/SKILL.md b/skills/coordinate/SKILL.md index 757c29f5..5f7bb7f0 100644 --- a/skills/coordinate/SKILL.md +++ b/skills/coordinate/SKILL.md @@ -3,7 +3,7 @@ name: coordinate description: "Coordinator mode for the session that owns a plan and delegates all of it, writing no product code itself. Use when many lanes are in flight, when a plan has dozens of work packages, when a session with open lanes continues after a compaction or a resume, or when the user says coordinate this, run the plan, you are the coordinator, keep the lanes moving, where does each lane stand. Not for one milestone with a handful of independent slices (spawn-milestone-team) and not for doing a task yourself (plan-task)." metadata: tier: task - version: 0.5.0 + version: 0.6.0 allowed-tools: - Bash - Read @@ -41,7 +41,7 @@ You MUST create a TodoWrite task for each of these items. Items 4 to 13 are one 6. **Finish reported lanes** -- `ytstack:finish-lane`, one lane at a time per pull request 7. **Run the factory tools** -- the route before every merge (also your own), the PR watch or `ytstack-watch`, `ytstack-watch release` after every merge to production, signals, review lessons, the lesson of every incident (a red `main`, a slip); each skipped only by its condition 8. **Queue and ask questions** -- look up, write the file, ask one, late -9. **Record standing instructions** -- one file per instruction in `standing/` when they are given +9. **Record standing instructions** -- `ytstack-standing add` when they are given, before the next dispatch; never only in agent memory 10. **Stop loops that do not converge** -- a diagnosis to the human instead of another dispatch 11. **Report status** -- only on a change the human acts on, or at a boundary he set 12. **Rotate** -- after one compaction or with a large context, in one step while lanes run: files current, handoff with the PR watch session, the watches and the workers' addresses, fresh session; this one stays open only as a relay @@ -137,10 +137,24 @@ echo "LESSONS_BEGIN" [ -z "$_LS" ] || printf '%s\n' "$_LS" | head -30 echo "LESSONS_END" echo "STANDING: $([ -n "$_YT_DIR" ] && [ -f "$_YT_DIR/STANDING.md" ] && echo yes || echo no)" -# One file per standing instruction (.ytstack/standing/): the ones in force, newest first. +# Coordinate mode (issue #72): the session marker hooks/standing-prompt and hooks/stop act on. +_SID="${CLAUDE_CODE_SESSION_ID:-}" +case "$_SID" in + ''|*[!A-Za-z0-9._-]*) echo "COORDINATE_MARKER: none (no session id on this host: the standing hooks stay off)" ;; + *) if [ -n "$_YT_DIR" ] && command -v yt_session_home >/dev/null 2>&1 && mkdir -p "$(yt_session_home)/$_SID" 2>/dev/null \ + && printf '%s\n' "$_YT_DIR" > "$(yt_session_home)/$_SID/coordinate" 2>/dev/null; then + echo "COORDINATE_MARKER: written" + else + echo "COORDINATE_MARKER: not written (the standing hooks stay off)" + fi ;; +esac +# One file per standing instruction (.ytstack/standing/): the newest entry's age and the +# human prompts since, the active ones, then ended, conditions to check and failed checks. echo "STANDING_ENTRIES_BEGIN" -if [ -n "$_YT_DIR" ] && [ -d "$_YT_DIR/standing" ]; then - command -v yt_standing >/dev/null 2>&1 && yt_standing "$_YT_DIR" || echo "list $_YT_DIR/standing/ yourself: newest first, skip superseded" +if [ -n "$_YT_DIR" ] && [ -f "$_BIN/ytstack-standing" ]; then + bash "$_BIN/ytstack-standing" -C "$_PROJECT_DIR" list 2>&1 | head -80 +elif [ -n "$_YT_DIR" ] && [ -d "$_YT_DIR/standing" ]; then + command -v yt_standing >/dev/null 2>&1 && yt_standing "$_YT_DIR" || echo "list $_YT_DIR/standing/ yourself: newest first, skip superseded and ended" else echo "no standing directory" fi @@ -193,7 +207,7 @@ The scripts live in `${CLAUDE_SKILL_DIR}/../../bin/`; the commands below are wri **Step 2 -- HARD-GATE.** `HAS_YTSTACK: no`: stop, "run `ytstack:init-project` or `ytstack:adopt-brownfield` first". `SLICE_PLANS: 0` and `no lanes`: stop, "nothing to coordinate; run `ytstack:slice-milestone`". One milestone with a handful of independent slices and no lane yet: `ytstack:spawn-milestone-team` does that with less ceremony; say so and stop unless the user asked for coordinator mode. -**Step 3 -- Start from files.** At the first start, after every compaction and after every resume, before anything else: read the standing instructions in full (every file listed between `STANDING_ENTRIES_BEGIN` and `STANDING_ENTRIES_END`, newest first, and `STANDING.md` when `STANDING: yes`; an entry that another entry supersedes is not listed and no longer holds), the rows between `LANES_BEGIN` and `LANES_END`, the frontier, every file listed between `QUESTIONS_BEGIN` and `QUESTIONS_END`, and the newer of the two handoffs. Do not rebuild who holds what from a conversation summary. Where a summary and a file disagree, the file is the claim, and Step 4 checks it against the host before anybody acts on it. A `running` row whose worker no longer exists in this session is not dispatched again blindly: read its branch (`git log ..`), then `ytstack-frontier release ` and claim it for a new worker that continues on that branch, or write a question. +**Step 3 -- Start from files.** At the first start, after every compaction and after every resume, before anything else: read the standing instructions in full (every entry listed as active between `STANDING_ENTRIES_BEGIN` and `STANDING_ENTRIES_END`, newest first, its file in `standing/`, and `STANDING.md` when `STANDING: yes`; an entry that another entry supersedes, or that ended, is not listed as active and no longer holds). Then act on the rest of that block: an entry under `ended` gets its closing entry now (`ytstack-standing end --reason ""`), an entry under `condition to check now` is checked against the host now and closed the same way when it is met, a line under `check failed` is an instruction you are not keeping: fix that first. Its first line counts the human prompts since the newest entry: more than a few after a compaction means instructions may be missing, so read the conversation summary for instructions and record them (Step 9) before you dispatch. Then the rows between `LANES_BEGIN` and `LANES_END`, the frontier, every file listed between `QUESTIONS_BEGIN` and `QUESTIONS_END`, and the newer of the two handoffs. Do not rebuild who holds what from a conversation summary. Where a summary and a file disagree, the file is the claim, and Step 4 checks it against the host before anybody acts on it. A `running` row whose worker no longer exists in this session is not dispatched again blindly: read its branch (`git log ..`), then `ytstack-frontier release ` and claim it for a new worker that continues on that branch, or write a question. When the newer handoff carries a "Rotation" block (Step 12 of the session before, `docs/ux/coordinator-format.md`), this session is its successor. Before Step 4: `ytstack-pr-watch handover --from ` (skip with `PR watch session: none`; check that the output names the moved pull requests), start the background watches it lists again, and leave the rows of its running workers alone: those workers report to the old session, which stays open as a relay and appends each report under "Reports after the rotation" in `HANDOFF.md` and sets the row to `reported`. Read the handoff again when such a row turns `reported`, and send a worker a message at its address only where the host lets this session reach it. Only when the person says the old session is closed before a worker reported does the rule above for a lost worker apply. @@ -254,7 +268,9 @@ A lane named in the `blocks:` of an open or asked question is not ready, whateve An `asked` question is never asked again: name it as waiting since its time. When the human answers, write what he said under `## Answer`, run `ytstack-questions answer `, and add a `DECISIONS.md` entry when it decides something that lasts. Never record an answer the human did not give, and never take a verdict a plan reserves for a person. At a slice boundary the open gates go out together through `ytstack:reassess-roadmap` (its Step 3b). A step only the human may perform (a secret, a production switch, a merge he reserved) goes through `ytstack:handover-step` as one staged script. `YTSTACK_NON_INTERACTIVE: true`: ask nothing; the files stay `open` and are listed in the status under "Waiting on a person". -**Step 9 -- Record standing instructions.** When the human gives an instruction that holds beyond the task at hand (when to report, what never to merge, what not to touch), write it down at once, before the next dispatch, as a new file `$_YT_DIR/standing/-.md` (`YT_DIR` from the preamble: `.ytstack/` in the repository, or `~/.ytstack/projects//` in user scope; UTC now): frontmatter `given` (the same time, ISO), `scope` (where it applies) and `supersedes` (empty), and the instruction in your own words as its body (`docs/ux/coordinator-format.md`). Never a quotation. An instruction that replaces an older one is a new file whose `supersedes` names the older file without `.md`; the older file is not edited and nothing is deleted. Then run `ytstack-check --standing` and fix what it prints. One file per instruction keeps two pull requests that each add one from touching the same line. `STANDING.md` is not edited per entry; only a project that has `STANDING.md` and no `standing/` directory yet keeps its form: append `- -- . Scope: ` and strike a replaced line (`~~...~~ Superseded : ...`). +**Step 9 -- Record standing instructions.** When the human gives an instruction that holds beyond the task at hand (when to report, what never to merge, what not to touch, a priority, an approval that covers later cases), record it at once, before the next dispatch, with one command: `ytstack-standing add "" --scope ""` (the script is `bin/ytstack-standing` of the plugin, beside `ytstack-frontier`). Add `--supersedes ` when it replaces an older entry, `--until ` when it ends at a time, `--until-condition ""` when it ends with an event, `--until-check ""` when that event can be checked by a command that exits 0 once it happened, and `--check ""` when keeping it can be checked (a command that fails while the instruction is not kept, such as a `LANES.md` older than the last lane change). Name the role in the scope when it applies to one (`the coordinator`, `every lane`, `every reviewer`; `docs/ux/coordinator-format.md`, "Scope and roles"): the SessionStart injection and the lane briefs filter by it. The command writes the entry in a worktree of its own outside the checkout, commits it and opens or updates the one standing pull request of the UTC day; `--here` writes into the resolved `.ytstack/standing/` only, for user scope (always) or a project where you may write in the checkout. It runs `ytstack-check --standing` itself. When `hooks/standing-prompt` says a prompt reads like a standing instruction, decide: record it, or go on when it is not one. The Stop hook blocks once when such prompts got no entry. An instruction that ended is closed with `ytstack-standing end --reason ""`; nothing is edited or deleted. + +Agent-private memory (a memory file, a note in your own context) is no substitute: a successor session, another host and the human read only the repository. An instruction that lives only in your memory is lost at the next rotation. Never a quotation; the body is the instruction in your own words. One file per instruction keeps two pull requests that each add one from touching the same line. `STANDING.md` is not edited per entry; only a project that has `STANDING.md` and no `standing/` directory yet keeps its form: append `- -- . Scope: ` and strike a replaced line (`~~...~~ Superseded : ...`). **Step 10 -- Stop loops that do not converge.** A lane gets the rounds `ytstack:code-review` allows ("Bounded review": round 1 complete, round 2 the fix, no third). A lane that failed verification twice, or that would need a third review, is not dispatched again: `ytstack-frontier set --status blocked --next "Q### with the human"`, and a question file with the diagnosis (the plan never decided the point, two rules conflict, or each fix moved the problem). diff --git a/tests/skill-preambles.test.sh b/tests/skill-preambles.test.sh index ee003745..816283f0 100644 --- a/tests/skill-preambles.test.sh +++ b/tests/skill-preambles.test.sh @@ -106,7 +106,7 @@ upstream_checks() { PD="$TMP/plugin-data" run_pre() { # run_pre