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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,31 +1,33 @@
1
1
  #!/usr/bin/env node
2
- import { readCaptureStatuses } from "../../adapters/src/status.js";
3
- import { parseArgs } from "node:util";
4
- import { createInterface } from "node:readline/promises";
5
- import { fileURLToPath } from "node:url";
6
- import { join, resolve, dirname } from "node:path";
7
- import { existsSync, readFileSync, accessSync, constants, rmSync, } from "node:fs";
8
- import { execFileSync } from "node:child_process";
9
- import { planConnection, applyConnectionPlan, planUninstall, clients, atomicWrite, readConnectionState, } from "./connections.js";
10
- import { installRuntime, readInstallation, defaultHome, runtimePaths, withInstallLock, activateRuntime, assertRuntimeCompatibility, packageName, } from "./runtime.js";
11
- import { resolveRepository } from "../../adapters/src/repository.js";
12
- const appRoot = fileURLToPath(new URL("../../../", import.meta.url));
13
- const packageRoot = existsSync(join(appRoot, "package.json"))
2
+ import { readCaptureStatuses } from '../../adapters/src/status.js';
3
+ import { parseArgs } from 'node:util';
4
+ import { createInterface } from 'node:readline/promises';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { join, resolve, dirname, basename } from 'node:path';
7
+ import { existsSync, readFileSync, accessSync, constants, } from 'node:fs';
8
+ import { execFileSync } from 'node:child_process';
9
+ import { planConnection, applyConnectionPlan, planUninstall, clients, atomicWrite, readConnectionState, rollbackConnectionPlan, } from './connections.js';
10
+ import { installRuntime, readInstallation, defaultHome, runtimePaths, withInstallLock, activateRuntime, assertRuntimeCompatibility, packageName, } from './runtime.js';
11
+ import { planAntigravity, verifyAntigravity, defaultAntigravityConfig, } from './antigravity.js';
12
+ import { antigravityServerName } from '../../adapters/src/server-name.js';
13
+ import { resolveRepository } from '../../adapters/src/repository.js';
14
+ const appRoot = fileURLToPath(new URL('../../../', import.meta.url));
15
+ const packageRoot = existsSync(join(appRoot, 'package.json'))
14
16
  ? appRoot
15
17
  : dirname(appRoot);
16
- const metadata = JSON.parse(readFileSync(join(packageRoot, "package.json"), "utf8"));
18
+ const metadata = JSON.parse(readFileSync(join(packageRoot, 'package.json'), 'utf8'));
17
19
  const version = metadata.version;
18
20
  async function confirm(text, yes = false) {
19
21
  if (yes)
20
22
  return true;
21
23
  if (!process.stdin.isTTY)
22
- throw new Error("Use --yes for noninteractive apply, or --preview to inspect without changes");
24
+ throw new Error('Use --yes for noninteractive apply, or --preview to inspect without changes');
23
25
  const reader = createInterface({
24
26
  input: process.stdin,
25
27
  output: process.stdout,
26
28
  });
27
29
  try {
28
- return /^y(es)?$/i.test((await reader.question(text + " [y/N] ")).trim());
30
+ return /^y(es)?$/i.test((await reader.question(text + ' [y/N] ')).trim());
29
31
  }
30
32
  finally {
31
33
  reader.close();
@@ -33,7 +35,7 @@ async function confirm(text, yes = false) {
33
35
  }
34
36
  async function ask(prompt) {
35
37
  if (!process.stdin.isTTY)
36
- throw new Error("Pass --workspace and --client for noninteractive setup");
38
+ throw new Error('Pass --workspace and --client for noninteractive setup');
37
39
  const reader = createInterface({
38
40
  input: process.stdin,
39
41
  output: process.stdout,
@@ -45,40 +47,28 @@ async function ask(prompt) {
45
47
  reader.close();
46
48
  }
47
49
  }
48
- function preview(plan) {
50
+ function preview(plan, contents = true) {
49
51
  for (const [path, content] of Object.entries(plan.changes)) {
50
- if (path.includes("npm-connection"))
52
+ if (path.includes('npm-connection'))
51
53
  continue;
52
- console.log((content === null ? "remove " : "merge ") + join(plan.workspace, path));
53
- if (content !== null && content !== plan.expected[path])
54
+ console.log((content === null ? 'remove ' : 'merge ') + join(plan.workspace, path));
55
+ if (contents && content !== null && content !== plan.expected[path])
54
56
  console.log(content);
55
57
  }
56
58
  }
57
- function applyAll(plans, commit) {
59
+ async function applyAll(plans, commit, verify = async () => { }) {
58
60
  const done = [];
59
61
  try {
60
62
  for (const plan of plans) {
61
63
  applyConnectionPlan(plan);
62
64
  done.push(plan);
63
65
  }
66
+ await verify();
64
67
  commit();
65
68
  }
66
69
  catch (error) {
67
70
  for (const plan of done.reverse())
68
- for (const [path, content] of Object.entries(plan.expected)) {
69
- // Already-written files are restored as one transaction; unrelated concurrent
70
- // edits are protected by each plan's optimistic concurrency check.
71
- const target = join(plan.workspace, path);
72
- const current = existsSync(target)
73
- ? readFileSync(target, "utf8")
74
- : null;
75
- if (current !== plan.changes[path])
76
- continue;
77
- if (content !== null)
78
- atomicWrite(join(plan.workspace, path), content);
79
- else
80
- rmSync(join(plan.workspace, path), { force: true });
81
- }
71
+ rollbackConnectionPlan(plan);
82
72
  throw error;
83
73
  }
84
74
  }
@@ -93,16 +83,17 @@ async function main() {
93
83
  const { values, positionals } = parseArgs({
94
84
  allowPositionals: true,
95
85
  options: {
96
- session: { type: "string" },
97
- workspace: { type: "string" },
98
- client: { type: "string", multiple: true },
99
- home: { type: "string" },
100
- package: { type: "string" },
101
- yes: { type: "boolean" },
102
- preview: { type: "boolean" },
103
- "capture-new-sessions": { type: "boolean" },
104
- version: { type: "boolean" },
105
- help: { type: "boolean" },
86
+ session: { type: 'string' },
87
+ workspace: { type: 'string' },
88
+ client: { type: 'string', multiple: true },
89
+ home: { type: 'string' },
90
+ package: { type: 'string' },
91
+ yes: { type: 'boolean' },
92
+ preview: { type: 'boolean' },
93
+ 'capture-new-sessions': { type: 'boolean' },
94
+ 'antigravity-config': { type: 'string' },
95
+ version: { type: 'boolean' },
96
+ help: { type: 'boolean' },
106
97
  },
107
98
  });
108
99
  if (values.version) {
@@ -111,16 +102,16 @@ async function main() {
111
102
  }
112
103
  const action = positionals[0];
113
104
  if (!action || values.help) {
114
- console.log("Knitt " +
105
+ console.log('Knitt ' +
115
106
  version +
116
- "\nCommands: setup, doctor, update, rollback, uninstall, serve, continue\nOptions: --workspace PATH --client codex|claude-code|antigravity|claude-desktop (repeatable)\n --capture-new-sessions --preview --yes --home PATH --package TARBALL_OR_VERSION_SPEC\nSetup configures a persistent local runtime; remote/team service is configured separately.");
107
+ '\nCommands: setup, doctor, update, rollback, uninstall, serve, continue\nOptions: --workspace PATH --client codex|claude-code|antigravity|claude-desktop (repeatable)\n --antigravity-config PATH --capture-new-sessions --preview --yes --home PATH --package TARBALL_OR_VERSION_SPEC\nSetup configures a persistent local runtime; remote/team service is configured separately.');
117
108
  return;
118
109
  }
119
110
  const home = resolve(values.home ?? defaultHome()), paths = runtimePaths(home);
120
- if (action === "continue") {
111
+ if (action === 'continue') {
121
112
  if (!values.workspace)
122
- throw new Error("Pass --workspace for the connected project");
123
- const common = (cwd) => execFileSync("git", ["rev-parse", "--path-format=absolute", "--git-common-dir"], { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
113
+ throw new Error('Pass --workspace for the connected project');
114
+ const common = (cwd) => execFileSync('git', ['rev-parse', '--path-format=absolute', '--git-common-dir'], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
124
115
  const expected = common(resolve(values.workspace));
125
116
  const state = readInstallation(home);
126
117
  const project = state?.projects.find((p) => {
@@ -132,57 +123,84 @@ async function main() {
132
123
  }
133
124
  });
134
125
  if (!project?.captureNewSessions)
135
- throw new Error("This project has not opted into local conversation mode; run setup --capture-new-sessions first");
126
+ throw new Error('This project has not opted into local conversation mode; run setup --capture-new-sessions first');
136
127
  process.env.MEMORY_DB = project.database;
137
128
  process.env.MEMORY_REPO = project.repoId;
138
- process.env.MEMORY_CONVERSATION_MODE = "1";
139
- await import("../../adapters/src/command.js");
129
+ process.env.MEMORY_CONVERSATION_MODE = '1';
130
+ await import('../../adapters/src/command.js');
140
131
  return;
141
132
  }
142
- if (action === "serve") {
143
- process.env.MEMORY_DB ??= join(paths.data, "events.sqlite");
144
- await import("../../../apps/server/src/main.js");
133
+ const initialState = readInstallation(home);
134
+ const configPath = resolve(values['antigravity-config'] ??
135
+ initialState?.antigravityConfig ??
136
+ defaultAntigravityConfig());
137
+ const globalOptions = (runtime, projects) => ({
138
+ configPath,
139
+ installationHome: home,
140
+ appRoot: runtime.appRoot,
141
+ node: runtime.node,
142
+ projects,
143
+ });
144
+ if (initialState?.antigravityConfig &&
145
+ configPath !== resolve(initialState.antigravityConfig))
146
+ throw new Error('This installation already manages another Antigravity config. Use its existing path: ' +
147
+ initialState.antigravityConfig);
148
+ if (action === 'serve') {
149
+ process.env.MEMORY_DB ??= join(paths.data, 'events.sqlite');
150
+ await import('../../../apps/server/src/main.js');
145
151
  return;
146
152
  }
147
- if (action === "doctor") {
153
+ if (action === 'doctor') {
148
154
  const state = readInstallation(home), problems = [];
149
- if (Number(process.versions.node.split(".")[0]) < 24)
150
- problems.push("Install Node.js 24+");
155
+ if (Number(process.versions.node.split('.')[0]) < 24)
156
+ problems.push('Install Node.js 24+');
151
157
  try {
152
- execFileSync("git", ["--version"], { stdio: "ignore" });
158
+ execFileSync('git', ['--version'], { stdio: 'ignore' });
153
159
  }
154
160
  catch {
155
- problems.push("Install Git and add it to PATH");
161
+ problems.push('Install Git and add it to PATH');
156
162
  }
157
163
  if (!state)
158
- problems.push("No persistent runtime installed. Run setup.");
164
+ problems.push('No persistent runtime installed. Run setup.');
159
165
  else {
160
166
  for (const file of [
161
167
  state.current.node,
162
- join(state.current.appRoot, "apps/server/src/main.js"),
168
+ join(state.current.appRoot, 'apps/server/src/main.js'),
163
169
  ])
164
170
  if (!existsSync(file))
165
- problems.push("Missing runtime path: " + file + ". Run setup again.");
171
+ problems.push('Missing runtime path: ' + file + '. Run setup again.');
166
172
  try {
167
173
  accessSync(paths.data, constants.W_OK);
168
174
  }
169
175
  catch {
170
- problems.push("Data directory is not writable: " + paths.data);
176
+ problems.push('Data directory is not writable: ' + paths.data);
177
+ }
178
+ try {
179
+ const globalPlan = planAntigravity(globalOptions(state.current, state.projects));
180
+ const before = globalPlan.expected[basename(configPath)];
181
+ const servers = before ? (JSON.parse(before).mcpServers ?? {}) : {};
182
+ for (const project of state.projects.filter((p) => p.clients.includes('antigravity'))) {
183
+ if (!servers[antigravityServerName(project.workspace)])
184
+ problems.push('Missing Antigravity server: ' + project.workspace);
185
+ }
186
+ }
187
+ catch (error) {
188
+ problems.push(error instanceof Error ? error.message : String(error));
171
189
  }
172
190
  for (const project of state.projects) {
173
191
  try {
174
192
  const managed = readConnectionState(project.workspace);
175
193
  if (!Object.keys(managed.files).length)
176
- problems.push("Missing connector state: " + project.workspace);
194
+ problems.push('Missing connector state: ' + project.workspace);
177
195
  for (const [path, snapshot] of Object.entries(managed.files)) {
178
- const current = readFileSync(join(project.workspace, path), "utf8");
196
+ const current = readFileSync(join(project.workspace, path), 'utf8');
179
197
  if (current !== snapshot.after)
180
- problems.push("Configuration changed; review before setup: " +
198
+ problems.push('Configuration changed; review before setup: ' +
181
199
  join(project.workspace, path));
182
200
  }
183
201
  }
184
202
  catch {
185
- problems.push("Missing or invalid project configuration: " + project.workspace);
203
+ problems.push('Missing or invalid project configuration: ' + project.workspace);
186
204
  }
187
205
  }
188
206
  }
@@ -190,7 +208,7 @@ async function main() {
190
208
  .filter((p) => p.captureNewSessions)
191
209
  .map((project) => {
192
210
  const observations = project.clients
193
- .flatMap((client) => readCaptureStatuses(join(dirname(project.database), "queue", client === "claude-code" ? "claude" : client)))
211
+ .flatMap((client) => readCaptureStatuses(join(dirname(project.database), 'queue', client === 'claude-code' ? 'claude' : client)))
194
212
  .filter((s) => s.session.repoId === project.repoId);
195
213
  return {
196
214
  workspace: project.workspace,
@@ -201,31 +219,31 @@ async function main() {
201
219
  });
202
220
  console.log(JSON.stringify({
203
221
  capture,
204
- status: problems.length ? "attention_required" : "configured",
222
+ status: problems.length ? 'attention_required' : 'configured',
205
223
  runtime: state?.current.version,
206
224
  problems,
207
- note: "Configuration check only; agent login/trust and live handoff are not verified.",
225
+ note: 'Configuration check only; agent login/trust and live handoff are not verified.',
208
226
  }, null, 2));
209
227
  if (problems.length)
210
228
  process.exitCode = 1;
211
229
  return;
212
230
  }
213
- if (!["setup", "update", "rollback", "uninstall"].includes(action))
214
- throw new Error("Unknown command: " + action);
231
+ if (!['setup', 'update', 'rollback', 'uninstall'].includes(action))
232
+ throw new Error('Unknown command: ' + action);
215
233
  let project;
216
- if (action === "setup") {
217
- const directory = values.workspace ?? (await ask("Project folder: "));
234
+ if (action === 'setup') {
235
+ const directory = values.workspace ?? (await ask('Project folder: '));
218
236
  const selected = values.client ??
219
- (await ask("Agents (comma separated: " + clients.join(", ") + "): "))
220
- .split(",")
237
+ (await ask('Agents (comma separated: ' + clients.join(', ') + '): '))
238
+ .split(',')
221
239
  .map((v) => v.trim());
222
240
  const { workspace, repoId } = resolveRepository(resolve(directory));
223
241
  project = {
224
242
  workspace,
225
243
  repoId,
226
244
  clients: selected,
227
- database: join(paths.data, "events.sqlite"),
228
- ...(values["capture-new-sessions"] ? { captureNewSessions: true } : {}),
245
+ database: join(paths.data, 'events.sqlite'),
246
+ ...(values['capture-new-sessions'] ? { captureNewSessions: true } : {}),
229
247
  };
230
248
  // Validate and show changes before installing dependencies or writing settings.
231
249
  const previousProject = readInstallation(home)?.projects.find((p) => p.workspace === workspace);
@@ -233,47 +251,68 @@ async function main() {
233
251
  project.repoId = previousProject.repoId;
234
252
  const plan = planConnection({ ...project, appRoot });
235
253
  preview(plan);
254
+ const projects = [
255
+ ...(initialState?.projects ?? []).filter((p) => p.workspace !== project.workspace),
256
+ {
257
+ ...project,
258
+ clients: [
259
+ ...new Set([
260
+ ...(initialState?.projects.find((p) => p.workspace === project.workspace)?.clients ?? []),
261
+ ...project.clients,
262
+ ]),
263
+ ],
264
+ },
265
+ ];
266
+ preview(planAntigravity(globalOptions({ version, appRoot, node: process.execPath }, projects)), false);
236
267
  if (values.preview) {
237
- console.log("Preview only. No runtime or configuration installed.");
268
+ console.log('Preview only. No runtime or configuration installed.');
238
269
  return;
239
270
  }
240
271
  }
241
272
  else {
242
273
  const state = readInstallation(home);
243
274
  if (!state)
244
- throw new Error("No installation found. Run setup first.");
245
- if (action === "uninstall") {
275
+ throw new Error('No installation found. Run setup first.');
276
+ if (action === 'uninstall') {
246
277
  const target = values.workspace
247
278
  ? resolveRepository(resolve(values.workspace)).workspace
248
279
  : null;
249
280
  if (!target)
250
- throw new Error("Pass --workspace to uninstall one project; memory data is always retained");
281
+ throw new Error('Pass --workspace to uninstall one project; memory data is always retained');
251
282
  if (!state.projects.some((p) => p.workspace === target))
252
- throw new Error("Project is not managed by this installation");
283
+ throw new Error('Project is not managed by this installation');
253
284
  preview(planUninstall(target));
285
+ preview(planAntigravity({
286
+ ...globalOptions(state.current, state.projects.filter((p) => p.workspace !== target)),
287
+ removeOnly: true,
288
+ }), false);
254
289
  }
255
290
  else
256
291
  console.log(action +
257
- " runtime for " +
292
+ ' runtime for ' +
258
293
  state.projects.length +
259
- " project(s); user memory is retained.");
294
+ ' project(s); user memory is retained.');
260
295
  if (values.preview)
261
296
  return;
262
297
  }
263
- if (!(await confirm("Apply " + action + "?", values.yes))) {
264
- console.log("Cancelled. No changes applied.");
298
+ if (!(await confirm('Apply ' + action + '?', values.yes))) {
299
+ console.log('Cancelled. No changes applied.');
265
300
  return;
266
301
  }
267
302
  await withInstallLock(home, async () => {
268
303
  const state = readInstallation(home);
269
- if (action === "uninstall") {
304
+ if (action === 'uninstall') {
270
305
  const target = resolveRepository(resolve(values.workspace)).workspace;
271
306
  const plan = planUninstall(target);
272
- applyAll([plan], () => atomicWrite(paths.state, JSON.stringify({
273
- ...state,
274
- projects: state.projects.filter((p) => p.workspace !== target),
275
- }, null, 2)));
276
- console.log("Project connectors removed where unchanged. User-edited settings and all memory retained. Runtime retained for other projects.");
307
+ const remaining = state.projects.filter((p) => p.workspace !== target);
308
+ await applyAll([
309
+ plan,
310
+ planAntigravity({
311
+ ...globalOptions(state.current, remaining),
312
+ removeOnly: true,
313
+ }),
314
+ ], () => atomicWrite(paths.state, JSON.stringify({ ...state, projects: remaining }, null, 2)));
315
+ console.log('Project connectors removed where unchanged. User-edited settings and all memory retained. Runtime retained for other projects.');
277
316
  return;
278
317
  }
279
318
  if (project) {
@@ -293,27 +332,35 @@ async function main() {
293
332
  project,
294
333
  ]
295
334
  : state.projects;
296
- if (action !== "rollback" && metadata.private && !values.package)
297
- throw new Error("This package is unpublished. Pass --package /absolute/path/to/the-built.tgz; registry installation is disabled until release.");
298
- const runtime = action === "rollback"
335
+ if (action !== 'rollback' && metadata.private && !values.package)
336
+ throw new Error('This package is unpublished. Pass --package /absolute/path/to/the-built.tgz; registry installation is disabled until release.');
337
+ const runtime = action === 'rollback'
299
338
  ? state?.previous
300
339
  : installRuntime(home, values.package ??
301
340
  packageName +
302
- "@" +
303
- (action === "update"
304
- ? version.includes("-")
305
- ? "next"
306
- : "latest"
341
+ '@' +
342
+ (action === 'update'
343
+ ? version.includes('-')
344
+ ? 'next'
345
+ : 'latest'
307
346
  : version));
308
347
  if (!runtime)
309
- throw new Error("No previous runtime available");
348
+ throw new Error('No previous runtime available');
310
349
  assertRuntimeCompatibility(runtime, projects);
311
350
  const plans = plansFor(runtime, projects);
312
- applyAll(plans, () => activateRuntime(home, runtime, projects));
313
- console.log("Installed runtime " + runtime.version + ". Data: " + paths.data);
314
- console.log("Restart connected agents and review MCP/hook trust prompts. Use /continue-chat to select your conversation.");
315
- if (projects.some((p) => p.clients.includes("claude-desktop")))
316
- console.log("Claude Desktop: merge the generated project .memory/connectors/claude-desktop.json fragment into Desktop MCP settings, then restart.");
351
+ plans.push(planAntigravity(globalOptions(runtime, projects)));
352
+ await applyAll(plans, () => activateRuntime(home, runtime, projects, projects.some((p) => p.clients.includes('antigravity'))
353
+ ? configPath
354
+ : state?.antigravityConfig), () => verifyAntigravity(globalOptions(runtime, projects)));
355
+ console.log('Installed runtime ' + runtime.version + '. Data: ' + paths.data);
356
+ console.log('Restart connected agents and review MCP/hook trust prompts. ' +
357
+ (existsSync(join(runtime.appRoot, 'skills/knit/SKILL.md')) ? 'Use /continue-chat for projects with --capture-new-sessions; use /knit for other projects.' : 'Use /continue-chat with this runtime.'));
358
+ if (projects.some((p) => p.clients.includes('antigravity')))
359
+ console.log('Antigravity: project memory servers registered in ' +
360
+ configPath +
361
+ ' and tool connections verified. Restart Antigravity and open a fresh project chat.');
362
+ if (projects.some((p) => p.clients.includes('claude-desktop')))
363
+ console.log('Claude Desktop: merge the generated project .memory/connectors/claude-desktop.json fragment into Desktop MCP settings, then restart.');
317
364
  });
318
365
  }
319
366
  try {