From 1d439679f6865893bb433a6978c0342cf8ae31f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 15:35:05 -0800 Subject: [PATCH 01/22] feat(hooks): name the waiting step in a crew launch that names none A step binds only to the launch whose description names it, so a Claude Code crew launch that named none of its member's steps started with no step; the tech lead learned it only afterwards and had to stop and relaunch the member (twice in two days). The PreToolUse hook checks a main-session Agent or Task call for a devkit crew member with the matcher the binder uses after the launch (progress._bind_step: the member's steps, scored by progress._name_score on the description's task text). When the description names none and exactly one step waits for that member's launch, the hook puts the step's name in the description, records it in the launch record so the agent binds that step, writes crew.launch-named to the audit trail, and tells the tech lead in the call's context. With two or more steps waiting, or two or more named equally, the tech lead gets the exact description that takes each. The new description and the brief's required sections go out in one updatedInput. Codex launches are left as they are: Codex applies updatedInput only to shell commands, and its spawn's task_name selects the step. Verified: dev test run (23 files that send launches through the hook): 605 passed; dev test prove: the 6 new tests fail without the change; python3 and /usr/bin/python3 -m unittest tests.test_hooks_launch: 6 passed; dev docs check: 0 issues --- docs/agents.md | 2 +- docs/crew.md | 6 +- lib/devkit/hooks.py | 135 ++++++++++++++++++++++++++++++++++-- plugin/skills/crew/SKILL.md | 4 +- tests/test_hooks_launch.py | 130 ++++++++++++++++++++++++++++++++++ 5 files changed, 268 insertions(+), 9 deletions(-) create mode 100644 tests/test_hooks_launch.py diff --git a/docs/agents.md b/docs/agents.md index cb9347a7..0fa419ec 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -240,7 +240,7 @@ works from the Desktop and ChatGPT apps, whose PATH is minimal. | --- | --- | --- | --- | | SessionStart | `startup\|resume\|clear\|compact`, 30 s | `startup\|resume\|clear\|compact`, 30 s | Records the session's starting commit and branch, refreshes the project's generated blocks, exports `DEVKIT_SESSION` (Claude), restores managed settings in the background, clones `node_modules` into a fresh worktree, queues a sync that pulls the claims of other machines, and prints the workspace context. Shows you the [welcome](concepts.md#the-session-start-welcome) as its `systemMessage`, on both agents (at most five lines: what needs you, what runs, what is next, and where you are), and tells the model which lines you saw; the notices about an older devkit copy and extensions become need lines in it, and a headless run, a crew member's session, or a scratch repository gets none. The context stays under both agents' limits on a hook's output (at most 9,000 bytes: past 10,000 characters Claude Code shows the model a 2,000-character preview, and Codex past about 2,500 tokens), with what matters most first, so a cut takes the end, the handoff note's excerpt, at whole lines. In a project, it carries an index of the kinds of work the agent declares by id, with the lesson anchors and where the rest is (`dev crew raci`, `dev crew rules`, and `config/skill-rules.json` for the skills); the three most relevant known pitfalls; and the handoff note's path, Now tasks, and current state. After a compaction or a resume, the continuity brief comes first, after the line about the welcome you saw: the run and its current step, the crew working now (not to relaunch), the decisions and messages waiting, your latest requests verbatim, the last status block and git, at most 4 KB. After `/clear`, a notice of the previous session's open run and `dev session carry` | | UserPromptSubmit | 10 s | 10 s | Starts the turn clock, except for a message you type while the agent works, which Claude Code sends with the running turn's `prompt_id` and Codex with the running turn's `turn_id`: devkit keeps that turn and its request, and adds the message beside them once, even when the transcript or rollout reports it again at a later hook; gives the agent a short reminder of the presentation rules the final message of its last development turn missed (the status block, a role, the Progress line with the run's current counts, the reply language), recorded by Stop instead of sending that turn back, tells it to follow them when this turn is development work, and not to rewrite or repeat that reply. The reminder comes with your prompts only, never with a background notification or a message typed mid-turn, and again at each one until a turn that Stop classes as development work ends after it; adds real progress records and the branch's CI/CD pipelines when you ask for status; reminds the tech lead to declare the request's kinds of work by their ids from the catalog and route each by the RACI, the same reminder in every language and never a guess from the request's words (`crew.route_hint` turns it off); reminds the agent of the status block in a session that already missed it once, naming the failure mode (nothing comes before the block); registers a session that missed SessionStart and injects its context, catalog included. When decisions wait for you that you have not seen since your last prompt, tells the tech lead once per batch to ask them together in as few question calls as the rules allow (see [The crew › How the tech lead asks you](crew.md#how-the-tech-lead-asks-you)). It does not read your prompt for corrections or for skills. Background notifications (subagent results, system notices) and relayed comments are not treated as your request. Keeps your prompt, redacted and cut to 1,000 characters, as pending in the session's continuity checkpoint until Stop classes the turn, and gives the main session, once and first, what waits for it: the brief of a compaction only the transcript showed, or "Not in the summary." A prompt that wakes the session for a background event (a task notification, an agent message) also carries what waits for it: crew questions, decisions, ready steps, CI results, and notices | -| PreToolUse | `Bash\|Monitor\|Write\|Edit\|MultiEdit\|NotebookEdit\|Agent\|Task\|WebFetch\|mcp__.*`, 15 s | `^(Bash\|apply_patch\|spawn_agent)$`, 15 s | `dev hook pre-tool` (`dev hook guard`, its earlier name, still runs it for sessions started before the update). It never refuses a call or asks you about one: its output is nothing, context for the call, or a crew member's command rewritten to carry its lane. On Codex, which reads no PreToolUse context, a member gets the advice as a devkit notice at its next PostToolUse, and a rewrite carries `allow` only when Codex's approval policy is `never`, or for one plain `dev progress`, `dev crew`, `dev watch`, or `dev session` call with nothing the shell would expand; otherwise the call is not rewritten and the member is told. Starts the call's timer, and records each shell call with the agent that made it (the call ledger that tells devkit [who is calling](crew.md#who-is-calling)). On a Claude Code subagent launch (Agent, Task), records its description for its lane and appends the required skills, the known pitfalls, and the report format to the brief. Codex fires no PreToolUse for `spawn_agent`: a Codex launch is recorded at SubagentStart (see below the table). A Codex `exec_command` is read by its `cmd` in its `workdir`, like Bash's `command`. Inside a subagent (the input carries `agent_id`), routes a single `dev progress` or `dev crew` command to that subagent's lane. Adds one line of advice to the call's context for a write outside a member's file scope or by a read-only member, a launch past the crew's slots, an edit of a file a working member holds, a lane call it cannot route (which runs as the main session), and a commit that would take untracked unfinished work. Names the open [lessons](lessons.md) anchored on the command the call runs or the file it writes, each at most once an hour per agent, and adds the lesson of each matching [lesson rule](lessons.md#lesson-rules). Codex does not read a call's context, so there a rule's lesson is not counted as shown. When the hook itself fails, it logs the error and the call runs | +| PreToolUse | `Bash\|Monitor\|Write\|Edit\|MultiEdit\|NotebookEdit\|Agent\|Task\|WebFetch\|mcp__.*`, 15 s | `^(Bash\|apply_patch\|spawn_agent)$`, 15 s | `dev hook pre-tool` (`dev hook guard`, its earlier name, still runs it for sessions started before the update). It never refuses a call or asks you about one: its output is nothing, context for the call, or a crew member's command rewritten to carry its lane. On Codex, which reads no PreToolUse context, a member gets the advice as a devkit notice at its next PostToolUse, and a rewrite carries `allow` only when Codex's approval policy is `never`, or for one plain `dev progress`, `dev crew`, `dev watch`, or `dev session` call with nothing the shell would expand; otherwise the call is not rewritten and the member is told. Starts the call's timer, and records each shell call with the agent that made it (the call ledger that tells devkit [who is calling](crew.md#who-is-calling)). On a Claude Code subagent launch (Agent, Task), records its description for its lane and appends the required skills, the known pitfalls, and the report format to the brief. Before that, a crew member's launch whose description names none of the member's steps gets the name of the one step that waits for its launch, so the launch binds it, and the tech lead is told; with two or more waiting, or two or more named equally, the tech lead gets the exact description that takes each. Codex fires no PreToolUse for `spawn_agent`: a Codex launch is recorded at SubagentStart (see below the table). A Codex `exec_command` is read by its `cmd` in its `workdir`, like Bash's `command`. Inside a subagent (the input carries `agent_id`), routes a single `dev progress` or `dev crew` command to that subagent's lane. Adds one line of advice to the call's context for a write outside a member's file scope or by a read-only member, a launch past the crew's slots, an edit of a file a working member holds, a lane call it cannot route (which runs as the main session), and a commit that would take untracked unfinished work. Names the open [lessons](lessons.md) anchored on the command the call runs or the file it writes, each at most once an hour per agent, and adds the lesson of each matching [lesson rule](lessons.md#lesson-rules). Codex does not read a call's context, so there a rule's lesson is not counted as shown. When the hook itself fails, it logs the error and the call runs | | PostToolUse | `Bash\|Agent\|Task\|TaskStop\|Monitor\|Write\|Edit\|MultiEdit\|WebFetch\|WebSearch\|AskUserQuestion\|SendMessage`, 10 s | `^(Bash\|apply_patch)$`, 10 s | Closes the shell call in the call ledger. Records every Write, Edit, and MultiEdit call with its file, its caller, and its time: a file that changed during a read-only member's shell call is credited only to the member whose own edit call touched it, and any other such file is held against the read-only member. Ends the lane of an agent TaskStop stopped (it fires no SubagentStop): its slot frees and its step waits for a new launch. Names the open lessons whose error signature the call's output shows, each at most once an hour per agent, and the lesson rules whose text it shows. Adds each call to the [bug registry's](bug-registry.md) session ledger, and, for a marker of devkit's own failure in the output, gives the known detour or tells the agent how to find one. Right after a call that usually ends the turn (a subagent launch, a monitor, a background command, or `dev progress done`, `dev handoff --log`, `dev sync`, `dev task done`, a push, a PR, or a release), shows the main session the status block its final message opens with, with the project and branch filled in, at most once per 2 minutes in a turn; records slow calls; delivers crew messages to their recipient (the main session, or the subagent that made the call); tells the main session about decisions waiting for you and members ready to launch; reminds the main session to update you after a long silence; after a `git commit`, `push`, `merge`, `tag`, `rebase`, `cherry-pick`, or `revert`, or a `gh pr create`, `gh pr merge`, or `gh release create`, queues a sync of the handoff repository (see [Teams and machines › Near-real-time sync](teams.md#near-real-time-sync)). Gives the main session, once and first, the brief of a compaction only the transcript showed or "Not in the summary"; gives a member, after its own compaction, a reminder of its role, step, scope, procedure, and report format. A SendMessage from the main session to a member answers the questions to the tech lead that its text names (`M3: …`): each is marked answered via SendMessage, the text is kept as its answer, and the audit trail records `crew.message-answered`; a SendMessage that names none answers none, and a notice lists the questions that still wait. In Claude Code's main session, reads the messages you typed while it worked from the transcript (Claude Code also runs UserPromptSubmit for each, with the running turn's `prompt_id`): each counts as your latest request for the crew slot kept for you and for continuity, never as an approval. The crew messages, decisions, ready steps, CI results, and notices it delivers are the ones a `dev watch --wait` takes too: each reaches the session once, whichever reads it first | | PostToolUseFailure | `Agent\|Task\|Bash`, 10 s | — | A subagent launch that failed (an unknown agent type, an interrupt) started no agent, so its launch record goes at once: it never labels another agent or holds a crew slot. A failed or interrupted shell call leaves the call ledger, and its line goes to the [bug registry's](bug-registry.md) session ledger. When one agent's shell command fails twice in a row with the same error, it stops that agent once per command with the root-cause paragraph, the lessons the error matches, and the devkit bugs the registry knows (see [Lessons › Recall](lessons.md#recall)); a crew member's third identical failure sends the tech lead one notice. Names the open lessons and lesson rules whose error text the failure shows, and, for a marker of devkit's own failure, the known detour | | SubagentStart · SubagentStop | 5 s · 10 s | 5 s · 10 s | Opens and closes the subagent's progress lane (its persona, its step, its active time); a lane binds to exactly one launch. At SubagentStop, for a member someone launched, sends it back once for each of these, in order: a report that does not start with its own status block (`**[Firefly> DevKit · Neo]**`); no `dev progress step` in its lane; and the [crew gates](crew.md#every-report-is-checked) (proofs, skills, unfinished work, tests that cannot fail, lessons). The gates get 6 s of the hook's 10: past that they do not judge the stop, the member goes through, no earlier pass of its gates approves anything, and the audit trail records `crew.gate` as let through. Then it closes the lane and its step, records no observed repeat for lessons shown without a later observed miss, without claiming success, and reads the member's transcript once more for a compaction no hook saw. The compaction summarizer's stop is skipped: it owes no report and binds nothing | diff --git a/docs/crew.md b/docs/crew.md index 10648418..27ba92c2 100644 --- a/docs/crew.md +++ b/docs/crew.md @@ -262,7 +262,11 @@ that launch alone, so two members launched together never swap lanes: - **The step it names.** A bound lane takes the ready step its launch's description names, never just the member's first step. `dev progress assign` gives a step to the member's working lane at once when that lane's launch names - the step or the lane holds no other open step. + the step or the lane holds no other open step. Before a Claude Code launch starts, the pre-tool hook checks its + description the same way: when it names none of the member's steps and one waits for its launch, the hook puts that + step's name in the description and tells the tech lead; when two or more wait or it names two or more equally, + the tech lead gets the exact description that takes each. Codex launches pick their step by `task_name` and are + not changed. - **The steps queued for it.** When every working lane of the member holds another open step, the step is queued for those lanes: once a lane's open step closes, that lane takes the first queued step whose dependencies are done, the step's scope becomes the lane's, and the member is told. With two or more lanes, the first lane whose step diff --git a/lib/devkit/hooks.py b/lib/devkit/hooks.py index 3ce1637b..2742cc3a 100644 --- a/lib/devkit/hooks.py +++ b/lib/devkit/hooks.py @@ -2905,6 +2905,119 @@ def _post_codex_advice(agent: str, data: dict, advice: list, unroutable: bool): _log(f"pre-tool codex advice {agent}: {traceback.format_exc()[-300:]}") +def _launchable_steps(run: dict, lane: dict) -> list: + """The steps a new launch of the member in `lane` can take, as progress._bind_step selects them: assigned to that + member and still with the tech lead, or left unverified by one of its member's lanes that ended.""" + from . import progress as pg + plan, lanes = run.get("plan") or [], run.get("agents") or {} + mine = [st for st in plan if st.get("label") and st.get("state") not in pg.DONE + and (st.get("owner") or "main") == "main" and pg._label_matches(st["label"], lane)] + return mine + [st for st in plan if st.get("state") == "unverified" and st.get("label") + and (lanes.get(st.get("owner")) or {}).get("state") in pg.ENDED_LANE + ("unverified",) + and pg._label_matches(st["label"], lane)] + + +def _named_steps(label: str, steps: list) -> tuple: + """Which of `steps` the launch description `label` names, scored as progress._bind_step scores it + (progress._name_score on its task text). -> (binds, tied): `binds` the step it takes, or every review it names + equally (one reviewer's launch holds them together); `tied` the steps it names equally otherwise. Both empty + when it names none.""" + from . import approvals, progress as pg + scored = [(pg._name_score(pg._task_text(label), st["name"]), st) for st in steps] + best = max(sc for sc, _ in scored) + top = [st for sc, st in scored if sc == best] + if not best[1]: + return [], [] + if len(top) == 1 or all(approvals.is_review(st) for st in top): + return top, [] + return [], top + + +def _naming_description(label: str, name: str, who: str, steps: list) -> str: + """The launch description that names step `name` alone among `steps`: the step's name put in front of the + description's task text ("Mouse: visual tests" -> "Mouse: v23-qa visual tests", progress._task_text keeps the + member's prefix), or, when that still names another step as well, the member's name and the step's alone + ("Mouse: v23-qa"). '' when neither does.""" + from . import progress as pg + task = pg._task_text(label).strip() + prefix = label.partition(":")[0].strip() if task != (label or "").strip() else "" + body = name if pg._words(task) <= pg._words(name) else f"{name} {task}" + for text in (f"{prefix}: {body}" if prefix else body, f"{prefix or who}: {name}"): + binds, _ = _named_steps(text, steps) + if [st["name"] for st in binds] == [name]: + return text + return "" + + +def _launch_naming(agent: str, data: dict) -> tuple: + """A crew launch from the main session, checked before it starts with the matcher that binds a launch to a step + once it runs (progress._bind_step): a step binds only to the launch whose description names it, so a launch that + names none of its member's steps starts with no step and has to be stopped and launched again. + - It names none, and exactly one of its member's steps waits for a launch (pending with the tech lead, its + dependencies done, queued for no lane): the call's new input, with that step's name in the description, and + the line that tells the tech lead. The launch record (progress.note_agent_launch) takes the new description, + so the agent binds that step when it starts. Recorded in the audit trail (crew.launch-named). + - It names none and several wait, or it names several equally: no new input, and the line that names them with + the exact description that takes each. + - It names one (or every review it names, which one reviewer's launch holds together), its member has no step + to take, or no step waits for it: (None, []). + Claude Code's Agent and Task calls only, launched by the main session with a devkit crew member's subagent_type. + Codex is left as it is: it applies updatedInput only to a shell command (_codex_may_rewrite), and its spawn's + task_name, not a description, selects the step (progress._native_launch_label, codexlaunch).""" + inp = data.get("tool_input") or {} + kind, label = str(inp.get("subagent_type") or ""), str(inp.get("description") or "") + if agent != "claude" or data.get("agent_id") or data.get("tool_name") not in ("Agent", "Task") or not label: + return None, [] + from . import crew, progress as pg + m = crew.member(kind.split(":")[-1]) if kind else None + sid = str(data.get("session_id") or "") + run = pg.load_run(agent, sid) if m and not m.get("main") and sid else None + if not run or not run.get("plan"): + return None, [] + run = pg.normalize(run) + lane = {"label": label, "persona": pg.persona(kind, label), "type": kind} + steps = _launchable_steps(run, lane) + if not steps: + return None, [] + binds, tied = _named_steps(label, steps) + if binds: + return None, [] + who = crew.who(m) + if tied: + given = [(st["name"], _naming_description(label, st["name"], m["name"], steps)) for st in tied] + names = ", ".join(f"“{n}”" for n, _ in given) + return None, [f"the launch “{label}” names {names} equally, so it takes none of {who}'s steps when it " + f"starts. The description that takes one: " + + " · ".join(f"“{d}” for “{n}”" for n, d in given if d) + + f"; for this launch, dev progress assign \"\" --to \"{label}\" links the one it does"] + waiting = [st for st in steps if not st.get("waits_lane") and st.get("state") in ("pending", "unverified") + and not pg.deps_open(run, st)] + if len(waiting) == 1: + name = waiting[0]["name"] + new = _naming_description(label, name, m["name"], steps) + if not new: + return None, [] + try: + from . import audit + audit.record("crew.launch-named", m["name"], f"“{label}” named none of its steps: launched as “{new}” " + f"for “{name}”", "ok", project=run.get("project") or "", + launch=str(data.get("tool_use_id") or "")[:40]) + except Exception as e: + _swallowed("pre-tool", e) + return dict(inp, description=new), [ + f"the launch “{label}” named none of {who}'s steps, so devkit put the one step waiting for its launch in " + f"its description: it starts as “{new}” and takes “{name}”. A launch binds only to the step its " + f"description names: name it there yourself next time."] + if len(waiting) > 1: + given = [(st["name"], _naming_description(label, st["name"], m["name"], steps)) for st in waiting] + names = ", ".join(f"“{n}”" for n, _ in given) + return None, [f"the launch “{label}” names none of {who}'s steps, and {len(waiting)} wait for its launch " + f"({names}): a launch binds only to the step its description names, so this one starts with " + f"no step. Stop it and launch it again with the description that takes the one it does: " + + " · ".join(f"“{d}” for “{n}”" for n, d in given if d)] + return None, [] + + def pre_tool(agent: str): """PreToolUse, `dev hook pre-tool` (`dev hook guard` runs it too, for sessions whose settings predate the name): it records the call, routes a crew member's devkit calls to its lane, and adds advice, a matching lesson rule's @@ -2958,9 +3071,16 @@ def _pre_tool(agent: str, data: dict): advice = _advice(agent, "crew-limits", lambda: _crew_limits_advice(agent, data)) + \ _advice(agent, "stub-commit", lambda: _stub_commit_advice(data)) + \ _advice(agent, "crew-scope", lambda: _scope_advice(agent, data)) - if tool in AGENT_LAUNCHES: # a subagent launch: its label for progress + named = None # a crew launch's input with the step its description names (_launch_naming) + if tool in ("Agent", "Task"): + try: + named, told = _launch_naming(agent, data) + advice += told + except Exception: + _log(f"pre-tool launch naming {agent}: {traceback.format_exc()[-300:]}") + if tool in AGENT_LAUNCHES: # a subagent launch: its label for progress, the one its agent binds by try: - progress.note_agent_launch(agent, data) + progress.note_agent_launch(agent, dict(data, tool_input=named) if named else data) except Exception as e: _swallowed("pre-tool", e) if agent == "codex" and tool == "apply_patch": @@ -2990,20 +3110,23 @@ def _pre_tool(agent: str, data: dict): out = _with_context(agent, _rewrite(agent, routed or stamped), data, skip, advice) print(json.dumps({"hookSpecificOutput": out}, ensure_ascii=False)) return - if tool in ("Agent", "Task"): # subagent briefs get the skills their work requires + if tool in ("Agent", "Task"): # subagent briefs get the skills their work requires, on the named description + base = named or data.get("tool_input") or {} try: from . import skillguard sf_ = _session_file(agent, data.get("session_id") or "-") sess_ = (core.read_json(sf_, {}) or {}) if sf_.exists() else {} - updated = skillguard.on_agent_brief(agent, data.get("tool_input") or {}, _session_project(data, sess_)) + updated = skillguard.on_agent_brief(agent, base, _session_project(data, sess_)) except Exception: updated = None + updated = updated or named # both rewrites go out in one updatedInput try: # the brief's lessons, for the member it launches (its first call records them as shown to it) - _stash_brief(agent, data, (updated or data.get("tool_input") or {}).get("prompt")) + _stash_brief(agent, data, (updated or base).get("prompt")) except Exception as e: _swallowed("pre-tool", e) if updated and (agent != "codex" or _codex_may_rewrite(data, updated)): # every Codex `allow` is checked - _log(f"skills {agent}: appended required skills and known pitfalls to a subagent brief") + _log(f"skills {agent}: a subagent brief with its required sections" + + (f", launched as “{named['description']}”" if named else "")) out = _rewrite(agent, updated) if advice: out["additionalContext"] = _advice_text(advice) diff --git a/plugin/skills/crew/SKILL.md b/plugin/skills/crew/SKILL.md index 2258c5da..2c6073b5 100644 --- a/plugin/skills/crew/SKILL.md +++ b/plugin/skills/crew/SKILL.md @@ -152,7 +152,9 @@ dev crew graph --global # every live session on this Mac (the defau - The plan's `after` dependencies and each lane (the main session, each member) give the ETA as a critical path: `api` and `ui` run in parallel, so the ETA counts the longer one, not both. - **A step binds to the launch that names it.** A new launch takes the ready step its description names, so put the - step's name in the launch description (`dev crew brief --step` does). `assign` gives a step to a member's working + step's name in the launch description (`dev crew brief --step` does). On Claude Code, a launch that names none of + its member's steps gets the one waiting step's name from the pre-tool hook, which tells you; with several waiting, + it gives you the exact description that takes each. `assign` gives a step to a member's working lane at once, when its dependencies are done, if that lane's launch names the step or the lane holds no other open step; otherwise the step is queued for the member's lanes (next item), or, when the member does not work, waits for a launch, and you are told why. A step delegated into a working lane closes only on that lane's own evidence: diff --git a/tests/test_hooks_launch.py b/tests/test_hooks_launch.py new file mode 100644 index 00000000..312d183b --- /dev/null +++ b/tests/test_hooks_launch.py @@ -0,0 +1,130 @@ +# Copyright (c) 2026 Firefly Software Solutions Inc. +# SPDX-License-Identifier: Apache-2.0 +# A crew launch is checked before it starts (hooks._launch_naming, run by the PreToolUse hook on Claude Code's Agent +# call): a step binds only to the launch whose description names it (progress._bind_step), so a description that +# names none of its member's steps gets the name of the one step waiting for that launch, in the same updatedInput +# that carries the brief's required skills; with several waiting, or several named equally, the tech lead gets the +# exact description to use. Progress state and the audit trail in a temporary folder (test_crew.TempState). +# Tests carry comments, not docstrings (`dev test prove` leaves out tests with one). +# Run: python3 -m unittest tests.test_hooks_launch -v +import contextlib +import io +import json +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) +import _hermetic # noqa: E402 + +_hermetic.activate() # run alone, this module gets the suite's temporary home too +sys.path.insert(0, str(ROOT / "lib")) + +from devkit import audit, hooks # noqa: E402 +from devkit import progress as pg # noqa: E402 +from test_crew import TempState # noqa: E402 + +VAGUE = "Mouse: visual acceptance tests" # the launch of lesson L-gj1ctj93041: it names no word of "v23-qa" + + +def call(description: str, tid: str = "toolu_m1", kind: str = "devkit:mouse") -> dict: + return {"session_id": "s1", "tool_name": "Agent", "tool_use_id": tid, "hook_event_name": "PreToolUse", + "cwd": tempfile.gettempdir(), + "tool_input": {"description": description, "subagent_type": kind, "prompt": "Write the tests."}} + + +def pre_tool(data: dict) -> dict: + # the hook as Claude Code runs it, in-process: its one JSON output, {} when it prints none + out = io.StringIO() + with contextlib.redirect_stdout(out): + hooks._pre_tool("claude", data) + return (json.loads(out.getvalue()) if out.getvalue().strip() else {}).get("hookSpecificOutput") or {} + + +def started(aid: str = "a1", tid: str = "toolu_m1", kind: str = "devkit:mouse"): + # the launched agent starts and the Agent call's result names it, as the hooks record them + pg.on_subagent("claude", {"session_id": "s1", "agent_id": aid, "agent_type": kind}, True) + pg.launch_result("claude", {"session_id": "s1", "tool_use_id": tid, "tool_response": {"agentId": aid}}) + + +def owner(step: str) -> str: + return next(s.get("owner") for s in pg.load_run("claude", "s1")["plan"] if s["name"] == step) + + +class OneWaitingStepTests(unittest.TestCase): + def test_a_launch_that_names_no_step_gets_the_waiting_steps_name_and_takes_that_step(self): + with TempState(): + pg.start("Acceptance", plan=["v23-qa", "docs"]) + pg.assign("v23-qa", "Mouse") + new = pre_tool(call(VAGUE)).get("updatedInput") or {} + started() + self.assertEqual(new.get("description"), "Mouse: v23-qa visual acceptance tests") + self.assertEqual(owner("v23-qa"), "a1") # the launch record holds the new description too + + def test_the_tech_lead_reads_the_added_step_in_the_context_and_the_audit_records_it(self): + with TempState(): + pg.start("Acceptance", plan=["v23-qa"]) + pg.assign("v23-qa", "Mouse") + context = pre_tool(call(VAGUE)).get("additionalContext") or "" + records = [r for r in audit.query(days=1) if r.get("action") == "crew.launch-named"] + self.assertIn("“Mouse: visual acceptance tests” named none of QA engineer (Mouse)'s steps", context) + self.assertIn("it starts as “Mouse: v23-qa visual acceptance tests” and takes “v23-qa”", context) + self.assertEqual(len(records), 1, records) + self.assertIn("launched as “Mouse: v23-qa visual acceptance tests” for “v23-qa”", records[0]["detail"]) + + def test_the_added_step_and_the_briefs_required_sections_go_out_in_one_input(self): + with TempState(): + pg.start("Acceptance", plan=["v23-qa"]) + pg.assign("v23-qa", "Mouse") + new = pre_tool(call(VAGUE)).get("updatedInput") or {} + self.assertEqual(new.get("description"), "Mouse: v23-qa visual acceptance tests") + self.assertTrue(new.get("prompt", "").startswith("Write the tests."), new) + self.assertIn("## devkit · your report", new.get("prompt", "")) + self.assertEqual(new.get("subagent_type"), "devkit:mouse") + + def test_a_description_without_a_member_prefix_gets_the_step_name_in_front(self): + with TempState(): + pg.start("Acceptance", plan=["v23-qa"]) + pg.assign("v23-qa", "Mouse") + new = pre_tool(call("visual acceptance tests")).get("updatedInput") or {} + started() + self.assertEqual(new.get("description"), "v23-qa visual acceptance tests") + self.assertEqual(owner("v23-qa"), "a1") + + +class NoticeTests(unittest.TestCase): + def test_several_waiting_steps_get_a_notice_with_the_description_for_each_and_no_rewrite(self): + with TempState(): + pg.start("Acceptance", plan=["v23-qa", "v24-a11y"]) + for step in ("v23-qa", "v24-a11y"): + pg.assign(step, "Mouse") + out = pre_tool(call(VAGUE)) + given = [hooks._launch_naming("claude", call(d, tid=f"toolu_{i}")) + for i, d in enumerate(("Mouse: v23-qa visual acceptance tests", + "Mouse: v24-a11y visual acceptance tests"))] + context = out.get("additionalContext") or "" + self.assertEqual((out.get("updatedInput") or {}).get("description", VAGUE), VAGUE) + self.assertIn("names none of QA engineer (Mouse)'s steps, and 2 wait for its launch (“v23-qa”, “v24-a11y”)", + context) + self.assertIn("“Mouse: v23-qa visual acceptance tests” for “v23-qa”", context) + self.assertIn("“Mouse: v24-a11y visual acceptance tests” for “v24-a11y”", context) + self.assertEqual(given, [(None, []), (None, [])]) # each description it gives names its step alone + + def test_a_description_that_names_two_steps_equally_gets_a_notice_that_tells_them_apart(self): + with TempState(): + pg.start("Tests", plan=["visual tests", "unit tests"]) + for step in ("visual tests", "unit tests"): + pg.assign(step, "Mouse") + new, told = hooks._launch_naming("claude", call("Mouse: tests")) + again = hooks._launch_naming("claude", call("Mouse: visual tests", tid="toolu_m2")) + self.assertIsNone(new) + self.assertEqual(len(told), 1, told) + self.assertIn("“Mouse: tests” names “visual tests”, “unit tests” equally", told[0]) + self.assertIn("“Mouse: visual tests” for “visual tests” · “Mouse: unit tests” for “unit tests”", told[0]) + self.assertEqual(again, (None, [])) + + +if __name__ == "__main__": + unittest.main() From 9f5dfd0a53a6d2e2260851cbb29fdf2978964b7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 15:43:19 -0800 Subject: [PATCH 02/22] fix(bugs): post registry records anew instead of editing them GitHub keeps every earlier body of an edited comment in a public edit history, so record comments the workflow edited in place still showed the old shared voter digests, which link one person's votes across reports. Root cause: the registry workflow wrote each record with PATCH on the same comment (_write called edit_comment), and a comment's edit history goes only when the comment is deleted Each write posts the record as a new comment, then deletes the old one with its history; posting first means a stopped run leaves two records, never none. The workflow and devkit read the newest bot record, and the next write deletes the older one. The record's seen counter skips the bot's own comments, so a reposted record does not trigger another rewrite. The manual run also posts anew the record of every registry issue closed more than 90 days ago when its comment was ever edited or still uses the older digests, keeping its votes and counts; a second run writes nothing. GitHub requests that may succeed later are tried up to three times, except posts. Verified: python3 -m unittest of test_bug_registry_action, test_bugs_sync, test_bugs_render, test_ci_commands, test_workflow_ci, test_consistency, test_docs_check, test_security_corpus (281 passed); dev test prove (9 new or changed tests fail without the fix) --- .github/workflows/bug-registry.yml | 3 +- docs/bug-registry.md | 19 +++-- lib/devkit/bugs.py | 13 +++- tests/test_bug_registry_action.py | 99 +++++++++++++++++++---- tests/test_bugs_sync.py | 18 +++++ tools/bug_registry_action.py | 121 +++++++++++++++++++++-------- 6 files changed, 217 insertions(+), 56 deletions(-) diff --git a/.github/workflows/bug-registry.yml b/.github/workflows/bug-registry.yml index 37b11bed..5a43f009 100644 --- a/.github/workflows/bug-registry.yml +++ b/.github/workflows/bug-registry.yml @@ -19,7 +19,8 @@ on: release: types: [published] # Run by hand once after a release that changes how registry issues read: it rewrites every registry issue's title, - # text and record, folding nothing. Only accounts with write access can start it. + # text and record, and posts anew the edited records of bugs closed longer ago, folding nothing. Only accounts with + # write access can start it. workflow_dispatch: permissions: {} diff --git a/docs/bug-registry.md b/docs/bug-registry.md index e7097da0..2815f9f2 100644 --- a/docs/bug-registry.md +++ b/docs/bug-registry.md @@ -448,7 +448,7 @@ This is a bug in devkit, not in your project. In a terminal: ## For maintainers - Fingerprint `fa07ec67c27c`, kind `crash`, component `progress`, score 10.0 (`dev bug top` ranks it). -- The workflow's record of this bug is its first comment. This text is written from it. +- The workflow's record of this bug is the newest comment its bot wrote with the record data. This text is written from it.
Report data for devkit's registry (do not edit) @@ -498,7 +498,7 @@ The registry is public: anyone can read its issues and comments on GitHub. | Your GitHub login | On each issue you opened and each comment devkit posted for you | Until you delete the comment; votes, confirmations, and failure marks are deleted by the workflow once it folds them | | The devkit facts of a report (see [What is sent, and what never is](#what-is-sent-and-what-never-is)) | Your report comment, or the issue you opened | Until the issue or comment is deleted | | Free text you or the agent wrote, cleaned | Escaped, and only in your own issue or your own comment | Until you remove it; the next rewrite of the issue follows | -| Your account in the record | A keyed hash of your account id, never your login, inside the record's collapsed block | Every write of the record drops accounts quiet for 90 days: their votes, regression marks, and detour marks. A team member's older confirmation or failure mark stays as a placeholder without the account's hash, so a detour's trust does not change | +| Your account in the record | A keyed hash of your account id, never your login, inside the record's collapsed block | Every write of the record drops accounts quiet for 90 days: their votes, regression marks, and detour marks. A team member's older confirmation or failure mark stays as a placeholder without the account's hash, so a detour's trust does not change. No edit history keeps an earlier record: each write posts the record anew and deletes the old comment | - **Stop posting.** `dev bug share off` stops every public post from your Mac, automatic reports included, and `bugs.sync: false` stops every send (see [Turn reporting off](#turn-reporting-off)). @@ -526,6 +526,11 @@ scoring code as the client (`lib/devkit/bugs.py`), so the two cannot disagree. too deep): any error while checking a payload marks it invalid, and folding goes on. A report counts only when its fingerprint is the one its kind, exception class, frames, refusal id, and command word give; the workflow recomputes it. A record a maintainer edited by hand is rewritten on the next fold. +- **The record is posted anew, never edited:** every earlier body of an edited comment stays in GitHub's public edit + history, which goes only with the comment. Each write of a record therefore posts it as a new comment, then deletes + the old one, and its history with it. The post comes first, so a run that stops in between leaves two + record comments and never none: devkit and the workflow read the newest, and the next write deletes the other. + Each write sends the issue's subscribers a notification, as any new comment does. - **Labels:** the workflow applies the labels after it validates the issue's first payload, because GitHub drops labels set by people without push access. An issue whose first payload fails validation gets no label, and devkit ignores it. @@ -634,9 +639,13 @@ gh workflow run bug-registry.yml --repo fireflysoftwaresolutions/devkit The run creates the verdict labels the repository lacks, then rewrites the title, body, and record of every registry issue, open or closed in the last 90 days, without folding anything: the score and what each bug has seen stay as -they are, and accounts quiet for 90 days go, as on any write. It waits at least a second between requests and stops -after 200 issues, printing how many are left. An issue whose text is current costs one read, so running it again -goes on where it stopped. +they are, and accounts quiet for 90 days go, as on any write. For a registry issue closed longer ago, it posts the +record anew only when its comment was ever edited or still names accounts by digests from before they were keyed +per bug: the same votes and counts, keyed per bug, and the issue's text left as it is. Either way the old comment +goes, with the earlier bodies its edit history kept. It waits at least a second between requests, tries a request +GitHub may answer later up to three times, and stops after 200 issues, printing how many it rewrote, how many it +posted anew, and how many are left. An issue that is current costs one read, so running it again goes on where it +stopped, and a run after the last one writes nothing. ### Plan a hotfix diff --git a/lib/devkit/bugs.py b/lib/devkit/bugs.py index 85255c27..00f1f131 100644 --- a/lib/devkit/bugs.py +++ b/lib/devkit/bugs.py @@ -1981,7 +1981,8 @@ def render_issue(rec: dict, first: dict = None, *, created: str = "", now: float "## For maintainers", "", f"- Fingerprint `{fp}`, kind `{_safe(rec.get('kind'))}`, component `{_safe(rec.get('component'))}`, " f"score {score_:.1f} (`dev bug top` ranks it).", - "- The workflow's record of this bug is its first comment. This text is written from it.", ""] + "- The workflow's record of this bug is the newest comment its bot wrote with the record data. " + "This text is written from it.", ""] if first.get("devkit_bug") == SCHEMA_VERSION: parts += ["
", "Report data for devkit's registry (do not edit)", "", _json_block(first), "", "
", ""] @@ -2243,7 +2244,9 @@ def match(fp: str, version: str): def _bot_record(comments: list): - for c in sorted((c for c in comments or [] if isinstance(c, dict)), key=lambda c: c.get("id") or 0): + """The record of the bot's newest readable record comment, or None. The workflow never edits a record in place: + it posts each new record before it deletes the old comment, so the newest one is current whatever its id.""" + for c in sorted((c for c in comments or [] if isinstance(c, dict)), key=lambda c: -(c.get("id") or 0)): user = c.get("user") or {} if user.get("login") == BOT_LOGIN and user.get("type") == "Bot": rec = parse_record(c.get("body")) @@ -2285,9 +2288,11 @@ def _iso(ts: float) -> str: def _fresh_records(client, since: str) -> dict: """{issue number: record} from the bot comments changed since `since`, through the client's repository-wide - comment listing (one request, where reading each issue's comments would take one per issue).""" + comment listing (one request, where reading each issue's comments would take one per issue). An issue's newest + bot record counts, as in _bot_record.""" found = {} - for c in sorted((c for c in client.updated_comments(since) if isinstance(c, dict)), key=lambda c: c.get("id") or 0): + for c in sorted((c for c in client.updated_comments(since) if isinstance(c, dict)), + key=lambda c: -(c.get("id") or 0)): m = re.search(r"/issues/(\d+)$", str(c.get("issue_url") or "")) if m and int(m.group(1)) not in found: rec = _bot_record([c]) diff --git a/tests/test_bug_registry_action.py b/tests/test_bug_registry_action.py index 698b6a20..d4953e90 100644 --- a/tests/test_bug_registry_action.py +++ b/tests/test_bug_registry_action.py @@ -138,6 +138,7 @@ def __init__(self): self.after_record_write = None # plays the reporter: edits the issue right after the bot writes its record self.max_body = 65536 # GitHub refuses a longer comment with HTTP 422 self.label_list, self.paced = [], 0.0 + self.delete_fails = False # plays a run stopped after it posted a record and before it deleted the old one # ---- set-up def add_issue(self, number, body, user, assoc="NONE", **fields): @@ -204,11 +205,12 @@ def comments(self, number): return copy.deepcopy(sorted((c for c in self.notes.values() if c["issue"] == number), key=lambda c: -c["id"])) def comment(self, cid): + """The comment, or {} once it is deleted, as the client answers a 404.""" self.calls.append(("comment", cid)) if self.on_reread: hook, self.on_reread = self.on_reread, None hook(self) - return copy.deepcopy(self.notes[cid]) + return copy.deepcopy(self.notes.get(cid) or {}) def _check_size(self, body): if self.max_body is not None and len(body) > self.max_body: @@ -221,14 +223,15 @@ def create_comment(self, number, body): self._wrote_record(body) return {"id": cid} - def edit_comment(self, cid, body): - self._check_size(body) - self.writes.append(("edit_comment", cid)) + def edit(self, cid, body, ts=NOW - 2 * DAY): + """Edit a comment as an older workflow or a person did: GitHub keeps the earlier body in its edit history and + moves updated_at. The client has no way to edit a comment, so the workflow cannot.""" self.notes[cid]["body"] = body - self.notes[cid]["updated_at"] = _iso(NOW) - self._wrote_record(body) + self.notes[cid]["updated_at"] = _iso(ts) def delete_comment(self, cid): + if self.delete_fails: + raise action.GitHubError(f"DELETE comments/{cid}: HTTP 502", status=502) self.writes.append(("delete_comment", cid)) self.notes.pop(cid, None) @@ -345,7 +348,7 @@ def test_folds_every_unfolded_payload_in_comment_id_order(self): self.assertEqual(set(rec["voters"]), {_h(1), _h(4), _h(5)}) self.assertEqual([(d["id"], d["trust"]) for d in rec["detours"]], [("d1", "verified")]) self.assertEqual(rec["seen"], last) - self.assertEqual(fake.record_comment(12)["id"], record_id) # the same comment, rewritten + self.assertNotIn(record_id, fake.ids(12)) # posted anew: the old comment went, with its edit history def test_invalid_payloads_are_ignored_and_left_alone(self): fake = FakeGitHub() @@ -564,15 +567,16 @@ def test_a_hand_edited_record_is_rewritten(self): rc, _, err = _run(fake, "issue_comment", 12, comment=chat) self.assertEqual(rc, 0, err) rec = fake.record(12) - self.assertEqual(fake.notes[record_id]["body"], bugs.render_record(rec)) - self.assertTrue(fake.notes[record_id]["body"].startswith(f"**Bug {FP}**")) + self.assertEqual(fake.record_comment(12)["body"], bugs.render_record(rec)) + self.assertTrue(fake.record_comment(12)["body"].startswith(f"**Bug {FP}**")) self.assertEqual(rec["detours"], []) self.assertIn(fake_record, fake.ids(12)) + note = fake.record_comment(12) note["body"] = note["body"].replace("```json\n{", "```json\n{{") # the JSON broken by an edit rc, _, err = _run(fake, "issue_comment", 12, comment=chat) self.assertEqual(rc, 0, err) - self.assertEqual(fake.record_comment(12)["id"], record_id) + self.assertNotIn(note["id"], fake.ids(12)) # rewritten as one new record, not doubled self.assertEqual(set(fake.record(12)["voters"]), {_h(1)}) def test_a_record_changed_while_folding_is_read_again(self): @@ -589,6 +593,23 @@ def release_writes_first(f): self.assertEqual((rec["fixed_in"], rec["status"]), ("26.11.8", "fixed")) self.assertIn(_h(3), rec["voters"]) + def test_a_record_is_posted_anew_before_its_old_comment_goes_so_a_stopped_run_loses_nothing(self): + fake = FakeGitHub() + record_id = fake.registry_issue(12) + fake.delete_fails = True # the run stops right after it posted the new record + vote = fake.add_comment(12, _body(_payload("vote")), _user(3)) + rc, _, err = _run(fake, "issue_comment", 12, comment=vote) + self.assertEqual(rc, 1, err) + held = sorted(c["id"] for c in fake.notes.values() if c["user"] == BOT and bugs.RECORD_MARK in c["body"]) + self.assertEqual(held[0], record_id) + self.assertIn(_h(3), bugs.parse_record(fake.notes[held[-1]]["body"])["voters"]) + fake.delete_fails = False + chat = fake.add_comment(12, "Same here.", _user(5)) + rc, _, err = _run(fake, "issue_comment", 12, comment=chat) + self.assertEqual(rc, 0, err) + self.assertEqual(set(fake.record(12)["voters"]), {_h(1), _h(3)}) # the newest record, and only it, is left + self.assertNotIn(record_id, fake.ids(12)) + class VoterPrivacyTests(unittest.TestCase): """An account's digest is keyed by the bug as well, so the public records cannot link one person's votes, @@ -1165,6 +1186,44 @@ def test_it_waits_a_second_between_requests_and_makes_the_verdict_labels(self): self.assertEqual(_run(fake, "workflow_dispatch")[0], 0) self.assertEqual(fake.writes, []) + def test_it_posts_an_edited_record_anew_with_its_votes_once(self): + fake = FakeGitHub() + for number in (12, 17): + fake.registry_issue(number) + self.assertEqual(_run(fake, "workflow_dispatch")[0], 0) + old = fake.record_comment(12) + voters = fake.record(12)["voters"] + fake.edit(old["id"], old["body"]) # edited in place by an older workflow: GitHub keeps the earlier bodies + fake.writes.clear() + rc, out, err = _run(fake, "workflow_dispatch") + self.assertEqual(rc, 0, err) + self.assertEqual(fake.writes, [("create_comment", 12), ("delete_comment", old["id"])]) + self.assertEqual(fake.record(12)["voters"], voters) + self.assertIn("rewrote 1 issue(s)", out) + fake.writes.clear() + self.assertEqual(_run(fake, "workflow_dispatch")[0], 0) + self.assertEqual(fake.writes, []) + + def test_it_posts_anew_the_record_of_a_bug_closed_long_ago_keyed_per_bug_with_every_vote(self): + fake = FakeGitHub() + record_id = fake.registry_issue(22, rec_ts=OLD) + fake.issues[22].update(state="closed", state_reason="completed", closed_at=_iso(OLD), updated_at=_iso(OLD)) + rec = fake.record(22) + rec.pop("voter_hash", None) # written by a workflow that published one digest per account on every bug + rec["voters"] = {_account(1): rec["voters"][_h(1)], _account(2): {"impact": "minor", "ts": OLD}} + fake.set_record(22, rec) + fake.edit(record_id, fake.notes[record_id]["body"], ts=OLD + DAY) + issue = copy.deepcopy(fake.issues[22]) + rc, out, err = _run(fake, "workflow_dispatch") + self.assertEqual(rc, 0, err) + self.assertEqual(fake.record(22)["voters"].keys(), {_h(1), _h(2)}) # rekeyed; none pruned, though quiet long + self.assertNotIn(record_id, fake.ids(22)) + self.assertEqual(fake.issues[22], issue) # its text stays as it is + self.assertIn("posted anew 1 record(s)", out) + fake.writes.clear() + self.assertEqual(_run(fake, "workflow_dispatch")[0], 0) + self.assertEqual(fake.writes, []) + class _Response: def __init__(self, status=200, data=None, link=""): @@ -1183,7 +1242,7 @@ def __exit__(self, *exc): class ClientTests(unittest.TestCase): def _client(self, answers): - seen = [] + seen, self.slept = [], [] def opener(req, timeout): seen.append(req) @@ -1191,7 +1250,7 @@ def opener(req, timeout): if isinstance(answer, int): raise urllib.error.HTTPError(req.full_url, answer, "error", {}, io.BytesIO(b'{"message":"no"}')) return answer - return action.GitHub(repo="owner/registry", token="t0k3n-value", opener=opener), seen + return action.GitHub(repo="owner/registry", token="t0k3n-value", opener=opener, sleep=self.slept.append), seen def test_requests_carry_the_token_in_a_header_and_read_every_page(self): client, seen = self._client([_Response(data=[{"id": 2}], link='; rel="next"'), @@ -1202,7 +1261,7 @@ def test_requests_carry_the_token_in_a_header_and_read_every_page(self): and "t0k3n" not in r.full_url for r in seen)) def test_membership_closures_and_gone_comments(self): - client, seen = self._client([_Response(status=204), 404, 404, _Response(data={"data": {"repository": { + client, seen = self._client([_Response(status=204), 404, 404, 404, _Response(data={"data": {"repository": { "issue": {"timelineItems": {"nodes": [{"actor": {"login": "maint", "databaseId": 9}, "stateReason": "COMPLETED", "closer": {"__typename": "PullRequest", "merged": True}}]}}}}})]) @@ -1210,10 +1269,20 @@ def test_membership_closures_and_gone_comments(self): self.assertFalse(client.is_member("outsider")) self.assertTrue(client.is_member("Owner")) # the repository's owner, without asking client.delete_comment(5) # already gone: nothing to do + self.assertEqual(client.comment(5), {}) # a record another run replaced reads as changed self.assertEqual(client.closure(60), {"actor": "maint", "actor_id": 9, "merged_pr": True}) - self.assertEqual(len(seen), 4) + self.assertEqual(len(seen), 5) with self.assertRaises(action.GitHubError): - self._client([500])[0].issue(1) + self._client([500, 500, 500])[0].issue(1) + + def test_a_request_github_may_answer_later_is_tried_three_times_but_a_post_once(self): + client, seen = self._client([502, 503, _Response(data={"number": 1})]) + self.assertEqual(client.issue(1), {"number": 1}) + self.assertEqual((len(seen), self.slept), (3, [2.0, 4.0])) + client, seen = self._client([502, _Response(data={"id": 9})]) + with self.assertRaises(action.GitHubError): # posting again after a lost answer could post a record twice + client.create_comment(12, "a record") + self.assertEqual((len(seen), self.slept), (1, [])) def test_the_duplicate_search_reads_only_registry_issues(self): label = [{"name": "devkit-bug"}] diff --git a/tests/test_bugs_sync.py b/tests/test_bugs_sync.py index ffc530a0..ca706b14 100644 --- a/tests/test_bugs_sync.py +++ b/tests/test_bugs_sync.py @@ -845,6 +845,24 @@ def test_cache_trusts_only_the_bot_record(self): self.assertEqual(bugs.match(FP, "26.11.7")["bug"]["number"], 42) self.assertIsNone(bugs.match("aaaaaaaaaaaa", "26.11.7")) + def test_the_cache_reads_the_newest_bot_record_of_an_issue(self): + # the workflow posts each record anew before it deletes the old one: a run stopped between leaves both + fixed = bugs.render_record(_record(status="fixed", fixed_in="26.11.7")) + client = FakeClient([_issue(42)], {42: [_bot(fixed, 15), _bot(bugs.render_record(_record()), 10)]}) + self.assertTrue(bugs.fetch(client, now=NOW)["ok"]) + self.assertEqual(bugs.match(FP, "26.11.7")["bug"]["fixed_in"], "26.11.7") + + def test_the_changed_comments_listing_takes_the_newest_bot_record_of_an_issue(self): + url = f"https://api.github.com/repos/{core.DEVKIT_REPO}/issues/42" + + class ListingClient(FakeClient): + def updated_comments(self, since): + return [{**_bot(bugs.render_record(_record()), 10), "issue_url": url}, + {**_bot(bugs.render_record(_record(status="fixed", fixed_in="26.11.7")), 15), + "issue_url": url}] + self.assertTrue(bugs.fetch(ListingClient([_issue(42)]), now=NOW)["ok"]) + self.assertEqual(bugs.match(FP, "26.11.7")["bug"]["fixed_in"], "26.11.7") + def test_match_serves_only_team_and_verified_for_the_version(self): detours = [{**TEAM_HINT, "id": "d1", "since": "26.11.5"}, {**TEAM_HINT, "id": "d2", "steps": [{"dev": "sync --offline"}], "since": "26.11.5", diff --git a/tools/bug_registry_action.py b/tools/bug_registry_action.py index 4c7e60fb..c9df2e96 100644 --- a/tools/bug_registry_action.py +++ b/tools/bug_registry_action.py @@ -25,6 +25,13 @@ only with the fingerprint its own fields give. - The record always fits in one comment (bugs.render_record). If GitHub still refuses it, the record keeps its old content with this run's `seen` and `folds`: the payloads count toward the cap and are not folded again. +- A record comment is never edited in place. GitHub shows every earlier body of an edited comment in its public edit + history, and drops that history only with the comment, so each write posts the record as a new comment and then + deletes the old one (_write). Posting first means a run stopped between the two leaves two records, never none; + the newest is the record, and the next write deletes the other. +- The manual run also posts anew the record of every registry issue closed longer ago: a record comment that was + ever edited, or that still names accounts by the older digests, gets the same record, keyed per bug, as a new + comment, and the old one goes with its history. A record posted anew has no edit, so a second run changes nothing. - A later issue for a fingerprint that already has one is closed as its duplicate. It keeps a small record of its own (status `duplicate`), and its payloads, now and later, are folded into the first issue's record. The first issue is a registry issue (labeled devkit-bug, which only this workflow sets), never one that merely quotes a fingerprint. @@ -75,6 +82,8 @@ RERENDER_PACE_S = 1.0 # seconds between two requests of a manual run, inside GitHub's limits for the workflow token TRIES = 3 # writes of one record that found it changed by another run, before the run gives up WAITS, WAIT_S = 4, 15 # a duplicate waits up to a minute for the first issue's own run to write its record +ATTEMPTS, RETRY_S = 3, 2.0 # tries of one request GitHub may answer later, and the wait before the second +RETRIED = frozenset({0, 429, 500, 502, 503, 504}) # no answer (status 0), rate limited, or a server error MAINTAINERS = Path(__file__).resolve().parents[1] / ".github" / "bug-registry-maintainers" MAINTAINER_RE = re.compile(r"([A-Za-z0-9][A-Za-z0-9-]{0,38})\s+([1-9][0-9]{0,15})") # a login, then its account id CLOSURE_QUERY = """query($owner: String!, $name: String!, $number: Int!) { @@ -246,27 +255,44 @@ def _number(value) -> int: def _read(client, number: int): """-> (the issue's comments in id order, the record comment, its record or None). The record comment is the - bot's first comment with the record marker, readable or not, so a broken one is rewritten rather than doubled.""" + bot's newest comment with the record marker, readable or not, so a broken one is rewritten rather than doubled. + Every write posts the record anew before it deletes the old comment (_write), so a run stopped between the two + leaves an older record comment behind: the holder lists those under "older", and the next write deletes them.""" comments = sorted((c for c in client.comments(number) or [] if isinstance(c, dict) and _number(c.get("id"))), key=lambda c: c["id"]) - holder = next((c for c in comments if _by_bot(c) and bugs.RECORD_MARK in (c.get("body") or "")), None) - return comments, holder, (bugs.parse_record(holder.get("body")) if holder else None) + held = [c for c in comments if _by_bot(c) and bugs.RECORD_MARK in (c.get("body") or "")] + if not held: + return comments, None, None + holder = {**held[-1], "older": [c["id"] for c in held[:-1]]} + return comments, holder, bugs.parse_record(holder.get("body")) + + +def _edited(comment: dict) -> bool: + """Whether GitHub keeps an edit history for the comment: its update time is not its creation time.""" + created, updated = comment.get("created_at"), comment.get("updated_at") + return bool(created and updated and created != updated) def _write(client, number: int, holder, rec: dict) -> bool: - """Write the record when the comment's text differs from it: after a fold, or after a person edited the comment. - The comment is read again just before; if it changed since this run read it, Changed says to start over. - -> whether it wrote.""" + """Write the record when the comment's text differs from it (after a fold, or after a person edited the + comment), when the comment was ever edited, or when an older record comment is left. The record is never edited + in place: GitHub keeps every earlier body of an edited comment in a public edit history, which goes only with + the comment. So the new body is posted as a new comment first and the old comment deleted after, and a run + stopped between the two loses no record (_read takes the newest). The comment is read again just before; if it + changed or went since this run read it, Changed says to start over. -> whether it wrote.""" body = bugs.render_record(rec) if holder is None: client.create_comment(number, body) return True - if holder.get("body") == body: - return False - if (client.comment(holder["id"]) or {}).get("body") != holder.get("body"): - raise Changed(number) - client.edit_comment(holder["id"], body) - return True + replaced = [holder["id"]] if holder.get("body") != body or _edited(holder) else [] + if replaced: + if (client.comment(holder["id"]) or {}).get("body") != holder.get("body"): + raise Changed(number) + client.create_comment(number, body) + gone = [cid for cid in holder.get("older") or [] if _number(cid)] + replaced + for cid in gone: + client.delete_comment(cid) + return bool(gone) # --------------------------------------------------------------------------- what the record keeps, and the issue's text @@ -556,7 +582,9 @@ def _fold_issue_once(client, key: bytes, number: int, now: float, sleep, maintai return f"#{number} has no valid first payload: left alone" fp = (rec or first)["fingerprint"] entries = _entries(key, issue, comments, rec, fp, maintainers) - seen = max([c["id"] for c in comments] + [_number((rec or {}).get("seen"))]) + # the bot's own comments are never payloads, and its record comment is posted anew on each write: counting it + # would make every later run see a new `seen` and post the record again + seen = max([c["id"] for c in comments if not _by_bot(c)] + [_number((rec or {}).get("seen"))]) if rec is None: target = _first_issue(client, fp, number, sleep) if target is not None: @@ -665,6 +693,23 @@ def _rerender(client, key: bytes, issue: dict, now: float): raise RegistryError(f"the record of issue #{number} kept changing while this run wrote it") +def _repost(client, key: bytes, issue: dict): + """Post the record of a registry issue closed more than bugs.CLOSED_DAYS ago anew when its comment was ever + edited or its text differs from the record keyed per bug: the same record, its accounts rekeyed per bug and + nothing pruned, so its votes and counts stay; the issue's text is left as it is. -> whether it wrote, or None for + an issue without a readable record of its own.""" + number = _number(issue.get("number")) + for _ in range(TRIES): + _, holder, rec = _read(client, number) + if rec is None or rec.get("status") == "duplicate": + return None + try: + return _write(client, number, holder, _rekeyed(key, rec)) + except Changed: + continue + raise RegistryError(f"the record of issue #{number} kept changing while this run wrote it") + + def _verdict_labels(client) -> list: """Create the `verdict:*` labels the repository lacks, each described by the sentence the issue's text states. -> the labels created.""" @@ -676,33 +721,34 @@ def _verdict_labels(client) -> list: def _rerender_all(client, key: bytes, now: float) -> str: - """Rewrite every registry issue, open or closed in the last 90 days, oldest first, at one request a second at - most. It stops once it has rewritten RERENDER_MAX issues and says how many are left; issues whose text is already - current cost one read each, so running it again goes on where it stopped.""" + """Rewrite every registry issue, open or closed in the last 90 days, and post anew the edited or older-keyed + record of every one closed longer ago (_repost), oldest first, at one request a second at most. It stops once it + has written RERENDER_MAX issues and says how many are left; issues already current cost one read each, so + running it again goes on where it stopped.""" client.pace(RERENDER_PACE_S) made = _verdict_labels(client) cut = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(now - bugs.CLOSED_DAYS * 86400)) - issues = sorted((i for i in client.registry_issues(cut) or [] if isinstance(i, dict) and _number(i.get("number")) - and not i.get("pull_request") and bugs.LABEL in _labels(i) - and (i.get("state") != "closed" or str(i.get("closed_at") or "") >= cut)), - key=lambda i: i["number"]) + issues = sorted((i for i in client.registry_issues("") or [] if isinstance(i, dict) and _number(i.get("number")) + and not i.get("pull_request") and bugs.LABEL in _labels(i)), key=lambda i: i["number"]) issues = list({i["number"]: i for i in issues}.values()) - counts = {"rewritten": 0, "current": 0, "no record": 0} + counts = {"rewritten": 0, "reposted": 0, "current": 0, "no record": 0} for n, issue in enumerate(issues): - if counts["rewritten"] >= RERENDER_MAX: + if counts["rewritten"] + counts["reposted"] >= RERENDER_MAX: break + recent = issue.get("state") != "closed" or str(issue.get("closed_at") or "") >= cut try: - wrote = _rerender(client, key, issue, now) + wrote = _rerender(client, key, issue, now) if recent else _repost(client, key, issue) except (GitHubError, RegistryError) as e: raise RegistryError(f"stopped at #{issue['number']} ({e}): {_tally(counts, made)}, " f"{len(issues) - n} left") from None - counts["rewritten" if wrote else "current" if wrote is False else "no record"] += 1 + counts[("rewritten" if recent else "reposted") if wrote else "current" if wrote is False else "no record"] += 1 return f"{_tally(counts, made)}, {len(issues) - sum(counts.values())} left" def _tally(counts: dict, made: list) -> str: return (f"created {len(made)} verdict label(s); " if made else "") + \ - f"rewrote {counts['rewritten']} issue(s), {counts['current']} already current, " \ + f"rewrote {counts['rewritten']} issue(s), posted anew {counts['reposted']} record(s) of bugs closed more " \ + f"than {bugs.CLOSED_DAYS} days ago, {counts['current']} already current, " \ f"{counts['no record']} without a record of their own" @@ -799,7 +845,21 @@ def _wait(self) -> None: self._sleep(self._gap - (self._clock() - self._last)) self._last = self._clock() - def _call(self, method: str, path: str, params: dict = None, body=None, missing_ok: bool = False): + def _call(self, method: str, path: str, params: dict = None, body=None, missing_ok: bool = False, + retry: bool = None): + """One request, tried up to ATTEMPTS times when GitHub may answer it later (no answer, 429, or a 5xx), with + waits of RETRY_S, then twice that. A POST is tried once unless `retry` says it only reads: posting a comment + again after a lost answer could post it twice.""" + retry = method != "POST" if retry is None else retry + for attempt in range(ATTEMPTS): + try: + return self._once(method, path, params, body, missing_ok) + except GitHubError as e: + if not retry or e.status not in RETRIED or attempt == ATTEMPTS - 1: + raise + self._sleep(RETRY_S * 2 ** attempt) + + def _once(self, method: str, path: str, params: dict, body, missing_ok: bool): self._wait() url = f"{self.API}/{path}" + (f"?{urllib.parse.urlencode(params)}" if params else "") data = None if body is None else json.dumps(body).encode("utf-8") @@ -840,14 +900,12 @@ def comments(self, number: int) -> list: return self._pages(f"{self._issues()}/{int(number)}/comments") def comment(self, comment_id: int) -> dict: - return self._call("GET", f"{self._issues()}/comments/{int(comment_id)}")[1] or {} + """The comment, or {} once it is deleted.""" + return self._call("GET", f"{self._issues()}/comments/{int(comment_id)}", missing_ok=True)[1] or {} def create_comment(self, number: int, body: str) -> dict: return self._call("POST", f"{self._issues()}/{int(number)}/comments", body={"body": body})[1] or {} - def edit_comment(self, comment_id: int, body: str) -> None: - self._call("PATCH", f"{self._issues()}/comments/{int(comment_id)}", body={"body": body}) - def delete_comment(self, comment_id: int) -> None: self._call("DELETE", f"{self._issues()}/comments/{int(comment_id)}", missing_ok=True) @@ -899,7 +957,8 @@ def closure(self, number: int) -> dict: merged, and an account id it cannot read as 0.""" owner, name = self.repo.split("/", 1) data = self._call("POST", "graphql", body={"query": CLOSURE_QUERY, - "variables": {"owner": owner, "name": name, "number": int(number)}})[1] + "variables": {"owner": owner, "name": name, "number": int(number)}}, + retry=True)[1] node = ((((data or {}).get("data") or {}).get("repository") or {}).get("issue") or {}) nodes = (node.get("timelineItems") or {}).get("nodes") or [] last = nodes[-1] if nodes and isinstance(nodes[-1], dict) else {} From 3582dc97d996a8abcf759a2aa78ed61399efd58e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 15:56:16 -0800 Subject: [PATCH 03/22] feat(progress): tell a member when its queued step goes to someone else A step queued for a member's busy lane is announced to that member (it joins your lane once your step closes); when the tech lead then assigned it to another member, the queue was cleared and the change recorded, but the member was never told and kept expecting the step. dev progress assign now sends each running lane the step was queued for a devkit notice that names the step and its new owner (and the step that lane goes on with), through the run's messages that the lane's next hook and dev watch --wait deliver. A step queued for no lane sends no lane anything. Verified: dev test run (47 files that assign steps): 1177 passed; dev test prove: the new test fails without the change (0 != 1 notices); python3 and /usr/bin/python3 -m unittest tests.test_progress_reassign: OK --- lib/devkit/progress.py | 17 ++++++++++ tests/test_progress_reassign.py | 58 +++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 tests/test_progress_reassign.py diff --git a/lib/devkit/progress.py b/lib/devkit/progress.py index 06b230a7..1c5bb330 100644 --- a/lib/devkit/progress.py +++ b/lib/devkit/progress.py @@ -1884,6 +1884,8 @@ def assign(which, label: str, cwd: str | None = None, now: float | None = None, if held and s.get("state") != "done" and not any(_label_matches(label, agents.get(k) or {}) for k in held): old = (agents.get(held[0]) or {}).get("persona") or held[0] _log_change(run, s, s.get("state"), "pending", "main", f"reassigned from {old} to {label}", now) + if owner == "main": # it was queued for those lanes, whose member was told it would join them + _tell_unqueued(run, s, held, label, now) s.update(owner="main", state="pending") # the other member's lane no longer owns it s.pop("waits_lane", None) # nor takes it when its open step closes s["label"] = label @@ -1920,6 +1922,21 @@ def assign(which, label: str, cwd: str | None = None, now: float | None = None, return run +def _tell_unqueued(run: dict, s: dict, lanes: list, label: str, now: float): + """Step `s`, queued for `lanes` (waits_lane), now goes to `label`: each of those lanes that still runs gets a + devkit notice naming the step and its new owner, which its next hook and `dev watch --wait` deliver, so its + member stops expecting the step it was told would join its lane (_route_to_lane).""" + from . import crew + agents = run.get("agents") or {} + for aid in lanes: + if (agents.get(aid) or {}).get("state") != "running": + continue + cur = _open_step_of(run, aid, s) + _post(run, "devkit", aid, f"devkit: the tech lead gave “{s['name']}” to {crew.who(label)}, so it no longer " + f"joins your lane" + (f"; go on with “{cur['name']}”" if cur else ""), now, from_name="devkit", + kind="notice") + + def _route_to_lane(run: dict, s: dict, label: str, live: list, now: float): """Step `s`, just assigned to `label` or reopened, goes to its member's live lane (`live`: working_agents) when devkit can tell which. A lane whose launch names it, or that holds no other open step, takes it now, once its diff --git a/tests/test_progress_reassign.py b/tests/test_progress_reassign.py new file mode 100644 index 00000000..187abd0e --- /dev/null +++ b/tests/test_progress_reassign.py @@ -0,0 +1,58 @@ +# Copyright (c) 2026 Firefly Software Solutions Inc. +# SPDX-License-Identifier: Apache-2.0 +# A step queued for a member's busy lane (`waits_lane`) was announced to that member ("it joins your lane once … +# closes"). When `dev progress assign` gives it to someone else, the reassignment clears the queue, and the member +# whose lane it was queued for gets a devkit notice that names the step and its new owner, through the run's messages +# that its next hook and `dev watch --wait` deliver. A step queued for nobody sends no lane anything. Progress state +# and the audit trail in a temporary folder (test_progress.TempState). +# Tests carry comments, not docstrings (`dev test prove` leaves out tests with one). +# Run: python3 -m unittest tests.test_progress_reassign -v +import sys +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) +import _hermetic # noqa: E402 + +_hermetic.activate() # run alone, this module gets the suite's temporary home too +sys.path.insert(0, str(ROOT / "lib")) + +from devkit import progress as pg # noqa: E402 +from test_progress import TempState, launch # noqa: E402 + + +def lane_messages(aid: str) -> list: + return [m for m in pg.load_run("claude", "s1").get("messages") or [] if m.get("to") == aid] + + +class ReassignQueuedStepTests(unittest.TestCase): + def test_the_lane_a_step_was_queued_for_is_told_its_new_owner_and_no_other_lane_is(self): + with TempState(): + pg.start("Importer", plan=["parser", "csv", "schema", "docs"]) + pg.assign("parser", "Neo", why="test") + pg.assign("schema", "Dozer", why="test") + launch("a_neo", "devkit:neo", "Neo: parser") + launch("a_dozer", "devkit:dozer", "Dozer: schema") + pg.assign("csv", "Neo: parser", why="test") # that lane works on parser: csv is queued for it + pg.assign("docs", "Mouse", why="test") # no Mouse lane works: docs waits for a launch, queued for nobody + told = {aid: len(lane_messages(aid)) for aid in ("a_neo", "a_dozer")} + queued = next(s for s in pg.load_run("claude", "s1")["plan"] if s["name"] == "csv").get("waits_lane") + pg.assign("csv", "Tank", why="test") + pg.assign("docs", "Tank", why="test") + neo = lane_messages("a_neo")[told["a_neo"]:] + dozer = lane_messages("a_dozer")[told["a_dozer"]:] + delivered = pg.on_tool_done("claude", {"session_id": "s1", "agent_id": "a_neo"}) or "" + csv = next(s for s in pg.load_run("claude", "s1")["plan"] if s["name"] == "csv") + self.assertEqual((queued or {}).get("lane"), "a_neo") + self.assertEqual(len(neo), 1, neo) + self.assertEqual(neo[0].get("kind"), "notice") + self.assertIn("the tech lead gave “csv” to Backend engineer (Tank)", neo[0]["text"]) + self.assertIn("no longer joins your lane", neo[0]["text"]) + self.assertIn(neo[0]["id"], delivered) # its next hook shows it + self.assertEqual(dozer, []) + self.assertNotIn("waits_lane", csv) + + +if __name__ == "__main__": + unittest.main() From 845a0d17e534c303f84f544eee49664e5a639676 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 15:57:18 -0800 Subject: [PATCH 04/22] docs(crew): say a lane is told when its queued step is reassigned dev progress assign now sends each lane a queued step was waiting for a notice naming the step and its new owner, and the crew guide described only the queue Verified: dev docs check docs/crew.md: markdownlint and links clean, one Vale warning on line 3 that predates this change --- docs/crew.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/crew.md b/docs/crew.md index 27ba92c2..f73c05a7 100644 --- a/docs/crew.md +++ b/docs/crew.md @@ -269,7 +269,8 @@ that launch alone, so two members launched together never swap lanes: not changed. - **The steps queued for it.** When every working lane of the member holds another open step, the step is queued for those lanes: once a lane's open step closes, that lane takes the first queued step whose dependencies are done, - the step's scope becomes the lane's, and the member is told. With two or more lanes, the first lane whose step + the step's scope becomes the lane's, and the member is told. When the tech lead gives a queued step to another + member, each lane it was queued for gets a notice that names the step and its new owner. With two or more lanes, the first lane whose step closes takes it; the tech lead's notice gives the `dev progress assign "" --to ""` line that gives it to one lane instead. Queued steps join one at a time, in the order they were assigned. When the lanes end or are resumed first, the step waits for a launch of its own, and the tech lead is told why. Reopening a step From 91cc623c27cf34a5b42e0c295e9451fb40cc3da1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 16:01:02 -0800 Subject: [PATCH 05/22] feat(lessons): count untraced lessons in one line of dev lesson review Most lessons have no Fix and no Evidence (1,090 of 1,516 on this Mac), so nothing traces them to a real event; listing them in the review would add a thousand lines and bury what needs acting on, and the review did not show them at all. lessons.review returns the lessons that are not retired and have no Fix and no Evidence. dev lesson review shows them as one line with their count and the flag that lists them; dev lesson review --untraced lists them one line each, with how to retire one. The shell completions, the command reference, the lessons guide and the learning-loop skill name the flag. Verified: python3 -m unittest tests.test_lessons_cli: 42 OK (2 new, failing before the change: no count line, unknown flag); tests.test_consistency: 31 OK (D4 and D13 clean); /usr/bin/python3 ReviewUntracedTests: OK; dev docs check: 0 issues; bin/dev lesson review on this Mac: 665 lines, one count line for 1,090 lessons --- docs/commands.md | 2 +- docs/lessons.md | 3 +++ lib/devkit/cli.py | 34 +++++++++++++++++++++++----- lib/devkit/lessons.py | 8 +++++-- plugin/skills/learning-loop/SKILL.md | 3 ++- shell/completions/_dev | 1 + shell/completions/dev.bash | 2 +- tests/test_lessons_cli.py | 31 +++++++++++++++++++++++++ 8 files changed, 73 insertions(+), 11 deletions(-) diff --git a/docs/commands.md b/docs/commands.md index ca542f08..7a6c5b18 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -450,7 +450,7 @@ start of one, or words of a title. | `dev lesson restore --why "…"` | Brings an archived lesson back as open | | `dev lesson release --why "…"` | Releases a held lesson after you review its exact text; the release counts for that text on this machine | | `dev lesson scan [--days N]` | Signals worth a lesson that have none yet: reverts, fixes, missed status blocks, bouncing tasks (default 14 days) | -| `dev lesson review` | Lessons missed twice after being shown, preventions that failed, recurring lessons that are not prevented, held lessons, open lessons not seen for four months; then the observed outcomes after exposure over 30 days, per place, and the lessons missed most | +| `dev lesson review` | Lessons missed twice after being shown, preventions that failed, recurring lessons that are not prevented, held lessons, open lessons not seen for four months; lessons with no Fix and no Evidence as one line with their count, and `--untraced` lists them; then the observed outcomes after exposure over 30 days, per place, and the lessons missed most | | `dev lesson lint` | Lesson files no command can read, each with the git command that shows its last good version; lessons recall cannot show (no root cause, no anchors, held); then broad and wrong anchors and file anchors that match no file, each with the command that fixes it. Every scope without `-p`, `-i`, or `--global`. Exit 1 when it finds something | | `dev lesson eval [--days N]` | For each repeat recorded here with `dev lesson recur` in the last 14 days, whether recall showed the lesson in that session before it: the coverage totals, then the newest 25 repeats | diff --git a/docs/lessons.md b/docs/lessons.md index 9166e217..0e39e551 100644 --- a/docs/lessons.md +++ b/docs/lessons.md @@ -369,6 +369,9 @@ unverified. - open lessons not seen for four months: retire them or confirm them; - prevented lessons this Mac holds no current receipt for, each with the reason (see [Verified and unverified preventions](#verified-and-unverified-preventions)); +- lessons whose root cause is a devkit bug, each with the bug registry command; +- how many lessons have no Fix and no Evidence, in one line, since nothing traces them to a real event: + `dev lesson review --untraced` lists them, one line each; - the observed outcomes after exposure over the last 30 days, per place it was shown, and the lessons missed most. The `lessons` job runs it every Friday and notifies you of the result. `dev lesson lint` checks the anchors (see diff --git a/lib/devkit/cli.py b/lib/devkit/cli.py index 7210504c..da773fd0 100644 --- a/lib/devkit/cli.py +++ b/lib/devkit/cli.py @@ -3216,12 +3216,25 @@ def _lesson_eval(a, lessons) -> int: EVAL_SHOWN = 25 # repeats `dev lesson eval` lists, newest first; the totals count them all -def _lesson_review(lessons) -> int: +def _lesson_review(lessons, untraced_only: bool = False) -> int: """`dev lesson review`: what to act on, most urgent first (lessons missed twice after being shown, preventions - that failed, recurring lessons, held lessons, stale ones, preventions this Mac has no current receipt for), then - the observations of shown lessons per channel over 30 days and the lessons missed most (lessonevents.rates).""" + that failed, recurring lessons, held lessons, stale ones, preventions this Mac has no current receipt for, lessons + whose cause is a devkit bug, then the lessons with no Fix and no Evidence as one line with their count), then the + observations of shown lessons per channel over 30 days and the lessons missed most (lessonevents.rates). + `untraced_only` (--untraced): the lessons with no Fix and no Evidence, one line each, and nothing else.""" from . import lessonevents r = lessons.review() + untraced = r.get("untraced") or [] + if untraced_only: + print(ui.section(f"No Fix and no Evidence · {len(untraced):,}")) + for x in untraced: + print(f" {ui.dim('·')} {x['meta']['id']} {x['meta']['title']} {ui.dim(x['meta']['scope'])}") + if untraced: + print(ui.dim(" retire one that no longer applies: dev lesson retire --why “…”; its next repeat " + "brings its evidence: dev lesson recur --evidence “…”")) + else: + print(f" {ui.OK} every lesson has a Fix or Evidence") + return 0 held = r.get("held") if held is None: # a review() that does not list held lessons: the holds its lessons carry in their front matter held = [{"lesson": x, "reason": x["meta"]["quarantine"]} for x in lessons.all_lessons() @@ -3273,7 +3286,13 @@ def named(x) -> str: print(f" {ui.WARN} {x['meta']['id']} {named(x)}\n " + ui.dim( (f"dev bug report {fp}" if fp != "-" else "dev bug search , or dev bug report --title “…”") + f"; then dev lesson retire {x['meta']['id']} --why “devkit bug …”")) - if not any((r["automate"], r["prevention_failed"], r["recurring"], held, r["stale"], unverified, causes)): + if untraced: # a count, not a list: on a real machine most lessons are untraced (--untraced lists them) + n = len(untraced) + print(ui.section("Untraced — nothing traces them to a real event")) + print(f" {ui.dim('·')} {n:,} lesson{'s have' if n != 1 else ' has'} no Fix and no Evidence: " + f"dev lesson review --untraced lists them") + if not any((r["automate"], r["prevention_failed"], r["recurring"], held, r["stale"], unverified, causes, + untraced)): print(f" {ui.OK} nothing to act on") rates = lessonevents.rates(30) print(ui.section(f"Lesson observations · last {rates['days']} days")) @@ -3424,7 +3443,7 @@ def cmd_lesson(a): print(f" {ui.WARN} {kind:<7} {detail}\n {ui.dim(cmd)}") return 0 if act == "review": - return _lesson_review(lessons) + return _lesson_review(lessons, untraced_only=getattr(a, "untraced", False)) except ValueError as e: ui.err(str(e)) return 2 @@ -4967,7 +4986,10 @@ def wanted(*names): x.add_argument("--why") x = lsp.add_parser("scan", help="signals worth a lesson: reverts, fixes, canary misses") x.add_argument("--days", type=int, default=14) - lsp.add_parser("review", help="what to act on: missed, failed preventions, recurring, held, stale; observations") + x = lsp.add_parser("review", help="what to act on: missed, failed preventions, recurring, held, stale; " + "observations") + x.add_argument("--untraced", action="store_true", help="list the lessons with no Fix and no Evidence, which the " + "review only counts") lsp.add_parser("lint", help="anchors to fix and lessons recall cannot show (exit 1 when there are any)") x = lsp.add_parser("eval", help="would recall have shown the lesson before each repeat recorded here?") x.add_argument("--days", type=int, default=14) diff --git a/lib/devkit/lessons.py b/lib/devkit/lessons.py index 9e2c5ca7..34fc69f6 100644 --- a/lib/devkit/lessons.py +++ b/lib/devkit/lessons.py @@ -1339,7 +1339,8 @@ def review(scope: str = None) -> dict: leaves out because the screen holds them, in their front matter or as loaded: [{lesson, reason}]; the developer releases one with `dev lesson release`), `recurring` (open, seen twice or more), `stale` (retire or confirm), `unverified` (prevented, with no current local verification receipt: [{lesson, reason}]), `devkit_cause` (not - retired, its root cause a devkit bug the registry does not record: [{lesson, fingerprint}]), and the counts.""" + retired, its root cause a devkit bug the registry does not record: [{lesson, fingerprint}]), `untraced` (not + retired, with no Fix and no Evidence: nothing traces it to a real event), and the counts.""" items = all_lessons(scope) why = held_reasons([x for x in items if x["meta"].get("status") != "retired"]) held = [{"lesson": x, "reason": why[x["meta"]["id"]]} for x in items if x["meta"]["id"] in why] @@ -1362,8 +1363,11 @@ def review(scope: str = None) -> dict: unproven = [{"lesson": x, "reason": r} for x in items for r in [unverified(x, cache)] if r] bugs_ = [{"lesson": x, "fingerprint": fp} for x in items if x["meta"].get("status") != "retired" for fp in [devkit_cause(x)] if fp] + untraced = [x for x in items if x["meta"].get("status") != "retired" + and all((x["sections"].get(s) or "").strip() in ("", "_—_") for s in ("Fix", "Evidence"))] return {"automate": automate_, "prevention_failed": failed, "held": held, "recurring": recurring, "stale": stale, - "unverified": unproven, "devkit_cause": bugs_, "counts": counts, "total": len(items)} + "unverified": unproven, "devkit_cause": bugs_, "untraced": untraced, "counts": counts, + "total": len(items)} def fixed_in_session(top: str, start_head: str) -> list: diff --git a/plugin/skills/learning-loop/SKILL.md b/plugin/skills/learning-loop/SKILL.md index 66306a1c..0b0fd87d 100644 --- a/plugin/skills/learning-loop/SKILL.md +++ b/plugin/skills/learning-loop/SKILL.md @@ -239,6 +239,7 @@ the next night would do. `dev lesson review` lists, most urgent first: lessons missed twice after being shown (automate them), preventions that failed, recurring lessons that are not prevented, held lessons awaiting content review, lessons not seen for four months (retire them with a reason or confirm them), and prevented lessons this Mac holds no current receipt for (with -the reason), then the observed outcomes after exposure. `dev lesson eval` says +the reason), then the observed outcomes after exposure. Lessons with no Fix and no Evidence get one line with their +count; `dev lesson review --untraced` lists them, so you can retire the ones that no longer apply. `dev lesson eval` says whether recall showed each lesson before its repeats. Run them before a release and in the weekly status (`dev report`). diff --git a/shell/completions/_dev b/shell/completions/_dev index ea6fafae..a6551a80 100644 --- a/shell/completions/_dev +++ b/shell/completions/_dev @@ -1139,6 +1139,7 @@ _dev__lesson__scan() { _dev__lesson__review() { _arguments -s -S : \ '(- *)'{-h,--help}'[show this help message and exit]' \ + '--untraced[list the lessons with no Fix and no Evidence, which the review only…]' \ '(--project -p)'{-p+,--project=}'[project]:project: _dev_live projects -' \ '(--initiative -i)'{-i+,--initiative=}'[initiative]:initiative: _dev_live initiatives -' \ '--global[global]' diff --git a/shell/completions/dev.bash b/shell/completions/dev.bash index f4af3919..8e56b424 100644 --- a/shell/completions/dev.bash +++ b/shell/completions/dev.bash @@ -315,7 +315,7 @@ _dev_spec() { 'lesson supersede') o='-h --help --by --why -p --project -i --initiative --global' v='--by=n --why=n -p=l:projects:-:: --project=l:projects:-:: -i=l:initiatives:-:: --initiative=l:initiatives:-::' p='n' ;; 'lesson release') o='-h --help --why -p --project -i --initiative --global' v='--why=n -p=l:projects:-:: --project=l:projects:-:: -i=l:initiatives:-:: --initiative=l:initiatives:-::' p='n' ;; 'lesson scan') o='-h --help --days -p --project -i --initiative --global' v='--days=n -p=l:projects:-:: --project=l:projects:-:: -i=l:initiatives:-:: --initiative=l:initiatives:-::' ;; - 'lesson review') o='-h --help -p --project -i --initiative --global' v='-p=l:projects:-:: --project=l:projects:-:: -i=l:initiatives:-:: --initiative=l:initiatives:-::' ;; + 'lesson review') o='-h --help --untraced -p --project -i --initiative --global' v='-p=l:projects:-:: --project=l:projects:-:: -i=l:initiatives:-:: --initiative=l:initiatives:-::' ;; 'lesson lint') o='-h --help -p --project -i --initiative --global' v='-p=l:projects:-:: --project=l:projects:-:: -i=l:initiatives:-:: --initiative=l:initiatives:-::' ;; 'lesson eval') o='-h --help --days -p --project -i --initiative --global' v='--days=n -p=l:projects:-:: --project=l:projects:-:: -i=l:initiatives:-:: --initiative=l:initiatives:-::' ;; 'lesson ls') o='-h --help -p --project -i --initiative --global' v='-p=l:projects:-:: --project=l:projects:-:: -i=l:initiatives:-:: --initiative=l:initiatives:-::' ;; diff --git a/tests/test_lessons_cli.py b/tests/test_lessons_cli.py index 7c82d2a5..edc85d18 100644 --- a/tests/test_lessons_cli.py +++ b/tests/test_lessons_cli.py @@ -454,6 +454,37 @@ def test_review_lists_no_cause_section_when_no_cause_names_a_devkit_bug(self): self.assertNotIn("Caused by a devkit bug", out) +class ReviewUntracedTests(LessonCLI): + # a lesson with no Fix and no Evidence cannot be traced to a real event; review counts them in one line with the + # flag that lists them, since a list of them (1,088 of 1,516 lessons on the machine that asked) buries the rest + def lessons_by_trace(self): + bare = [self.add(f"Close port {n} after the probe", files=[f"ports/{n}/**"])["meta"]["id"] for n in (1, 2, 3)] + traced = [self.add("Wait for the server before the probe", files=["probes/**"], evidence=["PR #12"]), + self.add("Stop the worker after the probe", files=["workers/**"], fix="stopped the worker")] + return bare, [x["meta"]["id"] for x in traced] + + def test_review_counts_the_lessons_with_no_fix_and_no_evidence_in_one_line(self): + bare, traced = self.lessons_by_trace() + rc, out = self.dev("review") + self.assertEqual(rc, 0, out) + counted = [ln for ln in out.splitlines() if "no Fix and no Evidence" in ln] + self.assertEqual(len(counted), 1, out) + self.assertIn("3 lessons have no Fix and no Evidence: dev lesson review --untraced lists them", counted[0]) + for lid in bare + traced: + self.assertNotIn(lid, out) + self.assertNotIn("nothing to act on", out) + + def test_review_untraced_lists_each_lesson_with_no_fix_and_no_evidence(self): + bare, traced = self.lessons_by_trace() + rc, out = self.dev("review", "--untraced") + self.assertEqual(rc, 0, out) + listed = self.block(out, "No Fix and no Evidence · 3") + for lid in bare: + self.assertIn("Close port", self.line(listed, lid)) + for lid in traced: + self.assertNotIn(lid, out) + + class ListTests(LessonCLI): def test_ls_marks_a_prevention_without_a_receipt_unverified(self): unverified = self.add("Close the port after the probe", scope="global", files=["ports/**"]) From 1bd5df6dc0f5e05a1f47aa50dd5a93d749da0e04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 16:06:42 -0800 Subject: [PATCH 06/22] fix(audit): classify the --untraced flag of dev lesson review The audit trail records each dev call's options by their class, and the test that every option is classified failed once dev lesson review gained --untraced. Root cause: the new --untraced option was added to the lesson review parser but not to audit.FLAG_OPTIONS, the list of option names that take no value Verified: dev test run tests/test_audit.py tests/test_lessons_cli.py tests/test_consistency.py: 198 passed (the classification test failed before: --untraced missing from FLAG_OPTIONS) --- lib/devkit/audit.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/devkit/audit.py b/lib/devkit/audit.py index 38baeeca..e09d2592 100644 --- a/lib/devkit/audit.py +++ b/lib/devkit/audit.py @@ -494,7 +494,7 @@ def _decided(rec: dict) -> dict: "--patch --pending --pending-launch --prerelease --preview --public --publish --queue --quiet --ready --rebase " "--record --recursive --refresh --regex --regions --remote --remove --replace --request-changes --resume --run " "--safe --scheduled --security --sign --skip --skip-heavy --skip-packages --squash --staged --standby --stat " - "--stdin --stop --strict --syntax --tab --tasks --team --tracked --untriaged --unverified --unwip --urgent " + "--stdin --stop --strict --syntax --tab --tasks --team --tracked --untraced --untriaged --unverified --unwip --urgent " "--verbose --wait --watch --wip --word --yes -F -R -a -f -h -l -r -s -v -y" ).split()) DEV_OPTIONS = TEXT_OPTIONS | NAME_OPTIONS | FLAG_OPTIONS From aab11af0827f6d1a3b97b4918e155d19ad2c2397 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 16:09:02 -0800 Subject: [PATCH 07/22] docs(crew): drop a weasel word from the launch naming sentence Vale flagged 'several' in the crew skill's sentence about the pre-tool hook naming a launch's step; the guide already says two or more. Verified: vale on plugin/skills/crew/SKILL.md: no finding on lines 154-158; dev docs check: 0 markdown issues, all links resolve --- plugin/skills/crew/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugin/skills/crew/SKILL.md b/plugin/skills/crew/SKILL.md index 2c6073b5..1de2ebf1 100644 --- a/plugin/skills/crew/SKILL.md +++ b/plugin/skills/crew/SKILL.md @@ -153,7 +153,7 @@ dev crew graph --global # every live session on this Mac (the defau `api` and `ui` run in parallel, so the ETA counts the longer one, not both. - **A step binds to the launch that names it.** A new launch takes the ready step its description names, so put the step's name in the launch description (`dev crew brief --step` does). On Claude Code, a launch that names none of - its member's steps gets the one waiting step's name from the pre-tool hook, which tells you; with several waiting, + its member's steps gets the one waiting step's name from the pre-tool hook, which tells you; with two or more waiting, it gives you the exact description that takes each. `assign` gives a step to a member's working lane at once, when its dependencies are done, if that lane's launch names the step or the lane holds no other open step; otherwise the step is queued for the member's lanes (next item), or, when the member does not work, waits From cde4fdbf89ddfcec55afa08df7549ebbd434e8b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 16:30:08 -0800 Subject: [PATCH 08/22] fix(ci): treat redirects and sudo tee writes as writes in dev ci --run MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit dev ci --run ran 'pytest > ~/.bashrc' as written, which overwrites the developer's shell settings with the test log, and skipped 'pytest | sudo tee /tmp/x.log' as runner setup, so its tests never ran while the evidence was recorded. Root cause: the step classifier dropped the redirect targets the shell reader returns (gitx._commands), so a redirect was never judged as a write, and it took any writing command run with sudo for the runner's own setup (the as_root branch of gitx._prep_one), whatever folder it wrote A shell redirect (>, >>, 2>, &>) is judged like tee: next to a check, one into a dotfile or dot folder of the home folder blocks the evidence; with no check beside it, a write into the home folder is the runner's setup; a log elsewhere in the home folder, in the checkout, or /dev/null still runs. A writing command run with sudo is the runner's setup only when every file it writes is in a system folder (/etc, /usr, /opt, /var outside its temporary folders, and the like): next to a check, any other root write blocks the evidence, so 'curl … | sudo tee /etc/apt/…' stays setup and 'pytest | sudo tee /tmp/x.log' blocks. The command reference and the local CI guide say so. Verified: python3 -m unittest tests.test_gitx tests.test_gitx_ci_shortcuts: 186 passed; test_ci_commands, test_cli_ci, test_workflow_ci, test_shellparse: 33 passed; test_security_corpus: 22 passed; dev test prove tests/test_gitx.py --runs 2: both new tests pass with the change and fail without it; dev docs check on both docs: 0 issues --- docs/commands.md | 2 +- docs/git-and-github.md | 2 +- lib/devkit/gitx.py | 118 ++++++++++++++++++++++++++++------------- tests/test_gitx.py | 47 ++++++++++++++++ 4 files changed, 130 insertions(+), 39 deletions(-) diff --git a/docs/commands.md b/docs/commands.md index 7a6c5b18..0a4531e5 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -631,7 +631,7 @@ Local CI evidence: proof that what CI runs passed on your Mac, on exactly the fi | Option | Effect | | --- | --- | -| `--run` | Runs the `run:` steps of the workflows that run on pushes and pull requests, in order, and records the evidence when all pass. Setup actions, dependency installs, side effects, a hosted runner's own setup (deletions outside the checkout, Docker prunes, setup run with `sudo`, OS package installs, `playwright install`, `git config --global`, Linux-only system setup such as `fc-cache`, `ldconfig`, or `locale-gen`, and `mkdir`, `cp`, `mv`, `ln`, `install`, `touch`, `tee`, or `rsync` writes into the home folder outside the checkout, unless the same pipeline runs a check, as `pytest \| tee ~/pytest.log` does; a check piped into the home folder through `sudo tee`, or into a dotfile such as `~/.bashrc`, blocks the evidence instead), and steps that need CI secrets are skipped, each with a line that says why. In a step that sets up a tool and runs it (`brew install gitleaks && gitleaks detect`), only the setup is left out and the check runs, so a tool missing on this Mac fails the evidence. A script run with `source` or `.`, and a command or process substitution, count as checks. A check that cannot be separated from its setup (a nested shell, a subshell, a substitution, a heredoc, a `case`), a check run with `sudo` (including `sudo test`, `sudo [`, and a reporting command with a substitution, such as `sudo echo "$(…)"`), and a step that names a Docker context this Mac lacks block the evidence (see [Git and GitHub › Local CI evidence](git-and-github.md#local-ci-evidence)) | +| `--run` | Runs the `run:` steps of the workflows that run on pushes and pull requests, in order, and records the evidence when all pass. Setup actions, dependency installs, side effects, a hosted runner's own setup (deletions outside the checkout, Docker prunes, setup run with `sudo`, OS package installs, `playwright install`, `git config --global`, Linux-only system setup such as `fc-cache`, `ldconfig`, or `locale-gen`, and `mkdir`, `cp`, `mv`, `ln`, `install`, `touch`, `tee`, or `rsync` writes and shell redirects (`>`, `>>`, `2>`, `&>`) into the home folder outside the checkout, unless the same pipeline runs a check, as `pytest \| tee ~/pytest.log` and `pytest > ~/pytest.log` do; a check that writes into a dotfile such as `~/.bashrc`, through `tee` or a redirect, or that is piped to `sudo tee` anywhere but a system folder such as `/etc` or `/usr/local`, blocks the evidence instead), and steps that need CI secrets are skipped, each with a line that says why. In a step that sets up a tool and runs it (`brew install gitleaks && gitleaks detect`), only the setup is left out and the check runs, so a tool missing on this Mac fails the evidence. A script run with `source` or `.`, and a command or process substitution, count as checks. A check that cannot be separated from its setup (a nested shell, a subshell, a substitution, a heredoc, a `case`), a check run with `sudo` (including `sudo test`, `sudo [`, and a reporting command with a substitution, such as `sudo echo "$(…)"`), and a step that names a Docker context this Mac lacks block the evidence (see [Git and GitHub › Local CI evidence](git-and-github.md#local-ci-evidence)) | | `--dry-run` | With `--run`: the plan, without running anything | | `--keep-going` | With `--run`: do not stop at the first failure | | `--step-timeout MIN` | With `--run`: minutes per step (default 30) | diff --git a/docs/git-and-github.md b/docs/git-and-github.md index 83f79f31..e65c440e 100644 --- a/docs/git-and-github.md +++ b/docs/git-and-github.md @@ -334,7 +334,7 @@ Steps that cannot or must not run on your Mac are skipped, with the reason: | Setup actions (`uses:`) | Your local toolchain stands in for them | | Dependency installs (`npm ci`, `pip install`, `uv sync`, …) | Your local environment is used; nothing is reinstalled | | Side effects: publishing, deploying, pushing, system installs, coverage uploads | They change things outside your Mac | -| A hosted runner's own setup: a step that deletes a path not inside the checkout (`rm -rf /opt/hostedtoolcache/…`), `docker` or `podman … prune`, setup run with `sudo` (`sudo systemctl …`), OS package installs and updates (`apt-get`, `brew`, `dnf`, `apk`, `choco`, …), `playwright install` and `install-deps`, `git config --global` or `--system`, a Linux runner's own system setup (`fc-cache`, `ldconfig`, `locale-gen`, `update-ca-certificates`, …), and `mkdir`, `cp`, `mv`, `ln`, `install`, `touch`, `tee`, or `rsync` writing into the home folder outside the checkout (`mkdir -p ~/.local/share/fonts`), unless the same pipeline runs a check (`pytest \| tee ~/pytest.log` runs; into the home folder through `sudo tee`, or into a dotfile such as `~/.bashrc`, it blocks the evidence) | They would delete your caches and images, install system packages, rewrite your settings, or fill your home folder; a Mac has no use for a Linux runner's system caches. Each skipped step gets a line that says why. devkit also reads the script a step hands to a shell with `-c` (`xvfb-run bash -c …`) | +| A hosted runner's own setup: a step that deletes a path not inside the checkout (`rm -rf /opt/hostedtoolcache/…`), `docker` or `podman … prune`, setup run with `sudo` (`sudo systemctl …`), OS package installs and updates (`apt-get`, `brew`, `dnf`, `apk`, `choco`, …), `playwright install` and `install-deps`, `git config --global` or `--system`, a Linux runner's own system setup (`fc-cache`, `ldconfig`, `locale-gen`, `update-ca-certificates`, …), and `mkdir`, `cp`, `mv`, `ln`, `install`, `touch`, `tee`, `rsync`, or a shell redirect (`>`, `>>`, `2>`, `&>`) writing into the home folder outside the checkout (`mkdir -p ~/.local/share/fonts`, `echo … > ~/.npmrc`), unless the same pipeline runs a check (`pytest \| tee ~/pytest.log` and `pytest > ~/pytest.log` run; into a dotfile such as `~/.bashrc`, through `tee` or a redirect, or through `sudo tee` anywhere but a system folder such as `/etc` or `/usr/local`, it blocks the evidence) | They would delete your caches and images, install system packages, rewrite your settings, or fill your home folder; a Mac has no use for a Linux runner's system caches. Each skipped step gets a line that says why. devkit also reads the script a step hands to a shell with `-c` (`xvfb-run bash -c …`) | | Steps that need CI secrets or write CI plumbing (`$GITHUB_ENV`, `$GITHUB_OUTPUT`) | They only make sense on the runner | | Jobs that deploy or publish, run on Windows, or only on other events | They are not part of the check of a change | diff --git a/lib/devkit/gitx.py b/lib/devkit/gitx.py index 2d449f9a..f9052907 100644 --- a/lib/devkit/gitx.py +++ b/lib/devkit/gitx.py @@ -2343,11 +2343,13 @@ def _wrapper_script(words, state): def _commands(code: str, as_root: bool = False, depth: int = 0, state=None, wrapped=None): - """(the words as written, the command they run, whether it runs as root, whether it holds a script of its own) - for each command of `code`, with the commands of the scripts it holds: the one a shell runs with `-c` (see - _segments), and, with `state` (the step's folder and variables), a wrapper script of the checkout that runs the - command it is given (see _wrapper_script), with that command where the script runs it (`wrapped`).""" - for argv, _ in shellparse.split_commands(code) or []: + """(the words as written, the command they run, whether it runs as root, whether it holds a script of its own, its + redirects) for each command of `code`, with the commands of the scripts it holds: the one a shell runs with `-c` + (see _segments), and, with `state` (the step's folder and variables), a wrapper script of the checkout that runs + the command it is given (see _wrapper_script), with that command where the script runs it (`wrapped`). The + redirects are (the files `>`, `>>`, `2>`, `&>` write, whether the shell that opens them runs as root): the shell + opens them, so `sudo pytest > ~/log` writes as the developer, and a `sudo sh -c` script's redirects as root.""" + for argv, targets in shellparse.split_commands(code) or []: argv = list(argv) if wrapped and _WRAPPED in argv: k = argv.index(_WRAPPED) @@ -2356,7 +2358,7 @@ def _commands(code: str, as_root: bool = False, depth: int = 0, state=None, wrap words = shellparse.unwrap(argv) script = _nested_script(argv) wrapper = _wrapper_script(words, state) if script is None and depth < 3 else None - yield argv, words, root, script is not None or wrapper is not None + yield argv, words, root, script is not None or wrapper is not None, (list(targets), as_root) if script is not None and depth < 3: yield from _commands(script, root, depth + 1, state, wrapped) elif wrapper: # the command it is given first, so a skip names it; then the script around it @@ -2375,13 +2377,49 @@ def _informational(argv, words) -> bool: _HOME_KINDS = ("home", "home-dot", "home-root") # a write into the home folder, least to most severe +# a write outside the checkout: setup with no check beside it; next to one, all but "home" block the step instead +_OUTSIDE_KINDS = _HOME_KINDS + ("root-write",) +# the folders a hosted runner's own system setup writes as root (`curl … | sudo tee /etc/apt/keyrings/…`, a tool into +# /usr/local/bin), and the temporary folders under them, which hold a check's log instead (/var/tmp, macOS's +# /var/folders); both are compared resolved, as _shell_path gives a path (on macOS /etc is /private/etc) +_SYSTEM_DIRS = ("/etc", "/usr", "/opt", "/bin", "/sbin", "/lib", "/lib32", "/lib64", "/libx32", "/boot", "/srv", + "/var", "/Library", "/System") +_TEMP_DIRS = ("/tmp", "/var/tmp", "/var/folders") + + +def _under(path: str, dirs) -> bool: + """The resolved path is one of the folders, or inside one of them, compared resolved.""" + return any(path == d or path.startswith(d.rstrip(os.sep) + os.sep) for d in {os.path.realpath(x) for x in dirs}) + + +def _system_file(path, top: str) -> bool: + """The resolved path lies in a system folder (_SYSTEM_DIRS), not in a temporary folder or the checkout.""" + return bool(path) and _under(path, _SYSTEM_DIRS) and not _under(path, _TEMP_DIRS + (tempfile.gettempdir(), top)) + + +def _home_write(targets, as_root: bool, state: dict): + """("home"|"home-dot"|"home-root", why) for the most severe of the files a command writes into the home folder + outside the checkout: a dotfile or dot folder holds the developer's own settings, and a write as root cannot run + here. None when it writes none there. `targets`: the words that name the files, as written.""" + env, top = state["env"], state["top"] + home = os.path.realpath(env.get("HOME") or os.path.expanduser("~")) + found = None # the most severe of its targets: one command can write several (tee ~/log ~/.bashrc) + for w in targets: + p = _shell_path(w, state["here"], env) + if p and (p == home or p.startswith(home + os.sep)) and p != top and not p.startswith(top + os.sep): + dot = any(part.startswith(".") and part != "." for part in os.path.relpath(p, home).split(os.sep)) + kind = "home-root" if as_root else "home-dot" if dot else "home" + if found is None or _HOME_KINDS.index(kind) > _HOME_KINDS.index(found[0]): + found = (kind, f"runner prep (writes {w} into the home folder, outside the checkout)") + return found def _prep_one(argv, words, as_root: bool, state: dict): """("setup", why) when this one command only sets up a hosted runner, ("home", why) when it writes into the home folder outside the checkout (setup unless its piece runs a check), ("home-dot", why) or ("home-root", why) when - that write goes into a dotfile or a dot folder, or runs as root (setup with no check beside it, and a block next - to one), ("root", why) when it is a check that runs as root, or None. `state` carries the folder `cd` went to ("here"), the checkout ("top") and the variables.""" + that write goes into a dotfile or a dot folder, or runs as root, ("root-write", why) when it writes as root + anywhere else but a system folder (`pytest | sudo tee /tmp/x.log`; these three are setup with no check beside + them, and a block next to one), ("root", why) when it is a check that runs as root, or None. `state` carries the folder `cd` went to ("here"), the checkout ("top") and the variables.""" if not words: return None env, top = state["env"], state["top"] @@ -2420,20 +2458,16 @@ def _prep_one(argv, words, as_root: bool, state: dict): elif name in _LINUX_SETUP: return "setup", f"runner prep ({name} sets up the Linux runner's own system; a Mac has no use for it)" elif name in _WRITERS: - home = os.path.realpath(env.get("HOME") or os.path.expanduser("~")) - found = None # the most severe of its targets: one command can write several (tee ~/log ~/.bashrc) - for w in _written(words, _WRITERS[name]): - p = _shell_path(w, state["here"], env) - if p and (p == home or p.startswith(home + os.sep)) and p != top and not p.startswith(top + os.sep): - # "home": setup only when its piece runs no check (_classify); a check's log piped to tee still runs. - # A dotfile or dot folder holds the developer's own settings, and a write as root cannot run here: - # next to a check, either one blocks the step instead. - dot = any(part.startswith(".") and part != "." for part in os.path.relpath(p, home).split(os.sep)) - kind = "home-root" if as_root else "home-dot" if dot else "home" - if found is None or _HOME_KINDS.index(kind) > _HOME_KINDS.index(found[0]): - found = (kind, f"runner prep (writes {w} into the home folder, outside the checkout)") + # "home": setup only when its piece runs no check (_classify); a check's log piped to tee still runs. A + # dotfile or dot folder, or a write as root, blocks the step instead next to a check. + targets = _written(words, _WRITERS[name]) + found = _home_write(targets, as_root, state) if found: return found + # As root, only a system folder is the runner's own setup: `pytest | sudo tee /tmp/x.log` cannot run here, + # and skipping it would leave its tests out of the evidence. + if as_root and not (targets and all(_system_file(_shell_path(w, state["here"], env), top) for w in targets)): + return "root-write", f"runner prep (sudo {' '.join(words[:2])} runs as root on the runner's machine)" if as_root: # setup the runner does as root, or a check that runs as root, which cannot run here if _informational(argv, words) and (name in ("test", "[", "[[") or any("$(" in w or "`" in w for w in words[1:])): @@ -2532,27 +2566,36 @@ def _classify(piece: dict, state: dict, installs: bool) -> dict: """What one top-level piece of a step's script does: its kind ("setup", "check", "root", "tangled" or "info") and why. A pipeline or a command substitution that feeds the runner's setup is setup too; a subshell, a nested shell or a substitution that runs the setup, next to a check, is tangled: the setup cannot be taken out without the check. - `source`/`.` and a command or process substitution (see _substitutions) are checks. A write into the home folder - is setup only in a piece that runs no check: `pytest | tee ~/pytest.log` is the check, and runs.""" + `source`/`.` and a command or process substitution (see _substitutions) are checks. A write into the home folder, + by a writing command or a shell redirect, is setup only in a piece that runs no check: `pytest | tee + ~/pytest.log` and `pytest > ~/pytest.log` are the check, and run.""" code = piece["code"] piped = _PIPED_INSTALLER.search(code) setup = "runner prep (curl … | sh runs an installer downloaded from the internet)" if piped else None first = "curl … | sh" if piped else None - install, checks, roots, nested, home, held = None, [], [], False, None, None - for argv, words, as_root, container in _commands(code, state=state): + install, checks, roots, nested, outside, held = None, [], [], False, None, None + + def wrote(got, words): # a write outside the checkout (_OUTSIDE_KINDS): setup alone, a block next to a check + nonlocal outside, held + outside = outside or (got[1], " ".join(words[:2])) + if got[0] in ("home-root", "root-write"): + held = held or ("root", f"runs {os.path.basename(words[0])} as root (sudo), which dev ci --run does " + f"not do on this Mac") + elif got[0] == "home-dot": + target = got[1].split("writes ", 1)[1].split(" into the home folder", 1)[0] + held = held or ("tangled", f"writes {target} into a dotfile of the home folder next to a check, which " + f"would change this Mac's own settings: write the log inside the checkout") + + for argv, words, as_root, container, redirects in _commands(code, state=state): + shell = _home_write(*redirects, state) # `pytest > ~/.bashrc`: the shell writes it, whatever the command + if shell: + wrote(shell, words) nested = nested or container if container: continue got = _prep_one(argv, words, as_root, state) - if got and got[0] in ("home", "home-dot", "home-root"): - home = home or (got[1], " ".join(words[:2])) - target = got[1].split("writes ", 1)[1].split(" into the home folder", 1)[0] - if got[0] == "home-root": - held = held or ("root", f"runs {os.path.basename(words[0])} as root (sudo), which dev ci --run does " - f"not do on this Mac") - elif got[0] == "home-dot": - held = held or ("tangled", f"writes {target} into a dotfile of the home folder next to a check, which " - f"would change this Mac's own settings: write the log inside the checkout") + if got and got[0] in _OUTSIDE_KINDS: + wrote(got, words) elif got and got[0] == "setup": setup = setup or got[1] first = first or " ".join(words[:2]) @@ -2565,17 +2608,18 @@ def _classify(piece: dict, state: dict, installs: bool) -> dict: checks.append(words) if held and (checks or roots): # a check whose output goes into a dotfile or through sudo: it cannot run here return {"kind": held[0], "why": held[1]} - if home and not (checks or roots): # it only writes into the home folder and reports: the runner's setup - setup, first = setup or home[0], first or home[1] + if outside and not (checks or roots): # it only writes outside the checkout and reports: the runner's setup + setup, first = setup or outside[0], first or outside[1] for script in _substitutions(shellparse.strip_heredocs(code)): # a substitution runs a command the reader keeps inside a word (`test -z "$(gofmt -l .)"`): a check. Setup it # runs cannot be left out without the command that uses its output, so next to a check it is tangled; one # that only feeds the setup (`apt-get install "linux-headers-$(uname -r)"`) leaves the piece setup. checks.append([script]) inside = dict(state) # it runs in a subshell of its own: a `cd` in it holds for the rest of it only - for argv, words, as_root, container in _commands(script, state=inside): + for argv, words, as_root, container, redirects in _commands(script, state=inside): got = None if container else _prep_one(argv, words, as_root, inside) - if got and got[0] in ("setup", "home", "home-dot", "home-root"): + got = got if got and got[0] in ("setup",) + _OUTSIDE_KINDS else _home_write(*redirects, inside) + if got: setup, first, nested = setup or got[1], first or " ".join(words[:2]), True why = setup or install if why and (checks or roots) and (nested or piece["subshell"]): diff --git a/tests/test_gitx.py b/tests/test_gitx.py index 8b04f200..4d0dd628 100644 --- a/tests/test_gitx.py +++ b/tests/test_gitx.py @@ -1194,6 +1194,53 @@ def test_a_check_piped_to_sudo_tee_or_into_a_home_dotfile_blocks_the_evidence(se self.assertFalse(got[name]["blocking"]) self.assertEqual((got["Log"]["skip"], got["Log"]["blocking"]), (None, False)) + # A shell redirect writes its target as tee does: `pytest > ~/.bashrc` would overwrite the developer's settings + # with the test log, so next to a check a redirect into a dotfile or dot folder of the home folder blocks the + # evidence; with no check beside it, it is the runner's setup (`echo … > ~/.npmrc`). A log in the home folder, in + # the checkout, or /dev/null still runs. + def test_a_check_redirected_into_a_home_dotfile_blocks_the_evidence(self): + with Sandbox() as s, mock.patch.dict(os.environ, {"HOME": str(s.root)}): + got = self.plan_steps(s, {"Truncate": "pytest > ~/.bashrc", + "Append": "pytest >> ~/.bashrc", + "Errors": "pytest 2> ~/.bashrc", + "Both": 'npm test &> "$HOME/.npmrc"', + "Dot folder": "pytest > ~/.config/tool/log.txt 2>&1", + "Dot setup": "echo registry=https://example.test > ~/.npmrc", + "Home log": "pytest > ~/pytest.log 2>&1", + "Checkout log": "pytest >> pytest.log", + "Discarded": "pytest 2>/dev/null"}) + for name in ("Truncate", "Append", "Errors", "Both", "Dot folder"): + with self.subTest(step=name): + self.assertTrue(got[name]["blocking"], got[name]["skip"]) + self.assertRegex(got[name]["skip"] or "", r"into a dotfile of the home folder next to a check") + self.assertRegex(got["Dot setup"]["skip"] or "", r"^runner prep \(writes ~/\.npmrc into the home folder") + self.assertFalse(got["Dot setup"]["blocking"]) + for name in ("Home log", "Checkout log", "Discarded"): + with self.subTest(step=name): + self.assertEqual((got[name]["skip"], got[name]["blocking"]), (None, False)) + + # `sudo tee` outside the home folder cannot run here either: skipping `pytest | sudo tee /tmp/x.log` as setup + # recorded evidence for tests that never ran, so a check beside it blocks the evidence. Writing a system folder as + # root (`curl … | sudo tee /etc/apt/…`) is the runner's setup, and so is a root write with no check beside it. + def test_a_check_piped_to_sudo_tee_outside_a_system_folder_blocks_the_evidence(self): + with Sandbox() as s: + got = self.plan_steps(s, {"Temp log": "pytest | sudo tee /tmp/x.log", + "Appended": "python -m pytest 2>&1 | sudo tee -a /var/tmp/pytest.log", + "Checkout log": "pytest | sudo tee pytest.log", + "No file": "pytest | sudo tee", + "Apt key": "curl -fsSL https://example.test/key.asc | sudo tee " + "/etc/apt/keyrings/example.asc", + "Tool": "curl -fsSL https://example.test/tool | sudo tee /usr/local/bin/tool", + "Root write alone": "echo 1 | sudo tee /tmp/flag"}) + for name in ("Temp log", "Appended", "Checkout log", "No file"): + with self.subTest(step=name): + self.assertTrue(got[name]["blocking"], got[name]["skip"]) + self.assertRegex(got[name]["skip"] or "", r"^runs tee as root \(sudo\)") + for name in ("Apt key", "Tool", "Root write alone"): + with self.subTest(step=name): + self.assertRegex(got[name]["skip"] or "", r"^runner prep \(sudo tee ") + self.assertFalse(got[name]["blocking"]) + def fake_tools(self, d: Path) -> Path: """A bin folder with a `brew` that leaves a marker when it runs and a `fakescan` that records its arguments and exits with the code in fakescan.rc.""" From 652ac0c135ab0af44ba0425103ec4f1780ede99c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 16:38:46 -0800 Subject: [PATCH 09/22] feat(dashboard): bring a project's tabs onto a phone's first screen On a 390 x 844 phone a project page showed its section tabs only after more than a screen of scrolling (tab bar at y 985): eight health reasons and four 2 x 2 chart tiles came first, so a link to a tab showed no line of it. At every width, a tab chosen from the stuck tab bar kept the old scroll offset, so the new panel started hidden above the window or the page jumped to its end. Under 481 px the reasons list shows the three most serious (the server's order) and a Show all N reasons button (aria-expanded, aria-controls) that shows the rest and reads Show fewer; it stays open while the page shows the project and closes when the person leaves it; print lists every reason. The four tiles become one row of figures, the number above its label, without charts. The Open tasks and Open PRs tiles carry their chart's words as hidden text at every width, so their accessible names keep the breakdown (2 doing, 1 blocked) where the chart is not drawn. On acme/widget the tabs move from y 985 to y 665 and the first Overview panel starts above the fold. At every width, a tab chosen from the stuck bar (by click or the arrow, Home and End keys) brings the bar back to its sticky top with the new panel right under it; the panel is then at least a window tall for the rest of the visit, so a short panel can bring the bar up too. With the bar not stuck the page does not move. From 481 px up nothing else changes. docs/dashboard.md, Project page, says how the page reads on a phone. Verified: dev test run on the 13 dashboard, page and dependent test files: 335 passed; after the last edit tests/test_dashboard.py, test_dashboard_now.py, test_dashboard_sessions.py: 158 passed; dev test prove: the 6 new browser tests pass 5 of 5 runs and fail without the change; dev visual captures at 390x844 and 1440x900 in light and dark; dev docs check docs/dashboard.md clean in my lines --- docs/dashboard.md | 12 ++++ lib/devkit/web/app.js | 54 ++++++++++++++--- lib/devkit/web/base.css | 15 +++++ tests/test_dashboard.py | 124 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 198 insertions(+), 7 deletions(-) diff --git a/docs/dashboard.md b/docs/dashboard.md index 9ef95fc6..c6eda6c9 100644 --- a/docs/dashboard.md +++ b/docs/dashboard.md @@ -237,6 +237,18 @@ long work takes here), **Tasks**, **Pull requests** (CI, review, merge state, si (below), **Worktrees** (`dev wt rm`), **Plans**, **Sessions**, and **Handoff note** (the full note, rendered). The repository facts on the Overview count the branches and those not backed up, and link to the Branches tab. +On a phone (under 481 px), the header and the tiles take less room, so the tabs and the first lines of the selected +tab fit on the first screen. The health reasons show the three most serious first, as the server orders them (risk +before warn), and a **Show all N reasons** button; pressed, it shows every reason and reads **Show fewer**. The list +stays open while the page shows the project, live updates included, and closes when you leave it; a printed page +lists every reason. The four tiles become one row of figures, each number over its label, without their charts. +**Open tasks** and **Open PRs** still open their tabs, and a screen reader still hears their breakdown, such as +_2 doing, 1 blocked_. Screens 481 px wide or wider show every reason and every chart. + +When you change tabs from the tab bar while it is stuck at the top of the window, the bar stays there, under the +navigation bar on a wider screen, and the new tab starts right under it, however short it is. The arrow keys, **Home**, +and **End** change tabs the same way. When the bar is not stuck, the page does not move. + **Plans** lists every plan and spec in the project's folder of the handoff repository, `plans//`, sub-folders included. When some sit in sub-folders, such as `product/` or `history/`, the project's own plans come first in a panel titled **Plans**, then one titled panel per sub-folder, in name order, each with its count. diff --git a/lib/devkit/web/app.js b/lib/devkit/web/app.js index e9955284..d2dce625 100644 --- a/lib/devkit/web/app.js +++ b/lib/devkit/web/app.js @@ -732,11 +732,15 @@ function sessBar(s, who, i) { h("span", {class: "sb-l"}, h("span", {class: "ell", text: scopeName(s.project || "") || s.agent || "session"}), h("span", {class: "num t2", text: p ? (blocked ? "blocked" : p.steps ? (p.step || 0) + "/" + p.steps : "") : ""})), h("span", {class: "sb-b"}, pct != null ? h("i", {style: "width:" + pct.toFixed(0) + "%"}) : null)); } -/* a stat tile: label, value, one visual, its legend */ +/* a stat tile: label, value, one visual, its legend. With `say`, the visual's label is the tile's own hidden text and the + visual is hidden from screen readers, so the tile keeps those words in its name where the visual is not drawn (the + project page's row of figures on a phone) and says them once where it is */ function statTile(o) { + const say = o.say && o.viz ? o.viz.getAttribute("aria-label") : ""; + if (say) o.viz.setAttribute("aria-hidden", "true"); return h(o.href ? "a" : "div", {class: "stile" + (o.cls ? " " + o.cls : ""), href: o.href || null, "data-nav": o.href ? "" : null, onclick: o.onclick || null}, h("span", {class: "s-l", text: o.label}), h("span", {class: "s-v"}, h("b", {class: "num", text: String(o.value)}), o.unit ? h("span", {class: "t2", text: o.unit}) : null), - o.viz || null, o.legend || null); + say ? h("span", {class: "sr", text: say}) : null, o.viz || null, o.legend || null); } function modalHref(kind, id) { return encode({...S, modal: kind + ":" + id, task: ""}); } function modalLink(kind, id, text, cls) { return h("a", {class: "rl" + (cls ? " " + cls : ""), href: modalHref(kind, id), "data-nav": "", onclick: e => { e.preventDefault(); openModal(kind, id); }, text}); } @@ -818,10 +822,29 @@ function callout(tone, title, body, act) { return h("div", {class: "callout " + tone, role: tone === "risk" ? "alert" : null}, tone === "info" ? null : h("span", {class: "dot d-" + (tone === "risk" ? "risk" : "warn"), "aria-hidden": "true"}), h("div", {class: "cbody"}, h("strong", {text: title}), body ? h("div", null, body) : null), act ? h("div", {class: "cact"}, act) : null); } +/* A tab chosen from the stuck tab bar: once the page is drawn again the bar is back at its sticky top and the new panel + starts right under it, at once. For the rest of the page's visit the panel is then at least a window tall (.floor), + so a short panel can bring the bar up too and a live update finds the page as tall as it left it. With the bar not + stuck, the page does not move. The draw is the hash change's, so the click notes the tab it wants and render() acts */ +const TABJUMP = {to: "", floor: ""}; +/* the window's scroll offset at which the bar reaches its sticky top: where it would sit in the page, less its top */ +function barRest(bar) { + bar.style.position = "static"; const y = bar.getBoundingClientRect().top + window.scrollY; bar.style.position = ""; + return y - (parseFloat(getComputedStyle(bar).top) || 0); +} +function tabJump(main, page) { + if (page !== lastView) TABJUMP.floor = TABJUMP.to = ""; + const bar = $(".ptabs", main), tp = $("#tabpanel", main), sel = bar && $('.ptab[aria-selected="true"]', bar); + const jump = !!TABJUMP.to && !!sel && sel.id === TABJUMP.to; TABJUMP.to = ""; + if (jump) TABJUMP.floor = page; + if (tp && TABJUMP.floor === page) tp.classList.add("floor"); + if (jump) window.scrollTo(0, barRest(bar)); +} function pageTabs(tabs, cur) { const bar = h("div", {class: "ptabs", role: "tablist", "aria-label": "Sections"}); for (const [key, label, n] of tabs) bar.append(h("button", {class: "ptab", role: "tab", type: "button", id: "tab-" + key, "aria-selected": String(cur === key), "aria-controls": "tabpanel", tabindex: cur === key ? "0" : "-1", - onclick: () => set({tab: key === tabs[0][0] ? "" : key, src: "all", tst: ""}, true)}, label, n != null ? h("span", {class: "n num", text: String(n)}) : null)); + onclick: () => { if (key !== cur && window.scrollY > barRest(bar) - 1) TABJUMP.to = "tab-" + key; set({tab: key === tabs[0][0] ? "" : key, src: "all", tst: ""}, true); }}, + label, n != null ? h("span", {class: "n num", text: String(n)}) : null)); bar.addEventListener("keydown", e => { if (!["ArrowRight", "ArrowLeft", "Home", "End"].includes(e.key)) return; e.preventDefault(); const bs = $$(".ptab", bar), i = bs.indexOf(document.activeElement); @@ -1675,6 +1698,22 @@ function timeBody(t, showProject) { (t.recent_runs || []).length ? [h("h3", {class: "sub3", text: "Recent runs: actual against estimate"}), h("ul", {class: "tl-rows"}, t.recent_runs.slice(0, 5).map(r => h("li", {class: "trow"}, h("span", {class: "tx ell", title: r.what, text: r.what || "run"}), h("span", {class: "num t2" + (r.estimate && r.secs / 60 > r.estimate * 1.5 ? " bad" : ""), text: fmtMin(r.secs / 60) + " of about " + fmtAbout(r.estimate)}))))] : null]; } +/* what a project needs looked at, most serious first (the server's order). On a phone the list shows the first three and + a button for the rest (the CSS clips .clip lists to three under 481 px); the list stays open while the page shows the + project, live updates included, and closes when the person leaves it */ +let openReasons = ""; +function reasonList(p) { + if (lastView !== S.view + "/" + S.id) openReasons = ""; + const rs = p.health.reasons, k = p.health.level === "risk" ? "risk" : "warn"; + if (!rs.length) return null; + const ul = h("ul", {class: "reasons", id: "reasons"}, rs.map(r => h("li", null, h("span", {class: "dot k-" + k, "aria-hidden": "true"}), r))); + if (rs.length <= 3) return ul; + const btn = h("button", {class: "btn ghost rmore", type: "button", id: "reasons-more", "aria-controls": "reasons"}); + const show = () => { const open = openReasons === p.id; ul.classList.toggle("clip", !open); btn.setAttribute("aria-expanded", String(open)); btn.textContent = open ? "Show fewer" : "Show all " + rs.length + " reasons"; }; + btn.addEventListener("click", () => { openReasons = openReasons === p.id ? "" : p.id; show(); }); + show(); + return [ul, btn]; +} function viewProject(main) { const p = BYID.get(S.id); if (!p) { viewUnknownProject(main); return; } @@ -1689,12 +1728,12 @@ function viewProject(main) { m.branch ? h("span", {class: "meta", title: "Current branch"}, icon("branch"), m.branch) : null, ns.due ? duePill(ns.due, p.status === "done") : null, lastSeen ? "active " + rel(lastSeen) : null, p.local ? null : "not cloned here")))), h("div", {class: "go"}, p.local ? cmdBtn("dev claude " + p.id, true, "Copy dev claude") : cmdBtn("dev clone " + p.id, true, "Copy dev clone"), cmdMenu("More commands", p.local ? [["Start Codex", "dev codex " + p.id], ["Go to the checkout", "dcd " + p.id], ["Write the handoff", "dev handoff " + p.id]] : [["Write the handoff", "dev handoff " + p.id]]))), - p.health.reasons.length ? h("ul", {class: "reasons"}, p.health.reasons.map(r => h("li", null, h("span", {class: "dot k-" + (p.health.level === "risk" ? "risk" : "warn"), "aria-hidden": "true"}), r))) : null, + reasonList(p), HWHY[st] ? h("p", {class: "t2", style: "margin:0;font-size:var(--fs-1)", text: HWHY[st] + "."}) : null, projFlags(p).map(flagLine))); const taskParts = [["mark", p.cnt.doing, "Doing"], ["risk", p.cnt.blocked, "Blocked"], ["none", p.cnt.todo, "To do"]]; - main.append(h("div", {class: "g12 tiles"}, - statTile({label: "Open tasks", value: p.cnt.open, href: link({tab: "tasks"}), viz: segBar(taskParts, "Open tasks"), legend: legend(taskParts), cls: "sp-3"}), - statTile({label: "Open PRs", value: p.prs, href: link({tab: "prs"}), viz: ciStrip(p, 14), cls: "sp-3"}), + main.append(h("div", {class: "g12 tiles pfigs"}, + statTile({label: "Open tasks", value: p.cnt.open, href: link({tab: "tasks"}), viz: segBar(taskParts, "Open tasks"), legend: legend(taskParts), cls: "sp-3", say: true}), + statTile({label: "Open PRs", value: p.prs, href: link({tab: "prs"}), viz: ciStrip(p, 14), cls: "sp-3", say: true}), statTile({label: "Commits, 14 days", value: commitSeries([p], 14).reduce((a, d) => a + d[1], 0), viz: spark(commitSeries([p], 14), "Commits per day", "commit", true), cls: "sp-3"}), statTile({label: "Live sessions", value: here.length, viz: here.length ? h("div", {class: "sbars"}, here.map(s => { const x = BYWHO.get(s.who), i = x ? x.sessions.indexOf(x.sessions.find(z => z.session === s.session && z.agent === s.agent)) : -1; return sessBar(s, s.who, Math.max(0, i)); })) : h("span", {class: "t2", text: "Nobody here now"}), cls: "sp-3"}))); main.append(pageTabs([["overview", "Overview"], ["tasks", "Tasks", p.cnt.open], ["prs", "Pull requests", p.prs], ["branches", "Branches", branchesKnown(p) ? p.branches.length : null], ["worktrees", "Worktrees", p.wts.length], ["plans", "Plans", plansL.length || (p.plans || []).length], ["sessions", "Sessions", sess.length], ["note", "Handoff note"]], tab)); @@ -2884,6 +2923,7 @@ function render() { RS = {...S}; renderModal(); if (fid) { const el = document.getElementById(fid); if (el && !$("#modal").open) el.focus({preventScroll: true}); } + tabJump(main, page); if (page !== lastView) { if (lastView) window.scrollTo(0, 0); lastView = page; document.title = pageTitle() + " · Firefly devkit"; } liveTicker(); } diff --git a/lib/devkit/web/base.css b/lib/devkit/web/base.css index 77011e3e..b083b451 100644 --- a/lib/devkit/web/base.css +++ b/lib/devkit/web/base.css @@ -267,6 +267,7 @@ table.pt .prs{flex-wrap:nowrap} .ptab[aria-selected="true"]{color:var(--ink-strong);font-weight:600;box-shadow:inset 0 -2px 0 var(--ink-strong)} .ptab .n{font-weight:400;color:var(--ink-2);font-variant-numeric:tabular-nums} .tabpanel{min-width:0} +.tabpanel.floor{min-height:calc(100vh - var(--nav-h) - var(--tabs-h) - var(--s6))} .seg{display:inline-flex;gap:2px;padding:2px;border-radius:8px;background:var(--surface-sunken);max-width:100%;overflow-x:auto;scrollbar-width:none} .seg::-webkit-scrollbar{display:none} .seg button{flex:none;border:0;background:none;height:28px;padding:0 10px;border-radius:var(--radius-control);cursor:pointer;font-size:var(--fs-1);color:var(--ink-2)} @@ -788,6 +789,20 @@ table.raci td,table.raci th[scope="row"]{height:auto;padding-top:var(--s2);paddi table.pt td.c-act,table.pt td.c-last,table.pt td.c-size{display:none} table.pt td:has(>.muted:only-child){display:none} } +/* a project page on a phone: the three most serious reasons and a button for the rest, its box on the column's edge and + its text in line with the reasons' text (a dot and its gap, 16 px, less the border); the tiles as one row of figures, + each number above its label (the DOM keeps label then number, as a screen reader reads it) and no chart */ +.btn.rmore{display:none} +@media screen and (max-width:480px){ + .reasons.clip>li:nth-child(n+4){display:none} + .btn.rmore{display:inline-flex;justify-self:start;margin-top:calc(var(--s1) - var(--s3));padding:0 calc(var(--s4) - 1px)} + .g12.tiles.pfigs{grid-template-columns:repeat(4,minmax(0,1fr));gap:var(--s2);align-items:stretch} + .g12.tiles.pfigs>.stile{grid-column:auto;gap:var(--s1);padding:var(--s2) 10px 10px} + .pfigs>.stile>.s-v{order:-1} + .pfigs>.stile>.s-v b{font-size:var(--fs-3)} + .pfigs>.stile>.s-l{line-height:1.3;overflow-wrap:break-word;hyphens:auto} + .pfigs>.stile>:not(.s-l,.s-v,.sr){display:none} +} @media (prefers-reduced-motion:reduce){ *,*::before,*::after{scroll-behavior:auto!important} .toast{transform:translate(-50%,0);transition:opacity .15s linear} diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index 562e85b8..2e6909bd 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -1629,6 +1629,20 @@ def test_a_phone_width_below_chromes_window_minimum_is_the_pages_own_width(self) self.assertEqual((out["inner"], out["p"]), (768, 768)) +# what the project page tests read: whether an element has a box, its rectangle, the name a screen reader gives it +# (its text and its images' labels, without what is aria-hidden or not displayed), the reasons shown and their button +PROJECT_JS = """const shown = el => !!el && el.getClientRects().length > 0, box = el => el.getBoundingClientRect(); + const said = el => { const out = []; (function walk(n) { for (const c of n.childNodes) { + if (c.nodeType === 3) out.push(c.textContent); + else if (c.nodeType === 1 && c.getAttribute("aria-hidden") !== "true" && getComputedStyle(c).display !== "none") { + if (c.getAttribute("role") === "img") out.push(c.getAttribute("aria-label") || ""); else walk(c); } } })(el); + return out.join(" ").replace(/\\s+/g, " ").trim(); }; + const reasons = () => $$("main .phead .reasons li").filter(shown).map(text); + const more = () => $$("main .phead button").find(b => /^Show (all|fewer)/.test(text(b)) && shown(b)); + const drawn = t => Array.from(t.children).filter(c => !c.matches(".s-l, .s-v, .sr") && shown(c)).map(c => c.className || c.tagName); + """ + + @unittest.skipUnless(CHROME, NO_CHROME) class PageBehaviorTests(unittest.TestCase): """The page's behavior from fixture data, in headless Chromium: what each view shows, the honest states, role-first names, @@ -1745,6 +1759,116 @@ def test_a_projects_plans_tab_lists_its_sub_folder_plans_under_the_folder(self): self.assertNotIn("render.py", out["text"]) self.assertNotIn("not a plan", out["text"]) + # Under 481 px the reasons list shows the three most serious (the server sends risk first) and a button for the rest, + # which opens and closes the list in place and keeps the focus; from 481 px up every reason shows and there is no button + def test_a_phone_shows_three_reasons_and_a_button_that_shows_them_all(self): + every = next(p for p in self.data["projects"] if p["id"] == "acme/widget")["health"]["reasons"] + self.assertEqual(len(every), 8) + out = self.probe(PROJECT_JS + """const ul = $("main .phead .reasons"), b = more(); + out.closed = [reasons(), text(b), b.getAttribute("aria-expanded"), !!ul.id && b.getAttribute("aria-controls") === ul.id, b.type]; + out.below = box(b).top >= box($$("li", ul).filter(shown).pop()).bottom; + b.focus(); b.click(); await tick(50); + out.open = [reasons(), text(b), b.getAttribute("aria-expanded"), document.activeElement === b]; + b.click(); await tick(50); + out.again = [reasons().length, text(b), b.getAttribute("aria-expanded"), document.activeElement === b];""", 390, "#/projects/acme/widget") + self.assertEqual(out["closed"], [every[:3], "Show all 8 reasons", "false", True, "button"]) + self.assertTrue(out["below"]) + self.assertEqual(out["open"], [every, "Show fewer", "true", True]) + self.assertEqual(out["again"], [3, "Show all 8 reasons", "false", True]) + for width in (481, 1440): + out = self.probe(PROJECT_JS + "out.r = reasons(); out.more = !!more();", width, "#/projects/acme/widget") + self.assertEqual((out["r"], out["more"]), (every, False), width) + + # The open list stays open while the page shows the project (a tab change draws the page again), and closes when the + # person leaves the project; the URL does not carry it + def test_the_open_reasons_list_stays_open_on_its_project_and_closes_when_the_person_leaves(self): + out = self.probe(PROJECT_JS + """more().click(); await tick(50); + await go("#/projects/acme/widget?tab=tasks"); out.tab = [reasons().length, text(more()), location.hash]; + await go("#/projects/acme/api"); await go("#/projects/acme/widget"); out.back = [reasons().length, text(more())];""", 390, "#/projects/acme/widget") + self.assertEqual(out["tab"][:2], [8, "Show fewer"]) + self.assertEqual(out["tab"][2], "#/projects/acme/widget?tab=tasks") + self.assertEqual(out["back"], [3, "Show all 8 reasons"]) + + # On a phone three reasons or fewer show whole, with no button; with none, the section tabs come up to the header + def test_a_phone_shows_three_reasons_or_fewer_whole_and_no_button(self): + def three(d): + p = next(p for p in d["projects"] if p["id"] == "acme/widget") + p["health"]["reasons"] = p["health"]["reasons"][:3] + out = self.probe(PROJECT_JS + "out.r = reasons().length; out.more = !!more();", 390, "#/projects/acme/widget", page=self.variant(three)) + self.assertEqual((out["r"], out["more"]), (3, False)) + out = self.probe(PROJECT_JS + """out.r = reasons().length; out.more = !!more(); out.tab = box($("#tab-overview")).top + scrollY;""", + 390, "#/projects/acme/api") + self.assertEqual((out["r"], out["more"]), (0, False)) + self.assertLessEqual(out["tab"], 580) + + # Under 481 px the four tiles are one row of figures: one top edge and one height, each number above its label, and no + # chart, legend or "Nobody here now" (a zero shows 0); the tabs and the first panel come up into the first screen, + # and the page never scrolls sideways. From 481 px up each tile keeps its chart + def test_a_phone_draws_the_tiles_as_one_row_of_figures_and_brings_the_tabs_up(self): + steps = PROJECT_JS + """const ts = $$("main .tiles > .stile"); + out.tiles = ts.map(t => [Math.round(box(t).top), Math.round(box(t).height), box($(".s-v", t)).bottom <= box($(".s-l", t)).top + 0.5]); + out.drawn = ts.map(drawn); out.values = ts.map(t => text($(".s-v", t))); + out.nobody = $$("main .tiles *").filter(e => !e.children.length && /Nobody here now/.test(e.textContent) && shown(e)).length; + out.tab = box($("#tab-overview")).top + scrollY; + const live = $$("#tabpanel h2").find(h => text(h) === "Live now"); out.live = live ? box(live).top + scrollY : null; + out.page = [document.documentElement.scrollWidth, innerWidth];""" + out = self.probe(steps, 390, "#/projects/acme/widget") + self.assertEqual(len(out["tiles"]), 4) + self.assertEqual(len({(top, height) for top, height, _ in out["tiles"]}), 1, out["tiles"]) + self.assertTrue(all(above for _, _, above in out["tiles"]), out["tiles"]) + self.assertEqual(out["drawn"], [[], [], [], []]) + self.assertLessEqual(out["tab"], 680) + self.assertLessEqual(out["live"], 790) + self.assertLessEqual(out["page"][0], out["page"][1]) + + def nobody_here(d): + for x in d["people"]: + x["sessions"] = [s for s in x["sessions"] if s.get("project") != "acme/widget"] + out = self.probe(steps, 390, "#/projects/acme/widget", page=self.variant(nobody_here)) + self.assertEqual((out["values"][3], out["nobody"], out["drawn"][3]), ("0", 0, [])) + out = self.probe(steps, 1440, "#/projects/acme/widget") + self.assertTrue(all(out["drawn"]), out["drawn"]) + self.assertEqual(len({top for top, _, _ in out["tiles"]}), 1, out["tiles"]) # four across, as before + self.assertTrue(all(not above for _, _, above in out["tiles"]), out["tiles"]) # the label above the number + + # The Open tasks and Open PRs tiles keep their breakdown in their names at every width, also on a phone, where the + # chart that carried it is not drawn + def test_the_task_and_pr_tiles_keep_their_breakdown_in_their_names_at_every_width(self): + steps = PROJECT_JS + """const ts = $$("main .tiles > a.stile"); out.names = ts.map(said); out.drawn = ts.map(drawn);""" + for width, charts in ((390, False), (1440, True)): + out = self.probe(steps, width, "#/projects/acme/widget") + tasks, prs = out["names"] + self.assertTrue(tasks.startswith("Open tasks 3"), (width, tasks)) + self.assertIn("2 doing, 1 blocked", tasks, width) + self.assertTrue(prs.startswith("Open PRs 6"), (width, prs)) + self.assertIn("2 failing, 4 passing", prs, width) + self.assertEqual([bool(d) for d in out["drawn"]], [charts, charts], (width, out["drawn"])) + + # A tab chosen from the stuck tab bar brings the new panel up right under the bar, which stays at its sticky top (0 on + # a phone, under the 56 px nav on a wide screen), however short the panel; the arrow keys choose a tab the same way + # and the focus stays on it. With the bar not stuck, choosing a tab leaves the page where it is + def test_a_tab_chosen_from_the_stuck_bar_starts_its_panel_right_under_the_bar(self): + steps = PROJECT_JS + """const under = () => { const b = box($(".ptabs")); return [Math.round(b.top), Math.round(box($("#tabpanel").firstElementChild).top - b.bottom)]; }; + scrollTo(0, 2000); await tick(50); out.before = under(); + $("#tab-tasks").click(); await tick(300); out.click = [...under(), $("#tab-tasks").getAttribute("aria-selected")]; + scrollTo(0, 2000); await tick(50); $("#tab-tasks").focus(); key($("#tab-tasks"), "ArrowRight"); await tick(300); + out.key = [...under(), document.activeElement && document.activeElement.id]; + scrollTo(0, 2000); await tick(50); $("#tab-worktrees").click(); await tick(300); out.short = under(); + scrollTo(0, 0); await tick(50); $("#tab-overview").click(); await tick(300); out.top = scrollY; + scrollTo(0, 100); await tick(50); $("#tab-tasks").click(); await tick(300); out.near = scrollY;""" + for width, top in ((390, 0), (1440, 56)): + out = self.probe(steps, width, "#/projects/acme/widget") + self.assertEqual(out["before"][0], top, (width, out)) # stuck before the change + self.assertEqual(out["click"][0], top, (width, out)) + self.assertTrue(0 <= out["click"][1] <= 40, (width, out)) + self.assertEqual(out["click"][2], "true", (width, out)) + self.assertEqual(out["key"][0], top, (width, out)) + self.assertTrue(0 <= out["key"][1] <= 40, (width, out)) + self.assertEqual(out["key"][2], "tab-prs", (width, out)) + self.assertEqual(out["short"][0], top, (width, out)) # two worktrees: a short panel + self.assertTrue(0 <= out["short"][1] <= 40, (width, out)) + self.assertEqual((out["top"], out["near"]), (0, 100), (width, out)) + def test_an_initiatives_own_plans_beside_a_sub_folder_are_labeled_with_the_initiatives_id(self): def rooms(d): train = next(p for p in d["plans"] if p["title"] == "Release train") From 91475daa6beddda2d7d11f75cd5bdbe1bb895e8b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 16:44:35 -0800 Subject: [PATCH 10/22] fix(peers): set aside unreadable boxes, remove lock files with boxes A peer box that was not a JSON object stayed forever: delivery to its session failed, and in the canonical store the hourly sweep stopped at it, as it did at a newer devkit's box, so void claims and old escalations were never cleaned up. Every box and escalation the sweep removed also left its lock file behind. Root cause: the sweep had no rule for a box it cannot read: its canonical loop let _read's refusal escape and its legacy loop skipped a box _read returned as None; state.remove deleted only the record, and its lock file could not go safely because state._acquire never checked after its flock that the lock path still named the file it locked, so a waiter on a removed lock file became a second holder state._acquire checks after its flock that the path still names the file it locked and otherwise locks the file the path names now, within the same wait. state.remove(with_lock=True) deletes the lock file under its flock, only as the outermost hold, when no record the lock covers is left, and never in the canonical message store, whose acquisition refuses a replaced lock. The sweep uses it for the legacy boxes and escalations it removes, whose waiters never write a missing record. A box whose bytes are not a JSON object is renamed .