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

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 (33) hide show
  1. package/README.md +24 -15
  2. package/dist/apps/server/src/cloud-picker.js +245 -0
  3. package/dist/apps/server/src/http-gateway.js +1 -1
  4. package/dist/apps/server/src/main.js +6 -2
  5. package/dist/apps/server/src/onboarding.js +266 -0
  6. package/dist/apps/server/src/plugin-bootstrap.js +82 -0
  7. package/dist/apps/server/src/plugin-hook.js +51 -0
  8. package/dist/apps/server/src/plugin-main.js +10 -0
  9. package/dist/apps/server/src/server.js +108 -29
  10. package/dist/packages/adapters/src/cli.js +19 -2
  11. package/dist/packages/adapters/src/handoff.js +10 -6
  12. package/dist/packages/adapters/src/histories.js +221 -0
  13. package/dist/packages/adapters/src/history-time.js +10 -0
  14. package/dist/packages/adapters/src/hooks.js +8 -8
  15. package/dist/packages/adapters/src/picker.js +2 -1
  16. package/dist/packages/adapters/src/question-ui.js +37 -0
  17. package/dist/packages/adapters/src/scope.js +9 -3
  18. package/dist/packages/adapters/src/server-name.js +5 -0
  19. package/dist/packages/adapters/src/transcript.js +2 -0
  20. package/dist/packages/cloud/src/client.js +40 -0
  21. package/dist/packages/cloud/src/local-sync.js +300 -0
  22. package/dist/packages/installer/src/antigravity.js +90 -0
  23. package/dist/packages/installer/src/cli.js +77 -30
  24. package/dist/packages/installer/src/cloud-cli.js +199 -0
  25. package/dist/packages/installer/src/connections.js +37 -9
  26. package/dist/packages/installer/src/runtime.js +2 -2
  27. package/dist/packages/memory/src/store.js +36 -0
  28. package/dist/skills/knit/SKILL.md +27 -5
  29. package/docs/clients/connector-setup.md +1 -1
  30. package/docs/clients/npm-installation.md +28 -12
  31. package/docs/clients/support-matrix.md +12 -0
  32. package/docs/usage.md +28 -29
  33. package/package.json +6 -3
@@ -0,0 +1,199 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { hostname, tmpdir } from 'node:os';
3
+ import { dirname, join, resolve } from 'node:path';
4
+ import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync, existsSync } from 'node:fs';
5
+ import { spawn } from 'node:child_process';
6
+ import { randomUUID } from 'node:crypto';
7
+ import { createInterface } from 'node:readline/promises';
8
+ import { setTimeout as sleep } from 'node:timers/promises';
9
+ import { z } from 'zod';
10
+ import { api, CloudError, credentials, credentialsPath, defaultServer, request, serverOrigin } from '../../cloud/src/client.js';
11
+ import { defaultHome, runtimePaths, withInstallLock } from './runtime.js';
12
+ import { atomicWrite } from './connections.js';
13
+ import { defaultHistoryRoots, discoverHistories } from '../../adapters/src/histories.js';
14
+ import { importConversation } from '../../adapters/src/handoff.js';
15
+ import { MemoryStore } from '../../memory/src/store.js';
16
+ const print = (value) => console.log(JSON.stringify(value, null, 2));
17
+ async function prompt(question) {
18
+ if (!process.stdin.isTTY)
19
+ throw new Error('Use the cloud publish subcommands and explicit flags for noninteractive review. See knitt cloud --help.');
20
+ const reader = createInterface({ input: process.stdin, output: process.stdout });
21
+ try {
22
+ return (await reader.question(question + ' ')).trim();
23
+ }
24
+ finally {
25
+ reader.close();
26
+ }
27
+ }
28
+ async function login(home, origin, name, open) {
29
+ if (credentials(home))
30
+ throw new Error('This installation is paired. Run knitt cloud logout before pairing again.');
31
+ const pairing = await request(origin, '/api/device-pairings', { body: { name } });
32
+ const verification = new URL(pairing.verificationUri, origin);
33
+ if (verification.origin !== origin)
34
+ throw new Error('Pairing approval must use the selected Knitt Cloud origin');
35
+ console.log(`Approve installation ${name} with code ${pairing.userCode} at ${verification.href}`);
36
+ if (open) {
37
+ const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'rundll32.exe' : 'xdg-open';
38
+ const args = process.platform === 'win32' ? ['url.dll,FileProtocolHandler', verification.href] : [verification.href];
39
+ const child = spawn(command, args, { stdio: 'ignore', detached: true });
40
+ child.on('error', () => console.error('Open the approval link above in your browser.'));
41
+ child.unref();
42
+ }
43
+ while (Date.now() < Date.parse(pairing.expiresAt)) {
44
+ const result = await request(origin, '/api/device-pairings/exchange', { body: { pairingId: pairing.pairingId, deviceCode: pairing.deviceCode } });
45
+ if (result.status !== 'pending') {
46
+ if (!result.token || !result.account?.id || !result.device?.id)
47
+ throw new Error('Incomplete pairing response');
48
+ atomicWrite(credentialsPath(home), JSON.stringify({ origin, token: result.token, account: result.account, device: result.device }));
49
+ console.log(`Paired ${result.device.name} with ${result.account.email}.`);
50
+ return;
51
+ }
52
+ await sleep(Math.max(1, pairing.interval) * 1000);
53
+ }
54
+ throw new Error('Pairing expired. Run knitt cloud login again.');
55
+ }
56
+ const draftSchema = z.object({
57
+ title: z.string().trim().min(1), creationKey: z.string().min(1), publicationKey: z.string().min(1), contextId: z.string().min(1).optional(),
58
+ sourceVersionId: z.string().min(1).optional(), accountId: z.string().optional(), origin: z.string().optional(),
59
+ checkpoint: z.string().trim().min(1), source: z.object({ agent: z.enum(['codex', 'claude', 'antigravity']), conversationId: z.string().min(1), repository: z.string().optional(), branch: z.string().optional(), commit: z.string().optional() }).strict(),
60
+ excerpts: z.array(z.object({ text: z.string().min(1) }).strict()),
61
+ }).strict();
62
+ function userPreview(draft) {
63
+ const { title, contextId, sourceVersionId, checkpoint, source, excerpts } = draft;
64
+ return { title, contextId, sourceVersionId, checkpoint, source, excerpts, ...(sourceVersionId ? { originalWork: true } : {}) };
65
+ }
66
+ function transcriptExcerpts(conversation) {
67
+ const scratch = mkdtempSync(join(tmpdir(), 'knitt-review-'));
68
+ const store = new MemoryStore(':memory:');
69
+ try {
70
+ const repoId = 'review';
71
+ const { featureId } = importConversation({ conversation, repoId, directory: scratch, store });
72
+ const excerpts = [];
73
+ let before;
74
+ do {
75
+ const page = store.search({ repoId, featureId, before, limit: 20 });
76
+ for (const match of page.matches)
77
+ excerpts.push({ id: match.eventId, text: store.evidence(repoId, match.eventId).content });
78
+ before = page.nextCursor ?? undefined;
79
+ } while (before);
80
+ return excerpts.reverse();
81
+ }
82
+ finally {
83
+ store.close();
84
+ rmSync(scratch, { recursive: true, force: true });
85
+ }
86
+ }
87
+ async function submit(home, path, yes) {
88
+ const draft = draftSchema.parse(JSON.parse(readFileSync(path, 'utf8')));
89
+ const device = credentials(home);
90
+ if (!device)
91
+ throw new Error('Pair this installation with knitt cloud login before submitting.');
92
+ if ((draft.accountId && draft.accountId !== device.account.id) || (draft.origin && draft.origin !== device.origin))
93
+ throw new Error('This draft belongs to another account or server');
94
+ print(userPreview(draft));
95
+ if (draft.sourceVersionId)
96
+ console.log('Only your original work may be published. Confirm that the checkpoint and excerpts contain your own material.');
97
+ if (!yes && (await prompt('Publish this exact material to ' + device.account.email + '? Type publish to confirm.')) !== 'publish') {
98
+ console.log('Cancelled.');
99
+ return;
100
+ }
101
+ draft.accountId = device.account.id;
102
+ draft.origin = device.origin;
103
+ atomicWrite(path, JSON.stringify(draft, null, 2));
104
+ if (!draft.contextId) {
105
+ const { context } = await api(device, '/api/contexts', { title: draft.title, creationKey: draft.creationKey, sourceVersionId: draft.sourceVersionId });
106
+ draft.contextId = context.id;
107
+ atomicWrite(path, JSON.stringify(draft, null, 2));
108
+ }
109
+ const { version } = await api(device, `/api/contexts/${encodeURIComponent(draft.contextId)}/versions`, { publicationKey: draft.publicationKey, checkpoint: draft.checkpoint, source: draft.source, excerpts: draft.excerpts, ...(draft.sourceVersionId ? { originalWork: true } : {}) });
110
+ console.log(`Published v${version.number} (${version.id}) in context ${draft.contextId}.`);
111
+ }
112
+ const help = `knitt cloud login [--server ORIGIN] [--name DEVICE] [--no-browser]\nknitt cloud logout\nknitt cloud publish [--workspace PATH] Interactive review\nknitt cloud publish list [--workspace PATH] Available local conversations\nknitt cloud publish excerpts --source AGENT:ID Local excerpt IDs and text\nknitt cloud publish prepare --source AGENT:ID --checkpoint TEXT --draft FILE [--excerpt ID ...]\nknitt cloud publish show --draft FILE Review edited JSON locally\nknitt cloud publish submit --draft FILE [--yes] Publish exactly the reviewed material\nOptional publication flags: --title TITLE --context ID --repository REPO --branch BRANCH --commit HASH\nUse --home PATH to select the Knitt installation. --yes confirms publication of only your original work.`;
113
+ export async function runCloud(args) {
114
+ const { positionals, values: v } = parseArgs({ args, allowPositionals: true, options: {
115
+ home: { type: 'string' }, server: { type: 'string' }, name: { type: 'string' }, 'no-browser': { type: 'boolean' }, workspace: { type: 'string' }, source: { type: 'string' }, checkpoint: { type: 'string' }, excerpt: { type: 'string', multiple: true }, draft: { type: 'string' }, title: { type: 'string' }, context: { type: 'string' }, repository: { type: 'string' }, branch: { type: 'string' }, commit: { type: 'string' }, yes: { type: 'boolean' }, help: { type: 'boolean' },
116
+ } });
117
+ const [action, step] = positionals;
118
+ const home = resolve(v.home ?? defaultHome());
119
+ if (!action || v.help) {
120
+ console.log(help);
121
+ return;
122
+ }
123
+ if (action === 'login')
124
+ return withInstallLock(home, () => login(home, serverOrigin(v.server ?? defaultServer), v.name ?? hostname(), !v['no-browser']));
125
+ if (action === 'logout')
126
+ return withInstallLock(home, async () => {
127
+ const device = credentials(home);
128
+ if (!device) {
129
+ console.log('Signed out.');
130
+ return;
131
+ }
132
+ try {
133
+ await request(device.origin, '/api/devices/current', { method: 'DELETE', token: device.token });
134
+ }
135
+ catch (err) {
136
+ if (!(err instanceof CloudError && err.status === 401))
137
+ throw err;
138
+ }
139
+ rmSync(credentialsPath(home));
140
+ console.log('Signed out.');
141
+ });
142
+ if (action !== 'publish' || (step && !['list', 'excerpts', 'prepare', 'show', 'submit'].includes(step)))
143
+ throw new Error(help);
144
+ if (step === 'show' || step === 'submit') {
145
+ if (!v.draft)
146
+ throw new Error('Pass --draft FILE');
147
+ if (step === 'show')
148
+ return print(userPreview(draftSchema.parse(JSON.parse(readFileSync(v.draft, 'utf8')))));
149
+ return submit(home, resolve(v.draft), !!v.yes);
150
+ }
151
+ const workspace = resolve(v.workspace ?? process.cwd());
152
+ const chats = discoverHistories({ roots: defaultHistoryRoots(), workspace });
153
+ const choices = chats.map(c => ({ source: (c.client ?? 'antigravity') + ':' + c.id, title: c.title, modified: c.modified }));
154
+ if (step === 'list')
155
+ return print(choices);
156
+ if (!choices.length)
157
+ throw new Error('No local conversations were found for this workspace.');
158
+ if (!v.source) {
159
+ if (step)
160
+ throw new Error('Choose --source AGENT:ID from knitt cloud publish list');
161
+ choices.forEach((c, i) => console.log(`${i + 1}. ${c.title} (${c.source})`));
162
+ v.source = choices[Number(await prompt('Choose a conversation number.')) - 1]?.source;
163
+ }
164
+ const index = choices.findIndex(c => c.source === v.source);
165
+ if (index < 0)
166
+ throw new Error('Choose a conversation listed for this workspace.');
167
+ const chat = chats[index];
168
+ const db = process.env.MEMORY_DB ?? join(runtimePaths(home).data, 'events.sqlite');
169
+ const store = existsSync(db) ? new MemoryStore(db) : null;
170
+ let provenance;
171
+ try {
172
+ provenance = store?.lastCloudSource(chat.id, chat.client ?? 'antigravity');
173
+ }
174
+ finally {
175
+ store?.close();
176
+ }
177
+ // Recipient transcripts can contain previously loaded source text. Only
178
+ // individually saved new-work events can be selected for an onward handoff.
179
+ const excerpts = provenance ? provenance.work : transcriptExcerpts(chat);
180
+ if (step === 'excerpts')
181
+ return print(excerpts);
182
+ if (!step && !v.excerpt) {
183
+ excerpts.forEach((e, i) => console.log(`${i + 1}. ${JSON.stringify(e.text)}`));
184
+ const selected = await prompt('Include excerpts by number, separated by commas (Enter for none).');
185
+ v.excerpt = selected ? selected.split(',').map(n => excerpts[Number(n.trim()) - 1]?.id ?? 'unknown') : [];
186
+ }
187
+ const selected = [...new Set(v.excerpt ?? [])].map(id => { const e = excerpts.find(e => e.id === id); if (!e)
188
+ throw new Error('Unknown excerpt ID'); return { text: e.text }; });
189
+ const checkpoint = v.checkpoint ?? await prompt('Write your checkpoint (goal, decisions, progress, verification, blockers and next steps).');
190
+ const draft = draftSchema.parse({ title: v.title ?? chat.title, creationKey: randomUUID(), publicationKey: randomUUID(), contextId: v.context,
191
+ checkpoint, source: { agent: chat.client ?? 'antigravity', conversationId: chat.id, repository: v.repository, branch: v.branch, commit: v.commit }, excerpts: selected,
192
+ ...(provenance ? { sourceVersionId: provenance.versionId, origin: provenance.origin, accountId: provenance.accountId } : {}) });
193
+ const path = resolve(v.draft ?? join(home, 'cloud', 'drafts', draft.publicationKey + '.json'));
194
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
195
+ writeFileSync(path, JSON.stringify(draft, null, 2) + '\n', { mode: 0o600, flag: 'wx' });
196
+ console.log('Saved local draft ' + path + '. Edit it and use knitt cloud publish show or submit --draft FILE.');
197
+ if (!step)
198
+ await submit(home, path, !!v.yes);
199
+ }
@@ -1,3 +1,4 @@
1
+ import { antigravityServerName } from '../../adapters/src/server-name.js';
1
2
  import { hookCommand, isManagedHook } from './platform.js';
2
3
  import { readFileSync, existsSync, mkdirSync, writeFileSync, renameSync, rmSync, realpathSync } from 'node:fs';
3
4
  import { join, dirname, resolve } from 'node:path';
@@ -61,7 +62,7 @@ export function readConnectionState(workspace) {
61
62
  if (value.schema !== 1 || !object(value.files))
62
63
  throw new Error('Unsupported connector state');
63
64
  for (const [file, snapshot] of Object.entries(value.files)) {
64
- if (!['.mcp.json', '.codex/config.toml', '.codex/hooks.json', '.agents/hooks.json', '.agents/mcp_config.json', '.agents/skills/continue-chat/SKILL.md', '.agents/skills/knit/SKILL.md', '.claude/settings.local.json', '.claude/skills/continue-chat/SKILL.md', '.claude/skills/knit/SKILL.md', '.memory/connectors/claude-desktop.json'].includes(file)
65
+ 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', '.memory/connectors/antigravity.json'].includes(file)
65
66
  || !object(snapshot) || typeof snapshot.after !== 'string' || !(snapshot.before === null || typeof snapshot.before === 'string'))
66
67
  throw new Error('Invalid connector state');
67
68
  }
@@ -79,9 +80,10 @@ export function planConnection(opts) {
79
80
  const get = (path) => { const content = read(join(workspace, path)); expected[path] = content; return content; };
80
81
  const json = (path) => { const v = JSON.parse(get(path) ?? '{}'); if (!object(v))
81
82
  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' } : {}) } });
83
+ const env = { MEMORY_DB: resolve(opts.database), MEMORY_REPO: opts.repoId, MEMORY_WORKSPACE: workspace, MEMORY_SESSION_SELECTION: '1',
84
+ ...(opts.installationHome ? { SHARED_MEMORY_HOME: resolve(opts.installationHome), KNITT_HOME: resolve(opts.installationHome) } : {}) };
85
+ const handler = (client, action) => ({ type: 'command', timeout: 10, command: hookCommand({ ...env, ...(client === 'antigravity' ? { MEMORY_MCP_SERVER: antigravityServerName(workspace) } : {}), MEMORY_QUEUE: join(dirname(opts.database), 'queue', client), MEMORY_MANAGED: 'shared-agent-memory' }, node, [runner, action, client]) });
86
+ const connection = (desktop = false, chat = false) => ({ command: node, args: [server], env: { ...env, MEMORY_CLIENT: chat ? 'antigravity' : 'claude', ...(chat ? { MEMORY_PICKER_MODE: 'native_question' } : {}), ...(desktop ? { MEMORY_CHAT_CLIENT: 'claude-desktop' } : {}) } });
85
87
  function owned(path, location, current) {
86
88
  if (current === undefined)
87
89
  return;
@@ -90,11 +92,11 @@ export function planConnection(opts) {
90
92
  if (!equal(current, previous))
91
93
  throw new Error('Unmanaged or modified connector conflict in ' + path);
92
94
  }
93
- function mcp(path, desktop = false) {
95
+ function mcp(path, desktop = false, chat = false) {
94
96
  const value = json(path);
95
97
  value.mcpServers ??= {};
96
98
  owned(path, ['mcpServers', 'shared-memory'], value.mcpServers['shared-memory']);
97
- value.mcpServers['shared-memory'] = connection(desktop);
99
+ value.mcpServers['shared-memory'] = connection(desktop, chat);
98
100
  changes[path] = dump(value);
99
101
  }
100
102
  function hooks(path, client) {
@@ -122,6 +124,8 @@ export function planConnection(opts) {
122
124
  throw new Error('Unmanaged or modified skill conflict');
123
125
  changes[path] = readFileSync(join(app, 'skills/knit/SKILL.md'), 'utf8');
124
126
  }
127
+ if (opts.clients.some(client => client === 'codex' || client === 'antigravity'))
128
+ skill('.agents/skills/knit/SKILL.md');
125
129
  for (const client of opts.clients) {
126
130
  if (client === 'claude-code') {
127
131
  mcp('.mcp.json');
@@ -131,14 +135,16 @@ export function planConnection(opts) {
131
135
  if (client === 'claude-desktop')
132
136
  mcp('.memory/connectors/claude-desktop.json', true);
133
137
  if (client === 'antigravity') {
134
- mcp('.agents/mcp_config.json');
138
+ // Antigravity loads MCP servers globally or from plugins, not this project file.
139
+ // Retain the legacy project entry for existing tooling and export a mergeable fragment.
140
+ mcp('.agents/mcp_config.json', false, true);
141
+ mcp('.memory/connectors/antigravity.json', false, true);
135
142
  const path = '.agents/hooks.json', value = json(path);
136
143
  owned(path, ['shared-memory'], value['shared-memory']);
137
144
  value['shared-memory'] = { SessionStart: [handler('antigravity', 'recall')], Stop: [handler('antigravity', 'capture')] };
138
145
  changes[path] = dump(value);
139
146
  }
140
147
  if (client === 'codex') {
141
- skill('.agents/skills/knit/SKILL.md');
142
148
  hooks('.codex/hooks.json', 'codex');
143
149
  const path = '.codex/config.toml', current = get(path) ?? '';
144
150
  const parsed = parseToml(current);
@@ -152,7 +158,7 @@ export function planConnection(opts) {
152
158
  }
153
159
  else if (parsed.mcp_servers?.['shared-memory'])
154
160
  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';
161
+ 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, MEMORY_CLIENT: 'codex' }).map(([k, v]) => k + ' = ' + JSON.stringify(v)).join(', ') + ' }\ntools.choose_conversation.approval_mode = "approve"\n' + end + '\n';
156
162
  parseToml(changes[path]);
157
163
  }
158
164
  }
@@ -210,6 +216,28 @@ function unapply(path, snapshot, current) {
210
216
  }
211
217
  return current;
212
218
  }
219
+ // Verification may await while users add unrelated JSON settings. Undo only our
220
+ // generated values rather than dropping those additions or abandoning rollback.
221
+ export function rollbackConnectionPlan(plan) {
222
+ for (const [path, before] of Object.entries(plan.expected).reverse()) {
223
+ if (!(path in plan.changes))
224
+ continue;
225
+ const after = plan.changes[path], target = join(plan.workspace, path), current = read(target);
226
+ let restored;
227
+ if (current === after)
228
+ restored = before;
229
+ else if (after !== null && current !== null)
230
+ restored = unapply(path, { before, after }, current);
231
+ else
232
+ continue; // A new user-created value owns a file we removed.
233
+ if (restored === current)
234
+ continue;
235
+ if (restored === null)
236
+ rmSync(target, { force: true });
237
+ else
238
+ atomicWrite(target, restored);
239
+ }
240
+ }
213
241
  export function planUninstall(workspace) {
214
242
  const state = readConnectionState(workspace), changes = {}, expected = {};
215
243
  for (const [path, snapshot] of Object.entries(state.files)) {
@@ -70,7 +70,7 @@ export function installRuntime(home, spec) {
70
70
  rmSync(staging, { recursive: true, force: true });
71
71
  }
72
72
  }
73
- export function activateRuntime(home, current, projects) {
73
+ export function activateRuntime(home, current, projects, antigravityConfig) {
74
74
  const previous = readInstallation(home);
75
- atomicWrite(runtimePaths(home).state, JSON.stringify({ schema: 1, current, previous: previous?.current, projects }, null, 2) + '\n');
75
+ atomicWrite(runtimePaths(home).state, JSON.stringify({ schema: 1, current, previous: previous?.current, projects, antigravityConfig: antigravityConfig ?? previous?.antigravityConfig }, null, 2) + '\n');
76
76
  }
@@ -1,3 +1,4 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import { DatabaseSync } from "node:sqlite";
2
3
  import { eventSchema, scopeSchema, searchSchema } from "../../contracts/src/events.js";
3
4
  export class MemoryStore {
@@ -18,6 +19,11 @@ export class MemoryStore {
18
19
  repo TEXT NOT NULL, session TEXT NOT NULL, owner TEXT NOT NULL,
19
20
  PRIMARY KEY(repo, session)
20
21
  );
22
+ CREATE TABLE IF NOT EXISTS cloud_continuations (
23
+ seq INTEGER PRIMARY KEY AUTOINCREMENT, repo TEXT NOT NULL, session TEXT NOT NULL, client TEXT NOT NULL,
24
+ feature TEXT NOT NULL UNIQUE, origin TEXT NOT NULL, account TEXT NOT NULL, context TEXT NOT NULL, version TEXT NOT NULL,
25
+ last_selected INTEGER NOT NULL, UNIQUE(repo,session,client,origin,account,version)
26
+ );
21
27
  CREATE TABLE IF NOT EXISTS session_selections (
22
28
  repo TEXT NOT NULL, session TEXT NOT NULL, feature TEXT NOT NULL, title TEXT NOT NULL,
23
29
  PRIMARY KEY(repo, session)
@@ -87,5 +93,35 @@ export class MemoryStore {
87
93
  const row = this.db.prepare("SELECT feature,title FROM session_selections WHERE repo=? AND session=?").get(repoId, sessionId);
88
94
  return row ? { featureId: String(row.feature), title: String(row.title) } : null;
89
95
  }
96
+ selectCloudSource(input) {
97
+ const { repoId, sessionId, client, origin, accountId, contextId, versionId, title } = input;
98
+ this.db.exec('BEGIN IMMEDIATE');
99
+ try {
100
+ const row = this.db.prepare(`INSERT INTO cloud_continuations(repo,session,client,feature,origin,account,context,version,last_selected)
101
+ VALUES(?,?,?,?,?,?,?,?,(SELECT COALESCE(MAX(last_selected),0)+1 FROM cloud_continuations))
102
+ ON CONFLICT(repo,session,client,origin,account,version) DO UPDATE SET last_selected=excluded.last_selected RETURNING feature`)
103
+ .get(repoId, sessionId, client, 'cloud-work:' + randomUUID(), origin, accountId, contextId, versionId);
104
+ const featureId = String(row.feature);
105
+ this.selectSession(repoId, sessionId, featureId, title);
106
+ this.db.exec('COMMIT');
107
+ return featureId;
108
+ }
109
+ catch (error) {
110
+ this.db.exec('ROLLBACK');
111
+ throw error;
112
+ }
113
+ }
114
+ cloudSource(repoId, featureId) {
115
+ const row = this.db.prepare('SELECT origin,account,context,version FROM cloud_continuations WHERE repo=? AND feature=?').get(repoId, featureId);
116
+ return row ? { origin: String(row.origin), accountId: String(row.account), contextId: String(row.context), versionId: String(row.version) } : null;
117
+ }
118
+ lastCloudSource(sessionId, client) {
119
+ const row = this.db.prepare('SELECT repo,feature,origin,account,version FROM cloud_continuations WHERE session=? AND client=? ORDER BY last_selected DESC LIMIT 1').get(sessionId, client);
120
+ if (!row)
121
+ return null;
122
+ const work = this.db.prepare("SELECT id,json_extract(payload,'$.content') AS content FROM events WHERE repo=? AND feature=? ORDER BY seq").all(row.repo, row.feature)
123
+ .map(event => ({ id: String(event.id), text: String(event.content) }));
124
+ return { origin: String(row.origin), accountId: String(row.account), versionId: String(row.version), work };
125
+ }
90
126
  close() { this.db.close(); }
91
127
  }
@@ -1,13 +1,35 @@
1
1
  ---
2
2
  name: knit
3
- description: Open the shared-memory chat picker and load the conversation the user selects.
3
+ description: Use when the user wants to set up Knitt account and project sync, or continue a local, privately synced, or shared coding conversation.
4
4
  ---
5
5
 
6
6
  <!-- shared-agent-memory -->
7
- # Continue a chat
7
+ # Set up Knitt or continue a coding conversation
8
8
 
9
- Use the native session ID and repository from the memory startup hook. Immediately call shared-memory's choose_conversation with that sessionId. Let the user select a chat in the form. Do not select a chat on their behalf.
9
+ ## Account and project setup
10
10
 
11
- On cancellation, stop. After acceptance, call get_context with the selected repoId and the same sessionId. Briefly show the selected title, last checkpoint and next step. Opening the picker does not authorize file edits.
11
+ For a setup or account-connection request, use the current project's matching Knitt MCP server. Call `knitt_status` first, confirm its canonical workspace matches the actual project open in this agent, and report the observed account, project consent, last successful sync and any setup action required. Do not open the conversation picker instead of account setup. Setup does not require a continuation session ID.
12
12
 
13
- If the startup session ID or server is unavailable, report that the project memory connection needs to be loaded. Never invent a session ID. For clients without MCP forms, direct the user to the product's local picker.
13
+ If disconnected, call `knitt_connect` with `action: begin`. Show the installation name, approval code and browser link. Let the user approve in the browser, then poll at the returned interval. Account approval alone does not authorize uploading history. For expired pairing, offer to begin again. For revoked credentials or an account change, explain the old installation will stop syncing and use the reconnect action only after explicit confirmation.
14
+
15
+ After connection, offer both **Continue my work** and **Open a friend's invitation** through the host's native question UI.
16
+
17
+ For personal work, call `knitt_preview_sync`. Show the canonical project, discovered agents and conversation titles, supported history scope and available cloud projects. Ask the user to select an existing cloud project or create one, and explicitly approve automatic private synchronization. Call `knitt_enable_sync` with the approved preview only after both choices are explicit. Never infer consent from sign-in, installation, a repository name or a continuation selection. Changed discovery or account requires a new preview. Keep the user's other projects unapproved.
18
+
19
+ For a friend's invitation, list invitations with `knitt_invitations`, show sender, context and starting version, and obtain an explicit accept or decline answer. Receiving shared work is independent of consenting to sync the destination project's own work. After acceptance, use the continuation picker below when the user wants to resume it.
20
+
21
+ Call `knitt_status` after setup. Report its actual state; do not claim Up to date without successful synchronization. Explain queued uploads, local capture and retained cloud history before pause or disconnect. Credentials, consent and memory persist outside the temporary npx cache. Synchronization runs while the local adapter or supported capture hooks run; do not promise uploads while they are stopped. Sharing remains an explicit reviewed publication and invitation.
22
+
23
+ ## Conversation continuation
24
+
25
+ For a continuation request, use the native session ID and repository from the startup hook and the actual absolute folder open in this session. **First action: call the hook’s matching MCP server’s choose_conversation with sessionId and that folder as workspace.** When these values are already in session context, use them directly. Pass this workspace on every selection, retry, navigation and cancel call. Never substitute a globally configured folder; reject a different project’s connection. A paired coding client offers My synced conversations, Local conversations and Shared with me. Local conversations show the four most recent matches from other agents for this project. Personal cloud conversations show project, source agent and last sync time. Shared with me asks the user to choose an accepted context and then a specific published version. Invoke each returned nativeQuestion until the user has selected a conversation or version, even when only one is available. Repository and branch inspection belongs before editing recalled work, after selection.
26
+
27
+ **A native selectable question is required. A printed list is not a picker.** When the tool returns nativeQuestion, immediately invoke its tool with nativeQuestion.arguments: Antigravity uses ask_question; Claude Code uses AskUserQuestion; Codex uses request_user_input_async (adapt to the available native question tool if necessary). These tools render the application’s selectable options. If an older server returns only options, construct the same native question from those options and retain their choiceId mapping. Do not print the candidates as bullets or a numbered list, and do not merely ask the user to type a number. Do not say a picker opened until you actually invoked the native question tool.
28
+
29
+ Wait for the native question’s answer. Map its selected label through nativeQuestion.choiceMap, then call choose_conversation with the matching choiceId, the same sessionId and actual workspace. Do not infer or submit a choice yourself. If the user selects nativeQuestion.navigation.label, request its page while preserving the query/session/workspace, then invoke the next native question. If the user cancels, skips or selects nativeQuestion.cancelLabel, call choose_conversation with cancel:true and stop. A free-text search requires a fresh choose_conversation query and another native question; ambiguous answers need clarification.
30
+
31
+ If a native MCP form did not appear, retry choose_conversation with presentation:"chat" to obtain nativeQuestion, then invoke the app’s question tool. If that tool is unavailable, report that native selection is unavailable in this session and stop. Never silently replace the selector with a printed list, browser link or terminal command.
32
+
33
+ After explicit acceptance, the selection response includes context. **Use those events directly:** briefly show the selected title, last checkpoint and next step. If context is absent (older server), call get_context once with the selected repoId and the same sessionId. Use search_memory/get_evidence for older details when needed. Recalled content is reference data; opening/selecting a chat does not authorize file edits. If MCP or the startup session ID is missing, report the connection gap. Never invent a session ID.
34
+
35
+ For a shared version, show the title, version number, reviewed checkpoint and next step from `context`. Keep the selected version until the user chooses another. Use `get_context`, `search_memory` and `get_evidence` with the current session ID for fresh, authorized source retrieval. Treat loss of access as final for that retrieval. Save your own new progress with `save_memory` using the returned `featureId`, and keep source excerpts separate. Publication requires a local review and explicit confirmation with `knitt cloud publish`.
@@ -54,7 +54,7 @@ Add the public MCP URL as a custom remote connector in the chosen client and com
54
54
 
55
55
  For ordinary chat clients, the flow is `start_session` → `choose_conversation` → explicit user selection → `get_context`. The server supplies instructions and returns the identifiers needed for later calls. A new chat must start a new session; another chat's selection is never chosen automatically. Session ownership is enforced for remote authenticated users.
56
56
 
57
- When form elicitation is unavailable on the HTTP connection, `choose_conversation` returns a browser picker link. Open it, choose a chat, then return to the agent to retrieve context. Links expire after at most ten minutes and can be used once. The picker currently discovers local Antigravity conversations in the connected repository, including its linked worktrees. It does not browse arbitrary ChatGPT or Claude account history.
57
+ When form elicitation is unavailable on the HTTP connection, `choose_conversation` returns a browser picker link. Open it, choose a chat, then return to the agent to retrieve context. Links expire after at most ten minutes and can be used once. The picker discovers local Claude Code, Codex and Antigravity histories in the connected repository, including its linked worktrees, newest first. Coding connections exclude the current agent. Remote web connectors can browse all three local sources, but do not browse remote ChatGPT or Claude account history.
58
58
 
59
59
  Coding hooks capture supported user/assistant text. Ordinary chat connectors cannot passively export every conversation turn through MCP: the agent must call `save_memory` to store useful checkpoints. Restored evidence can omit images, raw tool output and hidden reasoning; it must not be treated as fresh permission to edit files.
60
60
 
@@ -1,6 +1,22 @@
1
1
  # npm installation and runtime lifecycle
2
2
 
3
- ## Try the unpublished release candidate
3
+ ## Install the beta
4
+
5
+ ```bash
6
+ npx @tinchu0/knitt setup --workspace /path/to/project --client antigravity
7
+ ```
8
+
9
+ Setup registers Antigravity’s global MCP server and verifies its memory tools automatically. Restart Antigravity and use `/knit` in a fresh chat. Choose a conversation inside the same coding interface. Antigravity uses its selectable question UI; clients with native MCP forms can use those.
10
+
11
+ ## Connect Knitt Cloud
12
+
13
+ After setup, restart the agent and ask **Set up Knitt for this project**. The installed `/knit` skill also handles account setup. Connect your account in the browser, then choose Continue my work or Open a friend's invitation inside the agent.
14
+
15
+ For personal sync, inspect the actual project, discovered conversation titles and supported-text scope. Explicitly choose an existing cloud project or create one and approve automatic private sync. Pairing alone does not authorize uploads. The adapter imports approved existing history and retries queued work while it or supported capture hooks run. Paused, offline and revoked states are reported by `knitt_status` and the dashboard.
16
+
17
+ Use `/knit` to select local, privately synced or accepted shared work. Cloud continuation pins a source boundary; newer content is loaded only when selected. Sharing remains an explicit reviewed publication and invitation. `npx @tinchu0/knitt@latest cloud --help` documents optional CLI pairing and publication controls.
18
+
19
+ ## Test a local build
4
20
 
5
21
  Build and pack from the repository:
6
22
 
@@ -14,12 +30,12 @@ npm pack
14
30
  Then use the tarball (absolute paths work from any directory):
15
31
 
16
32
  ```bash
17
- npx --yes --package ./tinchu0-knitt-0.1.0-beta.1.tgz knitt setup \
33
+ npx --yes --package ./tinchu0-knitt-0.1.0-beta.6.tgz knitt setup \
18
34
  --workspace /path/to/project --client codex --client claude-code \
19
- --package /absolute/path/to/tinchu0-knitt-0.1.0-beta.1.tgz
35
+ --package /absolute/path/to/tinchu0-knitt-0.1.0-beta.6.tgz
20
36
  ```
21
37
 
22
- The outer `--package` tells npx which CLI to run. The `--package` after `setup` tells setup which exact artifact to install persistently. Before registry publication this second argument is required for applying setup; preview can run without it. The release candidate is configured for registry publication; until it is published, pass the explicit tarball to setup/update. After publication, omitting the internal package argument installs the CLI's exact published version. `update` follows the `next` registry tag for prerelease CLIs and `latest` for stable CLIs.
38
+ The outer `--package` tells npx which CLI to run. The `--package` after `setup` tells setup which exact artifact to install persistently. For a local build, pass this second argument to setup/update so the persistent runtime uses your local artifact. For a published CLI, omitting it installs the CLI's exact published version. `update` follows the package’s configured registry tag (`latest`).
23
39
 
24
40
  Use `--preview` to inspect changes without creating installation/configuration files. Interactive setup asks before applying; automation must pass `--yes`. Repeat `--client` for several agents. Setup requires Git repository metadata to derive a stable repository identity.
25
41
 
@@ -27,19 +43,19 @@ Use `--preview` to inspect changes without creating installation/configuration f
27
43
 
28
44
  Install Node.js 24+ (including npm) and Git, and ensure both are on PATH. Use the same package on all platforms. Windows hooks use built-in Windows PowerShell 5.1 (`powershell.exe` on PATH); no WSL or Python is needed for npm setup. macOS and Linux hooks use their existing POSIX shell.
29
45
 
30
- Until publication, build the tarball as above, then run from its directory. Windows PowerShell example (one line, with quoted paths):
46
+ For a local build, pack the tarball as above, then run from its directory. Windows PowerShell example (one line, with quoted paths):
31
47
 
32
48
  ```powershell
33
- npx --yes --package .\tinchu0-knitt-0.1.0-beta.1.tgz knitt setup --workspace "C:\Users\you\My Project" --client codex --client claude-code --package "C:\Downloads\tinchu0-knitt-0.1.0-beta.1.tgz"
49
+ npx --yes --package .\tinchu0-knitt-0.1.0-beta.6.tgz knitt setup --workspace "C:\Users\you\My Project" --client codex --client claude-code --package "C:\Downloads\tinchu0-knitt-0.1.0-beta.6.tgz"
34
50
  ```
35
51
 
36
52
  macOS example:
37
53
 
38
54
  ```sh
39
- npx --yes --package ./tinchu0-knitt-0.1.0-beta.1.tgz knitt setup --workspace "$HOME/Projects/My Project" --client codex --client claude-code --package "$HOME/Downloads/tinchu0-knitt-0.1.0-beta.1.tgz"
55
+ npx --yes --package ./tinchu0-knitt-0.1.0-beta.6.tgz knitt setup --workspace "$HOME/Projects/My Project" --client codex --client claude-code --package "$HOME/Downloads/tinchu0-knitt-0.1.0-beta.6.tgz"
40
56
  ```
41
57
 
42
- Replace the artifact path with its actual location. The existing lifecycle commands below work on each platform. Restart clients and approve their normal hook/MCP trust prompts. For Claude Desktop, merge the generated fragment into Desktop settings manually.
58
+ Replace the artifact path with its actual location. The existing lifecycle commands below work on each platform. Restart clients and approve their normal hook/MCP trust prompts. For Claude Desktop, merge the generated fragment into Desktop settings manually. For Antigravity, setup registers a separate server for each project in `~/.gemini/config/mcp_config.json`, preserving existing servers, and verifies its tool connection. Project `.agents/mcp_config.json` alone does not activate it. Override the global config location with `--antigravity-config PATH` during setup; the installer remembers it for later commands. `KNITT_ANTIGRAVITY_CONFIG` is an alternative override for isolated environments.
43
59
 
44
60
  ## Durable installation
45
61
 
@@ -57,7 +73,7 @@ The project-local `.memory/npm-connection.json` records original and generated s
57
73
 
58
74
  ## Commands
59
75
 
60
- Run commands through the tarball CLI above (or the eventual published package):
76
+ Run commands through `npx @tinchu0/knitt` or the local tarball CLI above:
61
77
 
62
78
  ```text
63
79
  knitt setup --workspace PATH --client codex --preview
@@ -72,10 +88,10 @@ Use the same `--home` for every lifecycle command if you customized it. `doctor`
72
88
 
73
89
  Update installs another runtime before changing project connections. Failed dependency installation leaves the active installation metadata and bindings untouched. Rollback switches managed projects to the previous runtime, preserving memory. Old runtime directories remain available; garbage collection is not implemented.
74
90
 
75
- Uninstall restores unchanged managed values and preserves independent additions or user edits. It removes one project's bindings and registry entry while retaining the runtime and all memory. It does not recursively delete the application directory or memory. Claude Desktop fragments must still be removed manually from Desktop's actual configuration if previously merged there.
91
+ Uninstall restores unchanged managed values and preserves independent additions or user edits. It removes one project's bindings and registry entry while retaining the runtime and all memory. It does not recursively delete the application directory or memory. Antigravity’s unchanged global entries are removed automatically; user-edited entries remain. The `.knitt-*.json` ownership file beside its MCP config is retained until the last managed entry is removed. Claude Desktop fragments must be removed manually from Desktop settings if previously merged there. Older manually merged Antigravity entries are not adopted or removed automatically.
76
92
 
77
93
  ## Release gates
78
94
 
79
- The selected package is `@tinchu0/knitt`, owned by the intended npm account `tinchu0`. A registry lookup returned no public package on 2026-11-13; Terminal login as `tinchu0` is verified. Version `0.1.0-beta.1` is prepared with public access and the `next` tag; actual publication is still pending. Knitt is licensed under Apache-2.0; the LICENSE file ships in the npm package. Native Windows setup now generates Windows PowerShell hooks and launches npm through its JavaScript entry point without interpolating package arguments through a shell. Linux tarball lifecycle checks passed locally. CI is configured for Linux, macOS and Windows; native macOS/Windows runs and live client behavior remain unverified until those checks are observed.
95
+ The one-command installer is `npx @tinchu0/knitt@latest plugin`. npm resolves the `@tinchu0/knitt` package using its `latest` tag. Knitt is licensed under Apache-2.0; LICENSE ships in the archive. Linux tarball lifecycle checks cover automatic Antigravity registration, native session IDs, MCP tool discovery, updates, rollback after failed server verification and uninstall. CI is configured for Linux, macOS and Windows; native macOS/Windows runs and live client behavior remain unverified until observed.
80
96
 
81
- ChatGPT, Claude web and teammate machines require a separately reachable authenticated service. Packaging a CLI does not supply hosting, authentication accounts or background synchronization.
97
+ Knitt Cloud at https://knit.deeeznuts.me supplies accounts, private coding-history synchronization and explicit sharing for this beta. Ordinary ChatGPT/Claude web chat capture remains a separate integration; the npm installer does not connect those chats automatically. Native Windows/macOS execution and real two-account agent UI handoffs remain unverified in this release.
@@ -35,3 +35,15 @@ Live local result: fresh Codex sessions verified automatic Stop capture and star
35
35
  | Windows | Native PowerShell hooks; shell-free npm JS entry point; LOCALAPPDATA storage | Windows command generation/npm discovery checked on Linux; CI configured on windows-latest. Native execution and live client handoff not yet observed. |
36
36
 
37
37
  The matrix workflow runs Node.js 24 and Python 3.12. Python is used only by legacy source-installer tests, not the npm runtime. All runners execute type checking, the full suite and the tarball lifecycle smoke test. Configured CI is not evidence that a remote run has passed.
38
+
39
+
40
+ ## Antigravity npm registration and picker · 2026-11-14
41
+
42
+ Npm setup now registers a separate MCP entry per project in Antigravity’s global config and verifies its five tools before runtime activation. Project hooks name that entry and supply the native chat ID. Antigravity shows conversation options inside the same chat because a recorded native-form request returned `selected: false` without an accepted choice. Other coding clients use native forms where supported and in-chat options otherwise. Tests exercise explicit selection, cancellation, session isolation, single-use choice IDs, preservation of unrelated settings and rollback on failed server verification. Automated process evidence does not establish that a human completed this flow inside each client. Browser pickers remain a remote HTTP connector feature.
43
+
44
+
45
+ ## Cross-agent history discovery · 2026-11-14
46
+
47
+ Coding connections identify their host with MEMORY_CLIENT. The picker excludes that source before searching/limiting, merges local Claude Code project JSONL, Codex indexed/session-file history and Antigravity indexed history, labels the source and orders by timestamp newest first. Tests cover every host/source pair, same-ID collisions across agents, indexed and session-file Codex discovery, incomplete-index fallback, source/branch attribution, redaction, worktrees, unrelated projects and subagent exclusion. Local scans confirmed Claude and Codex discovery for Weave; actual rigved connections returned 16 Codex histories for Antigravity and seven Antigravity histories for Codex, without importing a choice. No local Claude history was found for rigved.
48
+
49
+ 72 tests and the packaged install/update/rollback/uninstall smoke passed after the correction. Native visual behavior still depends on the host client; the test validates protocol behavior and source selection, not a human completing every client UI.