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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,25 +1,31 @@
1
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'));
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"))
14
+ ? appRoot
15
+ : dirname(appRoot);
16
+ const metadata = JSON.parse(readFileSync(join(packageRoot, "package.json"), "utf8"));
14
17
  const version = metadata.version;
15
18
  async function confirm(text, yes = false) {
16
19
  if (yes)
17
20
  return true;
18
21
  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 });
22
+ throw new Error("Use --yes for noninteractive apply, or --preview to inspect without changes");
23
+ const reader = createInterface({
24
+ input: process.stdin,
25
+ output: process.stdout,
26
+ });
21
27
  try {
22
- return /^y(es)?$/i.test((await reader.question(text + ' [y/N] ')).trim());
28
+ return /^y(es)?$/i.test((await reader.question(text + " [y/N] ")).trim());
23
29
  }
24
30
  finally {
25
31
  reader.close();
@@ -27,8 +33,11 @@ async function confirm(text, yes = false) {
27
33
  }
28
34
  async function ask(prompt) {
29
35
  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 });
36
+ throw new Error("Pass --workspace and --client for noninteractive setup");
37
+ const reader = createInterface({
38
+ input: process.stdin,
39
+ output: process.stdout,
40
+ });
32
41
  try {
33
42
  return (await reader.question(prompt)).trim();
34
43
  }
@@ -38,9 +47,9 @@ async function ask(prompt) {
38
47
  }
39
48
  function preview(plan) {
40
49
  for (const [path, content] of Object.entries(plan.changes)) {
41
- if (path.includes('npm-connection'))
50
+ if (path.includes("npm-connection"))
42
51
  continue;
43
- console.log((content === null ? 'remove ' : 'merge ') + join(plan.workspace, path));
52
+ console.log((content === null ? "remove " : "merge ") + join(plan.workspace, path));
44
53
  if (content !== null && content !== plan.expected[path])
45
54
  console.log(content);
46
55
  }
@@ -60,7 +69,9 @@ function applyAll(plans, commit) {
60
69
  // Already-written files are restored as one transaction; unrelated concurrent
61
70
  // edits are protected by each plan's optimistic concurrency check.
62
71
  const target = join(plan.workspace, path);
63
- const current = existsSync(target) ? readFileSync(target, 'utf8') : null;
72
+ const current = existsSync(target)
73
+ ? readFileSync(target, "utf8")
74
+ : null;
64
75
  if (current !== plan.changes[path])
65
76
  continue;
66
77
  if (content !== null)
@@ -71,134 +82,238 @@ function applyAll(plans, commit) {
71
82
  throw error;
72
83
  }
73
84
  }
74
- function plansFor(runtime, projects) { return projects.map(project => planConnection({ ...project, appRoot: runtime.appRoot, node: runtime.node })); }
85
+ function plansFor(runtime, projects) {
86
+ return projects.map((project) => planConnection({
87
+ ...project,
88
+ appRoot: runtime.appRoot,
89
+ node: runtime.node,
90
+ }));
91
+ }
75
92
  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
- } });
93
+ const { values, positionals } = parseArgs({
94
+ allowPositionals: true,
95
+ 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" },
106
+ },
107
+ });
81
108
  if (values.version) {
82
109
  console.log(version);
83
110
  return;
84
111
  }
85
112
  const action = positionals[0];
86
113
  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.');
114
+ console.log("Knitt " +
115
+ 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.");
88
117
  return;
89
118
  }
90
119
  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');
120
+ if (action === "continue") {
121
+ 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();
124
+ const expected = common(resolve(values.workspace));
125
+ const state = readInstallation(home);
126
+ const project = state?.projects.find((p) => {
127
+ try {
128
+ return common(p.workspace) === expected;
129
+ }
130
+ catch {
131
+ return false;
132
+ }
133
+ });
134
+ if (!project?.captureNewSessions)
135
+ throw new Error("This project has not opted into local conversation mode; run setup --capture-new-sessions first");
136
+ process.env.MEMORY_DB = project.database;
137
+ process.env.MEMORY_REPO = project.repoId;
138
+ process.env.MEMORY_CONVERSATION_MODE = "1";
139
+ await import("../../adapters/src/command.js");
94
140
  return;
95
141
  }
96
- if (action === 'doctor') {
142
+ if (action === "serve") {
143
+ process.env.MEMORY_DB ??= join(paths.data, "events.sqlite");
144
+ await import("../../../apps/server/src/main.js");
145
+ return;
146
+ }
147
+ if (action === "doctor") {
97
148
  const state = readInstallation(home), problems = [];
98
- if (Number(process.versions.node.split('.')[0]) < 24)
99
- problems.push('Install Node.js 24+');
149
+ if (Number(process.versions.node.split(".")[0]) < 24)
150
+ problems.push("Install Node.js 24+");
100
151
  try {
101
- execFileSync('git', ['--version'], { stdio: 'ignore' });
152
+ execFileSync("git", ["--version"], { stdio: "ignore" });
102
153
  }
103
154
  catch {
104
- problems.push('Install Git and add it to PATH');
155
+ problems.push("Install Git and add it to PATH");
105
156
  }
106
157
  if (!state)
107
- problems.push('No persistent runtime installed. Run setup.');
158
+ problems.push("No persistent runtime installed. Run setup.");
108
159
  else {
109
- for (const file of [state.current.node, join(state.current.appRoot, 'apps/server/src/main.js')])
160
+ for (const file of [
161
+ state.current.node,
162
+ join(state.current.appRoot, "apps/server/src/main.js"),
163
+ ])
110
164
  if (!existsSync(file))
111
- problems.push('Missing runtime path: ' + file + '. Run setup again.');
165
+ problems.push("Missing runtime path: " + file + ". Run setup again.");
112
166
  try {
113
167
  accessSync(paths.data, constants.W_OK);
114
168
  }
115
169
  catch {
116
- problems.push('Data directory is not writable: ' + paths.data);
170
+ problems.push("Data directory is not writable: " + paths.data);
117
171
  }
118
172
  for (const project of state.projects) {
119
173
  try {
120
174
  const managed = readConnectionState(project.workspace);
121
175
  if (!Object.keys(managed.files).length)
122
- problems.push('Missing connector state: ' + project.workspace);
176
+ problems.push("Missing connector state: " + project.workspace);
123
177
  for (const [path, snapshot] of Object.entries(managed.files)) {
124
- const current = readFileSync(join(project.workspace, path), 'utf8');
178
+ const current = readFileSync(join(project.workspace, path), "utf8");
125
179
  if (current !== snapshot.after)
126
- problems.push('Configuration changed; review before setup: ' + join(project.workspace, path));
180
+ problems.push("Configuration changed; review before setup: " +
181
+ join(project.workspace, path));
127
182
  }
128
183
  }
129
184
  catch {
130
- problems.push('Missing or invalid project configuration: ' + project.workspace);
185
+ problems.push("Missing or invalid project configuration: " + project.workspace);
131
186
  }
132
187
  }
133
188
  }
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));
189
+ const capture = (state?.projects ?? [])
190
+ .filter((p) => p.captureNewSessions)
191
+ .map((project) => {
192
+ const observations = project.clients
193
+ .flatMap((client) => readCaptureStatuses(join(dirname(project.database), "queue", client === "claude-code" ? "claude" : client)))
194
+ .filter((s) => s.session.repoId === project.repoId);
195
+ return {
196
+ workspace: project.workspace,
197
+ captureObserved: observations.some((s) => s.lastCaptureAt !== null),
198
+ startupObserved: observations.length > 0,
199
+ sessions: observations,
200
+ };
201
+ });
202
+ console.log(JSON.stringify({
203
+ capture,
204
+ status: problems.length ? "attention_required" : "configured",
205
+ runtime: state?.current.version,
206
+ problems,
207
+ note: "Configuration check only; agent login/trust and live handoff are not verified.",
208
+ }, null, 2));
135
209
  if (problems.length)
136
210
  process.exitCode = 1;
137
211
  return;
138
212
  }
139
- if (!['setup', 'update', 'rollback', 'uninstall'].includes(action))
140
- throw new Error('Unknown command: ' + action);
213
+ if (!["setup", "update", "rollback", "uninstall"].includes(action))
214
+ throw new Error("Unknown command: " + action);
141
215
  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());
216
+ if (action === "setup") {
217
+ const directory = values.workspace ?? (await ask("Project folder: "));
218
+ const selected = values.client ??
219
+ (await ask("Agents (comma separated: " + clients.join(", ") + "): "))
220
+ .split(",")
221
+ .map((v) => v.trim());
145
222
  const { workspace, repoId } = resolveRepository(resolve(directory));
146
- project = { workspace, repoId, clients: selected, database: join(paths.data, 'events.sqlite') };
223
+ project = {
224
+ workspace,
225
+ repoId,
226
+ clients: selected,
227
+ database: join(paths.data, "events.sqlite"),
228
+ ...(values["capture-new-sessions"] ? { captureNewSessions: true } : {}),
229
+ };
147
230
  // Validate and show changes before installing dependencies or writing settings.
231
+ const previousProject = readInstallation(home)?.projects.find((p) => p.workspace === workspace);
232
+ if (previousProject)
233
+ project.repoId = previousProject.repoId;
148
234
  const plan = planConnection({ ...project, appRoot });
149
235
  preview(plan);
150
236
  if (values.preview) {
151
- console.log('Preview only. No runtime or configuration installed.');
237
+ console.log("Preview only. No runtime or configuration installed.");
152
238
  return;
153
239
  }
154
240
  }
155
241
  else {
156
242
  const state = readInstallation(home);
157
243
  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;
244
+ throw new Error("No installation found. Run setup first.");
245
+ if (action === "uninstall") {
246
+ const target = values.workspace
247
+ ? resolveRepository(resolve(values.workspace)).workspace
248
+ : null;
161
249
  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');
250
+ throw new Error("Pass --workspace to uninstall one project; memory data is always retained");
251
+ if (!state.projects.some((p) => p.workspace === target))
252
+ throw new Error("Project is not managed by this installation");
165
253
  preview(planUninstall(target));
166
254
  }
167
255
  else
168
- console.log(action + ' runtime for ' + state.projects.length + ' project(s); user memory is retained.');
256
+ console.log(action +
257
+ " runtime for " +
258
+ state.projects.length +
259
+ " project(s); user memory is retained.");
169
260
  if (values.preview)
170
261
  return;
171
262
  }
172
- if (!await confirm('Apply ' + action + '?', values.yes)) {
173
- console.log('Cancelled. No changes applied.');
263
+ if (!(await confirm("Apply " + action + "?", values.yes))) {
264
+ console.log("Cancelled. No changes applied.");
174
265
  return;
175
266
  }
176
267
  await withInstallLock(home, async () => {
177
268
  const state = readInstallation(home);
178
- if (action === 'uninstall') {
269
+ if (action === "uninstall") {
179
270
  const target = resolveRepository(resolve(values.workspace)).workspace;
180
271
  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.');
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.");
183
277
  return;
184
278
  }
185
279
  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])];
280
+ const existing = state?.projects.find((p) => p.workspace === project.workspace);
281
+ if (existing) {
282
+ project.repoId = existing.repoId;
283
+ project.clients = [
284
+ ...new Set([...existing.clients, ...project.clients]),
285
+ ];
286
+ if (existing.captureNewSessions)
287
+ project.captureNewSessions = true;
288
+ }
189
289
  }
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));
290
+ const projects = project
291
+ ? [
292
+ ...(state?.projects ?? []).filter((p) => p.workspace !== project.workspace),
293
+ project,
294
+ ]
295
+ : 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"
299
+ ? state?.previous
300
+ : installRuntime(home, values.package ??
301
+ packageName +
302
+ "@" +
303
+ (action === "update"
304
+ ? version.includes("-")
305
+ ? "next"
306
+ : "latest"
307
+ : version));
194
308
  if (!runtime)
195
- throw new Error('No previous runtime available');
309
+ throw new Error("No previous runtime available");
310
+ assertRuntimeCompatibility(runtime, projects);
196
311
  const plans = plansFor(runtime, projects);
197
312
  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.');
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.");
202
317
  });
203
318
  }
204
319
  try {