diff --git a/.abcd/development/brief/04-surfaces/34-build.md b/.abcd/development/brief/04-surfaces/34-build.md index 2811fb8cda..41c4b63a75 100644 --- a/.abcd/development/brief/04-surfaces/34-build.md +++ b/.abcd/development/brief/04-surfaces/34-build.md @@ -347,16 +347,17 @@ intent's grounds entry is left as written. A run is paced without being told: a working window, a pause after it, a ceiling on the run's lanes and validators alive at once, and the fix rounds a -lane may take before it is handed back (ruling DR1, 2026-09-29: a per-run value -set beside the pace, default 3). The four numbers are +lane may take before its cap is judged (ruling DR1, 2026-09-29: a per-run value +set beside the pace, default 3, raised to 5 by the product thinker's ruling of 2 December +2026). The four numbers are resolved once, when a new run is created, through the one layered configuration reader (`internal/core/layered`), each key on its own, highest layer first: the build's own pace, sub-agent and fix-round flags, the pace written as `/`; `pace.work_minutes`, `pace.pause_minutes`, `pace.sub_agents` and `pace.fix_rounds` in the repository's `.abcd/config.json`; the same keys in `~/.abcd.noindex/config.json`; and -the bundled default, 120 minutes of work, no pause, 2 sub-agents and 3 fix -rounds (decision 5, the pause removed by the ruling of 2026-10-10, and ruling DR1), held in one set of constants. The files are read through the +the bundled default, 120 minutes of work, no pause, 2 sub-agents and 5 fix +rounds (decision 5, the pause removed by the ruling of 2026-10-10, and ruling DR1 as the ruling of 2 December 2026 raised it), held in one set of constants. The files are read through the reader's guards (a regular file inside the checkout; on the machine, one the caller owns and nobody else can write), and the reader claims the `pace` namespace, so a key under it the loop does not read is refused rather than @@ -1136,9 +1137,32 @@ the work, never closes like a pass). A return the loop cannot read as a verdict records nothing and is refused, so it starts no fix round and counts against nothing. -**The fix-round bound** (ruling DR1; itd-50, criterion 2). A round that does not -pass once the lane has taken the run's cap of fix rounds starts no further fix -round: the lane stops at the `handed-back` stage with a `hand_back` record (the +**The fix-round bound** (ruling DR1; itd-50, criterion 2; the product thinker's +ruling of 2 December 2026). A round that does not pass once the lane +has taken the run's cap of fix rounds starts no further fix round. When every +finding it leaves is minor or nitpick, the lane goes to its landing, and the +landing's records commit files each finding as an open issue through the +ledger's capture: found at the finding's location, with its severity and the +remedy the reviewer named (or the ledger's machine remedy), and found during a +line naming the lane, the run, the round and the head it judged, by which a +killed landing finds what it already filed. A finding carries no severity of its +own, so the cap reads the narrowest sound one (dcn-2612021257543635): a failing +security reviewer is a security finding, a failing intent-auditor a major one, +and a ruthless reviewer's finding carries the tag its bullet gives it after its +location (`[critical]`, `[major]`, `[minor]` or `[nitpick]`, which its brief +asks for), an untagged finding, a failing return that locates none, and any +bullet under Findings that does not lead with its `file:line` reading as major, +and two findings at one location keeping the worse tag; a ruthless finding +tagged `[security]` or worded on security holds the lane as a security finding +does and is never filed in public; a finding naming no file the lane's worktree +holds, or a reviewer whose model the records commit cannot disclose, holds the +lane too. A round a landing's sync opens that passes withdraws nothing the cap +round left, and one that fails hands the lane back. The records commit that +files the findings goes to a review round of its own in every facilitator mode +and is pushed only once that round passes; a round of it that does not pass +hands the lane back with nothing pushed. A capture refusal that would recur +hands the lane back at its landing with nothing committed. Otherwise the +lane stops at the `handed-back` stage with a `hand_back` record (the verdict `unachievable`, the round, the cap, the last round's verdicts, the returns of the validators that did not pass, and the criteria the audit judged not met or could not decide). The step's result carries it and says so first; diff --git a/.abcd/development/brief/04-surfaces/35-drain.md b/.abcd/development/brief/04-surfaces/35-drain.md index 25fe93ff65..2bd2aecf54 100644 --- a/.abcd/development/brief/04-surfaces/35-drain.md +++ b/.abcd/development/brief/04-surfaces/35-drain.md @@ -1465,7 +1465,7 @@ The drain then routes each hand-back: | `user-visible` | the issue is promoted to an intent draft by the capture verb's promotion | the draft, and the issue's `related_intents` naming it; nothing else | | `trust-rule` | flagged as needing a decision record, the lane's reason as the question | `decision_needed:` on the open issue, holding the question; nothing else; no record is minted | | `design-finding`, `second-package` | flagged with the home the lane names | nothing | -| a lane stopped after its fix rounds | flagged, the issue staying open with the last findings | nothing | +| a lane stopped after its fix rounds (a security, major or critical finding left; one leaving only minor or nitpick findings lands and files each as an open issue, by the ruling of 2 December 2026) | flagged, the issue staying open with the last findings | nothing | | a lane handed back as stuck (`stuck`) | flagged, the issue staying open, naming the discard of its run | nothing | | a lane whose pull request closed unmerged (`closed`) | flagged, the issue staying open, naming the discard of its run | nothing | diff --git a/.abcd/work/decisions/dcn-2612021257543635-at-a-lane-s-fix-round-cap-the-loop-reads.md b/.abcd/work/decisions/dcn-2612021257543635-at-a-lane-s-fix-round-cap-the-loop-reads.md new file mode 100644 index 0000000000..37d3601191 --- /dev/null +++ b/.abcd/work/decisions/dcn-2612021257543635-at-a-lane-s-fix-round-cap-the-loop-reads.md @@ -0,0 +1,6 @@ +--- +id: dcn-2612021257543635 +slug: at-a-lane-s-fix-round-cap-the-loop-reads +date: 2026-12-02 +--- +2026-12-02 — At a lane's fix-round cap the loop reads a finding's severity narrowly, since review findings carry none of their own: a failing security reviewer is a security finding and a failing intent-auditor a major one, so either hands the lane back; a ruthless reviewer's finding carries the ledger severity its bullet tags after its location ([critical], [major], [minor] or [nitpick]), which the reviewer's brief now asks for, and an untagged finding, a failing return that locates none, a finding naming no file in the lane's worktree, or a reviewer whose model the records commit cannot disclose in Assisted-by all hold the lane as major. Only a round whose every remaining finding is minor or nitpick lands, and the landing's records commit files each through the ledger's capture as an open issue (found_at the finding's location, remedy the reviewer's or the machine remedy, found_during naming lane, run, round and judged head, which also makes a killed landing file each once). Nothing new enters the run's state: the round is re-read from the returns as recorded. The reading fails closed and reads every line of the Findings section, a heading indented inside a list item included, and every list item after a heading that ends the section: a list item that does not lead with a file:line (no location, a tag before it, a directory, a file with no line, an indented bullet under no finding or opening with a tag or a location), a sub-heading or paragraph attached to no finding (the FIX-FIRST and NOTES labels excepted), a finding bullet a code fence or comment hides anywhere in the section (any list item at the top level, or one at any indent with a location or a tag), and a list item with a bold location or a tag after a heading that ended the section each hold the lane as major; a line at column 0 straight after a finding, or an indented line of its text, continues it, its tag and words read with it; two findings at one location are both read, the worse tag deciding. A ruthless finding that bears on security is never filed in public: one tagged [security], or whose bullet or a line under it carries one of twenty stems (security, vulnerab, inject, traversal, secret, credential, token, privileg, bypass, CWE, attacker, exploit, leak, symlink, untrusted, sanitiz, escap, overflow, password, auth), matched as a substring anywhere in any case so that an identifier counts (access_token, api_secret, oauth, unsanitized), with two exceptions only: cwe and leak match at the start of a word, and auth does not match where or follows it (author, authored, authority), save in authoris and authoriz, so authorization and unauthorized still count. A word-boundary reading tried in between hid the stems inside identifiers, so the coordinator returned to substrings; an escaped string or a tokenizer is an accepted false hold, holds the lane as a failing security reviewer does, and the hand-back names neither the finding nor its place. The run's coordinator, acting for the facilitator in auto mode, chose this narrowest safe rule and its first ten words on 2 December 2026 and added the other ten in the next review round from the security reviewer's note; its false holds are the accepted cost. A round a landing's sync opens over a merged default branch and that passes withdraws nothing, since the sync changed none of the lane's own work: the landing still files from the cap round; one that fails, on findings of any severity, hands the lane back, since the cap files one round's findings and never one round's in place of another's. A records commit carrying cap filings goes to a review round of its own in every facilitator mode, and a round of it that does not pass, or a records commit that would go to a person's pull request unread, hands the lane back with nothing pushed, so no filed record reaches the forge unjudged. A capture refusal that a later call meets again (a refused request or field, a missing remedy, a span the redactor cannot resolve or no scanner) hands the lane back at its landing with each record that call filed taken back out, while one that may pass later (the ledger's lock) leaves the lane at land; a finding citing a record id the lane's tree does not hold (an ADR by the number its file in the ADR store carries, an ordinal padded to four digits), which record-lint would refuse once filed, holds the lane at the cap. What the capture says of a record it altered or could not redact reaches the run's record, not the commit. The cap's route to the landing refuses a lane whose report states a verdict, as the passing route does. Applies the product thinker's ruling of 2 December 2026 on the fix-round cap. diff --git a/.abcd/work/issues/open/iss-2612021201375528-a-lane-s-fix-rounds-stop-at-three-by.md b/.abcd/work/issues/resolved/iss-2612021201375528-a-lane-s-fix-rounds-stop-at-three-by.md similarity index 88% rename from .abcd/work/issues/open/iss-2612021201375528-a-lane-s-fix-rounds-stop-at-three-by.md rename to .abcd/work/issues/resolved/iss-2612021201375528-a-lane-s-fix-rounds-stop-at-three-by.md index 805741bb4a..e062926c17 100644 --- a/.abcd/work/issues/open/iss-2612021201375528-a-lane-s-fix-rounds-stop-at-three-by.md +++ b/.abcd/work/issues/resolved/iss-2612021201375528-a-lane-s-fix-rounds-stop-at-three-by.md @@ -10,6 +10,10 @@ origin: researcher-authored production_mode: hand-written found_at: "internal/core/implement/loop/pace.go" remedy: "Raise BundledFixRounds to 5, keeping pace.fix_rounds and --fix-rounds as the repository and run layers; at the cap, hand the lane back only when a review still reports a security finding or a major or critical one, and otherwise capture each remaining minor or nitpick finding as an open issue that names the lane's intent or issue and the reviewed head, then let the lane go on to preflight and landing; state both rules where a run starts and in the drain and build pages, with tests for each outcome at the cap." +resolution: "A lane now runs up to five fix rounds by default, and a security finding at any severity holds the lane rather than spending rounds on it." +impact: fix +resolved_by: + commit: "6e8a929f15d61d374f2bf11e130a2cc128c3d438" --- A lane's fix rounds stop at three by default and the lane is then handed back whatever the remaining findings are, so a lane whose reviews ask only small fixes is stranded as surely as one with an open security finding. In the autonomous run of 25 November to 2 December, three lanes were set aside on one small finding each after their third round and two later steps never opened. The product thinker ruled on 2 December that the default becomes five rounds, still settable per repository, and that what happens at the cap depends on what is left: a lane stops only while a security finding or a major or critical finding persists, and otherwise its remaining minor and nitpick findings are captured as open issues linked to the lane and the lane lands. This replaces the default of three ruled on 29 September (DR1, itd-50 Decision 6), and it applies to every lane of a run, whether abcd or a host session drives it. diff --git a/commands/build.md b/commands/build.md index 0d77dff0f4..2f7c48ef01 100644 --- a/commands/build.md +++ b/commands/build.md @@ -661,7 +661,7 @@ naming the lane and making no commit: A new run is paced without being told: a working window, a pause after it, a ceiling on the run's lanes and validators alive at once, and the fix rounds a -lane may take before it is handed back. The four numbers are read once, when the +lane may take before its cap is judged. The four numbers are read once, when the run starts, each from the highest layer that sets it: 1. `--pace /` (for example `--pace 90/240`), @@ -669,7 +669,22 @@ run starts, each from the highest layer that sets it: 2. `pace.work_minutes`, `pace.pause_minutes`, `pace.sub_agents` and `pace.fix_rounds` in the repository's `.abcd/config.json`; 3. the same keys in `~/.abcd.noindex/config.json`, for every checkout on the machine; -4. the bundled 120/0 (no pause) with 2 sub-agents and 3 fix rounds. +4. the bundled 120/0 (no pause) with 2 sub-agents and 5 fix rounds. + +At the cap, a lane whose round still does not pass is handed back only while a +security finding, or a major or critical one, stands. Otherwise every finding +it leaves is minor or nitpick, and the lane lands: its records commit files +each finding as an open issue through the ledger's capture, at the finding's +location and with its remedy, naming the lane, the run and the head the round +judged. A failing security reviewer counts as a security finding, a failing +intent-auditor as a major one, and a ruthless reviewer's finding carries the +severity its tag gives it (`[minor]`, `[nitpick]`, `[major]`, `[critical]`), +an untagged one, or a bullet that does not lead with its `file:line`, counting +as major. A ruthless finding tagged `[security]` or worded on security holds +the lane as a security finding does and is never filed. The records commit +that files the findings is reviewed in a round of its own before anything is +pushed, and a round of it that does not pass hands the lane back. Tell the user +both rules when a run starts. The payload's `pace` carries each number as `value`, `layer` (`flag`, `repo`, `machine` or `bundled`) and `origin` (the flag as typed, or the file), and the diff --git a/commands/drain.md b/commands/drain.md index b788d77fc6..782caad7e1 100644 --- a/commands/drain.md +++ b/commands/drain.md @@ -1287,7 +1287,7 @@ it still holds is handed back. The drain routes each hand-back: | `user-visible` | `promoted`: an intent draft seeded from the issue (`capture promote`) | the draft, and the issue's `related_intents`; nothing else | | `trust-rule` | `decision-record`: flagged, with the lane's reason as `question` | `decision_needed:` on the open issue, holding the question; nothing else; no record is minted | | `design-finding`, `second-package` | `home`: flagged with the `home` the lane names | nothing | -| (fix rounds exhausted) | `home`: flagged, the issue staying open | nothing | +| (fix rounds exhausted with a security, major or critical finding left; a lane leaving only minor or nitpick findings lands, filing each as an open issue) | `home`: flagged, the issue staying open | nothing | | `stuck` (the lane kept refusing) | `home`: flagged, the issue staying open, naming the discard of the lane's run | nothing | | `closed` (its pull request closed unmerged) | `home`: flagged, the issue staying open, naming the discard of the lane's run | nothing | diff --git a/commands/implement.md b/commands/implement.md index a8d7d1302e..8e53c0ef70 100644 --- a/commands/implement.md +++ b/commands/implement.md @@ -934,7 +934,11 @@ the host. A routing table or provider configuration `step` cannot read is refused at `routing`, and its non-fatal reports are said on stderr; nothing is written by a refusal. A round's `routes` is state schema version 16's. A lane that has taken -the run's fix rounds (`build --fix-rounds`, bundled 3) and still does not pass +the run's fix rounds (`build --fix-rounds`, bundled 5) and still does not pass +lands when every finding the round leaves is minor or nitpick: the step goes to +`land`, and the records commit files each finding as an open issue (a failing +security reviewer or intent-auditor, a finding tagged `[major]` or +`[critical]`, and an untagged one count as more). Otherwise it is handed back: the result's `hand_back` names the verdict `unachievable` and the last findings, and the loop starts nothing further for it. Its sibling lanes finish under the same ceiling, window and fix rounds; no new lane opens, diff --git a/docs/reference/cli/commands.md b/docs/reference/cli/commands.md index b69f4b26c0..57708f234a 100644 --- a/docs/reference/cli/commands.md +++ b/docs/reference/cli/commands.md @@ -615,18 +615,20 @@ intent is not counted as a peer's. A session that has not joined is refused. Wit the run holds no claim, and the result says so. A new run is paced: a working window, a pause after it, a ceiling on the run's lanes and -validators alive at once, and the fix rounds a lane may take before it is handed back. The +validators alive at once, and the fix rounds a lane may take before its cap is judged. The four numbers are read once, when the run starts: --pace /, --sub-agents and --fix-rounds for this run, else pace.work_minutes, pace.pause_minutes, pace.sub_agents and pace.fix_rounds in the repository's .abcd/config.json, else in -~/.abcd.noindex/config.json, else the bundled 120/0 (no pause) with 2 sub-agents and 3 fix rounds. The result and the run +~/.abcd.noindex/config.json, else the bundled 120/0 (no pause) with 2 sub-agents and 5 fix rounds. The result and the run record name each number's layer. A malformed pace or ceiling, typed or configured, is refused naming the value and the accepted form, and writes nothing. Starting again keeps the run's pace; a flag naming another is refused. The window, the pause and the ceiling bind through `abcd implement step`, which hands out work only while a slot under the ceiling is free. A lane whose validators still do not pass after its fix rounds is -handed back: it stops as unachievable with the last round's findings, the run starts nothing -further for it, and `abcd implement step` refuses naming the hand-back. +handed back while a security finding, or a major or critical one, stands: it stops as +unachievable with the last round's findings, the run starts nothing further for it, and +`abcd implement step` refuses naming the hand-back. Otherwise every finding left is minor +or nitpick, and the lane lands with each filed as an open issue in its records commit. A new run reads its review set once, too: review.reviewers (one or two model classes per code-review role, for both roles or per role; bundled: research and default), review.judge @@ -713,7 +715,7 @@ Exit 2 on a refusal, exit 3 when a peer holds the intent or the run state is loc ``` --auto-plan[=true|false] plan a draft intent with no person present, after two plan reviews, on adr-2610310235000654's substitute for the sign-off - --fix-rounds string the fix rounds a lane of this run may take before it is handed back, a whole number from 0 (bundled: 3); wins over every configured layer + --fix-rounds string the fix rounds a lane of this run may take before its cap is judged, a whole number from 0 (bundled: 5); wins over every configured layer --pace string this run's working window and pause, / (e.g. 90/240); wins over every configured layer --release[=true|false] push the tombstone over this copy's reservation on the key, changing nothing in the run's state --session string the host session's id in the shared run state; a new run claims the intent for it @@ -791,7 +793,7 @@ state or the series is locked. **Flags:** ``` - --fix-rounds string the fix rounds a lane of the new run may take before it is handed back; wins over every configured layer + --fix-rounds string the fix rounds a lane of the new run may take before its cap is judged; wins over every configured layer --max int how many picks to make, one at a time under the pace rule; above 1 begins a series (default one pick) --pace string the new run's working window and pause, /; wins over every configured layer --session string the host session's id in the shared run state; the new run claims the picked intent for it @@ -2105,7 +2107,7 @@ passes that issue over as held. ``` --drive[=true|false] make every move from this terminal, starting each agent on a separate login and each next drain itself, until its end time, its own cap, an empty ledger or a stop --dry-run[=true|false] show every open issue's disposition and the order a drain takes them; writes nothing - --fix-rounds string the fix rounds a lane may take before it is handed back; wins over every configured layer + --fix-rounds string the fix rounds a lane may take before its cap is judged; wins over every configured layer --in-work int the most lanes a drain beginning now holds in work, 1 to 10; wins over the repository's drain.in_work_max (1 when neither sets it) --judgement string the host's answer to the judgement the drain awaits, at the path its request names --max int cap the lanes this drain opens, or with --drive the lanes the drive opens across the drains it works; the default is all @@ -4354,7 +4356,10 @@ round's routes with the failing gate output; a role on a runner, a review the re route takes, one pointed at a provider, a host-decides row and the implementer name no tier and do not move. A round that does not pass once the lane -has taken the run's fix rounds (--fix-rounds, bundled 3) hands the lane back instead: it +has taken the run's fix rounds (--fix-rounds, bundled 5) goes to its landing when every +finding it leaves is minor or nitpick (a security reviewer's failing verdict, an +intent-auditor's, and an untagged finding count as more), and the records commit files +each finding as an open issue; otherwise it hands the lane back instead: it stops as unachievable, the result and the run record name the last round's findings, and the run starts nothing further for it. Its sibling lanes finish: no new lane opens, no lane closes the spec, and a sibling whose round passes is held before its push, or before diff --git a/internal/core/implement/loop/capdefer.go b/internal/core/implement/loop/capdefer.go new file mode 100644 index 0000000000..2da640915e --- /dev/null +++ b/internal/core/implement/loop/capdefer.go @@ -0,0 +1,913 @@ +package loop + +// capdefer.go is what a lane does at its fix-round cap (the product thinker's +// ruling of 2 December 2026, iss-2612021201375528, replacing DR1's hand-back of +// every lane at the cap). A lane whose round still does not pass once it has +// taken the run's fix rounds is handed back only while a security finding, or a +// major or critical one, stands. Otherwise each finding the round leaves, minor +// or nitpick, is filed as an open issue through the ledger's capture, in the +// landing's records commit, and the lane goes on to land. +// +// A finding carries no severity of its own, so the rule reads the narrowest +// sound one (dcn-2612021257543635): +// +// - a security reviewer that did not pass is a security finding, whatever it +// located, and the intent-auditor that did not pass is a major one: a +// criterion not met, or not decided; +// - a ruthless reviewer's finding carries the severity its bullet's tag gives +// it, `[critical]`, `[major]`, `[minor]` or `[nitpick]` straight after its +// location, as the reviewer's brief asks (findingSeverityLine); an untagged +// finding reads as major, and so does a return that did not pass and +// locates none, since there is then nothing to file; +// - a finding filed must name a file the lane's worktree holds, as a +// capture's found_at must, and the reviewer whose words the record carries +// must name a model the records commit can disclose in its Assisted-by: +// trailer. +// +// Nothing new is kept in the run's state: the round the landing files from is +// the lane's latest round over its own change, read again from the returns as +// the loop recorded them (recordedReturn), and each record is known by its +// found_during, which names the lane, the run, the round and its head, and its +// found_at, so a call killed after a capture finds the record and files it once. + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "regexp" + "slices" + "strconv" + "strings" + "unicode/utf8" + + "github.com/intentdriven/abcd/internal/core/capture" + "github.com/intentdriven/abcd/internal/core/issuerecord" + "github.com/intentdriven/abcd/internal/core/issueschema" + "github.com/intentdriven/abcd/internal/core/mdrecord" + "github.com/intentdriven/abcd/internal/gitutil" + "github.com/intentdriven/abcd/internal/termsafe" +) + +// findingSeverityLine is what a ruthless reviewer's brief says of each finding's +// severity and remedy, which the fix-round cap reads. +const findingSeverityLine = "Tag each finding bullet with its severity straight after its location, one of `[security]`, `[critical]`, `[major]`, `[minor]` or `[nitpick]` " + + "(`- **path/file.go:12** [minor] — ...`; a NOTE is minor or nitpick, and any finding bearing on security is `[security]`), and give a minor or nitpick finding a nested `- *Remedy:* `. " + + "Once the lane has taken the run's fix rounds, a round whose findings are all minor or nitpick lets the lane land with each filed as an open issue; " + + "a security finding, an untagged one and a bullet that does not lead with its `file:line` hold the lane instead." + +// The severities a finding below major carries, which the cap files. +var belowMajor = []string{string(capture.SeverityMinor), string(capture.SeverityNitpick)} + +// severityTagRe is the severity tag a finding bullet's text opens with once its +// location is read. +var severityTagRe = regexp.MustCompile(`^\[(?i:(security|critical|major|minor|nitpick))\]`) + +// severitySecurity is the severity a ruthless reviewer's finding reads as when +// its tag or its words bear on security: it holds the lane as a failing +// security reviewer does, and nothing is filed for it in public. +const severitySecurity = "security" + +// securityWordsRe is the wording that makes a ruthless reviewer's finding read +// as bearing on security, wherever in its bullet or the lines nested under it +// (the rule the run's coordinator set for the facilitator in auto mode, +// dcn-2612021257543635). Each stem matches anywhere, in any case, inside an +// identifier too (access_token, api_secret, oauth, unsanitized), with two +// exceptions: cwe and leak only at the start of a word, and auth not where or +// follows it (author, authored, authority) unless authoris or authoriz does +// (authorization, unauthorized). The false holds this brings, an escaped +// string or a tokenizer, are the cost the rule accepts. +var securityWordsRe = regexp.MustCompile(`(?i)security|vulnerab|inject|traversal|secret|credential|token|privileg|bypass|\bcwe|` + + `attacker|exploit|\bleak|symlink|untrusted|sanitiz|escap|overflow|password|auth(?:$|[^o]|o(?:$|[^r])|ori[sz])`) + +// capLabelRe is a label a return writes between its findings, as a line or a +// sub-heading, which names no finding of its own. +var capLabelRe = regexp.MustCompile(`(?i)^[ \t]*(?:#{1,6}[ \t]+)?[*_]*[ \t]*(?:fix[- ]first|notes?|non[- ]blocking|blocking)[ \t]*[*_]*[ \t]*:?[ \t]*[*_]*[ \t]*$`) + +// severityRank orders the severities a location may carry, so the worst tag +// read at one location is the one it keeps; an untagged finding ranks as the +// worst, since nothing says it is small. +var severityRank = map[string]int{"nitpick": 1, "minor": 2, "major": 3, "critical": 4, severitySecurity: 5, "": 6} + +// nestedItemRe is an indented list item, the shape of a line nested under a +// finding bullet. +var nestedItemRe = regexp.MustCompile(`^(?:[ \t]{2,}|\t)(?:[-*+]|[0-9]{1,9}[.)])[ \t]+`) + +// recordIDRe is a record id written in prose, which record-lint holds to name a +// record the repository has. +var recordIDRe = regexp.MustCompile(`\b(?:iss|itd|spc|adr|dcn)-[0-9]+\b`) + +// The kinds of line eachCapFindingsLine hands over. +const ( + capLineSection = iota // a line of a Findings section + capLineMasked // one a code fence or HTML comment masks there + capLineAfter // one after a heading ended a Findings section +) + +// eachCapFindingsLine is eachFindingsLine with more handed over, so the cap +// reads every line a finding could hide in: the lines a code fence or an HTML +// comment masks inside a Findings section, a heading indented one to three +// columns there (as inside a list item) as a line of the section rather than +// its end, and every line after a column-0 heading ended a section, where a +// finding bullet stands outside any section. +func eachCapFindingsLine(text string, fn func(ln string, kind int)) { + lines := strings.Split(text, "\n") + mask := mdrecord.Read(lines, mdrecord.ListNested).Mask + depth, ended := 0, false + for i, ln := range lines { + if mask[i]&(mdrecord.MaskFence|mdrecord.MaskComment) != 0 { + if depth > 0 { + fn(ln, capLineMasked) + } + continue + } + d := headingDepth(ln) + switch { + case d > 0 && findingsHeading.MatchString(ln): + if depth == 0 || d < depth { + depth = d + } + case d > 0 && depth > 0 && (d > depth || ln[0] == ' ' || ln[0] == '\t'): + fn(ln, capLineSection) + case d > 0 && depth > 0: + depth, ended = 0, true + case depth > 0: + fn(ln, capLineSection) + case ended: + fn(ln, capLineAfter) + } + } +} + +// outsideFindingRe is a list item outside any Findings section that reads as +// a finding bullet: one leading with a bold location, or with a severity tag. +var outsideFindingRe = regexp.MustCompile("^[ \t]{0,3}(?:[-*+]|[0-9]{1,9}[.)])[ \t]+(?:(?:\\*\\*|__)`?/?[A-Za-z0-9_.][A-Za-z0-9_./+@-]*:[0-9]|[*_`]*\\[(?i:security|critical|major|minor|nitpick)\\])") + +// remedyLineRe is a nested line of a finding bullet naming its remedy: +// `- *Remedy:* ...`, `**Remedy**: ...` or `Remedy: ...`. +var remedyLineRe = regexp.MustCompile(`^[ \t]+(?:[-*+][ \t]+)?[*_]{0,2}(?i:remedy)[*_]{0,2}[ \t]*:[*_]{0,2}[ \t]*(\S.*)$`) + +// The bounds on what a filed record carries of a reviewer's words, in bytes. +const ( + maxCapStatement = 2000 + maxCapRemedy = 500 +) + +// capFinding is one finding a lane at its fix-round cap files as an open issue. +type capFinding struct { + file string + line int + severity string + statement string + remedy string + // role and reviewer are the reviewer whose return located it, and + // assisted the Assisted-by: value naming that reviewer's model. + role string + reviewer int + assisted string +} + +// foundAt is the finding's found_at. +func (f capFinding) foundAt() string { return f.file + ":" + strconv.Itoa(f.line) } + +// capFiling is what a lane's landing files at the fix-round cap: the round's +// findings, each one record, and the found_during every record carries. +type capFiling struct { + round ValidationRound + foundDuring string + findings []capFinding +} + +// capRound is the lane's round that left findings open at the fix-round cap, the +// round its landing files them from: its latest round over its own change (never +// the round that reads its records commit), when a validator of it did not pass +// and the lane is past its validate stage. nil otherwise, a lane still in its +// first validate stage included, where the cap is yet to be judged. +// +// A round a sync opened that passed after the cap round withdraws nothing: the +// sync merged the default branch and changed none of the lane's own work, so +// the findings the cap let the lane land with still stand, and the landing +// files them from the cap round. +func (l Lane) capRound() *ValidationRound { + if l.Stage != StageLand && l.Landing == nil { + return nil + } + for i := len(l.Validation) - 1; i >= 0; i-- { + r := l.Validation[i] + if l.readsRecords(r) { + continue + } + if slices.ContainsFunc(r.Validators, func(v ValidatorRun) bool { return v.Verdict != "" && !v.Pass }) { + return &l.Validation[i] + } + if !l.opensAfterSync(r) { + return nil + } + } + return nil +} + +// capRoundBefore reports whether round r, which a sync of the lane opened, +// follows a round the lane went to its landing from at the fix-round cap: the +// lane's latest round before it over its own change, past any other passing +// round a sync opened, did not pass. +func (l Lane) capRoundBefore(r ValidationRound) bool { + if !l.opensAfterSync(r) { + return false + } + at := slices.IndexFunc(l.Validation, func(v ValidationRound) bool { return v.Round == r.Round }) + for i := at - 1; i >= 0; i-- { + p := l.Validation[i] + if l.readsRecords(p) { + continue + } + if slices.ContainsFunc(p.Validators, func(v ValidatorRun) bool { return v.Verdict != "" && !v.Pass }) { + return true + } + if !l.opensAfterSync(p) { + return false + } + } + return false +} + +// opensAfterSync reports whether a sync of the lane opened round r. +func (l Lane) opensAfterSync(r ValidationRound) bool { + return slices.ContainsFunc(l.Syncs, func(s Sync) bool { return s.Round == r.Round }) +} + +// capFoundDuring is the found_during of every record a lane files from round r. +func capFoundDuring(st State, lane Lane, r ValidationRound) string { + return fmt.Sprintf("the review of %s in run %s, round %d at %s, left open at the fix-round cap", lane.ID, st.RunID, r.Round, r.HeadSHA) +} + +// capFilingFor reads what round r leaves at the fix-round cap: the filing when +// every validator that did not pass leaves only findings below major, or why +// the lane is handed back instead. +func capFilingFor(c Context, lane Lane, r ValidationRound) (*capFiling, string, error) { + f := &capFiling{round: r, foundDuring: capFoundDuring(c.State, lane, r)} + seen := map[location]bool{} + for _, v := range r.Validators { + if v.Verdict == "" || v.Pass { + continue + } + switch v.Role { + case RoleRuthless: + case RoleSecurity: + return nil, fmt.Sprintf("the %s said %s, a security finding", v.Role, v.Verdict), nil + default: + return nil, fmt.Sprintf("the %s said %s, which reads as a major finding", v.Role, v.Verdict), nil + } + assisted, problem := reviewerTrailer(v) + if problem != "" { + return nil, fmt.Sprintf("the %s's model cannot be disclosed in the records commit that would carry its words (its model %s)", v.Role, problem), nil + } + raw, err := recordedReturn(c.RepoRoot, lane, v) + if err != nil { + return nil, "", err + } + found, unread := readCapFindings(string(raw), lane.Worktree) + if unread != "" { + return nil, fmt.Sprintf("the %s's return holds %s, which reads as a major finding", v.Role, unread), nil + } + if len(found) == 0 { + return nil, fmt.Sprintf("the %s said %s and locates no finding to file, which reads as a major finding", v.Role, v.Verdict), nil + } + for _, x := range found { + switch { + case x.severity == severitySecurity: + // Neither the finding nor its place is named: a security finding is + // named nowhere public. + return nil, fmt.Sprintf("a finding of the %s bears on security, which holds the lane as a security finding does", v.Role), nil + case x.severity == "": + return nil, fmt.Sprintf("the %s's finding at %s carries no severity, which reads as major", v.Role, x.foundAt()), nil + case !slices.Contains(belowMajor, x.severity): + return nil, fmt.Sprintf("the %s's finding at %s is %s", v.Role, x.foundAt(), x.severity), nil + case !fileHeld(lane.Worktree, x.file): + return nil, fmt.Sprintf("the %s's finding at %s names no file the lane's worktree holds, so it cannot be filed there", v.Role, x.foundAt()), nil + } + if id := unresolvedID(lane.Worktree, x.statement+" "+x.remedy); id != "" { + return nil, fmt.Sprintf("the %s's finding at %s cites %s, which names no record the lane's worktree holds, so record-lint would refuse its record", v.Role, x.foundAt(), id), nil + } + at := location{x.file, x.line} + if seen[at] { + // Two reviewers citing one place file one record. + continue + } + seen[at] = true + x.role, x.reviewer, x.assisted = v.Role, v.Reviewer, assisted + if x.remedy == "" { + x.remedy = issueschema.MachineRemedy + } + f.findings = append(f.findings, x) + } + } + if len(f.findings) == 0 { + return nil, "no validator that did not pass left a finding to file", nil + } + return f, "", nil +} + +// capFilingOf is what the lane's landing files at the fix-round cap, nil when +// its latest round over its own change passed. A round that no longer reads as +// one to file from (a sync took away a file a finding names, say) is refused: +// capLanding hands the lane back on it instead, where the landing may. +func capFilingOf(c Context, lane Lane) (*capFiling, error) { + f, why, err := capLanding(c, lane) + if err != nil { + return nil, err + } + if why != "" { + return nil, refuse(string(StageLand), "", lane.ID, why, + "put back the round's returns as the loop recorded them, or restore the run's state file, then run `abcd implement step` again") + } + return f, nil +} + +// capLanding is capFilingOf with why the round no longer reads as one to file +// from, "" when it does or there is none. +func capLanding(c Context, lane Lane) (*capFiling, string, error) { + r := lane.capRound() + if r == nil { + return nil, "", nil + } + f, why, err := capFilingFor(c, lane, *r) + if err != nil || why == "" { + return f, "", err + } + return nil, fmt.Sprintf("round %d did not pass, and the lane went to its landing because every finding it left was below major, but now %s", r.Round, why), nil +} + +// reviewerTrailer is the Assisted-by: value naming the model whose words a +// reviewer's return carries, or what is wrong with it: the model its runner +// reported, else the one its return named, else the one it was asked for, a +// route's `/` taken off, as the trailer names a model. +func reviewerTrailer(v ValidatorRun) (string, string) { + model := v.ReviewerModel + if v.ModelStatus != ModelReported && v.ReviewerNamed != "" { + model = v.ReviewerNamed + } + if _, problem := modelTrailer(model); problem != "" { + if i := strings.LastIndex(model, "/"); i >= 0 { + model = model[i+1:] + } + } + return modelTrailer(model) +} + +// fileHeld reports whether the lane's worktree holds a regular file at rel. +func fileHeld(worktree, rel string) bool { + info, err := os.Lstat(filepath.Join(worktree, filepath.FromSlash(rel))) + return err == nil && info.Mode().IsRegular() +} + +// readCapFindings reads each finding bullet under a return's Findings headings, +// as recordFindings reads their locations: the severity its tag gives, or +// severitySecurity where its words bear on security, the statement after it, +// and the remedy a nested line names. A location cited twice keeps the worst +// severity read at it and both statements. It also says what of the section it +// cannot read, "" when it reads all of it. Every line of the section is read: +// a line at column 0 straight after a finding continues it, its tag and words +// read with it; a label (FIX-FIRST, NOTES) names no finding. What holds is a +// top-level list item that does not lead with a `file:line`, an indented one +// nested under no located finding or opening with a tag or a location, a +// sub-heading or a paragraph attached to no finding, and a finding bullet a +// code fence or comment hides, wherever in the section it opens or closes. +func readCapFindings(text, worktree string) ([]capFinding, string) { + var out []capFinding + index := map[location]int{} + cur := -1 + unread := "" + hold := func(why string) { + if unread == "" { + unread = why + } + } + // blank is whether the line before was blank, which ends a paragraph: a line + // at column 0 after it continues nothing. + blank := false + eachCapFindingsLine(relativeTo(text, worktree), func(ln string, kind int) { + switch kind { + case capLineAfter: + if outsideFindingRe.MatchString(ln) || locatedAndTagged(ln) { + hold("a finding bullet after a heading that ended the Findings section") + } + return + case capLineMasked: + if hiddenFinding(ln) { + hold("a finding bullet a code fence or comment hides") + } + blank = false + return + } + if strings.TrimSpace(ln) == "" { + blank = true + return + } + wasBlank := blank + blank = false + if capLabelRe.MatchString(ln) { + cur = -1 + return + } + if headingDepth(ln) > 0 { + hold("a sub-heading under Findings that is not a label") + cur = -1 + return + } + if at, rest, ok := leadBullet(ln); ok { + sev, statement := severityOf(rest) + if securityWordsRe.MatchString(rest) { + sev = severitySecurity + } + if i, seen := index[at]; seen { + if severityRank[sev] > severityRank[out[i].severity] { + out[i].severity = sev + } + if statement != "" { + out[i].statement = strings.TrimSpace(out[i].statement + "; " + statement) + } + cur = i + return + } + index[at] = len(out) + out = append(out, capFinding{file: at.file, line: at.line, severity: sev, statement: statement}) + cur = len(out) - 1 + return + } + if leadRe.MatchString(ln) { + hold("a finding bullet that does not lead with its file:line") + cur = -1 + return + } + if ln[0] != ' ' && ln[0] != '\t' { + if cur < 0 || wasBlank { + hold("a paragraph under Findings attached to no finding") + cur = -1 + return + } + // The finding's own text, wrapped onto a line at column 0. + line := strings.TrimSpace(ln) + if m := severityTagRe.FindStringSubmatch(strings.TrimLeft(line, "*_`")); m != nil { + if sev := strings.ToLower(m[1]); severityRank[sev] > severityRank[out[cur].severity] { + out[cur].severity = sev + } + } + if securityWordsRe.MatchString(line) { + out[cur].severity = severitySecurity + } + out[cur].statement = strings.TrimSpace(out[cur].statement + " " + line) + return + } + if cur < 0 { + hold("an indented line under Findings attached to no finding") + return + } + if m := nestedItemRe.FindStringIndex(ln); m != nil { + item := ln[m[1]:] + if bare := strings.TrimLeft(item, "*_`(<\"' \t"); severityTagRe.MatchString(bare) || + leadCitationRe.MatchString(strings.TrimLeft(bare, "[")) { + hold("an indented finding bullet under another finding") + return + } + } + if nestedItemRe.FindStringIndex(ln) == nil { + // An indented line of the finding's own text: a tag it opens with is + // the finding's too. + if m := severityTagRe.FindStringSubmatch(strings.TrimLeft(ln, " \t*_`")); m != nil { + if sev := strings.ToLower(m[1]); severityRank[sev] > severityRank[out[cur].severity] { + out[cur].severity = sev + } + } + } + if securityWordsRe.MatchString(ln) { + out[cur].severity = severitySecurity + } + if m := remedyLineRe.FindStringSubmatch(ln); m != nil && out[cur].remedy == "" { + out[cur].remedy = strings.TrimSpace(m[1]) + } + }) + if unread == "" && unclosedBlock(text) { + unread = "a code fence or comment left open, which hides every line after it" + } + return out, unread +} + +// locatedAndTagged reports whether a list item leads with a `file:line`, in +// whatever marks, followed by a severity tag: a finding's shape, never a +// verdict's line. +func locatedAndTagged(ln string) bool { + _, rest, ok := leadBullet(ln) + if !ok { + return false + } + sev, _ := severityOf(rest) + return sev != "" +} + +// hiddenFinding reports whether a line a fence or comment masks would read as a +// finding bullet: any list item at the top level, and at any indent one leading +// with a `file:line` or opening with a severity tag. A list quoted at the top +// level of an evidence fence holds the lane too, the cost of the rule. +func hiddenFinding(ln string) bool { + // A list item at the top level holds whatever it says: a fence closed in the + // wrong place may hide any finding, located or not. + if leadRe.MatchString(ln) { + return true + } + t := " " + strings.TrimLeft(ln, " \t") + if _, _, ok := leadBullet(t); ok { + return true + } + m := nestedItemRe.FindStringIndex(" " + t) + if m == nil { + return false + } + // The marks a location stands behind go; a tag keeps its own bracket. + return severityTagRe.MatchString(strings.TrimLeft((" " + t)[m[1]:], "*_`(<\"' \t")) +} + +// unclosedBlock reports whether text ends inside a fenced code block or an HTML +// comment, which masks every finding bullet after its opening: a line set after +// the text reads as masked only then. +func unclosedBlock(text string) bool { + lines := append(strings.Split(text, "\n"), "", "end") + mask := mdrecord.Read(lines, mdrecord.ListNested).Mask + return mask[len(lines)-1]&(mdrecord.MaskFence|mdrecord.MaskComment) != 0 +} + +// unresolvedID is the first record id text cites that names no record file +// under the worktree's .abcd/, "" when each names one. +func unresolvedID(worktree, text string) string { + ids := recordIDRe.FindAllString(text, -1) + if len(ids) == 0 { + return "" + } + var names, adrs []string + adrDir := filepath.Join(worktree, ".abcd", "development", "decisions", "adrs") + _ = filepath.WalkDir(filepath.Join(worktree, ".abcd"), func(path string, d os.DirEntry, err error) error { + if err == nil && !d.IsDir() && strings.HasSuffix(d.Name(), ".md") { + names = append(names, d.Name()) + if filepath.Dir(path) == adrDir { + adrs = append(adrs, d.Name()) + } + } + return nil + }) + named := func(in []string, key string) bool { + return slices.ContainsFunc(in, func(n string) bool { return n == key+".md" || strings.HasPrefix(n, key+"-") }) + } + for _, id := range ids { + if num, ok := strings.CutPrefix(id, "adr-"); ok { + // An ADR's file in the ADR store carries its number alone, an ordinal + // padded to four digits (adr-43 is 0043-...), and no adr- prefix. + if len(num) < 4 { + num = strings.Repeat("0", 4-len(num)) + num + } + if !named(adrs, num) { + return id + } + continue + } + if !named(names, id) { + return id + } + } + return "" +} + +// leadBullet is leadLocation with the text after the location. +func leadBullet(ln string) (location, string, bool) { + m := leadRe.FindStringIndex(ln) + if m == nil { + return location{}, "", false + } + c := leadCitationRe.FindStringSubmatch(ln[m[1]:]) + if c == nil { + return location{}, "", false + } + at, ok := toLocation(c[1], c[2]) + return at, ln[m[1]+len(c[0]):], ok +} + +// severityOf reads the severity tag and the statement from a finding bullet's +// text after its location: the closing marks the location stood behind go, +// then the tag, then the dash or colon before the statement. +func severityOf(rest string) (string, string) { + rest = strings.TrimLeft(rest, "*_`)]>\"' \t") + sev := "" + if m := severityTagRe.FindStringSubmatch(rest); m != nil { + sev = strings.ToLower(m[1]) + rest = rest[len(m[0]):] + } + rest = strings.TrimLeft(rest, " \t-:—–") + return sev, strings.TrimSpace(rest) +} + +// clipBytes bounds s to n bytes on a rune boundary. +func clipBytes(s string, n int) string { + if len(s) <= n { + return s + } + for n > 0 && !utf8.RuneStart(s[n]) { + n-- + } + return strings.TrimSpace(s[:n]) + "..." +} + +// capRecordText is the body of the record a lane files for f. +func capRecordText(st State, lane Lane, filing *capFiling, f capFinding) string { + statement := clipBytes(termsafe.Sanitize(f.statement), maxCapStatement) + if statement == "" { + statement = "The finding states nothing beyond its location." + } + what := "building " + st.Intent + " against " + st.Spec + if iss := st.Issue(); iss != "" { + what = "fixing " + iss + } + r := filing.round + return fmt.Sprintf("%s\n\nThe %s (reviewer %d) of lane %s in run %s, %s, found this at %s in round %d, which judged %s. "+ + "The round came after the run's cap of %s, and nothing it left was a security, major or critical finding, "+ + "so the lane landed and its landing filed this %s finding as an open issue.\n", + statement, f.role, f.reviewer, lane.ID, st.RunID, what, f.foundAt(), r.Round, r.HeadSHA, fixRoundsPhrase(st.FixRoundCap()), f.severity) +} + +// capRemedy is the remedy of the record a lane files for f: one line. +func capRemedy(f capFinding) string { + r := clipBytes(strings.Join(strings.Fields(termsafe.Sanitize(f.remedy)), " "), maxCapRemedy) + if r == "" { + return issueschema.MachineRemedy + } + return r +} + +// match is the index of the finding a record's text files, or -1: an issue +// record valid as written whose found_during is the filing's and whose +// found_at and severity are one finding's that taken does not hold already. +func (f *capFiling) match(content string, taken map[int]bool) int { + fm, _, err := issuerecord.Parse(content) + if err != nil || issuerecord.ValidateStrict(fm) != nil { + return -1 + } + if s, _ := fm["found_during"].(string); s != f.foundDuring { + return -1 + } + at, _ := fm["found_at"].(string) + sev, _ := fm["severity"].(string) + for i, x := range f.findings { + if !taken[i] && at == x.foundAt() && sev == x.severity { + return i + } + } + return -1 +} + +// captureAtCap is the ledger's capture the cap files through; a test stands in +// for it to make the capture refuse or degrade. +var captureAtCap = capture.Capture + +// capFiled is what fileAtCap did: how many records it filed, how many it found +// a killed call had filed, and what the capture said of each record it altered +// or could not redact (its redaction-degraded note), for the run's record. +type capFiled struct { + filed, found int + notes []string + // paths are the records this call wrote, which a refusal that will come + // again takes back out, so the hand-back leaves the worktree as it was. + paths []string +} + +// fileAtCap files each finding of filing as an open issue in the lane's +// worktree, through the ledger's capture, unless the worktree's open/ already +// holds its record, as a call killed after the capture leaves it. +func fileAtCap(st State, lane Lane, filing *capFiling) (capFiled, error) { + var done capFiled + open := filepath.Join(lane.Worktree, filepath.FromSlash(capture.LedgerRelPath), string(capture.StateOpen)) + names, err := filepath.Glob(filepath.Join(open, "iss-*.md")) + if err != nil { + return done, err + } + taken := map[int]bool{} + for _, name := range names { + info, err := os.Lstat(name) + if err != nil || !info.Mode().IsRegular() || info.Size() > maxRecordBytes { + continue + } + data, err := os.ReadFile(name) + if err != nil { + continue + } + if i := filing.match(string(data), taken); i >= 0 { + taken[i] = true + done.found++ + // A record a killed call filed is taken back out with this call's own. + done.paths = append(done.paths, name) + } + } + for i, x := range filing.findings { + if taken[i] { + continue + } + res, err := captureAtCap(capture.CaptureRequest{RepoRoot: lane.Worktree, Text: capRecordText(st, lane, filing, x), + Severity: capture.Severity(x.severity), Category: "bug", Source: "impl-review", + FoundDuring: filing.foundDuring, FoundAt: x.foundAt(), Remedy: capRemedy(x)}) + if err != nil { + return done, fmt.Errorf("filing the finding at %s: %w", x.foundAt(), err) + } + // The capture names its record relative to the worktree. + p := filepath.FromSlash(res.Path) + if !filepath.IsAbs(p) { + p = filepath.Join(lane.Worktree, p) + } + done.paths = append(done.paths, p) + if res.Degraded != "" { + done.notes = append(done.notes, fmt.Sprintf("the record filing the finding at %s was written with redaction degraded: %s", x.foundAt(), termsafe.Sanitize(res.Degraded))) + } + if res.Redacted > 0 { + done.notes = append(done.notes, fmt.Sprintf("the record filing the finding at %s had %d span(s) redacted", x.foundAt(), res.Redacted)) + } + done.filed++ + } + return done, nil +} + +// capRefusalFinal reports whether the capture's refusal is one a later call +// meets again: the request itself refused (a found_at, a remedy, a field +// value), or text the redactor cannot resolve or has no scanner for. Contention +// for the ledger's lock, and a write that failed, may pass on a later call. +func capRefusalFinal(err error) bool { + var field *capture.FieldValueError + return errors.As(err, &field) || errors.Is(err, capture.ErrRequestRefused) || errors.Is(err, capture.ErrRemedyRequired) || + errors.Is(err, capture.ErrRedactionResidual) || errors.Is(err, capture.ErrScannerUnavailable) +} + +// capHandBackOutcome is the outcome handing a lane back at its fix-round cap +// from round r: the hand-back's own summary for the run's record, and why the +// cap rule did not let the lane land, which names no finding's words. +func capHandBackOutcome(st State, r ValidationRound, why string) Outcome { + hb := capLandingHandBack(st, r) + return Outcome{HandBack: hb, Note: handBackSummary(keyOf(st), *hb) + "; " + why} +} + +// capLandingHandBack is the hand-back of a lane at its fix-round cap, at its +// validate stage or at a landing that cannot file what the cap round left: the +// round's verdicts, the returns of the validators that did not pass, and what +// an audit among them left unmet or undecided. +func capLandingHandBack(st State, r ValidationRound) *HandBack { + hb := &HandBack{Verdict: VerdictUnachievable, Round: r.Round, FixRounds: st.FixRoundCap(), Verdicts: verdictsLine(r)} + for _, v := range r.Validators { + if v.Verdict == "" || v.Pass { + continue + } + hb.Findings = append(hb.Findings, v.Return) + if v.Audit != nil { + hb.NotMet = append(hb.NotMet, v.Audit.NotMet...) + hb.Undecided = append(hb.Undecided, v.Audit.Inconclusive...) + } + } + return hb +} + +// openAdds are the entries of git's raw list that add a record to the issue +// store's open/. +func openAdds(raw string) ([]rawEntry, error) { + entries, err := parseRawDiff(raw) + if err != nil { + return nil, err + } + var out []rawEntry + for _, e := range entries { + if store, bucket, _, ok := storeRecord(e.path); ok && store.rel == issueStore.rel && bucket == string(capture.StateOpen) && e.status == "A" { + out = append(out, e) + } + } + return out, nil +} + +// filedAdds matches each added open record to the finding of filing it files: +// the id each finding's record carries, by the finding's index, and the path +// of the first added record that files none, "" when every one files one. +func filedAdds(repo string, filing *capFiling, adds []rawEntry) (map[int]string, string, error) { + ids := map[int]string{} + if len(adds) == 0 { + return ids, "", nil + } + if filing == nil { + return nil, adds[0].path, nil + } + objects := make([]string, len(adds)) + for i, e := range adds { + objects[i] = e.newObject + } + blobs, err := gitutil.CatFileBatch(repo, objects, len(adds)*(maxRecordBytes+256)) + if err != nil || len(blobs) != len(adds) { + return nil, adds[0].path, nil + } + taken := map[int]bool{} + for k, e := range adds { + if blobs[k].Missing { + return nil, e.path, nil + } + i := filing.match(blobs[k].Content, taken) + if i < 0 { + return nil, e.path, nil + } + taken[i] = true + fm, _, _ := issuerecord.Parse(blobs[k].Content) + id, _ := fm["id"].(string) + ids[i] = id + } + return ids, "", nil +} + +// filingLacks names the first finding of filing no record added in raw files, +// "" when each has its record. +func filingLacks(repo string, filing *capFiling, raw string) (string, error) { + if filing == nil { + return "", nil + } + adds, err := openAdds(raw) + if err != nil { + return "", err + } + ids, odd, err := filedAdds(repo, filing, adds) + if err != nil { + return "", err + } + if odd != "" { + return "a record of " + strconv.Quote(termsafe.Sanitize(odd)) + " that files no finding left at the fix-round cap", nil + } + for i, x := range filing.findings { + if _, ok := ids[i]; !ok { + return "the record filing the " + x.severity + " finding at " + x.foundAt() + " left at the fix-round cap", nil + } + } + return "", nil +} + +// filedIDs are the ids of the records the commit range base..head adds for +// filing, in finding order. +func filedIDs(repo string, filing *capFiling, base, head string) ([]string, error) { + if filing == nil { + return nil, nil + } + raw, err := gitutil.RunCappedAsStored(repo, maxBaseListing, "diff-tree", "-r", "--raw", "--no-renames", "--no-abbrev", "--ignore-submodules=none", "-z", base, head, "--") + if err != nil { + return nil, fmt.Errorf("reading what %s changes: %w", shortSHA(head), err) + } + adds, err := openAdds(raw) + if err != nil { + return nil, err + } + ids, _, err := filedAdds(repo, filing, adds) + if err != nil { + return nil, err + } + var out []string + for i := range filing.findings { + if id, ok := ids[i]; ok && id != "" { + out = append(out, id) + } + } + return out, nil +} + +// landingAssisted are the records commit's Assisted-by: trailers: one per model +// the lane's receipts reported, and, where the commit files findings left at the +// fix-round cap, one per model of the reviewers whose words those records carry. +func landingAssisted(lane Lane, filing *capFiling) ([]string, string) { + out, gap := assistedByTrailers(lane.Receipts) + if gap != "" { + return nil, gap + } + if filing != nil { + for _, f := range filing.findings { + if t := "Assisted-by: " + f.assisted; !slices.Contains(out, t) { + out = append(out, t) + } + } + } + return out, "" +} + +// filedPhrase names how many findings a filing holds. +func filedPhrase(n int) string { + if n == 1 { + return "1 finding" + } + return fmt.Sprintf("%d findings", n) +} + +// capFilingScope is what the round that reads a records commit is told of the +// records it files for the findings the lane left at the fix-round cap, "" for +// a lane that left none. +func capFilingScope(lane Lane) string { + r := lane.capRound() + if r == nil { + return "" + } + return fmt.Sprintf("This lane reached its landing at the run's cap of fix rounds: round %d at `%s` did not pass, and every finding it left was minor or nitpick, "+ + "so this commit also files each of them as an open issue in `%s/%s/`. Judge each such record against the finding it files: its location, severity, statement and remedy. "+ + "A record that bears on security must not be public: say so as a FIX FIRST finding against it, naming only its file.\n\n", + r.Round, r.HeadSHA, capture.LedgerRelPath, capture.StateOpen) +} diff --git a/internal/core/implement/loop/capdefer_test.go b/internal/core/implement/loop/capdefer_test.go new file mode 100644 index 0000000000..0bb25cbfed --- /dev/null +++ b/internal/core/implement/loop/capdefer_test.go @@ -0,0 +1,694 @@ +package loop + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "regexp" + "strings" + "testing" + + "github.com/intentdriven/abcd/internal/core/capture" + "github.com/intentdriven/abcd/internal/gittest" +) + +// The fix-round cap's ruling of 2 December 2026 (iss-2612021201375528): five +// rounds when nothing sets the cap, and at the cap a lane is handed back only +// while a security finding or a major or critical one stands; otherwise each +// finding left, minor or nitpick, is filed as an open issue and the lane lands. + +// capReviewerModel is the model a cap test's reviewer names: one the records +// commit can disclose, and not the fixtures' writer. +const capReviewerModel = "claude-sonnet-9" + +// capReturn is a ruthless reviewer's return naming capReviewerModel, with +// findings under its Findings heading. +func capReturn(verdict, findings string) string { + return ReviewerModelPrefix + " " + capReviewerModel + "\n\n### Analysis\n\nRead the lane's diff.\n\n### Findings\n\n" + findings + + "\n### Verdict\n\n- **" + verdict + "** — as stated.\n" +} + +// minorFinding is a finding bullet at one.txt:1 tagged minor, with its remedy. +const minorFinding = "- **one.txt:1** [minor] — the line ends without a newline.\n" + + " - *Failure scenario:* a reader concatenating files joins two lines.\n" + + " - *Remedy:* end the file with a newline.\n" + +// TestTheBundledFixRoundCapIsFive is the ruling's default: a run on nothing +// set takes five fix rounds before the cap is judged. +func TestTheBundledFixRoundCapIsFive(t *testing.T) { + if BundledFixRounds != 5 { + t.Fatalf("the bundled fix-round cap is 5, not %d", BundledFixRounds) + } + repo := loopRepo(t, readyIntent("", settledQuestions), specWithSteps("")) + res, err := startedOnce(t, repo, "itd-10") + if err != nil { + t.Fatal(err) + } + st, _ := ReadState(repo.Root(), res.RunID) + if f := st.Pace.FixRounds; f.Value != 5 || f.Layer != "bundled" { + t.Fatalf("a run on nothing set holds its lanes to 5 fix rounds: %+v", f) + } +} + +// atTheCap starts a run on itd-10 with no fix round allowed and implements its +// lane, so its first round that does not pass is judged at the cap. +func atTheCap(t *testing.T) (*gittest.Repo, string, Stages) { + t.Helper() + repo := briefRepo(t, agentsMarked) + start, err := Start(repo.Root(), "itd-10", Options{FixRounds: strp("0")}) + if err != nil { + t.Fatal(err) + } + implemented(t, repo, start.RunID, DefaultStages(), "one.txt") + return repo, start.RunID, DefaultStages() +} + +// TestAtTheCapARoundLeavingOnlyMinorFindingsGoesToItsLanding: a ruthless +// reviewer whose every finding is tagged minor or nitpick does not hand the +// lane back at the cap; the lane goes to its landing, naming the findings it +// will file, and no fix brief is written. +func TestAtTheCapARoundLeavingOnlyMinorFindingsGoesToItsLanding(t *testing.T) { + repo, id, stages := atTheCap(t) + handBack(t, repo, id, stages, RoleRuthless, capReturn("FIX FIRST", minorFinding+ + "- **one.txt:2** [nitpick] — a word is misspelt.\n")) + passRound(t, repo, id, stages, RoleSecurity, RoleAuditor) + res, err := advance(repo.Root(), id, stages, Options{}) + if err != nil { + t.Fatal(err) + } + if res.HandBack != nil || res.Awaiting != nil { + t.Fatalf("a round leaving only minor findings at the cap neither hands the lane back nor starts a fix round: %+v", res) + } + l := currentLane(t, repo, id) + if l.Stage != StageLand || l.HandBack != nil { + t.Fatalf("the lane goes to its landing: %+v", l) + } + st, _ := ReadState(repo.Root(), id) + var record strings.Builder + for _, e := range st.Record { + record.WriteString(e.Note + "\n") + } + for _, want := range []string{"minor or nitpick", "2 findings", "open issues"} { + if !strings.Contains(record.String(), want) { + t.Fatalf("the run record says why the lane lands and what it files (%q):\n%s", want, record.String()) + } + } + if _, err := os.Stat(filepath.Join(repo.Root(), filepath.FromSlash(RunRelDir), id, l.ID, "validate", "round-1", FixDirName)); !os.IsNotExist(err) { + t.Fatalf("no fix brief is written past the cap: %v", err) + } +} + +// TestAtTheCapASecurityOrMajorFindingHandsTheLaneBack: at the cap, a security +// reviewer that did not pass, a finding tagged major or critical, an untagged +// finding and a return that locates nothing each hand the lane back as before. +func TestAtTheCapASecurityOrMajorFindingHandsTheLaneBack(t *testing.T) { + for name, tc := range map[string]struct{ ruthless, security string }{ + "security": {capReturn("SHIP", ""), capReturn("BLOCK", minorFinding)}, + "major": {capReturn("FIX FIRST", minorFinding+"- **one.txt:3** [major] — the file is truncated.\n"), ""}, + "critical": {capReturn("FIX FIRST", "- **one.txt:3** [critical] — the file is lost.\n"), ""}, + "untagged": {capReturn("FIX FIRST", "- **one.txt:3** — the file is truncated.\n"), ""}, + "unlocated": {capReturn("FIX FIRST", "- the file is truncated somewhere.\n"), ""}, + "unheld": {capReturn("FIX FIRST", "- **gone.txt:3** [minor] — a file no tree holds.\n"), ""}, + } { + t.Run(name, func(t *testing.T) { + repo, id, stages := atTheCap(t) + handBack(t, repo, id, stages, RoleRuthless, tc.ruthless) + if tc.security != "" { + handBack(t, repo, id, stages, RoleSecurity, tc.security) + passRound(t, repo, id, stages, RoleAuditor) + } else { + passRound(t, repo, id, stages, RoleSecurity, RoleAuditor) + } + res, err := advance(repo.Root(), id, stages, Options{}) + if err != nil { + t.Fatal(err) + } + if res.HandBack == nil || res.Stage != StageHandedBack || res.HandBack.Verdict != VerdictUnachievable { + t.Fatalf("the lane is handed back at the cap: %+v", res) + } + }) + } +} + +// TestTheReviewerBriefAsksForEachFindingsSeverity: the ruthless reviewer's +// brief asks for the severity tag and the remedy the cap reads. +func TestTheReviewerBriefAsksForEachFindingsSeverity(t *testing.T) { + repo, id, stages := atTheCap(t) + res, err := advance(repo.Root(), id, stages, Options{}) + if err != nil || res.Awaiting == nil || res.Awaiting.Role != RoleRuthless { + t.Fatalf("want the ruthless reviewer handed out: %+v %v", res, err) + } + brief, err := os.ReadFile(filepath.Join(repo.Root(), filepath.FromSlash(res.Awaiting.Brief))) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(brief), findingSeverityLine) { + t.Fatalf("the ruthless reviewer's brief asks for each finding's severity and remedy:\n%s", brief) + } +} + +// TestALandingAtTheCapFilesEachFindingAsAnOpenIssue: the landing of a lane +// that reached it at the cap files each finding left as an open issue in its +// records commit, through the ledger's capture: found at the finding's +// location, with its severity and remedy, naming the lane, the run, the round +// and the head it judged; the commit discloses the reviewer whose words the +// records carry, and the pull request's body says what was filed. +func TestALandingAtTheCapFilesEachFindingAsAnOpenIssue(t *testing.T) { + f, judged := capLandingAt(t, minorFinding) + repo, id := f.repo, f.runID + + for range 2 { + if res := f.step(t); res.Stage != StageLand { + t.Fatalf("a landing step leaves the lane at land: %+v", res) + } + } + l := currentLane(t, repo, id) + if l.HeadSHA == judged || l.Landing == nil || !l.Landing.RecordsDone { + t.Fatalf("the landing's records are committed on the lane: %+v", l.Landing) + } + files := repo.Git("-C", l.Worktree, "diff-tree", "-r", "--name-status", "--no-renames", judged, l.HeadSHA) + var filed []string + for _, ln := range strings.Split(files, "\n") { + if p, ok := strings.CutPrefix(ln, "A\t.abcd/work/issues/open/"); ok { + filed = append(filed, p) + } + } + if len(filed) != 1 { + t.Fatalf("the records commit files the one finding left as an open issue:\n%s", files) + } + record := repo.Git("-C", l.Worktree, "show", l.HeadSHA+":.abcd/work/issues/open/"+filed[0]) + for _, field := range []string{`(?m)^severity: "?minor"?$`, `(?m)^found_at: "?one\.txt:1"?$`, `(?m)^remedy: "?end the file with a newline\.?"?$`} { + if !regexp.MustCompile(field).MatchString(record) { + t.Fatalf("the filed record's frontmatter matches %s:\n%s", field, record) + } + } + for _, want := range []string{"the line ends without a newline", + l.ID, id, "round 1", judged} { + if !strings.Contains(record, want) { + t.Fatalf("the filed record carries %q:\n%s", want, record) + } + } + msg := repo.Git("-C", l.Worktree, "log", "-1", "--format=%B", l.HeadSHA) + for _, want := range []string{"Assisted-by: Claude:" + capReviewerModel, "Assisted-by: Claude:" + f.model, "1 finding"} { + if !strings.Contains(msg, want) { + t.Fatalf("the records commit says what it filed and discloses the reviewer (%q):\n%s", want, msg) + } + } +} + +// capLandingAt drives a land fixture with no fix round allowed through its +// implementer and a round whose ruthless reviewer returns FIX FIRST with +// findings, to the first step of its landing, and returns the head judged. +func capLandingAt(t *testing.T, findings string) (*landFixture, string) { + t.Helper() + return capLandingIn(t, newLandFixture(t, queueRuleset("MERGE")), findings) +} + +// capLandingIn is capLandingAt on the land fixture f. +func capLandingIn(t *testing.T, f *landFixture, findings string) (*landFixture, string) { + t.Helper() + repo, id := f.repo, f.runID + // No fix round allowed: the first round that does not pass is at the cap. + path := filepath.Join(repo.Root(), filepath.FromSlash(StateRelPath(id))) + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var st State + if err := json.Unmarshal(raw, &st); err != nil { + t.Fatal(err) + } + st.Pace.FixRounds = PaceValue{Value: 0, Layer: "flag", Origin: "--fix-rounds 0"} + out, _ := json.Marshal(st) + if err := os.WriteFile(path, out, 0o600); err != nil { + t.Fatal(err) + } + + stepTo(t, repo, id, f.stages, StageImplement) + if res, err := advance(repo.Root(), id, f.stages, Options{}); err != nil || res.Awaiting == nil { + t.Fatalf("the implement stage awaits an implementer: %+v %v", res, err) + } + l := currentLane(t, repo, id) + dir := filepath.Join(repo.Root(), filepath.FromSlash(RunRelDir), id, l.ID) + sha := laneCommit(t, repo, l, "one.txt") + rc := goodReceipt(t, id, l, dir, sha) + receipt := writeReceipt(t, dir, map[string]any{ + "schema_version": rc.SchemaVersion, "run_id": rc.RunID, "lane": rc.Lane, "branch": rc.Branch, + "commits": rc.Commits, "definition_of_done": rc.DefinitionOfDone, "report": rc.Report, "model": f.model, + }) + if _, err := Receipt(repo.Root(), id, receipt, f.stages, Options{}); err != nil { + t.Fatalf("the receipt verifies: %v", err) + } + handBack(t, repo, id, f.stages, RoleRuthless, capReturn("FIX FIRST", findings)) + passRound(t, repo, id, f.stages, RoleSecurity, RoleAuditor) + l = stepTo(t, repo, id, f.stages, StageLand) + return f, l.HeadSHA + +} + +// handedBackAtTheCap judges a round at the cap whose ruthless reviewer returns +// FIX FIRST with findings while the other reviewers pass, and fails unless the +// lane is handed back. +func handedBackAtTheCap(t *testing.T, findings string) (*gittest.Repo, string) { + t.Helper() + repo, id, stages := atTheCap(t) + handBack(t, repo, id, stages, RoleRuthless, capReturn("FIX FIRST", findings)) + passRound(t, repo, id, stages, RoleSecurity, RoleAuditor) + res, err := advance(repo.Root(), id, stages, Options{}) + if err != nil { + t.Fatal(err) + } + if res.HandBack == nil || res.Stage != StageHandedBack || res.HandBack.Verdict != VerdictUnachievable { + t.Fatalf("the lane is handed back at the cap: %+v", res) + } + return repo, id +} + +// TestAtTheCapAFindingBulletTheCapCannotReadHoldsTheLane: beside a minor +// finding the cap reads, a finding bullet it cannot read (one with no +// location, its tag first, a directory, a file with no line, indented under +// nothing, or hidden by a fence left open) holds the lane as a major finding +// would, rather than being passed over. +func TestAtTheCapAFindingBulletTheCapCannotReadHoldsTheLane(t *testing.T) { + for name, extra := range map[string]string{ + "no location": "- [critical] nothing calls the new check.\n", + "tag first": "- [major] **one.txt:3** — the file is truncated.\n", + "directory": "- **internal/x/** [critical] — the verb is never wired.\n", + "no line": "- **one.txt** [critical] — the file is truncated.\n", + "indented": "\n - **one.txt:3** [critical] — the file is truncated.\n", + "indented tag": " - [critical] the file is truncated.\n", + "indented heading": "- **one.txt:2** [minor] — the comment is stale:\n # the old comment\n- **one.txt:3** [critical] — the write is lost on error.\n", + "plain location after a heading": "- **one.txt:2** [minor] — x.\n# the old comment\n- one.txt:3 [critical] — the write is lost on error.\n", + "backtick location after a heading": "- **one.txt:2** [minor] — x.\n# the old comment\n- `one.txt:3` [critical] — the write is lost on error.\n", + "column-0 heading": "- **one.txt:2** [minor] — the comment is stale:\n# the old comment\n- **one.txt:3** [critical] — the write is lost on error.\n", + "hidden plain bullet": "- **one.txt:2** [nitpick] — x.\n```\nquoted\n- nothing calls the new check.\n```go\nz\n```\n", + "indented tag line": "- **one.txt:2** [minor] — a word.\n [critical] the file is lost too.\n", + "paragraph": "\nThe file is also truncated.\n", + "sub-heading": "#### One more\n", + "continued tag": "- **one.txt:2** [minor] — a word\n[critical] the file is lost.\n", + "refenced nested": "- **one.txt:2** [nitpick] — x.\n ```\n quoted\n- **one.txt:3** [critical] — the file is lost.\n ```go\n z\n ```\n", + "refenced top": "- **one.txt:2** [nitpick] — x.\n```\nquoted\n- **one.txt:3** [critical] — the file is lost.\n```go\nz\n```\n", + "open fence": "- **one.txt:2** [nitpick] — a word.\n ```\n quoted\n- **one.txt:3** [critical] — the file is truncated.\n", + } { + t.Run(name, func(t *testing.T) { handedBackAtTheCap(t, minorFinding+extra) }) + } +} + +// TestAtTheCapTheWorstSeverityAtALocationHoldsTheLane: two findings at one +// location are each read, and the worse of their tags decides, in either +// order. +func TestAtTheCapTheWorstSeverityAtALocationHoldsTheLane(t *testing.T) { + for name, findings := range map[string]string{ + "minor then critical": minorFinding + "- **one.txt:1** [critical] — the file is lost.\n", + "nitpick then major": "- **one.txt:1** [nitpick] — a word.\n- **one.txt:1** [major] — the file is truncated.\n", + "untagged after": minorFinding + "- **one.txt:1** — the file is truncated.\n", + } { + t.Run(name, func(t *testing.T) { handedBackAtTheCap(t, findings) }) + } +} + +// TestAtTheCapARuthlessFindingOnSecurityHoldsTheLane: a ruthless reviewer's +// finding tagged security, or worded on security in its bullet or a line +// under it, holds the lane as a security reviewer that did not pass does, and +// the hand-back names neither the finding nor its place. +func TestAtTheCapARuthlessFindingOnSecurityHoldsTheLane(t *testing.T) { + cases := map[string]string{ + "tagged": "- **one.txt:1** [security] — see the analysis.\n", + "nested words": "- **one.txt:1** [minor] — see below.\n - *Failure scenario:* a credential reaches the log.\n", + "wrapped line": "- **one.txt:1** [minor] — the name is joined unchecked,\nso a crafted one is a traversal out of the root.\n", + } + for _, word := range []string{"security", "vulnerab", "injection", "traversal", "secret", "credential", "token", "privilege", "bypass", "CWE", + "attacker", "exploit", "leak", "symlink", "untrusted", "sanitiz", "escape", "overflow", "password", "auth", + "authentication", "authorization", "unauthenticated", "unauthorized", "bypassed", "leaked", "leaking", "privileged", "unprivileged", + "injected", "symlinked", "escapes", "unescaped", "unsanitized", + "access_token", "auth_token", "api_secret", "user_password", "accessToken", "oauth"} { + cases["word "+word] = fmt.Sprintf("- **one.txt:1** [minor] — the line reads %s here.\n", strings.ToUpper(word[:1])+word[1:]) + } + for name, findings := range cases { + t.Run(name, func(t *testing.T) { + repo, id := handedBackAtTheCap(t, findings) + st, _ := ReadState(repo.Root(), id) + for _, e := range st.Record { + if strings.Contains(e.Note, "one.txt") && strings.Contains(e.Note, "security") { + t.Fatalf("the hand-back's note names the place of a finding on security: %s", e.Note) + } + } + }) + } +} + +// TestAtTheCapAFindingCitingNoRecordHoldsTheLane: a finding whose words cite +// a record id the lane's tree does not hold would be refused by record-lint +// once filed, so it holds the lane at the cap instead. +func TestAtTheCapAFindingCitingNoRecordHoldsTheLane(t *testing.T) { + handedBackAtTheCap(t, "- **one.txt:1** [minor] — the line repeats iss-1.\n - *Remedy:* drop it.\n") +} + +// capSynced is a sync fixture whose lane went to its landing at the cap and +// whose landing's sync merged a moved default branch, the fresh round over the +// merge head yet to be judged, and the head the cap round judged. +type capSynced struct { + *landFixture + judged string +} + +// capSyncFixture walks a sync fixture with no fix round allowed through a cap +// round leaving one minor finding, to its landing's sync over a moved default +// branch. +func capSyncFixture(t *testing.T) capSynced { + t.Helper() + f := syncFixture(t) + repo := f.repo + path := filepath.Join(repo.Root(), filepath.FromSlash(StateRelPath(f.runID))) + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var st State + if err := json.Unmarshal(raw, &st); err != nil { + t.Fatal(err) + } + st.Pace.FixRounds = PaceValue{Value: 0, Layer: "flag", Origin: "--fix-rounds 0"} + out, _ := json.Marshal(st) + if err := os.WriteFile(path, out, 0o600); err != nil { + t.Fatal(err) + } + stepTo(t, repo, f.runID, f.stages, StageImplement) + if res, err := advance(repo.Root(), f.runID, f.stages, Options{}); err != nil || res.Awaiting == nil { + t.Fatalf("the implement stage awaits an implementer: %+v %v", res, err) + } + l := currentLane(t, repo, f.runID) + dir := filepath.Join(repo.Root(), filepath.FromSlash(RunRelDir), f.runID, l.ID) + sha := commitIn(t, repo, l, "fix.txt") + rc := goodReceipt(t, f.runID, l, dir, sha) + rc.Model = "claude-mythos-5" + rc.Resolves = []Resolution{{Issue: f.issue, Commit: sha, Note: "the page names the flag", Impact: "fix", + Grounds: "pursued: the page names the flag; shown wrong if it still does not"}} + if _, err := Receipt(repo.Root(), f.runID, writeReceipt(t, dir, rc), f.stages, Options{}); err != nil { + t.Fatal(err) + } + handBack(t, repo, f.runID, f.stages, RoleRuthless, capReturn("FIX FIRST", "- **fix.txt:1** [minor] — the line ends without a newline.\n - *Remedy:* end the file with a newline.\n")) + passRound(t, repo, f.runID, f.stages, RoleSecurity) + judged := stepTo(t, repo, f.runID, f.stages, StageLand).HeadSHA + f.moveMain(t, "another account's file\n", "other.txt") + + f.step(t) + if l := currentLane(t, repo, f.runID); l.Stage != StageValidate || len(l.Syncs) != 1 { + t.Fatalf("the sync merges the default branch and sends the lane to a fresh round: %+v", l) + } + return capSynced{f, judged} +} + +// TestAPassingSyncRoundAfterTheCapStillFilesItsFindings: a lane that went to +// its landing at the cap and whose landing's sync merged a moved default +// branch, the fresh round over the merge head passing, still files what the +// cap round left: the sync changed none of the lane's own work. +func TestAPassingSyncRoundAfterTheCapStillFilesItsFindings(t *testing.T) { + f := capSyncFixture(t) + repo, judged := f.repo, f.judged + passRound(t, repo, f.runID, f.stages, RoleRuthless, RoleSecurity) + l := stepTo(t, repo, f.runID, f.stages, StageLand) + if r := l.capRound(); r == nil || r.HeadSHA != judged { + t.Fatalf("the cap round still names what the landing files after a passing sync round: %+v", r) + } + for range 3 { + if l = currentLane(t, repo, f.runID); l.Landing != nil && l.Landing.RecordsDone { + break + } + f.step(t) + } + l = currentLane(t, repo, f.runID) + if l.Landing == nil || !l.Landing.RecordsDone { + t.Fatalf("the landing's records are committed: %+v", l.Landing) + } + files := repo.Git("-C", l.Worktree, "diff-tree", "-r", "--name-status", "--no-renames", "HEAD~1", "HEAD") + if !strings.Contains(files, "A\t.abcd/work/issues/open/") { + t.Fatalf("the records commit files the cap round's finding:\n%s", files) + } +} + +// stubCaptureAtCap stands fn in for the cap's capture for the test. +func stubCaptureAtCap(t *testing.T, fn func(capture.CaptureRequest) (capture.CaptureResult, error)) { + t.Helper() + was := captureAtCap + captureAtCap = fn + t.Cleanup(func() { captureAtCap = was }) +} + +// TestALandingAtTheCapRecordsWhatTheCaptureSaysOfItsRedaction: what the +// ledger's capture says of a record it filed (spans redacted, a redactor +// running degraded) reaches the run's record rather than being dropped. +func TestALandingAtTheCapRecordsWhatTheCaptureSaysOfItsRedaction(t *testing.T) { + stubCaptureAtCap(t, func(req capture.CaptureRequest) (capture.CaptureResult, error) { + res, err := capture.Capture(req) + res.Redacted, res.Degraded = 1, "the scanner could not be made" + return res, err + }) + f, _ := capLandingAt(t, minorFinding) + for range 2 { + f.step(t) + } + st, _ := ReadState(f.repo.Root(), f.runID) + var record strings.Builder + for _, e := range st.Record { + record.WriteString(e.Note + "\n") + } + for _, want := range []string{"redaction degraded: the scanner could not be made", "1 span(s) redacted"} { + if !strings.Contains(record.String(), want) { + t.Fatalf("the run's record keeps what the capture said (%q):\n%s", want, record.String()) + } + } +} + +// TestACaptureRefusingForGoodHandsTheLandingBack: a capture refusal that a +// later call would meet again hands the lane back at its landing, taking back +// any record the call filed first and committing nothing; a refusal that may +// pass later leaves the lane at land to be stepped again. +func TestACaptureRefusingForGoodHandsTheLandingBack(t *testing.T) { + two := minorFinding + "- **one.txt:2** [nitpick] — a word is misspelt.\n" + t.Run("for good", func(t *testing.T) { + stubCaptureAtCap(t, func(req capture.CaptureRequest) (capture.CaptureResult, error) { + if req.FoundAt == "one.txt:2" { + return capture.CaptureResult{}, fmt.Errorf("%w: a span", capture.ErrRedactionResidual) + } + return capture.Capture(req) + }) + f, judged := capLandingAt(t, two) + var res StepResult + for range 2 { + if res = f.step(t); res.HandBack != nil { + break + } + } + if res.HandBack == nil || res.Stage != StageHandedBack { + t.Fatalf("a capture refusing for good hands the landing back: %+v", res) + } + l := currentLane(t, f.repo, f.runID) + if tip := strings.TrimSpace(f.repo.Git("-C", l.Worktree, "rev-parse", "HEAD")); tip != judged { + t.Fatalf("nothing is committed: %s, judged %s", tip, judged) + } + if left := f.repo.Git("-C", l.Worktree, "status", "--porcelain", "--untracked-files=all", "--", ".abcd/work/issues/open"); strings.TrimSpace(left) != "" { + t.Fatalf("the record filed first is taken back:\n%s", left) + } + }) + t.Run("for now", func(t *testing.T) { + stubCaptureAtCap(t, func(capture.CaptureRequest) (capture.CaptureResult, error) { + return capture.CaptureResult{}, errors.New("the ledger's lock is held") + }) + f, _ := capLandingAt(t, two) + f.step(t) + if _, err := advance(f.repo.Root(), f.runID, f.stages, Options{}); err == nil { + t.Fatal("a capture that may pass later refuses the step") + } + if l := currentLane(t, f.repo, f.runID); l.Stage != StageLand || l.HandBack != nil { + t.Fatalf("the lane stays at land to be stepped again: %+v", l) + } + }) +} + +// TestAClosedFenceUnderAFindingLeavesItReadable: evidence quoted in a closed +// fence under a minor finding leaves the return wholly read, while the same +// fence left open does not. +func TestAClosedFenceUnderAFindingLeavesItReadable(t *testing.T) { + quoted := minorFinding + " ```go\n x := 1\n ```\n- **one.txt:2** [nitpick] — a word.\n" + found, unread := readCapFindings(capReturn("FIX FIRST", quoted), t.TempDir()) + if unread != "" || len(found) != 2 { + t.Fatalf("a closed fence hides nothing: %q %+v", unread, found) + } + open := minorFinding + " ```go\n x := 1\n- **one.txt:2** [critical] — the file is lost.\n" + if _, unread := readCapFindings(capReturn("FIX FIRST", open), t.TempDir()); unread == "" { + t.Fatal("a fence left open is read as hiding what follows it") + } +} + +// TestTheCapReadsItsLabelsAndWrappedLines: the FIX-FIRST and NOTES labels a +// ruthless return writes between its findings hold nothing, and a bullet +// wrapped onto a line at column 0 is read as one finding. +func TestTheCapReadsItsLabelsAndWrappedLines(t *testing.T) { + text := "FIX-FIRST\n\n- **one.txt:1** [minor] — the line ends\nwithout a newline.\n - *Remedy:* end it.\n\nNOTES\n\n- **one.txt:2** [nitpick] — a word.\n" + found, unread := readCapFindings(capReturn("FIX FIRST", text), t.TempDir()) + if unread != "" || len(found) != 2 || found[0].severity != "minor" || found[0].remedy != "end it." { + t.Fatalf("labels hold nothing and a wrapped line is its bullet's: %q %+v", unread, found) + } +} + +// TestACitedRecordResolvesByItsFileName: a finding's citation of an ADR, filed +// under its number alone, names a record; an id no file carries does not. +func TestACitedRecordResolvesByItsFileName(t *testing.T) { + root := t.TempDir() + for _, rel := range []string{".abcd/development/decisions/adrs/2610031751065746-the-worktree-store.md", ".abcd/work/issues/open/iss-2611111111111111-a.md"} { + path := filepath.Join(root, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte("x\n"), 0o600); err != nil { + t.Fatal(err) + } + } + if id := unresolvedID(root, "see adr-2610031751065746 and iss-2611111111111111"); id != "" { + t.Fatalf("both ids name a record: %s", id) + } + if id := unresolvedID(root, "see adr-2610031751065747"); id != "adr-2610031751065747" { + t.Fatalf("an ADR no file carries is named: %q", id) + } + for _, rel := range []string{".abcd/development/decisions/adrs/0043-inbound-equals-outbound.md", ".abcd/development/brief/04-surfaces/34-build.md"} { + path := filepath.Join(root, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte("x\n"), 0o600); err != nil { + t.Fatal(err) + } + } + if id := unresolvedID(root, "see adr-43"); id != "" { + t.Fatalf("an ordinal ADR resolves by its padded file: %s", id) + } + if id := unresolvedID(root, "see adr-34"); id != "adr-34" { + t.Fatalf("an ordinal ADR resolves on the ADR store alone, never a brief page of that number: %q", id) + } +} + +// landsAtTheCap judges a round at the cap whose ruthless reviewer returns FIX +// FIRST with findings while the other reviewers pass, and fails unless the lane +// goes to its landing. +func landsAtTheCap(t *testing.T, findings string) { + t.Helper() + repo, id, stages := atTheCap(t) + handBack(t, repo, id, stages, RoleRuthless, capReturn("FIX FIRST", findings)) + passRound(t, repo, id, stages, RoleSecurity, RoleAuditor) + res, err := advance(repo.Root(), id, stages, Options{}) + if err != nil { + t.Fatal(err) + } + if res.HandBack != nil || res.Stage != StageLand { + t.Fatalf("the lane goes to its landing: %+v", res) + } +} + +// TestTheSecurityWordsAreWholeWords: auth followed by or (author, authored, +// authority) is not read as bearing on security, so a minor finding stays +// minor. +func TestTheSecurityWordsAreWholeWords(t *testing.T) { + for name, findings := range map[string]string{ + "author": "- **one.txt:1** [minor] — the author line is blank.\n - *Remedy:* fill it.\n", + "authored": "- **one.txt:1** [minor] — the line authored last is blank.\n - *Remedy:* fill it.\n", + "authority": "- **one.txt:1** [minor] — the authority field is blank.\n - *Remedy:* fill it.\n", + } { + t.Run(name, func(t *testing.T) { landsAtTheCap(t, findings) }) + } +} + +// TestAtTheCapAReportCarryingAVerdictIsRefused: only the loop writes a verdict, +// so a lane whose report states one is refused at the cap whether its round +// passes or leaves only minor findings for its landing to file. +func TestAtTheCapAReportCarryingAVerdictIsRefused(t *testing.T) { + for name, judge := range map[string]func(*testing.T, *gittest.Repo, string, Stages){ + "passes": func(t *testing.T, repo *gittest.Repo, id string, stages Stages) { + passRound(t, repo, id, stages, RoleRuthless, RoleSecurity, RoleAuditor) + }, + "fails below major": func(t *testing.T, repo *gittest.Repo, id string, stages Stages) { + handBack(t, repo, id, stages, RoleRuthless, capReturn("FIX FIRST", minorFinding)) + passRound(t, repo, id, stages, RoleSecurity, RoleAuditor) + }, + } { + t.Run(name, func(t *testing.T) { + repo, id, stages := atTheCap(t) + report := filepath.Join(repo.Root(), filepath.FromSlash(RunRelDir), id, "lane-1", ReportFileName) + if err := os.WriteFile(report, []byte("built it\n\nVerdict: SHIP\n"), 0o600); err != nil { + t.Fatal(err) + } + judge(t, repo, id, stages) + _, err := advance(repo.Root(), id, stages, Options{}) + if r := mustRefusal(t, err); r.Stage != string(StageValidate) || !strings.Contains(r.Reason, "verdict") { + t.Fatalf("the report carrying a verdict is refused: %+v", r) + } + }) + } +} + +// TestACapLanesPassingRecordsRoundPushesInApprovalMode: in approval mode a cap +// lane's records commit goes to its own round, and once that round passes the +// landing pushes the records commit it read. +func TestACapLanesPassingRecordsRoundPushesInApprovalMode(t *testing.T) { + f, _ := capLandingAt(t, minorFinding) + f.step(t) + f.step(t) + records := currentLane(t, f.repo, f.runID).HeadSHA + f.recordsRound(t, "SHIP", "APPROVE") + l := f.pushToArm(t) + if l.Landing == nil || l.Landing.Pushed != records || f.remoteBranch(t, l.Branch) == "" { + t.Fatalf("the records commit the passing round read is pushed: %+v", l.Landing) + } +} + +// TestARecordsRoundFailingOverACapFilingHandsTheLaneBack: a lane whose landing +// filed findings at the cap sends its records commit to a round of its own in +// every facilitator mode, and a round of it that does not pass hands the lane +// back with nothing pushed, so a filed record never reaches the forge unread. +func TestARecordsRoundFailingOverACapFilingHandsTheLaneBack(t *testing.T) { + for name, fixture := range map[string]func(*testing.T) *landFixture{ + "auto": autoFixture, + "approval": func(t *testing.T) *landFixture { return newLandFixture(t, queueRuleset("MERGE")) }, + } { + t.Run(name, func(t *testing.T) { + f, _ := capLandingIn(t, fixture(t), minorFinding) + f.step(t) + f.step(t) + if l := currentLane(t, f.repo, f.runID); l.Landing == nil || !l.Landing.RecordsDone { + t.Fatalf("the records are committed: %+v", l.Landing) + } + // The step sends the records commit to its round, before any push. + f.recordsRound(t, "SHIP", "BLOCK") + res, err := advance(f.repo.Root(), f.runID, f.stages, Options{}) + if err != nil { + t.Fatal(err) + } + if res.HandBack == nil || res.Stage != StageHandedBack { + t.Fatalf("a records round that does not pass over a cap filing hands the lane back: %+v", res) + } + l := currentLane(t, f.repo, f.runID) + if f.remoteBranch(t, l.Branch) != "" || l.Landing.Pushed != "" { + t.Fatalf("nothing is pushed: %+v", l.Landing) + } + }) + } +} + +// TestAFailingSyncRoundAfterTheCapRoundHandsTheLaneBack: a lane that went to +// its landing at the cap and whose sync round then fails, even on findings +// below major, is handed back rather than filing the later round's findings +// in place of the cap round's. +func TestAFailingSyncRoundAfterTheCapRoundHandsTheLaneBack(t *testing.T) { + f := capSyncFixture(t) + handBack(t, f.repo, f.runID, f.stages, RoleRuthless, capReturn("FIX FIRST", "- **fix.txt:1** [nitpick] — another word.\n - *Remedy:* fix it.\n")) + passRound(t, f.repo, f.runID, f.stages, RoleSecurity) + res, err := advance(f.repo.Root(), f.runID, f.stages, Options{}) + if err != nil { + t.Fatal(err) + } + if res.HandBack == nil || res.Stage != StageHandedBack { + t.Fatalf("a failing sync round after the cap round hands the lane back: %+v", res) + } +} diff --git a/internal/core/implement/loop/fixrounds_test.go b/internal/core/implement/loop/fixrounds_test.go index 40936d4818..abb1f3bfd5 100644 --- a/internal/core/implement/loop/fixrounds_test.go +++ b/internal/core/implement/loop/fixrounds_test.go @@ -13,7 +13,7 @@ import ( // The fix-round rulings of 2026-09-29: DQ1a (an undecided criterion in the // fidelity audit reopens the work exactly as a not-met one does) and DR1 (the // fix rounds a lane may take before it is handed back are a per-run value set -// beside --pace, default 3), on itd-50's criteria 1 and 2 and +// beside --pace, default 3, raised to 5 on 2 December 2026), on itd-50's criteria 1 and 2 and // itd-2609211116005482's falsified pick. // TestAnUndecidedCriterionReopensTheWorkLikeANotMet is ruling DQ1a: an audit @@ -52,7 +52,7 @@ func TestAnUndecidedCriterionReopensTheWorkLikeANotMet(t *testing.T) { } // TestTheFixRoundCapIsSetBesideThePace is ruling DR1: a run's fix-round cap is -// 3 when nothing sets it, the repository's pace.fix_rounds over the bundled +// 5 when nothing sets it (iss-2612021201375528), the repository's pace.fix_rounds over the bundled // value, --fix-rounds over every layer; the run keeps it in its state and its // record names it; a malformed value is refused naming the accepted form and // writes no state; a resume naming another cap is refused. @@ -64,10 +64,10 @@ func TestTheFixRoundCapIsSetBesideThePace(t *testing.T) { t.Fatal(err) } st, _ := ReadState(repo.Root(), res.RunID) - if f := st.Pace.FixRounds; f.Value != BundledFixRounds || f.Layer != "bundled" || BundledFixRounds != 3 { - t.Fatalf("the bundled cap is 3 fix rounds: %+v", f) + if f := st.Pace.FixRounds; f.Value != BundledFixRounds || f.Layer != "bundled" || BundledFixRounds != 5 { + t.Fatalf("the bundled cap is 5 fix rounds: %+v", f) } - if note := paceRecord(t, st); !strings.Contains(note, "3 fix rounds") { + if note := paceRecord(t, st); !strings.Contains(note, "5 fix rounds") { t.Fatalf("the run record names the cap: %q", note) } }) diff --git a/internal/core/implement/loop/land.go b/internal/core/implement/loop/land.go index 5f5f085d3d..e94dcf0c04 100644 --- a/internal/core/implement/loop/land.go +++ b/internal/core/implement/loop/land.go @@ -63,6 +63,7 @@ import ( "encoding/json" "errors" "fmt" + "io/fs" "os" "path" "path/filepath" @@ -334,6 +335,21 @@ func landStage(c Context, lane *Lane) (Outcome, error) { switch { case !ld.RecordsDone: return landRecords(c, lane) + case ld.Pushed == "" && lane.capRound() != nil: + // A records commit that files what the fix-round cap left goes to a round + // of its own in every facilitator mode, and is pushed only once that round + // passed: a filed record never reaches the forge unread. + if r := lane.Validation[len(lane.Validation)-1]; lane.readsRecords(r) && + slices.ContainsFunc(r.Validators, func(v ValidatorRun) bool { return v.Verdict != "" && !v.Pass }) { + return capHandBackOutcome(c.State, r, fmt.Sprintf("round %d read the landing's records commit, which files what the fix-round cap left, and did not pass, so nothing is pushed", r.Round)), nil + } + if lane.recordsRoundDue() { + if why := recordsParked(c, *lane); why != "" { + return capHandBackOutcome(c.State, *lane.capRound(), "the landing's records commit files what the fix-round cap left, and it would go to a person's pull request unread: "+why), nil + } + return Outcome{Goto: StageValidate, LandLeft: true, Note: "the landing's records commit " + shortSHA(lane.HeadSHA) + " files what the fix-round cap left, so it goes to a review round of its own, before anything is pushed"}, nil + } + return landPush(c, lane) case ld.Pushed == "": due, err := recordsRoundWanted(c, *lane) if err != nil { @@ -461,6 +477,16 @@ func landPrepare(c Context, lane *Lane) (Outcome, error) { for _, r := range lane.Resolves { does = append(does, "resolves "+r.Issue) } + filing, why, err := capLanding(c, *lane) + if err != nil { + return Outcome{}, err + } + if why != "" { + return capHandBackOutcome(c.State, *lane.capRound(), why), nil + } + if filing != nil { + does = append(does, "files "+filedPhrase(len(filing.findings))+" left below major at the fix-round cap as open issues") + } if len(does) == 0 { // The records commit is made on every lane, so the rule the lane was // admitted under rides it into history (itd-2610301850454860). @@ -539,8 +565,16 @@ func landRecords(c Context, lane *Lane) (Outcome, error) { ld.Records, ld.RecordsDone, lane.HeadSHA = tip, true, tip return Outcome{Stay: true, Note: "found the landing's records commit " + shortSHA(tip) + " on " + lane.Branch}, nil } + // What the lane left at the fix-round cap, filed below as open issues. + filing, why, err := capLanding(c, *lane) + if err != nil { + return Outcome{}, err + } + if why != "" { + return capHandBackOutcome(st, *lane.capRound(), why), nil + } - if why, err := strayChanges(st, *lane); err != nil { + if why, err := strayChanges(st, *lane, filing); err != nil { return Outcome{}, fmt.Errorf("reading the lane's worktree: %w", err) } else if why != "" { return Outcome{}, strayRefusal(*lane, why) @@ -592,15 +626,41 @@ func landRecords(c Context, lane *Lane) (Outcome, error) { } assisted := []string{composedAssistedBy()} composed := true - if ld.Closes || len(lane.Resolves) > 0 || ld.SpecSettled { + if ld.Closes || len(lane.Resolves) > 0 || ld.SpecSettled || filing != nil { composed = false var gap string - if assisted, gap = assistedByTrailers(lane.Receipts); gap != "" { + if assisted, gap = landingAssisted(*lane, filing); gap != "" { return Outcome{}, modelGap(*lane, "the landing's records commit carries text the lane's implementer composed", gap) } } wt := lane.Worktree + // Each finding the round left at the cap becomes an open issue, through the + // ledger's capture, in the records this commit carries. It is filed before the + // landing writes anything else, so a capture that will refuse again hands the + // lane back with nothing else moved. + filedLine, filedNotes := "", []string(nil) + if filing != nil { + got, err := fileAtCap(st, *lane, filing) + if err != nil { + why := "the ledger's capture refused a finding left at the fix-round cap in the lane's worktree: " + termsafe.Sanitize(fsutil.RedactHome(err.Error())) + if capRefusalFinal(err) { + for _, path := range got.paths { + if err := os.Remove(path); err != nil && !errors.Is(err, fs.ErrNotExist) { + return Outcome{}, fmt.Errorf("taking back a record filed at the fix-round cap: %w", err) + } + } + return capHandBackOutcome(st, filing.round, why), nil + } + return Outcome{}, refuse(string(StageLand), "", lane.ID, why, + "settle what the capture store names in the lane's worktree and leave it uncommitted, then run `abcd implement step` again") + } + filedLine = fmt.Sprintf("filed %s left below major at the fix-round cap (round %d at %s) as open issues", filedPhrase(got.filed+got.found), filing.round.Round, shortSHA(filing.round.HeadSHA)) + if got.found > 0 { + filedLine += fmt.Sprintf(", %d of them found filed already", got.found) + } + filedNotes = got.notes + } var trailers, done []string if ld.SpecSettled { done = append(done, "carried the change to "+st.Spec+" left in the lane's worktree") @@ -721,6 +781,9 @@ func landRecords(c Context, lane *Lane) (Outcome, error) { done = append(done, "resolved "+r.Issue+" with "+shortSHA(r.Commit)) } } + if filedLine != "" { + done = append(done, filedLine) + } trailers = append(trailers, resolutionTrailers(st, *lane)...) if beforeLandingStage != nil { beforeLandingStage(wt) @@ -750,7 +813,7 @@ func landRecords(c Context, lane *Lane) (Outcome, error) { if err != nil { return Outcome{}, fmt.Errorf("reading the landing's staged records: %w", err) } - if why, err := judgeLandingDiff(wt, st, *lane, raw); err != nil { + if why, err := judgeLandingDiff(wt, st, *lane, raw, filing); err != nil { return Outcome{}, err } else if why != "" { return Outcome{}, strayRefusal(*lane, why) @@ -786,7 +849,7 @@ func landRecords(c Context, lane *Lane) (Outcome, error) { // A mark is abcd's only when this landing writes it. if !only || ld.MarkStep == 0 { var gap string - if assisted, gap = assistedByTrailers(lane.Receipts); gap != "" { + if assisted, gap = landingAssisted(*lane, filing); gap != "" { return Outcome{}, modelGap(*lane, "the landing's records commit carries text abcd did not compose", gap) } done = append(done, "carried what else was left in the lane's worktree") @@ -825,7 +888,9 @@ func landRecords(c Context, lane *Lane) (Outcome, error) { return Outcome{}, err } ld.Records, ld.RecordsDone, lane.HeadSHA = head, true, head - return Outcome{Stay: true, Note: "committed the landing's records as " + shortSHA(head) + ": " + strings.Join(done, "; ")}, nil + // What the capture said of the records it filed reaches the run's record, never + // the commit: a note may name what it could not redact. + return Outcome{Stay: true, Note: "committed the landing's records as " + shortSHA(head) + ": " + strings.Join(append(done, filedNotes...), "; ")}, nil } // refuseNotTheRecords holds a commit at the lane branch's tip to what the landing's @@ -849,7 +914,11 @@ func refuseNotTheRecords(c Context, lane Lane, tip, which string) error { if err != nil { return fmt.Errorf("reading what %s changes: %w", shortSHA(tip), err) } - if why, err := judgeLandingDiff(c.RepoRoot, st, lane, raw); err != nil { + filing, err := capFilingOf(c, lane) + if err != nil { + return err + } + if why, err := judgeLandingDiff(c.RepoRoot, st, lane, raw, filing); err != nil { return err } else if why != "" { return refuse(string(StageLand), "", lane.ID, shortSHA(tip)+", the commit "+which+" on the judged head "+shortSHA(lane.HeadSHA)+", holds "+why+", and "+strayRule, @@ -858,7 +927,7 @@ func refuseNotTheRecords(c Context, lane Lane, tip, which string) error { if err := refuseFoundCloseRecords(c, lane, tip, which, lane.Landing.Closes); err != nil { return err } - if lacks, err := foundCommitLacks(c, lane, tip, raw); err != nil { + if lacks, err := foundCommitLacks(c, lane, tip, raw, filing); err != nil { return err } else if lacks != "" { return refuse(string(StageLand), "", lane.ID, shortSHA(tip)+", the commit "+which+" on the judged head "+shortSHA(lane.HeadSHA)+", lacks "+lacks+", so it is not the landing's records", @@ -1484,7 +1553,7 @@ func stagedRawArgs(head string) []string { // strayChanges judges the lane's worktree as `git add` would stage it, on a copy of the // lane's index, so the lane's own index and its flags stay as they are and the person's // filters and ignore files read the tree. "" when nothing in it stops the landing. -func strayChanges(st State, lane Lane) (string, error) { +func strayChanges(st State, lane Lane, filing *capFiling) (string, error) { wt := lane.Worktree own, err := pickGit(wt, "rev-parse", "--git-path", "index") if err != nil { @@ -1517,7 +1586,7 @@ func strayChanges(st State, lane Lane) (string, error) { if err != nil { return "", err } - return judgeLandingDiff(wt, st, lane, raw) + return judgeLandingDiff(wt, st, lane, raw, filing) } // parseRawDiff reads git's raw NUL-separated list of changes. @@ -1551,15 +1620,15 @@ func parseRawDiff(raw string) ([]rawEntry, error) { // such resolution is returned as its pair of entries, the record leaving open/ and the // record standing in resolved/, for the caller to hold to what a resolve writes // (resolvedAsWritten). -func landingDiff(st State, lane Lane, raw string, named []string) ([]relink.Move, []rawEntry, [][2]rawEntry, string, error) { +func landingDiff(st State, lane Lane, raw string, named []string) ([]relink.Move, []rawEntry, [][2]rawEntry, []rawEntry, string, error) { entries, err := parseRawDiff(raw) if err != nil { - return nil, nil, nil, "", err + return nil, nil, nil, nil, "", err } from, to, left := map[string]string{}, map[string]string{}, map[string]string{} resolvedFrom, resolvedTo := map[string]rawEntry{}, map[string]rawEntry{} var resolutions [][2]rawEntry - var outside []rawEntry + var outside, adds []rawEntry for _, e := range entries { store, bucket, name, ok := storeRecord(e.path) if !ok { @@ -1581,8 +1650,12 @@ func landingDiff(st State, lane Lane, raw string, named []string) ([]relink.Move resolvedFrom[key] = e case e.status == "A" && bucket == string(capture.StateResolved) && namesIssueRecord(named, name): resolvedTo[key] = e + case e.status == "A" && bucket == string(capture.StateOpen): + // A record new to open/: one the landing files for a finding left at the + // fix-round cap, as the caller judges (filedAdds), unless it moved there. + adds = append(adds, e) default: - return nil, nil, nil, e.path, nil + return nil, nil, nil, nil, e.path, nil } continue } @@ -1593,6 +1666,11 @@ func landingDiff(st State, lane Lane, raw string, named []string) ([]relink.Move to[key] = e.path } } + for _, e := range adds { + if _, _, name, _ := storeRecord(e.path); left[issueStore.rel+"/"+name] != "" { + return nil, nil, nil, nil, e.path, nil + } + } // A resolution the lane's worktree made is one move: its record leaves open/ and // stands in resolved/, so either half alone is no resolution. The list's order picks // which path a refusal names. @@ -1608,7 +1686,7 @@ func landingDiff(st State, lane Lane, raw string, named []string) ([]relink.Move case !gone && !came: continue case !gone || !came: - return nil, nil, nil, e.path, nil + return nil, nil, nil, nil, e.path, nil } if _, seen := from[key]; !seen { resolutions = append(resolutions, [2]rawEntry{was, reached}) @@ -1625,7 +1703,7 @@ func landingDiff(st State, lane Lane, raw string, named []string) ([]relink.Move had = left[store.rel+"/"+name] } if !recordModeHolds(e.newMode, had) { - return nil, nil, nil, e.path, nil + return nil, nil, nil, nil, e.path, nil } } var moves []relink.Move @@ -1634,7 +1712,7 @@ func landingDiff(st State, lane Lane, raw string, named []string) ([]relink.Move moves = append(moves, relink.Move{From: was, To: reached}) } } - return moves, outside, resolutions, "", nil + return moves, outside, resolutions, adds, "", nil } // resolveFields are the frontmatter keys a resolve sets (capture.Resolve): its note, the @@ -1777,18 +1855,25 @@ type rawEntry struct { // head already holds. It says which path fails, "" when none does. Everything it needs is // in the list and the object store, so a call after a refusal or a kill reads the same // answer. -func judgeLandingDiff(repo string, st State, lane Lane, raw string) (string, error) { +func judgeLandingDiff(repo string, st State, lane Lane, raw string, filing *capFiling) (string, error) { named, err := shippedIssues(repo, st, lane) if err != nil { return "", err } - moves, outside, resolutions, odd, err := landingDiff(st, lane, raw, named) + moves, outside, resolutions, adds, odd, err := landingDiff(st, lane, raw, named) if err != nil { return "", err } if odd != "" { return strconv.Quote(termsafe.Sanitize(odd)), nil } + // A record new to open/ is the landing's only as the filing of a finding the lane + // left at the fix-round cap (capdefer.go). + if _, odd, err := filedAdds(repo, filing, adds); err != nil { + return "", err + } else if odd != "" { + return strconv.Quote(termsafe.Sanitize(odd)), nil + } if len(outside) > 0 || len(resolutions) > 0 { standing, err := standingMoves(repo, st, lane) if err != nil { @@ -1829,7 +1914,7 @@ func judgeLandingDiff(repo string, st State, lane Lane, raw string) (string, err // intent's record and the trailers the landing writes. Such a commit is the landing's // records, and any other leaves its close and resolutions unrun. raw is git's list of what // it changes. -func foundCommitLacks(c Context, lane Lane, tip, raw string) (string, error) { +func foundCommitLacks(c Context, lane Lane, tip, raw string, filing *capFiling) (string, error) { st, ld := c.State, lane.Landing // Only a landing that moves no spec record may change no file: one with nothing to // move, or one whose resolutions the branch already held, each checked below. @@ -1907,20 +1992,23 @@ func foundCommitLacks(c Context, lane Lane, tip, raw string) (string, error) { } } } - return foundTrailersLack(c, lane, tip, raw, delivers) + if lacks, err := filingLacks(c.RepoRoot, filing, raw); err != nil || lacks != "" { + return lacks, err + } + return foundTrailersLack(c, lane, tip, raw, delivers, filing) } // foundTrailersLack says which trailers a commit found on the judged head lacks, "" when // the ones it carries are the ones the landing writes: its delivery, each resolution and // its disclosure, which is abcd's only on a commit of the mark alone. -func foundTrailersLack(c Context, lane Lane, tip, raw string, delivers bool) (string, error) { +func foundTrailersLack(c Context, lane Lane, tip, raw string, delivers bool, filing *capFiling) (string, error) { st, ld := c.State, lane.Landing var want []string if delivers { want = append(want, "Delivers: "+st.Intent) } want = append(want, resolutionTrailers(st, lane)...) - composed := !ld.Closes && len(lane.Resolves) == 0 && !ld.SpecSettled + composed := !ld.Closes && len(lane.Resolves) == 0 && !ld.SpecSettled && filing == nil if composed && raw != "" { only, err := rawOnlyTheMark(c.RepoRoot, st.Spec, raw, shortSHA(lane.HeadSHA)) if err != nil { @@ -1932,7 +2020,7 @@ func foundTrailersLack(c Context, lane Lane, tip, raw string, delivers bool) (st if composed { want = append(want, composedAssistedBy()) } else { - assisted, gap := assistedByTrailers(lane.Receipts) + assisted, gap := landingAssisted(lane, filing) if gap != "" { return "a model to disclose: " + gap, nil } @@ -2103,7 +2191,20 @@ func recordsParked(c Context, lane Lane) string { if last.HeadSHA == lane.HeadSHA { return "" } - why, err := landing.RecordsCommitShape(c.RepoRoot, last.HeadSHA, lane.HeadSHA, last.ResolvesShown) + // The records the landing filed for the findings left at the fix-round cap are its + // own, as the resolutions the full round was shown are. + issues := last.ResolvesShown + filing, err := capFilingOf(c, lane) + if err == nil && filing != nil { + var filed []string + if filed, err = filedIDs(c.RepoRoot, filing, last.HeadSHA, lane.HeadSHA); err == nil { + issues = append(slices.Clone(issues), filed...) + } + } + if err != nil { + return termsafe.Sanitize(fsutil.RedactHome(err.Error())) + } + why, err := landing.RecordsCommitShape(c.RepoRoot, last.HeadSHA, lane.HeadSHA, issues) if err != nil { return termsafe.Sanitize(fsutil.RedactHome(err.Error())) } @@ -2629,9 +2730,16 @@ func prBodyParked(st State, lane Lane, assisted []string, parked bool) string { p("- Branch `%s`, from %s to %s.\n", lane.Branch, shortSHA(lane.BaseSHA), shortSHA(lane.HeadSHA)) if n := len(lane.Validation); n > 0 { r := lane.Validation[n-1] - if slices.ContainsFunc(r.Validators, func(v ValidatorRun) bool { return !v.Pass }) { + capped := lane.capRound() + if capped != nil { + p("- Validation round %d at %s did not pass (%s) after the run's fix rounds, and every finding it left is minor or nitpick, so the records commit files each as an open issue and the lane lands.\n", + capped.Round, shortSHA(capped.HeadSHA), verdictsLine(*capped)) + } + switch { + case capped != nil && capped.Round == r.Round: + case slices.ContainsFunc(r.Validators, func(v ValidatorRun) bool { return !v.Pass }): p("- Validation round %d at %s did not pass (%s), so the lane is parked at this pull request for a person.\n", r.Round, shortSHA(r.HeadSHA), verdictsLine(r)) - } else { + default: p("- Validation round %d at %s passed: %s.\n", r.Round, shortSHA(r.HeadSHA), verdictsLine(r)) } for _, v := range r.Validators { @@ -2686,7 +2794,11 @@ func landPullRequest(c Context, lane *Lane) (Outcome, error) { } else if note != "" { return Outcome{Stay: true, Note: note}, nil } - assisted, gap := assistedByTrailers(lane.Receipts) + filing, err := capFilingOf(c, *lane) + if err != nil { + return Outcome{}, err + } + assisted, gap := landingAssisted(*lane, filing) if gap != "" { return Outcome{}, modelGap(*lane, "the pull request's body describes a change carrying text the lane's implementer composed", gap) } diff --git a/internal/core/implement/loop/pace.go b/internal/core/implement/loop/pace.go index a8b0bdd3ce..c6c207c0d9 100644 --- a/internal/core/implement/loop/pace.go +++ b/internal/core/implement/loop/pace.go @@ -32,10 +32,13 @@ const ( BundledSubAgents = 2 ) -// BundledFixRounds is the fix rounds a lane may take before it is handed back -// when nothing sets it (ruling DR1 of 2026-09-29: "tied to the pace settings, a -// per-run value set alongside --pace, default 3"; itd-50 decision 2). -const BundledFixRounds = 3 +// BundledFixRounds is the fix rounds a lane may take before the cap is judged +// when nothing sets it: five, by the product thinker's ruling of 2 December 2026 +// (iss-2612021201375528), which replaced DR1's three of 2026-09-29 (itd-50 +// decision 2) and kept the value per run, beside --pace. At the cap a lane is +// handed back only while a security, major or critical finding stands, and +// otherwise lands with what it leaves filed as open issues (capdefer.go). +const BundledFixRounds = 5 // The accepted ranges. A week bounds the minutes, so the window arithmetic // stays far inside time.Duration and a typed extra digit is refused rather than @@ -143,7 +146,8 @@ func (p Pace) String() string { if p.FixRounds.Layer == "" { return head } - return fmt.Sprintf("%s; %s before a lane is handed back (%s)", head, fixRoundsPhrase(p.FixRounds.Value), describeOrigin(p.FixRounds)) + return fmt.Sprintf("%s; %s, then a lane is handed back only on a security or major finding and otherwise files what is left as issues and lands (%s)", + head, fixRoundsPhrase(p.FixRounds.Value), describeOrigin(p.FixRounds)) } // fixRoundsPhrase is a number of fix rounds in words a reader counts. diff --git a/internal/core/implement/loop/schedule.go b/internal/core/implement/loop/schedule.go index f638f22023..4b1ea9cb0a 100644 --- a/internal/core/implement/loop/schedule.go +++ b/internal/core/implement/loop/schedule.go @@ -341,7 +341,8 @@ func (l Lane) syncRoundDue() bool { // fixRoundsTaken is the fix rounds the lane has taken before its current // round: the rounds whose findings went to a fresh implementer. A round opened -// after a sync follows a passing round and counts none. +// after a sync follows a passing round, or the round a lane went to its landing +// from at the fix-round cap, and counts none. func (l Lane) fixRoundsTaken() int { n := 0 for i := 0; i+1 < len(l.Validation); i++ { diff --git a/internal/core/implement/loop/testdata/drain_bundle_one/cap-of-1.golden b/internal/core/implement/loop/testdata/drain_bundle_one/cap-of-1.golden index bf78fe4090..ec4bbc1e43 100644 --- a/internal/core/implement/loop/testdata/drain_bundle_one/cap-of-1.golden +++ b/internal/core/implement/loop/testdata/drain_bundle_one/cap-of-1.golden @@ -103,7 +103,7 @@ drive iss-2609300000000103's lane, run : run `abcd implement step` to take "fix_rounds": { "layer": "bundled", "origin": "bundled", - "value": 3 + "value": 5 }, "pause_minutes": { "layer": "bundled", @@ -151,7 +151,7 @@ drive iss-2609300000000103's lane, run : run `abcd implement step` to take "fix_rounds": { "layer": "bundled", "origin": "bundled", - "value": 3 + "value": 5 }, "pause_minutes": { "layer": "bundled", @@ -179,7 +179,7 @@ drive iss-2609300000000103's lane, run : run `abcd implement step` to take }, { "at": "