diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e989a41..db263176 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,73 @@ All notable changes to devkit. Versions follow CalVer `YY.MM.PATCH` (PATCH restarts at 0 each month); tags are `vYY.MM.PATCH`. Sections follow [Keep a Changelog](https://keepachangelog.com/). +## [26.11.21] - 2026-11-17 + +### Added + +- **The Chrome team's web platform guidance for frontend work.** `modern-web-guidance` (GoogleChrome, tag `v1.0.1`, + Apache-2.0) reaches Claude Code and Codex, and the `ui` rule requires it with `frontend-design` and `impeccable`: + more than 200 guides to current HTML, CSS, and client-side JavaScript, Core Web Vitals, accessibility, security, + and browser support, searched before an agent writes a web platform feature. The Frontend engineer (Trinity) uses + it in its Build phase, and the UX designer (Sati) loads it too. Its searches run `npx modern-web-guidance@latest`; + the guides are also Markdown files in the skill's folder. +- **Architecture, incident, and performance work require their skills.** `architecture` work now requires the + `architecture` (decision records) and `system-design` skills, not only `research` and `diagrams`; `incident` work + requires `incident-response` and `root-cause`; and `performance` work requires `root-cause`, which the Performance + analyst (The Merovingian) now loads. Go code that declares HTTP routes (`net/http`, Gin, Echo, chi, Fiber) requires + the `backend` skill, as Python, PHP, and Node routes already did. + +- **CI failures name their cause more often.** Of the failures devkit's CI watch diagnosed, most came out as + `unknown`, with only "read the log" as the next action. The first error is now the first line that both reads as an + error and says what failed, so a notice before it is no longer taken for it. Job and step names with spaces, and + the byte order mark GitHub opens each step's log with, no longer hide it. When it says too little, the end of the + failed log decides. A new class, `access`, covers a secret or variable that is not set, bad credentials, and a token + without the permission it needs, as git, gh and GitHub Actions word them; its next action is to set it, since no + code change fixes it. A test of an API that answers 401 or 403 stays a test failure. +- **`dev doctor` shows a scheduled job that is off.** A job turned off had no row, so the nightly `sleep` job could stay + off for weeks unnoticed while lessons stopped decaying and devkit's logs grew. It is now a warning row that says + what stops and gives `dev jobs enable `; a job you turned off in your configuration gets a passing row that + says the same. + +### Fixed + +- **A PR made ready was not watched to its end.** `dev pr ready` starts a new CI run on a commit that often has a + run already: the draft's push, which CI skipped. devkit's watch saw that skipped run, reported "CI skipped" at once, + and ended, so `dev watch --wait` had nothing to wait for while the real run went on. A watch after `pr ready` now + leaves out the runs CI skipped before the command and waits up to five minutes for a run that is not skipped; it + then reports the ready's own run. Where CI does not run on `ready` (GitHub's default `pull_request` trigger), it + reports the commit's earlier run instead. A watch of the draft's push that still runs, an agent's + `dev ci watch --wait` on the commit, and the Stop hook's check for an unwatched run follow the same rule. +- **The same CI result reached a session more than once.** Each `pr ready` or push of one commit joined the session + to a new watch, and each told it the same result. A session now gets each result once, however long each watch + waited. +- **Reading or acknowledging messages through a shell variable was refused.** `dev crew read "$r"` or + `dev crew ack "$r" …` in a loop said the caller was not the tech lead, because devkit matched only the words typed. + For `dev crew read`, `dev crew ack`, `dev session read` and `dev session ack`, a word with a shell expansion now + stands for the argument in its place. Commands that decide, answer or assign still need their words as typed. +- **A finished run's unread messages kept coming back.** Reports and notices nobody acknowledged came back every + minute after `dev progress done`, and each needed its own `dev crew read` and `dev crew ack`. They now close with + the run. `dev progress done` names them, and `dev crew read` still shows each one. +- **An urgent handoff pull could take another command's work item into its own commit.** The commit before a pull + took every change, including a work item another command had just written and not yet committed. That command's + commit and audit record were then lost. A record stays out of the sync's commit until its writer commits it, or + for two minutes at most. Each writer keeps its own marker, so two writers of one file never clear each other's. +- **An interrupted record write could leave its temporary file in the handoff repository.** A handoff made before its + template ignored such files committed it, and nothing removed it. Each Mac now ignores them in its own + `.git/info/exclude`, and `dev gc` removes one once it is an hour old. +- **A work item an editor saved with a byte order mark or Windows line ends lost its frontmatter.** devkit read it + without its id and title, and refused its next write as losing lines. Such a record now reads as it is. A blank + line inside a multi-line `--why` also stays in the item's history. +- **`dev progress start --plan` without `--estimate` told you to plan for `~0m`.** The steps set the run's + estimate, but not the copy corrected by how long runs here really take, which the ETA uses. +- **`dev progress assign`, `add`, `begin`, `reopen`, `skip` and `confirm` print what changed.** They printed the + whole plan, 70 lines and more on a long run, after every change. They now print the changed steps and one line + with the run's progress; `--verbose` prints the whole plan. +- **`dev progress step "api: …"` closes the step named `api`.** A description that starts with an open step's name and + a colon closes that step, instead of the running one, which it does not describe. +- **`dev plan revise`, `approve` and `supersede` take a plan's id.** `dev plan approve P-…` refused the id that + `dev plan ls` shows; it finds the plan now. + ## [26.11.20] - 2026-11-17 ### Changed diff --git a/VERSION b/VERSION index 4a750a9f..bf9a6dec 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -26.11.20 +26.11.21 diff --git a/agents/AGENTS.md b/agents/AGENTS.md index 05fbf67c..211a5b35 100644 --- a/agents/AGENTS.md +++ b/agents/AGENTS.md @@ -296,7 +296,7 @@ A devkit or CI notice, and a crew or peer message shown whole in the text a hook delivery. A longer message arrives as a preview: read it with `dev crew read REF --json` (main-session peer messages: `dev session read S-ID --json`), following `next_cursor` until `complete`, then acknowledge it with `dev crew ack REF --sha256 DIGEST --generation N` (or `dev session ack`); until then it comes back about once a -minute. A receipt never answers, decides, or approves. Send the whole body (positional text, `--text-file PATH`, or +minute, or until its run ends, which closes it unread. A receipt never answers, decides, or approves. Send the whole body (positional text, `--text-file PATH`, or `--stdin`, with `--request-id KEY` on retries), never a scratch path alone, to an exact lane when a role is ambiguous. When a lane is replaced, the tech lead sends the replacement a new message with the original reference and context, and never acknowledges for the old recipient. @@ -449,7 +449,7 @@ Follow the devkit `backend` skill for the detailed checklists. Always: installed `node_modules/` docs, framework MCPs), then web search. Check the version in the lockfile before using an API. - **Required skills are enforced.** devkit maps kinds of work to skills in `config/skill-rules.json`, for example - UI → `frontend-design` and `impeccable`, tests → `testing`, pipelines → `cicd`, Spring → `java-springboot`, + UI → `frontend-design`, `impeccable` and `modern-web-guidance`, tests → `testing`, pipelines → `cicd`, Spring → `java-springboot`, Postgres migrations → `supabase-postgres-best-practices`, workflows → `github-actions-hardening`, docs, skills and instructions → `docs`, pushes → `delivery`, releases → `release-policy`, and so on. devkit names the skills for the files you change; load them before you start. Briefs for Claude subagents get them appended. A turn that changed @@ -473,7 +473,8 @@ Follow the devkit `backend` skill for the detailed checklists. Always: (`/grill-with-docs`, `/improve-codebase-architecture`): a model cannot load them, so suggest them and never put them in a brief. ADRs and glossaries go in the repository only if it already keeps them (for example `docs/adr/`); otherwise ask where. -- **Frontend:** `frontend-design` and `impeccable` for UI quality; `angular-developer`, +- **Frontend:** `frontend-design` and `impeccable` for UI quality; `modern-web-guidance` (Chrome's guides) before + writing a web platform feature: HTML, CSS, client-side JavaScript, Core Web Vitals, accessibility; `angular-developer`, `react-best-practices`, `composition-patterns`; Chrome DevTools MCP and `playwright-cli` to verify in a real browser. Design first: take a screenshot, critique it, fix what the critique finds, and look again; settle the hierarchy (what the user sees first) before adding features, and prefer visuals with details on demand to more diff --git a/config/crew.json b/config/crew.json index a9c79a01..02cb996b 100644 --- a/config/crew.json +++ b/config/crew.json @@ -786,6 +786,7 @@ "frontend-design", "superpowers:test-driven-development", "impeccable", + "modern-web-guidance", "superpowers:verification-before-completion", "testing", "communicating" @@ -851,10 +852,11 @@ }, { "phase": "Build", - "do": "Build with the framework's current patterns and the project's components; keep state minimal; behavior tests first.", + "do": "Build with the framework's current patterns and the project's components; keep state minimal; behavior tests first. Before writing a web platform feature (a dialog, a form, a layout, an animation, dates, sanitizing HTML, Core Web Vitals), search `modern-web-guidance` for it and follow the guide it retrieves.", "skills": [ "superpowers:test-driven-development", - "impeccable" + "impeccable", + "modern-web-guidance" ], "devkit": [ "dev test" @@ -1542,6 +1544,7 @@ "skills": [ "frontend-design", "impeccable", + "modern-web-guidance", "communicating" ], "tools": "build", @@ -2514,6 +2517,7 @@ "missing traces or metrics" ], "skills": [ + "root-cause", "otel-instrumentation", "superpowers:systematic-debugging", "otel-semantic-conventions", diff --git a/config/skill-rules.json b/config/skill-rules.json index 101e0e45..e10dfc62 100644 --- a/config/skill-rules.json +++ b/config/skill-rules.json @@ -10,7 +10,7 @@ }, { "id": "ui", - "why": "UI quality: frontend-design for the direction, impeccable for hierarchy, layout, typography, color and the audit", + "why": "UI quality: frontend-design for the direction, impeccable for hierarchy, layout, typography, color and the audit, modern-web-guidance for current web platform practice (HTML, CSS, client-side JavaScript, Core Web Vitals, accessibility)", "activities": [ "ux", "frontend", @@ -61,11 +61,13 @@ "skills": { "claude": [ "frontend-design", - "impeccable" + "impeccable", + "modern-web-guidance" ], "codex": [ "frontend-design", - "impeccable" + "impeccable", + "modern-web-guidance" ] } }, @@ -222,7 +224,8 @@ "*.ts", "*.js", "*.mjs", - "*.cjs" + "*.cjs", + "*.go" ], "content_exclude": [ "test_*.py", @@ -239,7 +242,7 @@ "*Test.php", "conftest.py" ], - "content": "@(?:app|api|router|bp|blueprint|[a-z_]+_router)\\.(?:get|post|put|patch|delete|route|api_route|websocket)\\(|\\bAPIRouter\\(|\\bFastAPI\\(|\\bFlask\\(__name__|\\burlpatterns\\s*=|Route::(?:get|post|put|patch|delete|any|match|resource|apiResource|group|middleware|prefix|controller)\\b|#\\[Route\\(|\\b(?:app|router|server|fastify)\\.(?:get|post|put|patch|delete|all|route)\\(\\s*['\"`]/|from\\s+['\"]@nestjs/|require\\(['\"]express['\"]\\)|from\\s+['\"]express['\"]|\\bnew\\s+Hono\\(", + "content": "@(?:app|api|router|bp|blueprint|[a-z_]+_router)\\.(?:get|post|put|patch|delete|route|api_route|websocket)\\(|\\bAPIRouter\\(|\\bFastAPI\\(|\\bFlask\\(__name__|\\burlpatterns\\s*=|Route::(?:get|post|put|patch|delete|any|match|resource|apiResource|group|middleware|prefix|controller)\\b|#\\[Route\\(|\\b(?:app|router|server|fastify)\\.(?:get|post|put|patch|delete|all|route)\\(\\s*['\"`]/|from\\s+['\"]@nestjs/|require\\(['\"]express['\"]\\)|from\\s+['\"]express['\"]|\\bnew\\s+Hono\\(|\\bhttp\\.HandleFunc\\(|\\bgin\\.(?:Default|New)\\(|\\becho\\.New\\(|\\bchi\\.NewRouter\\(|\\bfiber\\.New\\(", "skills": { "claude": [ "backend" @@ -624,6 +627,55 @@ ] } }, + { + "id": "architecture", + "why": "Architecture decisions as ADRs with their trade-offs, and system design: boundaries, data and API contracts, scale and failure", + "activities": [ + "architecture" + ], + "skills": { + "claude": [ + "architecture", + "system-design" + ], + "codex": [ + "architecture", + "system-design" + ] + } + }, + { + "id": "incident", + "why": "An incident: stabilize first, then prove the root cause, keep the timeline and write the blameless postmortem", + "activities": [ + "incident" + ], + "skills": { + "claude": [ + "incident-response", + "root-cause" + ], + "codex": [ + "incident-response", + "root-cause" + ] + } + }, + { + "id": "performance", + "why": "Performance: measure before changing anything, prove the cause with a profile or a trace, then compare before and after", + "activities": [ + "performance" + ], + "skills": { + "claude": [ + "root-cause" + ], + "codex": [ + "root-cause" + ] + } + }, { "id": "functional-analysis", "why": "Requirements before design: actors, flows, numbered rules, edge cases and acceptance criteria with ids that tests trace", diff --git a/config/skills.json b/config/skills.json index 5a3103b7..752efcd1 100644 --- a/config/skills.json +++ b/config/skills.json @@ -31,6 +31,15 @@ "impeccable": ".claude/skills/impeccable" } }, + { + "repo": "GoogleChrome/modern-web-guidance", + "ref": "64a6d708f5a43f2cd3fde5d4d7db3905ba1bdf65", + "license": "Apache-2.0", + "why": "The Chrome team's web platform guidance (tag v1.0.1): modern HTML, CSS and JavaScript, Core Web Vitals, accessibility, security and browser support; its searches run npx modern-web-guidance@latest (npm, SLSA provenance), and its guides are in the skill folder", + "skills": { + "modern-web-guidance": "skills/modern-web-guidance" + } + }, { "repo": "mattpocock/skills", "ref": "4ae2317ddb22b046e26455e4f9c9b3aaaf62212d", diff --git a/desktop/manifest.json b/desktop/manifest.json index 094407f0..496003c8 100644 --- a/desktop/manifest.json +++ b/desktop/manifest.json @@ -2,7 +2,7 @@ "manifest_version": "0.4", "name": "devkit", "display_name": "devkit", - "version": "26.11.20", + "version": "26.11.21", "description": "Every repo in its place. Every agent on the same page. Your devkit portfolio, project status, tasks, CI and team, in Claude Desktop chat and Cowork.", "long_description": "devkit connects Claude Desktop to **devkit** from Firefly Software Solutions Inc.: every repository in its place under ~/Development, one handoff repository that keeps each project's status, tasks, plans, lessons and session log, and the same rules for Claude Code, Codex and the team. Claude Code already uses devkit through its plugin; this extension brings it to Desktop chat and Cowork.\n\n**What you can ask**\n\n- **Where things stand:** the portfolio overview, one project's status, its tasks, a standup of the last days, and a status report for the team or management.\n- **Delivery:** live CI/CD runs with job progress and an ETA, and a project's delivery policy (versioning, test gate, release flow) with its gaps.\n- **Team and history:** who is working on what, devkit's crew of specialist agents and the decisions waiting for you, lessons learned, devkit's audit trail, its scheduled jobs, and a health check of the whole setup.\n- **Tasks:** add a task, or start, finish, block, unblock or release one. Changes go through the `dev` command, so devkit's audit trail applies exactly as it does in the terminal.\n\nWhen Claude reports a project's status, it starts with the devkit status block (**[Firefly> DevKit]**), the same one Claude Code and Codex use.\n\n**Setting it up.** devkit must be installed on this Mac: run `./install.sh` in the devkit repository, which runs `dev setup`. The extension finds devkit on its own; set the devkit folder only if devkit is not where `dev setup` put it. At startup, the extension selects the configured devkit folder or the installed `dev` link. Install or update devkit through its supported policy, then restart Claude Desktop or turn the extension off and on to load the new tools. A running server keeps the version it started with. It needs Python 3.9 or later, which comes with the macOS Command Line Tools.\n\n**Privacy.** Everything runs on your Mac through the `dev` command and reads your workspace and handoff repository. The project status, CI status and doctor tools ask GitHub or your CI provider through your existing sign-in (for example `gh auth login`); task changes are pushed to your own handoff repository. No token is stored by the extension.", "author": { diff --git a/docs/ci-cd.md b/docs/ci-cd.md index d959a793..b4eb1bf2 100644 --- a/docs/ci-cd.md +++ b/docs/ci-cd.md @@ -380,6 +380,13 @@ session that sends a commit devkit already watches joins that watcher. The resul commit, each once, at its next hook or in its `dev watch --wait`. Each result is recorded once, whichever watch of the commit ends first. +A PR made ready (`dev pr ready`, `gh pr ready`) starts a new run on a commit that often has one already: the +draft's push, which CI skipped. Its watch leaves out the runs CI skipped before the command and waits up to five +minutes for a run that is not skipped, then reports that run. Where CI does not run on `ready` (GitHub's default +`pull_request` trigger runs on opened, synchronize and reopened), it reports the commit's earlier run instead. A +watch of the draft's push that still runs, an agent's `dev ci watch --wait` on the commit, and the Stop hook's check +for an unwatched run follow the same rule. + ```bash dev ci watch # the current branch at HEAD dev ci watch --branch feat/export --sha a1b2c3d --timeout 60 @@ -404,10 +411,13 @@ the run; a job the pull request run did not pass still holds it, even before `ma For each failed run, devkit finds the failed jobs and steps and reads the failed log from its **first** error, because the errors after it follow from it (`gh run view --log-failed` on GitHub, `glab ci trace` on GitLab; Bitbucket and -Azure give the job, the step, and the link). It sorts the error into one class and gives one next action: +Azure give the job, the step, and the link). The first error is the first line that both reads as an error and says +what failed, so a notice before it (`claude CLI not found: skipped`) is not taken for it. devkit sorts the error into +one class and gives one next action; when the first error says too little, the end of the failed log decides: | Class | Typical first error | Next action | | --- | --- | --- | +| `access` | A secret or variable that is not set, bad credentials, a token without the permission it needs (`Resource not accessible by integration`, HTTP 401 or 403) | Set it in the repository's settings (`gh secret set `) or grant the permission in the workflow's `permissions:` block (least privilege); no code change fixes it, so rerun once it is set | | `pipeline` | Invalid workflow file, an unknown property, an action that cannot be resolved | `dev ci audit`, fix the workflow, check it with actionlint, push once | | `infrastructure` | Network errors, rate limits, a lost runner, a full disk | Confirm it is not the change, then rerun once: `dev run rerun --flaky ""` | | `dependencies` | A version that cannot be resolved, a lockfile out of date | Install from the lockfile locally, fix, push once | diff --git a/docs/commands.md b/docs/commands.md index 8b87953d..d3e0d974 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -324,7 +324,7 @@ Versioned plans and specs in `plans//`. See [Templates](templates.md#plan | --- | --- | | `dev plan new "" [--kind plan\|spec\|spike\|bugfix\|adr]` | Creates `plans/<scope>/<date>-<slug>.md` from the template of that kind (default `plan`), at version 1, status draft | | `dev plan revise <file> --why "…"` | Records a change: bumps the version, logs who, when, why, and the size of the change, and commits. A plan written without devkit (for example by Superpowers) is adopted into the format on its first revision | -| `dev plan approve <file> [--why "…"]` | Sets the status to approved and records a version | +| `dev plan approve <file> [--why "…"]` | Sets the status to approved and records a version. `revise`, `approve` and `supersede` also take the plan's id (`P-…`, as `dev plan ls` shows it) instead of its file | | `dev plan supersede <file> --why "…"` | Sets the status to superseded and records a version | | `dev plan` · `dev plan ls` | Every plan (or the plans of `-p` / `-i`): id, status, version, title, path, and `✎ needs dev plan revise` when the body changed without a revision | @@ -356,9 +356,10 @@ Live progress of long agent work, with active time, a critical-path ETA and a pl | `dev progress add "<name>=<estimate> [after …] [<id>]" [--why "…"]` | Adds a step found during the work; add it when it starts. `[<id>]` declares its kind of work, as in a plan. Each quoted spec is a step (`dev progress add "a=5h [security]" "b=2h [testing]"` adds two), and so is each part between `;`; a step name that still holds an estimate (`a=5h b`) is refused. From a crew member, the step goes to its own lane | | `dev progress assign <step> --to <member> [--scope "<globs>"] [--activity ID] [--why "…"]` | Hands a step to a crew member; its time is that member's, and an edit outside the scope gets advice in the member's context. A working lane of that member that holds no other open step takes it at once, a member resumed with `SendMessage` included, so the lane gets the step's scope and its report closes it. When each working lane of the member holds another open step, the step is queued for those lanes and joins, with its scope, the first one whose step closes; `--to "<launch description>"` gives it to one lane. `--activity` declares the step's kind of work (an id from `dev crew raci`, such as `backend` or `ux`), so the RACI check and the approver do not depend on the language of the step's name. Refused when the crew's RACI does not make that member Responsible for the step's kind of work, unless `--why` gives the reason, which is recorded | | `dev progress begin <step>` | Starts a step in parallel with the running one | +| `… --verbose` on `add`, `assign`, `begin`, `reopen`, `skip` and `confirm` | Prints the whole plan after the change. Without it, these commands print the steps the change touched and one line with the run's progress | | `dev progress reopen <step> --why "…"` · `dev progress skip <step> --why "…"` · `dev progress confirm <step> --why "…"` | Undoes a wrong close, skips a step on purpose, or confirms a step whose dependencies were reopened and closed again | | `dev progress block "<why>" [--next "<what is needed>"]` | The run is blocked; prints the update and sends a desktop notification | -| `dev progress done "<outcome>" [--why "…"]` | The run is finished; refused while steps are pending, decisions wait, or an Accountable member has not approved the work they own. `--why` ends it without that approval and records the reason. Records the active time against the estimate and sends a desktop notification | +| `dev progress done "<outcome>" [--why "…"]` | The run is finished; refused while steps are pending, decisions wait, or an Accountable member has not approved the work they own. `--why` ends it without that approval and records the reason. Records the active time against the estimate and sends a desktop notification. The messages to you that nobody acknowledged close with the run, so they stop coming back, and it names them; `dev crew read` still shows each one | | `dev progress history` | Every step change: when, from → to, by whom (the tech lead (Morpheus), a crew member, devkit), why | | `dev progress` | Every run of the last 12 hours on this Mac, this session's run first and then the others, newest first, and the runs of other machines from their presence | | `dev progress time [--days N] [-p PROJECT]` | Same as `dev time` | diff --git a/docs/crew.md b/docs/crew.md index 6403ec83..8c729d83 100644 --- a/docs/crew.md +++ b/docs/crew.md @@ -470,7 +470,10 @@ and the same send repeated in that call is one. A message whose whole body fits in the preview the hook or the wait delivers (180 characters), and every notice from devkit or CI watch, counts as read once that preview is delivered: it never comes back. A longer message is a -preview: it comes back about once a minute until its recipient reads and acknowledges it. Use +preview: it comes back about once a minute until its recipient reads and acknowledges it, or until its run ends: +`dev progress done` closes the messages nobody acknowledged and names them, and `dev crew read` still shows each one. +A reference may come from a shell variable in `dev crew read` and `dev crew ack` +(`for r in …; do dev crew read "$r" --json; done`); commands that decide or answer need their words as typed. Use `dev crew inbox [--all] [--cursor CURSOR] [--json]` for the paged index, then `dev crew read REF --json`. Follow each `next_cursor` with `--cursor` until `complete` is true. Each serialized page fits 6,144 bytes. Only then acknowledge the returned digest and generation with `dev crew ack REF --sha256 DIGEST --generation N`. diff --git a/docs/jobs-and-audit.md b/docs/jobs-and-audit.md index 5c00b24c..4dfd4326 100644 --- a/docs/jobs-and-audit.md +++ b/docs/jobs-and-audit.md @@ -72,7 +72,9 @@ dev jobs journal --days 7 # past runs of every job: start, result, duration, las ``` `STATE` is `on` (loaded), `not loaded` (enabled but not loaded: run `dev jobs install`), or `off`. `dev doctor` checks -every enabled job: it must be loaded, and its last run must have passed. +every enabled job: it must be loaded, and its last run must have passed. A job that is `off` is a warning row that +says what stops while it is off (with `sleep` off, lessons never decay and devkit's logs keep growing) and how to turn +it on: `dev jobs enable <name>`. ## Change a schedule diff --git a/docs/skills-and-plugins.md b/docs/skills-and-plugins.md index bc8a5a4d..2bd083e1 100644 --- a/docs/skills-and-plugins.md +++ b/docs/skills-and-plugins.md @@ -74,13 +74,13 @@ one step: only Claude Code's subagent briefs get the required skills added by a | Rule | Claude Code | Codex | Matches (files; commands; kinds of work) | | --- | --- | --- | --- | -| `ui` | `frontend-design`, `impeccable` | the same | HTML, CSS, Sass, Less, TSX, JSX, Vue, and Svelte files; code in other languages, outside tests, that renders HTML or styles or declares an Angular component; `ux`, `frontend`, `design-system`, `accessibility`, and `i18n` work | +| `ui` | `frontend-design`, `impeccable`, `modern-web-guidance` | the same | HTML, CSS, Sass, Less, TSX, JSX, Vue, and Svelte files; code in other languages, outside tests, that renders HTML or styles or declares an Angular component; `ux`, `frontend`, `design-system`, `accessibility`, and `i18n` work | | `testing` | `testing` | `testing` | Test files of every stack, `conftest.py`, test runner configs; `pytest`, `jest`, `vitest`, `dev test`, `python3 -m unittest`; `testing` work | | `angular` | `angular-developer` | `angular-developer` | Components, `angular.json`, routes; `ng build`, `ng generate`, `ng serve`, `ng test`, `ng update` | | `react` | `react-best-practices` | `react-best-practices` | TSX and JSX files; `next build`, `next dev` | | `spring` | `java-springboot`, `backend` | the same | Java and Kotlin files that use `org.springframework` | | `java-tests` | `java-junit`, `spring-boot-testing` | the same | `*Test.java`, `*Tests.java`, `*IT.java` | -| `api` | `backend` | `backend` | OpenAPI, GraphQL, and protobuf files; Java, PHP, and TypeScript controllers; Python, PHP, and Node code, outside tests, that declares HTTP routes (FastAPI, Flask, Django, Laravel, Symfony, Express, NestJS, Fastify, Hono); `backend` and `sso` work | +| `api` | `backend` | `backend` | OpenAPI, GraphQL, and protobuf files; Java, PHP, and TypeScript controllers; Python, PHP, Node, and Go code, outside tests, that declares HTTP routes (FastAPI, Flask, Django, Laravel, Symfony, Express, NestJS, Fastify, Hono, `net/http`, Gin, Echo, chi, Fiber); `backend` and `sso` work | | `database` | `backend` | `backend` | SQL files and migration folders; `alembic`, `flyway`, `liquibase`, `prisma migrate`; `database` work | | `postgres` | `supabase-postgres-best-practices` | the same | SQL files and migration folders in a repository whose project files name Postgres; `psql`, `pg_dump`, `pg_restore` | | `workflows` | `cicd`, `github-actions-hardening`, `delivery` | the same | GitHub, GitLab, Bitbucket and Azure pipeline files; `gh workflow`; `cicd` work | @@ -95,6 +95,9 @@ one step: only Claude Code's subagent briefs get the required skills added by a | `learning` | `learning-loop` | `learning-loop` | `dev lesson add`, `dev lesson recur`, `dev lesson prevent`, `git revert`; `incident` work | | `root-cause` | `root-cause` | the same | `debug` work | | `research` | `research` | the same | `research` and `architecture` work | +| `architecture` | `architecture`, `system-design` | the same | `architecture` work | +| `incident` | `incident-response`, `root-cause` | the same | `incident` work | +| `performance` | `root-cause` | the same | `performance` work | | `functional-analysis` | `functional-analysis` | the same | `requirements` work | | `work-state` | `work-state` | `work-state` | `dev task reconcile`, `dev branch prune`, `dev crew withdraw`, `dev progress confirm`; `release` and `plan` work | | `configuration` | `configuration` | `configuration` | Devkit schema/core and configuration tests; `dev config set`, `dev config edit`, `dev config validate` | @@ -210,6 +213,12 @@ the plugin does not: `impeccable` (pbakaus/impeccable, tag `skill-v4.8.0`, Apach `frontend-design` (anthropics/claude-plugins-official, Apache-2.0) for Codex. The `ui` rule requires both: frontend-design for the direction, impeccable for hierarchy, layout, typography, color, and the audit. +`modern-web-guidance` (GoogleChrome/modern-web-guidance, tag `v1.0.1`, Apache-2.0) reaches both agents too, and the +`ui` rule requires it: the Chrome team's guides to current HTML, CSS, and client-side JavaScript, Core Web Vitals, +accessibility, security, and browser support. The agent searches them before it writes a web platform feature. Its +searches run `npx modern-web-guidance@latest`, an npm package the Chrome team publishes with SLSA provenance; the +same guides are Markdown files in the skill's `guides/` folder, which an agent can read without npm. + ### impeccable and its engine impeccable's first setup step is its `context` command, which loads the project's PRODUCT.md, DESIGN.md, and surface diff --git a/docs/work-states.md b/docs/work-states.md index 935c8007..64e76f54 100644 --- a/docs/work-states.md +++ b/docs/work-states.md @@ -204,8 +204,8 @@ and it does not stop `dev progress done`. If you answer it anyway, your answer s Every crew message has a kind. A devkit or CI notice, and a message shown whole in the text a hook or `dev watch` delivers (up to 180 characters), is read on delivery and does not come back. A longer message arrives as a preview and comes back about once a minute until its recipient reads it with `dev crew read REF --json` and -acknowledges the returned digest and generation with `dev crew ack`. An acknowledgment never answers, decides, or -approves. Pending and unacknowledged bodies remain in canonical storage; older runtime projections cannot change +acknowledges the returned digest and generation with `dev crew ack`, or until its run ends, which closes it unread +(`dev crew read` still shows it). An acknowledgment never answers, decides, or approves. Pending and unacknowledged bodies remain in canonical storage; older runtime projections cannot change their receipts or answers. When a lane is replaced, the lead reads the original body fully and sends a new message to the exact replacement diff --git a/lib/devkit/ciwatch.py b/lib/devkit/ciwatch.py index 0743a239..891346e2 100644 --- a/lib/devkit/ciwatch.py +++ b/lib/devkit/ciwatch.py @@ -34,6 +34,7 @@ """ from __future__ import annotations +import hashlib import json import os import re @@ -57,6 +58,8 @@ EXIT = {"passed": 0, "failed": 1, "timeout": 3, "none": 4} # 2: nothing to watch FINAL = ("passed", "failed", "none") # how a watch can end with its run's result DONE = ("success", "failed", "cancelled", "skipped") +NO_RUN_MIN = 5 # minutes without a run after which a watch says CI does not run for this commit +READY_SKEW_S = 10 # seconds before a `pr ready` call opened that its run may say it started (the host's clock) # How a run ended, as the host says it -> (the word a report uses, the verdict it counts for). GitHub gives its # conclusion; the other hosts give a status that cistatus reads as success, failed, cancelled or skipped. CONCLUSIONS = { @@ -84,8 +87,17 @@ r"checkstyle|spotless|ktlint|golangci-lint|phpstan|psalm|markdownlint|actionlint|zizmor|Vale"), ("build", r"error: cannot find symbol|compilation failed|BUILD FAILURE|Build failed|error\[E\d+\]|" r"SyntaxError|cannot compile|failed to compile|webpack.*error|vite.*error"), + # after test, lint and build: a test of an API prints 401 and 403 too, and is the test's failure, not access. + # Only the wording of git, gh and Actions about the run's own secrets, credentials and token + ("access", r"secret \S+ is not set|secrets?\.\w+ is (empty|not set|missing)|Bad credentials|" + r"Resource not accessible by integration|remote: Permission to \S+ denied|" + r"The requested URL returned error: 40[13]|" + r"Input required and not supplied: (token|github-token|password|api-key)"), ] ACTIONS = { + "access": "the workflow lacks a secret, a variable or a token permission it needs: set it in the repository's " + "settings (gh secret set <NAME>) or grant the permission in the workflow's permissions block (least " + "privilege); no code change fixes it, so rerun the run once it is set", "test": "a test failed: reproduce it locally (dev test run --failed or the exact test), fix the code or the test " "for the real reason, then dev ci --run --resume and push once", "lint": "a lint, format or type check failed: run the same check locally (dev ci --run), fix, push once", @@ -105,6 +117,10 @@ } ERROR_LINE = re.compile(r"(?i)\b(error|failed|failure|fatal|exception|traceback|assert|panic|cannot|could not|" r"not found|denied|exit code [1-9])\b|✗|##\[error\]") +# A line that names a class of failure (CLASSES) and reads as one: a tool's name alone ("Run ruff check") is no error +_SAYS_WHAT = re.compile("|".join(f"(?:{rx})" for _, rx in CLASSES)) +_ERRORISH = re.compile(r"(?i)error|fail|assert|exception|denied|not set|missing|unauthorized|forbidden|" + r"not accessible|credentials|required|reformat|would|cannot|could not|✗") def _key(repo: str, branch: str) -> str: @@ -172,15 +188,20 @@ def classify(text: str) -> str: def first_error(log: str, context: int = 6, limit: int = 30) -> str: - """The lines around the first error of a log, with timestamps and ANSI codes stripped and secrets redacted.""" + """The lines around the first error of a log, with timestamps and ANSI codes stripped and secrets redacted. The + first error is the first line that is an error and says what failed (a class's pattern: an assertion, a missing + secret, a compile error); else the first line that is an error at all, so a notice such as "claude CLI not found: + skipped" before the real failure is not taken for it.""" from .audit import redact lines = [] for raw in (log or "").splitlines(): - ln = re.sub(r"\x1b\[[0-9;]*m", "", raw) - ln = re.sub(r"^\S+\t\S+\t", "", ln) # gh --log-failed: "<job>\t<step>\t<line>" + ln = re.sub(r"\x1b\[[0-9;]*m", "", raw.replace("\ufeff", "")) # GitHub opens each step's log with a BOM + ln = re.sub(r"^[^\t\n]*\t[^\t\n]*\t", "", ln) # gh --log-failed: "<job>\t<step>\t<line>", names with spaces too ln = re.sub(r"^\d{4}-\d\d-\d\dT[\d:.]+Z\s?", "", ln) lines.append(ln.rstrip()) - i = next((n for n, ln in enumerate(lines) if ERROR_LINE.search(ln)), None) + said = [n for n, ln in enumerate(lines) if ERROR_LINE.search(ln) or _SAYS_WHAT.search(ln)] + i = next((n for n in said if _SAYS_WHAT.search(lines[n]) and _ERRORISH.search(lines[n])), None) + i = i if i is not None else next((n for n in said if ERROR_LINE.search(lines[n])), None) if i is None: chunk = lines[-limit:] else: @@ -213,6 +234,8 @@ def diagnose(provider: str, top: str, run: dict) -> dict: # a cancel or a timeout leaves "The operation was canceled" in the log: never read it as a flaky runner kind = "cancelled" if word in STOPPED else \ classify(excerpt or log[-20_000:] if log else " ".join(j.get("name", "") for j in jobs)) + if kind == "unknown" and log and word not in STOPPED: # the first error says too little: the failed log's end + kind = classify(first_error(log[-20_000:], context=0, limit=10_000) or log[-20_000:]) return {"run": run.get("name"), "number": run.get("number"), "id": run.get("id"), "url": run.get("url"), "sha": run.get("sha"), "conclusion": word, "failed_jobs": [{"name": j.get("name"), "step": j.get("current") or "", "url": j.get("url")} for j in jobs], @@ -250,11 +273,16 @@ def _final_jobs(provider: str, repo: str, run: dict) -> list: def watch(top: str, branch: str | None = None, sha: str | None = None, timeout_min: float = 90, poll: float = 20, quiet: bool = True, sleep=time.sleep, clock=time.time, runs_fn=None, on_event=None, - always_diagnose: bool = False) -> dict: + always_diagnose: bool = False, since: float | None = None) -> dict: """Follow the CI runs of a branch (for one commit when `sha` is given) until all finish or the timeout. A host error (network, rate limit, an outage) is retried until the timeout; a remote with no CI host devkit reads ends at once. on_event(line): each job of the commit's runs once, as it finishes (job_line). always_diagnose: diagnose - a failure that another watch reported first (an agent waits on this one). + a failure that another watch reported first (an agent waits on this one). `since` (a PR made ready, which starts a + new run on a commit that may have runs already; else the moment a watch record of the commit keeps, so a watch + of the draft's push that still runs follows the ready too): a run skipped before it is the draft's and is left + out, and the watch waits up to NO_RUN_MIN for a run from then on that is not skipped (a draft's run the same + command pushed can start after `since` and be skipped at once). Once one appears, only the runs from then on are + reported; when none does (a repository whose CI does not run on `ready`), the commit's other runs are. -> {"state": passed|failed|timeout|none, "runs": [...], "diagnoses": [...], ...}""" from . import cistatus runs_fn = runs_fn or cistatus.runs_for @@ -262,7 +290,9 @@ def watch(top: str, branch: str | None = None, sha: str | None = None, timeout_m sha = (sha or core.gitout(top, "rev-parse", "HEAD"))[:7] start = clock() seen_any, told, data, runs = False, set(), {}, [] + ident = repo_id(top) while True: + since = since or _since(ident, branch, sha) try: data = runs_fn(top, branch, limit=6, detail=True, max_age=0) or {} except Exception as e: # a host call that raised is as transient as one that returned its error @@ -270,7 +300,8 @@ def watch(top: str, branch: str | None = None, sha: str | None = None, timeout_m "error": str(e)[:300]} failing = bool(data.get("error")) and bool(data.get("provider")) if not failing: # a failed call keeps what the last good one saw - runs = [r for r in data.get("runs") or [] if not sha or (r.get("sha") or "")[:7] == sha] + runs = [r for r in data.get("runs") or [] if (not sha or (r.get("sha") or "")[:7] == sha) + and not (since and _before(r, since) and conclusion(r)[0] == "skipped")] if on_event and runs and all(r.get("status") in DONE for r in runs): for r in runs: r["jobs"] = r.get("jobs") or _final_jobs(data.get("provider") or "", data.get("repo") or "", r) @@ -282,12 +313,15 @@ def watch(top: str, branch: str | None = None, sha: str | None = None, timeout_m on_event(job_line(r, j)) if runs: seen_any = True - if runs and all(r.get("status") in DONE for r in runs): + waited = (clock() - start) / 60 + ready_run = bool(since) and any(not _before(r, since) and conclusion(r)[0] != "skipped" for r in runs) + if runs and all(r.get("status") in DONE for r in runs) and (not since or ready_run or waited >= NO_RUN_MIN): + if ready_run: # the ready run is the result; the runs before it were reported by the draft's watch + runs = [r for r in runs if not _before(r, since)] break if not data.get("provider"): # origin is no CI host devkit reads: no run will ever appear return _finish(top, data, branch, sha, runs, "none", start, clock, always_diagnose) - waited = (clock() - start) / 60 - if waited >= timeout_min or (not seen_any and not failing and waited >= 5): + if waited >= timeout_min or (not seen_any and not failing and waited >= NO_RUN_MIN): # no run after 5 minutes: CI does not run for this push return _finish(top, data, branch, sha, runs, "timeout" if seen_any or failing else "none", start, clock, always_diagnose) @@ -299,6 +333,11 @@ def watch(top: str, branch: str | None = None, sha: str | None = None, timeout_m return _finish(top, data, branch, sha, runs, verdict(runs), start, clock, always_diagnose) +def _before(run: dict, since: float) -> bool: + """Did the run start before `since`? A run with no start time counts as after it.""" + return bool(run.get("started")) and run["started"] < since + + def _finish(top, data, branch, sha, runs, state, start, clock, always_diagnose=False) -> dict: """The result of a watch. Each run carries how it ended and whether this watch is the first to report it (new); `repeat` when no run is new: a result reported before, which record and deliver then leave alone. A final result @@ -428,26 +467,45 @@ def _tell(agent: str, sid: str, res: dict) -> bool: return False from . import progress from .audit import redact - text = message(res) + from . import messaging + text, key = message(res), _result_key(res) try: run = progress.load_run(agent, sid) - if run and run.get("state") not in ("done", "orphaned"): - progress._ask_into(agent, sid, text, "main", "ci", time.time()) + if run and run.get("state") not in ("done", "orphaned"): # the same result told again is the same message + if any(m.get("request_id") == key for m in run.get("messages") or []): + return True + try: + progress._ask_into(agent, sid, text, "main", "ci", time.time(), request_id=key) + except messaging.MessageError as e: + if e.code != "idempotency_conflict": # another watch told it at the same moment, in other words + raise return True except Exception as error: _tell_failed(agent, sid, res, "its progress run", error) - ev = {"ts": res["ts"], "text": redact(text), "delivered": False, "repo": res.get("repo"), + ev = {"ts": res["ts"], "text": redact(text), "key": key, "delivered": False, "repo": res.get("repo"), "branch": res.get("branch"), "sha": res.get("sha"), "state": res.get("state"), "at": res.get("started") or res["ts"]} + def add(s): + if any(isinstance(e, dict) and e.get("key") == key for e in s.get("ci_events") or []): + return state.SKIP # the same result, told before (another watch's record of this session): once + s["ci_events"] = ((s.get("ci_events") or []) + [ev])[-10:] try: - return state.update(progress.SESSIONS / f"{agent}-{sid}.json", # the append on the fresh record - lambda s: s.update(ci_events=((s.get("ci_events") or []) + [ev])[-10:]), + return state.update(progress.SESSIONS / f"{agent}-{sid}.json", add, # the append on the fresh record create=False) is not None except Exception as error: _tell_failed(agent, sid, res, "its session record", error) return False +def _result_key(res: dict) -> str: + """What makes two watches' results the same result for a session: the commit, the state and how each run ended + (as claim keys them), never the text, which carries how long each watch waited.""" + runs = sorted(f"{r.get('id') or r.get('number')}:{r.get('conclusion')}" for r in res.get("runs") or []) + raw = f"{res.get('repo_id') or res.get('repo')}|{res.get('branch')}@{res.get('sha')}|{res.get('state')}|" + \ + ",".join(runs) + return "ci:" + hashlib.sha256(raw.encode()).hexdigest()[:32] + + def _tell_failed(agent: str, sid: str, res: dict, where: str, error: Exception): """A CI result that could not be written where a session reads it: kept in the audit trail (dev audit), with the error's kind and never the result's text.""" @@ -685,7 +743,9 @@ def _draft(prog: str, args: list) -> bool: def _sent(cmd, cwd: str) -> list: - """targets(), each with whether it came from a draft PR's creation: [(top, branch or tag, commit, draft)].""" + """targets(), each with whether it came from a draft PR's creation and whether from a PR made ready (whose run + starts on a commit the remote had already): [(top, branch or tag, commit, draft, ready)]. A commit both pushed + and made ready by one command line counts as made ready.""" out = [] for words in _commands(_script(cmd)): while words and (words[0] in _WRAPPERS or re.match(r"[A-Za-z_]\w*=", words[0])): @@ -696,10 +756,27 @@ def _sent(cmd, cwd: str) -> list: found = _git_push(args, cwd) if prog == "git" else _devkit_or_gh(prog, args, cwd) \ if prog in ("dev", "gh") else [] draft = prog in ("dev", "gh") and args[:2] == ["pr", "create"] and _draft(prog, args) - out += [(*t, draft) for t in found if t and all(t != o[:3] for o in out)] + ready = prog in ("dev", "gh") and args[:2] == ["pr", "ready"] + for t in found: + if not t: + continue + same = next((i for i, o in enumerate(out) if o[:3] == t), None) + if same is None: + out.append((*t, draft, ready)) + elif ready: + out[same] = (*out[same][:4], True) return out +def watch_targets(cmd, cwd: str, opened: float | None = None) -> list: + """targets(), each with the moment its runs count from: [(top, branch or tag, commit, since)]. A PR made ready + starts a new run on a commit that may have runs already (a draft's skipped run), so its runs count from the + moment the call opened (`opened`, the call ledger's time; else now), less READY_SKEW_S for the host's clock; + any other target counts every run of its commit (since None).""" + at = (opened or time.time()) - READY_SKEW_S + return [(top, ref, sha, at if ready else None) for top, ref, sha, _, ready in _sent(cmd, cwd)] + + def targets(cmd, cwd: str) -> list: """What a delivery command line sent to the remote, as (repository top, branch or tag, commit), each once: @@ -714,10 +791,12 @@ def targets(cmd, cwd: str) -> list: return [t[:3] for t in _sent(cmd, cwd)] -def start_background(top: str, session: str = "", branch: str = "", sha: str = "") -> bool: +def start_background(top: str, session: str = "", branch: str = "", sha: str = "", since: float | None = None) -> bool: """One detached watcher per repository, branch and commit (the hooks call this after a push or a PR). Each session that sent the commit gets a record of it (`dev ci watches`; what `dev ci watch --wait` follows by - default), naming the watcher, a new one or the one already running, and hears the watcher's result (deliver).""" + default), naming the watcher, a new one or the one already running, and hears the watcher's result (deliver). + `since`: a PR made ready, whose runs count from then on (watch); a watcher already running on the commit keeps + following it, and its record keeps the moment for the waits that join it.""" if os.environ.get("DEVKIT_NO_CI_WATCH"): return False branch = branch or core.gitout(top, "branch", "--show-current") @@ -729,7 +808,8 @@ def start_background(top: str, session: str = "", branch: str = "", sha: str = " lock = WATCH / f"{_key(repo, branch)}-{sha}.lock" agent, _, sid = session.partition(":") target = {"top": top, "ref": branch, "sha": sha, "repo_id": repo, - "kind": "tag" if _rev(top, f"refs/tags/{branch}") and not _rev(top, f"refs/heads/{branch}") else "branch"} + "kind": "tag" if _rev(top, f"refs/tags/{branch}") and not _rev(top, f"refs/heads/{branch}") else "branch", + **({"since": round(since, 3)} if since else {})} try: if lock.exists() and time.time() - lock.stat().st_mtime < 3 * 3600: pid = int((lock.read_text().split() or ["0"])[0]) @@ -740,7 +820,8 @@ def start_background(top: str, session: str = "", branch: str = "", sha: str = " pass log = open(STATE / "logs" / "ci-watch.log", "a") if (STATE / "logs").exists() else subprocess.DEVNULL p = subprocess.Popen([sys.executable, "-I", "-S", str(core.release_home() / "bin" / "dev"), "ci", "watch", - "--quiet", "--branch", branch, "--sha", sha] + (["--session", session] if session else []), + "--quiet", "--branch", branch, "--sha", sha] + (["--session", session] if session else []) + + (["--since", f"{since:.3f}"] if since else []), cwd=top, stdin=subprocess.DEVNULL, stdout=log, stderr=log, start_new_session=True, close_fds=True) lock.write_text(f"{p.pid} {int(time.time())}") @@ -781,17 +862,25 @@ def _update(rid: str, **fields): def register(target: dict, by: str, agent: str, sid: str, pid, timeout_min: float, now: float | None = None) -> str: """Record a watch of one commit's runs: devkit's background watch (by "devkit": it tells the session at its next hook) or an agent's `dev ci watch --wait` (by "agent": its output wakes the agent). A record already there for - the same watch stays. -> its id, "" when it cannot be written.""" + the same watch stays, and takes a later `since` (a PR made ready while the watch runs). -> its id, "" when it + cannot be written.""" now = round(now or time.time()) repo = target.get("repo_id") or repo_id(target["top"]) rid = re.sub(r"[^A-Za-z0-9_.-]+", "_", f"{by}-{agent}-{sid}-{repo}-{target['ref']}-{target['sha'][:7]}-{pid}")[:200] rec = {"id": rid, "by": by, "agent": agent, "session": sid, "top": target["top"], "repo": Path(target["top"]).name, "repo_id": repo, "ref": target["ref"], "sha": target["sha"], "kind": target.get("kind") or "branch", "pid": pid, "started": now, "expires": now + round(timeout_min * 60), "timeout_min": timeout_min, "state": "live", - "last_event": "", "last_ts": None} + "last_event": "", "last_ts": None, **({"since": target["since"]} if target.get("since") else {})} + def put(doc): + if not doc: + return rec + if rec.get("since") and (doc.get("since") or 0) < rec["since"]: # the same watch, now of a PR made ready + doc["since"] = rec["since"] + return None + return state.SKIP try: LIVE.mkdir(parents=True, exist_ok=True) - state.update(LIVE / f"{rid}.json", lambda doc: state.SKIP if doc else rec) + state.update(LIVE / f"{rid}.json", put) except Exception: return "" return rid @@ -807,6 +896,14 @@ def _on(rec: dict, repo, ref, sha) -> bool: return rec.get("ref") == ref and (rec.get("sha") or "")[:7] == (sha or "")[:7] and _repo_of(rec) == repo +def _since(repo, ref, sha) -> float | None: + """The moment the commit's runs count from for a wait that joins a PR made ready (start_background's `since`): + the latest one an open record of the commit keeps, else None (every run counts).""" + found = [r["since"] for r in _records() if r.get("state") in OPEN and isinstance(r.get("since"), (int, float)) + and _on(r, repo, ref, sha)] + return max(found) if found else None + + def _owed(repo, ref, sha) -> bool: """Does a session joined to devkit's background watch of the commit still wait to hear its result?""" return any(r.get("by") == "devkit" and r.get("state") in OPEN and _on(r, repo, ref, sha) for r in _records()) @@ -838,6 +935,8 @@ def _settle(res: dict) -> set: for rec in _records(): if rec.get("state") not in OPEN or not _on(rec, res.get("repo_id"), res.get("branch"), res.get("sha")): continue + if isinstance(rec.get("since"), (int, float)) and (res.get("started") or 0) < rec["since"]: + continue # a PR made ready after these runs started: their result is the draft's, not the ready's if rec.get("by") == "devkit": if not _take(rec["id"]): continue # another watch tells this session, and closes its record after @@ -848,13 +947,14 @@ def _settle(res: dict) -> set: return told -def _results() -> set: - """(repository, branch, commit) of each saved watch result that says how its runs ended. A result saved before +def _results(after: float | None = None) -> set: + """(repository, branch, commit) of each saved watch result that says how its runs ended (`after`: only a result + whose latest run started from then on, so a draft's result is never a PR made ready's). A result saved before results named their repository gives the host's owner/repo, which is the repository on GitHub.""" out = set() for f in WATCH.glob("*.json") if WATCH.exists() else []: r = state.read(f) or {} - if r.get("state") in FINAL: + if r.get("state") in FINAL and (after is None or (r.get("started") or 0) >= after): out.add((r.get("repo_id") or r.get("repo"), r.get("branch"), (r.get("sha") or "")[:7])) return out @@ -1073,7 +1173,9 @@ def emit(line): emit(f"CI none · nothing to watch: {why}") return 2 timeout = float(getattr(a, "timeout", None) or 90) - rid = register(target, "agent", agent, sid, os.getpid(), timeout, now=clock()) + since = _since(target.get("repo_id") or repo_id(target["top"]), target["ref"], target["sha"]) + rid = register(dict(target, **({"since": since} if since else {})), "agent", agent, sid, os.getpid(), timeout, + now=clock()) again = _wait_command(target, agent) def killed(signum, frame): @@ -1093,7 +1195,7 @@ def event(line): pass try: res = watch(target["top"], branch=target["ref"], sha=target["sha"], timeout_min=timeout, sleep=sleep, - clock=clock, runs_fn=runs_fn, on_event=event, always_diagnose=True) + clock=clock, runs_fn=runs_fn, on_event=event, always_diagnose=True, since=since) finally: for sig, handler in saved.items(): signal.signal(sig, handler) @@ -1319,7 +1421,8 @@ def _unfinished(sent: dict, runs_fn=None, now: float | None = None) -> tuple: cannot say within HOST_WAIT; (False, runs) once each run ended or a watch saw them end, or when origin is no CI host devkit reads.""" sha7 = sent["sha"][:7] - if (sent.get("repo_id") or repo_id(sent["top"]), sent["ref"], sha7) in _results(): + since = sent["at"] - READY_SKEW_S if sent.get("ready") else None # a PR made ready: its own run (watch) + if (sent.get("repo_id") or repo_id(sent["top"]), sent["ref"], sha7) in _results(after=since): return False, [] from . import cistatus try: @@ -1330,7 +1433,11 @@ def _unfinished(sent: dict, runs_fn=None, now: float | None = None) -> tuple: data = {"provider": "unknown", "error": str(e)[:200]} if not data.get("provider"): return False, [] - runs = [r for r in data.get("runs") or [] if (r.get("sha") or "")[:7] == sha7] + runs = [r for r in data.get("runs") or [] if (r.get("sha") or "")[:7] == sha7 + and not (since and _before(r, since) and conclusion(r)[0] == "skipped")] + if since and not any(not _before(r, since) and conclusion(r)[0] != "skipped" for r in runs) \ + and (now or time.time()) - sent["at"] < NO_RUN_MIN * 60: + return True, runs # the ready run has not appeared yet if runs: return any(r.get("status") not in DONE for r in runs), runs if data.get("error"): @@ -1377,17 +1484,19 @@ def stop_gate(agent: str, data: dict, runs_fn=None, now: float | None = None, de for c in calls[turn:]: if not SENDS.search(_script(c["command"])): continue - for top, ref, sha, draft in _sent(c["command"], c["cwd"] or data.get("cwd") or os.getcwd()): + for top, ref, sha, draft, ready in _sent(c["command"], c["cwd"] or data.get("cwd") or os.getcwd()): if all((top, ref, sha) != (s["top"], s["ref"], s["sha"]) for s in sent): - sent.append({"top": top, "ref": ref, "sha": sha, "draft": draft, "at": c["at"] or now, + sent.append({"top": top, "ref": ref, "sha": sha, "draft": draft, "ready": ready, "at": c["at"] or now, "kind": _kind(top, ref), "repo_id": repo_id(top)}) sid = data.get("session_id") or "" for w in watches(now): if w["status"] == "expired" and w.get("by") == "agent" and (w.get("agent"), w.get("session")) == (agent, sid) \ and now - (w.get("started") or 0) < 12 * 3600 and \ all(not _on(w, s["repo_id"], s["ref"], s["sha"]) for s in sent): - sent.append({"top": w["top"], "ref": w["ref"], "sha": w["sha"], "draft": False, - "at": w.get("started") or now, "kind": w.get("kind") or "branch", "repo_id": _repo_of(w)}) + ready = isinstance(w.get("since"), (int, float)) # a wait on a PR made ready: its run from then on + sent.append({"top": w["top"], "ref": w["ref"], "sha": w["sha"], "draft": False, "ready": ready, + "at": w["since"] + READY_SKEW_S if ready else w.get("started") or now, + "kind": w.get("kind") or "branch", "repo_id": _repo_of(w)}) if not sent: return None fits = WAKES.get(agent, WAKES["claude"]) diff --git a/lib/devkit/cli.py b/lib/devkit/cli.py index fc222c91..89884349 100644 --- a/lib/devkit/cli.py +++ b/lib/devkit/cli.py @@ -258,14 +258,21 @@ def _waiting(root: Path) -> bool: def _commit_handoff(root: Path, st: dict, quiet: bool) -> bool: """Stage and commit every change but a file over the size limit, which is left out (unstaged when someone staged - it) and recorded once: a critical, blocked `handoff.push` that names it. -> whether it committed.""" + it) and recorded once: a critical, blocked `handoff.push` that names it. A record a running devkit command has + written and not committed yet (work.writing) is left out too: its writer commits it with its own message and + audit record. -> whether it committed.""" from . import audit, identity, work _, held = _handoff_changes(root) - if held: - core.git(root, "add", "-A", "--", ".", *(f":(exclude,literal){p}" for p, _ in held)) - core.git(root, "reset", "-q", "--", *(p for p, _ in held)) + skip = [p for p, _ in held] + sorted(work.writing(root) - {p for p, _ in held}) + if skip: + core.git(root, "add", "-A", "--", ".", *(f":(exclude,literal){p}" for p in skip)) + if held: + core.git(root, "reset", "-q", "--", *(p for p, _ in held)) else: core.git(root, "add", "-A") + late = sorted(work.writing(root) - set(skip)) # written while this sync staged: its writer commits it + if late: + core.git(root, "reset", "-q", "--", *late) known = st.get("held") if isinstance(st.get("held"), dict) else {} for path, size in held: if path in known: @@ -2254,7 +2261,7 @@ def cmd_ci(a): def cmd_ci_watch(a, top): from . import ciwatch res = ciwatch.watch(top, branch=a.branch, sha=getattr(a, "sha", None), timeout_min=getattr(a, "timeout", 90) or 90, - quiet=getattr(a, "quiet", False) or a.json) + quiet=getattr(a, "quiet", False) or a.json, since=getattr(a, "since", None)) if getattr(a, "session", None) and ":" in a.session: ciwatch.deliver(*a.session.split(":", 1), res) if a.json: @@ -2705,8 +2712,10 @@ def cmd_plan(a): return 0 if act in ("revise", "approve", "supersede"): path = Path(os.path.expanduser(a.path)).resolve() + if not path.is_file() and re.fullmatch(r"P-[0-9a-z]+", a.path.strip()): # a plan's id, as dev plan ls shows + path = next((p_["path"] for p_ in plans.list_plans() if p_["id"] == a.path.strip()), path) if not path.is_file(): - ui.err(f"no plan at {a.path}: check the path; `dev plan ls` lists the plans") + ui.err(f"no plan at {a.path}: give its path or its id (P-…); `dev plan ls` lists the plans") return 2 status = {"approve": "approved", "supersede": "superseded"}.get(act) meta = plans.revise(path, a.why or ("approved" if act == "approve" else ""), status=status) @@ -2803,8 +2812,15 @@ def cmd_progress(a): if changed: print(ui.dim(" changed: " + " · ".join(f"{i}. {s['name']} {before.get(s['name']) or 'new'} → " f"{s.get('state')}" for i, s in changed))) + unread = [m["id"] for m in run.get("messages") or [] if kind == "done" and m.get("to") == "main" + and not m.get("receipts") and m.get("closed") == round(run.get("finished") or 0)] + if unread: + print(ui.dim(f" {len(unread)} unread message(s) to you closed with the run, so they stop coming back: " + f"{', '.join(unread[:12])}{' …' if len(unread) > 12 else ''}; dev crew read <id> still " + "shows one")) return 0 if act in ("assign", "begin", "add", "reopen", "skip", "confirm"): + marks = pg.step_marks(pg.load_run(*pg.current_session()) or {}) if not from_agent else {} try: if act == "assign": extra = {} @@ -2827,7 +2843,7 @@ def cmd_progress(a): except ValueError as e: ui.err(str(e)) return 2 - print(pg.render_update(run)) + print(pg.render_update(run) if getattr(a, "verbose", False) else pg.changed_lines(run, marks)) return 0 if act == "history": run = pg.normalize(pg.load_run(*pg.current_session()) or {}) @@ -4708,17 +4724,21 @@ def add(name, fn, help_, **kw): x.add_argument("--why", help="assign a member the crew's RACI does not make Responsible (recorded)") x.add_argument("--activity", help="the step's kind of work, an id from dev crew raci (backend, ux, …): it decides " "the RACI check and the approver, in any language") + x.add_argument("-v", "--verbose", action="store_true", help="print the whole plan, not only the changed steps") x = gsp.add_parser("begin", help="mark a plan step as started (parallel work you do yourself)") x.add_argument("which", help="step number or part of its name") + x.add_argument("-v", "--verbose", action="store_true", help="print the whole plan, not only the changed steps") x = gsp.add_parser("add", help="add a step found during the work: \"name=30m after other\"") x.add_argument("spec", nargs="+") x.add_argument("--why", help="why it was not in the plan") + x.add_argument("-v", "--verbose", action="store_true", help="print the whole plan, not only the changed steps") for verb, h_ in (("reopen", "undo a wrong close: the step goes back to running"), ("skip", "skip a step on purpose"), ("confirm", "a step flagged recheck still holds after the step it used was redone")): x = gsp.add_parser(verb, help=h_) x.add_argument("which", help="step number or part of its name") x.add_argument("--why", required=True, help="the reason (kept in the run's history)") + x.add_argument("-v", "--verbose", action="store_true", help="print the whole plan, not only the changed steps") gsp.add_parser("history", help="every step change: when, from → to, by whom, why") x = gsp.add_parser("time", help="how long things take: turns, slow commands, subagents, estimate accuracy") x.add_argument("--days", type=int, default=7) @@ -4969,6 +4989,7 @@ def add(name, fn, help_, **kw): p.add_argument("--pr", help="watch --wait: the runs of this PR's head, or of its merge commit once merged") p.add_argument("--timeout", type=float, default=90, help="watch: minutes before giving up (default 90)") p.add_argument("--session", help=argparse.SUPPRESS) + p.add_argument("--since", type=float, help=argparse.SUPPRESS) # a PR made ready: its runs count from then p.add_argument("--quiet", action="store_true", help="watch: no progress lines, only the result") p.add_argument("--commands", action="store_true", help="print only the run commands") p.add_argument("--runs", action="store_true", help="also list recent CI runs") diff --git a/lib/devkit/continuity.py b/lib/devkit/continuity.py index 87d367be..d2b8c47c 100644 --- a/lib/devkit/continuity.py +++ b/lib/devkit/continuity.py @@ -524,7 +524,7 @@ def _unacknowledged(run: dict) -> int: delivered to the tech lead closes the question they asked: neither counts, also in records from before progress._answered wrote the answerer's receipt.""" return len([m for m in (run or {}).get("messages") or [] if m.get("to") == "main" and not m.get("receipts") - and m.get("from") not in progress.NOTICE_SENDERS and m.get("kind") != "notice" + and not m.get("closed") and m.get("from") not in progress.NOTICE_SENDERS and m.get("kind") != "notice" and not m.get("answered") and not (m.get("kind") == "answer" and m.get("delivered"))]) diff --git a/lib/devkit/crew.py b/lib/devkit/crew.py index 18499866..7d9ff403 100644 --- a/lib/devkit/crew.py +++ b/lib/devkit/crew.py @@ -724,7 +724,8 @@ def open_messages(run: dict) -> list: from . import progress msgs = (run or {}).get("messages") or [] waiting = {m.get("id") for to in {m.get("to") for m in msgs} for m in progress.waiting_messages(run, to)} - return [m for m in msgs if (not m.get("receipts") and not m.get("delivered")) or m.get("id") in waiting] + return [m for m in msgs if (not m.get("receipts") and not m.get("delivered") and not m.get("closed")) + or m.get("id") in waiting] def run_view(run: dict, roster=None, now=None): diff --git a/lib/devkit/gc.py b/lib/devkit/gc.py index 434fdedf..35388d6e 100644 --- a/lib/devkit/gc.py +++ b/lib/devkit/gc.py @@ -233,6 +233,7 @@ def plan(reg: dict, with_sizes=True) -> dict: MESSAGE_DAYS = 30 # days the message store of a run that ended (or is gone), and an archived run's, is kept ATTEMPT_DAYS = 7 # days a desktop notification attempt is kept: its retry and dedupe window is seconds +LEFTOVER_DAYS = 1 / 24 # an hour: a record write takes milliseconds, so a temporary file this old has no writer # days a settled automatic bug report is kept after its last occurrence: an acknowledged one long enough that a repeat # updates its issue instead of opening another; an expired one a month past its retirement (bugs.REPORT_RETIRE_DAYS) BUG_REPORT_DAYS = {"acknowledged": 90, "expired": 30 + 30} @@ -270,9 +271,26 @@ def state_records(now: float | None = None) -> list: actions = [{"kind": "purge-record", "path": str(p), "kb": 0, "auto": True, "reason": f"{what}, untouched for more than {days} days"} for p, days, what in found if _old_record(p, days, now)] + actions += [{"kind": "purge-record", "path": str(p), "kb": 0, "auto": True, + "reason": "the temporary file of a handoff record write that was interrupted, untouched for more " + "than an hour"} + for p in _write_leftovers() if _old_record(p, LEFTOVER_DAYS, now)] return actions + _settled_bug_reports(now) +def _write_leftovers() -> list: + """The temporary files (`.<name>.<random>.tmp`, core.replace_text) that an interrupted write left in the handoff + repository, outside its .git folder.""" + root = core.HANDOFF + if not root.is_dir(): + return [] + out = [] + for folder, dirs, files in os.walk(root): + dirs[:] = [d for d in dirs if d != ".git"] # git's own objects are git's to clean + out += [Path(folder) / f for f in files if f.startswith(".") and f.endswith(".tmp")] + return sorted(out) + + def _settled_bug_reports(now: float) -> list: """Automatic bug reports that are settled (acknowledged or expired) and quiet past BUG_REPORT_DAYS since their last occurrence -> purge-record actions. A report still to send, or one quarantined as evidence, stays.""" diff --git a/lib/devkit/hooks.py b/lib/devkit/hooks.py index 89c02233..8fece662 100644 --- a/lib/devkit/hooks.py +++ b/lib/devkit/hooks.py @@ -3581,6 +3581,10 @@ def post_tool(agent: str): return _check_writes(agent, data) _note_plan_writes(agent, data) + try: # when the call opened, before its ledger entry closes: a PR made ready counts its runs from then + opened = progress.call_entry(data).get("ts") + except Exception: + opened = None _close_call(data) _reconcile(agent, data) _prompt_refresh(data) @@ -3614,10 +3618,10 @@ def post_tool(agent: str): # commit on the base branch, a release tag. A local branch or an unpushed commit starts no pipeline tin = data.get("tool_input") or {} raw = tin.get("command") or tin.get("cmd") or "" # a list stays a list: its shell's script - for top, ref, sha in ciwatch.targets(raw, _shell_cwd(data)): + for top, ref, sha, since in ciwatch.watch_targets(raw, _shell_cwd(data), opened): if not core.is_temp(top): ciwatch.start_background(top, session=f"{agent}:{data.get('session_id') or ''}", branch=ref, - sha=sha) + sha=sha, since=since) except Exception as e: _swallowed("post-tool", e) closing = background = "" diff --git a/lib/devkit/progress.py b/lib/devkit/progress.py index f857cf8e..c7756240 100644 --- a/lib/devkit/progress.py +++ b/lib/devkit/progress.py @@ -780,6 +780,36 @@ def _names_args(entry: dict, args: list) -> bool: at = i + len(a) else: return True + return not entry.get("cut") and _runs_with_expansions(texts[0], args) + + +_EXPANSION = re.compile(r"\$\{[^}]*\}|\$\([^)]*\)?|\$[A-Za-z_]\w*|\$[0-9@*#?$!-]|`[^`]*`?|\$") +# The commands whose arguments may come from a shell expansion: they read or acknowledge the caller's own messages +# and decide nothing. A command that decides, answers or assigns needs its words as typed, so that no other process +# running while the tech lead's loop is open can pass as the tech lead with words of its own. +EXPANDED_COMMANDS = (("crew", "read"), ("crew", "ack"), ("session", "read"), ("session", "ack")) + + +def _runs_with_expansions(text: str, args: list) -> bool: + """Does the call's text run `dev` with these arguments where it typed a shell expansion in their place (a loop's + `"$ref"`, `${id}`, `$(…)`)? Only for EXPANDED_COMMANDS, typed as they are. Each other word must be the argument + as typed, or a pattern whose expansions stand for any text.""" + if tuple(args[:2]) not in EXPANDED_COMMANDS or not any(c in text for c in "$`"): + return False + from . import shellparse + try: + calls = shellparse.shell_calls(text, None) or [] + except Exception: + return False + for argv, _ in calls: + words = shellparse.dev_args(argv) + if not words or len(words) != len(args) or words[:2] != args[:2]: + continue + if all(w == a or (_EXPANSION.search(w) and re.fullmatch( + "".join(".*" if _EXPANSION.fullmatch(p) else re.escape(p) + for p in re.split(f"({_EXPANSION.pattern})", w) if p), a, re.S)) + for w, a in zip(words, args)): + return True return False @@ -1279,6 +1309,8 @@ def _allocate(run): s["est"], s["est_auto"] = round(max(1.0, share), 1), True if not total and plan: run["estimate"] = round(sum(s["est"] for s in plan), 1) + ratio = run.get("cal_ratio") + run["estimate_cal"] = round(run["estimate"] * ratio, 1) if ratio else run["estimate"] def _open(run, kind, ident, now): @@ -1629,6 +1661,14 @@ def _find_step(run, which): next((s for s in plan if lw in s["name"].lower()), None) +def _named_by(plan: list, text: str): + """The open step a description names by starting with its exact name and a colon ("api: the export endpoint"), + else None.""" + m = re.match(r"\s*([^:\n]{1,120}):\s", text or "") + name = m.group(1).strip().lower() if m else "" + return next((s for s in plan if name and s["name"].lower() == name and s.get("state") not in DONE), None) + + def _rechecked(run, s) -> bool: """A step flagged recheck that finishes now, after every reopened step it used is closed again, did its work on their new version: its flag clears. -> whether it cleared""" @@ -2820,8 +2860,11 @@ def _ask_into(agent: str, sid: str, text: str, to, frm: str, now: float, kind: s if not run: raise ValueError("no progress run in this session: the tech lead starts one with dev progress start") run = normalize(run) + before = len(run.get("messages") or []) m = _post(run, frm, _addr(run, to or "", now, pending_launch=pending_launch), text, now, kind=kind if kind in ("notice", "answer") else "", request_id=request_id) + if len(run.get("messages") or []) == before: # its request key sent it before: that message, once + return m if m["to"].startswith("name:"): m["pending_launch"] = str(to) told = _waits_notice(run, m, frm, now) if m["to"].startswith("name:") and frm not in NOTICE_SENDERS else "" @@ -2963,14 +3006,25 @@ def waiting_messages(run, to: str = "main") -> list: return [m for m in _open_questions(run) if m.get("to") == to] +UNREAD_CLOSED = "its run ended before it was read" + + def _close_messages(run, reason: str, now: float) -> list: """A run ends or is replaced: each question in it that still waits for an answer, to the tech lead or to a - member, closes with the reason, and takes no answer any more. -> copies of the closed messages, for the audit - after the save.""" + member, closes with the reason, and takes no answer any more. Every other message nobody has acknowledged (a + report, a notice, a CI result) closes too, with UNREAD_CLOSED: its run's work is over, so it is no longer + delivered again every minute (_due), and `dev crew read` still shows it. -> copies of the closed messages, for + the audit after the save.""" + from . import messaging closed = [] for m in _open_questions(run): m.update(closed=round(now), reason=reason[:300]) closed.append(dict(m)) + for m in run.get("messages") or []: + if isinstance(m, dict) and not m.get("closed") and not m.get("receipts") and not m.get("answered") \ + and not messaging.delivered_before_upgrade(m): # one of those never comes back anyway + m.update(closed=round(now), reason=UNREAD_CLOSED) + closed.append(dict(m)) return closed @@ -3235,7 +3289,7 @@ def crew_inbox(from_agent: str | None = None, cwd: str | None = None, mark: bool run = normalize(run) lane = (run.get("agents") or {}).get(me) or {} return [dict(m, new=not bool(m.get("receipts"))) for m in run.get("messages") or [] - if _addressed_to(m, me, lane) and (all_ or not (m.get("receipts") or {}).get(me))] + if _addressed_to(m, me, lane) and (all_ or not ((m.get("receipts") or {}).get(me) or m.get("closed")))] def _addressed_to(m: dict, me: str, lane: dict) -> bool: @@ -3337,7 +3391,7 @@ def _due(m: dict, me: str, lane: dict) -> bool: earlier devkit, and never delivered or delivered over a minute ago without being read.""" from . import messaging return (not (m.get("receipts") or {}).get(me) and not messaging.delivered_before_upgrade(m) - and (not m.get("delivered") or time.time() - m.get("notification_at", 0) >= 60) + and not m.get("closed") and (not m.get("delivered") or time.time() - m.get("notification_at", 0) >= 60) and _addressed_to(m, me, lane)) @@ -4725,6 +4779,7 @@ def step(text: str, nxt: str = "", cwd: str | None = None, kind: str = "step", c raise StepError(f"no step “{which}” in the plan: " + "; ".join(f"{i}. {s['name']}" for i, s in enumerate(plan, 1))) if kind == "step": + target = target or _named_by(plan, text) # "ci-watch: …" names the open step ci-watch explicit = target is not None if not target: running = [s for s in plan if s.get("state") == "running" and (s.get("owner") or "main") == "main"] @@ -4896,28 +4951,7 @@ def render_update(run: dict, branch: str | None = None, now: float | None = None f"with the run, or: dev crew withdraw {d['id']} --why \"…\"" for d in moot] if plan: lines.append("") - for i, s in enumerate(plan, 1): - mark = {"done": "✓", "running": "▸", "blocked": "■", "skipped": "–"}.get(s.get("state"), "○") - main = (s.get("owner") or "main") == "main" - waits = deps_open(run, s) if s.get("state") in ("pending", "blocked") else [] - parts = [] if main else [_who_label(agents.get(s["owner"], {}).get("label") or "subagent")] - if waits: - parts.append("waiting for " + ", ".join(waits) + (f", then {_who_label(s['label'])}" - if main and s.get("label") else "")) - elif main and s.get("label"): - parts.append(f"waiting for {_who_label(s['label'])}") - if s.get("recheck"): - parts.append(f"recheck: {', '.join(s['recheck'])} reopened") - changed = other_writes_for(run, s) if s.get("state") not in DONE else [] - if changed: - parts.append("changed by another lane: " + ", ".join(f"{p} ({by}, {c})" for p, by, c in changed[:5]) - + (f" and {len(changed) - 5} more" if len(changed) > 5 else "")) - who = "".join(f" · {p}" for p in parts) - if s.get("state") in ("done", "running"): - tm = f" · {fmt_min(step_minutes(run, s, now))} of ~{fmt_about(s.get('est') or 0)}" - else: - tm = f" · ~{fmt_about(s.get('est') or 0)}" - lines.append(f"{mark} {i}. {s['name']}{who}{tm}") + lines += plan_lines(run, now) if agents: parts = [] for aid, a in agents.items(): @@ -4928,6 +4962,55 @@ def render_update(run: dict, branch: str | None = None, now: float | None = None return "\n".join(lines) +def step_marks(run: dict) -> dict: + """{step name: what its line shows that a change can move (state, owner, label, estimate, dependencies)}: taken + before and after a change, the steps whose marks differ are the ones the change touched (changed_lines).""" + return {s["name"]: (s.get("state"), s.get("owner"), s.get("label"), s.get("est"), tuple(s.get("after") or ())) + for s in normalize(run).get("plan") or []} + + +def changed_lines(run: dict, before: dict, now: float | None = None) -> str: + """What `dev progress assign`, `add`, `begin`, `reopen`, `skip` and `confirm` print: the line of each step the + change touched (step_marks before it), then the run's headline. `--verbose` prints the whole update instead.""" + now = now or time.time() + after = step_marks(run) + names = {name for name, mark in after.items() if before.get(name) != mark} + names |= {s["name"] for s in normalize(run).get("plan") or [] if s.get("state") == "running"} if not names else set() + lines = plan_lines(run, now, only=names) + return "\n".join(lines + [f" {headline(run, now)} · the whole plan: add --verbose"]) + + +def plan_lines(run: dict, now: float, only=None) -> list: + """One line per plan step, with its state, owner, what it waits for and its time; `only`: those step names.""" + run = normalize(run) + plan, agents, lines = run.get("plan") or [], run.get("agents") or {}, [] + for i, s in enumerate(plan, 1): + if only is not None and s["name"] not in only: + continue + mark = {"done": "✓", "running": "▸", "blocked": "■", "skipped": "–"}.get(s.get("state"), "○") + main = (s.get("owner") or "main") == "main" + waits = deps_open(run, s) if s.get("state") in ("pending", "blocked") else [] + parts = [] if main else [_who_label(agents.get(s["owner"], {}).get("label") or "subagent")] + if waits: + parts.append("waiting for " + ", ".join(waits) + (f", then {_who_label(s['label'])}" + if main and s.get("label") else "")) + elif main and s.get("label"): + parts.append(f"waiting for {_who_label(s['label'])}") + if s.get("recheck"): + parts.append(f"recheck: {', '.join(s['recheck'])} reopened") + changed = other_writes_for(run, s) if s.get("state") not in DONE else [] + if changed: + parts.append("changed by another lane: " + ", ".join(f"{p} ({by}, {c})" for p, by, c in changed[:5]) + + (f" and {len(changed) - 5} more" if len(changed) > 5 else "")) + who = "".join(f" · {p}" for p in parts) + if s.get("state") in ("done", "running"): + tm = f" · {fmt_min(step_minutes(run, s, now))} of ~{fmt_about(s.get('est') or 0)}" + else: + tm = f" · ~{fmt_about(s.get('est') or 0)}" + lines.append(f"{mark} {i}. {s['name']}{who}{tm}") + return lines + + def _publish(): """Push the new state to the team (presence + session line), debounced, in the background.""" try: diff --git a/lib/devkit/registry.py b/lib/devkit/registry.py index 9af6b94d..87ca1d24 100644 --- a/lib/devkit/registry.py +++ b/lib/devkit/registry.py @@ -1462,15 +1462,20 @@ def write_generated(path: Path, text: str) -> bool: # nothing for a copy git still tracks, as devkit 26.11.19 and older committed it, so a Mac still on one of those keeps # committing its own and this Mac never commits a change to it. LOCAL_ONLY = ("registry.json",) +# The temporary file of a record write (core.replace_text), which an interrupted write leaves behind, is ignored in +# this Mac's own .git/info/exclude (never committed), so a handoff made before its template ignored such files does +# not commit them, and no Mac on another devkit rewrites a shared rule back and forth. +LOCAL_EXCLUDE = ".*.tmp" IGNORE_START = "# devkit:local:start · each Mac's own files, kept in devkit's state folder; devkit keeps this block" IGNORE_END = "# devkit:local:end" def ensure_handoff_ignore(root: Path) -> bool: - """Keep the managed block (LOCAL_ONLY) in root/.gitignore. -> changed. The repository's own rules stay as they - are; the block is added at the end, or put back as devkit writes it. A file of the block that git tracks stays - tracked: untracking it would commit its removal, and a Mac on an older devkit would commit it back on every - sync.""" + """Keep the managed block (LOCAL_ONLY) in root/.gitignore, and LOCAL_EXCLUDE in this Mac's .git/info/exclude. + -> whether .gitignore changed. The repository's own rules stay as they are; the block is added at the end, or + put back as devkit writes it. A file of the block that git tracks stays tracked: untracking it would commit its + removal, and a Mac on an older devkit would commit it back on every sync.""" + _exclude_locally(root) f = root / ".gitignore" try: text = f.read_text() @@ -1485,6 +1490,17 @@ def ensure_handoff_ignore(root: Path) -> bool: return write_if_changed(f, new) +def _exclude_locally(root: Path) -> None: + f = root / ".git" / "info" / "exclude" + try: + text = f.read_text() if f.exists() else "" + if LOCAL_EXCLUDE not in text.splitlines() and (root / ".git").is_dir(): + f.parent.mkdir(parents=True, exist_ok=True) + f.write_text(text + ("\n" if text and not text.endswith("\n") else "") + LOCAL_EXCLUDE + "\n") + except OSError: + pass # without it, a leftover is only a change dev gc removes within the day + + def write_outputs(reg: dict) -> list: """Write the notes, the initiatives' task blocks and the generated maps of the handoff repository. -> the files that changed. Holds the notes lock (a caller may hold it already); [] while another process keeps it.""" diff --git a/lib/devkit/setup.py b/lib/devkit/setup.py index 8141ff51..0a723f12 100644 --- a/lib/devkit/setup.py +++ b/lib/devkit/setup.py @@ -3150,7 +3150,12 @@ def _canon_ok(m): try: # a job's state that cannot be read is a failed row, never a crash of the whole doctor from . import jobs as _jobs for jname, jj in _jobs.jobs().items(): - if not jj.get("enabled"): + if not jj.get("enabled"): # what it does stops: say what, and how to turn it on + chosen = ((core.CFG.get("jobs") or {}).get(jname) or {}).get("enabled") is False or \ + (jname == "gc" and (core.CFG.get("gc") or {}).get("auto", True) is False) + check("Automation", f"job {jname}", True if chosen else DOCTOR_WARN, + f"off{' in your configuration' if chosen else ''} · {jj.get('about') or 'a job of your own'}: " + "this does not run", f"dev jobs enable {jname}") continue lr = _jobs.last_run(jname) or {} ran = doctor_job_ran(jj, lr.get("rc")) diff --git a/lib/devkit/work.py b/lib/devkit/work.py index 96d76e91..b5d7e543 100644 --- a/lib/devkit/work.py +++ b/lib/devkit/work.py @@ -181,7 +181,10 @@ def __init__(self, path, lost): def split_frontmatter(text: str): - """-> (frontmatter text, the rest). Frontmatter runs from a first line `---` to the next `---` line.""" + """-> (frontmatter text, the rest). Frontmatter runs from a first line `---` to the next `---` line. A byte order + mark and Windows line ends, which an editor may add to a record, are read past.""" + text = text[1:] if text.startswith("\ufeff") else text + text = text.replace("\r\n", "\n") if "\r\n" in text else text if text.startswith("---\n"): end = text.find("\n---\n", 3) if end != -1: @@ -243,7 +246,7 @@ def split_changelog(body: str): return body, [] entries = [] for ln in lines[head + 1:]: - if entries and ln.startswith(" ") and ln.strip(): + if entries and ln.startswith(" "): # a blank line of a reason is kept: render writes it as two spaces entries[-1] += "\n" + ln[2:].rstrip() elif ln.startswith("- "): entries.append(ln[2:].strip()) @@ -328,9 +331,68 @@ def write_record(path: Path, text: str, edited=()) -> None: lost = lost_lines(before, text, edited) if lost: raise RecordLossError(path, lost) + _mark_writing(path) _replace(path, text) +# A record its writer has written and not committed yet: the writer commits it on its own (_commit), with its own +# message and audit record, so a sync's commit of everything that changed (cli._commit_handoff) leaves it out. One +# marker per file and writing process (two writers of one file each keep theirs), written whole (core.replace_text), +# in this Mac's state folder; a marker counts while its process runs, for WRITING_S at most. +WRITING_S = 120 + + +def _writing_dir() -> Path: + return core.STATE / "handoff-writing" + + +def _writing_marker(path) -> Path: + return _writing_dir() / f"{hashlib.sha256(str(Path(path).resolve()).encode()).hexdigest()[:32]}-{os.getpid()}" + + +def _mark_writing(path) -> None: + try: + _writing_dir().mkdir(parents=True, exist_ok=True) + core.replace_text(_writing_marker(path), json.dumps({"pid": os.getpid(), "ts": time.time(), + "path": str(Path(path).resolve())})) + except OSError: + pass # without its marker, a sync may commit the record first: its writer's commit then has nothing to add + + +def _unmark_writing(paths) -> None: + for p in paths: + try: + _writing_marker(p).unlink(missing_ok=True) + except OSError: + pass + + +def writing(root: Path) -> set: + """The files under `root`, relative to it, that a running devkit process has written and not committed yet. A + marker whose process ended, or older than WRITING_S, is removed: its file is an ordinary change again.""" + out, now, top = set(), time.time(), Path(root).resolve() + try: + markers = [f for f in _writing_dir().iterdir() if not f.name.startswith(".")] # never a marker half written + except OSError: + return out + for f in markers: + try: + doc = json.loads(f.read_text()) + pid, ts, path = int(doc["pid"]), float(doc["ts"]), Path(doc["path"]) + os.kill(pid, 0) + live = now - ts < WRITING_S + except PermissionError: + live = now - ts < WRITING_S + except (OSError, ValueError, KeyError, TypeError): + live = False + if not live: + f.unlink(missing_ok=True) + continue + if path.is_relative_to(top): + out.add(str(path.relative_to(top))) + return out + + def parse(text: str) -> dict: front, body = split_frontmatter(text) meta, extra = read_frontmatter(front) @@ -1209,17 +1271,21 @@ def push_handoff(timeout: int = 60) -> tuple: def _commit(paths, message: str, push: bool = True, wait: bool = False): """One commit per change (the audit trail); push in the background unless `wait` (push now).""" if not (HANDOFF / ".git").exists(): + _unmark_writing(paths) return True rel = [str(Path(p).relative_to(HANDOFF)) for p in paths] with _repo_lock() as got: - if got: - recover_rebase("a commit", keep=paths) - core.git(HANDOFF, "add", "--", *rel) - rc, _, _ = core.git(HANDOFF, "diff", "--cached", "--quiet") - if rc != 0: - core.git(HANDOFF, *NO_AUTO_GC, "commit", "-q", "-m", message, "--", *rel) - from . import audit - audit.record("handoff." + (rel[0].split("/")[0] if rel else "write"), ", ".join(rel)[:300], message) + try: + if got: + recover_rebase("a commit", keep=paths) + core.git(HANDOFF, "add", "--", *rel) + rc, _, _ = core.git(HANDOFF, "diff", "--cached", "--quiet") + if rc != 0: + core.git(HANDOFF, *NO_AUTO_GC, "commit", "-q", "-m", message, "--", *rel) + from . import audit + audit.record("handoff." + (rel[0].split("/")[0] if rel else "write"), ", ".join(rel)[:300], message) + finally: + _unmark_writing(paths) if not push or not _pushes(): return True if os.environ.get("DEVKIT_NO_AUTOSYNC") and not wait: # bulk operations push once at the end diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json index a83ec4a6..0ca4d28d 100644 --- a/plugin/.claude-plugin/plugin.json +++ b/plugin/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "devkit", - "version": "26.11.20", + "version": "26.11.21", "description": "Every repo in its place, every agent on the same page: project context and handoff notes, tasks, a portfolio overview, local-first delivery (one push, one CI run), backend methodology, and managed worktrees.", "icon": "./assets/icon.png", "author": { diff --git a/plugin/.codex-plugin/plugin.json b/plugin/.codex-plugin/plugin.json index 33f31bb8..3e2407bd 100644 --- a/plugin/.codex-plugin/plugin.json +++ b/plugin/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "devkit", - "version": "26.11.20", + "version": "26.11.21", "description": "Every repo in its place, every agent on the same page: project context and handoff notes, tasks, a portfolio overview, local-first delivery (one push, one CI run), backend methodology, and managed worktrees.", "author": { "name": "Firefly Software Solutions Inc.", diff --git a/plugin/agents/merovingian.md b/plugin/agents/merovingian.md index 8c0f767a..0268cd49 100644 --- a/plugin/agents/merovingian.md +++ b/plugin/agents/merovingian.md @@ -29,7 +29,7 @@ Not yours: running the platform and its alerts (Niobe); fixing the cause found ( Load each one with the Skill tool (it may list a plugin skill with its prefix, such as `devkit:testing`). Without the Skill tool, or when it does not list one, read the skill's SKILL.md. -`otel-instrumentation`, `superpowers:systematic-debugging`, `otel-semantic-conventions`, `communicating` +`root-cause`, `otel-instrumentation`, `superpowers:systematic-debugging`, `otel-semantic-conventions`, `communicating` ## Your procedure diff --git a/plugin/agents/sati.md b/plugin/agents/sati.md index 16fc7e1b..14b1b72a 100644 --- a/plugin/agents/sati.md +++ b/plugin/agents/sati.md @@ -28,7 +28,7 @@ Not yours: implementing the screens (Trinity). Say so in your report and leave i Load each one with the Skill tool (it may list a plugin skill with its prefix, such as `devkit:testing`). Without the Skill tool, or when it does not list one, read the skill's SKILL.md. -`frontend-design`, `impeccable`, `communicating` +`frontend-design`, `impeccable`, `modern-web-guidance`, `communicating` ## Your procedure diff --git a/plugin/agents/trinity.md b/plugin/agents/trinity.md index 8c5c9444..2b155454 100644 --- a/plugin/agents/trinity.md +++ b/plugin/agents/trinity.md @@ -27,7 +27,7 @@ Not yours: the visual direction from scratch (Sati); back-end APIs (Tank). Say s Load each one with the Skill tool (it may list a plugin skill with its prefix, such as `devkit:testing`). Without the Skill tool, or when it does not list one, read the skill's SKILL.md. -`root-cause`, `frontend-design`, `superpowers:test-driven-development`, `impeccable`, `superpowers:verification-before-completion`, `testing`, `communicating` +`root-cause`, `frontend-design`, `superpowers:test-driven-development`, `impeccable`, `modern-web-guidance`, `superpowers:verification-before-completion`, `testing`, `communicating` ## Your procedure @@ -35,7 +35,7 @@ Follow these phases in order. A phase is finished when its gate holds; `proof` m 1. **Design in hand.** Start from the design of the UX designer (Sati) with every state and its copy; ask for one when it is missing. Load `frontend-design` and `impeccable`, then run impeccable's setup once, from the project's root: `dev impeccable context`. Run the other impeccable commands the skill names the same way, `dev impeccable <verb>`, which runs the engine devkit installed and checked, never by the launcher's path. Follow what it prints, but write PRODUCT.md or DESIGN.md only when the developer asks. skills: `root-cause`, `frontend-design`, `impeccable` · devkit: `dev crew ask` · gate: every state of the screen is designed 2. **Contract.** Agree the data contract with the Backend engineer (Tank) before building on it. devkit: `dev crew ask` · gate: the API fields the screen uses exist -3. **Build.** Build with the framework's current patterns and the project's components; keep state minimal; behavior tests first. skills: `superpowers:test-driven-development`, `impeccable` · devkit: `dev test` · gate: component tests cover the behavior · proof: `dev test` +3. **Build.** Build with the framework's current patterns and the project's components; keep state minimal; behavior tests first. Before writing a web platform feature (a dialog, a form, a layout, an animation, dates, sanitizing HTML, Core Web Vitals), search `modern-web-guidance` for it and follow the guide it retrieves. skills: `superpowers:test-driven-development`, `impeccable`, `modern-web-guidance` · devkit: `dev test` · gate: component tests cover the behavior · proof: `dev test` 4. **Browser check.** Check in a real browser at 1440 px and 390 px, dark and light, with the keyboard and with no console errors; screenshot each state (with Chrome DevTools or `playwright-cli`). skills: `impeccable` · gate: the screens pass at both widths in both themes 5. **Verify.** Run the affected tests, then check the new tests fail without the change and that nothing is left unfinished. skills: `superpowers:verification-before-completion`, `testing` · devkit: `dev test`, `dev test prove`, `dev stubs` · gate: the blast radius passes, every new test fails without the change, no stubs · proof: `dev test prove` 6. **Hand off.** Record the step with its evidence, name who approves it (the RACI), and report with your status block. devkit: `dev progress step`, `dev crew ask` · gate: the step is recorded with its evidence · proof: `dev progress step` diff --git a/plugin/skills/cicd/SKILL.md b/plugin/skills/cicd/SKILL.md index 5291e21d..5c525b9c 100644 --- a/plugin/skills/cicd/SKILL.md +++ b/plugin/skills/cicd/SKILL.md @@ -125,10 +125,12 @@ sent work to origin and leaves its unfinished run with nothing watching it that watch delivers, so arm `dev ci watch --wait` only to follow one run job by job (`wait-and-wake` skill). A failure comes with the failed jobs and steps, **the first error of the log** (not the tail: later errors -follow from it), a class and one next action: +follow from it; the first line that reads as an error and says what failed), a class and one next action. A PR made +ready is watched to its own run, not the draft's skipped one: | Class | What it means | The one next action | | --- | --- | --- | +| access | a secret or variable not set, bad credentials, a token without a permission | set it (`gh secret set <NAME>`) or grant it in the workflow's `permissions:` block, least privilege; no code change fixes it, so rerun once it is set | | test | a test or assertion failed | reproduce it locally (`dev test run --failed`), fix the real cause, `dev ci --run --resume`, push once | | lint | lint, format, or types | run the same check locally, fix, push once | | build | compile or package | reproduce with CI's build command, fix, push once | diff --git a/plugin/skills/wait-and-wake/SKILL.md b/plugin/skills/wait-and-wake/SKILL.md index 6a9af01a..884eaa34 100644 --- a/plugin/skills/wait-and-wake/SKILL.md +++ b/plugin/skills/wait-and-wake/SKILL.md @@ -120,8 +120,9 @@ compound commands still count as failures. The original exit code remains availa A wait or hook carries bounded previews and exact recovery references. A devkit or CI notice, and a message shown whole (up to 180 characters), is read on delivery. Read a longer one with `dev crew read REF --json`, follow `next_cursor` until `complete`, then acknowledge its exact digest and generation with -`dev crew ack REF --sha256 DIGEST --generation N`; until then it comes back about once a minute. Do not act on a -truncated preview. Inbox and +`dev crew ack REF --sha256 DIGEST --generation N`; until then it comes back about once a minute, or until its run +ends (`dev progress done` closes it unread and names it). A loop may pass the reference in a shell variable +(`for r in …; do dev crew read "$r" --json; done`). Do not act on a truncated preview. Inbox and read are side-effect-free; use `--all` for history and `--cursor` for later pages. Main-session peer messages use the corresponding `dev session read`, `ack`, and `replay` commands. A member uses crew messages instead. Desktop notification failure never consumes a message; no alert click acknowledges, answers, or approves. diff --git a/shell/completions/_dev b/shell/completions/_dev index 92044693..4e38a0e1 100644 --- a/shell/completions/_dev +++ b/shell/completions/_dev @@ -852,12 +852,14 @@ _dev__progress__assign() { '--scope=[the files it owns, comma-separated globs]:scope: ' \ '--why=[assign a member the crew'\''s RACI does not make Responsible]:why: ' \ '--activity=[the step'\''s kind of work, an id from dev crew raci]:kind of work: _dev_live activities -' \ + '(--verbose -v)'{-v,--verbose}'[print the whole plan, not only the changed steps]' \ ':plan step: _dev_live steps -' } _dev__progress__begin() { _arguments -s -S : \ '(- *)'{-h,--help}'[show this help message and exit]' \ + '(--verbose -v)'{-v,--verbose}'[print the whole plan, not only the changed steps]' \ ':plan step: _dev_live steps -' } @@ -865,6 +867,7 @@ _dev__progress__add() { _arguments -s -S : \ '(- *)'{-h,--help}'[show this help message and exit]' \ '--why=[why it was not in the plan]:why: ' \ + '(--verbose -v)'{-v,--verbose}'[print the whole plan, not only the changed steps]' \ '*:spec: ' } @@ -872,6 +875,7 @@ _dev__progress__reopen() { _arguments -s -S : \ '(- *)'{-h,--help}'[show this help message and exit]' \ '--why=[the reason (kept in the run'\''s history)]:why: ' \ + '(--verbose -v)'{-v,--verbose}'[print the whole plan, not only the changed steps]' \ ':plan step: _dev_live steps -' } @@ -879,6 +883,7 @@ _dev__progress__skip() { _arguments -s -S : \ '(- *)'{-h,--help}'[show this help message and exit]' \ '--why=[the reason (kept in the run'\''s history)]:why: ' \ + '(--verbose -v)'{-v,--verbose}'[print the whole plan, not only the changed steps]' \ ':plan step: _dev_live steps -' } @@ -886,6 +891,7 @@ _dev__progress__confirm() { _arguments -s -S : \ '(- *)'{-h,--help}'[show this help message and exit]' \ '--why=[the reason (kept in the run'\''s history)]:why: ' \ + '(--verbose -v)'{-v,--verbose}'[print the whole plan, not only the changed steps]' \ ':plan step: _dev_live steps -' } diff --git a/shell/completions/dev.bash b/shell/completions/dev.bash index 6bc4fed2..6722e7d0 100644 --- a/shell/completions/dev.bash +++ b/shell/completions/dev.bash @@ -258,12 +258,12 @@ _dev_spec() { 'progress step') o='-h --help --next --check --step --force --no-check --approves' v='--next=n --check=n --step=l:steps:-:: --approves=l:steps:-::' p='*n' ;; 'progress block') o='-h --help --next --check --step --force' v='--next=n --check=n --step=l:steps:-::' p='*n' ;; 'progress done') o='-h --help --next --check --step --force --why' v='--next=n --check=n --step=l:steps:-:: --why=n' p='*n' ;; - 'progress assign') o='-h --help --to --scope --why --activity' v='--to=l:crew:-:: --scope=n --why=n --activity=l:activities:-::' p='l:steps:-::' ;; - 'progress begin') o='-h --help' p='l:steps:-::' ;; - 'progress add') o='-h --help --why' v='--why=n' p='*n' ;; - 'progress reopen') o='-h --help --why' v='--why=n' p='l:steps:-::' ;; - 'progress skip') o='-h --help --why' v='--why=n' p='l:steps:-::' ;; - 'progress confirm') o='-h --help --why' v='--why=n' p='l:steps:-::' ;; + 'progress assign') o='-h --help --to --scope --why --activity -v --verbose' v='--to=l:crew:-:: --scope=n --why=n --activity=l:activities:-::' p='l:steps:-::' ;; + 'progress begin') o='-h --help -v --verbose' p='l:steps:-::' ;; + 'progress add') o='-h --help --why -v --verbose' v='--why=n' p='*n' ;; + 'progress reopen') o='-h --help --why -v --verbose' v='--why=n' p='l:steps:-::' ;; + 'progress skip') o='-h --help --why -v --verbose' v='--why=n' p='l:steps:-::' ;; + 'progress confirm') o='-h --help --why -v --verbose' v='--why=n' p='l:steps:-::' ;; 'progress history') o='-h --help' ;; 'progress time') o='-h --help --days -p --project' v='--days=n -p=l:projects:-:: --project=l:projects:-::' ;; 'time') o='-h --help --days -p --project' v='--days=n -p=l:projects:-:: --project=l:projects:-::' ;; diff --git a/tests/test_acceptance_installer.py b/tests/test_acceptance_installer.py index 5c299fc1..a33e865e 100644 --- a/tests/test_acceptance_installer.py +++ b/tests/test_acceptance_installer.py @@ -163,8 +163,8 @@ def survey(): exec 3>&- echo "codex $* stdin=$in stdout=$out" >> "$STUB_LOG" case "$1" in - login) echo "Starting local login server on http://localhost:1455." - echo $$ > "$SCENARIO_STATE/codex.pid" + login) echo $$ > "$SCENARIO_STATE/codex.pid.tmp" && mv "$SCENARIO_STATE/codex.pid.tmp" "$SCENARIO_STATE/codex.pid" + echo "Starting local login server on http://localhost:1455." # the test's Ctrl+C comes after this line exec sleep 60 ;; esac ''' diff --git a/tests/test_caller_identity.py b/tests/test_caller_identity.py index d2822dd9..acdf2899 100644 --- a/tests/test_caller_identity.py +++ b/tests/test_caller_identity.py @@ -115,6 +115,42 @@ def test_same_text_from_member_and_main_is_refused(self): self.assertIn("only the tech lead", out) self.assertEqual(self.decision()["state"], "pending") + def test_morpheus_reads_and_acknowledges_messages_through_a_loop_variable(self): + # 26.11.20: `for r in …; do dev crew read "$r"; done` was refused as not the main session's own command + self.plan_with_tank() + report = pg.crew_ask("Report: " + "x" * 400, from_agent="a_tank") + self.call('for r in $(cat refs.txt); do dev crew read "$r" --json; done') + rc, out = self.dev("crew", "read", report["id"], "--json") + self.assertEqual(rc, 0, out) + page = json.loads(out) + self.call('while read -r r d g; do dev crew ack "$r" --sha256 "$d" --generation "$g"; done < acks.txt') + rc, out = self.dev("crew", "ack", report["id"], "--sha256", page["digest"], "--generation", + str(page["generation"])) + self.assertEqual(rc, 0, out) + self.assertIn("main", next(m for m in self.run_()["messages"] if m["id"] == report["id"])["receipts"]) + + def test_the_end_of_a_run_names_the_unread_messages_it_closes(self): + with mock.patch.object(pg, "caller", lambda *a, **k: {"caller": "main", "how": "test"}): + pg.start("Work", plan=["parser"]) + launch("a_tank", "general-purpose", "Tank: parser") + report = pg.crew_ask("Report: " + "x" * 400, from_agent="a_tank") + self.call('dev progress done "shipped" --force --why "the review is out of this test"') + rc, out = self.dev("progress", "done", "shipped", "--force", "--why", "the review is out of this test") + self.assertEqual(rc, 0, out) + self.assertIn(f"1 unread message(s) to you closed with the run, so they stop coming back: {report['id']}", out) + + def test_a_loop_variable_never_stands_for_a_word_of_a_command_that_decides(self): + # a loop of the tech lead's must not vouch for another process's decision while it runs + self.plan_with_tank() + for loop in ('for c in decide answer; do dev crew "$c" D1 yes; done', + 'while read -r d c; do dev crew decide "$d" "$c"; done < picks.txt'): + with self.subTest(loop): + self.call(loop) + rc, out = self.dev("crew", "decide", "D1", "yes") + self.assertEqual(rc, 2) + self.assertIn("only the tech lead", out) + self.assertEqual(self.decision()["state"], "pending") + def test_morpheus_plain_command_is_allowed(self): self.plan_with_tank() self.call("dev crew decide D1 yes") diff --git a/tests/test_ciwatch.py b/tests/test_ciwatch.py index e5dd3ef1..a7510bb9 100644 --- a/tests/test_ciwatch.py +++ b/tests/test_ciwatch.py @@ -100,6 +100,43 @@ def test_first_error_not_the_tail_and_secrets_redacted(self): self.assertNotIn("2026-11-06T", out) + def test_a_missing_secret_is_an_access_failure(self): + log = ("Fold registry payloads\tFold\t2026-11-09T16:10:32.0289938Z shell: /usr/bin/bash -e {0}\n" + "Fold registry payloads\tFold\t2026-11-09T16:10:32.1455789Z bug registry: the repository secret " + "BUG_REGISTRY_KEY is not set, so nothing was folded.\n" + "Fold registry payloads\tFold\t2026-11-09T16:10:32.1572708Z ##[error]Process completed with exit code 2.") + self.assertEqual(ciwatch.classify(ciwatch.first_error(log)), "access") + self.assertIn("gh secret set", ciwatch.ACTIONS["access"]) + + def test_a_test_of_an_api_that_answers_401_or_403_is_a_test_failure_not_access(self): + for log in ("E assert 403 == 201\n------ Captured log call ------\nINFO httpx:_client.py:1025 HTTP Request: " + "POST http://test/invoices \"HTTP/1.1 403 Forbidden\"\nFAILED tests/test_api.py::test_create", + "Expected: 200\nReceived: 401\n at Object.<anonymous> (auth.test.ts:12:5)\nHTTP 401 Unauthorized\n" + "Tests: 1 failed, 40 passed"): + with self.subTest(log[:20]): + self.assertEqual(ciwatch.classify(log), "test") + self.assertEqual(ciwatch.classify("fatal: unable to access 'https://github.com/acme/api/': The requested URL " + "returned error: 403"), "access") + + def test_the_first_error_is_the_line_that_says_what_failed_in_a_job_whose_name_has_spaces(self): + job = "pytest 2/2 · the quick checks\tUNKNOWN STEP\t" + log = "\n".join(job + f"2026-11-07T04:57:0{n}.1Z " + ln for n, ln in enumerate([ + "\ufeff▸ claude CLI not found: skipped `claude plugin validate`", + " FAILED app/tests/test_docs.py::test_images - AssertionError: workbench-dark.webp is stale", + " 1 failed, 821 passed in 339.69s"])) + out = ciwatch.first_error(log, context=0) + self.assertTrue(out.lstrip().startswith("FAILED app/tests/test_docs.py::test_images"), out) + self.assertNotIn("UNKNOWN STEP", out) + + def test_a_first_error_that_says_too_little_is_classified_from_the_end_of_the_failed_log(self): + log = "\n".join(["Run python -m unittest", "warning: could not import the optional plugin"] + + ["." * 80] * 40 + ["FAIL: test_x (tests.test_a.ATests)", "FAILED (failures=1)"]) + with mock.patch.object(ciwatch, "failed_log", lambda *a, **k: log): + d = ciwatch.diagnose("github", "/repo", {"id": "1", "name": "ci", "status": "failed", + "conclusion": "failure", "jobs": []}) + self.assertEqual(d["class"], "test") + + class WatchCase(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() @@ -174,6 +211,75 @@ def test_timeout(self): runs_fn=self.sequence([run("running")]), sleep=clock.sleep, clock=clock) self.assertEqual(res["state"], "timeout") + def test_a_pr_made_ready_follows_its_own_run_past_the_drafts_skipped_one(self): + # PR 43: the draft's push left run 78 skipped on the commit; marking it ready started run 79 + clock = Clock() + since = clock.t - 5 + draft = run("skipped", n=78, rid="78", started=since - 600, conclusion="skipped") + fn = self.sequence([draft], [draft, run("running", n=79, rid="79", started=since + 20)], + [draft, run("success", n=79, rid="79", started=since + 20)]) + res = ciwatch.watch("/repo", branch="fix/x", sha="abc1234", runs_fn=fn, sleep=clock.sleep, clock=clock, + since=since) + self.assertEqual((res["state"], [r["number"] for r in res["runs"]]), ("passed", [79])) + + def test_a_draft_run_skipped_after_the_ready_call_opened_does_not_end_the_watch(self): + # `dev push && dev pr ready`: the push's draft run starts after the call opened and is skipped at once + clock = Clock() + since = clock.t - 5 + draft = run("skipped", n=78, rid="78", started=since + 2, conclusion="skipped") + fn = self.sequence([draft], [draft], [draft, run("failed", n=79, rid="79", started=since + 40)]) + res = ciwatch.watch("/repo", branch="fix/x", sha="abc1234", runs_fn=fn, sleep=clock.sleep, clock=clock, + since=since) + self.assertEqual((res["state"], sorted(r["number"] for r in res["runs"])), ("failed", [78, 79])) + + def test_a_ready_commit_whose_ci_does_not_run_on_ready_reports_the_drafts_real_run(self): + # GitHub's pull_request runs on opened, synchronize and reopened: a repository that does not skip drafts + # starts no run on `ready`, and the draft push's run is the commit's result + clock = Clock() + since = clock.t - 5 + failed = run("failed", started=since - 300, conclusion="failure") + res = ciwatch.watch("/repo", branch="fix/x", sha="abc1234", runs_fn=self.sequence([failed]), sleep=clock.sleep, + clock=clock, since=since) + self.assertEqual(res["state"], "failed") + self.assertGreaterEqual(res["minutes"], ciwatch.NO_RUN_MIN) + + def test_a_watch_of_the_drafts_push_that_still_runs_follows_the_ready_that_came_after(self): + # the watch of `dev pr create --draft` was still waiting when `dev pr ready` joined it with a later moment + clock = Clock() + since = clock.t - 5 + target = {"top": "/repo", "ref": "fix/x", "sha": "abc1234"} + pid = os.getpid() + ciwatch.register(target, "devkit", "claude", "s1", pid, 90) + ciwatch.register(dict(target, since=since), "devkit", "claude", "s1", pid, 90) # the same record + self.assertEqual(ciwatch._since(ciwatch.repo_id("/repo"), "fix/x", "abc1234"), round(since, 3)) + draft = run("skipped", n=78, rid="78", started=since - 600, conclusion="skipped") + fn = self.sequence([draft], [draft, run("success", n=79, rid="79", started=since + 20)]) + res = ciwatch.watch("/repo", branch="fix/x", sha="abc1234", runs_fn=fn, sleep=clock.sleep, clock=clock) + self.assertEqual((res["state"], [r["number"] for r in res["runs"]]), ("passed", [79])) + + def test_a_drafts_result_neither_tells_nor_closes_the_watch_of_the_ready_that_came_after(self): + # the draft's watcher had left its loop when `dev pr ready` joined it: its result is not the ready's + clock = Clock() + target = {"top": "/repo", "ref": "fix/x", "sha": "abc1234"} + with TempState(): + pg.start("Release", plan=["ci"]) + ciwatch.register(dict(target, since=clock.t + 30), "devkit", "claude", "s1", os.getpid(), 90, now=clock.t) + draft = run("skipped", n=78, rid="78", started=clock.t - 600, conclusion="skipped") + res = ciwatch.watch("/repo", branch="fix/x", sha="abc1234", runs_fn=self.sequence([draft]), + sleep=clock.sleep, clock=clock) + self.assertEqual(res.get("told"), []) + self.assertEqual([w["status"] for w in ciwatch.watches(clock.t)], ["live"]) + self.assertEqual(ciwatch._results(after=clock.t), set()) # the Stop gate still asks for a wait + + def test_a_ready_commit_whose_runs_all_stay_skipped_ends_after_the_no_run_window(self): + clock = Clock() + since = clock.t + skipped = run("skipped", started=since + 2, conclusion="skipped") + res = ciwatch.watch("/repo", branch="fix/x", sha="abc1234", runs_fn=self.sequence([skipped]), + sleep=clock.sleep, clock=clock, since=since) + self.assertEqual(res["state"], "none") + self.assertGreaterEqual(res["minutes"], ciwatch.NO_RUN_MIN) + def test_the_result_reaches_the_session_that_pushed(self): clock = Clock() failed = run("failed", jobs=[{"name": "lint", "status": "failed", "current": "ruff"}]) @@ -188,6 +294,19 @@ def test_the_result_reaches_the_session_that_pushed(self): ciwatch.deliver("claude", "s1", res) # with a run: a message to Morpheus self.assertIn("CI failed on main", pg.on_tool_done("claude", {"session_id": "s1"})) + def test_a_session_that_three_watches_joined_hears_their_one_result_once(self): + # three `dev pr ready` calls started three watchers on one commit, and each told the session the same + # skipped run: the tech lead got it three times (M45 to M47) + skipped = run("skipped", conclusion="skipped") + target = {"top": "/repo", "ref": "main", "sha": "abc1234"} + with TempState(): + pg.start("Release", plan=["ci"]) + for pid in (dead_pid(), dead_pid(), dead_pid()): + ciwatch.register(target, "devkit", "claude", "s1", pid, 90) + self.watch([skipped]) + told = [m for m in pg.load_run("claude", "s1")["messages"] if m.get("from") == "ci"] + self.assertEqual(len(told), 1, [m["text"] for m in told]) + def test_a_result_for_a_session_whose_run_is_orphaned_waits_in_the_session(self): res = self.watch([run("failed", conclusion="failure")]) with TempState(): @@ -290,6 +409,26 @@ def test_a_pending_event_is_given_once_and_marked_delivered(self): events = json.loads(st.sess.read_text())["ci_events"] self.assertEqual([e.get("delivered") for e in events], [True]) + def test_the_same_result_told_twice_waits_in_the_session_once(self): + res = self.watch([run("skipped", conclusion="skipped")]) + with TempState() as st: + ciwatch._tell("claude", "s1", res) + ciwatch._tell("claude", "s1", res) # a second watch's record of the same session + self.assertEqual(len(json.loads(st.sess.read_text())["ci_events"]), 1) + + def test_two_watches_of_one_result_that_waited_different_times_tell_the_session_once(self): + res = self.watch([run("skipped", conclusion="skipped")]) + later = dict(res, minutes=round(res["minutes"] + 12.3, 1)) # its message says another number of minutes + self.assertNotEqual(ciwatch.message(res), ciwatch.message(later)) + with TempState() as st: + ciwatch._tell("claude", "s1", res) + ciwatch._tell("claude", "s1", later) + self.assertEqual(len(json.loads(st.sess.read_text())["ci_events"]), 1) + pg.start("Release", plan=["ci"]) + ciwatch._tell("claude", "s1", res) + ciwatch._tell("claude", "s1", later) + self.assertEqual(len([m for m in pg.load_run("claude", "s1")["messages"] if m.get("from") == "ci"]), 1) + def test_a_failure_that_a_later_pass_on_the_branch_supersedes_is_not_delivered(self): failed = self.watch([run("failed", conclusion="failure", rid="98", started=1_799_990_000, sha="1111111")], sha="1111111") @@ -337,6 +476,16 @@ def sleep(s): class WaitTests(WaitCase): + def test_a_wait_that_joins_a_pr_made_ready_follows_the_ready_run(self): + # devkit's watch of the ready PR keeps when its runs count from; the agent's own wait uses that moment too + since = Clock().t - 5 + ciwatch.register({"top": "/repo", "ref": "main", "sha": "abc1234", "since": since}, "devkit", "claude", "s1", + os.getpid(), 90) + draft = run("skipped", n=78, rid="78", started=since - 600, conclusion="skipped") + code, lines = self.wait([draft], [draft, run("success", n=79, rid="79", started=since + 30, + conclusion="success")]) + self.assertEqual((code, lines[-1].split(" · ")[0]), (0, "CI passed")) + def test_prints_one_line_per_finished_job_then_one_line_with_the_conclusion(self): code, lines = self.wait([run("running", jobs=[job("lint", "running"), job("tests", "queued")])], [run("running", jobs=[job("lint", "success"), job("tests", "running")])], @@ -686,6 +835,13 @@ def slow(top, branch, **kw): # the hook has seconds; the host takes longer answer.set() self.assertIn(self.watch_cmd(), why or "") + def test_a_pr_made_ready_needs_a_watch_while_only_the_drafts_skipped_run_shows(self): + self.prompt() + self.bash("dev pr ready") + draft = run("skipped", sha=self.sha[:7], started=time.time() - 600, conclusion="skipped") + why = self.gate(runs=[draft]) + self.assertIn(f"feat/x @ {self.sha[:7]}", why or "") + def test_a_draft_pr_whose_branch_shows_no_run_needs_no_watch(self): self.prompt() self.bash("gh pr create --draft --fill") diff --git a/tests/test_doctor_profiles.py b/tests/test_doctor_profiles.py index f426fc67..fa90ad4b 100644 --- a/tests/test_doctor_profiles.py +++ b/tests/test_doctor_profiles.py @@ -302,6 +302,22 @@ def test_the_doctor_job_is_judged_by_whether_it_ran(self): self.assertIn("ran; reported failed checks", row(run_doctor( job_defs={"doctor": week}, last_runs={"doctor": {"start": start, "rc": 1}})[1], "job doctor")) + # a job that is off is a warning: what it does stops (the nightly sleep job: lessons never decay, logs grow), and + # the row says what and how to turn it on + def test_a_job_that_is_off_is_a_warning_that_says_what_stops(self): + sleep = {"enabled": False, "at": "03:30", "cmd": ["sleep", "--quiet"], "about": "Lessons: decay, merge"} + _, out = run_doctor(job_defs={"sleep": sleep}, last_runs={}) + line = row(out, "job sleep") + self.assertEqual(line.split()[0], "!", out) + self.assertIn("off · Lessons: decay, merge: this does not run", line) + self.assertIn("dev jobs enable sleep", out) + # turned off in the configuration (`dev jobs disable`, or the wizard's report-only gc): a choice, not a fault + with mock.patch.dict(core.CFG, {"jobs": {"sleep": {"enabled": False}}}): + _, out = run_doctor(job_defs={"sleep": sleep}, last_runs={}) + line = row(out, "job sleep") + self.assertEqual(line.split()[0], "✓", out) + self.assertIn("off in your configuration · Lessons: decay, merge: this does not run", line) + # a usage limit reached is no setup fault: the quota row is a warning that names when it resets, it is not # counted as a failed check, and a quota with room left passes def test_a_used_up_quota_is_a_warning_not_a_failure(self): diff --git a/tests/test_gc.py b/tests/test_gc.py index fd0c1dab..881cd317 100644 --- a/tests/test_gc.py +++ b/tests/test_gc.py @@ -317,6 +317,16 @@ def test_old_message_copies_and_notification_records_go_and_live_ones_stay(self) self.assertEqual([p.name for p in keep if p.exists()], [p.name for p in keep]) self.assertEqual([p.name for p in gone if p.exists()], []) + def test_a_temporary_file_an_interrupted_handoff_write_left_goes_after_an_hour(self): + handoff = self.root / "handoff" + with mock.patch.object(core, "HANDOFF", handoff): + old = self.record("handoff/items/acme/api/.T-abc.md.k2j3h4.tmp", 2 / 24) + fresh = self.record("handoff/items/acme/api/.T-def.md.p9q8r7.tmp", 0) + in_git = self.record("handoff/.git/objects/.pack.x1.tmp", 2 / 24) + note = self.record("handoff/projects/acme/api.md", 2 / 24) + gc.apply({"actions": gc.state_records()}, only_auto=True, remote=False) + self.assertEqual([p.exists() for p in (old, fresh, in_git, note)], [False, True, True, True]) + def test_settled_automatic_bug_reports_go_after_a_quiet_period_and_open_ones_stay(self): # an acknowledged report stays long enough for a repeat to update its issue; an expired one (retired after # 30 quiet days), a month after its retirement; a report still to send, or quarantined as evidence, stays diff --git a/tests/test_handoff_push.py b/tests/test_handoff_push.py index e02d8da4..69202321 100644 --- a/tests/test_handoff_push.py +++ b/tests/test_handoff_push.py @@ -356,6 +356,40 @@ def test_a_claim_reaches_the_remote_with_the_change_a_background_sync_left_waiti self.assertEqual(m.pending(), ("", "0")) # the waiting view went out with the claim self.assertEqual(m.stopped(), [], m.problem()) + def test_a_pull_alone_commits_the_waiting_view_and_moves_the_checkout(self): + with Mac(interval=300) as m, contextlib.redirect_stderr(io.StringIO()): + self.view_waits_while_the_other_mac_changes_it(m) + self.assertTrue(work.pull()) + self.assertEqual(m.pending()[0], "") + self.assertIn("the other Mac's view", _git(m.here, "log", "-p", "--format=%s", "-3", "--", "TASKS.md")) + + def test_an_item_another_command_wrote_and_not_yet_committed_keeps_its_own_commit(self): + # an urgent pull committed everything that changed, so a writer's item went into "sync: …", and the writer's + # own commit, with its message and audit record, found nothing left to commit + with Mac(interval=300) as m, contextlib.redirect_stderr(io.StringIO()): + iid = m.shared_item("Export invoices") + self.view_waits_while_the_other_mac_changes_it(m) + it = m.item(iid) + it["meta"]["priority"] = "high" + work.write_record(it["path"], work.render(it)) # written; its commit comes next + self.assertTrue(work.pull()) + work._commit([it["path"]], f"{iid}: edit priority high (ana)") + rel = str(it["path"].relative_to(m.here)) + self.assertEqual(_git(m.here, "log", "-1", "--format=%s", "--", rel), f"{iid}: edit priority high (ana)") + self.assertEqual(work.writing(m.here), set()) + + def test_a_record_written_while_a_sync_stages_stays_out_of_its_commit(self): + with Mac(interval=300) as m, contextlib.redirect_stderr(io.StringIO()): + view = m.change("TASKS.md", "this Mac's view\n") + item = m.change("items/acme/api/T-late.md", "a record its writer has not committed yet\n") + seen = iter([set(), {"items/acme/api/T-late.md"}]) # marked between the first look and the staging + with mock.patch.object(work, "writing", lambda root: next(seen, set())): + self.assertEqual(cli.commit_push(quiet=True, urgent=True), "pushed") + self.assertIsNotNone(m.on_remote("TASKS.md")) + self.assertIsNone(m.on_remote("items/acme/api/T-late.md")) + self.assertIn("?? items/", m.pending()[0]) # still the writer's to commit + self.assertTrue(view.exists() and item.exists()) + def test_a_release_and_a_done_reach_the_remote_while_a_view_waits(self): with Mac(interval=300) as m, contextlib.redirect_stderr(io.StringIO()): iid = m.shared_item("Export invoices") diff --git a/tests/test_hooks_wiring.py b/tests/test_hooks_wiring.py index ee0a4c30..d2e91843 100644 --- a/tests/test_hooks_wiring.py +++ b/tests/test_hooks_wiring.py @@ -330,11 +330,12 @@ def setUp(self): subprocess.run(["git", "init", "-q", "--bare", str(remote)], check=True, env=GIT_ENV) git(self.repo, "remote", "add", "origin", str(remote)) git(self.repo, "push", "-q", "origin", "HEAD:refs/heads/main") - self.started, self.tops = [], [] + self.started, self.tops, self.since = [], [], [] def start(top, **kw): self.tops.append(os.path.realpath(top)) self.started.append((kw.get("branch"), kw.get("sha"))) + self.since.append(kw.get("since")) return True for p in (mock.patch.object(ciwatch, "start_background", start), mock.patch.object(core, "is_temp", lambda path: False), # the test's repository is a real one here @@ -365,6 +366,20 @@ def test_a_push_codex_runs_through_a_login_shell_watches_that_commit(self): git(self.repo, "push", "-q", "-u", "origin", "feat/x") self.assertEqual(self.after(["bash", "-lc", "git push -u origin feat/x"]), [("feat/x", sha)]) + def test_a_pr_made_ready_counts_its_runs_from_when_the_call_opened(self): + # the commit may have a draft's skipped run already: the watch follows the run that ready starts + from devkit import ciwatch + git(self.repo, "switch", "-qc", "feat/x") + sha = self.commit("feature\n") + git(self.repo, "push", "-q", "-u", "origin", "feat/x") + before = time.time() + self.hook("pre-tool", self.tool("Bash", {"command": "dev pr ready"}, tid="toolu_ci", cwd=self.repo)) + after = time.time() + self.assertEqual(self.after("dev pr ready"), [("feat/x", sha)]) + self.assertTrue(before - ciwatch.READY_SKEW_S <= self.since[0] <= after - ciwatch.READY_SKEW_S, self.since) + self.after("git push origin feat/x") # a push counts every run of its commit + self.assertEqual((self.started[1], self.since[1]), (("feat/x", sha), None)) + def test_a_branch_the_remote_does_not_have_is_not_watched(self): # made from the remote's main and tracking it: the same commit is on the remote, but not this branch git(self.repo, "switch", "-qc", "hotfix/26.11.6", "--track", "origin/main") diff --git a/tests/test_messaging.py b/tests/test_messaging.py index 8da0f392..d3268d36 100644 --- a/tests/test_messaging.py +++ b/tests/test_messaging.py @@ -337,6 +337,29 @@ def test_a_message_delivered_whole_does_not_come_back_but_a_longer_one_does(self again = [m["id"] for m in progress._take_messages("claude", "s1", "main", mark=False)] self.assertEqual([longer["id"]], again) + def test_a_finished_runs_unread_messages_stop_coming_back_and_stay_readable(self): + # after the 26.11.20 run ended, 25 messages to the tech lead kept coming back until each was read and acked + with TempState(): + progress.start("delivery", plan="verify=5m") + launch("a1", "devkit:neo", "Neo: verify") + report = progress.crew_ask("Report: " + "x" * 400, from_agent="a1") + progress._take_messages("claude", "s1", "main") # its preview was shown once, never read whole + progress.step("all done", kind="done", force=True) + with patch("time.time", return_value=time.time() + 120): + self.assertEqual(progress._take_messages("claude", "s1", "main", mark=False), []) + self.assertEqual(progress.crew_inbox(), []) + self.assertIn("Report: ", progress.crew_read(report["ref"])["text"]) + + def test_the_same_request_key_posts_one_message_and_notifies_once(self): + with TempState(): + progress.start("delivery", plan="verify=5m") + with patch.object(progress, "_notify_message") as notify: + for _ in range(3): + progress._ask_into("claude", "s1", "CI skipped on fix/x", "main", "ci", time.time(), + request_id="ci:same") + self.assertEqual(([m["text"] for m in progress.load_run("claude", "s1")["messages"]], notify.call_count), + (["CI skipped on fix/x"], 1)) + def test_a_reply_to_an_asker_that_ended_stays_with_it_and_tells_the_tech_lead(self): # an answer, a decision's result and a withdrawal keep their recipient; nobody reads an ended lane, so the # tech lead hears of each and forwards it or launches the member again diff --git a/tests/test_plans.py b/tests/test_plans.py index ae68451c..9e86f730 100644 --- a/tests/test_plans.py +++ b/tests/test_plans.py @@ -171,6 +171,16 @@ def test_a_plan_path_that_does_not_exist_is_a_plain_error_that_names_it(self): self.assertNotIn("devkit bug", err.getvalue() + out.getvalue()) self.assertFalse(missing.exists()) + def test_a_plan_is_approved_by_the_id_dev_plan_ls_shows(self): + with TempPlans(): + path = plans.new("acme/api", "Export invoices", a=A) + pid = next(p_["id"] for p_ in plans.list_plans() if p_["path"] == path) + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + rc = cli.main(["plan", "approve", pid, "--why", "agreed with the developer"]) + self.assertEqual(rc, 0, err.getvalue()) + self.assertIn(f"{pid} v2 · approved", out.getvalue()) + def test_a_file_that_is_not_markdown_is_refused_and_left_byte_for_byte(self): # a helper script kept beside the plans: a revision used to put YAML front matter on top of it, and the next # `python3 helper.py` failed with a SyntaxError. Only Markdown plans get front matter and versions diff --git a/tests/test_progress.py b/tests/test_progress.py index 5ef626a5..ec22c38c 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -236,6 +236,36 @@ def test_calibration_corrects_estimates(self): run = pg.start("Next feature", estimate="20m") self.assertAlmostEqual(run["estimate_cal"], 30, 0) + def test_a_description_that_starts_with_a_steps_name_and_a_colon_closes_that_step(self): + # "ci-watch: …" closed nothing: the running step was another one, and the text did not describe it + with TempState(): + os.environ["DEVKIT_SESSION"] = "claude:s1" + pg.start("Release", plan="ci-watch=40m; review=20m") + pg.begin("review") + run = pg.step("ci-watch: a PR made ready follows its own run", check="✓ 68 tests pass") + self.assertEqual({s["name"]: s["state"] for s in run["plan"]}["ci-watch"], "done") + + def test_a_change_to_one_step_prints_that_step_and_the_headline_not_the_whole_plan(self): + with TempState(): + os.environ["DEVKIT_SESSION"] = "claude:s1" + run = pg.start("Next feature", plan="api=40m; docs=20m; release=10m after docs") + marks = pg.step_marks(run) + run = pg.add_step(pg.spec_args(["notes=5m"]), why="found during the work") + out = pg.changed_lines(run, marks) + self.assertEqual([ln.split(" · ")[0] for ln in out.splitlines()[:-1]], ["○ 4. notes"]) + self.assertIn("of 4 steps", out.splitlines()[-1]) + + def test_a_plan_without_a_total_estimate_is_calibrated_from_its_steps(self): + # `dev progress start --plan "a=40m; b=60m"` printed "plan for ~0m": the steps made the estimate, not its + # calibrated copy + with TempState(): + for actual in (40, 45, 50): + pg.record("run", "claude", "s1", "x", actual * 60, "acme/api", estimate=30) + os.environ["DEVKIT_SESSION"] = "claude:s1" + run = pg.start("Next feature", plan="api=40m; docs=20m") + self.assertEqual(run["estimate"], 60) + self.assertAlmostEqual(run["estimate_cal"], 90, 0) + def test_status_question_gets_real_records(self): with TempState(): pg.start("Release", steps=4, estimate="1h") diff --git a/tests/test_registry.py b/tests/test_registry.py index 5d4c6b5b..01d343b9 100644 --- a/tests/test_registry.py +++ b/tests/test_registry.py @@ -268,6 +268,17 @@ def test_a_sync_writes_the_projects_map_to_the_state_folder_and_leaves_the_hando self.assertTrue(ignore.startswith(".DS_Store\n*.tmp\n"), ignore) # the repository's own rules stay first self.assertFalse(registry.ensure_handoff_ignore(self.handoff)) # the managed block stays one block + def test_a_handoff_made_before_its_template_ignored_temporary_files_ignores_them_after_a_sync(self): + # in this Mac's own exclude file: a shared .gitignore rule would be rewritten by Macs on an older devkit + (self.handoff / ".gitignore").write_text(".DS_Store\n") + registry.write_outputs(self.reg()) + (self.handoff / "items").mkdir(exist_ok=True) + (self.handoff / "items" / ".T-abc.md.k2j3h4.tmp").write_text("half a record") + self.assertEqual(git(self.handoff, "status", "--porcelain", "--untracked-files=all", "--", "items"), "") + self.assertNotIn("tmp", (self.handoff / ".gitignore").read_text()) + registry.write_outputs(self.reg()) # once + self.assertEqual((self.handoff / ".git" / "info" / "exclude").read_text().splitlines().count(".*.tmp"), 1) + def test_the_readers_take_the_state_folders_map_and_the_handoff_copy_only_before_the_first_sync(self): from devkit import bugs, completion, dashserver, prompt, sleep clone = self.root / "Development" / "acme" / "weave" diff --git a/tests/test_state_e2e.py b/tests/test_state_e2e.py index 317e78f8..aa1422f7 100644 --- a/tests/test_state_e2e.py +++ b/tests/test_state_e2e.py @@ -665,7 +665,7 @@ def setUp(self): def runs_for(top, branch=None, limit=5, detail=True, max_age=20): return {"provider": "github", "repo": PROJECT, "branch": branch, "runs": list(self.host.get(branch, []))} - def start(top, session="", branch="", sha=""): + def start(top, session="", branch="", sha="", since=None): self.started.append((branch or None, (sha or "")[:7] or None)) return True s = w.stack diff --git a/tests/test_work.py b/tests/test_work.py index 16a93a48..0aeff206 100644 --- a/tests/test_work.py +++ b/tests/test_work.py @@ -219,6 +219,40 @@ def test_a_why_with_list_and_heading_lines_stays_one_changelog_entry(self): self.assertEqual(len(log), 2, log) self.assertTrue(log[1].endswith("why: " + why), log[1]) + def test_a_record_being_written_is_listed_until_its_writer_commits_and_a_dead_writers_marker_goes(self): + with TempHandoff(): + it = work.create("acme/api", "Export invoices", why="a reason", a=A) + rel = str(it["path"].resolve().relative_to(work.HANDOFF.resolve())) + work.write_record(it["path"], it["path"].read_text() + "\n") # written, not committed yet + self.assertEqual(work.writing(work.HANDOFF), {rel}) + other = work._writing_dir() / (work._writing_marker(it["path"]).name.rsplit("-", 1)[0] + "-1") + other.write_text(json.dumps({"pid": 1, "ts": time.time(), "path": str(it["path"].resolve())})) + work._commit([it["path"]], "edit") # its own marker goes; the other writer's (pid 1) stays + self.assertEqual(work.writing(work.HANDOFF), {rel}) + dead = work._writing_dir() / "gone-0" + dead.write_text(json.dumps({"pid": 2 ** 22 + 7, "ts": time.time(), "path": str(it["path"].resolve())})) + other.write_text(json.dumps({"pid": 1, "ts": time.time() - work.WRITING_S - 1, + "path": str(it["path"].resolve())})) + self.assertEqual(work.writing(work.HANDOFF), set()) # an ended writer and an expired marker count no more + self.assertEqual((dead.exists(), other.exists()), (False, False)) + + def test_a_why_with_a_blank_line_keeps_it(self): + with TempHandoff(): + why = "two reasons:\n\nthe second one" + it = work.create("acme/api", "Export invoices", why=why, a=A) + work.update(work.load(it["path"]), "move", why="start now", a=A, bucket="now") + log = work.load(it["path"])["changelog"] + self.assertTrue(log[1].endswith("why: " + why), log[1]) + + def test_a_record_an_editor_saved_with_a_byte_order_mark_and_windows_line_ends_keeps_its_frontmatter(self): + with TempHandoff(): + it = work.create("acme/api", "Export invoices", why="a reason", a=A) + it["path"].write_text("\ufeff" + it["path"].read_text().replace("\n", "\r\n")) + again = work.load(it["path"]) + self.assertEqual((again["meta"]["id"], again["meta"]["title"]), (it["meta"]["id"], "Export invoices")) + work.update(again, "move", why="start now", a=A, bucket="now") # the rewrite loses no line + self.assertEqual(work.load(it["path"])["meta"]["bucket"], "now") + def test_a_write_may_drop_only_the_text_it_edits(self): with TempHandoff(): it = work.create("acme/api", "Export invoices", body="Context.", why="a reason", a=A)