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

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.
@@ -0,0 +1,32 @@
1
+ import { execFileSync } from "node:child_process";
2
+ export function resolveConnection(payload, env = process.env) {
3
+ const repoId = env.MEMORY_REPO;
4
+ if (!repoId)
5
+ throw new Error("Set MEMORY_REPO for the connected repository");
6
+ const workspacePaths = payload.workspacePaths;
7
+ const workspace = typeof payload.cwd === "string" ? payload.cwd :
8
+ Array.isArray(workspacePaths) && workspacePaths.length === 1 && typeof workspacePaths[0] === "string"
9
+ ? workspacePaths[0] : process.cwd();
10
+ if (env.MEMORY_WORKSPACE) {
11
+ const commonGitDir = (cwd) => execFileSync("git", ["rev-parse", "--path-format=absolute", "--git-common-dir"], {
12
+ cwd, encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"],
13
+ }).trim();
14
+ if (commonGitDir(workspace) !== commonGitDir(env.MEMORY_WORKSPACE)) {
15
+ throw new Error("Wrong workspace. Open " + env.MEMORY_WORKSPACE + " to continue this handoff. No memory was recalled or captured.");
16
+ }
17
+ }
18
+ return { repoId, workspace };
19
+ }
20
+ export function resolveScope(payload, env = process.env) {
21
+ const { repoId, workspace } = resolveConnection(payload, env);
22
+ let branch = env.MEMORY_BRANCH;
23
+ if (!branch && !env.MEMORY_FEATURE) {
24
+ branch = execFileSync("git", ["branch", "--show-current"], {
25
+ cwd: workspace, encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"],
26
+ }).trim();
27
+ }
28
+ const featureId = env.MEMORY_FEATURE ?? branch;
29
+ if (!featureId)
30
+ throw new Error("Detached HEAD requires an explicit MEMORY_FEATURE");
31
+ return { repoId, featureId, ...(branch ? { branch } : {}) };
32
+ }
@@ -0,0 +1,138 @@
1
+ import { openSync, closeSync, fstatSync, readSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { createHash } from "node:crypto";
4
+ import { openQueue, redact } from "./hooks.js";
5
+ import { eventSchema } from "../../contracts/src/events.js";
6
+ const windowBytes = 4 * 1024 * 1024;
7
+ const maxLineBytes = 1024 * 1024;
8
+ const hash = (s) => createHash("sha256").update(s).digest("hex");
9
+ function textBlocks(value) {
10
+ if (typeof value === "string")
11
+ return value;
12
+ if (!Array.isArray(value))
13
+ return "";
14
+ return value.flatMap(block => {
15
+ if (block && typeof block === "object" && typeof block.text === "string" &&
16
+ (!block.type || ["text", "input_text", "output_text"].includes(block.type)))
17
+ return [block.text];
18
+ return [];
19
+ }).join("\n");
20
+ }
21
+ function messageText(row) {
22
+ if (row.type === "USER_INPUT" && typeof row.content === "string") {
23
+ const request = row.content.match(/<USER_REQUEST>([\s\S]*?)<\/USER_REQUEST>/);
24
+ return "user: " + (request ? request[1].trim() : row.content);
25
+ }
26
+ if (["PLANNER_RESPONSE", "ASSISTANT_MESSAGE"].includes(row.type) && typeof row.content === "string") {
27
+ return "assistant: " + row.content;
28
+ }
29
+ const message = row.type === "response_item" ? row.payload : (row.message ?? row);
30
+ if (!message || typeof message !== "object")
31
+ return null;
32
+ const role = message.role ?? (["user", "assistant"].includes(row.type) ? row.type : undefined);
33
+ if (!["user", "assistant", "model"].includes(role))
34
+ return null;
35
+ const text = textBlocks(message.content ?? message.parts);
36
+ const blocks = message.content ?? message.parts;
37
+ const onlyNonText = Array.isArray(blocks) && blocks.every(block => block && typeof block === "object" && ["tool_use", "tool_result", "thinking", "redacted_thinking", "image"].includes(block.type));
38
+ if (!text && !onlyNonText)
39
+ throw new Error("Unsupported transcript message shape for role " + role);
40
+ return text ? role + ": " + text : null;
41
+ }
42
+ export function splitText(text) {
43
+ const result = [];
44
+ let part = "";
45
+ let bytes = 0;
46
+ for (const char of text) {
47
+ const size = Buffer.byteLength(char);
48
+ if (bytes + size > 6000) {
49
+ result.push(part);
50
+ part = "";
51
+ bytes = 0;
52
+ }
53
+ part += char;
54
+ bytes += size;
55
+ }
56
+ if (part)
57
+ result.push(part);
58
+ return result;
59
+ }
60
+ /** Queue complete JSONL records and their cursor atomically. Never advance past an unfinished line. */
61
+ export function captureTranscript(options) {
62
+ const { directory, client, scope, sessionId } = options;
63
+ if (!sessionId)
64
+ throw new Error("Transcript has no session identity");
65
+ const path = resolve(options.path);
66
+ const fd = openSync(path, "r");
67
+ const queue = openQueue(directory);
68
+ let transaction = false;
69
+ try {
70
+ queue.exec("CREATE TABLE IF NOT EXISTS cursors(id TEXT PRIMARY KEY, offset INTEGER NOT NULL, prefix TEXT NOT NULL)");
71
+ queue.exec("BEGIN IMMEDIATE");
72
+ transaction = true;
73
+ const key = hash(JSON.stringify({ client, scope, sessionId, path }));
74
+ const previous = queue.prepare("SELECT offset,prefix FROM cursors WHERE id=?").get(key);
75
+ const size = fstatSync(fd).size;
76
+ let offset = previous ? Number(previous.offset) : 0;
77
+ const prefix = (length) => {
78
+ const buffer = Buffer.alloc(Math.min(length, 128));
79
+ const count = readSync(fd, buffer, 0, buffer.length, 0);
80
+ return hash(buffer.subarray(0, count));
81
+ };
82
+ if (offset > size || (previous && prefix(offset) !== previous.prefix))
83
+ offset = 0;
84
+ const buffer = Buffer.alloc(Math.min(size - offset, windowBytes));
85
+ const read = readSync(fd, buffer, 0, buffer.length, offset);
86
+ let start = 0;
87
+ let events = 0;
88
+ let records = 0;
89
+ while (start < read && records < 500) {
90
+ const end = buffer.indexOf(10, start);
91
+ if (end < 0 || end >= read)
92
+ break;
93
+ if (end - start > maxLineBytes)
94
+ throw new Error("Transcript line exceeds 1 MiB");
95
+ const line = buffer.subarray(start, end).toString("utf8").trim();
96
+ if (line) {
97
+ let row;
98
+ try {
99
+ row = JSON.parse(line);
100
+ }
101
+ catch {
102
+ throw new Error("Invalid transcript JSON at byte " + (offset + start));
103
+ }
104
+ if (!row || typeof row !== "object" || Array.isArray(row))
105
+ throw new Error("Invalid transcript record");
106
+ const text = messageText(row);
107
+ if (text) {
108
+ const contentParts = splitText(redact(text));
109
+ for (const [index, content] of contentParts.entries()) {
110
+ const event = eventSchema.parse({
111
+ ...scope, sessionId, kind: "progress", content,
112
+ eventId: hash(JSON.stringify({ client, scope, sessionId, byte: offset + start, index, content })),
113
+ source: client + ":transcript:line-byte=" + (offset + start) + ":part=" + index,
114
+ });
115
+ queue.prepare("INSERT OR IGNORE INTO pending VALUES(?,?)").run(event.eventId, JSON.stringify(event));
116
+ events++;
117
+ }
118
+ }
119
+ }
120
+ records++;
121
+ start = end + 1;
122
+ }
123
+ if (read - start > maxLineBytes && records < 500)
124
+ throw new Error("Transcript line exceeds 1 MiB");
125
+ const nextOffset = offset + start;
126
+ queue.prepare("INSERT INTO cursors VALUES(?,?,?) ON CONFLICT(id) DO UPDATE SET offset=excluded.offset,prefix=excluded.prefix")
127
+ .run(key, nextOffset, prefix(nextOffset));
128
+ queue.exec("COMMIT");
129
+ transaction = false;
130
+ return { events, records, offset: nextOffset, remainingBytes: size - nextOffset };
131
+ }
132
+ finally {
133
+ if (transaction)
134
+ queue.exec("ROLLBACK");
135
+ queue.close();
136
+ closeSync(fd);
137
+ }
138
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,27 @@
1
+ import { z } from "zod";
2
+ const identifier = z.string().trim().min(1).max(256);
3
+ export const eventSchema = z.object({
4
+ eventId: identifier,
5
+ repoId: identifier,
6
+ featureId: identifier,
7
+ branch: identifier.optional(),
8
+ commit: identifier.optional(),
9
+ author: identifier.optional(),
10
+ sessionId: identifier.optional(),
11
+ source: z.string().max(2048).optional(),
12
+ kind: z.enum(["goal", "decision", "attempt", "progress", "test_result", "blocker", "next_step"]),
13
+ content: z.string().min(1).refine(s => Buffer.byteLength(s, "utf8") <= 32768, "Content exceeds 32 KiB"),
14
+ }).strict();
15
+ export const scopeSchema = z.object({
16
+ repoId: identifier,
17
+ featureId: identifier,
18
+ branch: identifier.optional(),
19
+ maxChars: z.number().int().min(256).max(24000).default(12000),
20
+ });
21
+ export const searchSchema = z.object({
22
+ repoId: identifier,
23
+ featureId: identifier,
24
+ query: z.string().max(256).default(""),
25
+ before: z.number().int().positive().optional(),
26
+ limit: z.number().int().min(1).max(20).default(10),
27
+ });
@@ -0,0 +1,210 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from 'node:util';
3
+ import { createInterface } from 'node:readline/promises';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { join, resolve, dirname } from 'node:path';
6
+ import { existsSync, readFileSync, accessSync, constants, rmSync } from 'node:fs';
7
+ import { execFileSync } from 'node:child_process';
8
+ import { planConnection, applyConnectionPlan, planUninstall, clients, atomicWrite, readConnectionState } from './connections.js';
9
+ import { installRuntime, readInstallation, defaultHome, runtimePaths, withInstallLock, activateRuntime, packageName } from './runtime.js';
10
+ import { resolveRepository } from '../../adapters/src/repository.js';
11
+ const appRoot = fileURLToPath(new URL('../../../', import.meta.url));
12
+ const packageRoot = existsSync(join(appRoot, 'package.json')) ? appRoot : dirname(appRoot);
13
+ const metadata = JSON.parse(readFileSync(join(packageRoot, 'package.json'), 'utf8'));
14
+ const version = metadata.version;
15
+ async function confirm(text, yes = false) {
16
+ if (yes)
17
+ return true;
18
+ if (!process.stdin.isTTY)
19
+ throw new Error('Use --yes for noninteractive apply, or --preview to inspect without changes');
20
+ const reader = createInterface({ input: process.stdin, output: process.stdout });
21
+ try {
22
+ return /^y(es)?$/i.test((await reader.question(text + ' [y/N] ')).trim());
23
+ }
24
+ finally {
25
+ reader.close();
26
+ }
27
+ }
28
+ async function ask(prompt) {
29
+ if (!process.stdin.isTTY)
30
+ throw new Error('Pass --workspace and --client for noninteractive setup');
31
+ const reader = createInterface({ input: process.stdin, output: process.stdout });
32
+ try {
33
+ return (await reader.question(prompt)).trim();
34
+ }
35
+ finally {
36
+ reader.close();
37
+ }
38
+ }
39
+ function preview(plan) {
40
+ for (const [path, content] of Object.entries(plan.changes)) {
41
+ if (path.includes('npm-connection'))
42
+ continue;
43
+ console.log((content === null ? 'remove ' : 'merge ') + join(plan.workspace, path));
44
+ if (content !== null && content !== plan.expected[path])
45
+ console.log(content);
46
+ }
47
+ }
48
+ function applyAll(plans, commit) {
49
+ const done = [];
50
+ try {
51
+ for (const plan of plans) {
52
+ applyConnectionPlan(plan);
53
+ done.push(plan);
54
+ }
55
+ commit();
56
+ }
57
+ catch (error) {
58
+ for (const plan of done.reverse())
59
+ for (const [path, content] of Object.entries(plan.expected)) {
60
+ // Already-written files are restored as one transaction; unrelated concurrent
61
+ // edits are protected by each plan's optimistic concurrency check.
62
+ const target = join(plan.workspace, path);
63
+ const current = existsSync(target) ? readFileSync(target, 'utf8') : null;
64
+ if (current !== plan.changes[path])
65
+ continue;
66
+ if (content !== null)
67
+ atomicWrite(join(plan.workspace, path), content);
68
+ else
69
+ rmSync(join(plan.workspace, path), { force: true });
70
+ }
71
+ throw error;
72
+ }
73
+ }
74
+ function plansFor(runtime, projects) { return projects.map(project => planConnection({ ...project, appRoot: runtime.appRoot, node: runtime.node })); }
75
+ async function main() {
76
+ const { values, positionals } = parseArgs({ allowPositionals: true, options: {
77
+ workspace: { type: 'string' }, client: { type: 'string', multiple: true }, home: { type: 'string' },
78
+ package: { type: 'string' }, yes: { type: 'boolean' }, preview: { type: 'boolean' },
79
+ version: { type: 'boolean' }, help: { type: 'boolean' },
80
+ } });
81
+ if (values.version) {
82
+ console.log(version);
83
+ return;
84
+ }
85
+ const action = positionals[0];
86
+ if (!action || values.help) {
87
+ console.log('Knitt ' + version + '\nCommands: setup, doctor, update, rollback, uninstall, serve\nOptions: --workspace PATH --client codex|claude-code|antigravity|claude-desktop (repeatable)\n --preview --yes --home PATH --package TARBALL_OR_VERSION_SPEC\nSetup configures a persistent local runtime; remote/team service is configured separately.');
88
+ return;
89
+ }
90
+ const home = resolve(values.home ?? defaultHome()), paths = runtimePaths(home);
91
+ if (action === 'serve') {
92
+ process.env.MEMORY_DB ??= join(paths.data, 'events.sqlite');
93
+ await import('../../../apps/server/src/main.js');
94
+ return;
95
+ }
96
+ if (action === 'doctor') {
97
+ const state = readInstallation(home), problems = [];
98
+ if (Number(process.versions.node.split('.')[0]) < 24)
99
+ problems.push('Install Node.js 24+');
100
+ try {
101
+ execFileSync('git', ['--version'], { stdio: 'ignore' });
102
+ }
103
+ catch {
104
+ problems.push('Install Git and add it to PATH');
105
+ }
106
+ if (!state)
107
+ problems.push('No persistent runtime installed. Run setup.');
108
+ else {
109
+ for (const file of [state.current.node, join(state.current.appRoot, 'apps/server/src/main.js')])
110
+ if (!existsSync(file))
111
+ problems.push('Missing runtime path: ' + file + '. Run setup again.');
112
+ try {
113
+ accessSync(paths.data, constants.W_OK);
114
+ }
115
+ catch {
116
+ problems.push('Data directory is not writable: ' + paths.data);
117
+ }
118
+ for (const project of state.projects) {
119
+ try {
120
+ const managed = readConnectionState(project.workspace);
121
+ if (!Object.keys(managed.files).length)
122
+ problems.push('Missing connector state: ' + project.workspace);
123
+ for (const [path, snapshot] of Object.entries(managed.files)) {
124
+ const current = readFileSync(join(project.workspace, path), 'utf8');
125
+ if (current !== snapshot.after)
126
+ problems.push('Configuration changed; review before setup: ' + join(project.workspace, path));
127
+ }
128
+ }
129
+ catch {
130
+ problems.push('Missing or invalid project configuration: ' + project.workspace);
131
+ }
132
+ }
133
+ }
134
+ console.log(JSON.stringify({ status: problems.length ? 'attention_required' : 'configured', runtime: state?.current.version, problems, note: 'Configuration check only; agent login/trust and live handoff are not verified.' }, null, 2));
135
+ if (problems.length)
136
+ process.exitCode = 1;
137
+ return;
138
+ }
139
+ if (!['setup', 'update', 'rollback', 'uninstall'].includes(action))
140
+ throw new Error('Unknown command: ' + action);
141
+ let project;
142
+ if (action === 'setup') {
143
+ const directory = values.workspace ?? await ask('Project folder: ');
144
+ const selected = values.client ?? (await ask('Agents (comma separated: ' + clients.join(', ') + '): ')).split(',').map(v => v.trim());
145
+ const { workspace, repoId } = resolveRepository(resolve(directory));
146
+ project = { workspace, repoId, clients: selected, database: join(paths.data, 'events.sqlite') };
147
+ // Validate and show changes before installing dependencies or writing settings.
148
+ const plan = planConnection({ ...project, appRoot });
149
+ preview(plan);
150
+ if (values.preview) {
151
+ console.log('Preview only. No runtime or configuration installed.');
152
+ return;
153
+ }
154
+ }
155
+ else {
156
+ const state = readInstallation(home);
157
+ if (!state)
158
+ throw new Error('No installation found. Run setup first.');
159
+ if (action === 'uninstall') {
160
+ const target = values.workspace ? resolveRepository(resolve(values.workspace)).workspace : null;
161
+ if (!target)
162
+ throw new Error('Pass --workspace to uninstall one project; memory data is always retained');
163
+ if (!state.projects.some(p => p.workspace === target))
164
+ throw new Error('Project is not managed by this installation');
165
+ preview(planUninstall(target));
166
+ }
167
+ else
168
+ console.log(action + ' runtime for ' + state.projects.length + ' project(s); user memory is retained.');
169
+ if (values.preview)
170
+ return;
171
+ }
172
+ if (!await confirm('Apply ' + action + '?', values.yes)) {
173
+ console.log('Cancelled. No changes applied.');
174
+ return;
175
+ }
176
+ await withInstallLock(home, async () => {
177
+ const state = readInstallation(home);
178
+ if (action === 'uninstall') {
179
+ const target = resolveRepository(resolve(values.workspace)).workspace;
180
+ const plan = planUninstall(target);
181
+ applyAll([plan], () => atomicWrite(paths.state, JSON.stringify({ ...state, projects: state.projects.filter(p => p.workspace !== target) }, null, 2)));
182
+ console.log('Project connectors removed where unchanged. User-edited settings and all memory retained. Runtime retained for other projects.');
183
+ return;
184
+ }
185
+ if (project) {
186
+ const existing = state?.projects.find(p => p.workspace === project.workspace);
187
+ if (existing)
188
+ project.clients = [...new Set([...existing.clients, ...project.clients])];
189
+ }
190
+ const projects = project ? [...(state?.projects ?? []).filter(p => p.workspace !== project.workspace), project] : state.projects;
191
+ if (action !== 'rollback' && metadata.private && !values.package)
192
+ throw new Error('This package is unpublished. Pass --package /absolute/path/to/the-built.tgz; registry installation is disabled until release.');
193
+ const runtime = action === 'rollback' ? state?.previous : installRuntime(home, values.package ?? packageName + '@' + (action === 'update' ? (version.includes('-') ? 'next' : 'latest') : version));
194
+ if (!runtime)
195
+ throw new Error('No previous runtime available');
196
+ const plans = plansFor(runtime, projects);
197
+ applyAll(plans, () => activateRuntime(home, runtime, projects));
198
+ console.log('Installed runtime ' + runtime.version + '. Data: ' + paths.data);
199
+ console.log('Restart connected agents and review MCP/hook trust prompts. Use /continue-chat to select your conversation.');
200
+ if (projects.some(p => p.clients.includes('claude-desktop')))
201
+ console.log('Claude Desktop: merge the generated project .memory/connectors/claude-desktop.json fragment into Desktop MCP settings, then restart.');
202
+ });
203
+ }
204
+ try {
205
+ await main();
206
+ }
207
+ catch (error) {
208
+ console.error(error instanceof Error ? error.message : String(error));
209
+ process.exitCode = 1;
210
+ }
@@ -0,0 +1,226 @@
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);
12
+ const equal = (a, b) => JSON.stringify(a) === JSON.stringify(b);
13
+ export function atomicWrite(path, content) {
14
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
15
+ const temporary = path + '.' + randomUUID() + '.tmp';
16
+ try {
17
+ writeFileSync(temporary, content, { mode: 0o600, flag: 'wx' });
18
+ renameSync(temporary, path);
19
+ }
20
+ finally {
21
+ rmSync(temporary, { force: true });
22
+ }
23
+ }
24
+ // Revert just our changes; later independent additions remain. Modified scalar
25
+ // values stay user-owned rather than being overwritten by an uninstall.
26
+ function restore(before, after, current) {
27
+ if (equal(current, after))
28
+ return before;
29
+ if (object(after) && object(current) && typeof after.command === 'string' && Array.isArray(after.args))
30
+ return current;
31
+ if (object(after) && object(current) && (before === undefined || object(before))) {
32
+ const result = { ...current };
33
+ for (const key of new Set([...Object.keys(before ?? {}), ...Object.keys(after)])) {
34
+ if (equal(before?.[key], after[key]))
35
+ continue;
36
+ const value = restore(before?.[key], after[key], current[key]);
37
+ if (value === undefined)
38
+ delete result[key];
39
+ else
40
+ result[key] = value;
41
+ }
42
+ return Object.keys(result).length === 0 && before === undefined ? undefined : result;
43
+ }
44
+ if (Array.isArray(after) && Array.isArray(current) && (before === undefined || Array.isArray(before))) {
45
+ 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)));
48
+ for (const v of previous)
49
+ if (!after.some(a => equal(a, v)) && !result.some(a => equal(a, v)))
50
+ result.push(v);
51
+ return result.length === 0 && before === undefined ? undefined : result;
52
+ }
53
+ return current;
54
+ }
55
+ export function readConnectionState(workspace) {
56
+ const text = read(join(workspace, statePath));
57
+ if (!text)
58
+ return { schema: 1, files: {} };
59
+ const value = JSON.parse(text);
60
+ if (value.schema !== 1 || !object(value.files))
61
+ throw new Error('Unsupported connector state');
62
+ 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');
66
+ }
67
+ return value;
68
+ }
69
+ 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
+ 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);
77
+ if (!existsSync(server) || !existsSync(runner))
78
+ throw new Error('Runtime files missing');
79
+ 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' } : {}) } });
87
+ function owned(path, location, current) {
88
+ if (current === undefined)
89
+ return;
90
+ const prior = state.files[path];
91
+ const previous = prior ? location.reduce((v, key) => v?.[key], JSON.parse(prior.after)) : undefined;
92
+ if (!equal(current, previous))
93
+ throw new Error('Unmanaged or modified connector conflict in ' + path);
94
+ }
95
+ function mcp(path, desktop = false) {
96
+ const value = json(path);
97
+ value.mcpServers ??= {};
98
+ owned(path, ['mcpServers', 'shared-memory'], value.mcpServers['shared-memory']);
99
+ value.mcpServers['shared-memory'] = connection(desktop);
100
+ changes[path] = dump(value);
101
+ }
102
+ function hooks(path, client) {
103
+ const value = json(path);
104
+ 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']]) {
107
+ const old = prior?.[event] ?? [];
108
+ const groups = value.hooks[event] ?? [];
109
+ if (!Array.isArray(groups))
110
+ throw new Error('Invalid hooks in ' + path);
111
+ // Only remove exact previously generated handlers. Edited handlers remain;
112
+ // 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')));
114
+ 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);
117
+ value.hooks[event] = [...kept, { hooks: [handler(client, action)] }];
118
+ }
119
+ changes[path] = dump(value);
120
+ }
121
+ function skill(path) {
122
+ const current = get(path);
123
+ 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');
126
+ }
127
+ 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');
132
+ }
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')] };
140
+ changes[path] = dump(value);
141
+ }
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) ?? '';
146
+ const parsed = parseToml(current);
147
+ let base = current;
148
+ if (current.includes(begin)) {
149
+ const previous = state.files[path];
150
+ const block = current.slice(current.indexOf(begin), current.indexOf(end) + end.length);
151
+ if (!previous || !previous.after.includes(block))
152
+ throw new Error('Modified or unmanaged Codex config conflict');
153
+ base = current.replace(block, '');
154
+ }
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';
158
+ parseToml(changes[path]);
159
+ }
160
+ }
161
+ 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 };
163
+ expected[statePath] = read(join(workspace, statePath));
164
+ changes[statePath] = dump(state);
165
+ return { workspace, changes, expected };
166
+ }
167
+ export function applyConnectionPlan(plan) {
168
+ // Optimistic concurrency prevents applying a preview over later user edits.
169
+ for (const [path, expected] of Object.entries(plan.expected))
170
+ if (read(join(plan.workspace, path)) !== expected)
171
+ throw new Error('Configuration changed since preview: ' + path);
172
+ const written = [];
173
+ try {
174
+ for (const [path, content] of Object.entries(plan.changes)) {
175
+ if (content === null)
176
+ rmSync(join(plan.workspace, path), { force: true });
177
+ else
178
+ atomicWrite(join(plan.workspace, path), content);
179
+ written.push(path);
180
+ }
181
+ }
182
+ catch (error) {
183
+ for (const path of written.reverse()) {
184
+ const old = plan.expected[path];
185
+ if (old === null || old === undefined)
186
+ rmSync(join(plan.workspace, path), { force: true });
187
+ else
188
+ atomicWrite(join(plan.workspace, path), old);
189
+ }
190
+ throw error;
191
+ }
192
+ 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');
197
+ }
198
+ catch { /* Non-Git projects can use the planner; CLI validates Git separately. */ }
199
+ }
200
+ function unapply(path, snapshot, current) {
201
+ const { before, after } = snapshot;
202
+ if (current === null || current === after)
203
+ return current === null ? null : before;
204
+ if (path.endsWith('.json')) {
205
+ const restored = restore(before === null ? undefined : JSON.parse(before), JSON.parse(after), JSON.parse(current));
206
+ return restored === undefined ? null : dump(restored);
207
+ }
208
+ if (path.endsWith('.toml')) {
209
+ const block = after.slice(after.indexOf(begin), after.indexOf(end) + end.length);
210
+ if (current.includes(block))
211
+ return current.replace(block, '').trim() || before;
212
+ }
213
+ return current;
214
+ }
215
+ export function planUninstall(workspace) {
216
+ const state = readConnectionState(workspace), changes = {}, expected = {};
217
+ for (const [path, snapshot] of Object.entries(state.files)) {
218
+ const current = read(join(workspace, path));
219
+ expected[path] = current;
220
+ changes[path] = unapply(path, snapshot, current);
221
+ }
222
+ expected[statePath] = read(join(workspace, statePath));
223
+ changes[statePath] = null;
224
+ return { workspace, changes, expected };
225
+ }
226
+ export function uninstallConnections(workspace) { applyConnectionPlan(planUninstall(workspace)); }