CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 | /**
* Tests for src/lib/migration-assistant.ts.
*
* Coverage:
* 1. Pure helpers — no DB, no Claude. Always run.
* - dependencyHints embeds the dep in each import idiom.
* - migrationBranchName respects the override and otherwise slugs
* the dependency + version cleanly.
* - buildMigrationPrompt + renderMigrationPrBody carry the metadata
* a reviewer needs.
* - detectMajorBump catches major bumps and ignores minor/patch.
*
* 2. End-to-end with an injected fake Claude client + a real bare repo
* on disk. The DB-touching steps (PR insert, audit, dedupe lookup)
* are gated on DATABASE_URL via `it.skipIf(!HAS_DB)` — without it
* we still verify the git side effects.
*
* 3. Watcher — DB-gated. Asserts the dedupe row blocks a repeat
* proposal within the throttle window.
*/
import { describe, it, expect, beforeAll, afterAll } from "bun:test";
import { join } from "path";
import { rm, mkdir } from "fs/promises";
import {
__test,
buildMigrationPrompt,
dependencyHints,
detectMajorBump,
findManifest,
findUsages,
migrationBranchName,
MIGRATION_AUDIT_ACTION,
MIGRATION_LABEL,
MIGRATION_MARKER,
proposeMajorMigration,
recentlyProposed,
renderMigrationPrBody,
runMigrationWatcherTaskOnce,
SUPPORTED_MANIFESTS,
} from "../lib/migration-assistant";
import {
initBareRepo,
createOrUpdateFileOnBranch,
refExists,
getBlob,
} from "../git/repository";
import { db } from "../db";
import { and, eq } from "drizzle-orm";
import {
auditLog,
pullRequests,
repositories,
users,
} from "../db/schema";
const HAS_DB = Boolean(process.env.DATABASE_URL);
const TEST_REPOS = join(
import.meta.dir,
"../../.test-repos-migration-" + Date.now()
);
beforeAll(async () => {
process.env.GIT_REPOS_PATH = TEST_REPOS;
process.env.DATABASE_URL = process.env.DATABASE_URL || "";
await rm(TEST_REPOS, { recursive: true, force: true });
await mkdir(TEST_REPOS, { recursive: true });
});
afterAll(async () => {
await rm(TEST_REPOS, { recursive: true, force: true });
});
// ---------------------------------------------------------------------------
// Pure helpers
// ---------------------------------------------------------------------------
describe("SUPPORTED_MANIFESTS", () => {
it("covers node, python, rust, and go", () => {
expect(SUPPORTED_MANIFESTS).toContain("package.json");
expect(SUPPORTED_MANIFESTS).toContain("pyproject.toml");
expect(SUPPORTED_MANIFESTS).toContain("Cargo.toml");
expect(SUPPORTED_MANIFESTS).toContain("go.mod");
});
});
describe("dependencyHints", () => {
it("returns common import idioms for an npm-style name", () => {
const hs = dependencyHints("hono");
expect(hs.length).toBeGreaterThan(0);
expect(hs).toContain(`"hono"`);
expect(hs).toContain(`'hono'`);
expect(hs).toContain(` from "hono"`);
expect(hs).toContain(`require("hono")`);
});
it("rewrites hyphens to underscores for Rust use clauses", () => {
const hs = dependencyHints("my-crate");
expect(hs.some((h) => h.includes("my_crate::"))).toBe(true);
});
it("returns empty when the name is blank", () => {
expect(dependencyHints("")).toEqual([]);
expect(dependencyHints(" ")).toEqual([]);
});
});
describe("migrationBranchName", () => {
it("honours an override", () => {
expect(migrationBranchName("hono", "4.0.0", "custom/branch")).toBe(
"custom/branch"
);
});
it("uses ai-migration/<slug>-<timestamp> by default", () => {
const name = migrationBranchName("@hono/zod-validator", "2.0.0");
expect(name.startsWith("ai-migration/")).toBe(true);
// No double slashes, no leading/trailing dashes in the slug portion.
expect(name).not.toMatch(/--/);
const ts = name.split("-").pop()!;
expect(/^\d+$/.test(ts)).toBe(true);
});
});
describe("detectMajorBump", () => {
it("returns from/to when major increases", () => {
expect(detectMajorBump("^3.2.1", "4.0.0")).toEqual({
from: "^3.2.1",
to: "4.0.0",
});
});
it("returns null when major matches", () => {
expect(detectMajorBump("^4.0.0", "4.5.2")).toBeNull();
});
it("returns null when latest is older", () => {
expect(detectMajorBump("^5.0.0", "4.0.0")).toBeNull();
});
it("returns null for non-semver inputs", () => {
expect(detectMajorBump("workspace:*", "4.0.0")).toBeNull();
expect(detectMajorBump("^3.0.0", "next")).toBeNull();
});
});
describe("buildMigrationPrompt", () => {
it("embeds the dep, version range, and file contents", () => {
const out = buildMigrationPrompt({
dependency: "hono",
fromVersion: "^3.0.0",
toVersion: "4.0.0",
manifestPath: "package.json",
changelog: "Removed Context.req.json()",
files: [
{ path: "src/app.ts", content: "import { Hono } from 'hono'" },
],
});
expect(out).toContain("hono");
expect(out).toContain("^3.0.0");
expect(out).toContain("4.0.0");
expect(out).toContain("package.json");
expect(out).toContain("src/app.ts");
expect(out).toContain("Removed Context.req.json()");
expect(out).toContain(`"patches"`);
expect(out).toContain(`"test_updates"`);
expect(out).toContain(`"explanation"`);
});
it("notes the missing changelog when none is provided", () => {
const out = buildMigrationPrompt({
dependency: "x",
fromVersion: "1",
toVersion: "2",
manifestPath: null,
files: [],
});
expect(out).toContain("(none provided)");
});
});
describe("renderMigrationPrBody", () => {
it("includes marker, label, and a split between source + test changes", () => {
const body = renderMigrationPrBody({
dependency: "hono",
fromVersion: "^3.0.0",
toVersion: "4.0.0",
explanation: "Replaced Context.req.json() with Context.req.json().",
patchPaths: ["src/app.ts"],
testPaths: ["test/app.test.ts"],
changelog: "Removed the old API.",
});
expect(body).toContain(MIGRATION_MARKER);
expect(body).toContain(MIGRATION_LABEL);
expect(body).toContain("hono");
expect(body).toContain("^3.0.0");
expect(body).toContain("4.0.0");
expect(body).toContain("src/app.ts");
expect(body).toContain("test/app.test.ts");
expect(body).toContain("Replaced Context.req.json");
expect(body).toContain("### Source changes");
expect(body).toContain("### Test changes");
});
it("falls back gracefully when explanation or changelog is missing", () => {
const body = renderMigrationPrBody({
dependency: "x",
fromVersion: "1.0.0",
toVersion: "2.0.0",
explanation: "",
patchPaths: [],
testPaths: [],
});
expect(body).toContain("(no explanation provided)");
expect(body).toContain("(none)");
expect(body).toContain("(no changelog provided)");
});
});
describe("__test internals", () => {
it("matchSemver parses 3-segment versions", () => {
const v = __test.matchSemver("^1.2.3");
expect(v).toEqual({ major: 1, minor: 2, patch: 3 });
});
it("matchSemver returns null on garbage", () => {
expect(__test.matchSemver("workspace:*")).toBeNull();
expect(__test.matchSemver("")).toBeNull();
});
});
// ---------------------------------------------------------------------------
// Bare-repo fixtures + fake Claude
// ---------------------------------------------------------------------------
const OWNER = "mig-test-" + Date.now().toString(36);
const REPO = "subject";
const PACKAGE_JSON =
JSON.stringify(
{
name: "subject",
dependencies: { hono: "^3.0.0" },
},
null,
2
) + "\n";
const APP_TS = `import { Hono } from "hono";\n\nconst app = new Hono();\napp.get('/', (c) => c.text('hello'));\nexport default app;\n`;
async function seedRepo(): Promise<{ baseSha: string }> {
await initBareRepo(OWNER, REPO);
const first = await createOrUpdateFileOnBranch({
owner: OWNER,
name: REPO,
branch: "main",
filePath: "package.json",
bytes: new TextEncoder().encode(PACKAGE_JSON),
message: "seed manifest",
authorName: "Seeder",
authorEmail: "seed@example.com",
});
if ("error" in first) throw new Error(`seed manifest: ${first.error}`);
const second = await createOrUpdateFileOnBranch({
owner: OWNER,
name: REPO,
branch: "main",
filePath: "src/app.ts",
bytes: new TextEncoder().encode(APP_TS),
message: "seed app",
authorName: "Seeder",
authorEmail: "seed@example.com",
});
if ("error" in second) throw new Error(`seed app: ${second.error}`);
return { baseSha: second.commitSha };
}
function fakeClient(responseText: string) {
return {
messages: {
create: async () => ({
content: [{ type: "text" as const, text: responseText }],
}),
},
} as any;
}
// ---------------------------------------------------------------------------
// Sandbox repo — git side effects (no DB required)
// ---------------------------------------------------------------------------
describe("findManifest + findUsages (no DB)", () => {
it("locates package.json + the call-site that imports the dep", async () => {
const { baseSha } = await seedRepo();
const m = await findManifest(OWNER, REPO, baseSha);
expect(m).not.toBeNull();
expect(m!.path).toBe("package.json");
expect(m!.content).toContain(`"hono"`);
const usages = await findUsages(OWNER, REPO, baseSha, "hono");
expect(usages).toContain("src/app.ts");
// manifest is filtered out of usages so the model gets a clean split.
expect(usages).not.toContain("package.json");
});
});
// ---------------------------------------------------------------------------
// End-to-end with injected Claude
// ---------------------------------------------------------------------------
describe("proposeMajorMigration", () => {
it("returns null when dependency or toVersion is missing", async () => {
const out = await proposeMajorMigration({
repositoryId: "00000000-0000-0000-0000-000000000000",
dependency: "",
fromVersion: "1",
toVersion: "2",
baseSha: "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
client: fakeClient("{}"),
});
expect(out).toBeNull();
});
it.skipIf(!HAS_DB)(
"creates branch + commit + PR when Claude returns a real patch",
async () => {
const username = `mig_${Date.now()}_${Math.random()
.toString(36)
.slice(2, 6)}`;
const [u] = await db
.insert(users)
.values({
username,
email: `${username}@example.com`,
passwordHash: "x",
})
.returning({ id: users.id });
const repoName = `subject_${Date.now()}`;
const [r] = await db
.insert(repositories)
.values({
ownerId: u.id,
name: repoName,
diskPath: `/tmp/${username}/${repoName}`,
defaultBranch: "main",
})
.returning({ id: repositories.id });
await initBareRepo(username, repoName);
const seedManifest = await createOrUpdateFileOnBranch({
owner: username,
name: repoName,
branch: "main",
filePath: "package.json",
bytes: new TextEncoder().encode(PACKAGE_JSON),
message: "seed manifest",
authorName: "Seeder",
authorEmail: "s@e.com",
});
if ("error" in seedManifest) throw new Error("seed manifest");
const seedApp = await createOrUpdateFileOnBranch({
owner: username,
name: repoName,
branch: "main",
filePath: "src/app.ts",
bytes: new TextEncoder().encode(APP_TS),
message: "seed app",
authorName: "Seeder",
authorEmail: "s@e.com",
});
if ("error" in seedApp) throw new Error("seed app");
const canned = JSON.stringify({
explanation: "Bumped hono and updated the import statement.",
patches: [
{
path: "package.json",
new_content: PACKAGE_JSON.replace("^3.0.0", "^4.0.0"),
},
{
path: "src/app.ts",
new_content: APP_TS.replace("hono", "hono"),
},
],
test_updates: [
{
path: "test/app.test.ts",
new_content:
"import app from '../src/app';\nimport { describe, it, expect } from 'bun:test';\ndescribe('app', () => { it('starts', () => { expect(app).toBeTruthy(); }); });\n",
},
],
});
const branchOverride = `ai-migration/test-${Date.now()}`;
const out = await proposeMajorMigration({
repositoryId: r.id,
dependency: "hono",
fromVersion: "^3.0.0",
toVersion: "4.0.0",
baseSha: seedApp.commitSha,
client: fakeClient(canned),
branchOverride,
});
expect(out).not.toBeNull();
expect(out!.branch).toBe(branchOverride);
expect(typeof out!.prNumber).toBe("number");
// Branch exists.
expect(
await refExists(username, repoName, `refs/heads/${branchOverride}`)
).toBe(true);
// Manifest on the new branch has the bump applied.
const newManifest = await getBlob(
username,
repoName,
branchOverride,
"package.json"
);
expect(newManifest).not.toBeNull();
expect(newManifest!.content).toContain("^4.0.0");
// Test file was created.
const newTest = await getBlob(
username,
repoName,
branchOverride,
"test/app.test.ts"
);
expect(newTest).not.toBeNull();
expect(newTest!.content).toContain("describe('app'");
// PR row exists with the right base/head + body markers.
const [pr] = await db
.select({
number: pullRequests.number,
headBranch: pullRequests.headBranch,
baseBranch: pullRequests.baseBranch,
title: pullRequests.title,
body: pullRequests.body,
})
.from(pullRequests)
.where(eq(pullRequests.repositoryId, r.id))
.limit(1);
expect(pr).toBeTruthy();
expect(pr!.headBranch).toBe(branchOverride);
expect(pr!.baseBranch).toBe("main");
expect(pr!.title).toContain("[migration]");
expect(pr!.title).toContain("hono");
expect(pr!.body).toContain(MIGRATION_MARKER);
expect(pr!.body).toContain(MIGRATION_LABEL);
// Audit row for the proposal exists with the right metadata.
const audits = await db
.select({ metadata: auditLog.metadata })
.from(auditLog)
.where(
and(
eq(auditLog.repositoryId, r.id),
eq(auditLog.action, MIGRATION_AUDIT_ACTION)
)
)
.limit(5);
expect(audits.length).toBeGreaterThan(0);
const md = JSON.parse(audits[0].metadata as string) as {
dependency: string;
toVersion: string;
};
expect(md.dependency).toBe("hono");
expect(md.toVersion).toBe("4.0.0");
},
25000
);
it.skipIf(!HAS_DB)(
"dedupes proposals for the same {dep, version} within 7 days",
async () => {
const username = `mig_dup_${Date.now()}_${Math.random()
.toString(36)
.slice(2, 6)}`;
const [u] = await db
.insert(users)
.values({
username,
email: `${username}@example.com`,
passwordHash: "x",
})
.returning({ id: users.id });
const repoName = `dup_${Date.now()}`;
const [r] = await db
.insert(repositories)
.values({
ownerId: u.id,
name: repoName,
diskPath: `/tmp/${username}/${repoName}`,
defaultBranch: "main",
})
.returning({ id: repositories.id });
await initBareRepo(username, repoName);
const seedManifest = await createOrUpdateFileOnBranch({
owner: username,
name: repoName,
branch: "main",
filePath: "package.json",
bytes: new TextEncoder().encode(PACKAGE_JSON),
message: "seed",
authorName: "S",
authorEmail: "s@e.com",
});
if ("error" in seedManifest) throw new Error("seed");
const seedApp = await createOrUpdateFileOnBranch({
owner: username,
name: repoName,
branch: "main",
filePath: "src/app.ts",
bytes: new TextEncoder().encode(APP_TS),
message: "seed app",
authorName: "S",
authorEmail: "s@e.com",
});
if ("error" in seedApp) throw new Error("seed app");
const canned = JSON.stringify({
explanation: "stub",
patches: [
{
path: "package.json",
new_content: PACKAGE_JSON.replace("^3.0.0", "^4.0.0"),
},
],
test_updates: [],
});
// First proposal lands.
const first = await proposeMajorMigration({
repositoryId: r.id,
dependency: "hono",
fromVersion: "^3.0.0",
toVersion: "4.0.0",
baseSha: seedApp.commitSha,
client: fakeClient(canned),
branchOverride: `ai-migration/dup-1-${Date.now()}`,
});
expect(first).not.toBeNull();
// Sanity: recentlyProposed should now report a hit.
expect(await recentlyProposed(r.id, "hono", "4.0.0")).toBe(true);
// Second proposal for the same dep+version is squashed by the
// throttle (skipThrottle defaults to false).
const second = await proposeMajorMigration({
repositoryId: r.id,
dependency: "hono",
fromVersion: "^3.0.0",
toVersion: "4.0.0",
baseSha: seedApp.commitSha,
client: fakeClient(canned),
branchOverride: `ai-migration/dup-2-${Date.now()}`,
});
expect(second).toBeNull();
// Only the first PR landed.
const prs = await db
.select({ id: pullRequests.id })
.from(pullRequests)
.where(eq(pullRequests.repositoryId, r.id));
expect(prs.length).toBe(1);
// skipThrottle:true lets the override land. (We don't actually
// assert a third PR because the manifest is already on 4.0.0;
// instead we check the function ran past the dedupe gate by
// observing recentlyProposed remains true.)
expect(await recentlyProposed(r.id, "hono", "4.0.0")).toBe(true);
},
30000
);
});
// ---------------------------------------------------------------------------
// Watcher
// ---------------------------------------------------------------------------
describe("runMigrationWatcherTaskOnce", () => {
it("returns zero-counters when no AI key and no propose injection", async () => {
const saved = process.env.ANTHROPIC_API_KEY;
delete process.env.ANTHROPIC_API_KEY;
try {
const out = await runMigrationWatcherTaskOnce();
expect(out.proposed).toBe(0);
expect(out.considered).toBe(0);
} finally {
if (saved !== undefined) process.env.ANTHROPIC_API_KEY = saved;
}
});
it.skipIf(!HAS_DB)(
"skips repos when migration_watch is disabled",
async () => {
const username = `mig_w_${Date.now()}_${Math.random()
.toString(36)
.slice(2, 6)}`;
const [u] = await db
.insert(users)
.values({
username,
email: `${username}@example.com`,
passwordHash: "x",
})
.returning({ id: users.id });
await db
.insert(repositories)
.values({
ownerId: u.id,
name: `w_${Date.now()}`,
diskPath: `/tmp/${username}/w`,
defaultBranch: "main",
})
.returning({ id: repositories.id });
let proposeCalls = 0;
const out = await runMigrationWatcherTaskOnce({
propose: async () => {
proposeCalls++;
return null;
},
isEnabled: async () => false,
fetchLatest: async () => "9.9.9",
maxReposPerTick: 50,
});
expect(proposeCalls).toBe(0);
expect(out.skippedNotEnabled).toBeGreaterThan(0);
}
);
});
|