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

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 (39) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +64 -2
  3. package/dist/apps/server/src/conversation-server.js +203 -0
  4. package/dist/apps/server/src/http-gateway.js +118 -0
  5. package/dist/apps/server/src/http-main.js +46 -0
  6. package/dist/apps/server/src/main.js +15 -0
  7. package/dist/apps/server/src/server.js +253 -0
  8. package/dist/apps/server/src/web-auth.js +30 -0
  9. package/dist/apps/server/src/web-picker.js +119 -0
  10. package/dist/memory-schema.json +1 -0
  11. package/dist/packages/adapters/src/cli.js +259 -0
  12. package/dist/packages/adapters/src/command.js +227 -0
  13. package/dist/packages/adapters/src/discovery.js +128 -0
  14. package/dist/packages/adapters/src/handoff.js +146 -0
  15. package/dist/packages/adapters/src/hooks.js +159 -0
  16. package/dist/packages/adapters/src/launch.js +21 -0
  17. package/dist/packages/adapters/src/picker.js +40 -0
  18. package/dist/packages/adapters/src/providers/jsonl.js +105 -0
  19. package/dist/packages/adapters/src/repository.js +36 -0
  20. package/dist/packages/adapters/src/scope.js +32 -0
  21. package/dist/packages/adapters/src/status.js +81 -0
  22. package/dist/packages/adapters/src/transcript.js +193 -0
  23. package/dist/packages/contracts/src/capabilities.js +1 -0
  24. package/dist/packages/contracts/src/conversations.js +30 -0
  25. package/dist/packages/contracts/src/events.js +27 -0
  26. package/dist/packages/installer/src/cli.js +325 -0
  27. package/dist/packages/installer/src/connections.js +352 -0
  28. package/dist/packages/installer/src/runtime.js +133 -0
  29. package/dist/packages/memory/src/checkpoints.js +68 -0
  30. package/dist/packages/memory/src/context.js +91 -0
  31. package/dist/packages/memory/src/conversations.js +148 -0
  32. package/dist/packages/memory/src/migrations.js +55 -0
  33. package/dist/packages/memory/src/store.js +269 -0
  34. package/dist/scripts/connector-setup.js +77 -0
  35. package/dist/skills/continue-chat/SKILL.md +13 -0
  36. package/docs/clients/connector-setup.md +63 -0
  37. package/docs/clients/local-agent-memory.md +50 -0
  38. package/docs/clients/npm-installation.md +67 -0
  39. package/package.json +50 -4
@@ -0,0 +1,269 @@
1
+ import { getConversationContext } from "./context.js";
2
+ import { saveCheckpoint, latestCheckpoint } from "./checkpoints.js";
3
+ import { DatabaseSync } from "node:sqlite";
4
+ import { eventSchema, scopeSchema, searchSchema, } from "../../contracts/src/events.js";
5
+ import { assertSupportedSchema, migrate } from "./migrations.js";
6
+ import { ConversationStore } from "./conversations.js";
7
+ export class MemoryStore {
8
+ db;
9
+ conversations;
10
+ constructor(path, options = {}) {
11
+ this.db = new DatabaseSync(path);
12
+ try {
13
+ assertSupportedSchema(this.db);
14
+ this.db.exec(`
15
+ PRAGMA journal_mode=WAL;
16
+ PRAGMA busy_timeout=5000;
17
+ CREATE TABLE IF NOT EXISTS events (
18
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
19
+ repo TEXT NOT NULL, id TEXT NOT NULL, feature TEXT NOT NULL,
20
+ branch TEXT, payload TEXT NOT NULL, received TEXT NOT NULL,
21
+ UNIQUE(repo, id)
22
+ );
23
+ CREATE INDEX IF NOT EXISTS events_scope ON events(repo, feature, seq);
24
+ CREATE TABLE IF NOT EXISTS chat_sessions (
25
+ repo TEXT NOT NULL, session TEXT NOT NULL, owner TEXT NOT NULL,
26
+ PRIMARY KEY(repo, session)
27
+ );
28
+ CREATE TABLE IF NOT EXISTS session_selections (
29
+ repo TEXT NOT NULL, session TEXT NOT NULL, feature TEXT NOT NULL, title TEXT NOT NULL,
30
+ PRIMARY KEY(repo, session)
31
+ );
32
+ `);
33
+ if (options.conversationMode) {
34
+ migrate(this.db);
35
+ this.conversations = new ConversationStore(this.db);
36
+ }
37
+ }
38
+ catch (error) {
39
+ this.db.close();
40
+ throw error;
41
+ }
42
+ }
43
+ conversationStore() {
44
+ if (!this.conversations)
45
+ throw new Error("Enable conversation mode");
46
+ return this.conversations;
47
+ }
48
+ ensureSession(key, location) {
49
+ return this.conversationStore().ensureSession(key, location);
50
+ }
51
+ listConversations(repoId) {
52
+ return this.conversationStore().list(repoId);
53
+ }
54
+ appendEvidence(key, input) {
55
+ const conversation = this.conversationStore().session(key), event = eventSchema.parse(input);
56
+ if (event.repoId !== key.repoId ||
57
+ event.featureId !== conversation.conversationId)
58
+ throw new Error("Evidence belongs to another conversation");
59
+ this.db.exec("BEGIN IMMEDIATE");
60
+ try {
61
+ const prior = this.db
62
+ .prepare("SELECT conversation FROM conversation_evidence WHERE repo=? AND event_id=?")
63
+ .get(key.repoId, event.eventId);
64
+ if (prior && prior.conversation !== conversation.conversationId)
65
+ throw new Error("Evidence belongs to another conversation");
66
+ const existing = this.evidence(key.repoId, event.eventId);
67
+ const withoutProvenance = (value) => JSON.stringify({
68
+ ...value,
69
+ branch: undefined,
70
+ commit: undefined,
71
+ receivedAt: undefined,
72
+ });
73
+ const saved = existing && withoutProvenance(existing) === withoutProvenance(event)
74
+ ? existing
75
+ : this.save(event);
76
+ this.db
77
+ .prepare("INSERT OR IGNORE INTO conversation_evidence VALUES(?,?,?)")
78
+ .run(key.repoId, event.eventId, conversation.conversationId);
79
+ this.db.exec("COMMIT");
80
+ return saved;
81
+ }
82
+ catch (error) {
83
+ this.db.exec("ROLLBACK");
84
+ throw error;
85
+ }
86
+ }
87
+ getConversationContext(key, options) {
88
+ return getConversationContext(this, key, options);
89
+ }
90
+ conversationLocation(repoId, conversationId) {
91
+ this.conversationStore().get(repoId, conversationId);
92
+ const row = this.db
93
+ .prepare("SELECT workspace,branch,commit_id FROM native_sessions WHERE repo=? AND conversation=? LIMIT 1")
94
+ .get(repoId, conversationId);
95
+ return row
96
+ ? {
97
+ workspace: String(row.workspace),
98
+ branch: row.branch ? String(row.branch) : undefined,
99
+ commit: row.commit_id ? String(row.commit_id) : undefined,
100
+ }
101
+ : {};
102
+ }
103
+ saveCheckpoint(key, entries) {
104
+ return saveCheckpoint(this.db, this, key, entries);
105
+ }
106
+ latestCheckpoint(repoId, conversationId, throughSeq, checkpointSeq) {
107
+ this.conversationStore();
108
+ return latestCheckpoint(this.db, repoId, conversationId, throughSeq, checkpointSeq);
109
+ }
110
+ issueSessionToken(key) {
111
+ return this.conversationStore().issueSessionToken(key);
112
+ }
113
+ assertSessionToken(key, token) {
114
+ this.conversationStore().assertSessionToken(key, token);
115
+ }
116
+ sessionConversation(key) {
117
+ return this.conversationStore().session(key);
118
+ }
119
+ sessionLocation(key) {
120
+ return this.conversationStore().location(key);
121
+ }
122
+ linkSource(key, sourceConversationId) {
123
+ return this.conversationStore().linkSource(key, sourceConversationId);
124
+ }
125
+ selectedSource(key) {
126
+ return this.conversationStore().selectedSource(key);
127
+ }
128
+ conversationRows(key) {
129
+ const own = this.sessionConversation(key), source = this.selectedSource(key);
130
+ return this.db
131
+ .prepare(`SELECT e.seq,e.payload,e.received,m.conversation FROM events e JOIN conversation_evidence m ON e.repo=m.repo AND e.id=m.event_id WHERE e.repo=? AND (m.conversation=? OR (m.conversation=? AND e.seq<=?)) ORDER BY e.seq DESC`)
132
+ .all(key.repoId, own.conversationId, source?.sourceConversationId ?? "", source?.throughSeq ?? 0);
133
+ }
134
+ conversationEvidence(key) {
135
+ return this.conversationRows(key).map((row) => ({
136
+ ...JSON.parse(String(row.payload)),
137
+ receivedAt: String(row.received),
138
+ }));
139
+ }
140
+ importLegacyEvidence(key, featureId) {
141
+ const own = this.sessionConversation(key);
142
+ this.db.exec("BEGIN IMMEDIATE");
143
+ try {
144
+ const conflicts = this.db
145
+ .prepare("SELECT 1 FROM events e JOIN conversation_evidence m ON m.repo=e.repo AND m.event_id=e.id WHERE e.repo=? AND e.feature=? AND m.conversation<>? AND json_extract(e.payload,'$.sessionId')=? AND json_extract(e.payload,'$.source') LIKE ? LIMIT 1")
146
+ .get(key.repoId, featureId, own.conversationId, key.nativeSessionId, key.client + ":%");
147
+ if (conflicts)
148
+ throw new Error("Imported evidence belongs to another conversation");
149
+ this.db
150
+ .prepare("INSERT OR IGNORE INTO conversation_evidence SELECT repo,id,? FROM events WHERE repo=? AND feature=? AND json_extract(payload,'$.sessionId')=? AND json_extract(payload,'$.source') LIKE ?")
151
+ .run(own.conversationId, key.repoId, featureId, key.nativeSessionId, key.client + ":%");
152
+ this.db.exec("COMMIT");
153
+ }
154
+ catch (error) {
155
+ this.db.exec("ROLLBACK");
156
+ throw error;
157
+ }
158
+ }
159
+ save(input) {
160
+ const event = eventSchema.parse(input);
161
+ const payload = JSON.stringify(event);
162
+ const received = new Date().toISOString();
163
+ this.db
164
+ .prepare("INSERT INTO events(repo,id,feature,branch,payload,received) VALUES(?,?,?,?,?,?) ON CONFLICT(repo,id) DO NOTHING")
165
+ .run(event.repoId, event.eventId, event.featureId, event.branch ?? null, payload, received);
166
+ const row = this.db
167
+ .prepare("SELECT payload,received FROM events WHERE repo=? AND id=?")
168
+ .get(event.repoId, event.eventId);
169
+ if (row.payload !== payload)
170
+ throw new Error("Event ID conflict");
171
+ return { ...event, receivedAt: String(row.received) };
172
+ }
173
+ context(input) {
174
+ const scope = scopeSchema.parse(input);
175
+ const where = "repo=? AND feature=?" + (scope.branch ? " AND branch=?" : "");
176
+ const params = scope.branch
177
+ ? [scope.repoId, scope.featureId, scope.branch]
178
+ : [scope.repoId, scope.featureId];
179
+ const count = this.db
180
+ .prepare("SELECT COUNT(*) AS total FROM events WHERE " + where)
181
+ .get(...params);
182
+ const rows = this.db
183
+ .prepare("SELECT payload,received FROM events WHERE " +
184
+ where +
185
+ " ORDER BY seq DESC LIMIT 1000")
186
+ .all(...params);
187
+ const events = [];
188
+ let used = 2;
189
+ for (const row of rows) {
190
+ const event = {
191
+ ...JSON.parse(String(row.payload)),
192
+ receivedAt: String(row.received),
193
+ };
194
+ const size = JSON.stringify(event).length + (events.length ? 1 : 0);
195
+ if (used + size > scope.maxChars)
196
+ break;
197
+ used += size;
198
+ events.push(event);
199
+ }
200
+ return {
201
+ events,
202
+ total: Number(count.total),
203
+ truncated: events.length < Number(count.total),
204
+ order: "newest_first",
205
+ contentTrust: "untrusted_reference",
206
+ };
207
+ }
208
+ evidence(repoId, eventId) {
209
+ const row = this.db
210
+ .prepare("SELECT payload,received FROM events WHERE repo=? AND id=?")
211
+ .get(repoId, eventId);
212
+ return row
213
+ ? { ...JSON.parse(String(row.payload)), receivedAt: String(row.received) }
214
+ : null;
215
+ }
216
+ search(input) {
217
+ const scope = searchSchema.parse(input);
218
+ const rows = this.db
219
+ .prepare("SELECT seq,payload,received FROM events WHERE repo=? AND feature=? AND seq < ? " +
220
+ "AND instr(lower(json_extract(payload,'$.content')),lower(?)) > 0 ORDER BY seq DESC LIMIT ?")
221
+ .all(scope.repoId, scope.featureId, scope.before ?? Number.MAX_SAFE_INTEGER, scope.query, scope.limit + 1);
222
+ const selected = rows.slice(0, scope.limit);
223
+ const matches = selected.map((row) => {
224
+ const event = JSON.parse(String(row.payload));
225
+ const { content, ...metadata } = event;
226
+ const match = content.toLowerCase().indexOf(scope.query.toLowerCase());
227
+ const start = Math.max(0, match - 100);
228
+ return {
229
+ ...metadata,
230
+ receivedAt: String(row.received),
231
+ excerpt: content.slice(start, start + 1000),
232
+ };
233
+ });
234
+ return {
235
+ matches,
236
+ nextCursor: rows.length > scope.limit
237
+ ? Number(selected[selected.length - 1].seq)
238
+ : null,
239
+ };
240
+ }
241
+ createChatSession(repoId, sessionId, owner) {
242
+ this.db
243
+ .prepare("INSERT INTO chat_sessions VALUES(?,?,?)")
244
+ .run(repoId, sessionId, owner);
245
+ }
246
+ ownsChatSession(repoId, sessionId, owner) {
247
+ return !!this.db
248
+ .prepare("SELECT 1 FROM chat_sessions WHERE repo=? AND session=? AND owner=?")
249
+ .get(repoId, sessionId, owner);
250
+ }
251
+ selectSession(repoId, sessionId, featureId, title) {
252
+ if (!repoId || !sessionId || !featureId)
253
+ throw new Error("Repository, session and selected feature are required");
254
+ this.db
255
+ .prepare("INSERT INTO session_selections VALUES(?,?,?,?) ON CONFLICT(repo,session) DO UPDATE SET feature=excluded.feature,title=excluded.title")
256
+ .run(repoId, sessionId, featureId, title);
257
+ }
258
+ sessionSelection(repoId, sessionId) {
259
+ const row = this.db
260
+ .prepare("SELECT feature,title FROM session_selections WHERE repo=? AND session=?")
261
+ .get(repoId, sessionId);
262
+ return row
263
+ ? { featureId: String(row.feature), title: String(row.title) }
264
+ : null;
265
+ }
266
+ close() {
267
+ this.db.close();
268
+ }
269
+ }
@@ -0,0 +1,77 @@
1
+ import { parseArgs } from "node:util";
2
+ import { resolve, join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { mkdirSync, writeFileSync } from "node:fs";
5
+ import { planConnection, applyConnectionPlan } from "../packages/installer/src/connections.js";
6
+ import { createHash } from "node:crypto";
7
+ import { resolveRepository } from "../packages/adapters/src/repository.js";
8
+ function secureUrl(value, name) {
9
+ const url = new URL(value);
10
+ if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash)
11
+ throw new Error(name + " must be a clean HTTPS URL");
12
+ return url;
13
+ }
14
+ try {
15
+ const { values } = parseArgs({ options: {
16
+ client: { type: "string" }, workspace: { type: "string", default: process.cwd() },
17
+ "public-url": { type: "string" }, issuer: { type: "string" },
18
+ subject: { type: "string", multiple: true }, preview: { type: "boolean", default: false },
19
+ } });
20
+ const client = values.client;
21
+ if (!client || !["claude-code", "claude-desktop", "chatgpt", "claude-web"].includes(client)) {
22
+ throw new Error("Choose --client claude-code, claude-desktop, chatgpt or claude-web");
23
+ }
24
+ const app = resolve(fileURLToPath(new URL("../", import.meta.url)));
25
+ const { workspace, repoId } = resolveRepository(resolve(values.workspace));
26
+ if (client === "claude-code" || client === "claude-desktop") {
27
+ const plan = planConnection({ workspace, appRoot: app, database: process.env.MEMORY_DB ?? join(app, ".memory/events.sqlite"), repoId, clients: [client] });
28
+ for (const path of Object.keys(plan.changes))
29
+ console.log("merge " + join(workspace, path));
30
+ if (!values.preview)
31
+ applyConnectionPlan(plan);
32
+ console.log(client === "claude-code"
33
+ ? "Start a fresh Claude Code session in this workspace, approve its MCP connection if prompted, and use /continue-chat."
34
+ : "Merge the generated .memory/connectors/claude-desktop.json entry into Claude Desktop's local MCP configuration, restart Claude Desktop, then call start_session and choose_conversation.");
35
+ }
36
+ else {
37
+ const publicUrl = values["public-url"] ? secureUrl(values["public-url"], "Public URL") : null;
38
+ if (publicUrl) {
39
+ if (!["/", "/mcp"].includes(publicUrl.pathname))
40
+ throw new Error("Use a dedicated HTTPS host or its /mcp endpoint");
41
+ publicUrl.pathname = "/mcp";
42
+ }
43
+ if (values.issuer)
44
+ secureUrl(values.issuer, "OAuth issuer");
45
+ const missing = [
46
+ ...(!publicUrl ? ["public HTTPS URL"] : []),
47
+ ...(!values.issuer ? ["OAuth issuer"] : []),
48
+ ...(!values.subject?.length ? ["allowed OAuth subject(s)"] : []),
49
+ ];
50
+ const profile = {
51
+ client, status: missing.length ? "configuration_required" : "ready_to_serve", missing,
52
+ server: {
53
+ repoId, workspace, database: process.env.MEMORY_DB ?? join(app, ".memory/events.sqlite"),
54
+ publicUrl: publicUrl?.href ?? null, issuer: values.issuer ?? null, allowedSubjects: values.subject ?? [],
55
+ },
56
+ connection: {
57
+ name: "Shared Memory — " + workspace.split("/").at(-1),
58
+ mcpUrl: publicUrl?.href ?? null, authentication: "OAuth 2.1",
59
+ setup: client === "chatgpt" ? "Add a custom MCP connector in ChatGPT's developer/connector settings."
60
+ : "Add a custom remote connector in Claude's connector settings.",
61
+ },
62
+ capture: "Tool-based saves. Ordinary chat clients do not expose coding-session capture hooks.",
63
+ };
64
+ const path = join(app, ".memory/connectors", client + "-" + createHash("sha256").update(repoId).digest("hex").slice(0, 8) + ".json");
65
+ if (!values.preview) {
66
+ mkdirSync(join(app, ".memory/connectors"), { recursive: true, mode: 0o700 });
67
+ writeFileSync(path, JSON.stringify(profile, null, 2) + "\n", { mode: 0o600 });
68
+ }
69
+ console.log(JSON.stringify({ path, ...profile }, null, 2));
70
+ if (!missing.length)
71
+ console.log("Start the authenticated gateway with: npm run serve:http -- --profile " + JSON.stringify(path));
72
+ }
73
+ }
74
+ catch (error) {
75
+ console.error(error instanceof Error ? error.message : String(error));
76
+ process.exitCode = 1;
77
+ }
@@ -0,0 +1,13 @@
1
+ ---
2
+ name: continue-chat
3
+ description: Open the shared-memory chat picker and load the conversation the user selects.
4
+ ---
5
+
6
+ <!-- shared-agent-memory -->
7
+ # Continue a chat
8
+
9
+ Use the native session ID and repository from the memory startup hook. In local conversation mode, also pass the sessionToken capability from that hook to every memory tool. Never invent or reuse another session capability. 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.
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.
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.
@@ -0,0 +1,63 @@
1
+ # Connector setup
2
+
3
+ Run commands from the memory product checkout with Node 24+ and dependencies installed (`npm ci`). Replace `/path/to/repository` with the project you want to continue. These commands configure that repository, not the memory product itself.
4
+
5
+ ## Claude Code
6
+
7
+ ```bash
8
+ npm run connect -- --client claude-code --workspace /path/to/repository
9
+ ```
10
+
11
+ This merges project MCP configuration, SessionStart/Stop hooks and the continue-chat skill while preserving unrelated settings. Start a fresh Claude Code session in the target project, log in and approve the project MCP connection. Invoke `/continue-chat`, select a conversation, and review the restored checkpoint before asking for implementation. Capture begins after selection. Hook execution depends on the client's trust settings.
12
+
13
+ ## Claude Desktop local MCP
14
+
15
+ ```bash
16
+ npm run connect -- --client claude-desktop --workspace /path/to/repository
17
+ ```
18
+
19
+ The installer writes a configuration fragment to the project's `.memory/connectors/claude-desktop.json`. Merge its `mcpServers` entry into Claude Desktop's local MCP configuration on the same machine, then restart Desktop. Absolute executable, application and database paths must exist on that machine. This command prepares the fragment; it does not modify or verify the Desktop application.
20
+
21
+ The server instructs the agent to call `start_session`, then `choose_conversation`. Choose explicitly in the form when supported. The local fallback is the terminal handoff picker. Local Desktop chat uses tool-based saves; coding hooks do not capture ordinary Desktop chats.
22
+
23
+ ## ChatGPT and Claude web
24
+
25
+ Generate a private setup profile:
26
+
27
+ ```bash
28
+ npm run connect -- --client chatgpt --workspace /path/to/repository
29
+ npm run connect -- --client claude-web --workspace /path/to/repository
30
+ ```
31
+
32
+ Without deployment values, these profiles report `configuration_required`. They do not establish a live connection. Complete a profile by rerunning with your actual values:
33
+
34
+ ```bash
35
+ npm run connect -- --client chatgpt --workspace /path/to/repository \
36
+ --public-url https://memory.example.com/mcp \
37
+ --issuer https://identity.example.com \
38
+ --subject YOUR_OAUTH_USER_SUBJECT
39
+ ```
40
+
41
+ Repeat `--subject` to allow teammates. Use `--preview` to inspect setup without writing files. Profiles are stored under the product's ignored `.memory/connectors/` directory. The generated output supplies the exact command to start the server:
42
+
43
+ ```bash
44
+ npm run serve:http -- --profile /absolute/path/to/generated-profile.json
45
+ ```
46
+
47
+ The gateway listens on `127.0.0.1:8787`. Forward the entire dedicated HTTPS hostname through a reverse proxy or tunnel, including `/mcp`, discovery and picker routes. This release uses local SQLite: keep the database on durable storage beside the running service. It is not a stateless Cloud Run deployment recipe.
48
+
49
+ Configure an external OAuth/OIDC provider with authorization-code flow and PKCE S256. Its discovery document must identify the exact configured issuer and an HTTPS JWKS endpoint. Access tokens must be signed JWTs (RS256 or ES256), with an expiry, an allowlisted subject, audience equal to the public `/mcp` URL, and `memory:read` scope. Add `memory:write` for checkpoint saves. The provider must support the target client's registration or preconfigured client credentials and redirect URLs; this service does not implement an authorization server or dynamic client registration itself. Opaque access tokens are unsupported.
50
+
51
+ Add the public MCP URL as a custom remote connector in the chosen client and complete OAuth there. Provider setup and a live client login are required in addition to running this gateway. One gateway profile binds one repository; allowed users share selected feature evidence in that repository.
52
+
53
+ ## Selecting and continuing
54
+
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
+
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.
58
+
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
+
61
+ ## Verification status
62
+
63
+ The automated suite exercises real MCP HTTP connections, OAuth validation, explicit selection, single-use picker links, independent chat sessions, user ownership and write scopes. Local Claude Code configuration is installed and recognized by the CLI, pending login and MCP approval. Desktop configuration is generated but the application is untested. ChatGPT and Claude web are not live-connected: public HTTPS and OAuth configuration are still required. Browser picker endpoints are tested; visual rendering has not been independently verified.
@@ -0,0 +1,50 @@
1
+ # Local conversation memory preview
2
+
3
+ This opt-in mode separates each coding session's evidence from the source conversation it continues. It remains local to one machine and uses the existing SQLite database, hook delivery queue and MCP server. Legacy connections keep their existing behavior.
4
+
5
+ ## Enable for a connected project
6
+
7
+ Build and pack this checkout, then use that tarball with the installer:
8
+
9
+ ```bash
10
+ npm run check
11
+ npm test
12
+ npm run build
13
+ npm pack
14
+ ```
15
+
16
+ Run the packaged CLI with `setup --workspace /absolute/path/to/project --client codex --client claude-code --capture-new-sessions --package /absolute/path/to/package.tgz --preview`. Review the output, then rerun without `--preview` to apply. `--capture-new-sessions` opts the connected project into capture of supported user/assistant text in fresh sessions; it is retained across subsequent setup/update operations. Select only clients you use. Restart them and approve MCP and hook trust using their normal interfaces.
17
+
18
+ No existing installation is upgraded by building this source. A connection upgrade creates a consistent, private SQLite backup beside an existing database before migrating its schema. New session identity is keyed by repository, coding client and native session ID. Branch and commit are provenance rather than identity.
19
+
20
+ ## Continue work
21
+
22
+ Use `/continue-chat` in a fresh native agent session. The startup hook provides its native session ID and a session capability. Every conversation-mode tool requires both; another known session ID alone grants no access. Capabilities rotate on startup and are stored only as hashes. Pick the source explicitly. The destination keeps its own history; its direct source is limited to the evidence, checkpoint revision and source location available when selected. Canceling preserves the previous link if one exists. Re-selecting refreshes the source cutoff. Ancestors are not recursively recalled.
23
+
24
+ The picker includes stored Knitt conversations and supported local Antigravity, Codex and Claude Code JSONL histories. External discovery reads bounded metadata from known client directories and imports text only after selection. Unsupported metadata and missing directories produce diagnostics. Titles for Codex/Claude discovery currently use the client and native session ID. Clients' local formats can change; fixture support does not establish live support for every release.
25
+
26
+ When MCP form selection is unavailable, use `knitt continue --workspace /absolute/path/to/project --session NATIVE_SESSION_ID --client codex` interactively, with the same `--home` as installation if customized. Use `claude` for Claude Code's native adapter name. The terminal picker requires a session already registered by its startup hook and uses the installation database. It refuses projects that have not opted in and validates session/schema readiness before opening the database for writes. It does not reconfigure the project or launch an agent.
27
+
28
+ ## Checkpoints and evidence
29
+
30
+ Ask the agent to use `save_checkpoint` for goals, decisions, rejected attempts, progress, test claims, blockers and next steps. Every entry requires real evidence IDs accessible to that session. Hooks capture on supported lifecycle invocations, so evidence may not exist until capture runs; use `save_memory` to explicitly record a checkpoint's supporting statement when necessary. Never invent citations.
31
+
32
+ Checkpoints are derived claims, not proof that tests ran. This preview accepts `reported` status and rejects unsupported `verified` claims. The server validates citations and scope but cannot establish semantic truth. Explicit supersession preserves old revisions and original evidence.
33
+
34
+ Recall prioritizes cited checkpoint entries and recent text, with attribution, branch/commit metadata, staleness and omission indicators. The serialized result is bounded to 12000 characters by default (256–24000 configurable); this is not a token count. Very small budgets omit metadata and say so. Search and evidence tools can retrieve older details within the same destination/direct-source scope. Switching sources excludes checkpoint entries whose citations no longer belong to the permitted scope.
35
+
36
+ ## Observe capture
37
+
38
+ `knitt doctor --home /installation/home` reports whether any capture status has been observed, last successful capture/delivery timestamps, per-session queued counts, observed-but-not-yet-captured sessions, partial or unsupported captures, and fixed error codes. It does not log message text. No observation means capture is unknown, not healthy. A missed stop hook cannot be diagnosed at the instant it fails to run; the next invocation or explicit inspection is needed. Queue retries remain invocation-driven, without a background daemon.
39
+
40
+ ## Compatibility and recovery
41
+
42
+ Keep the backup together with its schema version. To restore, first stop all connected servers and hooks; retain the current database and its WAL/SHM files for recovery, then restore a consistent backup through an explicit recovery operation. Restoring a backup discards later changes from the active database; never do this automatically as part of runtime rollback.
43
+
44
+ The updated installer refuses a target runtime whose declared supported schema is older than the database. Missing compatibility metadata means legacy schema zero. Old already-published binaries cannot be retroactively changed: invoking those directly bypasses the new installer's guard. Keep using the compatible installed CLI for update/rollback.
45
+
46
+ The conversation-mode server is for local coding clients. Ordinary-chat/HTTP connectors retain their legacy behavior; this change does not make remote clients conversation-aware.
47
+
48
+ ## Verification
49
+
50
+ Automated tests cover schema preservation/recovery, independent capture, deduplication, explicit selection/cancellation, source cutoffs, checkpoint citations, bounded Unicode recall, capture health and incompatible runtime refusal. Installed-package smoke tests exercise legacy and conversation-mode hooks/MCP, checkpoint handoff, source-history isolation, doctor, update, rollback, failed installation preservation and uninstall. See the implementation progress record for live-client evidence and remaining limits.
@@ -0,0 +1,67 @@
1
+ # npm installation and runtime lifecycle
2
+
3
+ ## Install the npm preview
4
+
5
+ Run the published CLI:
6
+
7
+ ```bash
8
+ npx @tinchu0/knitt@latest setup \
9
+ --workspace /path/to/project --client codex --client claude-code
10
+ ```
11
+
12
+ Add `--capture-new-sessions` to opt into independent local conversation histories and checkpoint-first handoffs. Version `0.1.0-beta.2` remains a preview. Both `latest` and `next` track the current preview release.
13
+
14
+ To test a source checkout before publication, run `npm ci`, `npm run check`, `npm run build` and `npm pack`, then install its exact artifact:
15
+
16
+ ```bash
17
+ npx --yes --package ./tinchu0-knitt-0.1.0-beta.2.tgz knitt setup \
18
+ --workspace /path/to/project --client codex --client claude-code \
19
+ --package /absolute/path/to/tinchu0-knitt-0.1.0-beta.2.tgz
20
+ ```
21
+
22
+ The outer `--package` selects the CLI; the `--package` after `setup` selects the artifact to install persistently. Without that inner option, setup installs the CLI's exact published version. `update` follows `next` for prerelease CLIs and `latest` for stable CLIs.
23
+
24
+ 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
+
26
+ ## Durable installation
27
+
28
+ The default installation directory is:
29
+
30
+ - Linux: `$XDG_DATA_HOME/shared-agent-memory` or `~/.local/share/shared-agent-memory`.
31
+ - macOS: `~/Library/Application Support/SharedAgentMemory` (platform validation pending).
32
+
33
+ Override with `SHARED_MEMORY_HOME` or `--home /absolute/path`. The directory contains private `data/`, versioned runtime installations and `installation.json`. Node and runtime paths in generated settings are absolute. Upgrading/removing Node itself can invalidate the executable path; rerun setup with the new Node installation.
34
+
35
+ The setup process uses npm to install production dependencies in staging with dependency lifecycle scripts disabled. It verifies the packaged executable before rebinding connectors. The temporary npx cache can then be removed without breaking installed connections. Installation metadata uses an exclusive lock; after a crash, inspect the PID in `install.lock/owner.json` before removing a stale lock.
36
+
37
+ The project-local `.memory/npm-connection.json` records original and generated settings. Keep it until uninstall. Do not commit this private file. Existing Git excludes are extended for local generated settings. Existing Python-installed connections are considered unmanaged by the new CLI: they are not silently adopted or overwritten. Use a fresh project for the release candidate, or restore the legacy connector backups before migrating deliberately.
38
+
39
+ ## Commands
40
+
41
+ Run commands through `npx @tinchu0/knitt@latest` or the tarball CLI above:
42
+
43
+ ```text
44
+ knitt setup --workspace PATH --client codex --preview
45
+ knitt doctor
46
+ knitt update --yes
47
+ knitt rollback --yes
48
+ knitt uninstall --workspace PATH --yes
49
+ knitt serve
50
+ ```
51
+
52
+ Use the same `--home` for every lifecycle command if you customized it. `doctor` checks local installation/configuration, not account login or a live model handoff. Changed settings are reported for review.
53
+
54
+ 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.
55
+
56
+ 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.
57
+
58
+ ## Release gates
59
+
60
+ The package is `@tinchu0/knitt`, published under npm account `tinchu0`, with Apache-2.0 licensing. The LICENSE file ships in the npm archive. Release `0.1.0-beta.2` includes opt-in local conversation memory. Native Windows setup deliberately fails rather than writing POSIX hook commands. Linux tarball checks are the local verification target; macOS/Windows live client behavior remains unverified.
61
+
62
+ ChatGPT, Claude web and teammate machines require a separately reachable authenticated service. Packaging a CLI does not supply hosting, authentication accounts or background synchronization.
63
+
64
+
65
+ ### Optional local conversation mode
66
+
67
+ Add `--capture-new-sessions` to setup to opt a connected project into independent session capture and explicit continuation links. The preference survives subsequent setup/update operations. Existing connections keep their previous semantics until opted in. This mode upgrades the database using consistent SQLite backups; the updated installer blocks incompatible runtime downgrade rather than restoring data automatically. Use `doctor` for content-free capture status. See [setup and recovery](local-agent-memory.md).
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@tinchu0/knitt",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-beta.2",
4
+ "type": "module",
5
+ "engines": {
6
+ "node": ">=24"
7
+ },
8
+ "scripts": {
9
+ "start": "node apps/server/src/main.ts",
10
+ "test": "node --test tests/*.test.ts",
11
+ "check": "tsc --noEmit",
12
+ "memory": "node packages/adapters/src/command.ts",
13
+ "connect": "node scripts/connector-setup.ts",
14
+ "serve:http": "node apps/server/src/http-main.ts",
15
+ "build": "node scripts/build.ts",
16
+ "test:package": "npm run build && node scripts/package-smoke.ts",
17
+ "prepack": "npm run check && npm run build"
18
+ },
19
+ "dependencies": {
20
+ "@modelcontextprotocol/sdk": "^1.32.2",
21
+ "express": "^5.3.0",
22
+ "jose": "^6.2.17",
23
+ "smol-toml": "^1.9.1",
24
+ "zod": "^4.6.7"
25
+ },
26
+ "devDependencies": {
27
+ "@types/express": "^5.0.6",
28
+ "@types/node": "^26.6.6",
29
+ "typescript": "^7.0.2"
30
+ },
31
+ "bin": {
32
+ "knitt": "dist/packages/installer/src/cli.js"
33
+ },
34
+ "files": [
35
+ "dist/",
36
+ "README.md",
37
+ "docs/clients/connector-setup.md",
38
+ "docs/clients/npm-installation.md",
39
+ "LICENSE",
40
+ "docs/clients/local-agent-memory.md"
41
+ ],
42
+ "repository": {
43
+ "type": "git",
44
+ "url": "git+https://github.com/darthnihilus01/knitt.git"
45
+ },
46
+ "description": "Shared conversation memory for coding agents",
47
+ "publishConfig": {
48
+ "access": "public",
49
+ "tag": "latest"
50
+ },
51
+ "license": "Apache-2.0"
52
+ }