An agent can hide an SSN in its final answer and still have received the full number in a tool result. By then, the value is already in the model's context and may be in the conversation trace. If the goal is to keep that value away from the model, the masking has to happen earlier.
That was the question I tested with Pi: could a producer supply useful test data without returning full customer identifiers to its model or the receiving agent? The project uses synthetic banking data with realistic formats. The code and captured run are available alongside the project demonstration.
The boundary is inside the tool
The producer's query tool applies the transformation before returning its result:
const { rows } = await dbPool().query(sql, args);
const masked = rows.map((row) => maskRow(params.entity as Entity, row));The SQL process necessarily handles the source values. The model-facing result contains the transformed rows. That order is the central design decision: query, mask, return. Redacting the final answer would leave the original tool result in the conversation and potentially in traces.
The second control limits the producer's available actions. Its tool-call hook refuses tools outside this list:
const PRODUCER_TOOLS = ["mailbox_wait", "mailbox_send", "query_masked"];
pi.on("tool_call", async (event) => {
if (!PRODUCER_TOOLS.includes(event.toolName)) {
return { block: true, reason: "Tool unavailable to the producer." };
}
});This abbreviated excerpt shows the enforcement point. Blocking the harness's filesystem and shell tools prevents the model from choosing those routes around query_masked. The database role, process environment, extension code, and logging still belong in the review. A tool allowlist is a control within this harness; it is not an operating-system sandbox.
Two roles, three databases
fintechP holds the source tables: customers, addresses, accounts, cards, and transactions. fintechT has the destination schema. A third database, bus, contains mq.messages, the mailbox between producer and consumer. Keeping the roles separate gives the consumer a way to request rows without receiving production credentials.
The same bank-db extension registers different tools according to PI_DB_ROLE. The producer gets query_masked. The consumer gets operations for inserting rows, querying its local database, and inspecting watermarks. The mailbox extension supplies the request and response channel.
A consumer requests an entity and a bounded batch. The producer queries that entity, masks the result, and sends the transformed rows. The destination loads parent records before their dependents: customers before addresses and accounts, then cards and transactions. A successful transfer needs both privacy controls and ordinary relational integrity. Masking a card number does not fix a missing account foreign key.
What the masking function preserves
pi/lib/mask.ts is a pure module. It takes an entity and a row, returns a new row, and makes no model, network, or database call. That makes individual transformations easy to test without running either agent.
| Field | Transformation |
|---|---|
| Last name | Keep the first letter |
| SSN | Keep the last four digits |
| Keep the first character and domain | |
| Birth date | Keep the year, set month and day to January 1 |
| Street address | Replace street text; retain coarse location fields |
| Account and routing numbers | Keep a masked suffix |
| Card number | Keep the first and last four digits |
| CVV | Replace with asterisks |
The date remains a valid DATE. It no longer supports an exact age calculation around someone's birthday. Similarly, a masked card string may fit a text column while failing a numeric-only or Luhn validator. Insert compatibility depends on the destination schema and constraints, not just the apparent shape of a value.
The less obvious risk is in how the masking function builds its result. It copies the input row with ...r, then overrides selected fields. Anything it doesn't recognize stays in the output.
There is already one protection against accidental schema growth: the query selects named columns from schema.ts, rather than using SELECT *. Adding a column to the database alone won't expose it through this tool. But imagine adding a tax_identifier column to that selected list and forgetting to update the masker. The row spread would carry it straight through. This is a hypothetical schema change, and the model-free test already demonstrates the underlying behavior with an unexpected field.
I would make the output policy explicit too: every returned field should have a deliberate keep, transform, or omit decision. That gives a schema review a concrete question to answer before a new field reaches the model.
Transactions pass through, and several useful attributes remain visible elsewhere. Those records can still carry sensitive information or support linkage with another dataset. Partial names, locations, dates, identifiers, and spending patterns do not become anonymous because an SSN is obscured. This is selective masking for a controlled test-data workflow, with residual exposure that depends on the receiving environment.
Masking and delivery solve different problems
The mailbox uses PostgreSQL row locking with FOR UPDATE SKIP LOCKED. A consumer can claim an available message while another worker skips that locked row. This is a useful queue primitive because workers do not all block on the same oldest message.
In this implementation, mailbox_wait marks the message consumed and commits before returning it. If the consumer crashes before loading those rows into fintechT, the message has already left the pending queue. Row locks coordinate claims; they don't make the claim and destination insert one transaction.
The insert tool does use ON CONFLICT (id) DO NOTHING, so retrying an existing ID won't create a duplicate row. That helps with replay, but it won't recover a consumed message or apply a changed value to an existing ID. Recovery still needs to account for partially loaded parent and child tables.
The source caps a response at 200 rows. Batching bounds an individual result and makes a run easier to inspect. It does not make unrestricted repeated requests harmless, so total access and logging still matter.
The incremental path uses a watermark: the largest local identifier per table. It asks for rows beyond that value. For an append-only sample with increasing IDs, that avoids retransmitting every record on each run. A simplified request sequence looks like this:
Read the destination maximum ID for customers
Request customers with ID greater than that value
Receive a masked batch
Insert the batch and repeat while more rows are availableAn update to an older customer will not move that customer's ID past the watermark. A deletion will not appear as a new row either. This approach is an incremental insert load, not general change data capture. A production synchronization design would need an update cursor, change log, or database replication mechanism with explicit deletion handling. It would also need to define what happens when rows become visible out of ID order.
What the captured checks establish
The saved run uses a Pi producer and an emulated consumer. It demonstrates the producer's tool boundary and transfer path; it is not a recording of two independent model agents. The replay makes the messages visible, and model-free tests exercise the shared masking functions separately.
One check searches mailbox bodies for unmasked values with familiar formats:
SELECT count(*) FROM mq.messages
WHERE body::text ~ '[0-9]{3}-[0-9]{2}-[0-9]{4}'
OR body::text ~ '[0-9]{16}';The recorded check reports zero matches. That means those patterns were not found in the checked messages. It does not prove that every sensitive value was absent: a formatted card number, an unexpected identifier, or a retained combination of attributes can escape those expressions. Raw source values should also be compared directly against outputs when testing a masking policy.
I want the tests to cover nulls, short values, malformed emails, unexpected columns, and every supported entity. The destination checks should establish row counts and relationships, while delivery tests should include interruption and retry. These are distinct failure modes. A green regex check cannot stand in for all of them.
The files I start with are mask.ts, bank-db.ts, and the mailbox extension. Together they show what the model can call, where rows change, and how those rows travel.
This experiment puts the masking decision in code before the tool result reaches the model. That is a useful boundary, and it leaves me with a concrete next improvement: explicitly approve the output columns, then test known source values against the actual tool outputs. A new field should require a privacy decision. It shouldn't inherit permission to leave just because someone added it to a query.
