Multiplayer agent harness for work.
Copy legacy tape step metadata into side tables before the tape is dropped (#2280)
Regan Bellcf0e475f50c0
diff --git a/package.json b/package.jsonindex add10677c..4d316dd55 100644--- a/package.json+++ b/package.json@@ -48,7 +48,7 @@"sandbox:local:build": "bash scripts/local-sandbox-build.sh","sandbox:porter:build": "docker build --platform linux/amd64 -t \"${PORTER_SANDBOX_IMAGE:?Set PORTER_SANDBOX_IMAGE to the registry tag to publish}\" porter && docker push \"$PORTER_SANDBOX_IMAGE\"","deploy:porter-runner-image": "docker build --platform linux/amd64 -t \"${PORTER_DEPLOY_RUNNER_IMAGE:?Set PORTER_DEPLOY_RUNNER_IMAGE to the registry tag to publish}\" -f deploy/porter-runner/Dockerfile . && docker push \"$PORTER_DEPLOY_RUNNER_IMAGE\"",- "test:pg": "node scripts/run-pg-tests.mjs test/batch-paths.test.ts test/session-append-many.test.ts test/cron-queue.test.ts test/postgres-migration-startup.test.ts test/postgres-swarms.test.ts test/postgres-store.test.ts test/postgres-tapeless-store.test.ts test/semantic-memory-pg.test.ts test/postgres-instance-registry.test.ts test/readiness.test.ts test/postgres-grant-store.test.ts test/postgres-acl-file-id-migration.test.ts test/postgres-admin-grants.test.ts test/postgres-teams.test.ts test/postgres-file-artifact-store.test.ts test/postgres-file-upload-store.test.ts test/postgres-directory-store.test.ts test/postgres-linked-identity-membership.test.ts test/postgres-map.test.ts test/postgres-background-ownership.test.ts test/postgres-resource-search.test.ts test/deploy-store-pg.test.ts test/postgres-cron-fires.test.ts test/postgres-cron-run-as-migration.test.ts test/postgres-legacy-harness-migration.test.ts test/postgres-migration-adoption.test.ts test/postgres-migrations.test.ts test/postgres-metrics-sink.test.ts test/postgres-error-log.test.ts test/postgres-audit-log.test.ts test/postgres-app-page-views.test.ts test/postgres-budget.test.ts test/postgres-rate-limiter.test.ts test/postgres-credential-usage-sink.test.ts test/postgres-config-store.test.ts test/postgres-delivery-store.test.ts test/postgres-replay-dedupe.test.ts test/postgres-broker-sessions.test.ts test/postgres-egress-audit-sink.test.ts test/postgres-memory-service.test.ts test/run-signal-store.test.ts test/postgres-listener.test.ts test/postgres-run-activity-store.test.ts test/leader-lease.test.ts test/advisory-lock.test.ts test/loop-ingress-pg.test.ts test/persistence-init-retry.test.ts test/migrate-principals.test.ts test/postgres-surface-cache.test.ts test/slack-mirror-fidelity.test.ts test/run-retry-delay.test.ts test/postgres-run-stream.test.ts test/migrate-main.test.ts",+ "test:pg": "node scripts/run-pg-tests.mjs test/batch-paths.test.ts test/session-append-many.test.ts test/cron-queue.test.ts test/postgres-migration-startup.test.ts test/postgres-swarms.test.ts test/postgres-store.test.ts test/postgres-tapeless-store.test.ts test/postgres-legacy-tape-steps.test.ts test/semantic-memory-pg.test.ts test/postgres-instance-registry.test.ts test/readiness.test.ts test/postgres-grant-store.test.ts test/postgres-acl-file-id-migration.test.ts test/postgres-admin-grants.test.ts test/postgres-teams.test.ts test/postgres-file-artifact-store.test.ts test/postgres-file-upload-store.test.ts test/postgres-directory-store.test.ts test/postgres-linked-identity-membership.test.ts test/postgres-map.test.ts test/postgres-background-ownership.test.ts test/postgres-resource-search.test.ts test/deploy-store-pg.test.ts test/postgres-cron-fires.test.ts test/postgres-cron-run-as-migration.test.ts test/postgres-legacy-harness-migration.test.ts test/postgres-migration-adoption.test.ts test/postgres-migrations.test.ts test/postgres-metrics-sink.test.ts test/postgres-error-log.test.ts test/postgres-audit-log.test.ts test/postgres-app-page-views.test.ts test/postgres-budget.test.ts test/postgres-rate-limiter.test.ts test/postgres-credential-usage-sink.test.ts test/postgres-config-store.test.ts test/postgres-delivery-store.test.ts test/postgres-replay-dedupe.test.ts test/postgres-broker-sessions.test.ts test/postgres-egress-audit-sink.test.ts test/postgres-memory-service.test.ts test/run-signal-store.test.ts test/postgres-listener.test.ts test/postgres-run-activity-store.test.ts test/leader-lease.test.ts test/advisory-lock.test.ts test/loop-ingress-pg.test.ts test/persistence-init-retry.test.ts test/migrate-principals.test.ts test/postgres-surface-cache.test.ts test/slack-mirror-fidelity.test.ts test/run-retry-delay.test.ts test/postgres-run-stream.test.ts test/migrate-main.test.ts","livetest": "node scripts/api-livetest.ts","bench:memory": "node --env-file-if-exists=.env scripts/memory-bench.ts","prepare": "node .husky/install.mjs",diff --git a/src/sessions/legacy-tape-steps.ts b/src/sessions/legacy-tape-steps.tsnew file mode 100644index 000000000..f5a3d93dd--- /dev/null+++ b/src/sessions/legacy-tape-steps.ts@@ -0,0 +1,185 @@+export const LEGACY_TAPE_STEPS_SQL = [+ `CREATE TABLE IF NOT EXISTS legacy_tape_steps(+ session_id TEXT NOT NULL,+ seq INT NOT NULL,+ step JSONB NOT NULL,+ wire JSONB,+ PRIMARY KEY (session_id, seq)+ )`,+ `CREATE TABLE IF NOT EXISTS legacy_turn_runs(+ session_id TEXT NOT NULL,+ seq INT NOT NULL,+ run_id TEXT NOT NULL,+ inferred BOOLEAN NOT NULL,+ PRIMARY KEY (session_id, seq)+ )`,+ `CREATE TABLE IF NOT EXISTS legacy_tape_steps_progress(+ singleton BOOLEAN PRIMARY KEY DEFAULT true CHECK (singleton),+ started_at BIGINT,+ last_session TEXT,+ done BOOLEAN NOT NULL DEFAULT false,+ invalid_messages BIGINT NOT NULL DEFAULT 0,+ keyed_blocks BIGINT NOT NULL DEFAULT 0,+ copied_steps BIGINT NOT NULL DEFAULT 0,+ copied_turns BIGINT NOT NULL DEFAULT 0+ )`,+ `INSERT INTO legacy_tape_steps_progress DEFAULT VALUES ON CONFLICT (singleton) DO NOTHING`,+ `CREATE TABLE IF NOT EXISTS legacy_tape_writes(at BIGINT NOT NULL)`,+ `CREATE OR REPLACE FUNCTION legacy_tape_written() RETURNS trigger LANGUAGE plpgsql AS $written$+BEGIN+ INSERT INTO legacy_tape_writes VALUES ((EXTRACT(EPOCH FROM clock_timestamp()) * 1000)::bigint);+ RETURN NULL;+END $written$`,+ `CREATE OR REPLACE PROCEDURE prepare_legacy_tape_steps(batch INT DEFAULT 50)+LANGUAGE plpgsql AS $prepare$+DECLARE+ ids TEXT[];+ frozen_at BIGINT;+ n_invalid BIGINT;+ n_keyed BIGINT;+ n_steps BIGINT;+ n_turns BIGINT;+BEGIN+ IF NOT pg_try_advisory_lock(hashtext('prepare_legacy_tape_steps')) THEN+ RAISE EXCEPTION 'prepare_legacy_tape_steps() is already running in another session';+ END IF;+ IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = 'legacy_tape_frozen' AND tgrelid = 'session_tape'::regclass) THEN+ IF EXISTS (SELECT 1 FROM legacy_tape_steps_progress WHERE started_at IS NOT NULL OR last_session IS NOT NULL OR done) THEN+ RAISE EXCEPTION 'legacy_tape_frozen is gone but a preparation already started: reset legacy_tape_steps_progress, legacy_tape_steps, legacy_turn_runs and legacy_tape_writes before starting again';+ END IF;+ PERFORM set_config('lock_timeout', '5s', true);+ CREATE TRIGGER legacy_tape_frozen AFTER INSERT OR UPDATE OR DELETE OR TRUNCATE ON session_tape+ FOR EACH STATEMENT EXECUTE FUNCTION legacy_tape_written();+ ALTER TABLE session_tape ENABLE ALWAYS TRIGGER legacy_tape_frozen;+ UPDATE legacy_tape_steps_progress SET started_at = (EXTRACT(EPOCH FROM clock_timestamp()) * 1000)::bigint;+ COMMIT;+ END IF;+ SELECT started_at INTO frozen_at FROM legacy_tape_steps_progress;+ IF to_regclass('legacy_prep_runs') IS NULL THEN+ CREATE TABLE legacy_prep_runs(+ id TEXT, session_id TEXT, turn_user_seq BIGINT, started_at BIGINT, finished_at BIGINT, prev_max_finished BIGINT+ );+ IF to_regclass('runs') IS NOT NULL THEN+ INSERT INTO legacy_prep_runs+ SELECT r.id, s.id, r.turn_user_seq, r.started_at, r.finished_at,+ max(COALESCE(r.finished_at, 9223372036854775807)) OVER (+ PARTITION BY s.id ORDER BY r.started_at, r.id ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)+ FROM runs r JOIN sessions s ON s.thread_ref = r.session_id+ WHERE r.started_at IS NOT NULL;+ END IF;+ CREATE INDEX legacy_prep_runs_by_seq ON legacy_prep_runs(session_id, turn_user_seq);+ CREATE INDEX legacy_prep_runs_by_start ON legacy_prep_runs(session_id, started_at DESC, id DESC);+ COMMIT;+ END IF;+ LOOP+ SELECT array_agg(id ORDER BY id) INTO ids+ FROM (SELECT id FROM sessions+ WHERE id > COALESCE((SELECT last_session FROM legacy_tape_steps_progress), '')+ ORDER BY id LIMIT batch) next_sessions;+ EXIT WHEN ids IS NULL;+ PERFORM set_config('enable_nestloop', 'off', true);+ CREATE TEMP TABLE legacy_batch_blocks ON COMMIT DROP AS+ WITH messages AS MATERIALIZED (+ SELECT t.session_id, t.seq, t.created_at, v.valid, m.*+ FROM session_tape t+ CROSS JOIN LATERAL (+ SELECT pg_input_is_valid(t.payload, 'jsonb') AND left(btrim(t.payload), 1) = '{' AS valid OFFSET 0+ ) v+ CROSS JOIN LATERAL (+ SELECT r.* FROM json_to_record(CASE WHEN v.valid THEN t.payload::json END)+ AS r(role TEXT, api TEXT, provider TEXT, model TEXT, "stopReason" TEXT, content JSON)+ OFFSET 0+ ) m+ WHERE t.session_id = ANY(ids) AND t.kind = 'message' AND COALESCE(t.harness, 'pi') = 'pi'+ AND (NOT v.valid OR m.role = 'assistant')+ )+ SELECT m.session_id, m.seq AS tape_seq, m.created_at, m.valid, m.api, m.provider, m.model,+ m."stopReason" AS stop_reason, b.blk, (b.ord - 1)::int AS idx,+ CASE b.blk ->> 'type'+ WHEN 'toolCall' THEN 'call:' || (b.blk ->> 'id')+ WHEN 'thinking' THEN CASE WHEN COALESCE(b.blk ->> 'thinkingSignature', '') <> ''+ THEN 'sig:' || (b.blk ->> 'thinkingSignature') END+ WHEN 'text' THEN 'text:' || (b.blk ->> 'text')+ END AS key+ FROM messages m+ LEFT JOIN LATERAL json_array_elements(+ CASE WHEN json_typeof(m.content) = 'array' THEN m.content ELSE '[]'::json END+ ) WITH ORDINALITY AS b(blk, ord) ON true;+ SELECT count(*) FILTER (WHERE NOT valid), count(*) FILTER (WHERE key IS NOT NULL)+ INTO n_invalid, n_keyed FROM legacy_batch_blocks;+ WITH tape_unique AS (+ SELECT b.* FROM legacy_batch_blocks b+ JOIN (SELECT session_id, key FROM legacy_batch_blocks WHERE key IS NOT NULL+ GROUP BY session_id, key HAVING count(*) = 1) u USING (session_id, key)+ ), entries AS (+ SELECT e.session_id, e.seq, e.type, e.created_at, p.j,+ CASE WHEN e.type = 'tool_call' THEN 'call:' || (p.j ->> 'callId')+ WHEN e.type = 'thinking' THEN 'sig:' || (p.j ->> 'thinkingSignature')+ ELSE 'text:' || (p.j ->> 'text') END AS key+ FROM session_entries e+ CROSS JOIN LATERAL (SELECT CASE WHEN pg_input_is_valid(e.payload, 'jsonb') THEN e.payload::jsonb END AS j) p+ WHERE e.session_id = ANY(ids)+ AND e.type IN ('tool_call', 'thinking', 'text', 'assistant') AND e.created_at < frozen_at+ AND jsonb_typeof(p.j) = 'object' AND NOT p.j ? 'step'+ ), entries_unique AS (+ SELECT x.* FROM entries x+ JOIN (SELECT session_id, key FROM entries WHERE key IS NOT NULL+ GROUP BY session_id, key HAVING count(*) = 1) u USING (session_id, key)+ )+ INSERT INTO legacy_tape_steps(session_id, seq, step, wire)+ SELECT e.session_id, e.seq,+ jsonb_strip_nulls(jsonb_build_object('id', 'tape:' || t.tape_seq, 'api', t.api, 'provider', t.provider,+ 'model', t.model, 'stopReason', t.stop_reason, 'index', t.idx)),+ NULLIF(+ COALESCE((SELECT jsonb_object_agg(f.key, f.value::jsonb) FROM json_each(t.blk) f+ WHERE f.key <> ALL (CASE t.blk ->> 'type'+ WHEN 'toolCall' THEN ARRAY['type', 'id', 'name', 'arguments']+ WHEN 'thinking' THEN ARRAY['type', 'thinking', 'thinkingSignature']+ ELSE ARRAY['type', 'text'] END)), '{}'::jsonb)+ || CASE WHEN e.type = 'tool_call' THEN+ jsonb_build_object('argumentsJson', COALESCE((t.blk -> 'arguments')::text, '{}'))+ || CASE WHEN (t.blk ->> 'name') IS DISTINCT FROM (e.j ->> 'tool')+ THEN jsonb_build_object('name', t.blk ->> 'name') ELSE '{}'::jsonb END+ ELSE '{}'::jsonb END,+ '{}'::jsonb)+ FROM entries_unique e+ JOIN tape_unique t USING (session_id, key)+ WHERE e.key NOT LIKE 'text:%' OR abs(e.created_at - t.created_at) <= 600000+ ON CONFLICT (session_id, seq) DO NOTHING;+ GET DIAGNOSTICS n_steps = ROW_COUNT;+ PERFORM set_config('enable_nestloop', 'on', true);+ INSERT INTO legacy_turn_runs(session_id, seq, run_id, inferred)+ SELECT e.session_id, e.seq, COALESCE(by_seq.id, by_window.id), by_seq.id IS NULL+ FROM session_entries e+ CROSS JOIN LATERAL (SELECT CASE WHEN pg_input_is_valid(e.payload, 'jsonb') THEN e.payload::jsonb END AS j) p+ LEFT JOIN LATERAL (+ SELECT CASE WHEN count(*) = 1 THEN min(r.id) END AS id FROM legacy_prep_runs r+ WHERE r.session_id = e.session_id AND r.turn_user_seq = e.seq+ ) by_seq ON true+ LEFT JOIN LATERAL (+ SELECT latest.id FROM (+ SELECT r.id, r.turn_user_seq, r.finished_at, r.prev_max_finished FROM legacy_prep_runs r+ WHERE r.session_id = e.session_id AND r.started_at <= e.created_at+ ORDER BY r.started_at DESC, r.id DESC LIMIT 1+ ) latest+ WHERE latest.turn_user_seq IS NULL AND e.created_at <= latest.finished_at+ AND COALESCE(latest.prev_max_finished, -1) < e.created_at+ ) by_window ON true+ WHERE e.session_id = ANY(ids) AND e.type = 'user' AND e.created_at < frozen_at AND jsonb_typeof(p.j) = 'object'+ AND NOT p.j @> '{"steered":true}' AND NOT p.j @> '{"overheard":true}'+ AND NOT COALESCE(jsonb_typeof(p.j -> 'runId') = 'string' AND p.j ->> 'runId' <> '', false)+ AND COALESCE(by_seq.id, by_window.id) IS NOT NULL+ ON CONFLICT (session_id, seq) DO NOTHING;+ GET DIAGNOSTICS n_turns = ROW_COUNT;+ UPDATE legacy_tape_steps_progress+ SET last_session = ids[array_length(ids, 1)],+ invalid_messages = invalid_messages + n_invalid, keyed_blocks = keyed_blocks + n_keyed,+ copied_steps = copied_steps + n_steps, copied_turns = copied_turns + n_turns;+ COMMIT;+ END LOOP;+ DROP TABLE legacy_prep_runs;+ UPDATE legacy_tape_steps_progress SET done = true;+ COMMIT;+ PERFORM pg_advisory_unlock(hashtext('prepare_legacy_tape_steps'));+END $prepare$`,+];diff --git a/src/sessions/postgres-session-store.ts b/src/sessions/postgres-session-store.tsindex 31eff8266..43c9105ee 100644--- a/src/sessions/postgres-session-store.ts+++ b/src/sessions/postgres-session-store.ts@@ -39,6 +39,7 @@ import type {StoreOptions,} from "./session-store.ts";import { tsPrefixQuery } from "./entry-search.ts";+import { LEGACY_TAPE_STEPS_SQL } from "./legacy-tape-steps.ts";import {cronIdOf,legacyOriginPattern,@@ -803,6 +804,10 @@ export function createPostgresSessionStore(connectionString: string, opts: Storeid: "sessions/store/0028-drop-run-tasks",statements: [`DROP TABLE IF EXISTS task_events`, `DROP TABLE IF EXISTS tasks`],},+ {+ id: "sessions/store/0029-legacy-tape-steps",+ statements: LEGACY_TAPE_STEPS_SQL,+ },],[{diff --git a/test/postgres-legacy-tape-steps.test.ts b/test/postgres-legacy-tape-steps.test.tsnew file mode 100644index 000000000..0e5282de2--- /dev/null+++ b/test/postgres-legacy-tape-steps.test.ts@@ -0,0 +1,205 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { randomUUID } from "node:crypto";+import { applyPgMigrations, registeredPgMigrations } from "../src/persistence/pg-pool.ts";+import { createPostgresSessionStore } from "../src/sessions/postgres-session-store.ts";+import { createPostgresRunStore } from "../src/runs/postgres-run-store.ts";+import { scopeId } from "../src/types.ts";++const URL = process.env.DATABASE_URL;+const skip = URL ? false : "set DATABASE_URL (a Postgres) to run the legacy tape steps test";++async function withSchema(fn: (raw: import("pg").Pool) => Promise<void>): Promise<void> {+ const pg = (await import("pg")).default;+ const admin = new pg.Pool({ connectionString: URL });+ const schema = `tape_steps_${randomUUID().replaceAll("-", "")}`;+ await admin.query(`CREATE SCHEMA ${schema}`);+ const url = new globalThis.URL(URL!);+ url.searchParams.set("options", `-c search_path=${schema}`);+ const raw = new pg.Pool({ connectionString: url.toString() });+ try {+ createPostgresSessionStore(url.toString());+ createPostgresRunStore(url.toString());+ await applyPgMigrations(raw, registeredPgMigrations(url.toString()));+ await fn(raw);+ } finally {+ await raw.end();+ await admin.query(`DROP SCHEMA ${schema} CASCADE`);+ await admin.end();+ }+}++const scope = scopeId("personal", "alice");+const message = (content: unknown[]) =>+ `{"role":"assistant","content":${JSON.stringify(content)},"api":"anthropic-messages","provider":"anthropic","model":"claude-opus-5-5","stopReason":"toolUse"}`;++async function seedSession(+ raw: import("pg").Pool,+ id: string,+ tape: string[],+ entries: Array<[string, unknown, number?]>,+) {+ await raw.query("INSERT INTO sessions(id, type, scope_id, thread_ref, created_at) VALUES ($1, 'dm', $2, $3, 1)", [+ id,+ scope,+ `web:${id}`,+ ]);+ for (const [seq, payload] of tape.entries())+ await raw.query(+ "INSERT INTO session_tape(session_id, seq, kind, harness, payload, scope_label, created_at) VALUES ($1, $2, 'message', 'pi', $3, $4, 1)",+ [id, seq, payload, scope],+ );+ for (const [seq, [type, payload, createdAt]] of entries.entries())+ await raw.query(+ "INSERT INTO session_entries(session_id, seq, parent_seq, type, payload, scope_label, created_at) VALUES ($1, $2, NULL, $3, $4, $5, $6)",+ [id, seq, type, JSON.stringify(payload), scope, createdAt ?? seq * 100],+ );+}++const addRuns = (raw: import("pg").Pool, rows: Array<[string, string, number | null, number, number | null]>) =>+ Promise.all(+ rows.map(([id, session, turnUserSeq, startedAt, finishedAt]) =>+ raw.query(+ "INSERT INTO runs(id, session_id, status, request, created_at, turn_user_seq, started_at, finished_at) VALUES ($1, $2, 'done', '{}', 1, $3, $4, $5)",+ [id, `web:${session}`, turnUserSeq, startedAt, finishedAt],+ ),+ ),+ );++const progress = async (raw: import("pg").Pool) =>+ (+ await raw.query(+ "SELECT last_session, done, invalid_messages::int, keyed_blocks::int, copied_steps::int, copied_turns::int FROM legacy_tape_steps_progress",+ )+ ).rows[0];++test("pg legacy tape steps keep each step's model and exact block wire, and map turns to runs", { skip }, async () => {+ await withSchema(async (raw) => {+ await seedSession(+ raw,+ "legacy",+ [+ message([+ { type: "thinking", thinking: "plan", thinkingSignature: "sig-1" },+ { type: "text", text: "Checking.", textSignature: "t-sig" },+ { type: "toolCall", id: "c1", name: "execute", arguments: { z: 1, a: { b: 2 } }, thoughtSignature: "ts" },+ ]),+ message([+ { type: "text", text: "Same" },+ { type: "text", text: "Same" },+ ]),+ '{"role":"assistant","content":[{"type":"text","text":"bad \\ud800"}]}',+ message([{ type: "text", text: "Done." }]),+ "null",+ "[]",+ ],+ [+ ["thinking", { thinking: "plan", thinkingSignature: "sig-1" }],+ ["assistant", { text: "Checking." }],+ ["tool_call", { tool: "execute", callId: "c1", a: { b: 2 }, z: 1 }],+ ["assistant", { text: "Same" }],+ ["tool_call", { tool: "execute", callId: "c9", x: 1 }],+ ["user", { text: "first turn" }],+ ["assistant", { text: "first reply" }],+ ["user", { text: "second turn" }],+ ["assistant", { text: "second reply" }],+ ["user", { text: "third turn", runId: "run-c" }],+ ["assistant", { text: "Checking.", step: { id: "s" } }],+ ["user", { text: "during an unfinished run" }],+ ["user", { text: "after the freeze" }, Number.MAX_SAFE_INTEGER],+ ["assistant", { text: "Done." }, 1300],+ ["user", { text: "inside a run that already has its turn" }, 600],+ ["user", { text: "inside a finished run while another is open" }, 1250],+ ],+ );+ await seedSession(raw, "tapeless", [], [["user", { text: "hi" }]]);+ await addRuns(raw, [+ ["run-a", "legacy", 5, 450, 650],+ ["run-b", "legacy", null, 650, 900],+ ["run-open", "legacy", null, 1050, null],+ ["run-late", "legacy", null, 1500, Number.MAX_SAFE_INTEGER],+ ["run-inner", "legacy", null, 1200, 1400],+ ]);+ await raw.query("UPDATE session_tape SET created_at = 10000000 WHERE session_id = 'legacy' AND seq = 3");++ await raw.query("CALL prepare_legacy_tape_steps(1)");++ const step = (index: number) => ({+ id: "tape:0",+ api: "anthropic-messages",+ provider: "anthropic",+ model: "claude-opus-5-5",+ stopReason: "toolUse",+ index,+ });+ assert.deepEqual(+ (await raw.query("SELECT session_id, seq, step, wire FROM legacy_tape_steps ORDER BY session_id, seq")).rows,+ [+ { session_id: "legacy", seq: 0, step: step(0), wire: null },+ { session_id: "legacy", seq: 1, step: step(1), wire: { textSignature: "t-sig" } },+ {+ session_id: "legacy",+ seq: 2,+ step: step(2),+ wire: { argumentsJson: '{"z":1,"a":{"b":2}}', thoughtSignature: "ts" },+ },+ ],+ );+ assert.deepEqual(+ (await raw.query("SELECT session_id, seq, run_id, inferred FROM legacy_turn_runs ORDER BY session_id, seq")).rows,+ [+ { session_id: "legacy", seq: 5, run_id: "run-a", inferred: false },+ { session_id: "legacy", seq: 7, run_id: "run-b", inferred: true },+ ],+ );+ assert.deepEqual(await progress(raw), {+ last_session: "tapeless",+ done: true,+ invalid_messages: 3,+ keyed_blocks: 6,+ copied_steps: 3,+ copied_turns: 2,+ });+ assert.equal((await raw.query("SELECT to_regclass('legacy_prep_runs') AS t")).rows[0].t, null);+ assert.equal((await raw.query("SELECT count(*)::int AS n FROM legacy_tape_writes")).rows[0].n, 0);+ });+});++test(+ "pg legacy tape step preparation resumes from its cursor and records every later tape write",+ { skip },+ async () => {+ await withSchema(async (raw) => {+ for (const id of ["s1", "s2", "s3"])+ await seedSession(+ raw,+ id,+ [message([{ type: "toolCall", id: `call-${id}`, name: "execute", arguments: { id } }])],+ [["tool_call", { tool: "execute", callId: `call-${id}`, id }]],+ );+ await raw.query("CALL prepare_legacy_tape_steps(1)");+ await raw.query("UPDATE legacy_tape_steps_progress SET last_session = 's1', done = false");+ await raw.query("DELETE FROM legacy_tape_steps WHERE session_id <> 's1'");++ await raw.query("CALL prepare_legacy_tape_steps(1)");++ assert.deepEqual(+ (await raw.query("SELECT session_id FROM legacy_tape_steps ORDER BY session_id")).rows.map((r) => r.session_id),+ ["s1", "s2", "s3"],+ );+ await raw.query("DELETE FROM session_tape WHERE session_id = 'none'");+ const client = await raw.connect();+ try {+ await client.query("SET session_replication_role = replica");+ await client.query("UPDATE session_tape SET harness = 'pi' WHERE session_id = 's1'");+ } finally {+ await client.query("RESET session_replication_role");+ client.release();+ }+ assert.equal((await raw.query("SELECT count(*)::int AS n FROM legacy_tape_writes")).rows[0].n, 2);++ await raw.query("DROP TRIGGER legacy_tape_frozen ON session_tape");+ await assert.rejects(raw.query("CALL prepare_legacy_tape_steps(1)"), /a preparation already started/);+ });+ },+);