Q136: remove rollback records that marked restores nothing performed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ZacharyZhang-NYandClaude Opus 5.5 committed 2026-10-08 21:53:26 -04:00
1 parent f8f852c326
commit 6e210301db
20 files changed
+31 -757

No files matched your search

+4 -4
View File
@@ -1,4 +1,4 @@
import { mkdirSync, realpathSync, rmSync, writeFileSync } from "node:fs";
import { mkdirSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { createHash, randomUUID } from "node:crypto";
@@ -35,7 +35,7 @@ describe("domain services", () => {
const connection = createConnection();
const rows = connection.db.prepare("select version from schema_migrations order by version asc").all() as Array<{ version: number }>;
expect(rows.map((row) => row.version)).toEqual([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]);
expect(rows.map((row) => row.version)).toEqual([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]);
connection.close();
});
@@ -592,14 +592,14 @@ describe("domain services", () => {
idMaps: Record<string, string[]>;
failures: Array<{ table: string; reason: string }>;
validationSummary: { missingTableCount: number; passed: boolean };
rollbackPack: { sourceDatabasePath: string };
};
expect(report.tableChecksums.agents).toHaveLength(64);
expect(report.idMaps.agents).toEqual(["agent-1"]);
expect(report.failures.some((failure) => failure.reason === "missing_table")).toBe(true);
expect(report.validationSummary.missingTableCount).toBeGreaterThan(0);
expect(report.validationSummary.passed).toBe(false);
expect(report.rollbackPack.sourceDatabasePath).toBe(realpathSync.native(legacyPath));
// A report validates the source; it promises no restore it cannot perform.
expect(Object.keys(report)).not.toContain("rollbackPack");
connection.close();
});
+1 -22
View File
@@ -45,16 +45,10 @@ interface MigrationReportBody {
relationFailureCount: number;
passed: boolean;
};
rollbackPack: {
sourceDatabasePath: string;
sourceFingerprint: string;
tableChecksums: Record<string, string>;
idMaps: Record<string, string[]>;
};
}
describe("migration service", () => {
test("creates idempotent reports with checksums, id maps, rollback pack, and integrity failures", () => {
test("creates idempotent reports with checksums, id maps, and integrity failures", () => {
const connection = createConnection();
const organization = new OrganizationService(connection.db);
const migrations = new MigrationService(connection.db);
@@ -87,9 +81,6 @@ describe("migration service", () => {
expect(body.tableCounts.organizations).toBe(1);
expect(body.tableChecksums.agents).toHaveLength(64);
expect(body.idMaps.tasks).toEqual(["task-1"]);
expect(body.rollbackPack.sourceFingerprint).toBe(body.sourceFingerprint);
expect(body.rollbackPack.tableChecksums.agents).toBe(body.tableChecksums.agents);
expect(body.rollbackPack.idMaps.tasks).toEqual(["task-1"]);
expect(body.failures).toContainEqual({ table: "agents", reason: "dangling_org_id", detail: "agent-1 -> org-missing" });
expect(body.failures).toContainEqual({ table: "tasks", reason: "dangling_assignee_agent_id", detail: "task-1 -> agent-missing" });
expect(body.validationSummary).toMatchObject({
@@ -171,9 +162,6 @@ describe("migration service", () => {
create table legal_holds(id text primary key, org_id text, created_by_employee_id text);
create table retention_freezes(id text primary key, org_id text, created_by_employee_id text);
create table search_documents(entity_id text);
create table rollback_snapshots(id text primary key, org_id text, migration_report_id text, created_by_employee_id text);
create table migration_cutover_events(id text primary key, org_id text, migration_report_id text, rollback_snapshot_id text);
create table migration_reconciliation_items(id text primary key, org_id text, migration_report_id text, rollback_snapshot_id text, resolved_by_employee_id text);
create table audit_events(id text primary key, org_id text);
insert into organizations(id) values ('org-1');
insert into employees(id, org_id) values ('emp-1', 'org-1');
@@ -236,9 +224,6 @@ describe("migration service", () => {
insert into legal_holds(id, org_id, created_by_employee_id) values ('hold-1', 'org-1', 'emp-1');
insert into retention_freezes(id, org_id, created_by_employee_id) values ('freeze-1', 'org-1', 'emp-1');
insert into search_documents(entity_id) values ('task-1');
insert into rollback_snapshots(id, org_id, migration_report_id, created_by_employee_id) values ('rollback-1', 'org-1', 'migration-1', 'emp-1');
insert into migration_cutover_events(id, org_id, migration_report_id, rollback_snapshot_id) values ('cutover-1', 'org-1', 'migration-1', 'rollback-1');
insert into migration_reconciliation_items(id, org_id, migration_report_id, rollback_snapshot_id, resolved_by_employee_id) values ('reconcile-1', 'org-1', 'migration-1', 'rollback-1', 'emp-1');
insert into audit_events(id, org_id) values ('audit-1', 'org-1');
`);
let orgId = "";
@@ -279,9 +264,6 @@ describe("migration service", () => {
expect(body.tableCounts.social_approval_routes).toBe(1);
expect(body.tableCounts.social_audit_records).toBe(1);
expect(body.tableCounts.compliance_exports).toBe(1);
expect(body.tableCounts.rollback_snapshots).toBe(1);
expect(body.tableCounts.migration_cutover_events).toBe(1);
expect(body.tableCounts.migration_reconciliation_items).toBe(1);
expect(body.tableCounts.search_documents).toBe(1);
expect(body.tableChecksums.audit_events).toHaveLength(64);
expect(body.idMaps.skill_runtime_snapshots).toEqual(["snapshot-1"]);
@@ -292,9 +274,6 @@ describe("migration service", () => {
expect(body.idMaps.board_interventions).toEqual(["bdi-1"]);
expect(body.idMaps.file_handoff_records).toEqual(["handoff-1"]);
expect(body.idMaps.retention_freezes).toEqual(["freeze-1"]);
expect(body.idMaps.rollback_snapshots).toEqual(["rollback-1"]);
expect(body.idMaps.migration_cutover_events).toEqual(["cutover-1"]);
expect(body.idMaps.migration_reconciliation_items).toEqual(["reconcile-1"]);
expect(body.idMaps.provider_usage_windows).toEqual(["usage-1"]);
expect(body.idMaps.provider_rate_limit_observations).toEqual(["quota-1"]);
expect(body.idMaps.provider_auth_profiles).toEqual(["authp-1"]);
-132
View File
@@ -1,132 +0,0 @@
import { randomUUID } from "node:crypto";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { DatabaseSync } from "node:sqlite";
import { describe, expect, test } from "vitest";
import { DatabaseConnection } from "../../src/main/database/connection";
import { AuditService } from "../../src/main/services/audit-service";
import { MigrationService } from "../../src/main/services/migration-service";
import { OrganizationService } from "../../src/main/services/organization-service";
import { RollbackService } from "../../src/main/services/rollback-service";
import { SnapshotService } from "../../src/main/services/snapshot-service";
function createConnection(): DatabaseConnection {
return new DatabaseConnection(join(tmpdir(), `agentcompany-new-rollback-${randomUUID()}.db`));
}
function createLegacyDatabase(): string {
const legacyPath = join(tmpdir(), `agentcompany-legacy-${randomUUID()}.db`);
const legacy = new DatabaseSync(legacyPath);
legacy.exec(`
create table organizations(id text primary key);
insert into organizations(id) values ('legacy-org');
`);
legacy.close();
return legacyPath;
}
describe("rollback service", () => {
test("creates immutable rollback snapshots from migration reports and workspace manifests", () => {
const connection = createConnection();
const organization = new OrganizationService(connection.db);
const migrations = new MigrationService(connection.db);
const rollback = new RollbackService(connection.db);
const snapshot = new SnapshotService(connection.db);
const audit = new AuditService(connection.db);
const legacyPath = createLegacyDatabase();
let orgId = "";
let employeeId = "";
let reportId = "";
let rollbackId = "";
let reconciliationId = "";
connection.transaction(() => {
orgId = organization.createOrganization({
organizationName: "Acme Operations",
employeeName: "Dana Lee",
mission: "Coordinate agents with auditable approvals.",
goal: "Ship a verified control plane.",
});
employeeId = (connection.db.prepare("select id from employees where org_id = ?").get(orgId) as { id: string }).id;
seedWorkspace(connection.db, orgId);
reportId = migrations.createReport({ orgId, sourceDatabasePath: legacyPath });
audit.record({
orgId,
entityType: "task",
entityId: "task-cutover",
actorType: "employee",
actorId: employeeId,
action: "created",
payload: { title: "Reconcile release delta" },
});
rollbackId = rollback.createSnapshot({ orgId, migrationReportId: reportId, createdByEmployeeId: employeeId });
rollback.setActive({ orgId, snapshotId: rollbackId, active: true, employeeId });
reconciliationId = (connection.db.prepare("select id from migration_reconciliation_items where org_id = ? limit 1")
.get(orgId) as { id: string }).id;
rollback.resolveReconciliationItem({ orgId, reconciliationItemId: reconciliationId, employeeId });
});
const state = snapshot.load();
const record = state.rollbackSnapshots[0];
if (!record) throw new Error("Rollback snapshot was not created.");
const workspaceManifest = JSON.parse(record.workspaceManifestJson) as { workspaces: unknown[]; files: unknown[] };
const deltaJournal = JSON.parse(record.deltaJournalJson) as unknown[];
const restorePlan = JSON.parse(record.restorePlanJson) as { migrationReportId: string; restoreStrategy: string };
expect(record).toMatchObject({ orgId, migrationReportId: reportId, active: true, createdByEmployeeId: employeeId });
expect(record.sourceDatabaseSha256).toHaveLength(64);
expect(record.workspaceManifestSha256).toHaveLength(64);
expect(workspaceManifest.workspaces).toHaveLength(1);
expect(workspaceManifest.files).toHaveLength(1);
expect(deltaJournal.length).toBeGreaterThan(0);
expect(restorePlan).toMatchObject({ migrationReportId: reportId, restoreStrategy: "legacy_snapshot_restore" });
expect(state.migrationCutoverEvents.map((event) => event.eventType).sort()).toEqual([
"migration_reconciliation_resolved",
"rollback_snapshot_activated",
"rollback_snapshot_created",
]);
expect(state.migrationReconciliationItems).toContainEqual(expect.objectContaining({
orgId,
migrationReportId: reportId,
rollbackSnapshotId: rollbackId,
targetType: "task",
targetId: "task-cutover",
reason: "manual_delta_replay",
state: "resolved",
resolvedByEmployeeId: employeeId,
}));
expect(() => connection.transaction(() => rollback.resolveReconciliationItem({ orgId, reconciliationItemId: reconciliationId, employeeId })))
.toThrow("Migration reconciliation item is already resolved.");
expect(state.auditEvents.some((event) => event.entityType === "rollback_snapshot" && event.action === "activated")).toBe(true);
expect(state.auditEvents.some((event) => event.entityType === "migration_reconciliation_item" && event.action === "resolved")).toBe(true);
connection.close();
});
});
function seedWorkspace(db: DatabaseSync, orgId: string): void {
const now = new Date().toISOString();
db.prepare(`
insert into workspaces(id, org_id, name, local_path, repo_url, repo_ref, project_id, is_primary, created_at, updated_at)
values (?, ?, ?, ?, ?, ?, null, 1, ?, ?)
`).run("wsp-rollback", orgId, "Primary", "C:\\repo\\workspace", "https://example.invalid/repo.git", "main", now, now);
db.prepare(`
insert into file_objects(
id, org_id, name, kind, size_bytes, sha256, storage_path, owner_type, owner_id,
created_at, pinned, space_id, updated_at, scan_state, scan_labels_json, scanned_at
) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, null, ?, ?, ?, ?)
`).run(
"file-rollback",
orgId,
"release.txt",
"document",
12,
"0".repeat(64),
"artifacts/release.txt",
"system",
null,
now,
now,
"approved",
"[]",
now,
);
}
@@ -23,3 +23,16 @@ describe("SDLC controls", () => {
connection.close();
});
});
describe("rollback records", () => {
test("offer no snapshot, cutover or reconciliation that marks a restore it never performs", () => {
const connection = new DatabaseConnection(join(tmpdir(), `agentcompany-new-rollback-${randomUUID()}.db`));
const tables = connection.db.prepare(`
select name from sqlite_master
where type = 'table' and name in ('rollback_snapshots', 'migration_cutover_events', 'migration_reconciliation_items')
`).all();
expect(tables).toEqual([]);
expect(Object.keys(IPC_CHANNELS).filter((name) => ["createRollbackSnapshot", "setRollbackSnapshotActive", "resolveMigrationReconciliation"].includes(name))).toEqual([]);
connection.close();
});
});