FN-5741: persist merge-request handoff shadow contract
Introduce Phase 1 write-only persistence for merge-request handoff acceptance across core and engine paths. - add persisted merge-request record types, schema/settings plumbing, and store write-path support - update merger/executor/self-healing/run-audit flows to emit and consume the handoff-accepted shadow marker - expand core/engine/roadmap tests and docs to cover the new merge-request shadow contract - add a patch changeset for @runfusion/fusion for this bundled package update Files changed: .changeset/fn-5741-merge-request-shadow.md | 5 + AGENTS.md | 1 + docs/architecture.md | 2 + docs/settings-reference.md | 1 + packages/core/src/__tests__/db-migrate.test.ts | 12 +- packages/core/src/__tests__/db.test.ts | 34 ++-- packages/core/src/__tests__/goals-schema.test.ts | 2 +- packages/core/src/__tests__/insight-store.test.ts | 10 +- .../src/__tests__/merge-request-record.test.ts | 97 +++++++++++ packages/core/src/__tests__/mission-store.test.ts | 2 +- packages/core/src/__tests__/run-audit.test.ts | 2 +- packages/core/src/__tests__/secrets-schema.test.ts | 6 +- .../core/src/__tests__/settings-parity.test.ts | 3 + .../core/src/__tests__/store-merge-queue.test.ts | 2 +- packages/core/src/__tests__/task-documents.test.ts | 2 +- packages/core/src/db.ts | 49 +++++- packages/core/src/index.ts | 4 +- packages/core/src/settings-schema.ts | 30 ++++ packages/core/src/store.ts | 189 ++++++++++++++++++++- packages/core/src/types.ts | 37 ++++ .../src/__tests__/merger-merge-lifecycle.test.ts | 54 ++++++ .../merge-request-shadow-handoff.test.ts | 74 ++++++++ packages/engine/src/executor.ts | 15 +- packages/engine/src/merger.ts | 37 ++++ packages/engine/src/run-audit.ts | 1 + packages/engine/src/self-healing.ts | 16 +- .../src/store/__tests__/roadmap-store.test.ts | 4 +- 27 files changed, 646 insertions(+), 45 deletions(-) Fusion-Task-Id: FN-5741 Fusion-Task-Lineage: 3fec14c3-47ff-4f14-bc02-24021518c992
This commit is contained in:
@@ -715,7 +715,7 @@ describe("schema migration", () => {
|
||||
|
||||
const row = db.prepare("SELECT deletedAt FROM tasks WHERE id = 'FN-legacy'").get() as { deletedAt: string | null };
|
||||
expect(row.deletedAt).toBeNull();
|
||||
expect(db.getSchemaVersion()).toBe(99);
|
||||
expect(db.getSchemaVersion()).toBe(100);
|
||||
|
||||
db.close();
|
||||
});
|
||||
@@ -748,7 +748,7 @@ describe("schema migration", () => {
|
||||
{ id: "WS-001", mode: "prompt", gateMode: "advisory" },
|
||||
{ id: "WS-002", mode: "script", gateMode: "advisory" },
|
||||
]);
|
||||
expect(db.getSchemaVersion()).toBe(99);
|
||||
expect(db.getSchemaVersion()).toBe(100);
|
||||
|
||||
db.close();
|
||||
});
|
||||
@@ -798,7 +798,7 @@ describe("schema migration", () => {
|
||||
reviewerContextRetryCount: 0,
|
||||
reviewerFallbackRetryCount: 0,
|
||||
});
|
||||
expect(db.getSchemaVersion()).toBe(99);
|
||||
expect(db.getSchemaVersion()).toBe(100);
|
||||
|
||||
db.close();
|
||||
});
|
||||
@@ -827,7 +827,7 @@ describe("schema migration", () => {
|
||||
|
||||
const columns = db.prepare("PRAGMA table_info(milestones)").all() as Array<{ name: string }>;
|
||||
expect(columns.map((column) => column.name)).toContain("acceptanceCriteria");
|
||||
expect(db.getSchemaVersion()).toBe(99);
|
||||
expect(db.getSchemaVersion()).toBe(100);
|
||||
|
||||
db.close();
|
||||
});
|
||||
@@ -868,7 +868,7 @@ describe("schema migration", () => {
|
||||
const missionColumns = db.prepare("PRAGMA table_info(missions)").all() as Array<{ name: string }>;
|
||||
expect(missionColumns.map((column) => column.name)).toContain("autoMerge");
|
||||
|
||||
expect(db.getSchemaVersion()).toBe(99);
|
||||
expect(db.getSchemaVersion()).toBe(100);
|
||||
db.close();
|
||||
});
|
||||
|
||||
@@ -902,7 +902,7 @@ describe("schema migration", () => {
|
||||
{ id: "WS-002", mode: "script", enabled: 1, gateMode: "advisory" },
|
||||
{ id: "WS-003", mode: "prompt", enabled: 0, gateMode: "advisory" },
|
||||
]);
|
||||
expect(db.getSchemaVersion()).toBe(99);
|
||||
expect(db.getSchemaVersion()).toBe(100);
|
||||
|
||||
db.close();
|
||||
});
|
||||
|
||||
@@ -330,7 +330,7 @@ describe("Database", () => {
|
||||
});
|
||||
|
||||
it("seeds schema version", () => {
|
||||
expect(db.getSchemaVersion()).toBe(99);
|
||||
expect(db.getSchemaVersion()).toBe(100);
|
||||
});
|
||||
|
||||
it("includes tokenUsageCacheWriteTokens on freshly initialized tasks table", () => {
|
||||
@@ -389,7 +389,7 @@ describe("Database", () => {
|
||||
|
||||
it("is idempotent - calling init() twice does not fail", () => {
|
||||
expect(() => db.init()).not.toThrow();
|
||||
expect(db.getSchemaVersion()).toBe(99);
|
||||
expect(db.getSchemaVersion()).toBe(100);
|
||||
});
|
||||
it("does not overwrite existing config on re-init", () => {
|
||||
// Update the config
|
||||
@@ -1459,7 +1459,7 @@ describe("schema migrations", () => {
|
||||
db.init();
|
||||
|
||||
// Verify version bumped to 29 (includes v1→v2 through v26→v29)
|
||||
expect(db.getSchemaVersion()).toBe(99);
|
||||
expect(db.getSchemaVersion()).toBe(100);
|
||||
|
||||
// Verify new columns exist and existing data is intact
|
||||
const cols = db.prepare("PRAGMA table_info(tasks)").all() as Array<{ name: string }>;
|
||||
@@ -1484,11 +1484,11 @@ describe("schema migrations", () => {
|
||||
const db = new Database(fusionDir);
|
||||
db.init();
|
||||
|
||||
expect(db.getSchemaVersion()).toBe(99);
|
||||
expect(db.getSchemaVersion()).toBe(100);
|
||||
|
||||
// Re-init should not fail
|
||||
db.init();
|
||||
expect(db.getSchemaVersion()).toBe(99);
|
||||
expect(db.getSchemaVersion()).toBe(100);
|
||||
|
||||
db.close();
|
||||
});
|
||||
@@ -1523,7 +1523,7 @@ describe("schema migrations", () => {
|
||||
|
||||
db.init();
|
||||
|
||||
expect(db.getSchemaVersion()).toBe(99);
|
||||
expect(db.getSchemaVersion()).toBe(100);
|
||||
|
||||
const cols = db.prepare("PRAGMA table_info(tasks)").all() as Array<{ name: string }>;
|
||||
expect(cols.map((col) => col.name)).toContain("priority");
|
||||
@@ -1564,7 +1564,7 @@ describe("schema migrations", () => {
|
||||
|
||||
db.init();
|
||||
|
||||
expect(db.getSchemaVersion()).toBe(99);
|
||||
expect(db.getSchemaVersion()).toBe(100);
|
||||
|
||||
const cols = db.prepare("PRAGMA table_info(tasks)").all() as Array<{ name: string }>;
|
||||
const colNames = cols.map((col) => col.name);
|
||||
@@ -1636,7 +1636,7 @@ describe("schema migrations", () => {
|
||||
|
||||
db.init();
|
||||
|
||||
expect(db.getSchemaVersion()).toBe(99);
|
||||
expect(db.getSchemaVersion()).toBe(100);
|
||||
|
||||
const cols = db.prepare("PRAGMA table_info(tasks)").all() as Array<{ name: string }>;
|
||||
const colNames = cols.map((col) => col.name);
|
||||
@@ -1876,7 +1876,7 @@ describe("schema migrations", () => {
|
||||
|
||||
db.init();
|
||||
|
||||
expect(db.getSchemaVersion()).toBe(99);
|
||||
expect(db.getSchemaVersion()).toBe(100);
|
||||
|
||||
const cols = db.prepare("PRAGMA table_info(chat_messages)").all() as Array<{ name: string }>;
|
||||
expect(cols.map((col) => col.name)).toContain("attachments");
|
||||
@@ -1950,7 +1950,7 @@ describe("schema migrations", () => {
|
||||
|
||||
db.init();
|
||||
|
||||
expect(db.getSchemaVersion()).toBe(99);
|
||||
expect(db.getSchemaVersion()).toBe(100);
|
||||
|
||||
const tables = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name = 'agentRatings'").all() as Array<{ name: string }>;
|
||||
expect(tables).toEqual([{ name: "agentRatings" }]);
|
||||
@@ -1974,7 +1974,7 @@ describe("schema migrations", () => {
|
||||
|
||||
db.init();
|
||||
|
||||
expect(db.getSchemaVersion()).toBe(99);
|
||||
expect(db.getSchemaVersion()).toBe(100);
|
||||
|
||||
const tables = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name = 'mission_events'").all() as Array<{ name: string }>;
|
||||
expect(tables).toEqual([{ name: "mission_events" }]);
|
||||
@@ -2078,7 +2078,7 @@ describe("schema migrations", () => {
|
||||
db.init();
|
||||
|
||||
// Verify version bumped to 29
|
||||
expect(db.getSchemaVersion()).toBe(99);
|
||||
expect(db.getSchemaVersion()).toBe(100);
|
||||
|
||||
// Verify new columns exist and existing data is intact
|
||||
const cols = db.prepare("PRAGMA table_info(tasks)").all() as Array<{ name: string }>;
|
||||
@@ -2297,7 +2297,7 @@ describe("schema migrations", () => {
|
||||
|
||||
localDb.init();
|
||||
|
||||
expect(localDb.getSchemaVersion()).toBe(99);
|
||||
expect(localDb.getSchemaVersion()).toBe(100);
|
||||
const columns = localDb.prepare("PRAGMA table_info(tasks)").all() as Array<{ name: string }>;
|
||||
expect(columns.map((column) => column.name)).toContain("tokenUsageCacheWriteTokens");
|
||||
|
||||
@@ -2608,7 +2608,7 @@ describe("createDatabase factory", () => {
|
||||
const db = createDatabase(fusionDir);
|
||||
db.init();
|
||||
|
||||
expect(db.getSchemaVersion()).toBe(99);
|
||||
expect(db.getSchemaVersion()).toBe(100);
|
||||
expect(db.getLastModified()).toBeGreaterThan(0);
|
||||
|
||||
db.close();
|
||||
@@ -2762,7 +2762,7 @@ describe("migration v77 task token budget columns", () => {
|
||||
|
||||
migrated = new Database(fusion);
|
||||
migrated.init();
|
||||
expect(migrated.getSchemaVersion()).toBe(99);
|
||||
expect(migrated.getSchemaVersion()).toBe(100);
|
||||
const rows = migrated.prepare("PRAGMA table_info(tasks)").all() as Array<{ name: string }>;
|
||||
const names = new Set(rows.map((row) => row.name));
|
||||
expect(names.has("tokenBudgetSoftAlertedAt")).toBe(true);
|
||||
@@ -2808,7 +2808,7 @@ describe("migration v67 drops orphan project auth tables", () => {
|
||||
|
||||
migrated = new Database(fusion);
|
||||
migrated.init();
|
||||
expect(migrated.getSchemaVersion()).toBe(99);
|
||||
expect(migrated.getSchemaVersion()).toBe(100);
|
||||
const tables = migrated
|
||||
.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'project_auth_%'")
|
||||
.all() as Array<{ name: string }>;
|
||||
@@ -2835,7 +2835,7 @@ describe("migration v67 drops orphan project auth tables", () => {
|
||||
|
||||
try {
|
||||
fresh.init();
|
||||
expect(fresh.getSchemaVersion()).toBe(99);
|
||||
expect(fresh.getSchemaVersion()).toBe(100);
|
||||
const tables = fresh
|
||||
.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'project_auth_%'")
|
||||
.all() as Array<{ name: string }>;
|
||||
|
||||
@@ -91,6 +91,6 @@ describe("goals schema", () => {
|
||||
});
|
||||
|
||||
it("reports schema version 92", () => {
|
||||
expect(db.getSchemaVersion()).toBe(99);
|
||||
expect(db.getSchemaVersion()).toBe(100);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1000,7 +1000,7 @@ describe("Migration: pre-33 DB upgrade", () => {
|
||||
// Step 1: Create a fresh database at v33 (runs all migrations up to 33)
|
||||
const db1 = createDatabase(legacyDir);
|
||||
db1.init();
|
||||
expect(db1.getSchemaVersion()).toBe(99);
|
||||
expect(db1.getSchemaVersion()).toBe(100);
|
||||
db1.close();
|
||||
|
||||
// Step 2: Manually downgrade to version 32 and drop insight tables
|
||||
@@ -1035,7 +1035,7 @@ describe("Migration: pre-33 DB upgrade", () => {
|
||||
expect(tableNamesBefore).not.toContain("project_insight_runs");
|
||||
// Now run init — this triggers the v32→v33 migration
|
||||
db3.init();
|
||||
expect(db3.getSchemaVersion()).toBe(99);
|
||||
expect(db3.getSchemaVersion()).toBe(100);
|
||||
|
||||
// Step 4: Verify insight tables exist after migration
|
||||
const tablesAfter = db3.prepare(
|
||||
@@ -1066,12 +1066,12 @@ describe("Migration: pre-33 DB upgrade", () => {
|
||||
try {
|
||||
const db1 = createDatabase(testDir);
|
||||
db1.init();
|
||||
expect(db1.getSchemaVersion()).toBe(99);
|
||||
expect(db1.getSchemaVersion()).toBe(100);
|
||||
db1.close();
|
||||
|
||||
const db2 = createDatabase(testDir);
|
||||
expect(() => db2.init()).not.toThrow();
|
||||
expect(db2.getSchemaVersion()).toBe(99);
|
||||
expect(db2.getSchemaVersion()).toBe(100);
|
||||
db2.close();
|
||||
} finally {
|
||||
rmSync(testDir, { recursive: true, force: true });
|
||||
@@ -1085,7 +1085,7 @@ describe("Migration: pre-33 DB upgrade", () => {
|
||||
// Step 1: Create a fresh DB and run migrations
|
||||
const db1 = createDatabase(compatDir);
|
||||
db1.init();
|
||||
expect(db1.getSchemaVersion()).toBe(99);
|
||||
expect(db1.getSchemaVersion()).toBe(100);
|
||||
|
||||
// Step 2: Strip lifecycle and cancelledAt columns by recreating the
|
||||
// table without them. This simulates a DB that was created before the
|
||||
|
||||
97
packages/core/src/__tests__/merge-request-record.test.ts
Normal file
97
packages/core/src/__tests__/merge-request-record.test.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { mkdtempSync } from "node:fs";
|
||||
import { rm } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import { TaskStore } from "../store.js";
|
||||
|
||||
function makeTmpDir(): string {
|
||||
return mkdtempSync(join(tmpdir(), "kb-merge-request-record-test-"));
|
||||
}
|
||||
|
||||
describe("TaskStore merge request record + completion handoff marker", () => {
|
||||
let rootDir: string;
|
||||
let globalDir: string;
|
||||
let store: TaskStore;
|
||||
|
||||
beforeEach(async () => {
|
||||
rootDir = makeTmpDir();
|
||||
globalDir = join(rootDir, ".fusion-global");
|
||||
store = new TaskStore(rootDir, globalDir);
|
||||
await store.init();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
store.close();
|
||||
await rm(rootDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });
|
||||
});
|
||||
|
||||
async function createTask(): Promise<string> {
|
||||
const task = await store.createTask({ description: "merge request test" });
|
||||
return task.id;
|
||||
}
|
||||
|
||||
it("creates merge-request and marker tables on fresh schema", () => {
|
||||
const db = store.getDatabase();
|
||||
const tableRows = db
|
||||
.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('merge_requests', 'completion_handoff_markers') ORDER BY name")
|
||||
.all() as Array<{ name: string }>;
|
||||
|
||||
expect(tableRows).toEqual([{ name: "completion_handoff_markers" }, { name: "merge_requests" }]);
|
||||
expect(db.getSchemaVersion()).toBe(100);
|
||||
});
|
||||
|
||||
it("upserts merge request records", async () => {
|
||||
const taskId = await createTask();
|
||||
const created = store.upsertMergeRequestRecord(taskId, {
|
||||
state: "queued",
|
||||
now: "2026-05-30T00:00:00.000Z",
|
||||
});
|
||||
expect(created).toMatchObject({ taskId, state: "queued", attemptCount: 0, lastError: null });
|
||||
|
||||
const updated = store.upsertMergeRequestRecord(taskId, {
|
||||
state: "manual-required",
|
||||
now: "2026-05-30T00:00:01.000Z",
|
||||
attemptCount: 2,
|
||||
lastError: "waiting for user",
|
||||
});
|
||||
expect(updated).toMatchObject({ taskId, state: "manual-required", attemptCount: 2, lastError: "waiting for user" });
|
||||
});
|
||||
|
||||
it("supports valid merge-request transitions", async () => {
|
||||
const taskId = await createTask();
|
||||
store.upsertMergeRequestRecord(taskId, { state: "queued", now: "2026-05-30T00:00:00.000Z" });
|
||||
|
||||
expect(store.transitionMergeRequestState(taskId, "running", { now: "2026-05-30T00:00:01.000Z" }).state).toBe("running");
|
||||
expect(store.transitionMergeRequestState(taskId, "retrying", { now: "2026-05-30T00:00:02.000Z", attemptCount: 1 }).state).toBe("retrying");
|
||||
expect(store.transitionMergeRequestState(taskId, "queued", { now: "2026-05-30T00:00:03.000Z" }).state).toBe("queued");
|
||||
expect(store.transitionMergeRequestState(taskId, "running", { now: "2026-05-30T00:00:04.000Z" }).state).toBe("running");
|
||||
expect(store.transitionMergeRequestState(taskId, "succeeded", { now: "2026-05-30T00:00:05.000Z" }).state).toBe("succeeded");
|
||||
});
|
||||
|
||||
it("rejects invalid merge-request transitions", async () => {
|
||||
const taskId = await createTask();
|
||||
store.upsertMergeRequestRecord(taskId, { state: "queued" });
|
||||
|
||||
expect(() => store.transitionMergeRequestState(taskId, "succeeded")).toThrow(
|
||||
`Invalid merge request state transition for ${taskId}: queued -> succeeded`,
|
||||
);
|
||||
});
|
||||
|
||||
it("sets and clears completion handoff marker", async () => {
|
||||
const taskId = await createTask();
|
||||
const marker = store.setCompletionHandoffAcceptedMarker(taskId, {
|
||||
acceptedAt: "2026-05-30T00:00:00.000Z",
|
||||
source: "executor:fn_task_done",
|
||||
});
|
||||
expect(marker).toEqual({
|
||||
taskId,
|
||||
acceptedAt: "2026-05-30T00:00:00.000Z",
|
||||
source: "executor:fn_task_done",
|
||||
});
|
||||
|
||||
expect(store.getCompletionHandoffAcceptedMarker(taskId)).toEqual(marker);
|
||||
store.clearCompletionHandoffAcceptedMarker(taskId);
|
||||
expect(store.getCompletionHandoffAcceptedMarker(taskId)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -3318,7 +3318,7 @@ describe("MissionStore", () => {
|
||||
|
||||
describe("Loop State & Validator Run Schema (v31)", () => {
|
||||
it("schema version is 40 after migration", () => {
|
||||
expect(db.getSchemaVersion()).toBe(99);
|
||||
expect(db.getSchemaVersion()).toBe(100);
|
||||
});
|
||||
|
||||
it("mission_features table has loop state columns", () => {
|
||||
|
||||
@@ -584,7 +584,7 @@ describe("Run Audit", () => {
|
||||
});
|
||||
|
||||
it("schema version is bumped to 40", () => {
|
||||
expect(db.getSchemaVersion()).toBe(99);
|
||||
expect(db.getSchemaVersion()).toBe(100);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -42,7 +42,7 @@ describe("secrets schema migrations", () => {
|
||||
const version = db
|
||||
.prepare("SELECT value FROM __meta WHERE key = 'schemaVersion'")
|
||||
.get() as { value: string };
|
||||
expect(version.value).toBe("99");
|
||||
expect(version.value).toBe("100");
|
||||
} finally {
|
||||
db.close();
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
@@ -105,7 +105,7 @@ describe("secrets schema migrations", () => {
|
||||
const version = db
|
||||
.prepare("SELECT value FROM __meta WHERE key = 'schemaVersion'")
|
||||
.get() as { value: string };
|
||||
expect(version.value).toBe("99");
|
||||
expect(version.value).toBe("100");
|
||||
} finally {
|
||||
db.close();
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
@@ -155,7 +155,7 @@ describe("secrets schema migrations", () => {
|
||||
.prepare("SELECT value FROM __meta WHERE key = 'schemaVersion'")
|
||||
.get() as { value: string };
|
||||
|
||||
expect(projectVersion.value).toBe("99");
|
||||
expect(projectVersion.value).toBe("100");
|
||||
expect(centralVersion.value).toBe("13");
|
||||
} finally {
|
||||
projectDb.close();
|
||||
|
||||
@@ -56,6 +56,8 @@ describe("settings key parity", () => {
|
||||
expect(isProjectSettingsKey("remoteAccess")).toBe(false);
|
||||
expect(isProjectSettingsKey("researchSettings")).toBe(true);
|
||||
expect(isGlobalSettingsKey("researchGlobalDefaults")).toBe(true);
|
||||
expect(isProjectSettingsKey("mergeRequestContractShadowEnabled")).toBe(true);
|
||||
expect(isGlobalSettingsKey("mergeRequestContractShadowEnabled")).toBe(true);
|
||||
expect(isProjectSettingsKey("themeMode")).toBe(false);
|
||||
expect(isGlobalSettingsKey("remoteAccess")).toBe(true);
|
||||
expect(isGlobalSettingsKey("persistAgentToolOutput")).toBe(true);
|
||||
@@ -307,6 +309,7 @@ describe("settings key parity", () => {
|
||||
const overlap = (GLOBAL_SETTINGS_KEYS as readonly string[]).filter((key) => projectKeySet.has(key));
|
||||
expect(overlap).toEqual([
|
||||
"testMode",
|
||||
"mergeRequestContractShadowEnabled",
|
||||
"taskTokenBudget",
|
||||
"githubTrackingDefaultRepo",
|
||||
"worktrunk",
|
||||
|
||||
@@ -60,7 +60,7 @@ describe("TaskStore merge queue", () => {
|
||||
expect.arrayContaining(["idx_mergeQueue_lease_ready", "idx_mergeQueue_leaseExpiresAt"]),
|
||||
);
|
||||
|
||||
expect(store.getDatabase().getSchemaVersion()).toBe(99);
|
||||
expect(store.getDatabase().getSchemaVersion()).toBe(100);
|
||||
});
|
||||
|
||||
it("migrates a legacy v88 database and preserves task rows", async () => {
|
||||
|
||||
@@ -51,7 +51,7 @@ describe("TaskStore task documents", () => {
|
||||
|
||||
expect(tableNames.has("task_documents")).toBe(true);
|
||||
expect(tableNames.has("task_document_revisions")).toBe(true);
|
||||
expect(db.getSchemaVersion()).toBe(99);
|
||||
expect(db.getSchemaVersion()).toBe(100);
|
||||
|
||||
const index = db
|
||||
.prepare(
|
||||
|
||||
@@ -149,7 +149,7 @@ export function probeFts5(db: DatabaseSync): boolean {
|
||||
|
||||
// ── Schema Definition ────────────────────────────────────────────────
|
||||
|
||||
const SCHEMA_VERSION = 99;
|
||||
const SCHEMA_VERSION = 100;
|
||||
|
||||
function normalizeTaskComments(
|
||||
steeringComments: SteeringComment[] | undefined,
|
||||
@@ -545,6 +545,23 @@ CREATE TABLE IF NOT EXISTS mergeQueue (
|
||||
CREATE INDEX IF NOT EXISTS idx_mergeQueue_lease_ready ON mergeQueue(leasedBy, priority, enqueuedAt);
|
||||
CREATE INDEX IF NOT EXISTS idx_mergeQueue_leaseExpiresAt ON mergeQueue(leaseExpiresAt);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS merge_requests (
|
||||
taskId TEXT PRIMARY KEY REFERENCES tasks(id) ON DELETE CASCADE,
|
||||
state TEXT NOT NULL,
|
||||
createdAt TEXT NOT NULL,
|
||||
updatedAt TEXT NOT NULL,
|
||||
attemptCount INTEGER NOT NULL DEFAULT 0,
|
||||
lastError TEXT
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_merge_requests_state_updatedAt ON merge_requests(state, updatedAt);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS completion_handoff_markers (
|
||||
taskId TEXT PRIMARY KEY REFERENCES tasks(id) ON DELETE CASCADE,
|
||||
acceptedAt TEXT NOT NULL,
|
||||
source TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_completion_handoff_markers_acceptedAt ON completion_handoff_markers(acceptedAt);
|
||||
|
||||
-- Task documents (key-value store per task with revision tracking)
|
||||
CREATE TABLE IF NOT EXISTS task_documents (
|
||||
id TEXT PRIMARY KEY,
|
||||
@@ -3737,6 +3754,36 @@ export class Database {
|
||||
});
|
||||
}
|
||||
|
||||
if (version < 100) {
|
||||
this.applyMigration(100, () => {
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS merge_requests (
|
||||
taskId TEXT PRIMARY KEY REFERENCES tasks(id) ON DELETE CASCADE,
|
||||
state TEXT NOT NULL,
|
||||
createdAt TEXT NOT NULL,
|
||||
updatedAt TEXT NOT NULL,
|
||||
attemptCount INTEGER NOT NULL DEFAULT 0,
|
||||
lastError TEXT
|
||||
)
|
||||
`);
|
||||
this.db.exec(`
|
||||
CREATE INDEX IF NOT EXISTS idx_merge_requests_state_updatedAt
|
||||
ON merge_requests(state, updatedAt)
|
||||
`);
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS completion_handoff_markers (
|
||||
taskId TEXT PRIMARY KEY REFERENCES tasks(id) ON DELETE CASCADE,
|
||||
acceptedAt TEXT NOT NULL,
|
||||
source TEXT NOT NULL
|
||||
)
|
||||
`);
|
||||
this.db.exec(`
|
||||
CREATE INDEX IF NOT EXISTS idx_completion_handoff_markers_acceptedAt
|
||||
ON completion_handoff_markers(acceptedAt)
|
||||
`);
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
export { COLUMNS, DEFAULT_COLUMN, isColumn, normalizeColumn, COLUMN_LABELS, COLUMN_DESCRIPTIONS, VALID_TRANSITIONS, DEFAULT_SETTINGS, DEFAULT_GLOBAL_SETTINGS, DEFAULT_PROJECT_SETTINGS, GLOBAL_SETTINGS_KEYS, PROJECT_SETTINGS_KEYS, isGlobalSettingsKey, isProjectSettingsKey, resolvePersistAgentThinkingLog, THINKING_LEVELS, THEME_MODES, COLOR_THEMES, WORKFLOW_STEP_TEMPLATES, AGENT_PERMISSIONS, PERMANENT_AGENT_ACTION_CATEGORIES, AGENT_PERMISSION_POLICY_ACTION_CATEGORIES, AGENT_PROVISIONING_APPROVAL_MODES, SANDBOX_PROVISIONING_APPROVAL_MODES, AGENT_PERMISSION_POLICY_PRESET_IDS, LEGACY_AGENT_PERMISSION_POLICY_ACTION_CATEGORY_ALIASES, APPROVAL_REQUEST_STATUSES, APPROVAL_REQUEST_AUDIT_EVENT_TYPES, normalizeApprovalRequestActionCategory, isValidApprovalRequestTransition, agentToConfigSnapshot, diffConfigSnapshots, isEphemeralAgent, hasAgentIdentity, CheckoutConflictError, DEFAULT_HEARTBEAT_PROCEDURE_PATH, getDefaultHeartbeatProcedurePath, EXECUTION_MODES, DEFAULT_EXECUTION_MODE, TASK_PRIORITIES, DEFAULT_TASK_PRIORITY, HIGH_FANOUT_BLOCKER_TODO_THRESHOLD, STALE_HIGH_FANOUT_BLOCKER_AGE_THRESHOLD_MS, DASHBOARD_USER_ID, normalizeMessageParticipant, validateMessageMetadata, validateDockerNodeConfig, sanitizeDockerNodeConfigForResponse, normalizeMergeIntegrationWorktreeMode, normalizeMergeAdvanceAutoSyncMode, MERGE_ADVANCE_AUTO_SYNC_MODES, normalizeMergeConflictStrategy, normalizeMergeStrategyOverlapBehavior, normalizePostMergeAuditMode, POST_MERGE_AUDIT_MODES, normalizeMergeAuditAutoRecovery, MERGE_AUDIT_AUTO_RECOVERY_MODES, normalizeMergerMode, MERGER_MODES, normalizeAutoRecovery, AUTO_RECOVERY_MODES, buildResearchDocumentKey, REPO_OVERRIDE_RE, SHARED_STATE_SNAPSHOT_VERSION } from "./types.js";
|
||||
export type { Column, IssueInfo, IssueState, TaskSourceIssue, PrInfo, PrConflictState, PrConflictDiagnostics, PrCheckState, PrCheckStatus, PrStatus, BranchGroup, BranchGroupCreateInput, BranchGroupUpdate, Task, TaskTokenUsage, TaskAttachment, TaskComment, TaskCommentInput, TaskDocument, TaskDocumentRevision, TaskDocumentCreateInput, TaskDocumentWithTask, TaskCreateInput, MeshReplicatedTaskCreatePayload, MeshReplicatedTaskApplyResult, TaskSource, SourceType, TaskDetail, RetrySummary, InboxTask, TodoList, TodoItem, TodoListCreateInput, TodoListUpdateInput, TodoItemCreateInput, TodoItemUpdateInput, TodoListWithItems, AgentLogEntry, AgentLogType, AgentRole, BoardConfig, DistributedTaskIdReserveInput, DistributedTaskIdReserveResult, DistributedTaskIdCommitInput, DistributedTaskIdCommitResult, DistributedTaskIdAbortInput, DistributedTaskIdAbortResult, DistributedTaskIdStateInput, DistributedTaskIdStateResult, AutostashOrphanRecord, AutostashOutcome, MergeDetails, MergeResult, MergeIntegrationWorktreeMode, MergeAdvanceAutoSyncMode, MergeConflictStrategy, CanonicalMergeConflictStrategy, MergeStrategyOverlapBehavior, PostMergeAuditMode, MergeAuditAutoRecoveryMode, MergerMode, MergerSettings, AutoRecoveryMode, AutoRecoveryFailureClass, AutoRecoverySettings, DirectMergeCommitStrategy, Settings, GlobalSettings, ProjectSettings, SecretsEnvConfig, WebSearchBackend, ResearchEnabledSources, ResearchGlobalDefaults, ResearchProjectLimits, ResearchProjectSettings, SandboxBackendName, SandboxFailureMode, SandboxPolicy, SandboxProjectSettings, EvalFollowUpPolicy, EvalProjectSettings, ResolvedEvalSettings, SettingsScope, DaemonTokenSettings, TaskStep, StepStatus, TaskLogEntry, RunMutationContext, ActivityLogEntry, ActivityEventType, ThinkingLevel, ThemeMode, ColorTheme, ExecutionMode, TaskPriority, MergeQueueEntry, MergeQueueEnqueueOptions, MergeQueueAcquireOptions, MergeQueueReleaseOutcome, HandoffEvidence, HandoffToReviewOptions, UnavailableNodePolicy, OwningNodeHandoffPolicy, PlanningQuestion, PlanningSummary, PlanningResponse, PlanningQuestionType, ArchivedTaskEntry, BatchStatusRequest, BatchStatusResponse, BatchStatusEntry, BatchStatusResult, GithubIssueAction, ModelPreset, WorkflowStep, WorkflowStepMode, WorkflowStepGateMode, WorkflowStepPhase, WorkflowStepInput, WorkflowStepResult, WorkflowStepTemplate, Agent, OrgTreeNode, AgentState, AgentDetail, AgentCreateInput, AgentUpdateInput, AgentApiKey, AgentApiKeyCreateResult, AgentCapability, AgentPromptTemplate, AgentPromptsConfig, AgentPermission, PermanentAgentActionCategory, PermanentAgentSensitiveActionCategory, PermanentAgentGatingContext, AgentPermissionPolicy, AgentPermissionPolicyRules, AgentPermissionPolicyActionCategory, AgentProvisioningApprovalMode, SandboxProvisioningApprovalMode, LegacyAgentPermissionPolicyActionCategory, ApprovalRequestActionCategoryInput, ApprovalRequestActionCategory, AgentPermissionPolicyDisposition, AgentPermissionPolicyPresetId, ApprovalRequestStatus, ApprovalRequestAuditEventType, ApprovalRequestActorSnapshot, ApprovalRequestTargetAction, ApprovalRequestAuditEvent, ApprovalRequest, ApprovalRequestCreateInput, ApprovalRequestDecisionInput, ApprovalRequestCompletionInput, ApprovalRequestListInput, TaskAssignSource, AgentAccessState, AgentHeartbeatConfig, AgentBudgetConfig, AgentBudgetStatus, InstructionsBundleConfig, MessageResponseMode, AgentHeartbeatEvent, AgentHeartbeatRun, BlockedStateSnapshot, HeartbeatInvocationSource, AgentTaskSession, AgentRating, AgentRatingSummary, AgentRatingInput, AgentConfigSnapshot, RevisionFieldDiff, AgentConfigRevision, AgentStats, ReflectionTrigger, ReflectionMetrics, AgentReflection, AgentPerformanceSummary, NtfyNotificationEvent, NotificationEvent, NotificationPayload, NotificationProviderConfig, CustomProvider, SteeringComment, ParticipantType, MessageType, Message, MessageCreateInput, MessageFilter, MessageMetadata, MessageReplyReference, Mailbox, CheckoutLease, CheckoutClaimPrecondition, TaskClaimRow, CentralClaimStore, RunAuditDomain, RunAuditEvent, RunAuditEventInput, RunAuditEventFilter, AgentMemoryInclusionMode, HeartbeatPromptTemplate, HeartbeatScopeDisciplineMode, WorktrunkSettings, WorktrunkOnFailure } from "./types.js";
|
||||
export { COLUMNS, DEFAULT_COLUMN, isColumn, normalizeColumn, COLUMN_LABELS, COLUMN_DESCRIPTIONS, VALID_TRANSITIONS, DEFAULT_SETTINGS, DEFAULT_GLOBAL_SETTINGS, DEFAULT_PROJECT_SETTINGS, GLOBAL_SETTINGS_KEYS, PROJECT_SETTINGS_KEYS, isGlobalSettingsKey, isProjectSettingsKey, isMergeRequestContractShadowEnabled, resolvePersistAgentThinkingLog, THINKING_LEVELS, THEME_MODES, COLOR_THEMES, WORKFLOW_STEP_TEMPLATES, AGENT_PERMISSIONS, PERMANENT_AGENT_ACTION_CATEGORIES, AGENT_PERMISSION_POLICY_ACTION_CATEGORIES, AGENT_PROVISIONING_APPROVAL_MODES, SANDBOX_PROVISIONING_APPROVAL_MODES, AGENT_PERMISSION_POLICY_PRESET_IDS, LEGACY_AGENT_PERMISSION_POLICY_ACTION_CATEGORY_ALIASES, APPROVAL_REQUEST_STATUSES, APPROVAL_REQUEST_AUDIT_EVENT_TYPES, normalizeApprovalRequestActionCategory, isValidApprovalRequestTransition, agentToConfigSnapshot, diffConfigSnapshots, isEphemeralAgent, hasAgentIdentity, CheckoutConflictError, DEFAULT_HEARTBEAT_PROCEDURE_PATH, getDefaultHeartbeatProcedurePath, EXECUTION_MODES, DEFAULT_EXECUTION_MODE, TASK_PRIORITIES, DEFAULT_TASK_PRIORITY, HIGH_FANOUT_BLOCKER_TODO_THRESHOLD, STALE_HIGH_FANOUT_BLOCKER_AGE_THRESHOLD_MS, DASHBOARD_USER_ID, normalizeMessageParticipant, validateMessageMetadata, validateDockerNodeConfig, sanitizeDockerNodeConfigForResponse, normalizeMergeIntegrationWorktreeMode, normalizeMergeAdvanceAutoSyncMode, MERGE_ADVANCE_AUTO_SYNC_MODES, normalizeMergeConflictStrategy, normalizeMergeStrategyOverlapBehavior, normalizePostMergeAuditMode, POST_MERGE_AUDIT_MODES, normalizeMergeAuditAutoRecovery, MERGE_AUDIT_AUTO_RECOVERY_MODES, normalizeMergerMode, MERGER_MODES, normalizeAutoRecovery, AUTO_RECOVERY_MODES, buildResearchDocumentKey, REPO_OVERRIDE_RE, SHARED_STATE_SNAPSHOT_VERSION } from "./types.js";
|
||||
export type { Column, IssueInfo, IssueState, TaskSourceIssue, PrInfo, PrConflictState, PrConflictDiagnostics, PrCheckState, PrCheckStatus, PrStatus, BranchGroup, BranchGroupCreateInput, BranchGroupUpdate, Task, TaskTokenUsage, TaskAttachment, TaskComment, TaskCommentInput, TaskDocument, TaskDocumentRevision, TaskDocumentCreateInput, TaskDocumentWithTask, TaskCreateInput, MeshReplicatedTaskCreatePayload, MeshReplicatedTaskApplyResult, TaskSource, SourceType, TaskDetail, RetrySummary, InboxTask, TodoList, TodoItem, TodoListCreateInput, TodoListUpdateInput, TodoItemCreateInput, TodoItemUpdateInput, TodoListWithItems, AgentLogEntry, AgentLogType, AgentRole, BoardConfig, DistributedTaskIdReserveInput, DistributedTaskIdReserveResult, DistributedTaskIdCommitInput, DistributedTaskIdCommitResult, DistributedTaskIdAbortInput, DistributedTaskIdAbortResult, DistributedTaskIdStateInput, DistributedTaskIdStateResult, AutostashOrphanRecord, AutostashOutcome, MergeDetails, MergeResult, MergeIntegrationWorktreeMode, MergeAdvanceAutoSyncMode, MergeConflictStrategy, CanonicalMergeConflictStrategy, MergeStrategyOverlapBehavior, PostMergeAuditMode, MergeAuditAutoRecoveryMode, MergerMode, MergerSettings, AutoRecoveryMode, AutoRecoveryFailureClass, AutoRecoverySettings, DirectMergeCommitStrategy, Settings, GlobalSettings, ProjectSettings, SecretsEnvConfig, WebSearchBackend, ResearchEnabledSources, ResearchGlobalDefaults, ResearchProjectLimits, ResearchProjectSettings, SandboxBackendName, SandboxFailureMode, SandboxPolicy, SandboxProjectSettings, EvalFollowUpPolicy, EvalProjectSettings, ResolvedEvalSettings, SettingsScope, DaemonTokenSettings, TaskStep, StepStatus, TaskLogEntry, RunMutationContext, ActivityLogEntry, ActivityEventType, ThinkingLevel, ThemeMode, ColorTheme, ExecutionMode, TaskPriority, MergeQueueEntry, MergeQueueEnqueueOptions, MergeQueueAcquireOptions, MergeQueueReleaseOutcome, MergeRequestState, MergeRequestRecord, CompletionHandoffMarker, HandoffEvidence, HandoffToReviewOptions, UnavailableNodePolicy, OwningNodeHandoffPolicy, PlanningQuestion, PlanningSummary, PlanningResponse, PlanningQuestionType, ArchivedTaskEntry, BatchStatusRequest, BatchStatusResponse, BatchStatusEntry, BatchStatusResult, GithubIssueAction, ModelPreset, WorkflowStep, WorkflowStepMode, WorkflowStepGateMode, WorkflowStepPhase, WorkflowStepInput, WorkflowStepResult, WorkflowStepTemplate, Agent, OrgTreeNode, AgentState, AgentDetail, AgentCreateInput, AgentUpdateInput, AgentApiKey, AgentApiKeyCreateResult, AgentCapability, AgentPromptTemplate, AgentPromptsConfig, AgentPermission, PermanentAgentActionCategory, PermanentAgentSensitiveActionCategory, PermanentAgentGatingContext, AgentPermissionPolicy, AgentPermissionPolicyRules, AgentPermissionPolicyActionCategory, AgentProvisioningApprovalMode, SandboxProvisioningApprovalMode, LegacyAgentPermissionPolicyActionCategory, ApprovalRequestActionCategoryInput, ApprovalRequestActionCategory, AgentPermissionPolicyDisposition, AgentPermissionPolicyPresetId, ApprovalRequestStatus, ApprovalRequestAuditEventType, ApprovalRequestActorSnapshot, ApprovalRequestTargetAction, ApprovalRequestAuditEvent, ApprovalRequest, ApprovalRequestCreateInput, ApprovalRequestDecisionInput, ApprovalRequestCompletionInput, ApprovalRequestListInput, TaskAssignSource, AgentAccessState, AgentHeartbeatConfig, AgentBudgetConfig, AgentBudgetStatus, InstructionsBundleConfig, MessageResponseMode, AgentHeartbeatEvent, AgentHeartbeatRun, BlockedStateSnapshot, HeartbeatInvocationSource, AgentTaskSession, AgentRating, AgentRatingSummary, AgentRatingInput, AgentConfigSnapshot, RevisionFieldDiff, AgentConfigRevision, AgentStats, ReflectionTrigger, ReflectionMetrics, AgentReflection, AgentPerformanceSummary, NtfyNotificationEvent, NotificationEvent, NotificationPayload, NotificationProviderConfig, CustomProvider, SteeringComment, ParticipantType, MessageType, Message, MessageCreateInput, MessageFilter, MessageMetadata, MessageReplyReference, Mailbox, CheckoutLease, CheckoutClaimPrecondition, TaskClaimRow, CentralClaimStore, RunAuditDomain, RunAuditEvent, RunAuditEventInput, RunAuditEventFilter, AgentMemoryInclusionMode, HeartbeatPromptTemplate, HeartbeatScopeDisciplineMode, WorktrunkSettings, WorktrunkOnFailure } from "./types.js";
|
||||
export { AGENT_VALID_TRANSITIONS, DUPLICATE_OF_METADATA_KEY } from "./types.js";
|
||||
export { customProviderRegistryKey } from "./custom-provider-key.js";
|
||||
export { MOCK_PROVIDER_ID } from "./mock-provider-constants.js";
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import type { GlobalSettings, ProjectSettings, Settings } from "./types.js";
|
||||
|
||||
export interface MergeRequestContractShadowSettingsSource {
|
||||
mergeRequestContractShadowEnabled?: boolean;
|
||||
}
|
||||
|
||||
type CompleteSettings<T> = { [K in keyof Required<T>]: Required<T>[K] | undefined };
|
||||
|
||||
/**
|
||||
@@ -18,6 +22,7 @@ export const DEFAULT_GLOBAL_SETTINGS = {
|
||||
defaultProvider: undefined,
|
||||
defaultModelId: undefined,
|
||||
testMode: undefined,
|
||||
mergeRequestContractShadowEnabled: false,
|
||||
fallbackProvider: undefined,
|
||||
fallbackModelId: undefined,
|
||||
defaultThinkingLevel: undefined,
|
||||
@@ -195,6 +200,7 @@ export const DEFAULT_PROJECT_SETTINGS = {
|
||||
overlapIgnorePaths: [],
|
||||
autoMerge: true,
|
||||
testMode: undefined,
|
||||
mergeRequestContractShadowEnabled: false,
|
||||
mergeStrategy: "direct",
|
||||
directMergeCommitStrategy: "always-squash",
|
||||
mergeIntegrationWorktree: "reuse-task-worktree",
|
||||
@@ -474,6 +480,30 @@ export function isGlobalOnlySettingsKey(key: string): key is keyof GlobalSetting
|
||||
return isGlobalSettingsKey(key) && !isProjectSettingsKey(key);
|
||||
}
|
||||
|
||||
export function isMergeRequestContractShadowEnabled(
|
||||
sources:
|
||||
| {
|
||||
project?: MergeRequestContractShadowSettingsSource;
|
||||
global?: MergeRequestContractShadowSettingsSource;
|
||||
}
|
||||
| MergeRequestContractShadowSettingsSource
|
||||
| undefined,
|
||||
): boolean {
|
||||
if (!sources) return false;
|
||||
|
||||
const scoped = sources as {
|
||||
project?: MergeRequestContractShadowSettingsSource;
|
||||
global?: MergeRequestContractShadowSettingsSource;
|
||||
};
|
||||
if (typeof scoped.project !== "undefined" || typeof scoped.global !== "undefined") {
|
||||
const projectValue = scoped.project?.mergeRequestContractShadowEnabled;
|
||||
if (typeof projectValue === "boolean") return projectValue;
|
||||
return scoped.global?.mergeRequestContractShadowEnabled === true;
|
||||
}
|
||||
|
||||
return (sources as MergeRequestContractShadowSettingsSource).mergeRequestContractShadowEnabled === true;
|
||||
}
|
||||
|
||||
export function resolvePersistAgentThinkingLog(
|
||||
settings: Partial<GlobalSettings> | undefined,
|
||||
opts: { ephemeral: boolean },
|
||||
|
||||
@@ -3,7 +3,7 @@ import { randomUUID } from "node:crypto";
|
||||
import { mkdir, readdir, readFile, writeFile, rename, unlink } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { existsSync, watch, type FSWatcher } from "node:fs";
|
||||
import type { Task, TaskDetail, TaskCreateInput, TaskAttachment, AgentLogEntry, BoardConfig, Column, CheckoutClaimPrecondition, MergeResult, Settings, GlobalSettings, ProjectSettings, ActivityLogEntry, ActivityEventType, TaskDocument, TaskDocumentRevision, TaskDocumentCreateInput, TaskDocumentWithTask, InboxTask, TaskLogEntry, RunMutationContext, RunAuditEvent, RunAuditEventInput, RunAuditEventFilter, ArchivedTaskEntry, ArchiveAgentLogMode, TaskPriority, SourceType, WorkflowStepTemplate, Agent, AutostashOrphanRecord, TaskCommitAssociation, TaskCommitAssociationMatchSource, TaskCommitAssociationConfidence, GithubIssueAction, MergeQueueEntry, MergeQueueEnqueueOptions, MergeQueueAcquireOptions, MergeQueueReleaseOutcome, HandoffToReviewOptions, GoalCitation, GoalCitationFilter, GoalCitationInput, GoalCitationSurface, BranchGroup, BranchGroupCreateInput, BranchGroupUpdate } from "./types.js";
|
||||
import type { Task, TaskDetail, TaskCreateInput, TaskAttachment, AgentLogEntry, BoardConfig, Column, CheckoutClaimPrecondition, MergeResult, Settings, GlobalSettings, ProjectSettings, ActivityLogEntry, ActivityEventType, TaskDocument, TaskDocumentRevision, TaskDocumentCreateInput, TaskDocumentWithTask, InboxTask, TaskLogEntry, RunMutationContext, RunAuditEvent, RunAuditEventInput, RunAuditEventFilter, ArchivedTaskEntry, ArchiveAgentLogMode, TaskPriority, SourceType, WorkflowStepTemplate, Agent, AutostashOrphanRecord, TaskCommitAssociation, TaskCommitAssociationMatchSource, TaskCommitAssociationConfidence, GithubIssueAction, MergeQueueEntry, MergeQueueEnqueueOptions, MergeQueueAcquireOptions, MergeQueueReleaseOutcome, HandoffToReviewOptions, GoalCitation, GoalCitationFilter, GoalCitationInput, GoalCitationSurface, BranchGroup, BranchGroupCreateInput, BranchGroupUpdate, MergeRequestRecord, MergeRequestState, CompletionHandoffMarker } from "./types.js";
|
||||
import { createActivityLogSnapshot, createRunAuditSnapshot, createTaskMetadataSnapshot, toTaskMetadataRecord, validateSnapshotEnvelope, type ActivityLogSnapshot, type RunAuditSnapshot, type TaskMetadataSnapshot } from "./shared-mesh-state.js";
|
||||
import { VALID_TRANSITIONS, DEFAULT_SETTINGS, isGlobalOnlySettingsKey, WORKFLOW_STEP_TEMPLATES, validateDocumentKey } from "./types.js";
|
||||
import { DEFAULT_PROJECT_SETTINGS } from "./settings-schema.js";
|
||||
@@ -309,6 +309,21 @@ interface MergeQueueRow {
|
||||
lastError: string | null;
|
||||
}
|
||||
|
||||
interface MergeRequestRow {
|
||||
taskId: string;
|
||||
state: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
attemptCount: number;
|
||||
lastError: string | null;
|
||||
}
|
||||
|
||||
interface CompletionHandoffMarkerRow {
|
||||
taskId: string;
|
||||
acceptedAt: string;
|
||||
source: string;
|
||||
}
|
||||
|
||||
/** Database row shape for the config table. */
|
||||
interface ConfigRow {
|
||||
nextId: number;
|
||||
@@ -6518,6 +6533,178 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
|
||||
};
|
||||
}
|
||||
|
||||
private normalizeMergeRequestState(value: string): MergeRequestState {
|
||||
switch (value) {
|
||||
case "queued":
|
||||
case "running":
|
||||
case "retrying":
|
||||
case "succeeded":
|
||||
case "exhausted":
|
||||
case "cancelled":
|
||||
case "manual-required":
|
||||
return value;
|
||||
default:
|
||||
return "queued";
|
||||
}
|
||||
}
|
||||
|
||||
private rowToMergeRequestRecord(row: MergeRequestRow): MergeRequestRecord {
|
||||
return {
|
||||
taskId: row.taskId,
|
||||
state: this.normalizeMergeRequestState(row.state),
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
attemptCount: row.attemptCount,
|
||||
lastError: row.lastError,
|
||||
};
|
||||
}
|
||||
|
||||
private rowToCompletionHandoffMarker(row: CompletionHandoffMarkerRow): CompletionHandoffMarker {
|
||||
return {
|
||||
taskId: row.taskId,
|
||||
acceptedAt: row.acceptedAt,
|
||||
source: row.source,
|
||||
};
|
||||
}
|
||||
|
||||
private isValidMergeRequestTransition(from: MergeRequestState, to: MergeRequestState): boolean {
|
||||
if (from === to) return true;
|
||||
const allowed: Record<MergeRequestState, ReadonlySet<MergeRequestState>> = {
|
||||
queued: new Set(["running", "cancelled"]),
|
||||
running: new Set(["retrying", "succeeded", "exhausted", "cancelled"]),
|
||||
retrying: new Set(["queued", "cancelled", "exhausted"]),
|
||||
succeeded: new Set([]),
|
||||
exhausted: new Set([]),
|
||||
cancelled: new Set([]),
|
||||
"manual-required": new Set(["succeeded", "cancelled"]),
|
||||
};
|
||||
return allowed[from].has(to);
|
||||
}
|
||||
|
||||
upsertMergeRequestRecord(
|
||||
taskId: string,
|
||||
input: { state: MergeRequestState; now?: string; attemptCount?: number; lastError?: string | null },
|
||||
): MergeRequestRecord {
|
||||
return this.db.transactionImmediate(() => {
|
||||
const now = input.now ?? new Date().toISOString();
|
||||
this.db.prepare(`
|
||||
INSERT INTO merge_requests (taskId, state, createdAt, updatedAt, attemptCount, lastError)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(taskId) DO UPDATE SET
|
||||
state = excluded.state,
|
||||
updatedAt = excluded.updatedAt,
|
||||
attemptCount = excluded.attemptCount,
|
||||
lastError = excluded.lastError
|
||||
`).run(taskId, input.state, now, now, input.attemptCount ?? 0, input.lastError ?? null);
|
||||
|
||||
const row = this.db.prepare("SELECT * FROM merge_requests WHERE taskId = ?").get(taskId) as MergeRequestRow | undefined;
|
||||
if (!row) throw new Error(`Failed to upsert merge request for ${taskId}`);
|
||||
|
||||
this.insertRunAuditEventRow({
|
||||
taskId,
|
||||
domain: "database",
|
||||
mutationType: "mergeRequest:upsert",
|
||||
target: taskId,
|
||||
metadata: { taskId, state: row.state, attemptCount: row.attemptCount, lastError: row.lastError },
|
||||
});
|
||||
|
||||
return this.rowToMergeRequestRecord(row);
|
||||
});
|
||||
}
|
||||
|
||||
transitionMergeRequestState(
|
||||
taskId: string,
|
||||
toState: MergeRequestState,
|
||||
opts: { now?: string; attemptCount?: number; lastError?: string | null } = {},
|
||||
): MergeRequestRecord {
|
||||
return this.db.transactionImmediate(() => {
|
||||
const now = opts.now ?? new Date().toISOString();
|
||||
const existing = this.db.prepare("SELECT * FROM merge_requests WHERE taskId = ?").get(taskId) as MergeRequestRow | undefined;
|
||||
if (!existing) {
|
||||
throw new Error(`Merge request record not found for ${taskId}`);
|
||||
}
|
||||
const fromState = this.normalizeMergeRequestState(existing.state);
|
||||
if (!this.isValidMergeRequestTransition(fromState, toState)) {
|
||||
throw new Error(`Invalid merge request state transition for ${taskId}: ${fromState} -> ${toState}`);
|
||||
}
|
||||
|
||||
this.db.prepare(`
|
||||
UPDATE merge_requests
|
||||
SET state = ?,
|
||||
updatedAt = ?,
|
||||
attemptCount = ?,
|
||||
lastError = ?
|
||||
WHERE taskId = ?
|
||||
`).run(toState, now, opts.attemptCount ?? existing.attemptCount, opts.lastError ?? existing.lastError, taskId);
|
||||
|
||||
const updated = this.db.prepare("SELECT * FROM merge_requests WHERE taskId = ?").get(taskId) as MergeRequestRow | undefined;
|
||||
if (!updated) throw new Error(`Merge request record disappeared for ${taskId}`);
|
||||
|
||||
this.insertRunAuditEventRow({
|
||||
taskId,
|
||||
domain: "database",
|
||||
mutationType: "mergeRequest:transition",
|
||||
target: taskId,
|
||||
metadata: { taskId, fromState, toState, attemptCount: updated.attemptCount, lastError: updated.lastError },
|
||||
});
|
||||
return this.rowToMergeRequestRecord(updated);
|
||||
});
|
||||
}
|
||||
|
||||
getMergeRequestRecord(taskId: string): MergeRequestRecord | null {
|
||||
const row = this.db.prepare("SELECT * FROM merge_requests WHERE taskId = ?").get(taskId) as MergeRequestRow | undefined;
|
||||
return row ? this.rowToMergeRequestRecord(row) : null;
|
||||
}
|
||||
|
||||
setCompletionHandoffAcceptedMarker(
|
||||
taskId: string,
|
||||
opts: { source: string; acceptedAt?: string },
|
||||
): CompletionHandoffMarker {
|
||||
return this.db.transactionImmediate(() => {
|
||||
const acceptedAt = opts.acceptedAt ?? new Date().toISOString();
|
||||
this.db.prepare(`
|
||||
INSERT INTO completion_handoff_markers (taskId, acceptedAt, source)
|
||||
VALUES (?, ?, ?)
|
||||
ON CONFLICT(taskId) DO UPDATE SET
|
||||
acceptedAt = excluded.acceptedAt,
|
||||
source = excluded.source
|
||||
`).run(taskId, acceptedAt, opts.source);
|
||||
|
||||
const row = this.db.prepare("SELECT * FROM completion_handoff_markers WHERE taskId = ?").get(taskId) as CompletionHandoffMarkerRow | undefined;
|
||||
if (!row) throw new Error(`Failed to set completion handoff marker for ${taskId}`);
|
||||
|
||||
this.insertRunAuditEventRow({
|
||||
taskId,
|
||||
domain: "database",
|
||||
mutationType: "task:completion-handoff-accepted",
|
||||
target: taskId,
|
||||
metadata: { taskId, acceptedAt: row.acceptedAt, source: row.source },
|
||||
});
|
||||
|
||||
return this.rowToCompletionHandoffMarker(row);
|
||||
});
|
||||
}
|
||||
|
||||
clearCompletionHandoffAcceptedMarker(taskId: string): void {
|
||||
this.db.transactionImmediate(() => {
|
||||
const existing = this.db.prepare("SELECT * FROM completion_handoff_markers WHERE taskId = ?").get(taskId) as CompletionHandoffMarkerRow | undefined;
|
||||
if (!existing) return;
|
||||
this.db.prepare("DELETE FROM completion_handoff_markers WHERE taskId = ?").run(taskId);
|
||||
this.insertRunAuditEventRow({
|
||||
taskId,
|
||||
domain: "database",
|
||||
mutationType: "task:completion-handoff-cleared",
|
||||
target: taskId,
|
||||
metadata: { taskId, acceptedAt: existing.acceptedAt, source: existing.source },
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
getCompletionHandoffAcceptedMarker(taskId: string): CompletionHandoffMarker | null {
|
||||
const row = this.db.prepare("SELECT * FROM completion_handoff_markers WHERE taskId = ?").get(taskId) as CompletionHandoffMarkerRow | undefined;
|
||||
return row ? this.rowToCompletionHandoffMarker(row) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a database row to a RunAuditEvent object.
|
||||
*/
|
||||
|
||||
@@ -38,6 +38,18 @@ export type TaskPriority = (typeof TASK_PRIORITIES)[number];
|
||||
*/
|
||||
export const DEFAULT_TASK_PRIORITY: TaskPriority = "normal";
|
||||
|
||||
export const MERGE_REQUEST_STATES = [
|
||||
"queued",
|
||||
"running",
|
||||
"retrying",
|
||||
"succeeded",
|
||||
"exhausted",
|
||||
"cancelled",
|
||||
"manual-required",
|
||||
] as const;
|
||||
|
||||
export type MergeRequestState = (typeof MERGE_REQUEST_STATES)[number];
|
||||
|
||||
export interface MergeQueueEntry {
|
||||
taskId: string;
|
||||
enqueuedAt: string;
|
||||
@@ -49,6 +61,21 @@ export interface MergeQueueEntry {
|
||||
lastError: string | null;
|
||||
}
|
||||
|
||||
export interface MergeRequestRecord {
|
||||
taskId: string;
|
||||
state: MergeRequestState;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
attemptCount: number;
|
||||
lastError: string | null;
|
||||
}
|
||||
|
||||
export interface CompletionHandoffMarker {
|
||||
taskId: string;
|
||||
acceptedAt: string;
|
||||
source: string;
|
||||
}
|
||||
|
||||
export interface MergeQueueEnqueueOptions {
|
||||
priority?: TaskPriority;
|
||||
now?: string;
|
||||
@@ -2405,6 +2432,11 @@ export interface GlobalSettings {
|
||||
* of per-task or per-lane overrides. No network calls, zero token cost.
|
||||
* Project `testMode` takes precedence over the global value. */
|
||||
testMode?: boolean;
|
||||
/** Phase-1 FN-5741 write-only shadow seam toggle.
|
||||
* When true, executor/self-healing/merger persist additive merge-request contract
|
||||
* records and completion-handoff markers without changing merge authority.
|
||||
* Project value (if set) takes precedence over this global value. Default: false. */
|
||||
mergeRequestContractShadowEnabled?: boolean;
|
||||
/** Fallback AI model provider used when the primary default model fails due to
|
||||
* transient provider-side issues such as rate limits or overloaded capacity.
|
||||
* Must be set together with `fallbackModelId`. */
|
||||
@@ -2894,6 +2926,10 @@ export interface ProjectSettings {
|
||||
/** When true, force every AI lane onto the deterministic mock provider regardless
|
||||
* of per-task or per-lane overrides. No network calls, zero token cost. */
|
||||
testMode?: boolean;
|
||||
/** Phase-1 FN-5741 write-only shadow seam toggle.
|
||||
* Overrides global `mergeRequestContractShadowEnabled` when defined.
|
||||
* Default: false. */
|
||||
mergeRequestContractShadowEnabled?: boolean;
|
||||
/** How completed in-review tasks should be finalized when autoMerge is enabled.
|
||||
* - "direct": preserve the existing local squash-merge flow into the current branch
|
||||
* - "pull-request": create or reuse a GitHub PR and wait for GitHub-side checks/reviews
|
||||
@@ -3680,6 +3716,7 @@ export {
|
||||
isGlobalOnlySettingsKey,
|
||||
isGlobalSettingsKey,
|
||||
isProjectSettingsKey,
|
||||
isMergeRequestContractShadowEnabled,
|
||||
resolvePersistAgentThinkingLog,
|
||||
} from "./settings-schema.js";
|
||||
|
||||
|
||||
Reference in New Issue
Block a user