Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,17 @@

### Fixed

1. **A direct `python extensions/mcp-binding/mcp_binding.py` now connects its servers.** The binding attached its boot
1. **The agent-question app keeps the first accepted decision when two devices decide one card at the same moment**
(RFC-0014 step 5, the live drive of 2026-11-19). Both clicks pass the open check and reach the engine, which resumes at
most once; the device that lost got `nothing waiting`, and the row took whichever outcome landed last - so a late 410
could overwrite the accepted decision and its operator. A decision's write now applies when the row is still open or
when the engine accepted the decision (`state = 'answered'`), in the memory inbox and in `SQL_DECIDED` alike; a
refused write answers the losing device with the row as it stands, so it sees who decided, and nothing is broadcast
for it. The shared vectors are version 2 with the two-devices transition case (`tests/vectors/agent-question-vectors.json`,
31 cases); a race test with a scripted reply endpoint pins both orderings. **Upgrade note:** none - the schema is
unchanged.

2. **A direct `python extensions/mcp-binding/mcp_binding.py` now connects its servers.** The binding attached its boot
and shutdown hooks to the platform only when loaded by `mercury-serve`; run directly, the Event API started with no
server connected and every bound route answered 503. Both entry points attach the hooks now, so a bad server file
stops the direct run by name as it stops the served one.
Expand Down
4 changes: 3 additions & 1 deletion extensions/agent-question/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ application is one of those routes. It is a standalone application on the packag
(`expired`); a refused decision or an endpoint that did not answer leaves it `open` with the outcome shown. An
advice is `open` until the person marks it `seen`. Open waits past their expiry are marked `expired` by a sweeper
and before every replay. The engine stays the authority: a second device on the same card gets `nothing waiting`,
and the row records the first. Rows are never deleted here; `schema/purge.sql` is the installation's.
and the row records the first: an acceptance always wins the row, and a `nothing waiting` that lands after one
never overwrites it (the live drive of 2026-11-19). Rows are never deleted here; `schema/purge.sql` is the
installation's.

The Node.js twin (mercury-nodejs `extensions/agent-question`) serves the same route, the same page and the same
schema, pinned by the same vector file.
Expand Down
17 changes: 14 additions & 3 deletions extensions/agent-question/agent_question.py
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,8 @@ async def decided(self, row_id: int, decisions: list[dict[str, Any]], who: str,
row = self._rows.get(row_id)
if row is None:
return None
if row.state != "open" and state != "answered":
return row # decided first by another device: a later nothing-waiting never overwrites it
row = replace(row, seq=self._bump(), state=state, decisions=decisions, outcome=outcome,
answered_by=who, answered_at=now, updated_at=now)
self._rows[row_id] = row
Expand Down Expand Up @@ -484,7 +486,7 @@ async def counts(self) -> dict[str, int]:
SQL_DECIDED = (
"UPDATE question_inbox SET seq = nextval('question_inbox_seq'), state = %s, decisions = %s::jsonb, "
"outcome = %s::jsonb, answered_by = %s, answered_at = %s::timestamptz, updated_at = %s::timestamptz "
f"WHERE id = %s RETURNING {COLUMNS}"
f"WHERE id = %s AND (state = 'open' OR %s::text = 'answered') RETURNING {COLUMNS}"
)
SQL_SEEN = (
"UPDATE question_inbox SET seq = nextval('question_inbox_seq'), state = 'seen', updated_at = %s::timestamptz "
Expand Down Expand Up @@ -583,7 +585,9 @@ async def since(self, seq: int, limit: int) -> list[Row]:

async def decided(self, row_id: int, decisions: list[dict[str, Any]], who: str, state: str,
outcome: dict[str, Any], now: str) -> Row | None:
return await self._one(SQL_DECIDED, (state, _compact(decisions), _compact(outcome), who, now, now, row_id))
row = await self._one(SQL_DECIDED, (state, _compact(decisions), _compact(outcome), who, now, now, row_id, state))
# no row: the guard kept a row another device decided first (or the row is gone) - answer with it as stored
return row if row is not None else await self.get(row_id)

async def seen(self, row_id: int, now: str) -> Row | None:
return await self._one(SQL_SEEN, (now, row_id))
Expand Down Expand Up @@ -910,7 +914,8 @@ async def _forward(url: str, body: dict[str, Any], settings: Settings) -> tuple[
async def decide(request: web.Request) -> web.Response:
"""``POST /questions/{id}/decide`` with ``{decisions, decided_by?}``: the click, automated - the decisions
go to the link's reply endpoint under this app's bearer, the outcome lands on the row, every device is
told, and the invoker gets the row with the outcome."""
told, and the invoker gets the row with the outcome. The first accepted decision stands: an acceptance always
wins the row, and a nothing-waiting that lands after one never overwrites it."""
settings = current_settings()
try:
body = await request.json()
Expand Down Expand Up @@ -952,6 +957,12 @@ async def decide(request: web.Request) -> web.Response:
updated = await inbox().decided(row_id, [dict(d) for d in decisions], identity.who, state, outcome, now)
if updated is None:
return _error(404, f"row {row_id} is not in the inbox")
if updated.answered_by != identity.who or updated.answered_at != now:
# two devices on one card: the other one's decision was accepted while this one was in flight, so the engine
# answered nothing-waiting here and the row stands as the first decision left it - this device sees who
log.info("Row %d: %s's decision met a row %s by %s - the row stands", row_id, identity.who, updated.state,
updated.answered_by)
return web.json_response({"row": updated.public(), "outcome": outcome})
_wakeups.publish([updated])
log.info("Row %d decided by %s via %s - %s -> %s", row_id, identity.who, identity.via, outcome["status"], state)
return web.json_response({"row": updated.public(), "outcome": outcome})
Expand Down
3 changes: 2 additions & 1 deletion extensions/ask-person/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,8 @@ engine; a malformed one or another version is a 400, one no key signs a 403.
renders as expired; an engine that has moved on shows its reply.
- `POST /ask/reply` takes `{"ticket": "...", "decisions": [...], "decided_by": "..."}`: `{id, approved, note?}` for a
tool call, `{id, answer}` for a question - the shapes the loop accepts. Each tool call's note is prefixed
`[<who> at <time>]`, so the audit store carries who decided without a new field; an answer travels unchanged. The
`[<who> at <time>]`; the audit store carries it when the note reaches the model, which the loop does for a refused
call - an approved call's decision stays on the channel's record and in this log; an answer travels unchanged. The
engine's status and JSON body come back as they are; a graph that does not answer or answers outside the contract is a
502 `{"type": "error", "message": ...}`; an expired ticket is a 410 `{"type": "expired"}`.
- **Who may answer** (`ask.reply.auth`): `none` in development - no sign-in, `decided_by` is taken as given or the
Expand Down
10 changes: 8 additions & 2 deletions memory/continuity.md
Original file line number Diff line number Diff line change
Expand Up @@ -275,10 +275,16 @@
`POST /questions/{id}/decide` to the link's own base under the app's bearer with `decided_by`, and `seen` for an
advice; states open, answered, expired, seen; a sweeper expires waits past their expiry. Identity `question.auth`:
`none`, `proxy`, `oauth2`. Pinned by `tests/vectors/agent-question-vectors.json` (30 cases) and 48 tests; the Node
twin follows. **How to apply:** the app is one channel among equals - a chat, mail or a topic adapter takes the same
twin follows. **Driven live 2026-11-19 (RFC-0014 step 5, mercury-composable `docs/test-reports/ask-a-person-live-drive.md`):**
the chain held on every scenario; one defect fixed here - two devices deciding one card at the same moment both reach
the engine (it resumes at most once), and the row took whichever outcome landed last, so a late `nothing waiting` could
overwrite the accepted decision: a decision's write now applies when the row is still open or when the engine accepted
it (`answered` always wins), the losing device gets the row as it stands, vectors version 2 (31 cases). **How to apply:**
the app is one channel among equals - a chat, mail or a topic adapter takes the same
event and keeps its own buffer; the app never talks to the engine, only to the reply endpoint the link names; a row is
never deleted by the app; a new card state is a change to `state_after` and the schema's check constraint in both
packs.
packs; a wait decided elsewhere stays open on a card until a device tries it (410 → expired) or it expires - the
acknowledgement advice beside it tells the person.
<!-- id: agent-question-app | created: 2026-11-19 | last_used: 2026-11-19 | uses: 1 | tier: working | origin: 2026-11-19-071444 -->

## Conventions
Expand Down
42 changes: 42 additions & 0 deletions memory/sessions/2026-11-19-084813.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Session (2026-11-19T08:48:13.000Z)

**Agent:** Claude Code
**Title:** RFC-0014 step 5, the live drive - the agent-question app keeps the first accepted decision when two devices decide one card
**User:** Eric - "please proceed with step 5 of the build plan. After that, please provide step-by-step instruction so I can run a manual regression test using the new agent-question UI app."

## What We Did

- **The live drive of the whole chain** (the record is the engines' `docs/test-reports/ask-a-person-live-drive.md`): the
Java Playground's `order-assistant` and `plan-assistant` on Haiku 4.5 through this pack's LLM helper (Redis store,
PostgreSQL audit), `extensions/ask-person` on 8091 and `extensions/agent-question` on 8092 with the inbox on the same
PostgreSQL - negative controls, a pack that is down, the link in a bare browser with no channel, a device online, a
device off and reconnecting, a decision after expiry, two devices on one ticket - then the Node twins behind the same
Playground. The device was headless (a client holding the stream as the page's script does; the page's endpoints
driven directly); the browser walk-through is the manual regression test at the report's end.
- **Defect found here and fixed:** the inbox's decision write was unconditional. Two devices deciding one card at the
same moment both pass the open check and both reach the engine, which resumes at most once; the loser gets
`nothing waiting`, and the row took whichever outcome landed last - in the drive the 410 landed first (22 ms against
1.5 s), so the row happened to end right, but the opposite order would have overwritten the accepted decision and its
operator. Now `MemoryInbox.decided` and `SQL_DECIDED` apply a write only when the row is still open or the state is
`answered` (an acceptance always wins); `PostgresInbox.decided` answers with the row as stored when the guard kept
it; the handler returns that row with the invoker's own outcome and broadcasts nothing for it. Re-driven twice live:
the losing device's 410 turned the row expired for a moment, the acceptance won it back.
- **Shared vectors version 2** (`tests/vectors/agent-question-vectors.json`, 31 cases): the two-devices transition case
pins both the overwrite that must not happen and the sequence standing still; the description says why. A race test
with a scripted reply endpoint (`t-race-slow`, `t-race-fast`) pins both orderings through the handler.
- **Narrowed a claim** in the ask-person README: who decided reaches the audit store only when the note reaches the model
(a refused call); an approved call's decision stays on the channel's record and in the log - a drive finding, with the
loop's follow-up recorded in the RFC.
- **Gates:** ruff OK, basedpyright 0 errors, the agent-question suite 48 passed (+1), the two extension suites 148; CHANGELOG
Unreleased/Fixed 1. Diff scanned for [[conv-compartment-downstream-secrets]]: fictional device and operator names only.
- The Node twin takes the same guard and the same vectors in its own PR; the engines' PR carries the report, the gate fix
of the reference graphs and the RFC's step-5 notes.
- Opened as PR #71.

## Memory References

- Referenced: agent-question-app (edited: driven live, the first-decision rule), ask-person-main-flow (the reply
endpoint's behaviour shaped every scenario), conv-python-quality-gates (the gates run), conv-compartment-downstream-secrets
(the diff scan)
- Created: (none)
- Superseded: (none)
50 changes: 48 additions & 2 deletions tests/test_agent_question.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def _case(section: str, name: str) -> dict[str, Any]:


def test_the_vector_file_is_the_shared_contract() -> None:
assert VECTORS["contract"] == "agent-question" and VECTORS["version"] == 1
assert VECTORS["contract"] == "agent-question" and VECTORS["version"] == 2
for section in ("row_cases", "outcome_cases", "click_cases", "transition_cases"):
assert VECTORS[section], section

Expand Down Expand Up @@ -256,13 +256,23 @@ class FakeReply:

def __init__(self) -> None:
self.posts: list[dict[str, Any]] = []
self.raced: dict[str, bool] = {}

async def reply(self, request: web.Request) -> web.Response:
body = await request.json()
self.posts.append({"body": body, "authorization": request.headers.get("authorization")})
ticket = body.get("ticket")
if ticket == "t-expired":
return web.json_response({"type": "expired", "message": "Ticket expired"}, status=410)
if ticket in ("t-race-slow", "t-race-fast"):
# two devices on one card: the engine resumes at most once - the first post is accepted, the next gets
# nothing-waiting; with t-race-slow the acceptance takes longer than the refusal, so the 410 lands first
if self.raced.get(ticket):
return web.json_response({"type": "nothing-waiting", "run": "fresh"}, status=410)
self.raced[ticket] = True
if ticket == "t-race-slow":
await asyncio.sleep(0.5)
return web.json_response({"type": "answer", "turn": 3, "run": "resume", "message": "Issued."})
if ticket == "t-refused":
return web.json_response({"type": "approval", "turn": 2, "error": "not a call waiting for approval",
"calls": CALLS})
Expand Down Expand Up @@ -416,6 +426,42 @@ async def test_a_decision_is_forwarded_recorded_and_broadcast(
aq._wakeups.unsubscribe(queue)


async def test_two_devices_on_one_card_the_first_accepted_decision_stands(
configure: Callable[[dict[str, Any]], Any], reply_endpoint: tuple[FakeReply, str], host: str
) -> None:
"""Both clicks pass the open check and reach the engine; whichever order the outcomes land in, the row ends
answered by the device the engine accepted, and the other device gets the row as it stands with its own 410."""
_, base = reply_endpoint
configure(BASE)
decisions = [{"id": "toolu_01A", "approved": True}]

async def click(http: aiohttp.ClientSession, row_id: int, who: str) -> tuple[int, dict[str, Any]]:
async with http.post(f"{host}/questions/{row_id}/decide",
json={"decisions": decisions, "decided_by": who}) as response:
return response.status, await response.json()

async with aiohttp.ClientSession() as http:
# the acceptance lands last: the losing device's 410 turned the row expired for a moment, then the acceptance won
slow = await _take(wait_event(ticket="t-race-slow", base=base, correlation_id="race-1"))
first, second = await asyncio.gather(click(http, slow.id, "device-1"), click(http, slow.id, "device-2"))
assert first[0] == 200 and first[1]["row"]["state"] == "answered"
assert first[1]["row"]["answered_by"] == "device-1" and first[1]["outcome"]["status"] == 200
assert second[0] == 200 and second[1]["row"]["state"] == "expired" and second[1]["outcome"]["status"] == 410
stored = await aq.inbox().get(slow.id)
assert stored is not None and stored.state == "answered" and stored.answered_by == "device-1"
# the acceptance lands first: the 410 that follows changes nothing, and the loser sees who decided
fast = await _take(wait_event(ticket="t-race-fast", base=base, correlation_id="race-2"))
first, second = await asyncio.gather(click(http, fast.id, "device-1"), click(http, fast.id, "device-2"))
assert first[1]["row"]["state"] == "answered" and first[1]["row"]["answered_by"] == "device-1"
assert second[0] == 200 and second[1]["outcome"]["status"] == 410
assert second[1]["row"]["state"] == "answered" and second[1]["row"]["answered_by"] == "device-1"
stored = await aq.inbox().get(fast.id)
assert stored is not None and stored.state == "answered" and stored.answered_by == "device-1"
# after the fact, the app itself refuses without an engine call
async with http.post(f"{host}/questions/{fast.id}/decide", json={"decisions": decisions}) as response:
assert response.status == 409 and "device-1" in (await response.json())["message"]


async def test_open_waits_past_their_expiry_are_marked_expired(
configure: Callable[[dict[str, Any]], Any], host: str
) -> None:
Expand Down Expand Up @@ -520,7 +566,7 @@ async def test_the_postgres_inbox_runs_the_statements_and_maps_the_records() ->
await box.decided(7, [{"id": "toolu_01A", "approved": True}], "operator-17", "answered", {"status": 200, "body": {}}, now)
sql, params = pool.log[-1]
assert sql == aq.SQL_DECIDED and params == ("answered", '[{"id":"toolu_01A","approved":true}]', '{"status":200,"body":{}}',
"operator-17", now, now, 7)
"operator-17", now, now, 7, "answered")
await box.seen(8, now)
assert pool.log[-1] == (aq.SQL_SEEN, (now, 8))
await box.expire(now)
Expand Down
Loading
Loading