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

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 (30) hide show
  1. package/README.md +15 -20
  2. package/dist/apps/server/src/server.js +37 -147
  3. package/dist/packages/adapters/src/cli.js +15 -163
  4. package/dist/packages/adapters/src/command.js +18 -149
  5. package/dist/packages/adapters/src/hooks.js +23 -96
  6. package/dist/packages/adapters/src/launch.js +3 -10
  7. package/dist/packages/adapters/src/repository.js +5 -21
  8. package/dist/packages/adapters/src/transcript.js +15 -70
  9. package/dist/packages/installer/src/cli.js +75 -190
  10. package/dist/packages/installer/src/connections.js +79 -196
  11. package/dist/packages/installer/src/runtime.js +37 -94
  12. package/dist/packages/memory/src/store.js +23 -201
  13. package/dist/scripts/connector-setup.js +1 -1
  14. package/dist/skills/{continue-chat → knit}/SKILL.md +2 -2
  15. package/docs/clients/connector-setup.md +1 -1
  16. package/docs/clients/npm-installation.md +17 -22
  17. package/docs/clients/support-matrix.md +37 -0
  18. package/docs/usage.md +179 -0
  19. package/package.json +5 -4
  20. package/dist/apps/server/src/conversation-server.js +0 -203
  21. package/dist/memory-schema.json +0 -1
  22. package/dist/packages/adapters/src/discovery.js +0 -128
  23. package/dist/packages/adapters/src/providers/jsonl.js +0 -105
  24. package/dist/packages/adapters/src/status.js +0 -81
  25. package/dist/packages/contracts/src/conversations.js +0 -30
  26. package/dist/packages/memory/src/checkpoints.js +0 -68
  27. package/dist/packages/memory/src/context.js +0 -91
  28. package/dist/packages/memory/src/conversations.js +0 -148
  29. package/dist/packages/memory/src/migrations.js +0 -55
  30. package/docs/clients/local-agent-memory.md +0 -50
@@ -1,26 +1,21 @@
1
- import { hookCommand, isManagedHook } from "./platform.js";
2
- import { readFileSync, existsSync, mkdirSync, writeFileSync, renameSync, rmSync, realpathSync, } from "node:fs";
3
- import { join, dirname, resolve } from "node:path";
4
- import { execFileSync } from "node:child_process";
5
- import { randomUUID } from "node:crypto";
6
- import { parse as parseToml } from "smol-toml";
7
- export const clients = [
8
- "codex",
9
- "claude-code",
10
- "antigravity",
11
- "claude-desktop",
12
- ];
13
- const begin = "# BEGIN shared-agent-memory", end = "# END shared-agent-memory";
14
- const statePath = ".memory/npm-connection.json";
15
- const read = (path) => existsSync(path) ? readFileSync(path, "utf8") : null;
16
- const dump = (v) => JSON.stringify(v, null, 2) + "\n";
17
- const object = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
1
+ import { hookCommand, isManagedHook } from './platform.js';
2
+ import { readFileSync, existsSync, mkdirSync, writeFileSync, renameSync, rmSync, realpathSync } from 'node:fs';
3
+ import { join, dirname, resolve } from 'node:path';
4
+ import { execFileSync } from 'node:child_process';
5
+ import { randomUUID } from 'node:crypto';
6
+ import { parse as parseToml } from 'smol-toml';
7
+ export const clients = ['codex', 'claude-code', 'antigravity', 'claude-desktop'];
8
+ const begin = '# BEGIN shared-agent-memory', end = '# END shared-agent-memory';
9
+ const statePath = '.memory/npm-connection.json';
10
+ const read = (path) => existsSync(path) ? readFileSync(path, 'utf8') : null;
11
+ const dump = (v) => JSON.stringify(v, null, 2) + '\n';
12
+ const object = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
18
13
  const equal = (a, b) => JSON.stringify(a) === JSON.stringify(b);
19
14
  export function atomicWrite(path, content) {
20
15
  mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
21
- const temporary = path + "." + randomUUID() + ".tmp";
16
+ const temporary = path + '.' + randomUUID() + '.tmp';
22
17
  try {
23
- writeFileSync(temporary, content, { mode: 0o600, flag: "wx" });
18
+ writeFileSync(temporary, content, { mode: 0o600, flag: 'wx' });
24
19
  renameSync(temporary, path);
25
20
  }
26
21
  finally {
@@ -32,19 +27,11 @@ export function atomicWrite(path, content) {
32
27
  function restore(before, after, current) {
33
28
  if (equal(current, after))
34
29
  return before;
35
- if (object(after) &&
36
- object(current) &&
37
- typeof after.command === "string" &&
38
- Array.isArray(after.args))
30
+ if (object(after) && object(current) && typeof after.command === 'string' && Array.isArray(after.args))
39
31
  return current;
40
- if (object(after) &&
41
- object(current) &&
42
- (before === undefined || object(before))) {
32
+ if (object(after) && object(current) && (before === undefined || object(before))) {
43
33
  const result = { ...current };
44
- for (const key of new Set([
45
- ...Object.keys(before ?? {}),
46
- ...Object.keys(after),
47
- ])) {
34
+ for (const key of new Set([...Object.keys(before ?? {}), ...Object.keys(after)])) {
48
35
  if (equal(before?.[key], after[key]))
49
36
  continue;
50
37
  const value = restore(before?.[key], after[key], current[key]);
@@ -53,18 +40,14 @@ function restore(before, after, current) {
53
40
  else
54
41
  result[key] = value;
55
42
  }
56
- return Object.keys(result).length === 0 && before === undefined
57
- ? undefined
58
- : result;
43
+ return Object.keys(result).length === 0 && before === undefined ? undefined : result;
59
44
  }
60
- if (Array.isArray(after) &&
61
- Array.isArray(current) &&
62
- (before === undefined || Array.isArray(before))) {
45
+ if (Array.isArray(after) && Array.isArray(current) && (before === undefined || Array.isArray(before))) {
63
46
  const previous = before ?? [];
64
- const added = after.filter((v) => !previous.some((p) => equal(p, v)));
65
- const result = current.filter((v) => !added.some((a) => equal(a, v)));
47
+ const added = after.filter(v => !previous.some((p) => equal(p, v)));
48
+ const result = current.filter(v => !added.some(a => equal(a, v)));
66
49
  for (const v of previous)
67
- if (!after.some((a) => equal(a, v)) && !result.some((a) => equal(a, v)))
50
+ if (!after.some(a => equal(a, v)) && !result.some(a => equal(a, v)))
68
51
  result.push(v);
69
52
  return result.length === 0 && before === undefined ? undefined : result;
70
53
  }
@@ -76,116 +59,59 @@ export function readConnectionState(workspace) {
76
59
  return { schema: 1, files: {} };
77
60
  const value = JSON.parse(text);
78
61
  if (value.schema !== 1 || !object(value.files))
79
- throw new Error("Unsupported connector state");
62
+ throw new Error('Unsupported connector state');
80
63
  for (const [file, snapshot] of Object.entries(value.files)) {
81
- if (![
82
- ".mcp.json",
83
- ".codex/config.toml",
84
- ".codex/hooks.json",
85
- ".agents/hooks.json",
86
- ".agents/mcp_config.json",
87
- ".agents/skills/continue-chat/SKILL.md",
88
- ".claude/settings.local.json",
89
- ".claude/skills/continue-chat/SKILL.md",
90
- ".memory/connectors/claude-desktop.json",
91
- ].includes(file) ||
92
- !object(snapshot) ||
93
- typeof snapshot.after !== "string" ||
94
- !(snapshot.before === null || typeof snapshot.before === "string"))
95
- throw new Error("Invalid connector state");
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'))
66
+ throw new Error('Invalid connector state');
96
67
  }
97
68
  return value;
98
69
  }
99
70
  export function planConnection(opts) {
100
71
  const workspace = realpathSync(opts.workspace), app = resolve(opts.appRoot), node = opts.node ?? process.execPath;
101
- if (!opts.clients.length ||
102
- opts.clients.some((c) => !clients.includes(c)))
103
- throw new Error("Choose a supported client");
104
- const extension = existsSync(join(app, "apps/server/src/main.js"))
105
- ? "js"
106
- : "ts";
107
- const server = join(app, "apps/server/src/main." + extension), runner = join(app, "packages/adapters/src/cli." + extension);
72
+ if (!opts.clients.length || opts.clients.some(c => !clients.includes(c)))
73
+ throw new Error('Choose a supported client');
74
+ const extension = existsSync(join(app, 'apps/server/src/main.js')) ? 'js' : 'ts';
75
+ const server = join(app, 'apps/server/src/main.' + extension), runner = join(app, 'packages/adapters/src/cli.' + extension);
108
76
  if (!existsSync(server) || !existsSync(runner))
109
- throw new Error("Runtime files missing");
77
+ throw new Error('Runtime files missing');
110
78
  const state = readConnectionState(workspace), changes = {}, expected = {};
111
- const get = (path) => {
112
- const content = read(join(workspace, path));
113
- expected[path] = content;
114
- return content;
115
- };
116
- const json = (path) => {
117
- const v = JSON.parse(get(path) ?? "{}");
118
- if (!object(v))
119
- throw new Error(path + " must be an object");
120
- return v;
121
- };
122
- const env = {
123
- MEMORY_DB: resolve(opts.database),
124
- MEMORY_REPO: opts.repoId,
125
- MEMORY_WORKSPACE: workspace,
126
- MEMORY_SESSION_SELECTION: "1",
127
- ...(opts.captureNewSessions
128
- ? { MEMORY_CONVERSATION_MODE: "1", MEMORY_CAPTURE_NEW_SESSIONS: "1" }
129
- : {}),
130
- };
131
- const handler = (client, action) => ({
132
- type: "command",
133
- timeout: 10,
134
- command: hookCommand({
135
- ...env,
136
- MEMORY_QUEUE: join(dirname(opts.database), "queue", client),
137
- MEMORY_MANAGED: "shared-agent-memory",
138
- }, node, [runner, action, client]),
139
- });
140
- const connection = (desktop = false, client = "claude") => {
141
- const clientEnv = {
142
- ...env,
143
- ...(desktop ? { MEMORY_CHAT_CLIENT: "claude-desktop" } : {}),
144
- ...(!desktop && opts.captureNewSessions ? { MEMORY_CLIENT: client } : {}),
145
- };
146
- if (desktop) {
147
- delete clientEnv.MEMORY_CONVERSATION_MODE;
148
- delete clientEnv.MEMORY_CAPTURE_NEW_SESSIONS;
149
- }
150
- return { command: node, args: [server], env: clientEnv };
151
- };
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' } : {}) } });
152
85
  function owned(path, location, current) {
153
86
  if (current === undefined)
154
87
  return;
155
88
  const prior = state.files[path];
156
- const previous = prior
157
- ? location.reduce((v, key) => v?.[key], JSON.parse(prior.after))
158
- : undefined;
89
+ const previous = prior ? location.reduce((v, key) => v?.[key], JSON.parse(prior.after)) : undefined;
159
90
  if (!equal(current, previous))
160
- throw new Error("Unmanaged or modified connector conflict in " + path);
91
+ throw new Error('Unmanaged or modified connector conflict in ' + path);
161
92
  }
162
- function mcp(path, desktop = false, client = "claude") {
93
+ function mcp(path, desktop = false) {
163
94
  const value = json(path);
164
95
  value.mcpServers ??= {};
165
- owned(path, ["mcpServers", "shared-memory"], value.mcpServers["shared-memory"]);
166
- value.mcpServers["shared-memory"] = connection(desktop, client);
96
+ owned(path, ['mcpServers', 'shared-memory'], value.mcpServers['shared-memory']);
97
+ value.mcpServers['shared-memory'] = connection(desktop);
167
98
  changes[path] = dump(value);
168
99
  }
169
100
  function hooks(path, client) {
170
101
  const value = json(path);
171
102
  value.hooks ??= {};
172
- const prior = state.files[path]
173
- ? JSON.parse(state.files[path].after).hooks
174
- : {};
175
- for (const [event, action] of [
176
- ["SessionStart", "recall"],
177
- ["Stop", "capture"],
178
- ]) {
103
+ const prior = state.files[path] ? JSON.parse(state.files[path].after).hooks : {};
104
+ for (const [event, action] of [['SessionStart', 'recall'], ['Stop', 'capture']]) {
179
105
  const old = prior?.[event] ?? [];
180
106
  const groups = value.hooks[event] ?? [];
181
107
  if (!Array.isArray(groups))
182
- throw new Error("Invalid hooks in " + path);
108
+ throw new Error('Invalid hooks in ' + path);
183
109
  // Only remove exact previously generated handlers. Edited handlers remain;
184
110
  // reject if they mention our runner to avoid duplicate capture.
185
111
  const oldOwned = old.filter((g) => g.hooks?.some((h) => isManagedHook(h.command)));
186
112
  const kept = groups.filter((g) => !oldOwned.some((p) => equal(p, g)));
187
113
  if (kept.some((g) => g.hooks?.some((h) => isManagedHook(h.command))))
188
- throw new Error("Modified hook conflict in " + path);
114
+ throw new Error('Modified hook conflict in ' + path);
189
115
  value.hooks[event] = [...kept, { hooks: [handler(client, action)] }];
190
116
  }
191
117
  changes[path] = dump(value);
@@ -193,72 +119,45 @@ export function planConnection(opts) {
193
119
  function skill(path) {
194
120
  const current = get(path);
195
121
  if (current && current !== state.files[path]?.after)
196
- throw new Error("Unmanaged or modified skill conflict");
197
- changes[path] = readFileSync(join(app, "skills/continue-chat/SKILL.md"), "utf8");
122
+ throw new Error('Unmanaged or modified skill conflict');
123
+ changes[path] = readFileSync(join(app, 'skills/knit/SKILL.md'), 'utf8');
198
124
  }
199
125
  for (const client of opts.clients) {
200
- if (client === "claude-code") {
201
- mcp(".mcp.json");
202
- hooks(".claude/settings.local.json", "claude");
203
- skill(".claude/skills/continue-chat/SKILL.md");
126
+ if (client === 'claude-code') {
127
+ mcp('.mcp.json');
128
+ hooks('.claude/settings.local.json', 'claude');
129
+ skill('.claude/skills/knit/SKILL.md');
204
130
  }
205
- if (client === "claude-desktop")
206
- mcp(".memory/connectors/claude-desktop.json", true);
207
- if (client === "antigravity") {
208
- mcp(".agents/mcp_config.json", false, "antigravity");
209
- const path = ".agents/hooks.json", value = json(path);
210
- owned(path, ["shared-memory"], value["shared-memory"]);
211
- value["shared-memory"] = {
212
- SessionStart: [handler("antigravity", "recall")],
213
- Stop: [handler("antigravity", "capture")],
214
- };
131
+ if (client === 'claude-desktop')
132
+ mcp('.memory/connectors/claude-desktop.json', true);
133
+ if (client === 'antigravity') {
134
+ mcp('.agents/mcp_config.json');
135
+ const path = '.agents/hooks.json', value = json(path);
136
+ owned(path, ['shared-memory'], value['shared-memory']);
137
+ value['shared-memory'] = { SessionStart: [handler('antigravity', 'recall')], Stop: [handler('antigravity', 'capture')] };
215
138
  changes[path] = dump(value);
216
139
  }
217
- if (client === "codex") {
218
- skill(".agents/skills/continue-chat/SKILL.md");
219
- hooks(".codex/hooks.json", "codex");
220
- const path = ".codex/config.toml", current = get(path) ?? "";
140
+ if (client === 'codex') {
141
+ skill('.agents/skills/knit/SKILL.md');
142
+ hooks('.codex/hooks.json', 'codex');
143
+ const path = '.codex/config.toml', current = get(path) ?? '';
221
144
  const parsed = parseToml(current);
222
145
  let base = current;
223
146
  if (current.includes(begin)) {
224
147
  const previous = state.files[path];
225
148
  const block = current.slice(current.indexOf(begin), current.indexOf(end) + end.length);
226
149
  if (!previous || !previous.after.includes(block))
227
- throw new Error("Modified or unmanaged Codex config conflict");
228
- base = current.replace(block, "");
150
+ throw new Error('Modified or unmanaged Codex config conflict');
151
+ base = current.replace(block, '');
229
152
  }
230
- else if (parsed.mcp_servers?.["shared-memory"])
231
- throw new Error("Unmanaged Codex server conflict");
232
- changes[path] =
233
- base.trimEnd() +
234
- "\n\n" +
235
- begin +
236
- '\n[mcp_servers.shared-memory]\ndefault_tools_approval_mode = "writes"\ncommand = ' +
237
- JSON.stringify(node) +
238
- "\nargs = " +
239
- JSON.stringify([server]) +
240
- "\ncwd = " +
241
- JSON.stringify(workspace) +
242
- "\nenv = { " +
243
- Object.entries({
244
- ...env,
245
- ...(opts.captureNewSessions ? { MEMORY_CLIENT: "codex" } : {}),
246
- })
247
- .map(([k, v]) => k + " = " + JSON.stringify(v))
248
- .join(", ") +
249
- ' }\ntools.choose_conversation.approval_mode = "approve"\n' +
250
- end +
251
- "\n";
153
+ else if (parsed.mcp_servers?.['shared-memory'])
154
+ 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';
252
156
  parseToml(changes[path]);
253
157
  }
254
158
  }
255
159
  for (const [path, after] of Object.entries(changes))
256
- state.files[path] = {
257
- before: state.files[path]
258
- ? unapply(path, state.files[path], expected[path] ?? null)
259
- : (expected[path] ?? null),
260
- after,
261
- };
160
+ state.files[path] = { before: state.files[path] ? unapply(path, state.files[path], expected[path] ?? null) : expected[path] ?? null, after };
262
161
  expected[statePath] = read(join(workspace, statePath));
263
162
  changes[statePath] = dump(state);
264
163
  return { workspace, changes, expected };
@@ -267,7 +166,7 @@ export function applyConnectionPlan(plan) {
267
166
  // Optimistic concurrency prevents applying a preview over later user edits.
268
167
  for (const [path, expected] of Object.entries(plan.expected))
269
168
  if (read(join(plan.workspace, path)) !== expected)
270
- throw new Error("Configuration changed since preview: " + path);
169
+ throw new Error('Configuration changed since preview: ' + path);
271
170
  const written = [];
272
171
  try {
273
172
  for (const [path, content] of Object.entries(plan.changes)) {
@@ -289,39 +188,25 @@ export function applyConnectionPlan(plan) {
289
188
  throw error;
290
189
  }
291
190
  try {
292
- const git = execFileSync("git", ["rev-parse", "--path-format=absolute", "--git-common-dir"], {
293
- cwd: plan.workspace,
294
- encoding: "utf8",
295
- stdio: ["ignore", "pipe", "ignore"],
296
- }).trim();
297
- const path = join(git, "info/exclude"), current = read(path) ?? "";
298
- const entries = [
299
- "/.memory/",
300
- ...Object.keys(plan.changes)
301
- .filter((p) => !p.startsWith(".memory/"))
302
- .map((p) => "/" + p),
303
- ];
304
- atomicWrite(path, current +
305
- "\n" +
306
- entries.filter((p) => !current.split("\n").includes(p)).join("\n") +
307
- "\n");
308
- }
309
- catch {
310
- /* Non-Git projects can use the planner; CLI validates Git separately. */
191
+ const git = execFileSync('git', ['rev-parse', '--path-format=absolute', '--git-common-dir'], { cwd: plan.workspace, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
192
+ 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');
311
195
  }
196
+ catch { /* Non-Git projects can use the planner; CLI validates Git separately. */ }
312
197
  }
313
198
  function unapply(path, snapshot, current) {
314
199
  const { before, after } = snapshot;
315
200
  if (current === null || current === after)
316
201
  return current === null ? null : before;
317
- if (path.endsWith(".json")) {
202
+ if (path.endsWith('.json')) {
318
203
  const restored = restore(before === null ? undefined : JSON.parse(before), JSON.parse(after), JSON.parse(current));
319
204
  return restored === undefined ? null : dump(restored);
320
205
  }
321
- if (path.endsWith(".toml")) {
206
+ if (path.endsWith('.toml')) {
322
207
  const block = after.slice(after.indexOf(begin), after.indexOf(end) + end.length);
323
208
  if (current.includes(block))
324
- return current.replace(block, "").trim() || before;
209
+ return current.replace(block, '').trim() || before;
325
210
  }
326
211
  return current;
327
212
  }
@@ -336,6 +221,4 @@ export function planUninstall(workspace) {
336
221
  changes[statePath] = null;
337
222
  return { workspace, changes, expected };
338
223
  }
339
- export function uninstallConnections(workspace) {
340
- applyConnectionPlan(planUninstall(workspace));
341
- }
224
+ export function uninstallConnections(workspace) { applyConnectionPlan(planUninstall(workspace)); }
@@ -1,51 +1,41 @@
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 { npmCommand } from "./platform.js";
7
- import { randomUUID } from "node:crypto";
8
- import { atomicWrite } from "./connections.js";
9
- export const packageName = "@tinchu0/knitt";
1
+ import { homedir } from 'node:os';
2
+ import { join, resolve } from 'node:path';
3
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, mkdtempSync, writeFileSync } from 'node:fs';
4
+ import { execFileSync } from 'node:child_process';
5
+ import { randomUUID } from 'node:crypto';
6
+ import { npmCommand } from './platform.js';
7
+ import { atomicWrite } from './connections.js';
8
+ export const packageName = '@tinchu0/knitt';
10
9
  export function defaultHome() {
11
10
  if (process.env.SHARED_MEMORY_HOME)
12
11
  return resolve(process.env.SHARED_MEMORY_HOME);
13
- if (process.platform === "darwin")
14
- return join(homedir(), "Library/Application Support/SharedAgentMemory");
15
- if (process.platform === "win32")
16
- return join(process.env.LOCALAPPDATA ?? join(homedir(), "AppData/Local"), "SharedAgentMemory");
17
- return join(process.env.XDG_DATA_HOME ?? join(homedir(), ".local/share"), "shared-agent-memory");
18
- }
19
- export function runtimePaths(home) {
20
- return {
21
- data: join(home, "data"),
22
- versions: join(home, "versions"),
23
- state: join(home, "installation.json"),
24
- };
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');
25
17
  }
18
+ export function runtimePaths(home) { return { data: join(home, 'data'), versions: join(home, 'versions'), state: join(home, 'installation.json') }; }
26
19
  export function readInstallation(home) {
27
20
  const path = runtimePaths(home).state;
28
21
  if (!existsSync(path))
29
22
  return null;
30
- const value = JSON.parse(readFileSync(path, "utf8"));
31
- if (value.schema !== 1 ||
32
- !value.current?.appRoot ||
33
- !Array.isArray(value.projects))
34
- throw new Error("Invalid installation metadata");
23
+ const value = JSON.parse(readFileSync(path, 'utf8'));
24
+ if (value.schema !== 1 || !value.current?.appRoot || !Array.isArray(value.projects))
25
+ throw new Error('Invalid installation metadata');
35
26
  return value;
36
27
  }
37
28
  export async function withInstallLock(home, work) {
38
29
  mkdirSync(home, { recursive: true, mode: 0o700 });
39
- const lock = join(home, "install.lock");
30
+ const lock = join(home, 'install.lock');
40
31
  try {
41
32
  mkdirSync(lock, { mode: 0o700 });
42
33
  }
43
34
  catch {
44
- throw new Error("Another installation is running, or a stale install.lock remains. Check for a running setup process before removing " +
45
- lock);
35
+ throw new Error('Another installation is running, or a stale install.lock remains. Check for a running setup process before removing ' + lock);
46
36
  }
47
37
  try {
48
- writeFileSync(join(lock, "owner.json"), JSON.stringify({ pid: process.pid, started: new Date().toISOString() }), { mode: 0o600 });
38
+ writeFileSync(join(lock, 'owner.json'), JSON.stringify({ pid: process.pid, started: new Date().toISOString() }), { mode: 0o600 });
49
39
  return await work();
50
40
  }
51
41
  finally {
@@ -53,47 +43,28 @@ export async function withInstallLock(home, work) {
53
43
  }
54
44
  }
55
45
  export function installRuntime(home, spec) {
56
- if (Number(process.versions.node.split(".")[0]) < 24)
57
- throw new Error("Node.js 24 or newer is required");
46
+ if (Number(process.versions.node.split('.')[0]) < 24)
47
+ throw new Error('Node.js 24 or newer is required');
58
48
  const paths = runtimePaths(home);
59
49
  mkdirSync(paths.versions, { recursive: true, mode: 0o700 });
60
50
  mkdirSync(paths.data, { recursive: true, mode: 0o700 });
61
- const staging = mkdtempSync(join(paths.versions, ".staging-"));
51
+ const staging = mkdtempSync(join(paths.versions, '.staging-'));
62
52
  try {
63
- writeFileSync(join(staging, "package.json"), JSON.stringify({ name: "shared-memory-runtime", private: true }), { mode: 0o600 });
53
+ writeFileSync(join(staging, 'package.json'), JSON.stringify({ name: 'shared-memory-runtime', private: true }), { mode: 0o600 });
64
54
  // Arguments are passed directly; no shell interpolation or install lifecycle scripts.
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, { 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());
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 });
57
+ const root = join(staging, 'node_modules', packageName);
58
+ const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
59
+ if (pkg.name !== packageName || !/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(pkg.version))
60
+ throw new Error('Unexpected runtime package');
61
+ for (const file of ['apps/server/src/main.js', 'packages/installer/src/cli.js'])
62
+ if (!existsSync(join(root, 'dist', file)))
63
+ throw new Error('Incomplete runtime: ' + file);
64
+ execFileSync(process.execPath, [join(root, 'dist/packages/installer/src/cli.js'), '--version'], { encoding: 'utf8', timeout: 10_000 });
65
+ const destination = join(paths.versions, pkg.version + '-' + randomUUID());
91
66
  renameSync(staging, destination);
92
- return {
93
- version: pkg.version,
94
- node: process.execPath,
95
- appRoot: join(destination, "node_modules", packageName, "dist"),
96
- };
67
+ return { version: pkg.version, node: process.execPath, appRoot: join(destination, 'node_modules', packageName, 'dist') };
97
68
  }
98
69
  finally {
99
70
  rmSync(staging, { recursive: true, force: true });
@@ -101,33 +72,5 @@ export function installRuntime(home, spec) {
101
72
  }
102
73
  export function activateRuntime(home, current, projects) {
103
74
  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
- }
75
+ atomicWrite(runtimePaths(home).state, JSON.stringify({ schema: 1, current, previous: previous?.current, projects }, null, 2) + '\n');
133
76
  }