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

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.
@@ -1,20 +1,26 @@
1
- import { readFileSync, existsSync, mkdirSync, writeFileSync, renameSync, rmSync, realpathSync } from 'node:fs';
2
- import { join, dirname, resolve } from 'node:path';
3
- import { execFileSync } from 'node:child_process';
4
- import { randomUUID } from 'node:crypto';
5
- import { parse as parseToml } from 'smol-toml';
6
- export const clients = ['codex', 'claude-code', 'antigravity', 'claude-desktop'];
7
- const begin = '# BEGIN shared-agent-memory', end = '# END shared-agent-memory';
8
- const statePath = '.memory/npm-connection.json';
9
- const read = (path) => existsSync(path) ? readFileSync(path, 'utf8') : null;
10
- const dump = (v) => JSON.stringify(v, null, 2) + '\n';
11
- 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 = [
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);
12
18
  const equal = (a, b) => JSON.stringify(a) === JSON.stringify(b);
13
19
  export function atomicWrite(path, content) {
14
20
  mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
15
- const temporary = path + '.' + randomUUID() + '.tmp';
21
+ const temporary = path + "." + randomUUID() + ".tmp";
16
22
  try {
17
- writeFileSync(temporary, content, { mode: 0o600, flag: 'wx' });
23
+ writeFileSync(temporary, content, { mode: 0o600, flag: "wx" });
18
24
  renameSync(temporary, path);
19
25
  }
20
26
  finally {
@@ -26,11 +32,19 @@ export function atomicWrite(path, content) {
26
32
  function restore(before, after, current) {
27
33
  if (equal(current, after))
28
34
  return before;
29
- if (object(after) && object(current) && typeof after.command === 'string' && Array.isArray(after.args))
35
+ if (object(after) &&
36
+ object(current) &&
37
+ typeof after.command === "string" &&
38
+ Array.isArray(after.args))
30
39
  return current;
31
- if (object(after) && object(current) && (before === undefined || object(before))) {
40
+ if (object(after) &&
41
+ object(current) &&
42
+ (before === undefined || object(before))) {
32
43
  const result = { ...current };
33
- for (const key of new Set([...Object.keys(before ?? {}), ...Object.keys(after)])) {
44
+ for (const key of new Set([
45
+ ...Object.keys(before ?? {}),
46
+ ...Object.keys(after),
47
+ ])) {
34
48
  if (equal(before?.[key], after[key]))
35
49
  continue;
36
50
  const value = restore(before?.[key], after[key], current[key]);
@@ -39,14 +53,18 @@ function restore(before, after, current) {
39
53
  else
40
54
  result[key] = value;
41
55
  }
42
- return Object.keys(result).length === 0 && before === undefined ? undefined : result;
56
+ return Object.keys(result).length === 0 && before === undefined
57
+ ? undefined
58
+ : result;
43
59
  }
44
- if (Array.isArray(after) && Array.isArray(current) && (before === undefined || Array.isArray(before))) {
60
+ if (Array.isArray(after) &&
61
+ Array.isArray(current) &&
62
+ (before === undefined || Array.isArray(before))) {
45
63
  const previous = before ?? [];
46
- const added = after.filter(v => !previous.some((p) => equal(p, v)));
47
- const result = current.filter(v => !added.some(a => equal(a, v)));
64
+ const added = after.filter((v) => !previous.some((p) => equal(p, v)));
65
+ const result = current.filter((v) => !added.some((a) => equal(a, v)));
48
66
  for (const v of previous)
49
- if (!after.some(a => equal(a, v)) && !result.some(a => equal(a, v)))
67
+ if (!after.some((a) => equal(a, v)) && !result.some((a) => equal(a, v)))
50
68
  result.push(v);
51
69
  return result.length === 0 && before === undefined ? undefined : result;
52
70
  }
@@ -58,62 +76,116 @@ export function readConnectionState(workspace) {
58
76
  return { schema: 1, files: {} };
59
77
  const value = JSON.parse(text);
60
78
  if (value.schema !== 1 || !object(value.files))
61
- throw new Error('Unsupported connector state');
79
+ throw new Error("Unsupported connector state");
62
80
  for (const [file, snapshot] of Object.entries(value.files)) {
63
- if (!['.mcp.json', '.codex/config.toml', '.codex/hooks.json', '.agents/hooks.json', '.agents/mcp_config.json', '.agents/skills/continue-chat/SKILL.md', '.claude/settings.local.json', '.claude/skills/continue-chat/SKILL.md', '.memory/connectors/claude-desktop.json'].includes(file)
64
- || !object(snapshot) || typeof snapshot.after !== 'string' || !(snapshot.before === null || typeof snapshot.before === 'string'))
65
- throw new Error('Invalid connector state');
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");
66
96
  }
67
97
  return value;
68
98
  }
69
99
  export function planConnection(opts) {
70
- if (process.platform === 'win32')
71
- throw new Error('Windows hook installation is not yet validated. Use WSL for this preview.');
72
100
  const workspace = realpathSync(opts.workspace), app = resolve(opts.appRoot), node = opts.node ?? process.execPath;
73
- if (!opts.clients.length || opts.clients.some(c => !clients.includes(c)))
74
- throw new Error('Choose a supported client');
75
- const extension = existsSync(join(app, 'apps/server/src/main.js')) ? 'js' : 'ts';
76
- const server = join(app, 'apps/server/src/main.' + extension), runner = join(app, 'packages/adapters/src/cli.' + extension);
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);
77
108
  if (!existsSync(server) || !existsSync(runner))
78
- throw new Error('Runtime files missing');
109
+ throw new Error("Runtime files missing");
79
110
  const state = readConnectionState(workspace), changes = {}, expected = {};
80
- const get = (path) => { const content = read(join(workspace, path)); expected[path] = content; return content; };
81
- const json = (path) => { const v = JSON.parse(get(path) ?? '{}'); if (!object(v))
82
- throw new Error(path + ' must be an object'); return v; };
83
- const env = { MEMORY_DB: resolve(opts.database), MEMORY_REPO: opts.repoId, MEMORY_WORKSPACE: workspace, MEMORY_SESSION_SELECTION: '1' };
84
- const quote = (s) => "'" + s.replaceAll("'", "'\\''") + "'";
85
- const handler = (client, action) => ({ type: 'command', timeout: 10, command: ['env', ...Object.entries({ ...env, MEMORY_QUEUE: join(dirname(opts.database), 'queue', client), MEMORY_MANAGED: 'shared-agent-memory' }).map(([k, v]) => k + '=' + v), node, runner, action, client].map(quote).join(' ') });
86
- const connection = (desktop = false) => ({ command: node, args: [server], env: { ...env, ...(desktop ? { MEMORY_CHAT_CLIENT: 'claude-desktop' } : {}) } });
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
+ };
87
152
  function owned(path, location, current) {
88
153
  if (current === undefined)
89
154
  return;
90
155
  const prior = state.files[path];
91
- const previous = prior ? location.reduce((v, key) => v?.[key], JSON.parse(prior.after)) : undefined;
156
+ const previous = prior
157
+ ? location.reduce((v, key) => v?.[key], JSON.parse(prior.after))
158
+ : undefined;
92
159
  if (!equal(current, previous))
93
- throw new Error('Unmanaged or modified connector conflict in ' + path);
160
+ throw new Error("Unmanaged or modified connector conflict in " + path);
94
161
  }
95
- function mcp(path, desktop = false) {
162
+ function mcp(path, desktop = false, client = "claude") {
96
163
  const value = json(path);
97
164
  value.mcpServers ??= {};
98
- owned(path, ['mcpServers', 'shared-memory'], value.mcpServers['shared-memory']);
99
- value.mcpServers['shared-memory'] = connection(desktop);
165
+ owned(path, ["mcpServers", "shared-memory"], value.mcpServers["shared-memory"]);
166
+ value.mcpServers["shared-memory"] = connection(desktop, client);
100
167
  changes[path] = dump(value);
101
168
  }
102
169
  function hooks(path, client) {
103
170
  const value = json(path);
104
171
  value.hooks ??= {};
105
- const prior = state.files[path] ? JSON.parse(state.files[path].after).hooks : {};
106
- for (const [event, action] of [['SessionStart', 'recall'], ['Stop', 'capture']]) {
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
+ ]) {
107
179
  const old = prior?.[event] ?? [];
108
180
  const groups = value.hooks[event] ?? [];
109
181
  if (!Array.isArray(groups))
110
- throw new Error('Invalid hooks in ' + path);
182
+ throw new Error("Invalid hooks in " + path);
111
183
  // Only remove exact previously generated handlers. Edited handlers remain;
112
184
  // reject if they mention our runner to avoid duplicate capture.
113
- const oldOwned = old.filter((g) => g.hooks?.some((h) => h.command?.includes('MEMORY_MANAGED=shared-agent-memory')));
185
+ const oldOwned = old.filter((g) => g.hooks?.some((h) => isManagedHook(h.command)));
114
186
  const kept = groups.filter((g) => !oldOwned.some((p) => equal(p, g)));
115
- if (kept.some((g) => g.hooks?.some((h) => h.command?.includes('MEMORY_MANAGED=shared-agent-memory'))))
116
- throw new Error('Modified hook conflict in ' + path);
187
+ if (kept.some((g) => g.hooks?.some((h) => isManagedHook(h.command))))
188
+ throw new Error("Modified hook conflict in " + path);
117
189
  value.hooks[event] = [...kept, { hooks: [handler(client, action)] }];
118
190
  }
119
191
  changes[path] = dump(value);
@@ -121,45 +193,72 @@ export function planConnection(opts) {
121
193
  function skill(path) {
122
194
  const current = get(path);
123
195
  if (current && current !== state.files[path]?.after)
124
- throw new Error('Unmanaged or modified skill conflict');
125
- changes[path] = readFileSync(join(app, 'skills/continue-chat/SKILL.md'), 'utf8');
196
+ throw new Error("Unmanaged or modified skill conflict");
197
+ changes[path] = readFileSync(join(app, "skills/continue-chat/SKILL.md"), "utf8");
126
198
  }
127
199
  for (const client of opts.clients) {
128
- if (client === 'claude-code') {
129
- mcp('.mcp.json');
130
- hooks('.claude/settings.local.json', 'claude');
131
- skill('.claude/skills/continue-chat/SKILL.md');
200
+ if (client === "claude-code") {
201
+ mcp(".mcp.json");
202
+ hooks(".claude/settings.local.json", "claude");
203
+ skill(".claude/skills/continue-chat/SKILL.md");
132
204
  }
133
- if (client === 'claude-desktop')
134
- mcp('.memory/connectors/claude-desktop.json', true);
135
- if (client === 'antigravity') {
136
- mcp('.agents/mcp_config.json');
137
- const path = '.agents/hooks.json', value = json(path);
138
- owned(path, ['shared-memory'], value['shared-memory']);
139
- value['shared-memory'] = { SessionStart: [handler('antigravity', 'recall')], Stop: [handler('antigravity', 'capture')] };
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
+ };
140
215
  changes[path] = dump(value);
141
216
  }
142
- if (client === 'codex') {
143
- skill('.agents/skills/continue-chat/SKILL.md');
144
- hooks('.codex/hooks.json', 'codex');
145
- const path = '.codex/config.toml', current = get(path) ?? '';
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) ?? "";
146
221
  const parsed = parseToml(current);
147
222
  let base = current;
148
223
  if (current.includes(begin)) {
149
224
  const previous = state.files[path];
150
225
  const block = current.slice(current.indexOf(begin), current.indexOf(end) + end.length);
151
226
  if (!previous || !previous.after.includes(block))
152
- throw new Error('Modified or unmanaged Codex config conflict');
153
- base = current.replace(block, '');
227
+ throw new Error("Modified or unmanaged Codex config conflict");
228
+ base = current.replace(block, "");
154
229
  }
155
- else if (parsed.mcp_servers?.['shared-memory'])
156
- throw new Error('Unmanaged Codex server conflict');
157
- 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';
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";
158
252
  parseToml(changes[path]);
159
253
  }
160
254
  }
161
255
  for (const [path, after] of Object.entries(changes))
162
- state.files[path] = { before: state.files[path] ? unapply(path, state.files[path], expected[path] ?? null) : expected[path] ?? null, after };
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
+ };
163
262
  expected[statePath] = read(join(workspace, statePath));
164
263
  changes[statePath] = dump(state);
165
264
  return { workspace, changes, expected };
@@ -168,7 +267,7 @@ export function applyConnectionPlan(plan) {
168
267
  // Optimistic concurrency prevents applying a preview over later user edits.
169
268
  for (const [path, expected] of Object.entries(plan.expected))
170
269
  if (read(join(plan.workspace, path)) !== expected)
171
- throw new Error('Configuration changed since preview: ' + path);
270
+ throw new Error("Configuration changed since preview: " + path);
172
271
  const written = [];
173
272
  try {
174
273
  for (const [path, content] of Object.entries(plan.changes)) {
@@ -190,25 +289,39 @@ export function applyConnectionPlan(plan) {
190
289
  throw error;
191
290
  }
192
291
  try {
193
- const git = execFileSync('git', ['rev-parse', '--path-format=absolute', '--git-common-dir'], { cwd: plan.workspace, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
194
- const path = join(git, 'info/exclude'), current = read(path) ?? '';
195
- const entries = ['/.memory/', ...Object.keys(plan.changes).filter(p => !p.startsWith('.memory/')).map(p => '/' + p)];
196
- atomicWrite(path, current + '\n' + entries.filter(p => !current.split('\n').includes(p)).join('\n') + '\n');
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. */
197
311
  }
198
- catch { /* Non-Git projects can use the planner; CLI validates Git separately. */ }
199
312
  }
200
313
  function unapply(path, snapshot, current) {
201
314
  const { before, after } = snapshot;
202
315
  if (current === null || current === after)
203
316
  return current === null ? null : before;
204
- if (path.endsWith('.json')) {
317
+ if (path.endsWith(".json")) {
205
318
  const restored = restore(before === null ? undefined : JSON.parse(before), JSON.parse(after), JSON.parse(current));
206
319
  return restored === undefined ? null : dump(restored);
207
320
  }
208
- if (path.endsWith('.toml')) {
321
+ if (path.endsWith(".toml")) {
209
322
  const block = after.slice(after.indexOf(begin), after.indexOf(end) + end.length);
210
323
  if (current.includes(block))
211
- return current.replace(block, '').trim() || before;
324
+ return current.replace(block, "").trim() || before;
212
325
  }
213
326
  return current;
214
327
  }
@@ -223,4 +336,6 @@ export function planUninstall(workspace) {
223
336
  changes[statePath] = null;
224
337
  return { workspace, changes, expected };
225
338
  }
226
- export function uninstallConnections(workspace) { applyConnectionPlan(planUninstall(workspace)); }
339
+ export function uninstallConnections(workspace) {
340
+ applyConnectionPlan(planUninstall(workspace));
341
+ }
@@ -0,0 +1,55 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ /** Resolve npm's JavaScript entry point on Windows: execFile cannot run npm.cmd.
4
+ * All package arguments stay in an argv array, never a command shell. */
5
+ export function npmCommand(args, options = {}) {
6
+ const platform = options.platform ?? process.platform, env = options.env ?? process.env, node = options.node ?? process.execPath;
7
+ if (platform !== 'win32')
8
+ return { command: 'npm', args };
9
+ const path = Object.entries(env).find(([key]) => key.toLowerCase() === 'path')?.[1] ?? '';
10
+ const candidates = [
11
+ ...(env.npm_execpath ? [join(dirname(env.npm_execpath), 'npm-cli.js')] : []),
12
+ join(dirname(node), 'node_modules/npm/bin/npm-cli.js'),
13
+ ...path.split(';').filter(Boolean).map(directory => join(directory.replace(/^"|"$/g, ''), 'node_modules/npm/bin/npm-cli.js')),
14
+ ];
15
+ const cli = candidates.find(candidate => existsSync(candidate));
16
+ if (!cli)
17
+ throw new Error('Cannot locate npm. Install Node.js 24+ with npm and add it to PATH.');
18
+ return { command: node, args: [cli, ...args] };
19
+ }
20
+ const marker = 'MEMORY_MANAGED=shared-agent-memory';
21
+ const powershell = 'powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand ';
22
+ /** Serialize a hook for the host shell without interpolating data as code. */
23
+ export function hookCommand(env, node, args, platform = process.platform) {
24
+ if (platform !== 'win32') {
25
+ const quote = (s) => "'" + s.replaceAll("'", "'\\''") + "'";
26
+ return ['env', ...Object.entries(env).map(([key, value]) => key + '=' + value), node, ...args].map(quote).join(' ');
27
+ }
28
+ const quote = (s) => "'" + s.replaceAll("'", "''") + "'";
29
+ // EncodedCommand avoids cmd.exe expanding %, &, or Unicode paths. PowerShell
30
+ // invokes Node directly with inherited stdin; no pipeline re-encodes hook JSON.
31
+ const assignments = Object.entries(env).map(([key, value]) => {
32
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))
33
+ throw new Error('Invalid hook environment key');
34
+ return '$env:' + key + '=' + quote(value) + ';';
35
+ }).join('');
36
+ const script = '[Console]::InputEncoding=[Console]::OutputEncoding=New-Object System.Text.UTF8Encoding;' +
37
+ assignments + '& ' + [node, ...args].map(quote).join(' ') + ';exit $LASTEXITCODE';
38
+ return powershell + Buffer.from(script, 'utf16le').toString('base64');
39
+ }
40
+ export function isManagedHook(command) {
41
+ if (typeof command !== 'string')
42
+ return false;
43
+ if (command.includes(marker))
44
+ return true; // Existing POSIX installations.
45
+ // PowerShell switches are case-insensitive and can be abbreviated/reordered.
46
+ // Recognize the payload even after a launcher edit so setup rejects conflicts.
47
+ for (const match of command.matchAll(/(?:^|\s)-([a-z]+)\s+(['"]?)([a-z0-9+/=]+)\2(?=\s|$)/gi)) {
48
+ if (!'encodedcommand'.startsWith(match[1].toLowerCase()))
49
+ continue;
50
+ const script = Buffer.from(match[3], 'base64').toString('utf16le');
51
+ if (/\$env:MEMORY_MANAGED\s*=\s*(['"])shared-agent-memory\1\s*;/i.test(script))
52
+ return true;
53
+ }
54
+ return false;
55
+ }
@@ -1,40 +1,51 @@
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 { atomicWrite } from './connections.js';
7
- export const packageName = '@tinchu0/knitt';
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";
8
10
  export function defaultHome() {
9
11
  if (process.env.SHARED_MEMORY_HOME)
10
12
  return resolve(process.env.SHARED_MEMORY_HOME);
11
- if (process.platform === 'darwin')
12
- return join(homedir(), 'Library/Application Support/SharedAgentMemory');
13
- if (process.platform === 'win32')
14
- return join(process.env.LOCALAPPDATA ?? join(homedir(), 'AppData/Local'), 'SharedAgentMemory');
15
- return join(process.env.XDG_DATA_HOME ?? join(homedir(), '.local/share'), 'shared-agent-memory');
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
+ };
16
25
  }
17
- export function runtimePaths(home) { return { data: join(home, 'data'), versions: join(home, 'versions'), state: join(home, 'installation.json') }; }
18
26
  export function readInstallation(home) {
19
27
  const path = runtimePaths(home).state;
20
28
  if (!existsSync(path))
21
29
  return null;
22
- const value = JSON.parse(readFileSync(path, 'utf8'));
23
- if (value.schema !== 1 || !value.current?.appRoot || !Array.isArray(value.projects))
24
- throw new Error('Invalid installation metadata');
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");
25
35
  return value;
26
36
  }
27
37
  export async function withInstallLock(home, work) {
28
38
  mkdirSync(home, { recursive: true, mode: 0o700 });
29
- const lock = join(home, 'install.lock');
39
+ const lock = join(home, "install.lock");
30
40
  try {
31
41
  mkdirSync(lock, { mode: 0o700 });
32
42
  }
33
43
  catch {
34
- 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);
35
46
  }
36
47
  try {
37
- writeFileSync(join(lock, 'owner.json'), JSON.stringify({ pid: process.pid, started: new Date().toISOString() }), { mode: 0o600 });
48
+ writeFileSync(join(lock, "owner.json"), JSON.stringify({ pid: process.pid, started: new Date().toISOString() }), { mode: 0o600 });
38
49
  return await work();
39
50
  }
40
51
  finally {
@@ -42,29 +53,47 @@ export async function withInstallLock(home, work) {
42
53
  }
43
54
  }
44
55
  export function installRuntime(home, spec) {
45
- if (process.platform === 'win32')
46
- throw new Error('Windows installer validation is pending; use WSL for this preview.');
47
- if (Number(process.versions.node.split('.')[0]) < 24)
48
- throw new Error('Node.js 24 or newer is required');
56
+ if (Number(process.versions.node.split(".")[0]) < 24)
57
+ throw new Error("Node.js 24 or newer is required");
49
58
  const paths = runtimePaths(home);
50
59
  mkdirSync(paths.versions, { recursive: true, mode: 0o700 });
51
60
  mkdirSync(paths.data, { recursive: true, mode: 0o700 });
52
- const staging = mkdtempSync(join(paths.versions, '.staging-'));
61
+ const staging = mkdtempSync(join(paths.versions, ".staging-"));
53
62
  try {
54
- writeFileSync(join(staging, 'package.json'), JSON.stringify({ name: 'shared-memory-runtime', private: true }), { mode: 0o600 });
63
+ writeFileSync(join(staging, "package.json"), JSON.stringify({ name: "shared-memory-runtime", private: true }), { mode: 0o600 });
55
64
  // Arguments are passed directly; no shell interpolation or install lifecycle scripts.
56
- execFileSync('npm', ['install', '--prefix', staging, '--ignore-scripts', '--omit=dev', '--no-audit', '--no-fund', '--save-exact', '--', spec], { 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());
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());
66
91
  renameSync(staging, destination);
67
- return { version: pkg.version, node: process.execPath, appRoot: join(destination, 'node_modules', packageName, 'dist') };
92
+ return {
93
+ version: pkg.version,
94
+ node: process.execPath,
95
+ appRoot: join(destination, "node_modules", packageName, "dist"),
96
+ };
68
97
  }
69
98
  finally {
70
99
  rmSync(staging, { recursive: true, force: true });
@@ -72,5 +101,33 @@ export function installRuntime(home, spec) {
72
101
  }
73
102
  export function activateRuntime(home, current, projects) {
74
103
  const previous = readInstallation(home);
75
- atomicWrite(runtimePaths(home).state, JSON.stringify({ schema: 1, current, previous: previous?.current, projects }, null, 2) + '\n');
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
+ }
76
133
  }