Skip to content

Commit a8b2deb

Browse files
feat: warn on SQLite schema changes (#1252)
1 parent a2641b2 commit a8b2deb

9 files changed

Lines changed: 245 additions & 1 deletion

‎src/clawsweeper-change-detection.ts‎

Lines changed: 109 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
1-
import type { ConfigSurfaceChange, DataModelChange, ItemContext } from "./clawsweeper-types.js";
1+
import type {
2+
ConfigSurfaceChange,
3+
DataModelChange,
4+
ItemContext,
5+
SqliteSchemaChange,
6+
} from "./clawsweeper-types.js";
27

38
function asRecord(value: unknown): Record<string, unknown> {
49
return value && typeof value === "object" ? (value as Record<string, unknown>) : {};
@@ -131,6 +136,109 @@ export function dataModelChangeFromPullFilesForTest(options: {
131136
return dataModelChangeFromContext(options.repo ?? "openclaw/openclaw", context);
132137
}
133138

139+
export function sqliteSchemaChangeFromContext(
140+
repo: string,
141+
context: ItemContext,
142+
): SqliteSchemaChange {
143+
if (repo !== "openclaw/openclaw") {
144+
return { change: false, files: [] };
145+
}
146+
147+
const files = new Set<string>();
148+
for (const entry of context.pullFiles ?? []) {
149+
const file = asRecord(entry);
150+
const path = typeof file.filename === "string" ? file.filename.trim() : "";
151+
const previousPath =
152+
typeof file.previous_filename === "string" ? file.previous_filename.trim() : "";
153+
const productionPaths = [path, previousPath].filter(isProductionSourcePath);
154+
if (productionPaths.length === 0) continue;
155+
156+
const patch = typeof file.patch === "string" ? file.patch : null;
157+
const likelySchemaPath = productionPaths.find(isLikelySqliteSchemaPath);
158+
if (patch === null) {
159+
if (likelySchemaPath) files.add(path || likelySchemaPath);
160+
continue;
161+
}
162+
163+
const changedLines = changedPatchLines(patch);
164+
if (
165+
sqliteSchemaPatchChangesTables(patch, changedLines) ||
166+
(likelySchemaPath &&
167+
(configSurfacePatchIsTruncated(patch) || changedLines.some(sqliteSchemaDeclarationLine)))
168+
) {
169+
files.add(path || likelySchemaPath || productionPaths[0]!);
170+
}
171+
}
172+
173+
return { change: files.size > 0, files: [...files].sort() };
174+
}
175+
176+
export function sqliteSchemaChangeFromPullFilesForTest(options: {
177+
repo?: string;
178+
pullFiles?: unknown[];
179+
pullFilesTruncated?: boolean;
180+
}): SqliteSchemaChange {
181+
const counts: ItemContext["counts"] = { comments: 0, timeline: 0 };
182+
if (options.pullFilesTruncated !== undefined)
183+
counts.pullFilesTruncated = options.pullFilesTruncated;
184+
const context: ItemContext = {
185+
issue: {},
186+
comments: [],
187+
timeline: [],
188+
counts,
189+
};
190+
if (options.pullFiles !== undefined) context.pullFiles = options.pullFiles;
191+
return sqliteSchemaChangeFromContext(options.repo ?? "openclaw/openclaw", context);
192+
}
193+
194+
function isProductionSourcePath(path: string): boolean {
195+
return Boolean(
196+
path &&
197+
!isDocsPath(path) &&
198+
!/(^|\/)(?:__tests__|examples?|fixtures?|test|tests)(?:\/|$)/i.test(path) &&
199+
!/\.(?:spec|test)\.[^/]+$/i.test(path),
200+
);
201+
}
202+
203+
function isLikelySqliteSchemaPath(path: string): boolean {
204+
return /(?:^|\/)(?:migrations?|sqlite)(?:\/|[-_.])|(?:sqlite|memory|database|db)[-_.]?schema|schema[-_.]?sqlite|sqlite[-_.]?store|\.sql$/i.test(
205+
path,
206+
);
207+
}
208+
209+
function sqliteSchemaPatchChangesTables(patch: string, changedLines: readonly string[]): boolean {
210+
const changedText = changedLines.join("\n");
211+
if (
212+
/\b(?:CREATE|ALTER|DROP)\s+(?:VIRTUAL\s+)?TABLE\b|\bRENAME\s+TABLE\b|\bsqliteTable\s*\(/i.test(
213+
changedText,
214+
)
215+
) {
216+
return true;
217+
}
218+
219+
const patchText = patch
220+
.split("\n")
221+
.filter((line) => !line.startsWith("@@") && !line.startsWith("+++") && !line.startsWith("---"))
222+
.map((line) => line.replace(/^[ +-]/, ""))
223+
.join("\n");
224+
return (
225+
/\b(?:CREATE|ALTER)\s+(?:VIRTUAL\s+)?TABLE\b|\bsqliteTable\s*\(/i.test(patchText) &&
226+
changedLines.some(sqliteSchemaDeclarationLine)
227+
);
228+
}
229+
230+
function sqliteSchemaDeclarationLine(line: string): boolean {
231+
const text = line.replace(/^[+-]/, "").trim();
232+
return (
233+
/\b(?:CREATE|ALTER|DROP)\s+(?:VIRTUAL\s+)?TABLE\b|\bRENAME\s+TABLE\b|\bsqliteTable\s*\(/i.test(
234+
text,
235+
) ||
236+
/^(?:[`"']?[A-Za-z_][\w$]*[`"']?\s+|[A-Za-z_$][\w$]*\s*:\s*)(?:BLOB|INTEGER|NULL|REAL|TEXT|ANY|blob|integer|numeric|real|text)\b/i.test(
237+
text,
238+
)
239+
);
240+
}
241+
134242
function isOpenClawConfigSurfacePath(path: string): boolean {
135243
return (
136244
/^src\/config\/(?:zod-schema[^/]*|types[^/]*|schema(?:[-.][^/]*)?)\.ts$/.test(path) ||

‎src/clawsweeper-orchestration-foundation.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -354,6 +354,35 @@ export function createReportOrchestrationFoundation(
354354
return `Persistent data-model change detected: ${surfaceText}${overflow}. ${proofLine}`;
355355
}
356356

357+
function renderSqliteSchemaWarningFromReport(markdown: string): string {
358+
if (
359+
frontMatterValue(markdown, "type") !== "pull_request" ||
360+
normalizeRepo(markdownRepository(markdown)) !== "openclaw/openclaw" ||
361+
(!frontMatterBoolean(markdown, "sqlite_schema_change") &&
362+
frontMatterStringArray(markdown, "sqlite_schema_files").length === 0)
363+
) {
364+
return "";
365+
}
366+
367+
const files = frontMatterStringArray(markdown, "sqlite_schema_files");
368+
const fileText = files.length
369+
? files
370+
.slice(0, 4)
371+
.map((file) => trustedCommentCodeSpan(file))
372+
.join(", ")
373+
: "an unidentified schema file";
374+
const overflow = files.length > 4 ? `, and ${files.length - 4} more` : "";
375+
const proofLine = dataModelUpgradeProofFromReport(markdown)
376+
? "Migration or upgrade compatibility proof is recorded, but maintainers should still confirm that the schema change is necessary."
377+
: "If the change is necessary, verify migration and upgrade compatibility against an existing database before merge.";
378+
return [
379+
"> [!WARNING]",
380+
"> **SQLite table change**",
381+
">",
382+
`> This PR modifies persisted SQLite tables in ${fileText}${overflow}. Prefer a design that avoids changing persisted SQLite tables. ${proofLine}`,
383+
].join("\n");
384+
}
385+
357386
function trustedCommentCodeSpan(value: string): string {
358387
const escaped = value
359388
.replace(/&/g, "&amp;")
@@ -529,6 +558,7 @@ export function createReportOrchestrationFoundation(
529558
shouldRenderOpenClawPrSurface,
530559
renderOpenClawPrSurfaceFromReport,
531560
renderDataModelWarningFromReport,
561+
renderSqliteSchemaWarningFromReport,
532562
trustedCommentCodeSpan,
533563
reviewMetricsFromReport,
534564
renderReviewMetricsDigest,

‎src/clawsweeper-report-comment-presentation.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ export function createReportCommentPresentation(
6161
realBehaviorProofBlocksMerge,
6262
renderCloseCommentFromReport,
6363
renderDataModelWarningFromReport,
64+
renderSqliteSchemaWarningFromReport,
6465
renderOpenClawPrSurfaceFromReport,
6566
renderReviewMetricsDigest,
6667
repairLoopPassModeFromReport,
@@ -198,6 +199,7 @@ export function createReportCommentPresentation(
198199
const lines = [`${verdictLine}${reviewFreshnessText(markdown)}`, ""];
199200
const prSurface = renderOpenClawPrSurfaceFromReport(markdown);
200201
const dataModelWarning = renderDataModelWarningFromReport(markdown);
202+
const sqliteSchemaWarning = renderSqliteSchemaWarningFromReport(markdown);
201203
const rootCauseClusterBlock = publicRootCauseClusterBlock(rootCauseCluster);
202204
const mantisSuggestion = isPullRequest
203205
? publicMantisRecommendationBlock(mantisRecommendation)
@@ -321,6 +323,7 @@ export function createReportCommentPresentation(
321323
});
322324
lines.push("# ClawSweeper review", "");
323325
appendHeadingSection(lines, "What this changes", changeSummaryLine);
326+
if (sqliteSchemaWarning) lines.push(sqliteSchemaWarning, "");
324327
if (regressionPublicLine) {
325328
appendHeadingSection(lines, "Regression provenance", regressionPublicLine);
326329
}

‎src/clawsweeper-report-document.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import {
22
configSurfaceChangeFromContext,
33
dataModelChangeFromContext,
4+
sqliteSchemaChangeFromContext,
45
} from "./clawsweeper-change-detection.js";
56
import { closeReasonText } from "./clawsweeper-close-reasons.js";
67
import { REVIEW_SECTIONS } from "./clawsweeper-policy.js";
@@ -581,6 +582,7 @@ export function createReportDocumentRendering(
581582
const pullFilesTruncated = Boolean(options.context.counts?.pullFilesTruncated);
582583
const configSurfaceChange = configSurfaceChangeFromContext(options.item.repo, options.context);
583584
const dataModelChange = dataModelChangeFromContext(options.item.repo, options.context);
585+
const sqliteSchemaChange = sqliteSchemaChangeFromContext(options.item.repo, options.context);
584586
const prSurfaceFiles = prSurfaceFilesFromContext(options.context);
585587
const reviewedPullStateDigest = reviewStructuralPullStateFromContext(options.context);
586588
const markdown = `---
@@ -719,6 +721,8 @@ config_surface_change: ${configSurfaceChange.change}
719721
config_surface_keys: ${jsonFrontMatterValue(configSurfaceChange.keys)}
720722
data_model_change: ${dataModelChange.change}
721723
data_model_surfaces: ${jsonFrontMatterValue(dataModelChange.surfaces)}
724+
sqlite_schema_change: ${sqliteSchemaChange.change}
725+
sqlite_schema_files: ${jsonFrontMatterValue(sqliteSchemaChange.files)}
722726
pr_surface_files: ${jsonFrontMatterValue(prSurfaceFiles)}
723727
pr_surface_files_truncated: ${pullFilesTruncated}
724728
item_category: ${options.decision.itemCategory}

‎src/clawsweeper-report-orchestration.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,7 @@ export function createReportOrchestration(dependencies: CreateReportOrchestratio
157157
prSurfaceFilesFromContext,
158158
renderOpenClawPrSurfaceFromReport,
159159
renderDataModelWarningFromReport,
160+
renderSqliteSchemaWarningFromReport,
160161
reviewMetricsFromReport,
161162
renderReviewMetricsDigest,
162163
labelSynchronization,
@@ -291,6 +292,7 @@ export function createReportOrchestration(dependencies: CreateReportOrchestratio
291292
pullHeadShaFromReport,
292293
realBehaviorProofBlocksMerge,
293294
renderDataModelWarningFromReport,
295+
renderSqliteSchemaWarningFromReport,
294296
renderOpenClawPrSurfaceFromReport,
295297
renderReviewMetricsDigest,
296298
repairLoopPassModeFromReport,

‎src/clawsweeper-report-rendering-dependencies.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,7 @@ export interface CreateReportRenderingDependencies {
156156
pullHeadShaFromReport: (markdown: string) => string | null;
157157
realBehaviorProofBlocksMerge: (markdown: string) => boolean;
158158
renderDataModelWarningFromReport: (markdown: string) => string;
159+
renderSqliteSchemaWarningFromReport: (markdown: string) => string;
159160
renderOpenClawPrSurfaceFromReport: (markdown: string) => string;
160161
renderReviewMetricsDigest: (metrics: readonly ReviewMetric[]) => string;
161162
repairLoopPassModeFromReport: (markdown: string) => "" | "autofix" | "automerge";

‎src/clawsweeper-runtime.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,7 @@ export { itemNumbersArg } from "./clawsweeper-args.js";
144144
export {
145145
configSurfaceChangeFromPullFilesForTest,
146146
dataModelChangeFromPullFilesForTest,
147+
sqliteSchemaChangeFromPullFilesForTest,
147148
} from "./clawsweeper-change-detection.js";
148149
export {
149150
prepareMediaProofArtifactsForTest,

‎src/clawsweeper-types.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1252,6 +1252,11 @@ export interface DataModelChange {
12521252
surfaces: string[];
12531253
}
12541254

1255+
export interface SqliteSchemaChange {
1256+
change: boolean;
1257+
files: string[];
1258+
}
1259+
12551260
export interface IssueAdvisoryLabelState {
12561261
type: string | undefined;
12571262
itemCategory: string | undefined;

‎test/pr-surface-policy.test.ts‎

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
dataModelChangeFromPullFilesForTest,
77
renderReviewCommentFromReport,
88
reviewAutomationMarkersFromReport,
9+
sqliteSchemaChangeFromPullFilesForTest,
910
} from "../dist/clawsweeper.js";
1011
import { reportFrontMatter } from "./helpers.ts";
1112

@@ -294,6 +295,95 @@ test("data model detector ignores query-only and non-semantic docs changes", ()
294295
assert.deepEqual(detection, { change: false, surfaces: [] });
295296
});
296297

298+
test("SQLite schema detector finds production table changes and ignores non-schema SQL", () => {
299+
const detection = sqliteSchemaChangeFromPullFilesForTest({
300+
pullFiles: [
301+
{
302+
filename: "packages/memory-host-sdk/src/host/memory-schema-base.ts",
303+
patch:
304+
"@@\n CREATE TABLE IF NOT EXISTS memory_index_chunks (\n id TEXT PRIMARY KEY,\n+ source_kind TEXT NOT NULL,\n );",
305+
},
306+
{
307+
filename: "src/transcripts/sqlite-schema.ts",
308+
patch:
309+
"@@\n+CREATE TABLE IF NOT EXISTS meeting_transcript_summaries (\n+ id TEXT PRIMARY KEY\n+);",
310+
},
311+
{
312+
filename: "src/memory/search.ts",
313+
patch: "@@\n+ return db.prepare('SELECT * FROM memory_index_chunks').all();",
314+
},
315+
{
316+
filename: "src/memory/manager-db.test.ts",
317+
patch: "@@\n+ db.exec('CREATE TABLE fixture_rows (id TEXT PRIMARY KEY)');",
318+
},
319+
{
320+
filename: "docs/storage.md",
321+
patch: "@@\n+CREATE TABLE example_rows (id TEXT PRIMARY KEY);",
322+
},
323+
],
324+
});
325+
326+
assert.deepEqual(detection, {
327+
change: true,
328+
files: [
329+
"packages/memory-host-sdk/src/host/memory-schema-base.ts",
330+
"src/transcripts/sqlite-schema.ts",
331+
],
332+
});
333+
});
334+
335+
test("SQLite schema warning is visible for table changes and absent otherwise", () => {
336+
const reportBody = `
337+
338+
## Summary
339+
340+
Keep this PR open for maintainer review.
341+
342+
## What This Changes
343+
344+
Adds a column to the persisted memory index.
345+
`;
346+
const warningComment = renderReviewCommentFromReport(
347+
`${reportFrontMatter({
348+
repository: "openclaw/openclaw",
349+
type: "pull_request",
350+
number: "74464",
351+
decision: "keep_open",
352+
close_reason: "none",
353+
work_candidate: "none",
354+
sqlite_schema_change: "true",
355+
sqlite_schema_files: JSON.stringify([
356+
"packages/memory-host-sdk/src/host/memory-schema-base.ts",
357+
]),
358+
})}${reportBody}`,
359+
"none",
360+
);
361+
const ordinaryComment = renderReviewCommentFromReport(
362+
`${reportFrontMatter({
363+
repository: "openclaw/openclaw",
364+
type: "pull_request",
365+
number: "74465",
366+
decision: "keep_open",
367+
close_reason: "none",
368+
work_candidate: "none",
369+
sqlite_schema_change: "false",
370+
sqlite_schema_files: JSON.stringify([]),
371+
})}${reportBody}`,
372+
"none",
373+
);
374+
375+
assert.match(warningComment, /> \[!WARNING\]/);
376+
assert.match(warningComment, /SQLite table change/);
377+
assert.match(warningComment, /`packages\/memory-host-sdk\/src\/host\/memory-schema-base\.ts`/);
378+
assert.match(warningComment, /Prefer a design that avoids changing persisted SQLite tables/);
379+
assert.ok(
380+
warningComment.indexOf("SQLite table change") <
381+
warningComment.indexOf("<summary><strong>Agent review details</strong></summary>"),
382+
);
383+
assert.doesNotMatch(ordinaryComment, /SQLite table change/);
384+
assert.doesNotMatch(ordinaryComment, /\[!WARNING\]/);
385+
});
386+
297387
test("data model detector flags path-hinted persisted field declarations", () => {
298388
const detection = dataModelChangeFromPullFilesForTest({
299389
pullFiles: [

0 commit comments

Comments
 (0)