Merge refusal/stale-base-movers into main
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents c19a862, f38905b · Browse files · 31 files·+646 added−58 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
31 files+646 added−58 removed
- tests:+284 added−15 removed
- other:+362 added−43 removed
Provenance
- Commit
a23e097- Tree
b490578- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
c19a862- Parent 2
f38905b
31 files changed+646 added−58 removed
modified:apps/platform/src/workflows/answer/program.ts+14 added-5 removed
179 unmodified lines180 /**181 * The port call `effect` names, run as the in-process run runs it182 * (`runStep`), on the answer's run as its project holds it now (as183 * `prepare` hands it on); `None` when the run no longer waits on `call`.184+ * A merge that conflicts reads the project's landings to name who moved185+ * each path.186 */187 const portCall = (188 params: AnswerParams,189 call: Call<"Land" | "Merge">,1 unmodified line191 prepare: (run: AnswerRun) => Effect.Effect<AnswerRun, never, Projects> = (192 run193 ) => Effect.succeed(run)194 ) =>193- Effect.flatMap(load(params), (run) =>194- Option.isSome(run) && waitsOn(run.value, call)195- ? Effect.flatMap(prepare(run.value), (ready) => runStep(ready, effect))196- : Effect.succeedNone197- );195+ Effect.gen(function* () {196+ const api = yield* projectOf(params.project);197+ const run = yield* api.answer(params.requestId);198 199+ if (Option.isNone(run) || !waitsOn(run.value, call)) {200+ return Option.none();201+ }202+203+ const ready = yield* prepare(run.value);204+205+ return yield* runStep(ready, effect, api.landings);206+ });207+208 /** A verdict as its note holds it: JSON. */209 const encodeVerdict = Schema.encodeEffect(Schema.fromJsonString(Verdict));210 211 /**544 unmodified linesmodified:apps/platform/test/core-loop.test.ts+11 added-1 removed
19 unmodified lines20 import { DecisionSubject } from "@repo/protocol/domain/decision";21 import { Outcome } from "@repo/protocol/domain/outcome";22 import {23 AskId,24+ Handle,25 LandedSha,26 LaneName,27 ProjectName,28 RepoPath,404 unmodified lines433 verdict: [[redThenGreen, "passed"]],434 });435 436 // 6. bob answered parse-month on the main he claimed at, in the436- // line alice's answer changed: his run ends refused, StaleBase.437+ // line alice's answer changed: his run ends refused, StaleBase,438+ // naming alice's landing as the one that moved the file.439 const bobsWork = yield* bobGit.clone(bobs.remote);440 441 const stale = yield* bobGit.commit(bobsWork, "Read the month", {442 "src/parse.ts": monthRead,39 unmodified lines482 new StaleBase({483 base: bobs.base,484 conflicts: [RepoPath.make("src/parse.ts")],485 main: landed,486+ movedBy: [487+ {488+ ask: parseIso,489+ author: Handle.make("alice"),490+ landing: landed,491+ path: RepoPath.make("src/parse.ts"),492+ },493+ ],494 }),495 ],496 }),497 ],149 unmodified linesadded:docs/adr/0028-the-cli-exits-with-the-code-a-refusal-calls-for.md+27 added
123456789101112131415161718192021222324252627---status: accepted---
# The CLI exits with the code a refusal calls for
Until now every refusal ended the CLI with 1, so a script or a harness that wanted to know what to do next had to read stderr or ask for `--json`. Now the code comes from sysexits(3) and follows the refusal's fixed `retryable`, in `packages/protocol/src/exit-code.ts`:
- A retryable refusal is 75 (`EX_TEMPFAIL`): run its `next`, and the same thing can pass.- A final refusal is 65 (`EX_DATAERR`) when what was sent has to change, 66 (`EX_NOINPUT`) when what was named does not exist or no longer stands open, and 77 (`EX_NOPERM`) when the caller may not do it. A table fixes one of the three per final tag. Its type is keyed by exactly the final tags, so a new final tag fails the typecheck until it has a code, and a retryable tag cannot be given anything but 75.- Refusals met together, as stage 1's are, end with the first of 77, 66, 65 and 75 among them: who is asking comes before what was named, which comes before what was sent, and 75 only when every one can be retried.- Not being signed in is 77, a platform that does not answer is 69 (`EX_UNAVAILABLE`), a misuse stays 2, and anything else stays 1.
Every command prints its refusals through `endRefused` (`packages/protocol/src/cli.ts`), which fails with `Reported` and their code, so a command cannot print a refusal and exit with another code. The code is the CLI's projection of the union, like the `--json` envelope: `/llms-full.txt` and the skills list each refusal's code from the same table. `packages/protocol/test/exit-code.test.ts` pins every tag's code. `apps/cli/test/build.test.ts` holds the built binary to it.
## Considered Options
- **Keep 1 for every refusal.** Nothing to learn, but the code says nothing a harness can act on, and `retryable` was already fixed per tag.- **One code per tag.** Exact, but 45 codes make a lookup table nobody keeps in their head, and the tag is already in `--json`.- **64 (`EX_USAGE`) for a misuse.** sysexits' own code, but effect/cli and most command lines use 2, and scripts already read it.- **76 (`EX_PROTOCOL`) for every final refusal**, as some tools use it for "the remote rejected the payload". It would merge three answers a caller acts on differently: change what you sent, name something that exists, or get let in.
## Consequences
- A script that checked for exit 1 after a refusal now sees 65, 66, 75 or 77; it should test for nonzero, or for the code it means.- `PostureChange` is 65, as a declined waiver's `Weakened` is: it is the refusal a declined decision stands for, so the answer has to change. Its row in the reference docs now says so.- A code is a public contract, like a tag: change one only with notice.added:docs/adr/0029-a-stale-answer-names-who-moved-each-conflicting-path.md+26 added
1234567891011121314151617181920212223242526---status: accepted---
# A stale answer names who moved each conflicting path
When an answer's merge onto main conflicts, `StaleBase` named the paths and nothing more, so whoever rebased had to dig through main's log to learn whose change they were resolving against. Now it carries `movedBy` as well, an optional field that is never empty. For each conflicting path the platform landed, it names the landing that last changed that path: its commit (`landing`), the person accountable for it (`author`), and the ask it answered or opened (`ask`, absent for a decider's own landing). The renderer puts each one after its path: `src/parse.ts (last changed by alice in bb5da9e, for parse-iso)`.
The merge step finds them (`packages/project/src/answer-runs/movers.ts`), after the Lander has said the merge conflicts:
- A three-way merge conflicts in a path only where main changed it since the answer's base. So the step walks main's first-parent line back from the main it merged onto, through `RepoHost` (the code reads' own tree lookups, shared as one view), and stops at the base or after `MOVER_SCAN` commits (50). For each path it takes the newest commit whose entry differs from its parent's.- It asks the project's record for those commits' landings (`AnswerQueue.landings`, which the Workflow reaches through the project's Durable Object), and names a path only when its commit is a landing there. A trailer in a commit never reads as one, as on the code pages.- The step reports the names in `MergeConflict`, and the landing lifecycle copies them onto the refusal, so the transition stays pure. A merge step recorded before this change has no `movedBy`, and still decodes.- The walk never fails the merge: a repo it cannot read, or anything else that goes wrong, leaves `movedBy` out and logs why.
## Considered Options
- **The Lander reads `Ask:` trailers and the author line from `git log` in its container.** One `git log` where the clone already is. But there are three Lander adapters to teach it, its wire would grow, and the names would rest on trailers rather than the record.- **The project's Durable Object walks the history in `advanceAnswer`.** It already holds the record, but the walk's reads would run under the project's one lock and stall every other call to the project.- **Every landing since the base that changed each path.** More complete, but the list has no bound. The newest is the version on main that the rebase meets, and `myr why` gives each line's landing.
## Consequences
- A conflict now costs one first-parent log read of up to 51 commits, plus each conflicting path's entry at each commit since the base. A clean merge costs nothing more.- Everything `movedBy` names is already public: the paths in `conflicts`, and the landings' commits, authors and asks on main. It reaches the verdict note on the answer's head, `myr status`, MCP and the web, which write it through the one renderer.- The decider's `land` names movers the same way, through the same step.modified:packages/agent-kit/src/full-llms.ts+6 added
153 unmodified lines154 "### Recover from `StaleBase`",155 "",156 `\`main\` moved under your answer, and the answer did not merge onto it. Rebase onto the new \`main\`, resolve what the rebase stops on, and push again: ${code(`git pull --rebase ${platformUrl}/<project>.git main`)}, then ${pushAnswer}.`,157 "",158+ `When the merge conflicted, \`conflicts\` names the paths, and \`movedBy\` names, for each one the platform landed, the landing that last changed it: its commit (\`landing\`), the person accountable for it (\`author\`) and the ask it answered or opened (\`ask\`).${withCommand(159+ typed(commands, "ask", {}, ["project"]),160+ (each) =>161+ ` Read that ask (${each}) before you resolve, so your answer keeps its change.`162+ ).join("")}`,163+ "",164 "### Follow an answer until it lands",165 "",166 ...withCommand(167 typed(commands, "status", {}, ["project"]),45 unmodified linesmodified:packages/agent-kit/src/refusals.ts+1 added-1 removed
96 unmodified lines97 todo: "Import the other module only through its public files.",98 },99 RepoBusy: { todo: "Push again." },100 StaleBase: {101- todo: "Main moved: rebase onto it, resolve the conflicts it names, and push again.",101+ todo: "Main moved: rebase onto it, resolve the conflicts it names, and push again. `movedBy` names the landing that last changed each conflicting path, with its `author` and `ask`: keep that change as you resolve.",102 },103 StaleLayer: { todo: "Nothing: the answer is checked again." },104 TouchedJudge: {105 todo: "Undo your changes to the paths it names: they decide what the checks do.",211 unmodified linesmodified:packages/agent-kit/test/golden/agent-plugins-stdio.txt+1 added-1 removed
65 unmodified lines66 | `TouchedJudge` | no | 65 | `__CLI__ check` | Undo your changes to the paths it names: they decide what the checks do. |67 | `Weakened` | no | 65 | `__CLI__ check` | Take the marker out; a marker without a reason may get one after ` -- ` for a decider to weigh, but one a decider declined stays out; never raise a ratchet. |68 | `PrivatePathInPublicTree` | no | 65 | `__CLI__ check` | Take the held-back paths it names out of your answer. |69 | `ReachedInternals` | no | 65 | `__CLI__ check` | Import the other module only through its public files. |70-| `StaleBase` | yes | 75 | `git pull --rebase` | Main moved: rebase onto it, resolve the conflicts it names, and push again. |70+| `StaleBase` | yes | 75 | `git pull --rebase` | Main moved: rebase onto it, resolve the conflicts it names, and push again. `movedBy` names the landing that last changed each conflicting path, with its `author` and `ask`: keep that change as you resolve. |71 | `StaleLayer` | yes | 75 | `__CLI__ status` | Nothing: the answer is checked again. |72 | `ChecksFailed` | no | 65 | the command that reproduces the failure | Run `next` to see the failure, fix it, and push again. |73 | `HeldBackFailed` | no | 65 | `__CLI__ status` | A held-back check failed; you see only its area and suite. Fix the behaviour and push again. |74 | `AttemptsExhausted` | yes | 75 | `__CLI__ status` | Wait until `resetsAt`: you used every attempt on that area's held-back checks for now. |23 unmodified linesmodified:packages/agent-kit/test/golden/agent-plugins.txt+1 added-1 removed
66 unmodified lines67 | `TouchedJudge` | no | 65 | `__CLI__ check` | Undo your changes to the paths it names: they decide what the checks do. |68 | `Weakened` | no | 65 | `__CLI__ check` | Take the marker out; a marker without a reason may get one after ` -- ` for a decider to weigh, but one a decider declined stays out; never raise a ratchet. |69 | `PrivatePathInPublicTree` | no | 65 | `__CLI__ check` | Take the held-back paths it names out of your answer. |70 | `ReachedInternals` | no | 65 | `__CLI__ check` | Import the other module only through its public files. |71-| `StaleBase` | yes | 75 | `git pull --rebase` | Main moved: rebase onto it, resolve the conflicts it names, and push again. |71+| `StaleBase` | yes | 75 | `git pull --rebase` | Main moved: rebase onto it, resolve the conflicts it names, and push again. `movedBy` names the landing that last changed each conflicting path, with its `author` and `ask`: keep that change as you resolve. |72 | `StaleLayer` | yes | 75 | `__CLI__ status` | Nothing: the answer is checked again. |73 | `ChecksFailed` | no | 65 | the command that reproduces the failure | Run `next` to see the failure, fix it, and push again. |74 | `HeldBackFailed` | no | 65 | `__CLI__ status` | A held-back check failed; you see only its area and suite. Fix the behaviour and push again. |75 | `AttemptsExhausted` | yes | 75 | `__CLI__ status` | Wait until `resetsAt`: you used every attempt on that area's held-back checks for now. |20 unmodified linesmodified:packages/agent-kit/test/golden/claude-plugin-stdio.txt+1 added-1 removed
64 unmodified lines65 | `TouchedJudge` | no | 65 | `__CLI__ check` | Undo your changes to the paths it names: they decide what the checks do. |66 | `Weakened` | no | 65 | `__CLI__ check` | Take the marker out; a marker without a reason may get one after ` -- ` for a decider to weigh, but one a decider declined stays out; never raise a ratchet. |67 | `PrivatePathInPublicTree` | no | 65 | `__CLI__ check` | Take the held-back paths it names out of your answer. |68 | `ReachedInternals` | no | 65 | `__CLI__ check` | Import the other module only through its public files. |69-| `StaleBase` | yes | 75 | `git pull --rebase` | Main moved: rebase onto it, resolve the conflicts it names, and push again. |69+| `StaleBase` | yes | 75 | `git pull --rebase` | Main moved: rebase onto it, resolve the conflicts it names, and push again. `movedBy` names the landing that last changed each conflicting path, with its `author` and `ask`: keep that change as you resolve. |70 | `StaleLayer` | yes | 75 | `__CLI__ status` | Nothing: the answer is checked again. |71 | `ChecksFailed` | no | 65 | the command that reproduces the failure | Run `next` to see the failure, fix it, and push again. |72 | `HeldBackFailed` | no | 65 | `__CLI__ status` | A held-back check failed; you see only its area and suite. Fix the behaviour and push again. |73 | `AttemptsExhausted` | yes | 75 | `__CLI__ status` | Wait until `resetsAt`: you used every attempt on that area's held-back checks for now. |58 unmodified linesmodified:packages/agent-kit/test/golden/claude-plugin.txt+1 added-1 removed
65 unmodified lines66 | `TouchedJudge` | no | 65 | `__CLI__ check` | Undo your changes to the paths it names: they decide what the checks do. |67 | `Weakened` | no | 65 | `__CLI__ check` | Take the marker out; a marker without a reason may get one after ` -- ` for a decider to weigh, but one a decider declined stays out; never raise a ratchet. |68 | `PrivatePathInPublicTree` | no | 65 | `__CLI__ check` | Take the held-back paths it names out of your answer. |69 | `ReachedInternals` | no | 65 | `__CLI__ check` | Import the other module only through its public files. |70-| `StaleBase` | yes | 75 | `git pull --rebase` | Main moved: rebase onto it, resolve the conflicts it names, and push again. |70+| `StaleBase` | yes | 75 | `git pull --rebase` | Main moved: rebase onto it, resolve the conflicts it names, and push again. `movedBy` names the landing that last changed each conflicting path, with its `author` and `ask`: keep that change as you resolve. |71 | `StaleLayer` | yes | 75 | `__CLI__ status` | Nothing: the answer is checked again. |72 | `ChecksFailed` | no | 65 | the command that reproduces the failure | Run `next` to see the failure, fix it, and push again. |73 | `HeldBackFailed` | no | 65 | `__CLI__ status` | A held-back check failed; you see only its area and suite. Fix the behaviour and push again. |74 | `AttemptsExhausted` | yes | 75 | `__CLI__ status` | Wait until `resetsAt`: you used every attempt on that area's held-back checks for now. |56 unmodified linesmodified:packages/agent-kit/test/golden/full-llms.txt+3 added-1 removed
67 unmodified lines68 | `TouchedJudge` | Shape | no | 65 | `__CLI__ check` | Undo your changes to the paths it names: they decide what the checks do. |69 | `Weakened` | Shape | no | 65 | `__CLI__ check` | Take the marker out; a marker without a reason may get one after ` -- ` for a decider to weigh, but one a decider declined stays out; never raise a ratchet. |70 | `PrivatePathInPublicTree` | Shape | no | 65 | `__CLI__ check` | Take the held-back paths it names out of your answer. |71 | `ReachedInternals` | Shape | no | 65 | `__CLI__ check` | Import the other module only through its public files. |72-| `StaleBase` | Merge | yes | 75 | `git pull --rebase` | Main moved: rebase onto it, resolve the conflicts it names, and push again. |72+| `StaleBase` | Merge | yes | 75 | `git pull --rebase` | Main moved: rebase onto it, resolve the conflicts it names, and push again. `movedBy` names the landing that last changed each conflicting path, with its `author` and `ask`: keep that change as you resolve. |73 | `StaleLayer` | Merge | yes | 75 | `__CLI__ status` | Nothing: the answer is checked again. |74 | `ChecksFailed` | Checks | no | 65 | the command that reproduces the failure | Run `next` to see the failure, fix it, and push again. |75 | `HeldBackFailed` | Checks | no | 65 | `__CLI__ status` | A held-back check failed; you see only its area and suite. Fix the behaviour and push again. |76 | `AttemptsExhausted` | Checks | yes | 75 | `__CLI__ status` | Wait until `resetsAt`: you used every attempt on that area's held-back checks for now. |96 unmodified lines173 ### Recover from `StaleBase`174 175 `main` moved under your answer, and the answer did not merge onto it. Rebase onto the new `main`, resolve what the rebase stops on, and push again: `git pull --rebase https://platform-test.example.workers.dev/<project>.git main`, then `git push __SLUG__ HEAD:main`.176 177+When the merge conflicted, `conflicts` names the paths, and `movedBy` names, for each one the platform landed, the landing that last changed it: its commit (`landing`), the person accountable for it (`author`) and the ask it answered or opened (`ask`). Read that ask (`__CLI__ ask <ask> --project <project>`) before you resolve, so your answer keeps its change.178+179 ### Follow an answer until it lands180 181 - `__CLI__ status --project <project>` shows your claims and answers and where each stands.182 - `__CLI__ verdict <ask> --project <project>` shows the verdict on an answer.10 unmodified linesmodified:packages/agent-kit/test/golden/platform-skill.txt+1 added-1 removed
58 unmodified lines59 | `TouchedJudge` | no | 65 | `__CLI__ check` | Undo your changes to the paths it names: they decide what the checks do. |60 | `Weakened` | no | 65 | `__CLI__ check` | Take the marker out; a marker without a reason may get one after ` -- ` for a decider to weigh, but one a decider declined stays out; never raise a ratchet. |61 | `PrivatePathInPublicTree` | no | 65 | `__CLI__ check` | Take the held-back paths it names out of your answer. |62 | `ReachedInternals` | no | 65 | `__CLI__ check` | Import the other module only through its public files. |63-| `StaleBase` | yes | 75 | `git pull --rebase` | Main moved: rebase onto it, resolve the conflicts it names, and push again. |63+| `StaleBase` | yes | 75 | `git pull --rebase` | Main moved: rebase onto it, resolve the conflicts it names, and push again. `movedBy` names the landing that last changed each conflicting path, with its `author` and `ask`: keep that change as you resolve. |64 | `StaleLayer` | yes | 75 | `__CLI__ status` | Nothing: the answer is checked again. |65 | `ChecksFailed` | no | 65 | the command that reproduces the failure | Run `next` to see the failure, fix it, and push again. |66 | `HeldBackFailed` | no | 65 | `__CLI__ status` | A held-back check failed; you see only its area and suite. Fix the behaviour and push again. |67 | `AttemptsExhausted` | yes | 75 | `__CLI__ status` | Wait until `resetsAt`: you used every attempt on that area's held-back checks for now. |9 unmodified linesmodified:packages/agent-kit/test/golden/project-skill.txt+2 added-2 removed
92 unmodified lines93 | `TouchedJudge` | no | 65 | `__CLI__ check` | Undo your changes to the paths it names: they decide what the checks do. |94 | `Weakened` | no | 65 | `__CLI__ check` | Take the marker out; a marker without a reason may get one after ` -- ` for a decider to weigh, but one a decider declined stays out; never raise a ratchet. |95 | `PrivatePathInPublicTree` | no | 65 | `__CLI__ check` | Take the held-back paths it names out of your answer. |96 | `ReachedInternals` | no | 65 | `__CLI__ check` | Import the other module only through its public files. |97-| `StaleBase` | yes | 75 | `git pull --rebase` | Main moved: rebase onto it, resolve the conflicts it names, and push again. |97+| `StaleBase` | yes | 75 | `git pull --rebase` | Main moved: rebase onto it, resolve the conflicts it names, and push again. `movedBy` names the landing that last changed each conflicting path, with its `author` and `ask`: keep that change as you resolve. |98 | `StaleLayer` | yes | 75 | `__CLI__ status` | Nothing: the answer is checked again. |99 | `ChecksFailed` | no | 65 | the command that reproduces the failure | Run `next` to see the failure, fix it, and push again. |100 | `HeldBackFailed` | no | 65 | `__CLI__ status` | A held-back check failed; you see only its area and suite. Fix the behaviour and push again. |101 | `AttemptsExhausted` | yes | 75 | `__CLI__ status` | Wait until `resetsAt`: you used every attempt on that area's held-back checks for now. |102 unmodified lines204 | `TouchedJudge` | no | 65 | `__CLI__ check` | Undo your changes to the paths it names: they decide what the checks do. |205 | `Weakened` | no | 65 | `__CLI__ check` | Take the marker out; a marker without a reason may get one after ` -- ` for a decider to weigh, but one a decider declined stays out; never raise a ratchet. |206 | `PrivatePathInPublicTree` | no | 65 | `__CLI__ check` | Take the held-back paths it names out of your answer. |207 | `ReachedInternals` | no | 65 | `__CLI__ check` | Import the other module only through its public files. |208-| `StaleBase` | yes | 75 | `git pull --rebase` | Main moved: rebase onto it, resolve the conflicts it names, and push again. |208+| `StaleBase` | yes | 75 | `git pull --rebase` | Main moved: rebase onto it, resolve the conflicts it names, and push again. `movedBy` names the landing that last changed each conflicting path, with its `author` and `ask`: keep that change as you resolve. |209 | `StaleLayer` | yes | 75 | `__CLI__ status` | Nothing: the answer is checked again. |210 | `ChecksFailed` | no | 65 | the command that reproduces the failure | Run `next` to see the failure, fix it, and push again. |211 | `HeldBackFailed` | no | 65 | `__CLI__ status` | A held-back check failed; you see only its area and suite. Fix the behaviour and push again. |212 | `AttemptsExhausted` | yes | 75 | `__CLI__ status` | Wait until `resetsAt`: you used every attempt on that area's held-back checks for now. |9 unmodified linesmodified:packages/project/src/answer-runs/inline.ts+3 added-2 removed
3 unmodified lines4 * the answer lands, is refused, or waits (on a person, the landing slot, or5 * a retry the project's alarm starts again). A run already under way for the6 * same request is not started twice.7 */8+import type { RepoHost } from "@repo/artifacts/repo-host";9 import type { CheckRunner } from "@repo/checks/check-runner";10 import type { RequestId } from "@repo/protocol/ids";11 import { Effect, Layer, Ref } from "effect";12 3 unmodified lines16 17 export const AnswerRunsInline: Layer.Layer<18 AnswerRuns,19 never,19- CheckRunner | Lander20+ CheckRunner | Lander | RepoHost21 > = Layer.effect(22 AnswerRuns,23 Effect.gen(function* () {23- const ports = yield* Effect.context<CheckRunner | Lander>();24+ const ports = yield* Effect.context<CheckRunner | Lander | RepoHost>();25 const running = yield* Ref.make<ReadonlySet<RequestId>>(new Set());26 27 const claimRun = (requestId: RequestId) =>28 Ref.modify(running, (under) =>29 unmodified linesadded:packages/project/src/answer-runs/movers.ts+157 added
1+/**2+ * Who moved the paths a merge conflicts in. A three-way merge conflicts in3+ * a path only where main changed it since the answer's base, so for each4+ * path the walk finds the newest commit on main's first-parent line since5+ * that base that changed it, and names it only when the project's record6+ * holds it as a landing (a trailer never reads as one). The walk reads the7+ * canonical repo through `RepoHost` (`code/tree.ts`'s lookups, shared as8+ * one view), stops at the base or after `MOVER_SCAN` commits, and never9+ * fails the merge: what it cannot read, it leaves out.10+ */11+import { RepoHost, Revision } from "@repo/artifacts/repo-host";12+import type { Commit, RepoNotFound } from "@repo/artifacts/repo-host";13+import type { LandingView } from "@repo/protocol/domain/landing";14+import type {15+ CommitSha,16+ LandedSha,17+ RepoName,18+ RepoPath,19+} from "@repo/protocol/ids";20+import type { MovedBy } from "@repo/protocol/refusal";21+import { Array, Cause, Effect, Equal, Option } from "effect";22+23+import { asOneView } from "../code/cache.ts";24+import { entryAt, READS_AT_ONCE } from "../code/tree.ts";25+26+/** The most first-parent commits back from main a walk reads. */27+export const MOVER_SCAN = 50;28+29+/** The landings among `shas`, as the project's record holds them. */30+export type LandingsOf = (31+ shas: readonly CommitSha[]32+) => Effect.Effect<readonly LandingView[]>;33+34+/** What a merge conflicted in: the repo, the answer's base, main, and the paths. */35+export interface Conflicted {36+ readonly repo: RepoName;37+ readonly base: CommitSha;38+ readonly main: LandedSha;39+ readonly conflicts: readonly RepoPath[];40+}41+42+/** What sits at `path` in `commit`: its mode and id, or nothing. */43+const idAt = (repo: RepoName, commit: Commit | undefined, path: RepoPath) =>44+ commit === undefined45+ ? Effect.succeedNone46+ : Effect.map(47+ entryAt(repo, commit.tree, path),48+ Option.map(({ mode, sha }) => `${mode} ${sha}`)49+ );50+51+/**52+ * The newest of the first `since` commits of `scan` that changed `path`53+ * from the commit after it, its first parent.54+ */55+const moverOf = (56+ repo: RepoName,57+ scan: readonly Commit[],58+ since: number,59+ path: RepoPath60+): Effect.Effect<Option.Option<CommitSha>, RepoNotFound, RepoHost> =>61+ Effect.map(62+ Effect.forEach(63+ Array.makeBy(since + 1, (at) => scan[at]),64+ (commit) => idAt(repo, commit, path),65+ { concurrency: READS_AT_ONCE }66+ ),67+ (ids) =>68+ Array.findFirst(scan.slice(0, since), (commit, at) =>69+ Equal.equals(ids[at], ids[at + 1])70+ ? Option.none()71+ : Option.some(commit.sha)72+ )73+ );74+75+/** Each conflicting path's newest change since the base, where one is found. */76+const moversOf = (input: Conflicted) =>77+ asOneView(78+ Effect.gen(function* () {79+ const scan = yield* RepoHost.use((host) =>80+ host.log(81+ input.repo,82+ Revision.Commit({ sha: input.main }),83+ MOVER_SCAN + 184+ )85+ );86+87+ const based = scan.findIndex(({ sha }) => sha === input.base);88+ const since = based === -1 ? Math.min(scan.length, MOVER_SCAN) : based;89+90+ const found = yield* Effect.forEach(91+ input.conflicts,92+ (path) =>93+ Effect.map(moverOf(input.repo, scan, since, path), (commit) =>94+ Option.map(commit, (sha) => ({ path, sha }))95+ ),96+ { concurrency: READS_AT_ONCE }97+ );98+99+ return Array.getSomes(found);100+ })101+ );102+103+/** A path's mover as the refusal names it, from its landing. */104+const movedByOf = (path: RepoPath, landing: LandingView): MovedBy => {105+ const ask = landing.ask ?? landing.opened;106+107+ return ask === undefined108+ ? { author: landing.author, landing: landing.sha, path }109+ : { ask, author: landing.author, landing: landing.sha, path };110+};111+112+/**113+ * Who last moved each path `input` conflicts in, by its landing, in the114+ * order of `input.conflicts`. None when no conflicting path's change is a115+ * landing the record holds, or when the walk could not read the repo.116+ */117+export const movedBy = (118+ input: Conflicted,119+ landings: LandingsOf120+): Effect.Effect<readonly MovedBy[], never, RepoHost> =>121+ Effect.gen(function* () {122+ if (input.conflicts.length === 0) {123+ return [];124+ }125+126+ const movers = yield* moversOf(input);127+128+ if (movers.length === 0) {129+ return [];130+ }131+132+ const bySha = new Map<string, LandingView>(133+ (yield* landings(Array.dedupe(movers.map(({ sha }) => sha)))).map(134+ (landing) => [landing.sha, landing]135+ )136+ );137+138+ return movers.flatMap(({ path, sha }) => {139+ const landing = bySha.get(sha);140+141+ return landing === undefined ? [] : [movedByOf(path, landing)];142+ });143+ }).pipe(144+ // Who moved a path is a courtesy on the refusal, never a reason to145+ // block it: an unreadable repo leaves it out.146+ Effect.catchCause((cause) =>147+ Cause.hasInterruptsOnly(cause)148+ ? Effect.interrupt149+ : Effect.as(150+ Effect.logWarning(151+ "who moved a merge's conflicting paths was not found",152+ cause153+ ),154+ []155+ )156+ )157+ );modified:packages/project/src/answer-runs/steps.ts+37 added-11 removed
6 unmodified lines7 *8 * The inline adapter drives them in a loop (`drive`); the Answer Workflow9 * runs each as a durable step.10 */11+import type { RepoHost } from "@repo/artifacts/repo-host";12 import { CheckAt, CheckRunner } from "@repo/checks/check-runner";13 import type { CheckLane, CheckRun } from "@repo/checks/check-runner";14 import { classifyFailure } from "@repo/gate/classify";15 import type { LaneOutcome, LaneResult } from "@repo/protocol/domain/answer";11 unmodified lines27 LandingEffect,28 LandingState,29 pendingEffects,30 } from "../landing.ts";31+import { movedBy } from "./movers.ts";32+import type { LandingsOf } from "./movers.ts";33 34 /** A step's result: the command it reports, and what it saw beside it. */35 export interface Reported {36 readonly command: LandingCommand;29 unmodified lines66 67 const reported = (command: LandingCommand, report?: AnswerReport): Reported =>68 report === undefined ? { command } : { command, report };69 67-/** The answer's head merged onto `main`: the tree to check, or the paths that conflict. */70+/**71+ * The answer's head merged onto `main`: the tree to check, or the paths72+ * that conflict, with the landing that last moved each one (`movedBy`).73+ */74 const merge = (75 run: AnswerRun,70- step: Extract<LandingEffect, { readonly _tag: "Merge" }>76+ step: Extract<LandingEffect, { readonly _tag: "Merge" }>,77+ landings: LandingsOf78 ) =>79 Lander.use((lander) =>80 lander.merge({81 base: step.base,7 unmodified lines89 reported(LandingCommand.Merged({ changes, main: step.main, tree }))90 ),91 Effect.catchTags({92 StaleBase: ({ conflicts }) =>86- Effect.succeed(87- reported(LandingCommand.MergeConflict({ conflicts, main: step.main }))93+ Effect.map(94+ movedBy(95+ { base: step.base, conflicts, main: step.main, repo: run.repo },96+ landings97+ ),98+ (moved) =>99+ reported(100+ Array.isReadonlyArrayNonEmpty(moved)101+ ? LandingCommand.MergeConflict({102+ conflicts,103+ main: step.main,104+ movedBy: moved,105+ })106+ : LandingCommand.MergeConflict({ conflicts, main: step.main })107+ )108 ),109 VerifierBlocked: () =>110 Effect.succeed(111 reported(LandingCommand.Blocked({ attempt: attemptOf(run.state) }))167 unmodified lines279 280 /**281 * One step: the port call `effect` names, run for `run`, and the command282 * that reports it. `None` when the run's state no longer waits on that call263- * (a replay after the state moved on).283+ * (a replay after the state moved on). A merge that conflicts asks284+ * `landings` who moved each path.285 */286 export const runStep = (287 run: AnswerRun,267- effect: LandingEffect268-): Effect.Effect<Option.Option<Reported>, never, CheckRunner | Lander> =>288+ effect: LandingEffect,289+ landings: LandingsOf290+): Effect.Effect<291+ Option.Option<Reported>,292+ never,293+ CheckRunner | Lander | RepoHost294+> =>295 LandingEffect.$match(effect, {296 Emit: () => Effect.succeedNone,297 Land: () =>298 LandingState.guards.Landing(run.state) && run.message !== undefined299 ? Effect.asSome(land(run, run.state, run.message))300 : Effect.succeedNone,275- Merge: (merging) => Effect.asSome(merge(run, merging)),301+ Merge: (merging) => Effect.asSome(merge(run, merging, landings)),302 Record: () => Effect.succeedNone,303 Retry: () => Effect.succeedNone,304 RunChecks: () =>305 LandingState.guards.Checking(run.state)18 unmodified lines324 */325 export const drive = (326 queue: AnswerQueue,327 requestId: RequestId302-): Effect.Effect<void, never, CheckRunner | Lander> => {328+): Effect.Effect<void, never, CheckRunner | Lander | RepoHost> => {329 const go = (330 steps: readonly LandingEffect[]305- ): Effect.Effect<void, never, CheckRunner | Lander> =>331+ ): Effect.Effect<void, never, CheckRunner | Lander | RepoHost> =>332 Effect.gen(function* () {333 const effect = steps.find(isStep);334 335 if (effect === undefined || steps.some(LandingEffect.$is("Retry"))) {5 unmodified lines341 if (Option.isNone(run)) {342 return;343 }344 319- const step = yield* runStep(run.value, effect);345+ const step = yield* runStep(run.value, effect, queue.landings);346 347 if (Option.isNone(step)) {348 return;349 }17 unmodified linesmodified:packages/project/src/answer-runs.ts+17 added-3 removed
18 unmodified lines19 import { Ask } from "@repo/protocol/domain/ask";20 import { RatchetSpec } from "@repo/protocol/domain/check";21 import { Choice } from "@repo/protocol/domain/decision";22 import { AskKind } from "@repo/protocol/domain/kind";23+import type { LandingView } from "@repo/protocol/domain/landing";24 import { Outcome } from "@repo/protocol/domain/outcome";25 import { RunBlock } from "@repo/protocol/domain/run";26 import { Territory } from "@repo/protocol/domain/territory";27 import {8 unmodified lines36 RepoPath,37 TreeSha,38 } from "@repo/protocol/ids";39 import type { RequestId } from "@repo/protocol/ids";39-import { Refusal, VerifierBlocked } from "@repo/protocol/refusal";40+import { MovedBy, Refusal, VerifierBlocked } from "@repo/protocol/refusal";41 import { Context, Effect, Option, Schema } from "effect";42 43 import { UnlandedRunEnv } from "./env-port.ts";44 import { Change, LandingState, PendingDecision } from "./landing.ts";18 unmodified lines63 Decided: { by: Handle, choice: Choice, decision: DecisionId },64 Finished: { by: Handle },65 LandedOk: { sha: LandedSha },66 MainMoved: { from: LandedSha, main: LandedSha },66- MergeConflict: { conflicts: Schema.Array(RepoPath), main: LandedSha },67+ MergeConflict: {68+ conflicts: Schema.Array(RepoPath),69+ main: LandedSha,70+ // Absent from a step recorded before a merge named who moved a path.71+ movedBy: Schema.optionalKey(Schema.NonEmptyArray(MovedBy)),72+ },73 Merged: { changes: Schema.Array(Change), main: LandedSha, tree: TreeSha },74 Start: { main: LandedSha },75 Wait: { parent: AskId },76 });130 unmodified lines207 * A project's answer queue, as a run sees it: read one answer's run, and208 * report what a step came to. `advanceAnswer` returns only the port calls209 * the run makes next (`Merge`, `RunChecks`, `Land`), and a `Retry` when it210 * should stop and wait for the project's alarm; the project settles205- * everything else itself.211+ * everything else itself. A merge that conflicts reads `landings` to name212+ * who moved each path.213 */214 export interface AnswerQueue {215 readonly advanceAnswer: (216 requestId: RequestId,2 unmodified lines219 ) => Effect.Effect<Advanced>;220 readonly answer: (221 requestId: RequestId222 ) => Effect.Effect<Option.Option<AnswerRun>>;223+ /**224+ * The landings among `shas` (at most `MAX_LANDINGS`), in their order: a225+ * commit the platform did not land, imported history among them, has none.226+ */227+ readonly landings: (228+ shas: readonly CommitSha[]229+ ) => Effect.Effect<readonly LandingView[]>;230 }231 232 /**233 * Starts the run of one answer request. Idempotent by id: starting a run14 unmodified linesmodified:packages/project/src/deciders.ts+10 added-3 removed
2073 unmodified lines2074 input: {2075 /** The env every check job carries: the decider's change is unlanded code. */2076 readonly env: UnlandedRunEnv;2077 readonly lanes: readonly CheckLane[];2078+ /** The project's record of landings, for a merge that conflicts. */2079+ readonly landings: AnswerQueue["landings"];2080 readonly message: string;2081 readonly now: DateTime.Utc;2082 /** The project's run block, which every check job carries. */2083 readonly run: RunBlock;18 unmodified lines2102 run: input.run,2103 state: step.state,2104 };2105 2104- const reported = yield* runStep(run, next);2106+ const reported = yield* runStep(run, next, input.landings);2107 2108 if (Option.isNone(reported)) {2109 return step.state;2110 }5 unmodified lines2116 );2117 });2118 2119 const landBody =2118- (caller: Person, input: Parameters<DeciderApi["land"]>[1]) =>2120+ (2121+ queue: AnswerQueue,2122+ caller: Person,2123+ input: Parameters<DeciderApi["land"]>[1]2124+ ) =>2125 (h: H, writes: W, now: DateTime.Utc) =>2126 Effect.gen(function* () {2127 const live = liveOf(h);2128 100 unmodified lines2229 const state = yield* kernel.withPorts(2230 carry(2231 {2232 env,2233+ landings: queue.landings,2234 lanes: Record.toEntries(policy.run.checks).map(2235 ([lane, command]) => CheckLane.make({ command, lane })2236 ),2237 message: formatLanding({185 unmodified lines2423 land: (2424 queue: AnswerQueue,2425 caller: Person,2426 input: Parameters<DeciderApi["land"]>[1]2420- ) => kernel.write(queue, landBody(caller, input)),2427+ ) => kernel.write(queue, landBody(queue, caller, input)),2428 proposeAsk: (2429 queue: AnswerQueue,2430 caller: Person,2431 input: Parameters<DeciderApi["proposeAsk"]>[1]10 unmodified linesmodified:packages/project/src/landing.ts+22 added-6 removed
29 unmodified lines30 Refusal,31 StaleBase,32 Weakened,33 } from "@repo/protocol/refusal";34+import type { MovedBy } from "@repo/protocol/refusal";35 import { Array, Data, DateTime, Duration, Match, Option, Schema } from "effect";36 37 import { ProjectEventInput } from "./events.ts";38 105 unmodified lines144 readonly changes: readonly Change[];145 readonly main: LandedSha;146 readonly tree: TreeSha;147 };147- /** The merge onto `main` conflicted in these paths. */148+ /**149+ * The merge onto `main` conflicted in these paths; `movedBy` names the150+ * landing that last changed each one the step found.151+ */152 MergeConflict: {153 readonly conflicts: readonly RepoPath[];154 readonly main: LandedSha;155+ readonly movedBy?: Array.NonEmptyReadonlyArray<MovedBy>;156 };157 /** The checks judged `tree`. */158 Checked: {159 readonly decisions: readonly PendingDecision[];167 unmodified lines327 })328 ),329 });330 331+/** The refusal a merge that conflicted stands for, naming who moved each path the step found. */332+const staleOn = (333+ base: CommitSha,334+ {335+ conflicts,336+ main,337+ movedBy,338+ }: Extract<LandingCommand, { readonly _tag: "MergeConflict" }>339+) =>340+ movedBy === undefined341+ ? new StaleBase({ base, conflicts, main })342+ : new StaleBase({ base, conflicts, main, movedBy });343+344 /** The refusal a declined decision stands for. */345 const declined = (subject: AnswerDecision): Refusal =>346 AnswerDecision.match(subject, {347 PostureChange: ({ from, to }) => new PostureChange({ from, to }),157 unmodified lines505 })506 )507 : stay(merging)508 ),491- Match.tag("MergeConflict", ({ conflicts, main }) =>492- main === merging.main493- ? refuse(merging.request, [494- new StaleBase({ base: merging.request.base, conflicts, main }),495- ])509+ Match.tag("MergeConflict", (conflict) =>510+ conflict.main === merging.main511+ ? refuse(merging.request, [staleOn(merging.request.base, conflict)])512 : stay(merging)513 ),514 Match.tag("Blocked", ({ attempt }) => retry(merging, attempt, now)),515 Match.orElse(() => stay(merging))80 unmodified linesmodified:packages/project/src/project.ts-7 removed
418 unmodified lines419 sha: CommitSha420 ) => Effect.Effect<{ readonly landing: LandingView }, UnknownCommit>;421 /** Where main has landed: none before the first push. */422 readonly head: () => Effect.Effect<{ readonly landed?: LandedSha }>;423- /**424- * The landings among `shas` (at most `MAX_LANDINGS`), in their order: a425- * commit the platform did not land, imported history among them, has none.426- */427- readonly landings: (428- shas: readonly CommitSha[]429- ) => Effect.Effect<readonly LandingView[]>;423 /** Every claim's fork, with its ask, claimant and the claim's state. */424 readonly forks: () => Effect.Effect<readonly ForkRef[]>;425 /**426 * The posture the ledger shows now, the next instant it moves by the5417 unmodified linesmodified:packages/project/test/visibility/attempts.test.ts+4 added-1 removed
283 unmodified lines284 );285 286 const run = Option.getOrThrow(yield* api.answer(requestId));287 const merge = Option.getOrThrow(Array.findFirst(nextSteps(run), isStep));288- const reported = Option.getOrThrow(yield* runStep(run, merge));288 289+ const reported = Option.getOrThrow(290+ yield* runStep(run, merge, api.landings)291+ );292+293 yield* api.advanceAnswer(requestId, reported.command, reported.report);294 295 return { claim, requestId };296 });39 unmodified linesmodified:packages/project/test/landing.test.ts+21 added
197 unmodified lines198 }),199 });200 });201 202+ it("names, in its refusal, the landing the merge found moved each path", () => {203+ const movedBy = [204+ { ask, author: bob, landing: main, path: changed },205+ ] as const;206+207+ const step = transition(208+ merging,209+ LandingCommand.MergeConflict({ conflicts: [changed], main, movedBy }),210+ now211+ );212+213+ expect(step.state).toStrictEqual(214+ Refused.make({215+ refusals: [216+ new StaleBase({ base, conflicts: [changed], main, movedBy }),217+ ],218+ request,219+ })220+ );221+ });222+223 it("lands the checked tree when its checks pass and nobody has to act", () => {224 const step = transition(checking, LandingCommand.Checked(clean), now);225 226 expect(step).toStrictEqual({558 unmodified linesmodified:packages/project/test/migrate.test.ts+3 added-1 removed
440 unmodified lines441 }),442 });443 444 const ports = Context.make(CheckRunner, runner).pipe(445- Context.add(Lander, lander)445+ Context.add(Lander, lander),446+ Context.add(RepoHost, host)447 );448 449 /** The project's queue, with the ratchets counted on a tree before its check is reported. */450 const counting = (queue: AnswerQueue): AnswerQueue => ({17 unmodified lines468 });469 })470 : queue.advanceAnswer(requestId, command, report),471 answer: queue.answer,472+ landings: queue.landings,473 });474 475 const leave = (requestId: RequestId) =>476 Ref.update(1201 unmodified linesadded:packages/project/test/movers.test.ts+163 added
1+/**2+ * Who moved the paths a merge conflicts in, over the memory repo host: for3+ * each path, the newest commit on main since the answer's base that changed4+ * it, named by its landing in the project's record. A change at or before5+ * the base is never named, nor a commit the record holds no landing for,6+ * and a repo the walk cannot read names nobody.7+ */8+import { describe, expect, it } from "@effect/vitest";9+import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";10+import type { LandingView } from "@repo/protocol/domain/landing";11+import {12+ AskId,13+ Handle,14+ LandedSha,15+ ProjectName,16+ RepoName,17+ RepoPath,18+} from "@repo/protocol/ids";19+import type { CommitSha } from "@repo/protocol/ids";20+import { DateTime, Effect, Ref } from "effect";21+22+import { movedBy } from "../src/answer-runs/movers.ts";23+import { Content, writer } from "./code-fixtures.ts";24+import type { Tree } from "./code-fixtures.ts";25+26+const project = ProjectName.make("movekit");27+28+const repo = RepoName.make(project);29+30+const pathOf = (name: string) => RepoPath.make(`src/${name}.ts`);31+32+const [a, b, c, d, e] = [33+ pathOf("a"),34+ pathOf("b"),35+ pathOf("c"),36+ pathOf("d"),37+ pathOf("e"),38+] as const;39+40+const alice = Handle.make("alice");41+42+const dora = Handle.make("dora");43+44+/** A version of each of the five files, in order. */45+type Versions = readonly [number, number, number, number, number];46+47+/** The five files, each holding the version `versions` gives it. */48+const files = (versions: Versions): Tree =>49+ [a, b, c, d, e].map((path, at) => [50+ path,51+ Content.Text({ text: `export const v = ${versions[at] ?? 0};\n` }),52+ ]);53+54+const landingOf = (55+ sha: CommitSha,56+ author: Handle,57+ ask: Partial<Pick<LandingView, "ask" | "opened">>58+): LandingView => ({59+ ...ask,60+ assisted: [],61+ author,62+ credits: [],63+ landedAt: DateTime.makeUnsafe("2026-10-07T12:00:00Z"),64+ project,65+ sha: LandedSha.make(sha),66+});67+68+/**69+ * Main's history: `c` changes at the base itself; since then a landing70+ * that answered an ask changes `a` twice, a decider's own landing `d`, an71+ * opening `e`, and a commit the record holds no landing for changes `b`.72+ */73+const history = Effect.gen(function* () {74+ const { commit, push } = yield* writer;75+76+ // Each commit on the one before, `at` seconds after the first.77+ const on = (78+ parent: CommitSha,79+ message: string,80+ versions: Versions,81+ at: number82+ ) => commit(message, files(versions), [parent], at);83+84+ const root = yield* commit("Start", files([0, 0, 0, 0, 0]), [], 0);85+ const base = yield* on(root, "Change c", [0, 0, 1, 0, 0], 1);86+ const fixA = yield* on(base, "Fix a", [1, 0, 1, 0, 0], 2);87+ const own = yield* on(fixA, "Change d", [1, 0, 1, 1, 0], 3);88+ const stray = yield* on(own, "Change b", [1, 1, 1, 1, 0], 4);89+ const opening = yield* on(stray, "Open add-e", [1, 1, 1, 1, 1], 5);90+ const fixAgain = yield* on(opening, "Fix a again", [2, 1, 1, 1, 1], 6);91+92+ yield* push(repo, [["refs/heads/main", fixAgain]]);93+94+ const record = [95+ landingOf(fixA, alice, { ask: AskId.make("fix-a") }),96+ landingOf(own, dora, {}),97+ landingOf(opening, dora, { opened: AskId.make("add-e") }),98+ landingOf(fixAgain, alice, { ask: AskId.make("fix-a-again") }),99+ ];100+101+ return { base, fixAgain, opening, own, record };102+});103+104+describe(movedBy, () => {105+ it.effect(106+ "names the newest landing since the base that changed each path, and no one else",107+ () =>108+ Effect.gen(function* () {109+ const { base, fixAgain, opening, own, record } = yield* history;110+ const asked = yield* Ref.make<readonly CommitSha[]>([]);111+112+ const moved = yield* movedBy(113+ {114+ base,115+ conflicts: [a, b, c, d, e],116+ main: LandedSha.make(fixAgain),117+ repo,118+ },119+ (shas) =>120+ Effect.as(121+ Ref.update(asked, (all) => [...all, ...shas]),122+ record.filter(({ sha }) => shas.includes(sha))123+ )124+ );125+126+ expect(moved).toStrictEqual([127+ {128+ ask: AskId.make("fix-a-again"),129+ author: alice,130+ landing: LandedSha.make(fixAgain),131+ path: a,132+ },133+ { author: dora, landing: LandedSha.make(own), path: d },134+ {135+ ask: AskId.make("add-e"),136+ author: dora,137+ landing: LandedSha.make(opening),138+ path: e,139+ },140+ ]);141+ // The base changed c, so nothing at or before it is asked about.142+ expect(yield* Ref.get(asked)).not.toContain(base);143+ }).pipe(Effect.provide(RepoHostMemory))144+ );145+146+ it.effect("names nobody when the repo cannot be read", () =>147+ Effect.gen(function* () {148+ const { base, fixAgain, record } = yield* history;149+150+ const moved = yield* movedBy(151+ {152+ base,153+ conflicts: [a],154+ main: LandedSha.make(fixAgain),155+ repo: RepoName.make("no-such-repo"),156+ },157+ () => Effect.succeed(record)158+ );159+160+ expect(moved).toStrictEqual([]);161+ }).pipe(Effect.provide(RepoHostMemory))162+ );163+});modified:packages/project/test/project.test.ts+12 added-2 removed
955 unmodified lines956 })957 );958 959 it.effect(960- "8. an answer whose re-merge conflicts is refused as stale, and main stays",960+ "8. an answer whose re-merge conflicts is refused as stale, naming the landing that moved the path, and main stays",961 () =>962 Effect.map(963 conflicting.pipe(Effect.provide(worldOf(scenario, store))),964 (raced) => {965+ const lexed = RepoPath.make("packages/lexer/src/lex.ts");966+967 expect(raced.tip).toBe(raced.between);968 expect(raced.outcomes).toStrictEqual([969 Outcome.cases.Refused.make({970 refusals: [971 new StaleBase({972 base: raced.base,971- conflicts: [RepoPath.make("packages/lexer/src/lex.ts")],973+ conflicts: [lexed],974 main: raced.between,975+ movedBy: [976+ {977+ ask: AskId.make("tidy-all"),978+ author: frank.handle,979+ landing: raced.between,980+ path: lexed,981+ },982+ ],983 }),984 ],985 }),986 ]);458 unmodified linesmodified:packages/project/test/visibility-ports.test.ts+4 added-1 removed
348 unmodified lines349 );350 351 const run = Option.getOrThrow(yield* api.answer(requestId));352 const merge = Option.getOrThrow(Array.findFirst(nextSteps(run), isStep));353- const reported = Option.getOrThrow(yield* runStep(run, merge));353 354+ const reported = Option.getOrThrow(355+ yield* runStep(run, merge, api.landings)356+ );357+358 yield* api.advanceAnswer(requestId, reported.command, reported.report);359 360 return { head, requestId };361 });180 unmodified linesmodified:packages/protocol/src/refusal.ts+23 added-1 removed
5 unmodified lines6 AskId,7 CommitSha,8 DecisionId,9 EnvKey,10+ Handle,11+ LandedSha,12 ProjectName,13 ProposalId,14 RepoPath,15 } from "./ids.ts";173 unmodified lines189 ) {}190 191 // Merge192 191-/** Main moved past the answer's base; git's `fetch first` and `stale ref` land here too. */193+/**194+ * The landing on main that last changed a path an answer conflicts in: its195+ * commit, the person accountable for it, and the ask it answered or opened196+ * (none for a decider's own landing).197+ */198+export const MovedBy = Schema.Struct({199+ ask: Schema.optionalKey(AskId),200+ author: Handle,201+ landing: LandedSha,202+ path: RepoPath,203+});204+205+export type MovedBy = typeof MovedBy.Type;206+207+/**208+ * Main moved past the answer's base; git's `fetch first` and `stale ref`209+ * land here too. When the merge onto main conflicts, `conflicts` names the210+ * paths, and `movedBy` the landing that last changed each one the211+ * project's record holds, so the rebase knows whose change to keep.212+ */213 export class StaleBase extends Schema.TaggedError<StaleBase>()("StaleBase", {214 ...Retryable,215 ...nextIs("git pull --rebase"),216 base: CommitSha,217 conflicts: Schema.Array(RepoPath),218 main: CommitSha,219+ movedBy: Schema.optionalKey(Schema.NonEmptyArray(MovedBy)),220 }) {}221 222 /**223 * A layer the answer was checked with moved since; the answer is checked344 unmodified linesmodified:packages/protocol/src/render.ts+18 added-3 removed
3 unmodified lines4 5 import type { AnswerReceipt } from "./domain/answer.ts";6 import { Outcome } from "./domain/outcome.ts";7 import { ChecksFailed } from "./refusal.ts";8-import type { CapReached, Refusal } from "./refusal.ts";8+import type { CapReached, MovedBy, Refusal } from "./refusal.ts";9 10 const short = (sha: string) => sha.slice(0, 7);11 12 const list = (items: readonly string[]) => items.join(", ");29 unmodified lines42 retryAfter === undefined43 ? held[limit](cap)44 : `you ${rated[limit].verb} ${counted(cap, rated[limit].noun)} in the last minute, the most the platform allows; try again in ${retryAfter}s`;45 46+/** A conflicting path, and the landing that last changed it when one is named. */47+const conflictIn = (path: string, movedBy: readonly MovedBy[]) => {48+ const mover = movedBy.find((moved) => moved.path === path);49+50+ if (mover === undefined) {51+ return path;52+ }53+54+ const { ask, author, landing } = mover;55+56+ return ask === undefined57+ ? `${path} (last changed by ${author} in ${short(landing)})`58+ : `${path} (last changed by ${author} in ${short(landing)}, for ${ask})`;59+};60+61 // A branch is what a person pushes; every other ref the platform writes.62 const BRANCH = "refs/heads/";63 64 // Reasons name only what the refusal's reader may see: held-back checks give59 unmodified lines124 `${from} reaches into ${to}, which its module does not export; import it through that module's public exports instead`,125 RepoBusy: () => "the repo was busy with another push",126 SecretInOutput: ({ item, where }) =>127 `the write-only value ${item} appeared in the ${where}`,113- StaleBase: ({ base, conflicts, main }) =>128+ StaleBase: ({ base, conflicts, main, movedBy = [] }) =>129 conflicts.length === 0130 ? `main moved to ${short(main)}, past your base ${short(base)}`116- : `main moved to ${short(main)}, past your base ${short(base)}; conflicts in ${list(conflicts)}`,131+ : `main moved to ${short(main)}, past your base ${short(base)}; conflicts in ${list(conflicts.map((path) => conflictIn(path, movedBy)))}`,132 StaleLayer: ({ layer }) =>133 `the ${layer} layer moved since this answer was checked; it will be checked again`,134 TouchedJudge: ({ paths }) =>135 `changes files that decide what the checks do: ${list(paths)}; the checks are fixed for this ask, so put them back, or flag the ask if a check is wrong`,85 unmodified linesmodified:packages/protocol/test/refusal.test.ts+34 added-1 removed
1 import { describe, expect, it } from "@effect/vitest";2 import { Brand } from "@repo/brand";3 import { Schema } from "effect";4 5-import { RepoPath } from "../src/ids.ts";5+import { AskId, Handle, LandedSha, RepoPath } from "../src/ids.ts";6 import { CapReached, groups, Refusal, StaleBase } from "../src/refusal.ts";7 import { base, examples, main } from "./examples.ts";8 9 // What Effect's MCP server sends for a declared tool failure that has no20 unmodified lines30 retryable: true,31 });32 });33 34+ it("sends who moved each conflicting path as JSON, and decodes it back", () => {35+ const landing = LandedSha.make("3333333333333333333333333333333333333333");36+37+ const moved = new StaleBase({38+ base,39+ conflicts: [RepoPath.make("src/a.ts")],40+ main,41+ movedBy: [42+ {43+ ask: AskId.make("fix-parser"),44+ author: Handle.make("alice"),45+ landing,46+ path: RepoPath.make("src/a.ts"),47+ },48+ ],49+ });50+51+ expect(JSON.parse(overTheWire(moved))).toStrictEqual({52+ _tag: moved._tag,53+ base,54+ conflicts: ["src/a.ts"],55+ main,56+ movedBy: [57+ { ask: "fix-parser", author: "alice", landing, path: "src/a.ts" },58+ ],59+ next: "git pull --rebase",60+ retryable: true,61+ });62+ expect(63+ Schema.decodeUnknownSync(Refusal)(JSON.parse(overTheWire(moved)))64+ ).toStrictEqual(moved);65+ });66+67 it.each(examples)("$_tag comes back from the wire as it left", (refusal) => {68 const decoded = Schema.decodeUnknownSync(Refusal)(69 JSON.parse(overTheWire(refusal))70 );193 unmodified linesmodified:packages/protocol/test/render.test.ts+22 added
6 unmodified lines7 AskId,8 CommitSha,9 DecisionId,10 EnvKey,11+ Handle,12 LandedSha,13 ProjectName,14 ProposalId,15 RepoPath,48 unmodified lines64 " retryable: yes",65 ]);66 });67 68+ it("names the landing that last changed each conflicting path it knows of", () => {69+ const landing = LandedSha.make("3333333333333333333333333333333333333333");70+ const other = RepoPath.make("src/b.ts");71+72+ expect(73+ explain([74+ new StaleBase({75+ base,76+ conflicts: [path, other, RepoPath.make("src/c.ts")],77+ main,78+ movedBy: [79+ { ask, author: Handle.make("alice"), landing, path },80+ { author: Handle.make("dora"), landing, path: other },81+ ],82+ }),83+ ])[0]84+ ).toBe(85+ "StaleBase: main moved to 2222222, past your base 1111111; conflicts in src/a.ts (last changed by alice in 3333333, for fix-parser), src/b.ts (last changed by dora in 3333333), src/c.ts"86+ );87+ });88+89 it("points at the line when the refusal has one", () => {90 expect(91 explain([92 new Weakened({435 unmodified linesmodified:README.md+1 added-1 removed
229 unmodified lines230 Each promise names the check that holds it, and `bun run verify` runs every one.231 232 | Promise | How to check |233 | --- | --- |234-| A push outside its ask's territory is refused in git's own `remote:` lines, and the fork keeps the commit. The fixed answer lands as the platform's commit, authored by the answerer, with `Asked-by` and `Signed-off-by`; a stale answer is `StaleBase`; replaying a request lands nothing twice. | `apps/platform/test/core-loop.test.ts` |234+| A push outside its ask's territory is refused in git's own `remote:` lines, and the fork keeps the commit. The fixed answer lands as the platform's commit, authored by the answerer, with `Asked-by` and `Signed-off-by`; a stale answer is `StaleBase`, naming the landing that last moved each conflicting path; replaying a request lands nothing twice. | `apps/platform/test/core-loop.test.ts` |235 | Refusals are one closed union of typed values, each with `retryable`, `next` and an optional `at`, and no `message`. MCP returns each one with its tag. | `packages/protocol/test/refusal.test.ts`, `packages/protocol/test/mcp.test.ts`, `apps/platform/test/mcp.test.ts` |236 | One renderer writes every refusal, for git, the CLI, MCP and the web. | `packages/protocol/test/render.test.ts` |237 | The CLI exits with each refusal's own code, 75 exactly when it is retryable, and the built binary does too. | `packages/protocol/test/exit-code.test.ts`, `apps/cli/test/build.test.ts` |238 | One push hears every shape refusal at once, not one per attempt. | `packages/gate/test/shape.test.ts` |157 unmodified lines