From fe4a7394fef0763ebed854c353fce1c05c2fb16a Mon Sep 17 00:00:00 2001 From: Alex Wegener Date: Sun, 15 Nov 2026 00:37:48 +0100 Subject: [PATCH 01/55] chore: plan M031 (factory tools explicit, #54/#61), M032 (incident to lesson loop, #53), M033 (upstream feedback channel, #55) Co-Authored-By: Claude Opus 5.5 --- .ytstack/M031-CONTEXT.md | 42 ++++++++++++++++++++++++++++++++++++++++ .ytstack/M031-ROADMAP.md | 35 +++++++++++++++++++++++++++++++++ .ytstack/M032-CONTEXT.md | 39 +++++++++++++++++++++++++++++++++++++ .ytstack/M032-ROADMAP.md | 33 +++++++++++++++++++++++++++++++ .ytstack/M033-CONTEXT.md | 36 ++++++++++++++++++++++++++++++++++ .ytstack/M033-ROADMAP.md | 31 +++++++++++++++++++++++++++++ .ytstack/ROADMAP.md | 3 +++ .ytstack/STATE.md | 6 ++++-- 8 files changed, 223 insertions(+), 2 deletions(-) create mode 100644 .ytstack/M031-CONTEXT.md create mode 100644 .ytstack/M031-ROADMAP.md create mode 100644 .ytstack/M032-CONTEXT.md create mode 100644 .ytstack/M032-ROADMAP.md create mode 100644 .ytstack/M033-CONTEXT.md create mode 100644 .ytstack/M033-ROADMAP.md diff --git a/.ytstack/M031-CONTEXT.md b/.ytstack/M031-CONTEXT.md new file mode 100644 index 00000000..daf57142 --- /dev/null +++ b/.ytstack/M031-CONTEXT.md @@ -0,0 +1,42 @@ +--- +milestone: M031 +project: ytstack +created: 2026-11-15T00:45:00Z +size: L +--- + +# M031 -- Context + +## Goal + +An agent in a project that adopted ytstack uses the factory tools that are already shipped (risk route, PR watch, release watch, signals, review lessons) without being told, learns when the plugin changed under it, and a person can set those tools up from one guide. + +## Exit criteria + +- `coordinate` has an explicit "Factory tools" step: `ytstack-risk route` before every merge (also when the coordinator merges itself, not only through `finish-lane`), PR watch registration of all open PRs, `ytstack-watch release` after every production release, `signal-intake` / `incident` for signals, `review-lessons` after a merge with a bot finding. Each tool is named with the command and the condition under which it is skipped. +- `ytstack-risk route` can return `unattended` in a repository where agents may not write in the main checkout and a ruleset binds reviews to the head: the review round comes from the host (the review on the current head: commit, author, verdict line) instead of a line the pull request has to commit. A fixture test reproduces the context-mcp case (issue #54 comment, context-mcp #1715) and routes it `unattended` where the rules allow it. +- The SessionStart block (and `ytstack-upkeep`) says once per session, in one line each and only when it applies: risk routing not configured although the project has `.ytstack/spec/` (everything goes to a person); PR watch off or its worker without a fresh heartbeat; `RUNTIME.md` without "Release" or "Signals" although the project releases or has signals; and "ytstack X.Y installed, this session loaded skills of A.B: reload the skills you use" with the CHANGELOG headings in between, when the installed plugin is newer than the one the session started on. +- `coordinate` can rotate in one step while lanes run: write the handoff, re-register the PR watches to the successor session, hand over the background agents' addresses; the rule "rotate after one compaction" becomes followable under load. +- `QUICKSTART.md` has a "Setting up the factory tools" section (greenfield and brownfield/upgrade variants: `REVIEW.md` and `auto_merge`/`merge_by: risk` with a dry `route` on a recent PR, PR watch enable/install-worker incl. the shim caveat and coordinator registration, `RUNTIME.md` "Release" and "Signals", `ytstack-upkeep` on a schedule) and an "Upgrading from 0.x" checklist. +- `reconcile` (or `adopt-brownfield`) detects a large plan outside `.ytstack/` (for example `plans/*.md` tables) and offers to map it into milestones and slices, so `ytstack-frontier` sees it. +- Docs, CHANGELOG; all suites, checker, spec lint/drift, Codex and Kimi tests and plugin validation pass; evals for changed skills with a case. + +## Size + +L -- 5 slices. + +## Planning input + +Issue #54 (coordinator session in context-mcp hand-built a PR babysitter, a review tiering and a release post-check that 0.7-0.9 already ship), its comments (setup guide gap; `route` can never return `unattended` there; the subagent-PR watch gap, closed in 0.9.1/0.9.2), and the two smaller observations of issue #61 (a session keeps the skill text it loaded; rotation after one compaction is not followable under load). Points 1 and 2 of #54 for the PR watch are done (0.9.1, 0.9.2). + +## Decisions locked in discuss phase + +2026-11-15: The milestone makes existing tools explicit and reachable; it adds no new factory tool. New tools for incidents and upstream feedback are M032 and M033. + +2026-11-15: Warnings appear only when they apply and once per session; a project that uses none of the tools sees nothing. + +## Open questions + +- Version awareness: where does a session learn which plugin version it started on? Candidates: the SessionStart hook writes the version into the session state directory; a later hook compares it with the installed version. +- Risk route: does every host expose the verdict line of a review with its commit (GitHub reviews: `commit_id`, `body`), and how does a round count across pushes without a file? +- External plans: detect only, or also convert? Plan: detect and propose the mapping as a question; the conversion runs only after a yes. diff --git a/.ytstack/M031-ROADMAP.md b/.ytstack/M031-ROADMAP.md new file mode 100644 index 00000000..1537e449 --- /dev/null +++ b/.ytstack/M031-ROADMAP.md @@ -0,0 +1,35 @@ +--- +milestone: M031 +project: ytstack +size: L +created: 2026-11-15T00:45:00Z +status: planned +total_slices: 5 +completed_slices: 0 +--- + +# M031 Roadmap + +**Goal:** An agent in a project that adopted ytstack uses the factory tools that are already shipped (risk route, PR watch, release watch, signals, review lessons) without being told, learns when the plugin changed under it, and a person can set those tools up from one guide. + +**Exit criteria:** see `M031-CONTEXT.md`. + +## Slices + +Slice detail lives in per-slice `M031-S##-PLAN.md` files, created by `ytstack:slice-milestone`. + +- [ ] S01 -- `coordinate` gets the "Factory tools" step (risk route per merge, PR watch, release watch, signals, review lessons) and a one-step rotation while lanes run. +- [ ] S02 -- `ytstack-risk route` reads the review round from the host, so a head-bound review gate can still route `unattended`. +- [ ] S03 -- SessionStart and `ytstack-upkeep` say, once and only when it applies, which factory tool is off and when the installed plugin is newer than the session's. +- [ ] S04 -- QUICKSTART "Setting up the factory tools" (greenfield, brownfield/upgrade) and an "Upgrading from 0.x" checklist. +- [ ] S05 -- `reconcile` detects a large plan outside `.ytstack/` and offers to map it into milestones and slices. + +## Run order + +S01 and S02 first (the field defects), then S03, S04 (documents what S01-S03 built), S05 last. After each slice, `ytstack:reassess-roadmap` checks if the plan still fits. + +## How to update this file + +- Flip slice checkbox `[ ]` to `[x]` when its tasks are all `summarize-task`-confirmed +- Update `completed_slices` count +- On milestone completion, flip `status: planned` to `status: done` and update global ROADMAP.md diff --git a/.ytstack/M032-CONTEXT.md b/.ytstack/M032-CONTEXT.md new file mode 100644 index 00000000..5bef1081 --- /dev/null +++ b/.ytstack/M032-CONTEXT.md @@ -0,0 +1,39 @@ +--- +milestone: M032 +project: ytstack +created: 2026-11-15T00:45:00Z +size: M +--- + +# M032 -- Context + +## Goal + +Every incident of any class (production, CI, evidence and receipts, review-caught defects, process slips of agents or the coordinator) ends in the same lesson loop: classify, route the lesson to a machine check first and a knowledge entry second, record it, and surface repeats, as a shared step no skill path can skip. + +## Exit criteria + +- One shared step (a skill or a section the paths call) that `incident` (after mitigation), `systematic-debugging` (after the root cause), `finish-lane` (when a review blocked or a check went red) and `coordinate` (on a red `main`) end with. It classifies the incident in one line, routes the lesson (test, guard, CI step or alert first; otherwise a `KNOWLEDGE.md` entry or the lane contract; never one more sentence in AGENTS.md or CLAUDE.md) and records it. +- Incidents and their lessons are records with a class and a target (reusing the signals ledger where it fits, `kind: incident` or a sibling), so a repeated class raises a count instead of a new record; a check (`ytstack-signals check` or `ytstack-lessons check`) fails when a recorded incident has no lesson with a target. +- `coordinate` shows the open-lessons count in its status; a lesson that is only a proposal goes to the person with the daily question; lesson lanes can be dispatched through the frontier. +- `retro` reports incidents per class and repeats for the window. +- Docs, CHANGELOG; all suites, checker, spec lint/drift, Codex and Kimi tests, plugin validation; an eval case for the shared step. + +## Size + +M -- 3 slices. + +## Planning input + +Issue #53 and its scope clarification: learning from incidents in general, as a standing behaviour, not only production incidents; ideally a shared step the existing skills call so no path can skip it. Eight such incidents in one coordinator day in context-mcp, several repeats of the same class. + +## Decisions locked in discuss phase + +2026-11-15: Machine check before knowledge entry; a new rule sentence in an instruction file is never the lesson (matches the `coordinate` anti-pattern). + +2026-11-15: Reuse the signals ledger and `review-lessons` patterns (class key, count, state) before adding a new record type. + +## Open questions + +- Shared step as its own skill (`lesson`) or as a section in an existing one? Plan: own skill, called by name, so the paths stay short and an eval can trigger it. +- Where the dated retro record lives: `.ytstack/signals/` next to the other kinds, or `.ytstack/archive//incident-retro.md` as the issue proposes. diff --git a/.ytstack/M032-ROADMAP.md b/.ytstack/M032-ROADMAP.md new file mode 100644 index 00000000..d4435fe3 --- /dev/null +++ b/.ytstack/M032-ROADMAP.md @@ -0,0 +1,33 @@ +--- +milestone: M032 +project: ytstack +size: M +created: 2026-11-15T00:45:00Z +status: planned +total_slices: 3 +completed_slices: 0 +--- + +# M032 Roadmap + +**Goal:** Every incident of any class ends in the same lesson loop: classify, route the lesson to a machine check first and a knowledge entry second, record it, and surface repeats, as a shared step no skill path can skip. + +**Exit criteria:** see `M032-CONTEXT.md`. + +## Slices + +Slice detail lives in per-slice `M032-S##-PLAN.md` files, created by `ytstack:slice-milestone`. + +- [ ] S01 -- Incident and lesson records with class, target and count, and a check that every incident has a lesson with a target. +- [ ] S02 -- The shared lesson step, called by `incident`, `systematic-debugging`, `finish-lane` and `coordinate`. +- [ ] S03 -- Open lessons in `coordinate`'s status and the frontier, repeats per class in `retro`. + +## Run order + +Sequential. After each slice, `ytstack:reassess-roadmap` checks if the plan still fits. + +## How to update this file + +- Flip slice checkbox `[ ]` to `[x]` when its tasks are all `summarize-task`-confirmed +- Update `completed_slices` count +- On milestone completion, flip `status: planned` to `status: done` and update global ROADMAP.md diff --git a/.ytstack/M033-CONTEXT.md b/.ytstack/M033-CONTEXT.md new file mode 100644 index 00000000..4997c379 --- /dev/null +++ b/.ytstack/M033-CONTEXT.md @@ -0,0 +1,36 @@ +--- +milestone: M033 +project: ytstack +created: 2026-11-15T00:45:00Z +size: S +--- + +# M033 -- Context + +## Goal + +Agents feed their experience with ytstack back upstream through an explicit, configurable channel: bugs, gaps and workarounds, proposals and field evidence become issues at `Yesterday-AI/ytstack` (filed by the agent or suggested to the person, per setting), without duplicates and without personal or customer data. + +## Exit criteria + +- A setting `upstream_feedback: suggest | file | off` (default `suggest`, today's behaviour) in `.ytstack/PREFERENCES.md`, with a user-level fallback in `~/.ytstack/config`; `using-ytstack`'s "Reporting ytstack issues" paragraph becomes this channel. +- The channel names what goes upstream and when: bugs; gaps and workarounds (a tool existed but was not used, or was missing); proposals from `retro`, `lane-retro`, `review-lessons` and the M032 lesson loop when the lesson concerns ytstack itself; field evidence from first real-host runs. +- Rules the agent follows, checked where a machine can: search existing issues first and comment instead of duplicating; one observation per issue with evidence (versions, commands, counts); no personal or customer data; tell the person the link in one line. +- `retro` and `lane-retro` end with an "Upstream" section filed per the setting. +- Docs, CHANGELOG; all suites, checker, Codex and Kimi tests, plugin validation; an eval case for `file` and `suggest`. + +## Size + +S -- 1 slice. + +## Planning input + +Issue #55: feedback guidance covers only misbehaving skills, as a suggestion; the person had to tell every session "file your experiences and optimization proposals there as issues, always". Issues #53, #54, #57 and #61 are themselves examples of the reports the channel should produce. + +## Decisions locked in discuss phase + +2026-11-15: Default stays `suggest`; `file` is opt-in per project or per user, because filing publishes text to a public repository. + +## Open questions + +- How the agent checks for duplicates cheaply (`gh issue list --search`), and what it does without `gh` auth (falls back to `suggest`). diff --git a/.ytstack/M033-ROADMAP.md b/.ytstack/M033-ROADMAP.md new file mode 100644 index 00000000..4a0665aa --- /dev/null +++ b/.ytstack/M033-ROADMAP.md @@ -0,0 +1,31 @@ +--- +milestone: M033 +project: ytstack +size: S +created: 2026-11-15T00:45:00Z +status: planned +total_slices: 1 +completed_slices: 0 +--- + +# M033 Roadmap + +**Goal:** Agents feed their experience with ytstack back upstream through an explicit, configurable channel (`upstream_feedback: suggest | file | off`), without duplicates and without personal or customer data. + +**Exit criteria:** see `M033-CONTEXT.md`. + +## Slices + +Slice detail lives in per-slice `M033-S##-PLAN.md` files, created by `ytstack:slice-milestone`. + +- [ ] S01 -- The `upstream_feedback` setting, the channel in `using-ytstack`, the agent rules, and an "Upstream" section in `retro` and `lane-retro`. + +## Run order + +After M032, so the lesson loop can hand ytstack-related lessons to this channel. After the slice, `ytstack:reassess-roadmap` checks if the plan still fits. + +## How to update this file + +- Flip slice checkbox `[ ]` to `[x]` when its tasks are all `summarize-task`-confirmed +- Update `completed_slices` count +- On milestone completion, flip `status: planned` to `status: done` and update global ROADMAP.md diff --git a/.ytstack/ROADMAP.md b/.ytstack/ROADMAP.md index f5fefad6..89763641 100644 --- a/.ytstack/ROADMAP.md +++ b/.ytstack/ROADMAP.md @@ -48,6 +48,9 @@ Progress legend: `[ ]` todo, `[~]` in progress, `[x]` done, `[-]` skipped. | M028 | Ship the six gstack skills as ytstack's own adaptations (DECISIONS 2026-11-14) -- self-contained `office-hours`, `plan-ceo-review`, `plan-eng-review`, `retro`, `ship`, `document-release` (no gstack install, nothing in `~/.claude/skills/`), `metadata.upstream` baselines, `bin/ytstack-gstack-diff` + release-checklist step, synced to gstack v1.99.3.0. Done 2026-11-14 (3 slices, 11 tasks); released in 0.6.0 (PRs #39, #40). M022-M024 merged with #37; M025-M027 are carried by PR #38. | **done** | 11 | 11 | | M029 | Optional PR watch (DECISIONS 2026-11-14 "PR watch ships inside ytstack as an optional, opt-in tool") -- engine in `tools/pr-watch/`, `bin/ytstack-pr-watch` (enable/disable, install-worker, migrate), Claude Code and Codex hooks that exit at once unless `pr_watch=on`, `docs/pr-watch.md`. Done 2026-11-14 (3 slices); released in 0.8.0 (PR #45), fixes in 0.8.1 and 0.8.2. | **done** | 3 | 3 | | M030 | Review lessons from bot findings -- `bin/ytstack-review-escapes` (bot thread resolution vs. own-role findings), `## Own reviewers` in `REVIEW.md`, escapes as signals of `kind: review`, skill `review-lessons` (role-file proposals for a person), escape rate in `retro`. Pilot and adoption: Yesterday-AI/context-mcp#1650. Done 2026-11-14 (3 slices); released in 0.9.0 (PR #51). | **done** | 9 | 9 | +| M031 | Factory tools explicit (issue #54 rest, #61 leftovers) -- `coordinate` "Factory tools" step and one-step rotation, `ytstack-risk route` reads the review round from the host, SessionStart/upkeep say which tool is off and when the plugin changed under the session, QUICKSTART setup guide and upgrade checklist, `reconcile` detects external plans. | planned | 0 | -- | +| M032 | Incident to lesson loop (issue #53) -- incident and lesson records with class, target and count, a shared lesson step called by `incident`, `systematic-debugging`, `finish-lane` and `coordinate`, open lessons in status and frontier, repeats in `retro`. | planned | 0 | -- | +| M033 | Upstream feedback channel (issue #55) -- `upstream_feedback: suggest / file / off`, the channel in `using-ytstack`, agent rules (search first, evidence, no personal data), "Upstream" section in `retro` and `lane-retro`. | planned | 0 | -- | **Total:** 39 tasks across M001-M009, 37 done (95%). 2 deferred to user action (git init + push, GitHub repo creation). M010 done (6/6, 2026-11-07); M011 task count pending milestone planning. diff --git a/.ytstack/STATE.md b/.ytstack/STATE.md index ec4ad10f..623c4977 100644 --- a/.ytstack/STATE.md +++ b/.ytstack/STATE.md @@ -1,14 +1,16 @@ --- project: ytstack slug: ytstack -last_updated: 2026-11-15T00:30:00Z -current_milestone: none +last_updated: 2026-11-15T00:45:00Z +current_milestone: M031 active_slice: none active_task: none --- # State +**Status (2026-11-15, planning):** M031 planned (L, 5 slices: factory tools explicit, issue #54 rest and #61 leftovers), then M032 (M, incident to lesson loop, #53) and M033 (S, upstream feedback channel, #55). Ready to slice M031. Next action: run `ytstack:slice-milestone` for M031. + **Status (2026-11-15, 0.10.0):** Release of issue #57 (PR #63, `38486b8`: `.ytstack/standing/` one file per instruction, `yt_standing`, `ytstack-check --standing`, `ytstack-risk` rule document, `coordinate` 0.3.0) and the main points of issue #61 (PRs #62, #64: skipped checks, head moved after own push, status block only on change, merge suggestion only after a bot finding). Open next: from #61 the "plugin updated, reload skills" notice and a one-step coordinator rotation; then plan the rest of #54, #53 and #55. **Status (2026-11-14, 0.9.2):** Patch release for the #54 field run (PR #59, `c737d84`): the PR watch CLI qualifies the current Claude session's bare id, `register` heals watches stored under it, `coordinate` 0.2.2 leaves `--session` out. The context-mcp coordinator needs a restart (its hooks are still 0.7.0), then `register --all-open` without `--session`. From a52933f5d514911caaf5aa455a67ed9c98b5fba7 Mon Sep 17 00:00:00 2001 From: Alex Wegener Date: Sun, 15 Nov 2026 00:45:40 +0100 Subject: [PATCH 02/55] M031-S05-T01: bin/ytstack-plans finds a plan outside .ytstack and lists its rows scan counts work rows (task lists, tables with a status or checkbox column) in plans/, roadmap/ and their docs/ variants and says when a directory is large enough to map; rows prints path:line, state, id, section and title per row. Read only. Co-Authored-By: Claude Opus 5.5 --- .ytstack/M031-S05-PLAN.md | 30 +++++ .ytstack/M031-S05-T01-PLAN.md | 48 +++++++ .ytstack/M031-S05-T01-SUMMARY.md | 39 ++++++ bin/ytstack-plans | 222 +++++++++++++++++++++++++++++++ tests/ytstack-plans.test.sh | 141 ++++++++++++++++++++ 5 files changed, 480 insertions(+) create mode 100644 .ytstack/M031-S05-PLAN.md create mode 100644 .ytstack/M031-S05-T01-PLAN.md create mode 100644 .ytstack/M031-S05-T01-SUMMARY.md create mode 100755 bin/ytstack-plans create mode 100644 tests/ytstack-plans.test.sh diff --git a/.ytstack/M031-S05-PLAN.md b/.ytstack/M031-S05-PLAN.md new file mode 100644 index 00000000..ccb5b48b --- /dev/null +++ b/.ytstack/M031-S05-PLAN.md @@ -0,0 +1,30 @@ +--- +milestone: M031 +slice: S05 +project: ytstack +created: 2026-11-15T09:00:00Z +status: in-progress +task_count: 3 +completed_tasks: 1 +--- + +# M031-S05 -- Slice Plan + +**Goal:** `reconcile` (and `adopt-brownfield` on such a repo) detects a large plan outside `.ytstack/` and offers to map its open rows into milestones and slices, so `ytstack-frontier` sees it. The external plan is never edited. + +**Blocked by:** none + +## Tasks + +- [x] T01 -- `bin/ytstack-plans`: `scan` finds plan directories (`plans/`, `plan/`, `planning/`, `roadmap/` and the same under `docs/`), counts work rows (task-list items and rows of tables with a status or checkbox column) as open, done or dropped, applies the thresholds and reads a recorded answer from `PREFERENCES.md`; `rows` prints one line per work row with `path:line`, state, id, section and title. `tests/ytstack-plans.test.sh` first. +- [ ] T02 -- The question and the mapping: `docs/ux/external-plans.md` (thresholds, mapping rules, pointer format, answer record); `reconcile` gets the class "External plan" (preamble line, one AskUserQuestion, the mapping after a yes); `adopt-brownfield` asks the same question after its artifacts exist. Preamble suite covers the new line. +- [ ] T03 -- Docs and checks: spec areas (`artifacts`, `checks-and-evals`), README tools list, the eval case `evals/external-plan/` with its README row, a `DECISIONS.md` entry for "script detects, agent maps". + +## Done when + +All tasks marked `[x]` and verified via `ytstack:summarize-task`. + +## Notes + +- Source: issue #54 point 5. Real example (read only, never written): `meinkontext/plans/`, 80 files, tables `| Done | ID | Deliverable | Gate | Can start | State |` with `[x]`/`[ ]` and task lists of several hundred items; frontier saw nothing and lanes were tracked by hand. +- The slice does not touch `hooks/lib/git-ctx.sh` (S03 works in the hooks); the detection lives in its own script that both skills call. diff --git a/.ytstack/M031-S05-T01-PLAN.md b/.ytstack/M031-S05-T01-PLAN.md new file mode 100644 index 00000000..0b1e3ce6 --- /dev/null +++ b/.ytstack/M031-S05-T01-PLAN.md @@ -0,0 +1,48 @@ +--- +milestone: M031 +slice: S05 +task: T01 +project: ytstack +created: 2026-11-15T09:05:00Z +status: done +--- + +# M031-S05-T01 -- Task Plan + +**Summary:** `bin/ytstack-plans` finds a plan outside `.ytstack/` from cheap local evidence (`scan`) and lists its work rows with a pointer each (`rows`). Read only. + +## Files + +- Create: `bin/ytstack-plans` +- Create: `tests/ytstack-plans.test.sh` + +## What this does + +`scan` looks at a fixed list of directories relative to the repository root: `plans`, `plan`, `planning`, `roadmap`, `docs/plans`, `docs/plan`, `docs/planning`, `docs/roadmap`. It reads every `*.md` up to three levels deep in one `awk` pass and counts work rows: + +- a task-list item (`- [ ]`, `- [x]`, also `*` and `+`); +- a data row of a Markdown table whose header names a status column (`Status`, `State`, `Done`, `Progress`, `Stand`, `Erledigt`) or whose first data row has a checkbox cell (`[ ]`, `[x]`). + +Fenced code blocks are skipped. A row's state: `done` (`[x]`, or a status cell starting with done, merged, complete, shipped, closed, finished, landed, released, erledigt, fertig or a check mark), `dropped` (dropped, cancelled, superseded, obsolete, wontfix, skipped, abandoned), else `open`. A file is a plan file with at least 3 work rows. A directory is `large` when its plan files hold at least 10 open rows (`YTSTACK_PLAN_MIN_OPEN` overrides). The answer recorded in `PREFERENCES.md` (`external_plans: mapped|declined `, one line per directory) is reported per directory. + +Output: one line per directory with plan files, `dir=plans files=12 open=340 done=820 verdict=large answer=none`; `no external plan` when there is none. Exit 0 when at least one directory is `large` with `answer=none` (there is something to offer), 1 otherwise, 64 on usage. + +`rows [--open] [PATH...]` prints one line per work row, tab separated: `path:line`, state, id (the `ID`-like column, else `-`), section (the nearest heading above), title (the deliverable-like column, else the first other cell, at most 100 characters). Without PATH: the plan files of every candidate directory. `-C DIR` like the other scripts. + +## Spec impact + +- checks-and-evals: Behavior -- a line on `bin/ytstack-plans`, path list (done in T03) + +## Verification + +```bash +/bin/bash tests/ytstack-plans.test.sh +``` + +Runs: once. Environment: local checkout (macOS, bash 3.2). + +Success: the suite ends with ` passed, 0 failed`; a run on the read-only real example (`meinkontext`) reports `verdict=large` for `plans` and leaves its files unchanged (checksums before and after). + +## Done signal + +Run `/ytstack:summarize-task` after execution to mark complete and advance STATE.md. diff --git a/.ytstack/M031-S05-T01-SUMMARY.md b/.ytstack/M031-S05-T01-SUMMARY.md new file mode 100644 index 00000000..2a1c4979 --- /dev/null +++ b/.ytstack/M031-S05-T01-SUMMARY.md @@ -0,0 +1,39 @@ +--- +milestone: M031 +slice: S05 +task: T01 +project: ytstack +closed: 2026-11-15T09:40:00Z +verification: passed +--- + +# M031-S05-T01 -- Summary + +## Commits + +- The commit that carries this file (`M031-S05-T01: bin/ytstack-plans finds a plan outside .ytstack and lists its rows`). + +## Outcome + +`bin/ytstack-plans` was written test-first. `scan` looks at eight fixed directories (`plans`, `plan`, `planning`, `roadmap` and the same under `docs/`), reads their `*.md` files up to three levels deep in one `awk` pass and prints one line per directory with plan files: files, open and done rows, `verdict=large|small` and the answer `PREFERENCES.md` records. It exits 0 only when a large directory has no answer yet, so a skill preamble can branch on the exit code. `rows` prints `path:line`, state, id, section and title per work row; `--open` filters, a PATH lists one file or directory in full. Work rows are task-list items and data rows of tables with a status or checkbox column; tables without one (comparisons, cost tables) and fenced code are not counted. Nothing is written. + +Thresholds: a file is a plan file from 3 work rows; a directory is large from 10 open rows (`YTSTACK_PLAN_MIN_OPEN`). + +## Deviations from plan + +- The header word `Step` is not an id column: a two-column table `| Step | Status |` would otherwise lose its title. +- `ok`, `yes` and a bare `x` are not read as done; they appear as free text in status cells too often. + +## Follow-ups + +- Task-list items under a work package that a board row marks done stay `open` (the real example ticks the board, not the checklist). The mapping rules in T02 tell the agent to map from the board when a file has one. + +## Spec + +- checks-and-evals: updated in T03 (path list and the script's behavior line) + +## Verification + +Command: `/bin/bash tests/ytstack-plans.test.sh` -- exit 0, last line `32 passed, 0 failed` (macOS bash 3.2.57; also under the default bash). + +Real example, read only: `bin/ytstack-plans -C .../meinkontext scan` printed `dir=plans files=23 open=1467 done=462 verdict=large answer=none`, exit 0, in 0.4 s. `rows` listed the board rows of the AV-08 package plan with their ids (70 open). A `cksum` over every file under its `plans/` was identical before and after. diff --git a/bin/ytstack-plans b/bin/ytstack-plans new file mode 100755 index 00000000..b919fdaa --- /dev/null +++ b/bin/ytstack-plans @@ -0,0 +1,222 @@ +#!/usr/bin/env bash +# ytstack plans: a plan that lives outside .ytstack/, which ytstack-frontier +# cannot see. Read only: no plan file is ever written. +# Format, thresholds and the mapping: docs/ux/external-plans.md. +# +# ytstack-plans [-C DIR] scan +# ytstack-plans [-C DIR] rows [--open] [PATH...] +# +# scan one line per candidate directory that holds plan files: +# dir= files= open= done= verdict=large|small answer=none|mapped|declined +# "no external plan" when no candidate directory holds one. +# Candidates (relative to the repository root): plans plan planning roadmap +# docs/plans docs/plan docs/planning docs/roadmap; *.md up to 3 levels deep. +# A plan file has at least 3 work rows. A directory is large at +# YTSTACK_PLAN_MIN_OPEN open rows (default 10). The answer comes from +# "external_plans: mapped|declined " lines in PREFERENCES.md. +# rows one line per work row, tab separated: path:line, state (open, done, +# dropped), id (an ID-like column, else -), section (nearest heading, +# else -), title (at most 100 characters). Without PATH: the plan files +# of every candidate directory; a PATH (file or directory) is listed in +# full. --open keeps the open rows. +# +# Work rows: task-list items (- [ ], * [x], + [X]) and the data rows of a +# Markdown table whose header names a status column (Status, State, Done, +# Progress, Stand, Erledigt) or whose first data row has a checkbox cell. +# Fenced code blocks are skipped. +# +# Exit codes +# scan 0 at least one large directory without an answer; 1 otherwise +# rows 0 +# 64 usage, or -C names no directory + +set -uo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +. "$ROOT/hooks/lib/git-ctx.sh" + +CANDIDATES="plans plan planning roadmap docs/plans docs/plan docs/planning docs/roadmap" +MIN_FILE_ROWS=3 +MIN_OPEN=${YTSTACK_PLAN_MIN_OPEN:-10} +case "$MIN_OPEN" in ''|*[!0-9]*) MIN_OPEN=10 ;; esac + +usage() { sed -n '5,6p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; } + +DIR="$PWD" +if [ "${1:-}" = "-C" ]; then DIR="${2:-}"; shift 2 || true; fi +CMD="${1:-}" +case "$CMD" in + scan|rows) shift ;; + -h|--help|help) usage; exit 0 ;; + *) usage >&2; exit 64 ;; +esac +[ -d "$DIR" ] || { echo "ytstack-plans: -C '$DIR' is not a directory" >&2; exit 64; } + +yt_git_ctx "$DIR" +yt_resolve_yt_dir >/dev/null +TOP="${YT_TOPLEVEL:-$DIR}" +cd "$TOP" || exit 64 + +# md_files : the Markdown files of a directory, sorted, relative to TOP. +md_files() { + find "$1" -maxdepth 3 -type f -name '*.md' -not -path '*/node_modules/*' 2>/dev/null | LC_ALL=C sort +} + +# work_rows : one line per work row (format of "rows"). +work_rows() { + [ $# -gt 0 ] || return 0 + awk ' + function trim(s) { gsub(/^[ \t]+|[ \t]+$/, "", s); return s } + function clean(s) { s = trim(s); gsub(/\*\*|__|`/, "", s); return trim(s) } + function cells(line, arr, n, i) { + line = trim(line); sub(/^\|/, "", line); sub(/\|$/, "", line) + n = split(line, arr, "|") + for (i = 1; i <= n; i++) arr[i] = clean(arr[i]) + return n + } + function is_sep(line) { return line ~ /^[ \t]*\|?[ \t]*:?-+:?[ \t]*(\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$/ } + function state(s, l) { + l = tolower(clean(s)) + if (l ~ /^\[x\]/) return "done" + if (l ~ /^\[ \]/) return "open" + if (l ~ /^(done|merged|complete|completed|shipped|closed|finished|landed|released|erledigt|fertig)([^a-z]|$)/) return "done" + if (index(s, "✅") == 1 || index(s, "✓") == 1 || index(s, "✔") == 1 || index(s, "☑") == 1) return "done" + if (l ~ /^(dropped|cancel|superseded|obsolete|wontfix|won.t|skipped|abandoned|verworfen)/ || index(s, "❌") == 1 || l ~ /^~~/) return "dropped" + return "open" + } + function emit(st, id, title) { + gsub(/\t/, " ", title); title = clean(title) + if (length(title) > 100) title = substr(title, 1, 97) "..." + print FILENAME ":" FNR "\t" st "\t" (id == "" ? "-" : id) "\t" (sec == "" ? "-" : sec) "\t" (title == "" ? "-" : title) + } + FNR == 1 { fence = 0; tbl = 0; pend = ""; sec = "" } + /^[ \t]*(```|~~~)/ { fence = !fence; tbl = 0; pend = ""; next } + fence { next } + /^#+[ \t]/ { + s = $0; sub(/^#+[ \t]+/, "", s); sub(/[ \t]+#+[ \t]*$/, "", s) + sec = clean(s); gsub(/\t/, " ", sec); tbl = 0; pend = ""; next + } + /^[ \t]*[-*+][ \t]+\[[ xX]\]([ \t]|$)/ { + t = $0; sub(/^[ \t]*[-*+][ \t]+/, "", t) + emit(t ~ /^\[[xX]\]/ ? "done" : "open", "", substr(t, 4)) + tbl = 0; pend = ""; next + } + /^[ \t]*\|/ { + if (tbl == 3) next + if (tbl == 1 || tbl == 2) { + n = cells($0, c) + if (tbl == 1) { + if (!scol) for (i = 1; i <= n; i++) if (c[i] ~ /^\[[ xX]\]$/) { scol = i; break } + if (!scol) { tbl = 3; next } + tbl = 2 + } + title = "" + if (tcol) title = c[tcol] + else for (i = 1; i <= n; i++) if (i != scol && i != icol && c[i] != "") { title = c[i]; break } + emit(state(c[scol]), icol ? c[icol] : "", title) + next + } + if (pend != "" && is_sep($0)) { + n = cells(pend, h); scol = 0; icol = 0; tcol = 0 + for (i = 1; i <= n; i++) { + l = tolower(h[i]) + if (!scol && l ~ /^(status|state|done|progress|stand|erledigt)$/) scol = i + else if (!icol && l ~ /^(id|ref|key|#|no\.?|nr\.?|wp|lane|ticket|issue)$/) icol = i + else if (!tcol && l ~ /^(deliverable|title|task|description|what|name|item|scope|goal|work|work package|package|summary|change|outcome)$/) tcol = i + } + tbl = 1; pend = ""; next + } + pend = $0; next + } + { tbl = 0; pend = "" } + ' "$@" +} + +# answer : what PREFERENCES.md records for the directory. +answer() { + local a="" + if [ -n "$YT_DIR" ] && [ -f "$YT_DIR/PREFERENCES.md" ]; then + a=$(YTP_DIR="$1" awk ' + /^[ \t]*external_plans[ \t]*:/ { + sub(/^[ \t]*external_plans[ \t]*:[ \t]*/, "") + d = $1; sub(/\/$/, "", d) + if (d == ENVIRON["YTP_DIR"] && ($2 == "mapped" || $2 == "declined")) { print $2; exit } + } + ' "$YT_DIR/PREFERENCES.md") + fi + printf '%s' "${a:-none}" +} + +cmd_scan() { + [ $# -eq 0 ] || { usage >&2; return 64; } + local d line any="" offer="" files ans verdict + for d in $CANDIDATES; do + [ -d "$d" ] || continue + files=$(md_files "$d") + [ -n "$files" ] || continue + # shellcheck disable=SC2086 -- the paths come from find under fixed names + line=$(IFS=' +'; work_rows $files | awk -F'\t' -v min="$MIN_FILE_ROWS" ' + { f = $1; sub(/:[0-9]+$/, "", f); n[f]++; s[f, $2]++ } + END { + for (f in n) if (n[f] >= min) { k++; o += s[f, "open"]; dn += s[f, "done"] } + print k + 0, o + 0, dn + 0 + }') + set -- $line + [ "${1:-0}" -gt 0 ] || continue + verdict=small; [ "$2" -ge "$MIN_OPEN" ] && verdict=large + ans=$(answer "$d") + echo "dir=$d files=$1 open=$2 done=$3 verdict=$verdict answer=$ans" + any=1 + [ "$verdict" = large ] && [ "$ans" = none ] && offer=1 + done + [ -n "$any" ] || echo "no external plan" + [ -n "$offer" ] +} + +cmd_rows() { + local open="" d p files="" plan + while [ $# -gt 0 ]; do + case "$1" in + --open) open=1; shift ;; + --) shift; break ;; + -*) usage >&2; return 64 ;; + *) break ;; + esac + done + if [ $# -gt 0 ]; then + for p in "$@"; do + p=${p%/} + if [ -d "$p" ]; then files="$files$(md_files "$p") +" + elif [ -f "$p" ]; then files="$files$p +" + else echo "ytstack-plans: no such file or directory: $p" >&2; return 64 + fi + done + plan=all + else + for d in $CANDIDATES; do + [ -d "$d" ] && files="$files$(md_files "$d") +" + done + plan=only + fi + # shellcheck disable=SC2086 + (IFS=' +'; work_rows $files) | awk -F'\t' -v min="$MIN_FILE_ROWS" -v plan="$plan" -v open="$open" ' + { f = $1; sub(/:[0-9]+$/, "", f); file[NR] = f; row[NR] = $0; st[NR] = $2; n[f]++ } + END { + for (i = 1; i <= NR; i++) { + if (plan == "only" && n[file[i]] < min) continue + if (open != "" && st[i] != "open") continue + print row[i] + } + }' + return 0 +} + +case "$CMD" in + scan) cmd_scan "$@" ;; + rows) cmd_rows "$@" ;; +esac diff --git a/tests/ytstack-plans.test.sh b/tests/ytstack-plans.test.sh new file mode 100644 index 00000000..cd7d768a --- /dev/null +++ b/tests/ytstack-plans.test.sh @@ -0,0 +1,141 @@ +#!/usr/bin/env bash +# Tests for bin/ytstack-plans: a plan outside .ytstack/ (format and thresholds: +# docs/ux/external-plans.md). +# +# Contract: +# scan one line per candidate directory with plan files: files, open, done, +# verdict (large at >= 10 open rows, YTSTACK_PLAN_MIN_OPEN overrides) +# and the answer recorded in PREFERENCES.md; exit 0 only when a large +# directory has no answer yet; "no external plan" and exit 1 otherwise +# rows path:line, state, id, section, title per work row; the line number +# points at the row; --open keeps the open ones +# work task-list items and rows of tables with a status or checkbox column; +# a table without one and anything in a code fence is not counted +# read the plan files are byte-identical after every call +# usage unknown command or a -C that is no directory: exit 64 +# +# Run: /bin/bash tests/ytstack-plans.test.sh (exit 0 = all pass; macOS bash 3.2) + +set -uo pipefail + +ROOT="$(cd "$(dirname "$0")/.." && pwd -P)" +BIN="$ROOT/bin/ytstack-plans" + +PASS=0; FAIL=0 +ok() { PASS=$((PASS+1)); echo " ok - $1"; } +bad() { FAIL=$((FAIL+1)); echo " FAIL - $1${2:+ ($2)}"; } +eq() { if [ "$2" = "$3" ]; then ok "$1"; else bad "$1" "expected '$2' got '$3'"; fi; } +has() { case "$3" in *"$2"*) ok "$1" ;; *) bad "$1" "no '$2' in: $3" ;; esac; } +hasnt() { case "$3" in *"$2"*) bad "$1" "unexpected '$2' in: $3" ;; *) ok "$1" ;; esac; } + +if [ ! -x "$BIN" ]; then + bad "bin/ytstack-plans exists and is executable" + echo "$PASS passed, $FAIL failed" + exit 1 +fi + +TMP=$(mktemp -d "${TMPDIR:-/tmp}/ytplans.XXXXXX"); TMP=$(cd "$TMP" && pwd -P) +trap 'rm -rf "$TMP"' EXIT +TAB=' ' + +run() { local d="$1"; shift; OUT=$(bash "$BIN" -C "$d" "$@" 2>&1); EC=$?; } +new_repo() { + local d="$TMP/$1" + mkdir -p "$d/.ytstack" + ( cd "$d" && git init -q -b main && git config user.email t@t.t && git config user.name t ) + printf -- '---\nproject: acme\ncurrent_milestone: none\n---\n\n# State\n' > "$d/.ytstack/STATE.md" + echo "$d" +} +sums() { find "$1" -type f -name '*.md' | sort | while read -r f; do cksum "$f"; done; } + +echo "== no plan directory" +R=$(new_repo empty) +run "$R" scan +eq "no plan -> exit 1" 1 "$EC" +has "no plan -> says so" "no external plan" "$OUT" + +echo "== a large plan in plans/" +R=$(new_repo big) +mkdir -p "$R/plans/sub" "$R/notes" +{ + printf '# v2 work packages\n\n## Board\n\n' + printf '| Done | ID | Deliverable | Gate | State |\n| --- | --- | --- | --- | --- |\n' + printf '| [x] | AV-01 | Toolchain bump | E | Merged #12 |\n' + printf '| [x] | AV-02 | Contract emit | E | Merged #13 |\n' + i=3; while [ $i -le 10 ]; do printf '| [ ] | AV-%02d | Package %d | AV-01 | open |\n' $i $i; i=$((i+1)); done + printf '\n## Comparison\n\n| Option | Cost |\n|---|---|\n| A | 1 |\n| B | 2 |\n| C | 3 |\n' + printf '\n```markdown\n- [ ] not a task, inside a fence\n| [ ] | AV-99 | fenced | x | open |\n```\n' +} > "$R/plans/2026-10-29-v2-packages.md" +{ + printf '# Teardown\n\n## Steps\n\n' + printf -- '- [ ] Remove the old bucket\n- [x] Snapshot the data\n* [ ] Switch DNS\n+ [X] Announce\n' +} > "$R/plans/sub/teardown.md" +printf '# Ideas\n\n- [ ] one\n- [ ] two\n' > "$R/plans/ideas.md" +{ + printf '# Status table\n\n| Step | Status |\n|---|---|\n| Migrate | done |\n| Backfill | Superseded by AV-04 |\n| Verify | in progress |\n| Cut over | ✅ |\n' +} > "$R/plans/status.md" +printf -- '- [ ] a\n- [ ] b\n- [ ] c\n- [ ] d\n- [ ] e\n- [ ] f\n- [ ] g\n- [ ] h\n- [ ] i\n- [ ] j\n- [ ] k\n' > "$R/notes/todo.md" +BEFORE=$(sums "$R/plans") +run "$R" scan +eq "large, unanswered -> exit 0" 0 "$EC" +# open: 8 (table) + 2 (teardown) + 1 (status: in progress) = 11; ideas.md has 2 rows (< 3, no plan file) +# done: 2 + 2 + 2 = 6 +has "dir line" "dir=plans files=3 open=11 done=6 verdict=large answer=none" "$OUT" +hasnt "notes/ is no candidate directory" "notes" "$OUT" + +run "$R" rows +has "rows: table row with id, section, title" "plans/2026-10-29-v2-packages.md:9${TAB}open${TAB}AV-03${TAB}Board${TAB}Package 3" "$OUT" +has "rows: done row" "${TAB}done${TAB}AV-01${TAB}Board${TAB}Toolchain bump" "$OUT" +has "rows: task item without id" "plans/sub/teardown.md:5${TAB}open${TAB}-${TAB}Steps${TAB}Remove the old bucket" "$OUT" +has "rows: capital X is done" "${TAB}done${TAB}-${TAB}Steps${TAB}Announce" "$OUT" +has "rows: superseded is dropped" "${TAB}dropped${TAB}-${TAB}Status table${TAB}Backfill" "$OUT" +has "rows: check mark is done" "${TAB}done${TAB}-${TAB}Status table${TAB}Cut over" "$OUT" +hasnt "rows: fenced content skipped" "AV-99" "$OUT" +hasnt "rows: fenced task skipped" "inside a fence" "$OUT" +hasnt "rows: table without status column skipped" "Comparison" "$OUT" +hasnt "rows: file below 3 rows is no plan file" "ideas.md" "$OUT" +# the pointer points at the row +LN=$(printf '%s\n' "$OUT" | awk -F'\t' '$3 == "AV-07" { split($1, a, ":"); print a[2] }') +has "rows: line number points at the row" "AV-07" "$(sed -n "${LN:-0}p" "$R/plans/2026-10-29-v2-packages.md")" + +run "$R" rows --open +hasnt "rows --open: no done rows" "${TAB}done${TAB}" "$OUT" +hasnt "rows --open: no dropped rows" "${TAB}dropped${TAB}" "$OUT" +N=$(printf '%s\n' "$OUT" | grep -c .) +eq "rows --open: 11 open rows" 11 "$N" + +run "$R" rows plans/ideas.md +has "rows PATH: an explicit file is listed even below 3 rows" "plans/ideas.md:3${TAB}open${TAB}-${TAB}Ideas${TAB}one" "$OUT" + +eq "plan files unchanged" "$BEFORE" "$(sums "$R/plans")" + +echo "== thresholds and answers" +R2=$(new_repo small) +mkdir -p "$R2/docs/plans" +printf '# Small\n\n- [ ] a\n- [ ] b\n- [ ] c\n- [x] d\n' > "$R2/docs/plans/small.md" +run "$R2" scan +eq "small -> exit 1" 1 "$EC" +has "small -> verdict small" "dir=docs/plans files=1 open=3 done=1 verdict=small answer=none" "$OUT" +OUT=$(YTSTACK_PLAN_MIN_OPEN=3 bash "$BIN" -C "$R2" scan 2>&1); EC=$? +eq "YTSTACK_PLAN_MIN_OPEN=3 -> exit 0" 0 "$EC" +has "YTSTACK_PLAN_MIN_OPEN=3 -> large" "verdict=large" "$OUT" + +printf '# Preferences\n\nexternal_plans: plans declined 2026-11-15\n' > "$R/.ytstack/PREFERENCES.md" +run "$R" scan +eq "declined -> exit 1" 1 "$EC" +has "declined -> reported" "verdict=large answer=declined" "$OUT" +printf '# Preferences\n\nexternal_plans: docs/plans declined 2026-11-15\nexternal_plans: plans mapped 2026-11-15\n' > "$R/.ytstack/PREFERENCES.md" +run "$R" scan +eq "mapped -> exit 1" 1 "$EC" +has "mapped -> reported per directory" "answer=mapped" "$OUT" + +echo "== from a subdirectory and usage" +OUT=$(cd "$R/plans/sub" && bash "$BIN" scan 2>&1); EC=$? +has "runs from a subdirectory of the repository" "dir=plans files=3" "$OUT" +run "$R" frobnicate +eq "unknown command -> 64" 64 "$EC" +OUT=$(bash "$BIN" -C "$TMP/nope" scan 2>&1); EC=$? +eq "-C to a missing directory -> 64" 64 "$EC" + +echo "$PASS passed, $FAIL failed" +[ "$FAIL" -eq 0 ] From f05852cf7cfb529772d78b71381dcaf78be01cb7 Mon Sep 17 00:00:00 2001 From: Alex Wegener Date: Sun, 15 Nov 2026 00:47:41 +0100 Subject: [PATCH 03/55] M031-S01-T01: ytstack-pr-watch handover hands a session's watches to its successor register refuses a PR another session owns, so a coordinator that rotates to a fresh session left its watches behind (issue #61). handover --from [--to ] moves the watches, the undelivered notices (not a Codex notice already in flight), the branch bindings and the candidates, and records the successor in meta (handover:). register follows that chain, so a PR a still-running subagent of the old session opens later is registered to the successor. Co-Authored-By: Claude Opus 5.5 --- .ytstack/M031-S01-PLAN.md | 30 +++++++ .ytstack/M031-S01-T01-PLAN.md | 51 +++++++++++ .ytstack/M031-S01-T01-SUMMARY.md | 38 ++++++++ .ytstack/spec/checks-and-evals.md | 2 +- .ytstack/spec/hooks-and-state.md | 2 +- bin/ytstack-pr-watch | 1 + docs/pr-watch.md | 24 ++++++ tests/pr_watch/test_handover.py | 139 ++++++++++++++++++++++++++++++ tools/pr-watch/pr-watch.py | 23 ++++- tools/pr-watch/prwatch/state.py | 37 ++++++++ 10 files changed, 343 insertions(+), 4 deletions(-) create mode 100644 .ytstack/M031-S01-PLAN.md create mode 100644 .ytstack/M031-S01-T01-PLAN.md create mode 100644 .ytstack/M031-S01-T01-SUMMARY.md create mode 100644 tests/pr_watch/test_handover.py diff --git a/.ytstack/M031-S01-PLAN.md b/.ytstack/M031-S01-PLAN.md new file mode 100644 index 00000000..0827f99e --- /dev/null +++ b/.ytstack/M031-S01-PLAN.md @@ -0,0 +1,30 @@ +--- +milestone: M031 +slice: S01 +project: ytstack +created: 2026-11-14T23:45:00Z +status: in-progress +task_count: 3 +completed_tasks: 1 +--- + +# M031-S01 -- Slice Plan + +**Goal:** A coordinator uses the shipped factory tools without being told (route before every merge, PR watch or `ytstack-watch`, release watch, signals, review lessons), and it can rotate to a fresh session in one step while lanes run, its PR watches going with it. + +**Blocked by:** none + +## Tasks + +- [x] T01 -- PR watch handover: `ytstack-pr-watch handover --from SESSION [--to SESSION]` moves every watch, undelivered notice, branch binding and candidate of the old session to the new one (default: the current session) and forwards later registrations for the old session to the new one. Unittests in `tests/pr_watch/test_handover.py`, `docs/pr-watch.md`, the `hooks-and-state` and `checks-and-evals` area files. +- [ ] T02 -- `coordinate` Step 7 becomes "Factory tools": one table with command, when and when skipped for the route (`ytstack-finish-lane route`, or `ytstack-risk route` for a merge outside the lanes, also when this session merges itself), the PR watch registration or `ytstack-watch`, `ytstack-watch release` after every merge to production, `signal-intake` / `incident`, `review-lessons` after a merge with a bot finding. The PR watch text of Step 7 is unified, not repeated. A test in `tests/skill-preambles.test.sh` checks that every `ytstack-*` command the step names exists with that subcommand. `skills` area file. +- [ ] T03 -- `coordinate` Step 12 rotates in one step while lanes run: handoff written from the files with the PR watch session, the background watches and every running worker's address; the successor's Step 3 runs `ytstack-pr-watch handover --from `; the old session stays open only as a relay for its workers' reports. `docs/ux/coordinator-format.md` "Rotation", test assertions, `skills` area file. + +## Done when + +All tasks marked `[x]` and verified via `ytstack:summarize-task`. + +## Notes + +- Sources: issue #54 point 1 and "coordinate: an explicit Factory tools step"; issue #61, the last smaller observation (rotation after one compaction is not followable under load). +- No renumbering: the factory tools take Step 7, which already held the PR watch and the release watch; no doc outside the skill cites a coordinate step number. diff --git a/.ytstack/M031-S01-T01-PLAN.md b/.ytstack/M031-S01-T01-PLAN.md new file mode 100644 index 00000000..47b058ff --- /dev/null +++ b/.ytstack/M031-S01-T01-PLAN.md @@ -0,0 +1,51 @@ +--- +milestone: M031 +slice: S01 +task: T01 +project: ytstack +created: 2026-11-14T23:46:00Z +status: done +--- + +# M031-S01-T01 -- Task Plan + +**Summary:** `ytstack-pr-watch handover --from SESSION [--to SESSION]` hands every PR watch of a session to its successor and forwards what still arrives for the old session. + +## Files + +- Modify: `tools/pr-watch/prwatch/state.py` +- Modify: `tools/pr-watch/pr-watch.py` +- Modify: `bin/ytstack-pr-watch` (usage header) +- Create: `tests/pr_watch/test_handover.py` +- Modify: `docs/pr-watch.md` +- Modify: `.ytstack/spec/hooks-and-state.md`, `.ytstack/spec/checks-and-evals.md` + +## What this does + +`register` refuses a PR another session owns, so a coordinator that rotates to a fresh session today loses its watches: the successor's `register --all-open` skips all of them by name. `handover` moves, in one transaction: + +- every watch of `--from` to `--to`; +- the notices of `--from` that are not delivered, not cancelled and not in flight to Codex (no `dispatch_id`), so they reach the successor; +- the branch bindings and candidates of `--from` (a PR opened later on a lane's branch is adopted for the successor); +- and it writes `handover:` = `` into `meta`. `register` follows that pointer (to its end, cycle-safe), so a PR a still-running subagent of the old session opens after the handover is registered to the successor. A handover to a session clears that session's own pointer, so handing back works. The successor's `surface:` fingerprint is reset so its next prompt shows the block. + +`--to` defaults to the current session like `register --session`. A bare id equal to the current Claude session is qualified. `--from` equal to `--to` is a usage error. The output names the moved PRs and the counts; a session with nothing to move still gets the forward and exit 0. + +## Spec impact + +- hooks-and-state: Behavior -- the `pr-watch` paragraph names `handover` and the forward in `register` +- checks-and-evals: Behavior -- the `tests/pr-watch.test.sh` line names `test_handover.py` + +## Verification + +```bash +python3 -m unittest discover -s tests/pr_watch -p 'test_*.py' && bash tests/pr-watch.test.sh +``` + +Runs: once. Environment: local checkout (macOS). + +Success: exit 0 for both; the unittest run reports `OK`. + +## Done signal + +Run `/ytstack:summarize-task` after execution to mark complete and advance STATE.md. diff --git a/.ytstack/M031-S01-T01-SUMMARY.md b/.ytstack/M031-S01-T01-SUMMARY.md new file mode 100644 index 00000000..34c15ea5 --- /dev/null +++ b/.ytstack/M031-S01-T01-SUMMARY.md @@ -0,0 +1,38 @@ +--- +milestone: M031 +slice: S01 +task: T01 +project: ytstack +closed: 2026-11-14T23:58:00Z +verification: passed +--- + +# M031-S01-T01 -- Summary + +## Commits + +- The commit that carries this file (`M031-S01-T01: ytstack-pr-watch handover hands a session's watches to its successor`). + +## Outcome + +`ytstack-pr-watch handover --from SESSION [--to SESSION]` was added. It moved every watch of the old session to the new one (default: the current session), with the notices not delivered yet, the branch bindings and the candidates, reset the new session's status fingerprint and wrote `meta` key `handover:`. `register` followed that chain, so a PR that a still-running subagent of the old session opened after the handover was registered to the successor; the CLI's `register` output named the successor too. A handover back to an earlier session made it the owner again, and a chain of three was followed. `tests/pr_watch/test_handover.py` pins it in seven cases. + +## Deviations from plan + +- A Codex notice with a `dispatch_id` stays with the old session: its turn may already have started, and the outbox never sends a notice twice. +- `--from` equal to the current Claude session's bare id is qualified like `--to`, so the old session can also hand over to a known successor id itself. + +## Follow-ups + +- The old session's own hooks still write bindings under its id after the handover; they are harmless (registration follows the chain) and are not cleaned up. + +## Spec + +- hooks-and-state: the `pr-watch` paragraph names `handover` and the chain in `register` +- checks-and-evals: the `tests/pr-watch.test.sh` line names `test_handover.py` + +## Verification + +Command: `python3 -m unittest discover -s tests/pr_watch -p 'test_*.py' && bash tests/pr-watch.test.sh` -- unittest `Ran 85 tests`, `OK`; the shell suite exit 0, last line `60 passed, 0 failed`, at the working tree on top of `fe4a739` in the local checkout (macOS, Python 3.13.7). The new file was red first (6 errors of 7 cases) before the engine change. + +Not checked: the handover against a live worker and a real Claude Code session (the worker's discovery path is covered through `register`, which it calls). diff --git a/.ytstack/spec/checks-and-evals.md b/.ytstack/spec/checks-and-evals.md index f0b411e2..ec4050de 100644 --- a/.ytstack/spec/checks-and-evals.md +++ b/.ytstack/spec/checks-and-evals.md @@ -96,7 +96,7 @@ Everything that tells a contributor whether a change is acceptable: the static c - Plain bash, no framework. A suite prints one line per assertion and ends with its pass and fail count; fixtures live in `mktemp` directories. The comment at the top of each file states the contract it pins. - `tests/run-all.sh` runs every suite from a neutral temporary directory and prints `PASS` or `FAIL` per suite with that suite's last line. It stops at the first failing suite, prints up to ten of its `FAIL` lines and exits 1. The last line is `ALL SUITES PASSED` or `SUITE FAILURE`. `--linux` runs the same inside an `alpine/git` container with the repository mounted read-only; without a working Docker daemon it prints a skip line and exits 0. - `tests/ytstack-check.test.sh` tests the checker on a copy of the plugin tree. `tests/ytstack-spec.test.sh` tests `bin/ytstack-spec` on fixture repositories, one case per rule. `tests/ytstack-brief.test.sh` does the same for `bin/ytstack-brief` and compares the rendered contract with the real `skills/minimal-code/SKILL.md`. `tests/evidence-rule.test.sh` pins the evidence reuse rule: the verifier, the dispatcher and the skills area reuse a PASS only for the same commit, and its git fixture shows why (an unchanged planned file, a changed imported helper, a failing check). -- `tests/pr-watch.test.sh` runs the PR watch engine's `unittest` suite (`tests/pr_watch/`, standard library, `gh` and the Codex daemon mocked) and then shell cases for `hooks/pr-watch` (off, on, malformed input), `bin/ytstack-pr-watch` (enable/disable, install-worker and migrate plans, migrate copy, the worker launcher's engine choice; `register --all-open` is covered in `tests/pr_watch/test_register_all.py`, the `claude:` qualification of a bare session id in `test_session_spelling.py`, skipped checks, a moved head (with `remote_head` against a real temporary repository), the once-per-change status block and the merge suggestion in `test_under_load.py`) under a temporary HOME. The resolver rule of `bin/ytstack-check` exempts `hooks/pr-watch` by name (`_HOOKS_WITHOUT_RESOLVER`). +- `tests/pr-watch.test.sh` runs the PR watch engine's `unittest` suite (`tests/pr_watch/`, standard library, `gh` and the Codex daemon mocked) and then shell cases for `hooks/pr-watch` (off, on, malformed input), `bin/ytstack-pr-watch` (enable/disable, install-worker and migrate plans, migrate copy, the worker launcher's engine choice; `register --all-open` is covered in `tests/pr_watch/test_register_all.py`, the `claude:` qualification of a bare session id in `test_session_spelling.py`, the handover to a successor session in `test_handover.py`, skipped checks, a moved head (with `remote_head` against a real temporary repository), the once-per-change status block and the merge suggestion in `test_under_load.py`) under a temporary HOME. The resolver rule of `bin/ytstack-check` exempts `hooks/pr-watch` by name (`_HOOKS_WITHOUT_RESOLVER`). **Python host tests: `tests/*_test.py`** diff --git a/.ytstack/spec/hooks-and-state.md b/.ytstack/spec/hooks-and-state.md index 10fd04ec..91051832 100644 --- a/.ytstack/spec/hooks-and-state.md +++ b/.ytstack/spec/hooks-and-state.md @@ -63,7 +63,7 @@ W8 and W9 are prompts for `ytstack:reconcile`, which moves history out with cons Every hook except `pr-watch` sources the library and resolves from the payload `cwd`. Every hook except `session-start` and `pr-watch` exits 0 silently when no `.ytstack` directory resolves. -`pr-watch` (SessionStart, UserPromptSubmit, PreToolUse and PostToolUse on `Bash|mcp__.*create_pull_request.*`; for Codex also Stop, via `bin/ytstack-codex hook pr-watch`) is the opt-in PR watch: it exits 0 with no output and without starting Python unless `~/.ytstack/config` has `pr_watch=on`, then hands the payload to `tools/pr-watch/pr-watch.py hook`. It works for any repository, with or without `.ytstack`, and fails open (an engine error is one stderr line, exit 0). Engine, state (`~/.ytstack/pr-watch/`), worker and migration are described in `docs/pr-watch.md`; `bin/ytstack-check` exempts this hook from the resolver rule by name. For Claude Code the UserPromptSubmit output is injected only when a status line changed since the last injection in that session (fingerprint in `meta` key `surface:`, reset on SessionStart) or a notice is pending; a `git push` the PostToolUse hook sees in a bound worktree sets `pushed_at` on that branch's watch when `refs/remotes/origin/` (without one, `refs/heads/`) then differs from the watched head, which shows `head moved` and makes the worker read it next tick (`tests/pr_watch/test_under_load.py`). A merge the worker observes queues one notice per PR when the watch saw a bot finding on it (outbox key `merged::`, a fixed template that names `ytstack:review-lessons`); it is delivered without the fresh GitHub read other notices get and is never cancelled by a later read (`tests/pr_watch/test_merge_notice.py`). +`pr-watch` (SessionStart, UserPromptSubmit, PreToolUse and PostToolUse on `Bash|mcp__.*create_pull_request.*`; for Codex also Stop, via `bin/ytstack-codex hook pr-watch`) is the opt-in PR watch: it exits 0 with no output and without starting Python unless `~/.ytstack/config` has `pr_watch=on`, then hands the payload to `tools/pr-watch/pr-watch.py hook`. It works for any repository, with or without `.ytstack`, and fails open (an engine error is one stderr line, exit 0). Engine, state (`~/.ytstack/pr-watch/`), worker and migration are described in `docs/pr-watch.md`; `bin/ytstack-check` exempts this hook from the resolver rule by name. For Claude Code the UserPromptSubmit output is injected only when a status line changed since the last injection in that session (fingerprint in `meta` key `surface:`, reset on SessionStart) or a notice is pending; a `git push` the PostToolUse hook sees in a bound worktree sets `pushed_at` on that branch's watch when `refs/remotes/origin/` (without one, `refs/heads/`) then differs from the watched head, which shows `head moved` and makes the worker read it next tick (`tests/pr_watch/test_under_load.py`). A merge the worker observes queues one notice per PR when the watch saw a bot finding on it (outbox key `merged::`, a fixed template that names `ytstack:review-lessons`); it is delivered without the fresh GitHub read other notices get and is never cancelled by a later read (`tests/pr_watch/test_merge_notice.py`). `handover --from [--to ]` moves a session's watches, its undelivered notices (not a Codex notice with a `dispatch_id`), bindings and candidates to its successor and writes `meta` key `handover:`; `register` follows that chain, so a PR a subagent of the old session opens later goes to the successor (`tests/pr_watch/test_handover.py`). | Hook | Event | Reads from the payload | Effect | Exit | |---|---|---|---|---| diff --git a/bin/ytstack-pr-watch b/bin/ytstack-pr-watch index 762e9114..e80d3e90 100755 --- a/bin/ytstack-pr-watch +++ b/bin/ytstack-pr-watch @@ -6,6 +6,7 @@ # ytstack-pr-watch install-worker [--yes] 60-second background worker (macOS launchd) # ytstack-pr-watch uninstall-worker [--yes] remove the worker, keep state # ytstack-pr-watch migrate --from DIR [--yes] copy the state of an existing local install +# ytstack-pr-watch handover --from SESSION [--to SESSION] hand a session's watches to its successor # ytstack-pr-watch status | register | create | inspect | pause | resume | tick | hook # # Without --yes the setup commands print their plan and write nothing. diff --git a/docs/pr-watch.md b/docs/pr-watch.md index 801bf65c..ba4e10db 100644 --- a/docs/pr-watch.md +++ b/docs/pr-watch.md @@ -70,6 +70,7 @@ Code, Codex and the worker, and stays the same across plugin updates. bin/ytstack-pr-watch create --repo OWNER/REPO --session SESSION_ID --cwd WORKTREE -- --title "..." --body-file body.md bin/ytstack-pr-watch register --repo OWNER/REPO --pr 123 --session SESSION_ID --cwd WORKTREE bin/ytstack-pr-watch register --repo OWNER/REPO --all-open # every open PR, for this session +bin/ytstack-pr-watch handover --from OLD_SESSION_ID # take over another session's watches bin/ytstack-pr-watch pause --repo OWNER/REPO --pr 123 # and resume bin/ytstack-pr-watch inspect --repo OWNER/REPO --pr 123 # read only, registers nothing bin/ytstack-pr-watch status @@ -98,6 +99,29 @@ are keyed by host: a bare id is a Codex thread, so a Claude id without its now qualifies the current Claude session's bare id, and `register` moves a watch stored under that bare id, with its undelivered notices, to `claude:`. +### Handing the watches to a successor session + +`register` refuses a PR another session owns, so a coordinator that rotates to +a fresh session would leave its watches behind: the successor's +`register --all-open` skips every one of them by name. The successor takes +them over in one call instead: + +```bash +bin/ytstack-pr-watch handover --from claude: # --to defaults to this session +``` + +It moves every watch of the old session to the new one, together with the +notices not delivered yet (a Codex notice whose turn may already have started +stays, so it is never sent twice), the branch bindings and the candidates, and +resets the new session's status fingerprint so its next prompt shows the block. +It also records the new session as the successor of the old one: a PR that a +still-running subagent of the old session opens later is registered to the new +session, and so is an explicit `register` for the old one. Handovers chain +(old to new to third), and a handover back to an earlier session makes it the +owner again. The old session's id is in its SessionStart context ("This session +is ...") and in `status`; a coordinator writes it into its handoff when it +rotates (`skills/coordinate/SKILL.md`, Step 12). + ## Delivery: Claude Code pulls, Codex is woken **Claude Code.** Sessions are stored as `claude:` and are never diff --git a/tests/pr_watch/test_handover.py b/tests/pr_watch/test_handover.py new file mode 100644 index 00000000..e56c0e62 --- /dev/null +++ b/tests/pr_watch/test_handover.py @@ -0,0 +1,139 @@ +"""`handover`: a coordinator that rotates to a fresh session takes its PR watches +along, also for PRs its still-running subagents open later (issue #61).""" +import importlib.util +import io +import os +import sys +import tempfile +import unittest +from contextlib import redirect_stdout +from pathlib import Path +from unittest.mock import patch + +ENGINE = Path(__file__).resolve().parents[2] / 'tools/pr-watch' +sys.path.insert(0, str(ENGINE)) +from prwatch import claude +from prwatch.state import connect, enqueue, register + +spec = importlib.util.spec_from_file_location('prwatch_cli', ENGINE / 'pr-watch.py') +cli = importlib.util.module_from_spec(spec) +spec.loader.exec_module(cli) + +OLD, NEW = 'claude:old-coordinator', 'claude:new-coordinator' + + +class Handover(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.env = patch.dict(os.environ, {'PR_WATCH_HOME': self.tmp.name}, clear=False) + self.env.start() + os.environ.pop('CLAUDE_CODE_SESSION_ID', None) + os.environ.pop('CODEX_THREAD_ID', None) + + def tearDown(self): + self.env.stop() + self.tmp.cleanup() + + def run_cli(self, *argv): + out = io.StringIO() + with patch.object(sys, 'argv', ['pr-watch', *argv]), redirect_stdout(out): + code = cli.main() + return code, out.getvalue() + + def rows(self, sql, *args): + db = connect() + result = [dict(r) for r in db.execute(sql, args)] + db.close() + return result + + def seed(self): + db = connect() + with db: + register(db, 'o/r', 1, OLD, '/tmp') + register(db, 'o/r', 2, OLD, '/tmp') + register(db, 'o/r', 3, 'claude:someone-else', '/tmp') + w1 = db.execute("SELECT * FROM watches WHERE number=1").fetchone() + enqueue(db, 'ci:o/r:1:abc', w1, 'red check') + enqueue(db, 'ci:o/r:1:old', w1, 'delivered long ago') + db.execute("UPDATE outbox SET delivered=1 WHERE event_key='ci:o/r:1:old'") + db.execute("INSERT INTO bindings VALUES('o/r','lane-a',?,'/wt/a',1,1)", (OLD,)) + db.execute("INSERT INTO candidates VALUES('o/r',9,?,'/wt/a',1)", (OLD,)) + db.execute('INSERT OR REPLACE INTO meta VALUES(?,?)', (claude.surface_key(NEW), 'stale')) + db.close() + + def test_moves_watches_notices_bindings_and_candidates(self): + self.seed() + code, out = self.run_cli('handover', '--from', OLD, '--to', NEW) + self.assertEqual(code, 0) + owners = {r['number']: r['session'] for r in self.rows('SELECT number, session FROM watches')} + self.assertEqual(owners, {1: NEW, 2: NEW, 3: 'claude:someone-else'}) + notices = {r['event_key']: r['session'] for r in self.rows('SELECT event_key, session FROM outbox')} + self.assertEqual(notices['ci:o/r:1:abc'], NEW) + # A delivered notice is history and stays where it was shown. + self.assertEqual(notices['ci:o/r:1:old'], OLD) + self.assertEqual([r['session'] for r in self.rows('SELECT session FROM bindings')], [NEW]) + self.assertEqual([r['session'] for r in self.rows('SELECT session FROM candidates')], [NEW]) + # The successor's next prompt shows the block again. + self.assertEqual(self.rows('SELECT * FROM meta WHERE key=?', claude.surface_key(NEW)), []) + self.assertIn(f'2 watches handed over from {OLD} to {NEW}: o/r#1 o/r#2', out) + self.assertIn('1 pending notice', out) + + def test_later_registrations_for_the_old_session_go_to_the_successor(self): + self.run_cli('handover', '--from', OLD, '--to', NEW) + db = connect() + with db: + # The worker adopts a PR a subagent of the old session opened after the handover. + register(db, 'o/r', 5, OLD, '/wt/b') + db.close() + self.assertEqual(self.rows('SELECT session FROM watches WHERE number=5'), [{'session': NEW}]) + + def test_a_chain_of_handovers_is_followed_and_handing_back_works(self): + self.run_cli('handover', '--from', OLD, '--to', NEW) + self.run_cli('handover', '--from', NEW, '--to', 'claude:third') + db = connect() + with db: + register(db, 'o/r', 6, OLD, '/tmp') + db.close() + self.assertEqual(self.rows('SELECT session FROM watches WHERE number=6'), [{'session': 'claude:third'}]) + # Back to the first session: it is live again, nothing loops. + self.run_cli('handover', '--from', 'claude:third', '--to', OLD) + db = connect() + with db: + register(db, 'o/r', 7, NEW, '/tmp') + register(db, 'o/r', 8, OLD, '/tmp') + db.close() + owners = {r['number']: r['session'] for r in self.rows('SELECT number, session FROM watches')} + self.assertEqual(owners, {6: OLD, 7: OLD, 8: OLD}) + + def test_a_codex_notice_in_flight_stays(self): + db = connect() + with db: + register(db, 'o/r', 1, 'thread-old', '/tmp') + w = db.execute("SELECT * FROM watches WHERE number=1").fetchone() + enqueue(db, 'ci:o/r:1:x', w, 'red check') + db.execute("UPDATE outbox SET dispatch_id='d1' WHERE event_key='ci:o/r:1:x'") + db.close() + self.run_cli('handover', '--from', 'thread-old', '--to', 'thread-new') + self.assertEqual(self.rows('SELECT session FROM outbox'), [{'session': 'thread-old'}]) + + def test_to_defaults_to_the_current_claude_session(self): + self.seed() + with patch.dict(os.environ, {'CLAUDE_CODE_SESSION_ID': 'new-coordinator'}): + code, out = self.run_cli('handover', '--from', OLD) + self.assertEqual(code, 0) + self.assertEqual(self.rows('SELECT session FROM watches WHERE number=1'), [{'session': NEW}]) + + def test_nothing_to_move_still_forwards(self): + code, out = self.run_cli('handover', '--from', OLD, '--to', NEW) + self.assertEqual(code, 0) + self.assertIn(f'0 watches handed over from {OLD} to {NEW}', out) + self.assertIn(f'later registrations for {OLD} go to {NEW}', out) + + def test_refuses_the_same_session_and_a_missing_target(self): + for argv in (('handover', '--from', OLD, '--to', OLD), ('handover', '--from', OLD)): + with self.assertRaises(SystemExit), patch('sys.stderr', io.StringIO()): + self.run_cli(*argv) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/pr-watch/pr-watch.py b/tools/pr-watch/pr-watch.py index 70b972c6..7ae18bdd 100755 --- a/tools/pr-watch/pr-watch.py +++ b/tools/pr-watch/pr-watch.py @@ -16,7 +16,7 @@ from prwatch import admin, claude, github from prwatch.hooks import handle -from prwatch.state import cli, connect, register, policy +from prwatch.state import cli, connect, handover, register, policy, successor from prwatch.worker import tick @@ -47,6 +47,10 @@ def main(): create.add_argument('--session', default=default_session) create.add_argument('--cwd', default=os.getcwd()) create.add_argument('gh_args', nargs=argparse.REMAINDER) + move_to = sub.add_parser('handover', help='Hand every watch of a session to its successor (a rotating ' + 'coordinator); later registrations for it follow') + move_to.add_argument('--from', dest='source', required=True, metavar='SESSION') + move_to.add_argument('--to', dest='session', default=default_session, metavar='SESSION') for command in ('pause', 'resume'): p = sub.add_parser(command, help=f'{command.capitalize()} notices for a watched PR') p.add_argument('--repo', required=True) @@ -68,6 +72,8 @@ def main(): own = os.environ.get('CLAUDE_CODE_SESSION_ID') if own and getattr(args, 'session', None) == own: args.session = claude.qualify(own) + if own and getattr(args, 'source', None) == own: + args.source = claude.qualify(own) if args.command == 'hook': try: result = handle(json.load(sys.stdin), args.host) @@ -125,7 +131,20 @@ def main(): else: db = connect() with db: - if args.command == 'register' and args.all_open: + if args.command == 'register' and args.session: + # A session that was handed over registers for its successor; say so in the output. + args.session = successor(db, args.session) + if args.command == 'handover': + if not args.session: + parser.error('--to or CODEX_THREAD_ID required') + if args.source == args.session: + parser.error('--from and --to name the same session') + moved, notices = handover(db, args.source, args.session) + print(f'{len(moved)} watches handed over from {args.source} to {args.session}' + + (': ' + ' '.join(f'{repo}#{number}' for repo, number in moved) if moved else '')) + print(f'{notices} pending notice{"" if notices == 1 else "s"} moved; ' + f'later registrations for {args.source} go to {args.session}') + elif args.command == 'register' and args.all_open: if not args.session: parser.error('--session or CODEX_THREAD_ID required') # One paginated list call (one REST call per 100 open PRs). diff --git a/tools/pr-watch/prwatch/state.py b/tools/pr-watch/prwatch/state.py index fa8cf79c..ed8df393 100644 --- a/tools/pr-watch/prwatch/state.py +++ b/tools/pr-watch/prwatch/state.py @@ -74,7 +74,44 @@ def enqueue(db, key, watch, message): (key, watch['repo'], watch['number'], watch['session'], message, time.time())) +def handover_key(session): + return f'handover:{session}' + + +def successor(db, session): + """The session a handover moved `session` to, followed to its end; `session` itself without one.""" + seen = {session} + while True: + row = db.execute('SELECT value FROM meta WHERE key=?', (handover_key(session),)).fetchone() + if not row or row['value'] in seen: + return session + session = row['value'] + seen.add(session) + + +def handover(db, source, target): + """Hand every watch of `source` to `target`, with its undelivered notices, branch bindings and + candidates, and forward later registrations for `source` to `target` (a rotating coordinator + whose subagents still run). Returns the moved watches and the number of moved notices.""" + moved = [(r['repo'], r['number']) for r in db.execute( + 'SELECT repo, number FROM watches WHERE session=? ORDER BY repo, number', (source,))] + db.execute('UPDATE watches SET session=? WHERE session=?', (target, source)) + # A Codex notice with a dispatch_id may already have started a turn: it stays (never sent twice). + notices = db.execute("UPDATE outbox SET session=?, error='' WHERE session=? AND delivered IS NULL " + "AND cancelled IS NULL AND dispatch_id IS NULL", (target, source)).rowcount + for table in ('bindings', 'candidates'): + db.execute(f'UPDATE OR IGNORE {table} SET session=? WHERE session=?', (target, source)) + db.execute(f'DELETE FROM {table} WHERE session=?', (source,)) + # The target is live again (handing back), the source points at it. + db.execute('DELETE FROM meta WHERE key=?', (handover_key(target),)) + db.execute('INSERT OR REPLACE INTO meta VALUES(?,?)', (handover_key(source), target)) + # The successor's next prompt shows the status block. + db.execute('DELETE FROM meta WHERE key=?', (f'surface:{target}',)) + return moved, notices + + def register(db, repo, number, session, cwd): + session = successor(db, session) if session.startswith('claude:'): # Heal a watch an older CLI stored under the bare Claude id (taken for a Codex thread). bare = session[len('claude:'):] From e39198bb4a24f69f72478ac48f9a731b01f1878d Mon Sep 17 00:00:00 2001 From: Alex Wegener Date: Sun, 15 Nov 2026 00:50:25 +0100 Subject: [PATCH 04/55] M031-S05-T02: reconcile and adopt-brownfield offer to map a large external plan Both preambles run ytstack-plans scan; a large plan directory without a recorded answer gets one question (map all / map the files I name / leave it). After a yes the agent maps the open rows into milestones and slices by docs/ux/external-plans.md, with a pointer back to each row; the plan itself is never written. Co-Authored-By: Claude Opus 5.5 --- .ytstack/M031-S05-PLAN.md | 4 +- .ytstack/M031-S05-T02-PLAN.md | 44 ++++++++++++++++ .ytstack/M031-S05-T02-SUMMARY.md | 40 +++++++++++++++ docs/ux/external-plans.md | 88 ++++++++++++++++++++++++++++++++ skills/adopt-brownfield/SKILL.md | 41 +++++++++++++-- skills/reconcile/SKILL.md | 52 +++++++++++++++---- tests/skill-preambles.test.sh | 22 +++++++- 7 files changed, 275 insertions(+), 16 deletions(-) create mode 100644 .ytstack/M031-S05-T02-PLAN.md create mode 100644 .ytstack/M031-S05-T02-SUMMARY.md create mode 100644 docs/ux/external-plans.md diff --git a/.ytstack/M031-S05-PLAN.md b/.ytstack/M031-S05-PLAN.md index ccb5b48b..976ecb4e 100644 --- a/.ytstack/M031-S05-PLAN.md +++ b/.ytstack/M031-S05-PLAN.md @@ -5,7 +5,7 @@ project: ytstack created: 2026-11-15T09:00:00Z status: in-progress task_count: 3 -completed_tasks: 1 +completed_tasks: 2 --- # M031-S05 -- Slice Plan @@ -17,7 +17,7 @@ completed_tasks: 1 ## Tasks - [x] T01 -- `bin/ytstack-plans`: `scan` finds plan directories (`plans/`, `plan/`, `planning/`, `roadmap/` and the same under `docs/`), counts work rows (task-list items and rows of tables with a status or checkbox column) as open, done or dropped, applies the thresholds and reads a recorded answer from `PREFERENCES.md`; `rows` prints one line per work row with `path:line`, state, id, section and title. `tests/ytstack-plans.test.sh` first. -- [ ] T02 -- The question and the mapping: `docs/ux/external-plans.md` (thresholds, mapping rules, pointer format, answer record); `reconcile` gets the class "External plan" (preamble line, one AskUserQuestion, the mapping after a yes); `adopt-brownfield` asks the same question after its artifacts exist. Preamble suite covers the new line. +- [x] T02 -- The question and the mapping: `docs/ux/external-plans.md` (thresholds, mapping rules, pointer format, answer record); `reconcile` gets the class "External plan" (preamble line, one AskUserQuestion, the mapping after a yes); `adopt-brownfield` asks the same question after its artifacts exist. Preamble suite covers the new line. - [ ] T03 -- Docs and checks: spec areas (`artifacts`, `checks-and-evals`), README tools list, the eval case `evals/external-plan/` with its README row, a `DECISIONS.md` entry for "script detects, agent maps". ## Done when diff --git a/.ytstack/M031-S05-T02-PLAN.md b/.ytstack/M031-S05-T02-PLAN.md new file mode 100644 index 00000000..3546e397 --- /dev/null +++ b/.ytstack/M031-S05-T02-PLAN.md @@ -0,0 +1,44 @@ +--- +milestone: M031 +slice: S05 +task: T02 +project: ytstack +created: 2026-11-15T09:45:00Z +status: done +--- + +# M031-S05-T02 -- Task Plan + +**Summary:** `reconcile` and `adopt-brownfield` ask once whether a large plan outside `.ytstack/` should be mapped into milestones and slices; after a yes the agent maps the open rows by the rules of `docs/ux/external-plans.md`, with a pointer back to each row, and never touches the plan. + +## Files + +- Create: `docs/ux/external-plans.md` (what counts, thresholds, the mapping, the pointer format, the answer record) +- Modify: `skills/reconcile/SKILL.md` (preamble lines `EXTERNAL_PLAN_OFFER` / `EXTERNAL_PLAN`, the class "External plan" with its question, Step 4 "Apply" allows the new milestone files and one `PREFERENCES.md` line; version 0.3.0) +- Modify: `skills/adopt-brownfield/SKILL.md` (the same preamble lines, Step 6b with the same question after the artifacts exist, the backlog slot skips a directory that 6b covers; version 0.3.0) +- Modify: `tests/skill-preambles.test.sh` (both preambles: no plan -> offer no; a plan with 10 open rows -> offer yes and the dir line) + +## What this does + +Detection runs through `bin/ytstack-plans scan` from T01. The mapping is done by the agent following the document, not by a script: which rows form a milestone, a slice or a task needs judgment the real example shows (a board of work packages plus checklists under each package, checklists left unticked under finished packages). `ytstack-plans rows --open` gives the agent exact pointers; `ytstack-frontier list --milestone M###` afterwards is the check that the frontier sees the new slices. + +Mapping rules (the document holds them in full): one milestone per plan file with open rows (per section when a file would give more than 12 slices); one slice per open board row, without a board one slice per section, at most 7 tasks; next free `M###`; `status: planned`; `**Source:**` with `path:line` and the row id on every slice, `(path:line)` on every task line; `**Blocked by:**` only for a dependency the row states on another mapped row; done rows are counted, not mapped; the answer is recorded as `external_plans: mapped|declined ` in `PREFERENCES.md`. + +## Spec impact + +- artifacts: Behavior -- `reconcile` may write new milestone files and one `PREFERENCES.md` line for the external plan class (done in T03) +- skills: none -- the procedures change, the classes do not + +## Verification + +```bash +/bin/bash tests/skill-preambles.test.sh && python3 bin/ytstack-check +``` + +Runs: once. Environment: local checkout (macOS, bash 3.2). + +Success: the suite ends with ` passed, 0 failed`; `ytstack-check` exits 0 or 2 without a `[fail]` line. By hand once: the mapping of a fixture plan by the document's rules gives files `ytstack-frontier list --milestone` lists. + +## Done signal + +Run `/ytstack:summarize-task` after execution to mark complete and advance STATE.md. diff --git a/.ytstack/M031-S05-T02-SUMMARY.md b/.ytstack/M031-S05-T02-SUMMARY.md new file mode 100644 index 00000000..3af10de5 --- /dev/null +++ b/.ytstack/M031-S05-T02-SUMMARY.md @@ -0,0 +1,40 @@ +--- +milestone: M031 +slice: S05 +task: T02 +project: ytstack +closed: 2026-11-15T10:20:00Z +verification: passed +--- + +# M031-S05-T02 -- Summary + +## Commits + +- The commit that carries this file (`M031-S05-T02: reconcile and adopt-brownfield offer to map a large external plan`). + +## Outcome + +`docs/ux/external-plans.md` fixes what counts as an external plan, the two thresholds and why, how the answer is recorded (`external_plans: mapped|declined ` in `PREFERENCES.md`), the question's three options and its recommendation rule, and the mapping: one milestone per plan file with open rows (per section above 12 slices), one slice per open board row or per section, at most 7 tasks, `status: planned`, done rows only counted, `**Blocked by:**` only for a dependency on another mapped open row, and a pointer back on every slice (`**Source:** path:line (row id, read date)`) and every task line. The plan is read only. + +`reconcile` 0.3.0 prints `EXTERNAL_PLAN_OFFER` and the `scan` lines in its preamble, asks the class "External plan" last, and its Step 4 allows the new milestone files, `ROADMAP.md` rows and one `PREFERENCES.md` line. `adopt-brownfield` 0.3.0 prints the same lines and asks the same question in a new Step 6b, after the artifacts exist; its backlog question skips a directory that 6b covers, the Adoption table and the report get a row. + +## Deviations from plan + +- The recommendation is conditional (A up to five plan files with open rows, B above). The real example has 23 plan files and 1467 open rows, most of them unticked checklists under finished packages; recommending "map all" there would flood the frontier. +- The re-ask footer of `adopt-brownfield` points at `reconcile`, because `adopt-brownfield` stops on an initialized project. +- `reconcile`'s preamble now prints `BRANCH` and `PROJECT_SLUG`, which the Re-ground of the new question needs. + +## Follow-ups + +- The mapping is prose the agent follows. Its quality on a real plan (board plus checklists) is graded only by the eval case of T03, which has not run. + +## Spec + +- artifacts: updated in T03 (`reconcile` writes for the external plan class) + +## Verification + +Command: `/bin/bash tests/skill-preambles.test.sh` -- exit 0, `549 passed, 0 failed` (541 before; 8 new: per skill no plan -> `EXTERNAL_PLAN_OFFER: no`, ten open rows -> `yes` and the dir line, a recorded answer -> `no`). `python3 bin/ytstack-check` -- exit 2, no `[fail]`; the only warning on this branch's files is the spec drift note for `checks-and-evals` (closed in T03). + +By hand, once: a fixture plan (`/tmp/s05map/plans/v2.md`, a board with 1 done and 11 open rows, AV-03 depending on AV-02, AV-02 on the done AV-01) mapped by the document's rules into `M001` with 11 slices; `ytstack-frontier list --milestone M001` printed S01 ready, S02 `blocked S01`, S03-S11 ready; without `--milestone` the frontier picked M001 (STATE names none); `ytstack-plans scan` then reported `answer=mapped` and exited 1. diff --git a/docs/ux/external-plans.md b/docs/ux/external-plans.md new file mode 100644 index 00000000..104a11ad --- /dev/null +++ b/docs/ux/external-plans.md @@ -0,0 +1,88 @@ +# External plans + +A project that ran for a while before ytstack, or beside it, often keeps its plan in `plans/*.md`: tables of work packages, checklists, a board with a "Done" column. `bin/ytstack-frontier` reads only milestones and slices inside `.ytstack/`, so it lists nothing for that work and the lanes get tracked by hand. This document fixes how ytstack finds such a plan, when it offers to map it, and how the mapping is written. `reconcile` and `adopt-brownfield` use it; `bin/ytstack-plans` does the detection. + +The external plan is the user's. ytstack reads it and links to it. It never edits, moves, renames or deletes a file in it, and it never ticks a row there. + +## What counts + +`bin/ytstack-plans scan` looks at these directories, relative to the repository root, and at their `*.md` files up to three levels deep: + +`plans/`, `plan/`, `planning/`, `roadmap/`, `docs/plans/`, `docs/plan/`, `docs/planning/`, `docs/roadmap/` + +A **work row** is: + +- a task-list item: `- [ ] ...`, `- [x] ...` (also `*` and `+`, `[X]`); +- a data row of a Markdown table whose header names a status column (`Status`, `State`, `Done`, `Progress`, `Stand`, `Erledigt`), or whose first data row has a checkbox cell (`[ ]`, `[x]`). + +A table without such a column (a comparison, a cost table) is not a plan. Anything inside a fenced code block is skipped. + +A row is `done` when its checkbox is ticked or its status cell starts with done, merged, complete(d), shipped, closed, finished, landed, released, erledigt, fertig or a check mark; `dropped` when it starts with dropped, cancel..., superseded, obsolete, wontfix, won't, skipped, abandoned, verworfen, a cross mark or strikethrough; `open` otherwise. + +## Thresholds + +| Threshold | Value | Why | +|---|---|---| +| Plan file | at least 3 work rows | a README with one checkbox is not a plan | +| Large directory | at least 10 open rows in its plan files (`YTSTACK_PLAN_MIN_OPEN`) | below that, two milestones' worth of slices at most: retyping them through `plan-milestone` costs less than a mapping | + +Only a large directory without a recorded answer is offered. `scan` prints one line per directory with plan files and exits 0 only in that case: + +``` +dir=plans files=23 open=1467 done=462 verdict=large answer=none +``` + +## The answer is recorded + +The question is asked once per directory. The answer goes into `.ytstack/PREFERENCES.md`, one line per directory: + +``` +external_plans: plans mapped 2026-11-15 +external_plans: docs/roadmap declined 2026-11-15 +``` + +`scan` reads these lines and reports `answer=mapped` or `answer=declined`. To be asked again, delete the line. Rows added to the plan after a mapping are not mapped by themselves: delete the line and run `reconcile` again, or plan them with `plan-milestone`. + +## The question + +One `AskUserQuestion` in the format of `askuserquestion-format.md`, tier `core`. The two skills carry the body; its options are always: + +- **A) Map all** -- every plan file with open rows becomes milestones and slices. +- **B) Map the files I name** -- the user names the files; the others are not mapped. The answer is recorded as `mapped` all the same. +- **C) Leave it** -- recorded as `declined`; nothing else is written. + +The recommendation is A when at most five plan files hold open rows, B otherwise (name the files with the most open rows: an old plan directory usually holds finished plans whose checklists nobody ticked). + +Without a person (`YTSTACK_NON_INTERACTIVE`), the recommendation is taken; for B the agent takes the file with the most open rows and says so. + +## The mapping + +The agent maps; no script writes the milestones. Which rows form a milestone, a slice or a task depends on how the plan is built, and the rows alone do not say it. `bin/ytstack-plans rows --open ` gives every open row with its exact pointer; read the file around those lines before writing. + +1. **Milestones.** One milestone per plan file with open rows. A file that would give more than 12 slices becomes one milestone per section (`##` heading) instead. Numbers continue after the highest `M###-*` file in `.ytstack/` (the rule of `plan-milestone`), in the order of the files. +2. **Slices.** When the file has a board (a table whose rows carry an id), each open board row is one slice and the board is the authority: a checklist under a package whose board row is done is not mapped, even with unticked boxes. Without a board, each section with open rows is one slice. A slice holds at most 7 tasks; a section with more open rows is split in order. +3. **Tasks.** The open checklist items of the package or section, one task each, in order. A board row without a checklist gets one task with the row's title. +4. **Done and dropped rows** are not mapped. The milestone's `CONTEXT` counts them and links the file. +5. **Dependencies.** `**Blocked by:**` names a slice only when the row states the dependency (a "Depends on", "Blocked by", "Can start" or "after" cell, or the text) and the row it names is mapped to an open slice of the same milestone. A dependency on a done row is satisfied and left out. A dependency on anything else (another milestone, a gate, a person) goes under the slice's `## Notes`, never into `**Blocked by:**`: the frontier would keep the slice blocked for good. +6. **Status.** Every file is written with `status: planned`. `STATE.md` is not changed: the user decides which milestone is current. + +### The pointer back + +Every artifact links the row it came from, so the plan stays the source of detail: + +- `M###-CONTEXT.md`: under `## Goal` the plan's H1 and first sentence in one line, then `## Source` with the file, the date of the mapping, and the counts: `Mapped from \`plans/2026-10-29-v2-packages.md\` on 2026-11-15: 8 open rows mapped, 2 done and 1 dropped not mapped. The file stays the source of detail; it is not kept in sync.` +- `M###-ROADMAP.md`: one line per slice, `- [ ] S01 -- AV-03 Package 3`. +- `M###-S##-PLAN.md`: directly under the goal, `**Source:** \`plans/2026-10-29-v2-packages.md:9\` (row \`AV-03\`, read 2026-11-15)`; each task line ends with its pointer: `- [ ] T01 -- Write the pass/fail matrix (plans/2026-10-29-v2-packages.md:407)`. + +Line numbers move when the plan is edited; the row id and the date keep the pointer findable. + +### The templates + +The frontmatter and sections are those of `plan-milestone` (CONTEXT, ROADMAP) and `slice-milestone` (slice plan), with these values: `size` from the slice count (1: S, 2-3: M, more: L), `created` the time of the mapping, exit criteria "All mapped slices done; the source rows they point at are done in ``", the slice goal the row's title in one sentence. + +### Afterwards + +1. A global `ROADMAP.md` with a milestone table gets one row per new milestone with status `planned`. +2. Record the answer in `PREFERENCES.md` (above). +3. Run `bin/ytstack-frontier list --milestone M###` for each new milestone. Every mapped slice is listed, and the ready ones are the open rows that nothing open blocks. A slice that is listed `blocked` names what blocks it; check that it is a mapped row. +4. Say in the report which hand-kept lane list the mapping replaces, if the project has one; it is not edited either. diff --git a/skills/adopt-brownfield/SKILL.md b/skills/adopt-brownfield/SKILL.md index aeafa5f7..ec22e403 100644 --- a/skills/adopt-brownfield/SKILL.md +++ b/skills/adopt-brownfield/SKILL.md @@ -3,7 +3,7 @@ name: adopt-brownfield description: "Brings an existing codebase under ytstack by reference, without a greenfield pitch. Use when a repo has a README, docs, CHANGELOG, ADRs or months of commits but no .ytstack/ yet, when a project has .ytstack/ but no technical spec under .ytstack/spec/ yet (adds only the spec), or when the user says adopt ytstack, set up ytstack here, onboard this codebase, map the codebase, write the technical spec. Not for ideas without code yet (office-hours, then init-project) and not for repos that already have .ytstack/ with a spec (resume-session)." metadata: tier: core - version: 0.2.1 + version: 0.3.0 triggers: - adopt ytstack - existing project @@ -54,6 +54,7 @@ You MUST create a TodoWrite task for each of these items and complete them in or 4. **Ask per artifact** -- one AskUserQuestion per candidate slot: reference / extract / move / leave 5. **Map the codebase** -- dispatch up to 4 read-only subagents, write `.ytstack/codebase/{stack,architecture,conventions,concerns}.md` 6. **Write the artifacts** -- PROJECT, DECISIONS, KNOWLEDGE, RUNTIME, STATE, PREFERENCES, each per its Step 4 decision; templates only for gaps +6b. **Offer the external plan mapping** (only if `EXTERNAL_PLAN_OFFER: yes`) -- one AskUserQuestion; after a yes, open rows become milestones and slices 7. **Write the technical spec** -- propose areas from `codebase/architecture.md` and the docs index, confirm them with one AskUserQuestion, read the code per area, write `.ytstack/spec/SPEC.md` + `.ytstack/spec/.md` (pointer-only where a document exists) 8. **Check the spec format** -- run `ytstack-spec lint` and fix what it reports; by hand against `docs/ux/spec-format.md` when the script is not reachable 9. **Write the `.gitignore` block** -- `.ytstack/.local/` via `yt_ensure_gitignore` @@ -137,6 +138,12 @@ _README_ONELINER="" if [ -f README.md ]; then _README_ONELINER=$(awk 'NF==0{next} /^#/{next} /^[!<\[|`-]/{next} {print; exit}' README.md | cut -c1-200) fi +# A large plan outside .ytstack/ that ytstack-frontier cannot see (M031-S05). +_EXT_PLAN="unknown (bin/ytstack-plans not reachable)"; _EXT_OFFER=no +_PLANS_BIN="${CLAUDE_SKILL_DIR}/../../bin/ytstack-plans" +if [ -f "$_PLANS_BIN" ]; then + _EXT_PLAN=$(bash "$_PLANS_BIN" -C "$_PROJECT_DIR" scan 2>/dev/null) && _EXT_OFFER=yes +fi echo "BRANCH: $(git branch --show-current 2>/dev/null || echo unknown)" echo "PROJECT_SLUG: $_PROJECT_SLUG" @@ -153,6 +160,8 @@ echo "ENTRY_DOC: ${_ENTRY_DOC:-none}" echo "PITCH: ${_PITCH:-none}" echo "README_ONELINER: ${_README_ONELINER:-none}" echo "BROWNFIELD_SIGNALS: $_BF_SIGNALS" +echo "EXTERNAL_PLAN_OFFER: $_EXT_OFFER" +echo "EXTERNAL_PLAN:"; printf '%s\n' "$_EXT_PLAN" | sed 's/^/ /' echo "CANDIDATES:" if [ -n "$_BF_HINTS" ]; then printf '%s\n' "$_BF_HINTS" | sed 's/^/ - /'; else echo " (none detected)"; fi ``` @@ -187,7 +196,7 @@ Read each candidate named under `CANDIDATES` (first 40 lines of each file is eno > | DECISIONS.md | `docs/adr/` ({n} records) | reference: one entry per ADR, linked | {conflict if two decision sources exist} | > | KNOWLEDGE.md | `docs/*.md` ({n} files) | reference: link index with H1 summaries | | > | RUNTIME.md | `package.json` scripts, `.env.example`, `compose.yml`, `.github/workflows/` | extract: commands, services, env keys, deploy target | values never copied, keys only | -> | ROADMAP backlog | `docs/plans/` / `ROADMAP.md` / `BACKLOG.md` | reference | open items become backlog, not a milestone | +> | ROADMAP backlog | `docs/plans/` / `ROADMAP.md` / `BACKLOG.md` | reference | open items become backlog, not a milestone; a directory with `verdict=large` under `EXTERNAL_PLAN` gets the mapping offer of Step 6b instead | > | STATE.md | nothing | gap: scaffold | `tracker:` field for Linear / GitHub Projects / Paperclip / Jira | > | Technical spec | {documents that describe a part of the system: `docs/architecture.md`, `docs/adr/`, an API reference, feature docs} + the codebase map | one file per system area under `.ytstack/spec/`, pointer-only where a document exists | you confirm the area list after the codebase is mapped; an area is marked implemented only after its code was read | > | Entry point | `{ENTRY_DOC}` | pointer section | never duplicated | @@ -201,7 +210,7 @@ If `PITCH` is not `none`: a pitch for new scope exists alongside the old codebas ### Step 4: Ask per artifact -One question per slot that has a source (PROJECT, DECISIONS, KNOWLEDGE, RUNTIME, backlog), in that order, one message each. Do not ask for gaps and do not ask for the entry point. The technical spec has its own question in Step 7, once the codebase map exists. +One question per slot that has a source (PROJECT, DECISIONS, KNOWLEDGE, RUNTIME, backlog), in that order, one message each. Do not ask for gaps and do not ask for the entry point. Do not ask the backlog question for a directory that Step 6b offers to map; ask it only for the other backlog sources. The technical spec has its own question in Step 7, once the codebase map exists. If `YTSTACK_NON_INTERACTIVE` is `true`, auto-pick the RECOMMENDATION for every slot and log one line each: `[ytstack:adopt-brownfield] auto-picked {X} for {SLOT} because YTSTACK_NON_INTERACTIVE=true`. @@ -464,6 +473,31 @@ explain_level: default Write `{YT_DIR}/backlog/README.md`: one line per open item found in the source with a relative link; heading `# Backlog (inherited from {SOURCE})`. Items become milestones only when `ytstack:plan-milestone` picks them up. +### Step 6b: Offer the external plan mapping + +Only when `EXTERNAL_PLAN_OFFER` is `yes` (a spec-only run skips this step; `ytstack:reconcile` offers it there). A directory such as `plans/` holds tables or checklists with at least ten open rows, and `ytstack-frontier` reads only milestones and slices inside `.ytstack/`. The rules (what counts, the mapping, the pointer back) are in `${CLAUDE_SKILL_DIR}/../../docs/ux/external-plans.md`; read it before you ask. For each directory with `verdict=large answer=none`, run `"${CLAUDE_SKILL_DIR}/../../bin/ytstack-plans" rows --open {dir}` and count the open rows per file. + +If `YTSTACK_NON_INTERACTIVE` is `true`, take the RECOMMENDATION (for B: the file with the most open rows) and log `[ytstack:adopt-brownfield] auto-picked {X} for the external plan in {dir} because YTSTACK_NON_INTERACTIVE=true`. Otherwise use AskUserQuestion: + +> Adopting ytstack for **{PROJECT_SLUG}** on branch `{BRANCH}`; the memory files are written. `{dir}/` holds a plan ytstack cannot see yet: {files} plan files, {open} open rows, {done} done. Most open rows: {up to five files with their open count}. +> +> The lane list (`ytstack-frontier`, which says what may start next and who works on what) reads only the milestones and slices inside `.ytstack/`. Mapping writes each open row of your plan as a slice or a task with a link back to its line, so the list sees that work from the first session on. Your plan files stay exactly as they are, and finished rows are only counted. +> +> RECOMMENDATION: Choose A when at most five files hold open rows, B otherwise, because a plan directory that grew for months usually holds finished plans whose checklists nobody ticked; mapping those would fill the lane list with work that is done. +> +> A) Map all -- one milestone per plan file with open rows, one slice per open work package, `status: planned`; `{dir}/` is not touched +> Completeness: 10/10, effort: human: review ~5 min / CC: ~10 min, tier: core +> +> B) Map the files I name -- tell me which files; the others stay unmapped +> Completeness: 8/10, effort: human: ~2 min / CC: ~5 min, tier: core +> +> C) Leave it -- record that you declined; the backlog slot keeps its pointer to `{dir}/` +> Completeness: 3/10, effort: human: 0 / CC: 0, tier: core +> +> (to re-ask later: delete the `external_plans: {dir}` line in `.ytstack/PREFERENCES.md`, then run `ytstack:reconcile`) + +On A or B, map by the document's section "The mapping" and run its "Afterwards" steps, including `ytstack-frontier list --milestone M###` for each new milestone; `STATE.md` keeps `current_milestone: none`. Either way, add the line `external_plans: {dir} mapped|declined {TODAY}` to `PREFERENCES.md` and a row `| Plan | {dir}/ | mapped: M###..M### / declined | .ytstack/M###-*.md |` to the Adoption table of `PROJECT.md`. Nothing in `{dir}/` is edited, moved or deleted, whatever the answer (the HARD-GATE above). + ### Step 7: Write the technical spec The artifacts say what the project is and where work stands. The technical spec says what applies now, per part of the system: `.ytstack/spec/SPEC.md` (the entry point, one page) and one `.ytstack/spec/.md` per area. The binding format is `docs/ux/spec-format.md` in the ytstack plugin (`${CLAUDE_SKILL_DIR}/../../docs/ux/spec-format.md`). Read it before writing; the templates below are that format filled in for an existing codebase. @@ -646,6 +680,7 @@ If `ENTRY_DOC` is `none`, write nothing and include the block in the report so t > | Codebase map | 4 subagents | `.ytstack/codebase/{stack,architecture,conventions,concerns}.md` | > | Technical spec | {n} areas: {i} implemented, {p} partial, {q} planned; {k} pointer-only | `.ytstack/spec/SPEC.md` + `.ytstack/spec/{area}.md` | > | Entry point | pointer section | `{ENTRY_DOC}` | +> | External plan | {mapped: {M} milestones, {S} slices from `{dir}/`, listed by `ytstack-frontier` / declined} (only after Step 6b) | `.ytstack/M###-*.md` | > > Spec, not established: {one line per area that is `planned` or `partial`, carries an `Unknown` or needs a new `verified_at` after a squash merge: `{area}` -- {what is missing}; or "nothing open"}. Spec format check: {clean | fixed: {what} | done by hand, `ytstack-spec` not reachable}. > diff --git a/skills/reconcile/SKILL.md b/skills/reconcile/SKILL.md index adc43886..3f492572 100644 --- a/skills/reconcile/SKILL.md +++ b/skills/reconcile/SKILL.md @@ -1,9 +1,9 @@ --- name: reconcile -description: "Consent-based cleanup of .ytstack/ leftovers: draft summary stubs, unfilled auto-drafts, milestones planned but never sliced, untracked .ytstack files, a .ytstack/.local without gitignore, history that grew inside STATE.md, slice and task files of closed milestones. Use when the SessionStart STATE lint reports warnings, or when the user says reconcile, clean up .ytstack, tidy the artifacts. Never deletes; the only sanctioned way to move .ytstack artifacts." +description: "Consent-based cleanup of .ytstack/ leftovers: draft summary stubs, unfilled auto-drafts, milestones planned but never sliced, untracked .ytstack files, a .ytstack/.local without gitignore, history that grew inside STATE.md, slice and task files of closed milestones, and a large plan outside .ytstack/ (plans/*.md tables or checklists) that ytstack-frontier cannot see. Use when the SessionStart STATE lint reports warnings, or when the user says reconcile, clean up .ytstack, tidy the artifacts, the frontier shows nothing, map our plans into milestones. Never deletes; the only sanctioned way to move .ytstack artifacts." metadata: tier: core - version: 0.2.0 + version: 0.3.0 allowed-tools: - Bash - Read @@ -26,8 +26,8 @@ You MUST create a TodoWrite task for each of these items and complete them in or 1. **Run preamble** -- counts and file lists per leftover class 2. **HARD-GATE** -- `.ytstack` present; nothing to do -> report and stop -3. **Per class: ask** -- close / archive / keep (one AskUserQuestion per non-empty class) -4. **Apply** -- moves inside `.ytstack/` only, status edits, gitignore block +3. **Per class: ask** -- close / archive / keep (one AskUserQuestion per non-empty class); map / leave for an external plan (only if `EXTERNAL_PLAN_OFFER: yes`) +4. **Apply** -- moves inside `.ytstack/` only, status edits, gitignore block; after a yes to the external plan, its open rows as new milestones and slices 5. **Write `RECONCILE-.md`** -- what was found, what was chosen 6. **Report + return** @@ -117,6 +117,15 @@ if [ -n "$_YT_DIR" ] && [ -f "$_YT_DIR/spec/SPEC.md" ]; then done fi +# A large plan outside .ytstack/ that ytstack-frontier cannot see (M031-S05). +_EXT_PLAN="unknown (bin/ytstack-plans not reachable)"; _EXT_OFFER=no +_PLANS_BIN="${CLAUDE_SKILL_DIR}/../../bin/ytstack-plans" +if [ -n "$_YT_DIR" ] && [ -f "$_PLANS_BIN" ]; then + _EXT_PLAN=$(bash "$_PLANS_BIN" -C "$_PROJECT_DIR" scan 2>/dev/null) && _EXT_OFFER=yes +fi + +echo "BRANCH: $(git branch --show-current 2>/dev/null || echo unknown)" +echo "PROJECT_SLUG: $_PROJECT_SLUG" echo "HAS_YTSTACK: $_HAS_YTSTACK" echo "DRAFT_STUBS: $(_count "$_DRAFT_STUBS")" echo "UNFILLED_DRAFTS: $(_count "$_UNFILLED")" @@ -125,6 +134,8 @@ echo "UNTRACKED: $(_count "$_UNTRACKED")" echo "LOCAL_DIR: $_LOCAL_DIR (gitignored: $_LOCAL_IGNORED)" echo "STATE_HISTORY: $_STATE_CLASS ($_STATE_HIST earlier status paragraph(s), $_STATE_BYTES bytes, bound $_STATE_MAX)" echo "CLOSED_MILESTONES: $(_count "$_CLOSED_MS")" +echo "EXTERNAL_PLAN_OFFER: $_EXT_OFFER" +echo "EXTERNAL_PLAN:"; printf '%s\n' "$_EXT_PLAN" | sed 's/^/ /' echo "LISTS_BEGIN" [ -n "$_CLOSED_MS" ] && { echo "[closed milestones]"; printf '%s\n' "$_CLOSED_MS"; } [ -n "$_DRAFT_STUBS" ] && { echo "[draft stubs]"; printf '%s\n' "$_DRAFT_STUBS" | head -20; } @@ -138,7 +149,7 @@ echo "LISTS_END" ### Step 2: HARD-GATE -`HAS_YTSTACK=no`: "Nothing to reconcile: no `.ytstack/` here." STOP. All counts zero, `STATE_HISTORY: no` and `LOCAL_DIR: no` (or gitignored): "`.ytstack/` is clean." STOP. +`HAS_YTSTACK=no`: "Nothing to reconcile: no `.ytstack/` here." STOP. All counts zero, `STATE_HISTORY: no`, `LOCAL_DIR: no` (or gitignored) and `EXTERNAL_PLAN_OFFER: no`: "`.ytstack/` is clean." STOP. ### Step 3: Ask per non-empty class @@ -182,18 +193,41 @@ On A: write the archive file first, then remove from `STATE.md` exactly the text > A) archive -- move each milestone's `M###-S##-*.md` files to `.ytstack/archive/{YYYY-MM-DD}/M###/`, one `INDEX.md` line per milestone. (Completeness: 9/10, tier: core) > B) keep -- no change. (Completeness: 6/10, tier: core) +**External plan** (`EXTERNAL_PLAN_OFFER: yes`), last. A directory such as `plans/` holds tables or checklists of open work, and `ytstack-frontier` reads only milestones and slices inside `.ytstack/`: the lanes for that work get tracked by hand. The rules (what counts, thresholds, the mapping, the pointer back) are in `${CLAUDE_SKILL_DIR}/../../docs/ux/external-plans.md`; read it before you ask. Ask once per directory with `verdict=large answer=none` in `EXTERNAL_PLAN`. First run `"${CLAUDE_SKILL_DIR}/../../bin/ytstack-plans" rows --open {dir}` and count the open rows per file, so the question can name the files. + +If `YTSTACK_NON_INTERACTIVE` is set, take the RECOMMENDATION (for B: the file with the most open rows) and log `[ytstack:reconcile] auto-picked {X} for the external plan in {dir} because YTSTACK_NON_INTERACTIVE=true`. Otherwise use AskUserQuestion: + +> Reconciling `.ytstack/` for **{PROJECT_SLUG}** on branch `{BRANCH}`. `{dir}/` holds a plan ytstack cannot see: {files} plan files, {open} open rows, {done} done. Most open rows: {up to five files with their open count}. +> +> The lane list (`ytstack-frontier`, which says what may start next and who works on what) reads only the milestones and slices inside `.ytstack/`. Your plan lives in `{dir}/`, so the list is empty for that work and lanes get tracked by hand. Mapping writes each open row as a slice or a task with a link back to its line; your plan files stay exactly as they are, and finished rows are only counted. +> +> RECOMMENDATION: Choose A when at most five files hold open rows, B otherwise, because a plan directory that grew for months usually holds finished plans whose checklists nobody ticked; mapping those would fill the lane list with work that is done. +> +> A) Map all -- one milestone per plan file with open rows, one slice per open work package, `status: planned`; `{dir}/` is not touched +> Completeness: 10/10, effort: human: review ~5 min / CC: ~10 min, tier: core +> +> B) Map the files I name -- tell me which files; the others stay unmapped +> Completeness: 8/10, effort: human: ~2 min / CC: ~5 min, tier: core +> +> C) Leave it -- record that you declined; the lane list keeps not seeing this plan +> Completeness: 3/10, effort: human: 0 / CC: 0, tier: core +> +> (to re-ask later: delete the `external_plans: {dir}` line in `.ytstack/PREFERENCES.md`) + +On A or B, map by the document's section "The mapping" and run its "Afterwards" steps, including `ytstack-frontier list --milestone M###` for each new milestone. On C, write only the `PREFERENCES.md` line. Either way the answer is recorded as `external_plans: {dir} mapped|declined {YYYY-MM-DD}`. + ### Step 4: Apply -Moves only inside `.ytstack/` (`git mv` when tracked, `mv` otherwise), edits only to frontmatter `status:`/`closed:` fields and the global `ROADMAP.md` rows. No `rm`. No edits to STATE.md pointer fields. The one edit to the body of `STATE.md` is the history move of the class above, and only after its answer A. +Moves only inside `.ytstack/` (`git mv` when tracked, `mv` otherwise), edits only to frontmatter `status:`/`closed:` fields and the global `ROADMAP.md` rows. No `rm`. No edits to STATE.md pointer fields. The one edit to the body of `STATE.md` is the history move of the class above, and only after its answer A. The external plan class adds files and changes none: new `M###-CONTEXT.md`, `M###-ROADMAP.md` and `M###-S##-PLAN.md` files, a `ROADMAP.md` row per new milestone and one line in `PREFERENCES.md`. Nothing outside `.ytstack/` is written; the external plan is read only. ### Step 5: Write the log -`.ytstack/RECONCILE-{YYYY-MM-DD}.md`: per class the items found and the choice made, plus the archive path. +`.ytstack/RECONCILE-{YYYY-MM-DD}.md`: per class the items found and the choice made, plus the archive path. For the external plan: the directory, the files mapped, and per new milestone its slices with the source file. ### Step 6: Report + return -> Reconciled `.ytstack/`: {N closed}, {N archived} (-> `archive/{date}/`), {N kept}. Log: `RECONCILE-{date}.md`. +> Reconciled `.ytstack/`: {N closed}, {N archived} (-> `archive/{date}/`), {N kept}{, external plan `{dir}/`: {M} milestones with {S} slices mapped (`M###`..`M###`), the frontier lists them | declined}. Log: `RECONCILE-{date}.md`. ## Terminal State -Return control after the report. Suggest `ytstack:reassess-roadmap` only when a milestone's status changed. Do NOT auto-invoke anything. +Return control after the report. Suggest `ytstack:reassess-roadmap` only when a milestone's status changed. After a mapping, say that `STATE.md` still names the old current milestone and that the user picks which mapped milestone becomes current. Do NOT auto-invoke anything. diff --git a/tests/skill-preambles.test.sh b/tests/skill-preambles.test.sh index a29ebea3..513df2e0 100644 --- a/tests/skill-preambles.test.sh +++ b/tests/skill-preambles.test.sh @@ -66,6 +66,22 @@ own_reviewers_on() { } own_reviewers_off() { rm -rf "$WT/.github" "$WT/.ytstack/spec/REVIEW.md"; rmdir "$WT/.ytstack/spec" 2>/dev/null; return 0; } +# ext_plan_checks: a large plan outside .ytstack/ is offered once (M031-S05); +# uses $s and $P of the loop below. +ext_plan_checks() { + run_pre "$P" "$WT" + has "$s: no plan directory -> nothing offered" "$OUT" "EXTERNAL_PLAN_OFFER: no" + mkdir -p "$WT/plans" + { printf '# v2 plan\n\n## Steps\n\n'; i=1; while [ $i -le 10 ]; do printf -- '- [ ] step %d\n' $i; i=$((i+1)); done; } > "$WT/plans/v2.md" + run_pre "$P" "$WT" + has "$s: 10 open rows in plans/ -> offered" "$OUT" "EXTERNAL_PLAN_OFFER: yes" + has "$s: the directory line is printed" "$OUT" "dir=plans files=1 open=10 done=0 verdict=large answer=none" + printf 'external_plans: plans declined 2026-11-15\n' >> "$WT/.ytstack/PREFERENCES.md" + run_pre "$P" "$WT" + has "$s: a recorded answer -> not offered again" "$OUT" "EXTERNAL_PLAN_OFFER: no" + rm -rf "$WT/plans" "$WT/.ytstack/PREFERENCES.md" +} + PD="$TMP/plugin-data" run_pre() { # run_pre