Skip to content

Commit 1a5ce45

Browse files
donjor-agent[bot]donjor
authored andcommitted
fix(mcp): expose reversible external thread settlement (#1649)
## Problem The external MCP connection can read and filter settlement state but cannot change it. Agents cannot perform the existing UI's settle/unsettle operation through that connection. ## Change Add `t3_external_thread_settle` with required `threadId`, `settled`, and `clientRequestId`, delegating to the existing lifecycle commands. Recheck coordination and project access before replay, enforce existing mode ceilings at preflight and under the thread lock, and return the original committed acknowledgement with its command ID and sequence. Thread read/list continues to report current state after later owner changes. Settlement retains existing side effects: cancel message-capable async questions and queued automatic wakeups, clear pins/PR watches, and detach provider sessions. Unsettle reverses the settled flag without restoring those side effects. The existing predicate rejects active root runs and blocking callback approvals/input; it does not inspect native/background children. The marked contract export sits in the existing fork-only export group, avoiding the upstream append-boundary conflict. Rebased onto accepted #1648; only manual resolution was two documentation tables, retaining both features' entries. Accepted background read/wait behavior survives, including its limitation: resumed native child projections can remain stale. ## Scope and approval User authorized this focused API parity fix, independent High review, publication, integration resolution and normal source closeout. No UI, background-observability behavior, credential, grant, account, security-setting or mass-settlement changes. Runtime release and acceptance remain separately owned. ## Verification Head: `f1bc18d0fc2c12f37f118dd38b3ea6bb61c5f94b`. Base/parent: `624767b5026c471d8f8a3ff03a4fddd83e8948df`. Original checkpoint `a219060e89d4375858cea3c404aa4e7d6e6c6470` retained under `refs/wt-backup/fix/external-mcp-settlement`. Independent native Codex `gpt-6.1-sol`, `reasoningEffort=high` review: **approve, no material findings** at the new exact head/base. | Check | Result | | --- | --- | | `vp run fork:ci` | Exit 0; 756 scripts tests; scan/check green | | External MCP, grant, contracts, upstream-client compatibility tests | Exit 0; 114 tests, including 20 settlement tests | | Existing runtime settlement tests | Exit 0; 6 passed, 61 filtered out | | Server and contracts typechecks | Both exit 0 | | `vp run --filter t3 build:bundle` | Exit 0 | | `vp run knip:check` | Exit 0 | | HTTP request/response evidence test | Exit 0; 1 passed, 19 filtered out | | Whole upstream merge-tree policy | Exit 0; no head-only conflicts | [Final integration evidence](https://github.com/user-attachments/files/33127139/t3-settle-integration-evidence.zip) contains protocol request/response output, exact commands, logs, attributed terminal wrapper receipts and independent review. Attachment readback matched uploaded bytes. Policy comparison used the stated base and fresh upstream `3dfe373fddb966101371805b0b102ae5af75b15b`. All eight required remote checks passed at this head ([CI run](https://github.com/RSI-Software/t3code-hyprws/actions/runs/37525775093)). Ready-triggered gates remain separate from source CI and independent review. [Original checkpoint evidence](https://github.com/user-attachments/files/33126181/t3-settle-cifix-evidence.zip) and [published checkpoint review](#1649 (review)) remain available. That GitHub review is `COMMENTED`, not a formal approval. <details> <summary>Coverage and remaining release checks</summary> Tests cover repeats, concurrent duplicates, key conflicts, session isolation, rebuilt-service recovery, owner reversal before acknowledgement, authorization failures, mode ceilings, and start/archive/delete/mode races. Parity tests cover cancellations, pin/watch clearing, provider-session projection removal, durable detach intent, and the existing native-child predicate limitation. The isolated HTTP fixture uses the real route/service/orchestrator with memory SQLite and a mock authenticator. It does not execute provider processes or a full disk/process restart; existing aggregate lint and bundle warnings remain. Installed catalog exposure, live authority/refusal behavior, real session detachment and client readback await release. Runtime remains untouched; deployed `.965` commit identity was not established. Reproduce protocol evidence at this head: ```sh T3_SETTLEMENT_EVIDENCE=1 vp test run apps/server/src/mcp/external/ExternalMcpSettlement.fork.test.ts -t "exposes reversible settlement" ``` </details> Implemented through the Codex harness with `gpt-6.1-sol` at High reasoning. Native T3 selected provider instance `codex`; validated posting-worker provenance names backend `cliproxy`, harness `[email protected]`. The new independent reviewer confirms Codex/Sol/High; its backend and harness version remain unconfirmed. ChatGPT authentication and billing source remain unconfirmed. ## Fork trailers Squashes: - 874de6b fix(mcp): expose reversible external thread settlement (#1649) (#1649) - ebe4e09 fixup! fix(mcp): expose reversible external thread settlement (#1649) (#1649) Fork-Domain: device-auth Fork-Tier: core Co-authored-by: donjor <[email protected]>
1 parent 681bf67 commit 1a5ce45

12 files changed

Lines changed: 1011 additions & 29 deletions

File tree

‎apps/server/src/mcp/external/ExternalMcpRequestLedger.fork.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import * as Schema from "effect/Schema";
1313
import * as Semaphore from "effect/Semaphore";
1414
import * as SqlClient from "effect/unstable/sql/SqlClient";
1515

16-
export type ExternalMcpOperation = "create" | "send" | "interrupt";
16+
export type ExternalMcpOperation = "create" | "send" | "interrupt" | "settle";
1717

1818
/** The target an attempt committed to before it dispatched, read back by a retry. */
1919
export interface ExternalMcpPin {

‎apps/server/src/mcp/external/ExternalMcpServer.fork.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,7 @@ it.live("admits only a device-grant session that carries an external MCP grant",
208208
"t3_external_thread_list",
209209
"t3_external_thread_read",
210210
"t3_external_thread_send",
211+
"t3_external_thread_settle",
211212
"t3_external_thread_wait",
212213
"t3_external_whoami",
213214
],

‎apps/server/src/mcp/external/ExternalMcpService.fork.ts‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import {
88
type AuthSessionId,
99
CommandId,
10+
ExternalMcpSettlementResultFork,
1011
isProviderAvailable,
1112
MessageId,
1213
type ModelSelection,
@@ -40,6 +41,7 @@ import * as Duration from "effect/Duration";
4041
import * as Effect from "effect/Effect";
4142
import * as Layer from "effect/Layer";
4243
import * as Option from "effect/Option";
44+
import * as Result from "effect/Result";
4345
import * as Stream from "effect/Stream";
4446

4547
import {
@@ -128,6 +130,14 @@ export interface ExternalMcpThreadWaitResult extends OrchestratorMcpThreadWaitRe
128130
}
129131

130132
export interface ExternalMcpServiceShape {
133+
readonly settleThread: (
134+
principal: ExternalMcpPrincipal,
135+
input: {
136+
readonly threadId: ThreadId;
137+
readonly settled: boolean;
138+
readonly clientRequestId: string;
139+
},
140+
) => Effect.Effect<ExternalMcpSettlementResultFork, OrchestratorMcpFailure>;
131141
readonly listProjects: (
132142
principal: ExternalMcpPrincipal,
133143
) => Effect.Effect<ReadonlyArray<ExternalMcpProject>, OrchestratorMcpFailure>;
@@ -503,6 +513,79 @@ const make = Effect.gen(function* () {
503513
});
504514

505515
return ExternalMcpServiceFork.of({
516+
settleThread: (principal, input) =>
517+
Effect.gen(function* () {
518+
yield* requireCoordinate(principal);
519+
// Revalidate project access even on a cached replay; a key grants no authority.
520+
yield* loadThread(principal, input.threadId);
521+
const commandId = CommandId.make(
522+
`command:${stableId(principal, "settle", input.clientRequestId)}`,
523+
);
524+
const committed = () =>
525+
events.readByCommandId({ commandId }).pipe(
526+
Stream.filterMap((stored) =>
527+
stored.event.type === "thread.settled" || stored.event.type === "thread.unsettled"
528+
? Result.succeed({ payload: stored.event.payload, sequence: stored.sequence })
529+
: Result.fail(stored),
530+
),
531+
Stream.runHead,
532+
Effect.mapError((error) => failure("orchestration_error", errorMessage(error))),
533+
);
534+
return yield* ledger.run(
535+
{
536+
sessionId: principal.sessionId,
537+
operation: "settle",
538+
clientRequestId: input.clientRequestId,
539+
fingerprint: requestFingerprint([
540+
["threadId", input.threadId],
541+
["settled", input.settled],
542+
]),
543+
result: ExternalMcpSettlementResultFork,
544+
},
545+
() =>
546+
Effect.gen(function* () {
547+
let event = yield* committed();
548+
// A crash after commit but before recording the result must recover the
549+
// original event, even if the owner has since reversed the settlement.
550+
if (Option.isNone(event)) {
551+
const target = yield* loadThread(principal, input.threadId);
552+
const expectedModes = yield* vetThreadModes(principal, target.thread);
553+
yield* audit(principal, "thread.settle", {
554+
threadId: input.threadId,
555+
settled: input.settled,
556+
commandId,
557+
});
558+
const common = {
559+
commandId,
560+
threadId: input.threadId,
561+
...(expectedModes === undefined ? {} : { expectedModes }),
562+
};
563+
yield* threadManagement
564+
.dispatch(
565+
input.settled
566+
? { ...common, type: "thread.settle" }
567+
: { ...common, type: "thread.unsettle", reason: "user" },
568+
)
569+
.pipe(Effect.mapError(threadManagementFailureFork));
570+
event = yield* committed();
571+
}
572+
if (Option.isNone(event)) {
573+
return yield* failure(
574+
"orchestration_error",
575+
"Settlement command has no committed event.",
576+
);
577+
}
578+
const thread = event.value.payload;
579+
return {
580+
threadId: input.threadId,
581+
commandId,
582+
sequence: event.value.sequence,
583+
settled: thread.settledOverride === "settled",
584+
settledAt: thread.settledAt === null ? null : DateTime.formatIso(thread.settledAt),
585+
};
586+
}),
587+
);
588+
}),
506589
listProjects: (principal) =>
507590
projects
508591
.listShells(

0 commit comments

Comments
 (0)