From a7514496330095fc6957d97baf82e93229c0c960 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Tue, 17 Nov 2026 00:33:26 -0800 Subject: [PATCH 1/2] fix: stop double reports and handoff churn, fix daily-use bugs The developer asked for devkit to be as stable as possible for daily, heavy use, and main's CI failed after v26.11.19. Root cause: The wait printed a crew or peer message before claiming it, so a hook that took it in between reported it too (main CI run 44027389111). The handoff repository took a commit and push on every hook sync and tracked a per-Mac registry cache, so it grew about 10 MB a day; the audit copy was one monthly file that stopped publishing past 45 MB; audit queries cleaned every record before filtering. The rest came from a triage of this Mac's logs, held bug reports, GitHub issues and the backlog: task writes printed the whole list after their own line, several ids were joined into one search, a peer's malformed presence file crashed dev progress, answered questions stayed unacknowledged, writers shared one fixed temp file name, dev plan revise stamped non-Markdown files, a two-word Spanish message counted as unclear, dev test prove took an import error as proof, and the test runner's receipt was refused by the repository's test guard. dev watch claims each message under the lock before printing and gives the claim back on failure. Background syncs push the handoff at most every sync.push_interval seconds (default 300) through one flusher per Mac; urgent changes push at once; files over 45 MB are never committed; gc runs only in the scheduled sync. registry.json leaves git, generated views skip timestamp-only changes, note blocks are written only by a Mac with the clone, presence is written on real changes. The audit copy is one file per closed UTC day; queries filter before cleaning and the table cleans only the rows it shows. dev doctor judges its own job, shows quota as a warning, prints each header once. Plus the triaged fixes listed in the CHANGELOG, the Chrome test harness retry, and docs. Verified: lanes' runs on python3 3.15 and /usr/bin/python3 3.9: dev test 4,733/4,737 with the 3 release-argument failures fixed and rerun green; dev test prove on every new test; dev docs check 0 issues; plain dev audit 4.87 s to 0.35 s on this Mac's 91,000-record month --- CHANGELOG.md | 48 +++ docs/audit.md | 112 ++++-- docs/commands.md | 10 +- docs/concepts.md | 9 +- docs/configuration.md | 3 +- docs/jobs-and-audit.md | 11 +- docs/teams.md | 7 +- lib/devkit/audit.py | 559 ++++++++++++++++++++++------ lib/devkit/branches.py | 19 +- lib/devkit/bugs.py | 45 ++- lib/devkit/cli.py | 465 ++++++++++++++++++----- lib/devkit/configschema.py | 4 +- lib/devkit/continuity.py | 7 +- lib/devkit/dashboard.py | 4 +- lib/devkit/gitx.py | 24 +- lib/devkit/hooks.py | 8 +- lib/devkit/language.py | 156 ++++++-- lib/devkit/peers.py | 27 ++ lib/devkit/plans.py | 5 +- lib/devkit/progress.py | 66 +++- lib/devkit/registry.py | 74 +++- lib/devkit/setup.py | 110 ++++-- lib/devkit/shellparse.py | 3 +- lib/devkit/testx.py | 24 +- lib/devkit/watch.py | 86 +++-- lib/devkit/wizard.py | 10 +- lib/devkit/work.py | 149 +++++--- shell/completions/_dev | 5 +- shell/completions/dev.bash | 2 +- templates/handoff/README.md | 2 +- tests/test_acceptance_management.py | 50 ++- tests/test_audit.py | 544 ++++++++++++++++++++++++--- tests/test_bugs_cli.py | 19 + tests/test_bugs_sync.py | 37 ++ tests/test_canary_language.py | 10 + tests/test_cli_wiring.py | 31 ++ tests/test_continuity.py | 17 + tests/test_dashboard.py | 135 ++++++- tests/test_doctor_profiles.py | 101 +++++ tests/test_gitx.py | 20 + tests/test_handoff_push.py | 374 +++++++++++++++++++ tests/test_language.py | 56 +++ tests/test_plans.py | 18 +- tests/test_progress.py | 11 + tests/test_registry.py | 106 ++++++ tests/test_shared_writes.py | 169 +++++++++ tests/test_store_locks.py | 1 + tests/test_sync.py | 4 +- tests/test_testx.py | 69 ++++ tests/test_watch.py | 38 ++ tests/test_watch_peers.py | 30 ++ tests/test_wizard.py | 18 + tests/test_work.py | 110 ++++++ 53 files changed, 3527 insertions(+), 495 deletions(-) create mode 100644 tests/test_handoff_push.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 505aac19..0dceef8d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,54 @@ 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.20] - 2026-11-17 + +### Changed + +- **The handoff repository pushes in batches.** A background `dev sync` (the hooks' syncs, queued runs) now commits + and pushes the handoff repository at most once every `sync.push_interval` seconds (default 300; `0` pushes on every + sync, as before). One background flusher per Mac pushes what waited, on time. Claims, embargoes, the end of a + session and a `dev sync` you run yourself still push at once. A heavy day on one Mac goes from about 700 handoff + commits to under 300. +- **Generated files stop churning.** `registry.json`, a cache only one Mac reads, is no longer tracked by git (it had + been committed thousands of times and made up a third of the repository's history). Generated views are not + rewritten when only a timestamp changed, a project note's generated block is written only by a Mac that has the + project cloned, and presence is written when its sessions or locks change, otherwise at most every 10 minutes. +- **The audit trail's handoff copy is one file per day.** Every month is published as + `audit/@/YYYY-MM/YYYY-MM-DD.jsonl`, one file per closed UTC day, each written once. A month past + 45 MB publishes again (November had been stuck since Nov 12), a single day over 45 MB is held with a small marker + and named by `dev doctor`, and `dev audit verify` follows one chain across the files. A copy an earlier devkit + published stays as it is. Records now wait up to about 29 hours to be published, instead of about 24. +- **`dev audit` is fast on a heavy month.** Time, action and other stored fields are checked before a record is + cleaned, and the table view cleans only the rows it shows: a 7-day query of a 90,000-record month went from 8 s to + under 1 s. +- **`dev doctor`** judges its own weekly job by whether it ran, shows a used-up agent quota as a warning, and prints + each section header once; the setup wizard says how many warnings remain. + +### Fixed + +- **`dev watch` reported one message twice.** The wait printed a crew or peer message before claiming it, so a hook + that delivered the same message in between reported it too. The wait now claims under the lock first, and gives the + claim back if printing fails. +- **Tests in devkit's own repository.** `dev test run` marked a passing run incomplete because the repository's test + guard refused the runner's completion file; the runner now writes its files to its own temporary folder. + `dev test prove` no longer counts a test that stops at an import or collection error without the change as proof. + The dashboard's browser tests retry once with a fresh Chrome after a hang, instead of failing every later test. +- **Task commands.** `dev task start`, `done`, `cancel`, `reopen`, `move` and `edit` print only their own result, + and a command given several ids acts on each. +- **Reply language.** A short message such as "¿cómo vamos?" decides the reply language when its words or marks + name one; an unclear one follows most of the recent messages, not only the newest. +- **Plans.** `dev plan revise` versions only Markdown plans and leaves other files in the plans folder untouched, and + the Stop hook asks only for those. +- **Writers that collided between sessions** (the status line's quota, the dashboard, the settings repair) use unique + temporary files. +- **Crew messages.** An answered question and a delivered answer count as read, so the continuity brief no longer + lists hundreds of messages waiting for acknowledgement. +- **`dev progress`** skips another Mac's malformed presence file instead of crashing. +- **Bug reports** queued by an older devkit in a format that cannot be sent are named as such, with + `dev bug drop `, instead of being said to go with the next sync. +- **`dev release `** takes the version as a plain argument too. + ## [26.11.19] - 2026-11-16 ### Removed diff --git a/docs/audit.md b/docs/audit.md index d33f6cab..ec37cc9a 100644 --- a/docs/audit.md +++ b/docs/audit.md @@ -15,14 +15,14 @@ that publishes them and a first look at `dev audit`, see ## Retention Each machine appends its records to `~/.local/state/devkit/audit/YYYY-MM.jsonl` (mode 0600, in a 0700 folder). The -daily `audit` job copies the last three month files to `audit/@/` in the handoff repository, then -prunes. Prune also covers the folders this Mac wrote under a hostname it had before (`audit/@/`), for -the month files whose last record this Mac wrote. +daily `audit` job publishes the last three months to `audit/@/` in the handoff repository, one file +per day (see [The handoff copy](#the-handoff-copy)), then prunes. Prune also covers the folders this Mac wrote under a +hostname it had before (`audit/@/`), for the month files whose last record this Mac wrote. | Key | Default | What it keeps | | --- | --- | --- | | `audit.retention.local_months` | `13` | Month files on this machine: a full year plus one month, so a yearly review or a year-over-year incident still has its records | -| `audit.retention.team_months` | `13` | This machine's month files in the handoff copy. The team copy is read by more people, so by default it keeps no longer than the machine | +| `audit.retention.team_months` | `13` | This machine's months in the handoff copy: each month's folder of day files, and a one-file copy where an earlier devkit published one. The team copy is read by more people, so by default it keeps no longer than the machine | | `audit.retention.floor_months` | `3` | The least any retention may be. Three months covers the time it takes to notice an incident and investigate it, so 3 is also the hard minimum: `dev config validate` refuses 1 or 2 | | `audit.hold` | `false` | A legal hold: `true` stops all pruning on this machine and in the handoff copy | @@ -46,6 +46,49 @@ anyone else gets access to the handoff repository, or before the first published Each machine prunes only its own folder. The folder of a retired machine stays until that cleanup also covers other machines' folders, which is planned and not built yet. +## The handoff copy + +The daily `audit` job publishes each machine's records to the handoff repository one UTC day at a time. GitHub +refuses a pushed file over 100 MB, and from then on every push of the handoff repository, so no published file is +ever over 45 MiB, and no file is rewritten every day. + +```text +audit/ana@m-s9jn9xnz/ + 2026-11.jsonl a one-file copy that devkit 26.11.19 or earlier published: it stays as it is + 2026-11/ + 2026-11-16.jsonl the records after that copy's last byte, to the end of the 16th (UTC) + 2026-11-17.jsonl one file per UTC day + 2026-11-18.held.json a day over 45 MiB: its size, count, and SHA-256, not its records + 2026-11-19.jsonl +``` + +- **One file per closed day.** A day is closed once a record of a later UTC day follows it in the local month file, + or once that month has ended on the machine. The job publishes each closed day once and never rewrites it. The + open day waits for the next run, so a record waits up to about 29 hours to be anchored: the rest of its UTC day, + plus the time to the next 05:00 run. +- **Days are UTC days,** taken from each record's time and kept within the local month file the record was written + to. A record whose clock went back stays in the day it follows, so the day files joined in order are the local + month file, byte for byte, and one chain. +- **A one-file copy stays.** devkit 26.11.19 and earlier published `YYYY-MM.jsonl` whole, every day. Such a copy is + never rewritten nor removed; the day files go on from its last byte. +- **A day over 45 MiB is held.** Its records stay in this machine's local trail, where `dev audit verify` checks them. + `YYYY-MM-DD.held.json` keeps the day's size, record count, and SHA-256, and where the chain stands at its end, so + the days after it still publish and verify on every machine. The job records `audit.publish` as blocked with + `warning` severity, and `dev audit stats` and `dev doctor` name the day, with the command that shows what filled + it: `dev audit stats --since --until `. A day that size is far beyond a heavy day (about 10 MiB), so + look for an action that repeats. + +`dev audit --team`, `dev audit export --team`, `dev audit verify`, and the embargo check read both layouts and count +each record once. A machine still on devkit 26.11.19 or earlier reads the day files too, but its `dev audit verify` +checks each day on its own and reports the first record of each day as not linked: update that machine. + +After an update, a month over 45 MiB shows in `dev audit stats` and `dev doctor` as _not published yet_ until the next +`audit` job publishes it by day. To publish it at once, run: + +```bash +dev jobs run audit +``` + ## Personal data and the GDPR The audit records show what a person did, on which machine, and when, so they are personal data. Developers in the @@ -325,9 +368,9 @@ Refusals, overrides, and configuration changes are recorded at every level, so ` Each record's `hash` is the SHA-256 of its canonical JSON (keys sorted, no spaces, without `hash` itself). Its `prev` is the `hash` of the v2 record before it in the same month file, with any lines between them (v1 records) sealed -into the link. Editing, removing, or inserting a record breaks the chain from that point on. The copy that the daily -`audit` job publishes to the handoff repository is the anchor: each local month file must start with its published -copy and only add to it. +into the link. Editing, removing, or inserting a record breaks the chain from that point on. What the daily `audit` +job publishes to the handoff repository is the anchor: each local month file must start with the files published of +its month, in order, and only add to them. A held day counts by its size and SHA-256. ```bash dev audit verify @@ -335,34 +378,36 @@ dev audit verify ```text ✓ ~/.local/state/devkit/audit/2026-11.jsonl 1786 record(s), 3324 v1 line(s) outside the chain - ✓ ~/Development/.handoff/audit/ana@mac/2026-11.jsonl 0 record(s), 1159 v1 line(s) outside the chain -✓ the chain holds: 1786 record(s) · 1786 not yet published, so not yet anchored + ✓ ~/Development/.handoff/audit/ana@m-s9jn9xnz/2026-11/2026-11-16.jsonl 912 record(s), 3324 v1 line(s) outside the chain + ✓ ~/Development/.handoff/audit/ana@m-s9jn9xnz/2026-11/2026-11-17.jsonl 614 record(s) +✓ the chain holds: 3312 record(s) · 260 not yet published, so not yet anchored ``` -It checks every local month file and every copy in the handoff repository, and exits `0` when the chain holds. On a -problem it prints the file, the line, and the record's id, and exits `1`: +It checks every local month file and every copy in the handoff repository, and exits `0` when the chain holds. A +month published by day is one chain across its one-file copy, when it has one, and its day files, so a day file +removed from the middle breaks the link at the first record of the next one. On a problem it prints the file, the +line, and the record's id, and exits `1`: | Problem | Meaning | | --- | --- | | does not match its hash | The record was changed after it was written | | no message of the developer backs it | A `crew.evidence` record points to no prompt or question tool answer of the developer in the session's transcript | | the transcript shows another answer, match, label, or asked | `dev audit verify` reran the matcher on the question and label in the transcript, against the decision as the session's run holds it, else as its `crew.decision` record keeps it (`options`, `labels`), and the evidence record says otherwise. `asked` is checked while the run still holds the question | -| does not link to the one before it | A record was removed, inserted, or changed before this one | +| does not link to the one before it | A record was removed, inserted, or changed before this one, or a day file before it is missing | | differs from the published copy | Records were changed or removed after they were published | -| unreadable | The month file could not be read | +| differs from what a held day's record says | Records of a day held over 45 MiB were changed or removed after the job recorded that day | +| unreadable | The month file, or a held day's record, could not be read | Some checks cannot run on every record. When a `crew.decision` record kept its options or labels only up to the 300-character limit, verify cannot rebuild that decision: it prints a note marked `!` and still exits `0`, because a -check it cannot run is no evidence of a change. +check it cannot run is no evidence of a change. A held day's records are checked only on the machine that wrote them: +elsewhere, verify prints a note for that day and follows the chain on from where its record says the chain stands. -Records written since the last publish are counted as _not yet published, so not yet anchored_. Every run is itself -recorded as `audit.verify`, with `critical` severity when it fails. The daily job never publishes a local file over a -published copy it no longer extends; it records `audit.publish` as blocked and critical instead. It never publishes a -month file over 45 MiB either, because GitHub refuses files over 100 MB and then every handoff push: that month's copy -stays as it was, the job records `audit.publish` as blocked with `warning` severity, and `dev audit stats` and -`dev doctor` report the publication hold. The size hold does not delete local records: the local trail remains -available under the normal retention policy, and `dev audit verify` checks it. Publication remains paused for the -oversized month. Daily segments are planned, not implemented; no version update is promised to remove this hold. +Records not published yet are counted as _not yet published, so not yet anchored_, and so are the records of a held +day. Every run is itself recorded as `audit.verify`, with `critical` severity when it fails. The daily job never +publishes over a file this machine's month file no longer extends; it records `audit.publish` as blocked and +critical instead, and leaves the published files as they are. How the job splits a month into days, and what it does +with a day over 45 MiB, is in [The handoff copy](#the-handoff-copy). ## Query and export @@ -370,6 +415,7 @@ oversized month. Daily segments are planned, not implemented; no version update ```bash dev audit # the last 7 days, the newest 60 records +dev audit -n 200 --action guard # the newest 200 guard records of the last 7 days dev audit --since 2026-11-01 --until 2026-11-06 --category refusal dev audit --member Tank --severity warning # this severity and above dev audit --grep 'push' --outcome blocked # a regular expression over action, target, detail, and why @@ -380,7 +426,27 @@ dev audit config # the effective settings, the file The filters are `--days`, `--since`, `--until`, `--action` (the start of the action), `--actor` (`user@`, the user alone, or the agent), `-p` or `--project`, `--member`, `--category`, `--severity`, `--outcome`, and `--grep`. `--format` takes -`table` (the default), `json`, or `csv`; `--json` is the same as `--format json`. +`table` (the default), `json`, or `csv`; `--json` is the same as `--format json`. The table shows the newest `-n` +matches (60 by default), and its header counts every match; `json`, `csv`, and `dev audit export` return every match. + +### Query speed + +Cleaning a record for reading is most of a query's time, so devkit checks what it can on the stored record first and +cleans only the records that pass: + +| Filter | Checked on | +| --- | --- | +| `--days`, `--since`, `--until`, `--action` | The stored record | +| `--category`, `--severity`, `--outcome`, `--actor` | The stored record when it is v2, since cleaning never changes these fields; the cleaned record when it is v1 | +| `-p`, `--member`, `--grep` | The cleaned record, since cleaning can change them: a home folder becomes `~` | + +The table view with only time and action filters cleans just the rows it shows. On a month of 91,000 records, the +default `dev audit` shows a week of 51,000 matches in under a second. + +If a query is slow, a filter in the last row of the table, `json`, `csv`, or an export is cleaning every record of +the window. Narrow it with a filter from the first two rows, such as `--days 1` or `--action guard`, and run it again. + +### Export and forwarding `dev audit export` takes the same filters and writes the records in one of four formats: diff --git a/docs/commands.md b/docs/commands.md index 1c099317..8b87953d 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -1076,10 +1076,11 @@ a fresh fetch, that `origin` has nothing you lack, no WIP or fixup commits, a fi | `dev run view [id] [--failed] [--lines N] [--json]` | A run's failing jobs and their failing step (default: the branch's latest run); `--failed` adds the trimmed logs (30 lines). Exits with `1` when a job failed | | `dev run rerun --flaky "test and evidence" [--all-jobs]` | Re-runs the failed jobs of a run, only with a reason for a proven flaky test, which is recorded in `~/.local/state/devkit/flaky.jsonl` and the project's session log | -### `dev release [--version V] [--notes-file F] [--ci-passed] [--sign] [--draft] [--prerelease] [--dry-run] [--why REASON]` +### `dev release [V | --version V] [--notes-file F] [--ci-passed] [--sign] [--draft] [--prerelease] [--dry-run] [--why REASON]` Tags and publishes a release from a clean default branch that is in step with `origin`, by the delivery policy: -the next CalVer version unless `--version` (required for other schemes), version files that agree, local CI evidence, +the next CalVer version unless you name one (`dev release 26.11.20` or `--version 26.11.20`, with or without a +leading `v`; required for other schemes), version files that agree, local CI evidence, CI on GitHub not failing or running, and notes from the CHANGELOG section. It creates the annotated (or signed) tag, pushes it, and creates the GitHub release. A project that releases with release-please or semantic-release is refused. See [Git and GitHub › Releases](git-and-github.md#releases). @@ -1337,7 +1338,10 @@ back): Rebuilds the projects map (`PROJECTS.md`, `TASKS.md`, `ACTIVITY.md`, `registry.json`), the generated blocks of the handoff notes, this machine's presence file and the dashboard, then commits and pushes the handoff repository when -something changed. Hourly (`--scheduled`) and at the end of a session, it first backs up every project's branches +something changed. A sync you run, the hourly one and the one at the end of a session push at once; a background sync +(the hooks' and queued runs) pushes at most once every `sync.push_interval` seconds (default 300), and one background +flusher per Mac pushes what waited, on time. A file over 45 MB is never committed, and `git gc --auto` runs only in +the hourly sync. Hourly (`--scheduled`) and at the end of a session, it first backs up every project's branches that the branch map shows as not backed up, with the checks of `dev backup` and only the commits older than `backup.after_minutes` (default 30: a younger commit may still be amended); `backup.auto: false` turns that off, and `--offline` or `--no-push` skip it. It backs up only the projects whose backup policy is `on` (by default a diff --git a/docs/concepts.md b/docs/concepts.md index 4584e4ee..2eb215cb 100644 --- a/docs/concepts.md +++ b/docs/concepts.md @@ -124,7 +124,7 @@ devkit keeps one hierarchy for everyone who shares a handoff repository: | Level | What it is | Where it lives | Main commands | | --- | --- | --- | --- | -| Portfolio | Every initiative and project | `PROJECTS.md`, `TASKS.md`, `registry.json` | `dev overview`, `dev report`, `dev dashboard` | +| Portfolio | Every initiative and project | `PROJECTS.md`, `TASKS.md`, `registry.json` (this Mac's copy, not in git) | `dev overview`, `dev report`, `dev dashboard` | | Initiative | Projects that work toward one goal: an integration, a platform, a program. Optional | `initiatives//README.md` | `dev initiative`, `dev task -i ` | | Project | One repository | `projects/.md` | `dev status`, `dev task`, `dev note set` | | Work item | One task, feature, bug, or spike, which carries a lock and a changelog | `items//.md` | `dev task add\|start\|done` | @@ -176,7 +176,7 @@ that you, Claude Code and Codex share across sessions, machines, and developers. | `PROJECTS.md` | Live map: initiatives, then every project with stack, branch, state, worktrees, open PRs, last activity, size, attention items, and the canary rate | `dev sync` | | `TASKS.md` | Every open task across projects and initiatives (Now, Next, Later), blocked, and overdue items | `dev sync` | | `ACTIVITY.md` | Sessions and operations of the last 30 days | `dev sync` | -| `registry.json` | The same data, machine-readable (`dev overview --json`, the dashboard) | `dev sync` | +| `registry.json` | The same data, machine-readable (`dev overview --json`, the dashboard); each Mac keeps its own copy, which git ignores | `dev sync` | | `projects/.md` | One handoff note per project | agents, `dev note`, `dev sync` | | `initiatives//` | One folder per initiative: `README.md`, plus `source.md`, `MIGRATION.md`, and `docs/` for adopted programs | member projects, `dev initiative` | | `items//.md` | Work items, one versioned file each | `dev task` only | @@ -186,7 +186,7 @@ that you, Claude Code and Codex share across sessions, machines, and developers. | `policies/.json` | The delivery policy of a project (or the release train of an initiative), versioned with its history | `dev delivery apply` only | | `crew/crew.json` · `crew/README.md` | The team's changes to the crew's roster and RACI, versioned with who and why, and their summary for people | `dev crew set`, `dev crew raci --set` | | `lessons//L-….md` | Lessons from mistakes, versioned; `lessons/archive/` holds forgotten ones, `lessons/usage/@.json` each machine's usage counts | `dev lesson`, `dev sleep` | -| `audit/@/YYYY-MM.jsonl` | Each machine's audit trail | the `audit` job | +| `audit/@/YYYY-MM/YYYY-MM-DD.jsonl` | Each machine's audit trail, one file per closed UTC day; a `YYYY-MM.jsonl` that an earlier devkit published stays beside it (see [The audit trail › The handoff copy](audit.md#the-handoff-copy)) | the `audit` job | | `log/YYYY-MM.md` | Append-only operations log: worktree removals, cleanups, adoptions, imports, restored settings | `dev` | | `.gitattributes` | Merge rules that keep machines from conflicting | `dev install` | @@ -229,7 +229,8 @@ generated from the work items - The **frontmatter** holds status, priority, milestone, due date, tags, and an optional manual `progress`. `dev note set` writes it. -- The **auto block** is regenerated by `dev sync` and at session start. Never edit inside it. +- The **auto block** is regenerated by `dev sync` and at session start, only on a Mac that has the project cloned, + and only when more than its timestamps changed. Never edit inside it. - The **Tasks block** is generated from the work items. Change tasks with `dev task`, never in the note. - The **sections** are kept up to date by the agents with the devkit `handoff` skill, and by you. - The **size budget** is about 150 lines of authored text. `dev doctor` excludes complete generated auto and Tasks diff --git a/docs/configuration.md b/docs/configuration.md index fc6da30b..5e44ce7d 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -338,7 +338,8 @@ See [Git and GitHub](git-and-github.md). | Key | Default | Meaning | | --- | --- | --- | -| `sync.push` | `true` | Push the handoff repository after each sync and each work-item change | +| `sync.push` | `true` | Push the handoff repository to its remote; `false` keeps the commits on this Mac | +| `sync.push_interval` | `300` | Seconds a background `dev sync` lets pass after this Mac's last handoff push before it commits and pushes again (0 to 3,600). Changes made in between wait in the working tree, and one background flush pushes them on time. Task claims and releases, embargoes, the sync that ends a session, the hourly sync, and a `dev sync` you run push at once. `0` pushes on every sync | | `sync.interval_minutes` | `60` | The sync interval that `dev setup` asks for. The `sync` job's schedule is `jobs.sync`; change it with `dev jobs set sync --every 30m` | | `gc.auto` | `true` | The nightly `gc` job applies the safe cleanup; `false` (the wizard's "report only") keeps the job off | | `gc.grace_hours` | `24` | Idle time before a merged or fully contained worktree is removed | diff --git a/docs/jobs-and-audit.md b/docs/jobs-and-audit.md index 9f8dc104..5c00b24c 100644 --- a/docs/jobs-and-audit.md +++ b/docs/jobs-and-audit.md @@ -151,10 +151,13 @@ decision questions are never recorded, and `/Users/` becomes `~`. See [The audit trail › What a record holds](audit.md#what-a-record-holds-and-what-it-never-holds). **Where it lives.** Each machine appends to `~/.local/state/devkit/audit/YYYY-MM.jsonl` and keeps 13 months by -default (`audit.retention.local_months`). Every day at 05:00 the `audit` job copies this month's file and the two -before into the handoff repository as `audit/@/YYYY-MM.jsonl`, in one commit, so the team shares one -history and git keeps it. Set `audit.publish` to `false` to keep the trail on your Mac. Retention, the legal hold, and -what git history keeps are in [The audit trail › Retention](audit.md#retention). +default (`audit.retention.local_months`). Every day at 05:00 the `audit` job publishes the closed UTC days of this +month and the two before into the handoff repository as `audit/@/YYYY-MM/YYYY-MM-DD.jsonl`, one file +per day, each written once, in one commit, so the team shares one history and git keeps it. No file goes past 45 MiB, +below GitHub's 100 MB limit: a day over it stays on the machine and is reported by `dev doctor`. The layout, the +older one-file copies, and held days are in [The audit trail › The handoff copy](audit.md#the-handoff-copy). Set +`audit.publish` to `false` to keep the trail on your Mac. Retention, the legal hold, and what git history keeps are in +[The audit trail › Retention](audit.md#retention). ### Read it diff --git a/docs/teams.md b/docs/teams.md index 14f28401..35add8bc 100644 --- a/docs/teams.md +++ b/docs/teams.md @@ -285,7 +285,8 @@ there is one per scope and month, so concurrent machines never conflict. ## Presence and `dev team` -Each machine writes only its own file, `presence/@.json`, on every sync: its tracked sessions (agent, +Each machine writes only its own file, `presence/@.json`, when its sessions or locks change, and +otherwise at most every 10 minutes: its tracked sessions (agent, project, branch, start time, latest status, progress of the current run, running subagents, turn start, and whether the session is still active) and the locks it holds. A session that has ended is removed before the sync that ends it publishes presence, and a session marked not active is left out wherever presence is read. Presence carries a summary @@ -548,7 +549,7 @@ the rules a newer devkit adds, and two Macs that upgrade only ever add lines: | `log/**` | `union` | The monthly operations log is append-only too | | `.gitattributes` | `union` | The rules file itself, so two Macs that add the same new rule do not conflict | | `presence/*.json` | `ours` | Each machine writes only its own file | -| `PROJECTS.md`, `TASKS.md`, `ACTIVITY.md`, `registry.json` | `ours` | Generated views: the local copy is kept and regenerated after the pull | +| `PROJECTS.md`, `TASKS.md`, `ACTIVITY.md` | `ours` | Generated views: the local copy is kept and regenerated after the pull. `registry.json` is no longer in git: each Mac keeps its own | Work items are separate files, so conflicts are rare. A sync rebases this Mac's commits on the remote's in a private checkout, never in the repository's own, then moves the repository's checkout to the result with `git reset --keep`, @@ -616,7 +617,7 @@ devkit no longer refuses a direct edit, so a wrong one shows only as a conflict | Records | Write them with | | --- | --- | | Files under `items/`, `sessions/`, or `presence/` | `dev task` or `dev handoff --log` | -| `PROJECTS.md`, `TASKS.md`, `ACTIVITY.md`, `registry.json`, or `log/` | Nothing: `dev sync` generates them | +| `PROJECTS.md`, `TASKS.md`, `ACTIVITY.md`, `registry.json` (never in git), or `log/` | Nothing: `dev sync` generates them | | Files under `policies/` | `dev delivery apply` | | Files under `lessons/` | `dev lesson add\|recur\|prevent\|retire` | | A project's note or plans | The session of that project only (section 11 of the global instructions) | diff --git a/lib/devkit/audit.py b/lib/devkit/audit.py index 11abfbb4..1a8ab8df 100644 --- a/lib/devkit/audit.py +++ b/lib/devkit/audit.py @@ -15,10 +15,13 @@ Integrity: each record's `hash` is the SHA-256 of its canonical JSON; its `prev` links it to the record before it in the same month file (lines that are not v2 records are sealed into that link), so an edit, a removal or an insertion breaks the chain. The copy published to the handoff repository is the anchor: a local file must extend it. -`dev audit verify` checks both and reports the first broken link. +`dev audit verify` checks both and reports the first broken link; a month published as daily files is one chain +across them. Where: ~/.local/state/devkit/audit/YYYY-MM.jsonl on this machine (append-only, 0600 in a 0700 folder), published -daily by the `audit` job to the handoff repository as audit/@/YYYY-MM.jsonl. Kept for +daily by the `audit` job to the handoff repository as audit/@/YYYY-MM/YYYY-MM-DD.jsonl, one file per +closed UTC day, each under PUBLISH_LIMIT (a day over it is held: YYYY-MM-DD.held.json says so); a one-file copy +audit/@/YYYY-MM.jsonl that an earlier devkit published stays as it is, and the days go on after it. Kept for audit.retention.local_months here and team_months there, never under floor_months (at least 3), and not pruned at all under audit.hold; the team policy (/policy/audit.json) raises any of them. Pruning the handoff copy removes files from its working copy only: git history keeps every published month. Crew message text, the developer's @@ -31,6 +34,7 @@ from __future__ import annotations import argparse +import calendar import contextlib import contextvars import csv @@ -380,7 +384,7 @@ def _decided(rec: dict) -> dict: "prompt": "action:name?", "push": "", "rebase": "", - "release": "", + "release": "version_word:name?", "report": "", "rm": "paths:name*", "run": "", "run ls": "", "run rerun": "id:name", "run view": "id:name?", @@ -422,7 +426,8 @@ def _decided(rec: dict) -> dict: "--assignee", "--at", "--base", "--body-file", "--branch", "--by", "--category", "--command", "--commit-template", "--generation", "--sha256", "--text-file", "--config", "--context", "--cwd", "--days", "--delay", "--depth", "--due", "--estimate", "--every", "--export", - "--ext", "--fd", "--file", "--files", "--first", "--fold", "--for", "--format", "--from", "--glob", "--hours", + "--ext", "--fd", "--file", "--files", "--first", "--flush-at", "--fold", "--for", "--format", "--from", "--glob", + "--hours", "--initiative", "--interval", "--kind", "--label", "--lang", "--license", "--limit", "--lines", "--max", "--max-per-file", "--member", "--min-severity", "--mode", "--model", "--notes-file", "--only", "--out", "--outcome", "--owner", "--path", "--pr", "--priority", "--project", "--projects", "--provider", @@ -2297,6 +2302,11 @@ def _reclean(r: dict, rx) -> dict: return out +def _v1_id(r: dict, line: bytes = b"") -> str: + """The id a v1 record reads with: it stored none, so its line's hash.""" + return "V1" + hashlib.sha256(line or json.dumps(r, sort_keys=True).encode()).hexdigest()[:24].upper() + + def lift(r: dict, line: bytes = b"", extra=None) -> dict: """A record as schema v2 reads it, cleaned as a record is when it is written today: no secret, message text, approval line or home folder, so no query or export shows them. v2 records keep their fields (`cleaned` when @@ -2309,7 +2319,7 @@ def lift(r: dict, line: bytes = b"", extra=None) -> dict: out, code, raw = outcome_of(r.get("outcome")) cat, sev = kind(r.get("action")) action = str(r.get("action") or "") - rec = {"v": 1, "id": "V1" + hashlib.sha256(line or json.dumps(r, sort_keys=True).encode()).hexdigest()[:24].upper(), + rec = {"v": 1, "id": _v1_id(r, line), "ts": ts, "time": iso(ts), "actor": {k: str(r.get(k) or "") for k in ("user", "host", "agent", "session")}, "action": action, "category": cat, "severity": sev, "target": _field(action, "target", r.get("target") or "", rx, r), @@ -2340,12 +2350,18 @@ def _files(team: bool = False) -> list: return files + (sorted(AUDIT.glob("*.jsonl")) if AUDIT.exists() else []) -def _read(team: bool = False): +def _stored_ts(r: dict) -> float: + """A stored record's time as lift reads it: a v1 record's text time as a number, none as 0.""" + return (r.get("ts") if r.get("v") == V else float(r.get("ts") or 0)) or 0 + + +def _stored(team: bool = False, lo=None, hi=None, action=None, keep=None): + """Every stored record once, not lifted, as (record, line): the first copy of an id read decides, as a published + day repeats this Mac's lines. `lo`, `hi` (epoch) and `action` (a prefix) are checked on the stored time and + action, which lift does not change (a v1 record's as lift maps them); `keep`, on a v2 record only, checks the + fields lift leaves as they are (see _checks). Cleaning is most of a query's time, so a reader lifts only what + passes.""" seen = set() - try: - rx = _extra_rules(settings()["redact"]["extra"]) - except Exception: - rx = [] for f in _files(team): try: data = f.read_bytes() @@ -2358,12 +2374,35 @@ def _read(team: bool = False): continue if not isinstance(r, dict): continue - rec = lift(r, ln, rx) - key = rec["id"] + v2 = r.get("v") == V + key = r["id"] if v2 else _v1_id(r, ln) if key in seen: continue seen.add(key) - yield rec + if lo or hi: + ts = _stored_ts(r) + if (lo and ts < lo) or (hi and ts > hi): + continue + if action and not (r["action"] if v2 else str(r.get("action") or "")).startswith(action): + continue + if keep and v2 and not keep(r): + continue + yield r, ln + + +def _redact_rules() -> list: + """The compiled audit.redact.extra patterns a reader cleans with; none when the settings cannot be read.""" + try: + return _extra_rules(settings()["redact"]["extra"]) + except Exception: + return [] + + +def _read(team: bool = False, lo=None, hi=None, action=None, keep=None): + """Every record once, lifted, of those _stored passes.""" + rx = _redact_rules() + for r, ln in _stored(team, lo, hi, action, keep): + yield lift(r, ln, rx) def when(text: str, end: bool = False): @@ -2378,12 +2417,17 @@ def when(text: str, end: bool = False): raise ValueError(f"“{text}” is not a date: YYYY-MM-DD or YYYY-MM-DDTHH:MM") -def query(since=None, until=None, days=None, action=None, actor_=None, project=None, member=None, category=None, - severity=None, outcome=None, grep=None, team=False) -> list: - """Records that match every filter, oldest first. `severity`: that level and above; `grep`: a regular - expression (any case) over the action, target, detail and why; `member`: a crew member's name or id.""" +def _window(since=None, until=None, days=None) -> tuple: + """(lo, hi) in epoch seconds, None where open: --since (or the last `days`) and --until, a date's whole day.""" lo = when(since) if since else (time.time() - days * 86400 if days else None) - hi = when(until, end=True) if until else None + return lo, (when(until, end=True) if until else None) + + +def _checks(actor_=None, project=None, member=None, category=None, severity=None, outcome=None, grep=None) -> tuple: + """The filters past the time and the action, as two checks of a lifted record -> (same, rest). `same` reads the + fields lift never changes (category, severity, outcome and actor: it cleans text, never these), so it also holds + on a stored v2 record, before lift; `rest` reads the fields cleaning can change (the project, the member and the + text --grep reads: a home folder becomes ~), on the lifted record only.""" want_member = _member(member)[0] if member else None min_sev = SEVERITIES.index(severity) if severity in SEVERITIES else 0 want_out = outcome_of(outcome)[0] if outcome else None @@ -2393,33 +2437,53 @@ def query(since=None, until=None, days=None, action=None, actor_=None, project=N rx = re.compile(grep, re.I) except re.error: rx = re.compile(re.escape(grep), re.I) - out = [] - for r in _read(team): - ts = r.get("ts") or 0 - if (lo and ts < lo) or (hi and ts > hi): - continue - if action and not r["action"].startswith(action): - continue + + def same(r: dict) -> bool: if actor_: a = r.get("actor") or {} if actor_ not in f"{a.get('user')}@{a.get('host')} {a.get('agent')}": - continue - if project and not (r.get("project") == project or str(r.get("project", "")).startswith(project.rstrip("/") + "/")): - continue - if want_member and (r.get("crew") or {}).get("member") != want_member: - continue + return False if category and r.get("category") != category: - continue + return False if min_sev and SEVERITIES.index(r.get("severity", "info")) < min_sev: - continue - if want_out and r.get("outcome") != want_out: - continue - if rx and not rx.search(" ".join(str(r.get(k) or "") for k in ("action", "target", "detail", "why"))): - continue - out.append(r) + return False + return not (want_out and r.get("outcome") != want_out) + + def rest(r: dict) -> bool: + if project and not (r.get("project") == project or str(r.get("project", "")).startswith(project.rstrip("/") + "/")): + return False + if want_member and (r.get("crew") or {}).get("member") != want_member: + return False + return not (rx and not rx.search(" ".join(str(r.get(k) or "") for k in ("action", "target", "detail", "why")))) + + return same, rest + + +def query(since=None, until=None, days=None, action=None, actor_=None, project=None, member=None, category=None, + severity=None, outcome=None, grep=None, team=False) -> list: + """Records that match every filter, oldest first. `severity`: that level and above; `grep`: a regular + expression (any case) over the action, target, detail and why; `member`: a crew member's name or id. The time, + the action and, on a v2 record, the fields lift never changes are checked before a record is lifted.""" + lo, hi = _window(since, until, days) + same, rest = _checks(actor_, project, member, category, severity, outcome, grep) + out = [r for r in _read(team, lo, hi, action, same) if same(r) and rest(r)] # same again: a v1 record, lifted return sorted(out, key=lambda r: r.get("ts") or 0) +def latest(n: int, since=None, until=None, days=None, action=None, actor_=None, project=None, member=None, + category=None, severity=None, outcome=None, grep=None, team=False) -> tuple: + """(how many records match the filters, the newest `n` of them oldest first): what the table view shows, the same + as (len(q), q[-n:]) for q = query(...). With only the time and action filters, it finds the matches on the stored + records and lifts only the ones it returns: a heavy week's table cleans its 60 rows, not the week's 50,000.""" + if actor_ or project or member or category or severity or outcome or grep: + recs = query(since, until, days, action, actor_, project, member, category, severity, outcome, grep, team) + return len(recs), recs[-n:] + lo, hi = _window(since, until, days) + found = sorted(_stored(team, lo, hi, action), key=lambda p: _stored_ts(p[0])) # stable: read order on a tie + rx = _redact_rules() + return len(found), [lift(r, ln, rx) for r, ln in found[-n:]] + + def records(days: float = 7, action: str = None, actor_: str = None, team: bool = False) -> list: """The old reader's API: the last `days`, by action prefix and actor.""" return query(days=days, action=action, actor_=actor_, team=team) @@ -2453,17 +2517,23 @@ def stats(recs: list) -> dict: # --------------------------------------------------------------------------- verify (R2) -def verify_file(path: Path) -> dict: +def verify_file(path: Path, chain: dict = None) -> dict: """The chain of one month file: its first broken link, and what the CHECKS find in the intact records: their - problems (`checks`) and their notes (`notes`, no problem).""" + problems (`checks`) and their notes (`notes`, no problem). `chain` carries the chain in from the file before it, + for a month published as daily files (_verify_parts), and is updated to this file's end: `last` (the hash of the + last v2 record), `tail` (the lines after it), `link` (the `prev` a held day leaves when lines outside the chain + ended it), `carry` (a line the file before ended in the middle of) and `more` (another file follows).""" res = {"path": str(path), "records": 0, "v1": 0, "first": None, "checks": [], "notes": []} + c = chain if chain is not None else {} try: - data = Path(path).read_bytes() + data = c.get("carry", b"") + Path(path).read_bytes() except OSError as e: res["first"] = {"path": str(path), "line": 0, "id": "", "kind": "unreadable", "problem": str(e)} return res - last, tail = "", b"" - for n, raw in enumerate(data.splitlines(keepends=True), 1): + last, tail, link = c.get("last", ""), c.get("tail", b""), c.get("link") + lines = data.splitlines(keepends=True) + carry = lines.pop() if c.get("more") and lines and not lines[-1].endswith((b"\n", b"\r")) else b"" + for n, raw in enumerate(lines, 1): body = raw.rstrip(b"\r\n") try: r = json.loads(body) if body.strip() else None @@ -2471,16 +2541,22 @@ def verify_file(path: Path) -> dict: r = None if isinstance(r, dict) and r.get("v") == V: res["records"] += 1 + # the link it must have; None when a held day left a link and lines outside the chain follow it here + want = seal(last, tail) if link is None else (None if tail else link) + last, tail, link = str(r.get("hash") or ""), b"", None # the chain goes on from this record, intact or not if res["first"]: continue where = {"path": str(path), "line": n, "id": str(r.get("id") or "")} if r.get("hash") != digest(r): res["first"] = {**where, "kind": "edited", "problem": "the record does not match its hash: it was " "changed after it was written"} - elif r.get("prev") != seal(last, tail): + elif want is not None and r.get("prev") != want: res["first"] = {**where, "kind": "unlinked", "problem": "the record does not link to the one before " "it: a record was removed, inserted or changed before it"} else: + if want is None: + res["notes"].append({**where, "kind": "note", "note": "its link to the held day before it cannot " + "be checked here: lines outside the chain come between them"}) for chk in list(CHECKS): try: problem = chk(r, path, n) @@ -2490,14 +2566,126 @@ def verify_file(path: Path) -> dict: res["notes"].append({**where, "kind": "note", "note": str(problem)}) elif problem: res["checks"].append({**where, "kind": "check", "problem": str(problem)}) - last, tail = r["hash"], b"" continue if isinstance(r, dict): res["v1"] += 1 tail += raw + if chain is not None: + chain.update(last=last, tail=tail, link=link, carry=carry) return res +_MONTH = re.compile(r"\d{4}-\d{2}") +_DAY_PART = re.compile(r"(\d{4}-\d{2}-\d{2})(\.jsonl|\.held\.json)") # in a month folder: a day's file, a held day + + +def _parts(where: Path, month: str) -> list: + """What a machine's folder publishes of one month, in chain order -> [(kind, path)]: ("file", the one-file copy + YYYY-MM.jsonl), then per day ("file", YYYY-MM/YYYY-MM-DD.jsonl) or ("held", YYYY-MM/YYYY-MM-DD.held.json). A + held day's record wins over a file of the same day.""" + whole, folder = where / f"{month}.jsonl", where / month + parts = [("file", whole)] if whole.is_file() else [] + days = {} + for p in (folder.iterdir() if folder.is_dir() else ()): + m = _DAY_PART.fullmatch(p.name) + if m and m.group(1).startswith(month + "-") and p.is_file(): + if m.group(2) == ".held.json": + days[m.group(1)] = ("held", p) + else: + days.setdefault(m.group(1), ("file", p)) + return parts + [days[d] for d in sorted(days)] + + +def _held_info(path: Path): + """A held day's record (what _held_day wrote), or None when it cannot be read.""" + try: + info = json.loads(Path(path).read_text()) + except (OSError, ValueError): + return None + ok = isinstance(info, dict) and isinstance(info.get("bytes"), int) and isinstance(info.get("sha256"), str) + return info if ok else None + + +def _verify_parts(parts: list) -> list: + """One machine's month in the handoff repository, verified as one chain across its files -> a result per file, + in order. A held day was never published: the chain goes on from the head its record names, and a note says the + day is checked on its own machine only.""" + out, chain = [], {} + for i, (kind, path) in enumerate(parts): + if kind == "file": + chain["more"] = i + 1 < len(parts) and parts[i + 1][0] == "file" + out.append(verify_file(path, chain)) + continue + res = {"path": str(path), "records": 0, "v1": 0, "first": None, "checks": [], "notes": []} + info = _held_info(path) + if info is None: + res["first"] = {"path": str(path), "line": 0, "id": "", "kind": "unreadable", + "problem": "the record of a held day cannot be read"} + chain = {} + else: + res["notes"].append({"path": str(path), "line": 0, "id": "", "kind": "note", + "note": f"{info.get('day')} is held on its machine ({_mb(info['bytes'])}, over the " + f"{_mb(PUBLISH_LIMIT)} limit for one handoff file): its " + f"{info.get('records', 0)} record(s) are checked there only"}) + ended = bool(info.get("tail_bytes")) # lines outside the chain ended the day: only their seal is known + chain = {"last": str(info.get("head") or ""), "tail": b"", "link": str(info.get("link") or "") if ended + else None} + out.append(res) + return out + + +def _verify_team(root: Path) -> list: + """Every copy in the handoff repository, in path order: a month published as daily files is one chain across + its one-file copy (when it has one) and its days.""" + units, single = {}, [] + for f in sorted(root.rglob("*.jsonl")) + sorted(root.rglob("*.held.json")): + m = _DAY_PART.fullmatch(f.name) + if m and _MONTH.fullmatch(f.parent.name) and m.group(1).startswith(f.parent.name + "-"): + units[str(f.parent.parent / f"{f.parent.name}.jsonl")] = f.parent + elif f.name.endswith(".jsonl"): + single.append(f) + units.update({str(f): f for f in single if str(f) not in units}) + out = [] + for key in sorted(units): + u = units[key] + out += _verify_parts(_parts(u.parent, u.name)) if u.is_dir() else [verify_file(u)] + return out + + +def _v2_count(data: bytes) -> int: + return sum(1 for ln in data.splitlines() if _v2(ln)) + + +def _anchor(f: Path, data: bytes, parts: list): + """How far a local month file is anchored by what this machine published of it -> (offset, records of held + days, problem or None). The parts must match the local bytes in order; the last one may be a copy published + while the month was shorter.""" + off, held_n = 0, 0 + for kind, path in parts: + if kind == "held": + info = _held_info(path) + n = info["bytes"] if info else 0 + if not info or hashlib.sha256(data[off:off + n]).hexdigest() != info["sha256"]: + line = data.count(b"\n", 0, off) + 1 + return off, held_n, {"path": str(f), "line": line, "id": "", "kind": "diverged", + "problem": f"the local file differs from what {core.tilde(path)} records of the " + f"day it held, from line {line}: records were changed or removed " + f"after that day was held"} + off, held_n = off + n, held_n + int(info.get("records") or 0) + continue + try: + p = path.read_bytes() + except OSError as e: + return off, held_n, {"path": str(path), "line": 0, "id": "", "kind": "unreadable", "problem": str(e)} + if not data.startswith(p, off): + line = data.count(b"\n", 0, off) + _diverges(data[off:], p) + return off, held_n, {"path": str(f), "line": line, "id": "", "kind": "diverged", + "problem": f"the local file differs from the published copy {core.tilde(path)} from " + f"line {line}: records were changed or removed after they were published"} + off += len(p) + return off, held_n, None + + def _diverges(local: bytes, published: bytes): """None when the local file extends the published copy, else the first local line that differs (1-based).""" if local.startswith(published): @@ -2514,30 +2702,23 @@ def verify(team: bool = True) -> dict: problem.""" out = {"ok": True, "first": None, "files": [], "records": 0, "unpublished": 0 if team else None} local = sorted(AUDIT.glob("*.jsonl")) if AUDIT.exists() else [] - files = local + ([f for f in sorted((core.HANDOFF / "audit").rglob("*.jsonl"))] - if team and (core.HANDOFF / "audit").exists() else []) + results = [verify_file(f) for f in local] + if team and (core.HANDOFF / "audit").exists(): + results += _verify_team(core.HANDOFF / "audit") problems = [] - for f in files: - r = verify_file(f) + for r in results: out["files"].append(r) out["records"] += r["records"] problems += ([r["first"]] if r["first"] else []) + r["checks"] if team: mine = team_dir() for f in local: - pub = mine / f.name data = f.read_bytes() - if not pub.exists(): - out["unpublished"] += sum(1 for ln in data.splitlines() if _v2(ln)) - continue - p = pub.read_bytes() - line = _diverges(data, p) - if line: - problems.append({"path": str(f), "line": line, "id": "", "kind": "diverged", - "problem": f"the local file differs from the published copy {core.tilde(pub)} from " - f"line {line}: records were changed or removed after they were published"}) - else: - out["unpublished"] += sum(1 for ln in data[len(p):].splitlines() if _v2(ln)) + off, held_n, problem = _anchor(f, data, _parts(mine, f.stem)) + if problem: + problems.append(problem) + else: # a held day's records are anchored nowhere, so they count as not yet published + out["unpublished"] += held_n + _v2_count(data[off:]) out["first"] = problems[0] if problems else None out["problems"] = problems out["notes"] = [n for f in out["files"] for n in f.get("notes") or []] @@ -2547,35 +2728,151 @@ def verify(team: bool = True) -> dict: # --------------------------------------------------------------------------- publish and prune (R2 anchor, R3) -# GitHub refuses a pushed file over 100 MB, and from then on every handoff push, so no month copy is published past -# this. Daily segments are planned; until then, an oversized month's published copy stays as it was. +# GitHub refuses a pushed file over 100 MB, and from then on every handoff push, so no file over this is ever +# published: each month goes out as one file per UTC day, and a single day over it is held (_held_day). PUBLISH_LIMIT = 45 * 1024 * 1024 -HELD_FIX = ("records remain in this machine's local trail under its retention policy; run dev audit verify to " - "check integrity. Publication remains paused above the size limit; daily segments are planned, " - "not yet available") +LIMIT_WHY = "GitHub refuses files over 100 MB, and then every handoff push" def _mb(n: int) -> str: return core.human_kb(n / 1024) -def _held(f: Path, size: int) -> dict: - # a month file over PUBLISH_LIMIT: what the job's record, dev audit stats and dev doctor say about it - pub = team_dir() / f.name - published = pub.stat().st_size if pub.exists() else 0 - return {"month": f.stem, "path": str(f), "bytes": size, "published": published, "limit": PUBLISH_LIMIT, - "text": f"{f.stem} is not published: {_mb(size)} here, over the {_mb(PUBLISH_LIMIT)} limit for a " - f"handoff copy (GitHub refuses files over 100 MB, and then every handoff push); its handoff " - f"copy stays at {_mb(published)}", - "fix": HELD_FIX} +def _pending(f: Path, size: int) -> dict: + # a month over PUBLISH_LIMIT that the audit job has not published by day yet (the first job after the update) + return {"month": f.stem, "day": None, "path": str(f), "bytes": size, "limit": PUBLISH_LIMIT, + "text": f"{f.stem} is not published yet: {_mb(size)} here, over the {_mb(PUBLISH_LIMIT)} limit for one " + f"handoff file ({LIMIT_WHY}), so the audit job publishes it as one file per UTC day", + "fix": "run dev jobs run audit to publish it now; until then its records stay in this machine's local " + "trail. If the job still leaves it, run dev audit verify: it names the published file the month " + "no longer extends"} + + +def _held_text(month: str, day: str, size: int) -> str: + return (f"{day} is not published: {_mb(size)} that day, over the {_mb(PUBLISH_LIMIT)} limit for one handoff " + f"file ({LIMIT_WHY}); the other days of {month} publish as usual") + + +def _held_entry(f: Path, day: str, size: int, records: int) -> dict: + # one day over PUBLISH_LIMIT: what the job's record, dev audit stats and dev doctor say about it + return {"month": f.stem, "day": day, "path": str(f), "bytes": size, "records": records, "limit": PUBLISH_LIMIT, + "text": _held_text(f.stem, day, size), + "fix": f"its {records} record(s) stay in this machine's local trail, where dev audit verify checks them; " + f"to see what filled that day, run dev audit stats --since {day} --until {day}"} def _to_publish() -> list: - return sorted(AUDIT.glob("*.jsonl"))[-3:] if AUDIT.exists() else [] # this machine's last three month files + # this machine's last three month files + return [f for f in sorted(AUDIT.glob("*.jsonl")) if _MONTH.fullmatch(f.stem)][-3:] if AUDIT.exists() else [] + + +def _day_of(line: bytes): + """(the UTC day of a line's record, or None when it has no time; 1 when it is a v2 record, else 0).""" + if not line.startswith(b"{"): + return None, 0 + try: + r = json.loads(line) + except ValueError: + return None, 0 + if not isinstance(r, dict): + return None, 0 + v2 = 1 if r.get("v") == V and isinstance(r.get("hash"), str) else 0 + ts = r.get("ts") + if isinstance(ts, bool) or not isinstance(ts, (int, float)): + return None, v2 + try: + return time.strftime("%Y-%m-%d", time.gmtime(ts)), v2 + except (OverflowError, OSError, ValueError): + return None, v2 + + +def _days(data: bytes, month: str, start: int = 0) -> list: + """A month file's bytes from `start` on, one run per UTC day -> [(day, begin, end, v2 records)]. A run starts at + the first record of a later day. Lines without a time, and records of an earlier day (a clock set back), stay in + the run they follow, so the runs are contiguous and joined they give the bytes back, one chain. Days stay within + the file's month, which is the local one: a record of a late evening can carry the next month's UTC date. Lines + before the first record with a time join its run; with no such record there is no run yet.""" + y, m = int(month[:4]), int(month[5:7]) + lo, hi = f"{month}-01", f"{month}-{calendar.monthrange(y, m)[1]:02d}" + runs, day, begin, n, pos = [], None, start, 0, start + for line in data[start:].splitlines(keepends=True): + d, v2 = _day_of(line) + if d is not None: + d = min(max(d, lo), hi) + if day is None: + day = d + elif d > day: + runs.append((day, begin, pos, n)) + day, begin, n = d, pos, 0 + n += v2 + pos += len(line) + if day is not None: + runs.append((day, begin, pos, n)) + return runs + + +def _chain_end(data: bytes, end: int): + """(the hash of the last v2 record before byte `end`, the bytes after it up to `end`): where the chain stands.""" + e = end + while e > 0: + s = data.rfind(b"\n", 0, e - 1) + 1 + r = _v2(data[s:e]) + if r is not None: + return r["hash"], data[e:end] + e = s + return "", data[:end] + + +def _held_day(data: bytes, day: str, begin: int, end: int, records: int) -> dict: + """What the handoff copy keeps of a day over PUBLISH_LIMIT instead of its records: its size, count and SHA-256, + which anchor it on this machine, and where the chain stands at its end, so verify goes on to the next day.""" + head, tail = _chain_end(data, end) + return {"v": 1, "day": day, "bytes": end - begin, "records": records, + "sha256": hashlib.sha256(data[begin:end]).hexdigest(), "head": head, "link": seal(head, tail), + "tail_bytes": len(tail), "limit": PUBLISH_LIMIT} + + +def _write(target: Path, data: bytes): + target.parent.mkdir(parents=True, exist_ok=True) + tmp = target.with_name(f".{target.name}.{os.getpid()}.tmp") + tmp.write_bytes(data) + os.replace(tmp, target) + + +def _published_bytes(parts: list) -> int: + total = 0 + for kind, path in parts: + info = _held_info(path) if kind == "held" else None + total += info["bytes"] if info else (path.stat().st_size if kind == "file" else 0) + return total + + +def _held_days(f: Path, size: int) -> list: + """The days of a month published by day that are over PUBLISH_LIMIT: those held, and those not published yet + (the open day too), read from where the published files end, so dev doctor reads no more than that.""" + parts = _parts(team_dir(), f.stem) + out = [] + for kind, path in parts: + info = _held_info(path) if kind == "held" else None + if info: + out.append(_held_entry(f, str(info.get("day") or path.name[:10]), info["bytes"], + int(info.get("records") or 0))) + done = _published_bytes(parts) + if size - done <= PUBLISH_LIMIT: + return out + try: + with open(f, "rb") as fh: + fh.seek(done) + rest = fh.read() + except OSError: + return out + return out + [_held_entry(f, day, end - begin, n) for day, begin, end, n in _days(rest, f.stem) + if end - begin > PUBLISH_LIMIT] def held() -> list: - # the month files the audit job leaves unpublished because they passed PUBLISH_LIMIT + """What the audit job leaves unpublished because of PUBLISH_LIMIT: a month over it that the job has not + published by day yet, and each day over it.""" if not settings()["publish"]: return [] out = [] @@ -2584,47 +2881,70 @@ def held() -> list: size = f.stat().st_size except OSError: continue - if size > PUBLISH_LIMIT: - out.append(_held(f, size)) + if (team_dir() / f.stem).is_dir(): + out += _held_days(f, size) + elif size > PUBLISH_LIMIT: + out.append(_pending(f, size)) return out def publish_checks() -> list: - # dev doctor's rows (group, name, ok, detail, fix): one per held month, else one that passes; none when publish - # is off + # dev doctor's rows (group, name, ok, detail, fix): one per month or day held, else one that passes; none when + # publish is off if not settings()["publish"]: return [] rows = [("Automation", "audit handoff copy", False, h["text"], h["fix"]) for h in held()] + daily = [f.stem for f in _to_publish() if (team_dir() / f.stem).is_dir()] return rows or [("Automation", "audit handoff copy", True, - f"every month under the {_mb(PUBLISH_LIMIT)} limit for a handoff copy", "")] + f"every handoff file under the {_mb(PUBLISH_LIMIT)} limit" + + (f"; {', '.join(daily)} published as one file per UTC day" if daily else ""), "")] + + +def _publish_days(f: Path, dest: Path) -> list: + """Publish a month file as one file per UTC day in /YYYY-MM/, after the one-file copy an earlier devkit + published (which stays as it is). Only closed days go out: a day is closed once a record of a later day follows + it, or once the month has ended here. Each is written once; a day over PUBLISH_LIMIT is held, and its .held.json + keeps the chain going for the days after it. A local file that no longer extends what was published is never + published over it. -> files changed.""" + parts = _parts(dest, f.stem) + data = f.read_bytes() + _, _, problem = _anchor(f, data, parts) + if problem: + record("audit.publish", core.tilde(f), f"not published: {problem['problem']}; run dev audit verify", + "blocked", severity="critical") + return [] + folder = dest / f.stem + folder.mkdir(parents=True, exist_ok=True) # this month is published by day, even before its first day closes + whole = dest / f.name + runs = _days(data, f.stem, whole.stat().st_size if whole.is_file() else 0) + if runs and f.stem >= time.strftime("%Y-%m"): + runs.pop() # the open day: a record may still join it + changed = [] + for day, begin, end, n in runs: + seg, stub = folder / f"{day}.jsonl", folder / f"{day}.held.json" + if end - begin > PUBLISH_LIMIT: + info = _held_day(data, day, begin, end, n) + old = _held_info(stub) + if old and (old.get("bytes"), old.get("sha256")) == (info["bytes"], info["sha256"]): + continue + _write(stub, (json.dumps(info, indent=1) + "\n").encode()) + changed.append(stub) + record("audit.publish", core.tilde(f), _held_text(f.stem, day, end - begin), "blocked", + severity="warning") + elif not (seg.is_file() and seg.stat().st_size == end - begin): # the anchor matched what is there + _write(seg, data[begin:end]) + changed.append(seg) + return changed def publish() -> list: - """Copy this machine's last three month files into the handoff repository (audit/@/). A local file - that no longer extends its published copy is never published over it, and one over PUBLISH_LIMIT is not - published at all (its copy stays as it was). -> files changed.""" + """Publish this machine's last three month files into the handoff repository (audit/@/), one file + per UTC day (_publish_days). -> files changed.""" if not settings()["publish"] or not AUDIT.exists(): return [] dest, changed = team_dir(), [] for f in _to_publish(): - target = dest / f.name - size = f.stat().st_size # measured before reading, so a held file is never loaded on the daily run - if size > PUBLISH_LIMIT: - record("audit.publish", core.tilde(f), _held(f, size)["text"], "blocked", severity="warning") - continue - data = f.read_bytes() - old = target.read_bytes() if target.exists() else b"" - if old == data: - continue - if old and not data.startswith(old): - record("audit.publish", core.tilde(f), f"not published: it no longer extends {core.tilde(target)} " - f"(line {_diverges(data, old)}); run dev audit verify", "blocked", severity="critical") - continue - target.parent.mkdir(parents=True, exist_ok=True) - tmp = target.with_name(f".{target.name}.{os.getpid()}.tmp") - tmp.write_bytes(data) - os.replace(tmp, target) - changed.append(target) + changed += _publish_days(f, dest) return changed @@ -2643,6 +2963,9 @@ def _plan_prune(now: float, cfg: dict) -> dict: mine = team_dir() team = [f for f in sorted(mine.glob("*.jsonl")) if month.fullmatch(f.stem) and f.stem < tcut] \ if mine.exists() and not cfg["hold"] else [] + if mine.exists() and not cfg["hold"]: # the months published by day: every file of the month's folder + team += [p for d in sorted(mine.iterdir()) if d.is_dir() and month.fullmatch(d.name) and d.name < tcut + for p in sorted(d.iterdir()) if p.is_file()] if not cfg["hold"]: team += [f for d in _former_team_dirs() for f in sorted(d.glob("*.jsonl")) if month.fullmatch(f.stem) and f.stem < tcut and _this_macs_copy(f)] @@ -2703,13 +3026,17 @@ def prune(now: float = None) -> dict: except OSError: continue out["team"].append(f) + for d in sorted({f.parent for f in out["team"] if _MONTH.fullmatch(f.parent.name)}): + with contextlib.suppress(OSError): + d.rmdir() # a month's folder, once its days are gone if out["removed"] or out["team"]: parts = [] if out["removed"]: parts.append(f"removed {len(out['removed'])} file(s), {out['records']} record(s) here: " f"{', '.join(out['removed'])}; kept {r['local_months']} month(s) (from {plan['keeps_from']})") if out["team"]: - parts.append(f"removed {len(out['team'])} handoff copy(ies): {', '.join(f.stem for f in out['team'])}; " + months = sorted({f.name[:7] for f in out["team"]}) + parts.append(f"removed {len(out['team'])} handoff file(s) of {', '.join(months)}; " f"kept {r['team_months']} month(s) (from {plan['team_keeps_from']})") record("audit.prune", "local and team copies", "; ".join(parts), "ok", count=out["records"]) return out @@ -2736,7 +3063,7 @@ def config_report(now: float = None) -> dict: cfg = settings() local = sorted(AUDIT.glob("*.jsonl")) if AUDIT.exists() else [] mine = team_dir() - team = sorted(mine.glob("*.jsonl")) if mine.exists() else [] + team = sorted(mine.rglob("*.jsonl")) if mine.exists() else [] # one-file copies and the days of each month plan = _plan_prune(now, cfg) at = None try: @@ -2913,7 +3240,9 @@ def add_arguments(p: argparse.ArgumentParser) -> argparse.ArgumentParser: p.add_argument("--format", help="table, json or csv; export: jsonl, csv, ocsf or cef") p.add_argument("--json", action="store_true", help="the same as --format json") p.add_argument("-o", "--out", help="export: write to this file (0600) instead of the terminal") - p.add_argument("-n", "--lines", type=int, default=60) + p.add_argument("-n", "--lines", type=int, default=60, + help="table: show the newest N matches (default 60); the header counts every match, and json, " + "csv and export return them all") p.add_argument("--publish", action="store_true", help=argparse.SUPPRESS) # the audit job p.add_argument("--quiet", action="store_true") return p @@ -2965,7 +3294,15 @@ def cmd_audit(a) -> int: return 0 if act == "config": return _cmd_config(a, ui) - recs = query(**_filters(a)) + fmt = "json" if a.json else (a.format or "table") + if act != "stats" and fmt not in ("table", "json", "csv"): + ui.err("--format takes table, json or csv (export: dev audit export --format jsonl|csv|ocsf|cef)") + return 2 + if act != "stats" and fmt == "table": # the newest -n rows, and the count of every match + total, recs = latest(a.lines, **_filters(a)) + else: + recs = query(**_filters(a)) + total = len(recs) except ValueError as e: ui.err(str(e)) return 2 @@ -2984,10 +3321,6 @@ def cmd_audit(a) -> int: print(ui.table([[d] + [row.get(c, 0) for c in cats] for d, row in sorted(st["days"].items())], ["DAY"] + [c.upper() for c in cats])) return 0 - fmt = "json" if a.json else (a.format or "table") - if fmt not in ("table", "json", "csv"): - ui.err("--format takes table, json or csv (export: dev audit export --format jsonl|csv|ocsf|cef)") - return 2 if fmt == "json": print(json.dumps(recs, indent=1, ensure_ascii=False)) return 0 @@ -2996,8 +3329,8 @@ def cmd_audit(a) -> int: return 0 f = _filters(a) span = f"last {f['days']:g} days" if f["days"] else " – ".join(x for x in (a.since or "", a.until or "") if x) - print(ui.section(f"Audit · {span}" + (" · team" if a.team else "") + f" · {len(recs)} record(s)")) - for r in recs[-a.lines:]: + print(ui.section(f"Audit · {span}" + (" · team" if a.team else "") + f" · {total} record(s)")) + for r in recs: bad = r.get("outcome") in ("blocked", "failed") print(f" {ui.dim(core.fmt_ts(r['ts']))} {(ui.red if bad else ui.cyan)(r.get('action', '')[:28]):<28} " f"{r.get('target', '')[:70]} {ui.dim(_who(r))}" + (f" {ui.red(r['outcome'])}" if bad else "")) @@ -3022,7 +3355,7 @@ def _cmd_verify(a, ui) -> int: if len(res["problems"]) > 1: print(ui.dim(f" and {len(res['problems']) - 1} more problem(s) in other files or checks")) for n in res["notes"]: - print(f" {ui.WARN} {core.tilde(n['path'])} line {n['line']}: {n['note']}") + print(f" {ui.WARN} {core.tilde(n['path'])}" + (f" line {n['line']}" if n["line"] else "") + f": {n['note']}") record("audit.verify", f"{len(res['files'])} file(s)", "the chain holds" if res["ok"] else f"{res['first']['kind']} at {core.tilde(res['first']['path'])}:{res['first']['line']}", "ok" if res["ok"] else "failed", count=res["records"], diff --git a/lib/devkit/branches.py b/lib/devkit/branches.py index 35bb7186..d244421b 100644 --- a/lib/devkit/branches.py +++ b/lib/devkit/branches.py @@ -1074,7 +1074,7 @@ def cmd_embargo(a) -> int: return 0 audit.record("git.embargo", b, "lifted" + (f" (it was: {old.get('why')})" if old.get("why") else ""), "ok", project=pid, branch=b, category="security", severity="notice") - _share(b) + _push_embargo() print(f"{ui.OK} {b}: embargo lifted · the next backup may push it (dev backup {b})") return 0 why = (a.why or "").strip() @@ -1092,7 +1092,7 @@ def cmd_embargo(a) -> int: record_tips(pid, {b: tip}) audit.record("git.embargo", b, f"set: {why}" + (f' (until "{until}")' if until else ""), "ok", project=pid, branch=b, commit=tip, category="security", severity="notice") # the trail keeps it (B2a) - _share(b) + _push_embargo() on_remote = [x for x in core.gitout(top, "for-each-ref", "--format=%(refname:short)", f"refs/remotes/*/{b}").splitlines() if x] print(f"{ui.OK} {b} is embargoed" + (f' until "{until}"' if until else "") + ": dev backup, dev sync and dev push " @@ -1105,6 +1105,21 @@ def cmd_embargo(a) -> int: return 0 +def _push_embargo() -> None: + """Commit and push the handoff note now, without waiting for sync.push_interval, so every machine sees an embargo + (or its lift) before its next backup. When the push does not reach the remote, say so: the next dev sync tries + again.""" + try: + from . import cli + result = cli.commit_push(push=(core.CFG.get("sync") or {}).get("push", True), quiet=True, urgent=True, + reason="embargo") + except Exception: # never let the push break the embargo, which is already in the note + result = "failed" + if result == "failed": + print(f" {ui.WARN} the handoff repository did not reach its remote, so other machines do not see this yet; " + f"dev sync pushes it", file=sys.stderr) + + def _share(branch: str, what: str = "embargo") -> None: """Commit and push the handoff note soon, so every machine sees the embargo (or the answer) before its next backup.""" diff --git a/lib/devkit/bugs.py b/lib/devkit/bugs.py index c4aa8d76..e41d0321 100644 --- a/lib/devkit/bugs.py +++ b/lib/devkit/bugs.py @@ -2587,14 +2587,33 @@ def _digest(payload) -> str: .encode()).hexdigest() +def _old_format(item: dict) -> bool: + """An item an older devkit queued: it has no record of where it came from (capture provenance), so no sync sends + it, approved or not.""" + return item.get("legacy_version") != 2 + + +def old_format_problem(item_id) -> str: + return (f"queued by an older devkit without the record of where it came from, so it is never sent; " + f"`dev bug drop {item_id}` removes it") + + def pending() -> list: - """The items held for the developer's review (_needs_review), oldest first, each as it would be sent, with - `approved` True when the developer approved its exact payload and `consent` True when it waits only for their - consent to the current text (_awaits_consent).""" + """The items held for the developer's review (_needs_review) and the old-format items (_old_format), oldest + first, each as it would be sent, with `sendable` False for an old-format item (its `problem` says why and how to + remove it), `approved` True when a sendable item's exact payload was approved and `consent` True when it waits + only for the developer's consent to the current text (_awaits_consent).""" approvals = core.read_json(BUGS / "approvals.json", {}) or {} - return [{**it, "approved": approvals.get(str(it.get("id"))) == _digest(it.get("payload")), - "consent": _awaits_consent(it)} - for it in map(_load_item, map(str, _item_ids())) if it and _needs_review(it)] + out = [] + for it in map(_load_item, map(str, _item_ids())): + if not it or not (_old_format(it) or _needs_review(it)): + continue + sendable = not _old_format(it) + out.append({**it, "sendable": sendable, + "approved": sendable and approvals.get(str(it.get("id"))) == _digest(it.get("payload")), + "consent": sendable and _awaits_consent(it), + **({} if sendable else {"problem": old_format_problem(it.get("id"))})}) + return out def waiting_for_consent() -> int: @@ -2626,6 +2645,8 @@ def approve(item_id: str) -> None: item = _load_item(item_id) if item is None: raise KeyError(item_id) + if _old_format(item): # an approval would send nothing: say so instead of promising it + raise ValueError(f"item {int(item_id)} cannot be sent: {old_format_problem(int(item_id))}") path = BUGS / "approvals.json" with core.file_lock(path, COMMAND_WAIT) as got: if not got: @@ -3317,8 +3338,8 @@ def _flush_legacy(client=None, now: float = None, *, limit: int = 50, scan_limit processed = 0 for item in items: p = item.get("payload") if isinstance(item.get("payload"), dict) else {} - if item.get("legacy_version") != 2: - item.update(state="quarantined", held=True, problem="legacy envelope has no capture provenance") + if _old_format(item): + item.update(state="quarantined", held=True, problem=old_format_problem(item.get("id"))) _save_item(item) counts["held"] += 1 continue @@ -4351,7 +4372,8 @@ def status_line(now: float = None): otherwise.""" now = time.time() if now is None else now waiting = pending() - held = [it for it in waiting if not it.get("approved") and not it.get("consent")] + old = sum(1 for it in waiting if not it["sendable"]) + held = [it for it in waiting if it["sendable"] and not it.get("approved") and not it.get("consent")] consent_waits = consent_note(sum(1 for it in waiting if it.get("consent"))) midnight = time.mktime(time.localtime(now)[:3] + (0, 0, 0, 0, 0, -1)) hit = {o.get("fingerprint") for o in occurrences() if isinstance(o.get("ts"), (int, float)) and o["ts"] >= midnight} @@ -4366,6 +4388,9 @@ def status_line(now: float = None): if held: parts.append(f"{len(held)} item{'s wait' if len(held) != 1 else ' waits'} for your review; " f"`dev bug send ` sends one") + if old: + parts.append(f"{old} old-format report{'s' if old != 1 else ''} cannot be sent: `dev bug pending` lists " + f"{'them' if old != 1 else 'it'}, `dev bug drop ` removes one") if consent_waits: parts.append(consent_waits) later = limit_note(now) @@ -4376,7 +4401,7 @@ def status_line(now: float = None): if not parts: return None return {"text": "devkit's bug registry: " + " · ".join(parts), - "command": "dev bug pending" if held or consent_waits or later else "dev bug ls --local"} + "command": "dev bug pending" if held or old or consent_waits or later else "dev bug ls --local"} def outbox_status(now=None): diff --git a/lib/devkit/cli.py b/lib/devkit/cli.py index 5b5680fa..244397b2 100644 --- a/lib/devkit/cli.py +++ b/lib/devkit/cli.py @@ -6,6 +6,7 @@ import argparse import contextlib import json +import math import os import re import shlex @@ -178,44 +179,219 @@ def _state(co): return ui.green(s) if s == "clean" else ui.yellow(s) -def commit_push(push=True, quiet=False): - """Commit what changed in the handoff repository and push it. A rebase left stopped is aborted first, a pull - settles every conflict in a private checkout (work.rebase_fetched), and every failure is recorded in - handoff-push-failed.json, which `dev status` shows until a push succeeds. The commit, the fetch and the push hold - work._repo_lock; the rebase holds the notes lock first, so it runs after that lock is released.""" +# --------------------------------------------------------------------------- the handoff push (batched) +# A background `dev sync` runs every 30-90 s per Mac. It still writes the handoff working tree each time, but it +# commits and pushes only when the push is due: `sync.push_interval` seconds after this Mac's last push (0: every +# sync), or at once when the caller is urgent (an embargo, the sync that ends a session, the scheduled one, one a +# person runs). A change that waits is never stranded: the first wait starts one detached `dev sync --flush-at +# ` (flush_handoff), which pushes it on time. STATE/handoff-push.json keeps {repo, last_push, deferred_since, +# flusher, flush_at, held}, read and written under work._repo_lock. + +FLUSH_GRACE = 900 # seconds past its time that a recorded flusher still counts as at work (its push runs then) +FLUSH_ROUNDS = 12 # rounds a flusher pushes while changes keep coming (an hour at the default interval) +FLUSH_MAX_WAIT = 3600 # the longest one round waits: the hourly sync pushes too + + +def _push_state_file() -> Path: + return core.STATE / "handoff-push.json" + + +def _push_state(root: Path) -> dict: + """The pusher's state for the handoff repository at `root`: a state another repository left (handoff_dir moved) + counts as none, so its pushes never delay this one's.""" + s = core.read_json(_push_state_file(), {}) + return s if isinstance(s, dict) and s.get("repo") == str(root) else {"repo": str(root)} + + +def _save_push_state(s: dict) -> None: + f = _push_state_file() + try: + f.parent.mkdir(parents=True, exist_ok=True) + core.replace_text(f, json.dumps(s, sort_keys=True) + "\n") + except OSError: + pass + + +def push_interval() -> int: + """sync.push_interval: the seconds a background sync lets pass after this Mac's last push before it pushes again + (0: it pushes on every sync).""" + v = (CFG.get("sync") or {}).get("push_interval", 300) + return min(int(v), 3600) if isinstance(v, (int, float)) and not isinstance(v, bool) and v >= 0 else 300 + + +def _handoff_changes(root: Path) -> tuple: + """The handoff repository's changes not committed yet -> (paths, held): `held` lists (path, bytes) of each file + over the size a handoff file may have (audit.PUBLISH_LIMIT, 45 MB): GitHub refuses a file over 100 MB, and + then every later push of every Mac.""" + from . import audit + paths, held = [], [] + parts = core.gitout(root, "status", "--porcelain", "-z", "--untracked-files=all").split("\0") + i = 0 + while i < len(parts): + entry, i = parts[i], i + 1 + if len(entry) < 4: + continue + code, path = entry[:2], entry[3:] + if "R" in code or "C" in code: # a rename or copy names its source next + i += 1 + try: + size = os.lstat(root / path).st_size + except OSError: # deleted + size = 0 + if size > audit.PUBLISH_LIMIT: + held.append((path, size)) + else: + paths.append(path) + return paths, held + + +def _ahead(root: Path) -> int: + n = core.gitout(root, "rev-list", "--count", "@{u}..HEAD") + return int(n) if n.isdigit() else 0 + + +def _waiting(root: Path) -> bool: + """Is something on this Mac that the remote does not have yet: a change to commit, or a commit to push?""" + return bool(_handoff_changes(root)[0]) or _ahead(root) > 0 + + +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.""" 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)) + else: + core.git(root, "add", "-A") + known = st.get("held") if isinstance(st.get("held"), dict) else {} + for path, size in held: + if path in known: + continue + why = (f"held: {core.human_kb(size / 1024)} is over the {core.human_kb(audit.PUBLISH_LIMIT / 1024)} a handoff " + "file may have (GitHub refuses a file over 100 MB, and then every push); it stays on this Mac, " + "not committed") + audit.record("handoff.push", path, why, "blocked", severity="critical") + if not quiet: + ui.warn(f"handoff repository: {path} {why}. Move it out of {tilde(root)} or make it smaller.") + st["held"] = {p: s for p, s in held} + if core.git(root, "diff", "--cached", "--quiet")[0] == 0: + return False + n = len(core.gitout(root, "diff", "--cached", "--name-only").splitlines()) + m = identity.machine() # the hostname a person knows, and the id presence and locks name the Mac by + core.git(root, *work.NO_AUTO_GC, "commit", "-q", "-m", f"sync: {n} file(s) from " + + (m.label if m.label == m.id else f"{m.label} ({m.id})")) + return True + + +def _running(pid) -> bool: + try: + os.kill(int(pid), 0) + return True + except PermissionError: + return True + except (OSError, TypeError, ValueError): + return False + + +def _spawn_flusher(at: int): + """Start `dev sync --quiet --flush-at ` detached, as work.request_sync starts a queued sync. -> its pid, or + None when it did not start (DEVKIT_NO_AUTOSYNC: that process asked for no background sync).""" + import subprocess + if os.environ.get("DEVKIT_NO_AUTOSYNC"): + return None + log = core.STATE / "logs" / "sync.log" + try: + log.parent.mkdir(parents=True, exist_ok=True) + out = open(log, "a") + except OSError: + out = subprocess.DEVNULL + try: + p = subprocess.Popen([sys.executable, "-I", "-S", str(core.release_home() / "bin" / "dev"), "sync", "--quiet", + "--flush-at", str(int(at))], stdin=subprocess.DEVNULL, stdout=out, stderr=out, + start_new_session=True, close_fds=True) # isolated, as its shebang runs it + return p.pid + except OSError: + return None + finally: + if out is not subprocess.DEVNULL: + out.close() # the child holds its own copy of the log + + +def _defer(root: Path, st: dict) -> str: + """A push that is not due yet, under work._repo_lock: leave the changes as they are, and make sure one flusher + waits for the time the push is due. -> "deferred", or "nothing" when nothing waits.""" + if not _waiting(root): + return "nothing" + now = time.time() + st["deferred_since"] = st.get("deferred_since") or int(now) + pid, at = st.get("flusher"), st.get("flush_at") or 0 + if not (pid and _running(pid) and now < float(at) + FLUSH_GRACE): + at = int(math.ceil(float(st.get("last_push") or now) + push_interval())) + st.update(flusher=_spawn_flusher(at), flush_at=at) + _save_push_state(st) + return "deferred" + + +def _pushed(root: Path) -> None: + """After a due push (or a fetch that found nothing to push): when it happened, and whether anything still waits.""" + from . import work + with work._repo_lock() as got: + if not got: + return + st = _push_state(root) + st["last_push"] = round(time.time(), 3) + if not _waiting(root): + st["deferred_since"] = None + _save_push_state(st) + + +def commit_push(push: bool = True, quiet: bool = False, urgent: bool = False, reason: str = "") -> str: + """Commit what changed in the handoff repository and push it, when the push is due: `urgent`, or no push from this + Mac for sync.push_interval seconds. Otherwise the changes stay as they are and one detached flusher pushes them + on time (`_defer`); nothing is recorded for a wait. A file over the size limit is never committed + (`_commit_handoff`). A rebase left stopped is aborted first, a pull settles every conflict in a private checkout + (work.rebase_fetched), and every failure is recorded in handoff-push-failed.json, which `dev status` shows until a + push succeeds. The commit, the fetch and the push hold work._repo_lock; the rebase holds the notes lock first, so + it runs after that lock is released. `reason`: why it pushes (the audit record says it). + -> "pushed" | "committed" (no remote, or push off) | "deferred" | "nothing" | "failed".""" + from . import audit, work root = work.HANDOFF # the repository work.pull_rebase works on, read now (tests point it elsewhere) if not (root / ".git").exists(): - return + return "nothing" failed = work.push_failed_file() with work._repo_lock() as got: if not got: if not quiet: ui.warn("handoff sync skipped: another devkit process is using the handoff repository") - return + return "failed" work.recover_rebase("dev sync") - core.git(root, "add", "-A") - rc, _, _ = core.git(root, "diff", "--cached", "--quiet") - if rc != 0: - n = len(core.gitout(root, "diff", "--cached", "--name-only").splitlines()) - m = identity.machine() # the hostname a person knows, and the id presence and locks name the Mac by - core.git(root, "commit", "-q", "-m", f"sync: {n} file(s) from " + - (m.label if m.label == m.id else f"{m.label} ({m.id})")) - if not push or not core.gitout(root, "remote"): - return - core.git(root, "fetch", "-q", "origin", timeout=60) + remote = bool(push) and bool(core.gitout(root, "remote")) + st = _push_state(root) + last = float(st.get("last_push") or 0) + if remote and not urgent and push_interval() and 0 <= time.time() - last < push_interval(): + return _defer(root, st) + committed = _commit_handoff(root, st, quiet) + _save_push_state(st) + if not remote: + return "committed" if committed else "nothing" + core.git(root, *work.NO_AUTO_GC, "fetch", "-q", "origin", timeout=60) ok, err = work.rebase_fetched() ahead = core.gitout(root, "rev-list", "--count", "@{u}..HEAD") + result = "nothing" if ok else "failed" if ok and ahead not in ("", "0"): ok, err = work.push_handoff(timeout=120) if not ok: # someone pushed in between: rebase on it and try once more ok, err = work.pull_rebase() ok, err = work.push_handoff(timeout=120) if ok else (False, err) if ok: - audit.record("handoff.push", core.handoff_repo(), f"{ahead} commit(s)") + audit.record("handoff.push", core.handoff_repo(), f"{ahead} commit(s)" + (f" · {reason}" if reason else "")) if failed.exists(): failed.unlink() + result = "pushed" else: + result = "failed" audit.record("handoff.push", core.handoff_repo(), err[:300], "failed") failed.write_text(json.dumps({"ts": int(time.time()), "error": err[:300]})) try: # each live session hears of it once, with its next wake or hook @@ -226,8 +402,63 @@ def commit_push(push=True, quiet=False): "the next dev sync tries again") except Exception: pass + _pushed(root) if not ok and not quiet: ui.warn(f"handoff push failed: {err}") + return result + + +def flush_handoff(at: float, quiet: bool = True, clock=time.time, sleep=time.sleep) -> str: + """`dev sync --flush-at `: wait until `at`, then commit and push what waited (commit_push, urgent). One per + Mac: a second flusher leaves at once (the `handoff-flush` lock). While changes keep coming it waits one more + interval after each push, up to FLUSH_ROUNDS times; it gives the lock back under work._repo_lock, so a sync that + defers right after it ends finds no flusher recorded and starts a new one. -> the last push's result.""" + from . import work + root, result = work.HANDOFF, "nothing" + flush = core.Lock("handoff-flush") + if not flush.__enter__(): + return "nothing" + try: + target = float(at) + for _ in range(FLUSH_ROUNDS): + wait = min(max(0.0, target - clock()), FLUSH_MAX_WAIT) + if wait > 0: + sleep(wait) + if (root / ".git").exists() and _waiting(root): + result = commit_push(push=CFG["sync"].get("push", True), quiet=quiet, urgent=True, reason="flush") + with work._repo_lock() as got: + if not got: + break + st = _push_state(root) + if not (root / ".git").exists() or not _waiting(root): + if st.get("flusher") in (os.getpid(), None): + st.update(flusher=None, flush_at=None) + _save_push_state(st) + flush.__exit__(None, None, None) + return result + target = float(st.get("last_push") or clock()) + push_interval() + st.update(flusher=os.getpid(), flush_at=int(math.ceil(target))) + _save_push_state(st) + finally: + flush.__exit__(None, None, None) + return result + + +def _sync_handoff(a) -> str: + """The handoff commit and push that end a `dev sync`. Urgent (no wait for sync.push_interval): the sync that ends a + session (--finish), the scheduled one, and one a person runs (no --session, not queued with --delay); a hook's + sync and a queued one wait. The scheduled sync then lets git pack the repository (`git gc --auto`, never + --prune=now): the only place devkit does. -> commit_push's result.""" + person = not (a.session or getattr(a, "delay", 0)) + urgent = bool(a.finish or a.scheduled or person) + reason = "finish" if a.finish else "scheduled" if a.scheduled else "dev sync" if person else "" + result = commit_push(push=CFG["sync"].get("push", True) and not a.no_push, quiet=a.quiet, urgent=urgent, + reason=reason) + if a.scheduled: + from . import work + if (work.HANDOFF / ".git").exists(): + core.git(work.HANDOFF, "-c", "gc.autoDetach=false", "gc", "--auto", "--quiet", timeout=600) + return result # --------------------------------------------------------------------------- dashboard & help @@ -1542,6 +1773,9 @@ def cmd_wt(a): def cmd_sync(a): from . import hooks STATE.mkdir(parents=True, exist_ok=True) + if getattr(a, "flush_at", 0): # the detached flusher a deferred push started: push what waited, on time + flush_handoff(a.flush_at, quiet=a.quiet) + return 0 reasons = [] if getattr(a, "delay", 0): # a queued near-real-time run: let a burst of events settle, then take them all time.sleep(min(int(a.delay), 120)) @@ -1641,7 +1875,7 @@ def cmd_sync(a): except Exception as e: # never let the view break the sync if not a.quiet: ui.warn(f"dashboard: {e}") - commit_push(push=CFG["sync"].get("push", True) and not a.no_push, quiet=a.quiet) + _sync_handoff(a) (STATE / "last-sync.json").write_text(json.dumps({"ts": time.time(), "changed": changed, "gc": [m for _, m in results]})) if a.scheduled: @@ -2282,6 +2516,70 @@ def _task_reconcile(a, scope: str, label: str) -> int: return 0 +# The task writes that take several items, with the check (work.check: its op and the status a release goes to) each +# item named passes before the first one changes. +_TASK_CHECKS = {"start": ("claim", None), "claim": ("claim", None), "release": ("release", "todo"), + "done": ("release", "done"), "reopen": ("reopen", None), "block": ("block", None), + "unblock": ("unblock", None), "link": ("link", None), "cancel": ("cancel", None), + "move": ("move", None), "edit": ("edit", None)} +_ITEM_REF = re.compile(r"^(?:[TFBS]-[0-9a-z]+|\d+)$", re.I) # an item id (or its prefix), or a number of the list + + +def _task_items(words: list, scope: str) -> list: + """The items a task verb names, each found (work.find) before any changes: every word on its own when there are + several and each is an item id or a number of the list `dev task` showed (`done T-… T-…`, `done 1 3`), an item + named twice once; otherwise the words together, as a part of a title (`done the login timeout`).""" + from . import work + named = list(words) if len(words) > 1 and all(_ITEM_REF.match(w) for w in words) else [" ".join(words)] + found = {} + for sel in named: + it = work.find(sel, scope) + found.setdefault(it["meta"]["id"], it) + return list(found.values()) + + +def _task_item(words: list, scope: str, act: str) -> dict: + """The one item `dev task ` takes (ValueError when the words name several).""" + items = _task_items(words, scope) + if len(items) > 1: + raise ValueError(f"`dev task {act}` takes one item; {len(items)} given: " + + ", ".join(it["meta"]["id"] for it in items)) + return items[0] + + +def _task_write(act: str, it: dict, a, scope: str, changes: dict) -> None: + """One task write on item `it`, and its line: the verb, the item's id and title.""" + from . import work + why = a.why or "" + if act in ("start", "claim"): + it = work.claim(it, why=why, branch=_task_branch(scope)) + print(f"{ui.OK} {work.acted('claimed', it)} until {it['meta']['lock_expires']} — others see it as yours") + elif act == "release": + print(f"{ui.OK} {work.acted('released', work.release(it, why=why, status='todo'))}") + elif act == "done": + print(f"{ui.OK} {work.acted('done', work.release(it, why=why, status='done'))}") + elif act == "reopen": + print(f"{ui.OK} {work.acted('reopened', work.reopen(it, why=why))} (todo) · why: {a.why}") + elif act == "block": + print(f"{ui.OK} {work.acted('blocked', work.update(it, 'block', why=why, status='blocked'))}") + elif act == "unblock": + holder, expired = work.lock_holder(it) + it = work.update(it, "unblock", why=why, status="doing" if holder and not expired else "todo") + print(f"{ui.OK} {work.acted('unblocked', it)} ({it['meta']['status']})") + elif act == "link": + links = list(dict.fromkeys((it["meta"].get("links") or []) + [f"initiative:{a.to}"])) + print(f"{ui.OK} {work.acted('linked', work.update(it, 'link', why=why, links=links))}: counts toward " + f"initiative {a.to}") + elif act == "cancel": + it = work.update(it, "cancel", why=why, status="cancelled", claimed_by="", claimed_at="", lock_expires="") + print(f"{ui.OK} {work.acted('cancelled', it)}") + elif act == "move": + print(f"{ui.OK} {work.acted('moved', work.update(it, 'move', why=why, bucket=a.to))} → {a.to}") + elif act == "edit": + it = work.update(it, "edit", why=why, **changes) + print(f"{ui.OK} {work.acted('edited', it)} v{it['meta']['version']}") + + def cmd_task(a): from . import work scope, label = _scope(a) @@ -2300,63 +2598,33 @@ def cmd_task(a): print(f"{ui.OK} claimed by you") if bucket == "now" and work.now_warning(scope): ui.warn(work.now_warning(scope)) - elif act in ("start", "claim"): - it = work.claim(work.find(" ".join(a.selector), scope), why=a.why or "", branch=_task_branch(scope)) - print(f"{ui.OK} {work.acted('claimed', it)} until {it['meta']['lock_expires']} — others see it as yours") - elif act == "release": - it = work.release(work.find(" ".join(a.selector), scope), why=a.why or "", status="todo") - print(f"{ui.OK} {work.acted('released', it)}") - elif act == "done": - it = work.find(" ".join(a.selector), scope) - it = work.release(it, why=a.why or "", status="done") - print(f"{ui.OK} {work.acted('done', it)}") - elif act == "reopen": - it = work.reopen(work.find(" ".join(a.selector), scope), why=a.why or "") - print(f"{ui.OK} {work.acted('reopened', it)} (todo) · why: {a.why}") - elif act == "block": - it = work.update(work.find(" ".join(a.selector), scope), "block", why=a.why or "", status="blocked") - print(f"{ui.OK} {work.acted('blocked', it)}") - elif act == "unblock": - it = work.find(" ".join(a.selector), scope) - holder, expired = work.lock_holder(it) - it = work.update(it, "unblock", why=a.why or "", status="doing" if holder and not expired else "todo") - print(f"{ui.OK} {work.acted('unblocked', it)} ({it['meta']['status']})") - elif act == "link": - it = work.find(" ".join(a.selector), scope) - tag = f"initiative:{a.to}" - if not registry.initiative_path(a.to).exists(): + elif act in _TASK_CHECKS: + if act == "link" and not registry.initiative_path(a.to).exists(): ui.err(f"no initiative “{a.to}” — `dev initiative ls`") return 2 - links = list(dict.fromkeys((it["meta"].get("links") or []) + [tag])) - it = work.update(it, "link", why=a.why or "", links=links) - print(f"{ui.OK} {work.acted('linked', it)}: counts toward initiative {a.to}") - elif act == "cancel": - it = work.find(" ".join(a.selector), scope) - it = work.update(it, "cancel", why=a.why or "", status="cancelled", claimed_by="", claimed_at="", - lock_expires="") - print(f"{ui.OK} {work.acted('cancelled', it)}") - elif act == "move": - it = work.update(work.find(" ".join(a.selector), scope), "move", why=a.why or "", bucket=a.to) - print(f"{ui.OK} {work.acted('moved', it)} → {a.to}") - if a.to == "now" and work.now_warning(scope): - ui.warn(work.now_warning(scope)) - elif act == "edit": changes = {} - if a.title: - changes["title"] = a.title - if a.body_file: - changes["body"] = Path(a.body_file).read_text() - if a.priority_set: - changes["priority"] = a.priority_set - if a.due: - changes["due"] = a.due - if not changes: - ui.err("nothing to change: --title, --body-file, --priority or --due") - return 2 - it = work.update(work.find(" ".join(a.selector), scope), "edit", why=a.why or "", **changes) - print(f"{ui.OK} {work.acted('edited', it)} v{it['meta']['version']}") + if act == "edit": + if a.title: + changes["title"] = a.title + if a.body_file: + changes["body"] = Path(a.body_file).read_text() + if a.priority_set: + changes["priority"] = a.priority_set + if a.due: + changes["due"] = a.due + if not changes: + ui.err("nothing to change: --title, --body-file, --priority or --due") + return 2 + items = _task_items(a.selector, scope) + op, status = _TASK_CHECKS[act] + for it in items: # every item named takes the write, or none changes + work.check(it, op, why=a.why or "", status=status) + for it in items: + _task_write(act, it, a, scope, changes) + if act == "move" and a.to == "now" and work.now_warning(scope): + ui.warn(work.now_warning(scope)) elif act == "delegate": - it = work.find(" ".join(a.selector), scope) + it = _task_item(a.selector, scope, act) who = a.to.lstrip("@") if (it["meta"].get("claimed_by") or "").startswith(work.actor()["user"] + "@"): it = work.release(it, why=f"handed to {who}", status="todo") @@ -2373,7 +2641,7 @@ def cmd_task(a): elif act == "reconcile": return _task_reconcile(a, scope, label) elif act in ("show", "history"): - it = work.find(" ".join(a.selector), scope) + it = _task_item(a.selector, scope, act) m = it["meta"] if act == "show": print(ui.section(f"{m['id']} · {m['title']}")) @@ -2390,7 +2658,8 @@ def cmd_task(a): except ValueError as e: ui.err(str(e)) return 2 - _print_items(scope, label, getattr(a, "all", False), rebind=act == "ls") + if act == "ls": # a write prints its own lines only: a list after them would end on other items + _print_items(scope, label, getattr(a, "all", False)) return 0 @@ -2541,10 +2810,11 @@ def cmd_progress(a): runs = pg.active_runs(first=pg.current_session()) from . import work me = work.actor() # this Mac's presence, also a file under a hostname it carried then, is not another machine's - team = work.team() - others = [(_presence_name(t, team), s_) for t in team for s_ in t.get("sessions", []) - if s_.get("progress") and not work.mine(f"{t['user']}@{t['host']}", me, - at=work.parse_iso(t.get("updated")) or None)] + skipped = [] + team = work.team(skipped=skipped) + others = [(_presence_name(t, team), s_) for t in team for s_ in t["sessions"] + if isinstance(s_.get("progress"), dict) and not work.mine(f"{t['user']}@{t['host']}", me, + at=work.parse_iso(t.get("updated")) or None)] print(ui.section("Progress")) if not runs and not others: print(" no runs — agents start one with dev progress start \"\" --steps N --estimate 30m") @@ -2556,14 +2826,30 @@ def cmd_progress(a): + (f" · next: {last.get('next')}" if last.get("next") else "")) shown = _from_presence # another machine's run, as its presence summarizes it for who, s_ in others: - p_ = s_["progress"] + p_, eta = s_["progress"], _presence_eta(s_["progress"].get("eta_min")) print(f" {ui.ACTIVE} {who} · {shown(s_.get('agent'))} · {shown(s_.get('project'))} · {shown(p_.get('goal'))}" f" — {shown(p_.get('step'))}/{shown(p_.get('steps') or '?')}" - + (f" · ETA ~{_about(p_['eta_min'])}" if p_.get("eta_min") else "")) + + (f" · ETA ~{_about(eta)}" if eta else "")) print() + _name_skipped_presence(skipped) return 0 +def _presence_eta(value): + """The minutes left another Mac's presence gives for a run, or None when they are no finite number.""" + ok = isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) + return value if ok else None + + +def _name_skipped_presence(skipped: list) -> None: + """One line naming the presence files work.team left out, each once, so a bad file another Mac wrote is seen + instead of ending the command.""" + from . import work + if skipped: + ui.warn(f"left out {len(skipped)} presence file{'s' if len(skipped) != 1 else ''} devkit cannot read: " + + ", ".join(_from_presence(s) for s in skipped) + f" (in {tilde(work.PRESENCE)})") + + def _about(m) -> str: """An estimate or a time left, as the dashboard shows it (fmtAbout): to 5 minutes, and to the minute under 10, so "~" claims no more precision than an estimate has. Measured times keep progress.fmt_min.""" @@ -3283,11 +3569,19 @@ def _bug_pending(a, bugs): if not items: print("Nothing waits for review.") return 0 - print(f"{len(items)} item{'s wait' if len(items) != 1 else ' waits'} for your review; `dev bug send ` sends " - f"one, exactly as printed here:") + old = sum(1 for it in items if not it.get("sendable", True)) + if len(items) > old: + n = len(items) - old + print(f"{n} item{'s wait' if n != 1 else ' waits'} for your review; `dev bug send ` sends one, exactly as " + f"printed here:") + if old: + print(f"{old} old-format item{'s' if old != 1 else ''} cannot be sent: an older devkit queued " + f"{'them' if old != 1 else 'it'} without the record of where {'they' if old != 1 else 'it'} came from; " + f"`dev bug drop ` removes one:") for it in items: p = it["payload"] if isinstance(it.get("payload"), dict) else {} - state = "approved, goes with the next sync" if it.get("approved") else \ + state = "cannot be sent" if not it.get("sendable", True) else \ + "approved, goes with the next sync" if it.get("approved") else \ f"waits for your consent to the new text, or dev bug send {it.get('id')}" if it.get("consent") else \ f"dev bug send {it.get('id')}" print(f"\n {it.get('id')} · {p.get('type')} · {p.get('fingerprint')} · {state}" + @@ -3464,7 +3758,8 @@ def _presence_name(rec: dict, team: list = None) -> str: def cmd_team(a): from . import work - t = work.team(max_age_h=a.hours) + skipped = [] + t = work.team(max_age_h=a.hours, skipped=skipped) print(ui.section(f"Team · machines active in the last {a.hours} h")) if not t: print(" no presence yet (each machine publishes it on sync)") @@ -3478,6 +3773,7 @@ def cmd_team(a): print(f" 🔒 {shown(l_.get('id'))} {shown(l_.get('title'))}" f" {ui.dim(shown(l_.get('scope')) + ' · until ' + shown(l_.get('until')))}") print() + _name_skipped_presence(skipped) return 0 @@ -4611,6 +4907,7 @@ def add(name, fn, help_, **kw): p.add_argument("--quiet", action="store_true") p.add_argument("--renew", metavar="AGENT", help=argparse.SUPPRESS) p.add_argument("--delay", type=int, default=0, help=argparse.SUPPRESS) + p.add_argument("--flush-at", type=float, default=0, help=argparse.SUPPRESS) from . import disk as _disk _disk.add_du_arguments(add("du", cmd_du, "What fills your disk, why, and the plan to free it safely")) _disk.add_free_arguments(add("free", cmd_free, "Free items of the dev du plan by number, or every safe one: " diff --git a/lib/devkit/configschema.py b/lib/devkit/configschema.py index 23a78460..0047015a 100644 --- a/lib/devkit/configschema.py +++ b/lib/devkit/configschema.py @@ -16,7 +16,7 @@ "github_user": "", # empty: detected from `gh api user` "handoff_repo": "", # empty: /handoff "handoff_dir": "", # empty: /.handoff - "sync": {"push": True, "interval_minutes": 60}, + "sync": {"push": True, "interval_minutes": 60, "push_interval": 300}, # push_interval: seconds, 0 every sync "gc": { "auto": True, # the background job applies the safe class automatically "grace_hours": 24, # merged / fully-contained worktrees idle this long are removed @@ -429,7 +429,7 @@ def _default_rule(value): "host_dirs": mapping(HOST.check, pattern(r"[A-Za-z0-9][A-Za-z0-9._-]*", "a relative folder alias")), "stacks": array(enum(*STACKS)), "frameworks": array(enum(*FRAMEWORKS)), "hosts": array(enum(*HOSTS)), "clouds": array(enum(*CLOUDS)), - "sync": obj({"push": BOOL, "interval_minutes": POSINT}), + "sync": obj({"push": BOOL, "interval_minutes": POSINT, "push_interval": number(0, 3600, whole=True)}), "docker": obj({"cpu": POSINT, "memory": POSINT, "disk": POSINT, "vm_type": enum("vz", "qemu"), "mount_type": enum("virtiofs", "sshfs", "9p"), "rosetta": BOOL, "autostart": BOOL}), "claude": obj({"default_mode": enum("bypassPermissions", "acceptEdits", "default"), diff --git a/lib/devkit/continuity.py b/lib/devkit/continuity.py index f1f23799..87d367be 100644 --- a/lib/devkit/continuity.py +++ b/lib/devkit/continuity.py @@ -520,9 +520,12 @@ def _messages(run: dict) -> list: def _unacknowledged(run: dict) -> int: """Messages to the tech lead that the crew or the developer sent and nobody acknowledged; devkit's notices and - CI results tell and need no acknowledgement.""" + CI results tell and need no acknowledgement. A question answered was read by whoever answered it, and an answer + 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 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"))]) def _run_part(run: dict) -> dict: diff --git a/lib/devkit/dashboard.py b/lib/devkit/dashboard.py index abdf7919..609ce804 100644 --- a/lib/devkit/dashboard.py +++ b/lib/devkit/dashboard.py @@ -1657,9 +1657,7 @@ def write(reg: dict, handoff: Path = None) -> Path: """Render to ~/.local/state/devkit/dashboard/index.html (atomic) and return the path.""" out = core.STATE / "dashboard" / "index.html" out.parent.mkdir(parents=True, exist_ok=True) - tmp = out.with_suffix(".html.tmp") - tmp.write_text(render(reg, handoff=handoff), encoding="utf-8") - os.replace(tmp, out) + core.replace_text(out, render(reg, handoff=handoff)) # its own temporary name: two writers never share one return out diff --git a/lib/devkit/gitx.py b/lib/devkit/gitx.py index 6297af2f..a9201033 100644 --- a/lib/devkit/gitx.py +++ b/lib/devkit/gitx.py @@ -2772,14 +2772,18 @@ def step_records(c) -> dict: def _save_step(c, key, rec) -> None: + """Record step `key`'s result in the project's steps file, read, changed and written under the file's lock (a + second `dev ci --run` of the project saving at once waits instead of dropping this step) and written in one step + through a temporary file of its own (core.replace_text). A lock still held after its wait is written over: a lost + record only runs its step again on --resume.""" f = _steps_file(c) f.parent.mkdir(parents=True, exist_ok=True) - data = core.read_json(f, {}) or {} - data.setdefault("steps", {})[key] = rec - data["repo"] = c.pid - tmp = f.with_suffix(".tmp") - tmp.write_text(json.dumps(data, indent=1)) - os.replace(tmp, f) + with core.file_lock(f): + data = core.read_json(f, {}) + data = data if isinstance(data, dict) else {} + data.setdefault("steps", {})[key] = rec + data["repo"] = c.pid + core.replace_text(f, json.dumps(data, indent=1)) def _step_key(s) -> str: @@ -4763,6 +4767,11 @@ def vouches(runs): def cmd_release(a) -> int: + word = getattr(a, "version_word", None) + if word and a.version: + return refuse(f"the version is given twice ({word} and --version {a.version}): give the version once", + f"dev release {word}") + a.version = a.version or word c = ctx() if c is None: return _need_repo(c) @@ -5396,7 +5405,7 @@ def cmd_gh(a) -> int: ("push [--force-with-lease]", "One push: local-CI evidence, embargoes, no default branch, URL of the PR"), ("pr create|view|ls|checks|merge", "PRs from the template; checks --watch with failing logs; gated merge"), ("run ls|view --failed|rerun", "CI runs, failing logs trimmed; rerun only with --flaky \"reason\""), - ("release [--version V]", "Tag and publish from a verified default branch (CalVer by default)"), + ("release [V | --version V]", "Tag and publish from a verified default branch (CalVer by default)"), ("issue ls|view|create", "Issues, compact"), ("git … · gh …", "Escape hatches with the same policy checks"), ]) @@ -5554,6 +5563,7 @@ def register(add): q.add_argument("--all-jobs", action="store_true") p = add("release", cmd_release, "Tag and publish a release from a verified default branch (CalVer by default)") + p.add_argument("version_word", nargs="?", metavar="VERSION", help="the version, as --version takes it") p.add_argument("--version", help="YY.MM.PATCH (default: the next CalVer) or X.Y.Z for other schemes") p.add_argument("--notes-file", help="release notes (default: the CHANGELOG section, else generated)") p.add_argument("--ci-passed", action="store_true", help="attest that the local suite passed on HEAD") diff --git a/lib/devkit/hooks.py b/lib/devkit/hooks.py index 92f1cbd2..1f1a9826 100644 --- a/lib/devkit/hooks.py +++ b/lib/devkit/hooks.py @@ -1405,9 +1405,7 @@ def _devkit_env_change(path: str, settings: dict, managed: bool = True) -> list: settings["env"] = {**env, **{k: json.loads(v) for k, v in want.items()}} if not settings["env"]: settings.pop("env") - tmp = Path(f"{path}.devkit.tmp") - tmp.write_text(json.dumps(settings, indent=2) + "\n") - os.replace(tmp, path) + core.replace_text(path, json.dumps(settings, indent=2) + "\n") # its own temporary name: sessions start at once return changed @@ -3974,9 +3972,7 @@ def statusline(agent: str): rec = {"ts": int(time.time()), "five_hour": rl.get("five_hour"), "seven_day": rl.get("seven_day")} if any(old.get(k) != rec[k] for k in ("five_hour", "seven_day")) or rec["ts"] - (old.get("ts") or 0) > 300: QUOTA.mkdir(parents=True, exist_ok=True) - tmp = f.with_suffix(".tmp") - tmp.write_text(json.dumps(rec)) - os.replace(tmp, f) + core.replace_text(f, json.dumps(rec)) # its own temporary name: sessions draw the line at once except Exception as e: _swallowed("statusline", e) ws = data.get("workspace") or {} diff --git a/lib/devkit/language.py b/lib/devkit/language.py index 92c72809..34a6ff25 100644 --- a/lib/devkit/language.py +++ b/lib/devkit/language.py @@ -3,9 +3,9 @@ """The developer's language: what the agents reply in, and how devkit tells. The rule (the developer, 2026-11-12): reply in the developer's language, by default American English. With devkit's -`language` setting at `auto` (the default), that is the language of the developer's latest message, or of the earlier -ones when the latest is too short to tell ("ok", "continua", a command); a set locale (es-ES, en-US) fixes it whatever -the developer writes. Only what the developer reads follows it: code, comments, commits, PRs, docs, devkit's records +`language` setting at `auto` (the default), that is the language of the developer's latest message (when it is short, +the language its words and marks name: "¿cómo vamos?"), or of most of the recent ones when the latest names none +("ok", "continua", a command); a set locale (es-ES, en-US) fixes it whatever the developer writes. Only what the developer reads follows it: code, comments, commits, PRs, docs, devkit's records and the crew's briefs and reports stay in American English. `detect` reads the prose of a text only: code blocks and spans, links, paths, commands, log lines, quoted text and the @@ -88,9 +88,9 @@ ("ò", ("it", "ca")), ("ì", ("it",)), ("ù", ("it", "fr"))) -def _index() -> dict: +def _index(lexicon: dict = _WORDS) -> dict: owners = {} - for lang, words in _WORDS.items(): + for lang, words in lexicon.items(): for w in words.split(): owners.setdefault(w, set()).add(lang) return {w: tuple(sorted(langs)) for w, langs in owners.items()} @@ -123,6 +123,41 @@ def _index() -> dict: _LABEL = re.compile(r"(?im)^([ \t]*[-*•][ \t]+)(?:\*+[ \t]*)?(?:done|check|progress|crew|you|next)[ \t*]*:[ \t*]*|" r"needs from the tech lead[ \t]*:") _WORD = re.compile(r"[^\W\d_]+(?:'[^\W\d_]+)*") +# a token with a digit or an underscore is an identifier (call_29e1bebf…, a hash, snake_case), never prose: its letter +# runs ("e", "a") would read as function words. Linear: the lookahead runs once per token, from its first character +_IDENT = re.compile(r"(?", "") + + +def _answers(block: str) -> list: + """The answers in one reply block's JSON ([{"question": …, "answer": …}]); [] when it is no such JSON.""" + try: + items = json.loads(block) + except (ValueError, RecursionError): + return [] + found = [] + for item in items if isinstance(items, list) else [items]: + answer = item.get("answer") if isinstance(item, dict) else None + found += [a for a in (answer if isinstance(answer, list) else [answer]) if isinstance(a, str)] + return found + + +def _with_answers(text: str) -> str: + """The text with each Codex reply block (_REPLY) replaced by the developer's answers in it, one per line: the + question is the agent's words and the ids are no prose. An unclosed block runs to the end.""" + start, end = _REPLY + out, at = [], 0 + while True: + i = text.find(start, at) + if i < 0: + out.append(text[at:]) + return "".join(out) + j = text.find(end, i) + out += [text[at:i], "\n" + "\n".join(_answers(text[i + len(start):j if j >= 0 else len(text)])) + "\n"] + if j < 0: + return "".join(out) + at = j + len(end) def _without_fences(text: str) -> str: @@ -161,8 +196,9 @@ def _without_tagged(text: str) -> str: def prose(text: str) -> str: """The text without what is not the writer's own prose.""" - text = _without_tagged(_without_fences((text or "")[:MAX_TEXT].replace("’", "'"))) - for pat in (_LOGLINE, _SPAN, _URL, _PATH, _QUOTED, _BLOCKQUOTE, _COMMAND, _MARKER, _TAG): # whole log lines first + text = _without_tagged(_without_fences(_with_answers((text or "")[:MAX_TEXT].replace("’", "'")))) + for pat in (_LOGLINE, _SPAN, _URL, _PATH, _QUOTED, _BLOCKQUOTE, _COMMAND, _MARKER, _TAG, # whole log lines first + _IDENT): text = pat.sub(" ", text) return _LABEL.sub(lambda m: m.group(1) or " ", text) @@ -268,6 +304,54 @@ def _reading(text: str) -> tuple: return (lang, "") if lang else (None, BROUGHT) +# A message too short for prose to decide ("¿cómo vamos?", "ok") is read again with these: everyday words of a short +# turn that are no function words, and the accented letters several languages share. They count only there. +_SHORT_WORDS = { + "es": "vamos seguimos falta faltan queda quedan perfecto adelante listo hola bueno has", + "pt": "vamos seguimos falta obrigado obrigada beleza ótimo", + "fr": "oui alors ça voilà allez", + "it": "grazie allora avanti andiamo bene", + "de": "weiter gut genau fertig dank", + "ca": "endavant anem", + "nl": "verder goed dank", +} +_SHORT_INDEX = _index(_SHORT_WORDS) +_SHORT_LETTERS = (("á", ("es", "pt")), ("í", ("ca", "es", "pt")), ("ó", ("ca", "es", "pt")), ("ú", ("ca", "es", "pt")), + ("ç", ("ca", "fr", "pt"))) +_SPANISH_MARKS = ("¿", "¡") + + +def _short_reading(text: str) -> tuple: + """A message too short for its prose to decide: (the language its words or marks name, or None; the languages it + has words or marks of, maybe none). One language names it when it has a whole word's weight and no other language + has any ("sigue", "how's it going?"), or when Spanish leads a message with ¿ or ¡ ("¿cómo vamos?").""" + body = prose(text) + scores, _ = _count(body) + + def add(langs, weight): + for lang in langs: + scores[lang] = scores.get(lang, 0.0) + weight / len(langs) + + for w in _WORD.findall(body.lower()): + if w in _SHORT_INDEX: + add(_SHORT_INDEX[w], 1.0) + for ch, langs in _SHORT_LETTERS: + if ch in w: + add(langs, 0.5) + break + marked = any(m in body for m in _SPANISH_MARKS) + if marked: + add(("es",), 1.0) + ranked = _ranked(scores) + heard = frozenset(lang for lang, score in ranked if score > 0) + if ranked: + best, top = ranked[0] + second = ranked[1][1] if len(ranked) > 1 else 0.0 + if (top >= 1.0 and not second) or (marked and best == "es" and top >= MARGIN * second): + return best, heard + return None, heard + + def detect(text: str): """The language a developer's message is written in ("es"), or None when unsure. When it brings text to work on (an email to translate, strings to check, output to read), only the developer's own words decide. The leading @@ -391,28 +475,52 @@ def name(lang: str) -> str: return LOCALE_NAMES.get(key) or NAMES.get(_base(lang)) or lang +RECENT = 3 # the developer's latest messages that tell a language, which decide for a short one that names none + + +def _recent(messages, heard) -> str: + """The language most of the developer's RECENT latest messages that tell one are in (newest first; a tie goes to + the newest), among `heard` when the short message they decide for has words of some languages: it never asks for + a language it has no word of. None when none tells. A message with prose that cannot tell ends the look back: an + older message never decides past it.""" + told = [] + for text in messages: + lang, why = _reading(text) + if not lang and why == SHORT: + lang = _short_reading(text)[0] + if not lang: + continue + if not lang: + break + told.append(lang) + if len(told) == RECENT: + break + votes = [lang for lang in told if not heard or lang in heard] + return max(dict.fromkeys(votes), key=votes.count) if votes else None # max keeps the newest of equal counts + + def wanted(prompt=None, transcript=None, cfg=None) -> tuple: """(language, how) the reply must be in: ("fr", "set") for a set locale; ("es", "latest") from the developer's - latest message; ("es", "earlier") from an earlier one only when the latest is too short to tell ("ok", a - command); (None, "") when nothing tells, and when the latest has prose that cannot tell (a close call, or text to - work on that the developer's own words cannot place): an older message never decides for it.""" + latest message, its prose or, when it is too short for that, its words and marks ("¿cómo vamos?"); + ("es", "earlier") when the latest is short and names no language ("ok", "como vamos?", which is Spanish and + Portuguese alike): the language of most of the recent messages that tell one, among those the short message has + words of (_recent); (None, "") when nothing tells, and when the latest has prose that cannot tell (a close call, or + text to work on that the developer's own words cannot place): an older message never decides for it.""" value = setting(cfg) if value != AUTO: return _base(value), "set" - latest = bool(prompt) and not prompt.lstrip().startswith(_NOT_HUMAN) - if latest: - lang, why = _reading(prompt) - if lang or why != SHORT: # only a message too short to tell leaves it to the earlier ones - return (lang, "latest") if lang else (None, "") - first = not latest - for text in developer_messages(transcript): # newest first: the first one with enough prose decides, or nothing - lang, why = _reading(text) - if lang: - return lang, "latest" if first else "earlier" - if why != SHORT: # it could not decide: an older message never decides for it - return None, "" - first = False - return None, "" + earlier = developer_messages(transcript) # newest first + latest = prompt if prompt and not prompt.lstrip().startswith(_NOT_HUMAN) else next(earlier, None) + if latest is None: + return None, "" + lang, why = _reading(latest) + if lang or why != SHORT: # only a message too short to tell leaves it to its words, then to the earlier ones + return (lang, "latest") if lang else (None, "") + lang, heard = _short_reading(latest) + if lang: + return lang, "latest" + lang = _recent(earlier, heard) + return (lang, "earlier") if lang else (None, "") def prompt_line(prompt: str, transcript=None, cfg=None) -> str: diff --git a/lib/devkit/peers.py b/lib/devkit/peers.py index 8f95dde9..99f79f67 100644 --- a/lib/devkit/peers.py +++ b/lib/devkit/peers.py @@ -1215,6 +1215,33 @@ def fn(doc): return [] +def untell(agent: str, sid: str, told: list) -> None: + """Give back messages `take` told (`told`: what it returned) whose frame could not be written, as when the wait's + output fails: each is unread again and due at once, without the receipt its telling wrote. One told again since + keeps its new state. Raises what the store raises; the caller decides what a failed give-back means.""" + claims = {m.get("id"): m for m in told if m.get("id")} + if not claims: + return + me = key(agent, sid) + + def fn(doc): + changed = False + for m in doc.get("inbox", []): + claim = claims.get(m.get("id")) + if claim is None or not m.get("told") or m.get("told") != claim.get("told"): + continue + m.pop("told", None) + receipts = m.get("receipts") or {} + if me in receipts and receipts[me] == (claim.get("receipts") or {}).get(me): + del receipts[me] + changed = True + return None if changed else state.SKIP + for box_key, _ in _boxes(_View(), me, strict=True): + _update(box_path(*_split(box_key)), fn, create=False) + now = time.time() + _touch(_marker(agent, sid), times=(now, now)) + + def inbox(agent: str, sid: str, all_=False) -> list: """The messages of a session and its older ids, oldest first: the unread ones, or all with all_. Read-only.""" view = _View() diff --git a/lib/devkit/plans.py b/lib/devkit/plans.py index 02f0c0e7..3f65dd52 100644 --- a/lib/devkit/plans.py +++ b/lib/devkit/plans.py @@ -118,10 +118,13 @@ def revise(path: Path, why: str, a=None, status: str = None) -> dict: """Record a change of the plan: bump the version, log who/when/why and the size of the change, commit. An approval covers the text approved: an approved plan whose text changed goes back to draft when it is revised without a `status`, and the changelog line names the version the approval covered.""" + path = Path(path) + if path.suffix != ".md": # a script or data file kept beside the plans: front matter would break it + raise ValueError(f"{path.name} is not a Markdown plan: only .md files in the plans folder get front matter " + "and versions, and devkit leaves other files as they are") if not why.strip(): raise ValueError("a plan revision needs the reason: --why \"…\"") a = a or work.actor() - path = Path(path) with work.record_lock(path): # another session revising this plan waits, then reads what this one wrote meta = _revise_locked(path, why, a, status) # committed before the lock is released (the plan's lock, then the repository's, as for items): a revision diff --git a/lib/devkit/progress.py b/lib/devkit/progress.py index 645df949..f857cf8e 100644 --- a/lib/devkit/progress.py +++ b/lib/devkit/progress.py @@ -3094,6 +3094,14 @@ def _closed_why(run, m: dict) -> str: return "its run ended" if (run or {}).get("state") == "done" and _asks(m) else "" +def _answered(q: dict, a: dict, who: str) -> None: + """Question `q` is answered by message `a`, which `who` (main or a lane id) sent: answering reads the question, + so it carries `who`'s receipt, leaves their inbox and is never delivered to them again as unread.""" + from . import messaging + q.update(answered=True, answered_by=a["ref"]) + q.setdefault("receipts", {}).setdefault(who, messaging.delivery_receipt(q)) + + def crew_answer(msg_id: str, text: str, from_agent: str | None = None, cwd: str | None = None, now: float | None = None, request_id: str = "") -> dict: """Answer crew message `msg_id` (`dev crew answer`): mark it answered and post the answer, in the run that holds @@ -3146,7 +3154,7 @@ def crew_answer(msg_id: str, text: str, from_agent: str | None = None, cwd: str a = _post(run, from_agent or "main", q["from"], text, now or time.time(), kind="answer", request_id=request_id, reply_to=q["id"]) a["to_name"] = q["from_name"] - q.update(answered=True, answered_by=a["ref"]) + _answered(q, a, from_agent or "main") _ended_asker_notice(run, a["to"], f"the answer {a['id']} to their question {q['id']}", now or time.time()) _save(run, touch_session=False) _audit("crew.message", f"{a['from_name']} → {a['to_name']}", "", project=run.get("project") or "", @@ -3315,7 +3323,8 @@ def names_question(ref, question): a.get("to_name")) a["reply_refs"] = [q.get("ref", q["id"]) for q in asked] for q in asked: - q.update(answered=True, answered_by=a["ref"], via="SendMessage") + _answered(q, a, "main") + q["via"] = "SendMessage" _save(run, touch_session=False) for q in asked: # never the text: crew messages quote the developer's requests _audit("crew.message-answered", q["id"], f"answered via SendMessage to {q.get('from_name') or q['from']}", @@ -3323,14 +3332,21 @@ def names_question(ref, question): return [q["id"] for q in asked] +def _due(m: dict, me: str, lane: dict) -> bool: + """Is message `m` still to deliver to `me`: addressed to it, no receipt of `me`, not delivered for good by an + 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 _addressed_to(m, me, lane)) + + def _take_messages(agent, sid, me: str, mark=True, select=None, limit=None) -> list: """The messages for `me` not delivered yet; with mark, they are marked delivered (once each, under the lock). `select(run, message)`: only the messages it keeps; `limit`: at most that many, oldest first (watch.mail). Every hook call asks: the lock is taken only when there is something to take. A message delivered but not read comes back after a minute (one its preview showed whole is read on delivery: acknowledge_on_delivery); one an earlier devkit delivered before messages had receipts never comes back.""" - from . import messaging - def mine(run): run = normalize(run) lane = (run.get("agents") or {}).get(me) or {} @@ -3338,9 +3354,7 @@ def mine(run): for m in run.get("messages") or []: if limit is not None and len(new) >= limit: break - if (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 _addressed_to(m, me, lane) and (select is None or select(run, m))): + if _due(m, me, lane) and (select is None or select(run, m)): new.append(m) return run, new run = load_run(agent, sid) @@ -3362,6 +3376,44 @@ def mine(run): return out +def claim_message(agent, sid, me: str, mid: str, select=None): + """Claim message `mid` for `me` before its line is written (the wait): under the run's lock, and only while it is + still due (the test _take_messages applies, then `select(run, message)`), it is marked delivered. -> (the message + as it was before the claim, the claim's time), or None when it is no longer due: a hook or another wait took it + since it was read. unclaim_message gives a claim back.""" + with _tx(agent, sid): + run = normalize(load_run(agent, sid) or {}) + lane = (run.get("agents") or {}).get(me) or {} + for m in run.get("messages") or []: + if m.get("id") != mid: + continue + if not _due(m, me, lane) or (select is not None and not select(run, m)): + return None + before, now = dict(m), time.time() + m["delivered"], m["notification_at"] = True, now + _save(run, touch_session=False) + return before, now + return None + + +def unclaim_message(agent, sid, before: dict, at: float): + """Give back a claim (claim_message) whose line could not be written: the message is due again as it was before + the claim. One claimed again since keeps its new claim.""" + with _tx(agent, sid): + run = load_run(agent, sid) + for m in (run or {}).get("messages") or []: + if m.get("id") != before.get("id"): + continue + if m.get("notification_at") == at: + for field in ("delivered", "notification_at"): + if field in before: + m[field] = before[field] + else: + m.pop(field, None) + _save(run, touch_session=False) + return + + def read_on_delivery(m: dict) -> bool: """Does delivering the message's preview count as reading it? For devkit's own notices and CI results (their line is the digest an agent acts on), and for a body the preview shows whole. A longer body is read with diff --git a/lib/devkit/registry.py b/lib/devkit/registry.py index 0c9d522b..805f5d4c 100644 --- a/lib/devkit/registry.py +++ b/lib/devkit/registry.py @@ -1303,14 +1303,15 @@ def _update_note(p: dict, create: bool) -> bool: text = pre + block + rest.split(TASKS_END, 1)[1] else: text = _with_tasks_block(text, block) or text - auto = render_auto(p) - if AUTO_START in text and AUTO_END in text: + if not is_local(p): # the auto block tells of a checkout: only a Mac that has one writes it, so two never trade it + new = text + elif AUTO_START in text and AUTO_END in text: pre, rest = text.split(AUTO_START, 1) _, post = rest.split(AUTO_END, 1) - new = pre + auto + post + new = pre + render_auto(p) + post else: head, _, body = text.partition("\n") - new = head + "\n\n" + auto + "\n" + body + new = head + "\n\n" + render_auto(p) + "\n" + body if f.exists(): text = f.read_text() old_wo = re.sub(r"_Auto-refreshed by `dev sync` · [^.]*\.", "", text) @@ -1440,6 +1441,56 @@ def render_activity(reg: dict, days: int = 30) -> str: return "\n".join(out).rstrip() +_STAMP = re.compile(r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}") + + +def write_generated(path: Path, text: str) -> bool: + """Write `text` when it differs from the file with every `YYYY-MM-DD HH:MM` masked. -> whether it wrote. + A generated view whose only change is the time it was made, or a time it shows, stays as it is, so it gives the + handoff repository no commit; a time that appears or goes is a change.""" + try: + old = path.read_text() + except (OSError, UnicodeDecodeError): + old = None + if old is not None and _STAMP.sub("