Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

fix: count usable security replay samples before limiting (#1033)

Joshua France6917bbcd0552
diff --git a/src/sessions/postgres-session-store.ts b/src/sessions/postgres-session-store.ts
index d8c85427a..ab782efbd 100644
--- a/src/sessions/postgres-session-store.ts
+++ b/src/sessions/postgres-session-store.ts
@@ -962,29 +962,40 @@ export function createPostgresSessionStore(connectionString: string, opts: Store
},
async listScreenSamples(limit): Promise<ScreenSample[]> {
- const rows = await q(
- `SELECT r.id, r.session_id, r.scope_label, r.created_at, r.model, e.body AS prompt_body
- FROM session_llm_requests r JOIN llm_prompt_envelopes e ON e.hash = r.prompt_hash
- WHERE r.step = $1
- ORDER BY r.created_at DESC, r.id DESC
- LIMIT $2`,
- [SECURITY_SCREEN_STEP, Math.max(0, Math.trunc(limit))],
- );
- return rows.flatMap((r) => {
- const payload = screenPayloadFromEnvelope(JSON.parse(r.prompt_body as string));
- return payload
- ? [
- {
- id: r.id as string,
- sessionId: r.session_id as string,
- scopeLabel: r.scope_label as ScopeId,
- createdAt: Number(r.created_at),
- model: r.model as string,
- payload,
- },
- ]
- : [];
- });
+ const wanted = Math.max(0, Math.trunc(limit));
+ const pageSize = Math.max(wanted, 100);
+ const samples: ScreenSample[] = [];
+ let beforeAt: number | null = null;
+ let beforeId: string | null = null;
+ while (samples.length < wanted) {
+ const rows = await q(
+ `SELECT r.id, r.session_id, r.scope_label, r.created_at, r.model, e.body AS prompt_body
+ FROM session_llm_requests r JOIN llm_prompt_envelopes e ON e.hash = r.prompt_hash
+ WHERE r.step = $1
+ AND ($3::bigint IS NULL OR (r.created_at, r.id) < ($3::bigint, $4::text))
+ ORDER BY r.created_at DESC, r.id DESC
+ LIMIT $2`,
+ [SECURITY_SCREEN_STEP, pageSize, beforeAt, beforeId],
+ );
+ for (const r of rows) {
+ const payload = screenPayloadFromEnvelope(JSON.parse(r.prompt_body as string));
+ if (!payload) continue;
+ samples.push({
+ id: r.id as string,
+ sessionId: r.session_id as string,
+ scopeLabel: r.scope_label as ScopeId,
+ createdAt: Number(r.created_at),
+ model: r.model as string,
+ payload,
+ });
+ if (samples.length === wanted) return samples;
+ }
+ if (rows.length < pageSize) break;
+ const last = rows.at(-1)!;
+ beforeAt = Number(last.created_at);
+ beforeId = last.id as string;
+ }
+ return samples;
},
async addParticipant(sessionId, principalId, title, opts): Promise<void> {
diff --git a/test/postgres-store.test.ts b/test/postgres-store.test.ts
index 59a8901a0..8277b48fc 100644
--- a/test/postgres-store.test.ts
+++ b/test/postgres-store.test.ts
@@ -8,6 +8,7 @@ import {
createPostgresSessionStore,
rowToSession,
} from "../src/sessions/postgres-session-store.ts";
+import { SECURITY_SCREEN_STEP } from "../src/security/security-posture.ts";
import { createPostgresRunStore } from "../src/runs/postgres-run-store.ts";
import { scopeId, type Principal, type TurnResult } from "../src/types.ts";
import type { OrchestratorInput } from "../src/core/orchestrator.ts";
@@ -86,6 +87,78 @@ test("pg session store: a bare failed acquire means the session is gone, not a l
await s.releaseLease(reacquired.lease!);
});
+test("pg session store: replay windows count usable payloads, not metadata-only screens", { skip }, async () => {
+ let now = Date.now();
+ const store = createPostgresSessionStore(URL!, { now: () => now });
+ const scope = scopeId("personal", "screen-window");
+ const session = await store.getOrCreateByThread("screen-window", "dm", scope);
+ const record = (promptEnvelope: unknown, step = SECURITY_SCREEN_STEP) =>
+ store.recordLlmRequest(session.id, {
+ turnSeq: step === SECURITY_SCREEN_STEP ? null : 1,
+ step,
+ model: "screen-test",
+ scopeLabel: scope,
+ promptEnvelope,
+ usage: { input: 1, output: 2, cacheRead: 3, cacheWrite: 4, totalTokens: 10, costUsd: 0.01 },
+ });
+ const envelope = (content: unknown) => ({ messages: [{ role: "user", content }] });
+
+ const unusable = [
+ undefined,
+ null,
+ { system: "Claude configuration only" },
+ { threadStart: { model: "Codex" } },
+ { system: "OpenCode configuration without messages" },
+ { messages: [] },
+ { messages: { role: "user", content: "not an array" } },
+ { messages: [null] },
+ { messages: [{ role: "assistant", content: "not a user payload" }] },
+ { messages: [...envelope("one").messages, ...envelope("two").messages] },
+ envelope(42),
+ envelope(null),
+ envelope(["not string content"]),
+ envelope(""),
+ envelope(" \t\r\n\u00a0\u2003\ufeff "),
+ ];
+ for (const payload of unusable) await record(payload);
+ for (let i = 0; i < 205; i++) await record({ system: "metadata only" });
+ assert.deepEqual(await store.listScreenSamples(2), []);
+ now -= 2;
+ const oldest = await record(envelope(" older usable payload "));
+ now++;
+ const newest = await record(envelope("newer usable payload"));
+ now += 2;
+ await record(envelope("ordinary turn, not a screening"), 0);
+ const before = await store.listLlmRequests(session.id);
+
+ assert.deepEqual(
+ (await store.listScreenSamples(2)).map((sample) => sample.id),
+ [newest.id, oldest.id],
+ );
+ assert.deepEqual(
+ (await store.listScreenSamples(1)).map((sample) => sample.id),
+ [newest.id],
+ );
+ assert.deepEqual(
+ (await store.listScreenSamples(1000)).map((sample) => sample.payload),
+ ["newer usable payload", "older usable payload"],
+ );
+ assert.deepEqual(await store.listScreenSamples(0), []);
+ assert.deepEqual(await store.listScreenSamples(-1), []);
+ assert.equal((await store.listScreenSamples(1.9)).length, 1);
+ assert.deepEqual(await store.listLlmRequests(session.id), before);
+ assert.equal(before.length, unusable.length + 208);
+
+ const tied = [await record(envelope("tied A")), await record(envelope("tied B"))];
+ assert.deepEqual(
+ (await store.listScreenSamples(2)).map((sample) => sample.id),
+ tied
+ .map((row) => row.id)
+ .sort()
+ .reverse(),
+ );
+});
+
test("pg session store: one-per-thread, TTL/fenced lease, monotonic log, visibility window", { skip }, async () => {
let now = Date.now();
const s = createPostgresSessionStore(URL!, { leaseTtlMs: 50, now: () => now });