Follow-up review of the pairing path and a second pass over seeding: - `isPersistedServerRuntimeStateLive` reported non-positive pids as live. `process.kill` reads 0 and -1 as signal-group targets rather than process lookups, so neither throws and both were caught by the "it didn't throw, so it's running" branch. A truncated or hand-edited file recording either would be believed forever — the dev candidate wins the devUrl preference, so it also outranks a genuinely live server elsewhere and mints tokens into a database nothing reads. Rejected in the schema and re-checked at the call site; the errno cast is now a guard, since an out-of-range pid throws a TypeError with no `code`. - `pairing url --json` emitted warnings on stdout ahead of the payload. The probe reads both state directories, so a corrupt file in the one *not* in use broke JSON for any consumer piping it; the quiet-logs layer was only applied around the issuing step that runs after. Verified with a crafted fixture: stdout is now valid JSON. - Turns copied in the `pending` state were left unsettled. Same defect as the `running` case fixed previously — a user message accepted before its provider turn started, which only that thread's next message would ever clear. - The source was read across a dozen implicit transactions while the installed app may be writing to it, so a project could vanish between the query that selected it and the copy that read its row. One deferred read transaction pins every query to a single snapshot. - `--from` and `--to` resolving to the same directory is now refused. Not for the data loss it appears to be (the source reads a pre-transaction snapshot, so the rows come back — verified in both journal modes), but because the event log, the cursors, and everything outside the caps do not. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
278 lines
11 KiB
JavaScript
278 lines
11 KiB
JavaScript
#!/usr/bin/env node
|
|
|
|
// @effect-diagnostics nodeBuiltinImport:off - node:os resolves the shared T3 home guard.
|
|
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
|
import * as NodeOS from "node:os";
|
|
import * as Console from "effect/Console";
|
|
import * as DateTime from "effect/DateTime";
|
|
import * as Effect from "effect/Effect";
|
|
import * as FileSystem from "effect/FileSystem";
|
|
import * as Layer from "effect/Layer";
|
|
import * as Logger from "effect/Logger";
|
|
import * as Option from "effect/Option";
|
|
import * as Path from "effect/Path";
|
|
import * as Schema from "effect/Schema";
|
|
import { Command, Flag } from "effect/unstable/cli";
|
|
|
|
import { resolveWorktreeT3Home } from "@t3tools/shared/devHome";
|
|
|
|
import { DevSeedError, seedDevDatabase } from "./lib/dev-seed.ts";
|
|
import { findRunningServerPid } from "./lib/server-runtime-probe.ts";
|
|
|
|
const DEFAULT_THREAD_LIMIT = 25;
|
|
const DEFAULT_ACTIVITY_LIMIT = 200;
|
|
/** SQLite's default SQLITE_MAX_VARIABLE_NUMBER; one bound parameter per thread. */
|
|
const MAX_THREAD_LIMIT = 32_766;
|
|
|
|
class DevSeedTargetError extends Schema.TaggedErrorClass<DevSeedTargetError>()(
|
|
"DevSeedTargetError",
|
|
{
|
|
reason: Schema.Literals([
|
|
"shared-home",
|
|
"missing-target",
|
|
"not-a-worktree",
|
|
"server-running",
|
|
"same-source",
|
|
]),
|
|
detail: Schema.String,
|
|
},
|
|
) {
|
|
override get message(): string {
|
|
switch (this.reason) {
|
|
case "shared-home":
|
|
return [
|
|
`Refusing to seed ${this.detail}: that is the shared T3 Code home.`,
|
|
"This command overwrites projection tables. Run it from a worktree, or pass --to <base-dir>.",
|
|
].join("\n");
|
|
case "missing-target":
|
|
return [
|
|
`No database at ${this.detail}.`,
|
|
"Start the dev server once so migrations run (`bun run dev`), then seed.",
|
|
].join("\n");
|
|
case "not-a-worktree":
|
|
return [
|
|
"Not inside a git worktree, so there is no worktree-local data directory to seed.",
|
|
"Pass --to <base-dir> to choose one explicitly.",
|
|
].join("\n");
|
|
case "server-running":
|
|
return [
|
|
`A T3 Code server (pid ${this.detail}) is running against this data directory.`,
|
|
"Seeding replaces its projections and empties its event log while it holds them open,",
|
|
"which leaves the running server's in-memory read model describing rows that no longer exist.",
|
|
"Stop it, run the seed, then start it again.",
|
|
].join("\n");
|
|
case "same-source":
|
|
return [
|
|
`Refusing to seed ${this.detail} from itself.`,
|
|
"The copy would restore what the delete removed, but the event log and the",
|
|
"projector cursors are cleared either way — so the directory loses its history",
|
|
"and keeps only whatever the thread and activity caps selected.",
|
|
].join("\n");
|
|
}
|
|
}
|
|
}
|
|
|
|
const stateDbPath = (path: Path.Path, baseDir: string) =>
|
|
path.join(baseDir, "userdata", "state.sqlite");
|
|
|
|
/**
|
|
* Copies the files behind the copied messages' attachment references.
|
|
*
|
|
* The rows carry only metadata; the bytes sit in a flat directory beside the
|
|
* database as `<attachmentId><ext>` (apps/server/src/attachmentStore.ts). Copy
|
|
* the rows alone and a seeded thread renders an image whose request 404s.
|
|
*
|
|
* Matched by directory listing rather than by reconstructing the extension: the
|
|
* server infers it from mime type and file name at upload, and duplicating that
|
|
* inference here would rot independently of it.
|
|
*/
|
|
const copyAttachments = Effect.fn("devSeed.copyAttachments")(function* (input: {
|
|
readonly sourceDir: string;
|
|
readonly targetDir: string;
|
|
readonly attachmentIds: ReadonlyArray<string>;
|
|
}) {
|
|
const fileSystem = yield* FileSystem.FileSystem;
|
|
const path = yield* Path.Path;
|
|
|
|
if (input.attachmentIds.length === 0) {
|
|
return 0;
|
|
}
|
|
|
|
const entries = yield* fileSystem
|
|
.readDirectory(input.sourceDir)
|
|
.pipe(Effect.orElseSucceed(() => [] as Array<string>));
|
|
if (entries.length === 0) {
|
|
return 0;
|
|
}
|
|
|
|
const wanted = new Set(input.attachmentIds);
|
|
const matches = entries.filter((entry) => wanted.has(path.parse(entry).name));
|
|
if (matches.length === 0) {
|
|
return 0;
|
|
}
|
|
|
|
yield* fileSystem.makeDirectory(input.targetDir, { recursive: true });
|
|
// Attachments are decoration on a dev fixture: one unreadable file should
|
|
// leave the rest of the seed intact rather than fail a completed copy.
|
|
const copied = yield* Effect.forEach(matches, (entry) =>
|
|
fileSystem.copyFile(path.join(input.sourceDir, entry), path.join(input.targetDir, entry)).pipe(
|
|
Effect.as(1),
|
|
Effect.orElseSucceed(() => 0),
|
|
),
|
|
);
|
|
return copied.reduce((total, one) => total + one, 0);
|
|
});
|
|
|
|
const devSeedCli = Command.make("dev-seed", {
|
|
from: Flag.string("from").pipe(
|
|
Flag.withDescription(
|
|
"Base directory to copy from (default: the shared T3 Code home, ~/.t3). Read-only.",
|
|
),
|
|
Flag.optional,
|
|
Flag.map(Option.getOrUndefined),
|
|
),
|
|
to: Flag.string("to").pipe(
|
|
Flag.withDescription(
|
|
"Base directory to seed (default: this worktree's .t3). Its projection tables are replaced.",
|
|
),
|
|
Flag.optional,
|
|
Flag.map(Option.getOrUndefined),
|
|
),
|
|
// Bounded below: SQLite reads a negative LIMIT as "no limit", which would
|
|
// quietly turn a capped copy into a full-table one. Bounded above because
|
|
// every selected thread becomes one bound parameter in the copy's `IN (...)`,
|
|
// and SQLite's compiled-in ceiling is 32766 — past it the seed dies with
|
|
// "too many SQL variables" after the target has already been emptied.
|
|
threads: Flag.integer("threads").pipe(
|
|
Flag.withSchema(
|
|
Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(MAX_THREAD_LIMIT)),
|
|
),
|
|
Flag.withDescription(
|
|
`How many recent threads to copy (default ${String(DEFAULT_THREAD_LIMIT)}, max ${String(MAX_THREAD_LIMIT)}).`,
|
|
),
|
|
Flag.withDefault(DEFAULT_THREAD_LIMIT),
|
|
),
|
|
activities: Flag.integer("activities").pipe(
|
|
Flag.withSchema(Schema.Int.check(Schema.isGreaterThan(0))),
|
|
Flag.withDescription(
|
|
`Newest activities kept per thread (default ${String(DEFAULT_ACTIVITY_LIMIT)}).`,
|
|
),
|
|
Flag.withDefault(DEFAULT_ACTIVITY_LIMIT),
|
|
),
|
|
}).pipe(
|
|
Command.withDescription(
|
|
"Copy recent projects and threads from a T3 Code data directory into an isolated dev one.",
|
|
),
|
|
Command.withHandler((input) =>
|
|
Effect.gen(function* () {
|
|
const fileSystem = yield* FileSystem.FileSystem;
|
|
const path = yield* Path.Path;
|
|
|
|
const sharedHome = path.join(NodeOS.homedir(), ".t3");
|
|
const sourceBaseDir = input.from ? path.resolve(input.from) : sharedHome;
|
|
|
|
const defaultTarget = yield* resolveWorktreeT3Home(process.cwd());
|
|
const targetBaseDir = input.to ? path.resolve(input.to) : defaultTarget;
|
|
if (targetBaseDir === undefined) {
|
|
return yield* new DevSeedTargetError({ reason: "not-a-worktree", detail: process.cwd() });
|
|
}
|
|
|
|
// The whole point is to keep dev data off the real home; overwriting it
|
|
// here would be the exact accident this command exists to avoid.
|
|
const [canonicalTarget, canonicalSource, canonicalShared] = yield* Effect.all([
|
|
fileSystem.realPath(targetBaseDir).pipe(Effect.orElseSucceed(() => targetBaseDir)),
|
|
fileSystem.realPath(sourceBaseDir).pipe(Effect.orElseSucceed(() => sourceBaseDir)),
|
|
fileSystem.realPath(sharedHome).pipe(Effect.orElseSucceed(() => sharedHome)),
|
|
]);
|
|
if (canonicalTarget === canonicalShared) {
|
|
return yield* new DevSeedTargetError({ reason: "shared-home", detail: targetBaseDir });
|
|
}
|
|
// Seeding a directory from itself is not the data loss it looks like —
|
|
// the source reads a pre-transaction snapshot, so the copy puts the rows
|
|
// back. What does not come back is the event log and the cursors, and
|
|
// anything outside the caps. Nobody means to ask for that.
|
|
if (canonicalTarget === canonicalSource) {
|
|
return yield* new DevSeedTargetError({ reason: "same-source", detail: targetBaseDir });
|
|
}
|
|
|
|
const targetDbPath = stateDbPath(path, targetBaseDir);
|
|
if (!(yield* fileSystem.exists(targetDbPath))) {
|
|
return yield* new DevSeedTargetError({ reason: "missing-target", detail: targetDbPath });
|
|
}
|
|
|
|
// SQLite locking is not enough on its own: the seed's transaction can take
|
|
// the write lock between a running server's own writes and commit cleanly.
|
|
// What it cannot do is tell that server the projections it is holding in
|
|
// memory, and the event log it is appending to, were both replaced under
|
|
// it. Its next write then lands on top of a read model it never built.
|
|
const runningPid = yield* findRunningServerPid(targetBaseDir);
|
|
if (Option.isSome(runningPid)) {
|
|
return yield* new DevSeedTargetError({
|
|
reason: "server-running",
|
|
detail: String(runningPid.value),
|
|
});
|
|
}
|
|
|
|
const seededAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
|
|
const summary = yield* Effect.try({
|
|
try: () =>
|
|
seedDevDatabase({
|
|
sourceDbPath: stateDbPath(path, sourceBaseDir),
|
|
targetDbPath,
|
|
threadLimit: input.threads,
|
|
activityLimit: input.activities,
|
|
seededAt,
|
|
}),
|
|
catch: (cause) => cause as DevSeedError,
|
|
});
|
|
|
|
const copiedAttachments = yield* copyAttachments({
|
|
sourceDir: path.join(sourceBaseDir, "userdata", "attachments"),
|
|
targetDir: path.join(targetBaseDir, "userdata", "attachments"),
|
|
attachmentIds: summary.attachmentIds,
|
|
});
|
|
|
|
yield* Console.log(
|
|
[
|
|
`Seeded ${targetDbPath}`,
|
|
` from ${stateDbPath(path, sourceBaseDir)}`,
|
|
` projects ${String(summary.projects)}`,
|
|
` threads ${String(summary.threads)}`,
|
|
` messages ${String(summary.messages)}`,
|
|
` activity ${String(summary.activities)}`,
|
|
` turns ${String(summary.turns)} sessions ${String(summary.sessions)}`,
|
|
...(summary.attachmentIds.length > 0
|
|
? [
|
|
` files ${String(copiedAttachments)}/${String(summary.attachmentIds.length)} attachment(s)`,
|
|
]
|
|
: []),
|
|
...(summary.skippedColumns.length > 0
|
|
? [
|
|
` note: skipped ${String(summary.skippedColumns.length)} column(s) absent from the target schema`,
|
|
` (${summary.skippedColumns.join(", ")})`,
|
|
]
|
|
: []),
|
|
"",
|
|
"Restart the dev server to pick it up.",
|
|
].join("\n"),
|
|
);
|
|
}).pipe(
|
|
Effect.tapError((error) =>
|
|
Effect.logError(
|
|
error instanceof DevSeedError
|
|
? `${error.message}${error.hint ? `\n${error.hint}` : ""}`
|
|
: error.message,
|
|
),
|
|
),
|
|
),
|
|
),
|
|
);
|
|
|
|
if (import.meta.main) {
|
|
Command.run(devSeedCli, { version: "0.0.0" }).pipe(
|
|
Effect.provide(Layer.mergeAll(Logger.layer([Logger.consolePretty()]), NodeServices.layer)),
|
|
NodeRuntime.runMain,
|
|
);
|
|
}
|