From 7917b646bcd82a05cd3418dee1356f04ba1615f4 Mon Sep 17 00:00:00 2001 From: Alex Wegener Date: Sun, 15 Nov 2026 19:53:29 +0100 Subject: [PATCH 01/13] feat: parked lane status; the open-PR cap counts PRs ready for review (#83) ytstack-frontier set --status parked holds a lane whose pull request waits open, for a cap or a person; upkeep lists it as held and ytstack-status counts it in review. The open-prs gate of ytstack-finish-lane counts open pull requests that are not drafts and fails when more than 100 are open. Co-Authored-By: Claude Opus 5.5 --- bin/ytstack-finish-lane | 22 ++++++++++++++++------ bin/ytstack-frontier | 3 ++- bin/ytstack-status | 6 +++--- bin/ytstack-upkeep | 4 ++-- tests/ytstack-finish-lane.test.sh | 15 ++++++++++----- tests/ytstack-frontier.test.sh | 4 ++-- tests/ytstack-status.test.sh | 2 +- 7 files changed, 36 insertions(+), 20 deletions(-) diff --git a/bin/ytstack-finish-lane b/bin/ytstack-finish-lane index 84f53ee..63205fc 100755 --- a/bin/ytstack-finish-lane +++ b/bin/ytstack-finish-lane @@ -59,6 +59,7 @@ # threads no unresolved review thread # mergeable open and without a conflict # open-prs with --max-open: at most N open pull requests +# ready for review (drafts do not count) # merge runs gates for --at SHA, merges only when all hold, pinned to # that commit on the host's side, and reads the state back. No # auto-merge, no administrator override. It does not read the @@ -367,8 +368,10 @@ VIEW_JQ=' # shortcut: the first 100 review threads; more than that fails the gate instead # of being paged through. # shellcheck disable=SC2016 -THREADS_QUERY='query($owner: String!, $repo: String!, $number: Int!) { repository(owner: $owner, name: $repo) { pullRequests(states: OPEN) { totalCount } pullRequest(number: $number) { reviewThreads(first: 100) { totalCount pageInfo { hasNextPage } nodes { isResolved } } } } }' -THREADS_JQ='.data.repository | "open\t\(.pullRequests.totalCount)", +# open: the open pull requests that are ready for review (drafts do not count +# toward a cap, issue #83), all open ones, and whether more than 100 are open. +THREADS_QUERY='query($owner: String!, $repo: String!, $number: Int!) { repository(owner: $owner, name: $repo) { pullRequests(states: OPEN, first: 100) { totalCount nodes { isDraft } } pullRequest(number: $number) { reviewThreads(first: 100) { totalCount pageInfo { hasNextPage } nodes { isResolved } } } } }' +THREADS_JQ='.data.repository | "open\t\([.pullRequests.nodes[]? | select(.isDraft | not)] | length)\t\(.pullRequests.totalCount)\t\(.pullRequests.totalCount > 100)", (.pullRequest.reviewThreads | "threads\t\([ .nodes[] | select(.isResolved | not) ] | length)\t\(.totalCount)\t\(.pageInfo.hasNextPage)")' gate() { # @@ -403,7 +406,7 @@ gate_args() { # read_gates: one read of the host, one line per gate, the time of the read. # Returns 0 when every gate holds; sets HOST_HEAD. read_gates() { - local v g t short checks n open state m reviews newest unresolved total more count + local v g t short checks n open state m reviews newest unresolved total more count drafts v=$(gh pr view "$PR" --json state,headRefOid,mergeable,statusCheckRollup,reviews --jq "$VIEW_JQ") \ && g=$(gh api graphql -f query="$THREADS_QUERY" -F owner='{owner}' -F repo='{repo}' -F number="$PR" --jq "$THREADS_JQ") # shellcheck disable=SC2181 @@ -455,9 +458,16 @@ EOF fi if [ -n "$MAX_OPEN" ]; then - count=$(rows "$g" open) - if is_int "$count" && [ "$count" -le "$MAX_OPEN" ]; then gate ok open-prs "$count open, limit $MAX_OPEN" - else gate FAIL open-prs "${count:-unknown} open, limit $MAX_OPEN" + IFS=$'\t' read -r count total more < 2 { split($0, c, "|"); for (i = 2; i <= 6; i++) gsub(/^[ \t]+|[ \t]+$/, "", c[i]) - if (c[4] ~ /^(claimed|running|reported|in-review|ready)$/ && c[6] != "-" && c[6] != "") print c[6] tab c[2] " (" c[4] ")" + if (c[4] ~ /^(claimed|running|reported|in-review|ready|parked)$/ && c[6] != "-" && c[6] != "") print c[6] tab c[2] " (" c[4] ")" }' "$lanes") # info : INFO, and ok=yes when the branch may go: its # pull request is merged or closed, none is open, no lane holds it, and its @@ -314,7 +314,7 @@ $(awk -v tab="$TAB" ' /^\|/ && ++n > 2 { split($0, c, "|") for (i = 2; i <= 11; i++) { gsub(/^[ \t]+|[ \t]+$/, "", c[i]); if (c[i] == "") c[i] = "-" } - if (c[4] ~ /^(claimed|running|reported|in-review|ready)$/) print c[2] tab c[4] tab c[5] tab c[11] + if (c[4] ~ /^(claimed|running|reported|in-review|ready|parked)$/) print c[2] tab c[4] tab c[5] tab c[11] }' "$YT_DIR/LANES.md") EOF # A stale lane (issue #84) is listed once: not again when it is listed above. diff --git a/tests/ytstack-finish-lane.test.sh b/tests/ytstack-finish-lane.test.sh index 7601c4f..8423825 100644 --- a/tests/ytstack-finish-lane.test.sh +++ b/tests/ytstack-finish-lane.test.sh @@ -300,7 +300,8 @@ has "it says so" "not in this checkout" "$OUT" # ---- 7. gates ----------------------------------------------------------------- echo "# gates" G="$P"; SHA="$TIP" -# host: a pull request at $SHA whose gates all hold, 3 open pull requests, one resolved thread +# host: a pull request at $SHA whose gates all hold, 3 open pull requests ready +# for review and one draft (issue #83: the cap counts the ready ones), one resolved thread host() { jq -n --arg h "$SHA" '{state: "OPEN", headRefOid: $h, mergeable: "MERGEABLE", statusCheckRollup: [ @@ -310,7 +311,7 @@ host() { reviews: [ {author: {login: "rev"}, state: "COMMENTED", submittedAt: "2026-11-13T10:00:00Z", commit: {oid: $h}, body: "Verdict: approved\r\nReviewed commit: \($h)"} ]}' > "$GH_FIX/view.json" - jq -n '{data: {repository: {pullRequests: {totalCount: 3}, + jq -n '{data: {repository: {pullRequests: {totalCount: 4, nodes: [{isDraft: false}, {isDraft: true}, {isDraft: false}, {isDraft: false}]}, pullRequest: {reviewThreads: {totalCount: 1, pageInfo: {hasNextPage: false}, nodes: [{isResolved: true}]}}}}}' > "$GH_FIX/graphql.json" rm -f "$GH_FIX"/*.fail "$GH_FIX/merge.queue" "$GH_FIX/log" } @@ -334,7 +335,8 @@ has "the checks line counts them and names the commit" "ok checks: 3 concluded has "the threads were read for this pull request" "-F number=7" "$(calls)" host; run "$G" gates --pr 7 --reviewed-head "${SHA:0:7}" --max-open 3 eq "a short commit id and a limit that is just met: exit 0" 0 "$EC" -has "the limit has its own line" "ok open-prs: 3 open, limit 3" "$OUT" +has "the limit has its own line, drafts not counted" "ok open-prs: 3 open for review, limit 3 (1 draft not counted)" "$OUT" +has "the query reads the drafts" "isDraft" "$(calls)" host; tweak view '.headRefOid = "ffffffffffffffffffffffffffffffffffffffff"'; gates only "the head moved after the review" head @@ -375,7 +377,10 @@ host; tweak view '.state = "CLOSED"'; gates only "a closed pull request" mergeable host; gates --max-open 2 only "too many open pull requests" open-prs -has "count and limit are printed" "3 open, limit 2" "$OUT" +has "count and limit are printed" "3 open for review, limit 2" "$OUT" +host; tweak graphql '.data.repository.pullRequests |= (.totalCount = 140)'; gates --max-open 5 +only "more open pull requests than were read" open-prs +has "says so" "140 open, only the first 100 were read" "$OUT" host; gates --verdict-pattern '^Verdict: approved$' eq "the newest review matches the verdict pattern: exit 0" 0 "$EC" @@ -399,7 +404,7 @@ has "after the gate lines" "ok head: ${SHA:0:7} is the reviewed commit" "$OUT" host; run "$G" merge --pr 7 --at "$SHA" --method rebase --max-open 5 --verdict-pattern 'approved' eq "method and gate options pass through" 0 "$EC" has "the method reaches gh" "pr merge 7 --rebase --match-head-commit $SHA" "$(calls)" -has "the limit was checked" "ok open-prs: 3 open, limit 5" "$OUT" +has "the limit was checked" "ok open-prs: 3 open for review, limit 5" "$OUT" host; tweak view '.headRefOid = "ffffffffffffffffffffffffffffffffffffffff"'; run "$G" merge --pr 7 --at "$SHA" eq "the head moved after the review: merge refuses" 1 "$EC" has "the gate is named" "FAIL head:" "$OUT" diff --git a/tests/ytstack-frontier.test.sh b/tests/ytstack-frontier.test.sh index 2389129..a893a62 100644 --- a/tests/ytstack-frontier.test.sh +++ b/tests/ytstack-frontier.test.sh @@ -261,7 +261,7 @@ run "$R" claim review-pr-12 --by rev-1 --kind review eq "a lane outside the milestone plan can be claimed" 0 "$EC" has "with its kind" "| review-pr-12 | review | claimed | rev-1 " "$(rowof "$R" review-pr-12)" -for S in running reported in-review ready; do +for S in running reported in-review ready parked; do run "$R" set M004-S02 --status "$S" run "$R" claim M004-S02 --by second-worker eq "status $S holds the lane" 1 "$EC" @@ -322,7 +322,7 @@ run "$R" set M004-S02 --next "wait for the review" eq "one option changes one cell" "| M004-S02 | implement | reported | impl-M004-S02 2026-11-13T10:02Z | work/s02 | wt/s02 | 12 | d4e5f6a | 1 | wait for the review |" "$(rowof "$R" M004-S02)" run "$R" set M004-S02 --pr "" has "an empty value clears the cell" "| wt/s02 | - | d4e5f6a |" "$(rowof "$R" M004-S02)" -for S in claimed running reported in-review ready merged blocked dropped; do +for S in claimed running reported in-review ready parked merged blocked dropped; do run "$R" set M004-S02 --status "$S" eq "--status $S is accepted" "0 $S" "$EC $(rowof "$R" M004-S02 | awk -F' [|] ' '{ print $3 }')" done diff --git a/tests/ytstack-status.test.sh b/tests/ytstack-status.test.sh index fe87b7c..4cc8ff5 100644 --- a/tests/ytstack-status.test.sh +++ b/tests/ytstack-status.test.sh @@ -194,7 +194,7 @@ road "$P" M003 done "x S01" "- S02" road "$P" M004 active "x S01" "- S02" "- S03" "- S04" road "$P" M005 dropped "- S01" road "$P" M007 backlog "- S01" "- S02" -printf -- '---\nupdated: 2026-11-15T10:00:00Z\n---\n\n# Lanes\n\n| Lane | Kind | Status | Claimed by | Branch | Worktree | PR | Reviewed head | Round | Next action |\n|---|---|---|---|---|---|---|---|---|---|\n| M004-S02 | implement | merged | w 2026-11-15T08:00Z | - | - | 3 | abc1234 | 1 | - |\n| M004-S03 | implement | in-review | w 2026-11-15T09:00Z | - | - | 4 | - | 1 | - |\n' > "$P/.ytstack/LANES.md" +printf -- '---\nupdated: 2026-11-15T10:00:00Z\n---\n\n# Lanes\n\n| Lane | Kind | Status | Claimed by | Branch | Worktree | PR | Reviewed head | Round | Next action |\n|---|---|---|---|---|---|---|---|---|---|\n| M004-S02 | implement | merged | w 2026-11-15T08:00Z | - | - | 3 | abc1234 | 1 | - |\n| M004-S03 | implement | parked | w 2026-11-15T09:00Z | - | - | 4 | - | 1 | - |\n' > "$P/.ytstack/LANES.md" ph "$P" eq "--phases: exit 0" 0 "$EC" eq "one line per phase, dropped and backlog left out, done counts all, the total, the read line" \ From 1a0b3cc47f09edd2c6487672a82739c4e8e9524b Mon Sep 17 00:00:00 2001 From: Alex Wegener Date: Sun, 15 Nov 2026 19:53:40 +0100 Subject: [PATCH 02/13] feat: hooks read a stale checkout from origin and keep a coordinator on its path (#82, #83) #82: on the default branch behind origin/ (local refs, no fetch) SessionStart and Stop read the pointer and Next action from origin's STATE.md and say how far behind the checkout is (yt_behind_origin). The Stop task reminder is said once per session and pointer, never in a coordinate session, and a pointer older than YT_POINTER_STALE_DAYS (3) days is STATE lint W10 instead. The Next action is no longer cut for the 10,000-char cap: the using-ytstack body yields last, with a pointer to its file. A manual handoff older than the automatic one is listed as older. #83, coordinate mode only, hints never denies: pre-tool-use-agent (now also on Bash) on an Agent dispatch without isolation, on gh pr merge and on gh pr close; pre-compact counts compactions beside the marker, SessionStart says "Compaction N of this coordinator: ... rotate now", Stop repeats it once per compaction from the second; post-tool-use-bash notes ytstack:lesson when gh run list --branch shows a failed run. Co-Authored-By: Claude Opus 5.5 --- hooks/hooks.json | 4 +- hooks/lib/git-ctx.sh | 29 +++++ hooks/post-tool-use-bash | 31 +++++ hooks/pre-compact | 11 +- hooks/pre-tool-use-agent | 59 ++++++--- hooks/session-start | 225 +++++++++++++++++---------------- hooks/stop | 62 ++++++++- tests/git-ctx.test.sh | 24 ++++ tests/hooks-coordinate.test.sh | 57 ++++++++- tests/hooks-json.test.sh | 2 +- tests/hooks-readonly.test.sh | 36 +++++- tests/hooks-standing.test.sh | 7 +- tests/hooks-stop.test.sh | 56 ++++++-- 13 files changed, 449 insertions(+), 154 deletions(-) diff --git a/hooks/hooks.json b/hooks/hooks.json index 7296607..f4863b0 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/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/pre-tool-use-agent (PreToolUse on Agent, Task, SendMessage) warns in the same mode when a dispatch carries no rendered brief, and hooks/stop warns when LANES.md lags the dispatches and reports or the STATE pointer is behind, blocking once after three sessions in a row. 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/pre-tool-use-agent (PreToolUse on Agent, Task, SendMessage, Bash) warns in the same mode when a dispatch carries no rendered brief or no isolation and when a command runs gh pr merge or gh pr close by hand, and hooks/stop warns when LANES.md lags the dispatches and reports or the STATE pointer is behind, blocking once after three sessions in a row. 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": [ { @@ -154,7 +154,7 @@ ] }, { - "matcher": "Agent|Task|SendMessage", + "matcher": "Agent|Task|SendMessage|Bash", "hooks": [ { "type": "command", diff --git a/hooks/lib/git-ctx.sh b/hooks/lib/git-ctx.sh index 098030f..71359f0 100644 --- a/hooks/lib/git-ctx.sh +++ b/hooks/lib/git-ctx.sh @@ -456,6 +456,8 @@ EOF # W7 malformed `progress` block (one finding per problem) # W8 STATE.md larger than YT_STATE_MAX_BYTES (it is a pointer, not a ledger) # W9 earlier status paragraphs beside the current one (history) +# W10 an active task with last_updated older than YT_POINTER_STALE_DAYS +# (default 3) days: hooks/stop leaves such a pointer to this line # W8 and W9 are prompts for ytstack:reconcile; no skill stops on them. YT_STATE_MAX_BYTES=12000 yt_state_lint() { @@ -505,6 +507,14 @@ yt_state_lint() { _yt_warn "last_updated $lu is older than the newest commit touching .ytstack ($(git -C "$ytd" log -1 --format=%cI -- . 2>/dev/null))" fi fi + # W10 (issue #82): a task pointer that has not moved for days + local days="${YT_POINTER_STALE_DAYS:-3}" + case "$days" in ''|*[!0-9]*) days=3 ;; esac + case "$t" in T[0-9][0-9]) + if [ -n "$lu_epoch" ] && [ $(( $(date +%s) - lu_epoch )) -gt $((days * 86400)) ]; then + _yt_warn "active task $m-$s-$t unchanged since last_updated $lu (more than $days days): close it (summarize-task), hand it off, or set active_task none" + fi ;; + esac # W6: current milestone done but a slice still active if [ "$m" != none ] && [ -f "$ytd/$m-ROADMAP.md" ] && [ "$s" != none ]; then if [ "$(sed -n 's/^status: *//p' "$ytd/$m-ROADMAP.md" | head -1)" = done ]; then @@ -698,6 +708,25 @@ yt_standing_default_ref() { return 0 } +# yt_behind_origin [yt_dir] (issue #82): is the checkout on the +# default branch and behind origin's copy of it? Local refs only, no fetch. +# Sets YT_BEHIND_N (0 when not on the default branch, without an origin ref, +# or not behind), YT_BEHIND_REF (origin/) and, for a inside +# the checkout, YT_BEHIND_STATE: STATE.md as that ref has it ("" without one). +yt_behind_origin() { + local top="$1" ytd="${2:-}" r cur n + YT_BEHIND_N=0; YT_BEHIND_REF=""; YT_BEHIND_STATE="" + r=$(yt_standing_default_ref "$top") + case "$r" in refs/remotes/origin/*) ;; *) return 0 ;; esac + cur=$(git -C "$top" symbolic-ref -q --short HEAD 2>/dev/null) + [ -n "$cur" ] && [ "$cur" = "${r#refs/remotes/origin/}" ] || return 0 + n=$(git -C "$top" rev-list --count "HEAD..$r" 2>/dev/null) + case "$n" in ''|0|*[!0-9]*) return 0 ;; esac + YT_BEHIND_N=$n; YT_BEHIND_REF="origin/$cur" + case "$ytd" in "$top"/*) YT_BEHIND_STATE=$(git -C "$top" show "$r:${ytd#"$top"/}/STATE.md" 2>/dev/null) ;; esac + return 0 +} + # yt_standing_pending -> " TAB " per entry that is # pending: on a local branch standing/* or the upstream it tracks (written by # this machine's ytstack-standing add), not in the working tree and not on the diff --git a/hooks/post-tool-use-bash b/hooks/post-tool-use-bash index 2e2fea2..7bfa973 100644 --- a/hooks/post-tool-use-bash +++ b/hooks/post-tool-use-bash @@ -30,6 +30,37 @@ trap '' PIPE yt_read_stdin +# Coordinate mode (issue #83, the marker of the coordinate preamble): a +# `gh run list --branch ` whose output shows a failed run is a red +# main; one note per distinct set of failed lines: run ytstack:lesson. Lines +# read: the tab-separated output (status, conclusion, ...), JSON +# "conclusion": "failure", and the terminal form starting with X. +red_main() { + local sid="${YT_SESSION_ID:-}" sd br def out bad key jq_bin cmd + local re_list='(^|[;&|()[:space:]])gh[[:space:]]+run[[:space:]]+list([[:space:]]|$)' + local re_br='(--branch[=[:space:]]|-b[[:space:]]+)([A-Za-z0-9._/-]+)' + case "$sid" in ''|.|..|*[!A-Za-z0-9._-]*) return 0 ;; esac + sd="$(yt_session_home)/$sid" + [ -f "$sd/coordinate" ] || return 0 + cmd=$(printf '%s' "$YT_TOOL_CMD" | tr -d "\"'") + [[ "$cmd" =~ $re_list ]] || return 0 + [[ "$cmd" =~ $re_br ]] || return 0 + br="${BASH_REMATCH[2]}" + yt_git_ctx "${YT_CWD:-$PWD}" + def=$(yt_standing_default_ref "$YT_TOPLEVEL"); def="${def#refs/remotes/origin/}"; def="${def#refs/heads/}" + [ -n "$def" ] && [ "$br" = "$def" ] || return 0 + jq_bin=$(yt_jq); [ -n "$jq_bin" ] || return 0 + out=$(printf '%s' "$YT_STDIN" | "$jq_bin" -r '(.tool_response | objects | .stdout) // "" | tostring' 2>/dev/null) + bad=$(printf '%s\n' "$out" | grep -E '^completed (failure|timed_out|startup_failure) |"conclusion": *"(failure|timed_out|startup_failure)"|^X ' 2>/dev/null) + [ -n "$bad" ] || return 0 + key=$(printf '%s' "$bad" | cksum | tr -d ' ') + grep -qxF -- "$key" "$sd/red-main-said" 2>/dev/null && return 0 + printf '%s\n' "$key" >> "$sd/red-main-said" 2>/dev/null || return 0 + printf '%s' "ytstack: gh run list shows a failed run on $def, the default branch. A red main blocks every lane that merges after it: invoke ytstack:lesson before the next dispatch (area ci, the check, the commit, the lane that merged it) and dispatch the repair as a lane (ytstack:coordinate Step 7, \"A red main\")." \ + | "$jq_bin" -Rs '{hookSpecificOutput: {hookEventName: "PostToolUse", additionalContext: .}}' 2>/dev/null +} +red_main + # Only successful calls (exit code absent or 0). case "${YT_TOOL_EXIT:-0}" in 0|"") ;; *) exit 0 ;; esac diff --git a/hooks/pre-compact b/hooks/pre-compact index ee2afee..710867d 100644 --- a/hooks/pre-compact +++ b/hooks/pre-compact @@ -1,7 +1,8 @@ #!/usr/bin/env bash # ytstack PreCompact hook # -# Fires before the host (Claude Code, or Codex via bin/ytstack-codex) compacts the conversation. Two jobs: +# Fires before the host (Claude Code, or Codex via bin/ytstack-codex) compacts the conversation. Two jobs +# (and in a coordinate session a third: count the compaction beside the marker): # # 1. Write an automatic handoff breadcrumb OUT OF TREE, per session and per # worktree, and refresh the worktree's `latest-handoff` symlink. @@ -100,6 +101,14 @@ else echo "[ytstack pre-compact] could not write $AUTO" >&2 fi +# A coordinate session (the marker the coordinate preamble writes) counts its +# compactions beside the marker: hooks/session-start and hooks/stop say to +# rotate from them (issue #83, coordinate Step 12). +case "${YT_SESSION_ID:-}" in ''|.|..|*[!A-Za-z0-9._-]*) ;; *) + _SD="$(yt_session_home)/$YT_SESSION_ID" + [ ! -f "$_SD/coordinate" ] || printf '%s\n' "$(date +%s)" >> "$_SD/compactions" 2>/dev/null ;; +esac + # Compaction instructions (stdout, exit 0). Keep well under the 10,000-char cap. INSTR="ytstack compaction guidance. Preserve verbatim in the summary: - Project ${PROJECT:-unknown}, position ${CURRENT_MILESTONE:-none}${ACTIVE_SLICE:+ / $ACTIVE_SLICE}${ACTIVE_TASK:+ / $ACTIVE_TASK}, working tree $YT_TOPLEVEL${YT_IS_LINKED:+ (linked worktree: $YT_IS_LINKED)}. diff --git a/hooks/pre-tool-use-agent b/hooks/pre-tool-use-agent index a59fa8d..8ef8db2 100644 --- a/hooks/pre-tool-use-agent +++ b/hooks/pre-tool-use-agent @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# ytstack PreToolUse hook on Agent and SendMessage (issue #76, part of #75): +# ytstack PreToolUse hook on Agent, Task, SendMessage and Bash (issues #76, #83): # in a coordinate session (the marker of hooks/standing-prompt), a dispatch # whose prompt carries no rendered brief gets one line of additionalContext: # render it with ytstack-brief. It never blocks (no permissionDecision). @@ -12,7 +12,13 @@ # statusline-setup, any type naming search or explore) without a brief is # neither warned nor counted. Every other Agent call is a dispatch, appended # to /dispatches (epoch per line) for the LANES.md staleness -# check of hooks/stop. +# check of hooks/stop. An Agent call that is no lookup and has no +# `isolation` gets one more line: dispatch with isolation "worktree" (#83). +# +# Bash (issue #83): a `gh pr merge` by hand gets the ytstack-finish-lane merge +# line, a `gh pr close` the line that a cap waits (parked) and CI reruns with +# gh run rerun. Only a call after a command separator, optionally behind the +# wrapper tokens of hooks/post-tool-use-bash, counts; an echo of the words not. # # Files only. Fail open: any problem ends silent with exit 0. @@ -27,14 +33,15 @@ case "$SID" in ''|.|..|*[!A-Za-z0-9._-]*) exit 0 ;; esac SD="$(yt_session_home)/$SID" [ -f "$SD/coordinate" ] || exit 0 JQ=$(yt_jq); PY=$(yt_python) -# field : tool_name, text (prompt, message or content of tool_input) or -# type (its subagent_type), through jq, else python3. +# field : tool_name, text (prompt, message or content of tool_input), +# type (its subagent_type) or isolation, through jq, else python3. field() { if [ -n "$JQ" ]; then case "$1" in tool) printf '%s' "$YT_STDIN" | "$JQ" -r '.tool_name // ""' ;; text) printf '%s' "$YT_STDIN" | "$JQ" -r '(.tool_input // {}) | (.prompt // .message // .content // "") | if type == "string" then . else tostring end' ;; type) printf '%s' "$YT_STDIN" | "$JQ" -r '(.tool_input // {}) | (.subagent_type // "") | tostring' ;; + isolation) printf '%s' "$YT_STDIN" | "$JQ" -r '(.tool_input // {}) | (.isolation // "") | tostring' ;; esac elif [ -n "$PY" ]; then printf '%s' "$YT_STDIN" | "$PY" -I -c ' @@ -46,15 +53,38 @@ except Exception: ti = d.get("tool_input") if isinstance(d.get("tool_input"), dict) else {} if sys.argv[1] == "tool": v = d.get("tool_name", "") -elif sys.argv[1] == "type": - v = ti.get("subagent_type", "") +elif sys.argv[1] in ("type", "isolation"): + v = ti.get("subagent_type" if sys.argv[1] == "type" else "isolation", "") else: v = ti.get("prompt") or ti.get("message") or ti.get("content") or "" print(v if isinstance(v, str) else json.dumps(v), end="")' "$1" fi } 2>/dev/null [ -n "$JQ$PY" ] || exit 0 -TOOL=$(field tool); TEXT=$(field text); TYPE=$(field type) +TOOL=$(field tool) +ROOT="${CLAUDE_PLUGIN_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}" +emit() { # emit : the PreToolUse additionalContext, then exit 0 + if [ -n "$JQ" ]; then + printf '%s' "$1" | "$JQ" -Rs '{hookSpecificOutput: {hookEventName: "PreToolUse", additionalContext: .}}' 2>/dev/null + else + printf '%s' "$1" | "$PY" -I -c 'import sys, json; print(json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse", "additionalContext": sys.stdin.read()}}))' 2>/dev/null + fi + exit 0 +} + +if [ "$TOOL" = Bash ]; then + _WRAP='((rtk|sudo|command|env([[:space:]]+[A-Za-z_][A-Za-z0-9_]*=[^[:space:]]*)*)[[:space:]]+)*' + _GH="(^|[;&|()])[[:space:]]*${_WRAP}gh[[:space:]]+pr[[:space:]]+" + _MERGE="${_GH}merge([[:space:]]|\$)"; _CLOSE="${_GH}close([[:space:]]|\$)" + if [[ "$YT_TOOL_CMD" =~ $_MERGE ]]; then + emit "ytstack: in a coordinator session a merge goes through bash \"$ROOT/bin/ytstack-finish-lane\" -C merge --pr --at --verdict-pattern '^Verdict: approved', after the route (ytstack:coordinate Step 6 and Step 7, ytstack:finish-lane Step 11). It reads the gates and merges at the reviewed commit only; gh pr merge by hand skips both." + elif [[ "$YT_TOOL_CMD" =~ $_CLOSE ]]; then + emit "ytstack: a coordinator never closes, reopens to retrigger or deletes the branch of a lane's pull request (HARD-GATE of ytstack:coordinate). A cap waits: bash \"$ROOT/bin/ytstack-frontier\" set --status parked --next \"wait for the cap\", the pull request stays open. A check reruns with gh run rerun --failed. Only the person closes open work; if the person asked to close this one, go on." + fi + exit 0 +fi + +TEXT=$(field text); TYPE=$(field type) BRIEF=no case "$TEXT" in "# Brief: "*|*" # Brief: "*) BRIEF=yes ;; esac @@ -69,13 +99,12 @@ case "$TOOL" in SendMessage) [ "${#TEXT}" -gt 400 ] || exit 0 ;; *) exit 0 ;; esac -[ "$BRIEF" = no ] || exit 0 - -ROOT="${CLAUDE_PLUGIN_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}" -MSG="ytstack: this $TOOL prompt carries no rendered brief (no line \"# Brief: ()\"). If it dispatches lane work, the path is: bash \"$ROOT/bin/ytstack-frontier\" claim --by , then bash \"$ROOT/bin/ytstack-brief\" render --task|--slice [--kind ...] as the prompt (ytstack:coordinate Step 5). A hand-written brief skips the scope, the verification, the spec areas and the standing instructions. A lookup that is no lane needs nothing." -if [ -n "$JQ" ]; then - printf '%s' "$MSG" | "$JQ" -Rs '{hookSpecificOutput: {hookEventName: "PreToolUse", additionalContext: .}}' 2>/dev/null -else - printf '%s' "$MSG" | "$PY" -I -c 'import sys, json; print(json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse", "additionalContext": sys.stdin.read()}}))' 2>/dev/null +MSG="" +[ "$BRIEF" = yes ] || MSG="ytstack: this $TOOL prompt carries no rendered brief (no line \"# Brief: ()\"). If it dispatches lane work, the path is: bash \"$ROOT/bin/ytstack-frontier\" claim --by , then bash \"$ROOT/bin/ytstack-brief\" render --task|--slice [--kind ...] as the prompt (ytstack:coordinate Step 5). A hand-written brief skips the scope, the verification, the spec areas and the standing instructions. A lookup that is no lane needs nothing." +# An Agent dispatch that is no lookup runs in a worktree of its own (#83). +if [ "$TOOL" != SendMessage ] && [ "$LOOKUP" = no ] && [ -z "$(field isolation)" ]; then + MSG="${MSG:+$MSG +}ytstack: dispatch lane work with isolation: \"worktree\" (ytstack:coordinate Step 5): without it the worker edits the checkout this session and the other lanes share." fi +[ -z "$MSG" ] || emit "$MSG" exit 0 diff --git a/hooks/session-start b/hooks/session-start index 6a6d1f6..f524a3b 100644 --- a/hooks/session-start +++ b/hooks/session-start @@ -17,7 +17,8 @@ # DECISIONS 2026-11-07). Read-only: writes nothing anywhere. # # Claude Code caps SessionStart additionalContext at 10,000 characters; the -# hook measures its output and drops the Next-action excerpt first if needed. +# hook measures its output and shrinks the blocks named above the cap code; +# the Next action excerpt is never cut (issue #82). set -uo pipefail trap '' PIPE @@ -36,18 +37,13 @@ STATE_FILE="${YT_DIR:+$YT_DIR/STATE.md}" # route greenfield build-intent to office-hours BEFORE any infra exists. PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}" USING_YTSTACK_FILE="$PLUGIN_ROOT/skills/using-ytstack/SKILL.md" -USING_YTSTACK_CONTENT="" -if [ -f "$USING_YTSTACK_FILE" ]; then - USING_YTSTACK_CONTENT=$(cat "$USING_YTSTACK_FILE") - if [ -n "${YTSTACK_HOST_CONTEXT:-}" ]; then - USING_YTSTACK_CONTENT="$YTSTACK_HOST_CONTEXT - -$USING_YTSTACK_CONTENT" - fi -fi +USING_SKILL="" +[ ! -f "$USING_YTSTACK_FILE" ] || USING_SKILL=$(cat "$USING_YTSTACK_FILE") # The only no-op case: we cannot prime the agent if the directive is missing. -[ -z "$USING_YTSTACK_CONTENT" ] && exit 0 +[ -z "$USING_SKILL" ] && exit 0 +NL=' +' # Helper: emit additionalContext JSON, or raw context for a plain-stdout host. emit_json() { @@ -67,11 +63,17 @@ emit_json() { fi } -DIRECTIVE=" +# directive : DIRECTIVE, with the host context in front when set. +directive() { + DIRECTIVE=" You have ytstack. Below is the full content of your 'ytstack:using-ytstack' skill, which tells you how to find and invoke ytstack skills based on user intent. Follow it. For all other skills, use the 'Skill' tool: -$USING_YTSTACK_CONTENT +${YTSTACK_HOST_CONTEXT:+$YTSTACK_HOST_CONTEXT + +}$1 " +} +directive "$USING_SKILL" # Greenfield: no .ytstack/ exists for this checkout. An existing, documented # codebase (README, docs/, CHANGELOG, ADRs, commit history; M010 / issue #18) @@ -117,8 +119,24 @@ if [ ! -f "$STATE_FILE" ]; then exit 0 fi +# A checkout on the default branch behind origin/ (local refs, no +# fetch; issue #82): its STATE.md is stale, so pointer and Next action come +# from origin's copy, and the line says how far behind it is. +STATE_TEXT=$(cat "$STATE_FILE" 2>/dev/null) +BEHIND_LINE="" +YT_BEHIND_N=0 +[ "$YT_IS_GIT" != yes ] || yt_behind_origin "$YT_TOPLEVEL" "$YT_DIR" +if [ "${YT_BEHIND_N:-0}" -gt 0 ]; then + if [ -n "$YT_BEHIND_STATE" ]; then + STATE_TEXT="$YT_BEHIND_STATE" + BEHIND_LINE="Checkout: $YT_BEHIND_N commit(s) behind $YT_BEHIND_REF (local refs, not fetched). Pointer and Next action are read from $YT_BEHIND_REF; the other files here are older, so the STATE lint waits. Bring the checkout up to date first: git merge --ff-only $YT_BEHIND_REF." + else + BEHIND_LINE="Checkout: $YT_BEHIND_N commit(s) behind $YT_BEHIND_REF (local refs, not fetched); the files here are older. Bring the checkout up to date first: git merge --ff-only $YT_BEHIND_REF." + fi +fi + # Extract frontmatter fields from STATE.md -get_field() { sed -n "s/^$1: *//p" "$STATE_FILE" | head -1; } +get_field() { printf '%s\n' "$STATE_TEXT" | sed -n "s/^$1: *//p" | head -1; } PROJECT=$(get_field project) CURRENT_MILESTONE=$(get_field current_milestone) ACTIVE_SLICE=$(get_field active_slice) @@ -126,7 +144,7 @@ ACTIVE_TASK=$(get_field active_task) LAST_UPDATED=$(get_field last_updated) # "Next action" body (up to the next ## header), trimmed -NEXT_ACTION=$(awk '/^## Next action/{flag=1; next} /^## /{flag=0} flag' "$STATE_FILE" | sed '/^$/d' | head -5 | cut -c1-600) +NEXT_ACTION=$(printf '%s\n' "$STATE_TEXT" | awk '/^## Next action/{flag=1; next} /^## /{flag=0} flag' | sed '/^$/d' | head -5 | cut -c1-600) # Lifecycle hints (M019-S03): a closed slice or milestone has a documented next step. LIFECYCLE_LINES="" @@ -156,7 +174,7 @@ IN_PROGRESS_N=${IN_PROGRESS_N:-0} # STATE pointer lint + ceremony dials (M018): read-only, both from the lib. yt_state_lint "$YT_DIR" >/dev/null LINT_LINES="" -if [ "${YT_STATE_WARN_COUNT:-0}" -gt 0 ]; then +if [ "${YT_STATE_WARN_COUNT:-0}" -gt 0 ] && [ "${YT_BEHIND_N:-0}" -eq 0 ]; then LINT_LINES="STATE lint ($YT_STATE_WARN_COUNT): $(printf '%s\n' "$YT_STATE_WARNINGS" | head -5 | sed 's/^/- /') A malformed pointer stops plan-task and summarize-task: fix STATE.md first. Size and history findings do not block; ytstack:reconcile moves history out with your consent." @@ -181,19 +199,27 @@ $(printf '%s\n' "$YT_FACTORY_NOTICES" | sed 's/^/- /')" esac # Handoffs: the user-written one in the tree, the automatic one out of tree. +# A manual handoff older than the automatic one is listed as older (#82). HANDOFF_LINES="" -if [ -f "$YT_DIR/HANDOFF.md" ]; then - H_EVENT=$(sed -n 's/^event: *//p' "$YT_DIR/HANDOFF.md" | head -1) - H_TS=$(sed -n 's/^timestamp: *//p' "$YT_DIR/HANDOFF.md" | head -1) - HANDOFF_LINES="Manual handoff: $YT_DIR/HANDOFF.md (event: ${H_EVENT:-unknown}${H_TS:+, $H_TS})" -fi +A_TS="" # Path computed without creating anything (read-only hook). LATEST_LINK="$(yt_state_base)/repos/$YT_REPO_KEY/worktrees/$YT_WT_KEY/latest-handoff" if [ -L "$LATEST_LINK" ] && [ -f "$LATEST_LINK" ]; then A_TARGET=$(readlink "$LATEST_LINK") A_TS=$(sed -n 's/^timestamp: *//p' "$A_TARGET" 2>/dev/null | head -1) - HANDOFF_LINES="${HANDOFF_LINES:+$HANDOFF_LINES -}Latest automatic handoff: $A_TARGET${A_TS:+ ($A_TS)}" + HANDOFF_LINES="Latest automatic handoff: $A_TARGET${A_TS:+ ($A_TS)}" +fi +if [ -f "$YT_DIR/HANDOFF.md" ]; then + H_EVENT=$(sed -n 's/^event: *//p' "$YT_DIR/HANDOFF.md" | head -1) + H_TS=$(sed -n 's/^timestamp: *//p' "$YT_DIR/HANDOFF.md" | head -1) + _HE=$(yt_epoch "$H_TS"); _AE=$(yt_epoch "$A_TS") + if [ -n "$_HE" ] && [ -n "$_AE" ] && [ "$_HE" -lt "$_AE" ]; then + HANDOFF_LINES="$HANDOFF_LINES +Older manual handoff: $YT_DIR/HANDOFF.md (event: ${H_EVENT:-unknown}, $H_TS; older than the automatic one)" + else + HANDOFF_LINES="Manual handoff: $YT_DIR/HANDOFF.md (event: ${H_EVENT:-unknown}${H_TS:+, $H_TS})${HANDOFF_LINES:+ +$HANDOFF_LINES}" + fi fi # Standing instructions (issue #74): the active entries of standing/, files @@ -225,6 +251,13 @@ if [ "$_ROLE" = coordinator ]; then CHECKLIST_LINES=$(awk '// { f = 0 } f { print } // { f = 1 }' "$PLUGIN_ROOT/docs/ux/coordinator-format.md" 2>/dev/null) [ -z "$CHECKLIST_LINES" ] || MINIMAL_CODE_LINES="" fi +# After a compaction of a coordinator (counted by hooks/pre-compact beside the +# marker; issue #83): rotate now, coordinate Step 12. +COMPACT_LINE="" +if [ "$_ROLE" = coordinator ] && [ "${YT_SOURCE:-}" = compact ]; then + _CN=$(grep -c . "$(yt_session_home)/$YT_SESSION_ID/compactions" 2>/dev/null); case "$_CN" in ''|*[!0-9]*|0) _CN=1 ;; esac + COMPACT_LINE="Compaction $_CN of this coordinator: ytstack:coordinate Step 12, rotate now." +fi # Technical spec (M022): name the entry point when the project has one. SPEC_HINT="" @@ -239,6 +272,15 @@ Current: ${CURRENT_MILESTONE:-none}${ACTIVE_SLICE:+ / $ACTIVE_SLICE}${ACTIVE_TAS Last updated: ${LAST_UPDATED:-unknown} Working tree: $YT_TOPLEVEL${YT_IS_LINKED:+ (linked worktree: $YT_IS_LINKED)} ytstack dir: $YT_DIR" + if [ -n "$BEHIND_LINE" ]; then + ctx="$ctx +$BEHIND_LINE" + fi + if [ -n "$COMPACT_LINE" ]; then + ctx="$ctx + +$COMPACT_LINE" + fi if [ -n "$next" ]; then ctx="$ctx @@ -305,103 +347,62 @@ FULL_CONTEXT="$DIRECTIVE $STATE_CONTEXT" # Claude Code drops SessionStart additionalContext beyond 10,000 chars (the -# overflow is spilled to a file the agent is not told about). Shed the Next -# action excerpt first, then warn. The cap is Claude Code's: host context a -# non-Claude adapter prepends (YTSTACK_HOST_CONTEXT, e.g. codex/adapter.md) -# is not counted; that host's own limit lives in its hooks config. +# overflow is spilled to a file the agent is not told about). The cap is +# Claude Code's: host context a non-Claude adapter prepends +# (YTSTACK_HOST_CONTEXT, e.g. codex/adapter.md) is not counted; that host's +# own limit lives in its hooks config. Above the guard the blocks shrink in +# this order: the standing lines to the three newest, the factory lines to a +# pointer, the minimal-code line to its pointer, the closing line to its +# short form, the standing lines to a pointer, last the using-ytstack body to +# what fits, cut at a line end, with a pointer to the file (issue #82: the +# Next action comes before that body). The Next action excerpt (at most five +# lines of 600 characters), the operating checklist and the lines about the +# checkout and a compaction are never cut. Still above the guard: a warning. _HOST="${YTSTACK_HOST_CONTEXT:-}"; _HOST_LEN=${#_HOST} -_NEXT_SHORT="$NEXT_ACTION" -# First the standing lines shrink to the three newest at 100 characters: the -# next action outranks a long list (the rest is a pointer line away). -if [ $(( ${#FULL_CONTEXT} - _HOST_LEN )) -gt 9500 ] && [ -n "${_SL:-}" ]; then - STANDING_LINES="$_SH -$(yt_standing_lines "$YT_DIR" "$_ROLE" 3 | cut -c1-100)" +over() { [ $(( ${#FULL_CONTEXT} - _HOST_LEN )) -gt 9500 ]; } +rebuild() { STATE_CONTEXT=$(build_state_context "$NEXT_ACTION") FULL_CONTEXT="$DIRECTIVE --- $STATE_CONTEXT" +} +if over && [ -n "${_SL:-}" ]; then + STANDING_LINES="$_SH +$(yt_standing_lines "$YT_DIR" "$_ROLE" 3 | cut -c1-100)" + rebuild fi -if [ $(( ${#FULL_CONTEXT} - _HOST_LEN )) -gt 9500 ]; then - # Cut the excerpt to what still fits instead of dropping it: the next action - # is the one line a session needs most. Below 200 characters it says nothing - # useful, so then it is left out as before. - _OVER=$(( ${#FULL_CONTEXT} - _HOST_LEN - 9500 )) - _KEEP=$(( ${#NEXT_ACTION} - _OVER - 40 )) - if [ "$_KEEP" -ge 200 ]; then - _NEXT_SHORT="${NEXT_ACTION:0:$_KEEP} ... (cut: rest in STATE.md)" - elif [ "${#NEXT_ACTION}" -le 70 ]; then - # Shorter than the omission note itself: dropping it would cost space. - _NEXT_SHORT="$NEXT_ACTION" - else - _NEXT_SHORT="(omitted: see STATE.md -- injection near the 10,000-char cap)" - fi - STATE_CONTEXT=$(build_state_context "$_NEXT_SHORT") - FULL_CONTEXT="$DIRECTIVE - ---- - -$STATE_CONTEXT" - # Second to go: the factory lines shrink to one pointer line. - if [ $(( ${#FULL_CONTEXT} - _HOST_LEN )) -gt 9500 ] && [ -n "$FACTORY_LINES" ]; then - _FN=$(printf '%s\n' "$YT_FACTORY_NOTICES" | grep -c .) - FACTORY_LINES="Factory tools: $_FN off (list cut for the 10,000-char cap): bin/ytstack-upkeep names them." - STATE_CONTEXT=$(build_state_context "$_NEXT_SHORT") - FULL_CONTEXT="$DIRECTIVE - ---- - -$STATE_CONTEXT" - fi - # Third: the minimal-code line shrinks to its pointer; fourth: the standing - # lines shrink to one pointer line (they outrank both: issue #74). - if [ $(( ${#FULL_CONTEXT} - _HOST_LEN )) -gt 9500 ] && [ -n "$MINIMAL_CODE_LINES" ]; then - MINIMAL_CODE_LINES="Minimal-code guard is on: load ytstack:minimal-code before writing code." - STATE_CONTEXT=$(build_state_context "$_NEXT_SHORT") - FULL_CONTEXT="$DIRECTIVE - ---- - -$STATE_CONTEXT" - fi - # Then the closing line keeps only its point (the files are the truth). - if [ $(( ${#FULL_CONTEXT} - _HOST_LEN )) -gt 9500 ]; then - CLOSING_LINE="The files in $YT_DIR are the source of truth (STATE.md,${SPEC_HINT} DECISIONS.md, KNOWLEDGE.md), not the conversation." - STATE_CONTEXT=$(build_state_context "$_NEXT_SHORT") - FULL_CONTEXT="$DIRECTIVE - ---- - -$STATE_CONTEXT" - fi - # The next action was left out before the later blocks shrank: give it back - # the room they freed. - case "$_NEXT_SHORT" in "(omitted:"*) - _KEEP=$(( 9500 - (${#FULL_CONTEXT} - _HOST_LEN - ${#_NEXT_SHORT}) - 40 )) - if [ "$_KEEP" -ge 200 ] && [ "$_KEEP" -lt "${#NEXT_ACTION}" ]; then - _NEXT_SHORT="${NEXT_ACTION:0:$_KEEP} ... (cut: rest in STATE.md)" - STATE_CONTEXT=$(build_state_context "$_NEXT_SHORT") - FULL_CONTEXT="$DIRECTIVE - ---- - -$STATE_CONTEXT" - fi ;; - esac - # Last the standing lines shrink to a pointer. - if [ $(( ${#FULL_CONTEXT} - _HOST_LEN )) -gt 9500 ] && [ -n "$STANDING_LINES" ]; then - STANDING_LINES="Standing instructions: $STANDING_N in force for role $_ROLE (cut for the cap): bin/ytstack-standing list, before you act." - STATE_CONTEXT=$(build_state_context "$_NEXT_SHORT") - FULL_CONTEXT="$DIRECTIVE - ---- - -$STATE_CONTEXT" - fi - if [ $(( ${#FULL_CONTEXT} - _HOST_LEN )) -gt 9500 ]; then - echo "[ytstack session-start] injection is $(( ${#FULL_CONTEXT} - _HOST_LEN )) chars; Claude Code caps additionalContext at 10,000. Shorten skills/using-ytstack/SKILL.md." >&2 - fi +if over && [ -n "$FACTORY_LINES" ]; then + _FN=$(printf '%s\n' "$YT_FACTORY_NOTICES" | grep -c .) + FACTORY_LINES="Factory tools: $_FN off (list cut for the 10,000-char cap): bin/ytstack-upkeep names them." + rebuild +fi +if over && [ -n "$MINIMAL_CODE_LINES" ]; then + MINIMAL_CODE_LINES="Minimal-code guard is on: load ytstack:minimal-code before writing code." + rebuild +fi +if over; then + CLOSING_LINE="The files in $YT_DIR are the source of truth (STATE.md,${SPEC_HINT} DECISIONS.md, KNOWLEDGE.md), not the conversation." + rebuild +fi +if over && [ -n "$STANDING_LINES" ]; then + STANDING_LINES="Standing instructions: $STANDING_N in force for role $_ROLE (cut for the cap): bin/ytstack-standing list, before you act." + rebuild +fi +if over; then + _NOTE="(cut for the 10,000-char cap: read the rest in $USING_YTSTACK_FILE)" + _KEEP=$(( ${#USING_SKILL} - (${#FULL_CONTEXT} - _HOST_LEN - 9500) - ${#_NOTE} - 2 )) + [ "$_KEEP" -gt 0 ] || _KEEP=0 + _CUT="${USING_SKILL:0:$_KEEP}" + _CUT="${_CUT%"$NL"*}" + directive "$_CUT + +$_NOTE" + rebuild +fi +if over; then + echo "[ytstack session-start] injection is $(( ${#FULL_CONTEXT} - _HOST_LEN )) chars; Claude Code caps additionalContext at 10,000. Shorten skills/using-ytstack/SKILL.md." >&2 fi # The running version's bin/ (issue #85), on every source: skills run bins as diff --git a/hooks/stop b/hooks/stop index 89a7d26..1be07f6 100644 --- a/hooks/stop +++ b/hooks/stop @@ -5,8 +5,11 @@ # # 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. +# via `systemMessage`, once per session and pointer, never in coordinate +# mode, not for a pointer the STATE lint reports as days old (W10). A +# checkout on the default branch behind origin gets one message with +# origin's pointer instead (issue #82). 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 @@ -21,6 +24,8 @@ # session's dispatches and reports, the STATE pointer behind the newest # milestone. Said once per session; after YT_LINT_STREAK_N sessions in a # row (default 3) the stop is blocked once. See the section below. +# 4. Rotation (coordinate mode, issue #83): from the second compaction of +# the session, one reminder per compaction to rotate (Step 12). # # 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 @@ -145,28 +150,73 @@ coordinate_lints() { } coordinate_lints -# ---- 1. task reminder -------------------------------------------------------------- +# ---- 4. rotation (coordinate mode, issue #83) --------------------------------------- +# From the second compaction of a coordinator session (counted by hooks/pre-compact +# in /compactions): one reminder per compaction to rotate (Step 12). +ROTATE_MSG="" +rotate_msg() { + local sid="${YT_SESSION_ID:-}" sd n + case "$sid" in ''|.|..|*[!A-Za-z0-9._-]*) return 0 ;; esac + sd="$(yt_session_home)/$sid" + [ -f "$sd/coordinate" ] || return 0 + n=$(grep -c . "$sd/compactions" 2>/dev/null); case "$n" in ''|*[!0-9]*) n=0 ;; esac + [ "$n" -ge 2 ] && [ "$(cat "$sd/rotate-said" 2>/dev/null)" != "$n" ] || return 0 + printf '%s\n' "$n" > "$sd/rotate-said" 2>/dev/null || return 0 + ROTATE_MSG="ytstack: this coordinator session was compacted $n times. Rotate now (ytstack:coordinate Step 12): rows and standing instructions current, HANDOFF.md with the Rotation block, a fresh session with ytstack:coordinate; this one stays open only as a relay." +} +rotate_msg + +# ---- 1. task reminder (issue #82) --------------------------------------------------- +# Once per session and pointer (/stop-said holds what was said). +# On the default branch behind origin/ (local refs, no fetch) the +# local STATE.md is stale: one message with the count and origin's pointer +# instead, also in coordinate mode. A coordinate session holds no task: no +# reminder. A pointer older than YT_POINTER_STALE_DAYS is the STATE lint's +# line W10 (SessionStart), not a message on every stop. +said() { # said : 0 when this session said it already; records it otherwise + local sid="${YT_SESSION_ID:-}" f + case "$sid" in ''|.|..|*[!A-Za-z0-9._-]*) return 1 ;; esac + f="$(yt_session_home)/$sid/stop-said" + grep -qxF -- "$1" "$f" 2>/dev/null && return 0 + mkdir -p "${f%/*}" 2>/dev/null && printf '%s\n' "$1" >> "$f" 2>/dev/null + return 1 +} task_msg() { - local ytd state m s t summary + local ytd state m s t summary sid="${YT_SESSION_ID:-}" ptr 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) + get_field() { sed -n "s/^$1: *//p" 2>/dev/null | head -1; } + if [ "$YT_IS_GIT" = yes ]; then + yt_behind_origin "$YT_TOPLEVEL" "$ytd" + if [ "${YT_BEHIND_N:-0}" -gt 0 ]; then + said "behind:$(git -C "$YT_TOPLEVEL" rev-parse -q --verify "refs/remotes/$YT_BEHIND_REF" 2>/dev/null)" && return 0 + ptr="$(printf '%s\n' "$YT_BEHIND_STATE" | get_field current_milestone) / $(printf '%s\n' "$YT_BEHIND_STATE" | get_field active_slice) / $(printf '%s\n' "$YT_BEHIND_STATE" | get_field active_task)" + MSG="ytstack: this checkout ($YT_TOPLEVEL) is $YT_BEHIND_N commit(s) behind $YT_BEHIND_REF (local refs, not fetched): its STATE.md is stale. $YT_BEHIND_REF points at $ptr. Bring it up to date (git merge --ff-only $YT_BEHIND_REF) before acting on the pointer." + return 0 + fi + fi + case "$sid" in ''|.|..|*[!A-Za-z0-9._-]*) ;; *) [ ! -f "$(yt_session_home)/$sid/coordinate" ] || return 0 ;; esac + m=$(get_field current_milestone < "$state"); s=$(get_field active_slice < "$state"); t=$(get_field active_task < "$state") case "$t" in ""|none|all) return 0 ;; esac case "$s" in ""|none|all) return 0 ;; esac case "$m" in ""|none) return 0 ;; esac + yt_state_lint "$ytd" >/dev/null + case "${YT_STATE_WARNINGS:-}" in *"active task $m-$s-$t unchanged since"*) return 0 ;; esac # The summary where the task's milestone lives (issue #70), flat or nested. summary=$(yt_artifact_path "$ytd" "$m-$s-$t-SUMMARY.md") if [ ! -f "$summary" ]; then + said "task:$m-$s-$t:missing" && return 0 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 + said "task:$m-$s-$t:draft" && return 0 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="" task_msg +[ -z "$ROTATE_MSG" ] || MSG="${MSG:+$MSG }$ROTATE_MSG" [ -z "$LINT_MSG" ] || MSG="${MSG:+$MSG }$LINT_MSG" [ -n "$MSG$BLOCK_REASON" ] || exit 0 diff --git a/tests/git-ctx.test.sh b/tests/git-ctx.test.sh index 4bf7407..adb940d 100644 --- a/tests/git-ctx.test.sh +++ b/tests/git-ctx.test.sh @@ -279,6 +279,14 @@ case "$(lint "$SL/.ytstack")" in *"older than the newest commit"*) ok "lint: sta write_state "$NOW" M003 S01 T02 printf -- '---\nmilestone: M003\nstatus: done\n---\n' > "$SL/.ytstack/M003-ROADMAP.md" case "$(lint "$SL/.ytstack")" in *"status: done"*) ok "lint: done milestone still current with open slice";; *) bad "lint: done but current" "$(lint "$SL/.ytstack")";; esac +printf -- '---\nmilestone: M003\nstatus: in-progress\n---\n' > "$SL/.ytstack/M003-ROADMAP.md" +# W10 (issue #82): an active task whose pointer did not move for YT_POINTER_STALE_DAYS days +case "$(lint "$SL/.ytstack")" in *"unchanged since"*) bad "lint: a fresh pointer is no stale task";; *) ok "lint: a fresh pointer is no stale task";; esac +E5=$(( $(date +%s) - 5 * 86400 )) +write_state "$(date -u -r "$E5" +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date -u -d "@$E5" +%Y-%m-%dT%H:%M:%SZ)" M003 S01 T02 +case "$(lint "$SL/.ytstack")" in *"active task M003-S01-T02 unchanged since last_updated "*"(more than 3 days)"*) ok "lint: a pointer 5 days old is one line (W10)";; *) bad "lint: W10" "$(lint "$SL/.ytstack")";; esac +eq "lint: YT_POINTER_STALE_DAYS moves the threshold" 0 "$( ( YT_POINTER_STALE_DAYS=9; . "$LIB"; yt_state_lint "$SL/.ytstack" >/dev/null; printf '%s' "$YT_STATE_WARNINGS" | grep -c 'unchanged since' ) )" +write_state "$NOW" M003 S01 T02 # ---- 13b. progress block (M021, issue #31) ------------------------------------ echo "# progress block" @@ -440,6 +448,22 @@ eq "standing lines: lane sees the role-free entry only" "- 20261114T1040Z-englis 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 )" +# ---- yt_behind_origin: a checkout on the default branch behind origin (issue #82) ---- +echo "# behind origin" +BO="$TMP/bo-origin.git"; git init -q --bare "$BO" +BC=$(new_repo bo-clone); mkdir -p "$BC/.ytstack" +( cd "$BC" || exit 2; git branch -M main; printf 'current_milestone: M001\n' > .ytstack/STATE.md; git add -A; git commit -qm state + git remote add origin "$BO"; git push -q -u origin main + printf 'current_milestone: M007\n' > .ytstack/STATE.md; git commit -qam next; git push -q origin main + git checkout -q --detach HEAD~1 && git branch -q -f main HEAD && git checkout -q main ) >/dev/null 2>&1 +bo() { ( . "$LIB"; yt_behind_origin "$1" "$1/.ytstack"; printf '%s|%s|%s' "$YT_BEHIND_N" "$YT_BEHIND_REF" "$YT_BEHIND_STATE" ); } +eq "behind: one commit behind origin/main, STATE read from it" "1|origin/main|current_milestone: M007" "$(bo "$BC")" +( cd "$BC" && git checkout -q -b side ) >/dev/null 2>&1 +eq "behind: another branch is not the default branch" "0||" "$(bo "$BC")" +( cd "$BC" && git checkout -q main && git merge -q --ff-only origin/main ) >/dev/null 2>&1 +eq "behind: up to date" "0||" "$(bo "$BC")" +eq "behind: no origin" "0||" "$(bo "$(new_repo bo-plain)")" + echo echo "$PASS passed, $FAIL failed" [ "$FAIL" -eq 0 ] diff --git a/tests/hooks-coordinate.test.sh b/tests/hooks-coordinate.test.sh index 28cc101..b69264e 100644 --- a/tests/hooks-coordinate.test.sh +++ b/tests/hooks-coordinate.test.sh @@ -46,7 +46,7 @@ marker() { mkdir -p "$SH/$1"; printf '%s\n' "$P/.ytstack" > "$SH/$1/coordinate"; tool() { # tool -> OUT OUT=$("$JQ" -n --arg s "$1" --arg t "$2" --arg x "$3" --arg c "$P" \ - '{session_id: $s, cwd: $c, hook_event_name: "PreToolUse", tool_name: $t, tool_input: (if $t == "SendMessage" then {to: "w1", message: $x} else {prompt: $x, description: "d"} end)}' \ + '{session_id: $s, cwd: $c, hook_event_name: "PreToolUse", tool_name: $t, tool_input: (if $t == "SendMessage" then {to: "w1", message: $x} elif $t == "Bash" then {command: $x} else {prompt: $x, description: "d", isolation: "worktree"} end)}' \ | bash "$H/pre-tool-use-agent" 2>&1) } stop() { OUT=$("$JQ" -n --arg s "$1" --arg c "$P" '{session_id: $s, cwd: $c, hook_event_name: "Stop"}' | bash "$H/stop" 2>&1); } @@ -87,6 +87,28 @@ OUT=$("$JQ" -n --arg c "$P" '{session_id: "a1", cwd: $c, hook_event_name: "PreTo has "no jq: still warned, through python3" "$(ctx .hookSpecificOutput.additionalContext)" "no rendered brief" eq "no jq: still counted" 5 "$(grep -c . "$SH/a1/dispatches")" +echo "# pre-tool-use-agent: isolation, merges and closes by hand (issue #83)" +noiso() { OUT=$("$JQ" -n --arg c "$P" --arg t "$1" '{session_id: "a1", cwd: $c, hook_event_name: "PreToolUse", tool_name: "Agent", tool_input: {prompt: "# Brief: M001-S01 (p)\nx", subagent_type: $t}}' | bash "$H/pre-tool-use-agent" 2>&1); } +noiso general-purpose +has "a rendered brief without isolation: hinted" "$(ctx .hookSpecificOutput.additionalContext)" 'isolation: "worktree"' +case "$(ctx .hookSpecificOutput.additionalContext)" in *"no rendered brief"*) bad "and not called hand-written";; *) ok "and not called hand-written";; esac +eq "never a permission decision" "" "$(ctx .hookSpecificOutput.permissionDecision)" +noiso Explore; eq "a lookup without isolation: silent" "" "$OUT" +OUT=$("$JQ" -n --arg c "$P" '{session_id: "a1", cwd: $c, hook_event_name: "PreToolUse", tool_name: "Agent", tool_input: {prompt: "Implement it.", subagent_type: "general-purpose"}}' | YT_FORCE_NO_JQ=1 bash "$H/pre-tool-use-agent" 2>&1) +has "no jq: the isolation hint too" "$(ctx .hookSpecificOutput.additionalContext)" 'isolation: "worktree"' +N0=$(grep -c . "$SH/a1/dispatches") +tool a1 Bash "gh pr merge 12 --squash" +has "gh pr merge by hand: the finish-lane merge is named" "$(ctx .hookSpecificOutput.additionalContext)" "bin/ytstack-finish-lane\" -C merge --pr --at " +tool a1 Bash "cd /x && rtk gh pr merge 12" +has "behind cd and a wrapper too" "$(ctx .hookSpecificOutput.additionalContext)" "ytstack-finish-lane" +tool a1 Bash "gh pr close 14 --comment 'cap'" +has "gh pr close: a cap waits" "$(ctx .hookSpecificOutput.additionalContext)" "--status parked" +has "and CI reruns" "$(ctx .hookSpecificOutput.additionalContext)" "gh run rerun" +tool a1 Bash "gh pr view 12 --json state"; eq "another gh call: silent" "" "$OUT" +tool a1 Bash "echo 'gh pr merge is not run here' > notes.txt"; eq "an echo of the words: silent" "" "$OUT" +eq "Bash calls are no dispatches" "$N0" "$(grep -c . "$SH/a1/dispatches")" +tool nomark Bash "gh pr merge 12"; eq "no marker: silent" "" "$OUT" + echo "# session-start: operating checklist" WANT=$(awk '// { f = 0 } f { print } // { f = 1 }' "$ROOT/docs/ux/coordinator-format.md") [ -n "$WANT" ] && ok "the doc has the checklist block" || bad "the doc has the checklist block" @@ -152,6 +174,39 @@ mkdir -p "$SH/u2"; printf '%s\nkeytwo\n' "$P/.ytstack" > "$SH/u2/coordinate"; da eq "two keys, two counters" "1|1" "$(awk -F '\t' '$1 == "lanes" { print $2 }' "$XDG_STATE_HOME/ytstack/repos/keyone/coordinate-lints" 2>/dev/null)|$(awk -F '\t' '$1 == "lanes" { print $2 }' "$XDG_STATE_HOME/ytstack/repos/keytwo/coordinate-lints" 2>/dev/null)" eq "nothing written into the project" "?? .ytstack/LANES.md" "$(git -C "$P" status --porcelain)" +echo "# compactions of a coordinator: rotate (issue #83)" +rm -rf "$XDG_STATE_HOME/ytstack/repos"; touch "$P/.ytstack/LANES.md" +compact() { "$JQ" -n --arg s "$1" --arg c "$P" '{session_id: $s, cwd: $c, hook_event_name: "PreCompact", trigger: "auto"}' | bash "$H/pre-compact" >/dev/null 2>&1; } +ss() { OUT=$("$JQ" -n --arg s "$1" --arg c "$P" --arg src "$2" '{session_id: $s, cwd: $c, source: $src}' | CLAUDE_PLUGIN_ROOT="$ROOT" bash "$H/session-start" 2>/dev/null); C=$(ctx .hookSpecificOutput.additionalContext); } +marker r1 +compact r1; ss r1 compact +has "first compaction: SessionStart says rotate now" "$C" "Compaction 1 of this coordinator: ytstack:coordinate Step 12, rotate now" +stop r1; case "$(ctx .systemMessage)" in *"Rotate now"*) bad "first compaction: no Stop reminder yet";; *) ok "first compaction: no Stop reminder yet";; esac +compact r1; ss r1 compact +has "second compaction: counted" "$C" "Compaction 2 of this coordinator" +if [ "${#C}" -le 9500 ]; then ok "fits the guard (${#C})"; else bad "fits the guard" "${#C}"; fi +stop r1; has "second compaction: the Stop reminder" "$(ctx .systemMessage)" "compacted 2 times. Rotate now (ytstack:coordinate Step 12)" +stop r1; case "$(ctx .systemMessage)" in *"Rotate now"*) bad "once per compaction";; *) ok "once per compaction";; esac +ss r1 startup; case "$C" in *"Compaction "*) bad "a startup source: no compaction line";; *) ok "a startup source: no compaction line";; esac +compact plain1; ss plain1 compact; case "$C" in *"of this coordinator"*) bad "no marker: no compaction line";; *) ok "no marker: no compaction line";; esac +eq "no marker: nothing counted" no "$([ -e "$SH/plain1/compactions" ] && echo yes || echo no)" + +echo "# post-tool-use-bash: a red default branch read with gh run list (issue #83)" +DEF=$(git -C "$P" symbolic-ref --short HEAD) +runs() { OUT=$("$JQ" -n --arg s "$1" --arg c "$P" --arg cmd "$2" --arg o "$3" '{session_id: $s, cwd: $c, hook_event_name: "PostToolUse", tool_name: "Bash", tool_input: {command: $cmd}, tool_response: {stdout: $o, stderr: "", interrupted: false}}' | bash "$H/post-tool-use-bash" 2>&1); } +RED=$(printf 'completed\tsuccess\tfix: a\tci\t%s\tpush\t101\t1m\t2h\ncompleted\tfailure\tfeat: b\tci\t%s\tpush\t102\t3m\t1h\n' "$DEF" "$DEF") +GREEN=$(printf 'completed\tsuccess\tfix: a\tci\t%s\tpush\t101\t1m\t2h\n' "$DEF") +runs a1 "gh run list --branch $DEF --limit 5" "$RED" +has "a failed run on the default branch: run ytstack:lesson" "$(ctx .hookSpecificOutput.additionalContext)" "ytstack:lesson" +eq "as PostToolUse context" PostToolUse "$(ctx .hookSpecificOutput.hookEventName)" +runs a1 "gh run list --branch $DEF --limit 5" "$RED"; eq "the same failure: said once" "" "$OUT" +runs a1 "gh run list -b $DEF --json conclusion" '[{"conclusion":"success"},{"conclusion":"failure","databaseId":103}]' +has "JSON output, -b: said" "$(ctx .hookSpecificOutput.additionalContext)" "ytstack:lesson" +runs a1 "gh run list --branch $DEF" "$GREEN"; eq "all green: silent" "" "$OUT" +runs a1 "gh run list --branch feature-x" "$(printf 'completed\tfailure\tx\tci\tfeature-x\tpush\t104\t1m\t1h\n')"; eq "another branch: silent" "" "$OUT" +runs a1 "gh run list" "$(printf 'completed\tfailure\tx\tci\t%s\tpush\t105\t1m\t1h\n' "$DEF")"; eq "no --branch: silent" "" "$OUT" +runs nomark "gh run list --branch $DEF" "$RED"; eq "no marker: silent" "" "$OUT" + echo echo "$PASS passed, $FAIL failed" [ "$FAIL" -eq 0 ] diff --git a/tests/hooks-json.test.sh b/tests/hooks-json.test.sh index d002c20..023a3de 100644 --- a/tests/hooks-json.test.sh +++ b/tests/hooks-json.test.sh @@ -40,7 +40,7 @@ eq "version-notice is the first UserPromptSubmit entry, 5 s" 'bash "${CLAUDE_PLU "$(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 "pre-tool-use-agent on Agent|Task|SendMessage, 5 s (issue #76)" 'Agent|Task|SendMessage|5' \ +eq "pre-tool-use-agent on Agent|Task|SendMessage|Bash, 5 s (issues #76, #83)" 'Agent|Task|SendMessage|Bash|5' \ "$(jq -r '.hooks.PreToolUse[] | select(.hooks[0].command == "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/pre-tool-use-agent\"") | "\(.matcher)|\(.hooks[0].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-readonly.test.sh b/tests/hooks-readonly.test.sh index ba5a9bc..f1c3c34 100644 --- a/tests/hooks-readonly.test.sh +++ b/tests/hooks-readonly.test.sh @@ -115,12 +115,46 @@ rm -f "$MAIN/.ytstack/PREFERENCES.md" run session-start "{\"session_id\":\"s1cut\",\"cwd\":$(jstr "$MAIN")}" CTX=$(printf '%s' "$OUT" | jq -r '.hookSpecificOutput.additionalContext // empty' 2>/dev/null) has "ss-main: long next action -> its start is kept" "$CTX" "NEXTLINE0 xxx" -has "ss-main: long next action -> the cut is marked" "$CTX" "(cut: rest in STATE.md)" +# issue #82: the Next action comes before the using-ytstack body in the budget +has "ss-main: long next action -> kept whole" "$CTX" "NEXTLINE4 xxx" +lacks "ss-main: long next action -> not cut" "$CTX" "(cut: rest in STATE.md)" lacks "ss-main: long next action -> not dropped" "$CTX" "(omitted: see STATE.md" +has "ss-main: the using-ytstack body yields, with a pointer" "$CTX" "(cut for the 10,000-char cap: read the rest in $ROOT/skills/using-ytstack/SKILL.md)" +has "ss-main: and keeps its start" "$CTX" "# Using ytstack" lacks "ss-main: long next action -> YT_BIN yields first (issue #85)" "$CTX" "YT_BIN=" 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" +# ---- 1c2. session-start: a manual handoff older than the automatic one (issue #82) +cp "$MAIN/.ytstack/HANDOFF.md" "$TMP/handoff.good" +printf -- '---\nkind: handoff\nevent: user-triggered\ntimestamp: 2020-01-01T00:00:00Z\n---\n# manual\n' > "$MAIN/.ytstack/HANDOFF.md" +run session-start "{\"session_id\":\"s1ho\",\"cwd\":$(jstr "$MAIN")}" +CTX=$(printf '%s' "$OUT" | jq -r '.hookSpecificOutput.additionalContext // empty' 2>/dev/null) +has "ss-handoff: an older manual handoff is named older" "$CTX" "Older manual handoff: $MAIN/.ytstack/HANDOFF.md (event: user-triggered, 2020-01-01T00:00:00Z; older than the automatic one)" +lacks "ss-handoff: and not as the current one" "$CTX" " +Manual handoff:" +printf -- '---\nkind: handoff\nevent: user-triggered\ntimestamp: 2099-01-01T00:00:00Z\n---\n# manual\n' > "$MAIN/.ytstack/HANDOFF.md" +run session-start "{\"session_id\":\"s1ho2\",\"cwd\":$(jstr "$MAIN")}" +CTX=$(printf '%s' "$OUT" | jq -r '.hookSpecificOutput.additionalContext // empty' 2>/dev/null) +has "ss-handoff: a newer manual handoff stays the manual handoff" "$CTX" "Manual handoff: $MAIN/.ytstack/HANDOFF.md" +cp "$TMP/handoff.good" "$MAIN/.ytstack/HANDOFF.md" + +# ---- 1c3. session-start: a checkout behind origin reads STATE.md from origin (issue #82) +BH="$TMP/behind"; BO="$TMP/behind-origin.git"; git init -q --bare "$BO" +( mkdir -p "$BH/.ytstack" && cd "$BH" || exit 2; git init -q && git config user.email t@t.t && git config user.name t && git config commit.gpgsign false + printf 'project: fixture\ncurrent_milestone: M001\nactive_slice: none\nactive_task: none\n\n## Next action\n\nOld plan.\n' > .ytstack/STATE.md + git add -A && git commit -qm seed && git branch -M main && git remote add origin "$BO" && git push -q -u origin main + printf 'project: fixture\ncurrent_milestone: M050\nactive_slice: S01\nactive_task: T02\n\n## Next action\n\nOrigin plan.\n' > .ytstack/STATE.md + git commit -qam next && git push -q origin main && git commit -q --allow-empty -m more && git push -q origin main + git checkout -q --detach HEAD~2 && git branch -q -f main HEAD && git checkout -q main ) >/dev/null 2>&1 || { echo FATAL behind fixture; exit 2; } +run session-start "{\"session_id\":\"s1bh\",\"cwd\":$(jstr "$BH")}" +CTX=$(printf '%s' "$OUT" | jq -r '.hookSpecificOutput.additionalContext // empty' 2>/dev/null) +has "ss-behind: says how far behind" "$CTX" "Checkout: 2 commit(s) behind origin/main (local refs, not fetched)" +has "ss-behind: the pointer from origin" "$CTX" "Current: M050 / S01 / T02" +has "ss-behind: the next action from origin" "$CTX" "Origin plan." +lacks "ss-behind: not the stale local one" "$CTX" "Old plan." +eq "ss-behind: nothing written" "" "$(git -C "$BH" status --porcelain)" + # ---- 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"; } diff --git a/tests/hooks-standing.test.sh b/tests/hooks-standing.test.sh index 990cd4e..9a4e2f4 100644 --- a/tests/hooks-standing.test.sh +++ b/tests/hooks-standing.test.sh @@ -12,7 +12,8 @@ # - 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 +# - stop_hook_active -> silent; a block with an active task pointer comes +# without the task reminder (a coordinate session holds no task, #82) # # Run: /bin/bash tests/hooks-standing.test.sh (exit 0 = all pass) @@ -115,8 +116,8 @@ 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" +eq "block with an active task pointer: block" block "$(printf '%s' "$OUT" | "$JQ" -r '.decision // empty')" +eq "a coordinate session holds no task: no task reminder (issue #82)" "" "$(printf '%s' "$OUT" | "$JQ" -r '.systemMessage // empty')" rm -f "$SD/coordinate" prompt "Never again."; stop hasnt "marker gone: no block" "$OUT" '"decision"' diff --git a/tests/hooks-stop.test.sh b/tests/hooks-stop.test.sh index 360c570..42eadfa 100644 --- a/tests/hooks-stop.test.sh +++ b/tests/hooks-stop.test.sh @@ -1,11 +1,16 @@ #!/usr/bin/env bash -# Tests for the advisory Stop hook (M019-S04). +# Tests for the advisory Stop hook (M019-S04, issue #82). # # - active task without summary -> systemMessage reminder, exit 0 # - active task with a draft stub -> reminder # - active task with a real summary -> silent # - no active task / no .ytstack / stop_hook_active true -> silent -# - resolves from payload cwd (worktree), never writes anything +# - resolves from payload cwd (worktree), never writes into the checkout +# - a reminder is said once per (session, pointer); a coordinate session +# (the marker) gets none; a pointer older than YT_POINTER_STALE_DAYS is +# left to the STATE lint line (W10) +# - on the default branch behind origin/ (local refs): one message +# with the count and the pointer origin's STATE.md has, once per origin head # # Run: /bin/bash tests/hooks-stop.test.sh (exit 0 = all pass) @@ -18,47 +23,62 @@ 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'";; esac; } +has() { case "$2" in *"$3"*) ok "$1";; *) bad "$1" "missing '$3' in: $2";; esac; } TMP=$(mktemp -d "${TMPDIR:-/tmp}/ytstop.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 ELSEWHERE="$TMP/elsewhere"; mkdir -p "$ELSEWHERE" jstr() { printf '%s' "$1" | jq -Rs .; } MAIN="$TMP/main"; mkdir -p "$MAIN/.ytstack" -( cd "$MAIN" || exit 2; git init -q && git config user.email t@t.t && git config user.name t +( cd "$MAIN" || exit 2; git init -q && git config user.email t@t.t && git config user.name t && git config commit.gpgsign false printf 'current_milestone: M042\nactive_slice: S03\nactive_task: T07\n' > .ytstack/STATE.md echo seed > f; git add -A; git commit -qm seed ) >/dev/null 2>&1 || { echo FATAL fixture; exit 2; } -fire() { # fire [extra-json] - printf '{"session_id":"s","cwd":%s,"hook_event_name":"Stop"%s}' "$(jstr "$1")" "${2:-}" \ +# fire [extra-json]: the session id is $SID (a new one per case: a +# reminder is said once per session and pointer) +fire() { + printf '{"session_id":"%s","cwd":%s,"hook_event_name":"Stop"%s}' "${SID:-s}" "$(jstr "$1")" "${2:-}" \ | ( cd "$ELSEWHERE" && CLAUDE_PROJECT_DIR="$ELSEWHERE" bash "$HOOK" 2>"$TMP/err" ); EC=$? } echo "# active task without summary" -OUT=$(fire "$MAIN"); eq "exit 0" 0 "$?" +SID=s1; OUT=$(fire "$MAIN"); eq "exit 0" 0 "$?" has "reminder names the task" "$OUT" "M042-S03-T07" has "reminder is a systemMessage JSON" "$OUT" '"systemMessage"' if printf '%s' "$OUT" | jq -e .systemMessage >/dev/null 2>&1; then ok "valid JSON"; else bad "valid JSON" "$OUT"; fi eq "git status clean" "" "$(git -C "$MAIN" status --porcelain)" +OUT=$(fire "$MAIN"); eq "the same session and pointer: said once" "" "$OUT" +SID=s2; OUT=$(fire "$MAIN"); has "another session: said again" "$OUT" "M042-S03-T07" echo "# draft stub" printf -- '---\nclosed: draft\n---\n' > "$MAIN/.ytstack/M042-S03-T07-SUMMARY.md" -OUT=$(fire "$MAIN"); has "draft stub -> reminder" "$OUT" "draft summary stub" +SID=s3; OUT=$(fire "$MAIN"); has "draft stub -> reminder" "$OUT" "draft summary stub" echo "# real summary" printf -- '---\nclosed: 2026-11-07T00:00:00Z\n---\n' > "$MAIN/.ytstack/M042-S03-T07-SUMMARY.md" -OUT=$(fire "$MAIN"); eq "real summary -> silent" "" "$OUT" +SID=s4; OUT=$(fire "$MAIN"); eq "real summary -> silent" "" "$OUT" rm -f "$MAIN/.ytstack/M042-S03-T07-SUMMARY.md" echo "# summary in milestones/M042/ (#70)" mkdir -p "$MAIN/.ytstack/milestones/M042" printf -- '---\nclosed: 2026-11-07T00:00:00Z\n---\n' > "$MAIN/.ytstack/milestones/M042/M042-S03-T07-SUMMARY.md" -OUT=$(fire "$MAIN"); eq "moved summary -> silent" "" "$OUT" +SID=s5; OUT=$(fire "$MAIN"); eq "moved summary -> silent" "" "$OUT" rm -rf "$MAIN/.ytstack/milestones" +echo "# coordinate session and an old pointer (issue #82)" +mkdir -p "$XDG_STATE_HOME/ytstack/sessions/c1"; printf '%s\n' "$MAIN/.ytstack" > "$XDG_STATE_HOME/ytstack/sessions/c1/coordinate" +SID=c1; OUT=$(fire "$MAIN"); eq "coordinate marker: no task reminder" "" "$OUT" +cp "$MAIN/.ytstack/STATE.md" "$TMP/state.keep" +E5=$(( $(date +%s) - 5 * 86400 )) +printf 'last_updated: %s\n' "$(date -u -r "$E5" +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date -u -d "@$E5" +%Y-%m-%dT%H:%M:%SZ)" >> "$MAIN/.ytstack/STATE.md" +SID=s6; OUT=$(fire "$MAIN"); eq "a pointer 5 days old: left to the STATE lint, silent" "" "$OUT" +cp "$TMP/state.keep" "$MAIN/.ytstack/STATE.md" + echo "# guards" -OUT=$(fire "$MAIN" ',"stop_hook_active":true'); eq "stop_hook_active -> silent" "" "$OUT" +SID=s7; OUT=$(fire "$MAIN" ',"stop_hook_active":true'); eq "stop_hook_active -> silent" "" "$OUT" printf 'current_milestone: M042\nactive_slice: none\nactive_task: none\n' > "$MAIN/.ytstack/STATE.md" OUT=$(fire "$MAIN"); eq "no active task -> silent" "" "$OUT" PLAIN="$TMP/plain"; mkdir -p "$PLAIN" @@ -70,9 +90,21 @@ printf 'current_milestone: M042\nactive_slice: S03\nactive_task: T07\n' > "$MAIN ( cd "$MAIN" && git add -A && git commit -qm state ) >/dev/null 2>&1 WT="$TMP/wt"; git -C "$MAIN" worktree add -q -b wt "$WT" >/dev/null 2>&1 printf -- '---\nclosed: 2026-11-07T00:00:00Z\n---\n' > "$WT/.ytstack/M042-S03-T07-SUMMARY.md" -OUT=$(fire "$WT"); eq "worktree with summary -> silent (resolved from cwd, not main)" "" "$OUT" +SID=s8; OUT=$(fire "$WT"); eq "worktree with summary -> silent (resolved from cwd, not main)" "" "$OUT" OUT=$(fire "$MAIN"); has "main without summary -> reminder" "$OUT" "M042-S03-T07" +echo "# a checkout behind origin (issue #82)" +O="$TMP/origin.git"; git init -q --bare "$O" +( cd "$MAIN" || exit 2; git branch -M main; git remote add origin "$O"; git push -q -u origin main + printf 'current_milestone: M050\nactive_slice: S01\nactive_task: T02\n' > .ytstack/STATE.md; git commit -qam next; git push -q origin main + git checkout -q --detach HEAD~1 && git branch -q -f main HEAD && git checkout -q main ) >/dev/null 2>&1 +SID=b1; OUT=$(fire "$MAIN") +has "behind: the count and the ref" "$OUT" "1 commit(s) behind origin/main" +has "behind: the pointer origin has" "$OUT" "M050 / S01 / T02" +case "$OUT" in *"M042-S03-T07 is still the active task"*) bad "behind: no reminder for the stale local pointer";; *) ok "behind: no reminder for the stale local pointer";; esac +OUT=$(fire "$MAIN"); eq "behind: said once per origin head" "" "$OUT" +SID=c1; OUT=$(fire "$MAIN"); has "behind: said in a coordinate session too" "$OUT" "behind origin/main" + echo echo "$PASS passed, $FAIL failed" [ "$FAIL" -eq 0 ] From 07a73ee5ed2569442e6a72d70d7a5368de88f059 Mon Sep 17 00:00:00 2001 From: Alex Wegener Date: Sun, 15 Nov 2026 19:53:46 +0100 Subject: [PATCH 03/13] feat: coordinate and finish-lane never close a lane PR; every round runs ytstack-frontier check (#83) coordinate 0.7.0 and finish-lane 0.6.0: a hard-gate sentence against closing, reopening to retrigger or deleting the branch of a lane's pull request (a cap waits as parked, a check reruns with gh run rerun); the cap counts pull requests ready for review. coordinate Step 5 starts every round of the loop with ytstack-frontier check and acts on each stale: line (exit 2) before any new dispatch; Step 12 names the compaction line. The operating checklist gets the loop check and the merge/close rule; coordinator-format documents parked and the new hooks. Co-Authored-By: Claude Opus 5.5 --- docs/ux/coordinator-format.md | 13 ++++++++++--- skills/coordinate/SKILL.md | 14 ++++++++------ skills/finish-lane/SKILL.md | 8 ++++---- tests/skill-preambles.test.sh | 19 +++++++++++++++++++ 4 files changed, 41 insertions(+), 13 deletions(-) diff --git a/docs/ux/coordinator-format.md b/docs/ux/coordinator-format.md index 3302e70..c31193d 100644 --- a/docs/ux/coordinator-format.md +++ b/docs/ux/coordinator-format.md @@ -19,7 +19,9 @@ Coordinator operating checklist (scripts in bin/ of the plugin): 2. Report: ytstack-brief check -> ytstack-frontier set --status reported -> ytstack:finish-lane. 3. Human instruction beyond the task: ytstack-standing add, before the next dispatch; never only in memory. 4. Merge to production: ytstack-watch release --commit . -5. After a compaction: run the coordinate preamble again first. +5. After a compaction: run the coordinate preamble again, then rotate (Step 12). +6. Every round: ytstack-frontier check; act on each stale: line. +7. Merge: ytstack-finish-lane merge, never gh pr merge. Never close a lane PR: a cap waits (parked), CI reruns via gh run rerun. ## `LANES.md` -- who works on what @@ -43,7 +45,7 @@ updated: 2026-11-13T10:42:00Z |---|---| | Lane | The reference. Unique in the file. | | Kind | `implement`, `review` or `prepare` (see "Lane kinds"). | -| Status | `claimed` (taken, not dispatched yet), `running`, `reported` (the worker's report is in and passed the check), `in-review`, `ready` (its gates held when last read), `merged`, `blocked`, `dropped`. What the coordinator did or saw last; not a host fact. | +| Status | `claimed` (taken, not dispatched yet), `running`, `reported` (the worker's report is in and passed the check), `in-review`, `ready` (its gates held when last read), `parked` (held; its pull request waits open, for a cap on open pull requests or for a person; never closed to make room), `merged`, `blocked`, `dropped`. What the coordinator did or saw last; not a host fact. | | Claimed by | The worker's name and the UTC time of the claim. `-` when nobody holds it. | | Branch, Worktree | Where the work is. `-` when it does not apply. | | PR | The number, as an identifier. Its state is read from the host when needed. | @@ -264,7 +266,12 @@ The `coordinate` preamble writes the session marker `/ - `hooks/pre-tool-use-agent` (PreToolUse on `Agent`, `Task`, `SendMessage`) adds one line of context when the prompt has no line starting with `# Brief: ` (the first line `ytstack-brief render` prints): the path is claim, render, dispatch. It never denies the call; a lookup that is no lane needs no brief. A `SendMessage` of up to 400 characters is a follow-up and is not checked. An `Agent` call of a lookup type (`Explore`, `Plan`, `claude-code-guide`, `statusline-setup`, a type naming search or explore) without a brief is neither warned about nor counted; every other `Agent` call is appended to `dispatches`; a task notification the prompt hook sees is appended to `reports`. - `hooks/stop` warns, once per session as a `systemMessage`, when `LANES.md` changed more than five minutes before the newest dispatch or report of the session (or does not exist although lanes were dispatched), and when the `STATE.md` pointer is behind the newest milestone on disk. A warning that comes in three sessions in a row (`YT_LINT_STREAK_N`; counter `/repos//coordinate-lints`) blocks the stop once in the third session. A session counts once when the finding was there at any of its stops (a session that begins with a status question and dispatches later counts); a session that ended without it breaks the row; overlapping sessions count once each. -Claude Code only: Codex registers no UserPromptSubmit or Agent hook of ytstack (its subagent tools are not covered), and Kimi's shell has no session id to write the marker with. +- `hooks/pre-tool-use-agent` also adds a line when an `Agent` call that is no lookup has no `isolation` (dispatch lane work with `isolation: "worktree"`), and, on `Bash`, when the command runs `gh pr merge` (the merge is `ytstack-finish-lane merge --at `) or `gh pr close` (a cap waits with the lane `parked`, a check reruns with `gh run rerun`). Advisory, never a deny: the person may have asked for that close. +- `hooks/pre-compact` counts the session's compactions in `compactions` beside the marker. After one, `hooks/session-start` says `Compaction N of this coordinator: ytstack:coordinate Step 12, rotate now`; from the second on, `hooks/stop` says it too, once per compaction. +- `hooks/post-tool-use-bash` adds one note when the output of `gh run list --branch ` shows a failed run (the tab-separated form, JSON `"conclusion": "failure"`, or the terminal form): a red main, run `ytstack:lesson`. One note per distinct set of failed lines. +- `hooks/stop` gives a coordinate session no reminder about the `STATE.md` task pointer: a coordinator holds no task. + +Claude Code only: Codex registers no UserPromptSubmit or Agent hook of ytstack (its subagent tools are not covered), its PreToolUse and PostToolUse entries on `Bash` run only the PR watch, and Kimi's shell has no session id to write the marker with. On both the skill text (HARD-GATE, Steps 5, 6 and 12) carries these rules without the hooks. ### `STANDING.md` diff --git a/skills/coordinate/SKILL.md b/skills/coordinate/SKILL.md index 63aee4b..3214996 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.6.2 + version: 0.7.0 allowed-tools: - Bash - Read @@ -18,7 +18,7 @@ allowed-tools: One session owns the plan and hands out all of the work. Its state lives in four places (`LANES.md`, the frontier, `questions/`, the standing instructions in `standing/` or `STANDING.md`; formats in `docs/ux/coordinator-format.md`), so it can lose its context, or be replaced by another session, person or host, and continue. It edits `.ytstack/` and pull request bodies. Nothing else. -Do NOT edit product code, tests or configuration, do NOT review a diff yourself, and do NOT state anything about a pull request, its checks or a deployed build that you did not read from the host for this statement. This applies to EVERY lane regardless of how small the change looks. +Do NOT edit product code, tests or configuration, do NOT review a diff yourself, and do NOT state anything about a pull request, its checks or a deployed build that you did not read from the host for this statement. Do NOT close a lane's pull request, reopen it to retrigger checks or delete its branch: a lane that waits for a cap is `parked` with its pull request open, a check reruns with `gh run rerun`, and only the person closes open work. This applies to EVERY lane regardless of how small the change looks. ## Anti-Pattern: "I know where the lanes stand" @@ -37,7 +37,7 @@ You MUST create a TodoWrite task for each of these items. Items 4 to 13 are one 2. **HARD-GATE** -- `.ytstack` and a sliced plan exist; this is the right skill 3. **Start from files** -- at the first start and after every compaction or resume 4. **Read host facts fresh** -- `ytstack-watch --once`, every fact with its read time -5. **Delegate what is ready** -- claim, render the brief, dispatch, check the report +5. **Delegate what is ready** -- `ytstack-frontier check` and an action for every `stale:` line first, then claim, render the brief, dispatch, check the report 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 @@ -231,7 +231,9 @@ ytstack-watch --pr --once One line per pull request (state, head, checks, newest review and its commit, mergeable or conflict) ending in `read `. That stamp travels with the fact wherever it is used. A deployed build is read with the command `RUNTIME.md` names, with its time. None of this is written into `.ytstack/` as current: `LANES.md` records what you did (dispatched, reviewed commit X) and identifiers (a branch, a number). `PR_HOST: none`: there is no host to read. Say that the picture rests on the files and on local git, and state nothing about pull requests. -**Step 5 -- Delegate what is ready.** Product code, reviews and research run in fresh-context workers. The order is the one of the operating checklist the preamble prints between `OPERATING_CHECKLIST_BEGIN` and `OPERATING_CHECKLIST_END`; in this session `hooks/pre-tool-use-agent` says so when an `Agent` prompt is no rendered brief, and the Stop hook says when `LANES.md` lags the dispatches and reports or the `STATE.md` pointer is behind, and holds the stop once when that came three sessions in a row. For each lane that `ytstack-frontier list --ready` prints: +**Step 5 -- Delegate what is ready.** Product code, reviews and research run in fresh-context workers. The order is the one of the operating checklist the preamble prints between `OPERATING_CHECKLIST_BEGIN` and `OPERATING_CHECKLIST_END`; in this session `hooks/pre-tool-use-agent` says so when an `Agent` prompt is no rendered brief, and the Stop hook says when `LANES.md` lags the dispatches and reports or the `STATE.md` pointer is behind, and holds the stop once when that came three sessions in a row; it also says when a dispatch has no `isolation`. + +Every round of this loop starts here, before `list --ready`: run `ytstack-frontier check`. Exit 0 prints `lanes ok`, exit 1 names the broken lines of `LANES.md` (repair them first), exit 2 prints one `stale:` line per lane that stalls. Each `stale:` line gets its action in this round, before any new dispatch: a running lane whose worktree is gone ended, so read its branch (`git log ..`) and set the row (`reported` when its report is in, else release it and claim it for a new worker on that branch); a lane without a commit or a report for too long gets one message at its worker's address asking for its state, and on the next `stale:` line for it the release and a new claim; a ready lane nobody claimed is claimed and dispatched now. A `stale:` line never releases a lane by itself, and it is never a reason to close a pull request. For each lane that `ytstack-frontier list --ready` prints: 1. `ytstack-frontier claim --by --kind --branch `. Claim before dispatch. A refused claim names the holder: do not dispatch. 2. `ytstack-brief render --slice --kind --branch --base ` (`--task` for a task lane, `--lesson F###` for a lesson lane `lesson-F###`, `--head ` for a review lane). The output is the worker's prompt, with the work contract and the report shape. Never write a brief by hand. @@ -242,7 +244,7 @@ A lane named in the `blocks:` of an open or asked question is not ready, whateve **Lesson lanes.** The frontier lists a lesson whose check is still to be built as `lesson-F###` after the slices (`docs/ux/coordinator-format.md`, "Lesson lanes"). It is dispatched like any lane, with `ytstack-signals set F### --state planned --ref lesson-F###` at the claim. A lesson lane listed as `blocked` with "unplanned" needs its `## Files` and `## Verification` first: write them into the lesson from what it says (the check, where it lives, the command that fails on what happened), as you write any file under `.ytstack/`. -**Step 6 -- Finish reported lanes.** A `reported` lane goes through `ytstack:finish-lane`: the review at a pinned head with the class its reviewer states, the route of the change, the gates read from the host, the merge at the reviewed commit or not at all. Who merges follows `merge_by` in `PREFERENCES.md`. With `risk`, the default, `finish-lane` merges a lane itself when `bin/ytstack-finish-lane route` printed `route: unattended` and the host's gates hold; every other lane stops at `ready` with its merge command and the reasons, and waits for a person. You state no class and you change no ceiling: the class is the reviewer's, the ceiling stands in the area file of the technical spec (`docs/ux/review-policy-format.md`). A change that requires lenses (`.ytstack/spec/REVIEW.md`) gets one more fresh reviewer per lens from `finish-lane`. A lens reviewer is a lane of kind `review` and never the lane's worker; a lens with visual evidence needs a session that can start the product and has a browser tool. One lane at a time per pull request. `finish-lane` writes the reviewed head and the round into the lane's row; a row that lacks them after a review is repaired before anything else (`ytstack-frontier set --head --round --pr `). Never merge around it. A cap on open pull requests, when the project or a standing instruction sets one, is a gate of `finish-lane`: a lane that waits for it stays where it is. +**Step 6 -- Finish reported lanes.** A `reported` lane goes through `ytstack:finish-lane`: the review at a pinned head with the class its reviewer states, the route of the change, the gates read from the host, the merge at the reviewed commit or not at all. Who merges follows `merge_by` in `PREFERENCES.md`. With `risk`, the default, `finish-lane` merges a lane itself when `bin/ytstack-finish-lane route` printed `route: unattended` and the host's gates hold; every other lane stops at `ready` with its merge command and the reasons, and waits for a person. You state no class and you change no ceiling: the class is the reviewer's, the ceiling stands in the area file of the technical spec (`docs/ux/review-policy-format.md`). A change that requires lenses (`.ytstack/spec/REVIEW.md`) gets one more fresh reviewer per lens from `finish-lane`. A lens reviewer is a lane of kind `review` and never the lane's worker; a lens with visual evidence needs a session that can start the product and has a browser tool. One lane at a time per pull request. `finish-lane` writes the reviewed head and the round into the lane's row; a row that lacks them after a review is repaired before anything else (`ytstack-frontier set --head --round --pr `). Never merge around it. A cap on open pull requests, when the project or a standing instruction sets one, is a gate of `finish-lane` and counts the pull requests that are ready for review; drafts do not count. A lane that waits for it is set to `parked` (`ytstack-frontier set --status parked --next "wait for the cap"`) and its pull request stays open. A pull request is never closed to get under the cap, and never closed and reopened to retrigger a check: `gh run rerun --failed` does that. **Step 7 -- Run the factory tools.** The plugin already ships what a coordinator under load starts to build by hand: a pull request babysitter, a review tiering, a release check. Use these tools and build none of your own. `ytstack:finish-lane` runs the route, the release watch and the escape check for the merges it makes (its Steps 9, 12 and 13), and the lesson of a blocked review or a red check of its lane (its Step 14); this step holds for everything else too: a merge you make yourself, a merge a person made, a release, a signal. A tool is skipped only for the reason in its row; the preamble prints the lines that decide it (`MERGE_BY`, `REVIEW_POLICY`, `OWN_REVIEWERS`, `PR_WATCH`, `RELEASE`, `SIGNALS`). @@ -288,7 +290,7 @@ Agent-private memory (a memory file, a note in your own context) is no substitut **Step 11 -- Report status.** Only when something changed that the human acts on (a question, a blocker, a finished plan, a lane that waits for his merge), or at a boundary he set in a standing instruction. No interim reports that work is running. A lane that merged without a person is no reason for a status of its own: the next status that is due names it in one line, with its class and the ceiling it merged under. A status is two to four full sentences with pointers (files, commits, pull request numbers). When the plan has gates it carries two numbers side by side, closed by work and accepted, as `ytstack:reassess-roadmap` counts them. Progress per phase comes from `ytstack-status --phases` (`--json` for a chart), never from a count by hand: it names every change of a total since the last report with its cause, so a grown total is not read as lost progress. When `LESSONS` counts open lessons, the status names them in one line as the preamble prints them (`lessons: 3 open (1 proposals, 2 checks to build)`), with the class of each one that counts 2 or more. Every host fact in it comes from a read made for this status and carries `read `. When the human asks where the lanes stand, answer per lane instead: the status and the next action of its row as written, then the open and asked questions with what they block. -**Step 12 -- Rotate.** When the session has been compacted once (a summary stands where the conversation was, or `HANDOFF_AUTO` is from this session), or its context is large by the host's indicator, rotate now. Do not wait for a quiet moment, for workers to report or for checks to finish: under load there is none, and a second compaction costs more than a rotation. It is one step, done in this order without dispatching anything in between: +**Step 12 -- Rotate.** When the session has been compacted once (a summary stands where the conversation was, or `HANDOFF_AUTO` is from this session), or its context is large by the host's indicator, rotate now. Do not wait for a quiet moment, for workers to report or for checks to finish: under load there is none, and a second compaction costs more than a rotation. In a coordinate session the SessionStart context after a compaction says `Compaction N of this coordinator: ytstack:coordinate Step 12, rotate now`, and from the second compaction on the Stop hook says it too: that line is this step, now. It is one step, done in this order without dispatching anything in between: 1. Bring the rows' next actions up to date, run `ytstack-frontier check` and `ytstack-questions check`, and make sure the standing instructions hold every instruction given so far. 2. Write `$_YT_DIR/HANDOFF.md` yourself in the format of `ytstack:handoff-session` (its Step 7), without its questions: the answers are in the files, and the handoff points at them. Its "In-flight work" carries the "Rotation" block of `docs/ux/coordinator-format.md`: `PR watch session:` with this session's id as the PR watch stores it (`echo "${CODEX_THREAD_ID:-claude:$CLAUDE_CODE_SESSION_ID}"`; `none` when `PR_WATCH` is `off`), `Background watches:` with the command of every `ytstack-watch` that runs in this session, and under `Running workers:` one line per worker that has not reported: lane, name, address (what the host gave you to reach it: the agent's id or name in Claude Code, another host's process id and log file), worktree, branch, dispatch time, and under `Peers:` the lines between `PEERS_BEGIN` and `PEERS_END` (`ytstack-frontier peer list`), so the successor writes to the right session of another repository. Its "Next action": start `ytstack:coordinate` in a fresh session; its Step 3 runs `ytstack-pr-watch handover --from `. diff --git a/skills/finish-lane/SKILL.md b/skills/finish-lane/SKILL.md index cf52a6c..1a6ad7e 100644 --- a/skills/finish-lane/SKILL.md +++ b/skills/finish-lane/SKILL.md @@ -3,7 +3,7 @@ name: finish-lane description: "Takes a delegated lane from the worker's report to a pull request merged at the reviewed commit, with every gate read from the host. Use in the coordinating session when a lane reported and its work has to become a merged pull request, or when the user says finish the lane, land this lane, get this lane merged. Not for the session's own branch (finish-branch), not for a release (ship) and not for the worker of the lane." metadata: tier: task - version: 0.5.0 + version: 0.6.0 allowed-tools: - Bash - Read @@ -17,7 +17,7 @@ allowed-tools: A lane is finished when its pull request is merged at the commit an independent review looked at. Between the worker's report and that merge lie a handful of steps. Each is one call of `bin/ytstack-finish-lane`, which prints what it did or what it read and refuses instead of assuming. Whether a person has to make the merge is decided per change, from the class its reviewer stated and from what the project declared (`docs/ux/review-policy-format.md`). After the merge the release is watched. This skill is for the session that dispatched the lane, not for the worker. -Do NOT commission a review before `wait-head` passed. Do NOT call a lane ready on anything but a `gates` read made in this run. Do NOT merge unless `MERGE_BY` is `coordinator`, or it is `risk` and a `route` call of this run printed `route: unattended` for the reviewed commit. Do NOT merge at all when a standing instruction reserves the merge. Do NOT record a class or a lens verdict that its reviewer did not report. Do NOT deploy, restart, revert or roll back anything on the target. +Do NOT commission a review before `wait-head` passed. Do NOT call a lane ready on anything but a `gates` read made in this run. Do NOT merge unless `MERGE_BY` is `coordinator`, or it is `risk` and a `route` call of this run printed `route: unattended` for the reviewed commit. Do NOT merge at all when a standing instruction reserves the merge. Do NOT record a class or a lens verdict that its reviewer did not report. Do NOT deploy, restart, revert or roll back anything on the target. Do NOT close the lane's pull request, reopen it to retrigger checks or delete its branch: a lane that waits for the cap is `parked` with its pull request open, a check reruns with `gh run rerun`. This applies to EVERY lane regardless of how small the diff is. @@ -352,7 +352,7 @@ The route speaks about the change, not about the host: the checks, the threads a "${CLAUDE_SKILL_DIR}/../../bin/ytstack-finish-lane" -C {WT} gates --pr {N} --reviewed-head {SHA} --verdict-pattern '^Verdict: approved' ``` -Add `--max-open {n}` when a standing instruction or the plan caps the open pull requests, and `--allow-no-checks` only when the project states that this repository runs no checks. The output is one line per gate (`ok` or `FAIL`) and a last line `read `. Keep both for the report. +Add `--max-open {n}` when a standing instruction or the plan caps the open pull requests (the gate counts the ones ready for review; drafts do not count), and `--allow-no-checks` only when the project states that this repository runs no checks. The output is one line per gate (`ok` or `FAIL`) and a last line `read `. Keep both for the report. All hold: `ytstack-frontier set {REF} --status ready --next "merge at {SHA}"`. Otherwise the failing gate says what happens next: @@ -363,7 +363,7 @@ All hold: `ytstack-frontier set {REF} --status ready --next "merge at {SHA}"`. O | `review` | changes are requested on this head, or the posted verdict is missing | Open findings go to the worker. A missing verdict means Step 7 did not happen on this head. | | `threads` | a review thread is unresolved | It is answered and resolved by whoever owns it: the worker for a finding in its code, the human for a question to them. You resolve no thread you did not open. | | `mergeable` | a conflict with the base, or the host has not decided | Conflict: the worker integrates the base; the head moves, so the fix round follows. Undecided: read again. | -| `open-prs` | more pull requests are open than the cap | Finish others first. The lane stays where it is. | +| `open-prs` | more pull requests are ready for review than the cap | Finish others first. The lane waits as `parked` (`"${CLAUDE_SKILL_DIR}/../../bin/ytstack-frontier" set {REF} --status parked --next "wait for the cap"`) with its pull request open; none is closed to make room. | ### Step 11: Merge or hand over diff --git a/tests/skill-preambles.test.sh b/tests/skill-preambles.test.sh index b6b511f..06a1016 100644 --- a/tests/skill-preambles.test.sh +++ b/tests/skill-preambles.test.sh @@ -368,6 +368,19 @@ PEERS_END" rm -rf "$WT/.ytstack/signals" awk '/^\*\*Step 5 --/ { p = 1 } /^\*\*Step 6 --/ { p = 0 } p' "$ROOT/skills/$s/SKILL.md" | grep_q -F -- '--lesson F###' \ && ok "$s: Step 5 renders the brief of a lesson lane" || bad "$s: Step 5 renders the brief of a lesson lane" + # issue #83: every round starts with the liveness check; a cap waits, nothing is closed + awk '/^\*\*Step 5 --/ { p = 1 } /^\*\*Step 6 --/ { p = 0 } p' "$ROOT/skills/$s/SKILL.md" > "$TMP/step5.md" + for want in 'ytstack-frontier check' 'stale:' 'exit 2'; do + grep_q -F -- "$want" "$TMP/step5.md" && ok "$s: Step 5 runs $want" || bad "$s: Step 5 runs $want" + done + awk '/^\*\*Step 6 --/ { p = 1 } /^\*\*Step 7 --/ { p = 0 } p' "$ROOT/skills/$s/SKILL.md" | grep_q -F -- '--status parked' \ + && ok "$s: Step 6 parks a lane that waits for the cap" || bad "$s: Step 6 parks a lane that waits for the cap" + awk '/^/ { p = 1 } /^<\/HARD-GATE>/ { p = 0 } p' "$ROOT/skills/$s/SKILL.md" > "$TMP/gate.md" + for want in 'close' 'gh run rerun' 'parked'; do + grep_q -F -- "$want" "$TMP/gate.md" && ok "$s: HARD-GATE names $want" || bad "$s: HARD-GATE names $want" + done + awk '/^\*\*Step 12 --/ { p = 1 } /^\*\*Step 13 --/ { p = 0 } p' "$ROOT/skills/$s/SKILL.md" | grep_q -F 'Compaction N of this coordinator' \ + && ok "$s: Step 12 names the compaction line" || bad "$s: Step 12 names the compaction line" awk '/^\*\*Step 8 --/ { p = 1 } /^\*\*Step 9 --/ { p = 0 } p' "$ROOT/skills/$s/SKILL.md" | grep_q -F 'daily question' \ && ok "$s: Step 8 asks a lesson proposal with the daily question" || bad "$s: Step 8 asks a lesson proposal with the daily question" awk '/^\*\*Step 11 --/ { p = 1 } /^\*\*Step 12 --/ { p = 0 } p' "$ROOT/skills/$s/SKILL.md" | grep_q -F 'LESSONS' \ @@ -421,6 +434,12 @@ PY sed -n '1,40p' "$ROOT/bin/$tool" | grep_q -w -- "$sub" && ok "$s: $tool $sub is in its usage" || bad "$s: $tool $sub is in its usage" done < "$TMP/step7.cmds" ;; finish-lane) + # issue #83: never close or reopen a lane's pull request; the cap counts ready ones + awk '/^/ { p = 1 } /^<\/HARD-GATE>/ { p = 0 } p' "$ROOT/skills/$s/SKILL.md" > "$TMP/gate.md" + for want in 'close' 'gh run rerun' 'parked'; do + grep_q -F -- "$want" "$TMP/gate.md" && ok "$s: HARD-GATE names $want" || bad "$s: HARD-GATE names $want" + done + grep_q -F 'ready for review' "$ROOT/skills/$s/SKILL.md" && ok "$s: the cap counts pull requests ready for review" || bad "$s: the cap counts pull requests ready for review" # who merges (M025): risk unless PREFERENCES says otherwise; a typo reads as human has "$s: no merge_by in PREFERENCES -> risk" "$OUT" "MERGE_BY: risk" printf 'merge_by: coordinater\n' > "$WT/.ytstack/PREFERENCES.md" From 684dc5fc293dcfccdf16efb7844f65eeafb1d52d Mon Sep 17 00:00:00 2001 From: Alex Wegener Date: Sun, 15 Nov 2026 19:53:51 +0100 Subject: [PATCH 04/13] docs: spec, DECISIONS and CHANGELOG for the coordinator path (#82, #83) Co-Authored-By: Claude Opus 5.5 --- .ytstack/DECISIONS.md | 22 +++++++++++++++++++++ .ytstack/spec/checks-and-evals.md | 6 +++--- .ytstack/spec/hooks-and-state.md | 31 +++++++++++++++--------------- .ytstack/spec/skills.md | 6 +++--- CHANGELOG.md | 32 +++++++++++++++++++++++++++++++ 5 files changed, 75 insertions(+), 22 deletions(-) diff --git a/.ytstack/DECISIONS.md b/.ytstack/DECISIONS.md index 0fd25f9..04c1466 100644 --- a/.ytstack/DECISIONS.md +++ b/.ytstack/DECISIONS.md @@ -1377,3 +1377,25 @@ Plus: ops-layer split during the same session (yopstack created as own public re **Reason:** "Merged" is the one state in which a person looked at the command (a change under `standing/` goes to a person). C would drop the compliance check of issue #74. Starting the new day from the pending branch keeps one pull request per day and lets `end`/`--supersedes` see what waits; the cost is that a day's pull request carries the earlier day's commits until that one merges. **Supersedes:** Narrows "2026-11-15: Standing entries end by `until` ...": the commands run only for merged entries. + +## 2026-11-15: Hooks read a stale checkout from origin, say a reminder once per session and pointer, and keep a coordinator on its path with hints, not denies (issues #82, #83) + +**Context:** In a four-day coordinator run the Stop hook sent the same "M034-S04-T05 has no summary" 1,645 times and nobody acted on it: the coordinator's `main` was 168 commits behind `origin/main`, so every hook read a stale `STATE.md`, a coordinator holds no task anyway, and SessionStart cut the Next action for the `using-ytstack` body (#82). The same run merged 509 pull requests with `gh pr merge` by hand, dispatched 603 agents without `isolation`, rotated 0 times across 23 compactions, ran no lesson for 57 red `main` reads, and closed 14 pull requests, some to fit under the open-PR cap and some to retrigger CI (#83). + +**Options considered:** +- For the stale checkout: `git fetch` in the hook; local refs only and `STATE.md` read from `origin/`; only a warning. +- For the repetition: a block after N repeats; once per (session, pointer) plus a lint line for an old pointer. +- For the budget: the Next action before the directive in the text; the `using-ytstack` body yields before the Next action. +- For the coordinator path: PreToolUse denies on `gh pr merge` / `gh pr close`; advisory `additionalContext` lines in the existing coordinate-mode hooks; skill text only. +- For a waiting pull request: a new `parked` lane status; keep `ready`. + +**Chose:** Local refs only: on the default branch behind `origin/` both hooks read pointer and Next action from `git show origin/:.ytstack/STATE.md` and say "N commit(s) behind" with `git merge --ff-only` (`yt_behind_origin`). The Stop reminder is said once per session and pointer (`stop-said` under the session home), never in coordinate mode, and a pointer whose `last_updated` is older than `YT_POINTER_STALE_DAYS` (3) days is lint W10 instead. In the SessionStart budget the Next action excerpt is no longer cut; the `using-ytstack` body is the last block to yield, cut at a line with a pointer to its file. A manual handoff older than the automatic one is listed as older. In coordinate mode, advisory lines only: `hooks/pre-tool-use-agent` (now also on `Bash`) on an `Agent` without `isolation`, on `gh pr merge` and on `gh pr close`; `hooks/pre-compact` counts compactions beside the marker, SessionStart says "Compaction N of this coordinator: ... rotate now" and Stop repeats it once per compaction from the second; `hooks/post-tool-use-bash` notes `ytstack:lesson` for a failed run in `gh run list --branch `. `coordinate` and `finish-lane` get a hard-gate sentence: never close, reopen to retrigger or delete the branch of a lane's pull request. `parked` is a held lane status for a pull request that waits open; the `open-prs` gate counts pull requests ready for review. Coordinate Step 5 starts every round with `ytstack-frontier check` and acts on each `stale:` line. + +**Reason:** A fetch in a hook is a network call under a 5-10 s budget and can hang; the stale checkout is visible from local refs, and the origin ref is what the person merged. A reminder nobody acts on after the first time is noise that trains the agent to ignore the hook; once per pointer keeps the signal, the lint keeps the old pointer visible at the next start without a loop. The Next action is what a session needs first; the directive's tail is a file read away. A deny would also stop a close or merge the person asked for, and the hooks cannot tell; a hint on the exact command makes the bypass visible (as #76 chose for briefs). `parked` keeps a waiting pull request distinguishable from a lane that is ready to merge, and drafts are no review load. The liveness check existed (#84) but ran only at rotation; the loop is where stalls happen. + +**How to apply:** +- No hook fetches. `stop-said` is the only session-home file a non-coordinate session gets; everything else of #83 needs the coordinate marker. +- Codex and Kimi: not covered by the hooks (Codex has ytstack `Bash` hooks only for the PR watch and none on its subagent tools; Kimi has no session id for the marker); the skill text carries the rules. +- A new held status is added to `HELD` in `bin/ytstack-frontier`, to the held lists of `bin/ytstack-upkeep` and to the in-review count of `bin/ytstack-status`. + +**Supersedes:** None. Extends "2026-11-15: In coordinate mode the operating path is injected and checked by hooks that warn ..." with four more hints, and changes the SessionStart cap order of "2026-11-15: Standing entries end by `until` ..." (How to apply, third point): the standing lines are no longer cut after the Next action, the `using-ytstack` body is cut last instead. diff --git a/.ytstack/spec/checks-and-evals.md b/.ytstack/spec/checks-and-evals.md index 9cdb88c..86fea84 100644 --- a/.ytstack/spec/checks-and-evals.md +++ b/.ytstack/spec/checks-and-evals.md @@ -92,10 +92,10 @@ Everything that tells a contributor whether a change is acceptable: the static c **The coordinator scripts** (formats and rules: `docs/ux/coordinator-format.md`; each has a suite of the same name under `tests/`) -- `bin/ytstack-frontier`: `list` prints lane, state and detail per slice (done, claimed, blocked, ready) of the current milestone (with `none`: the highest roadmap not `done`, `dropped`, `shipped-informally` or `backlog`), then one lesson lane `lesson-F###` per open or planned lesson whose target is a check (blocked without non-empty "Files" and "Verification" in the lesson; listed also without a milestone); `claim` refuses a held lane and names the holder; `claim`, `set` and `release` change one row of `LANES.md` under a lock; `check` validates the file and then prints one `stale:` line per lane that stalls, exit 2 (issue #84): a `running` row whose worktree no longer exists, an `implement` row whose branch had no commit for `--minutes` (default 60, from the claim when that is newer, or from the first sight of its fix round when the row carries a pull request), a `review` or `prepare` row running 3 x `--minutes` since its claim, and a `ready` lane nobody claimed for `--minutes` since a check first saw it (first sights in `/repos//frontier-seen`, outside the tree, under a noclobber lock); `peer set` and `peer list` keep the `## Peers` lines of `LANES.md` (role, repository, address, last contact), list items that no table reader sees. The lock is the file `LANES.md.lock`, created by the shell under noclobber and not by `mkdir`, which is no lock on Ubuntu 26.04 (see `.ytstack/KNOWLEDGE.md`). +- `bin/ytstack-frontier`: `list` prints lane, state and detail per slice (done, claimed, blocked, ready) of the current milestone (with `none`: the highest roadmap not `done`, `dropped`, `shipped-informally` or `backlog`), then one lesson lane `lesson-F###` per open or planned lesson whose target is a check (blocked without non-empty "Files" and "Verification" in the lesson; listed also without a milestone); `claim` refuses a held lane and names the holder (held: `claimed`, `running`, `reported`, `in-review`, `ready`, and `parked`, a lane whose pull request waits open for a cap or a person, issue #83); `claim`, `set` and `release` change one row of `LANES.md` under a lock; `check` validates the file and then prints one `stale:` line per lane that stalls, exit 2 (issue #84): a `running` row whose worktree no longer exists, an `implement` row whose branch had no commit for `--minutes` (default 60, from the claim when that is newer, or from the first sight of its fix round when the row carries a pull request), a `review` or `prepare` row running 3 x `--minutes` since its claim, and a `ready` lane nobody claimed for `--minutes` since a check first saw it (first sights in `/repos//frontier-seen`, outside the tree, under a noclobber lock); `peer set` and `peer list` keep the `## Peers` lines of `LANES.md` (role, repository, address, last contact), list items that no table reader sees. The lock is the file `LANES.md.lock`, created by the shell under noclobber and not by `mkdir`, which is no lock on Ubuntu 26.04 (see `.ytstack/KNOWLEDGE.md`). - `bin/ytstack-plans` (`docs/ux/external-plans.md`): `scan` counts the work rows (task-list items, rows of tables with a status or checkbox column, nothing in a code fence) of `plans/`, `roadmap/` and their variants and prints one line per directory with `verdict=large` from 10 open rows and the answer recorded in `PREFERENCES.md`; exit 0 only for a large directory without an answer. `rows` prints `path:line`, state, id, section and title per row; a relative PATH is read from where the command was started, else from the repository root, and the output names files relative to the root. It writes nothing; the mapping is the agent's (`reconcile`, `adopt-brownfield`). - `bin/ytstack-questions`: `new`, `list`, `next`, `ask` (once), `answer` (refused without text under "Answer"), `check`. `bin/ytstack-standing` (`docs/ux/coordinator-format.md`, "standing/"): `add` writes one entry, validated by `ytstack-check --standing` before anything is committed, by default in its own worktree outside the checkout on `standing/` with a commit, a push and one pull request per UTC day (opened through `ytstack-pr-watch create` when `pr_watch=on` and the session has an id, else `gh pr create`; updated when one is open); `--here` and user scope write into the resolved directory only; exit 3 when the commit stands but the push or the PR failed; a new day's branch starts from the newest pending standing branch, an earlier one with unpushed commits is pushed first. `end` writes the closing entry of `kind: end`, also of a pending entry. `list` prints the newest entry's age and the human prompts since (from the coordinate session's counter), the active entries with the pending ones marked (local `standing/*` branches and their upstreams only), then the ended ones, the conditions to check and the failed checks; it is the only place `until-check` and `check` run, and only for a working-tree entry identical to the default branch's (bash in its own process group, killed on timeout, stdin closed, `YTSTACK_STANDING_TIMEOUT` seconds each, default 5, at most ten per call, every one not run says why), `--no-checks` runs none. Its suite uses a stand-in for `gh`, a local bare remote behind an `insteadOf` URL and the real `ytstack-pr-watch create`. -- `bin/ytstack-finish-lane`: one step per call (`leftovers`, `commit`, `push`, `open-pr`, `wait-head`, `body-check`, `gates`, `merge`, `route`); every gate is read from GitHub through `gh` at the moment of the call, and `merge` passes the reviewed commit to the host so that a moved head cannot be merged. `route --lane [--pr ]` reads the lane's worker (the author) and plan from `LANES.md` and runs `bin/ytstack-risk route`; with `--pr` it passes the pull request on, and a lane without a plan file is routed from the host's reviews. `leftovers` and `commit` leave the evidence directory out. Its suite uses a stand-in for `gh` and a local bare remote. +- `bin/ytstack-finish-lane`: one step per call (`leftovers`, `commit`, `push`, `open-pr`, `wait-head`, `body-check`, `gates`, `merge`, `route`); every gate is read from GitHub through `gh` at the moment of the call, and `merge` passes the reviewed commit to the host so that a moved head cannot be merged. The `open-prs` gate (`--max-open`) counts the open pull requests that are ready for review, drafts not, and fails when more than 100 are open (only those are read; issue #83). `route --lane [--pr ]` reads the lane's worker (the author) and plan from `LANES.md` and runs `bin/ytstack-risk route`; with `--pr` it passes the pull request on, and a lane without a plan file is routed from the host's reviews. `leftovers` and `commit` leave the evidence directory out. Its suite uses a stand-in for `gh` and a local bare remote. - `bin/ytstack-handover`: `new` copies `skills/handover-step/template.sh`; `check` is the static verification of a staged script (syntax, unchanged helper block, no raw command, a confirmation of its own before every mutation, no pipe into a shell). The helpers hold the same rule when the script runs: one yes carries one change. - `bin/ytstack-watch`: polls pull requests through `gh` and prints a line only when head, checks, review or mergeability changed; `--once` prints the snapshot with its read time. `release --commit ` runs `deployed` of "Release" until it names the commit (or `--timeout`, default 900 s), then `healthy` for the settle time, and ends with five receipt lines (`Target:`, `Commit:`, `Arrived:`, `Health:`, `Result:`) with read times. Exit 0 released or no health command, 2 not arrived, 3 unhealthy, 4 no "Release" section, 1 `RUNTIME.md` fails its check. It runs only those two commands and changes nothing. @@ -188,7 +188,7 @@ Not covered by these checks: `claude plugin eval` (costs money). `bash tests/run - DECISIONS.md -- "2026-11-13: Production findings and incidents are skill work on read-only access; a mitigation is a handover script a person runs (M027)". Source of `bin/ytstack-signals`. "2026-11-15: Feedback about ytstack itself goes through one channel with a setting; a script checks the body, the agent posts (M033-S01, issue #55)" is the source of `bin/ytstack-upstream`. - DECISIONS.md -- "2026-11-13: The technical spec is a set of artifacts of its own under `.ytstack/spec/` (M022, issue #36)". Source of `bin/ytstack-spec` and the two spec checks. - DECISIONS.md -- "2026-11-13: Verification, review and orchestration work are bounded like code (M023, issue #35)". Source of `bin/ytstack-brief`. -- DECISIONS.md -- "2026-11-13: Coordinator mode keeps lanes, questions and standing instructions in files and reads host facts fresh (M024, issue #34)". Source of the five coordinator scripts; the pipeline and the watcher support GitHub through `gh` only. Extended by "2026-11-14: Standing instructions are one file per entry in `.ytstack/standing/`; `STANDING.md` stays valid (issue #57)", the source of `check_standing`, by "2026-11-15: Standing entries end by `until`, `until-condition` or `until-check` and are closed by an entry of `kind: end`; their commands run only in `ytstack-standing list` (issues #73, #74)", the source of `bin/ytstack-standing` and the optional keys of `check_standing`, and by "2026-11-15: A plan outside `.ytstack/` is detected by a script and mapped by the agent, after one question (M031-S05, issue #54)", the source of `bin/ytstack-plans`. +- DECISIONS.md -- "2026-11-13: Coordinator mode keeps lanes, questions and standing instructions in files and reads host facts fresh (M024, issue #34)". Source of the five coordinator scripts; the pipeline and the watcher support GitHub through `gh` only. Extended by "2026-11-14: Standing instructions are one file per entry in `.ytstack/standing/`; `STANDING.md` stays valid (issue #57)", the source of `check_standing`, by "2026-11-15: Standing entries end by `until`, `until-condition` or `until-check` and are closed by an entry of `kind: end`; their commands run only in `ytstack-standing list` (issues #73, #74)", the source of `bin/ytstack-standing` and the optional keys of `check_standing`, and by "2026-11-15: A plan outside `.ytstack/` is detected by a script and mapped by the agent, after one question (M031-S05, issue #54)", the source of `bin/ytstack-plans`, and by "2026-11-15: Hooks read a stale checkout from origin, say a reminder once per session and pointer, and keep a coordinator on its path with hints, not denies (issues #82, #83)", the source of `parked` and of the `open-prs` count. - DECISIONS.md -- "2026-04-23: UX contracts enforced by CI, not convention" - DECISIONS.md -- "2026-05-31: Add `kind: reference` skill class (exempt from procedure-section contract)" - DECISIONS.md -- "2026-11-07: Hooks never write relative to CLAUDE_PROJECT_DIR; volatile state lives out-of-tree, per session and per worktree". Source of the banned shell patterns and the shared-resolver rule in the checker. diff --git a/.ytstack/spec/hooks-and-state.md b/.ytstack/spec/hooks-and-state.md index 5636d1b..9205619 100644 --- a/.ytstack/spec/hooks-and-state.md +++ b/.ytstack/spec/hooks-and-state.md @@ -37,7 +37,7 @@ The lifecycle hooks under `hooks/` and the shared library `hooks/lib/git-ctx.sh` - `yt_commit_ref_pattern` renders a task's commit pattern from `commit_ref_pattern` in `PREFERENCES.md`, or from the default. `yt_task_commits` lists commits whose subject matches it. When none match, it falls back to the commits on the current branch after the merge-base with the default branch, and reports which source it used. - `yt_find_artifacts` lists artifacts newest first from the flat layout and from the alternative layouts named in its comment. Reading tolerates those layouts. `yt_artifact_dir` and `yt_artifact_path` say where a milestone's files live and where its new ones go: the directory that already holds its roadmap or files, else flat ([artifacts.md](artifacts.md), "Location and scope"). `post-tool-use-bash`, `task-completed`, `stop`, `pre-tool-use-edit` and `session-start` find the milestone's files through them; `task-created` and `teammate-idle` list its slice plans in every layout through `yt_find_artifacts`, one per name, so a plan that landed flat before the milestone moved counts too. - `yt_factory_notices` returns one line per factory tool that is off although the project would use it, from local files only: risk routing (`spec/` without `REVIEW.md` or without an area whose frontmatter allows `auto_merge: low|normal`, quotes allowed, read with `yt_fm`, the reader `bin/ytstack-risk` uses; while `merge_by` is `risk`), the PR watch on a GitHub `origin` (no line in `~/.ytstack/config` that turns the hook on, read as `hooks/pr-watch` does: any `pr_watch=on` line; or `on` with a heartbeat missing or 10 minutes old; `yt_pr_watch_heartbeat` reads `watch.sqlite3`, else the time of `worker.lock`), and `RUNTIME.md` without "Release" or "Signals" while deploy or signal evidence exists (`ytstack-runtime sections`). `merge_by: human|coordinator` and `pr_watch=off` are choices and stay silent. `yt_read_stdin` also sets `YT_SOURCE`. -- `yt_standing` lists the standing instructions in force from `.ytstack/standing/` (name, `given`, `scope`, tab separated), newest first by the time in the name (missing seconds count as `00`), without the entries another entry names in `supersedes`, without entries of `kind: end` and without entries whose `until` has passed. It prints nothing without the directory; `STANDING.md` is read by the skills themselves. `yt_standing_fields` prints the same entries with every key, the first sentence of the body, `active` or `expired`, the source and the whole body on one line (`-` for an empty value); with `pending` as third argument also the entries of `yt_standing_pending` (on a local `standing/*` branch or the upstream it tracks, not in the working tree, not on `yt_standing_default_ref`), read with `git show`, source `pending:`. `yt_standing_default_ref` is `origin/HEAD`, else `origin/main`, `origin/master`, `main`, `master`. `yt_standing_lines [max] [full]` prints the active ones for a role (with `full` the whole body, for briefs) (`docs/ux/coordinator-format.md`, "Scope and roles"), pending ones included and marked, as `- (): `, with a pointer line past `max`. None of them runs a command of an entry. `yt_latest_handoff` (for skill preambles) finds the newest `latest-handoff` of the worktree under every base a hook may have used: `CLAUDE_PLUGIN_DATA`, `PLUGIN_DATA`, each `~/.claude/plugins/data/ytstack*` and the XDG base. `coordinate` and `resume-session` use it; before, they looked under `yt_state_base` only, which in the Bash tool is not where the hook wrote. `yt_session_home` is `${XDG_STATE_HOME:-~/.local/state}/ytstack/sessions`: per-session state that a hook and the Bash tool of the same session both find (`CLAUDE_PLUGIN_DATA` reaches hooks only). It holds the coordinate marker (the resolved `.ytstack` on line 1, the repository key on line 2, which keys the lint counter also in user scope), the prompt counter and the standing flags of a session. +- `yt_standing` lists the standing instructions in force from `.ytstack/standing/` (name, `given`, `scope`, tab separated), newest first by the time in the name (missing seconds count as `00`), without the entries another entry names in `supersedes`, without entries of `kind: end` and without entries whose `until` has passed. It prints nothing without the directory; `STANDING.md` is read by the skills themselves. `yt_standing_fields` prints the same entries with every key, the first sentence of the body, `active` or `expired`, the source and the whole body on one line (`-` for an empty value); with `pending` as third argument also the entries of `yt_standing_pending` (on a local `standing/*` branch or the upstream it tracks, not in the working tree, not on `yt_standing_default_ref`), read with `git show`, source `pending:`. `yt_standing_default_ref` is `origin/HEAD`, else `origin/main`, `origin/master`, `main`, `master`. `yt_standing_lines [max] [full]` prints the active ones for a role (with `full` the whole body, for briefs) (`docs/ux/coordinator-format.md`, "Scope and roles"), pending ones included and marked, as `- (): `, with a pointer line past `max`. None of them runs a command of an entry. `yt_latest_handoff` (for skill preambles) finds the newest `latest-handoff` of the worktree under every base a hook may have used: `CLAUDE_PLUGIN_DATA`, `PLUGIN_DATA`, each `~/.claude/plugins/data/ytstack*` and the XDG base. `coordinate` and `resume-session` use it; before, they looked under `yt_state_base` only, which in the Bash tool is not where the hook wrote. `yt_session_home` is `${XDG_STATE_HOME:-~/.local/state}/ytstack/sessions`: per-session state that a hook and the Bash tool of the same session both find (`CLAUDE_PLUGIN_DATA` reaches hooks only). It holds the coordinate marker (the resolved `.ytstack` on line 1, the repository key on line 2, which keys the lint counter also in user scope), the prompt counter and the standing flags of a session. `yt_behind_origin [yt_dir]` (issue #82) says whether the checkout is on the default branch (`yt_standing_default_ref`, only when that is an `origin` ref) and behind it, from local refs only, never a fetch (an `origin/` that was never fetched counts as current): `YT_BEHIND_N` (0 when not), `YT_BEHIND_REF` (`origin/`) and `YT_BEHIND_STATE`, the `STATE.md` of that ref when the `.ytstack` lies inside the checkout. ### STATE lint and progress block @@ -55,8 +55,9 @@ The lifecycle hooks under `hooks/` and the shared library `hooks/lib/git-ctx.sh` | W7 | the `progress` block is malformed, one finding per problem | | W8 | `STATE.md` is larger than `YT_STATE_MAX_BYTES` (set beside the function): it is a pointer, not a ledger | | W9 | `STATE.md` carries status paragraphs beside the current one (`**Previous ...**`, `**Prior ...**`, a second `**Status ...**`) | +| W10 | an active task is set and `last_updated` is older than `YT_POINTER_STALE_DAYS` days (default 3) | -W8 and W9 are prompts for `ytstack:reconcile`, which moves history out with consent. No skill stops on them. +W8 and W9 are prompts for `ytstack:reconcile`, which moves history out with consent. No skill stops on them, nor on W10: `hooks/stop` leaves such a pointer to this line instead of a message at every stop. W10 reads `last_updated`, not the time the pointer itself last changed; an edit that bumps `last_updated` without moving the pointer resets it. `yt_progress_parse` is the only parser of the optional `progress` block in the `STATE.md` frontmatter. It reports `none`, `ok` or `bad`. The lint and `bin/ytstack-status` both call it, so they agree on what is malformed. @@ -71,12 +72,12 @@ Every hook except `pr-watch` sources the library and resolves from the payload ` | `session-start` | SessionStart | `cwd`, `source` | prints the injection as JSON on stdout, writes nothing | 0 | | `version-notice` | UserPromptSubmit (first entry) | `session_id` | records the plugin version of the session's first prompt in `/sessions//plugin-version`; when the installed version (`installed_plugins.json` entries of this root's marketplace with scope `user`, or `project`/`local` whose `projectPath` is the session's project; else the newest cache sibling without `.orphaned_at`) is newer, prints once per installed version "ytstack X installed, this session loaded A: reload the skills you use" and the CHANGELOG entry titles in between (cut at 600 characters), and writes `notified-` after the notice was printed | 0 | | `standing-prompt` | UserPromptSubmit (second entry) | `session_id`, `prompt` | only with the coordinate marker `//coordinate`: appends the epoch of every human prompt (not one that starts with `<`) to `prompts`; a prompt that reads like a standing instruction (instruction phrases in the script, English and German; a prompt that is only one question never) goes into `standing-flags` and gets one line of `additionalContext`: record it with `ytstack-standing add` before the next dispatch | 0 | -| `pre-compact` | PreCompact | `cwd`, `session_id`, `trigger` | writes `HANDOFF.auto.md` into the session state directory, renames a fresh `latest-handoff` symlink into the worktree state directory, prints compaction guidance on stdout | 0 | +| `pre-compact` | PreCompact | `cwd`, `session_id`, `trigger` | writes `HANDOFF.auto.md` into the session state directory, renames a fresh `latest-handoff` symlink into the worktree state directory, prints compaction guidance on stdout; with the coordinate marker appends the epoch to `compactions` beside it (issue #83) | 0 | | `session-end` | SessionEnd | `cwd`, `session_id`, `reason` | appends one JSON line to `session.jsonl` in the session state directory | 0 | -| `stop` | Stop | `cwd`, `session_id`, `stop_hook_active` | prints a `systemMessage` when the active task has no summary or only a draft; with the coordinate marker and flagged prompts not handled yet, `decision: block` once when no standing entry exists since the first of them (working tree, or added on any ref after it), then writes `standing-stop`; with the marker also the coordinate lints: a `systemMessage` once per session when `LANES.md` lags the session's dispatches and reports by more than five minutes or the STATE pointer is behind (W2), and a block once when the same lint came in `YT_LINT_STREAK_N` (3) sessions in a row, a session counting once when the lint was there at any of its stops, overlapping sessions once each (counter `/repos//coordinate-lints`) | 0 | -| `pre-tool-use-agent` | PreToolUse on `Agent`, `Task`, `SendMessage` | `session_id`, `tool_name`, the prompt or message, `subagent_type` | only with the coordinate marker: appends every `Agent` call to `dispatches` except a lookup type (`Explore`, `Plan`, `claude-code-guide`, `statusline-setup`, a type naming search or explore) without a brief; a prompt without a line starting with `# Brief: ` (a `SendMessage` only above 400 characters) gets one line of `additionalContext` naming claim, render, dispatch; never a permission decision | 0 | +| `stop` | Stop | `cwd`, `session_id`, `stop_hook_active` | prints a `systemMessage` when the active task has no summary or only a draft, once per session and pointer (`stop-said`), not with the coordinate marker and not for a pointer the lint reports as W10; on the default branch behind `origin/` instead one message per origin head with the count and the pointer of origin's `STATE.md` (issue #82); with the coordinate marker from the second compaction one reminder per compaction to rotate (Step 12, `rotate-said`; issue #83); with the coordinate marker and flagged prompts not handled yet, `decision: block` once when no standing entry exists since the first of them (working tree, or added on any ref after it), then writes `standing-stop`; with the marker also the coordinate lints: a `systemMessage` once per session when `LANES.md` lags the session's dispatches and reports by more than five minutes or the STATE pointer is behind (W2), and a block once when the same lint came in `YT_LINT_STREAK_N` (3) sessions in a row, a session counting once when the lint was there at any of its stops, overlapping sessions once each (counter `/repos//coordinate-lints`) | 0 | +| `pre-tool-use-agent` | PreToolUse on `Agent`, `Task`, `SendMessage`, `Bash` | `session_id`, `tool_name`, the prompt or message, `subagent_type`, `isolation`, the command | only with the coordinate marker: appends every `Agent` call to `dispatches` except a lookup type (`Explore`, `Plan`, `claude-code-guide`, `statusline-setup`, a type naming search or explore) without a brief; a prompt without a line starting with `# Brief: ` (a `SendMessage` only above 400 characters) gets one line of `additionalContext` naming claim, render, dispatch; an `Agent` call that is no lookup and has no `isolation` one line naming `isolation: "worktree"`; a `Bash` command that runs `gh pr merge` or `gh pr close` after a command separator (wrapper tokens as in `post-tool-use-bash`) one line naming `ytstack-finish-lane merge`, or `parked` and `gh run rerun` (issue #83); never a permission decision | 0 | | `pre-tool-use-edit` | PreToolUse on `Edit`, `Write`, `MultiEdit` | `cwd`, target path | prints a drift warning on stderr | 0 | -| `post-tool-use-bash` | PostToolUse on `Bash` | `cwd`, command, exit code | creates a draft task summary once | 0 | +| `post-tool-use-bash` | PostToolUse on `Bash` | `cwd`, command, exit code, `tool_response.stdout` | creates a draft task summary once; with the coordinate marker, a `gh run list --branch ` (or `-b`) whose output has a failed run (tab-separated `completed`/`failure`, `timed_out` or `startup_failure`, JSON `"conclusion"` with one of them, or a line starting with `X `) gets one `additionalContext` note to run `ytstack:lesson`, once per distinct set of those lines (`red-main-said`; issue #83) | 0 | | `task-created` | TaskCreated | `cwd`, subject, description | prints a scope warning on stderr | 2 on drift, else 0 | | `task-completed` | TaskCompleted | `cwd`, subject | writes an auto summary, ticks the slice plan checkbox | 0 | | `teammate-idle` | TeammateIdle | `cwd` | prints the open task count on stderr | 2 while tasks are open, else 0 | @@ -84,17 +85,16 @@ Every hook except `pr-watch` sources the library and resolves from the payload ` - `pre-tool-use-edit` skips paths under `.ytstack/` and the artifact file names listed in the script. Scope drift means: the active task has a plan, and neither the checkout-relative path nor its basename occurs anywhere in that plan. Schema drift means: the target matches a model or schema pattern from the script and the plan names no migration path. - `post-tool-use-bash` acts only when all of this holds: the call succeeded, the command contains a real `git commit` (after a command separator, optionally behind the wrapper tokens the script lists), `STATE.md` names an active slice and task, HEAD's subject matches the task's commit pattern, and no summary file exists. The stub carries `closed: draft`. - `task-created` runs only with an active milestone. It extracts file-like paths from subject and description. Drift is a path that occurs in no slice plan of the current milestone and not in its roadmap. -- `task-completed` needs an `M###-S##-T##` id in the task subject. It never overwrites an existing summary. -- `teammate-idle` counts unchecked `T##` checkboxes across the slice plans of the current milestone. -- `stop` speaks only when milestone, slice and task are all set and the task's summary is missing or a draft, or when the standing check blocks. It stays silent when `stop_hook_active` is true. The standing check counts an entry whose name time is in or after the minute of the first unhandled flagged prompt, in the working tree's `standing/` or in `git log --all --since= --diff-filter=A` of the repository; local git only, no host call. +- `task-completed` needs an `M###-S##-T##` id in the task subject. It never overwrites an existing summary. `teammate-idle` counts unchecked `T##` checkboxes across the slice plans of the current milestone. +- `stop` speaks only when milestone, slice and task are all set and the task's summary is missing or a draft (once per session and pointer, not in a coordinate session, not for a W10 pointer), when the checkout is behind origin, when a coordinator should rotate, or when the standing check or a coordinate lint speaks. It stays silent when `stop_hook_active` is true. The standing check counts an entry whose name time is in or after the minute of the first unhandled flagged prompt, in the working tree's `standing/` or in `git log --all --since= --diff-filter=A` of the repository; local git only, no host call. ### SessionStart injection - Always: the full text of `skills/using-ytstack/SKILL.md` in an `` envelope. If that file is missing, the hook prints nothing. If `YTSTACK_HOST_CONTEXT` is set, its text goes in front of the skill text. - No `.ytstack`: a greenfield block that routes build intent to `office-hours`. With two or more brownfield signals it routes to `adopt-brownfield` and names the signals. - `.ytstack` without `STATE.md`: a one-line repair notice. -- Otherwise a state block, in this order: scope, project, pointer, last update, working tree with the linked-worktree flag, `.ytstack` path, a Next action excerpt, the three newest summary names, a notice when more than one milestone roadmap is `in-progress`, in a coordinate session the operating checklist of `docs/ux/coordinator-format.md` (in place of the minimal-code line), the standing instructions in force for the session's role (coordinator with the coordinate marker, else lane; pending ones too, also before the checkout has `standing/`; at most six lines from `yt_standing_lines`, files only, and a line naming `STANDING.md` when it exists), the manual and the latest automatic handoff, a lifecycle hint for a finished slice or a finished milestone without retro, up to five STATE lint findings, the minimal-code line when `minimal_code` is on, a "Factory tools" block with the lines of `yt_factory_notices` (only when the payload `source` is `startup` or `clear`, or absent on a SessionStart, so it is said once per session without a file), and a closing line that names the files as the source of truth. When `spec/SPEC.md` exists, the closing line names it as the place for what applies now. -- Cap: the hook measures the injection without the host context. Above the guard threshold in the script, which sits just under the host's 10,000-character limit, it first cuts the standing lines to the three newest, then the Next action excerpt to what still fits and marks the cut; when less than a useful rest would remain, it replaces the excerpt with a one-line note (a Next action shorter than that note stays). Next, the Factory tools block shrinks to one line that counts them and names `bin/ytstack-upkeep`, then the minimal-code line to its short pointer, then the closing line to its short form; an omitted Next action gets back the room these freed, when that is a useful rest; last the standing lines shrink to one line that counts them, names the role and `bin/ytstack-standing list`. The operating checklist is not cut. If the text is still above the threshold, it warns on stderr and emits the text anyway. Nothing else is dropped. Last, with a state block and on every source (also resume and compaction): one line `YT_BIN=`, the directory skills run ytstack's bins from as `"$YT_BIN/ytstack-"` (issue #85). It is added only when it still fits under the guard, so it never costs the Next action excerpt; the `coordinate` preamble prints it too. +- Otherwise a state block, in this order: scope, project, pointer, last update, working tree with the linked-worktree flag, `.ytstack` path, on the default branch behind `origin/` a line with the count and `git merge --ff-only` (pointer and Next action are then read from that ref's `STATE.md` and the STATE lint is left out; `yt_behind_origin`, issue #82), in a coordinate session after a compaction `Compaction N of this coordinator: ytstack:coordinate Step 12, rotate now` (N from `compactions`, at least 1; issue #83), a Next action excerpt, the three newest summary names, a notice when more than one milestone roadmap is `in-progress`, in a coordinate session the operating checklist of `docs/ux/coordinator-format.md` (in place of the minimal-code line), the standing instructions in force for the session's role (coordinator with the coordinate marker, else lane; pending ones too, also before the checkout has `standing/`; at most six lines from `yt_standing_lines`, files only, and a line naming `STANDING.md` when it exists), the manual and the latest automatic handoff (a manual one whose `timestamp` is older than the automatic one's is listed after it as "Older manual handoff"), a lifecycle hint for a finished slice or a finished milestone without retro, up to five STATE lint findings, the minimal-code line when `minimal_code` is on, a "Factory tools" block with the lines of `yt_factory_notices` (only when the payload `source` is `startup` or `clear`, or absent on a SessionStart, so it is said once per session without a file), and a closing line that names the files as the source of truth. When `spec/SPEC.md` exists, the closing line names it as the place for what applies now. +- Cap: the hook measures the injection without the host context. Above the guard threshold in the script, which sits just under the host's 10,000-character limit, it first cuts the standing lines to the three newest, then the Factory tools block shrinks to one line that counts them and names `bin/ytstack-upkeep`, then the minimal-code line to its short pointer, then the closing line to its short form, then the standing lines to one line that counts them, names the role and `bin/ytstack-standing list`; last the `using-ytstack` body is cut to what fits, at a line end, with the line `(cut for the 10,000-char cap: read the rest in )` (issue #82: the Next action comes before that body). The Next action excerpt (at most five lines of 600 characters), the operating checklist and the lines about the checkout and a compaction are never cut. If the text is still above the threshold, it warns on stderr and emits the text anyway. Nothing else is dropped. Last, with a state block and on every source (also resume and compaction): one line `YT_BIN=`, the directory skills run ytstack's bins from as `"$YT_BIN/ytstack-"` (issue #85). It is added only when it still fits under the guard, so it never costs the Next action excerpt; the `coordinate` preamble prints it too. - Output is the existing Claude-compatible JSON envelope by default. `YTSTACK_HOOK_FORMAT=plain` emits the raw context instead. Kimi's helper uses this mode only to prepare pending context, not as a claim that SessionStart stdout is consumed. ### Kimi pending bridge @@ -120,7 +120,7 @@ See `docs/statusline.md`. It was read against `bin/ytstack-status` at `verified_ - Volatile state (automatic handoff, journal, Kimi pending context, the session's plugin version, the phase snapshot and denominator log of `ytstack-status --phases`, the first time `ytstack-frontier check` saw a lane ready) is written outside the tree. `version-notice` writes only `plugin-version` and `notified-` under `/sessions//`, keyed by the session and not by the checkout, and only for a session id of letters, digits, `.`, `_` and `-`. The only in-tree location is the `.ytstack/.local` fallback. - No hook creates or changes `.ytstack/HANDOFF.md` or `STATE.md`. - Two hooks write deliberate artifacts into the resolved `.ytstack`: `post-tool-use-bash` (the draft stub) and `task-completed` (auto summary, checkbox). Both write into the checkout the payload names, so a session that works in a linked worktree leaves the main checkout unchanged. -- `standing-prompt` writes only `prompts`, `reports` and `standing-flags`, `pre-tool-use-agent` only `dispatches`, and `stop` only `standing-stop`, `lint-warned-` and `lint-blocked-` under `//` plus the `coordinate-lints` counter under the state base, and only when the coordinate marker is there; a session id with other characters than letters, digits, `.`, `_` and `-` is ignored. No hook runs the `until-check` or `check` command of a standing entry (`docs/ux/coordinator-format.md`, "Where the commands of an entry run"). `session-start`, `pre-tool-use-edit`, `task-created` and `teammate-idle` write no files. Plain mode does not change this; the Kimi helper owns the pending write. +- `standing-prompt` writes only `prompts`, `reports` and `standing-flags`, `pre-tool-use-agent` only `dispatches`, `pre-compact` there only `compactions`, `post-tool-use-bash` there only `red-main-said`, and `stop` only `standing-stop`, `rotate-said`, `lint-warned-` and `lint-blocked-` under `//` plus the `coordinate-lints` counter under the state base, and only when the coordinate marker is there; the one exception is `stop-said`, which `stop` keeps for every session (what it said once, issue #82); a session id with other characters than letters, digits, `.`, `_` and `-` is ignored. No hook runs the `until-check` or `check` command of a standing entry (`docs/ux/coordinator-format.md`, "Where the commands of an entry run"). `session-start`, `pre-tool-use-edit`, `task-created` and `teammate-idle` write no files. Plain mode does not change this; the Kimi helper owns the pending write. - Files under `sessions//` have one writer. There is no locking. Kimi's consume-by-rename is atomic even when two prompt hooks race. - The payload is trusted as coming from the host. Its fields are shell-quoted before evaluation, but `session_id` is used as a directory name without sanitising. @@ -139,13 +139,12 @@ See `docs/statusline.md`. It was read against `bin/ytstack-status` at `verified_ - `pre-tool-use-edit` warns on stderr and exits 0. The Claude Code hooks reference says the agent never sees stderr of a hook that exits 0. Who sees the warning: Unknown -- not reproduced in a live session. - `task-created` exits 2 on drift and its message says the task is still created. The Claude Code hooks reference says exit 2 on TaskCreated rolls the creation back. Actual effect: Unknown -- not reproduced in a live session. -- The injection shares the 10,000-character cap with `using-ytstack` (about 7,400 characters). A project with two handoffs and long paths is near the cap already: there the standing list is cut to its pointer line, in a coordinate session after the checklist. A Next action shorter than the omission note is kept. -- `session-start` looks for `latest-handoff` only under the state base. An automatic handoff written to a fallback location is not announced. +- The injection shares the 10,000-character cap with `using-ytstack` (about 7,400 characters). A project with two handoffs and long paths is near the cap already: there the standing list is cut to its pointer line, in a coordinate session after the checklist, and a long Next action cuts the end of the `using-ytstack` body, which the agent then reads from the file the pointer names.- `session-start` looks for `latest-handoff` only under the state base. An automatic handoff written to a fallback location is not announced. - `yt_resolve_yt_dir` looks only at the toplevel. Outside Git, a subdirectory does not find its parent's `.ytstack`. - `post-tool-use-bash` attributes a commit to the payload `cwd`, also when the command changed directory first. - The scope check in `pre-tool-use-edit` is a substring match over the whole task plan, not over its Files section. - `session.jsonl` has no reader in this repository. -- Codex and Kimi do not register `version-notice`; their sessions get no version notice. The standing hooks are Claude Code only too: Codex registers no ytstack UserPromptSubmit hook, and a Kimi shell has no session id for the coordinate marker. `standing-prompt` matches phrases (also a hold with until/bis and a time or condition, "hold merges until 12:37", "bis 12:37 keine Merges"), so an instruction in other words is not flagged, and a phrase in an ordinary sentence is; the stop block comes once per flagged batch and the agent may answer that none was a standing instruction. Whether Claude Code sends a task notification through UserPromptSubmit is not verified; without it the `reports` file stays empty and the LANES check sees dispatches only. `pre-tool-use-agent` tells a lookup from a lane only by the agent type and therefore never denies. With several ytstack entries in `installed_plugins.json` that count the highest version counts. The PR watch notice keys on a GitHub `origin`, not on open pull requests (that needs a host call). +- Codex and Kimi do not register `version-notice`; their sessions get no version notice. The standing hooks are Claude Code only too: Codex registers no ytstack UserPromptSubmit hook, and a Kimi shell has no session id for the coordinate marker. So are the hints of issue #83 (isolation, `gh pr merge`, `gh pr close`, compactions, the red-main note): Codex runs only the PR watch on `Bash` and has no ytstack hook on its subagent tools; there the skill text carries the rules. `standing-prompt` matches phrases (also a hold with until/bis and a time or condition, "hold merges until 12:37", "bis 12:37 keine Merges"), so an instruction in other words is not flagged, and a phrase in an ordinary sentence is; the stop block comes once per flagged batch and the agent may answer that none was a standing instruction. Whether Claude Code sends a task notification through UserPromptSubmit is not verified; without it the `reports` file stays empty and the LANES check sees dispatches only. `pre-tool-use-agent` tells a lookup from a lane only by the agent type and therefore never denies. With several ytstack entries in `installed_plugins.json` that count the highest version counts. The PR watch notice keys on a GitHub `origin`, not on open pull requests (that needs a host call). - The key digest depends on the tool `yt_sha16` finds first, so keys can differ between machines. ## Where implemented @@ -182,7 +181,7 @@ python3 -m unittest discover -s tests -p 'kimi_lifecycle_test.py' -v ## Decisions that apply now -- DECISIONS.md -- "2026-11-15: Coordinate mode is a session marker the coordinate preamble writes; the standing hooks act only with it (issue #72)"; "2026-11-15: In coordinate mode the operating path is injected and checked by hooks that warn; a lint repeated in three sessions blocks once (issue #76)"; "2026-11-15: Standing entries end by `until`, `until-condition` or `until-check` and are closed by an entry of `kind: end`; their commands run only in `ytstack-standing list` (issues #73, #74)", narrowed by "2026-11-15: A standing entry's command runs only when the entry is merged; pending means this machine's standing branches (review of PR #87)" +- DECISIONS.md -- "2026-11-15: Coordinate mode is a session marker the coordinate preamble writes; the standing hooks act only with it (issue #72)"; "2026-11-15: In coordinate mode the operating path is injected and checked by hooks that warn; a lint repeated in three sessions blocks once (issue #76)"; "2026-11-15: Standing entries end by `until`, `until-condition` or `until-check` and are closed by an entry of `kind: end`; their commands run only in `ytstack-standing list` (issues #73, #74)", narrowed by "2026-11-15: A standing entry's command runs only when the entry is merged; pending means this machine's standing branches (review of PR #87)"; extended by "2026-11-15: Hooks read a stale checkout from origin, say a reminder once per session and pointer, and keep a coordinator on its path with hints, not denies (issues #82, #83)" (the behind check, the once-per-pointer reminder, the cap order, the hints and the compaction count) - DECISIONS.md -- "2026-11-15: SessionStart stays read-only; factory-tool notices are said on startup only, the plugin version is recorded by a prompt hook (M031-S03)" - DECISIONS.md -- "2026-11-15: PR watch bulk registration takes only your own ready PRs; bins are called through `YT_BIN` (issue #85)" - DECISIONS.md -- "2026-11-14: Kimi uses native plugin bootstrap and pending lifecycle context (M020)" (plain output is explicit, the helper owns pending context and consumes it once) diff --git a/.ytstack/spec/skills.md b/.ytstack/spec/skills.md index 2199183..873075e 100644 --- a/.ytstack/spec/skills.md +++ b/.ytstack/spec/skills.md @@ -105,9 +105,9 @@ Read from `PREFERENCES.md` in the resolved `.ytstack` directory by `yt_prefs` in Formats: `docs/ux/coordinator-format.md`. The four skills below are for the session that owns a plan and delegates all of it; none of them writes product code. -- `coordinate` is a loop with a fixed order: start from the standing instructions (the entries of `standing/` in the resolved `YT_DIR`, project or user scope, newest first without superseded ones, and `STANDING.md`), `LANES.md`, the frontier and the questions (never from a conversation summary), read host facts fresh and stamp them with their read time, claim a lane before dispatching it, finish lanes through `finish-lane`, run the factory tools of Step 7 (one table of command, when and skip condition; the preamble prints `MERGE_BY`, `REVIEW_POLICY`, `OWN_REVIEWERS`, `PR_WATCH` with the heartbeat age, `RELEASE` and `SIGNALS`, and `YT_BIN=`, through which it runs every bin): the route before every merge, also one it makes itself outside `finish-lane` (then through `ytstack-finish-lane merge` and `finish-lane`'s rule of who merges), with the PR watch on (flag set and a worker heartbeat under 10 minutes old) register the repository's open pull requests by its own GitHub login, without drafts and do-not-merge labels, to itself as their owning session (`ytstack-pr-watch register --all-open` without `--session`, at the start, after every restart or rotation and after a worker opened one) and otherwise poll through `bin/ytstack-watch`, `ytstack-watch release` after every merge to production, `signal-intake` / `incident` for signals and `review-lessons` after a merge with a bot finding, `lesson` on a red `main` and on every slip of a lane or its own (the open lessons in every status from the preamble's `LESSONS` line, a lesson proposal asked with the daily question, lesson lanes `lesson-F###` dispatched from the frontier with `ytstack-brief render --lesson` and set `fixed` after their merge), ask one question at a time from a question file, write a standing instruction down when it is given, before the next dispatch, with `ytstack-standing add` (a new file in `standing/` on the day's standing branch and pull request, `--here` in user scope; `STANDING.md` only where no `standing/` exists; agent memory is no substitute), close an ended one with `ytstack-standing end`, act on the ended, to-check and failed-check lines its preamble prints from `ytstack-standing list` (with the newest entry's age and the human prompts since), its preamble writes the coordinate session marker (the resolved `.ytstack` and the repository key) the coordinate-mode hooks act on, finds the automatic handoff through `yt_latest_handoff`, and prints the operating checklist of `docs/ux/coordinator-format.md` (the same block `session-start` injects), stop a lane that failed verification twice or needs a third review, and rotate after the first compaction in one step while lanes run: a handoff written from the files with the "Rotation" block of `docs/ux/coordinator-format.md` (PR watch session, background watches, each running worker's address), the successor's Step 3 takes the PR watches over with `ytstack-pr-watch handover --from `, and the old session stays open only as a relay that appends its workers' reports to `HANDOFF.md`. It also prints the sessions in other repositories it works with between `PEERS_BEGIN` and `PEERS_END` (`ytstack-frontier peer list`, the `## Peers` lines of `LANES.md`), carries them under `Peers:` in the Rotation block, and takes progress per phase for a status from `ytstack-status --phases` (issues #81, #84). +- `coordinate` is a loop with a fixed order: start from the standing instructions (the entries of `standing/` in the resolved `YT_DIR`, project or user scope, newest first without superseded ones, and `STANDING.md`), `LANES.md`, the frontier and the questions (never from a conversation summary), read host facts fresh and stamp them with their read time, claim a lane before dispatching it, finish lanes through `finish-lane`, run the factory tools of Step 7 (one table of command, when and skip condition; the preamble prints `MERGE_BY`, `REVIEW_POLICY`, `OWN_REVIEWERS`, `PR_WATCH` with the heartbeat age, `RELEASE` and `SIGNALS`, and `YT_BIN=`, through which it runs every bin): the route before every merge, also one it makes itself outside `finish-lane` (then through `ytstack-finish-lane merge` and `finish-lane`'s rule of who merges), with the PR watch on (flag set and a worker heartbeat under 10 minutes old) register the repository's open pull requests by its own GitHub login, without drafts and do-not-merge labels, to itself as their owning session (`ytstack-pr-watch register --all-open` without `--session`, at the start, after every restart or rotation and after a worker opened one) and otherwise poll through `bin/ytstack-watch`, `ytstack-watch release` after every merge to production, `signal-intake` / `incident` for signals and `review-lessons` after a merge with a bot finding, `lesson` on a red `main` and on every slip of a lane or its own (the open lessons in every status from the preamble's `LESSONS` line, a lesson proposal asked with the daily question, lesson lanes `lesson-F###` dispatched from the frontier with `ytstack-brief render --lesson` and set `fixed` after their merge), ask one question at a time from a question file, write a standing instruction down when it is given, before the next dispatch, with `ytstack-standing add` (a new file in `standing/` on the day's standing branch and pull request, `--here` in user scope; `STANDING.md` only where no `standing/` exists; agent memory is no substitute), close an ended one with `ytstack-standing end`, act on the ended, to-check and failed-check lines its preamble prints from `ytstack-standing list` (with the newest entry's age and the human prompts since), its preamble writes the coordinate session marker (the resolved `.ytstack` and the repository key) the coordinate-mode hooks act on, finds the automatic handoff through `yt_latest_handoff`, and prints the operating checklist of `docs/ux/coordinator-format.md` (the same block `session-start` injects), stop a lane that failed verification twice or needs a third review, and rotate after the first compaction in one step while lanes run: a handoff written from the files with the "Rotation" block of `docs/ux/coordinator-format.md` (PR watch session, background watches, each running worker's address), the successor's Step 3 takes the PR watches over with `ytstack-pr-watch handover --from `, and the old session stays open only as a relay that appends its workers' reports to `HANDOFF.md`. It also prints the sessions in other repositories it works with between `PEERS_BEGIN` and `PEERS_END` (`ytstack-frontier peer list`, the `## Peers` lines of `LANES.md`), carries them under `Peers:` in the Rotation block, and takes progress per phase for a status from `ytstack-status --phases` (issues #81, #84). Every round of its loop starts with `ytstack-frontier check` in Step 5, and each `stale:` line (exit 2) gets its action in that round before any new dispatch. Its hard gate forbids closing a lane's pull request, reopening it to retrigger checks and deleting its branch: a lane that waits for a cap (which counts pull requests ready for review) is `parked` with its pull request open, a check reruns with `gh run rerun`; in Claude Code the coordinate hooks hint at this, at a dispatch without `isolation`, at `gh pr merge`, at a red `main` read with `gh run list`, and at rotation after a compaction (issue #83). - `spawn-milestone-team` claims each lane with `bin/ytstack-frontier` before it dispatches, keeps the lane's row current, and looks at the frontier again whenever a lane is verified or merged. -- `finish-lane` takes a reported lane to a merged pull request with `bin/ytstack-finish-lane`: review pinned to the host's head, the required lenses, `route`, the gates read from the host, the merge decided by `merge_by` and the route, then `bin/ytstack-watch release` on the merge commit when `RUNTIME.md` has a "Release" section (in the background; the receipt goes into the report, nothing is rolled back). A merge without a person is reported in one line with class, ceiling and lenses. After a merge it made itself, and when `REVIEW.md` declares own reviewers, it invokes `review-lessons` for the pull request. Before a lane goes back for a review that requested changes, a failed lens or a failed check, it invokes `lesson` (its Step 14). These two are the skills it may invoke. The pipeline supports GitHub through `gh` only; on another host the skill stops after the route. +- `finish-lane` takes a reported lane to a merged pull request with `bin/ytstack-finish-lane`: review pinned to the host's head, the required lenses, `route`, the gates read from the host, the merge decided by `merge_by` and the route, then `bin/ytstack-watch release` on the merge commit when `RUNTIME.md` has a "Release" section (in the background; the receipt goes into the report, nothing is rolled back). A merge without a person is reported in one line with class, ceiling and lenses. After a merge it made itself, and when `REVIEW.md` declares own reviewers, it invokes `review-lessons` for the pull request. Before a lane goes back for a review that requested changes, a failed lens or a failed check, it invokes `lesson` (its Step 14). These two are the skills it may invoke. Its hard gate forbids closing the lane's pull request, reopening it to retrigger checks and deleting its branch; the `open-prs` gate counts pull requests ready for review, and a lane that waits for it is `parked` (issue #83). The pipeline supports GitHub through `gh` only; on another host the skill stops after the route. - **The class of a change.** `code-review` prints the floor of `bin/ytstack-risk` and has a reviewer that is not the author end with `Risk:`, `Severity:`, `Reach:` and `Invariants touched:`, read against "Invariants and security boundaries" and "Decisions that apply now" of the touched areas, also when only code moved. The round line records class, invariants and reviewer; a session reviewing its own change writes `by: self`, which routes to a person. On a pull request `finish-lane` and `code-review` post the round and lens lines in the body of a review on the reviewed head, and `finish-lane` routes with `--pr`: the record needs no commit that would move the head away from a head-bound review. Each lens the floor names gets a separate fresh reviewer with the lens brief (`bin/ytstack-brief render --kind review --lens `) and one lens line. - `visual-review` is the lens reviewer of a user interface change: its own worktree at the reviewed commit, `bin/ytstack-runtime up`, a browser tool that renders and returns screenshots, its own screenshots of the changed views, states and two widths, reviewed against the lens documents; evidence with `MANIFEST` in the main checkout. It is `not run`, never `pass`, when the reviewer is the author, a document or the "Run" section is missing, the product does not come up or no browser tool exists. It edits no product file. - `signal-intake` reads every source of "Signals" once with its read time, separates findings from noise by stated rules, records through `bin/ytstack-signals new` (an unreadable source is a finding too) and changes nothing else. `incident` puts the mitigation before the cause: facts with read times, timeline, hypotheses, mitigations as handover scripts it never runs, one question at a time, and never picks a mitigation without a person; once mitigated it records the lesson through `lesson` with `--incident`, and the cause goes to `systematic-debugging` afterwards, which records the cause's lesson the same way. @@ -196,5 +196,5 @@ Formats: `docs/ux/coordinator-format.md`. The four skills below are for the sess - DECISIONS.md -- "2026-10-13: Remove generated Codex copies; load the existing skills directly" (one skill tree for both hosts) - DECISIONS.md -- "2026-11-13: The technical spec is a set of artifacts of its own under `.ytstack/spec/` (M022, issue #36)" (the spec steps in the loop) - DECISIONS.md -- "2026-11-13: Verification, review and orchestration work are bounded like code (M023, issue #35)" (the work contract; extends the ceremony entry of 2026-11-07 from code to evidence and review) -- DECISIONS.md -- "2026-11-13: Coordinator mode keeps lanes, questions and standing instructions in files and reads host facts fresh (M024, issue #34)", extended by "2026-11-14: Standing instructions are one file per entry in `.ytstack/standing/`; `STANDING.md` stays valid (issue #57)", by "2026-11-15: PR watch bulk registration takes only your own ready PRs; bins are called through `YT_BIN` (issue #85)", by "2026-11-15: Lane liveness is part of `ytstack-frontier check`, worktree cleanup only prints commands, peers are list lines in `LANES.md` (issue #84)" (the peers of `coordinate`), by "2026-11-15: Coordinate mode is a session marker the coordinate preamble writes; the standing hooks act only with it (issue #72)", "2026-11-15: In coordinate mode the operating path is injected and checked by hooks that warn; a lint repeated in three sessions blocks once (issue #76)" and "2026-11-15: Standing entries end by `until`, `until-condition` or `until-check` and are closed by an entry of `kind: end`; their commands run only in `ytstack-standing list` (issues #73, #74)" +- DECISIONS.md -- "2026-11-13: Coordinator mode keeps lanes, questions and standing instructions in files and reads host facts fresh (M024, issue #34)", extended by "2026-11-14: Standing instructions are one file per entry in `.ytstack/standing/`; `STANDING.md` stays valid (issue #57)", by "2026-11-15: PR watch bulk registration takes only your own ready PRs; bins are called through `YT_BIN` (issue #85)", by "2026-11-15: Lane liveness is part of `ytstack-frontier check`, worktree cleanup only prints commands, peers are list lines in `LANES.md` (issue #84)" (the peers of `coordinate`), by "2026-11-15: Coordinate mode is a session marker the coordinate preamble writes; the standing hooks act only with it (issue #72)", "2026-11-15: In coordinate mode the operating path is injected and checked by hooks that warn; a lint repeated in three sessions blocks once (issue #76)" and "2026-11-15: Standing entries end by `until`, `until-condition` or `until-check` and are closed by an entry of `kind: end`; their commands run only in `ytstack-standing list` (issues #73, #74)" and "2026-11-15: Hooks read a stale checkout from origin, say a reminder once per session and pointer, and keep a coordinator on its path with hints, not denies (issues #82, #83)" (the hard gate of `coordinate` and `finish-lane`, `parked`, the cap on ready pull requests, Step 5's liveness check) - DECISIONS.md -- "2026-11-13: `STATE.md` is a pointer with a size bound; history leaves it through `reconcile`, a closed milestone is folded into the spec (M022-S03)" diff --git a/CHANGELOG.md b/CHANGELOG.md index 0a5de99..ff3a8e2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -61,9 +61,41 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 hook warns when `LANES.md` lags the session's dispatches or the STATE pointer is behind, and holds the stop once when that came three sessions in a row. +- **A coordinator stays on the path** (issue #83, Claude Code). In a + `coordinate` session the hooks add one line when an `Agent` dispatch has no + `isolation`, when a Bash command runs `gh pr merge` (use + `ytstack-finish-lane merge --at `) or `gh pr close` (a cap + waits, CI reruns with `gh run rerun`), and when `gh run list --branch + ` shows a failed run (run `ytstack:lesson`). After a compaction the + SessionStart context says "Compaction N of this coordinator: ... + Step 12, rotate now"; from the second the Stop hook says it too. Hints, + never a deny. +- **`parked` lane status**: `ytstack-frontier set --status parked` + holds a lane whose pull request waits open, for a cap or a person. +- **A checkout behind origin is named** (issue #82): on the default branch + behind `origin/` (local refs, no fetch), SessionStart and Stop say + "N commit(s) behind" and read the pointer and Next action from origin's + `STATE.md`. STATE lint W10 names an active task whose `last_updated` is + more than three days old (`YT_POINTER_STALE_DAYS`). ### Changed +- **The Stop reminder is said once** (issue #82): once per session and task + pointer, never in a `coordinate` session (a coordinator holds no task), and + not for a pointer W10 already names. +- **The Next action is never cut from the SessionStart context** (issue #82): + near the 10,000-character cap the end of the `using-ytstack` body yields + instead, with a pointer to its file. A hand-written handoff older than the + newest automatic one is listed as older. +- `coordinate` 0.7.0: a hard gate against closing, reopening to retrigger or + deleting the branch of a lane's pull request; Step 5 starts every round + with `ytstack-frontier check` and acts on each `stale:` line; Step 6 parks + a lane that waits for the cap; Step 12 names the compaction line. The + operating checklist has two more lines. +- `finish-lane` 0.6.0: the same hard gate; the `open-prs` gate of + `ytstack-finish-lane` counts pull requests ready for review, drafts do not + count, and a lane waiting for it is `parked`. + - **PR watch stays on your own PRs and says less** (issue #85). `ytstack-pr-watch register --all-open` registers only open PRs you authored (the `gh` login) and skips drafts and do-not-merge labels, each named with From eb46da7287cb4c19b122091421e7595aa6f02479 Mon Sep 17 00:00:00 2001 From: Alex Wegener Date: Sun, 15 Nov 2026 19:54:24 +0100 Subject: [PATCH 05/13] docs: host-adapters names the Bash matcher and the uncovered hints; dependencies verified (#82, #83) Co-Authored-By: Claude Opus 5.5 --- .ytstack/spec/dependencies.md | 2 +- .ytstack/spec/host-adapters.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.ytstack/spec/dependencies.md b/.ytstack/spec/dependencies.md index 03d0247..d6beb9d 100644 --- a/.ytstack/spec/dependencies.md +++ b/.ytstack/spec/dependencies.md @@ -7,7 +7,7 @@ paths: - NOTICE - hooks/lib/git-ctx.sh - bin/ytstack-gstack-diff -verified_at: 39275b7 +verified_at: 1a0b3cc --- # dependencies diff --git a/.ytstack/spec/host-adapters.md b/.ytstack/spec/host-adapters.md index 54162cf..ede6fa2 100644 --- a/.ytstack/spec/host-adapters.md +++ b/.ytstack/spec/host-adapters.md @@ -36,7 +36,7 @@ How one `skills/` tree and one set of hook scripts serve Claude Code, Codex and - `.claude-plugin/plugin.json` holds metadata only. It names no component paths and no dependencies. The host loads `skills/`, `agents/` and `hooks/hooks.json` from their default locations. - `.claude-plugin/marketplace.json` makes the repository its own marketplace: the marketplace is named like the plugin and its one entry points at the repository root. -- `hooks/hooks.json` registers the nine lifecycle hooks, `version-notice` (first on UserPromptSubmit, Claude Code only), `standing-prompt` (second on UserPromptSubmit) and `pre-tool-use-agent` (PreToolUse on `Agent|Task|SendMessage`), both Claude Code only and active only in a coordinate session, and the opt-in `pr-watch`. Each entry runs `bash "${CLAUDE_PLUGIN_ROOT}/hooks/"` synchronously with `shell: bash`. SessionStart also fires on `fork`. +- `hooks/hooks.json` registers the nine lifecycle hooks, `version-notice` (first on UserPromptSubmit, Claude Code only), `standing-prompt` (second on UserPromptSubmit) and `pre-tool-use-agent` (PreToolUse on `Agent|Task|SendMessage|Bash`), both Claude Code only and active only in a coordinate session, and the opt-in `pr-watch`. Each entry runs `bash "${CLAUDE_PLUGIN_ROOT}/hooks/"` synchronously with `shell: bash`. SessionStart also fires on `fork`. - Plugin root: the host fills `${CLAUDE_PLUGIN_ROOT}` in hook commands. The hook scripts find the library relative to their own path. `hooks/session-start` falls back to its own parent directory when the variable is unset. - Skill directory: the host substitutes `${CLAUDE_SKILL_DIR}` in skill text. Preambles reach the library and the vendored files through `${CLAUDE_SKILL_DIR}/../../`. - Volatile state goes under `CLAUDE_PLUGIN_DATA` when the host sets it. @@ -116,7 +116,7 @@ How one `skills/` tree and one set of hook scripts serve Claude Code, Codex and - Kimi headless `kimi -p` does not deliver SessionEnd in the tested path (upstream #4380). Interactive Ctrl+C twice after the trust prompt is verified; web idle/unload and the tested archive/shutdown paths produce no journal. - Kimi 2.6.2 from the local macOS npm installation exited 126 without diagnostics. The 2.6.2 support claim applies to the fresh Linux container, not that local installation. - Real-model semantic skill selection is not established by the local fake-model tests. -- Codex and Kimi register no `version-notice`: a session there is not told that the installed plugin is newer than the one it loaded. Neither runs the coordinate-mode hooks (`standing-prompt`, `pre-tool-use-agent`, the standing and lint parts of `stop`; Codex's subagent tools have no ytstack hook): Codex registers no ytstack UserPromptSubmit hook and its `stop` entry is the PR watch's, and a Kimi shell has no session id for the coordinate marker. The standing lines of the shared SessionStart hook reach both. The Factory tools lines of the shared SessionStart hook reach both. +- Codex and Kimi register no `version-notice`: a session there is not told that the installed plugin is newer than the one it loaded. Neither runs the coordinate-mode hooks (`standing-prompt`, `pre-tool-use-agent` with its isolation, `gh pr merge` and `gh pr close` hints, the standing, lint and rotation parts of `stop`, the compaction count of `pre-compact`, the red-main note of `post-tool-use-bash`; Codex's subagent tools have no ytstack hook, its `Bash` entries run only the PR watch): Codex registers no ytstack UserPromptSubmit hook and its `stop` entry is the PR watch's, and a Kimi shell has no session id for the coordinate marker. The standing lines of the shared SessionStart hook reach both. The Factory tools lines of the shared SessionStart hook reach both. - Listing in the external catalog (`Yesterday-AI/skills`): Unknown -- it lives in another repository. - The Codex and Kimi packages are repository and local distributions, not public directory submissions. - Native Windows shells and remote environments without the plugin files are not covered. From 235b511d54b5f4bc3300b213baa80e3683593f1c Mon Sep 17 00:00:00 2001 From: Alex Wegener Date: Sun, 15 Nov 2026 19:59:17 +0100 Subject: [PATCH 06/13] fix: YT_BIN line yields when the using-ytstack body was cut (#82) The body cut stops at a line end and can leave room; the YT_BIN line still does not take it, as issue #85 decided for the Next action. Found by the Linux run (shorter temp paths). Co-Authored-By: Claude Opus 5.5 --- .ytstack/spec/hooks-and-state.md | 2 +- hooks/session-start | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/.ytstack/spec/hooks-and-state.md b/.ytstack/spec/hooks-and-state.md index 9205619..62bd5b8 100644 --- a/.ytstack/spec/hooks-and-state.md +++ b/.ytstack/spec/hooks-and-state.md @@ -94,7 +94,7 @@ Every hook except `pr-watch` sources the library and resolves from the payload ` - No `.ytstack`: a greenfield block that routes build intent to `office-hours`. With two or more brownfield signals it routes to `adopt-brownfield` and names the signals. - `.ytstack` without `STATE.md`: a one-line repair notice. - Otherwise a state block, in this order: scope, project, pointer, last update, working tree with the linked-worktree flag, `.ytstack` path, on the default branch behind `origin/` a line with the count and `git merge --ff-only` (pointer and Next action are then read from that ref's `STATE.md` and the STATE lint is left out; `yt_behind_origin`, issue #82), in a coordinate session after a compaction `Compaction N of this coordinator: ytstack:coordinate Step 12, rotate now` (N from `compactions`, at least 1; issue #83), a Next action excerpt, the three newest summary names, a notice when more than one milestone roadmap is `in-progress`, in a coordinate session the operating checklist of `docs/ux/coordinator-format.md` (in place of the minimal-code line), the standing instructions in force for the session's role (coordinator with the coordinate marker, else lane; pending ones too, also before the checkout has `standing/`; at most six lines from `yt_standing_lines`, files only, and a line naming `STANDING.md` when it exists), the manual and the latest automatic handoff (a manual one whose `timestamp` is older than the automatic one's is listed after it as "Older manual handoff"), a lifecycle hint for a finished slice or a finished milestone without retro, up to five STATE lint findings, the minimal-code line when `minimal_code` is on, a "Factory tools" block with the lines of `yt_factory_notices` (only when the payload `source` is `startup` or `clear`, or absent on a SessionStart, so it is said once per session without a file), and a closing line that names the files as the source of truth. When `spec/SPEC.md` exists, the closing line names it as the place for what applies now. -- Cap: the hook measures the injection without the host context. Above the guard threshold in the script, which sits just under the host's 10,000-character limit, it first cuts the standing lines to the three newest, then the Factory tools block shrinks to one line that counts them and names `bin/ytstack-upkeep`, then the minimal-code line to its short pointer, then the closing line to its short form, then the standing lines to one line that counts them, names the role and `bin/ytstack-standing list`; last the `using-ytstack` body is cut to what fits, at a line end, with the line `(cut for the 10,000-char cap: read the rest in )` (issue #82: the Next action comes before that body). The Next action excerpt (at most five lines of 600 characters), the operating checklist and the lines about the checkout and a compaction are never cut. If the text is still above the threshold, it warns on stderr and emits the text anyway. Nothing else is dropped. Last, with a state block and on every source (also resume and compaction): one line `YT_BIN=`, the directory skills run ytstack's bins from as `"$YT_BIN/ytstack-"` (issue #85). It is added only when it still fits under the guard, so it never costs the Next action excerpt; the `coordinate` preamble prints it too. +- Cap: the hook measures the injection without the host context. Above the guard threshold in the script, which sits just under the host's 10,000-character limit, it first cuts the standing lines to the three newest, then the Factory tools block shrinks to one line that counts them and names `bin/ytstack-upkeep`, then the minimal-code line to its short pointer, then the closing line to its short form, then the standing lines to one line that counts them, names the role and `bin/ytstack-standing list`; last the `using-ytstack` body is cut to what fits, at a line end, with the line `(cut for the 10,000-char cap: read the rest in )` (issue #82: the Next action comes before that body). The Next action excerpt (at most five lines of 600 characters), the operating checklist and the lines about the checkout and a compaction are never cut. If the text is still above the threshold, it warns on stderr and emits the text anyway. Nothing else is dropped. Last, with a state block and on every source (also resume and compaction): one line `YT_BIN=`, the directory skills run ytstack's bins from as `"$YT_BIN/ytstack-"` (issue #85). It is added only when it still fits under the guard and the `using-ytstack` body was not cut, so it never costs the Next action excerpt or the directive; the `coordinate` preamble prints it too. - Output is the existing Claude-compatible JSON envelope by default. `YTSTACK_HOOK_FORMAT=plain` emits the raw context instead. Kimi's helper uses this mode only to prepare pending context, not as a claim that SessionStart stdout is consumed. ### Kimi pending bridge diff --git a/hooks/session-start b/hooks/session-start index f524a3b..d7c0a06 100644 --- a/hooks/session-start +++ b/hooks/session-start @@ -400,6 +400,7 @@ if over; then $_NOTE" rebuild + _BODY_CUT=yes fi if over; then echo "[ytstack session-start] injection is $(( ${#FULL_CONTEXT} - _HOST_LEN )) chars; Claude Code caps additionalContext at 10,000. Shorten skills/using-ytstack/SKILL.md." >&2 @@ -407,10 +408,11 @@ fi # The running version's bin/ (issue #85), on every source: skills run bins as # "$YT_BIN/ytstack-", not by a path from an earlier context. Only where it -# still fits under the guard; it never costs the Next action (coordinate's +# still fits under the guard and the using-ytstack body was not cut; it never +# costs the Next action or the directive (coordinate's # preamble prints it too). _YT_BIN_LINE="YT_BIN=$(cd "$PLUGIN_ROOT/bin" 2>/dev/null && pwd -P || printf '%s' "$PLUGIN_ROOT/bin")" -if [ $(( ${#FULL_CONTEXT} - _HOST_LEN + ${#_YT_BIN_LINE} + 2 )) -le 9500 ]; then +if [ "${_BODY_CUT:-no}" = no ] && [ $(( ${#FULL_CONTEXT} - _HOST_LEN + ${#_YT_BIN_LINE} + 2 )) -le 9500 ]; then FULL_CONTEXT="$FULL_CONTEXT $_YT_BIN_LINE" From 97c2a1129e2a9b15e7786ac4ead7b30ca243af16 Mon Sep 17 00:00:00 2001 From: Alex Wegener Date: Sun, 15 Nov 2026 21:47:44 +0100 Subject: [PATCH 07/13] fix: read origin's STATE.md only when strictly behind and unedited; skip user scope (PR #94 review) yt_behind_origin now needs a .ytstack inside the checkout whose STATE.md origin has (user scope and an untracked STATE.md stay out entirely), and hands out origin's copy only when HEAD is an ancestor of origin/, origin changed STATE.md since the merge base and the working tree's copy is HEAD's. Diverged or edited with an origin change: SessionStart reads the local file and says "N ahead, M behind", no --ff-only. Stop prunes old session dirs that only hold stop-said when it makes a new one. Co-Authored-By: Claude Opus 5.5 --- hooks/lib/git-ctx.sh | 30 ++++++++++++++++++++++-------- hooks/session-start | 23 ++++++++++++----------- hooks/stop | 19 ++++++++++++++----- tests/git-ctx.test.sh | 27 ++++++++++++++++++++++----- tests/hooks-readonly.test.sh | 23 +++++++++++++++++++++++ tests/hooks-stop.test.sh | 26 ++++++++++++++++++++++++++ 6 files changed, 119 insertions(+), 29 deletions(-) diff --git a/hooks/lib/git-ctx.sh b/hooks/lib/git-ctx.sh index 71359f0..4bce438 100644 --- a/hooks/lib/git-ctx.sh +++ b/hooks/lib/git-ctx.sh @@ -708,22 +708,36 @@ yt_standing_default_ref() { return 0 } -# yt_behind_origin [yt_dir] (issue #82): is the checkout on the +# yt_behind_origin (issue #82): is the checkout on the # default branch and behind origin's copy of it? Local refs only, no fetch. -# Sets YT_BEHIND_N (0 when not on the default branch, without an origin ref, -# or not behind), YT_BEHIND_REF (origin/) and, for a inside -# the checkout, YT_BEHIND_STATE: STATE.md as that ref has it ("" without one). +# Only for a inside the checkout whose STATE.md origin has; else +# (user scope, an untracked STATE.md) everything stays 0 / "". +# YT_BEHIND_N, YT_AHEAD_N commits HEAD..origin/ and back +# YT_BEHIND_REF origin/ +# YT_BEHIND_CHANGED yes when origin changed STATE.md since the +# merge base, else no +# YT_BEHIND_STATE origin's STATE.md, only when that is the one to +# read: strictly behind (not diverged), origin +# changed it, and the working tree's STATE.md is +# HEAD's (no local edit) yt_behind_origin() { - local top="$1" ytd="${2:-}" r cur n - YT_BEHIND_N=0; YT_BEHIND_REF=""; YT_BEHIND_STATE="" + local top="$1" ytd="${2:-}" r cur n a rel txt + YT_BEHIND_N=0; YT_AHEAD_N=0; YT_BEHIND_REF=""; YT_BEHIND_CHANGED=no; YT_BEHIND_STATE="" + case "$ytd" in "$top"/*) rel="${ytd#"$top"/}/STATE.md" ;; *) return 0 ;; esac r=$(yt_standing_default_ref "$top") case "$r" in refs/remotes/origin/*) ;; *) return 0 ;; esac cur=$(git -C "$top" symbolic-ref -q --short HEAD 2>/dev/null) [ -n "$cur" ] && [ "$cur" = "${r#refs/remotes/origin/}" ] || return 0 n=$(git -C "$top" rev-list --count "HEAD..$r" 2>/dev/null) case "$n" in ''|0|*[!0-9]*) return 0 ;; esac - YT_BEHIND_N=$n; YT_BEHIND_REF="origin/$cur" - case "$ytd" in "$top"/*) YT_BEHIND_STATE=$(git -C "$top" show "$r:${ytd#"$top"/}/STATE.md" 2>/dev/null) ;; esac + txt=$(git -C "$top" show "$r:$rel" 2>/dev/null) + [ -n "$txt" ] || return 0 + a=$(git -C "$top" rev-list --count "$r..HEAD" 2>/dev/null); case "$a" in ''|*[!0-9]*) a=0 ;; esac + YT_BEHIND_N=$n; YT_AHEAD_N=$a; YT_BEHIND_REF="origin/$cur" + git -C "$top" diff --quiet "HEAD...$r" -- "$rel" 2>/dev/null || YT_BEHIND_CHANGED=yes + if [ "$a" -eq 0 ] && [ "$YT_BEHIND_CHANGED" = yes ] && git -C "$top" diff --quiet HEAD -- "$rel" 2>/dev/null; then + YT_BEHIND_STATE="$txt" + fi return 0 } diff --git a/hooks/session-start b/hooks/session-start index d7c0a06..a90ae95 100644 --- a/hooks/session-start +++ b/hooks/session-start @@ -120,19 +120,20 @@ if [ ! -f "$STATE_FILE" ]; then fi # A checkout on the default branch behind origin/ (local refs, no -# fetch; issue #82): its STATE.md is stale, so pointer and Next action come -# from origin's copy, and the line says how far behind it is. +# fetch; issue #82). Strictly behind, origin changed STATE.md and no local +# edit: pointer and Next action come from origin's copy and the STATE lint +# waits. Diverged or locally edited while origin changed it: the local file +# is read and the line says so. Otherwise (user scope, untracked STATE.md, +# origin did not touch it): nothing. STATE_TEXT=$(cat "$STATE_FILE" 2>/dev/null) BEHIND_LINE="" -YT_BEHIND_N=0 +YT_BEHIND_STATE="" [ "$YT_IS_GIT" != yes ] || yt_behind_origin "$YT_TOPLEVEL" "$YT_DIR" -if [ "${YT_BEHIND_N:-0}" -gt 0 ]; then - if [ -n "$YT_BEHIND_STATE" ]; then - STATE_TEXT="$YT_BEHIND_STATE" - BEHIND_LINE="Checkout: $YT_BEHIND_N commit(s) behind $YT_BEHIND_REF (local refs, not fetched). Pointer and Next action are read from $YT_BEHIND_REF; the other files here are older, so the STATE lint waits. Bring the checkout up to date first: git merge --ff-only $YT_BEHIND_REF." - else - BEHIND_LINE="Checkout: $YT_BEHIND_N commit(s) behind $YT_BEHIND_REF (local refs, not fetched); the files here are older. Bring the checkout up to date first: git merge --ff-only $YT_BEHIND_REF." - fi +if [ -n "$YT_BEHIND_STATE" ]; then + STATE_TEXT="$YT_BEHIND_STATE" + BEHIND_LINE="Checkout: $YT_BEHIND_N commit(s) behind $YT_BEHIND_REF (local refs, not fetched). Pointer and Next action are read from $YT_BEHIND_REF; the other files here are older, so the STATE lint waits. Bring the checkout up to date first: git merge --ff-only $YT_BEHIND_REF." +elif [ "${YT_BEHIND_CHANGED:-no}" = yes ]; then + BEHIND_LINE="Checkout: $YT_AHEAD_N ahead, $YT_BEHIND_N behind $YT_BEHIND_REF (local refs, not fetched), and $YT_BEHIND_REF changed STATE.md: the local STATE.md is read as it is here. Merge $YT_BEHIND_REF before you trust the pointer." fi # Extract frontmatter fields from STATE.md @@ -174,7 +175,7 @@ IN_PROGRESS_N=${IN_PROGRESS_N:-0} # STATE pointer lint + ceremony dials (M018): read-only, both from the lib. yt_state_lint "$YT_DIR" >/dev/null LINT_LINES="" -if [ "${YT_STATE_WARN_COUNT:-0}" -gt 0 ] && [ "${YT_BEHIND_N:-0}" -eq 0 ]; then +if [ "${YT_STATE_WARN_COUNT:-0}" -gt 0 ] && [ -z "$YT_BEHIND_STATE" ]; then LINT_LINES="STATE lint ($YT_STATE_WARN_COUNT): $(printf '%s\n' "$YT_STATE_WARNINGS" | head -5 | sed 's/^/- /') A malformed pointer stops plan-task and summarize-task: fix STATE.md first. Size and history findings do not block; ytstack:reconcile moves history out with your consent." diff --git a/hooks/stop b/hooks/stop index 1be07f6..2a6d5d9 100644 --- a/hooks/stop +++ b/hooks/stop @@ -168,9 +168,10 @@ rotate_msg # ---- 1. task reminder (issue #82) --------------------------------------------------- # Once per session and pointer (/stop-said holds what was said). -# On the default branch behind origin/ (local refs, no fetch) the -# local STATE.md is stale: one message with the count and origin's pointer -# instead, also in coordinate mode. A coordinate session holds no task: no +# On the default branch strictly behind origin/ (local refs, no +# fetch), when origin changed STATE.md and the local one has no edit +# (yt_behind_origin), the local STATE.md is stale: one message with the count +# and origin's pointer instead, also in coordinate mode. A coordinate session holds no task: no # reminder. A pointer older than YT_POINTER_STALE_DAYS is the STATE lint's # line W10 (SessionStart), not a message on every stop. said() { # said : 0 when this session said it already; records it otherwise @@ -178,7 +179,15 @@ said() { # said : 0 when this session said it already; records it otherwise case "$sid" in ''|.|..|*[!A-Za-z0-9._-]*) return 1 ;; esac f="$(yt_session_home)/$sid/stop-said" grep -qxF -- "$1" "$f" 2>/dev/null && return 0 - mkdir -p "${f%/*}" 2>/dev/null && printf '%s\n' "$1" >> "$f" 2>/dev/null + if [ ! -d "${f%/*}" ]; then + # A new session dir: prune the dirs of old sessions that only ever held + # stop-said (14 days untouched); a coordinate session's dir stays. + find "$(yt_session_home)" -mindepth 2 -maxdepth 2 -name stop-said -mtime +14 2>/dev/null | while IFS= read -r o; do + [ "$(ls -A "${o%/*}" 2>/dev/null)" = stop-said ] && rm -f "$o" && rmdir "${o%/*}" 2>/dev/null + done + mkdir -p "${f%/*}" 2>/dev/null || return 1 + fi + printf '%s\n' "$1" >> "$f" 2>/dev/null return 1 } task_msg() { @@ -190,7 +199,7 @@ task_msg() { get_field() { sed -n "s/^$1: *//p" 2>/dev/null | head -1; } if [ "$YT_IS_GIT" = yes ]; then yt_behind_origin "$YT_TOPLEVEL" "$ytd" - if [ "${YT_BEHIND_N:-0}" -gt 0 ]; then + if [ -n "$YT_BEHIND_STATE" ]; then said "behind:$(git -C "$YT_TOPLEVEL" rev-parse -q --verify "refs/remotes/$YT_BEHIND_REF" 2>/dev/null)" && return 0 ptr="$(printf '%s\n' "$YT_BEHIND_STATE" | get_field current_milestone) / $(printf '%s\n' "$YT_BEHIND_STATE" | get_field active_slice) / $(printf '%s\n' "$YT_BEHIND_STATE" | get_field active_task)" MSG="ytstack: this checkout ($YT_TOPLEVEL) is $YT_BEHIND_N commit(s) behind $YT_BEHIND_REF (local refs, not fetched): its STATE.md is stale. $YT_BEHIND_REF points at $ptr. Bring it up to date (git merge --ff-only $YT_BEHIND_REF) before acting on the pointer." diff --git a/tests/git-ctx.test.sh b/tests/git-ctx.test.sh index adb940d..3842c46 100644 --- a/tests/git-ctx.test.sh +++ b/tests/git-ctx.test.sh @@ -456,13 +456,30 @@ BC=$(new_repo bo-clone); mkdir -p "$BC/.ytstack" git remote add origin "$BO"; git push -q -u origin main printf 'current_milestone: M007\n' > .ytstack/STATE.md; git commit -qam next; git push -q origin main git checkout -q --detach HEAD~1 && git branch -q -f main HEAD && git checkout -q main ) >/dev/null 2>&1 -bo() { ( . "$LIB"; yt_behind_origin "$1" "$1/.ytstack"; printf '%s|%s|%s' "$YT_BEHIND_N" "$YT_BEHIND_REF" "$YT_BEHIND_STATE" ); } -eq "behind: one commit behind origin/main, STATE read from it" "1|origin/main|current_milestone: M007" "$(bo "$BC")" +# bo [yt dir] -> behind|ahead|ref|changed|origin STATE when it is to be read +bo() { ( . "$LIB"; yt_behind_origin "$1" "${2:-$1/.ytstack}"; printf '%s|%s|%s|%s|%s' "$YT_BEHIND_N" "$YT_AHEAD_N" "$YT_BEHIND_REF" "$YT_BEHIND_CHANGED" "$YT_BEHIND_STATE" ); } +eq "behind: strictly behind, origin changed STATE.md: read from origin" "1|0|origin/main|yes|current_milestone: M007" "$(bo "$BC")" +printf 'current_milestone: M009\n' > "$BC/.ytstack/STATE.md" +eq "behind: a local edit of STATE.md: the local file stays" "1|0|origin/main|yes|" "$(bo "$BC")" +( cd "$BC" && git commit -qam local ) >/dev/null 2>&1 +eq "behind: diverged (a local commit): counted, the local file stays" "1|1|origin/main|yes|" "$(bo "$BC")" +( cd "$BC" && git checkout -q --detach HEAD~1 && git branch -q -f main HEAD && git checkout -q main ) >/dev/null 2>&1 +eq "behind: user scope (.ytstack outside the checkout): nothing" "0|0||no|" "$(bo "$BC" "$TMP/elsewhere/.ytstack")" ( cd "$BC" && git checkout -q -b side ) >/dev/null 2>&1 -eq "behind: another branch is not the default branch" "0||" "$(bo "$BC")" +eq "behind: another branch is not the default branch" "0|0||no|" "$(bo "$BC")" ( cd "$BC" && git checkout -q main && git merge -q --ff-only origin/main ) >/dev/null 2>&1 -eq "behind: up to date" "0||" "$(bo "$BC")" -eq "behind: no origin" "0||" "$(bo "$(new_repo bo-plain)")" +eq "behind: up to date" "0|0||no|" "$(bo "$BC")" +BU=$(new_repo bo-unrel); ( cd "$BU" || exit 2; mkdir .ytstack; git branch -M main; printf 'current_milestone: M001\n' > .ytstack/STATE.md; git add -A; git commit -qm s + git init -q --bare "$TMP/bu.git"; git remote add origin "$TMP/bu.git"; git push -q -u origin main + echo y > y; git add y; git commit -qm unrelated; git push -q origin main + git checkout -q --detach HEAD~1 && git branch -q -f main HEAD && git checkout -q main ) >/dev/null 2>&1 +eq "behind: origin did not change STATE.md: the local file stays" "1|0|origin/main|no|" "$(bo "$BU")" +BN=$(new_repo bo-untracked); ( cd "$BN" || exit 2; git branch -M main; git init -q --bare "$TMP/bn.git"; git remote add origin "$TMP/bn.git"; git push -q -u origin main + echo y > y; git add y; git commit -qm unrelated; git push -q origin main + git checkout -q --detach HEAD~1 && git branch -q -f main HEAD && git checkout -q main + mkdir .ytstack; printf 'current_milestone: M001\n' > .ytstack/STATE.md ) >/dev/null 2>&1 +eq "behind: an untracked STATE.md (origin has none): nothing" "0|0||no|" "$(bo "$BN")" +eq "behind: no origin" "0|0||no|" "$(bo "$(new_repo bo-plain)")" echo echo "$PASS passed, $FAIL failed" diff --git a/tests/hooks-readonly.test.sh b/tests/hooks-readonly.test.sh index f1c3c34..f8c76a3 100644 --- a/tests/hooks-readonly.test.sh +++ b/tests/hooks-readonly.test.sh @@ -154,6 +154,29 @@ has "ss-behind: the pointer from origin" "$CTX" "Current: M050 / S01 / T02" has "ss-behind: the next action from origin" "$CTX" "Origin plan." lacks "ss-behind: not the stale local one" "$CTX" "Old plan." eq "ss-behind: nothing written" "" "$(git -C "$BH" status --porcelain)" +# PR #94 review: a local edit or a diverged checkout keeps the local STATE.md +ssbh() { run session-start "{\"session_id\":\"$1\",\"cwd\":$(jstr "$BH")}"; CTX=$(printf '%s' "$OUT" | jq -r '.hookSpecificOutput.additionalContext // empty' 2>/dev/null); } +printf 'project: fixture\ncurrent_milestone: M070\nactive_slice: none\nactive_task: none\n\n## Next action\n\nUncommitted plan.\n' > "$BH/.ytstack/STATE.md" +ssbh s1bh2 +has "ss-behind: a local edit is read" "$CTX" "Uncommitted plan." +lacks "ss-behind: not origin's" "$CTX" "Origin plan." +has "ss-behind: the line says origin changed it" "$CTX" "Checkout: 0 ahead, 2 behind origin/main (local refs, not fetched), and origin/main changed STATE.md" +( cd "$BH" && git commit -qam "local plan" ) >/dev/null 2>&1 +ssbh s1bh3 +has "ss-behind: diverged: the local file" "$CTX" "Uncommitted plan." +has "ss-behind: diverged: ahead and behind" "$CTX" "Checkout: 1 ahead, 2 behind origin/main" +lacks "ss-behind: diverged: no --ff-only" "$CTX" "--ff-only" +# origin moved without touching STATE.md: no line, the local file +BU="$TMP/behind-unrel"; BUO="$TMP/behind-unrel.git"; git init -q --bare "$BUO" +( mkdir -p "$BU/.ytstack" && cd "$BU" || exit 2; git init -q && git config user.email t@t.t && git config user.name t && git config commit.gpgsign false + printf 'project: fixture\ncurrent_milestone: M001\nactive_slice: none\nactive_task: none\n\n## Next action\n\nOld plan.\n' > .ytstack/STATE.md + git add -A && git commit -qm seed && git branch -M main && git remote add origin "$BUO" && git push -q -u origin main + echo x > x && git add x && git commit -qm other && git push -q origin main && git checkout -q --detach HEAD~1 && git branch -q -f main HEAD && git checkout -q main + printf 'project: fixture\ncurrent_milestone: M060\nactive_slice: none\nactive_task: none\n\n## Next action\n\nNew local plan.\n' > .ytstack/STATE.md && git commit -qam advance ) >/dev/null 2>&1 || { echo FATAL unrel fixture; exit 2; } +run session-start "{\"session_id\":\"s1bu\",\"cwd\":$(jstr "$BU")}" +CTX=$(printf '%s' "$OUT" | jq -r '.hookSpecificOutput.additionalContext // empty' 2>/dev/null) +has "ss-behind: origin did not touch STATE.md: the local plan" "$CTX" "New local plan." +lacks "ss-behind: and no checkout line" "$CTX" "Checkout:" # ---- 1e2. session-start: standing entries in force, filtered by role (issue #74) SDIR="$MAIN/.ytstack/standing"; mkdir -p "$SDIR" diff --git a/tests/hooks-stop.test.sh b/tests/hooks-stop.test.sh index 42eadfa..52110ac 100644 --- a/tests/hooks-stop.test.sh +++ b/tests/hooks-stop.test.sh @@ -104,6 +104,32 @@ has "behind: the pointer origin has" "$OUT" "M050 / S01 / T02" case "$OUT" in *"M042-S03-T07 is still the active task"*) bad "behind: no reminder for the stale local pointer";; *) ok "behind: no reminder for the stale local pointer";; esac OUT=$(fire "$MAIN"); eq "behind: said once per origin head" "" "$OUT" SID=c1; OUT=$(fire "$MAIN"); has "behind: said in a coordinate session too" "$OUT" "behind origin/main" +# PR #94 review: origin's copy only when strictly behind, origin changed it and there is no local edit +printf 'current_milestone: M044\nactive_slice: S01\nactive_task: T01\n' > "$MAIN/.ytstack/STATE.md" +SID=b2; OUT=$(fire "$MAIN"); has "behind with a local edit: the local pointer" "$OUT" "M044-S01-T01 is still the active task" +case "$OUT" in *"behind origin"*) bad "and no behind message";; *) ok "and no behind message";; esac +( cd "$MAIN" && git commit -qam "local pointer" ) >/dev/null 2>&1 +SID=b3; OUT=$(fire "$MAIN"); has "diverged: the local pointer" "$OUT" "M044-S01-T01 is still the active task" +case "$OUT" in *"behind origin"*|*"ff-only"*) bad "diverged: no ff-only message";; *) ok "diverged: no ff-only message";; esac + +echo "# user scope behind origin: no behind logic (PR #94 review)" +UH="$TMP/uhome"; U="$TMP/u"; mkdir -p "$UH"; git init -q --bare "$TMP/u.git" +( mkdir -p "$U" && cd "$U" || exit 2; git init -q && git config user.email t@t.t && git config user.name t && git config commit.gpgsign false + echo a > a && git add a && git commit -qm a && git branch -M main && git remote add origin "$TMP/u.git" && git push -q -u origin main + echo b > b && git add b && git commit -qm b && git push -q origin main && git checkout -q --detach HEAD~1 && git branch -q -f main HEAD && git checkout -q main ) >/dev/null 2>&1 +UK=$(HOME="$UH" bash -c '. "$1/hooks/lib/git-ctx.sh"; yt_git_ctx "$2"; printf %s "$YT_REPO_KEY"' _ "$ROOT" "$U") +mkdir -p "$UH/.ytstack/projects/$UK"; printf 'current_milestone: M042\nactive_slice: S03\nactive_task: T07\n' > "$UH/.ytstack/projects/$UK/STATE.md" +OUT=$(printf '{"session_id":"u1","cwd":%s,"hook_event_name":"Stop"}' "$(jstr "$U")" | HOME="$UH" XDG_STATE_HOME="$XDG_STATE_HOME" bash "$HOOK" 2>/dev/null) +has "user scope: the ordinary reminder" "$OUT" "M042-S03-T07 is still the active task" +case "$OUT" in *"behind"*|*" / / "*) bad "user scope: no empty origin pointer";; *) ok "user scope: no empty origin pointer";; esac + +echo "# old session dirs that only held stop-said are pruned (PR #94 review)" +SHM="$XDG_STATE_HOME/ytstack/sessions" +mkdir -p "$SHM/old1" "$SHM/oldc"; : > "$SHM/old1/stop-said"; : > "$SHM/oldc/stop-said"; : > "$SHM/oldc/coordinate" +touch -t 202001010000 "$SHM/old1/stop-said" "$SHM/oldc/stop-said" +SID=fresh2; printf 'current_milestone: M042\nactive_slice: S09\nactive_task: T09\n' > "$WT/.ytstack/STATE.md"; OUT=$(fire "$WT"); has "a new session's reminder" "$OUT" "M042-S09-T09" +eq "an old stop-said-only dir is gone" no "$([ -d "$SHM/old1" ] && echo yes || echo no)" +eq "an old dir with a coordinate marker stays" yes "$([ -d "$SHM/oldc" ] && echo yes || echo no)" echo echo "$PASS passed, $FAIL failed" From 436536ed3022b2b36e869ac54f34ea95816db0d7 Mon Sep 17 00:00:00 2001 From: Alex Wegener Date: Sun, 15 Nov 2026 21:47:44 +0100 Subject: [PATCH 08/13] fix: coordinate hints read commands, not text; red main per workflow and repo; compactions counted anywhere (PR #94 review) pre-tool-use-agent finds gh pr merge/close per line and segment, after assignments, if/then, wrappers, env, xargs and gh -R/--repo, and ignores quoted text and comments. post-tool-use-bash counts only the newest run of each workflow and only origin's repository under --repo/-R. pre-compact counts a coordinator's compaction before the .ytstack exit. The status test keeps an in-review row beside the parked one. Co-Authored-By: Claude Opus 5.5 --- hooks/post-tool-use-bash | 19 ++++++++++++++---- hooks/pre-compact | 17 ++++++++-------- hooks/pre-tool-use-agent | 31 ++++++++++++++++++++++------- tests/hooks-coordinate.test.sh | 36 ++++++++++++++++++++++++++++++++-- tests/ytstack-status.test.sh | 6 +++--- 5 files changed, 85 insertions(+), 24 deletions(-) diff --git a/hooks/post-tool-use-bash b/hooks/post-tool-use-bash index 7bfa973..7a7c342 100644 --- a/hooks/post-tool-use-bash +++ b/hooks/post-tool-use-bash @@ -32,13 +32,15 @@ yt_read_stdin # Coordinate mode (issue #83, the marker of the coordinate preamble): a # `gh run list --branch ` whose output shows a failed run is a red -# main; one note per distinct set of failed lines: run ytstack:lesson. Lines -# read: the tab-separated output (status, conclusion, ...), JSON -# "conclusion": "failure", and the terminal form starting with X. +# main; one note per distinct set of failed runs: run ytstack:lesson. Only +# the newest run of each workflow counts (gh lists newest first), in the +# tab-separated output (status, conclusion, title, workflow, ...) or a JSON +# array (conclusion, workflowName). With --repo/-R it must name origin. red_main() { local sid="${YT_SESSION_ID:-}" sd br def out bad key jq_bin cmd local re_list='(^|[;&|()[:space:]])gh[[:space:]]+run[[:space:]]+list([[:space:]]|$)' local re_br='(--branch[=[:space:]]|-b[[:space:]]+)([A-Za-z0-9._/-]+)' + local re_repo='(--repo[=[:space:]]|-R[[:space:]]+)([A-Za-z0-9._-]+/[A-Za-z0-9._-]+)' origin case "$sid" in ''|.|..|*[!A-Za-z0-9._-]*) return 0 ;; esac sd="$(yt_session_home)/$sid" [ -f "$sd/coordinate" ] || return 0 @@ -49,9 +51,18 @@ red_main() { yt_git_ctx "${YT_CWD:-$PWD}" def=$(yt_standing_default_ref "$YT_TOPLEVEL"); def="${def#refs/remotes/origin/}"; def="${def#refs/heads/}" [ -n "$def" ] && [ "$br" = "$def" ] || return 0 + # Another repository's main is not this one's: --repo/-R must name origin. + if [[ "$cmd" =~ $re_repo ]]; then + origin=$(git -C "$YT_TOPLEVEL" remote get-url origin 2>/dev/null | sed -E 's#\.git$##; s#.*[:/]([^/:]+/[^/]+)$#\1#' | tr '[:upper:]' '[:lower:]') + [ -n "$origin" ] && [ "$origin" = "$(printf '%s' "${BASH_REMATCH[2]}" | tr '[:upper:]' '[:lower:]')" ] || return 0 + fi jq_bin=$(yt_jq); [ -n "$jq_bin" ] || return 0 out=$(printf '%s' "$YT_STDIN" | "$jq_bin" -r '(.tool_response | objects | .stdout) // "" | tostring' 2>/dev/null) - bad=$(printf '%s\n' "$out" | grep -E '^completed (failure|timed_out|startup_failure) |"conclusion": *"(failure|timed_out|startup_failure)"|^X ' 2>/dev/null) + # Only the newest run of each workflow counts (gh lists newest first). + case "$out" in + '['*) bad=$(printf '%s' "$out" | "$jq_bin" -c 'reduce .[] as $r ({}; ($r.workflowName // "") as $w | if has($w) then . else .[$w] = $r end) | .[] | select(.conclusion == "failure" or .conclusion == "timed_out" or .conclusion == "startup_failure")' 2>/dev/null) ;; + *) bad=$(printf '%s\n' "$out" | awk -F '\t' 'NF >= 7 && !seen[$4]++ && $1 == "completed" && ($2 == "failure" || $2 == "timed_out" || $2 == "startup_failure")') ;; + esac [ -n "$bad" ] || return 0 key=$(printf '%s' "$bad" | cksum | tr -d ' ') grep -qxF -- "$key" "$sd/red-main-said" 2>/dev/null && return 0 diff --git a/hooks/pre-compact b/hooks/pre-compact index 710867d..8b336aa 100644 --- a/hooks/pre-compact +++ b/hooks/pre-compact @@ -23,6 +23,15 @@ trap '' PIPE . "$(cd "$(dirname "$0")" && pwd)/lib/git-ctx.sh" yt_read_stdin + +# A coordinate session (the marker the coordinate preamble writes) counts its +# compactions beside the marker, wherever its cwd is: hooks/session-start and +# hooks/stop say to rotate from them (issue #83, coordinate Step 12). +case "${YT_SESSION_ID:-}" in ''|.|..|*[!A-Za-z0-9._-]*) ;; *) + _SD="$(yt_session_home)/$YT_SESSION_ID" + [ ! -f "$_SD/coordinate" ] || printf '%s\n' "$(date +%s)" >> "$_SD/compactions" 2>/dev/null ;; +esac + yt_git_ctx "${YT_CWD:-$PWD}" YT_DIR=$(yt_resolve_yt_dir) @@ -101,14 +110,6 @@ else echo "[ytstack pre-compact] could not write $AUTO" >&2 fi -# A coordinate session (the marker the coordinate preamble writes) counts its -# compactions beside the marker: hooks/session-start and hooks/stop say to -# rotate from them (issue #83, coordinate Step 12). -case "${YT_SESSION_ID:-}" in ''|.|..|*[!A-Za-z0-9._-]*) ;; *) - _SD="$(yt_session_home)/$YT_SESSION_ID" - [ ! -f "$_SD/coordinate" ] || printf '%s\n' "$(date +%s)" >> "$_SD/compactions" 2>/dev/null ;; -esac - # Compaction instructions (stdout, exit 0). Keep well under the 10,000-char cap. INSTR="ytstack compaction guidance. Preserve verbatim in the summary: - Project ${PROJECT:-unknown}, position ${CURRENT_MILESTONE:-none}${ACTIVE_SLICE:+ / $ACTIVE_SLICE}${ACTIVE_TASK:+ / $ACTIVE_TASK}, working tree $YT_TOPLEVEL${YT_IS_LINKED:+ (linked worktree: $YT_IS_LINKED)}. diff --git a/hooks/pre-tool-use-agent b/hooks/pre-tool-use-agent index 8ef8db2..2637328 100644 --- a/hooks/pre-tool-use-agent +++ b/hooks/pre-tool-use-agent @@ -17,8 +17,8 @@ # # Bash (issue #83): a `gh pr merge` by hand gets the ytstack-finish-lane merge # line, a `gh pr close` the line that a cap waits (parked) and CI reruns with -# gh run rerun. Only a call after a command separator, optionally behind the -# wrapper tokens of hooks/post-tool-use-bash, counts; an echo of the words not. +# gh run rerun. Only a command counts (see gh_pr below); the words in quotes, +# in a comment or in an echo do not. # # Files only. Fail open: any problem ends silent with exit 0. @@ -73,12 +73,29 @@ emit() { # emit : the PreToolUse additionalContext, then exit 0 } if [ "$TOOL" = Bash ]; then - _WRAP='((rtk|sudo|command|env([[:space:]]+[A-Za-z_][A-Za-z0-9_]*=[^[:space:]]*)*)[[:space:]]+)*' - _GH="(^|[;&|()])[[:space:]]*${_WRAP}gh[[:space:]]+pr[[:space:]]+" - _MERGE="${_GH}merge([[:space:]]|\$)"; _CLOSE="${_GH}close([[:space:]]|\$)" - if [[ "$YT_TOOL_CMD" =~ $_MERGE ]]; then + # gh_pr: "merge" or "close" when a command (not quoted text, not a comment) + # runs gh pr merge|close: per line and per segment between ; & | ( ) && ||, + # after assignments, if/then/!/time, rtk/sudo/command/exec/nohup, env and + # xargs with their options, and gh's own -R/--repo. + GH_PR=$(printf '%s\n' "$YT_TOOL_CMD" | awk -v q="'" ' + { + l = $0; gsub(q "[^" q "]*" q, " ", l); gsub(/"[^"]*"/, " ", l); sub(/(^|[ \t])#.*/, "", l) + n = split(l, seg, /[;&|()]/) + for (i = 1; i <= n; i++) { + m = split(seg[i], t, /[ \t]+/); j = 1 + while (j <= m && t[j] == "") j++ + while (j <= m && (t[j] ~ /^[A-Za-z_][A-Za-z0-9_]*=/ || t[j] ~ /^(if|then|else|elif|do|while|until|!|time|rtk|sudo|command|exec|nohup)$/)) j++ + if (t[j] == "env") { j++; while (j <= m && (t[j] ~ /=/ || t[j] ~ /^-/)) j++ } + if (t[j] == "xargs") { j++; while (j <= m && t[j] ~ /^-/) { if (t[j] ~ /^-[nPILsdE]$/) j++; j++ } } + if (t[j] != "gh") continue + j++ + while (j <= m && t[j] ~ /^-/) { if (t[j] == "-R" || t[j] == "--repo") j++; j++ } + if (t[j] == "pr" && (t[j + 1] == "merge" || t[j + 1] == "close")) { print t[j + 1]; exit } + } + }' 2>/dev/null) + if [ "$GH_PR" = merge ]; then emit "ytstack: in a coordinator session a merge goes through bash \"$ROOT/bin/ytstack-finish-lane\" -C merge --pr --at --verdict-pattern '^Verdict: approved', after the route (ytstack:coordinate Step 6 and Step 7, ytstack:finish-lane Step 11). It reads the gates and merges at the reviewed commit only; gh pr merge by hand skips both." - elif [[ "$YT_TOOL_CMD" =~ $_CLOSE ]]; then + elif [ "$GH_PR" = close ]; then emit "ytstack: a coordinator never closes, reopens to retrigger or deletes the branch of a lane's pull request (HARD-GATE of ytstack:coordinate). A cap waits: bash \"$ROOT/bin/ytstack-frontier\" set --status parked --next \"wait for the cap\", the pull request stays open. A check reruns with gh run rerun --failed. Only the person closes open work; if the person asked to close this one, go on." fi exit 0 diff --git a/tests/hooks-coordinate.test.sh b/tests/hooks-coordinate.test.sh index b69264e..37bf4ea 100644 --- a/tests/hooks-coordinate.test.sh +++ b/tests/hooks-coordinate.test.sh @@ -104,6 +104,20 @@ has "behind cd and a wrapper too" "$(ctx .hookSpecificOutput.additionalContext)" tool a1 Bash "gh pr close 14 --comment 'cap'" has "gh pr close: a cap waits" "$(ctx .hookSpecificOutput.additionalContext)" "--status parked" has "and CI reruns" "$(ctx .hookSpecificOutput.additionalContext)" "gh run rerun" +# a command, not text (PR #94 review) +hint() { tool a1 Bash "$1"; case "$OUT" in *finish-lane*) HV=merge ;; *parked*) HV=close ;; '') HV=silent ;; *) HV=other ;; esac + [ -z "$OUT" ] || printf '%s' "$OUT" | "$JQ" -e . >/dev/null 2>&1 || HV="$HV invalid-json"; eq "$2: $(printf '%s' "$1" | tr '\n' '|')" "$3" "$HV"; } +hint $'cd /x\ngh pr merge 12 --squash' "on the next line" merge +hint 'if gh pr merge 12; then echo ok; fi' "after if" merge +hint 'GH_TOKEN=x gh pr merge 12' "behind an assignment" merge +hint 'gh -R o/r pr merge 12' "with -R before pr" merge +hint 'gh --repo o/r pr close 9' "with --repo before pr" close +hint 'xargs -n1 gh pr close < list' "behind xargs" close +hint 'test -n "$x" || gh pr close 4' "after ||" close +hint 'git commit -m "docs: note; gh pr merge is forbidden"' "inside double quotes" silent +hint "echo 'a; gh pr close 3'" "inside single quotes" silent +hint '# later: ; gh pr merge 5' "in a comment" silent +hint 'ls # gh pr merge 5' "in a trailing comment" silent tool a1 Bash "gh pr view 12 --json state"; eq "another gh call: silent" "" "$OUT" tool a1 Bash "echo 'gh pr merge is not run here' > notes.txt"; eq "an echo of the words: silent" "" "$OUT" eq "Bash calls are no dispatches" "$N0" "$(grep -c . "$SH/a1/dispatches")" @@ -190,18 +204,36 @@ stop r1; case "$(ctx .systemMessage)" in *"Rotate now"*) bad "once per compactio ss r1 startup; case "$C" in *"Compaction "*) bad "a startup source: no compaction line";; *) ok "a startup source: no compaction line";; esac compact plain1; ss plain1 compact; case "$C" in *"of this coordinator"*) bad "no marker: no compaction line";; *) ok "no marker: no compaction line";; esac eq "no marker: nothing counted" no "$([ -e "$SH/plain1/compactions" ] && echo yes || echo no)" +mkdir -p "$TMP/noyt"; "$JQ" -n --arg c "$TMP/noyt" '{session_id: "r1", cwd: $c, hook_event_name: "PreCompact"}' | bash "$H/pre-compact" >/dev/null 2>&1 +eq "a compaction in a directory without .ytstack still counts (PR #94 review)" 3 "$(grep -c . "$SH/r1/compactions")" echo "# post-tool-use-bash: a red default branch read with gh run list (issue #83)" DEF=$(git -C "$P" symbolic-ref --short HEAD) runs() { OUT=$("$JQ" -n --arg s "$1" --arg c "$P" --arg cmd "$2" --arg o "$3" '{session_id: $s, cwd: $c, hook_event_name: "PostToolUse", tool_name: "Bash", tool_input: {command: $cmd}, tool_response: {stdout: $o, stderr: "", interrupted: false}}' | bash "$H/post-tool-use-bash" 2>&1); } -RED=$(printf 'completed\tsuccess\tfix: a\tci\t%s\tpush\t101\t1m\t2h\ncompleted\tfailure\tfeat: b\tci\t%s\tpush\t102\t3m\t1h\n' "$DEF" "$DEF") +# gh run list prints the newest run first +RED=$(printf 'completed\tfailure\tfeat: b\tci\t%s\tpush\t102\t3m\t1h\ncompleted\tsuccess\tfix: a\tci\t%s\tpush\t101\t1m\t2h\n' "$DEF" "$DEF") GREEN=$(printf 'completed\tsuccess\tfix: a\tci\t%s\tpush\t101\t1m\t2h\n' "$DEF") runs a1 "gh run list --branch $DEF --limit 5" "$RED" has "a failed run on the default branch: run ytstack:lesson" "$(ctx .hookSpecificOutput.additionalContext)" "ytstack:lesson" eq "as PostToolUse context" PostToolUse "$(ctx .hookSpecificOutput.hookEventName)" runs a1 "gh run list --branch $DEF --limit 5" "$RED"; eq "the same failure: said once" "" "$OUT" -runs a1 "gh run list -b $DEF --json conclusion" '[{"conclusion":"success"},{"conclusion":"failure","databaseId":103}]' +runs a1 "gh run list -b $DEF --json conclusion,workflowName" '[{"conclusion":"failure","workflowName":"ci","databaseId":103},{"conclusion":"success","workflowName":"ci"}]' has "JSON output, -b: said" "$(ctx .hookSpecificOutput.additionalContext)" "ytstack:lesson" +# PR #94 review: only the newest run of each workflow counts; another repository is not this one +runs a1 "gh run list --branch $DEF --limit 10" "$(printf 'completed\tsuccess\tfix: repair\tci\t%s\tpush\t3\t9m\t1h\ncompleted\tfailure\tfeat: broke\tci\t%s\tpush\t2\t9m\t2h\n' "$DEF" "$DEF")" +eq "a failure the newer run of its workflow repaired: silent" "" "$OUT" +runs a1 "gh run list --branch $DEF" "$(printf 'in_progress\t\tfix\tci\t%s\tpush\t4\t1m\t1m\ncompleted\tfailure\tx\tci\t%s\tpush\t5\t1m\t1h\n' "$DEF" "$DEF")" +eq "a running newest run: silent" "" "$OUT" +runs a1 "gh run list --branch $DEF" "$(printf 'completed\tsuccess\ta\tci\t%s\tpush\t6\t1m\t1h\ncompleted\tfailure\tb\tdeploy\t%s\tpush\t7\t1m\t2h\n' "$DEF" "$DEF")" +has "another workflow's newest run failed: said" "$(ctx .hookSpecificOutput.additionalContext)" "ytstack:lesson" +runs a1 "gh run list -R other/repo --branch $DEF" "$(printf 'completed\tfailure\tz\tci\t%s\tpush\t8\t1m\t1h\n' "$DEF")" +eq "--repo of another repository: silent" "" "$OUT" +git -C "$P" remote add origin git@github.com:Acme/P.git +runs a1 "gh run list --repo acme/p --branch $DEF" "$(printf 'completed\tfailure\tz\tci\t%s\tpush\t9\t1m\t1h\n' "$DEF")" +has "--repo naming origin: said" "$(ctx .hookSpecificOutput.additionalContext)" "ytstack:lesson" +git -C "$P" remote remove origin +runs a1 "gh run list --json conclusion,workflowName --branch $DEF" '[{"conclusion":"success","workflowName":"ci"},{"conclusion":"failure","workflowName":"ci"}]' +eq "JSON: a failure behind a newer success of its workflow: silent" "" "$OUT" runs a1 "gh run list --branch $DEF" "$GREEN"; eq "all green: silent" "" "$OUT" runs a1 "gh run list --branch feature-x" "$(printf 'completed\tfailure\tx\tci\tfeature-x\tpush\t104\t1m\t1h\n')"; eq "another branch: silent" "" "$OUT" runs a1 "gh run list" "$(printf 'completed\tfailure\tx\tci\t%s\tpush\t105\t1m\t1h\n' "$DEF")"; eq "no --branch: silent" "" "$OUT" diff --git a/tests/ytstack-status.test.sh b/tests/ytstack-status.test.sh index 4cc8ff5..5e11b73 100644 --- a/tests/ytstack-status.test.sh +++ b/tests/ytstack-status.test.sh @@ -194,13 +194,13 @@ road "$P" M003 done "x S01" "- S02" road "$P" M004 active "x S01" "- S02" "- S03" "- S04" road "$P" M005 dropped "- S01" road "$P" M007 backlog "- S01" "- S02" -printf -- '---\nupdated: 2026-11-15T10:00:00Z\n---\n\n# Lanes\n\n| Lane | Kind | Status | Claimed by | Branch | Worktree | PR | Reviewed head | Round | Next action |\n|---|---|---|---|---|---|---|---|---|---|\n| M004-S02 | implement | merged | w 2026-11-15T08:00Z | - | - | 3 | abc1234 | 1 | - |\n| M004-S03 | implement | parked | w 2026-11-15T09:00Z | - | - | 4 | - | 1 | - |\n' > "$P/.ytstack/LANES.md" +printf -- '---\nupdated: 2026-11-15T10:00:00Z\n---\n\n# Lanes\n\n| Lane | Kind | Status | Claimed by | Branch | Worktree | PR | Reviewed head | Round | Next action |\n|---|---|---|---|---|---|---|---|---|---|\n| M004-S02 | implement | merged | w 2026-11-15T08:00Z | - | - | 3 | abc1234 | 1 | - |\n| M004-S03 | implement | in-review | w 2026-11-15T09:00Z | - | - | 4 | - | 1 | - |\n| M004-S04 | implement | parked | w 2026-11-15T09:30Z | - | - | 5 | - | 1 | - |\n' > "$P/.ytstack/LANES.md" ph "$P" eq "--phases: exit 0" 0 "$EC" eq "one line per phase, dropped and backlog left out, done counts all, the total, the read line" \ "M003${TAB}2/2 done (100%)${TAB}0 in review -M004${TAB}2/4 done (50%)${TAB}1 in review -total${TAB}4/6 done (66%)${TAB}1 in review" "$(printf '%s\n' "$OUT" | sed '$d')" +M004${TAB}2/4 done (50%)${TAB}2 in review +total${TAB}4/6 done (66%)${TAB}2 in review" "$(printf '%s\n' "$OUT" | sed '$d')" LOG=$(find "$TMP/data" -name denominator.log | head -1) like() { if printf '%s\n' "$3" | grep -E -- "$2" >/dev/null; then ok "$1"; else bad "$1" "no line matches /$2/ in: $3"; fi; } like "the last line: read time and the log" "^read [0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}Z, log .*/repos/[0-9a-f]+/phases/denominator.log\$" "$OUT" From 11409f1c7f56395a466918ff96543f1ff2808209 Mon Sep 17 00:00:00 2001 From: Alex Wegener Date: Sun, 15 Nov 2026 21:47:44 +0100 Subject: [PATCH 09/13] fix: the open-PR cap limits opening, never a merge (PR #94 review) With closing a lane PR forbidden, an open-prs gate on merge deadlocks. gates and merge drop --max-open; open-pr --max-open opens a draft at the cap (drafts do not count) and says so. coordinate dispatches no new implement lane at the cap; a parked PR leaves the count with gh pr ready --undo and comes back with gh pr ready. The two new checklist lines are shorter. Co-Authored-By: Claude Opus 5.5 --- bin/ytstack-finish-lane | 49 +++++++++++++------------------ docs/ux/coordinator-format.md | 8 ++--- skills/coordinate/SKILL.md | 2 +- skills/finish-lane/SKILL.md | 7 ++--- tests/ytstack-finish-lane.test.sh | 35 ++++++++++++---------- 5 files changed, 49 insertions(+), 52 deletions(-) diff --git a/bin/ytstack-finish-lane b/bin/ytstack-finish-lane index 75a28fc..f5e690a 100755 --- a/bin/ytstack-finish-lane +++ b/bin/ytstack-finish-lane @@ -6,13 +6,13 @@ # ytstack-finish-lane leftovers [--scope PATH ...] # ytstack-finish-lane commit --message MSG [--scope PATH ...] # ytstack-finish-lane push -# ytstack-finish-lane open-pr --title T --body-file F [--base B] +# ytstack-finish-lane open-pr --title T --body-file F [--base B] [--max-open N] # ytstack-finish-lane wait-head --pr N [--timeout SECONDS] # ytstack-finish-lane body-check --pr N | --body-file F [--base B] -# ytstack-finish-lane gates --pr N --reviewed-head SHA [--max-open N] +# ytstack-finish-lane gates --pr N --reviewed-head SHA # [--verdict-pattern ERE] [--allow-no-checks] # ytstack-finish-lane merge --pr N --at SHA [--method squash|merge|rebase] -# [--max-open N] [--verdict-pattern ERE] [--allow-no-checks] +# [--verdict-pattern ERE] [--allow-no-checks] # ytstack-finish-lane route --lane REF --base SHA --head SHA [--pr N] [--report F] # # All commands take -C DIR first: the lane's worktree (default: $PWD). A @@ -38,6 +38,9 @@ # push the current branch to origin, with upstream. A rejected push # stays rejected: the script has no way to overwrite the remote. # open-pr opens the pull request for the current branch; prints its number. +# With --max-open N and N or more open pull requests ready for +# review (drafts do not count), it opens a draft and says so on +# stderr: the cap limits opening, never a merge. # wait-head polls until the pull request's head on the host is the local # tip (default 120 s). A review starts only after this passed. # body-check backticked paths in the body (the pull request's, or a file's) @@ -58,8 +61,6 @@ # on the head must also match it (grep -E, per line) # threads no unresolved review thread # mergeable open and without a conflict -# open-prs with --max-open: at most N open pull requests -# ready for review (drafts do not count) # merge runs gates for --at SHA, merges only when all hold, pinned to # that commit on the host's side, and reads the state back. No # auto-merge, no administrator override. It does not read the @@ -252,13 +253,14 @@ cmd_push() { } cmd_open_pr() { - local title="" body="" base="" out n + local title="" body="" base="" max="" out n count="" draft=no while [ $# -gt 0 ]; do [ $# -ge 2 ] || bad_usage "$1 needs a value" case "$1" in --title) title="$2" ;; --body-file) body=$(abs "$2") ;; --base) base="$2" ;; + --max-open) max="$2"; is_int "$max" || bad_usage "--max-open is a number" ;; *) bad_usage "open-pr: unknown argument '$1'" ;; esac shift 2 @@ -266,11 +268,20 @@ cmd_open_pr() { [ -n "$title" ] && [ -n "$body" ] || bad_usage "open-pr needs --title and --body-file" [ -r "$body" ] && [ ! -d "$body" ] || bad_usage "cannot read body file '$body'" enter; need_gh; current_branch + # The cap (issue #83, PR #94 review) limits pull requests ready for review + # that are opened, never a merge: at the cap the new one opens as a draft. + if [ -n "$max" ]; then + count=$(gh pr list --state open --limit 1000 --json isDraft --jq '[.[] | select(.isDraft | not)] | length') \ + && is_int "$count" || die "gh could not count the open pull requests for --max-open" + [ "$count" -lt "$max" ] || draft=yes + fi set -- pr create --title "$title" --body-file "$body" --head "$BRANCH" [ -z "$base" ] || set -- "$@" --base "$base" + [ "$draft" = no ] || set -- "$@" --draft out=$(gh "$@") || die "gh pr create failed for $BRANCH" n=$(printf '%s\n' "$out" | tail -1); n="${n##*/}" is_int "$n" || die "gh pr create did not end with a pull request URL: $out" + [ "$draft" = no ] || echo "draft: $count open for review, limit $max: opened as a draft; gh pr ready $n once the count is under the cap" >&2 echo "$n" } @@ -356,7 +367,7 @@ EOF } # ---- gates, merge -------------------------------------------------------------- -PR=""; SHA=""; MAX_OPEN=""; PATTERN=""; ALLOW_NONE=no; METHOD=squash; HOST_HEAD=""; GATES_HOLD=yes +PR=""; SHA=""; PATTERN=""; ALLOW_NONE=no; METHOD=squash; HOST_HEAD=""; GATES_HOLD=yes # One answer per line, "keyvalue": the pull request with its checks and # the reviews on its head, read in one request so that they describe one commit. @@ -380,11 +391,8 @@ VIEW_JQ=' # shortcut: the first 100 review threads; more than that fails the gate instead # of being paged through. # shellcheck disable=SC2016 -# open: the open pull requests that are ready for review (drafts do not count -# toward a cap, issue #83), all open ones, and whether more than 100 are open. -THREADS_QUERY='query($owner: String!, $repo: String!, $number: Int!) { repository(owner: $owner, name: $repo) { pullRequests(states: OPEN, first: 100) { totalCount nodes { isDraft } } pullRequest(number: $number) { reviewThreads(first: 100) { totalCount pageInfo { hasNextPage } nodes { isResolved } } } } }' -THREADS_JQ='.data.repository | "open\t\([.pullRequests.nodes[]? | select(.isDraft | not)] | length)\t\(.pullRequests.totalCount)\t\(.pullRequests.totalCount > 100)", - (.pullRequest.reviewThreads | "threads\t\([ .nodes[] | select(.isResolved | not) ] | length)\t\(.totalCount)\t\(.pageInfo.hasNextPage)")' +THREADS_QUERY='query($owner: String!, $repo: String!, $number: Int!) { repository(owner: $owner, name: $repo) { pullRequest(number: $number) { reviewThreads(first: 100) { totalCount pageInfo { hasNextPage } nodes { isResolved } } } } }' +THREADS_JQ='.data.repository | (.pullRequest.reviewThreads | "threads\t\([ .nodes[] | select(.isResolved | not) ] | length)\t\(.totalCount)\t\(.pageInfo.hasNextPage)")' gate() { # if [ "$1" = ok ]; then printf 'ok %s: %s\n' "$2" "$3"; else printf 'FAIL %s: %s\n' "$2" "$3"; GATES_HOLD=no; fi @@ -399,7 +407,6 @@ gate_args() { case "$mode:$1" in *:--pr) PR="$2" ;; gates:--reviewed-head|merge:--at) SHA="$2" ;; - *:--max-open) MAX_OPEN="$2"; is_int "$MAX_OPEN" || bad_usage "--max-open is a number" ;; *:--verdict-pattern) PATTERN="$2" [ -n "$PATTERN" ] || bad_usage "--verdict-pattern is empty" @@ -418,7 +425,7 @@ gate_args() { # read_gates: one read of the host, one line per gate, the time of the read. # Returns 0 when every gate holds; sets HOST_HEAD. read_gates() { - local v g t short checks n open state m reviews newest unresolved total more count drafts + local v g t short checks n open state m reviews newest unresolved total more v=$(gh pr view "$PR" --json state,headRefOid,mergeable,statusCheckRollup,reviews --jq "$VIEW_JQ") \ && g=$(gh api graphql -f query="$THREADS_QUERY" -F owner='{owner}' -F repo='{repo}' -F number="$PR" --jq "$THREADS_JQ") # shellcheck disable=SC2181 @@ -469,20 +476,6 @@ EOF else gate FAIL mergeable "the host has not decided yet (${m:-no answer}); read again" fi - if [ -n "$MAX_OPEN" ]; then - IFS=$'\t' read -r count total more <. 5. After a compaction: run the coordinate preamble again, then rotate (Step 12). -6. Every round: ytstack-frontier check; act on each stale: line. -7. Merge: ytstack-finish-lane merge, never gh pr merge. Never close a lane PR: a cap waits (parked), CI reruns via gh run rerun. +6. Each round: ytstack-frontier check, act on each stale: line. +7. Merge via ytstack-finish-lane; never gh pr merge or close a lane PR (cap: parked; CI: gh run rerun). ## `LANES.md` -- who works on what @@ -45,7 +45,7 @@ updated: 2026-11-13T10:42:00Z |---|---| | Lane | The reference. Unique in the file. | | Kind | `implement`, `review` or `prepare` (see "Lane kinds"). | -| Status | `claimed` (taken, not dispatched yet), `running`, `reported` (the worker's report is in and passed the check), `in-review`, `ready` (its gates held when last read), `parked` (held; its pull request waits open, for a cap on open pull requests or for a person; never closed to make room), `merged`, `blocked`, `dropped`. What the coordinator did or saw last; not a host fact. | +| Status | `claimed` (taken, not dispatched yet), `running`, `reported` (the worker's report is in and passed the check), `in-review`, `ready` (its gates held when last read), `parked` (held; its pull request waits open, for a person or for the cap on open pull requests, then as a draft: the cap counts pull requests ready for review, limits opening and dispatching, never a merge; `gh pr ready ` under the cap, `gh pr ready --undo` takes one out of the count; never closed to make room), `merged`, `blocked`, `dropped`. What the coordinator did or saw last; not a host fact. | | Claimed by | The worker's name and the UTC time of the claim. `-` when nobody holds it. | | Branch, Worktree | Where the work is. `-` when it does not apply. | | PR | The number, as an identifier. Its state is read from the host when needed. | @@ -270,7 +270,7 @@ The `coordinate` preamble writes the session marker `/ - `hooks/pre-tool-use-agent` also adds a line when an `Agent` call that is no lookup has no `isolation` (dispatch lane work with `isolation: "worktree"`), and, on `Bash`, when the command runs `gh pr merge` (the merge is `ytstack-finish-lane merge --at `) or `gh pr close` (a cap waits with the lane `parked`, a check reruns with `gh run rerun`). Advisory, never a deny: the person may have asked for that close. - `hooks/pre-compact` counts the session's compactions in `compactions` beside the marker. After one, `hooks/session-start` says `Compaction N of this coordinator: ytstack:coordinate Step 12, rotate now`; from the second on, `hooks/stop` says it too, once per compaction. -- `hooks/post-tool-use-bash` adds one note when the output of `gh run list --branch ` shows a failed run (the tab-separated form, JSON `"conclusion": "failure"`, or the terminal form): a red main, run `ytstack:lesson`. One note per distinct set of failed lines. +- `hooks/post-tool-use-bash` adds one note when the output of `gh run list --branch ` shows that the newest run of a workflow failed (the tab-separated form or a JSON array with `conclusion` and `workflowName`; with `--repo`/`-R` only for the repository of `origin`): a red main, run `ytstack:lesson`. One note per distinct set of failed runs. - `hooks/stop` gives a coordinate session no reminder about the `STATE.md` task pointer: a coordinator holds no task. Claude Code only: Codex registers no UserPromptSubmit or Agent hook of ytstack (its subagent tools are not covered), its PreToolUse and PostToolUse entries on `Bash` run only the PR watch, and Kimi's shell has no session id to write the marker with. On both the skill text (HARD-GATE, Steps 5, 6 and 12) carries these rules without the hooks. diff --git a/skills/coordinate/SKILL.md b/skills/coordinate/SKILL.md index 3214996..438b24d 100644 --- a/skills/coordinate/SKILL.md +++ b/skills/coordinate/SKILL.md @@ -244,7 +244,7 @@ A lane named in the `blocks:` of an open or asked question is not ready, whateve **Lesson lanes.** The frontier lists a lesson whose check is still to be built as `lesson-F###` after the slices (`docs/ux/coordinator-format.md`, "Lesson lanes"). It is dispatched like any lane, with `ytstack-signals set F### --state planned --ref lesson-F###` at the claim. A lesson lane listed as `blocked` with "unplanned" needs its `## Files` and `## Verification` first: write them into the lesson from what it says (the check, where it lives, the command that fails on what happened), as you write any file under `.ytstack/`. -**Step 6 -- Finish reported lanes.** A `reported` lane goes through `ytstack:finish-lane`: the review at a pinned head with the class its reviewer states, the route of the change, the gates read from the host, the merge at the reviewed commit or not at all. Who merges follows `merge_by` in `PREFERENCES.md`. With `risk`, the default, `finish-lane` merges a lane itself when `bin/ytstack-finish-lane route` printed `route: unattended` and the host's gates hold; every other lane stops at `ready` with its merge command and the reasons, and waits for a person. You state no class and you change no ceiling: the class is the reviewer's, the ceiling stands in the area file of the technical spec (`docs/ux/review-policy-format.md`). A change that requires lenses (`.ytstack/spec/REVIEW.md`) gets one more fresh reviewer per lens from `finish-lane`. A lens reviewer is a lane of kind `review` and never the lane's worker; a lens with visual evidence needs a session that can start the product and has a browser tool. One lane at a time per pull request. `finish-lane` writes the reviewed head and the round into the lane's row; a row that lacks them after a review is repaired before anything else (`ytstack-frontier set --head --round --pr `). Never merge around it. A cap on open pull requests, when the project or a standing instruction sets one, is a gate of `finish-lane` and counts the pull requests that are ready for review; drafts do not count. A lane that waits for it is set to `parked` (`ytstack-frontier set --status parked --next "wait for the cap"`) and its pull request stays open. A pull request is never closed to get under the cap, and never closed and reopened to retrigger a check: `gh run rerun --failed` does that. +**Step 6 -- Finish reported lanes.** A `reported` lane goes through `ytstack:finish-lane`: the review at a pinned head with the class its reviewer states, the route of the change, the gates read from the host, the merge at the reviewed commit or not at all. Who merges follows `merge_by` in `PREFERENCES.md`. With `risk`, the default, `finish-lane` merges a lane itself when `bin/ytstack-finish-lane route` printed `route: unattended` and the host's gates hold; every other lane stops at `ready` with its merge command and the reasons, and waits for a person. You state no class and you change no ceiling: the class is the reviewer's, the ceiling stands in the area file of the technical spec (`docs/ux/review-policy-format.md`). A change that requires lenses (`.ytstack/spec/REVIEW.md`) gets one more fresh reviewer per lens from `finish-lane`. A lens reviewer is a lane of kind `review` and never the lane's worker; a lens with visual evidence needs a session that can start the product and has a browser tool. One lane at a time per pull request. `finish-lane` writes the reviewed head and the round into the lane's row; a row that lacks them after a review is repaired before anything else (`ytstack-frontier set --head --round --pr `). Never merge around it. A cap on open pull requests, when the project or a standing instruction sets one, counts the pull requests that are ready for review (drafts do not count) and limits what is opened, never a merge: merging lowers the count. While the count is at the cap, no new implement lane is dispatched, and `finish-lane` opens a reported lane's pull request as a draft (`open-pr --max-open`) and sets the lane `parked` (`ytstack-frontier set --status parked --next "wait for the cap"`); `gh pr ready ` takes it out of draft under the cap, `gh pr ready --undo` takes a parked one out of the count. A pull request is never closed to get under the cap, and never closed and reopened to retrigger a check: `gh run rerun --failed` does that. **Step 7 -- Run the factory tools.** The plugin already ships what a coordinator under load starts to build by hand: a pull request babysitter, a review tiering, a release check. Use these tools and build none of your own. `ytstack:finish-lane` runs the route, the release watch and the escape check for the merges it makes (its Steps 9, 12 and 13), and the lesson of a blocked review or a red check of its lane (its Step 14); this step holds for everything else too: a merge you make yourself, a merge a person made, a release, a signal. A tool is skipped only for the reason in its row; the preamble prints the lines that decide it (`MERGE_BY`, `REVIEW_POLICY`, `OWN_REVIEWERS`, `PR_WATCH`, `RELEASE`, `SIGNALS`). diff --git a/skills/finish-lane/SKILL.md b/skills/finish-lane/SKILL.md index b439b67..fb8ba83 100644 --- a/skills/finish-lane/SKILL.md +++ b/skills/finish-lane/SKILL.md @@ -233,7 +233,7 @@ Lane: {REF} "${CLAUDE_SKILL_DIR}/../../bin/ytstack-frontier" set {REF} --pr {N} ``` -`open-pr` prints the number. When it fails, `gh` said why above the last line: not signed in is the user's to fix; a pull request that already exists for the branch is the one to use. +Add `--max-open {n}` to `open-pr` when a standing instruction or the plan caps the open pull requests. The cap counts the ones ready for review (drafts do not count) and limits opening, never a merge: at the cap the pull request opens as a draft (`draft:` line), the lane is `parked` (`"${CLAUDE_SKILL_DIR}/../../bin/ytstack-frontier" set {REF} --status parked --next "wait for the cap"`), and `gh pr ready {N}` takes it out of draft once the count is under the cap. `gh pr ready {N} --undo` turns a parked pull request that is still ready for review into a draft; none is closed to make room. `open-pr` prints the number. When it fails, `gh` said why above the last line: not signed in is the user's to fix; a pull request that already exists for the branch is the one to use. ### Step 5: Wait for the head, check the body @@ -354,7 +354,7 @@ The route speaks about the change, not about the host: the checks, the threads a "${CLAUDE_SKILL_DIR}/../../bin/ytstack-finish-lane" -C {WT} gates --pr {N} --reviewed-head {SHA} --verdict-pattern '^Verdict: approved' ``` -Add `--max-open {n}` when a standing instruction or the plan caps the open pull requests (the gate counts the ones ready for review; drafts do not count), and `--allow-no-checks` only when the project states that this repository runs no checks. The output is one line per gate (`ok` or `FAIL`) and a last line `read `. Keep both for the report. +A cap on open pull requests is no gate here: merging lowers the count. Add `--allow-no-checks` only when the project states that this repository runs no checks. The output is one line per gate (`ok` or `FAIL`) and a last line `read `. Keep both for the report. All hold: `ytstack-frontier set {REF} --status ready --next "merge at {SHA}"`. Otherwise the failing gate says what happens next: @@ -365,7 +365,6 @@ All hold: `ytstack-frontier set {REF} --status ready --next "merge at {SHA}"`. O | `review` | changes are requested on this head, or the posted verdict is missing | Open findings go to the worker. A missing verdict means Step 7 did not happen on this head. | | `threads` | a review thread is unresolved | It is answered and resolved by whoever owns it: the worker for a finding in its code, the human for a question to them. You resolve no thread you did not open. | | `mergeable` | a conflict with the base, or the host has not decided | Conflict: the worker integrates the base; the head moves, so the fix round follows. Undecided: read again. | -| `open-prs` | more pull requests are ready for review than the cap | Finish others first. The lane waits as `parked` (`"${CLAUDE_SKILL_DIR}/../../bin/ytstack-frontier" set {REF} --status parked --next "wait for the cap"`) with its pull request open; none is closed to make room. | ### Step 11: Merge or hand over @@ -434,7 +433,7 @@ Invoke `ytstack:review-lessons` with the pull request `{N}`. It reads the review ### Step 14: Lesson -A review that requested changes, a lens that failed and a check that failed are incidents: something got this far that should not have. Each one gets its lesson before the lane goes back, also in round 2. Invoke `ytstack:lesson` once per event of this run and hand it: what got through (the blocking finding in one sentence, or the failed check's name), the lane `{REF}`, the pull request `{N}` and the commit `{SHA}`; the area `review` for a round or a lens, `ci` for a check; and that this session changes no code: a check the lesson needs becomes a lesson lane or goes into the fix brief, never an edit from here. A check that is only pending, and a gate that failed for the host's reasons (the head moved, a conflict, the cap on open pull requests), are no incident. Its `Recorded:` line goes into the report. +A review that requested changes, a lens that failed and a check that failed are incidents: something got this far that should not have. Each one gets its lesson before the lane goes back, also in round 2. Invoke `ytstack:lesson` once per event of this run and hand it: what got through (the blocking finding in one sentence, or the failed check's name), the lane `{REF}`, the pull request `{N}` and the commit `{SHA}`; the area `review` for a round or a lens, `ci` for a check; and that this session changes no code: a check the lesson needs becomes a lesson lane or goes into the fix brief, never an edit from here. A check that is only pending, and a gate that failed for the host's reasons (the head moved, a conflict), are no incident. Its `Recorded:` line goes into the report. ### Step 15: Report + return diff --git a/tests/ytstack-finish-lane.test.sh b/tests/ytstack-finish-lane.test.sh index 803e3a1..4fd5d10 100644 --- a/tests/ytstack-finish-lane.test.sh +++ b/tests/ytstack-finish-lane.test.sh @@ -72,6 +72,7 @@ answer() { } case "${1:-} ${2:-}" in "pr create") [ ! -f "$GH_FIX/create.fail" ] || { echo "fake gh: create failed" >&2; exit 1; }; cat "$GH_FIX/create.out" ;; + "pr list") answer "$GH_FIX/list.json" ;; "pr view") [ ! -f "$GH_FIX/view.fail" ] || { echo "fake gh: view failed" >&2; exit 1; }; answer "$GH_FIX/view.json" ;; "api graphql") answer "$GH_FIX/graphql.json" ;; "api repos/"*/pulls/*/reviews) answer "$GH_FIX/reviews.json" ;; @@ -235,6 +236,17 @@ run "$P" open-pr --title T --body-file "$TMP/body.md" eq "no pull request URL in the answer: open-pr fails" 1 "$EC" run "$P" open-pr --title T --body-file "$TMP/none.md" eq "an unreadable body file: exit 64" 64 "$EC" +# The cap limits opening, never merging (issue #83, PR #94 review): at the cap +# the new pull request opens as a draft; drafts do not count. +echo "https://github.com/acme/app/pull/8" > "$GH_FIX/create.out" +printf '[{"isDraft":false},{"isDraft":true},{"isDraft":false}]\n' > "$GH_FIX/list.json" +quiet; run "$P" open-pr --title T --body-file "$TMP/body.md" --max-open 3 +eq "under the cap (2 ready, a draft not counted): exit 0" 0 "$EC" +hasnt "and not a draft" "--draft" "$(calls)" +quiet; run "$P" open-pr --title T --body-file "$TMP/body.md" --max-open 2 +eq "at the cap: still opened" "0 8" "$EC $(printf '%s\n' "$OUT" | tail -1)" +has "as a draft" "--draft" "$(calls)" +has "and says how to take it out of draft" "draft: 2 open for review, limit 2: opened as a draft; gh pr ready 8" "$OUT" # ---- 5. wait-head ------------------------------------------------------------- echo "# wait-head" @@ -302,8 +314,7 @@ has "it says so" "not in this checkout" "$OUT" # ---- 7. gates ----------------------------------------------------------------- echo "# gates" G="$P"; SHA="$TIP" -# host: a pull request at $SHA whose gates all hold, 3 open pull requests ready -# for review and one draft (issue #83: the cap counts the ready ones), one resolved thread +# host: a pull request at $SHA whose gates all hold, one resolved thread host() { jq -n --arg h "$SHA" '{state: "OPEN", headRefOid: $h, mergeable: "MERGEABLE", statusCheckRollup: [ @@ -313,7 +324,7 @@ host() { reviews: [ {author: {login: "rev"}, state: "COMMENTED", submittedAt: "2026-11-13T10:00:00Z", commit: {oid: $h}, body: "Verdict: approved\r\nReviewed commit: \($h)"} ]}' > "$GH_FIX/view.json" - jq -n '{data: {repository: {pullRequests: {totalCount: 4, nodes: [{isDraft: false}, {isDraft: true}, {isDraft: false}, {isDraft: false}]}, + jq -n '{data: {repository: { pullRequest: {reviewThreads: {totalCount: 1, pageInfo: {hasNextPage: false}, nodes: [{isResolved: true}]}}}}}' > "$GH_FIX/graphql.json" rm -f "$GH_FIX"/*.fail "$GH_FIX/merge.queue" "$GH_FIX/log" } @@ -335,10 +346,10 @@ case "$(printf '%s\n' "$OUT" | tail -1)" in esac has "the checks line counts them and names the commit" "ok checks: 3 concluded successfully on ${SHA:0:7}" "$OUT" has "the threads were read for this pull request" "-F number=7" "$(calls)" -host; run "$G" gates --pr 7 --reviewed-head "${SHA:0:7}" --max-open 3 -eq "a short commit id and a limit that is just met: exit 0" 0 "$EC" -has "the limit has its own line, drafts not counted" "ok open-prs: 3 open for review, limit 3 (1 draft not counted)" "$OUT" -has "the query reads the drafts" "isDraft" "$(calls)" +host; run "$G" gates --pr 7 --reviewed-head "${SHA:0:7}" +eq "a short commit id: exit 0" 0 "$EC" +host; run "$G" gates --pr 7 --reviewed-head "$SHA" --max-open 3 +eq "the cap is no gate of a merge (PR #94 review): exit 64" 64 "$EC" host; tweak view '.headRefOid = "ffffffffffffffffffffffffffffffffffffffff"'; gates only "the head moved after the review" head @@ -377,12 +388,6 @@ host; tweak view '.mergeable = "UNKNOWN"'; gates only "mergeability the host has not decided" mergeable host; tweak view '.state = "CLOSED"'; gates only "a closed pull request" mergeable -host; gates --max-open 2 -only "too many open pull requests" open-prs -has "count and limit are printed" "3 open for review, limit 2" "$OUT" -host; tweak graphql '.data.repository.pullRequests |= (.totalCount = 140)'; gates --max-open 5 -only "more open pull requests than were read" open-prs -has "says so" "140 open, only the first 100 were read" "$OUT" host; gates --verdict-pattern '^Verdict: approved$' eq "the newest review matches the verdict pattern: exit 0" 0 "$EC" @@ -403,10 +408,10 @@ eq "all gates hold: merge succeeds" 0 "$EC" has "the merge is pinned to the full reviewed commit" "pr merge 7 --squash --match-head-commit $SHA" "$(calls)" eq "it prints what it merged and where" "merged #7 at $SHA (squash)" "$(printf '%s\n' "$OUT" | tail -1)" has "after the gate lines" "ok head: ${SHA:0:7} is the reviewed commit" "$OUT" -host; run "$G" merge --pr 7 --at "$SHA" --method rebase --max-open 5 --verdict-pattern 'approved' +host; run "$G" merge --pr 7 --at "$SHA" --method rebase --verdict-pattern 'approved' eq "method and gate options pass through" 0 "$EC" has "the method reaches gh" "pr merge 7 --rebase --match-head-commit $SHA" "$(calls)" -has "the limit was checked" "ok open-prs: 3 open for review, limit 5" "$OUT" +hasnt "no open-prs gate before a merge" "open-prs" "$OUT" host; tweak view '.headRefOid = "ffffffffffffffffffffffffffffffffffffffff"'; run "$G" merge --pr 7 --at "$SHA" eq "the head moved after the review: merge refuses" 1 "$EC" has "the gate is named" "FAIL head:" "$OUT" From 18d12865eb84cdcd3578205b6f0a28277ea4f303 Mon Sep 17 00:00:00 2001 From: Alex Wegener Date: Sun, 15 Nov 2026 21:47:45 +0100 Subject: [PATCH 10/13] docs: spec, DECISIONS and CHANGELOG for the PR #94 review fixes Co-Authored-By: Claude Opus 5.5 --- .ytstack/DECISIONS.md | 16 ++++++++++++++++ .ytstack/spec/checks-and-evals.md | 4 ++-- .ytstack/spec/hooks-and-state.md | 14 +++++++------- .ytstack/spec/skills.md | 6 +++--- CHANGELOG.md | 19 ++++++++++++------- 5 files changed, 40 insertions(+), 19 deletions(-) diff --git a/.ytstack/DECISIONS.md b/.ytstack/DECISIONS.md index 8c27111..9c524b2 100644 --- a/.ytstack/DECISIONS.md +++ b/.ytstack/DECISIONS.md @@ -1507,3 +1507,19 @@ Plus: ops-layer split during the same session (yopstack created as own public re **How to apply:** This replaces the first two "How to apply" points of "2026-11-15: `finish-lane`'s route checks the spec delta; a gap routes to a person (issue #75)": a plan of the range that names an area is still checked with `impact` and the report cannot override it, but a plan no longer stands in for areas its task did not touch. **Supersedes:** None. Narrows the entry named above. + +## 2026-11-15: The open-PR cap limits opening, never a merge; origin's STATE.md is read only when the checkout is strictly behind and unedited (review of PR #94) + +**Context:** The independent review of PR #94 found two flaws. With closing a lane's pull request forbidden, an `open-prs` gate on `merge` deadlocks: at the cap nothing merges, so the count never falls. And `yt_behind_origin` replaced a diverged or locally edited `STATE.md` with origin's copy, and gave an empty pointer in user scope. + +**Options considered:** +- Cap: keep it a merge gate and exclude the PR being merged; or move it to opening and dispatching. +- Behind: read origin's copy whenever behind; or only when it is safe. + +**Chose:** The cap counts pull requests ready for review and limits what is opened and dispatched, never a merge (merging lowers the count). `ytstack-finish-lane open-pr --max-open N` opens a draft at the cap and says so; `gates` and `merge` have no cap. The lane is `parked`; `gh pr ready ` under the cap, `gh pr ready --undo` takes a parked one out of the count; nothing is closed. Origin's `STATE.md` is read only when HEAD is an ancestor of `origin/`, the range changed `STATE.md` and the working tree's copy equals HEAD's; diverged or edited with an origin change gives "N ahead, M behind" and the local file, without `--ff-only`. Without origin's copy (user scope, untracked) the behind logic stays out entirely. + +**Reason:** A gate that only a forbidden action can open is a deadlock. Origin's copy is only a better truth than the local one when the local one is an unedited ancestor. + +**How to apply:** While the ready-for-review count is at the cap, the coordinator dispatches no new implement lane. + +**Supersedes:** Narrows "2026-11-15: Hooks read a stale checkout from origin ..." (the behind conditions; "the `open-prs` gate counts pull requests ready for review" becomes the cap on opening). diff --git a/.ytstack/spec/checks-and-evals.md b/.ytstack/spec/checks-and-evals.md index a867d8c..cd5b45d 100644 --- a/.ytstack/spec/checks-and-evals.md +++ b/.ytstack/spec/checks-and-evals.md @@ -96,7 +96,7 @@ Everything that tells a contributor whether a change is acceptable: the static c - `bin/ytstack-frontier`: `list` prints lane, state and detail per slice (done, claimed, blocked, ready) of the current milestone (with `none`: the highest roadmap not `done`, `dropped`, `shipped-informally` or `backlog`), then one lesson lane `lesson-F###` per open or planned lesson whose target is a check (blocked without non-empty "Files" and "Verification" in the lesson; listed also without a milestone); `claim` refuses a held lane and names the holder (held: `claimed`, `running`, `reported`, `in-review`, `ready`, and `parked`, a lane whose pull request waits open for a cap or a person, issue #83); `claim`, `set` and `release` change one row of `LANES.md` under a lock; `check` validates the file and then prints one `stale:` line per lane that stalls, exit 2 (issue #84): a `running` row whose worktree no longer exists, an `implement` row whose branch had no commit for `--minutes` (default 60, from the claim when that is newer, or from the first sight of its fix round when the row carries a pull request), a `review` or `prepare` row running 3 x `--minutes` since its claim, and a `ready` lane nobody claimed for `--minutes` since a check first saw it (first sights in `/repos//frontier-seen`, outside the tree, under a noclobber lock); `peer set` and `peer list` keep the `## Peers` lines of `LANES.md` (role, repository, address, last contact), list items that no table reader sees. The lock is the file `LANES.md.lock`, created by the shell under noclobber and not by `mkdir`, which is no lock on Ubuntu 26.04 (see `.ytstack/KNOWLEDGE.md`). - `bin/ytstack-plans` (`docs/ux/external-plans.md`): `scan` counts the work rows (task-list items, rows of tables with a status or checkbox column, nothing in a code fence) of `plans/`, `roadmap/` and their variants and prints one line per directory with `verdict=large` from 10 open rows and the answer recorded in `PREFERENCES.md`; exit 0 only for a large directory without an answer. `rows` prints `path:line`, state, id, section and title per row; a relative PATH is read from where the command was started, else from the repository root, and the output names files relative to the root. It writes nothing; the mapping is the agent's (`reconcile`, `adopt-brownfield`). `bin/ytstack-reconcile` (the two migration classes of `reconcile`, issue #76): `skeletons` lists, per open task of a slice that has no task plan at all and no `## Files` of its own, in a milestone not done, dropped, shipped-informally or backlog, the task, the plan to write beside the slice plan and the number of paths found; `--write` (optionally `--slice M###-S##`) writes each in `plan-task`'s format with Files from the task line's backticked paths or the slice plan's `Own:`/`Files:` lines, Spec impact lines per area with `TODO` fields that `ytstack-spec impact` rejects until filled, a `TODO` verification, `skeleton: reconcile `, and never over an existing file. `pointer` says `ok`, `no milestone in progress` or `behind` (exit 10) when `current_milestone` is closed, `none` or older than the newest roadmap `in-progress`; `--fix` sets `current_milestone`, `active_slice` (its first open slice), `active_task: none` and `last_updated` in the pointer block only (the frontmatter, or the `key: value` lines a file without one starts with), adds the keys that are missing there, refuses a file with neither (exit 1, nothing written) and reports what the file says after the write. - `bin/ytstack-questions`: `new`, `list`, `next`, `ask` (once), `answer` (refused without text under "Answer"), `check`. `bin/ytstack-standing` (`docs/ux/coordinator-format.md`, "standing/"): `add` writes one entry, validated by `ytstack-check --standing` before anything is committed, by default in its own worktree outside the checkout on `standing/` with a commit, a push and one pull request per UTC day (opened through `ytstack-pr-watch create` when `pr_watch=on` and the session has an id, else `gh pr create`; updated when one is open); `--here` and user scope write into the resolved directory only; exit 3 when the commit stands but the push or the PR failed; a new day's branch starts from the newest pending standing branch, an earlier one with unpushed commits is pushed first. `end` writes the closing entry of `kind: end`, also of a pending entry. `list` prints the newest entry's age and the human prompts since (from the coordinate session's counter), the active entries with the pending ones marked (local `standing/*` branches and their upstreams only), then the ended ones, the conditions to check and the failed checks; it is the only place `until-check` and `check` run, and only for a working-tree entry identical to the default branch's (bash in its own process group, killed on timeout, stdin closed, `YTSTACK_STANDING_TIMEOUT` seconds each, default 5, at most ten per call, every one not run says why), `--no-checks` runs none. Its suite uses a stand-in for `gh`, a local bare remote behind an `insteadOf` URL and the real `ytstack-pr-watch create`. -- `bin/ytstack-finish-lane`: one step per call (`leftovers`, `commit`, `push`, `open-pr`, `wait-head`, `body-check`, `gates`, `merge`, `route`); every gate is read from GitHub through `gh` at the moment of the call, and `merge` passes the reviewed commit to the host so that a moved head cannot be merged. The `open-prs` gate (`--max-open`) counts the open pull requests that are ready for review, drafts not, and fails when more than 100 are open (only those are read; issue #83). `route --lane [--pr ] [--report ]` reads the lane's worker (the author) and plan from `LANES.md` and runs `bin/ytstack-risk route`; with `--pr` it passes the pull request on, and a lane without a plan file is routed from the host's reviews. With a technical spec it then checks the spec delta and prints `spec:` lines: every plan of the lane that belongs to the range (changed in it, or a commit `:` in it; a slice lane's task plans too) with a "Spec impact" through `ytstack-spec impact --base --head`; then every area the diff touches (`--no-renames`) needs its area file or a source in the diff, a plan of the range with `none -- ` for the files of its commits, or `Spec: none -- ` in the worker's report; a path the report names is the area file or a source of its area, and in the diff. Each gap is a `reason: spec` line and turns `unattended` into `person` (exit 10). When `REVIEW.md` keeps a "Checks" section and the diff edits CI without touching `REVIEW.md`, one `checks:` line says so (a note, CI changes go to a person anyway). `leftovers` and `commit` leave the evidence directory out. Its suite uses a stand-in for `gh` and a local bare remote. +- `bin/ytstack-finish-lane`: one step per call (`leftovers`, `commit`, `push`, `open-pr`, `wait-head`, `body-check`, `gates`, `merge`, `route`); every gate is read from GitHub through `gh` at the moment of the call, and `merge` passes the reviewed commit to the host so that a moved head cannot be merged. A cap on open pull requests is no gate of `gates` or `merge`: `open-pr --max-open N` counts the open pull requests ready for review (drafts not) and at N or more opens the new one as a draft with a `draft:` line on stderr (issue #83, PR #94 review). `route --lane [--pr ] [--report ]` reads the lane's worker (the author) and plan from `LANES.md` and runs `bin/ytstack-risk route`; with `--pr` it passes the pull request on, and a lane without a plan file is routed from the host's reviews. With a technical spec it then checks the spec delta and prints `spec:` lines: every plan of the lane that belongs to the range (changed in it, or a commit `:` in it; a slice lane's task plans too) with a "Spec impact" through `ytstack-spec impact --base --head`; then every area the diff touches (`--no-renames`) needs its area file or a source in the diff, a plan of the range with `none -- ` for the files of its commits, or `Spec: none -- ` in the worker's report; a path the report names is the area file or a source of its area, and in the diff. Each gap is a `reason: spec` line and turns `unattended` into `person` (exit 10). When `REVIEW.md` keeps a "Checks" section and the diff edits CI without touching `REVIEW.md`, one `checks:` line says so (a note, CI changes go to a person anyway). `leftovers` and `commit` leave the evidence directory out. Its suite uses a stand-in for `gh` and a local bare remote. - `bin/ytstack-handover`: `new` copies `skills/handover-step/template.sh`; `check` is the static verification of a staged script (syntax, unchanged helper block, no raw command, a confirmation of its own before every mutation, no pipe into a shell). The helpers hold the same rule when the script runs: one yes carries one change. - `bin/ytstack-watch`: polls pull requests through `gh` and prints a line only when head, checks, review or mergeability changed; `--once` prints the snapshot with its read time. `release --commit ` runs `deployed` of "Release" until it names the commit (or `--timeout`, default 900 s), then `healthy` for the settle time, and ends with five receipt lines (`Target:`, `Commit:`, `Arrived:`, `Health:`, `Result:`) with read times. Exit 0 released or no health command, 2 not arrived, 3 unhealthy, 4 no "Release" section, 1 `RUNTIME.md` fails its check. It runs only those two commands and changes nothing. @@ -187,7 +187,7 @@ Not covered by these checks: `claude plugin eval` (costs money). `bash tests/run - DECISIONS.md -- "2026-11-13: After a merge the release is watched, not driven; upkeep is a script and a recipe, not a skill (M026)". Source of `release` and `bin/ytstack-upkeep`. Extended by "2026-11-15: Lane liveness is part of `ytstack-frontier check`, worktree cleanup only prints commands, peers are list lines in `LANES.md` (issue #84)": the `stale:` lines, `ytstack-upkeep --worktrees`, `peer set` and `peer list`. - DECISIONS.md -- "2026-11-13: Production findings and incidents are skill work on read-only access; a mitigation is a handover script a person runs (M027)". Source of `bin/ytstack-signals`. "2026-11-15: Feedback about ytstack itself goes through one channel with a setting; a script checks the body, the agent posts (M033-S01, issue #55)" is the source of `bin/ytstack-upstream`. - DECISIONS.md -- "2026-11-13: The technical spec is a set of artifacts of its own under `.ytstack/spec/` (M022, issue #36)". Source of `bin/ytstack-spec` and the two spec checks. -- DECISIONS.md -- "2026-11-13: Coordinator mode keeps lanes, questions and standing instructions in files and reads host facts fresh (M024, issue #34)". Source of the five coordinator scripts; the pipeline and the watcher support GitHub through `gh` only. Extended by "2026-11-14: Standing instructions are one file per entry in `.ytstack/standing/`; `STANDING.md` stays valid (issue #57)", the source of `check_standing`, by "2026-11-15: Standing entries end by `until`, `until-condition` or `until-check` and are closed by an entry of `kind: end`; their commands run only in `ytstack-standing list` (issues #73, #74)", the source of `bin/ytstack-standing` and the optional keys of `check_standing`, and by "2026-11-15: A plan outside `.ytstack/` is detected by a script and mapped by the agent, after one question (M031-S05, issue #54)", the source of `bin/ytstack-plans`, and by "2026-11-15: Hooks read a stale checkout from origin, say a reminder once per session and pointer, and keep a coordinator on its path with hints, not denies (issues #82, #83)", the source of `parked` and of the `open-prs` count. +- DECISIONS.md -- "2026-11-13: Coordinator mode keeps lanes, questions and standing instructions in files and reads host facts fresh (M024, issue #34)". Source of the five coordinator scripts; the pipeline and the watcher support GitHub through `gh` only. Extended by "2026-11-14: Standing instructions are one file per entry in `.ytstack/standing/`; `STANDING.md` stays valid (issue #57)", the source of `check_standing`, by "2026-11-15: Standing entries end by `until`, `until-condition` or `until-check` and are closed by an entry of `kind: end`; their commands run only in `ytstack-standing list` (issues #73, #74)", the source of `bin/ytstack-standing` and the optional keys of `check_standing`, and by "2026-11-15: A plan outside `.ytstack/` is detected by a script and mapped by the agent, after one question (M031-S05, issue #54)", the source of `bin/ytstack-plans`, and by "2026-11-15: Hooks read a stale checkout from origin, say a reminder once per session and pointer, and keep a coordinator on its path with hints, not denies (issues #82, #83)", the source of `parked`, and by "2026-11-15: The open-PR cap limits opening, never a merge; origin's STATE.md is read only when the checkout is strictly behind and unedited (review of PR #94)", the source of `open-pr --max-open`. - DECISIONS.md -- "2026-11-13: Verification, review and orchestration work are bounded like code (M023, issue #35)". Source of `bin/ytstack-brief`. Extended by "2026-11-15: The spec delta is the report's existing `Spec:` label, checked for its form (issue #75)" and "2026-11-15: A brief for an unplanned task makes the task plan its first deliverable (issue #76)". "2026-11-15: `finish-lane`'s route checks the spec delta; a gap routes to a person (issue #75)" and "2026-11-15: The checks inventory is a `## Checks` section of `REVIEW.md`, not an area file (issue #75)" are the source of the `spec:` and `checks:` lines of `ytstack-finish-lane route`, `ytstack-spec impact --head` and the "Checks" rules of `ytstack-risk check`; "2026-11-15: `reconcile` writes task-plan skeletons and fixes the STATE pointer, after asking; the logic is `bin/ytstack-reconcile` (issue #76)" of `bin/ytstack-reconcile`. - DECISIONS.md -- "2026-04-23: UX contracts enforced by CI, not convention" - DECISIONS.md -- "2026-05-31: Add `kind: reference` skill class (exempt from procedure-section contract)" diff --git a/.ytstack/spec/hooks-and-state.md b/.ytstack/spec/hooks-and-state.md index 62bd5b8..802754b 100644 --- a/.ytstack/spec/hooks-and-state.md +++ b/.ytstack/spec/hooks-and-state.md @@ -37,7 +37,7 @@ The lifecycle hooks under `hooks/` and the shared library `hooks/lib/git-ctx.sh` - `yt_commit_ref_pattern` renders a task's commit pattern from `commit_ref_pattern` in `PREFERENCES.md`, or from the default. `yt_task_commits` lists commits whose subject matches it. When none match, it falls back to the commits on the current branch after the merge-base with the default branch, and reports which source it used. - `yt_find_artifacts` lists artifacts newest first from the flat layout and from the alternative layouts named in its comment. Reading tolerates those layouts. `yt_artifact_dir` and `yt_artifact_path` say where a milestone's files live and where its new ones go: the directory that already holds its roadmap or files, else flat ([artifacts.md](artifacts.md), "Location and scope"). `post-tool-use-bash`, `task-completed`, `stop`, `pre-tool-use-edit` and `session-start` find the milestone's files through them; `task-created` and `teammate-idle` list its slice plans in every layout through `yt_find_artifacts`, one per name, so a plan that landed flat before the milestone moved counts too. - `yt_factory_notices` returns one line per factory tool that is off although the project would use it, from local files only: risk routing (`spec/` without `REVIEW.md` or without an area whose frontmatter allows `auto_merge: low|normal`, quotes allowed, read with `yt_fm`, the reader `bin/ytstack-risk` uses; while `merge_by` is `risk`), the PR watch on a GitHub `origin` (no line in `~/.ytstack/config` that turns the hook on, read as `hooks/pr-watch` does: any `pr_watch=on` line; or `on` with a heartbeat missing or 10 minutes old; `yt_pr_watch_heartbeat` reads `watch.sqlite3`, else the time of `worker.lock`), and `RUNTIME.md` without "Release" or "Signals" while deploy or signal evidence exists (`ytstack-runtime sections`). `merge_by: human|coordinator` and `pr_watch=off` are choices and stay silent. `yt_read_stdin` also sets `YT_SOURCE`. -- `yt_standing` lists the standing instructions in force from `.ytstack/standing/` (name, `given`, `scope`, tab separated), newest first by the time in the name (missing seconds count as `00`), without the entries another entry names in `supersedes`, without entries of `kind: end` and without entries whose `until` has passed. It prints nothing without the directory; `STANDING.md` is read by the skills themselves. `yt_standing_fields` prints the same entries with every key, the first sentence of the body, `active` or `expired`, the source and the whole body on one line (`-` for an empty value); with `pending` as third argument also the entries of `yt_standing_pending` (on a local `standing/*` branch or the upstream it tracks, not in the working tree, not on `yt_standing_default_ref`), read with `git show`, source `pending:`. `yt_standing_default_ref` is `origin/HEAD`, else `origin/main`, `origin/master`, `main`, `master`. `yt_standing_lines [max] [full]` prints the active ones for a role (with `full` the whole body, for briefs) (`docs/ux/coordinator-format.md`, "Scope and roles"), pending ones included and marked, as `- (): `, with a pointer line past `max`. None of them runs a command of an entry. `yt_latest_handoff` (for skill preambles) finds the newest `latest-handoff` of the worktree under every base a hook may have used: `CLAUDE_PLUGIN_DATA`, `PLUGIN_DATA`, each `~/.claude/plugins/data/ytstack*` and the XDG base. `coordinate` and `resume-session` use it; before, they looked under `yt_state_base` only, which in the Bash tool is not where the hook wrote. `yt_session_home` is `${XDG_STATE_HOME:-~/.local/state}/ytstack/sessions`: per-session state that a hook and the Bash tool of the same session both find (`CLAUDE_PLUGIN_DATA` reaches hooks only). It holds the coordinate marker (the resolved `.ytstack` on line 1, the repository key on line 2, which keys the lint counter also in user scope), the prompt counter and the standing flags of a session. `yt_behind_origin [yt_dir]` (issue #82) says whether the checkout is on the default branch (`yt_standing_default_ref`, only when that is an `origin` ref) and behind it, from local refs only, never a fetch (an `origin/` that was never fetched counts as current): `YT_BEHIND_N` (0 when not), `YT_BEHIND_REF` (`origin/`) and `YT_BEHIND_STATE`, the `STATE.md` of that ref when the `.ytstack` lies inside the checkout. +- `yt_standing` lists the standing instructions in force from `.ytstack/standing/` (name, `given`, `scope`, tab separated), newest first by the time in the name (missing seconds count as `00`), without the entries another entry names in `supersedes`, without entries of `kind: end` and without entries whose `until` has passed. It prints nothing without the directory; `STANDING.md` is read by the skills themselves. `yt_standing_fields` prints the same entries with every key, the first sentence of the body, `active` or `expired`, the source and the whole body on one line (`-` for an empty value); with `pending` as third argument also the entries of `yt_standing_pending` (on a local `standing/*` branch or the upstream it tracks, not in the working tree, not on `yt_standing_default_ref`), read with `git show`, source `pending:`. `yt_standing_default_ref` is `origin/HEAD`, else `origin/main`, `origin/master`, `main`, `master`. `yt_standing_lines [max] [full]` prints the active ones for a role (with `full` the whole body, for briefs) (`docs/ux/coordinator-format.md`, "Scope and roles"), pending ones included and marked, as `- (): `, with a pointer line past `max`. None of them runs a command of an entry. `yt_latest_handoff` (for skill preambles) finds the newest `latest-handoff` of the worktree under every base a hook may have used: `CLAUDE_PLUGIN_DATA`, `PLUGIN_DATA`, each `~/.claude/plugins/data/ytstack*` and the XDG base. `coordinate` and `resume-session` use it; before, they looked under `yt_state_base` only, which in the Bash tool is not where the hook wrote. `yt_session_home` is `${XDG_STATE_HOME:-~/.local/state}/ytstack/sessions`: per-session state that a hook and the Bash tool of the same session both find (`CLAUDE_PLUGIN_DATA` reaches hooks only). It holds the coordinate marker (the resolved `.ytstack` on line 1, the repository key on line 2, which keys the lint counter also in user scope), the prompt counter and the standing flags of a session. `yt_behind_origin ` (issue #82) says whether the checkout is on the default branch (`yt_standing_default_ref`, only when that is an `origin` ref) and behind it, from local refs only, never a fetch (an `origin/` that was never fetched counts as current), and only for a `.ytstack` inside the checkout whose `STATE.md` that ref has (else all 0 and empty: user scope, an untracked `STATE.md`): `YT_BEHIND_N`, `YT_AHEAD_N`, `YT_BEHIND_REF` (`origin/`), `YT_BEHIND_CHANGED` (`yes` when origin changed `STATE.md` since the merge base) and `YT_BEHIND_STATE`, origin's `STATE.md` only when it is the one to read: strictly behind (not diverged), changed, and the working tree's `STATE.md` is HEAD's (PR #94 review). ### STATE lint and progress block @@ -72,12 +72,12 @@ Every hook except `pr-watch` sources the library and resolves from the payload ` | `session-start` | SessionStart | `cwd`, `source` | prints the injection as JSON on stdout, writes nothing | 0 | | `version-notice` | UserPromptSubmit (first entry) | `session_id` | records the plugin version of the session's first prompt in `/sessions//plugin-version`; when the installed version (`installed_plugins.json` entries of this root's marketplace with scope `user`, or `project`/`local` whose `projectPath` is the session's project; else the newest cache sibling without `.orphaned_at`) is newer, prints once per installed version "ytstack X installed, this session loaded A: reload the skills you use" and the CHANGELOG entry titles in between (cut at 600 characters), and writes `notified-` after the notice was printed | 0 | | `standing-prompt` | UserPromptSubmit (second entry) | `session_id`, `prompt` | only with the coordinate marker `//coordinate`: appends the epoch of every human prompt (not one that starts with `<`) to `prompts`; a prompt that reads like a standing instruction (instruction phrases in the script, English and German; a prompt that is only one question never) goes into `standing-flags` and gets one line of `additionalContext`: record it with `ytstack-standing add` before the next dispatch | 0 | -| `pre-compact` | PreCompact | `cwd`, `session_id`, `trigger` | writes `HANDOFF.auto.md` into the session state directory, renames a fresh `latest-handoff` symlink into the worktree state directory, prints compaction guidance on stdout; with the coordinate marker appends the epoch to `compactions` beside it (issue #83) | 0 | +| `pre-compact` | PreCompact | `cwd`, `session_id`, `trigger` | writes `HANDOFF.auto.md` into the session state directory, renames a fresh `latest-handoff` symlink into the worktree state directory, prints compaction guidance on stdout; with the coordinate marker appends the epoch to `compactions` beside it, also without a `.ytstack` (issue #83) | 0 | | `session-end` | SessionEnd | `cwd`, `session_id`, `reason` | appends one JSON line to `session.jsonl` in the session state directory | 0 | -| `stop` | Stop | `cwd`, `session_id`, `stop_hook_active` | prints a `systemMessage` when the active task has no summary or only a draft, once per session and pointer (`stop-said`), not with the coordinate marker and not for a pointer the lint reports as W10; on the default branch behind `origin/` instead one message per origin head with the count and the pointer of origin's `STATE.md` (issue #82); with the coordinate marker from the second compaction one reminder per compaction to rotate (Step 12, `rotate-said`; issue #83); with the coordinate marker and flagged prompts not handled yet, `decision: block` once when no standing entry exists since the first of them (working tree, or added on any ref after it), then writes `standing-stop`; with the marker also the coordinate lints: a `systemMessage` once per session when `LANES.md` lags the session's dispatches and reports by more than five minutes or the STATE pointer is behind (W2), and a block once when the same lint came in `YT_LINT_STREAK_N` (3) sessions in a row, a session counting once when the lint was there at any of its stops, overlapping sessions once each (counter `/repos//coordinate-lints`) | 0 | -| `pre-tool-use-agent` | PreToolUse on `Agent`, `Task`, `SendMessage`, `Bash` | `session_id`, `tool_name`, the prompt or message, `subagent_type`, `isolation`, the command | only with the coordinate marker: appends every `Agent` call to `dispatches` except a lookup type (`Explore`, `Plan`, `claude-code-guide`, `statusline-setup`, a type naming search or explore) without a brief; a prompt without a line starting with `# Brief: ` (a `SendMessage` only above 400 characters) gets one line of `additionalContext` naming claim, render, dispatch; an `Agent` call that is no lookup and has no `isolation` one line naming `isolation: "worktree"`; a `Bash` command that runs `gh pr merge` or `gh pr close` after a command separator (wrapper tokens as in `post-tool-use-bash`) one line naming `ytstack-finish-lane merge`, or `parked` and `gh run rerun` (issue #83); never a permission decision | 0 | +| `stop` | Stop | `cwd`, `session_id`, `stop_hook_active` | prints a `systemMessage` when the active task has no summary or only a draft, once per session and pointer (`stop-said`), not with the coordinate marker and not for a pointer the lint reports as W10; when `yt_behind_origin` gives origin's `STATE.md` instead one message per origin head with the count and its pointer (issue #82); when a new session dir is made, dirs of sessions untouched for 14 days that only hold `stop-said` are removed; with the coordinate marker from the second compaction one reminder per compaction to rotate (Step 12, `rotate-said`; issue #83); with the coordinate marker and flagged prompts not handled yet, `decision: block` once when no standing entry exists since the first of them (working tree, or added on any ref after it), then writes `standing-stop`; with the marker also the coordinate lints: a `systemMessage` once per session when `LANES.md` lags the session's dispatches and reports by more than five minutes or the STATE pointer is behind (W2), and a block once when the same lint came in `YT_LINT_STREAK_N` (3) sessions in a row, a session counting once when the lint was there at any of its stops, overlapping sessions once each (counter `/repos//coordinate-lints`) | 0 | +| `pre-tool-use-agent` | PreToolUse on `Agent`, `Task`, `SendMessage`, `Bash` | `session_id`, `tool_name`, the prompt or message, `subagent_type`, `isolation`, the command | only with the coordinate marker: appends every `Agent` call to `dispatches` except a lookup type (`Explore`, `Plan`, `claude-code-guide`, `statusline-setup`, a type naming search or explore) without a brief; a prompt without a line starting with `# Brief: ` (a `SendMessage` only above 400 characters) gets one line of `additionalContext` naming claim, render, dispatch; an `Agent` call that is no lookup and has no `isolation` one line naming `isolation: "worktree"`; a `Bash` command that runs `gh pr merge` or `gh pr close` as a command (per line and segment, after assignments, `if`/`then`/`!`, wrappers, `env`, `xargs` and `gh -R`; not in quotes or after `#`) one line naming `ytstack-finish-lane merge`, or `parked` and `gh run rerun` (issue #83); never a permission decision | 0 | | `pre-tool-use-edit` | PreToolUse on `Edit`, `Write`, `MultiEdit` | `cwd`, target path | prints a drift warning on stderr | 0 | -| `post-tool-use-bash` | PostToolUse on `Bash` | `cwd`, command, exit code, `tool_response.stdout` | creates a draft task summary once; with the coordinate marker, a `gh run list --branch ` (or `-b`) whose output has a failed run (tab-separated `completed`/`failure`, `timed_out` or `startup_failure`, JSON `"conclusion"` with one of them, or a line starting with `X `) gets one `additionalContext` note to run `ytstack:lesson`, once per distinct set of those lines (`red-main-said`; issue #83) | 0 | +| `post-tool-use-bash` | PostToolUse on `Bash` | `cwd`, command, exit code, `tool_response.stdout` | creates a draft task summary once; with the coordinate marker, a `gh run list --branch ` (or `-b`) whose output has a failed run (tab-separated `completed`/`failure`, `timed_out` or `startup_failure`, or a JSON array with `conclusion` and `workflowName`), counting only the newest run of each workflow and, with `--repo`/`-R`, only the repository of `origin`, gets one `additionalContext` note to run `ytstack:lesson`, once per distinct set of those runs (`red-main-said`; issue #83) | 0 | | `task-created` | TaskCreated | `cwd`, subject, description | prints a scope warning on stderr | 2 on drift, else 0 | | `task-completed` | TaskCompleted | `cwd`, subject | writes an auto summary, ticks the slice plan checkbox | 0 | | `teammate-idle` | TeammateIdle | `cwd` | prints the open task count on stderr | 2 while tasks are open, else 0 | @@ -93,7 +93,7 @@ Every hook except `pr-watch` sources the library and resolves from the payload ` - Always: the full text of `skills/using-ytstack/SKILL.md` in an `` envelope. If that file is missing, the hook prints nothing. If `YTSTACK_HOST_CONTEXT` is set, its text goes in front of the skill text. - No `.ytstack`: a greenfield block that routes build intent to `office-hours`. With two or more brownfield signals it routes to `adopt-brownfield` and names the signals. - `.ytstack` without `STATE.md`: a one-line repair notice. -- Otherwise a state block, in this order: scope, project, pointer, last update, working tree with the linked-worktree flag, `.ytstack` path, on the default branch behind `origin/` a line with the count and `git merge --ff-only` (pointer and Next action are then read from that ref's `STATE.md` and the STATE lint is left out; `yt_behind_origin`, issue #82), in a coordinate session after a compaction `Compaction N of this coordinator: ytstack:coordinate Step 12, rotate now` (N from `compactions`, at least 1; issue #83), a Next action excerpt, the three newest summary names, a notice when more than one milestone roadmap is `in-progress`, in a coordinate session the operating checklist of `docs/ux/coordinator-format.md` (in place of the minimal-code line), the standing instructions in force for the session's role (coordinator with the coordinate marker, else lane; pending ones too, also before the checkout has `standing/`; at most six lines from `yt_standing_lines`, files only, and a line naming `STANDING.md` when it exists), the manual and the latest automatic handoff (a manual one whose `timestamp` is older than the automatic one's is listed after it as "Older manual handoff"), a lifecycle hint for a finished slice or a finished milestone without retro, up to five STATE lint findings, the minimal-code line when `minimal_code` is on, a "Factory tools" block with the lines of `yt_factory_notices` (only when the payload `source` is `startup` or `clear`, or absent on a SessionStart, so it is said once per session without a file), and a closing line that names the files as the source of truth. When `spec/SPEC.md` exists, the closing line names it as the place for what applies now. +- Otherwise a state block, in this order: scope, project, pointer, last update, working tree with the linked-worktree flag, `.ytstack` path, when `yt_behind_origin` gives origin's `STATE.md` a line with the count and `git merge --ff-only` (pointer and Next action are then read from it and the STATE lint is left out; issue #82), when origin changed `STATE.md` but the checkout diverged or edited it locally a line with ahead and behind and the local file read, in a coordinate session after a compaction `Compaction N of this coordinator: ytstack:coordinate Step 12, rotate now` (N from `compactions`, at least 1; issue #83), a Next action excerpt, the three newest summary names, a notice when more than one milestone roadmap is `in-progress`, in a coordinate session the operating checklist of `docs/ux/coordinator-format.md` (in place of the minimal-code line), the standing instructions in force for the session's role (coordinator with the coordinate marker, else lane; pending ones too, also before the checkout has `standing/`; at most six lines from `yt_standing_lines`, files only, and a line naming `STANDING.md` when it exists), the manual and the latest automatic handoff (a manual one whose `timestamp` is older than the automatic one's is listed after it as "Older manual handoff"), a lifecycle hint for a finished slice or a finished milestone without retro, up to five STATE lint findings, the minimal-code line when `minimal_code` is on, a "Factory tools" block with the lines of `yt_factory_notices` (only when the payload `source` is `startup` or `clear`, or absent on a SessionStart, so it is said once per session without a file), and a closing line that names the files as the source of truth. When `spec/SPEC.md` exists, the closing line names it as the place for what applies now. - Cap: the hook measures the injection without the host context. Above the guard threshold in the script, which sits just under the host's 10,000-character limit, it first cuts the standing lines to the three newest, then the Factory tools block shrinks to one line that counts them and names `bin/ytstack-upkeep`, then the minimal-code line to its short pointer, then the closing line to its short form, then the standing lines to one line that counts them, names the role and `bin/ytstack-standing list`; last the `using-ytstack` body is cut to what fits, at a line end, with the line `(cut for the 10,000-char cap: read the rest in )` (issue #82: the Next action comes before that body). The Next action excerpt (at most five lines of 600 characters), the operating checklist and the lines about the checkout and a compaction are never cut. If the text is still above the threshold, it warns on stderr and emits the text anyway. Nothing else is dropped. Last, with a state block and on every source (also resume and compaction): one line `YT_BIN=`, the directory skills run ytstack's bins from as `"$YT_BIN/ytstack-"` (issue #85). It is added only when it still fits under the guard and the `using-ytstack` body was not cut, so it never costs the Next action excerpt or the directive; the `coordinate` preamble prints it too. - Output is the existing Claude-compatible JSON envelope by default. `YTSTACK_HOOK_FORMAT=plain` emits the raw context instead. Kimi's helper uses this mode only to prepare pending context, not as a claim that SessionStart stdout is consumed. @@ -181,7 +181,7 @@ python3 -m unittest discover -s tests -p 'kimi_lifecycle_test.py' -v ## Decisions that apply now -- DECISIONS.md -- "2026-11-15: Coordinate mode is a session marker the coordinate preamble writes; the standing hooks act only with it (issue #72)"; "2026-11-15: In coordinate mode the operating path is injected and checked by hooks that warn; a lint repeated in three sessions blocks once (issue #76)"; "2026-11-15: Standing entries end by `until`, `until-condition` or `until-check` and are closed by an entry of `kind: end`; their commands run only in `ytstack-standing list` (issues #73, #74)", narrowed by "2026-11-15: A standing entry's command runs only when the entry is merged; pending means this machine's standing branches (review of PR #87)"; extended by "2026-11-15: Hooks read a stale checkout from origin, say a reminder once per session and pointer, and keep a coordinator on its path with hints, not denies (issues #82, #83)" (the behind check, the once-per-pointer reminder, the cap order, the hints and the compaction count) +- DECISIONS.md -- "2026-11-15: Coordinate mode is a session marker the coordinate preamble writes; the standing hooks act only with it (issue #72)"; "2026-11-15: In coordinate mode the operating path is injected and checked by hooks that warn; a lint repeated in three sessions blocks once (issue #76)"; "2026-11-15: Standing entries end by `until`, `until-condition` or `until-check` and are closed by an entry of `kind: end`; their commands run only in `ytstack-standing list` (issues #73, #74)", narrowed by "2026-11-15: A standing entry's command runs only when the entry is merged; pending means this machine's standing branches (review of PR #87)"; extended by "2026-11-15: Hooks read a stale checkout from origin, say a reminder once per session and pointer, and keep a coordinator on its path with hints, not denies (issues #82, #83)" (the behind check, the once-per-pointer reminder, the cap order, the hints and the compaction count), narrowed by "2026-11-15: The open-PR cap limits opening, never a merge; origin's STATE.md is read only when the checkout is strictly behind and unedited (review of PR #94)" - DECISIONS.md -- "2026-11-15: SessionStart stays read-only; factory-tool notices are said on startup only, the plugin version is recorded by a prompt hook (M031-S03)" - DECISIONS.md -- "2026-11-15: PR watch bulk registration takes only your own ready PRs; bins are called through `YT_BIN` (issue #85)" - DECISIONS.md -- "2026-11-14: Kimi uses native plugin bootstrap and pending lifecycle context (M020)" (plain output is explicit, the helper owns pending context and consumes it once) diff --git a/.ytstack/spec/skills.md b/.ytstack/spec/skills.md index cedebe9..6dc3ca8 100644 --- a/.ytstack/spec/skills.md +++ b/.ytstack/spec/skills.md @@ -105,9 +105,9 @@ Read from `PREFERENCES.md` in the resolved `.ytstack` directory by `yt_prefs` in Formats: `docs/ux/coordinator-format.md`. The four skills below are for the session that owns a plan and delegates all of it; none of them writes product code. -- `coordinate` is a loop with a fixed order: start from the standing instructions (the entries of `standing/` in the resolved `YT_DIR`, project or user scope, newest first without superseded ones, and `STANDING.md`), `LANES.md`, the frontier and the questions (never from a conversation summary), read host facts fresh and stamp them with their read time, claim a lane before dispatching it, finish lanes through `finish-lane`, run the factory tools of Step 7 (one table of command, when and skip condition; the preamble prints `MERGE_BY`, `REVIEW_POLICY`, `OWN_REVIEWERS`, `PR_WATCH` with the heartbeat age, `RELEASE` and `SIGNALS`, and `YT_BIN=`, through which it runs every bin): the route before every merge, also one it makes itself outside `finish-lane` (then through `ytstack-finish-lane merge` and `finish-lane`'s rule of who merges), with the PR watch on (flag set and a worker heartbeat under 10 minutes old) register the repository's open pull requests by its own GitHub login, without drafts and do-not-merge labels, to itself as their owning session (`ytstack-pr-watch register --all-open` without `--session`, at the start, after every restart or rotation and after a worker opened one) and otherwise poll through `bin/ytstack-watch`, `ytstack-watch release` after every merge to production, `signal-intake` / `incident` for signals and `review-lessons` after a merge with a bot finding, `lesson` on a red `main` and on every slip of a lane or its own (the open lessons in every status from the preamble's `LESSONS` line, a lesson proposal asked with the daily question, lesson lanes `lesson-F###` dispatched from the frontier with `ytstack-brief render --lesson` and set `fixed` after their merge), ask one question at a time from a question file, write a standing instruction down when it is given, before the next dispatch, with `ytstack-standing add` (a new file in `standing/` on the day's standing branch and pull request, `--here` in user scope; `STANDING.md` only where no `standing/` exists; agent memory is no substitute), close an ended one with `ytstack-standing end`, act on the ended, to-check and failed-check lines its preamble prints from `ytstack-standing list` (with the newest entry's age and the human prompts since), its preamble writes the coordinate session marker (the resolved `.ytstack` and the repository key) the coordinate-mode hooks act on, finds the automatic handoff through `yt_latest_handoff`, and prints the operating checklist of `docs/ux/coordinator-format.md` (the same block `session-start` injects), stop a lane that failed verification twice or needs a third review, and rotate after the first compaction in one step while lanes run: a handoff written from the files with the "Rotation" block of `docs/ux/coordinator-format.md` (PR watch session, background watches, each running worker's address), the successor's Step 3 takes the PR watches over with `ytstack-pr-watch handover --from `, and the old session stays open only as a relay that appends its workers' reports to `HANDOFF.md`. It also prints the sessions in other repositories it works with between `PEERS_BEGIN` and `PEERS_END` (`ytstack-frontier peer list`, the `## Peers` lines of `LANES.md`), carries them under `Peers:` in the Rotation block, and takes progress per phase for a status from `ytstack-status --phases` (issues #81, #84). Every round of its loop starts with `ytstack-frontier check` in Step 5, and each `stale:` line (exit 2) gets its action in that round before any new dispatch. Its hard gate forbids closing a lane's pull request, reopening it to retrigger checks and deleting its branch: a lane that waits for a cap (which counts pull requests ready for review) is `parked` with its pull request open, a check reruns with `gh run rerun`; in Claude Code the coordinate hooks hint at this, at a dispatch without `isolation`, at `gh pr merge`, at a red `main` read with `gh run list`, and at rotation after a compaction (issue #83). +- `coordinate` is a loop with a fixed order: start from the standing instructions (the entries of `standing/` in the resolved `YT_DIR`, project or user scope, newest first without superseded ones, and `STANDING.md`), `LANES.md`, the frontier and the questions (never from a conversation summary), read host facts fresh and stamp them with their read time, claim a lane before dispatching it, finish lanes through `finish-lane`, run the factory tools of Step 7 (one table of command, when and skip condition; the preamble prints `MERGE_BY`, `REVIEW_POLICY`, `OWN_REVIEWERS`, `PR_WATCH` with the heartbeat age, `RELEASE` and `SIGNALS`, and `YT_BIN=`, through which it runs every bin): the route before every merge, also one it makes itself outside `finish-lane` (then through `ytstack-finish-lane merge` and `finish-lane`'s rule of who merges), with the PR watch on (flag set and a worker heartbeat under 10 minutes old) register the repository's open pull requests by its own GitHub login, without drafts and do-not-merge labels, to itself as their owning session (`ytstack-pr-watch register --all-open` without `--session`, at the start, after every restart or rotation and after a worker opened one) and otherwise poll through `bin/ytstack-watch`, `ytstack-watch release` after every merge to production, `signal-intake` / `incident` for signals and `review-lessons` after a merge with a bot finding, `lesson` on a red `main` and on every slip of a lane or its own (the open lessons in every status from the preamble's `LESSONS` line, a lesson proposal asked with the daily question, lesson lanes `lesson-F###` dispatched from the frontier with `ytstack-brief render --lesson` and set `fixed` after their merge), ask one question at a time from a question file, write a standing instruction down when it is given, before the next dispatch, with `ytstack-standing add` (a new file in `standing/` on the day's standing branch and pull request, `--here` in user scope; `STANDING.md` only where no `standing/` exists; agent memory is no substitute), close an ended one with `ytstack-standing end`, act on the ended, to-check and failed-check lines its preamble prints from `ytstack-standing list` (with the newest entry's age and the human prompts since), its preamble writes the coordinate session marker (the resolved `.ytstack` and the repository key) the coordinate-mode hooks act on, finds the automatic handoff through `yt_latest_handoff`, and prints the operating checklist of `docs/ux/coordinator-format.md` (the same block `session-start` injects), stop a lane that failed verification twice or needs a third review, and rotate after the first compaction in one step while lanes run: a handoff written from the files with the "Rotation" block of `docs/ux/coordinator-format.md` (PR watch session, background watches, each running worker's address), the successor's Step 3 takes the PR watches over with `ytstack-pr-watch handover --from `, and the old session stays open only as a relay that appends its workers' reports to `HANDOFF.md`. It also prints the sessions in other repositories it works with between `PEERS_BEGIN` and `PEERS_END` (`ytstack-frontier peer list`, the `## Peers` lines of `LANES.md`), carries them under `Peers:` in the Rotation block, and takes progress per phase for a status from `ytstack-status --phases` (issues #81, #84). Every round of its loop starts with `ytstack-frontier check` in Step 5, and each `stale:` line (exit 2) gets its action in that round before any new dispatch. Its hard gate forbids closing a lane's pull request, reopening it to retrigger checks and deleting its branch: a cap counts pull requests ready for review and limits opening and dispatching, never a merge, and a lane that waits for it is `parked` with a draft pull request, a check reruns with `gh run rerun`; in Claude Code the coordinate hooks hint at this, at a dispatch without `isolation`, at `gh pr merge`, at a red `main` read with `gh run list`, and at rotation after a compaction (issue #83). - `spawn-milestone-team` claims each lane with `bin/ytstack-frontier` before it dispatches, keeps the lane's row current, and looks at the frontier again whenever a lane is verified or merged. -- `finish-lane` takes a reported lane to a merged pull request with `bin/ytstack-finish-lane`: review pinned to the host's head, the required lenses, `route` with the worker's report (its spec delta is checked against the diff, so a lane that skipped `summarize-task` and changed an area without its description or a reason goes to a person, under `merge_by: coordinator` back to the worker; a `checks:` line notes a CI edit that the checks inventory of `REVIEW.md` did not follow and goes to the person who merges), the gates read from the host, the merge decided by `merge_by` and the route, then `bin/ytstack-watch release` on the merge commit when `RUNTIME.md` has a "Release" section (in the background; the receipt goes into the report, nothing is rolled back). A merge without a person is reported in one line with class, ceiling and lenses. After a merge it made itself, and when `REVIEW.md` declares own reviewers, it invokes `review-lessons` for the pull request. Before a lane goes back for a review that requested changes, a failed lens or a failed check, it invokes `lesson` (its Step 14). These two are the skills it may invoke. Its hard gate forbids closing the lane's pull request, reopening it to retrigger checks and deleting its branch; the `open-prs` gate counts pull requests ready for review, and a lane that waits for it is `parked` (issue #83). The pipeline supports GitHub through `gh` only; on another host the skill stops after the route. +- `finish-lane` takes a reported lane to a merged pull request with `bin/ytstack-finish-lane`: review pinned to the host's head, the required lenses, `route` with the worker's report (its spec delta is checked against the diff, so a lane that skipped `summarize-task` and changed an area without its description or a reason goes to a person, under `merge_by: coordinator` back to the worker; a `checks:` line notes a CI edit that the checks inventory of `REVIEW.md` did not follow and goes to the person who merges), the gates read from the host, the merge decided by `merge_by` and the route, then `bin/ytstack-watch release` on the merge commit when `RUNTIME.md` has a "Release" section (in the background; the receipt goes into the report, nothing is rolled back). A merge without a person is reported in one line with class, ceiling and lenses. After a merge it made itself, and when `REVIEW.md` declares own reviewers, it invokes `review-lessons` for the pull request. Before a lane goes back for a review that requested changes, a failed lens or a failed check, it invokes `lesson` (its Step 14). These two are the skills it may invoke. Its hard gate forbids closing the lane's pull request, reopening it to retrigger checks and deleting its branch; a cap counts pull requests ready for review and limits opening (`open-pr --max-open` opens a draft at the cap, the lane is `parked`), never a merge (issue #83). The pipeline supports GitHub through `gh` only; on another host the skill stops after the route. - **The class of a change.** `code-review` prints the floor of `bin/ytstack-risk` and has a reviewer that is not the author end with `Risk:`, `Severity:`, `Reach:` and `Invariants touched:`, read against "Invariants and security boundaries" and "Decisions that apply now" of the touched areas, also when only code moved. The round line records class, invariants and reviewer; a session reviewing its own change writes `by: self`, which routes to a person. On a pull request `finish-lane` and `code-review` post the round and lens lines in the body of a review on the reviewed head, and `finish-lane` routes with `--pr`: the record needs no commit that would move the head away from a head-bound review. Each lens the floor names gets a separate fresh reviewer with the lens brief (`bin/ytstack-brief render --kind review --lens `) and one lens line. - `visual-review` is the lens reviewer of a user interface change: its own worktree at the reviewed commit, `bin/ytstack-runtime up`, a browser tool that renders and returns screenshots, its own screenshots of the changed views, states and two widths, reviewed against the lens documents; evidence with `MANIFEST` in the main checkout. It is `not run`, never `pass`, when the reviewer is the author, a document or the "Run" section is missing, the product does not come up or no browser tool exists. It edits no product file. - `signal-intake` reads every source of "Signals" once with its read time, separates findings from noise by stated rules, records through `bin/ytstack-signals new` (an unreadable source is a finding too) and changes nothing else. `incident` puts the mitigation before the cause: facts with read times, timeline, hypotheses, mitigations as handover scripts it never runs, one question at a time, and never picks a mitigation without a person; once mitigated it records the lesson through `lesson` with `--incident`, and the cause goes to `systematic-debugging` afterwards, which records the cause's lesson the same way. @@ -195,6 +195,6 @@ Formats: `docs/ux/coordinator-format.md`. The four skills below are for the sess - DECISIONS.md -- "2026-11-07: Brownfield adoption is a reference-first distillation, never a pitch" (narrows the greenfield flow: an existing codebase skips the pitch) - DECISIONS.md -- "2026-10-13: Remove generated Codex copies; load the existing skills directly" (one skill tree for both hosts) - DECISIONS.md -- "2026-11-13: The technical spec is a set of artifacts of its own under `.ytstack/spec/` (M022, issue #36)" (the spec steps in the loop) -- DECISIONS.md -- "2026-11-13: Coordinator mode keeps lanes, questions and standing instructions in files and reads host facts fresh (M024, issue #34)", extended by "2026-11-14: Standing instructions are one file per entry in `.ytstack/standing/`; `STANDING.md` stays valid (issue #57)", by "2026-11-15: PR watch bulk registration takes only your own ready PRs; bins are called through `YT_BIN` (issue #85)", by "2026-11-15: Lane liveness is part of `ytstack-frontier check`, worktree cleanup only prints commands, peers are list lines in `LANES.md` (issue #84)" (the peers of `coordinate`), by "2026-11-15: Coordinate mode is a session marker the coordinate preamble writes; the standing hooks act only with it (issue #72)", "2026-11-15: In coordinate mode the operating path is injected and checked by hooks that warn; a lint repeated in three sessions blocks once (issue #76)" and "2026-11-15: Standing entries end by `until`, `until-condition` or `until-check` and are closed by an entry of `kind: end`; their commands run only in `ytstack-standing list` (issues #73, #74)" and "2026-11-15: Hooks read a stale checkout from origin, say a reminder once per session and pointer, and keep a coordinator on its path with hints, not denies (issues #82, #83)" (the hard gate of `coordinate` and `finish-lane`, `parked`, the cap on ready pull requests, Step 5's liveness check) +- DECISIONS.md -- "2026-11-13: Coordinator mode keeps lanes, questions and standing instructions in files and reads host facts fresh (M024, issue #34)", extended by "2026-11-14: Standing instructions are one file per entry in `.ytstack/standing/`; `STANDING.md` stays valid (issue #57)", by "2026-11-15: PR watch bulk registration takes only your own ready PRs; bins are called through `YT_BIN` (issue #85)", by "2026-11-15: Lane liveness is part of `ytstack-frontier check`, worktree cleanup only prints commands, peers are list lines in `LANES.md` (issue #84)" (the peers of `coordinate`), by "2026-11-15: Coordinate mode is a session marker the coordinate preamble writes; the standing hooks act only with it (issue #72)", "2026-11-15: In coordinate mode the operating path is injected and checked by hooks that warn; a lint repeated in three sessions blocks once (issue #76)" and "2026-11-15: Standing entries end by `until`, `until-condition` or `until-check` and are closed by an entry of `kind: end`; their commands run only in `ytstack-standing list` (issues #73, #74)" and "2026-11-15: Hooks read a stale checkout from origin, say a reminder once per session and pointer, and keep a coordinator on its path with hints, not denies (issues #82, #83)" (the hard gate of `coordinate` and `finish-lane`, `parked`, Step 5's liveness check), narrowed by "2026-11-15: The open-PR cap limits opening, never a merge; origin's STATE.md is read only when the checkout is strictly behind and unedited (review of PR #94)" (the cap) - DECISIONS.md -- "2026-11-13: Verification, review and orchestration work are bounded like code (M023, issue #35)" (the work contract; extends the ceremony entry of 2026-11-07 from code to evidence and review), extended by "2026-11-15: The spec delta is the report's existing `Spec:` label, checked for its form (issue #75)", "2026-11-15: A brief for an unplanned task makes the task plan its first deliverable (issue #76)", "2026-11-15: `finish-lane`'s route checks the spec delta; a gap routes to a person (issue #75)" as narrowed by "2026-11-15: The spec delta of a lane is checked per area, from the plans of its own range (PR #88 review)", and "2026-11-15: The checks inventory is a `## Checks` section of `REVIEW.md`, not an area file (issue #75)" (the `code-review` finding) - DECISIONS.md -- "2026-11-13: `STATE.md` is a pointer with a size bound; history leaves it through `reconcile`, a closed milestone is folded into the spec (M022-S03)"; "2026-11-15: `reconcile` writes task-plan skeletons and fixes the STATE pointer, after asking; the logic is `bin/ytstack-reconcile` (issue #76)" narrows its rule that `reconcile` leaves the pointer alone diff --git a/CHANGELOG.md b/CHANGELOG.md index ec01261..0605a7d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -73,9 +73,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **`parked` lane status**: `ytstack-frontier set --status parked` holds a lane whose pull request waits open, for a cap or a person. - **A checkout behind origin is named** (issue #82): on the default branch - behind `origin/` (local refs, no fetch), SessionStart and Stop say + strictly behind `origin/` (local refs, no fetch), when origin + changed `STATE.md` and the local one has no edit, SessionStart and Stop say "N commit(s) behind" and read the pointer and Next action from origin's - `STATE.md`. STATE lint W10 names an active task whose `last_updated` is + `STATE.md`; a diverged or locally edited checkout keeps its own file and + SessionStart says "N ahead, M behind". STATE lint W10 names an active task whose `last_updated` is more than three days old (`YT_POINTER_STALE_DAYS`). - **A checks inventory in `REVIEW.md`** (issue #75): a `## Checks` section lists the machine checks a reviewer can rely on, one line each @@ -104,12 +106,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 newest automatic one is listed as older. - `coordinate` 0.7.0: a hard gate against closing, reopening to retrigger or deleting the branch of a lane's pull request; Step 5 starts every round - with `ytstack-frontier check` and acts on each `stale:` line; Step 6 parks - a lane that waits for the cap; Step 12 names the compaction line. The + with `ytstack-frontier check` and acts on each `stale:` line; Step 6: a cap + on open pull requests counts those ready for review and limits opening and + dispatching, never a merge; Step 12 names the compaction line. The operating checklist has two more lines. -- `finish-lane` 0.7.0: the same hard gate; the `open-prs` gate of - `ytstack-finish-lane` counts pull requests ready for review, drafts do not - count, and a lane waiting for it is `parked`. +- `finish-lane` 0.7.0: the same hard gate. The cap moved from `gates` and + `merge` to `ytstack-finish-lane open-pr --max-open`, which opens a draft at + the cap (drafts do not count); the lane is `parked` until `gh pr ready`. + `gates --max-open` is gone: a gate that only closing could open would + deadlock. - **PR watch stays on your own PRs and says less** (issue #85). `ytstack-pr-watch register --all-open` registers only open PRs you authored From 89d01b4a622a5b44057db693170f785c19e65608 Mon Sep 17 00:00:00 2001 From: Alex Wegener Date: Sun, 15 Nov 2026 21:47:54 +0100 Subject: [PATCH 11/13] docs: dependencies area verified against the lib change (PR #94 review) Co-Authored-By: Claude Opus 5.5 --- .ytstack/spec/dependencies.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.ytstack/spec/dependencies.md b/.ytstack/spec/dependencies.md index d6beb9d..5ec073b 100644 --- a/.ytstack/spec/dependencies.md +++ b/.ytstack/spec/dependencies.md @@ -7,7 +7,7 @@ paths: - NOTICE - hooks/lib/git-ctx.sh - bin/ytstack-gstack-diff -verified_at: 1a0b3cc +verified_at: 97c2a11 --- # dependencies From aa4a37ec51f2ead2d4ac42a1413bf4044b947aba Mon Sep 17 00:00:00 2001 From: Alex Wegener Date: Sun, 15 Nov 2026 23:55:53 +0100 Subject: [PATCH 12/13] docs: dependencies area verified after the merge (only lib additions, no gstack) Co-Authored-By: Claude Opus 5.5 --- .ytstack/spec/dependencies.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.ytstack/spec/dependencies.md b/.ytstack/spec/dependencies.md index 57accae..25b04f1 100644 --- a/.ytstack/spec/dependencies.md +++ b/.ytstack/spec/dependencies.md @@ -7,7 +7,7 @@ paths: - NOTICE - hooks/lib/git-ctx.sh - bin/ytstack-gstack-diff -verified_at: 97beca9 +verified_at: f7c0e3c --- # dependencies From 3b04969514750f0b9279c3792b67914b81494da9 Mon Sep 17 00:00:00 2001 From: Alex Wegener Date: Mon, 16 Nov 2026 00:02:28 +0100 Subject: [PATCH 13/13] fix: standing lines stay the last block cut; the using-ytstack tail yields before them With #93's checklist line a coordinate session near the cap lost its standing list to the pointer line while the directive's tail stayed. The order is now: ..., closing line, using-ytstack body (with a pointer to the file), standing pointer last, as #74 decided. The Next action is still never cut. Co-Authored-By: Claude Opus 5.5 --- .ytstack/DECISIONS.md | 4 ++-- .ytstack/spec/hooks-and-state.md | 4 ++-- hooks/session-start | 14 +++++++------- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/.ytstack/DECISIONS.md b/.ytstack/DECISIONS.md index 709d252..88256e9 100644 --- a/.ytstack/DECISIONS.md +++ b/.ytstack/DECISIONS.md @@ -1389,7 +1389,7 @@ Plus: ops-layer split during the same session (yopstack created as own public re - For the coordinator path: PreToolUse denies on `gh pr merge` / `gh pr close`; advisory `additionalContext` lines in the existing coordinate-mode hooks; skill text only. - For a waiting pull request: a new `parked` lane status; keep `ready`. -**Chose:** Local refs only: on the default branch behind `origin/` both hooks read pointer and Next action from `git show origin/:.ytstack/STATE.md` and say "N commit(s) behind" with `git merge --ff-only` (`yt_behind_origin`). The Stop reminder is said once per session and pointer (`stop-said` under the session home), never in coordinate mode, and a pointer whose `last_updated` is older than `YT_POINTER_STALE_DAYS` (3) days is lint W10 instead. In the SessionStart budget the Next action excerpt is no longer cut; the `using-ytstack` body is the last block to yield, cut at a line with a pointer to its file. A manual handoff older than the automatic one is listed as older. In coordinate mode, advisory lines only: `hooks/pre-tool-use-agent` (now also on `Bash`) on an `Agent` without `isolation`, on `gh pr merge` and on `gh pr close`; `hooks/pre-compact` counts compactions beside the marker, SessionStart says "Compaction N of this coordinator: ... rotate now" and Stop repeats it once per compaction from the second; `hooks/post-tool-use-bash` notes `ytstack:lesson` for a failed run in `gh run list --branch `. `coordinate` and `finish-lane` get a hard-gate sentence: never close, reopen to retrigger or delete the branch of a lane's pull request. `parked` is a held lane status for a pull request that waits open; the `open-prs` gate counts pull requests ready for review. Coordinate Step 5 starts every round with `ytstack-frontier check` and acts on each `stale:` line. +**Chose:** Local refs only: on the default branch behind `origin/` both hooks read pointer and Next action from `git show origin/:.ytstack/STATE.md` and say "N commit(s) behind" with `git merge --ff-only` (`yt_behind_origin`). The Stop reminder is said once per session and pointer (`stop-said` under the session home), never in coordinate mode, and a pointer whose `last_updated` is older than `YT_POINTER_STALE_DAYS` (3) days is lint W10 instead. In the SessionStart budget the Next action excerpt is no longer cut; the `using-ytstack` body yields after the other shrinkable blocks and before the standing lines, cut at a line with a pointer to its file. A manual handoff older than the automatic one is listed as older. In coordinate mode, advisory lines only: `hooks/pre-tool-use-agent` (now also on `Bash`) on an `Agent` without `isolation`, on `gh pr merge` and on `gh pr close`; `hooks/pre-compact` counts compactions beside the marker, SessionStart says "Compaction N of this coordinator: ... rotate now" and Stop repeats it once per compaction from the second; `hooks/post-tool-use-bash` notes `ytstack:lesson` for a failed run in `gh run list --branch `. `coordinate` and `finish-lane` get a hard-gate sentence: never close, reopen to retrigger or delete the branch of a lane's pull request. `parked` is a held lane status for a pull request that waits open; the `open-prs` gate counts pull requests ready for review. Coordinate Step 5 starts every round with `ytstack-frontier check` and acts on each `stale:` line. **Reason:** A fetch in a hook is a network call under a 5-10 s budget and can hang; the stale checkout is visible from local refs, and the origin ref is what the person merged. A reminder nobody acts on after the first time is noise that trains the agent to ignore the hook; once per pointer keeps the signal, the lint keeps the old pointer visible at the next start without a loop. The Next action is what a session needs first; the directive's tail is a file read away. A deny would also stop a close or merge the person asked for, and the hooks cannot tell; a hint on the exact command makes the bypass visible (as #76 chose for briefs). `parked` keeps a waiting pull request distinguishable from a lane that is ready to merge, and drafts are no review load. The liveness check existed (#84) but ran only at rotation; the loop is where stalls happen. @@ -1398,7 +1398,7 @@ Plus: ops-layer split during the same session (yopstack created as own public re - Codex and Kimi: not covered by the hooks (Codex has ytstack `Bash` hooks only for the PR watch and none on its subagent tools; Kimi has no session id for the marker); the skill text carries the rules. - A new held status is added to `HELD` in `bin/ytstack-frontier`, to the held lists of `bin/ytstack-upkeep` and to the in-review count of `bin/ytstack-status`. -**Supersedes:** None. Extends "2026-11-15: In coordinate mode the operating path is injected and checked by hooks that warn ..." with four more hints, and changes the SessionStart cap order of "2026-11-15: Standing entries end by `until` ..." (How to apply, third point): the standing lines are no longer cut after the Next action, the `using-ytstack` body is cut last instead. +**Supersedes:** None. Extends "2026-11-15: In coordinate mode the operating path is injected and checked by hooks that warn ..." with four more hints, and changes the SessionStart cap order of "2026-11-15: Standing entries end by `until` ..." (How to apply, third point): the Next action is no longer cut; the `using-ytstack` body yields before the standing lines, which stay the last block cut. ## 2026-11-15: The spec delta is the report's existing `Spec:` label, checked for its form (issue #75) diff --git a/.ytstack/spec/hooks-and-state.md b/.ytstack/spec/hooks-and-state.md index 90523af..b4972ea 100644 --- a/.ytstack/spec/hooks-and-state.md +++ b/.ytstack/spec/hooks-and-state.md @@ -94,7 +94,7 @@ Every hook except `pr-watch` sources the library and resolves from the payload ` - No `.ytstack`: a greenfield block that routes build intent to `office-hours`. With two or more brownfield signals it routes to `adopt-brownfield` and names the signals. - `.ytstack` without `STATE.md`: a one-line repair notice. - Otherwise a state block, in this order: scope, project, pointer, last update, working tree with the linked-worktree flag, `.ytstack` path, when `yt_behind_origin` gives origin's `STATE.md` a line with the count and `git merge --ff-only` (pointer and Next action are then read from it and the STATE lint is left out; issue #82), when origin changed `STATE.md` but the checkout diverged or edited it locally a line with ahead and behind and the local file read, in a coordinate session after a compaction `Compaction N of this coordinator: ytstack:coordinate Step 12, rotate now` (N from `compactions`, at least 1; issue #83), a Next action excerpt, the three newest summary names, a notice when more than one milestone roadmap is `in-progress`, in a coordinate session the operating checklist of `docs/ux/coordinator-format.md` (in place of the minimal-code line), the standing instructions in force for the session's role (coordinator with the coordinate marker, else lane; pending ones too, also before the checkout has `standing/`; at most six lines from `yt_standing_lines`, files only, and a line naming `STANDING.md` when it exists), the manual and the latest automatic handoff (a manual one whose `timestamp` is older than the automatic one's is listed after it as "Older manual handoff"), a lifecycle hint for a finished slice or a finished milestone without retro, up to five STATE lint findings, the minimal-code line when `minimal_code` is on, a "Factory tools" block with the lines of `yt_factory_notices` (only when the payload `source` is `startup` or `clear`, or absent on a SessionStart, so it is said once per session without a file), and a closing line that names the files as the source of truth. When `spec/SPEC.md` exists, the closing line names it as the place for what applies now. -- Cap: the hook measures the injection without the host context. Above the guard threshold in the script, which sits just under the host's 10,000-character limit, it first cuts the standing lines to the three newest, then the Factory tools block shrinks to one line that counts them and names `bin/ytstack-upkeep`, then the minimal-code line to its short pointer, then the closing line to its short form, then the standing lines to one line that counts them, names the role and `bin/ytstack-standing list`; last the `using-ytstack` body is cut to what fits, at a line end, with the line `(cut for the 10,000-char cap: read the rest in )` (issue #82: the Next action comes before that body). The Next action excerpt (at most five lines of 600 characters), the operating checklist and the lines about the checkout and a compaction are never cut. If the text is still above the threshold, it warns on stderr and emits the text anyway. Nothing else is dropped. Last, with a state block and on every source (also resume and compaction): one line `YT_BIN=`, the directory skills run ytstack's bins from as `"$YT_BIN/ytstack-"` (issue #85). It is added only when it still fits under the guard and the `using-ytstack` body was not cut, so it never costs the Next action excerpt or the directive; the `coordinate` preamble prints it too. +- Cap: the hook measures the injection without the host context. Above the guard threshold in the script, which sits just under the host's 10,000-character limit, it first cuts the standing lines to the three newest, then the Factory tools block shrinks to one line that counts them and names `bin/ytstack-upkeep`, then the minimal-code line to its short pointer, then the closing line to its short form, then the `using-ytstack` body is cut to what fits, at a line end, with the line `(cut for the 10,000-char cap: read the rest in )` (issue #82: the Next action comes before that body); last the standing lines shrink to one line that counts them, names the role and `bin/ytstack-standing list`. The Next action excerpt (at most five lines of 600 characters), the operating checklist and the lines about the checkout and a compaction are never cut. If the text is still above the threshold, it warns on stderr and emits the text anyway. Nothing else is dropped. Last, with a state block and on every source (also resume and compaction): one line `YT_BIN=`, the directory skills run ytstack's bins from as `"$YT_BIN/ytstack-"` (issue #85). It is added only when it still fits under the guard and the `using-ytstack` body was not cut, so it never costs the Next action excerpt or the directive; the `coordinate` preamble prints it too. - Output is the existing Claude-compatible JSON envelope by default. `YTSTACK_HOOK_FORMAT=plain` emits the raw context instead. Kimi's helper uses this mode only to prepare pending context, not as a claim that SessionStart stdout is consumed. ### Kimi pending bridge @@ -139,7 +139,7 @@ See `docs/statusline.md`. It was read against `bin/ytstack-status` at `verified_ - `pre-tool-use-edit` warns on stderr and exits 0. The Claude Code hooks reference says the agent never sees stderr of a hook that exits 0. Who sees the warning: Unknown -- not reproduced in a live session. - `task-created` exits 2 on drift and its message says the task is still created. The Claude Code hooks reference says exit 2 on TaskCreated rolls the creation back. Actual effect: Unknown -- not reproduced in a live session. -- The injection shares the 10,000-character cap with `using-ytstack` (about 7,400 characters). A project with two handoffs and long paths is near the cap already: there the standing list is cut to its pointer line, in a coordinate session after the checklist, and a long Next action cuts the end of the `using-ytstack` body, which the agent then reads from the file the pointer names.- `session-start` looks for `latest-handoff` only under the state base. An automatic handoff written to a fallback location is not announced. +- The injection shares the 10,000-character cap with `using-ytstack` (about 7,400 characters). A project with two handoffs and long paths is near the cap already: there, and in every coordinate session on this repository, the end of the `using-ytstack` body is cut, which the agent then reads from the file the pointer names.- `session-start` looks for `latest-handoff` only under the state base. An automatic handoff written to a fallback location is not announced. - `yt_resolve_yt_dir` looks only at the toplevel. Outside Git, a subdirectory does not find its parent's `.ytstack`. - `post-tool-use-bash` attributes a commit to the payload `cwd`, also when the command changed directory first. - The scope check in `pre-tool-use-edit` is a substring match over the whole task plan, not over its Files section. diff --git a/hooks/session-start b/hooks/session-start index a90ae95..e47a1ba 100644 --- a/hooks/session-start +++ b/hooks/session-start @@ -354,9 +354,9 @@ $STATE_CONTEXT" # own limit lives in its hooks config. Above the guard the blocks shrink in # this order: the standing lines to the three newest, the factory lines to a # pointer, the minimal-code line to its pointer, the closing line to its -# short form, the standing lines to a pointer, last the using-ytstack body to -# what fits, cut at a line end, with a pointer to the file (issue #82: the -# Next action comes before that body). The Next action excerpt (at most five +# short form, then the using-ytstack body to what fits, cut at a line end, +# with a pointer to the file (issue #82: the Next action comes before that +# body), last the standing lines to a pointer (they outrank the body's tail). The Next action excerpt (at most five # lines of 600 characters), the operating checklist and the lines about the # checkout and a compaction are never cut. Still above the guard: a warning. _HOST="${YTSTACK_HOST_CONTEXT:-}"; _HOST_LEN=${#_HOST} @@ -387,10 +387,6 @@ if over; then CLOSING_LINE="The files in $YT_DIR are the source of truth (STATE.md,${SPEC_HINT} DECISIONS.md, KNOWLEDGE.md), not the conversation." rebuild fi -if over && [ -n "$STANDING_LINES" ]; then - STANDING_LINES="Standing instructions: $STANDING_N in force for role $_ROLE (cut for the cap): bin/ytstack-standing list, before you act." - rebuild -fi if over; then _NOTE="(cut for the 10,000-char cap: read the rest in $USING_YTSTACK_FILE)" _KEEP=$(( ${#USING_SKILL} - (${#FULL_CONTEXT} - _HOST_LEN - 9500) - ${#_NOTE} - 2 )) @@ -403,6 +399,10 @@ $_NOTE" rebuild _BODY_CUT=yes fi +if over && [ -n "$STANDING_LINES" ]; then + STANDING_LINES="Standing instructions: $STANDING_N in force for role $_ROLE (cut for the cap): bin/ytstack-standing list, before you act." + rebuild +fi if over; then echo "[ytstack session-start] injection is $(( ${#FULL_CONTEXT} - _HOST_LEN )) chars; Claude Code caps additionalContext at 10,000. Shorten skills/using-ytstack/SKILL.md." >&2 fi