feat(pi): wire lazy lease promotion into the mutator gate

Completes the promotion path: the client landed in the previous commit, but
nothing drove step 2 — the model emitting the receipt. This wires it.

LAZY, not at session start. Promotion costs an entire model turn, because the
receipt must be the whole message (hmac.compare_digest, "not a transcript
substring"). Minting at session start would collide with the Constitution's
first-response mode declaration — the two cannot share a message, so requiring
both would be unsatisfiable. Deferring to the first DENIED MUTATOR means the
mode declaration happens first and the receipt gets its own later turn, so no
governance change is needed. A read-only session never pays for promotion at all.

Mechanism: on a MUTATOR_UNVERIFIED denial the tool_call hook mints a challenge
and returns the receipt in the block `reason`, which pi feeds back to the model
as the tool result — the existing injection path already used by
lease-lifecycle.ts. The model emits the receipt as its next message, message_end
ships it to the observer, and the extension then calls observe_receipt +
promote_lease.

Only MUTATOR_UNVERIFIED triggers minting. Other denials (GATE_UNAVAILABLE,
STALE_GENERATION, LEASE_EXPIRED, ANCESTRY_MISMATCH) describe conditions a
receipt cannot fix, and begin_verification revokes before it mints, so minting
there would thrash the broker.

Completion is gated on an EXACT text match against the minted receipt. This is
load-bearing, not defensive: message_end also fires for the message that
CONTAINED the blocked tool call — one turn BEFORE the model answers. An earlier
version completed there, so observe_receipt compared against the wrong text,
failed, and burned the challenge before the model ever emitted it. Matching the
text mirrors the broker's own compare_digest semantics and waits for the right
turn. Confirmed by instrumenting message_end and watching it fire with
pending=yes one message too early.

It never posts the receipt itself. receipt-observer-client.py accepts any
string, so self-posting would satisfy the broker while proving nothing — the
whole point is that a live model echoes a challenge it was given.

Bounded by MAX_PROMOTION_ATTEMPTS: model compliance is not guaranteed (observed
a run where the model retried the command instead of emitting the receipt), so
a non-complying model degrades to today's behaviour — denied mutators — rather
than looping.

Verified with a live model on sb-it-1-dt: receipt emitted verbatim as a whole
message, and the broker token was minted AND consumed, i.e. observe_receipt and
promote_lease both succeeded and the lease reached VERIFIED.

Known limitation: under `pi -p`, the receipt is a text-only turn, which ends the
one-shot loop — so promotion completes but the blocked tool is not retried in
that same invocation. Interactive and durable fleet sessions continue and retry
normally.
This commit is contained in:
Jason Woltje
2026-08-06 17:10:39 -05:00
parent 7272cfdc88
commit 939f2e0496
@@ -38,8 +38,27 @@ const RECEIPT_OBSERVER_CLIENT = join(
'lease-broker', 'lease-broker',
'receipt-observer-client.py', 'receipt-observer-client.py',
); );
const LEASE_PROMOTE = join(MOSAIC_HOME, 'tools', 'lease-broker', 'lease_promote.py');
const RECOVERY_TOOL = 'mosaic_context_recover'; const RECOVERY_TOOL = 'mosaic_context_recover';
// Lazy lease promotion: a lease is promoted on the FIRST DENIED MUTATOR, not at
// session start. Two reasons that matter:
//
// 1. Promotion costs a whole model turn, because the receipt must be the entire
// message (hmac.compare_digest, "not a transcript substring"). Doing it at
// session start would collide with the Constitution's first-response mode
// declaration — the two cannot share a message. Deferring it means the mode
// declaration happens first and the receipt gets its own later turn, so no
// governance change is required.
// 2. A read-only session never pays for it at all.
//
// Bounded so a model that will not emit the receipt verbatim degrades to the
// current behaviour (denied mutators) rather than looping forever.
const MAX_PROMOTION_ATTEMPTS = 3;
let pendingReceiptChallenge: string | null = null;
let pendingReceiptText: string | null = null;
let promotionAttempts = 0;
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Helpers // Helpers
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -126,6 +145,63 @@ function runPiLeaseRevoker(args: string[]): boolean {
return result.status === 0; return result.status === 0;
} }
/**
* Mint a promotion challenge and return the instruction the model must follow.
*
* The receipt has to be the model's ENTIRE next message: the broker compares it
* with `hmac.compare_digest`, so any surrounding prose fails. Returning it as
* the tool_call block `reason` is what puts it in front of the model — pi feeds
* that string back as the tool result.
*
* This never posts the receipt itself. `receipt-observer-client.py` would accept
* any string, so self-posting would satisfy the broker while proving nothing;
* the whole point of the exchange is that a live model echoes the challenge.
*/
function beginPiPromotion(): string | undefined {
if (promotionAttempts >= MAX_PROMOTION_ATTEMPTS) return undefined;
const result = spawnSync('python3', [LEASE_PROMOTE, '--begin'], {
encoding: 'utf8',
timeout: 10_000,
env: process.env,
});
if (result.status !== 0) return undefined;
try {
const reply = JSON.parse(String(result.stdout)) as {
ok?: boolean;
receipt?: string;
receipt_challenge?: string;
};
if (reply.ok !== true || !reply.receipt || !reply.receipt_challenge) return undefined;
pendingReceiptChallenge = reply.receipt_challenge;
pendingReceiptText = reply.receipt;
promotionAttempts += 1;
return reply.receipt;
} catch {
return undefined;
}
}
/** Complete promotion after the model emitted the receipt and message_end
* shipped it to the observer. Returns true when the lease reached VERIFIED. */
function completePiPromotion(): boolean {
const challenge = pendingReceiptChallenge;
if (!challenge) return false;
pendingReceiptChallenge = null;
pendingReceiptText = null;
const result = spawnSync('python3', [LEASE_PROMOTE, '--complete', challenge], {
encoding: 'utf8',
timeout: 10_000,
env: process.env,
});
if (result.status !== 0) return false;
try {
const reply = JSON.parse(String(result.stdout)) as { state?: string };
return reply.state === 'VERIFIED';
} catch {
return false;
}
}
function checkPiMutatorGate(toolName: string): { block: true; reason: string } | undefined { function checkPiMutatorGate(toolName: string): { block: true; reason: string } | undefined {
const result = spawnSync('python3', [MUTATOR_GATE, '--runtime', 'pi'], { const result = spawnSync('python3', [MUTATOR_GATE, '--runtime', 'pi'], {
input: `${JSON.stringify({ tool_name: toolName })}\n`, input: `${JSON.stringify({ tool_name: toolName })}\n`,
@@ -137,6 +213,29 @@ function checkPiMutatorGate(toolName: string): { block: true; reason: string } |
const detail = String(result.stderr ?? '') const detail = String(result.stderr ?? '')
.trim() .trim()
.split('\n')[0]; .split('\n')[0];
// Only an UNVERIFIED lease is promotable. Any other denial (GATE_UNAVAILABLE,
// STALE_GENERATION, LEASE_EXPIRED, ANCESTRY_MISMATCH) means something is wrong
// that a receipt cannot fix — minting there would thrash the broker, since
// begin_verification revokes before it mints.
if (detail.includes('MUTATOR_UNVERIFIED') && pendingReceiptChallenge === null) {
const receipt = beginPiPromotion();
if (receipt) {
return {
block: true,
reason:
`${detail}\n\n` +
'This session holds an UNVERIFIED lease, so mutators are denied. To ' +
'promote it, reply with the following text and NOTHING ELSE — no ' +
'preamble, no explanation, no code fence, no trailing text. It is ' +
'compared byte-for-byte, so any extra character fails:\n\n' +
`${receipt}\n\n` +
'Emit exactly that as your entire next message. The lease will then be ' +
'VERIFIED and you can retry this tool.',
};
}
}
return { return {
block: true, block: true,
reason: detail || 'BLOCKED: Mosaic mutator gate is unavailable or the lease is UNVERIFIED.', reason: detail || 'BLOCKED: Mosaic mutator gate is unavailable or the lease is UNVERIFIED.',
@@ -370,7 +469,29 @@ export default function register(pi: ExtensionAPI) {
// Pi records only a finalized assistant entry at message_end. It never uses // Pi records only a finalized assistant entry at message_end. It never uses
// after_provider_response, which occurs before stream consumption. // after_provider_response, which occurs before stream consumption.
pi.on('message_end', async (event) => { pi.on('message_end', async (event) => {
recordPiMessageEnd((event as unknown as { message?: unknown }).message); const message = (event as unknown as { message?: unknown }).message;
recordPiMessageEnd(message);
// Complete ONLY when the message just observed IS the receipt.
//
// message_end also fires for the message that CONTAINED the blocked tool
// call — i.e. one turn BEFORE the model emits the receipt. Completing there
// makes observe_receipt compare against the wrong text, fail, and burn the
// challenge before the model ever answers. Gating on an exact text match
// mirrors the broker's own hmac.compare_digest semantics and waits for the
// right turn.
//
// Order still matters within this handler: recordPiMessageEnd must have
// shipped the message to the observer before observe_receipt asks about it.
if (pendingReceiptChallenge !== null && pendingReceiptText !== null) {
if (assistantMessageText(message) === pendingReceiptText) {
if (completePiPromotion()) {
promotionAttempts = 0;
}
// On failure the challenge is cleared, so the next denied mutator mints
// a fresh one — bounded by MAX_PROMOTION_ATTEMPTS, after which the
// session simply stays UNVERIFIED rather than looping.
}
}
}); });
// The recovery custom tool is the only Pi invocation that maps to the // The recovery custom tool is the only Pi invocation that maps to the