@tinchu0/knitt 0.0.0-stage → 0.1.0-beta.2

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.
Files changed (39) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +64 -2
  3. package/dist/apps/server/src/conversation-server.js +203 -0
  4. package/dist/apps/server/src/http-gateway.js +118 -0
  5. package/dist/apps/server/src/http-main.js +46 -0
  6. package/dist/apps/server/src/main.js +15 -0
  7. package/dist/apps/server/src/server.js +253 -0
  8. package/dist/apps/server/src/web-auth.js +30 -0
  9. package/dist/apps/server/src/web-picker.js +119 -0
  10. package/dist/memory-schema.json +1 -0
  11. package/dist/packages/adapters/src/cli.js +259 -0
  12. package/dist/packages/adapters/src/command.js +227 -0
  13. package/dist/packages/adapters/src/discovery.js +128 -0
  14. package/dist/packages/adapters/src/handoff.js +146 -0
  15. package/dist/packages/adapters/src/hooks.js +159 -0
  16. package/dist/packages/adapters/src/launch.js +21 -0
  17. package/dist/packages/adapters/src/picker.js +40 -0
  18. package/dist/packages/adapters/src/providers/jsonl.js +105 -0
  19. package/dist/packages/adapters/src/repository.js +36 -0
  20. package/dist/packages/adapters/src/scope.js +32 -0
  21. package/dist/packages/adapters/src/status.js +81 -0
  22. package/dist/packages/adapters/src/transcript.js +193 -0
  23. package/dist/packages/contracts/src/capabilities.js +1 -0
  24. package/dist/packages/contracts/src/conversations.js +30 -0
  25. package/dist/packages/contracts/src/events.js +27 -0
  26. package/dist/packages/installer/src/cli.js +325 -0
  27. package/dist/packages/installer/src/connections.js +352 -0
  28. package/dist/packages/installer/src/runtime.js +133 -0
  29. package/dist/packages/memory/src/checkpoints.js +68 -0
  30. package/dist/packages/memory/src/context.js +91 -0
  31. package/dist/packages/memory/src/conversations.js +148 -0
  32. package/dist/packages/memory/src/migrations.js +55 -0
  33. package/dist/packages/memory/src/store.js +269 -0
  34. package/dist/scripts/connector-setup.js +77 -0
  35. package/dist/skills/continue-chat/SKILL.md +13 -0
  36. package/docs/clients/connector-setup.md +63 -0
  37. package/docs/clients/local-agent-memory.md +50 -0
  38. package/docs/clients/npm-installation.md +67 -0
  39. package/package.json +50 -4
@@ -0,0 +1,133 @@
1
+ import { DatabaseSync } from "node:sqlite";
2
+ import { homedir } from "node:os";
3
+ import { join, resolve } from "node:path";
4
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, mkdtempSync, writeFileSync, } from "node:fs";
5
+ import { execFileSync } from "node:child_process";
6
+ import { randomUUID } from "node:crypto";
7
+ import { atomicWrite } from "./connections.js";
8
+ export const packageName = "@tinchu0/knitt";
9
+ export function defaultHome() {
10
+ if (process.env.SHARED_MEMORY_HOME)
11
+ return resolve(process.env.SHARED_MEMORY_HOME);
12
+ if (process.platform === "darwin")
13
+ return join(homedir(), "Library/Application Support/SharedAgentMemory");
14
+ if (process.platform === "win32")
15
+ return join(process.env.LOCALAPPDATA ?? join(homedir(), "AppData/Local"), "SharedAgentMemory");
16
+ return join(process.env.XDG_DATA_HOME ?? join(homedir(), ".local/share"), "shared-agent-memory");
17
+ }
18
+ export function runtimePaths(home) {
19
+ return {
20
+ data: join(home, "data"),
21
+ versions: join(home, "versions"),
22
+ state: join(home, "installation.json"),
23
+ };
24
+ }
25
+ export function readInstallation(home) {
26
+ const path = runtimePaths(home).state;
27
+ if (!existsSync(path))
28
+ return null;
29
+ const value = JSON.parse(readFileSync(path, "utf8"));
30
+ if (value.schema !== 1 ||
31
+ !value.current?.appRoot ||
32
+ !Array.isArray(value.projects))
33
+ throw new Error("Invalid installation metadata");
34
+ return value;
35
+ }
36
+ export async function withInstallLock(home, work) {
37
+ mkdirSync(home, { recursive: true, mode: 0o700 });
38
+ const lock = join(home, "install.lock");
39
+ try {
40
+ mkdirSync(lock, { mode: 0o700 });
41
+ }
42
+ catch {
43
+ throw new Error("Another installation is running, or a stale install.lock remains. Check for a running setup process before removing " +
44
+ lock);
45
+ }
46
+ try {
47
+ writeFileSync(join(lock, "owner.json"), JSON.stringify({ pid: process.pid, started: new Date().toISOString() }), { mode: 0o600 });
48
+ return await work();
49
+ }
50
+ finally {
51
+ rmSync(lock, { recursive: true, force: true });
52
+ }
53
+ }
54
+ export function installRuntime(home, spec) {
55
+ if (process.platform === "win32")
56
+ throw new Error("Windows installer validation is pending; use WSL for this preview.");
57
+ if (Number(process.versions.node.split(".")[0]) < 24)
58
+ throw new Error("Node.js 24 or newer is required");
59
+ const paths = runtimePaths(home);
60
+ mkdirSync(paths.versions, { recursive: true, mode: 0o700 });
61
+ mkdirSync(paths.data, { recursive: true, mode: 0o700 });
62
+ const staging = mkdtempSync(join(paths.versions, ".staging-"));
63
+ try {
64
+ writeFileSync(join(staging, "package.json"), JSON.stringify({ name: "shared-memory-runtime", private: true }), { mode: 0o600 });
65
+ // Arguments are passed directly; no shell interpolation or install lifecycle scripts.
66
+ execFileSync("npm", [
67
+ "install",
68
+ "--prefix",
69
+ staging,
70
+ "--ignore-scripts",
71
+ "--omit=dev",
72
+ "--no-audit",
73
+ "--no-fund",
74
+ "--save-exact",
75
+ "--",
76
+ spec,
77
+ ], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 180_000 });
78
+ const root = join(staging, "node_modules", packageName);
79
+ const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
80
+ if (pkg.name !== packageName ||
81
+ !/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(pkg.version))
82
+ throw new Error("Unexpected runtime package");
83
+ for (const file of [
84
+ "apps/server/src/main.js",
85
+ "packages/installer/src/cli.js",
86
+ ])
87
+ if (!existsSync(join(root, "dist", file)))
88
+ throw new Error("Incomplete runtime: " + file);
89
+ execFileSync(process.execPath, [join(root, "dist/packages/installer/src/cli.js"), "--version"], { encoding: "utf8", timeout: 10_000 });
90
+ const destination = join(paths.versions, pkg.version + "-" + randomUUID());
91
+ renameSync(staging, destination);
92
+ return {
93
+ version: pkg.version,
94
+ node: process.execPath,
95
+ appRoot: join(destination, "node_modules", packageName, "dist"),
96
+ };
97
+ }
98
+ finally {
99
+ rmSync(staging, { recursive: true, force: true });
100
+ }
101
+ }
102
+ export function activateRuntime(home, current, projects) {
103
+ const previous = readInstallation(home);
104
+ atomicWrite(runtimePaths(home).state, JSON.stringify({
105
+ schema: 1,
106
+ current,
107
+ previous: previous?.current,
108
+ projects,
109
+ }, null, 2) + "\n");
110
+ }
111
+ export function assertRuntimeCompatibility(runtime, projects) {
112
+ const marker = join(runtime.appRoot, "memory-schema.json");
113
+ const supported = existsSync(marker)
114
+ ? JSON.parse(readFileSync(marker, "utf8")).supportedSchema
115
+ : 0;
116
+ if (!Number.isInteger(supported) || supported < 0)
117
+ throw new Error("Invalid runtime schema compatibility metadata");
118
+ for (const database of new Set(projects.map((p) => p.database))) {
119
+ if (!existsSync(database))
120
+ continue;
121
+ const db = new DatabaseSync(database, { readOnly: true });
122
+ try {
123
+ const actual = Number(db.prepare("PRAGMA user_version").get().user_version);
124
+ if (actual > supported)
125
+ throw new Error("Runtime is incompatible with memory schema " +
126
+ actual +
127
+ ". Use a compatible runtime or explicitly restore a consistent backup; no data was changed.");
128
+ }
129
+ finally {
130
+ db.close();
131
+ }
132
+ }
133
+ }
@@ -0,0 +1,68 @@
1
+ import { createHash } from "node:crypto";
2
+ import { z } from "zod";
3
+ import { checkpointEntrySchema } from "../../contracts/src/conversations.js";
4
+ import { redact } from "../../adapters/src/hooks.js";
5
+ export function latestCheckpoint(db, repoId, conversationId, throughSeq = Number.MAX_SAFE_INTEGER, checkpointSeq = Number.MAX_SAFE_INTEGER) {
6
+ const row = db
7
+ .prepare("SELECT payload FROM checkpoints WHERE repo=? AND conversation=? AND through_seq<=? AND seq<=? ORDER BY seq DESC LIMIT 1")
8
+ .get(repoId, conversationId, throughSeq, checkpointSeq);
9
+ return row ? JSON.parse(String(row.payload)) : null;
10
+ }
11
+ export function saveCheckpoint(db, store, key, input) {
12
+ const entries = z.array(checkpointEntrySchema).min(1).max(100).parse(input);
13
+ const conversation = store.sessionConversation(key);
14
+ db.exec("BEGIN IMMEDIATE");
15
+ try {
16
+ const rows = store.conversationRows(key), permitted = new Set(rows.map((r) => String(JSON.parse(String(r.payload)).eventId)));
17
+ const ids = new Set();
18
+ const previous = latestCheckpoint(db, key.repoId, conversation.conversationId);
19
+ const active = new Map((previous?.entries ?? [])
20
+ .filter((e) => e.evidenceIds.every((id) => permitted.has(id)))
21
+ .map((e) => [e.id, e]));
22
+ for (const original of entries) {
23
+ const entry = { ...original, content: redact(original.content) };
24
+ if (ids.has(entry.id))
25
+ throw new Error("Duplicate checkpoint entry ID");
26
+ ids.add(entry.id);
27
+ if (entry.status === "verified")
28
+ throw new Error("No trusted execution evidence supports verified status; use reported");
29
+ if (!entry.evidenceIds.every((id) => permitted.has(id)))
30
+ throw new Error("Checkpoint evidence is unavailable in this conversation");
31
+ if (db
32
+ .prepare("SELECT 1 FROM retired_checkpoint_entries WHERE repo=? AND conversation=? AND id=?")
33
+ .get(key.repoId, conversation.conversationId, entry.id))
34
+ throw new Error("Checkpoint entry was retired by supersession; use a new ID");
35
+ const old = active.get(entry.id);
36
+ if (old && JSON.stringify(old) !== JSON.stringify(entry))
37
+ throw new Error("Entry ID conflict; supersede the old entry explicitly");
38
+ if (old)
39
+ continue;
40
+ if (entry.supersedes) {
41
+ if (entry.supersedes === entry.id || !active.has(entry.supersedes))
42
+ throw new Error("Unknown superseded checkpoint entry");
43
+ active.delete(entry.supersedes);
44
+ db.prepare("INSERT OR IGNORE INTO retired_checkpoint_entries VALUES(?,?,?)").run(key.repoId, conversation.conversationId, entry.supersedes);
45
+ }
46
+ active.set(entry.id, entry);
47
+ }
48
+ const throughSeq = rows
49
+ .filter((r) => r.conversation === conversation.conversationId)
50
+ .reduce((max, r) => Math.max(max, Number(r.seq)), 0);
51
+ const body = {
52
+ conversationId: conversation.conversationId,
53
+ throughSeq,
54
+ entries: [...active.values()],
55
+ };
56
+ const checkpointId = createHash("sha256")
57
+ .update(JSON.stringify(body))
58
+ .digest("hex");
59
+ const checkpoint = { checkpointId, ...body };
60
+ db.prepare("INSERT OR IGNORE INTO checkpoints(repo,conversation,id,through_seq,payload) VALUES(?,?,?,?,?)").run(key.repoId, conversation.conversationId, checkpointId, throughSeq, JSON.stringify(checkpoint));
61
+ db.exec("COMMIT");
62
+ return checkpoint;
63
+ }
64
+ catch (error) {
65
+ db.exec("ROLLBACK");
66
+ throw error;
67
+ }
68
+ }
@@ -0,0 +1,91 @@
1
+ import { z } from "zod";
2
+ export function getConversationContext(store, key, options) {
3
+ const maxChars = z
4
+ .number()
5
+ .int()
6
+ .min(256)
7
+ .max(24000)
8
+ .default(12000)
9
+ .parse(options.maxChars);
10
+ const own = store.sessionConversation(key), source = store.selectedSource(key), rows = store.conversationRows(key), events = rows.map((row) => ({
11
+ ...JSON.parse(String(row.payload)),
12
+ receivedAt: String(row.received),
13
+ }));
14
+ const allowed = new Set(events.map((e) => e.eventId));
15
+ const ownCheckpoint = store.latestCheckpoint(key.repoId, own.conversationId), sourceCheckpoint = source
16
+ ? store.latestCheckpoint(key.repoId, source.sourceConversationId, source.throughSeq, source.checkpointSeq)
17
+ : null;
18
+ const revisions = [ownCheckpoint, sourceCheckpoint].filter((cp) => cp !== null);
19
+ const entries = revisions.flatMap((cp) => cp.entries
20
+ .filter((e) => e.evidenceIds.every((id) => allowed.has(id)))
21
+ .map((e) => ({ ...e, conversationId: cp.conversationId })));
22
+ const stale = revisions.some((cp) => rows.some((row) => row.conversation === cp.conversationId &&
23
+ Number(row.seq) > cp.throughSeq));
24
+ const provenance = {
25
+ destination: { ...own, ...store.sessionLocation(key) },
26
+ source: source
27
+ ? {
28
+ ...source,
29
+ ...source.location,
30
+ }
31
+ : null,
32
+ scope: "destination_and_direct_source_only",
33
+ };
34
+ let result = {
35
+ checkpoint: null,
36
+ events: [],
37
+ provenance,
38
+ stale,
39
+ truncated: events.length > 0 || entries.length > 0,
40
+ omitted: { entries: entries.length, events: events.length },
41
+ contentTrust: "untrusted_reference",
42
+ checkpointStatus: revisions.length ? "available" : "missing",
43
+ };
44
+ if (JSON.stringify(result).length > maxChars) {
45
+ result = { ...result, provenance: { omitted: true }, truncated: true };
46
+ // The minimum budget can carry a compact, truthful envelope, not identifiers.
47
+ if (JSON.stringify(result).length > maxChars) {
48
+ delete result.provenance.omitted;
49
+ }
50
+ }
51
+ const checkpoint = {
52
+ entries: [],
53
+ revisions: revisions.map(({ checkpointId, conversationId, throughSeq }) => ({
54
+ checkpointId,
55
+ conversationId,
56
+ throughSeq,
57
+ })),
58
+ };
59
+ for (const entry of entries) {
60
+ const candidateCheckpoint = {
61
+ ...checkpoint,
62
+ entries: [...checkpoint.entries, entry],
63
+ };
64
+ const candidate = {
65
+ ...result,
66
+ checkpoint: candidateCheckpoint,
67
+ omitted: { ...result.omitted, entries: result.omitted.entries - 1 },
68
+ };
69
+ if (JSON.stringify(candidateCheckpoint).length <= Math.floor(maxChars / 2) &&
70
+ JSON.stringify(candidate).length + 1 <= maxChars) {
71
+ checkpoint.entries.push(entry);
72
+ result = candidate;
73
+ }
74
+ }
75
+ for (const event of events) {
76
+ const candidate = {
77
+ ...result,
78
+ events: [...result.events, event],
79
+ omitted: { ...result.omitted, events: result.omitted.events - 1 },
80
+ };
81
+ if (JSON.stringify(candidate).length + 1 <= maxChars)
82
+ result = candidate;
83
+ }
84
+ result.truncated =
85
+ result.truncated &&
86
+ (result.omitted.entries > 0 ||
87
+ result.omitted.events > 0 ||
88
+ result.provenance.omitted === true ||
89
+ Object.keys(result.provenance).length === 0);
90
+ return result;
91
+ }
@@ -0,0 +1,148 @@
1
+ import { randomUUID, randomBytes, createHash, timingSafeEqual, } from "node:crypto";
2
+ import { sessionKeySchema, locationSchema, } from "../../contracts/src/conversations.js";
3
+ export class ConversationStore {
4
+ db;
5
+ constructor(db) {
6
+ this.db = db;
7
+ }
8
+ ensureSession(input, location) {
9
+ const key = sessionKeySchema.parse(input), loc = locationSchema.parse(location);
10
+ this.db.exec("BEGIN IMMEDIATE");
11
+ try {
12
+ const row = this.db
13
+ .prepare("SELECT conversation FROM native_sessions WHERE repo=? AND client=? AND native_id=?")
14
+ .get(key.repoId, key.client, key.nativeSessionId);
15
+ const id = row
16
+ ? String(row.conversation)
17
+ : "conversation:" + randomUUID();
18
+ if (!row) {
19
+ this.db
20
+ .prepare("INSERT INTO conversations VALUES(?,?,?,?,?)")
21
+ .run(key.repoId, id, key.client + " session " + key.nativeSessionId.slice(0, 24), key.client, new Date().toISOString());
22
+ this.db
23
+ .prepare("INSERT INTO native_sessions(repo,client,native_id,conversation,workspace,branch,commit_id) VALUES(?,?,?,?,?,?,?)")
24
+ .run(key.repoId, key.client, key.nativeSessionId, id, loc.workspace, loc.branch ?? null, loc.commit ?? null);
25
+ }
26
+ else
27
+ this.db
28
+ .prepare("UPDATE native_sessions SET workspace=?,branch=?,commit_id=? WHERE repo=? AND client=? AND native_id=?")
29
+ .run(loc.workspace, loc.branch ?? null, loc.commit ?? null, key.repoId, key.client, key.nativeSessionId);
30
+ const conversation = this.get(key.repoId, id);
31
+ this.db.exec("COMMIT");
32
+ return conversation;
33
+ }
34
+ catch (error) {
35
+ this.db.exec("ROLLBACK");
36
+ throw error;
37
+ }
38
+ }
39
+ session(input) {
40
+ const key = sessionKeySchema.parse(input);
41
+ const row = this.db
42
+ .prepare("SELECT conversation FROM native_sessions WHERE repo=? AND client=? AND native_id=?")
43
+ .get(key.repoId, key.client, key.nativeSessionId);
44
+ if (!row)
45
+ throw new Error("Unknown conversation session");
46
+ return this.get(key.repoId, String(row.conversation));
47
+ }
48
+ get(repoId, id) {
49
+ const row = this.db
50
+ .prepare("SELECT * FROM conversations WHERE repo=? AND id=?")
51
+ .get(repoId, id);
52
+ if (!row)
53
+ throw new Error("Unknown conversation in repository");
54
+ return {
55
+ repoId: String(row.repo),
56
+ conversationId: String(row.id),
57
+ title: String(row.title),
58
+ client: String(row.client),
59
+ };
60
+ }
61
+ list(repoId) {
62
+ return this.db
63
+ .prepare("SELECT id FROM conversations WHERE repo=? ORDER BY created DESC,id")
64
+ .all(repoId)
65
+ .map((r) => this.get(repoId, String(r.id)));
66
+ }
67
+ location(key) {
68
+ this.session(key);
69
+ const row = this.db
70
+ .prepare("SELECT workspace,branch,commit_id FROM native_sessions WHERE repo=? AND client=? AND native_id=?")
71
+ .get(key.repoId, key.client, key.nativeSessionId);
72
+ return {
73
+ workspace: String(row.workspace),
74
+ branch: row.branch ? String(row.branch) : undefined,
75
+ commit: row.commit_id ? String(row.commit_id) : undefined,
76
+ };
77
+ }
78
+ issueSessionToken(key) {
79
+ this.session(key);
80
+ const token = randomBytes(32).toString("base64url");
81
+ this.db
82
+ .prepare("UPDATE native_sessions SET token_hash=? WHERE repo=? AND client=? AND native_id=?")
83
+ .run(createHash("sha256").update(token).digest("hex"), key.repoId, key.client, key.nativeSessionId);
84
+ return token;
85
+ }
86
+ assertSessionToken(key, token) {
87
+ this.session(key);
88
+ const row = this.db
89
+ .prepare("SELECT token_hash FROM native_sessions WHERE repo=? AND client=? AND native_id=?")
90
+ .get(key.repoId, key.client, key.nativeSessionId);
91
+ if (!token || token.length > 128 || !row?.token_hash)
92
+ throw new Error("Use the sessionToken from this native session's startup hook");
93
+ const expected = Buffer.from(String(row.token_hash), "hex"), actual = createHash("sha256").update(token).digest();
94
+ if (expected.length !== actual.length || !timingSafeEqual(expected, actual))
95
+ throw new Error("Wrong session capability");
96
+ }
97
+ selectedSource(key) {
98
+ this.session(key);
99
+ const row = this.db
100
+ .prepare("SELECT source,through_seq,checkpoint_seq,source_location FROM continuation_links WHERE repo=? AND client=? AND native_id=?")
101
+ .get(key.repoId, key.client, key.nativeSessionId);
102
+ return row
103
+ ? {
104
+ sourceConversationId: String(row.source),
105
+ throughSeq: Number(row.through_seq),
106
+ checkpointSeq: Number(row.checkpoint_seq),
107
+ location: JSON.parse(String(row.source_location)),
108
+ }
109
+ : null;
110
+ }
111
+ linkSource(key, sourceConversationId) {
112
+ const own = this.session(key);
113
+ this.get(key.repoId, sourceConversationId);
114
+ if (own.conversationId === sourceConversationId)
115
+ throw new Error("Cannot link a conversation to itself");
116
+ this.db.exec("BEGIN IMMEDIATE");
117
+ try {
118
+ const seq = this.db
119
+ .prepare("SELECT COALESCE(MAX(e.seq),0) AS seq FROM events e JOIN conversation_evidence m ON e.repo=m.repo AND e.id=m.event_id WHERE m.repo=? AND m.conversation=?")
120
+ .get(key.repoId, sourceConversationId);
121
+ const revision = this.db
122
+ .prepare("SELECT COALESCE(MAX(seq),0) AS seq FROM checkpoints WHERE repo=? AND conversation=?")
123
+ .get(key.repoId, sourceConversationId);
124
+ const location = this.db
125
+ .prepare("SELECT workspace,branch,commit_id FROM native_sessions WHERE repo=? AND conversation=? LIMIT 1")
126
+ .get(key.repoId, sourceConversationId);
127
+ const frozen = {
128
+ workspace: String(location.workspace),
129
+ ...(location.branch ? { branch: String(location.branch) } : {}),
130
+ ...(location.commit_id ? { commit: String(location.commit_id) } : {}),
131
+ };
132
+ this.db
133
+ .prepare("INSERT INTO continuation_links(repo,client,native_id,source,through_seq,checkpoint_seq,source_location) VALUES(?,?,?,?,?,?,?) ON CONFLICT(repo,client,native_id) DO UPDATE SET source=excluded.source,through_seq=excluded.through_seq,checkpoint_seq=excluded.checkpoint_seq,source_location=excluded.source_location")
134
+ .run(key.repoId, key.client, key.nativeSessionId, sourceConversationId, Number(seq.seq), Number(revision.seq), JSON.stringify(frozen));
135
+ this.db.exec("COMMIT");
136
+ return {
137
+ sourceConversationId,
138
+ throughSeq: Number(seq.seq),
139
+ checkpointSeq: Number(revision.seq),
140
+ location: frozen,
141
+ };
142
+ }
143
+ catch (error) {
144
+ this.db.exec("ROLLBACK");
145
+ throw error;
146
+ }
147
+ }
148
+ }
@@ -0,0 +1,55 @@
1
+ import { chmodSync } from "node:fs";
2
+ import { randomUUID } from "node:crypto";
3
+ export const schemaVersion = 4;
4
+ export function assertSupportedSchema(db) {
5
+ const version = Number(db.prepare("PRAGMA user_version").get().user_version);
6
+ if (version > schemaVersion)
7
+ throw new Error("Unsupported memory schema; use a compatible Knitt runtime");
8
+ return version;
9
+ }
10
+ export function migrate(db) {
11
+ const version = assertSupportedSchema(db);
12
+ if (version === schemaVersion)
13
+ return;
14
+ const file = String(db.prepare("PRAGMA database_list").get().file);
15
+ if (file) {
16
+ const backup = file + ".backup-v" + version + "-" + randomUUID();
17
+ db.exec("VACUUM INTO '" + backup.replaceAll("'", "''") + "'");
18
+ chmodSync(backup, 0o600);
19
+ }
20
+ db.exec("BEGIN IMMEDIATE");
21
+ try {
22
+ // Recheck under the write lock: another process may already have upgraded.
23
+ if (assertSupportedSchema(db) === schemaVersion) {
24
+ db.exec("COMMIT");
25
+ return;
26
+ }
27
+ if (version < 1)
28
+ db.exec(`CREATE TABLE conversations(repo TEXT NOT NULL,id TEXT NOT NULL,title TEXT NOT NULL,client TEXT NOT NULL,created TEXT NOT NULL,PRIMARY KEY(repo,id));
29
+ CREATE TABLE native_sessions(repo TEXT NOT NULL,client TEXT NOT NULL,native_id TEXT NOT NULL,conversation TEXT NOT NULL,workspace TEXT NOT NULL,branch TEXT,commit_id TEXT,PRIMARY KEY(repo,client,native_id));
30
+ CREATE TABLE conversation_evidence(repo TEXT NOT NULL,event_id TEXT NOT NULL,conversation TEXT NOT NULL,PRIMARY KEY(repo,event_id));
31
+ CREATE INDEX conversation_evidence_scope ON conversation_evidence(repo,conversation);
32
+ PRAGMA user_version=1;`);
33
+ if (version < 2)
34
+ db.exec(`CREATE TABLE continuation_links(repo TEXT NOT NULL,client TEXT NOT NULL,native_id TEXT NOT NULL,source TEXT NOT NULL,through_seq INTEGER NOT NULL,PRIMARY KEY(repo,client,native_id)); PRAGMA user_version=2;`);
35
+ if (version < 3)
36
+ db.exec(`CREATE TABLE checkpoints(seq INTEGER PRIMARY KEY AUTOINCREMENT,repo TEXT NOT NULL,conversation TEXT NOT NULL,id TEXT NOT NULL,through_seq INTEGER NOT NULL,payload TEXT NOT NULL,UNIQUE(repo,id)); CREATE INDEX checkpoints_scope ON checkpoints(repo,conversation,seq); PRAGMA user_version=3;`);
37
+ if (version < 4)
38
+ db.exec(`
39
+ ALTER TABLE native_sessions ADD COLUMN token_hash TEXT;
40
+ ALTER TABLE continuation_links ADD COLUMN checkpoint_seq INTEGER NOT NULL DEFAULT 0;
41
+ ALTER TABLE continuation_links ADD COLUMN source_location TEXT NOT NULL DEFAULT '{}';
42
+ CREATE TABLE retired_checkpoint_entries(repo TEXT NOT NULL,conversation TEXT NOT NULL,id TEXT NOT NULL,PRIMARY KEY(repo,conversation,id));
43
+ INSERT OR IGNORE INTO retired_checkpoint_entries
44
+ SELECT checkpoints.repo,checkpoints.conversation,json_extract(entry.value,'$.supersedes')
45
+ FROM checkpoints,json_each(checkpoints.payload,'$.entries') entry
46
+ WHERE json_type(entry.value,'$.supersedes')='text';
47
+ PRAGMA user_version=4;
48
+ `);
49
+ db.exec("COMMIT");
50
+ }
51
+ catch (error) {
52
+ db.exec("ROLLBACK");
53
+ throw error;
54
+ }
55
+ }