chore: docs, dev scripts and CI catch up with orchestration V2 (#15041)

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
Theo BrowneandClaude Opus 5.5 authored and GitHub committed 2026-10-02 22:25:00 -07:00
1 parent c5a929e1ac
commit ddcd310282
29 files changed
+303 -415

No files matched your search

+66 -27
View File
@@ -14,24 +14,21 @@ const withDatabase = <A, E>(
effect: Effect.Effect<A, E, SqlClient.SqlClient>,
) => effect.pipe(Effect.provide(NodeSqliteClient.layer({ filename: databasePath })));
/** A migrated source db with one thread per lifecycle state. Only
* `stopped-thread` qualifies for the clone. */
/** A migrated source db with one V2 thread per lifecycle state. Only
* `stopped-thread` and its fork qualify for the clone. */
const createFixtureSource = Effect.fn("createMigrateDevDbFixtureSource")(function* (
baseDir: string,
) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const stateDir = path.join(baseDir, "userdata");
const databasePath = path.join(stateDir, "state.sqlite");
const databasePath = path.join(stateDir, "statev2.sqlite");
yield* fs.makeDirectory(stateDir, { recursive: true });
yield* withDatabase(
databasePath,
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* runMigrations();
// The real shared db carries this column from a branch build without a
// matching migration; reproduce that drift so the filter is exercised.
yield* sql`ALTER TABLE projection_threads ADD COLUMN monitor_json TEXT`;
yield* sql`INSERT INTO projection_projects
(project_id, title, workspace_root, scripts_json, created_at, updated_at, deleted_at)
@@ -39,23 +36,56 @@ const createFixtureSource = Effect.fn("createMigrateDevDbFixtureSource")(functio
('project-kept', 'Kept', '/tmp/kept', '[]', '2026-08-01', '2026-08-01', NULL),
('project-deleted', 'Deleted', '/tmp/deleted', '[]', '2026-08-01', '2026-08-02', '2026-08-02')`;
const forkPayload =
'{"lineage":{"parentThreadId":"stopped-thread","relationshipToParent":"fork","rootThreadId":"stopped-thread"}}';
const subagentPayload =
'{"lineage":{"parentThreadId":"subagent-parent","relationshipToParent":"subagent","rootThreadId":"subagent-parent"},"forkedFrom":{"type":"node","nodeId":"node-1"}}';
// Excluded threads are newer than the kept family, so only the filters
// can keep them out of a one-family-per-project clone.
const threads = [
["stopped-thread", "project-kept", "stopped", null, null],
["running-thread", "project-kept", "running", null, null],
["settled-thread", "project-kept", "stopped", "2026-08-01", null],
["monitored-thread", "project-kept", "stopped", null, '{"kind":"pr"}'],
["deleted-project-thread", "project-deleted", "stopped", null, null],
["stopped-thread", "project-kept", "completed", "{}", "2026-08-01"],
["fork-thread", "project-kept", "completed", forkPayload, "2026-08-02"],
["running-thread", "project-kept", "running", "{}", "2026-08-05"],
["settled-thread", "project-kept", "completed", '{"settledAt":"2026-08-01"}', "2026-08-05"],
[
"limit-thread",
"project-kept",
"completed",
'{"limitRecovery":{"autoResume":true}}',
"2026-08-05",
],
// Its result never reached the parent, so startup would deliver it.
["subagent-parent", "project-kept", "completed", "{}", "2026-08-05"],
["subagent-child", "project-kept", "completed", subagentPayload, "2026-08-05"],
["deleted-project-thread", "project-deleted", "completed", "{}", "2026-08-05"],
] as const;
for (const [threadId, projectId, status, settledAt, monitorJson] of threads) {
yield* sql`INSERT INTO projection_threads
(thread_id, project_id, title, created_at, updated_at, settled_at, monitor_json)
VALUES (${threadId}, ${projectId}, ${threadId}, '2026-08-01', '2026-08-01', ${settledAt}, ${monitorJson})`;
yield* sql`INSERT INTO projection_thread_sessions (thread_id, status, updated_at)
VALUES (${threadId}, ${status}, '2026-08-01')`;
for (const [threadId, projectId, runStatus, payload, updatedAt] of threads) {
yield* sql`INSERT INTO orchestration_v2_projection_threads
(thread_id, project_id, title, default_provider, runtime_mode, interaction_mode, created_at, updated_at, payload_json)
VALUES (${threadId}, ${projectId}, ${threadId}, 'codex', 'full-access', 'default', '2026-08-01', ${updatedAt}, ${payload})`;
yield* sql`INSERT INTO orchestration_v2_projection_runs
(run_id, thread_id, ordinal, provider, status, requested_at, payload_json)
VALUES (${`run-${threadId}`}, ${threadId}, 1, 'codex', ${runStatus}, '2026-08-01', '{}')`;
yield* sql`INSERT INTO orchestration_events
(event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at, actor_kind, payload_json, metadata_json)
VALUES (${`event-${threadId}`}, 'thread', ${threadId}, 0, 'thread.created', '2026-08-01', 'user', '{}', '{}')`;
}
// A provider session shared by two threads names its latest writer.
yield* sql`INSERT INTO orchestration_v2_projection_provider_sessions
(provider_session_id, thread_id, provider, status, updated_at, payload_json)
VALUES ('session-shared', 'running-thread', 'codex', 'stopped', '2026-08-01', '{}')`;
yield* sql`INSERT INTO orchestration_v2_projection_provider_session_bindings
(provider_session_id, thread_id)
VALUES ('session-shared', 'running-thread'), ('session-shared', 'stopped-thread')`;
yield* sql`INSERT INTO orchestration_v2_projection_context_transfers
(context_transfer_id, source_thread_id, target_thread_id, type, status, updated_at, payload_json)
VALUES ('transfer-1', 'settled-thread', 'stopped-thread', 'provider_handoff', 'completed', '2026-08-01', '{}')`;
yield* sql`INSERT INTO scheduled_tasks
(task_id, title, prompt, enabled, schedule_json, project_id, workspace_strategy_json,
model_selection_json, runtime_mode, interaction_mode, created_by, creation_source,
created_at, updated_at, last_run_status, run_count)
VALUES ('task-1', 'Nightly', 'Run it', 1, '{}', 'project-kept', '{}', '{}',
'full-access', 'default', 'user', 'user', '2026-08-01', '2026-08-01', 'never', 0)`;
yield* sql`INSERT INTO auth_sessions (session_id, subject, scopes, method, issued_at, expires_at)
VALUES ('session-1', 'user', '[]', 'pairing', '2026-08-01', '2027-08-01')`;
}),
@@ -64,7 +94,7 @@ const createFixtureSource = Effect.fn("createMigrateDevDbFixtureSource")(functio
});
it.layer(NodeServices.layer)("migrate-dev-db", (it) => {
it.effect("keeps only stopped threads from live projects and clears auth state", () =>
it.effect("keeps stopped thread families from live projects and clears pending work", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -73,7 +103,7 @@ it.layer(NodeServices.layer)("migrate-dev-db", (it) => {
const source = yield* createFixtureSource(sourceDir);
const result = yield* runMigrateDevDb(
{ baseDir: destDir, source, projects: 5, threadsPerProject: 10 },
{ baseDir: destDir, source, projects: 5, threadsPerProject: 1 },
{ sharedHome: sourceDir },
);
@@ -83,23 +113,32 @@ it.layer(NodeServices.layer)("migrate-dev-db", (it) => {
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const threads = yield* sql<{ thread_id: string }>`
SELECT thread_id FROM projection_threads ORDER BY thread_id`;
SELECT thread_id FROM orchestration_v2_projection_threads ORDER BY thread_id`;
const events = yield* sql<{ stream_id: string }>`
SELECT stream_id FROM orchestration_events`;
const [auth] = yield* sql<{ count: number }>`
SELECT COUNT(*) AS count FROM auth_sessions`;
return { threads, events, authCount: auth?.count ?? 0 };
SELECT stream_id FROM orchestration_events ORDER BY stream_id`;
const sessions = yield* sql<{ provider_session_id: string }>`
SELECT provider_session_id FROM orchestration_v2_projection_provider_sessions`;
const [leftovers] = yield* sql<{ auth: number; tasks: number; transfers: number }>`
SELECT
(SELECT COUNT(*) FROM auth_sessions) AS auth,
(SELECT COUNT(*) FROM scheduled_tasks) AS tasks,
(SELECT COUNT(*) FROM orchestration_v2_projection_context_transfers) AS transfers`;
return { threads, events, sessions, leftovers };
}),
);
assert.deepStrictEqual(
kept.threads.map((row) => row.thread_id),
["stopped-thread"],
["fork-thread", "stopped-thread"],
);
assert.deepStrictEqual(
kept.events.map((row) => row.stream_id),
["stopped-thread"],
["fork-thread", "stopped-thread"],
);
assert.equal(kept.authCount, 0);
assert.deepStrictEqual(
kept.sessions.map((row) => row.provider_session_id),
["session-shared"],
);
assert.deepStrictEqual(kept.leftovers, { auth: 0, tasks: 0, transfers: 0 });
}),
);
+107 -58
View File
@@ -6,10 +6,12 @@
*
* `vp run migrate-dev-db` from a worktree:
* 1. Nukes `<worktree>/.t3/userdata/statev2.sqlite`.
* 2. Snapshots the real db (read-only VACUUM INTO) and prunes it to the
* most recently updated projects and, per project, the most recent
* threads that have fully stopped. Working, settled, and monitored
* threads are skipped so the dev server never adopts live work.
* 2. Snapshots the real db (`~/.t3/userdata/statev2.sqlite`, read-only
* VACUUM INTO) and prunes it to the most recently updated projects and,
* per project, the most recent threads that have fully stopped, with
* their forks and subagents. Working, settled, and archived threads, and
* threads with pending recovery, are skipped, and scheduled tasks and
* queued effects are dropped, so the dev server never adopts live work.
* Auth sessions, pairing links, command receipts, and provider
* runtime rows are dropped — pair a fresh browser against dev.
* 3. Runs migrations on the result. Because the clone carries the real
@@ -19,9 +21,8 @@
* `Migrations/NNN_` id (the second one's CREATE TABLE is skipped).
*
* The event log (`orchestration_events`) is pruned per stream while
* `sqlite_sequence` and `projection_state` carry over untouched, so new
* events keep appending after the old high-water mark and projection
* cursors never rewind.
* `sqlite_sequence` and the projection cursors carry over untouched, so new events keep appending
* after the old high-water mark and projection cursors never rewind.
*/
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
@@ -31,12 +32,14 @@ import { resolveWorktreeT3Home } from "@t3tools/shared/devHome";
import * as Console from "effect/Console";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { Command, Flag } from "effect/unstable/cli";
import * as ProjectionStore from "../src/orchestration-v2/ProjectionStore.ts";
import { migrationManifest, runMigrations } from "../src/persistence/Migrations.ts";
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
@@ -143,7 +146,7 @@ export class MigrateDevDbPhaseError extends Schema.TaggedError<MigrateDevDbPhase
export interface RunMigrateDevDbInput {
/** Isolated .t3 directory. Defaults to `<worktree>/.t3` of the cwd. */
readonly baseDir?: string | undefined;
/** Source database. Defaults to `~/.t3/userdata/state.sqlite`. */
/** Source database. Defaults to `~/.t3/userdata/statev2.sqlite`. */
readonly source?: string | undefined;
readonly projects: number;
readonly threadsPerProject: number;
@@ -232,31 +235,56 @@ const ensureNotInUse = Effect.fn("ensureDevDbNotInUse")(function* (databasePath:
}
});
const RECOVERY_KINDS: ReadonlyArray<ProjectionStore.ProjectionRecoveryKind> = [
"queued-runs",
"runtime",
"subagent-results",
"delegated-completions",
];
const pruneSnapshot = Effect.fn("pruneDevDbSnapshot")(function* (input: RunMigrateDevDbInput) {
const sql = yield* SqlClient.SqlClient;
// The shared db can carry monitor_json from a branch build even though no
// migration in this checkout creates it, so filter it only when present.
const threadColumns = yield* sql<{ name: string }>`
SELECT name FROM pragma_table_info('projection_threads')`;
const monitorFilter = threadColumns.some((column) => column.name === "monitor_json")
? "AND t.monitor_json IS NULL"
: "";
// Threads the server would resume or start work on by itself. Its own
// recovery queries find most of them; usage-limit recovery also depends on
// settings, so any thread whose latest run failed or that has a recovery
// choice counts as live too.
const projections = yield* ProjectionStore.ProjectionStoreV2;
const recoveryThreadIds = yield* Effect.forEach(RECOVERY_KINDS, (kind) =>
projections.getRecoveryThreadIds(kind),
);
yield* sql`CREATE TEMP TABLE live_threads (thread_id TEXT PRIMARY KEY)`;
for (const threadId of new Set(recoveryThreadIds.flat())) {
yield* sql`INSERT INTO live_threads (thread_id) VALUES (${threadId})`;
}
yield* sql`INSERT OR IGNORE INTO live_threads (thread_id)
SELECT r.thread_id FROM orchestration_v2_projection_runs r
WHERE r.status = 'failed' AND r.ordinal = (
SELECT MAX(latest.ordinal) FROM orchestration_v2_projection_runs latest
WHERE latest.thread_id = r.thread_id)
UNION
SELECT thread_id FROM orchestration_v2_projection_threads
WHERE json_extract(payload_json, '$.limitRecovery') IS NOT NULL`;
// "Stopped" is the persisted subset of the UI's thread status: the session
// reached status 'stopped' and nothing marks the thread settled or
// monitored. The in-memory working/monitoring liveness never persists, so
// filtering the session status is sufficient.
yield* sql.unsafe(`CREATE TEMP TABLE stopped_threads AS
SELECT t.thread_id, t.project_id, t.updated_at
FROM projection_threads t
JOIN projection_thread_sessions s ON s.thread_id = t.thread_id
WHERE t.deleted_at IS NULL
AND t.archived_at IS NULL
AND t.settled_at IS NULL
AND (t.settled_override IS NULL OR t.settled_override <> 'settled')
${monitorFilter}
AND s.status = 'stopped'`).unprepared;
// Forks and subagents read history and results through their lineage, so
// a thread family is cloned or dropped as a whole. A family is stopped when
// its root is visible and unsettled and none of its threads is live.
yield* sql`CREATE TEMP TABLE thread_families AS
SELECT thread_id, updated_at,
COALESCE(json_extract(payload_json, '$.lineage.rootThreadId'), thread_id) AS root_id
FROM orchestration_v2_projection_threads`;
yield* sql`CREATE TEMP TABLE stopped_families AS
SELECT f.root_id, root.project_id, MAX(f.updated_at) AS updated_at
FROM thread_families f
JOIN orchestration_v2_projection_threads root ON root.thread_id = f.root_id
WHERE root.deleted_at IS NULL
AND json_extract(root.payload_json, '$.deletedAt') IS NULL
AND json_extract(root.payload_json, '$.archivedAt') IS NULL
AND json_extract(root.payload_json, '$.settledAt') IS NULL
AND json_extract(root.payload_json, '$.settledOverride') IS NOT 'settled'
GROUP BY f.root_id, root.project_id
HAVING SUM(f.thread_id IN (SELECT thread_id FROM live_threads)) = 0`;
// Projects with clonable threads outrank empty-but-recent ones: the point
// of the exercise is thread data, not the project list.
@@ -265,7 +293,7 @@ const pruneSnapshot = Effect.fn("pruneDevDbSnapshot")(function* (input: RunMigra
FROM projection_projects p
LEFT JOIN (
SELECT project_id, MAX(updated_at) AS last_stopped_at
FROM stopped_threads
FROM stopped_families
GROUP BY project_id
) q ON q.project_id = p.project_id
WHERE p.deleted_at IS NULL
@@ -274,42 +302,56 @@ const pruneSnapshot = Effect.fn("pruneDevDbSnapshot")(function* (input: RunMigra
LIMIT ${input.projects}`;
yield* sql`CREATE TEMP TABLE kept_threads AS
SELECT thread_id FROM (
SELECT
st.thread_id,
ROW_NUMBER() OVER (
PARTITION BY st.project_id
ORDER BY st.updated_at DESC
) AS recency_rank
FROM stopped_threads st
JOIN kept_projects kp ON kp.project_id = st.project_id
)
WHERE recency_rank <= ${input.threadsPerProject}`;
SELECT f.thread_id FROM thread_families f
WHERE f.root_id IN (
SELECT root_id FROM (
SELECT
sf.root_id,
ROW_NUMBER() OVER (
PARTITION BY sf.project_id
ORDER BY sf.updated_at DESC
) AS recency_rank
FROM stopped_families sf
JOIN kept_projects kp ON kp.project_id = sf.project_id
)
WHERE recency_rank <= ${input.threadsPerProject}
)`;
// Every V2 table and every V1 table the lazy importer reads is keyed by
// thread_id, so one sweep covers both and new tables need no change here.
// Provider sessions are shared between threads and pruned by binding below.
const threadTables = yield* sql<{ name: string }>`
SELECT m.name FROM sqlite_master m, pragma_table_info(m.name) c
WHERE m.type = 'table' AND c.name = 'thread_id'
AND m.name <> 'orchestration_v2_projection_provider_sessions'`;
yield* sql.withTransaction(
Effect.gen(function* () {
yield* sql`DELETE FROM projection_projects
WHERE project_id NOT IN (SELECT project_id FROM kept_projects)`;
yield* sql`DELETE FROM projection_threads
WHERE thread_id NOT IN (SELECT thread_id FROM kept_threads)`;
for (const table of [
"projection_thread_messages",
"projection_thread_activities",
"projection_thread_sessions",
"projection_turns",
"projection_pending_approvals",
"projection_thread_proposed_plans",
"checkpoint_diff_blobs",
]) {
yield* sql`DELETE FROM orchestration_v2_projection_provider_sessions
WHERE COALESCE(thread_id, '') NOT IN (SELECT thread_id FROM kept_threads)
AND provider_session_id NOT IN (
SELECT provider_session_id FROM orchestration_v2_projection_provider_session_bindings
WHERE thread_id IN (SELECT thread_id FROM kept_threads)
)`;
for (const { name } of threadTables) {
yield* sql.unsafe(
`DELETE FROM ${table} WHERE thread_id NOT IN (SELECT thread_id FROM kept_threads)`,
`DELETE FROM "${name}" WHERE thread_id NOT IN (SELECT thread_id FROM kept_threads)`,
).unprepared;
}
yield* sql`DELETE FROM orchestration_v2_projection_context_transfers
WHERE source_thread_id NOT IN (SELECT thread_id FROM kept_threads)
OR target_thread_id NOT IN (SELECT thread_id FROM kept_threads)`;
yield* sql`DELETE FROM orchestration_events
WHERE (aggregate_kind = 'thread'
AND stream_id NOT IN (SELECT thread_id FROM kept_threads))
OR (aggregate_kind = 'project'
AND stream_id NOT IN (SELECT project_id FROM kept_projects))`;
// Pending work the dev server would otherwise pick up and run.
yield* sql`DELETE FROM scheduled_tasks`;
yield* sql`DELETE FROM orchestration_v2_effect_outbox`;
yield* sql`DELETE FROM orchestration_v2_thread_launch_workflows`;
yield* sql`DELETE FROM orchestration_command_receipts`;
yield* sql`DELETE FROM provider_session_runtime`;
yield* sql`DELETE FROM auth_sessions`;
@@ -320,7 +362,8 @@ const pruneSnapshot = Effect.fn("pruneDevDbSnapshot")(function* (input: RunMigra
const keptProjects = yield* sql<{ title: string; threads: number }>`
SELECT
p.title,
(SELECT COUNT(*) FROM projection_threads t WHERE t.project_id = p.project_id) AS threads
(SELECT COUNT(*) FROM orchestration_v2_projection_threads t
WHERE t.project_id = p.project_id) AS threads
FROM projection_projects p
ORDER BY p.updated_at DESC`;
const [events] = yield* sql<{ count: number }>`
@@ -362,7 +405,7 @@ export const runMigrateDevDb = Effect.fn("runMigrateDevDb")(function* (
const sharedHome = path.resolve(options.sharedHome ?? path.join(NodeOS.homedir(), ".t3"));
const sourcePath = path.resolve(
input.source ?? path.join(sharedHome, "userdata", "state.sqlite"),
input.source ?? path.join(sharedHome, "userdata", "statev2.sqlite"),
);
const baseDir =
@@ -458,7 +501,11 @@ export const runMigrateDevDb = Effect.fn("runMigrateDevDb")(function* (
`Pruning to ${input.projects} projects, ${input.threadsPerProject} stopped threads each...`,
);
const result = yield* pruneSnapshot(input).pipe(
Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })),
Effect.provide(
ProjectionStore.layer.pipe(
Layer.provideMerge(NodeSqliteClient.layer({ filename: snapshotPath })),
),
),
wrapPhase("prune", snapshotPath),
);
@@ -512,7 +559,9 @@ export const migrateDevDbCommand = Command.make(
),
threadsPerProject: Flag.Int("threads-per-project").pipe(
Flag.withDefault(10),
Flag.withDescription("How many recent stopped threads to keep per project."),
Flag.withDescription(
"How many recent stopped threads, with their forks and subagents, to keep per project.",
),
),
baseDir: Flag.String("base-dir").pipe(
Flag.optional,
@@ -520,7 +569,7 @@ export const migrateDevDbCommand = Command.make(
),
source: Flag.String("source").pipe(
Flag.optional,
Flag.withDescription("Source database. Defaults to ~/.t3/userdata/state.sqlite."),
Flag.withDescription("Source database. Defaults to ~/.t3/userdata/statev2.sqlite."),
),
},
({ projects, threadsPerProject, baseDir, source }) =>