diff --git a/.ytstack/DECISIONS.md b/.ytstack/DECISIONS.md index d3024f1a..0fd25f9a 100644 --- a/.ytstack/DECISIONS.md +++ b/.ytstack/DECISIONS.md @@ -1305,3 +1305,75 @@ Plus: ops-layer split during the same session (yopstack created as own public re - `--worktrees` prints no command for a branch with any open pull request, or whose local head is in neither the pull request head nor `origin/` (unpushed commits). It leaves out the worktree it runs in and reads `LANES.md` from the main checkout (PR #90 review). **Supersedes:** None. Extends "2026-11-13: Coordinator mode keeps lanes, questions and standing instructions in files and reads host facts fresh (M024, issue #34)". + +## 2026-11-15: Coordinate mode is a session marker the coordinate preamble writes; the standing hooks act only with it (issue #72) + +**Context:** A 12-hour coordinator run got seven standing instructions in one day and recorded none in `.ytstack/standing/`; it wrote them to its private memory. Issue #72 asks for a prompt hook that flags such instructions and a Stop check that holds the turn when they were not recorded, both only in coordinate mode. Nothing marked a session as a coordinator: `LANES.md` exists in every checkout of a project that ever coordinated, also in a worker's or a human's other session. + +**Options considered:** +- A) `LANES.md` (or `standing/`) in the resolved `.ytstack` means coordinate mode. +- B) The `coordinate` preamble writes a marker per session out of tree; the hooks act only with it. +- C) Parse the transcript for a `ytstack:coordinate` invocation. + +**Chose:** B. The marker is `//coordinate` with the resolved `.ytstack` on its first line. `` is `${XDG_STATE_HOME:-~/.local/state}/ytstack/sessions` (`yt_session_home`), not `yt_state_base`: Claude Code exports `CLAUDE_PLUGIN_DATA` to hooks only, so a skill preamble in the Bash tool and a hook would resolve two different directories. The session id in the preamble is `CLAUDE_CODE_SESSION_ID`, the hook payload's `session_id` in the hooks. + +**Reason:** A marker is written exactly by the session that runs the skill and survives compactions and worktree moves (keyed by the session only, like `plugin-version`). A would flag prompts of every session in the project. C is slow, host-specific and undocumented. + +**How to apply:** +- `hooks/standing-prompt` (UserPromptSubmit) and the standing part of `hooks/stop` end at once without the marker; they read files and local git only, never the network and never a command of an entry. +- The prompt counter (`prompts`) and the flags (`standing-flags`) live beside the marker; `hooks/stop` writes `standing-stop`, so the same flagged prompts block once. +- Claude Code only. Codex registers no ytstack UserPromptSubmit hook and a Kimi shell has no session id; both keep the skill's Step 9 and the preamble's prompt-gap line without the hooks. + +**Supersedes:** None. Narrows "2026-11-15: SessionStart stays read-only ...": session state a skill writes goes under the session home, not under `yt_state_base`. + +## 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) + +**Context:** Many standing instructions are temporary ("until the load test ends", "while the v2 plan runs"). They could only be written as prose and ended when someone remembered. Issue #74 adds a compliance self-check (`check:`), a SessionStart injection of the active entries and the entries in lane briefs. Both kinds of command come from a file in the repository. + +**Options considered:** +- A) `until` only; conditions stay prose. +- B) `until`, `until-condition` and `until-check` (a command, exit 0 = ended), plus `check` (non-zero = not kept); an ended entry is closed by a new entry. +- C) As B, but an ended entry is edited or deleted. + +**Chose:** B. `until-check` may stand alone: the command is then the condition; with `until-condition` the sentence says for people what it checks. The closing entry has `kind: end` and `supersedes: ` and is no instruction itself; `ytstack-standing end` writes it. The commands run only in `ytstack-standing list`, which the `coordinate` preamble calls: `bash -c` in the checkout's toplevel, stdin closed, `YTSTACK_STANDING_TIMEOUT` seconds each (default 5), at most ten per call; a timeout counts as not ended and as a failed check. No hook runs them; `session-start` and the readers apply only a passed `until`. Roles in the scope (coordinator, lane, reviewer as whole words) filter the injection and the briefs; a scope naming no role is for everyone. + +**Reason:** Append-only stays (C would lose why and when an instruction ended). A hook runs on every prompt or session start under a seconds budget; a repository command there would slow every session and run before a person looked at it. In the coordinate preamble the session is already working in the repository, and a change under `standing/` goes to a person (`bin/ytstack-risk floor`). + +**How to apply:** +- `bin/ytstack-check --standing` validates the keys: `until` a real ISO UTC time after `given`, the three others one line, `kind` only `end`, an `end` names its entry. +- `bin/ytstack-standing add` writes by default in its own worktree on `standing/`, commits, pushes and opens or updates one pull request per UTC day (`ytstack-pr-watch create` when the PR watch is on); `--here` and user scope write in place. +- The SessionStart injection keeps at most six lines and is the last block cut for the 10,000-character cap, after the Next action, the factory tools and the minimal-code line. + +**Supersedes:** None. Extends "2026-11-14: Standing instructions are one file per entry in `.ytstack/standing/` ..." with optional keys and a closing entry. + +## 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) + +**Context:** A 12-hour coordinator run used almost none of ytstack's tooling: hand-written briefs, a `LANES.md` stale for a day, instructions in private memory, no release watch, a STATE pointer two milestones behind with a lint nobody acted on. Every rule was in the skill text; nothing on the path failed when it was skipped. Issue #75's correction names the same bypass of `ytstack-brief render`. + +**Options considered:** +- A) More skill text. +- B) In coordinate mode (the session marker): an ordered operating checklist injected at SessionStart and printed by the preamble; a PreToolUse hook on `Agent`, `Task`, `SendMessage` that warns on a prompt without a rendered brief; a Stop check for `LANES.md` and the STATE pointer that warns, and blocks once when the same finding came in N sessions in a row. +- C) As B, but the PreToolUse hook denies a dispatch without a brief. + +**Chose:** B with N = 3 (`YT_LINT_STREAK_N`). The checklist lives once, between markers in `docs/ux/coordinator-format.md`; the hook and the preamble read it from there and a test compares them. The marker of a rendered brief is its first line `# Brief: ()`, which `ytstack-brief render` already prints; no new line was added. `LANES.md` counts as stale when it changed more than five minutes before the newest dispatch or report of the session (a claim comes just before its dispatch). The counter is per repository out of tree (`/repos//coordinate-lints`); a session counts once, a clean stop resets it. + +**Reason:** A checklist that arrives with every compaction is read when the skill text is not. A deny (C) would also hit a research or lookup agent, which needs no brief; a warning on the path is enough to make the bypass visible. Blocking at once on a lint would stop a session for a pointer the human may want to keep for a day; three sessions in a row is a pattern, not a moment. + +**How to apply:** The hooks act only with the coordinate marker and read local files only. A coordinate session gets the checklist instead of the minimal-code line. Codex and Kimi are not covered (no ytstack hook on their subagent tools; no session id in a Kimi shell). + +**Supersedes:** None. Extends "2026-11-15: Coordinate mode is a session marker ..." with three more hook parts. + +## 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) + +**Context:** The independent review of PR #87 found that `ytstack-standing list` read every `origin/standing/*` branch and ran the `check` and `until-check` of its entries: anyone who can push a branch got code execution in the coordinator's preamble. It also found that pending entries never reached the SessionStart injection or the briefs, and that an entry on an earlier day's unmerged branch could not be superseded. + +**Options considered:** +- A) Run the commands of every entry the list shows, as before. +- B) Run commands only for a working-tree entry whose file is the one on the default branch; read pending entries only from local `standing/*` branches and their upstreams, as text; start a new day's branch from the newest pending one. +- C) Never run commands. + +**Chose:** B. Pending entries are shown (marked) in `list`, the SessionStart injection and the briefs, never executed (`[check not run: pending]`, `[check not run: not on ]`). Outside a repository and in one without a commit the files are the user's own and run. A remote branch no local branch tracks is not read at all. + +**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. diff --git a/.ytstack/spec/artifacts.md b/.ytstack/spec/artifacts.md index 0ebb22a5..55a1b465 100644 --- a/.ytstack/spec/artifacts.md +++ b/.ytstack/spec/artifacts.md @@ -66,7 +66,7 @@ The `.ytstack/` artifact model: the Markdown files that hold a project's memory | `HANDOFF.md` | `handoff-session`; `coordinate` when it rotates (its format with the "Rotation" block of `docs/ux/coordinator-format.md`) | the user; the rotating coordinator appends its workers' reports under "Reports after the rotation"; no hook writes it | | `LANES.md` | `bin/ytstack-frontier claim` or `peer set` (first write) | `bin/ytstack-frontier` (`set`, `release`), one row per call; called by `spawn-milestone-team`, `coordinate`, `finish-lane`; its `## Peers` lines (sessions in other repositories) by `ytstack-frontier peer set` from `coordinate` | | `questions/Q###-.md` | `bin/ytstack-questions new` (from `coordinate`, `reassess-roadmap`, `review-lessons` (a proposed line for a role file, `blocks:` the finding), and from `bin/ytstack-upkeep --question`, which keeps at most one open or asked file titled `Upkeep found ...`) | the agent fills Context, Options, Recommendation; `ask` and `answer` change the state; the answer text is the human's | -| `standing/-.md`, `STANDING.md` | `coordinate`, when the human gives an instruction that holds beyond the task: a new file with `given`, `scope`, `supersedes` (`docs/ux/coordinator-format.md`); appended to `STANDING.md` only where no `standing/` exists | an entry is never edited; a newer one supersedes it by name, readers skip it; `STANDING.md` alone stays valid, also as an index, and is read beside the directory | +| `standing/-.md`, `STANDING.md` | `coordinate` through `bin/ytstack-standing add`, when the human gives an instruction that holds beyond the task: a new file with `given`, `scope`, `supersedes` and optionally `until`, `until-condition`, `until-check`, `check` (`docs/ux/coordinator-format.md`), by default on the day's `standing/` branch and pull request; appended to `STANDING.md` only where no `standing/` exists | an entry is never edited; a newer one supersedes it by name, an ended one is closed by an entry of `kind: end` (`ytstack-standing end`), readers skip both and an entry whose `until` passed; `STANDING.md` alone stays valid, also as an index, and is read beside the directory | | `handover/-.sh` and its receipt | `handover-step` through `bin/ytstack-handover new`; the receipt by the script when the human runs it | a script that ran is not edited | | `retro/LANES-.md` | `lane-retro`, with a `## Upstream` section like the retro's | appended on a second run of the same day | | `archive//`, `archive/INDEX.md`, `RECONCILE-.md` | `reconcile` | -- | @@ -190,7 +190,7 @@ Automatic handoffs and the session journal are not artifacts. `hooks/pre-compact - DECISIONS.md -- "2026-11-13: Verification, review and orchestration work are bounded like code (M023, issue #35)" (the `Runs:` line, `## Gates`, `## Review`, the evidence fields of a summary) - 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: A plan outside `.ytstack/` is detected by a script and mapped by the agent, after one question (M031-S05, issue #54)" (the external plan class) - DECISIONS.md -- "2026-11-13: Coordinator mode keeps lanes, questions and standing instructions in files and reads host facts fresh (M024, issue #34)" (the lanes table is not part of `STATE.md`, which narrows the proposal in issue #34) -- DECISIONS.md -- "2026-11-14: Standing instructions are one file per entry in `.ytstack/standing/`; `STANDING.md` stays valid (issue #57)" +- DECISIONS.md -- "2026-11-14: Standing instructions are one file per entry in `.ytstack/standing/`; `STANDING.md` stays valid (issue #57)", extended 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)" - DECISIONS.md -- "2026-04-23: `.ytstack/` location is user-chosen (project vs user vs both)"; "2026-11-15: New artifacts follow the directory a milestone already lives in (issue #70)" - DECISIONS.md -- "2026-05-31: active_slice is plan-task-owned and team-member-guarded (M012 / issue #21-RC1)" - DECISIONS.md -- "2026-05-31: post-tool-use-bash is stub-once; summarize-task owns commit-to-task linking (M015 / issue #22)" diff --git a/.ytstack/spec/checks-and-evals.md b/.ytstack/spec/checks-and-evals.md index 979a2626..9cdb88cd 100644 --- a/.ytstack/spec/checks-and-evals.md +++ b/.ytstack/spec/checks-and-evals.md @@ -7,6 +7,7 @@ paths: - bin/ytstack-brief - bin/ytstack-frontier - bin/ytstack-questions + - bin/ytstack-standing - bin/ytstack-finish-lane - bin/ytstack-handover - bin/ytstack-watch @@ -30,7 +31,7 @@ sources: - docs/ux/signal-format.md - docs/ux/external-plans.md - docs/ux/upstream-feedback.md -verified_at: db07481 +verified_at: 1234c16 --- # checks-and-evals @@ -44,7 +45,7 @@ Everything that tells a contributor whether a change is acceptable: the static c **`bin/ytstack-check`: static contracts** - A Python script on the standard library. It finds the plugin root by walking up to `.claude-plugin/plugin.json`; an optional path argument sets where it starts. -- `check_standing` validates `.ytstack/standing/` (`docs/ux/coordinator-format.md`): the name `-.md` with a date and time that exist, `given` as an existing ISO UTC time in the minute of the name, a `scope`, a body, and a `supersedes` that names an earlier existing entry (missing seconds count as `00`). The full run checks the plugin's own directory; `--standing []` runs only this check in any project with `.ytstack/`, resolved through `hooks/lib/git-ctx.sh` like the preambles (user scope included), and needs no plugin root (exit 0 or 1). +- `check_standing` validates `.ytstack/standing/` (`docs/ux/coordinator-format.md`): the name `-.md` with a date and time that exist, `given` as an existing ISO UTC time in the minute of the name, a `scope`, a body, and a `supersedes` that names an earlier existing entry (missing seconds count as `00`); `until` an existing ISO UTC time after `given`, `until-condition`, `until-check` and `check` one non-empty line each when present (`until-check` may stand alone), `kind` absent or `end`, an `end` with a `supersedes`. The full run checks the plugin's own directory; `--standing []` runs only this check in any project with `.ytstack/`, resolved through `hooks/lib/git-ctx.sh` like the preambles (user scope included), and needs no plugin root (exit 0 or 1). - It reads `skills/*/SKILL.md`, `agents/*.md`, the scripts in `hooks/`, both manifests in `.claude-plugin/` and this repository's own `.ytstack/spec/`. One function per contract: `check_skill`, `check_agent`, `check_cross_refs`, `check_vendor_sibling_refs`, `check_resolver_contract`, `check_inline_leaks`, `check_gstack_adapted`, `check_spec`, `check_keeping_block`. Those functions are the complete rule list; the two groups below summarize them. - `check_spec` runs `bin/ytstack-spec lint` and `drift` on the plugin root and is skipped when the tree has no `.ytstack/spec/`. A format error is a failure; an area whose paths changed after its description is a warning to look. `check_keeping_block` fails when the "Keeping this true" block in `skills/init-project/SKILL.md` or `skills/adopt-brownfield/SKILL.md` differs from the one in `docs/ux/spec-format.md`. - Failures (`[fail]`): skill frontmatter missing, `name` different from the directory, no description or one over the length limit; a procedure skill without `## Checklist` or `## Terminal State`; an agent file that breaks `docs/ux/agent-structure.md` (required fields, examples, existing `ytstack:` skills, hard line limit); a role named in `skills/spawn-milestone-team/SKILL.md` without `agents/.md`; a wrapper naming a vendored `SKILL.md` that does not exist; a banned shell pattern (`_BANNED`) in a skill or hook; a preamble or hook that does not source `hooks/lib/git-ctx.sh`; inlined vendor text without a covering `## Namespace note`; an adapted gstack skill without `metadata.upstream`, with a gstack runtime reference, a symlink or an em-dash. @@ -86,14 +87,14 @@ Everything that tells a contributor whether a change is acceptable: the static c **`bin/ytstack-brief`: the brief of a dispatched worker and its report** - A bash script on awk. `render --task ` or `--slice ` prints a brief built from the plan files and `skills/spawn-milestone-team/brief-template.md`, and includes the body of `skills/minimal-code/SKILL.md` as the work contract, read at render time. It prints no brief when the plan, its `## Files` section, the template or the contract is missing (exit 1). -- `render --kind implement|review|prepare` adds what the worker may do; a review brief pins the commit range it reviews (`--head`, optionally `--base`) and has no Git section. `render --lesson F###` builds the brief of the lesson lane `lesson-F###` from the lesson in `signals/` (outcome from its title, target and "Assessment"; scope and check from its "Files" and "Verification"; commit prefix the lane). +- `render --kind implement|review|prepare` adds what the worker may do; a review brief pins the commit range it reviews (`--head`, optionally `--base`) and has no Git section. Every brief carries a section "Standing instructions" with the active entries for its kind (`review`: the reviewer role, else lane; `yt_standing_lines`), left out when there are none. `render --lesson F###` builds the brief of the lesson lane `lesson-F###` from the lesson in `signals/` (outcome from its title, target and "Assessment"; scope and check from its "Files" and "Verification"; commit prefix the lane). - `check` validates a worker's report from a file or stdin: the labels of the template's "Report" section, each with a value, an exit code in every `Checks run:` line, one of the three `Status:` values and its consistency with `Blockers:`. It prints one line per problem and exits 1, or `report ok`. **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-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-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-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. @@ -160,12 +161,11 @@ Everything that tells a contributor whether a change is acceptable: the static c ## Where implemented - `bin/ytstack-check` -- the checker; its docstring names the flags and exit codes. `bin/ytstack-spec` (the spec tool) and `bin/ytstack-brief` (brief renderer and report check), pinned by `tests/ytstack-spec.test.sh` and `tests/ytstack-brief.test.sh`. -- `bin/ytstack-frontier`, `bin/ytstack-questions`, `bin/ytstack-finish-lane`, `bin/ytstack-handover`, `bin/ytstack-watch` -- the coordinator scripts, each with `tests/.test.sh`. +- `bin/ytstack-frontier`, `bin/ytstack-questions`, `bin/ytstack-standing`, `bin/ytstack-finish-lane`, `bin/ytstack-handover`, `bin/ytstack-watch` -- the coordinator scripts, each with `tests/.test.sh`. - `bin/ytstack-risk`, `bin/ytstack-review-escapes`, `bin/ytstack-runtime`, `bin/ytstack-signals`, `bin/ytstack-upkeep`, `bin/ytstack-plans`, `bin/ytstack-upstream`, each with `tests/.test.sh` (the live cases of `ytstack-runtime` need `python3` and are skipped without it). Suites under `pipefail` read pipes to the end (`grep_q`, not `grep -q`: SIGPIPE). `tests/evals-frontmatter.test.sh` lints every `evals/*/prompt.md` frontmatter for plain scalars holding `: ` or ` #`, which keep a case from loading. - `tests/run-all.sh` -- the suite runner. `tests/*.test.sh` -- the suites. `tests/codex_plugin_test.py`, `kimi_plugin_test.py`, `kimi_lifecycle_test.py`, `kimi_live_test.py` -- the Python host tests. `evals//` -- the eval cases. `evals/README.md` -- how to run them. -- `.github/workflows/ci.yml`, `plugin-check.yml`, `secret-scan.yml`. +- `.github/workflows/ci.yml`, `plugin-check.yml`, `secret-scan.yml`; `CONTRIBUTING.md` ("Release checklist") -- the checks expected before a release. - `docs/ux/skill-structure.md`, `docs/ux/agent-structure.md`, `docs/ux/writing-style.md` -- the contracts the checker enforces in part. -- `CONTRIBUTING.md` ("Release checklist") -- the checks expected before a release. ## How to verify @@ -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`, 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`. - 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/dependencies.md b/.ytstack/spec/dependencies.md index de9c0daf..03d02470 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: db07481 +verified_at: 39275b7 --- # dependencies diff --git a/.ytstack/spec/hooks-and-state.md b/.ytstack/spec/hooks-and-state.md index 970231f7..5636d1bc 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`. It prints nothing without the directory; `STANDING.md` is read by the skills themselves. +- `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. ### STATE lint and progress block @@ -70,9 +70,11 @@ 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 | | `session-end` | SessionEnd | `cwd`, `session_id`, `reason` | appends one JSON line to `session.jsonl` in the session state directory | 0 | -| `stop` | Stop | `cwd`, `stop_hook_active` | prints a `systemMessage` when the active task has no summary or only a draft | 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 | | `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 | | `task-created` | TaskCreated | `cwd`, subject, description | prints a scope warning on stderr | 2 on drift, else 0 | @@ -84,16 +86,15 @@ Every hook except `pr-watch` sources the library and resolves from the payload ` - `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. It stays silent when `stop_hook_active` is true. +- `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. ### 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`, 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 cuts 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. Next, the Factory tools block shrinks to one line that counts them and names `bin/ytstack-upkeep`. 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, 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. - 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 @@ -108,7 +109,7 @@ See `docs/statusline.md`. It was read against `bin/ytstack-status` at `verified_ ## Interfaces and contracts -- `hooks/hooks.json` registers the nine lifecycle hooks, `version-notice` and `pr-watch` for Claude Code: event, matcher, timeout. The Codex and Kimi registrations are in the `host-adapters` area. +- `hooks/hooks.json` registers the nine lifecycle hooks, `version-notice`, `standing-prompt`, `pre-tool-use-agent` and `pr-watch` for Claude Code: event, matcher, timeout. The Codex and Kimi registrations are in the `host-adapters` area. - The `YT_*` globals each function sets are named in the comment above that function. Consumers are every hook, the skill preambles and `bin/ytstack-status`. - Files other parts read: `HANDOFF.auto.md` and `latest-handoff` (read by `hooks/session-start` and `skills/resume-session/SKILL.md`), draft and auto summaries (replaced by `summarize-task`, listed by `reconcile`). Kimi also reads and removes `pending-context.md` through its helper. - The `progress` block and the segment's exit codes: `docs/statusline.md`. @@ -119,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. -- `session-start`, `stop`, `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`, 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. - 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. @@ -138,22 +139,23 @@ 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. - `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. 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. `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 - `hooks/lib/git-ctx.sh` -- resolver, state directories, preferences, lint, progress parser, brownfield signals, commit discovery - `hooks/hooks.json` -- registration -- `hooks/session-start`, `hooks/version-notice`, `hooks/pre-compact`, `hooks/session-end`, `hooks/stop`, `hooks/pre-tool-use-edit`, `hooks/post-tool-use-bash`, `hooks/task-created`, `hooks/task-completed`, `hooks/teammate-idle` +- `hooks/session-start`, `hooks/version-notice`, `hooks/standing-prompt`, `hooks/pre-tool-use-agent`, `hooks/pre-compact`, `hooks/session-end`, `hooks/stop`, `hooks/pre-tool-use-edit`, `hooks/post-tool-use-bash`, `hooks/task-created`, `hooks/task-completed`, `hooks/teammate-idle` - `bin/ytstack-status` -- status line segment, and progress per phase (`--phases`) - `bin/ytstack-check` (`check_resolver_contract`) -- banned patterns -- Tests: `tests/git-ctx.test.sh`, `tests/hooks-json.test.sh`, `tests/hooks-readonly.test.sh`, `tests/hooks-stop.test.sh`, `tests/hooks-worktree.test.sh`, `tests/hooks-concurrency.test.sh`, `tests/post-tool-use-bash.test.sh`, `tests/pre-compact.test.sh`, `tests/session-end.test.sh`, `tests/session-notices.test.sh`, `tests/ytstack-status.test.sh`, `tests/kimi_lifecycle_test.py` +- Tests: `tests/git-ctx.test.sh`, `tests/hooks-json.test.sh`, `tests/hooks-readonly.test.sh`, `tests/hooks-stop.test.sh`, `tests/hooks-standing.test.sh`, `tests/hooks-coordinate.test.sh`, `tests/hooks-worktree.test.sh`, `tests/hooks-concurrency.test.sh`, `tests/post-tool-use-bash.test.sh`, `tests/pre-compact.test.sh`, `tests/session-end.test.sh`, `tests/session-notices.test.sh`, `tests/ytstack-status.test.sh`, `tests/kimi_lifecycle_test.py` ## How to verify @@ -164,6 +166,8 @@ bash tests/git-ctx.test.sh bash tests/hooks-json.test.sh bash tests/hooks-readonly.test.sh bash tests/hooks-stop.test.sh +bash tests/hooks-standing.test.sh +bash tests/hooks-coordinate.test.sh bash tests/hooks-worktree.test.sh bash tests/hooks-concurrency.test.sh bash tests/post-tool-use-bash.test.sh @@ -178,6 +182,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: 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/host-adapters.md b/.ytstack/spec/host-adapters.md index f4d47502..54162cfe 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) 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`), 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. 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`, 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. - 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. diff --git a/.ytstack/spec/skills.md b/.ytstack/spec/skills.md index 7209eb68..21991839 100644 --- a/.ytstack/spec/skills.md +++ b/.ytstack/spec/skills.md @@ -105,7 +105,7 @@ 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 (a new file in `standing/`; `STANDING.md` only where no `standing/` exists), 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). - `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. - **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. @@ -122,7 +122,7 @@ Formats: `docs/ux/coordinator-format.md`. The four skills below are for the sess - `docs/ux/askuserquestion-format.md`: the four-part question body, option annotations, tiers. - `docs/ux/agent-structure.md`: agent frontmatter, body sections, size limit. - `hooks/lib/git-ctx.sh`: the comment above each function names the globals it sets. -- The worker brief and the report shape: `skills/spawn-milestone-team/brief-template.md`, rendered by `bin/ytstack-brief`. Dispatch, report check and verifier prompt: `skills/spawn-milestone-team/SKILL.md`, Steps 5 to 7. +- The worker brief and the report shape: `skills/spawn-milestone-team/brief-template.md`, rendered by `bin/ytstack-brief`; its "Standing instructions" carry the whole text of each entry for the lane's role, pending ones included. Dispatch, report check and verifier prompt: `skills/spawn-milestone-team/SKILL.md`, Steps 5 to 7. - The artifacts skills read and write: [artifacts.md](artifacts.md). ## Invariants and security boundaries @@ -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)" and 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`) +- 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: `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 c36e56b7..0a5de996 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,37 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `## Peers` section of `LANES.md` (`ytstack-frontier peer set` / `peer list`); `coordinate` prints them in its preamble and its Rotation block, so a compaction no longer loses which session is which. +- **Standing instructions are recorded under load** (issue #72): in a + `coordinate` session the new prompt hook `hooks/standing-prompt` flags a + prompt that reads like a standing instruction ("always", "never", "from now + on", "until", "priorisiere", "fass ... nicht an", ...) and says to record it + before the next dispatch; the Stop hook holds the turn once when flagged + prompts got no entry. Coordinate mode is a session marker the `coordinate` + preamble writes. Claude Code only. +- **`bin/ytstack-standing`**: `add` records an entry in one command, in its + own worktree with a commit and one standing pull request per UTC day (or in + place with `--here`); `end` closes one; `list` prints the active entries, + the ended ones, the conditions to check and the failed checks. The + `coordinate` preamble prints it, with the newest entry's age and the human + prompts since. +- **Temporary and conditional entries** (issue #73): optional `until`, + `until-condition` and `until-check`; an ended entry is closed by an entry of + `kind: end`. `ytstack-check --standing` validates the new keys. +- **Standing entries reach every context** (issue #74): `hooks/session-start` + injects the active entries for the session's role (also after a + compaction), `ytstack-brief render` puts the ones for lanes or reviewers + into the brief, and an optional `check:` command shows a broken instruction + in the `coordinate` preamble. Commands of an entry run only there, bounded + by a timeout. +- **Coordinate mode keeps the operating path** (issue #76, part of #75): a + short ordered checklist (claim, render, dispatch; check, set; standing + entry; release watch) is injected at session start and after a compaction + and printed by the `coordinate` preamble, from one place in + `docs/ux/coordinator-format.md`. The new `hooks/pre-tool-use-agent` warns + when an `Agent` or long `SendMessage` prompt is no rendered brief. The Stop + 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. ### Changed @@ -50,6 +81,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `coordinate` runs its bins as `"$YT_BIN/ytstack-"`, so a long session no longer calls a removed version's path after an update. +- `coordinate` 0.6.2: Step 9 records with `ytstack-standing add` and says + that agent memory is no substitute; Step 3 acts on ended entries, + conditions and failed checks. +- `ytstack-standing list` runs an entry's `check` and `until-check` only when + the entry is merged on the default branch, never from a pending or a + remote-only branch; a timeout kills the command's whole process group. ### Fixed @@ -72,6 +109,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 moved. - `teammate-idle` no longer fails on a slice plan without an open task (`grep -c ... || echo 0` produced `0` twice and broke the sum). +- `coordinate` and `resume-session` (0.1.2) find the automatic handoff the + PreCompact hook wrote under `CLAUDE_PLUGIN_DATA`, which their shell does + not see (`yt_latest_handoff`). +- The SessionStart injection near its cap shrinks the standing list before it + cuts the Next action, and keeps a Next action shorter than its omission + note. ## [0.11.0] - 2026-11-15 diff --git a/bin/ytstack-brief b/bin/ytstack-brief index 65773a48..2eaaaba8 100755 --- a/bin/ytstack-brief +++ b/bin/ytstack-brief @@ -300,6 +300,11 @@ EOF B_CONTEXT="$B_CONTEXT$NL- \`$(rel "$YT_DIR/KNOWLEDGE.md")\`" fi + # The standing instructions for this kind of lane (issue #74): the active + # entries whose scope names lanes (a review: reviewers) or no role at all. + x=lane; [ "$lane" != review ] || x=reviewer + B_STANDING=$(yt_standing_lines "$YT_DIR" "$x" 0 full) + # What the worker may do: the kind's fixed sentences, then its commit rule, # which the Git section repeats. The inserted values are a validated # reference and hex digits, so no character of them is special to the @@ -344,7 +349,7 @@ EOF # shortcut: values travel through the environment, so one value is limited to # what the OS allows per variable (about 128 KB on Linux); upgrade to # temporary files if a plan section ever gets that long. - export B_REF B_PROJECT B_OUTCOME B_KIND B_LENS B_FILES B_CONTEXT B_VERIFICATION B_SPEC_IMPACT B_GATES B_BRANCH B_BASE B_COMMIT_RULE B_CONTRACT + export B_REF B_PROJECT B_OUTCOME B_KIND B_LENS B_FILES B_CONTEXT B_STANDING B_VERIFICATION B_SPEC_IMPACT B_GATES B_BRANCH B_BASE B_COMMIT_RULE B_CONTRACT awk ' function flush() { if (!drop) printf "%s", buf; buf = ""; drop = 0 } /^ +Coordinator operating checklist (scripts in bin/ of the plugin): +1. Dispatch: ytstack-frontier claim --by -> ytstack-brief render -> Agent with that brief. Never a hand-written brief. +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. + + ## `LANES.md` -- who works on what A lane is one unit of delegated work: by default one slice (`M004-S02`), where a plan needs it one task (`M004-S02-T03`), a lesson whose check is still to be built (`lesson-F012`, see below) or a named piece outside the milestone plan (`review-pr-12`). `STATE.md` stays the pointer of the session's own position and links this file; the table does not live in `STATE.md`. @@ -203,14 +216,56 @@ One review per lane, a second only for the fix. | `given` | The UTC time, ISO (`YYYY-MM-DDTHH:MMZ`, seconds optional). The same minute as the file name, whose time orders the entries; missing seconds count as `00`. | | `scope` | Where the instruction applies. Not empty. | | `supersedes` | Empty, or the file name (without `.md`) of the earlier entry this one replaces. | +| `until` | Optional. An ISO UTC time after `given`; from then on the entry has ended. | +| `until-condition` | Optional. One sentence naming the event that ends the entry ("PR #1879 merged"). The coordinator checks it when the list names it. | +| `until-check` | Optional. A command that exits 0 once the entry has ended (`gh pr view 1879 --json state -q .state \| grep -qx MERGED`). It may stand alone (the command is the condition) or beside `until-condition` (the sentence says for people what it checks). | +| `check` | Optional. A command that exits non-zero while the instruction is not kept; its first output line is the warning (`test -n "$(find .ytstack/LANES.md -mmin -120)" \|\| echo "LANES.md older than 2 h"; ...`). | +| `kind` | Optional. Only `end`: the entry closes the one its `supersedes` names and is no instruction itself. | Rules: - Own words, never a quotation. The body is the instruction. - An entry is not edited after it is written and nothing is deleted. An instruction that replaces another is a new file whose `supersedes` names the old one; from then on the old one no longer holds. -- Readers take the entries newest first and skip every entry that another entry supersedes. `yt_standing` in `hooks/lib/git-ctx.sh` prints them; the preambles of `coordinate`, `finish-lane` and `signal-intake` list them between `STANDING_ENTRIES_BEGIN` and `STANDING_ENTRIES_END`. The coordinator reads every listed file at every start and after every compaction, before it acts. +- An entry ends by its `until`, by an `until-check` that exits 0, or when the coordinator finds its `until-condition` met. It is then closed with a short entry of `kind: end` that supersedes it, whose body says what ended it ("Ended: PR #1879 merged at 2026-11-15T10:02Z."); `ytstack-standing end --reason "..."` writes it. That keeps the record append-only. +- Readers take the entries newest first and skip every entry that another entry supersedes, every entry of `kind: end` and every entry whose `until` has passed. `yt_standing` in `hooks/lib/git-ctx.sh` prints them; the preambles of `finish-lane` and `signal-intake` list them between `STANDING_ENTRIES_BEGIN` and `STANDING_ENTRIES_END`, the preamble of `coordinate` lists there what `ytstack-standing list` prints. The coordinator reads every listed file at every start and after every compaction, before it acts. - A `README.md` in the directory is a note for people and is not an entry. +### Writing and listing: `bin/ytstack-standing` + +- `add "" --scope "" [--supersedes ] [--until ] [--until-condition ""] [--until-check ""] [--check ""]` writes the entry, named from UTC now and the first words of the text. By default it writes in a worktree of its own outside the checkout (`/repos//standing-worktree`), on the branch `standing/`, commits, pushes and opens one pull request per UTC day, or adds to the open one (through `ytstack-pr-watch create` when the PR watch is on, else `gh pr create`). `--here` writes into the resolved `standing/` and commits nothing; user scope always does that. The entry has to pass `ytstack-check --standing`, else nothing is written. A new day's branch starts from the newest pending standing branch (see below), so that an entry can supersede or end one that still waits in that pull request; an earlier day's branch with commits origin does not have is pushed first. `--supersedes`, `--until`, `--slug` and `--base` take one line. +- `end --reason ""` writes the closing entry (`kind: end`, the scope of the closed one), also for an entry that is still pending. +- `list` prints, in this order: the newest entry with its age and the number of human prompts this session sent since (from `hooks/standing-prompt`), the active entries as `- (): ` (pending ones marked `(pending: )`), the ended ones (to close), the conditions to check now, and the failed checks. `--no-checks` runs no command. + +**Pending** entries are the ones on a local branch `standing/*` (the branches `ytstack-standing add` creates on this machine) or on the upstream such a branch tracks, that are neither in the working tree nor on the default branch. A remote branch that no local branch tracks is never read: anyone who can push a branch could put an entry there. `list`, the SessionStart injection and the lane briefs show pending entries (text only, with the role filter); `yt_standing`, which `finish-lane` and `signal-intake` print, reads the working tree only. + +### Where the commands of an entry run + +`until-check` and `check` come from a file in the repository. They run only in `ytstack-standing list` (and so in the `coordinate` preamble), and only for an entry of the working tree whose file is the same as on the default branch (`origin/HEAD`, else `origin/main`, `origin/master`, `main`, `master`; `add` asks the remote first when `origin/HEAD` is missing): merged, so a person reviewed it (a change under `standing/` goes to a person, `bin/ytstack-risk floor`). A pending entry and an unmerged file in the checkout never run; the list says `[check not run: pending]` or `[check not run: not on ]`. Outside a repository (user scope) and in a repository without a commit the files are the user's own and run; a repository with commits whose default branch cannot be found runs none (`[check not run: default branch unknown ...]`). A pending entry's whole text is in `list`, since its file is not on disk. Each runs with `bash -c` in the checkout's toplevel, in a process group of its own, stdin closed, at most `YTSTACK_STANDING_TIMEOUT` seconds (default 5; then the whole group is killed, a timeout counts as "not ended" and as a failed check), and at most ten commands per call; past that each entry says `[check not run: limit of 10 commands per list]`. No hook runs them: `hooks/session-start`, `hooks/standing-prompt` and `hooks/stop` read files only, and an `until` that passed is the only end they apply. + +### Scope and roles + +The scope is free text. Three roles are read from it, as whole words, case-insensitive: + +| Role | Words in the scope | +|---|---| +| coordinator | `coordinator`, `coordinators` | +| lane | `lane`, `lanes`, `worker`, `workers`, `implementer`, `implementers` | +| reviewer | `reviewer`, `reviewers`, `review`, `reviews` | + +A scope that names no role applies to everyone. The coordinator gets every entry. `hooks/session-start` injects the active entries for the session's role (coordinator when the `coordinate` preamble left its session marker, else lane), pending ones included, at most six lines; near the injection cap first the three newest (before the Next action is cut), last one pointer line. `ytstack-brief render` puts the entries for its kind (`review`: reviewer, else lane) under "Standing instructions". + +### Coordinate mode and the hooks + +The `coordinate` preamble writes the session marker `//coordinate` (`yt_session_home`: `${XDG_STATE_HOME:-~/.local/state}/ytstack/sessions`; the id is `CLAUDE_CODE_SESSION_ID`), with the resolved `.ytstack` on its first line and the repository key on its second (in user scope the `.ytstack` lies outside the repository). Only then do these hooks act, so a session that never ran `coordinate` is not touched. + +- `hooks/standing-prompt` (UserPromptSubmit) counts every human prompt and flags one that reads like a standing instruction. It looks for instruction phrases, not single words: from now on, going forward, until further notice, don't touch, hands off, prioritise, remember to, an imperative "always/never " at the start of a clause, a temporary hold or prohibition with until, till or while and a time or condition ("hold merges until 12:37", "no deploys while the load test runs", "until the load test ends"); German ab jetzt, ab sofort, von nun an, bis auf weiteres, solange ... nicht, grundsaetzlich, immer wenn, nie wieder, nie mehr, niemals, denk dran, merk dir, priorisiere, fass ... nicht an, kuenftig, and the temporary forms "bis 12:37 keine ...", "keine ... bis/solange/waehrend ...", "solange ..." at the start of a clause. A prompt that is one question and nothing else is never flagged ("bis wann ist das fertig?", "ist das immer noch rot?"). A flagged prompt gets one line of context: record it before the next dispatch. +- `hooks/stop` blocks the stop once when flagged prompts have no entry since: an entry counts when its name time is in or after the minute of the first flagged prompt, in the working tree or added on any ref of the repository after it (local branches, and the remote-tracking branch a pushed standing pull request left). Local git only. The same prompts never block twice. +- `hooks/session-start` injects the "Operating checklist" above, in place of the minimal-code line (a coordinator writes no product code). +- `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. + ### `STANDING.md` The single file of earlier versions stays valid. A project without `standing/` keeps it as it was: one line per instruction, time, the instruction, its scope; a replaced line is struck through and dated. @@ -257,4 +312,4 @@ The old session stays open as a relay until every listed worker has reported. Pe - `bin/ytstack-questions check`: ids are unique and match the file name, `state` holds a listed value, `asked` and `answered` are set exactly when the state says so, an answered file has text under `## Answer`. - `bin/ytstack-brief check`: the report labels, the three `Status:` values and their consistency with `Blockers:`. - `bin/ytstack-handover check`: the staged script of a human-only step (see `skills/handover-step/SKILL.md`). -- `bin/ytstack-check --standing []`: every entry in `standing/` has a name of the form above with a date and time that exist, `given` as an existing ISO UTC time in the minute of its name, a `scope` and a body, and every `supersedes` names an earlier entry that exists (missing seconds count as `00`). Without a directory argument it resolves `.ytstack` like the skill preambles, user scope included. +- `bin/ytstack-check --standing []`: every entry in `standing/` has a name of the form above with a date and time that exist, `given` as an existing ISO UTC time in the minute of its name, a `scope` and a body, and every `supersedes` names an earlier entry that exists (missing seconds count as `00`); `until` is an existing ISO UTC time after `given`, `until-condition`, `until-check` and `check` are one non-empty line when present, `kind` is `end` or absent, and an `end` names the entry it closes. Without a directory argument it resolves `.ytstack` like the skill preambles, user scope included. diff --git a/hooks/hooks.json b/hooks/hooks.json index 19f47a3f..72966077 100644 --- a/hooks/hooks.json +++ b/hooks/hooks.json @@ -1,5 +1,5 @@ { - "description": "ytstack lifecycle hooks: inject project state at session boundaries, persist volatile session state OUT OF TREE on compaction and end-of-session, link commits to tasks. All hooks resolve the checkout from the payload cwd via hooks/lib/git-ctx.sh (never CLAUDE_PROJECT_DIR) and fail open (no onFailure: block). SessionEnd hooks get a 1.5 s default budget from Claude Code; the hook runs in ~0.3-0.5 s. hooks/version-notice (UserPromptSubmit) says once when the installed plugin is newer than the one the session loaded. hooks/pr-watch (SessionStart, UserPromptSubmit, PreToolUse and PostToolUse on Bash or an MCP create_pull_request) is the opt-in PR watch: it exits at once unless ~/.ytstack/config has pr_watch=on (docs/pr-watch.md).", + "description": "ytstack lifecycle hooks: inject project state at session boundaries, persist volatile session state OUT OF TREE on compaction and end-of-session, link commits to tasks. All hooks resolve the checkout from the payload cwd via hooks/lib/git-ctx.sh (never CLAUDE_PROJECT_DIR) and fail open (no onFailure: block). SessionEnd hooks get a 1.5 s default budget from Claude Code; the hook runs in ~0.3-0.5 s. hooks/version-notice (UserPromptSubmit) says once when the installed plugin is newer than the one the session loaded. hooks/standing-prompt (UserPromptSubmit) acts only in a coordinate session (the marker the coordinate preamble writes): it counts human prompts and flags one that reads like a standing instruction, and hooks/stop then blocks once when no standing entry was written since; hooks/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).", "hooks": { "SessionStart": [ { @@ -39,6 +39,17 @@ } ] }, + { + "hooks": [ + { + "type": "command", + "shell": "bash", + "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/standing-prompt\"", + "async": false, + "timeout": 5 + } + ] + }, { "hooks": [ { @@ -142,6 +153,18 @@ } ] }, + { + "matcher": "Agent|Task|SendMessage", + "hooks": [ + { + "type": "command", + "shell": "bash", + "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/pre-tool-use-agent\"", + "async": false, + "timeout": 5 + } + ] + }, { "matcher": "Bash|mcp__.*create_pull_request.*", "hooks": [ diff --git a/hooks/lib/git-ctx.sh b/hooks/lib/git-ctx.sh index 4c90111a..098030f4 100644 --- a/hooks/lib/git-ctx.sh +++ b/hooks/lib/git-ctx.sh @@ -674,42 +674,195 @@ yt_artifact_path() { return 0 } -# ---- standing instructions, one file per entry (issue #57) -------------------- +# ---- standing instructions, one file per entry (issues #57, #72, #73, #74) ------ # yt_standing -> the standing entries in force, newest first, one per # line: TAB TAB . Entries live in # /standing/-.md (docs/ux/coordinator-format.md); # the time in the name orders them (missing seconds count as 00). An entry that another entry names in `supersedes` -# is skipped. Prints nothing when the directory does not exist; STANDING.md -# is read by the caller as before. +# is skipped, so is an entry whose `until` has passed and an entry of +# `kind: end` (it only closes another one). Prints nothing when the directory +# does not exist; STANDING.md is read by the caller as before. yt_standing() { - local sd="$1/standing" names - [ -n "$1" ] && [ -d "$sd" ] || return 0 - names=$(ls "$sd" 2>/dev/null | grep -E '^[0-9]{8}T[0-9]{4}([0-9]{2})?Z-[A-Za-z0-9._-]+\.md$') - [ -n "$names" ] || return 0 - # shellcheck disable=SC2086 # the names match the pattern above: no spaces - ( cd "$sd" && awk -v q="'" ' + yt_standing_fields "$1" | awk -F '\t' '$9 == "active" { print $1 "\t" $2 "\t" ($3 == "-" ? "" : $3) }' + return 0 +} + +# yt_standing_default_ref -> the ref of the default branch: +# origin/HEAD, else origin/main, origin/master, main, master ("" when none). +yt_standing_default_ref() { + local r + r=$(git -C "$1" symbolic-ref -q refs/remotes/origin/HEAD 2>/dev/null) + for r in $r refs/remotes/origin/main refs/remotes/origin/master refs/heads/main refs/heads/master; do + git -C "$1" rev-parse -q --verify "$r" >/dev/null 2>&1 && { printf '%s' "$r"; return 0; } + done + 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 +# default branch. A remote branch no local branch tracks is never read. +yt_standing_pending() { + local ytd="$1" top rel base ref up r p b seen=" " + top=$(git -C "$ytd" rev-parse --show-toplevel 2>/dev/null) || return 0 + top=$(yt_canon "$top"); ytd=$(yt_canon "$ytd") + case "$ytd" in "$top"/*) rel="${ytd#"$top"/}" ;; *) return 0 ;; esac + base=$(yt_standing_default_ref "$top") + git -C "$top" for-each-ref --format='%(refname) %(upstream)' refs/heads/standing 2>/dev/null | while read -r ref up; do + for r in $ref $up; do + for p in $(git -C "$top" ls-tree --name-only "$r" -- "$rel/standing/" 2>/dev/null); do + b=${p##*/} + printf '%s\n' "$b" | grep -Eq '^[0-9]{8}T[0-9]{4}([0-9]{2})?Z-[A-Za-z0-9._-]+\.md$' || continue + [ ! -f "$ytd/standing/$b" ] || continue + [ -z "$base" ] || ! git -C "$top" cat-file -e "$base:$p" 2>/dev/null || continue + case "$seen" in *" $b "*) continue ;; esac + seen="$seen$b " + printf '%s\t%s\n' "${r#refs/*/}" "$p" + done + done + done + return 0 +} + +# yt_standing_fields [] [pending] -> every +# entry no other entry supersedes and not of kind end, newest first, TAB +# separated: +# name given scope until until-condition until-check check summary state source body +# (body: the whole body on one line) +# An empty value is "-". summary is the first sentence of the body (at most 160 +# characters). state is "expired" when `until` is at or before now, else +# "active". source is "-" for the working tree; with "pending" as third +# argument the entries of yt_standing_pending are read too (text only, through +# git show) with source "pending:". No command of an entry runs here +# (bin/ytstack-standing list runs until-check and check, never a pending one). +yt_standing_fields() { + local ytd="$1" sd="$1/standing" now="${2:-}" f b br p + [ -n "$ytd" ] || return 0 + [ -d "$sd" ] || [ "${3:-}" = pending ] || return 0 + [ -n "$now" ] || now=$(date -u +%Y%m%d%H%M%S) + { + for f in "$sd"/*.md; do + [ -f "$f" ] || continue + b=${f##*/} + printf '%s\n' "$b" | grep -Eq '^[0-9]{8}T[0-9]{4}([0-9]{2})?Z-[A-Za-z0-9._-]+\.md$' || continue + printf '@@ytstack-entry@@%s\t-\n' "$b"; cat "$f"; printf '\n' + done + if [ "${3:-}" = pending ]; then + yt_standing_pending "$ytd" | while IFS="$(printf '\t')" read -r br p; do + printf '@@ytstack-entry@@%s\tpending:%s\n' "${p##*/}" "$br" + git -C "$ytd" show "$br:$p" 2>/dev/null; printf '\n' + done + fi + } | awk -v q="'" ' function clean(v, f) { - gsub(/^[ \t]+|[ \t]+$/, "", v) + gsub(/\t/, " ", v); gsub(/^[ \t]+|[ \t]+$/, "", v) f = substr(v, 1, 1) if (length(v) >= 2 && (f == q || f == "\"") && substr(v, length(v)) == f) v = substr(v, 2, length(v) - 2) return v } + function d(v) { return v == "" ? "-" : v } + function val(key) { return clean(substr($0, length(key) + 2)) } # Sort key YYYYMMDDHHMMSS: a name without seconds counts as :00, so that # 20261114T1225Z sorts before 20261114T122530Z. - function out( k) { k = substr(fn, 1, 8) substr(fn, 10, 4) (substr(fn, 14, 1) == "Z" ? "00" : substr(fn, 14, 2)); print k "\t" fn "\t" g "\t" s "\t" u } - FNR == 1 { if (fn != "") out(); fn = FILENAME; infm = ($0 == "---"); g = ""; s = ""; u = ""; next } + function out( k) { + k = substr(fn, 1, 8) substr(fn, 10, 4) (substr(fn, 14, 1) == "Z" ? "00" : substr(fn, 14, 2)) + print k "\t" fn "\t" d(g) "\t" d(s) "\t" d(u) "\t" d(un) "\t" d(uc) "\t" d(uk) "\t" d(ck) "\t" d(kd) "\t" d(sm) "\t" src "\t" d(bd) + } + /^@@ytstack-entry@@/ { if (fn != "") out(); fn = substr($0, 18); src = fn; sub(/\t.*/, "", fn); sub(/^[^\t]*\t/, "", src); first = 1; infm = 0; g = s = u = un = uc = uk = ck = kd = sm = bd = ""; next } + first { first = 0; if ($0 == "---") { infm = 1; next } } infm && /^---[ \t]*$/ { infm = 0; next } - infm && /^given:/ { g = clean(substr($0, 7)) } - infm && /^scope:/ { s = clean(substr($0, 7)) } - infm && /^supersedes:/ { u = clean(substr($0, 12)); sub(/\.md$/, "", u) } + infm && /^given:/ { g = val("given") } + infm && /^scope:/ { s = val("scope") } + infm && /^supersedes:/ { u = val("supersedes"); sub(/\.md$/, "", u) } + infm && /^until:/ { un = val("until") } + infm && /^until-condition:/ { uc = val("until-condition") } + infm && /^until-check:/ { uk = val("until-check") } + infm && /^check:/ { ck = val("check") } + infm && /^kind:/ { kd = val("kind") } + !infm && NF && !/^---[ \t]*$/ { t = $0; gsub(/\t/, " ", t); bd = (bd == "" ? t : bd " " t) } + !infm && sm == "" && NF { + sm = $0; gsub(/\t/, " ", sm); sub(/^[ ]*([-*#>]+[ ]+)?/, "", sm) + if (match(sm, /[.!?]( |$)/)) sm = substr(sm, 1, RSTART) + if (length(sm) > 160) sm = substr(sm, 1, 157) "..." + } END { if (fn != "") out() } - ' $names ) | sort -r | awk -F '\t' ' - { n[NR] = $2; l[NR] = $2 "\t" $3 "\t" $4; if ($5 != "" && $5 != "none" && $5 != "None" && $5 != "-") sup[$5] = 1 } - END { for (i = 1; i <= NR; i++) { b = n[i]; sub(/\.md$/, "", b); if (!(b in sup)) print l[i] } } + ' | sort -r | awk -F '\t' -v now="$now" ' + function key(t) { gsub(/[^0-9]/, "", t); return length(t) == 12 ? t "00" : t } + { r[NR] = $0; n[NR] = $2; if ($5 != "-" && $5 != "none" && $5 != "None") sup[$5] = 1 } + END { + for (i = 1; i <= NR; i++) { + split(r[i], f, "\t"); b = n[i]; sub(/\.md$/, "", b) + if ((b in sup) || f[10] == "end") continue + st = (f[6] != "-" && length(key(f[6])) == 14 && key(f[6]) <= now) ? "expired" : "active" + print f[2] "\t" f[3] "\t" f[4] "\t" f[6] "\t" f[7] "\t" f[8] "\t" f[9] "\t" f[11] "\t" st "\t" f[12] "\t" f[13] + } + } + ' + return 0 +} + +# yt_standing_lines [] [full] -> the active entries +# that apply to as "- (): " (with "full": the +# whole body, for briefs, where a pending file is not on disk), newest first, pending +# ones (yt_standing_pending) included and marked " [pending:]"; past +# one line "- ... more: bin/ytstack-standing list". Roles +# (docs/ux/coordinator-format.md, "Scope and roles"): coordinator gets every +# entry; lane and reviewer get the entries whose scope names their role or no +# role at all. Role words in the scope: coordinator(s); lane(s), worker(s), +# implementer(s); reviewer(s), review(s). +yt_standing_lines() { + yt_standing_fields "$1" "" pending | awk -F '\t' -v role="${2:-coordinator}" -v max="${3:-0}" -v full="${4:-}" ' + function roles(s, t, r) { + t = " " tolower(s) " "; gsub(/[^a-z]+/, " ", t); r = "" + if (t ~ / (coordinator|coordinators)( |$)/) r = r "c" + if (t ~ / (lane|lanes|worker|workers|implementer|implementers)( |$)/) r = r "l" + if (t ~ / (reviewer|reviewers|review|reviews)( |$)/) r = r "r" + return r + } + $9 != "active" { next } + { rs = roles($3) } + role != "coordinator" && rs != "" && index(rs, substr(role, 1, 1)) == 0 { next } + { n++; if (max > 0 && n > max) { more++; next } + b = $1; sub(/\.md$/, "", b) + t = (full == "full" && $11 != "-") ? $11 : $8 + print "- " b " (" $3 "): " (t == "-" ? "(no text)" : t) ($10 ~ /^pending:/ ? " [" $10 "]" : "") } + END { if (more) print "- ... " more " more: bin/ytstack-standing list" } ' return 0 } +# yt_session_home -> the directory of per-session state that a hook and the +# Bash tool of the same session both find: ${XDG_STATE_HOME:-~/.local/state}/ +# ytstack/sessions. Not yt_state_base: Claude Code sets CLAUDE_PLUGIN_DATA for +# hooks only, never for commands of the Bash tool. Files under +# //: `coordinate` (written by the coordinate preamble: the +# YT_DIR on line 1, YT_REPO_KEY on line 2), `prompts` (hooks/standing-prompt: one epoch per human +# prompt), `standing-flags` (epoch TAB YYYYMMDDHHMM TAB ISO TAB excerpt per +# prompt that looks like a standing instruction), `standing-stop` (hooks/stop: +# the epoch up to which flags were handled). +# +# yt_latest_handoff -> the target of the newest `latest-handoff` link of this +# worktree (call yt_git_ctx first), across every base a hook may have written +# it to: CLAUDE_PLUGIN_DATA and PLUGIN_DATA when set, each +# ${CLAUDE_CONFIG_DIR:-~/.claude}/plugins/data/ytstack* (the hooks' +# CLAUDE_PLUGIN_DATA, which the Bash tool does not see) and the XDG base. "" +# when there is none. For skill preambles; hooks use yt_state_base. +yt_latest_handoff() { + local b l tgt t best="" bt=-1 + for b in "${CLAUDE_PLUGIN_DATA:-}" "${PLUGIN_DATA:-}" "${CLAUDE_CONFIG_DIR:-$HOME/.claude}"/plugins/data/ytstack* "${XDG_STATE_HOME:-$HOME/.local/state}/ytstack"; do + [ -n "$b" ] && [ -d "$b" ] || continue + l="$b/repos/${YT_REPO_KEY:-none}/worktrees/${YT_WT_KEY:-none}/latest-handoff" + [ -L "$l" ] && [ -f "$l" ] || continue + tgt=$(readlink "$l"); t=$(yt_mtime "$tgt"); case "$t" in ''|*[!0-9]*) t=0 ;; esac + if [ "$t" -gt "$bt" ]; then bt=$t; best=$tgt; fi + done + printf '%s' "$best" +} + +yt_session_home() { + printf '%s' "${XDG_STATE_HOME:-$HOME/.local/state}/ytstack/sessions" +} + # ---- factory tools that are off (M031-S03, issues #54 and #61) ----------------- # yt_mtime -> seconds since epoch of the last change ("" when unreadable). # GNU and BusyBox take -c; BSD stat rejects -c and takes -f. diff --git a/hooks/pre-tool-use-agent b/hooks/pre-tool-use-agent new file mode 100644 index 00000000..a59fa8d9 --- /dev/null +++ b/hooks/pre-tool-use-agent @@ -0,0 +1,81 @@ +#!/usr/bin/env bash +# ytstack PreToolUse hook on Agent and SendMessage (issue #76, part of #75): +# 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). +# +# The marker of a rendered brief is its first line "# Brief: ()" +# (skills/spawn-milestone-team/brief-template.md); it counts anywhere in the +# prompt, at the start of a line. SendMessage is checked only when its text is +# longer than 400 characters: a short follow-up ("go on", an answer) is no +# dispatch. An Agent call of a lookup type (Explore, Plan, claude-code-guide, +# 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. +# +# Files only. Fail open: any problem ends silent with exit 0. + +set -uo pipefail +trap '' PIPE + +. "$(cd "$(dirname "$0")" && pwd)/lib/git-ctx.sh" + +yt_read_stdin +SID="${YT_SESSION_ID:-}" +case "$SID" in ''|.|..|*[!A-Za-z0-9._-]*) exit 0 ;; esac +SD="$(yt_session_home)/$SID" +[ -f "$SD/coordinate" ] || exit 0 +JQ=$(yt_jq); PY=$(yt_python) +# field : tool_name, text (prompt, message or content of tool_input) or +# type (its subagent_type), 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' ;; + esac + elif [ -n "$PY" ]; then + printf '%s' "$YT_STDIN" | "$PY" -I -c ' +import json, sys +try: + d = json.load(sys.stdin) +except Exception: + d = {} +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", "") +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) +BRIEF=no +case "$TEXT" in "# Brief: "*|*" +# Brief: "*) BRIEF=yes ;; esac +# A lookup agent (read-only search or planning types) is no lane: neither a +# dispatch for the LANES.md check nor a missing brief. +LOOKUP=no +case "$TYPE" in Explore|Plan|claude-code-guide|statusline-setup|*[Ss]earch*|*[Ee]xplore*) LOOKUP=yes ;; esac +case "$TOOL" in + Agent|Task) + [ "$BRIEF" = yes ] || [ "$LOOKUP" = no ] || exit 0 + printf '%s\n' "$(date +%s)" >> "$SD/dispatches" 2>/dev/null ;; + 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 +fi +exit 0 diff --git a/hooks/session-start b/hooks/session-start index d1ae3ea3..6a6d1f65 100644 --- a/hooks/session-start +++ b/hooks/session-start @@ -196,6 +196,36 @@ if [ -L "$LATEST_LINK" ] && [ -f "$LATEST_LINK" ]; then }Latest automatic handoff: $A_TARGET${A_TS:+ ($A_TS)}" fi +# Standing instructions (issue #74): the active entries of standing/, files +# only (no until-check or check runs here; a passed `until` is applied), for +# the session's role: coordinator when the coordinate preamble left its +# session marker, else lane. At most 6 lines; the rest is a pointer. Pending +# entries count too, also before the checkout has a standing/ directory. +STANDING_LINES=""; STANDING_N=0 +_ROLE=lane +case "${YT_SESSION_ID:-}" in ''|.|..|*[!A-Za-z0-9._-]*) ;; *) [ ! -f "$(yt_session_home)/$YT_SESSION_ID/coordinate" ] || _ROLE=coordinator ;; esac +_ALL=$(yt_standing_lines "$YT_DIR" "$_ROLE") +_SL="" +if [ -n "$_ALL" ]; then + _SL=$(yt_standing_lines "$YT_DIR" "$_ROLE" 6 | cut -c1-150) + STANDING_N=$(printf '%s\n' "$_ALL" | grep -c .) + _SH="Standing instructions in force (role: $_ROLE; they override defaults; full text in standing/, of a pending one in bin/ytstack-standing list):" + STANDING_LINES="$_SH +$_SL" +fi +[ ! -f "$YT_DIR/STANDING.md" ] || STANDING_LINES="${STANDING_LINES:+$STANDING_LINES +}Also read $YT_DIR/STANDING.md." + +# Coordinate mode (issue #76): the operating checklist, read from its one +# place (docs/ux/coordinator-format.md, between the operating-checklist +# markers). A coordinator writes no product code, so the minimal-code line +# gives way to it. +CHECKLIST_LINES="" +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 + # Technical spec (M022): name the entry point when the project has one. SPEC_HINT="" [ ! -f "$YT_DIR/spec/SPEC.md" ] || SPEC_HINT=" spec/SPEC.md for what applies now," @@ -224,6 +254,16 @@ Recent tasks: $RECENT_SUMMARIES" ctx="$ctx Milestones in progress: $IN_PROGRESS (more than one -- check the STATE pointer; run ytstack:reassess-roadmap to close or drop the stale one)" + fi + if [ -n "$CHECKLIST_LINES" ]; then + ctx="$ctx + +$CHECKLIST_LINES" + fi + if [ -n "$STANDING_LINES" ]; then + ctx="$ctx + +$STANDING_LINES" fi if [ -n "$HANDOFF_LINES" ]; then ctx="$ctx @@ -252,9 +292,10 @@ $FACTORY_LINES" fi ctx="$ctx -The files in $YT_DIR are the source of truth for this project's state. Read STATE.md for the full dashboard,${SPEC_HINT} DECISIONS.md for locked architectural choices, KNOWLEDGE.md for patterns and gotchas, ROADMAP.md for the task list. Do not rely on prior-conversation context for these facts." +$CLOSING_LINE" printf '%s' "$ctx" } +CLOSING_LINE="The files in $YT_DIR are the source of truth for this project's state. Read STATE.md for the full dashboard,${SPEC_HINT} DECISIONS.md for locked architectural choices, KNOWLEDGE.md for patterns and gotchas, ROADMAP.md for the task list. Do not rely on prior-conversation context for these facts." STATE_CONTEXT=$(build_state_context "$NEXT_ACTION") FULL_CONTEXT="$DIRECTIVE @@ -269,6 +310,19 @@ $STATE_CONTEXT" # 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. _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)" + STATE_CONTEXT=$(build_state_context "$NEXT_ACTION") + FULL_CONTEXT="$DIRECTIVE + +--- + +$STATE_CONTEXT" +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 @@ -277,6 +331,9 @@ if [ $(( ${#FULL_CONTEXT} - _HOST_LEN )) -gt 9500 ]; then _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 @@ -295,6 +352,51 @@ $STATE_CONTEXT" --- +$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 diff --git a/hooks/standing-prompt b/hooks/standing-prompt new file mode 100644 index 00000000..c899b58e --- /dev/null +++ b/hooks/standing-prompt @@ -0,0 +1,107 @@ +#!/usr/bin/env bash +# ytstack UserPromptSubmit hook: standing instructions in a coordinator session +# (issue #72). Active only in coordinate mode: the coordinate preamble writes +# the marker //coordinate (yt_session_home in +# hooks/lib/git-ctx.sh; DECISIONS 2026-11-15 "coordinate mode is a session +# marker"). Without it the hook ends at once, without reading git. +# +# In coordinate mode, per human prompt: +# 1. appends the epoch to /prompts (the coordinate preamble +# counts the prompts since the newest standing entry); +# 2. when the prompt reads like a standing instruction (instruction phrases: +# from now on, going forward, until further notice, don't touch, +# prioritise, an imperative "always/never " at a clause start; +# German: ab jetzt, ab sofort, von nun an, bis auf weiteres, solange ... +# nicht, grundsaetzlich, immer wenn, nie wieder, denk dran, merk dir, +# priorisiere, fass ... nicht an; a prompt that is only a question is not), +# appends it to /standing-flags for hooks/stop and injects +# one line: record it under .ytstack/standing/ before the next dispatch. +# A prompt that starts with "<" (a task notification, a system message) is no +# human prompt and is skipped; a task notification (a worker's report) is +# appended to /reports for hooks/stop. +# +# Files and grep only; no command of a standing entry runs here. Fail open: +# any problem ends silent with exit 0. Output: the UserPromptSubmit +# additionalContext JSON; YTSTACK_HOOK_FORMAT=plain prints the text. + +set -uo pipefail +trap '' PIPE + +. "$(cd "$(dirname "$0")" && pwd)/lib/git-ctx.sh" + +yt_read_stdin +SID="${YT_SESSION_ID:-}" +case "$SID" in ''|.|..|*[!A-Za-z0-9._-]*) exit 0 ;; esac +SD="$(yt_session_home)/$SID" +[ -f "$SD/coordinate" ] || exit 0 + +JQ=$(yt_jq) +if [ -n "$JQ" ]; then + PROMPT=$(printf '%s' "$YT_STDIN" | "$JQ" -r '.prompt | if type == "string" then . elif type == "array" then map(.text? // "") | join(" ") else "" end' 2>/dev/null) || exit 0 +elif [ -n "$(yt_python)" ]; then + PROMPT=$(printf '%s' "$YT_STDIN" | "$(yt_python)" -I -c ' +import json, sys +try: + p = json.load(sys.stdin).get("prompt", "") +except Exception: + p = "" +if isinstance(p, list): + p = " ".join(str(i.get("text", "")) for i in p if isinstance(i, dict)) +print(p if isinstance(p, str) else "") +' 2>/dev/null) || exit 0 +else + exit 0 +fi +PROMPT="${PROMPT:0:4000}" +# A worker's report arrives as a task notification: a lane event for the +# LANES.md check of hooks/stop (issue #76), not a human prompt. +case "${PROMPT#"${PROMPT%%[![:space:]]*}"}" in + '> "$SD/reports" 2>/dev/null; exit 0 ;; + ''|'<'*) exit 0 ;; +esac + +NOW=$(date +%s) +printf '%s\n' "$NOW" >> "$SD/prompts" 2>/dev/null || exit 0 + +# Instruction phrases, not single words: "bis", "nie", "immer", "while", +# "until" and "never" alone occur in ordinary questions ("bis wann?", "never +# mind", "ist das immer noch rot?"). "always"/"never" count only as an +# imperative at the start of a clause ("Never merge on Fridays."). A prompt +# that is one question and nothing else is never flagged. +# Word boundaries without \b (BSD and BusyBox grep differ): a non-letter or the +# line edge on both sides. LC_ALL=C keeps the umlaut bytes out of [:alnum:]. +B='(^|[^[:alnum:]])' +E='([^[:alnum:]]|$)' +# Temporary instructions (#73): a hold or prohibition with until/bis and a time +# or a condition ("hold merges until 12:37", "bis 12:37 keine Merges", "no +# deploys while the load test runs"), and until/solange opening a clause. +EN="from now on|going forward|from here on|until further notice|don'?t touch|do not touch|hands off|prioriti[sz]e|leave [^.!?]{1,60} alone|remember to|keep in mind|no more [a-z]+ until|(hold|pause|freeze|block|stop|no|don'?t|do not|never)[^.!?]{0,40} (until|till|while) [a-z0-9]+" +DE="ab jetzt|ab sofort|von nun an|von jetzt an|ab heute|bis auf weiteres|solange [^.!?]{1,60} (nicht|keine?)|grunds(ae|ä)tzlich|immer wenn|nie wieder|nie mehr|niemals|denk dran|denk daran|merk dir|priorisier[a-z]*|fass [^.!?]{1,60} nicht an|nicht anfassen|k(ue|ü)nftig|in zukunft|bis [0-9][0-9:.]*( uhr)?[^.!?]{0,30} (keine?|nicht|nichts)|(keine?|nicht|nichts)[^.!?]{0,40} (bis|solange|w(ae|ä)hrend) [a-z0-9]+" +# At the start of the prompt or of a clause (after . ! ? ; : or a dash): +# always/never + a verb (not "never mind"), until + a condition, solange + a clause. +IMP='(^|[.!?;:]|--| - )[[:space:]]*(please[[:space:]]+)?((always|never)[[:space:]]+[a-z]+|until[[:space:]]+[a-z0-9]+|solange[[:space:]]+[a-z]+)' +LOW=$(printf '%s' "$PROMPT" | tr '\n\r' ' ' | LC_ALL=C tr '[:upper:]' '[:lower:]') +TRIM=$(printf '%s' "$LOW" | sed 's/[[:space:]]*$//') +case "$TRIM" in + *'?') case "${TRIM%?}" in *[.!?]*) ;; *) exit 0 ;; esac ;; +esac +HIT=$(printf '%s' "$LOW" | LC_ALL=C grep -Eo "$B($EN|$DE)$E" 2>/dev/null | head -1 | LC_ALL=C sed 's/^[^[:alnum:]]*//; s/[^[:alnum:]]*$//') +if [ -z "$HIT" ]; then + HIT=$(printf '%s' "$LOW" | LC_ALL=C grep -Eo "$IMP" 2>/dev/null | grep -v 'never mind' | head -1 | LC_ALL=C sed 's/^[^[:alnum:]]*//') +fi +[ -n "$HIT" ] || exit 0 + +EXCERPT=$(printf '%s' "$PROMPT" | tr '\n\r\t' ' ' | cut -c1-100) +printf '%s\t%s\t%s\t%s\n' "$NOW" "$(date -u +%Y%m%d%H%M)" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$EXCERPT" >> "$SD/standing-flags" 2>/dev/null || exit 0 + +ROOT="${CLAUDE_PLUGIN_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}" +TEXT="ytstack: this prompt reads like a standing instruction (\"$HIT\"). If it holds beyond the task at hand, record it before the next dispatch, in your own words: bash \"$ROOT/bin/ytstack-standing\" add \"\" --scope \"\" (add --until or --until-condition \"\" when it ends). Agent memory is no substitute: a successor and other hosts read only .ytstack/standing/. If it is not one, go on." + +if [ "${YTSTACK_HOOK_FORMAT:-json}" = plain ]; then + printf '%s\n' "$TEXT" +elif [ -n "$JQ" ]; then + printf '%s' "$TEXT" | "$JQ" -Rs '{hookSpecificOutput: {hookEventName: "UserPromptSubmit", additionalContext: .}}' 2>/dev/null +elif [ -n "$(yt_python)" ]; then + printf '%s' "$TEXT" | "$(yt_python)" -I -c 'import sys, json; print(json.dumps({"hookSpecificOutput": {"hookEventName": "UserPromptSubmit", "additionalContext": sys.stdin.read()}}))' 2>/dev/null +fi +exit 0 diff --git a/hooks/stop b/hooks/stop index d0186fad..89a7d260 100644 --- a/hooks/stop +++ b/hooks/stop @@ -1,10 +1,26 @@ #!/usr/bin/env bash -# ytstack Stop hook (advisory, M019) +# ytstack Stop hook (M019, issue #72) # -# Fires when the main agent is about to stop. If STATE.md still points at an -# active task whose SUMMARY is missing or a draft stub, surface a one-line -# reminder to the user via `systemMessage`. Never blocks (exit 0, no -# `decision: block`): the user may well be stopping on purpose. +# Fires when the main agent is about to stop. +# +# 1. Task reminder (advisory): if STATE.md still points at an active task +# whose SUMMARY is missing or a draft stub, surface a one-line reminder +# via `systemMessage`. Never blocks for this: the user may well be +# stopping on purpose. +# 2. Standing instructions (coordinate mode only, the session marker of +# hooks/standing-prompt): when hooks/standing-prompt flagged human +# prompts that were not handled yet and no standing entry was written +# since the first of them, block the stop ONCE with the list +# (`decision: block`). An entry counts when its name time is in or after +# the minute of that prompt and it is in the working tree's standing/, +# or any ref of the repository (local branches, and the remote-tracking +# branch of a pushed standing PR) added it after that prompt. Local git +# only, no network. Afterwards the flags count as handled +# (/standing-stop), so the same prompts never block twice. +# 3. Coordinate lints (coordinate mode, issue #76): LANES.md behind the +# 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. # # Resolution: payload `cwd` via hooks/lib/git-ctx.sh (never CLAUDE_PROJECT_DIR). # Respects `stop_hook_active` (set when a previous Stop hook already continued @@ -16,38 +32,157 @@ trap '' PIPE . "$(cd "$(dirname "$0")" && pwd)/lib/git-ctx.sh" yt_read_stdin +JQ=$(yt_jq) # stop_hook_active: do nothing when we are inside a hook-continued turn -if [ -n "${YT_STDIN:-}" ]; then - JQ=$(yt_jq) - if [ -n "$JQ" ] && [ "$(printf '%s' "$YT_STDIN" | "$JQ" -r '.stop_hook_active // false' 2>/dev/null)" = true ]; then - exit 0 - fi +if [ -n "${YT_STDIN:-}" ] && [ -n "$JQ" ] && [ "$(printf '%s' "$YT_STDIN" | "$JQ" -r '.stop_hook_active // false' 2>/dev/null)" = true ]; then + exit 0 fi -yt_git_ctx "${YT_CWD:-$PWD}" -YT_DIR=$(yt_resolve_yt_dir) -[ -z "$YT_DIR" ] && exit 0 -STATE_FILE="$YT_DIR/STATE.md" -[ -f "$STATE_FILE" ] || exit 0 +# ---- 2. standing instructions (coordinate mode) ---------------------------------- +standing_block() { + local sid="${YT_SESSION_ID:-}" sd ytd done_at first_m first_iso last_e n f list + case "$sid" in ''|.|..|*[!A-Za-z0-9._-]*) return 0 ;; esac + sd="$(yt_session_home)/$sid" + [ -f "$sd/coordinate" ] && [ -s "$sd/standing-flags" ] || return 0 + ytd=$(sed -n 1p "$sd/coordinate" 2>/dev/null) + [ -n "$ytd" ] && [ -d "$ytd" ] || return 0 + done_at=$(sed -n 1p "$sd/standing-stop" 2>/dev/null); case "$done_at" in ''|*[!0-9]*) done_at=0 ;; esac + list=$(awk -F '\t' -v d="$done_at" '$1 + 0 > d + 0' "$sd/standing-flags" 2>/dev/null) + [ -n "$list" ] || return 0 + first_m=$(printf '%s\n' "$list" | awk -F '\t' 'NR == 1 { print $2 }') + first_iso=$(printf '%s\n' "$list" | awk -F '\t' 'NR == 1 { print $3 }') + last_e=$(printf '%s\n' "$list" | awk -F '\t' 'END { print $1 }') + printf '%s\n' "$last_e" > "$sd/standing-stop" 2>/dev/null || return 0 + + # An entry since the first flagged prompt? Name time YYYYMMDDHHMM >= its minute. + newer() { awk -v m="$first_m" '{ b = $0; sub(/.*\//, "", b); k = substr(b, 1, 8) substr(b, 10, 4) } k ~ /^[0-9]+$/ && k >= m { f = 1 } END { exit !f }'; } + for f in "$ytd"/standing/*.md; do [ -f "$f" ] && printf '%s\n' "$f"; done | newer && return 0 + if [ "$(git -C "$ytd" rev-parse --is-inside-work-tree 2>/dev/null)" = true ]; then + git -C "$ytd" log --all --since="$first_iso" --diff-filter=A --name-only --format= -- standing/ 2>/dev/null | newer && return 0 + fi + n=$(printf '%s\n' "$list" | grep -c .) + BLOCK_REASON="ytstack: $n human prompt(s) in this coordinator session read like standing instructions, and no standing entry was written since $first_iso: +$(printf '%s\n' "$list" | awk -F '\t' '{ print "- " $3 ": \"" $4 "\"" }') +Record each one that holds beyond the task at hand, in your own words: bash \"${CLAUDE_PLUGIN_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}/bin/ytstack-standing\" add \"\" --scope \"\" (ytstack:coordinate Step 9). If none of them is one, say so in one line and stop. This check blocks once for these prompts." +} +BLOCK_REASON="" +standing_block -get_field() { sed -n "s/^$1: *//p" "$STATE_FILE" 2>/dev/null | head -1; } -M=$(get_field current_milestone); S=$(get_field active_slice); T=$(get_field active_task) -case "$T" in ""|none|all) exit 0 ;; esac -case "$S" in ""|none|all) exit 0 ;; esac -case "$M" in ""|none) exit 0 ;; esac +# ---- 3. coordinate lints, escalating (issue #76) ---------------------------------- +# lanes: LANES.md older than the newest lane event minus 5 minutes (a claim comes +# right before its dispatch), or missing although lanes were dispatched; the +# events are /dispatches (hooks/pre-tool-use-agent) and reports +# (hooks/standing-prompt). state: the STATE pointer is behind the newest +# milestone on disk (yt_state_lint W2). Each is said once per session as a +# systemMessage. A finding present in YT_LINT_STREAK_N sessions in a row (default +# 3; counter /repos//coordinate-lints, kind TAB count TAB +# last session TAB counted TAB the counted session ids) blocks the stop once in +# that session; overlapping sessions count once each. A session +# counts once when the finding was there at any of its stops, also when its +# first stop came before its first dispatch. +LINT_MSG="" +coordinate_lints() { + local sid="${YT_SESSION_ID:-}" sd ytd key last lm kind present n s seen ids streak need tmp text + case "$sid" in ''|.|..|*[!A-Za-z0-9._-]*) return 0 ;; esac + sd="$(yt_session_home)/$sid" + [ -f "$sd/coordinate" ] || return 0 + ytd=$(sed -n 1p "$sd/coordinate" 2>/dev/null) + [ -n "$ytd" ] && [ -d "$ytd" ] || return 0 + need="${YT_LINT_STREAK_N:-3}"; case "$need" in ''|*[!0-9]*) need=3 ;; esac + # The repository key from the marker's second line (the coordinate preamble's + # YT_REPO_KEY): in user scope the .ytstack lies outside the repository. + key=$(sed -n 2p "$sd/coordinate" 2>/dev/null); case "$key" in *[!A-Za-z0-9]*) key="" ;; esac + if [ -z "$key" ]; then yt_git_ctx "$(dirname "$ytd")"; key="${YT_REPO_KEY:-unknown}"; fi + streak="$(yt_state_base)/repos/$key/coordinate-lints" + mkdir -p "$(dirname "$streak")" 2>/dev/null || return 0 + last=$(cat "$sd/dispatches" "$sd/reports" 2>/dev/null | awk '$1 + 0 > m { m = $1 + 0 } END { print m + 0 }') + yt_state_lint "$ytd" >/dev/null + for kind in lanes state; do + text="" + if [ "$kind" = lanes ] && [ "${last:-0}" -gt 0 ]; then + lm=$(yt_mtime "$ytd/LANES.md"); case "$lm" in ''|*[!0-9]*) lm=0 ;; esac + if [ "$lm" -eq 0 ]; then + text="lanes were dispatched in this session, but $ytd/LANES.md does not exist: claim every lane with ytstack-frontier claim before its dispatch." + elif [ $((lm + 300)) -lt "$last" ]; then + text="LANES.md last changed $(( (last - lm) / 60 )) min before the newest dispatch or report of this session: ytstack-frontier claim before a dispatch, ytstack-frontier set after a report." + fi + elif [ "$kind" = state ]; then + text=$(printf '%s\n' "${YT_STATE_WARNINGS:-}" | grep 'is behind the newest milestone' | head -1) + [ -z "$text" ] || text="STATE lint: $text. Set current_milestone in $ytd/STATE.md." + fi + present=no; [ -z "$text" ] || present=yes + # Per kind: n sessions in a row ending with session s; seen = s counted. + # A session counts once when the finding was there at any of its stops; + # a session that ended without it breaks the row (seen at the next one). + # ids: the sessions counted in the current row, so that overlapping + # sessions (A, B, A) are counted once each. + s=$(awk -F '\t' -v k="$kind" '$1 == k { print $3 }' "$streak" 2>/dev/null) + seen=$(awk -F '\t' -v k="$kind" '$1 == k { print $4 }' "$streak" 2>/dev/null) + ids=$(awk -F '\t' -v k="$kind" '$1 == k { print $5 }' "$streak" 2>/dev/null); [ "$ids" != - ] || ids="" + if [ "$s" != "$sid" ]; then + [ "$seen" = 1 ] || ids="" + case ",$ids," in *",$sid,"*) seen=1 ;; *) seen=0 ;; esac + fi + if [ "$present" = yes ]; then + case ",$ids," in *",$sid,"*) ;; *) ids="${ids:+$ids,}$sid" ;; esac + seen=1 + fi + n=$(printf '%s' "$ids" | tr ',' '\n' | grep -c .) + [ "$present" = yes ] || rm -f "$sd/lint-warned-$kind" 2>/dev/null + tmp="$streak.$$" + { awk -F '\t' -v k="$kind" '$1 != k' "$streak" 2>/dev/null; printf '%s\t%s\t%s\t%s\t%s\n' "$kind" "$n" "$sid" "$seen" "${ids:--}"; } > "$tmp" 2>/dev/null && mv -f "$tmp" "$streak" 2>/dev/null + [ "$present" = yes ] || continue + if [ "$n" -ge "$need" ] && [ ! -e "$sd/lint-blocked-$kind" ]; then + : > "$sd/lint-blocked-$kind" 2>/dev/null + BLOCK_REASON="${BLOCK_REASON:+$BLOCK_REASON -SUMMARY=$(yt_artifact_path "$YT_DIR" "$M-$S-$T-SUMMARY.md") +}ytstack: this coordinator warning came in $n sessions in a row and now holds the stop once: $text Fix it now, then stop." + elif [ ! -e "$sd/lint-warned-$kind" ]; then + : > "$sd/lint-warned-$kind" 2>/dev/null + LINT_MSG="${LINT_MSG:+$LINT_MSG }ytstack: $text" + fi + done +} +coordinate_lints + +# ---- 1. task reminder -------------------------------------------------------------- +task_msg() { + local ytd state m s t summary + yt_git_ctx "${YT_CWD:-$PWD}" + ytd=$(yt_resolve_yt_dir) + [ -n "$ytd" ] && [ -f "$ytd/STATE.md" ] || return 0 + state="$ytd/STATE.md" + get_field() { sed -n "s/^$1: *//p" "$state" 2>/dev/null | head -1; } + m=$(get_field current_milestone); s=$(get_field active_slice); t=$(get_field active_task) + case "$t" in ""|none|all) return 0 ;; esac + case "$s" in ""|none|all) return 0 ;; esac + case "$m" in ""|none) return 0 ;; esac + # 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 + MSG="ytstack: $m-$s-$t is still the active task and has no summary. If the work is done, run /ytstack:summarize-task; if you are pausing, /ytstack:handoff-session keeps the thread." + elif [ "$(sed -n 's/^closed: *//p' "$summary" | head -1)" = draft ]; then + MSG="ytstack: $m-$s-$t has only a draft summary stub. Run /ytstack:summarize-task to close it, or /ytstack:handoff-session if you are pausing." + fi +} MSG="" -if [ ! -f "$SUMMARY" ]; then - MSG="ytstack: $M-$S-$T is still the active task and has no summary. If the work is done, run /ytstack:summarize-task; if you are pausing, /ytstack:handoff-session keeps the thread." -elif [ "$(sed -n 's/^closed: *//p' "$SUMMARY" | head -1)" = draft ]; then - MSG="ytstack: $M-$S-$T has only a draft summary stub. Run /ytstack:summarize-task to close it, or /ytstack:handoff-session if you are pausing." -fi -[ -z "$MSG" ] && exit 0 +task_msg +[ -z "$LINT_MSG" ] || MSG="${MSG:+$MSG }$LINT_MSG" -JQ=$(yt_jq) +[ -n "$MSG$BLOCK_REASON" ] || exit 0 if [ -n "$JQ" ]; then - printf '%s' "$MSG" | "$JQ" -Rs '{systemMessage: .}' + "$JQ" -n --arg m "$MSG" --arg r "$BLOCK_REASON" \ + '(if $r != "" then {decision: "block", reason: $r} else {} end) + (if $m != "" then {systemMessage: $m} else {} end)' +elif [ -n "$(yt_python)" ]; then + "$(yt_python)" -I -c ' +import json, sys +m, r = sys.argv[1], sys.argv[2] +o = {} +if r: + o.update(decision="block", reason=r) +if m: + o["systemMessage"] = m +print(json.dumps(o))' "$MSG" "$BLOCK_REASON" else printf '{"systemMessage":"%s"}\n' "$(printf '%s' "$MSG" | sed 's/"/\\"/g')" fi diff --git a/skills/coordinate/SKILL.md b/skills/coordinate/SKILL.md index 7ee12f60..63aee4bf 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.1 + version: 0.6.2 allowed-tools: - Bash - Read @@ -41,7 +41,7 @@ You MUST create a TodoWrite task for each of these items. Items 4 to 13 are one 6. **Finish reported lanes** -- `ytstack:finish-lane`, one lane at a time per pull request 7. **Run the factory tools** -- the route before every merge (also your own), the PR watch or `ytstack-watch`, `ytstack-watch release` after every merge to production, signals, review lessons, the lesson of every incident (a red `main`, a slip); each skipped only by its condition 8. **Queue and ask questions** -- look up, write the file, ask one, late -9. **Record standing instructions** -- one file per instruction in `standing/` when they are given +9. **Record standing instructions** -- `ytstack-standing add` when they are given, before the next dispatch; never only in agent memory 10. **Stop loops that do not converge** -- a diagnosis to the human instead of another dispatch 11. **Report status** -- only on a change the human acts on, or at a boundary he set 12. **Rotate** -- after one compaction or with a large context, in one step while lanes run: files current, handoff with the PR watch session, the watches and the workers' addresses, fresh session; this one stays open only as a relay @@ -138,10 +138,29 @@ echo "LESSONS_BEGIN" [ -z "$_LS" ] || printf '%s\n' "$_LS" | head -30 echo "LESSONS_END" echo "STANDING: $([ -n "$_YT_DIR" ] && [ -f "$_YT_DIR/STANDING.md" ] && echo yes || echo no)" -# One file per standing instruction (.ytstack/standing/): the ones in force, newest first. +# The operating checklist (issue #76): one place, docs/ux/coordinator-format.md. +echo "OPERATING_CHECKLIST_BEGIN" +awk '// { f = 0 } f { print } // { f = 1 }' "${CLAUDE_SKILL_DIR}/../../docs/ux/coordinator-format.md" 2>/dev/null \ + | grep . || echo "read the Operating checklist in docs/ux/coordinator-format.md of the plugin" +echo "OPERATING_CHECKLIST_END" +# Coordinate mode (issue #72): the session marker hooks/standing-prompt, hooks/pre-tool-use-agent and hooks/stop act on. +_SID="${CLAUDE_CODE_SESSION_ID:-}" +case "$_SID" in + ''|*[!A-Za-z0-9._-]*) echo "COORDINATE_MARKER: none (no session id on this host: the standing hooks stay off)" ;; + *) if [ -n "$_YT_DIR" ] && command -v yt_session_home >/dev/null 2>&1 && mkdir -p "$(yt_session_home)/$_SID" 2>/dev/null \ + && printf '%s\n%s\n' "$_YT_DIR" "$_PROJECT_KEY" > "$(yt_session_home)/$_SID/coordinate" 2>/dev/null; then + echo "COORDINATE_MARKER: written" + else + echo "COORDINATE_MARKER: not written (the standing hooks stay off)" + fi ;; +esac +# One file per standing instruction (.ytstack/standing/): the newest entry's age and the +# human prompts since, the active ones, then ended, conditions to check and failed checks. echo "STANDING_ENTRIES_BEGIN" -if [ -n "$_YT_DIR" ] && [ -d "$_YT_DIR/standing" ]; then - command -v yt_standing >/dev/null 2>&1 && yt_standing "$_YT_DIR" || echo "list $_YT_DIR/standing/ yourself: newest first, skip superseded" +if [ -n "$_YT_DIR" ] && [ -f "$_BIN/ytstack-standing" ]; then + bash "$_BIN/ytstack-standing" -C "$_PROJECT_DIR" list 2>&1 | head -80 +elif [ -n "$_YT_DIR" ] && [ -d "$_YT_DIR/standing" ]; then + command -v yt_standing >/dev/null 2>&1 && yt_standing "$_YT_DIR" || echo "list $_YT_DIR/standing/ yourself: newest first, skip superseded and ended" else echo "no standing directory" fi @@ -185,11 +204,10 @@ echo "QUESTIONS_END" _MANUAL_TS=none [ -f "$_YT_DIR/HANDOFF.md" ] && _MANUAL_TS=$(sed -n 's/^timestamp: *//p' "$_YT_DIR/HANDOFF.md" | head -1) _AUTO=none; _AUTO_TS=none -if command -v yt_state_base >/dev/null 2>&1 && [ -n "${YT_REPO_KEY:-}" ]; then - _LINK="$(yt_state_base)/repos/$YT_REPO_KEY/worktrees/${YT_WT_KEY:-}/latest-handoff" - if [ -L "$_LINK" ] && [ -f "$_LINK" ]; then - _AUTO=$(readlink "$_LINK"); _AUTO_TS=$(sed -n 's/^timestamp: *//p' "$_AUTO" 2>/dev/null | head -1) - fi +# yt_latest_handoff also looks where the hook wrote it (CLAUDE_PLUGIN_DATA is not set in this shell). +if command -v yt_latest_handoff >/dev/null 2>&1 && [ -n "${YT_REPO_KEY:-}" ]; then + _AUTO=$(yt_latest_handoff) + if [ -n "$_AUTO" ]; then _AUTO_TS=$(sed -n 's/^timestamp: *//p' "$_AUTO" 2>/dev/null | head -1); else _AUTO=none; fi fi echo "HANDOFF_MANUAL: ${_MANUAL_TS:-none}" echo "HANDOFF_AUTO: ${_AUTO_TS:-none} ($_AUTO)" @@ -201,7 +219,7 @@ The scripts live in the directory the preamble prints as `YT_BIN=` (also in **Step 2 -- HARD-GATE.** `HAS_YTSTACK: no`: stop, "run `ytstack:init-project` or `ytstack:adopt-brownfield` first". `SLICE_PLANS: 0` and `no lanes`: stop, "nothing to coordinate; run `ytstack:slice-milestone`". One milestone with a handful of independent slices and no lane yet: `ytstack:spawn-milestone-team` does that with less ceremony; say so and stop unless the user asked for coordinator mode. -**Step 3 -- Start from files.** At the first start, after every compaction and after every resume, before anything else: read the standing instructions in full (every file listed between `STANDING_ENTRIES_BEGIN` and `STANDING_ENTRIES_END`, newest first, and `STANDING.md` when `STANDING: yes`; an entry that another entry supersedes is not listed and no longer holds), the rows between `LANES_BEGIN` and `LANES_END`, the frontier, every file listed between `QUESTIONS_BEGIN` and `QUESTIONS_END`, and the newer of the two handoffs. Do not rebuild who holds what from a conversation summary. Where a summary and a file disagree, the file is the claim, and Step 4 checks it against the host before anybody acts on it. A `running` row whose worker no longer exists in this session is not dispatched again blindly: read its branch (`git log ..`), then `ytstack-frontier release ` and claim it for a new worker that continues on that branch, or write a question. +**Step 3 -- Start from files.** At the first start, after every compaction and after every resume, before anything else: read the standing instructions in full (every entry listed as active between `STANDING_ENTRIES_BEGIN` and `STANDING_ENTRIES_END`, newest first, its file in `standing/`, and `STANDING.md` when `STANDING: yes`; an entry that another entry supersedes, or that ended, is not listed as active and no longer holds). Then act on the rest of that block: an entry under `ended` gets its closing entry now (`ytstack-standing end --reason ""`), an entry under `condition to check now` is checked against the host now and closed the same way when it is met, a line under `check failed` is an instruction you are not keeping: fix that first. Its first line counts the human prompts since the newest entry: more than a few after a compaction means instructions may be missing, so read the conversation summary for instructions and record them (Step 9) before you dispatch. Then the rows between `LANES_BEGIN` and `LANES_END`, the frontier, every file listed between `QUESTIONS_BEGIN` and `QUESTIONS_END`, and the newer of the two handoffs. Do not rebuild who holds what from a conversation summary. Where a summary and a file disagree, the file is the claim, and Step 4 checks it against the host before anybody acts on it. A `running` row whose worker no longer exists in this session is not dispatched again blindly: read its branch (`git log ..`), then `ytstack-frontier release ` and claim it for a new worker that continues on that branch, or write a question. When the newer handoff carries a "Rotation" block (Step 12 of the session before, `docs/ux/coordinator-format.md`), this session is its successor. Before Step 4: `ytstack-pr-watch handover --from ` (skip with `PR watch session: none`; check that the output names the moved pull requests), start the background watches it lists again, and leave the rows of its running workers alone: those workers report to the old session, which stays open as a relay and appends each report under "Reports after the rotation" in `HANDOFF.md` and sets the row to `reported`. Read the handoff again when such a row turns `reported`, and send a worker a message at its address only where the host lets this session reach it. Only when the person says the old session is closed before a worker reported does the rule above for a lost worker apply. @@ -213,7 +231,7 @@ 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. 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. 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. @@ -262,7 +280,9 @@ A lane named in the `blocks:` of an open or asked question is not ready, whateve An `asked` question is never asked again: name it as waiting since its time. When the human answers, write what he said under `## Answer`, run `ytstack-questions answer `, and add a `DECISIONS.md` entry when it decides something that lasts. Never record an answer the human did not give, and never take a verdict a plan reserves for a person. At a slice boundary the open gates go out together through `ytstack:reassess-roadmap` (its Step 3b). A step only the human may perform (a secret, a production switch, a merge he reserved) goes through `ytstack:handover-step` as one staged script. `YTSTACK_NON_INTERACTIVE: true`: ask nothing; the files stay `open` and are listed in the status under "Waiting on a person". -**Step 9 -- Record standing instructions.** When the human gives an instruction that holds beyond the task at hand (when to report, what never to merge, what not to touch), write it down at once, before the next dispatch, as a new file `$_YT_DIR/standing/-.md` (`YT_DIR` from the preamble: `.ytstack/` in the repository, or `~/.ytstack/projects//` in user scope; UTC now): frontmatter `given` (the same time, ISO), `scope` (where it applies) and `supersedes` (empty), and the instruction in your own words as its body (`docs/ux/coordinator-format.md`). Never a quotation. An instruction that replaces an older one is a new file whose `supersedes` names the older file without `.md`; the older file is not edited and nothing is deleted. Then run `ytstack-check --standing` and fix what it prints. One file per instruction keeps two pull requests that each add one from touching the same line. `STANDING.md` is not edited per entry; only a project that has `STANDING.md` and no `standing/` directory yet keeps its form: append `- -- . Scope: ` and strike a replaced line (`~~...~~ Superseded : ...`). +**Step 9 -- Record standing instructions.** When the human gives an instruction that holds beyond the task at hand (when to report, what never to merge, what not to touch, a priority, an approval that covers later cases), record it at once, before the next dispatch, with one command: `ytstack-standing add "" --scope ""` (the script is `bin/ytstack-standing` of the plugin, beside `ytstack-frontier`). Add `--supersedes ` when it replaces an older entry, `--until ` when it ends at a time, `--until-condition ""` when it ends with an event, `--until-check ""` when that event can be checked by a command that exits 0 once it happened, and `--check ""` when keeping it can be checked (a command that fails while the instruction is not kept, such as a `LANES.md` older than the last lane change). Name the role in the scope when it applies to one (`the coordinator`, `every lane`, `every reviewer`; `docs/ux/coordinator-format.md`, "Scope and roles"): the SessionStart injection and the lane briefs filter by it. The command writes the entry in a worktree of its own outside the checkout, commits it and opens or updates the one standing pull request of the UTC day; `--here` writes into the resolved `.ytstack/standing/` only, for user scope (always) or a project where you may write in the checkout. It runs `ytstack-check --standing` itself. When `hooks/standing-prompt` says a prompt reads like a standing instruction, decide: record it, or go on when it is not one. The Stop hook blocks once when such prompts got no entry. An instruction that ended is closed with `ytstack-standing end --reason ""`; nothing is edited or deleted. + +Agent-private memory (a memory file, a note in your own context) is no substitute: a successor session, another host and the human read only the repository. An instruction that lives only in your memory is lost at the next rotation. Never a quotation; the body is the instruction in your own words. One file per instruction keeps two pull requests that each add one from touching the same line. `STANDING.md` is not edited per entry; only a project that has `STANDING.md` and no `standing/` directory yet keeps its form: append `- -- . Scope: ` and strike a replaced line (`~~...~~ Superseded : ...`). **Step 10 -- Stop loops that do not converge.** A lane gets the rounds `ytstack:code-review` allows ("Bounded review": round 1 complete, round 2 the fix, no third). A lane that failed verification twice, or that would need a third review, is not dispatched again: `ytstack-frontier set --status blocked --next "Q### with the human"`, and a question file with the diagnosis (the plan never decided the point, two rules conflict, or each fix moved the problem). diff --git a/skills/resume-session/SKILL.md b/skills/resume-session/SKILL.md index f3cd49d6..802fce8f 100644 --- a/skills/resume-session/SKILL.md +++ b/skills/resume-session/SKILL.md @@ -3,7 +3,7 @@ name: resume-session description: "Rebuilds working context at the start of a session from STATE.md, handoffs and the latest summaries into a where-we-are briefing. Use when a session starts in a project with .ytstack/, or when the user says resume, where were we, pick up where I left off. Not for writing a handoff (handoff-session) and not for repos without .ytstack/ (init-project or adopt-brownfield)." metadata: tier: core - version: 0.1.1 + version: 0.1.2 triggers: - resume session - where were we @@ -58,11 +58,13 @@ if [ "$_HAS_HANDOFF" = yes ]; then fi # Automatic handoff (written out of tree by the pre-compact hook, per worktree; M016) _LATEST_AUTO_HANDOFF=none; _AUTO_HANDOFF_TS=none -if command -v yt_state_base >/dev/null 2>&1 && [ -n "${YT_REPO_KEY:-}" ]; then - _LATEST_LINK="$(yt_state_base)/repos/$YT_REPO_KEY/worktrees/$YT_WT_KEY/latest-handoff" - if [ -L "$_LATEST_LINK" ] && [ -f "$_LATEST_LINK" ]; then - _LATEST_AUTO_HANDOFF=$(readlink "$_LATEST_LINK") +# yt_latest_handoff also looks where the hook wrote it (CLAUDE_PLUGIN_DATA is not set in this shell). +if command -v yt_latest_handoff >/dev/null 2>&1 && [ -n "${YT_REPO_KEY:-}" ]; then + _LATEST_AUTO_HANDOFF=$(yt_latest_handoff) + if [ -n "$_LATEST_AUTO_HANDOFF" ]; then _AUTO_HANDOFF_TS=$(sed -n 's/^timestamp: *//p' "$_LATEST_AUTO_HANDOFF" 2>/dev/null | head -1) + else + _LATEST_AUTO_HANDOFF=none fi fi diff --git a/skills/spawn-milestone-team/brief-template.md b/skills/spawn-milestone-team/brief-template.md index b9ea8d5a..b8e313c8 100644 --- a/skills/spawn-milestone-team/brief-template.md +++ b/skills/spawn-milestone-team/brief-template.md @@ -1,5 +1,5 @@ - + @@ -58,6 +58,12 @@ Anything outside these files is reported as a blocker, not changed. Other plans, summaries and the history in STATE.md are not needed for this task. +## Standing instructions + +{{STANDING}} + +The human gave these once and for all; they override the defaults of this brief. Each line is the whole instruction; one marked `pending` is recorded but its pull request is not merged yet, and it holds all the same. + ## Verification {{VERIFICATION}} diff --git a/tests/git-ctx.test.sh b/tests/git-ctx.test.sh index 486568a3..4bf74073 100644 --- a/tests/git-ctx.test.sh +++ b/tests/git-ctx.test.sh @@ -419,6 +419,26 @@ ST2="$TMP/st2/.ytstack"; mkdir -p "$ST2/standing" printf -- '---\ngiven: 2026-11-14T12:25:00Z\nscope: x\nsupersedes:\n---\n\nOld.\n' > "$ST2/standing/20261114T1225Z-old.md" printf -- '---\ngiven: 2026-11-14T12:25:30Z\nscope: x\nsupersedes:\n---\n\nNew.\n' > "$ST2/standing/20261114T122530Z-new.md" eq "standing: optional seconds sort as :00 (12:25:30 before 12:25)" "20261114T122530Z-new.md 20261114T1225Z-old.md" "$(st "$ST2" | cut -f1 | tr '\n' ' ' | sed 's/ $//')" +# until, kind end, the fields and the role filter (issues #73, #74) +ST3="$TMP/st3/.ytstack"; mkdir -p "$ST3/standing" +printf -- '---\ngiven: 2026-11-14T10:00:00Z\nscope: every lane\nsupersedes:\nuntil: 2026-11-14T12:37Z\n---\n\nHold merges. Until the test ends.\n' > "$ST3/standing/20261114T1000Z-hold.md" +printf -- '---\ngiven: 2026-11-14T10:10:00Z\nscope: the coordinator\nsupersedes:\nuntil-condition: PR 1879 merged\ncheck: test -f LANES.md\n---\n\n- Keep LANES.md current!\n' > "$ST3/standing/20261114T1010Z-lanes.md" +printf -- '---\ngiven: 2026-11-14T10:20:00Z\nscope: every reviewer\nsupersedes:\n---\n\nName the commit.\n' > "$ST3/standing/20261114T1020Z-commit.md" +printf -- '---\ngiven: 2026-11-14T10:30:00Z\nscope: every reviewer\nsupersedes: 20261114T1020Z-commit\nkind: end\n---\n\nEnded: x.\n' > "$ST3/standing/20261114T1030Z-end-commit.md" +printf -- '---\ngiven: 2026-11-14T10:40:00Z\nscope: this project\nsupersedes:\n---\n\nEnglish in code.\n' > "$ST3/standing/20261114T1040Z-english.md" +sf() { ( . "$LIB"; yt_standing_fields "$@" ); } +eq "standing fields: before until -> active, end entry and its target gone" \ + "20261114T1040Z-english.md|20261114T1010Z-lanes.md|20261114T1000Z-hold.md" "$(sf "$ST3" 20261114120000 | cut -f1 | tr '\n' '|' | sed 's/|$//')" +eq "standing fields: until passed -> expired" "expired" "$(sf "$ST3" 20261114130000 | awk -F '\t' '$1 ~ /hold/ { print $9 }')" +eq "standing fields: until exactly now -> expired" "expired" "$(sf "$ST3" 20261114123700 | awk -F '\t' '$1 ~ /hold/ { print $9 }')" +eq "standing fields: the keys and the first sentence" "the coordinator|-|PR 1879 merged|-|test -f LANES.md|Keep LANES.md current!|active" \ + "$(sf "$ST3" 20261114120000 | awk -F '\t' '$1 ~ /lanes/ { print $3 "|" $4 "|" $5 "|" $6 "|" $7 "|" $8 "|" $9 }')" +eq "standing: yt_standing skips the expired entry" "20261114T1040Z-english.md 20261114T1010Z-lanes.md" "$(st "$ST3" | cut -f1 | tr '\n' ' ' | sed 's/ $//')" +sl() { ( . "$LIB"; yt_standing_lines "$@" ); } +eq "standing lines: coordinator sees all active" 2 "$(sl "$ST3" coordinator | grep -c .)" +eq "standing lines: lane sees the role-free entry only" "- 20261114T1040Z-english (this project): English in code." "$(sl "$ST3" lane)" +eq "standing lines: the cap leaves a pointer" "- ... 1 more: bin/ytstack-standing list" "$(sl "$ST3" coordinator 1 | sed -n 2p)" +eq "session home follows XDG_STATE_HOME" "/x/ytstack/sessions" "$( . "$LIB"; XDG_STATE_HOME=/x yt_session_home )" echo echo "$PASS passed, $FAIL failed" diff --git a/tests/hooks-coordinate.test.sh b/tests/hooks-coordinate.test.sh new file mode 100644 index 00000000..28cc1015 --- /dev/null +++ b/tests/hooks-coordinate.test.sh @@ -0,0 +1,157 @@ +#!/usr/bin/env bash +# Tests for the operating path of a coordinate session (issue #76, part of #75). +# +# hooks/pre-tool-use-agent (PreToolUse on Agent, Task, SendMessage) +# - no coordinate marker -> silent +# - Agent prompt without "# Brief: " line -> additionalContext warning, never a deny +# - Agent prompt with a rendered brief -> silent; every Agent call is logged +# - short SendMessage -> silent; long SendMessage without a brief -> warning +# hooks/session-start +# - coordinate marker -> the operating checklist, byte for byte the block of +# docs/ux/coordinator-format.md; without the marker -> none +# hooks/stop (coordinate lints) +# - LANES.md older than the newest dispatch -> systemMessage once per session +# - STATE pointer behind the newest milestone -> systemMessage +# - the same finding in 3 sessions in a row -> block once; cleared -> streak 0 +# +# Run: /bin/bash tests/hooks-coordinate.test.sh (exit 0 = all pass) + +set -uo pipefail +ROOT="$(cd "$(dirname "$0")/.." && pwd -P)" +H="$ROOT/hooks" + +PASS=0; FAIL=0 +ok() { PASS=$((PASS+1)); echo " ok - $1"; } +bad() { FAIL=$((FAIL+1)); echo " FAIL - $1${2:+ ($2)}"; } +eq() { if [ "$2" = "$3" ]; then ok "$1"; else bad "$1" "expected '$2' got '$3'"; fi; } +has() { case "$2" in *"$3"*) ok "$1";; *) bad "$1" "missing '$3' in: $2";; esac; } +hasnt() { case "$2" in *"$3"*) bad "$1" "unexpected '$3'";; *) ok "$1";; esac; } + +JQ=""; for c in /usr/bin/jq /opt/homebrew/bin/jq /usr/local/bin/jq; do [ -x "$c" ] && { JQ="$c"; break; }; done +[ -n "$JQ" ] || JQ=$(command -v jq) +[ -n "$JQ" ] || { echo "FATAL: jq needed"; exit 2; } + +TMP=$(mktemp -d "${TMPDIR:-/tmp}/ytcoord.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 +SH="$XDG_STATE_HOME/ytstack/sessions" + +P="$TMP/p"; mkdir -p "$P/.ytstack" +( cd "$P" || exit 2; git init -q && git config user.email t@t.t && git config user.name t && git config commit.gpgsign false + printf 'project: p\nlast_updated: %s\ncurrent_milestone: M001\nactive_slice: none\nactive_task: none\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > .ytstack/STATE.md + printf -- '---\nmilestone: M001\n---\n' > .ytstack/M001-ROADMAP.md + git add -A; git commit -qm seed ) >/dev/null 2>&1 || { echo FATAL fixture; exit 2; } +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)}' \ + | 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); } +ctx() { printf '%s' "$OUT" | "$JQ" -r "$1 // empty" 2>/dev/null; } + +echo "# pre-tool-use-agent" +tool a1 Agent "Implement the export." +eq "no marker: silent" "" "$OUT" +marker a1 +tool a1 Agent "Implement the export. Change src/a.ts." +has "hand-written Agent prompt: warned" "$(ctx .hookSpecificOutput.additionalContext)" "carries no rendered brief" +has "names ytstack-brief render" "$(ctx .hookSpecificOutput.additionalContext)" "bin/ytstack-brief\" render" +eq "never a permission decision" "" "$(ctx .hookSpecificOutput.permissionDecision)" +tool a1 Agent "# Brief: M001-S01-T01 (p) + +## Outcome +x" +eq "rendered brief: silent" "" "$OUT" +tool a1 Agent "Context first. +# Brief: M001-S01-T01 (p)" +eq "brief marker on a later line: silent" "" "$OUT" +eq "every Agent call logged" 3 "$(grep -c . "$SH/a1/dispatches")" +tool a1 SendMessage "Go on." +eq "short SendMessage: silent" "" "$OUT" +LONG=$(awk 'BEGIN { for (i = 0; i < 60; i++) printf "do the thing "; }') +tool a1 SendMessage "$LONG" +has "long SendMessage without a brief: warned" "$(ctx .hookSpecificOutput.additionalContext)" "SendMessage prompt carries no rendered brief" +tool a1 Bash "ls" +eq "another tool: silent" "" "$OUT" +lookup() { OUT=$("$JQ" -n --arg t "$1" --arg c "$P" '{session_id: "a1", cwd: $c, hook_event_name: "PreToolUse", tool_name: "Agent", tool_input: {prompt: "Where is X defined?", subagent_type: $t}}' | bash "$H/pre-tool-use-agent" 2>&1); } +lookup Explore; eq "an Explore lookup: no warning" "" "$OUT" +lookup semble-search; eq "a search agent: no warning" "" "$OUT" +eq "lookups are not counted as dispatches" 3 "$(grep -c . "$SH/a1/dispatches")" +lookup general-purpose; has "a general-purpose agent without a brief: warned" "$(ctx .hookSpecificOutput.additionalContext)" "no rendered brief" +eq "and counted" 4 "$(grep -c . "$SH/a1/dispatches")" +# without jq the hook reads and writes JSON through python3 (Codex finding on PR #87) +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: still warned, through python3" "$(ctx .hookSpecificOutput.additionalContext)" "no rendered brief" +eq "no jq: still counted" 5 "$(grep -c . "$SH/a1/dispatches")" + +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" +OUT=$("$JQ" -n --arg c "$P" '{session_id: "a1", cwd: $c, source: "compact"}' | CLAUDE_PLUGIN_ROOT="$ROOT" bash "$H/session-start" 2>/dev/null) +C=$(ctx .hookSpecificOutput.additionalContext) +has "coordinate session: the checklist, as in the doc" "$C" "$WANT" +hasnt "coordinate session: no minimal-code line" "$C" "Minimal-code guard is on" +if [ "${#C}" -le 9500 ]; then ok "fits the guard (${#C})"; else bad "fits the guard" "${#C}"; fi +OUT=$("$JQ" -n --arg c "$P" '{session_id: "other", cwd: $c, source: "compact"}' | CLAUDE_PLUGIN_ROOT="$ROOT" bash "$H/session-start" 2>/dev/null) +hasnt "other session: no checklist" "$(ctx .hookSpecificOutput.additionalContext)" "Coordinator operating checklist" +P2=$(grep -c 'operating-checklist:begin' "$ROOT/skills/coordinate/SKILL.md") +eq "the coordinate preamble reads the same block" 1 "$P2" + +echo "# stop: coordinate lints" +marker s1 +printf '| a |\n' > "$P/.ytstack/LANES.md"; touch -t 202001010000 "$P/.ytstack/LANES.md" +printf '%s\n' "$(date +%s)" > "$SH/s1/dispatches" +stop s1 +has "LANES.md behind the dispatches: warned" "$(ctx .systemMessage)" "LANES.md last changed" +eq "a first session: no block" "" "$(ctx .decision)" +stop s1 +hasnt "said once per session" "$(ctx .systemMessage)" "LANES.md last changed" +touch "$P/.ytstack/LANES.md"; stop s1 +eq "LANES.md current: silent" "" "$OUT" +printf -- '---\nmilestone: M003\n---\n' > "$P/.ytstack/M003-ROADMAP.md" +marker s2; stop s2 +has "STATE pointer behind: warned" "$(ctx .systemMessage)" "current_milestone M001 is behind the newest milestone on disk (M003)" +eq "session 1 of the state streak: no block" "" "$(ctx .decision)" +marker s3; stop s3; eq "session 2: no block" "" "$(ctx .decision)" +marker s4; stop s4 +eq "session 3 in a row: block" block "$(ctx .decision)" +has "the block names the streak" "$(ctx .reason)" "3 sessions in a row" +stop s4; eq "the block comes once per session" "" "$(ctx .decision)" +rm -f "$P/.ytstack/M003-ROADMAP.md" +marker s5; stop s5; eq "cleared: silent" "" "$OUT" +printf -- '---\nmilestone: M003\n---\n' > "$P/.ytstack/M003-ROADMAP.md" +marker s6; stop s6 +eq "a clean session broke the row: the next one counts 1" 1 "$(awk -F '\t' '$1 == "state" { print $2 }' "$XDG_STATE_HOME"/ytstack/repos/*/coordinate-lints)" +eq "and does not block" "" "$(ctx .decision)" +rm -f "$P/.ytstack/M003-ROADMAP.md" + +echo "# stop: the first stop of a session comes before its first dispatch (a status question)" +rm -rf "$XDG_STATE_HOME/ytstack/repos" +touch -t 202001010000 "$P/.ytstack/LANES.md" +for s in q1 q2 q3; do + marker "$s"; stop "$s" + [ "$s" != q1 ] || eq "q1: the first stop, no dispatch yet: silent" "" "$OUT" + date +%s >> "$SH/$s/dispatches"; stop "$s" +done +eq "the third such session blocks" block "$(ctx .decision)" + +echo "# stop: overlapping sessions count once each (A, B, A)" +rm -rf "$XDG_STATE_HOME/ytstack/repos" +for s in ov-a ov-b; do marker "$s"; date +%s > "$SH/$s/dispatches"; done +stop ov-a; stop ov-b; stop ov-a +eq "A, B, A: two sessions, not three" 2 "$(awk -F '\t' '$1 == "lanes" { print $2 }' "$XDG_STATE_HOME"/ytstack/repos/*/coordinate-lints)" +eq "and no block" "" "$(ctx .decision)" + +echo "# stop: the streak is kept per repository key from the marker (user scope)" +rm -rf "$XDG_STATE_HOME/ytstack/repos" +mkdir -p "$SH/u1"; printf '%s\nkeyone\n' "$P/.ytstack" > "$SH/u1/coordinate"; date +%s > "$SH/u1/dispatches"; stop u1 +mkdir -p "$SH/u2"; printf '%s\nkeytwo\n' "$P/.ytstack" > "$SH/u2/coordinate"; date +%s > "$SH/u2/dispatches"; stop u2 +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 +echo "$PASS passed, $FAIL failed" +[ "$FAIL" -eq 0 ] diff --git a/tests/hooks-json.test.sh b/tests/hooks-json.test.sh index 758eed63..d002c202 100644 --- a/tests/hooks-json.test.sh +++ b/tests/hooks-json.test.sh @@ -38,6 +38,10 @@ eq "pr-watch timeouts are 15 s" "15" \ "$(jq -r --arg c "$PW" '[.hooks[][].hooks[] | select(.command == $c) | .timeout] | unique | join(",")' "$J")" eq "version-notice is the first UserPromptSubmit entry, 5 s" 'bash "${CLAUDE_PLUGIN_ROOT}/hooks/version-notice"|5' \ "$(jq -r '.hooks.UserPromptSubmit[0].hooks[0] | "\(.command)|\(.timeout)"' "$J")" +eq "standing-prompt is the second UserPromptSubmit entry, 5 s (issue #72)" 'bash "${CLAUDE_PLUGIN_ROOT}/hooks/standing-prompt"|5' \ + "$(jq -r '.hooks.UserPromptSubmit[1].hooks[0] | "\(.command)|\(.timeout)"' "$J")" +eq "pre-tool-use-agent on Agent|Task|SendMessage, 5 s (issue #76)" 'Agent|Task|SendMessage|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 ca5509f8..ba5a9bc7 100644 --- a/tests/hooks-readonly.test.sh +++ b/tests/hooks-readonly.test.sh @@ -121,6 +121,61 @@ lacks "ss-main: long next action -> YT_BIN yields first (issue #85)" "$CTX" "YT_ if [ "${#CTX}" -le 9500 ]; then ok "ss-main: cut injection fits the guard (${#CTX})"; else bad "ss-main: cut injection fits the guard" "${#CTX}"; fi cp "$TMP/state.good" "$MAIN/.ytstack/STATE.md" +# ---- 1e2. session-start: standing entries in force, filtered by role (issue #74) +SDIR="$MAIN/.ytstack/standing"; mkdir -p "$SDIR" +sw() { printf -- '---\ngiven: %s\nscope: %s\nsupersedes: %s\n%b---\n\n%s\n' "$2" "$3" "$4" "$5" "$6" > "$SDIR/$1.md"; } +sw 20261101T1000Z-old 2026-11-01T10:00:00Z "every lane" "" "" "Old rule." +sw 20261101T1100Z-new 2026-11-01T11:00:00Z "every lane" 20261101T1000Z-old "" "Lanes run their own tests. Second sentence." +sw 20261101T1200Z-coord 2026-11-01T12:00:00Z "the coordinator" "" "" "Lanes are tracked in LANES.md at all times." +sw 20261101T1300Z-window 2026-11-01T13:00:00Z "everyone" "" 'until: 2026-11-01T14:00Z\n' "Hold merges until the measurement ends." +sw 20261101T1400Z-all 2026-11-01T14:00:00Z "this project" "" 'check: false\nuntil-check: touch $HOME/RAN\n' "Status only at slice boundaries." +run session-start "{\"session_id\":\"s1st\",\"cwd\":$(jstr "$MAIN"),\"source\":\"compact\"}" HOME="$TMP/h" +CTX=$(printf '%s' "$OUT" | jq -r '.hookSpecificOutput.additionalContext // empty' 2>/dev/null) +has "ss-standing: block names the role (lane without marker)" "$CTX" "Standing instructions in force (role: lane" +has "ss-standing: entry with scope and first sentence" "$CTX" "- 20261101T1100Z-new (every lane): Lanes run their own tests." +lacks "ss-standing: superseded entry skipped" "$CTX" "20261101T1000Z-old" +lacks "ss-standing: expired entry skipped" "$CTX" "20261101T1300Z-window" +lacks "ss-standing: coordinator entry not for a lane" "$CTX" "20261101T1200Z-coord" +has "ss-standing: entry naming no role is for everyone" "$CTX" "20261101T1400Z-all" +[ ! -e "$TMP/h/RAN" ] && ok "ss-standing: no until-check runs in the hook" || bad "ss-standing: no until-check runs in the hook" +mkdir -p "$TMP/xdg/ytstack/sessions/s1co"; printf '%s\n' "$MAIN/.ytstack" > "$TMP/xdg/ytstack/sessions/s1co/coordinate" +run session-start "{\"session_id\":\"s1co\",\"cwd\":$(jstr "$MAIN"),\"source\":\"compact\"}" XDG_STATE_HOME="$TMP/xdg" +CTX=$(printf '%s' "$OUT" | jq -r '.hookSpecificOutput.additionalContext // empty' 2>/dev/null) +# This fixture sits at the cap (two handoffs with long paths, the checklist): the list +# shrinks to the three newest or to its pointer, by the length of the temp paths. +case "$CTX" in + *"Standing instructions in force (role: coordinator"*|*"Standing instructions: 3 in force for role coordinator (cut for the cap)"*) ok "ss-standing: at the cap -> the list or its pointer, with the role" ;; + *) bad "ss-standing: at the cap -> the list or its pointer, with the role" ;; +esac +has "ss-standing: the operating checklist stays" "$CTX" "Coordinator operating checklist" +if [ "${#CTX}" -le 9500 ]; then ok "ss-standing: injection fits the guard (${#CTX})"; else bad "ss-standing: injection fits the guard" "${#CTX}"; fi +# A lighter project (no handoffs): the coordinator gets the list itself. +LIGHT="$TMP/light"; mkdir -p "$LIGHT/.ytstack"; cp "$TMP/state.good" "$LIGHT/.ytstack/STATE.md"; cp -R "$SDIR" "$LIGHT/.ytstack/standing" +( cd "$LIGHT" && git init -q ) >/dev/null 2>&1 +printf '%s\n' "$LIGHT/.ytstack" > "$TMP/xdg/ytstack/sessions/s1co/coordinate" +run session-start "{\"session_id\":\"s1co\",\"cwd\":$(jstr "$LIGHT"),\"source\":\"compact\"}" XDG_STATE_HOME="$TMP/xdg" +CTX=$(printf '%s' "$OUT" | jq -r '.hookSpecificOutput.additionalContext // empty' 2>/dev/null) +has "ss-standing: coordinate marker -> role coordinator" "$CTX" "(role: coordinator" +has "ss-standing: coordinator sees its entry" "$CTX" "20261101T1200Z-coord (the coordinator)" +if [ "${#CTX}" -le 9500 ]; then ok "ss-standing: light project fits the guard (${#CTX})"; else bad "ss-standing: light project fits the guard" "${#CTX}"; fi +# A long next action and fifty long entries: the list shrinks to three before the next action is cut. +awk -v lu="$(date -u +%Y-%m-%dT%H:%M:%SZ)" 'BEGIN { printf "project: p\nlast_updated: %s\ncurrent_milestone: M001\nactive_slice: S01\nactive_task: T01\n\n## Next action\n\n", lu; for (i = 0; i < 300; i++) printf "word%d ", i; print "" }' > "$LIGHT/.ytstack/STATE.md" +for i in 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39; do + printf -- '---\ngiven: 2026-11-15T10:%s:00Z\nscope: the coordinator and every lane\nsupersedes:\n---\n\nThis is a very long standing instruction number %s that goes on and on about what must never happen and why.\n' "$i" "$i" > "$LIGHT/.ytstack/standing/20261115T10${i}Z-s$i.md" +done +run session-start "{\"session_id\":\"x9\",\"cwd\":$(jstr "$LIGHT"),\"source\":\"compact\"}" XDG_STATE_HOME="$TMP/xdg" +CTX=$(printf '%s' "$OUT" | jq -r '.hookSpecificOutput.additionalContext // empty' 2>/dev/null) +case "$CTX" in + *"Next action: +word0 word1"*|*"(omitted: see STATE.md"*) ok "ss-standing: long list -> the next action is cut by the room left, not by the list" ;; + *) bad "ss-standing: long list -> the next action is cut by the room left, not by the list" ;; +esac +lacks "ss-standing: long list -> not cut to the pointer" "$CTX" "(cut for the cap): bin/ytstack-standing list" +has "ss-standing: long list -> three lines and a count of the rest" "$CTX" "- ... 29 more: bin/ytstack-standing list" +if [ "${#CTX}" -le 9500 ]; then ok "ss-standing: long list fits the guard (${#CTX})"; else bad "ss-standing: long list fits the guard" "${#CTX}"; fi +eq "ss-standing: git status shows only the fixture entries" "?? .ytstack/standing/" "$(git -C "$MAIN" status --porcelain)" +rm -rf "$SDIR" "$TMP/xdg" + # ---- 1f. session-start: no roadmap in progress -> clean count, no stderr noise run session-start "{\"session_id\":\"s1j\",\"cwd\":$(jstr "$MAIN")}" eq "ss-main: no in-progress roadmap -> no 'integer expression' error on stderr" 0 "$(grep -c 'integer expression' "$ERR")" diff --git a/tests/hooks-standing.test.sh b/tests/hooks-standing.test.sh new file mode 100644 index 00000000..990cd4eb --- /dev/null +++ b/tests/hooks-standing.test.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Tests for the standing-instruction hooks of a coordinator session (issue #72). +# +# hooks/standing-prompt (UserPromptSubmit) +# - no coordinate marker -> silent, writes nothing +# - marker: every human prompt is counted (/prompts) +# - a prompt that reads like a standing instruction (English and German) +# is flagged and gets the record instruction as additionalContext +# - a plain prompt is counted, not flagged; a "" is neither +# hooks/stop +# - flagged prompt, no entry since -> decision block once, with the list +# - the next stop with the same flags -> no block (handled) +# - an entry in the working tree since the prompt -> no block +# - an entry only on a branch since the prompt -> no block +# - stop_hook_active -> silent; the task reminder still works beside a block +# +# Run: /bin/bash tests/hooks-standing.test.sh (exit 0 = all pass) + +set -uo pipefail +ROOT="$(cd "$(dirname "$0")/.." && pwd -P)" +HP="$ROOT/hooks/standing-prompt"; HS="$ROOT/hooks/stop" + +PASS=0; FAIL=0 +ok() { PASS=$((PASS+1)); echo " ok - $1"; } +bad() { FAIL=$((FAIL+1)); echo " FAIL - $1${2:+ ($2)}"; } +eq() { if [ "$2" = "$3" ]; then ok "$1"; else bad "$1" "expected '$2' got '$3'"; fi; } +has() { case "$2" in *"$3"*) ok "$1";; *) bad "$1" "missing '$3' in: $2";; esac; } +hasnt() { case "$2" in *"$3"*) bad "$1" "unexpected '$3'";; *) ok "$1";; esac; } + +JQ=""; for c in /usr/bin/jq /opt/homebrew/bin/jq /usr/local/bin/jq; do [ -x "$c" ] && { JQ="$c"; break; }; done +[ -n "$JQ" ] || JQ=$(command -v jq) +[ -n "$JQ" ] || { echo "FATAL: jq needed"; exit 2; } + +TMP=$(mktemp -d "${TMPDIR:-/tmp}/ytstdhook.XXXXXX"); TMP=$(cd "$TMP" && pwd -P) +trap 'rm -rf "$TMP"' EXIT +export XDG_STATE_HOME="$TMP/state" +unset CLAUDE_PLUGIN_DATA PLUGIN_DATA 2>/dev/null +SD="$XDG_STATE_HOME/ytstack/sessions/s1" + +P="$TMP/p"; mkdir -p "$P/.ytstack" +( cd "$P" || exit 2; git init -q && git config user.email t@t.t && git config user.name t && git config commit.gpgsign false + printf 'x\n' > .ytstack/STATE.md; git add -A; git commit -qm seed ) >/dev/null 2>&1 || { echo FATAL fixture; exit 2; } + +prompt() { # prompt -> OUT + OUT=$("$JQ" -n --arg p "$1" --arg c "$P" '{session_id: "s1", cwd: $c, hook_event_name: "UserPromptSubmit", prompt: $p}' | bash "$HP" 2>&1) +} +stop() { # stop [extra jq object] -> OUT + local extra="${1:-}"; [ -n "$extra" ] || extra='{}' + OUT=$("$JQ" -n --arg c "$P" '{session_id: "s1", cwd: $c, hook_event_name: "Stop"}' | "$JQ" -c ". + $extra" | bash "$HS" 2>&1) +} +lines() { [ -f "$1" ] && grep -c . "$1" || echo 0; } + +echo "# no coordinate marker" +prompt "From now on always merge green pull requests." +eq "silent without the marker" "" "$OUT" +[ -e "$SD" ] && bad "writes nothing without the marker" || ok "writes nothing without the marker" + +echo "# coordinate marker" +mkdir -p "$SD"; printf '%s\n' "$P/.ytstack" > "$SD/coordinate" +prompt "What is the state of lane S02?" +eq "plain prompt: silent" "" "$OUT" +eq "plain prompt: counted" 1 "$(lines "$SD/prompts")" +eq "plain prompt: not flagged" 0 "$(lines "$SD/standing-flags")" +prompt "agent done, never mind" +eq "task notification: silent" "" "$OUT" +eq "task notification: not counted" 1 "$(lines "$SD/prompts")" +prompt "From now on merge green PRs promptly." +has "English standing phrase -> instruction injected" "$OUT" "reads like a standing instruction" +has "names the command" "$OUT" "bin/ytstack-standing\\\" add" +has "says memory is no substitute" "$OUT" "Agent memory is no substitute" +if printf '%s' "$OUT" | "$JQ" -e '.hookSpecificOutput.additionalContext' >/dev/null 2>&1; then ok "UserPromptSubmit JSON"; else bad "UserPromptSubmit JSON" "$OUT"; fi +for p in "Bitte priorisiere M004 vor M005." "Fass PR 1336 nicht an, solange der Plan laeuft." "Denk dran: immer erst den Review." "Never touch the release branch." "Don't touch PR 12 while the load test runs." "Bis auf weiteres keine Merges ohne mein OK."; do + prompt "$p"; has "flagged: $p" "$OUT" "standing instruction" +done +eq "all seven flagged" 7 "$(lines "$SD/standing-flags")" +eq "eight prompts counted" 8 "$(lines "$SD/prompts")" +# more true positives, English and German (review of PR #87) +for p in "Ab jetzt merge grüne PRs sofort." "Von nun an Status nur an Slice-Grenzen." "Grundsätzlich keine Force-Pushes." "Immer wenn ein Release rausgeht, starte den Watch." "Nie wieder ohne Review mergen." "Merk dir: der Dev-Cluster bleibt unangetastet." "Going forward, report only at slice boundaries." "Until further notice the PR limit is 15." "OK. Always run the full suite before a merge." "Please prioritise lane 7 over lane 3." "Lass PR 9 in Ruhe -- fass ihn nicht an." "hold merges until 12:37" "bis 12:37 keine merges" "until the load test ends" "solange der Lasttest läuft" "No deploys while the load test runs." "Keine Merges bis der Lasttest durch ist."; do + prompt "$p"; has "flagged: $p" "$OUT" "standing instruction" +done +# ordinary prompts that only contain a word such instructions use (false positives of 0.11) +for p in "bis wann ist das fertig?" "Danke, bis später" "never mind, wrong lane" "schau mal, ob CI noch läuft während ich esse" "what happened while I was away?" "ist das immer noch rot?" "Prüf bitte, warum der Test nie grün wird" "nie gehört, was ist das?" "wie ist der stand?" "ok, mach weiter" "merge #87" "Kein Problem, danke." "The pipeline is evergreen and nobody minds." "Can you always tell me what you changed?"; do + prompt "$p"; eq "not flagged: $p" "" "$OUT" +done +eq "only the true positives were flagged" 24 "$(lines "$SD/standing-flags")" +# the stop cases below start from the first seven flags +head -7 "$SD/standing-flags" > "$SD/sf.tmp" && mv "$SD/sf.tmp" "$SD/standing-flags" + +echo "# stop: block once" +stop +eq "block decision" block "$(printf '%s' "$OUT" | "$JQ" -r '.decision // empty' 2>/dev/null)" +R=$(printf '%s' "$OUT" | "$JQ" -r '.reason // empty' 2>/dev/null) +has "reason counts the prompts" "$R" "7 human prompt(s)" +has "reason lists a prompt" "$R" "Bitte priorisiere M004" +has "reason names the command" "$R" "bin/ytstack-standing\" add" +stop; eq "second stop, same flags: silent" "" "$OUT" +eq "git status of the project stays clean" "" "$(git -C "$P" status --porcelain)" + +echo "# stop: an entry since the prompt counts" +# A flag in the same second as the last stop counts as handled: wait one. +sleep 1; prompt "Always ask before a production deploy." +mkdir -p "$P/.ytstack/standing" +printf -- '---\ngiven: x\nscope: y\nsupersedes:\n---\n\nAsk first.\n' > "$P/.ytstack/standing/$(date -u +%Y%m%dT%H%MZ)-ask-first.md" +stop; eq "entry in the working tree -> no block" "" "$OUT" +rm -rf "$P/.ytstack/standing" + +sleep 1; prompt "Never merge on Fridays." +( cd "$P" || exit 2; git switch -q -c standing/x && mkdir -p .ytstack/standing \ + && printf 'e\n' > ".ytstack/standing/$(date -u +%Y%m%dT%H%MZ)-no-fridays.md" && git add -A && git commit -qm entry && git switch -q - ) >/dev/null 2>&1 +[ ! -d "$P/.ytstack/standing" ] && ok "fixture: entry only on the branch" || bad "fixture: entry only on the branch" +stop; eq "entry on a local branch -> no block" "" "$OUT" + +echo "# stop: guards and the task reminder" +sleep 1; prompt "Never deploy without a watch." +stop '{"stop_hook_active": true}'; eq "stop_hook_active -> silent" "" "$OUT" +printf 'current_milestone: M042\nactive_slice: S03\nactive_task: T07\n' > "$P/.ytstack/STATE.md" +stop +eq "block and task reminder together: block" block "$(printf '%s' "$OUT" | "$JQ" -r '.decision // empty')" +has "block and task reminder together: reminder" "$(printf '%s' "$OUT" | "$JQ" -r '.systemMessage // empty')" "M042-S03-T07" +rm -f "$SD/coordinate" +prompt "Never again."; stop +hasnt "marker gone: no block" "$OUT" '"decision"' + +echo +echo "$PASS passed, $FAIL failed" +[ "$FAIL" -eq 0 ] diff --git a/tests/skill-preambles.test.sh b/tests/skill-preambles.test.sh index e1d3a15c..b6b511fc 100644 --- a/tests/skill-preambles.test.sh +++ b/tests/skill-preambles.test.sh @@ -22,6 +22,7 @@ ROOT="$(cd "$(dirname "$0")/.." && pwd -P)" PASS=0; FAIL=0 ok() { PASS=$((PASS+1)); echo " ok - $1"; } +eq() { if [ "$2" = "$3" ]; then ok "$1"; else bad "$1" "expected '$2' got '$3'"; fi; } bad() { FAIL=$((FAIL+1)); echo " FAIL - $1${2:+ ($2)}"; } has() { case "$2" in *"$3"*) ok "$1";; *) bad "$1" "missing '$3'";; esac; } @@ -106,10 +107,16 @@ upstream_checks() { PD="$TMP/plugin-data" run_pre() { # run_pre