pal-code 0.0.7 → 0.0.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/SYSTEM.md +3 -3
- package/bin/pal-code.js +37 -11
- package/package.json +11 -11
- package/packages/cli/README.md +2 -2
- package/packages/cli/src/commands/ext.ts +1 -1
- package/packages/cli/src/commands.ts +1 -1
- package/packages/cli/src/components/render-history.ts +2 -2
- package/packages/cli/src/config.ts +2 -2
- package/packages/cli/src/index.ts +8 -10
- package/packages/cli/src/overlays/key-input.ts +1 -1
- package/packages/cli/src/overlays/model-picker.ts +2 -2
- package/packages/cli/src/overlays/session-picker.ts +1 -1
- package/packages/cli/src/overlays/wizard.ts +1 -1
- package/packages/cli/src/state.ts +2 -2
- package/packages/cli/src/turn.ts +14 -9
- package/packages/cli/src/utils/permissions.ts +3 -3
- package/packages/cli/src/utils/format.test.ts +0 -167
- package/packages/core/src/agent/events.ts +0 -36
- package/packages/core/src/agent/fallback.test.ts +0 -99
- package/packages/core/src/agent/fallback.ts +0 -344
- package/packages/core/src/agent/index.ts +0 -35
- package/packages/core/src/agent/protocol.test.ts +0 -136
- package/packages/core/src/agent/resume-compaction.test.ts +0 -116
- package/packages/core/src/agent/roles.ts +0 -188
- package/packages/core/src/agent/run.test.ts +0 -207
- package/packages/core/src/agent/run.ts +0 -713
- package/packages/core/src/agent/scope.ts +0 -34
- package/packages/core/src/agent/todos.ts +0 -66
- package/packages/core/src/compaction.protocol.test.ts +0 -90
- package/packages/core/src/compaction.test.ts +0 -101
- package/packages/core/src/compaction.ts +0 -243
- package/packages/core/src/config.test.ts +0 -40
- package/packages/core/src/config.ts +0 -387
- package/packages/core/src/extensions.ts +0 -178
- package/packages/core/src/index.ts +0 -157
- package/packages/core/src/logger.ts +0 -54
- package/packages/core/src/provider/auth.ts +0 -153
- package/packages/core/src/provider/complete.ts +0 -63
- package/packages/core/src/provider/index.ts +0 -6
- package/packages/core/src/provider/openrouter.test.ts +0 -59
- package/packages/core/src/provider/openrouter.ts +0 -304
- package/packages/core/src/provider/pick-model.ts +0 -43
- package/packages/core/src/provider/registry.ts +0 -222
- package/packages/core/src/provider/types.ts +0 -61
- package/packages/core/src/repo-map.ts +0 -177
- package/packages/core/src/session/index.ts +0 -2
- package/packages/core/src/session/migration.test.ts +0 -104
- package/packages/core/src/session/store-v2-repair.test.ts +0 -209
- package/packages/core/src/session/store.test.ts +0 -235
- package/packages/core/src/session/store.ts +0 -677
- package/packages/core/src/session/types.ts +0 -72
- package/packages/core/src/snapshots.ts +0 -107
- package/packages/core/src/tools/definitions.ts +0 -365
- package/packages/core/src/tools/executor.test.ts +0 -122
- package/packages/core/src/tools/executor.ts +0 -1363
- package/packages/core/src/tools/index.ts +0 -5
- package/packages/core/src/tools/search.ts +0 -201
- package/scripts/postinstall.js +0 -121
- package/scripts/preinstall.js +0 -51
- package/scripts/sync-version.js +0 -35
|
@@ -1,177 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* repo-map — lightweight structural overview of source files.
|
|
3
|
-
* Extracts top-level declarations using @ast-grep/napi with regex fallback.
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
import {readFile, readdir} from 'fs/promises';
|
|
7
|
-
import {join, relative, extname} from 'path';
|
|
8
|
-
|
|
9
|
-
interface RepoMapEntry {
|
|
10
|
-
file: string;
|
|
11
|
-
declarations: string[];
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
// Patterns for top-level declarations (ast-grep pattern syntax)
|
|
15
|
-
const PATTERNS: Record<string, string[]> = {
|
|
16
|
-
typescript: [
|
|
17
|
-
'function $NAME($$$)',
|
|
18
|
-
'export function $NAME($$$)',
|
|
19
|
-
'class $NAME { $$$ }',
|
|
20
|
-
'export class $NAME { $$$ }',
|
|
21
|
-
'interface $NAME { $$$ }',
|
|
22
|
-
'export interface $NAME { $$$ }',
|
|
23
|
-
'type $NAME = $$$',
|
|
24
|
-
'export type $NAME = $$$',
|
|
25
|
-
'const $NAME = ($$$) => $$$',
|
|
26
|
-
'export const $NAME = ($$$) => $$$',
|
|
27
|
-
'export default function $NAME($$$)',
|
|
28
|
-
'enum $NAME { $$$ }',
|
|
29
|
-
'export enum $NAME { $$$ }',
|
|
30
|
-
],
|
|
31
|
-
javascript: [
|
|
32
|
-
'function $NAME($$$)',
|
|
33
|
-
'export function $NAME($$$)',
|
|
34
|
-
'class $NAME { $$$ }',
|
|
35
|
-
'export class $NAME { $$$ }',
|
|
36
|
-
'const $NAME = ($$$) => $$$',
|
|
37
|
-
'export const $NAME = ($$$) => $$$',
|
|
38
|
-
'export default function $NAME($$$)',
|
|
39
|
-
'module.exports = $EXPR',
|
|
40
|
-
],
|
|
41
|
-
};
|
|
42
|
-
|
|
43
|
-
const SCAN_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs']);
|
|
44
|
-
const IGNORE_DIRS = new Set([
|
|
45
|
-
'node_modules',
|
|
46
|
-
'.git',
|
|
47
|
-
'dist',
|
|
48
|
-
'build',
|
|
49
|
-
'.zig-cache',
|
|
50
|
-
'__pycache__',
|
|
51
|
-
'.next',
|
|
52
|
-
'.turbo',
|
|
53
|
-
]);
|
|
54
|
-
|
|
55
|
-
// Regex fallback when @ast-grep/napi unavailable
|
|
56
|
-
const REGEX_DECLARATIONS: Array<{pattern: RegExp; nameGroup: number}> = [
|
|
57
|
-
{pattern: /(?:export\s+)?(?:async\s+)?function\s+(\w+)/g, nameGroup: 1},
|
|
58
|
-
{pattern: /(?:export\s+)?class\s+(\w+)/g, nameGroup: 1},
|
|
59
|
-
{pattern: /(?:export\s+)?interface\s+(\w+)/g, nameGroup: 1},
|
|
60
|
-
{pattern: /(?:export\s+)?type\s+(\w+)/g, nameGroup: 1},
|
|
61
|
-
{pattern: /(?:export\s+)?enum\s+(\w+)/g, nameGroup: 1},
|
|
62
|
-
{pattern: /(?:export\s+)?const\s+(\w+)\s*=\s*(?:\(|async\s*\()/g, nameGroup: 1},
|
|
63
|
-
];
|
|
64
|
-
|
|
65
|
-
async function extractDeclarations(filePath: string): Promise<string[]> {
|
|
66
|
-
const content = await readFile(filePath, 'utf-8');
|
|
67
|
-
const ext = extname(filePath);
|
|
68
|
-
const declarations: string[] = [];
|
|
69
|
-
|
|
70
|
-
try {
|
|
71
|
-
const sg = await import('@ast-grep/napi');
|
|
72
|
-
const LangMap: Record<string, (typeof sg.Lang)[keyof typeof sg.Lang]> = {
|
|
73
|
-
'.ts': sg.Lang.TypeScript,
|
|
74
|
-
'.tsx': sg.Lang.Tsx,
|
|
75
|
-
'.js': sg.Lang.JavaScript,
|
|
76
|
-
'.jsx': sg.Lang.Tsx,
|
|
77
|
-
};
|
|
78
|
-
const lang = LangMap[ext] ?? sg.Lang.TypeScript;
|
|
79
|
-
const patterns =
|
|
80
|
-
PATTERNS[ext === '.tsx' || ext === '.jsx' ? 'typescript' : 'javascript'] ??
|
|
81
|
-
PATTERNS.typescript;
|
|
82
|
-
|
|
83
|
-
const root = sg.parse(lang, content);
|
|
84
|
-
const seen = new Set<string>();
|
|
85
|
-
|
|
86
|
-
for (const pattern of patterns) {
|
|
87
|
-
try {
|
|
88
|
-
const matches = root.root().findAll(pattern);
|
|
89
|
-
for (const m of matches) {
|
|
90
|
-
const name = m.getMatch('NAME')?.text();
|
|
91
|
-
if (name && !seen.has(name)) {
|
|
92
|
-
seen.add(name);
|
|
93
|
-
declarations.push(name);
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
} catch {
|
|
97
|
-
/* pattern may not match this language */
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
} catch {
|
|
101
|
-
// Regex fallback
|
|
102
|
-
for (const re of REGEX_DECLARATIONS) {
|
|
103
|
-
let match: RegExpExecArray | null;
|
|
104
|
-
const regex = new RegExp(re.pattern.source, re.pattern.flags);
|
|
105
|
-
while ((match = regex.exec(content)) !== null) {
|
|
106
|
-
const name = match[re.nameGroup];
|
|
107
|
-
if (name && !declarations.includes(name)) {
|
|
108
|
-
declarations.push(name);
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
return declarations;
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
export async function buildRepoMap(
|
|
118
|
-
dir: string,
|
|
119
|
-
maxTokens: number = 1000,
|
|
120
|
-
/** `.pal.json` ignore predicate — absolute path in, "skip" out. */
|
|
121
|
-
isIgnored?: (absPath: string) => boolean,
|
|
122
|
-
): Promise<string> {
|
|
123
|
-
const entries: RepoMapEntry[] = [];
|
|
124
|
-
|
|
125
|
-
async function walk(current: string, depth: number) {
|
|
126
|
-
if (depth > 30) return; // safety net; symlinks are already not followed
|
|
127
|
-
let items;
|
|
128
|
-
try {
|
|
129
|
-
items = await readdir(current, {withFileTypes: true});
|
|
130
|
-
} catch {
|
|
131
|
-
return; // unreadable dir
|
|
132
|
-
}
|
|
133
|
-
for (const item of items) {
|
|
134
|
-
if (IGNORE_DIRS.has(item.name)) continue;
|
|
135
|
-
const fullPath = join(current, item.name);
|
|
136
|
-
if (isIgnored?.(fullPath)) continue;
|
|
137
|
-
if (item.isDirectory()) {
|
|
138
|
-
await walk(fullPath, depth + 1);
|
|
139
|
-
} else if (SCAN_EXTENSIONS.has(extname(item.name))) {
|
|
140
|
-
try {
|
|
141
|
-
const declarations = await extractDeclarations(fullPath);
|
|
142
|
-
if (declarations.length > 0) {
|
|
143
|
-
entries.push({
|
|
144
|
-
file: relative(dir, fullPath).replace(/\\/g, '/'),
|
|
145
|
-
declarations,
|
|
146
|
-
});
|
|
147
|
-
}
|
|
148
|
-
} catch {
|
|
149
|
-
/* skip unreadable files */
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
await walk(dir, 0);
|
|
156
|
-
|
|
157
|
-
// Format as tree
|
|
158
|
-
const lines: string[] = [];
|
|
159
|
-
let tokenEstimate = 0;
|
|
160
|
-
|
|
161
|
-
for (const entry of entries) {
|
|
162
|
-
const fileLine = `📄 ${entry.file}`;
|
|
163
|
-
if (tokenEstimate + Math.ceil(fileLine.length / 4) > maxTokens) break;
|
|
164
|
-
lines.push(fileLine);
|
|
165
|
-
tokenEstimate += Math.ceil(fileLine.length / 4);
|
|
166
|
-
|
|
167
|
-
for (const decl of entry.declarations) {
|
|
168
|
-
const declLine = ` └─ ${decl}`;
|
|
169
|
-
if (tokenEstimate + Math.ceil(declLine.length / 4) > maxTokens) break;
|
|
170
|
-
lines.push(declLine);
|
|
171
|
-
tokenEstimate += Math.ceil(declLine.length / 4);
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
if (lines.length === 0) return 'No source files found.';
|
|
176
|
-
return lines.join('\n');
|
|
177
|
-
}
|
|
@@ -1,104 +0,0 @@
|
|
|
1
|
-
import {test, expect} from 'bun:test';
|
|
2
|
-
import {rm} from 'fs/promises';
|
|
3
|
-
import {rmSync} from 'fs';
|
|
4
|
-
import {join} from 'path';
|
|
5
|
-
import {Database} from 'bun:sqlite';
|
|
6
|
-
import {SessionStore} from './store.js';
|
|
7
|
-
|
|
8
|
-
const DB_PATH = join(import.meta.dir, '.test-migration.db');
|
|
9
|
-
|
|
10
|
-
/** Build a v0 database: sessions table with a JSON `messages` blob column. */
|
|
11
|
-
function seedLegacyDb(): void {
|
|
12
|
-
// Start from a clean slate — a leftover file from a previous run would make
|
|
13
|
-
// the CREATE TABLE fail and mis-attribute the error.
|
|
14
|
-
rmSync(DB_PATH, {force: true});
|
|
15
|
-
rmSync(`${DB_PATH}-wal`, {force: true});
|
|
16
|
-
rmSync(`${DB_PATH}-shm`, {force: true});
|
|
17
|
-
|
|
18
|
-
const db = new Database(DB_PATH);
|
|
19
|
-
db.exec(`
|
|
20
|
-
CREATE TABLE sessions (
|
|
21
|
-
id TEXT PRIMARY KEY,
|
|
22
|
-
title TEXT,
|
|
23
|
-
messages TEXT NOT NULL,
|
|
24
|
-
input_tokens INTEGER NOT NULL DEFAULT 0,
|
|
25
|
-
output_tokens INTEGER NOT NULL DEFAULT 0,
|
|
26
|
-
cached_tokens INTEGER NOT NULL DEFAULT 0,
|
|
27
|
-
cost REAL NOT NULL DEFAULT 0,
|
|
28
|
-
created_at INTEGER NOT NULL,
|
|
29
|
-
updated_at INTEGER NOT NULL
|
|
30
|
-
);
|
|
31
|
-
`);
|
|
32
|
-
const history = [
|
|
33
|
-
{role: 'user', content: 'first'},
|
|
34
|
-
{role: 'assistant', content: 'second'},
|
|
35
|
-
{role: 'tool', tool_call_id: 'c1', content: 'third'},
|
|
36
|
-
];
|
|
37
|
-
db.run(
|
|
38
|
-
'INSERT INTO sessions (id, title, messages, created_at, updated_at) VALUES (?, ?, ?, ?, ?)',
|
|
39
|
-
['legacy-1', 'Old session', JSON.stringify(history), 1000, 2000],
|
|
40
|
-
);
|
|
41
|
-
// A row with malformed JSON must not abort the migration.
|
|
42
|
-
db.run(
|
|
43
|
-
'INSERT INTO sessions (id, title, messages, created_at, updated_at) VALUES (?, ?, ?, ?, ?)',
|
|
44
|
-
['legacy-bad', 'Broken', '{not json', 1000, 2000],
|
|
45
|
-
);
|
|
46
|
-
db.close();
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
test('migration: explodes legacy JSON blobs into message rows', () => {
|
|
50
|
-
seedLegacyDb();
|
|
51
|
-
const store = new SessionStore({dbPath: DB_PATH});
|
|
52
|
-
store.init();
|
|
53
|
-
|
|
54
|
-
try {
|
|
55
|
-
const rows = store.getMessages('legacy-1');
|
|
56
|
-
expect(rows.map((r) => r.seq)).toEqual([1, 2, 3]);
|
|
57
|
-
expect(rows.map((r) => r.role)).toEqual(['user', 'assistant', 'tool']);
|
|
58
|
-
expect(rows[2].toolCallId).toBe('c1');
|
|
59
|
-
|
|
60
|
-
const session = store.get('legacy-1');
|
|
61
|
-
expect(session?.title).toBe('Old session');
|
|
62
|
-
expect(session?.messages).toEqual([
|
|
63
|
-
{role: 'user', content: 'first'},
|
|
64
|
-
{role: 'assistant', content: 'second'},
|
|
65
|
-
{role: 'tool', tool_call_id: 'c1', content: 'third'},
|
|
66
|
-
]);
|
|
67
|
-
|
|
68
|
-
// The malformed row survives as an empty session (no rows exploded).
|
|
69
|
-
expect(store.getMessages('legacy-bad')).toEqual([]);
|
|
70
|
-
} finally {
|
|
71
|
-
store.close();
|
|
72
|
-
}
|
|
73
|
-
});
|
|
74
|
-
|
|
75
|
-
test('migration: re-running on a migrated DB is a no-op (idempotent)', () => {
|
|
76
|
-
const store = new SessionStore({dbPath: DB_PATH});
|
|
77
|
-
store.init();
|
|
78
|
-
try {
|
|
79
|
-
// A second init on the same file must not duplicate rows or throw.
|
|
80
|
-
store.init();
|
|
81
|
-
expect(store.getMessages('legacy-1').length).toBe(3);
|
|
82
|
-
} finally {
|
|
83
|
-
store.close();
|
|
84
|
-
}
|
|
85
|
-
});
|
|
86
|
-
|
|
87
|
-
test('migration: appends continue after migrated history', () => {
|
|
88
|
-
const store = new SessionStore({dbPath: DB_PATH});
|
|
89
|
-
store.init();
|
|
90
|
-
try {
|
|
91
|
-
store.appendMessage('legacy-1', {role: 'user', content: 'after migration'});
|
|
92
|
-
const rows = store.getMessages('legacy-1');
|
|
93
|
-
expect(rows.map((r) => r.seq)).toEqual([1, 2, 3, 4]);
|
|
94
|
-
expect(rows[3].content).toBe('after migration');
|
|
95
|
-
} finally {
|
|
96
|
-
store.close();
|
|
97
|
-
}
|
|
98
|
-
});
|
|
99
|
-
|
|
100
|
-
test('migration cleanup', async () => {
|
|
101
|
-
await rm(DB_PATH, {force: true});
|
|
102
|
-
await rm(`${DB_PATH}-wal`, {force: true});
|
|
103
|
-
await rm(`${DB_PATH}-shm`, {force: true});
|
|
104
|
-
});
|
|
@@ -1,209 +0,0 @@
|
|
|
1
|
-
import {test, expect} from 'bun:test';
|
|
2
|
-
import {rm} from 'fs/promises';
|
|
3
|
-
import {join} from 'path';
|
|
4
|
-
import {Database} from 'bun:sqlite';
|
|
5
|
-
import {SessionStore} from './store.js';
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* Each test gets its own file. Sharing one path let a Windows file lock leak a
|
|
9
|
-
* previous test's schema into the next — which produced confusing failures
|
|
10
|
-
* ("table sessions already exists") unrelated to the code under test.
|
|
11
|
-
*/
|
|
12
|
-
const pathFor = (name: string) => join(import.meta.dir, `.test-v2-${name}.db`);
|
|
13
|
-
|
|
14
|
-
async function cleanup(name: string): Promise<void> {
|
|
15
|
-
for (const suffix of ['', '-wal', '-shm']) {
|
|
16
|
-
await rm(`${pathFor(name)}${suffix}`, {force: true});
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
/** `messages_backup`'s NOT NULL flag, or undefined when the column is absent. */
|
|
21
|
-
function backupNotNull(p: string): number | undefined {
|
|
22
|
-
const db = new Database(p, {readonly: true});
|
|
23
|
-
const col = (
|
|
24
|
-
db.query('PRAGMA table_info(sessions)').all() as Array<{name: string; notnull: number}>
|
|
25
|
-
).find((c) => c.name === 'messages_backup');
|
|
26
|
-
db.close();
|
|
27
|
-
return col?.notnull;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
function userVersion(p: string): number {
|
|
31
|
-
const db = new Database(p, {readonly: true});
|
|
32
|
-
const v = (db.query('PRAGMA user_version').get() as {user_version: number}).user_version;
|
|
33
|
-
db.close();
|
|
34
|
-
return v;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
/**
|
|
38
|
-
* Seed the exact broken state a real DB lands in after the old migration:
|
|
39
|
-
* `messages_backup` inherited the legacy `NOT NULL`, history *was* exploded into
|
|
40
|
-
* `messages` rows, and user_version was already bumped — so `migrate()` returned
|
|
41
|
-
* early and could never repair the constraint.
|
|
42
|
-
*/
|
|
43
|
-
function seedBrokenV1(p: string): void {
|
|
44
|
-
const db = new Database(p);
|
|
45
|
-
db.exec(`
|
|
46
|
-
CREATE TABLE sessions (
|
|
47
|
-
id TEXT PRIMARY KEY,
|
|
48
|
-
title TEXT,
|
|
49
|
-
messages_backup TEXT NOT NULL,
|
|
50
|
-
input_tokens INTEGER NOT NULL DEFAULT 0,
|
|
51
|
-
output_tokens INTEGER NOT NULL DEFAULT 0,
|
|
52
|
-
cached_tokens INTEGER NOT NULL DEFAULT 0,
|
|
53
|
-
cost REAL NOT NULL DEFAULT 0,
|
|
54
|
-
created_at INTEGER NOT NULL,
|
|
55
|
-
updated_at INTEGER NOT NULL,
|
|
56
|
-
compacted_upto_seq INTEGER NOT NULL DEFAULT 0
|
|
57
|
-
);
|
|
58
|
-
CREATE TABLE messages (
|
|
59
|
-
id TEXT PRIMARY KEY,
|
|
60
|
-
session_id TEXT NOT NULL,
|
|
61
|
-
seq INTEGER NOT NULL,
|
|
62
|
-
role TEXT NOT NULL,
|
|
63
|
-
content TEXT NOT NULL,
|
|
64
|
-
tool_calls TEXT,
|
|
65
|
-
tool_call_id TEXT,
|
|
66
|
-
tool_name TEXT,
|
|
67
|
-
tool_status TEXT,
|
|
68
|
-
agent_role TEXT,
|
|
69
|
-
created_at INTEGER NOT NULL,
|
|
70
|
-
UNIQUE(session_id, seq)
|
|
71
|
-
);
|
|
72
|
-
CREATE TABLE session_compactions (
|
|
73
|
-
id TEXT PRIMARY KEY,
|
|
74
|
-
session_id TEXT NOT NULL,
|
|
75
|
-
from_seq INTEGER NOT NULL,
|
|
76
|
-
to_seq INTEGER NOT NULL,
|
|
77
|
-
summary TEXT NOT NULL,
|
|
78
|
-
created_at INTEGER NOT NULL
|
|
79
|
-
);
|
|
80
|
-
`);
|
|
81
|
-
db.run(
|
|
82
|
-
'INSERT INTO sessions (id, title, messages_backup, created_at, updated_at, compacted_upto_seq) VALUES (?, ?, ?, ?, ?, 0)',
|
|
83
|
-
['broken-1', 'Pre-existing', '[{"role":"user","content":"old"}]', 1000, 2000],
|
|
84
|
-
);
|
|
85
|
-
// History was exploded into rows before the rename — mirror that.
|
|
86
|
-
db.run(
|
|
87
|
-
'INSERT INTO messages (id, session_id, seq, role, content, created_at) VALUES (?, ?, ?, ?, ?, ?)',
|
|
88
|
-
['m1', 'broken-1', 1, 'user', 'old', 1000],
|
|
89
|
-
);
|
|
90
|
-
db.exec('PRAGMA user_version = 1');
|
|
91
|
-
db.close();
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
test('repair: an already-migrated v1 DB can create sessions again', async () => {
|
|
95
|
-
const p = pathFor('broken');
|
|
96
|
-
await cleanup('broken');
|
|
97
|
-
seedBrokenV1(p);
|
|
98
|
-
|
|
99
|
-
expect(backupNotNull(p)).toBe(1); // the broken constraint
|
|
100
|
-
expect(userVersion(p)).toBe(1); // and the version that blocked repair
|
|
101
|
-
|
|
102
|
-
const store = new SessionStore({dbPath: p});
|
|
103
|
-
store.init();
|
|
104
|
-
try {
|
|
105
|
-
expect(userVersion(p)).toBe(2);
|
|
106
|
-
expect(backupNotNull(p)).toBe(0); // relaxed
|
|
107
|
-
|
|
108
|
-
// The bug: this INSERT used to fail with
|
|
109
|
-
// "NOT NULL constraint failed: sessions.messages_backup".
|
|
110
|
-
const s = store.create([{role: 'user', content: 'new'}], 'Fresh');
|
|
111
|
-
expect(store.get(s.id)?.messages).toEqual([{role: 'user', content: 'new'}]);
|
|
112
|
-
|
|
113
|
-
// The pre-existing session, its exploded rows and its audit blob all survive.
|
|
114
|
-
expect(store.get('broken-1')?.title).toBe('Pre-existing');
|
|
115
|
-
expect(store.get('broken-1')?.messages).toEqual([{role: 'user', content: 'old'}]);
|
|
116
|
-
} finally {
|
|
117
|
-
store.close();
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
// The audit blob is still physically present after the table rebuild.
|
|
121
|
-
const raw = new Database(p, {readonly: true});
|
|
122
|
-
const blob = raw.query('SELECT messages_backup b FROM sessions WHERE id = ?').get('broken-1') as {
|
|
123
|
-
b: string | null;
|
|
124
|
-
};
|
|
125
|
-
raw.close();
|
|
126
|
-
expect(blob.b).toBe('[{"role":"user","content":"old"}]');
|
|
127
|
-
|
|
128
|
-
await cleanup('broken');
|
|
129
|
-
});
|
|
130
|
-
|
|
131
|
-
test('repair: a legacy v0 DB migrates all the way to a writable v2', async () => {
|
|
132
|
-
const p = pathFor('legacy');
|
|
133
|
-
await cleanup('legacy');
|
|
134
|
-
|
|
135
|
-
const db = new Database(p);
|
|
136
|
-
db.exec(`
|
|
137
|
-
CREATE TABLE sessions (
|
|
138
|
-
id TEXT PRIMARY KEY,
|
|
139
|
-
title TEXT,
|
|
140
|
-
messages TEXT NOT NULL,
|
|
141
|
-
input_tokens INTEGER NOT NULL DEFAULT 0,
|
|
142
|
-
output_tokens INTEGER NOT NULL DEFAULT 0,
|
|
143
|
-
cached_tokens INTEGER NOT NULL DEFAULT 0,
|
|
144
|
-
cost REAL NOT NULL DEFAULT 0,
|
|
145
|
-
created_at INTEGER NOT NULL,
|
|
146
|
-
updated_at INTEGER NOT NULL
|
|
147
|
-
);
|
|
148
|
-
`);
|
|
149
|
-
db.run(
|
|
150
|
-
'INSERT INTO sessions (id, title, messages, created_at, updated_at) VALUES (?, ?, ?, ?, ?)',
|
|
151
|
-
['legacy-1', 'Legacy', '[{"role":"user","content":"hi"}]', 1000, 2000],
|
|
152
|
-
);
|
|
153
|
-
db.close();
|
|
154
|
-
|
|
155
|
-
const store = new SessionStore({dbPath: p});
|
|
156
|
-
store.init();
|
|
157
|
-
try {
|
|
158
|
-
// One pass takes v0 → v2, leaving the backend writable.
|
|
159
|
-
expect(userVersion(p)).toBe(2);
|
|
160
|
-
expect(backupNotNull(p)).toBe(0);
|
|
161
|
-
expect(store.getMessages('legacy-1').length).toBe(1);
|
|
162
|
-
|
|
163
|
-
const s = store.create([{role: 'user', content: 'post-migration'}]);
|
|
164
|
-
expect(store.get(s.id)?.messages).toEqual([{role: 'user', content: 'post-migration'}]);
|
|
165
|
-
} finally {
|
|
166
|
-
store.close();
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
await cleanup('legacy');
|
|
170
|
-
});
|
|
171
|
-
|
|
172
|
-
test('repair: a fresh DB is written straight to v2 with no backup column', async () => {
|
|
173
|
-
const p = pathFor('fresh');
|
|
174
|
-
await cleanup('fresh');
|
|
175
|
-
|
|
176
|
-
const store = new SessionStore({dbPath: p});
|
|
177
|
-
store.init();
|
|
178
|
-
try {
|
|
179
|
-
expect(userVersion(p)).toBe(2);
|
|
180
|
-
expect(backupNotNull(p)).toBe(undefined);
|
|
181
|
-
|
|
182
|
-
const s = store.create([{role: 'user', content: 'hello'}]);
|
|
183
|
-
expect(store.get(s.id)?.messages).toEqual([{role: 'user', content: 'hello'}]);
|
|
184
|
-
} finally {
|
|
185
|
-
store.close();
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
await cleanup('fresh');
|
|
189
|
-
});
|
|
190
|
-
|
|
191
|
-
test('repair: re-running init on a repaired DB is a no-op', async () => {
|
|
192
|
-
const p = pathFor('idempotent');
|
|
193
|
-
await cleanup('idempotent');
|
|
194
|
-
seedBrokenV1(p);
|
|
195
|
-
|
|
196
|
-
const store = new SessionStore({dbPath: p});
|
|
197
|
-
store.init();
|
|
198
|
-
try {
|
|
199
|
-
const s = store.create([{role: 'user', content: 'one'}]);
|
|
200
|
-
store.init(); // must not rebuild again or lose rows
|
|
201
|
-
expect(store.get(s.id)?.messages).toEqual([{role: 'user', content: 'one'}]);
|
|
202
|
-
expect(store.get('broken-1')?.title).toBe('Pre-existing');
|
|
203
|
-
expect(store.get('broken-1')?.messages).toEqual([{role: 'user', content: 'old'}]);
|
|
204
|
-
} finally {
|
|
205
|
-
store.close();
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
await cleanup('idempotent');
|
|
209
|
-
});
|