Skip to content

feat(mcp): worker agents change patches, and a retried change is applied once - #887

Merged
allisonmahmood merged 6 commits into
mainfrom
mcp/855-change-patch
Oct 23, 2026
Merged

allisonmahmood merged 6 commits into
mainfrom
mcp/855-change-patch

Conversation

@allisonmahmood

@allisonmahmood allisonmahmood commented Oct 22, 2026 •

Copy link
Copy Markdown
Owner

Stacked on #886 (ticket #855); merges with the rest of #833's stack, not alone.

What changed

A worker agent can now change a patch through change_patch, and retrying a change never applies it twice. Until now the door refused change_patch as not built.

Each change carries a change key, any string the agent picks, such as import-monday. Patchy keeps it for 24 hours, per agent connection and patch, in a new change_keys table. Every host replica therefore answers a retry the same way:

  • A mutation's first try gets a fresh Runtime mutation key, and every retry reuses it. A committed change is answered again with replayed: true and runs nothing. A try that ended any other way, unknown_outcome included, runs again under the same mutation key, so Runtime commits it at most once. When Runtime's own record answers that retry, it carries replayed: true too.
  • An action's key runs once. Any later try is refused unrun.
  • A try while the key's first try is still running is refused busy with retryAfterSeconds: 1. The same key for another tool or other arguments is refused, and so is a retry after a publish.
  • A change whose result is too large for an agent to read succeeds with the result left out.

Closes #855

Look at

  • packages/mcp/src/ChangeKeys.ts, the record. It is three statements on the database's clock.

    • The claim inserts the key, or takes over one past its 24 hours.
    • A retry of the same mutation takes over a record that no try holds and Patchy hasn't seen commit.
    • A read decides the rest: conflict, version changed, busy, used, or replay.

    It stores only hashes of the key (as JSON, so lone surrogates stay distinct) and of the arguments' canonical JSON. Key order and how a number is written don't make two changes of one.

  • Calls.change in packages/mcp/src/Calls.ts. It claims the key only after every check passes, and only on a host that runs patch code, so a refusal before running leaves the key free. The request calls Runtime itself, as read_patch does, so a hang-up reaches Runtime and the request's event keeps its measurements. A try that ends settles its key, time-bounded. A try whose agent hung up keeps the key held until its lease runs out (the spec's busy while it may still be running), and a retry then resolves through Runtime's record.

Codex on a dev instance, with two server processes over one database. pnpm dev up (team scenario), then a tier 2 call-log patch with an agent/ area (logCalls takes a list, listCalls, sendDigest, and later slowLog and exportCalls), published from the environment's workspace. Ada turned agent access on at Company.

"Another replica" is a second server process (apps/server/src/start.ts) started against the same dev database and storage on its own port. Its PATCHY_PUBLIC_BASE_URL was its own address, because the door answers only its own Host. Codex had both as MCP servers: patchy (the instance's server) and patchy_b (the second process). Both servers' own events confirm it: the first wrote replayed: false and the second replayed: true.

Codex ran as Ada with a token from pnpm dev mcp-token ada --client Codex, from a temp dir outside $HOME: codex exec --json --ephemeral --ignore-user-config -s read-only -c 'mcp_servers.patchy.url=…' -c 'mcp_servers.patchy.bearer_token_env_var="PATCHY_MCP_TOKEN"', and the same two settings for patchy_b. Codex honoured change_patch's destructive mark: under exec with no approver it refused every change ("MCP tool call requires approval, but approval policy is never"). So the runs add -c 'mcp_servers.<server>.tools.change_patch.approval_mode="approve"'. Tool results are cut here.

Three calls in one change, then the retry on the other replica
agent: I’ll find and open the call-log patch, add the three calls in one change, then repeat the identical request through patchy_b and check the rows.
(Codex read the machine's global Patchy skill)
mcp_tool_call patchy.find_patches({"search": "call"}) -> completed: {"actingFor": {"person": "Ada Park", "company": "Acme Co"}, "total": 1, "patches": [{"name": "call-log", "description": "Logs sales calls; people's agents log a day's calls at once.", "owner": "Ada Park", "address": "<instance>…
mcp_tool_call patchy.open_patch({"patch": "call-log"}) -> completed: {"name": "call-log", "description": "Logs sales calls; people's agents log a day's calls at once.", "owner": "Ada Park", "address": "<instance>/acme/call-log", "tools": [{"name": "listCalls", "kind": "read", "description
mcp_tool_call patchy.change_patch({"patch": "call-log", "tool": "logCalls", "key": "import-monday", "args": {"calls": [{"who": "Grace Hopper at Globex", "note": "Wants a renewal quote."}, {"who": "Linus Pauling at Initech", "note": "Churn risk; call back Friday."}, {"who": "Ada Lovelace at Hooli", "note": "New lead; send a deck."}]}}) -> completed: {"result": {"logged": 3}, "version": 1}
mcp_tool_call patchy_b.change_patch({"patch": "call-log", "tool": "logCalls", "key": "import-monday", "args": {"calls": [{"who": "Grace Hopper at Globex", "note": "Wants a renewal quote."}, {"who": "Linus Pauling at Initech", "note": "Churn risk; call back Friday."}, {"who": "Ada Lovelace at Hooli", "note": "New lead; send a deck."}]}}) -> completed: {"result": {"logged": 3}, "version": 1, "replayed": true}
mcp_tool_call patchy.read_patch({"patch": "call-log", "tool": "listCalls", "args": {}}) -> completed: {"result": [{"id": "01a16526-7270-7d76-9fed-296f59a0e27f", "who": "Ada Lovelace at Hooli", "note": "New lead; send a deck.", "createdAt": "2026-10-22T19:46:20.913143Z", "updatedAt": "2026-10-22T19:46:20.913143Z"}, {"id": "01a16526-7269-78ed-a19b-fc0cb9cfdce9",
agent: There are **3 rows**, one for each call. The identical retry with key `import-monday` created no duplicates.

- **patchy:** `{"result":{"logged":3},"version":1}`
- **patchy_b:** `{"result":{"logged":3},"version":1,"replayed":true}`
A reused key for another change, and an action's key used twice
agent: I’ll find the call-log patch, run the three calls separately with your exact keys, and report each response verbatim.
(Codex read the machine's global Patchy skill)
mcp_tool_call patchy.find_patches({"search": "call-log"}) -> completed: {"actingFor": {"person": "Ada Park", "company": "Acme Co"}, "total": 1, "patches": [{"name": "call-log", "description": "Logs sales calls; people's agents log a day's calls at once.", "owner": "Ada Park", "address": "<instance>…
mcp_tool_call patchy.open_patch({"patch": "call-log"}) -> completed: {"name": "call-log", "description": "Logs sales calls; people's agents log a day's calls at once.", "owner": "Ada Park", "address": "<instance>/acme/call-log", "tools": [{"name": "listCalls", "kind": "read", "description
mcp_tool_call patchy.change_patch({"patch": "call-log", "tool": "logCalls", "key": "import-monday", "args": {"calls": [{"who": "Katherine Johnson at Pied Piper", "note": "asked for pricing"}]}}) -> failed: {"error": {"code": "key_conflict", "from": "patchy", "message": "That key was used for a different change to call-log; pick a new one. A key names one change: one tool with the same arguments."}}
mcp_tool_call patchy.change_patch({"patch": "call-log", "tool": "sendDigest", "args": {}, "key": "digest-1"}) -> completed: {"result": {"calls": 3}, "version": 1}
mcp_tool_call patchy.change_patch({"patch": "call-log", "tool": "sendDigest", "args": {}, "key": "digest-1"}) -> failed: {"error": {"code": "key_used", "from": "patchy", "message": "sendDigest is an action, and it already ran with this key; an action that writes is not safe to retry, so Patchy never runs its key twice. Read what it changes first, then retry with a new key if it 
agent: 1) `logCalls`, key `"import-monday"`:
```text
That key was used for a different change to call-log; pick a new one. A key names one change: one tool with the same arguments.
```

2) `sendDigest`, key `"digest-1"`:
```json
{"result":{"calls":3},"version":1}
```

3) `sendDigest`, key `"digest-1"`:
```text
sendDigest is an action, and it already ran with this key; an action that writes is not safe to retry, so Patchy never runs its key twice. Read what it changes first, then retry with a new key if it still needs doing.
```
After a second publish: the retry is refused, and a large result is left out
agent: I’ll check the Patchy instructions, then make each requested call once and report its response verbatim.

(Codex read the machine's global Patchy skill)
mcp_tool_call patchy.open_patch({"patch": "call-log"}) -> completed: {"name": "call-log", "description": "Logs sales calls; people's agents log a day's calls at once.", "owner": "Ada Park", "address": "<instance>/acme/call-log", "tools": [{"name": "exportCalls", "kind": "change", "descrip
mcp_tool_call patchy.change_patch({"patch": "call-log", "tool": "logCalls", "key": "import-monday", "args": {"calls": [{"who": "Grace Hopper at Globex", "note": "Wants a renewal quote."}, {"who": "Linus Pauling at Initech", "note": "Churn risk; call back Friday."}, {"who": "Ada Lovelace at Hooli", "note": "New lead; send a deck."}]}}) -> failed: {"error": {"code": "version_changed", "from": "patchy", "message": "call-log was published since your first try with this key; read before retrying. If the change still needs making, make it with a new key."}}
mcp_tool_call patchy.open_patch({"patch": "call-log"}) -> completed: {"name": "call-log", "description": "Logs sales calls; people's agents log a day's calls at once.", "owner": "Ada Park", "address": "<instance>/acme/call-log", "tools": [{"name": "exportCalls", "kind": "change", "descrip
mcp_tool_call patchy.change_patch({"patch": "call-log", "tool": "exportCalls", "args": {}, "key": "export-1"}) -> completed: {"version": 2, "resultLeftOut": "exportCalls succeeded, but its result came to 120,029 characters, more than the 100,000 an agent reads in one answer, so it was left out. Read what you need of the change through the patch's read tools."}
agent: 1) `import-monday`

```text
call-log was published since your first try with this key; read before retrying. If the change still needs making, make it with a new key.
```

2) `export-1`

```json
{"version":2,"resultLeftOut":"exportCalls succeeded, but its result came to 120,029 characters, more than the 100,000 an agent reads in one answer, so it was left out. Read what you need of the change through the patch's read tools."}
```

Neither call was retried.
busy: two tries of one key racing on the two processes (curl, same token)

One Codex session can't send two calls at once, so this race used curl with Codex's token. slowLog waits three seconds before it writes.

B during it:    {"error": {"code": "busy", "from": "patchy", "message": "The first try with this key is still running. Try again in a second with the same key.", "retryAfterSeconds": 1}}
A first try:    {"result": {"id": "01a16527-f852-7428-be04-21bf0028408e"}, "version": 2}
B after it:     {"result": {"id": "01a16527-f852-7428-be04-21bf0028408e"}, "version": 2, "replayed": true}

Afterwards, change_keys held four rows, each with a 64-hex key hash and none with a key in clear. Neither server's log contains import-monday.

How it was verified

  • ChangeKeys.test.ts drives the door against an alternate Runtime layer, with two doors over one database as two replicas:
    • a fresh mutation key of Runtime's shape on a first try, and a replay on the other replica with arguments reordered and 1.0 for 1;
    • two replicas racing one key: one runs, and the other is busy, or replayed if its claim lands after the commit;
    • key_conflict for other arguments and for another tool, and version_changed after a publish;
    • unknown_outcome, then a patch refusal, then a success, all under one mutation key, then a replay;
    • an action runs once, a timed-out action says it may have partly happened, and a result over 100,000 characters is left out;
    • keys scoped per connection and per patch;
    • only hashes stored, a key just inside 24 hours still replayed, a key past 24 hours treated as a new change, and the sweep;
    • bad keys, wrong_kind and a host without patch code all leave no row.
  • ChangeKeys.workerd.test.ts runs on real workerd with two invocations and doors over one database:
    • three rows written once;
    • the retry on the other replica writes nothing;
    • a retry whose result the door never recorded resolves through Runtime's own mutation key, still three rows;
    • the action runs once.
  • Unit and wiring tests: changeAnswer in agentTools.test.ts, the hourly sweep in SweepSchedules.test.ts, and the migration record's ids.
  • Targeted runs: packages/mcp (65 tests), packages/api agentTools (26), patchy dev agent (6), the server's sweep and migrations (5).
  • Typecheck and lint: pnpm turbo run build --filter=@patchy/server --filter=patchy, tsc -p tsconfig.test.json, and eslint and prettier on the changed files.
  • Rollback rehearsal: the new table is composed into apps/server/src/migrations.ts, which the vitest template and the rehearsal both apply.

Choices where the spec is silent

  • Codes: key_conflict (same key, another tool or arguments), version_changed (a retry after a publish), key_used (a later try with an action's key) and key_expired (below). busy is the spec's.
  • Result left out: { version, resultLeftOut }. It has no result, and resultLeftOut says the change succeeded and to read through the patch's read tools. changeAnswer in @patchy/api gives patchy dev agent the same shape.
  • A retry Patchy hasn't seen commit stops a few minutes before 24 hours. It runs under the first try's mutation key only while Runtime is sure to keep that key's outcome. The window is the mutation key's own 24 hours, aged from the time in it as Runtime ages it, less one try's longest run and Runtime's allowed clock skew (about 6 minutes in all). After that it is key_expired, saying to read first and use a new key, because a later retry could find Runtime's outcome swept and write twice. A change Patchy saw commit is answered from its own record for the full 24 hours.
  • An action's key is spent by any try that reached Runtime, including one Runtime refused busy before starting. An action's refusal can't say whether it started (a callback's busy can surface after a write), so the literal rule is the safe one: the agent retries with a new key.

One Runtime change. Invocation.callAgent takes an optional onReplay, carried on the Binding. Invocation calls it when a top-level mutation answers with its key's outcome stored by another invocation. That lets the door, and patchy dev agent, put replayed: true on a retry that Runtime's own record answered, such as one after an unknown_outcome. Mutation keys and page calls are unchanged.

Release impact

  • Breaking — requires action from anyone already running this
  • Not breaking — no action required

It adds a table (0024_change_keys) and a door tool that was refused until now.

  • What does a revert leave behind? The change_keys table and any rows in it: hashes of keys, version ids, and committed mutation results of at most 64 KiB. Its foreign keys to agent_connections and patches cascade on delete.
  • Does the release before it still work with that? Yes. Nothing before it reads the table, and the cascades keep a patch purge or a connection's removal working on any release.

Built by Claude Opus 5.5 (xhigh) in Claude Code on T3 Code; reviewed and accepted by GPT-6.1-Sol (xhigh).

@github-actions github-actions Bot added area:server Touches the server area area:cli Touches the cli area area:docs Touches the docs area size:xl Over 1,000 changed lines; review in multiple passes labels Oct 22, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Rollback rehearsal against a main commit that has both #837 and #838 (pnpm test:rollback-rehearsal --live e4243ff), run at 25306e0: e4243ff → 25306e0 → e4243ff → 25306e0, every step passed (167 s). The head is now a7c9781, restacked onto #854's 8d83b9f. It differs from 25306e0 only by that base's patchy-server SKILL.md docs commit, so neither migrations nor descriptors changed.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Rollback rehearsal again after round 1, now with a stored change key (pnpm test:rollback-rehearsal --live e4243ff, at 2d148e2, whose code is the head's): e4243ff → 2d148e2 → e4243ff → 2d148e2, every step passed (200 s). Step 2 turned agent access on and made a change_patch through HEAD's door, and step 4 retried it under the same key and got the first result with replayed: true.

@github-actions github-actions Bot added the area:ci CI, shared testing infrastructure, development scripts and tooling label Oct 22, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Review rounds (GPT-6.1-Sol, xhigh)

Round 1, on 25306e0: changes requested

  1. Blocking: expiry wasn't coordinated with Runtime's record of the mutation key. Fixed.
    • The problem: a takeover near the end of the 24 hours could pass Runtime's key-age check, wait for admission, and then find Runtime's outcome row already swept, so it would run again. Database and host clocks could also disagree near the boundary.
    • The fix: a retry under the first try's mutation key is now allowed only while Runtime is sure to keep that outcome. The window ends tier2.mutation.keyLifetime minus one try's longest run minus tier2.mutation.keyFutureSkew after the first try, on the database's clock. Past it, a retry Patchy hasn't seen commit is refused key_expired: read first, then use a new key. A change Patchy saw commit is still answered from its own record for the full 24 hours, since that never reaches Runtime.
    • Tested in ChangeKeys.test.ts (23h55m).
  2. A committed change recovered through Runtime lacked replayed: true. Fixed.
    • Runtime's agent call takes an optional onReplay (AgentCall, carried on the Binding). Invocation calls it when a top-level mutation answers with its key's stored outcome and another invocation committed it (storedOutcome.invocationId !== id), so a try's own uncertain commit isn't counted.
    • The door then answers replayed: true, and the event says so. patchy dev agent's own retry after unknown_outcome does the same.
    • Tested in InvocationLocal.test.ts on real workerd, ChangeKeys.test.ts and ChangeKeys.workerd.test.ts. The last checks a retry whose result the door never recorded and finds replayed: true with no new rows.
  3. Settling could hold the request, and shutdown, on a stalled row. Fixed. Settling runs in a transaction with statement_timeout set to the settlement cleanup (5 s). A settle that can't finish leaves the hold to its lease, and a retry then resolves it.
  4. The sweep couldn't use its expiry index. Fixed. The sweep uses now(), one cutoff for the statement.
  5. Key length limits contradicted "any string". Fixed. Any string is a key, "" included; only its hash is stored. Tested with "", 5,000 characters and non-ASCII.
  6. The rollback rehearsal never stored a change key. Fixed.
    • The rehearsal's agent area gains an addNote mutation. At step 2, HEAD turns agent access on as the publisher through Company's form and makes a change_patch through /mcp under a change key.
    • At step 4, after the live release ran on that data, the same key must answer the first result with replayed: true.
    • The read-only action's check now looks for that action's note rather than an empty table.
  7. Nit: schemas follow the service tag. Fixed: Keyed and Stored now come before ChangeKeys.

Held by the review: racing retries, conflicts and canonicalization, retries after a publish, actions never replayed, scoping per connection and patch, too-large results, key privacy, and crash takeover.

Round 2, on a594349: one blocking, two should-fix

  1. Blocking: the retry window aged from when the row was written, not from the mutation key's mint. Fixed in 4ce47b6. Migration 0024 (not yet landed) gains issued_at, the time in Runtime's <ms>-<random> key. The window is issued_at within lifetime − mutation lease − keyFutureSkew of the database's clock. Runtime's sweeper reads the same issued time, so only its host skew and one try's run need subtracting. Tested by aging only issued_at.
  2. Settling could block on pool acquisition inside the uninterruptible region. Fixed in 4ce47b6, then reworked in 6aa70a8 (round 3). The uninterruptible region is gone, and settling is one UPDATE under Effect.timeoutOption(cleanup), run interruptibly.
  3. Lone surrogates collided in the key hash. Fixed: the key hashes in its JSON form, through canonicalArgs since 391f500, because the repo's TS44 rule bars JSON.stringify. Tested with "\ud800" and "\ud801".

Round 3, on 4ce47b6: nothing blocking, two should-fix

  1. A disconnect closed the request's event early, and 2. Runtime's replyDelivered stayed true, both caused by 4ce47b6's detached fiber. Fixed in 6aa70a8: the request calls Runtime itself, as read_patch does, so a hang-up reaches Runtime (replyDelivered: false). A try whose agent went away keeps its key held until the lease runs out (the spec's busy), and a retry then resolves through Runtime's record with replayed: true. Tested by interrupting a try mid-flight.

Round 4, on 6aa70a8: nothing blocking, three should-fix

  1. A disconnected request's event lacks Runtime's late measurements and replayed. Dismissed. That is how every Runtime call's event works today, pages and read_patch included. The request's event closes as interrupted when its client leaves, and Runtime's invocation log still records the settlement with replyDelivered: false. Making request events follow work that outlives the request is cross-cutting and outside this ticket.
  2. A replay from the record skipped the result cap. Fixed in 875e632: it goes through changeAnswer too. Unreachable today, since Runtime caps mutation results at 64 KiB, well under 100,000 characters.
  3. changeAnswer dropped replayed when it left a result out. Fixed in 875e632, with a unit test.

Review stopped after round 4, which found nothing blocking. CI is green on 6aa70a8, and on 875e632 as recorded below.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

pnpm verify on 875e632: format, lint, typecheck, synth, postgres-concurrency, cli-smoke, tier2-smoke and browser passed. test failed only on timeouts while the shared machine's load average was 28, in files this PR doesn't touch (PGlite, CLI repo builds, the SDK archive, Fleet). The rerun of pnpm test left five such timeouts, and those five files pass alone: 53 tests, --no-file-parallelism. CI's own test jobs pass on this head. clerk-live timed out twice while installing Chromium (the runner hung for 10 minutes there) and passed on its third attempt.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Acceptance: PASS

Checked 875e63209d2fd28c693f2683a03057318bf5277a (stacked base 8d83b9ff4930a33303dee8090b8156b8fa2033f3, mcp/854-read-patch) on fresh team and brightline environments, by GPT-6.1-Sol (xhigh) in the Codex harness on T3 Code. The PR head was unchanged before posting.

Done means

  • Codex logs three calls in one change_patch: passed against a published tier 2 call-log fixture on real workerd.
  • Identical retry on another replica returns replayed: true and writes nothing twice: passed. These were two separate server processes sharing only the throwaway instance's database and storage; the same agent connection called both.
  • key: "import-monday": passed, used verbatim in that run.
  • Each specified refusal: passed. Direct MCP checks returned key_conflict for different arguments and another tool, version_changed after publishing version 2, and busy with retryAfterSeconds: 1 during a three-second mutation. An action wrote once and its retry returned key_used. The focused suite also checked the timed-out action's “may have partly happened” and read-first/new-key instructions.

Codex's clean run, with per-invocation MCP configuration in a temporary directory outside HOME and an isolated CODEX_HOME:

patchy.change_patch(call-log, logCalls, key="import-monday", three calls)
  {"result":{"logged":3},"version":1}
patchy_b.change_patch(the identical request)
  {"result":{"logged":3},"version":1,"replayed":true}
patchy_b.read_patch(call-log, listCalls, {})
  ["Ada Lovelace at Hooli: Send a deck",
   "Katherine Johnson at Initech: Call back Friday",
   "Grace Hopper at Globex: Renewal quote"]
Number of calls: 3

Golden journeys

  • Use a tier 2 tool (brightline): passed. New Business opened with its sample deals. Jordan moved Northline Bikes from Proposal to Negotiation; Allison's already-open page updated without reloading. Jordan moved it back, and Allison updated live again. Spend refused Priya approving her own submitted request with own_approval, displayed “You can't approve your own request.” and retained Waiting status.
  • Additional publish/lifecycle smoke (team): passed. Ada published a tier 0 file; Ben opened it. Retirement showed the retired notice, and restore returned the same address to the published page. A signed-out reader received 401.
  • Agent/browser interaction: passed. A page mutation by Ben and a separate MCP mutation both appeared in Ada's and Ben's subscribed tier 2 pages without reloads.

Other risks checked

  • Removed only the local door's cached result for the committed import-monday change, leaving Runtime's outcome intact. The retry on replica B returned the original result with replayed: true; the three original calls remained unique.
  • A mutation that inserted and then threw was tried twice: both attempts returned handler_failed, with zero inserted rows left behind.
  • A concurrent retry was refused busy, then replayed after completion; exactly one row was written. A 120,000-character action result was omitted with resultLeftOut while its write committed.
  • The focused suite passed key scoping, canonical arguments, arbitrary string keys, hash-only storage, 24-hour expiry and sweep, the safe retry window, unknown outcomes, disconnects, wrong-kind/key-free refusals, and result caps. Both server logs recorded replay status without the change key.
pnpm exec vitest run packages/mcp packages/api/src/agentTools.test.ts \
  packages/patchy/src/devAgent.test.ts packages/runtime/src/InvocationLocal.test.ts \
  apps/server/src/SweepSchedules.test.ts apps/server/src/migrations.test.ts
Test Files  13 passed (13)
Tests       102 passed (102)

Surface checklist: wire/result shaping and API docs, CLI/dev-agent and project skill, vocabulary, migrations/server composition, sweep and analytics applied. No dev-runner, new company-database caller, served-page layout, lifecycle API or repository-layout changes. Key expiry supplies the reverse path; the migration's foreign keys cascade when its connection or patch is removed.

Rollback answers: match the diff. Reverting leaves the additive change_keys table and rows; the base ignores them, and the cascading foreign keys preserve deletion. No one-way label is needed. I read the successful rollback rehearsal: e4243ff → bb59cf5 → e4243ff → bb59cf5, all four steps passed, including the stored-key retry on the final upgrade. bb59cf5 is GitHub's merge of the named base and head, and its tree is identical to 875e632.

Not run

  • No separate local rerun of the broader suites: the head CI run passed every job, including browser, live Clerk, packed CLI/tier 2, Postgres concurrency and the Node 22/24/26 tests. These results supplement the local checks above.

Notes

  • All environments and mutations were disposable and local. CLI invocations used env -u PATCHY_API_URL -u PATCHY_API_TOKEN PATCHY_STATE_DIR=<env>/cli-state; tier 2 publishing used the fixture repo's pinned CLI under that guard. MCP clients targeted only the dev instance. Production and ~/Patchy were untouched. No PR code, branch, body or labels were changed.

@allisonmahmood allisonmahmood mentioned this pull request Oct 23, 2026
Base automatically changed from mcp/854-read-patch to main October 23, 2026 15:59
…ied once

change_patch runs a patch's change tools under a change key the agent picks.
Patchy keeps each key for its agent connection and patch for 24 hours, with
the first try's version, tool and arguments, in a new change_keys table. A
mutation's first try gets a fresh Runtime mutation key that every retry
reuses, so a committed change is answered again with replayed: true from any
replica, and an unknown outcome resolves on retry without writing twice. An
action's key runs once. A try while the first still runs is busy; another
change under the key, or a retry after a publish, is refused. A change whose
result is too large for an agent succeeds with the result left out.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…own replays say so

A retry Patchy hasn't seen commit runs under the first try's mutation key only
while Runtime is sure to keep that key's outcome; after that it is refused
key_expired. Runtime tells an agent call when another invocation's stored
outcome answered it, so that retry also carries replayed: true. Any string is
a change key. Settling a key is bounded, the sweep reads its index, and the
rollback rehearsal stores a change key and replays it after a rollback.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…holds a request, and every string is its own key

The retry window reads the time in the first try's mutation key, which
Runtime ages it from, instead of when its row was written. The try and its
settling run in a fiber the request only joins, with settling bounded, so a
stalled pool can't hold a request or shutdown. Keys hash as JSON, so two lone
surrogates stay two keys.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… keeps its key held and its event

The request runs the try directly, so a disconnect reaches Runtime as it does
for reads and the request's event keeps Runtime's measurements and replayed.
A try that ends settles its key, bounded; one whose agent went away keeps its
key held until the lease runs out, the spec's busy, and a retry then resolves
through Runtime's record.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…hen its result is left out

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@allisonmahmood
allisonmahmood merged commit 45e476e into main Oct 23, 2026
14 checks passed
@allisonmahmood
allisonmahmood deleted the mcp/855-change-patch branch October 23, 2026 16:15
allisonmahmood added a commit that referenced this pull request Oct 23, 2026
… Claude" (#888)

Stacked on #887 (ticket #855); merges with the rest of #833's stack, not
alone.

## What changed

When someone's agent changes a patch through Patchy MCP, the log already
recorded the agent's client name (#843) but showed only the person, so
an owner couldn't tell a colleague's own edits from their agent's. Now
everywhere the log names a person, agent work reads **"Jordan Lee via
Codex"**, with the client name shown at consent: the Log tab's Person
column and the steps that acted as the person, the card's Recent
activity, a connection's recent calls, and `patchy logs` (text and
`--json`). There is no new column, tag or filter.

Closes #856

## Look at

**Codex on a dev instance (Done means).** On `brightline`, New Business
got two agent tools (`listDeals`, a query; `addNote`, a mutation).
Jordan's Codex connection (`pnpm dev mcp-token jordan --client Codex`,
per-invocation config outside `$HOME`) first listed the deals, then was
asked to add a note:

```
find_patches → open_patch → read_patch listDeals                          (run 1: list the deals)
find_patches → open_patch → read_patch listDeals → change_patch addNote   (run 2: add a note)
```

The database afterwards: the two quiet `listDeals` reads rolled up with
no row; the change has one.

```
runtime_invocations:   agent.addNote | mutation | usr_env_brightline_jordan | agent_name Codex | success
                       sample.load   | mutation | usr_env_brightline_allison | (none)          | success
runtime_query_rollups: agent.listDeals | 2 runs
```

**`patchy logs`** on that patch, base CLI and server vs. this branch,
same data:

```diff
-2026-10-22T20:12:29.005Z · v2 · agent.addNote (mutation) · success · 33 ms · Jordan Lee
+2026-10-22T20:12:29.005Z · v2 · agent.addNote (mutation) · success · 33 ms · Jordan Lee via Codex
   entry inv_… · correlation call_…
   - tables.update deals · as the patch · success · 4 ms · 1 rows
   - tables.insert activity · as the patch · success · 2 ms · 1 rows
```

`--json`, each entry's `{ handler, viewer, agent }`: before, entries had
no `agent`; after:

```
{"handler":"agent.addNote","viewer":{"id":"usr_env_brightline_jordan","name":"Jordan Lee"},"agent":{"name":"Codex"}}
{"handler":"sample.load","viewer":{"id":"usr_env_brightline_allison","name":"Allison Mahmood"},"agent":null}
```

`agent` decodes with a default, so a newer CLI reading an instance from
before agents (or after a rollback) prints `null` instead of failing to
decode; `docs/API.md` shows it as `agent?`.

**The pages**, as Allison (the owner and admin), after (before one click
away):

Log tab: ![Log tab
after](https://github.com/user-attachments/assets/f01f8a0c-2108-4448-baaf-a5543a14552c)

<details><summary>Log tab before</summary>

![Log tab
before](https://github.com/user-attachments/assets/c89b059a-9478-4d64-8458-e23493fbaee4)

</details>

Card, Recent activity: ![Card
after](https://github.com/user-attachments/assets/73c89ab6-5bfe-4f36-83cb-5389715f5dc7)

<details><summary>Card before</summary>

![Card
before](https://github.com/user-attachments/assets/4ca4342e-8d12-4667-a22e-bab46a86891d)

</details>

A connection's recent calls: ![Recent calls
after](https://github.com/user-attachments/assets/9bc76b9c-2845-469f-b74c-a0b97ad4b1c8)

<details><summary>Recent calls before</summary>

![Recent calls
before](https://github.com/user-attachments/assets/ed68483a-ee4a-40d4-aa87-4a0fd2b9cf6d)

</details>

<details><summary>Phones, 390 px: before | after</summary>

| Before | After |
|---|---|
| ![Log before,
phone](https://github.com/user-attachments/assets/265fbcdd-83df-41fb-86f2-89522c2f9cbb)
| ![Log after,
phone](https://github.com/user-attachments/assets/2564ac2d-6651-42ac-b38b-7627e720b738)
|
| ![Card before,
phone](https://github.com/user-attachments/assets/d5f5f3bb-da01-4103-8ba2-aef3ca0c1db6)
| ![Card after,
phone](https://github.com/user-attachments/assets/bae8b346-4395-4238-80e3-d3d757a09f26)
|
| ![Calls before,
phone](https://github.com/user-attachments/assets/5b2257a6-02c4-4da9-a1d7-45a03b74af53)
| ![Calls after,
phone](https://github.com/user-attachments/assets/ea75daaf-428d-49b8-9862-784655f56609)
|

At 390 px the Log and recent-calls tables scroll sideways, as they did
before; the longer name wraps in its cell.

</details>

The recent calls are **staged**: a dev instance can't reach a real
Postgres (connections need a public TLS host), so the
`postgres/warehouse` connection and its two calls (Jordan's page, then
Jordan via Codex) were written straight into the dev database.
Everything else above came from real calls. `pnpm dev compare` would
have shown no change, since no scenario seeds agent activity, so both
sides are this worktree's instance on the same data, with the base's
five changed source files restored for "before".

**The rule** is pinned at the door on real workerd
(`packages/mcp/src/Log.workerd.test.ts`): a quiet agent query leaves no
row; a query that logs, a query that fails, a read-only action and a
change each get a row naming the person and the agent. Runtime never
looked at the agent when deciding to log, so this test passed before the
change and keeps it that way.

**Escaping.** The client name is a stranger's string (≤ 64 characters,
controls and bidi marks removed by #846). Every HTML surface escapes it;
the portal and connection tests use `Claude <Code> & co`. The person
always comes first and from Patchy's own records, so a client's name
can't change whose work a row shows.

## How it was verified

- On the head `fd27c49` (on #887's `875e632`): CI is all green. `pnpm
verify` passed format, lint, typecheck, synth, postgres-concurrency,
cli-smoke, tier2-smoke and browser. Its `test` job hit 8 timeouts in
suites this PR doesn't touch, at a load average near 30; those 8 files
then passed alone (82 tests).
- Targeted suites: portal pages, connection pages, patches API, the
whole `packages/mcp` suite (workerd included), `patchy logs` text and
CLI, and the api package: 20 files, 279 tests.
- Review: GPT-6.1-Sol found nothing in one round (comment below); the
diff it read is unchanged by the restacks since.
- Acceptance: PASS with notes on `fd27c49` (comment below), on fresh
`brightline` data. Its notes are outside this diff: the environment
CLI's workerd lookup when publishing (#859) and a cold release build.
- `dev.log` keeps writing `usr_dev via patchy dev` (#844): it names
everyone by id, so it matches the platform's "<person> via <client>" in
its own terms.
- `patchy-server`'s agent area states the rule in the tested skill
text's words: "Patchy's log records each change and action as "Person
via Client", failures included. A query that succeeds without `ctx.log`
leaves no row; a patch that wants agent reads seen logs them itself,
using `ctx.agent` for the name."
- No migration and no descriptor or publish changes, so
`rollback-rehearsal` has nothing of this PR's to rehearse; the stack's
rehearsal waits on #837 and #838 as #833 says.
- An earlier head's CI failed once on Node 24 in `PatchesApi.test.ts ›
refuses a blank or over-long description in the bundle` ("Invalid server
manifest: inspection."), a case this PR doesn't touch. It passed on Node
22 and 26 then, alone on Node 24 in acceptance, and on every Node at
`fd27c49`. It isn't filed as a known flake.

## Release impact

- [ ] **Breaking** — requires action from anyone already running this
- [x] **Not breaking** — no action required

An additive field on the log's wire shape and wording on existing pages;
no migration.

- **What does a revert leave behind?** Nothing: no schema or rows. Agent
rows written meanwhile keep `agent_name` from #843's migration.
- **Does the release before it still work with that?** Yes. A CLI from
this release reading an older instance prints `agent: null`.

Built by Claude Opus 5.5 (xhigh) in Claude Code on T3 Code; reviewed and
accepted by GPT-6.1-Sol (xhigh).
allisonmahmood added a commit that referenced this pull request Oct 23, 2026
## What changed

This PR adds release 17's What's new entry, written from `5dd94f3`. It
covers everything merged since release 16's `through` (`dd3f41f`), and
it sets the `patchy` release to `0.17.0` in
`packages/patchy/package.json` and `CURRENT_RELEASE`. With this release,
people's agents can use their company's patches through Patchy MCP
(#833).

| Change | PRs |
| --- | --- |
| New: Your AI agent can use your company's tools | #873, #878, #880,
#881, #882, #883, #884, #886, #887 |
| New: Admins choose whether agents can use the company's tools | #871 |
| Improved: Your machines shows your agents too (Revoke all machines is
now Disconnect everything) | #885, #879 |
| New: See what agents can do with a tool | #876 |
| New: The log says when an agent made a change | #888 |
| New: Your agent can make a tool ready for agents | #869, #870, #872,
#875, #896 |
| Behind the scenes: agents' calls have their own limits, and a server
only an agent uses rests a minute after its last call | #889, #892 |
| Behind the scenes: New and Improved changes are public, for
patchyhq.com | #893 |
| Behind the scenes: library updates | #899 |

Five merged PRs get no line:
- #874 is release 16's own entry.
- #894 is dev tooling: worker agent launchers and scenario data. Its one
CLI fix lets a `patchy` installed outside a tier 2 repo publish it. The
skills have agents use the repo's pinned `pnpm patchy` instead, so that
path is off the documented one.
- #900 is CI.
- #901 rewords an internal skill.

## Look at

- **The entry**, at the top of `releases` in
`packages/core/src/whatsNew.ts`.
- It names only Claude Code and Codex. Both have connected through real
consent against dev instances. Hosted clients (Claude.ai, ChatGPT) are
checked in production only (`docs/product.md` › Patchy MCP ›
Acceptance).
- Its labels are the pages' own: Agent access on Company, Your machines,
What agents can do, Disconnect everything, and "Jordan Lee via Claude".
- **Rollback safety, from the live commit `e4243ff` to `5dd94f3`.**
- No PR in the range is labelled `one-way`, and every PR answers both
Release impact questions with "Yes".
  - Migrations 0020–0025 are all additive:
    - three defaulted or nullable columns on `companies`;
- `agent_name` on the runtime log, with a widened `credential_kind`
check;
    - the agent connection tables, `agent_consents` and `change_keys`;
    - two columns on execution bindings.

The new tables reference `users` without a cascade, but no release
deletes users or companies. Release 16 reads the runtime log only for
credential kinds it knows, so rows from agents can't break it.
- `rollback-rehearsal` on #892 rehearsed the whole stack, since #892
adds the last migration and the rest of the stack sits below it:
`Exercised rollback paths passed: e4243ff → c8bede4 → e4243ff → c8bede4,
in 238s.` #896's run skipped, because it changes no migration or handler
descriptor.
- #883 turns on the load balancer's host header preservation, which the
Deploy workflow's app stack deploy applies. A rollback leaves it on.
That's harmless, because release 16's server never reads `Host`.
- A rollback takes `/mcp` and `/whats-new.json` away. Connected agents
get a 404 until this release returns, and then their connections work
again, unless one ended in between. Agent tools published in between
stay refused to pages, because #837 already shipped in release 16.

## How it was verified

- `pnpm check` on `2d528b1`: format, lint, typecheck and synth passed.
In the test step, 2,300 of 2,301 tests passed. The one failure was
`packages/sdk/src/install.test.ts` › "says how to reach patchy when the
prefix's bin is not on PATH", which timed out at 180 s while the shared
machine was loaded. Rerun alone, that file passes all 7 tests in 62 s.
The release's own tests pass too: `whatsNew.test.ts`, `schemas.test.ts`
and `WhatsNewPages.test.ts`.
- The live commit was pinned from `/healthz/deep`: `e4243ff`, release
16. The Deploy run updated last succeeded, and none is unfinished.
- Each PR in the range was read with `gh pr view`, including its Release
impact answers.

## Release impact

- [ ] **Breaking** — requires action from anyone already running this
- [x] **Not breaking** — no action required

This PR changes only the changelog text and the `patchy` version. As
with every release, a CLI installed before this deploy is told to
upgrade.

- **What does a revert leave behind?** Nothing. People whose seen marker
reached 17 would just see no new release.
- **Does the release before it still work with that?** Yes.

If this release misbehaves, roll back to
`e4243ff54d2acbbc88b60eeb0cf9b82a26dc9d5d` (release 16).

Prepared by Claude Opus 5.5 (xhigh) in Claude Code on T3 Code.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:ci CI, shared testing infrastructure, development scripts and tooling area:cli Touches the cli area area:docs Touches the docs area area:server Touches the server area size:xl Over 1,000 changed lines; review in multiple passes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Worker agents change patches, and a retried change is applied once

1 participant