@tinchu0/knitt 0.1.0-beta.4 → 0.1.0-beta.5

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 (40) hide show
  1. package/README.md +26 -15
  2. package/dist/apps/server/src/conversation-server.js +203 -0
  3. package/dist/apps/server/src/http-gateway.js +1 -1
  4. package/dist/apps/server/src/main.js +6 -2
  5. package/dist/apps/server/src/server.js +292 -81
  6. package/dist/memory-schema.json +1 -0
  7. package/dist/packages/adapters/src/cli.js +193 -45
  8. package/dist/packages/adapters/src/command.js +149 -18
  9. package/dist/packages/adapters/src/discovery.js +128 -0
  10. package/dist/packages/adapters/src/handoff.js +13 -8
  11. package/dist/packages/adapters/src/histories.js +222 -0
  12. package/dist/packages/adapters/src/history-time.js +10 -0
  13. package/dist/packages/adapters/src/hooks.js +123 -44
  14. package/dist/packages/adapters/src/launch.js +10 -3
  15. package/dist/packages/adapters/src/picker.js +2 -1
  16. package/dist/packages/adapters/src/providers/jsonl.js +105 -0
  17. package/dist/packages/adapters/src/question-ui.js +37 -0
  18. package/dist/packages/adapters/src/repository.js +32 -5
  19. package/dist/packages/adapters/src/scope.js +9 -3
  20. package/dist/packages/adapters/src/server-name.js +6 -0
  21. package/dist/packages/adapters/src/status.js +81 -0
  22. package/dist/packages/adapters/src/transcript.js +72 -15
  23. package/dist/packages/contracts/src/conversations.js +30 -0
  24. package/dist/packages/installer/src/antigravity.js +90 -0
  25. package/dist/packages/installer/src/cli.js +210 -48
  26. package/dist/packages/installer/src/connections.js +193 -38
  27. package/dist/packages/installer/src/runtime.js +73 -11
  28. package/dist/packages/memory/src/checkpoints.js +68 -0
  29. package/dist/packages/memory/src/context.js +91 -0
  30. package/dist/packages/memory/src/conversations.js +148 -0
  31. package/dist/packages/memory/src/migrations.js +55 -0
  32. package/dist/packages/memory/src/store.js +201 -23
  33. package/dist/skills/continue-chat/SKILL.md +15 -0
  34. package/dist/skills/knit/SKILL.md +11 -5
  35. package/docs/clients/connector-setup.md +1 -1
  36. package/docs/clients/local-agent-memory.md +50 -0
  37. package/docs/clients/npm-installation.md +23 -11
  38. package/docs/clients/support-matrix.md +12 -0
  39. package/docs/usage.md +19 -29
  40. package/package.json +5 -4
@@ -1,10 +1,16 @@
1
+ import { antigravityServerName } from '../../adapters/src/server-name.js';
1
2
  import { hookCommand, isManagedHook } from './platform.js';
2
- import { readFileSync, existsSync, mkdirSync, writeFileSync, renameSync, rmSync, realpathSync } from 'node:fs';
3
+ import { readFileSync, existsSync, mkdirSync, writeFileSync, renameSync, rmSync, realpathSync, } from 'node:fs';
3
4
  import { join, dirname, resolve } from 'node:path';
4
5
  import { execFileSync } from 'node:child_process';
5
6
  import { randomUUID } from 'node:crypto';
6
7
  import { parse as parseToml } from 'smol-toml';
7
- export const clients = ['codex', 'claude-code', 'antigravity', 'claude-desktop'];
8
+ export const clients = [
9
+ 'codex',
10
+ 'claude-code',
11
+ 'antigravity',
12
+ 'claude-desktop',
13
+ ];
8
14
  const begin = '# BEGIN shared-agent-memory', end = '# END shared-agent-memory';
9
15
  const statePath = '.memory/npm-connection.json';
10
16
  const read = (path) => existsSync(path) ? readFileSync(path, 'utf8') : null;
@@ -27,11 +33,19 @@ export function atomicWrite(path, content) {
27
33
  function restore(before, after, current) {
28
34
  if (equal(current, after))
29
35
  return before;
30
- if (object(after) && object(current) && typeof after.command === 'string' && Array.isArray(after.args))
36
+ if (object(after) &&
37
+ object(current) &&
38
+ typeof after.command === 'string' &&
39
+ Array.isArray(after.args))
31
40
  return current;
32
- if (object(after) && object(current) && (before === undefined || object(before))) {
41
+ if (object(after) &&
42
+ object(current) &&
43
+ (before === undefined || object(before))) {
33
44
  const result = { ...current };
34
- for (const key of new Set([...Object.keys(before ?? {}), ...Object.keys(after)])) {
45
+ for (const key of new Set([
46
+ ...Object.keys(before ?? {}),
47
+ ...Object.keys(after),
48
+ ])) {
35
49
  if (equal(before?.[key], after[key]))
36
50
  continue;
37
51
  const value = restore(before?.[key], after[key], current[key]);
@@ -40,14 +54,18 @@ function restore(before, after, current) {
40
54
  else
41
55
  result[key] = value;
42
56
  }
43
- return Object.keys(result).length === 0 && before === undefined ? undefined : result;
57
+ return Object.keys(result).length === 0 && before === undefined
58
+ ? undefined
59
+ : result;
44
60
  }
45
- if (Array.isArray(after) && Array.isArray(current) && (before === undefined || Array.isArray(before))) {
61
+ if (Array.isArray(after) &&
62
+ Array.isArray(current) &&
63
+ (before === undefined || Array.isArray(before))) {
46
64
  const previous = before ?? [];
47
- const added = after.filter(v => !previous.some((p) => equal(p, v)));
48
- const result = current.filter(v => !added.some(a => equal(a, v)));
65
+ const added = after.filter((v) => !previous.some((p) => equal(p, v)));
66
+ const result = current.filter((v) => !added.some((a) => equal(a, v)));
49
67
  for (const v of previous)
50
- if (!after.some(a => equal(a, v)) && !result.some(a => equal(a, v)))
68
+ if (!after.some((a) => equal(a, v)) && !result.some((a) => equal(a, v)))
51
69
  result.push(v);
52
70
  return result.length === 0 && before === undefined ? undefined : result;
53
71
  }
@@ -61,47 +79,112 @@ export function readConnectionState(workspace) {
61
79
  if (value.schema !== 1 || !object(value.files))
62
80
  throw new Error('Unsupported connector state');
63
81
  for (const [file, snapshot] of Object.entries(value.files)) {
64
- if (!['.mcp.json', '.codex/config.toml', '.codex/hooks.json', '.agents/hooks.json', '.agents/mcp_config.json', '.agents/skills/continue-chat/SKILL.md', '.agents/skills/knit/SKILL.md', '.claude/settings.local.json', '.claude/skills/continue-chat/SKILL.md', '.claude/skills/knit/SKILL.md', '.memory/connectors/claude-desktop.json'].includes(file)
65
- || !object(snapshot) || typeof snapshot.after !== 'string' || !(snapshot.before === null || typeof snapshot.before === 'string'))
82
+ if (![
83
+ '.mcp.json',
84
+ '.codex/config.toml',
85
+ '.codex/hooks.json',
86
+ '.agents/hooks.json',
87
+ '.agents/mcp_config.json',
88
+ '.agents/skills/continue-chat/SKILL.md',
89
+ '.agents/skills/knit/SKILL.md',
90
+ '.claude/settings.local.json',
91
+ '.claude/skills/continue-chat/SKILL.md',
92
+ '.claude/skills/knit/SKILL.md',
93
+ '.memory/connectors/claude-desktop.json',
94
+ '.memory/connectors/antigravity.json',
95
+ ].includes(file) ||
96
+ !object(snapshot) ||
97
+ typeof snapshot.after !== 'string' ||
98
+ !(snapshot.before === null || typeof snapshot.before === 'string'))
66
99
  throw new Error('Invalid connector state');
67
100
  }
68
101
  return value;
69
102
  }
70
103
  export function planConnection(opts) {
71
- const workspace = realpathSync(opts.workspace), app = resolve(opts.appRoot), node = opts.node ?? process.execPath;
72
- if (!opts.clients.length || opts.clients.some(c => !clients.includes(c)))
104
+ const workspace = realpathSync.native(opts.workspace), app = resolve(opts.appRoot), node = opts.node ?? process.execPath;
105
+ if (!opts.clients.length ||
106
+ opts.clients.some((c) => !clients.includes(c)))
73
107
  throw new Error('Choose a supported client');
74
- const extension = existsSync(join(app, 'apps/server/src/main.js')) ? 'js' : 'ts';
108
+ const extension = existsSync(join(app, 'apps/server/src/main.js'))
109
+ ? 'js'
110
+ : 'ts';
75
111
  const server = join(app, 'apps/server/src/main.' + extension), runner = join(app, 'packages/adapters/src/cli.' + extension);
76
112
  if (!existsSync(server) || !existsSync(runner))
77
113
  throw new Error('Runtime files missing');
78
114
  const state = readConnectionState(workspace), changes = {}, expected = {};
79
- const get = (path) => { const content = read(join(workspace, path)); expected[path] = content; return content; };
80
- const json = (path) => { const v = JSON.parse(get(path) ?? '{}'); if (!object(v))
81
- throw new Error(path + ' must be an object'); return v; };
82
- const env = { MEMORY_DB: resolve(opts.database), MEMORY_REPO: opts.repoId, MEMORY_WORKSPACE: workspace, MEMORY_SESSION_SELECTION: '1' };
83
- const handler = (client, action) => ({ type: 'command', timeout: 10, command: hookCommand({ ...env, MEMORY_QUEUE: join(dirname(opts.database), 'queue', client), MEMORY_MANAGED: 'shared-agent-memory' }, node, [runner, action, client]) });
84
- const connection = (desktop = false) => ({ command: node, args: [server], env: { ...env, ...(desktop ? { MEMORY_CHAT_CLIENT: 'claude-desktop' } : {}) } });
115
+ const get = (path) => {
116
+ const content = read(join(workspace, path));
117
+ expected[path] = content;
118
+ return content;
119
+ };
120
+ const json = (path) => {
121
+ const v = JSON.parse(get(path) ?? '{}');
122
+ if (!object(v))
123
+ throw new Error(path + ' must be an object');
124
+ return v;
125
+ };
126
+ const env = {
127
+ MEMORY_DB: resolve(opts.database),
128
+ MEMORY_REPO: opts.repoId,
129
+ MEMORY_WORKSPACE: workspace,
130
+ MEMORY_SESSION_SELECTION: '1',
131
+ ...(opts.captureNewSessions
132
+ ? { MEMORY_CONVERSATION_MODE: '1', MEMORY_CAPTURE_NEW_SESSIONS: '1' }
133
+ : {}),
134
+ };
135
+ const handler = (client, action) => ({
136
+ type: 'command',
137
+ timeout: 10,
138
+ command: hookCommand({
139
+ ...env,
140
+ ...(client === 'antigravity'
141
+ ? { MEMORY_MCP_SERVER: antigravityServerName(workspace) }
142
+ : {}),
143
+ MEMORY_QUEUE: join(dirname(opts.database), 'queue', client),
144
+ MEMORY_MANAGED: 'shared-agent-memory',
145
+ }, node, [runner, action, client]),
146
+ });
147
+ const connection = (desktop = false, client = 'claude') => {
148
+ const clientEnv = {
149
+ ...env,
150
+ MEMORY_CLIENT: client,
151
+ ...(client === 'antigravity' && !opts.captureNewSessions ? { MEMORY_PICKER_MODE: 'native_question' } : {}),
152
+ ...(desktop ? { MEMORY_CHAT_CLIENT: 'claude-desktop' } : {}),
153
+ ...(!desktop && opts.captureNewSessions ? { MEMORY_CLIENT: client } : {}),
154
+ };
155
+ if (desktop) {
156
+ delete clientEnv.MEMORY_CONVERSATION_MODE;
157
+ delete clientEnv.MEMORY_CAPTURE_NEW_SESSIONS;
158
+ }
159
+ return { command: node, args: [server], env: clientEnv };
160
+ };
85
161
  function owned(path, location, current) {
86
162
  if (current === undefined)
87
163
  return;
88
164
  const prior = state.files[path];
89
- const previous = prior ? location.reduce((v, key) => v?.[key], JSON.parse(prior.after)) : undefined;
165
+ const previous = prior
166
+ ? location.reduce((v, key) => v?.[key], JSON.parse(prior.after))
167
+ : undefined;
90
168
  if (!equal(current, previous))
91
169
  throw new Error('Unmanaged or modified connector conflict in ' + path);
92
170
  }
93
- function mcp(path, desktop = false) {
171
+ function mcp(path, desktop = false, client = 'claude') {
94
172
  const value = json(path);
95
173
  value.mcpServers ??= {};
96
174
  owned(path, ['mcpServers', 'shared-memory'], value.mcpServers['shared-memory']);
97
- value.mcpServers['shared-memory'] = connection(desktop);
175
+ value.mcpServers['shared-memory'] = connection(desktop, client);
98
176
  changes[path] = dump(value);
99
177
  }
100
178
  function hooks(path, client) {
101
179
  const value = json(path);
102
180
  value.hooks ??= {};
103
- const prior = state.files[path] ? JSON.parse(state.files[path].after).hooks : {};
104
- for (const [event, action] of [['SessionStart', 'recall'], ['Stop', 'capture']]) {
181
+ const prior = state.files[path]
182
+ ? JSON.parse(state.files[path].after).hooks
183
+ : {};
184
+ for (const [event, action] of [
185
+ ['SessionStart', 'recall'],
186
+ ['Stop', 'capture'],
187
+ ]) {
105
188
  const old = prior?.[event] ?? [];
106
189
  const groups = value.hooks[event] ?? [];
107
190
  if (!Array.isArray(groups))
@@ -120,25 +203,38 @@ export function planConnection(opts) {
120
203
  const current = get(path);
121
204
  if (current && current !== state.files[path]?.after)
122
205
  throw new Error('Unmanaged or modified skill conflict');
123
- changes[path] = readFileSync(join(app, 'skills/knit/SKILL.md'), 'utf8');
206
+ changes[path] = readFileSync(join(app, 'skills', path.includes('continue-chat') ? 'continue-chat' : 'knit', 'SKILL.md'), 'utf8');
207
+ }
208
+ const hasKnit = existsSync(join(app, 'skills/knit/SKILL.md'));
209
+ const hasContinue = existsSync(join(app, 'skills/continue-chat/SKILL.md'));
210
+ const skillNames = [...(hasKnit ? ['knit'] : []), ...(hasContinue ? ['continue-chat'] : [])];
211
+ if (!skillNames.length)
212
+ throw new Error('Target runtime has no continuation skill');
213
+ for (const name of skillNames) {
214
+ if (opts.clients.some(client => client === 'codex' || client === 'antigravity'))
215
+ skill('.agents/skills/' + name + '/SKILL.md');
216
+ if (opts.clients.includes('claude-code'))
217
+ skill('.claude/skills/' + name + '/SKILL.md');
124
218
  }
125
219
  for (const client of opts.clients) {
126
220
  if (client === 'claude-code') {
127
221
  mcp('.mcp.json');
128
222
  hooks('.claude/settings.local.json', 'claude');
129
- skill('.claude/skills/knit/SKILL.md');
130
223
  }
131
224
  if (client === 'claude-desktop')
132
225
  mcp('.memory/connectors/claude-desktop.json', true);
133
226
  if (client === 'antigravity') {
134
- mcp('.agents/mcp_config.json');
227
+ mcp('.agents/mcp_config.json', false, 'antigravity');
228
+ mcp('.memory/connectors/antigravity.json', false, 'antigravity');
135
229
  const path = '.agents/hooks.json', value = json(path);
136
230
  owned(path, ['shared-memory'], value['shared-memory']);
137
- value['shared-memory'] = { SessionStart: [handler('antigravity', 'recall')], Stop: [handler('antigravity', 'capture')] };
231
+ value['shared-memory'] = {
232
+ SessionStart: [handler('antigravity', 'recall')],
233
+ Stop: [handler('antigravity', 'capture')],
234
+ };
138
235
  changes[path] = dump(value);
139
236
  }
140
237
  if (client === 'codex') {
141
- skill('.agents/skills/knit/SKILL.md');
142
238
  hooks('.codex/hooks.json', 'codex');
143
239
  const path = '.codex/config.toml', current = get(path) ?? '';
144
240
  const parsed = parseToml(current);
@@ -152,12 +248,33 @@ export function planConnection(opts) {
152
248
  }
153
249
  else if (parsed.mcp_servers?.['shared-memory'])
154
250
  throw new Error('Unmanaged Codex server conflict');
155
- changes[path] = base.trimEnd() + '\n\n' + begin + '\n[mcp_servers.shared-memory]\ndefault_tools_approval_mode = "writes"\ncommand = ' + JSON.stringify(node) + '\nargs = ' + JSON.stringify([server]) + '\ncwd = ' + JSON.stringify(workspace) + '\nenv = { ' + Object.entries(env).map(([k, v]) => k + ' = ' + JSON.stringify(v)).join(', ') + ' }\ntools.choose_conversation.approval_mode = "approve"\n' + end + '\n';
251
+ changes[path] =
252
+ base.trimEnd() +
253
+ '\n\n' +
254
+ begin +
255
+ '\n[mcp_servers.shared-memory]\ndefault_tools_approval_mode = "writes"\ncommand = ' +
256
+ JSON.stringify(node) +
257
+ '\nargs = ' +
258
+ JSON.stringify([server]) +
259
+ '\ncwd = ' +
260
+ JSON.stringify(workspace) +
261
+ '\nenv = { ' +
262
+ Object.entries({ ...env, MEMORY_CLIENT: 'codex' })
263
+ .map(([k, v]) => k + ' = ' + JSON.stringify(v))
264
+ .join(', ') +
265
+ ' }\ntools.choose_conversation.approval_mode = "approve"\n' +
266
+ end +
267
+ '\n';
156
268
  parseToml(changes[path]);
157
269
  }
158
270
  }
159
271
  for (const [path, after] of Object.entries(changes))
160
- state.files[path] = { before: state.files[path] ? unapply(path, state.files[path], expected[path] ?? null) : expected[path] ?? null, after };
272
+ state.files[path] = {
273
+ before: state.files[path]
274
+ ? unapply(path, state.files[path], expected[path] ?? null)
275
+ : (expected[path] ?? null),
276
+ after,
277
+ };
161
278
  expected[statePath] = read(join(workspace, statePath));
162
279
  changes[statePath] = dump(state);
163
280
  return { workspace, changes, expected };
@@ -188,12 +305,26 @@ export function applyConnectionPlan(plan) {
188
305
  throw error;
189
306
  }
190
307
  try {
191
- const git = execFileSync('git', ['rev-parse', '--path-format=absolute', '--git-common-dir'], { cwd: plan.workspace, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
308
+ const git = execFileSync('git', ['rev-parse', '--path-format=absolute', '--git-common-dir'], {
309
+ cwd: plan.workspace,
310
+ encoding: 'utf8',
311
+ stdio: ['ignore', 'pipe', 'ignore'],
312
+ }).trim();
192
313
  const path = join(git, 'info/exclude'), current = read(path) ?? '';
193
- const entries = ['/.memory/', ...Object.keys(plan.changes).filter(p => !p.startsWith('.memory/')).map(p => '/' + p)];
194
- atomicWrite(path, current + '\n' + entries.filter(p => !current.split('\n').includes(p)).join('\n') + '\n');
314
+ const entries = [
315
+ '/.memory/',
316
+ ...Object.keys(plan.changes)
317
+ .filter((p) => !p.startsWith('.memory/'))
318
+ .map((p) => '/' + p),
319
+ ];
320
+ atomicWrite(path, current +
321
+ '\n' +
322
+ entries.filter((p) => !current.split('\n').includes(p)).join('\n') +
323
+ '\n');
324
+ }
325
+ catch {
326
+ /* Non-Git projects can use the planner; CLI validates Git separately. */
195
327
  }
196
- catch { /* Non-Git projects can use the planner; CLI validates Git separately. */ }
197
328
  }
198
329
  function unapply(path, snapshot, current) {
199
330
  const { before, after } = snapshot;
@@ -210,6 +341,28 @@ function unapply(path, snapshot, current) {
210
341
  }
211
342
  return current;
212
343
  }
344
+ // Verification may await while users add unrelated JSON settings. Undo only our
345
+ // generated values rather than dropping those additions or abandoning rollback.
346
+ export function rollbackConnectionPlan(plan) {
347
+ for (const [path, before] of Object.entries(plan.expected).reverse()) {
348
+ if (!(path in plan.changes))
349
+ continue;
350
+ const after = plan.changes[path], target = join(plan.workspace, path), current = read(target);
351
+ let restored;
352
+ if (current === after)
353
+ restored = before;
354
+ else if (after !== null && current !== null)
355
+ restored = unapply(path, { before, after }, current);
356
+ else
357
+ continue; // A new user-created value owns a file we removed.
358
+ if (restored === current)
359
+ continue;
360
+ if (restored === null)
361
+ rmSync(target, { force: true });
362
+ else
363
+ atomicWrite(target, restored);
364
+ }
365
+ }
213
366
  export function planUninstall(workspace) {
214
367
  const state = readConnectionState(workspace), changes = {}, expected = {};
215
368
  for (const [path, snapshot] of Object.entries(state.files)) {
@@ -221,4 +374,6 @@ export function planUninstall(workspace) {
221
374
  changes[statePath] = null;
222
375
  return { workspace, changes, expected };
223
376
  }
224
- export function uninstallConnections(workspace) { applyConnectionPlan(planUninstall(workspace)); }
377
+ export function uninstallConnections(workspace) {
378
+ applyConnectionPlan(planUninstall(workspace));
379
+ }
@@ -1,6 +1,7 @@
1
+ import { DatabaseSync } from 'node:sqlite';
1
2
  import { homedir } from 'node:os';
2
3
  import { join, resolve } from 'node:path';
3
- import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, mkdtempSync, writeFileSync } from 'node:fs';
4
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, mkdtempSync, writeFileSync, } from 'node:fs';
4
5
  import { execFileSync } from 'node:child_process';
5
6
  import { randomUUID } from 'node:crypto';
6
7
  import { npmCommand } from './platform.js';
@@ -15,13 +16,21 @@ export function defaultHome() {
15
16
  return join(process.env.LOCALAPPDATA ?? join(homedir(), 'AppData/Local'), 'SharedAgentMemory');
16
17
  return join(process.env.XDG_DATA_HOME ?? join(homedir(), '.local/share'), 'shared-agent-memory');
17
18
  }
18
- export function runtimePaths(home) { return { data: join(home, 'data'), versions: join(home, 'versions'), state: join(home, 'installation.json') }; }
19
+ export function runtimePaths(home) {
20
+ return {
21
+ data: join(home, 'data'),
22
+ versions: join(home, 'versions'),
23
+ state: join(home, 'installation.json'),
24
+ };
25
+ }
19
26
  export function readInstallation(home) {
20
27
  const path = runtimePaths(home).state;
21
28
  if (!existsSync(path))
22
29
  return null;
23
30
  const value = JSON.parse(readFileSync(path, 'utf8'));
24
- if (value.schema !== 1 || !value.current?.appRoot || !Array.isArray(value.projects))
31
+ if (value.schema !== 1 ||
32
+ !value.current?.appRoot ||
33
+ !Array.isArray(value.projects))
25
34
  throw new Error('Invalid installation metadata');
26
35
  return value;
27
36
  }
@@ -32,7 +41,8 @@ export async function withInstallLock(home, work) {
32
41
  mkdirSync(lock, { mode: 0o700 });
33
42
  }
34
43
  catch {
35
- throw new Error('Another installation is running, or a stale install.lock remains. Check for a running setup process before removing ' + lock);
44
+ throw new Error('Another installation is running, or a stale install.lock remains. Check for a running setup process before removing ' +
45
+ lock);
36
46
  }
37
47
  try {
38
48
  writeFileSync(join(lock, 'owner.json'), JSON.stringify({ pid: process.pid, started: new Date().toISOString() }), { mode: 0o600 });
@@ -52,25 +62,77 @@ export function installRuntime(home, spec) {
52
62
  try {
53
63
  writeFileSync(join(staging, 'package.json'), JSON.stringify({ name: 'shared-memory-runtime', private: true }), { mode: 0o600 });
54
64
  // Arguments are passed directly; no shell interpolation or install lifecycle scripts.
55
- const npm = npmCommand(['install', '--prefix', staging, '--ignore-scripts', '--omit=dev', '--no-audit', '--no-fund', '--save-exact', '--', spec]);
56
- execFileSync(npm.command, npm.args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 180_000 });
65
+ const npm = npmCommand([
66
+ 'install',
67
+ '--prefix',
68
+ staging,
69
+ '--ignore-scripts',
70
+ '--omit=dev',
71
+ '--no-audit',
72
+ '--no-fund',
73
+ '--save-exact',
74
+ '--',
75
+ spec,
76
+ ]);
77
+ execFileSync(npm.command, npm.args, {
78
+ encoding: 'utf8',
79
+ stdio: ['ignore', 'pipe', 'pipe'],
80
+ timeout: 180_000,
81
+ });
57
82
  const root = join(staging, 'node_modules', packageName);
58
83
  const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
59
- if (pkg.name !== packageName || !/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(pkg.version))
84
+ if (pkg.name !== packageName ||
85
+ !/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(pkg.version))
60
86
  throw new Error('Unexpected runtime package');
61
- for (const file of ['apps/server/src/main.js', 'packages/installer/src/cli.js'])
87
+ for (const file of [
88
+ 'apps/server/src/main.js',
89
+ 'packages/installer/src/cli.js',
90
+ ])
62
91
  if (!existsSync(join(root, 'dist', file)))
63
92
  throw new Error('Incomplete runtime: ' + file);
64
93
  execFileSync(process.execPath, [join(root, 'dist/packages/installer/src/cli.js'), '--version'], { encoding: 'utf8', timeout: 10_000 });
65
94
  const destination = join(paths.versions, pkg.version + '-' + randomUUID());
66
95
  renameSync(staging, destination);
67
- return { version: pkg.version, node: process.execPath, appRoot: join(destination, 'node_modules', packageName, 'dist') };
96
+ return {
97
+ version: pkg.version,
98
+ node: process.execPath,
99
+ appRoot: join(destination, 'node_modules', packageName, 'dist'),
100
+ };
68
101
  }
69
102
  finally {
70
103
  rmSync(staging, { recursive: true, force: true });
71
104
  }
72
105
  }
73
- export function activateRuntime(home, current, projects) {
106
+ export function activateRuntime(home, current, projects, antigravityConfig) {
74
107
  const previous = readInstallation(home);
75
- atomicWrite(runtimePaths(home).state, JSON.stringify({ schema: 1, current, previous: previous?.current, projects }, null, 2) + '\n');
108
+ atomicWrite(runtimePaths(home).state, JSON.stringify({
109
+ schema: 1,
110
+ current,
111
+ previous: previous?.current,
112
+ projects,
113
+ antigravityConfig: antigravityConfig ?? previous?.antigravityConfig,
114
+ }, null, 2) + '\n');
115
+ }
116
+ export function assertRuntimeCompatibility(runtime, projects) {
117
+ const marker = join(runtime.appRoot, 'memory-schema.json');
118
+ const supported = existsSync(marker)
119
+ ? JSON.parse(readFileSync(marker, 'utf8')).supportedSchema
120
+ : 0;
121
+ if (!Number.isInteger(supported) || supported < 0)
122
+ throw new Error('Invalid runtime schema compatibility metadata');
123
+ for (const database of new Set(projects.map((p) => p.database))) {
124
+ if (!existsSync(database))
125
+ continue;
126
+ const db = new DatabaseSync(database, { readOnly: true });
127
+ try {
128
+ const actual = Number(db.prepare('PRAGMA user_version').get().user_version);
129
+ if (actual > supported)
130
+ throw new Error('Runtime is incompatible with memory schema ' +
131
+ actual +
132
+ '. Use a compatible runtime or explicitly restore a consistent backup; no data was changed.');
133
+ }
134
+ finally {
135
+ db.close();
136
+ }
137
+ }
76
138
  }
@@ -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
+ }