context-mule 0.0.0-stage → 1.0.0
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.
- package/LICENSE +21 -0
- package/README.md +104 -2
- package/dist/cli/index.js +4010 -0
- package/dist/public/assets/index-BJ_K99FZ.css +1 -0
- package/dist/public/assets/index-BUIbAVL-.js +165 -0
- package/dist/public/index.html +24 -0
- package/package.json +55 -4
|
@@ -0,0 +1,4010 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// packages/cli/src/commands/handlers.ts
|
|
4
|
+
import { spawnSync as spawnSync2 } from "node:child_process";
|
|
5
|
+
import { existsSync as existsSync7 } from "node:fs";
|
|
6
|
+
import { resolve as resolve3 } from "node:path";
|
|
7
|
+
|
|
8
|
+
// packages/adapters/dist/index.js
|
|
9
|
+
import { existsSync as existsSync3, readdirSync } from "node:fs";
|
|
10
|
+
import { homedir as homedir2 } from "node:os";
|
|
11
|
+
import { join as join5 } from "node:path";
|
|
12
|
+
|
|
13
|
+
// packages/adapters/dist/drivers/jsonl-adapters.js
|
|
14
|
+
import { existsSync } from "node:fs";
|
|
15
|
+
import { basename as basename2, dirname as dirname2, join as join2 } from "node:path";
|
|
16
|
+
|
|
17
|
+
// packages/core/dist/types.js
|
|
18
|
+
var CLI_SOURCES = ["agy", "gemini", "claude", "codex", "cursor", "manual"];
|
|
19
|
+
var DECISION_CATEGORIES = [
|
|
20
|
+
"architecture",
|
|
21
|
+
"constraint",
|
|
22
|
+
"dead_end",
|
|
23
|
+
"tradeoff",
|
|
24
|
+
"next_step"
|
|
25
|
+
];
|
|
26
|
+
var HANDOFF_REASONS = [
|
|
27
|
+
"quota_exhausted",
|
|
28
|
+
"model_specialization",
|
|
29
|
+
"user_switch",
|
|
30
|
+
"manual"
|
|
31
|
+
];
|
|
32
|
+
|
|
33
|
+
// packages/core/dist/security/redactor.js
|
|
34
|
+
import { createHash } from "node:crypto";
|
|
35
|
+
var SECRET_PATTERNS = [
|
|
36
|
+
{
|
|
37
|
+
kind: "PEM_KEY",
|
|
38
|
+
regex: /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----/g
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
kind: "ANTHROPIC_KEY",
|
|
42
|
+
regex: /\bsk-ant-[A-Za-z0-9_-]{12,}\b/g
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
kind: "OPENAI_KEY",
|
|
46
|
+
regex: /\bsk-(?:proj|svcacct|live|test)?-?[A-Za-z0-9_-]{20,}\b/g
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
kind: "GOOGLE_KEY",
|
|
50
|
+
regex: /\bAIza[0-9A-Za-z_-]{20,}\b/g
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
kind: "GITHUB_TOKEN",
|
|
54
|
+
regex: /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}\b|\bgithub_pat_[A-Za-z0-9_]{20,}\b/g
|
|
55
|
+
},
|
|
56
|
+
{
|
|
57
|
+
kind: "AWS_KEY",
|
|
58
|
+
regex: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
kind: "STRIPE_KEY",
|
|
62
|
+
regex: /\b(?:sk_live|rk_live|whsec)_[A-Za-z0-9]{16,}\b/g
|
|
63
|
+
},
|
|
64
|
+
{
|
|
65
|
+
kind: "SLACK_TOKEN",
|
|
66
|
+
regex: /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
kind: "BEARER_TOKEN",
|
|
70
|
+
regex: /(Authorization\s*:\s*Bearer\s+)([A-Za-z0-9._~+/-]{16,}=*)/gi
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
kind: "DB_URL_CREDS",
|
|
74
|
+
regex: /\b((?:postgres|postgresql|mysql|mongodb(?:\+srv)?|redis|amqp):\/\/[^:\s/]+:)([^@\s]{4,})(@)/gi
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
kind: "ENV_SECRET",
|
|
78
|
+
regex: /\b([A-Z0-9_]*(?:API_KEY|SECRET_KEY|ACCESS_TOKEN|AUTH_TOKEN|PRIVATE_KEY|PASSWORD|CLIENT_SECRET)[A-Z0-9_]*\s*[:=]\s*["']?)([A-Za-z0-9+/=._-]{12,})(["']?)/g
|
|
79
|
+
}
|
|
80
|
+
];
|
|
81
|
+
function shortHash(value) {
|
|
82
|
+
return createHash("sha256").update(value).digest("hex").slice(0, 6);
|
|
83
|
+
}
|
|
84
|
+
function shannonEntropy(input) {
|
|
85
|
+
if (input.length === 0)
|
|
86
|
+
return 0;
|
|
87
|
+
const freq = /* @__PURE__ */ new Map();
|
|
88
|
+
for (const ch of input) {
|
|
89
|
+
freq.set(ch, (freq.get(ch) ?? 0) + 1);
|
|
90
|
+
}
|
|
91
|
+
let entropy = 0;
|
|
92
|
+
for (const count of freq.values()) {
|
|
93
|
+
const p = count / input.length;
|
|
94
|
+
entropy -= p * Math.log2(p);
|
|
95
|
+
}
|
|
96
|
+
return entropy;
|
|
97
|
+
}
|
|
98
|
+
function isLikelySafeToken(token) {
|
|
99
|
+
if (token.startsWith("[REDACTED:"))
|
|
100
|
+
return true;
|
|
101
|
+
if (/^[0-9a-f]{32,64}$/i.test(token))
|
|
102
|
+
return true;
|
|
103
|
+
if (token.includes("/") && !token.includes("=") && !token.includes("+"))
|
|
104
|
+
return true;
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
var Redactor = class _Redactor {
|
|
108
|
+
static sanitize(input) {
|
|
109
|
+
if (!input)
|
|
110
|
+
return input;
|
|
111
|
+
let out = input;
|
|
112
|
+
for (const { kind, regex } of SECRET_PATTERNS) {
|
|
113
|
+
regex.lastIndex = 0;
|
|
114
|
+
if (kind === "BEARER_TOKEN") {
|
|
115
|
+
out = out.replace(regex, (_full, prefix, secret) => {
|
|
116
|
+
return `${prefix}[REDACTED:${kind}:${shortHash(secret)}]`;
|
|
117
|
+
});
|
|
118
|
+
} else if (kind === "DB_URL_CREDS") {
|
|
119
|
+
out = out.replace(regex, (_full, prefix, secret, suffix) => {
|
|
120
|
+
return `${prefix}[REDACTED:${kind}:${shortHash(secret)}]${suffix}`;
|
|
121
|
+
});
|
|
122
|
+
} else if (kind === "ENV_SECRET") {
|
|
123
|
+
out = out.replace(regex, (_full, prefix, secret, suffix) => {
|
|
124
|
+
if (secret.startsWith("[REDACTED:"))
|
|
125
|
+
return _full;
|
|
126
|
+
return `${prefix}[REDACTED:${kind}:${shortHash(secret)}]${suffix}`;
|
|
127
|
+
});
|
|
128
|
+
} else {
|
|
129
|
+
out = out.replace(regex, (match) => `[REDACTED:${kind}:${shortHash(match)}]`);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
out = out.replace(/(["'=:\s])([A-Za-z0-9+/_-]{28,}={0,2})(?=["'\s,;]|$)/g, (full, prefix, candidate) => {
|
|
133
|
+
if (isLikelySafeToken(candidate))
|
|
134
|
+
return full;
|
|
135
|
+
if (shannonEntropy(candidate) >= 4.5 && /[A-Z]/.test(candidate) && /[a-z]/.test(candidate) && /\d/.test(candidate)) {
|
|
136
|
+
return `${prefix}[REDACTED:HIGH_ENTROPY:${shortHash(candidate)}]`;
|
|
137
|
+
}
|
|
138
|
+
return full;
|
|
139
|
+
});
|
|
140
|
+
return out;
|
|
141
|
+
}
|
|
142
|
+
static sanitizeRecord(value) {
|
|
143
|
+
if (typeof value === "string") {
|
|
144
|
+
return _Redactor.sanitize(value);
|
|
145
|
+
}
|
|
146
|
+
if (Array.isArray(value)) {
|
|
147
|
+
return value.map((item) => _Redactor.sanitizeRecord(item));
|
|
148
|
+
}
|
|
149
|
+
if (value !== null && typeof value === "object") {
|
|
150
|
+
const result = {};
|
|
151
|
+
for (const [key, val] of Object.entries(value)) {
|
|
152
|
+
result[key] = _Redactor.sanitizeRecord(val);
|
|
153
|
+
}
|
|
154
|
+
return result;
|
|
155
|
+
}
|
|
156
|
+
return value;
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
// packages/core/dist/tokens/estimator.js
|
|
161
|
+
function estimateTokens(text) {
|
|
162
|
+
if (!text)
|
|
163
|
+
return 0;
|
|
164
|
+
const trimmed = text.trim();
|
|
165
|
+
if (!trimmed)
|
|
166
|
+
return 0;
|
|
167
|
+
const symbolMatches = trimmed.match(/[{}\[\]().,:;<>+=\-*/\\|`'"!@#$%^&?~]/g);
|
|
168
|
+
const symbolCount = symbolMatches ? symbolMatches.length : 0;
|
|
169
|
+
const charEstimate = trimmed.length / 3.85;
|
|
170
|
+
const symbolAdjusted = (trimmed.length - symbolCount) / 4.1 + symbolCount * 0.68;
|
|
171
|
+
return Math.max(1, Math.ceil((charEstimate + symbolAdjusted) / 2));
|
|
172
|
+
}
|
|
173
|
+
function truncateToTokenBudget(text, maxTokens) {
|
|
174
|
+
if (maxTokens <= 0 || !text)
|
|
175
|
+
return "";
|
|
176
|
+
if (estimateTokens(text) <= maxTokens)
|
|
177
|
+
return text;
|
|
178
|
+
const approxMaxChars = Math.max(12, Math.floor(maxTokens * 3.5));
|
|
179
|
+
if (text.length <= approxMaxChars)
|
|
180
|
+
return text;
|
|
181
|
+
let slice = text.slice(0, approxMaxChars);
|
|
182
|
+
const lastBreak = Math.max(slice.lastIndexOf("\n"), slice.lastIndexOf(" "));
|
|
183
|
+
if (lastBreak > approxMaxChars * 0.65) {
|
|
184
|
+
slice = slice.slice(0, lastBreak);
|
|
185
|
+
}
|
|
186
|
+
const result = `${slice.trimEnd()}\u2026`;
|
|
187
|
+
while (estimateTokens(result) > maxTokens && slice.length > 16) {
|
|
188
|
+
slice = slice.slice(0, Math.floor(slice.length * 0.85));
|
|
189
|
+
const trimmed = `${slice.trimEnd()}\u2026`;
|
|
190
|
+
if (estimateTokens(trimmed) <= maxTokens) {
|
|
191
|
+
return trimmed;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
return result;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// packages/core/dist/db/client.js
|
|
198
|
+
import { mkdirSync } from "node:fs";
|
|
199
|
+
import { homedir } from "node:os";
|
|
200
|
+
import { dirname, join } from "node:path";
|
|
201
|
+
import { DatabaseSync } from "node:sqlite";
|
|
202
|
+
|
|
203
|
+
// packages/core/dist/db/schema-sql.js
|
|
204
|
+
var INIT_PRAGMAS = `
|
|
205
|
+
PRAGMA journal_mode = WAL;
|
|
206
|
+
PRAGMA synchronous = NORMAL;
|
|
207
|
+
PRAGMA foreign_keys = ON;
|
|
208
|
+
PRAGMA busy_timeout = 5000;
|
|
209
|
+
PRAGMA temp_store = MEMORY;
|
|
210
|
+
PRAGMA cache_size = -16384;
|
|
211
|
+
`;
|
|
212
|
+
var INIT_SQL = `
|
|
213
|
+
CREATE TABLE IF NOT EXISTS projects (
|
|
214
|
+
id TEXT PRIMARY KEY,
|
|
215
|
+
slug TEXT NOT NULL UNIQUE,
|
|
216
|
+
name TEXT NOT NULL,
|
|
217
|
+
repo_root TEXT NOT NULL UNIQUE,
|
|
218
|
+
default_branch TEXT NOT NULL DEFAULT 'main',
|
|
219
|
+
active_branch TEXT NOT NULL DEFAULT 'main',
|
|
220
|
+
active_cli TEXT CHECK (active_cli IN ('agy', 'gemini', 'claude', 'codex', 'cursor', 'manual')),
|
|
221
|
+
created_at TEXT NOT NULL,
|
|
222
|
+
updated_at TEXT NOT NULL
|
|
223
|
+
);
|
|
224
|
+
|
|
225
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
226
|
+
id TEXT PRIMARY KEY,
|
|
227
|
+
project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
|
|
228
|
+
parent_session_id TEXT REFERENCES sessions(id) ON DELETE SET NULL,
|
|
229
|
+
cli_source TEXT NOT NULL CHECK (cli_source IN ('agy', 'gemini', 'claude', 'codex', 'cursor', 'manual')),
|
|
230
|
+
external_session_id TEXT NOT NULL,
|
|
231
|
+
source_log_path TEXT,
|
|
232
|
+
account_label TEXT NOT NULL DEFAULT 'default',
|
|
233
|
+
model_name TEXT NOT NULL,
|
|
234
|
+
git_branch TEXT NOT NULL,
|
|
235
|
+
status TEXT NOT NULL CHECK (status IN ('active', 'idle', 'quota_blocked', 'completed', 'handed_off', 'error')),
|
|
236
|
+
quota_limit_type TEXT CHECK (quota_limit_type IN ('5h_window', 'weekly_cap', 'rpm_429', 'insufficient_quota', 'unknown')),
|
|
237
|
+
quota_reset_at TEXT,
|
|
238
|
+
turn_count INTEGER NOT NULL DEFAULT 0,
|
|
239
|
+
raw_input_tokens INTEGER NOT NULL DEFAULT 0,
|
|
240
|
+
raw_output_tokens INTEGER NOT NULL DEFAULT 0,
|
|
241
|
+
raw_cached_tokens INTEGER NOT NULL DEFAULT 0,
|
|
242
|
+
started_at TEXT NOT NULL,
|
|
243
|
+
ended_at TEXT,
|
|
244
|
+
last_activity_at TEXT NOT NULL,
|
|
245
|
+
UNIQUE(cli_source, external_session_id)
|
|
246
|
+
);
|
|
247
|
+
|
|
248
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_project_time ON sessions(project_id, last_activity_at DESC);
|
|
249
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_status ON sessions(status);
|
|
250
|
+
|
|
251
|
+
CREATE TABLE IF NOT EXISTS context_capsules (
|
|
252
|
+
id TEXT PRIMARY KEY,
|
|
253
|
+
project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
|
|
254
|
+
session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
|
|
255
|
+
version INTEGER NOT NULL,
|
|
256
|
+
trigger_reason TEXT NOT NULL CHECK (trigger_reason IN ('turn_checkpoint', 'quota_blocked', 'manual_edit', 'handoff_prepare', 'mcp_checkpoint')),
|
|
257
|
+
git_branch TEXT NOT NULL,
|
|
258
|
+
git_head_sha TEXT NOT NULL,
|
|
259
|
+
is_dirty_tree INTEGER NOT NULL DEFAULT 0 CHECK (is_dirty_tree IN (0, 1)),
|
|
260
|
+
goal_summary TEXT NOT NULL,
|
|
261
|
+
capsule_json TEXT NOT NULL,
|
|
262
|
+
capsule_markdown TEXT NOT NULL,
|
|
263
|
+
raw_tokens_covered INTEGER NOT NULL,
|
|
264
|
+
capsule_tokens INTEGER NOT NULL CHECK (capsule_tokens <= 2000),
|
|
265
|
+
tokens_saved INTEGER NOT NULL,
|
|
266
|
+
source_chain_json TEXT NOT NULL,
|
|
267
|
+
is_active INTEGER NOT NULL DEFAULT 0 CHECK (is_active IN (0, 1)),
|
|
268
|
+
created_at TEXT NOT NULL,
|
|
269
|
+
UNIQUE(project_id, version)
|
|
270
|
+
);
|
|
271
|
+
|
|
272
|
+
CREATE INDEX IF NOT EXISTS idx_capsules_project_active ON context_capsules(project_id, is_active, version DESC);
|
|
273
|
+
CREATE INDEX IF NOT EXISTS idx_capsules_session ON context_capsules(session_id, version DESC);
|
|
274
|
+
|
|
275
|
+
CREATE TABLE IF NOT EXISTS decision_logs (
|
|
276
|
+
id TEXT PRIMARY KEY,
|
|
277
|
+
project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
|
|
278
|
+
session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
|
|
279
|
+
capsule_id TEXT REFERENCES context_capsules(id) ON DELETE SET NULL,
|
|
280
|
+
cli_source TEXT NOT NULL CHECK (cli_source IN ('agy', 'gemini', 'claude', 'codex', 'cursor', 'manual')),
|
|
281
|
+
category TEXT NOT NULL CHECK (category IN ('architecture', 'constraint', 'dead_end', 'tradeoff', 'next_step')),
|
|
282
|
+
title TEXT NOT NULL,
|
|
283
|
+
body TEXT NOT NULL,
|
|
284
|
+
rationale TEXT NOT NULL DEFAULT '',
|
|
285
|
+
error_fingerprint TEXT,
|
|
286
|
+
retry_count INTEGER NOT NULL DEFAULT 1,
|
|
287
|
+
file_refs_json TEXT NOT NULL DEFAULT '[]',
|
|
288
|
+
is_pinned INTEGER NOT NULL DEFAULT 0 CHECK (is_pinned IN (0, 1)),
|
|
289
|
+
is_superseded INTEGER NOT NULL DEFAULT 0 CHECK (is_superseded IN (0, 1)),
|
|
290
|
+
superseded_by_id TEXT REFERENCES decision_logs(id) ON DELETE SET NULL,
|
|
291
|
+
is_resolved INTEGER NOT NULL DEFAULT 0 CHECK (is_resolved IN (0, 1)),
|
|
292
|
+
created_at TEXT NOT NULL
|
|
293
|
+
);
|
|
294
|
+
|
|
295
|
+
CREATE INDEX IF NOT EXISTS idx_decisions_project_cat ON decision_logs(project_id, category, is_superseded, created_at DESC);
|
|
296
|
+
CREATE INDEX IF NOT EXISTS idx_decisions_fingerprint ON decision_logs(project_id, error_fingerprint);
|
|
297
|
+
|
|
298
|
+
CREATE TABLE IF NOT EXISTS file_snapshots (
|
|
299
|
+
id TEXT PRIMARY KEY,
|
|
300
|
+
project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
|
|
301
|
+
session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
|
|
302
|
+
capsule_id TEXT NOT NULL REFERENCES context_capsules(id) ON DELETE CASCADE,
|
|
303
|
+
file_path TEXT NOT NULL,
|
|
304
|
+
change_status TEXT NOT NULL CHECK (change_status IN ('modified', 'added', 'deleted', 'renamed', 'unmodified')),
|
|
305
|
+
line_ranges_json TEXT NOT NULL DEFAULT '[]',
|
|
306
|
+
lines_added INTEGER NOT NULL DEFAULT 0,
|
|
307
|
+
lines_removed INTEGER NOT NULL DEFAULT 0,
|
|
308
|
+
progress_note TEXT NOT NULL DEFAULT '',
|
|
309
|
+
content_sha256 TEXT NOT NULL,
|
|
310
|
+
unified_diff TEXT NOT NULL,
|
|
311
|
+
captured_at TEXT NOT NULL
|
|
312
|
+
);
|
|
313
|
+
|
|
314
|
+
CREATE INDEX IF NOT EXISTS idx_snapshots_capsule ON file_snapshots(capsule_id, file_path);
|
|
315
|
+
CREATE INDEX IF NOT EXISTS idx_snapshots_project_file ON file_snapshots(project_id, file_path, captured_at DESC);
|
|
316
|
+
|
|
317
|
+
CREATE TABLE IF NOT EXISTS handoff_events (
|
|
318
|
+
id TEXT PRIMARY KEY,
|
|
319
|
+
project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
|
|
320
|
+
capsule_id TEXT NOT NULL REFERENCES context_capsules(id) ON DELETE CASCADE,
|
|
321
|
+
from_session_id TEXT REFERENCES sessions(id) ON DELETE SET NULL,
|
|
322
|
+
to_session_id TEXT REFERENCES sessions(id) ON DELETE SET NULL,
|
|
323
|
+
from_cli TEXT NOT NULL CHECK (from_cli IN ('agy', 'gemini', 'claude', 'codex', 'cursor', 'manual')),
|
|
324
|
+
to_cli TEXT NOT NULL CHECK (to_cli IN ('agy', 'gemini', 'claude', 'codex', 'cursor', 'manual')),
|
|
325
|
+
from_account TEXT NOT NULL,
|
|
326
|
+
to_account TEXT NOT NULL,
|
|
327
|
+
reason TEXT NOT NULL CHECK (reason IN ('quota_exhausted', 'model_specialization', 'user_switch', 'manual')),
|
|
328
|
+
delivery_method TEXT NOT NULL CHECK (delivery_method IN ('cli_prompt', 'claude_md', 'gemini_md', 'agents_md', 'cursor_rule', 'clipboard', 'mcp_pull')),
|
|
329
|
+
injected_tokens INTEGER NOT NULL,
|
|
330
|
+
raw_tokens_avoided INTEGER NOT NULL,
|
|
331
|
+
handoff_command TEXT NOT NULL,
|
|
332
|
+
created_at TEXT NOT NULL
|
|
333
|
+
);
|
|
334
|
+
|
|
335
|
+
CREATE INDEX IF NOT EXISTS idx_handoffs_project_time ON handoff_events(project_id, created_at DESC);
|
|
336
|
+
|
|
337
|
+
CREATE TABLE IF NOT EXISTS adapter_cursors (
|
|
338
|
+
file_path TEXT PRIMARY KEY,
|
|
339
|
+
cli_source TEXT NOT NULL CHECK (cli_source IN ('agy', 'gemini', 'claude', 'codex', 'cursor')),
|
|
340
|
+
inode INTEGER NOT NULL DEFAULT 0,
|
|
341
|
+
byte_offset INTEGER NOT NULL DEFAULT 0,
|
|
342
|
+
last_item_index INTEGER NOT NULL DEFAULT 0,
|
|
343
|
+
content_sha256 TEXT NOT NULL DEFAULT '',
|
|
344
|
+
mtime_ms INTEGER NOT NULL DEFAULT 0,
|
|
345
|
+
updated_at TEXT NOT NULL
|
|
346
|
+
);
|
|
347
|
+
|
|
348
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS memory_fts USING fts5(
|
|
349
|
+
entity_type UNINDEXED,
|
|
350
|
+
entity_id UNINDEXED,
|
|
351
|
+
project_id UNINDEXED,
|
|
352
|
+
session_id UNINDEXED,
|
|
353
|
+
cli_source,
|
|
354
|
+
category,
|
|
355
|
+
title,
|
|
356
|
+
body,
|
|
357
|
+
file_refs,
|
|
358
|
+
tokenize = 'porter unicode61'
|
|
359
|
+
);
|
|
360
|
+
|
|
361
|
+
CREATE TRIGGER IF NOT EXISTS trg_decision_logs_ai AFTER INSERT ON decision_logs BEGIN
|
|
362
|
+
INSERT INTO memory_fts(entity_type, entity_id, project_id, session_id, cli_source, category, title, body, file_refs)
|
|
363
|
+
VALUES ('decision', NEW.id, NEW.project_id, NEW.session_id, NEW.cli_source, NEW.category,
|
|
364
|
+
NEW.title, NEW.body || ' ' || NEW.rationale, NEW.file_refs_json);
|
|
365
|
+
END;
|
|
366
|
+
|
|
367
|
+
CREATE TRIGGER IF NOT EXISTS trg_decision_logs_ad AFTER DELETE ON decision_logs BEGIN
|
|
368
|
+
DELETE FROM memory_fts WHERE entity_type = 'decision' AND entity_id = OLD.id;
|
|
369
|
+
END;
|
|
370
|
+
|
|
371
|
+
CREATE TRIGGER IF NOT EXISTS trg_decision_logs_au AFTER UPDATE ON decision_logs BEGIN
|
|
372
|
+
DELETE FROM memory_fts WHERE entity_type = 'decision' AND entity_id = OLD.id;
|
|
373
|
+
INSERT INTO memory_fts(entity_type, entity_id, project_id, session_id, cli_source, category, title, body, file_refs)
|
|
374
|
+
VALUES ('decision', NEW.id, NEW.project_id, NEW.session_id, NEW.cli_source, NEW.category,
|
|
375
|
+
NEW.title, NEW.body || ' ' || NEW.rationale, NEW.file_refs_json);
|
|
376
|
+
END;
|
|
377
|
+
|
|
378
|
+
CREATE TRIGGER IF NOT EXISTS trg_capsules_ai AFTER INSERT ON context_capsules BEGIN
|
|
379
|
+
INSERT INTO memory_fts(entity_type, entity_id, project_id, session_id, cli_source, category, title, body, file_refs)
|
|
380
|
+
VALUES ('capsule', NEW.id, NEW.project_id, NEW.session_id, NEW.source_chain_json, 'capsule',
|
|
381
|
+
NEW.git_branch || ': ' || NEW.goal_summary, NEW.capsule_markdown, '');
|
|
382
|
+
END;
|
|
383
|
+
|
|
384
|
+
CREATE TRIGGER IF NOT EXISTS trg_capsules_ad AFTER DELETE ON context_capsules BEGIN
|
|
385
|
+
DELETE FROM memory_fts WHERE entity_type = 'capsule' AND entity_id = OLD.id;
|
|
386
|
+
END;
|
|
387
|
+
`;
|
|
388
|
+
|
|
389
|
+
// packages/core/dist/db/client.js
|
|
390
|
+
function resolveCmemHome() {
|
|
391
|
+
return process.env.CMEM_HOME ?? join(homedir(), ".cmem");
|
|
392
|
+
}
|
|
393
|
+
function resolveDatabasePath(explicitPath) {
|
|
394
|
+
if (explicitPath)
|
|
395
|
+
return explicitPath;
|
|
396
|
+
if (process.env.CMEM_DB_PATH)
|
|
397
|
+
return process.env.CMEM_DB_PATH;
|
|
398
|
+
return join(resolveCmemHome(), "cmem.db");
|
|
399
|
+
}
|
|
400
|
+
function openDatabase(explicitPath) {
|
|
401
|
+
const dbPath = resolveDatabasePath(explicitPath);
|
|
402
|
+
if (dbPath !== ":memory:") {
|
|
403
|
+
mkdirSync(dirname(dbPath), { recursive: true, mode: 448 });
|
|
404
|
+
}
|
|
405
|
+
const db = new DatabaseSync(dbPath);
|
|
406
|
+
db.exec(INIT_PRAGMAS);
|
|
407
|
+
db.exec(INIT_SQL);
|
|
408
|
+
return db;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
// packages/core/dist/db/seed.js
|
|
412
|
+
var capGwV1Payload = {
|
|
413
|
+
schemaVersion: "1.0",
|
|
414
|
+
capsuleId: "cap_gw_v1",
|
|
415
|
+
projectId: "proj_acme_gw",
|
|
416
|
+
projectName: "acme-payments-gateway",
|
|
417
|
+
repoRoot: "/Users/dev/work/acme-payments-gateway",
|
|
418
|
+
gitBranch: "feat/idempotent-webhook-worker",
|
|
419
|
+
gitHeadSha: "a4f9c21",
|
|
420
|
+
isDirtyTree: true,
|
|
421
|
+
sourceChain: ["agy"],
|
|
422
|
+
goal: {
|
|
423
|
+
summary: "Implement Stripe idempotent webhook worker using Postgres FOR UPDATE SKIP LOCKED and dead-letter replay.",
|
|
424
|
+
originalIntent: "Build an idempotent Stripe webhook background worker with Postgres SKIP LOCKED, retry backoff, and dead-letter replay."
|
|
425
|
+
},
|
|
426
|
+
decisionsLocked: [
|
|
427
|
+
{
|
|
428
|
+
id: "dec_01",
|
|
429
|
+
statement: "Use raw pool.query with FOR UPDATE SKIP LOCKED instead of Prisma $transaction",
|
|
430
|
+
rationale: "Avoids Prisma transaction connection-pool exhaustion under 200+ concurrent webhook bursts.",
|
|
431
|
+
cliSource: "agy",
|
|
432
|
+
lockedAt: "2026-11-25T10:15:00Z"
|
|
433
|
+
}
|
|
434
|
+
],
|
|
435
|
+
filesProgress: [
|
|
436
|
+
{
|
|
437
|
+
path: "db/migrations/014_webhook_jobs.sql",
|
|
438
|
+
status: "added",
|
|
439
|
+
lineRanges: ["L1-L42"],
|
|
440
|
+
linesAdded: 42,
|
|
441
|
+
linesRemoved: 0,
|
|
442
|
+
progressNote: "Created webhook_jobs DDL with unique (provider, external_event_id) + partial pending index"
|
|
443
|
+
},
|
|
444
|
+
{
|
|
445
|
+
path: "src/webhooks/worker.ts",
|
|
446
|
+
status: "added",
|
|
447
|
+
lineRanges: ["L1-L148"],
|
|
448
|
+
linesAdded: 148,
|
|
449
|
+
linesRemoved: 0,
|
|
450
|
+
progressNote: "Added polling loop, SKIP LOCKED claim query, and signature verification stub"
|
|
451
|
+
}
|
|
452
|
+
],
|
|
453
|
+
deadEndsAvoid: [
|
|
454
|
+
{
|
|
455
|
+
fingerprint: "err_prisma_tx_timeout_pgboss",
|
|
456
|
+
attempted: "pg-boss v10 advisory locks inside Prisma $transaction",
|
|
457
|
+
errorSummary: "PrismaClientUnknownRequestError: Unable to start a transaction in the given time",
|
|
458
|
+
occurrences: 3,
|
|
459
|
+
cliSource: "agy"
|
|
460
|
+
}
|
|
461
|
+
],
|
|
462
|
+
nextSteps: [
|
|
463
|
+
{
|
|
464
|
+
order: 1,
|
|
465
|
+
task: "Extract exponential backoff + full jitter into src/webhooks/backoff.ts",
|
|
466
|
+
done: false
|
|
467
|
+
},
|
|
468
|
+
{
|
|
469
|
+
order: 2,
|
|
470
|
+
task: "Wire OpenTelemetry span attributes (webhook.event_id, webhook.attempt)",
|
|
471
|
+
done: false
|
|
472
|
+
},
|
|
473
|
+
{
|
|
474
|
+
order: 3,
|
|
475
|
+
task: "Add Vitest suite verifying duplicate delivery + DLQ transition",
|
|
476
|
+
verifyCommand: "npx vitest run tests/webhooks/worker.test.ts",
|
|
477
|
+
done: false
|
|
478
|
+
}
|
|
479
|
+
],
|
|
480
|
+
telemetry: {
|
|
481
|
+
rawSessionTokens: 68420,
|
|
482
|
+
capsuleTokens: 980,
|
|
483
|
+
tokensSaved: 67440,
|
|
484
|
+
compressionPct: 98.6,
|
|
485
|
+
generatedAt: "2026-11-25T11:44:02Z",
|
|
486
|
+
trigger: "quota_blocked"
|
|
487
|
+
}
|
|
488
|
+
};
|
|
489
|
+
var capGwV2Payload = {
|
|
490
|
+
schemaVersion: "1.0",
|
|
491
|
+
capsuleId: "cap_gw_v2",
|
|
492
|
+
projectId: "proj_acme_gw",
|
|
493
|
+
projectName: "acme-payments-gateway",
|
|
494
|
+
repoRoot: "/Users/dev/work/acme-payments-gateway",
|
|
495
|
+
gitBranch: "feat/idempotent-webhook-worker",
|
|
496
|
+
gitHeadSha: "a4f9c21",
|
|
497
|
+
isDirtyTree: true,
|
|
498
|
+
sourceChain: ["agy", "claude"],
|
|
499
|
+
goal: {
|
|
500
|
+
summary: "Complete webhook worker exponential backoff + OTel spans and verify idempotency/DLQ tests in Vitest.",
|
|
501
|
+
originalIntent: capGwV1Payload.goal.originalIntent
|
|
502
|
+
},
|
|
503
|
+
decisionsLocked: [
|
|
504
|
+
...capGwV1Payload.decisionsLocked,
|
|
505
|
+
{
|
|
506
|
+
id: "dec_03",
|
|
507
|
+
statement: "Inject Clock interface { sleep(ms), now() } for retry loops; forbid vi.useFakeTimers() with pg-pool",
|
|
508
|
+
rationale: "Allows deterministic instant backoff unit tests without stalling real socket timers.",
|
|
509
|
+
cliSource: "claude",
|
|
510
|
+
lockedAt: "2026-11-25T13:18:00Z"
|
|
511
|
+
},
|
|
512
|
+
{
|
|
513
|
+
id: "dec_05",
|
|
514
|
+
statement: "Enforce SHA-256 payload guard returning 422 IDEMPOTENCY_CONFLICT and routing to dead_letter",
|
|
515
|
+
rationale: "Prevents silent acceptance of mutated payloads under a reused Stripe event ID.",
|
|
516
|
+
cliSource: "claude",
|
|
517
|
+
lockedAt: "2026-11-25T14:20:00Z"
|
|
518
|
+
}
|
|
519
|
+
],
|
|
520
|
+
filesProgress: [
|
|
521
|
+
capGwV1Payload.filesProgress[0],
|
|
522
|
+
{
|
|
523
|
+
path: "src/webhooks/backoff.ts",
|
|
524
|
+
status: "added",
|
|
525
|
+
lineRanges: ["L1-L64"],
|
|
526
|
+
linesAdded: 64,
|
|
527
|
+
linesRemoved: 0,
|
|
528
|
+
progressNote: "Added computeFullJitterDelayMs + injectable Clock interface"
|
|
529
|
+
},
|
|
530
|
+
{
|
|
531
|
+
path: "src/webhooks/worker.ts",
|
|
532
|
+
status: "modified",
|
|
533
|
+
lineRanges: ["L88-L162"],
|
|
534
|
+
linesAdded: 48,
|
|
535
|
+
linesRemoved: 11,
|
|
536
|
+
progressNote: "Integrated backoff.ts, OTel span webhook.process, and 422 payload hash check"
|
|
537
|
+
}
|
|
538
|
+
],
|
|
539
|
+
deadEndsAvoid: [
|
|
540
|
+
...capGwV1Payload.deadEndsAvoid,
|
|
541
|
+
{
|
|
542
|
+
fingerprint: "err_vitest_faketimers_pgpool",
|
|
543
|
+
attempted: "vi.useFakeTimers() against pg-pool connect() timeout",
|
|
544
|
+
errorSummary: "Vitest hook deadlock at 5000ms timeout",
|
|
545
|
+
occurrences: 2,
|
|
546
|
+
cliSource: "claude"
|
|
547
|
+
}
|
|
548
|
+
],
|
|
549
|
+
nextSteps: [
|
|
550
|
+
{
|
|
551
|
+
order: 1,
|
|
552
|
+
task: "Add signature/payload mismatch 422 test + DLQ test in tests/webhooks/worker.test.ts",
|
|
553
|
+
verifyCommand: "npx vitest run tests/webhooks/worker.test.ts",
|
|
554
|
+
done: false
|
|
555
|
+
},
|
|
556
|
+
{
|
|
557
|
+
order: 2,
|
|
558
|
+
task: "Run full test suite and TypeScript typecheck",
|
|
559
|
+
verifyCommand: "npx vitest run tests/webhooks/worker.test.ts && npx tsc --noEmit",
|
|
560
|
+
done: false
|
|
561
|
+
}
|
|
562
|
+
],
|
|
563
|
+
telemetry: {
|
|
564
|
+
rawSessionTokens: 54190,
|
|
565
|
+
capsuleTokens: 1185,
|
|
566
|
+
tokensSaved: 53005,
|
|
567
|
+
compressionPct: 97.8,
|
|
568
|
+
generatedAt: "2026-11-25T14:52:03Z",
|
|
569
|
+
trigger: "quota_blocked"
|
|
570
|
+
}
|
|
571
|
+
};
|
|
572
|
+
var capGwV3Payload = {
|
|
573
|
+
schemaVersion: "1.0",
|
|
574
|
+
capsuleId: "cap_gw_v3",
|
|
575
|
+
projectId: "proj_acme_gw",
|
|
576
|
+
projectName: "acme-payments-gateway",
|
|
577
|
+
repoRoot: "/Users/dev/work/acme-payments-gateway",
|
|
578
|
+
gitBranch: "feat/idempotent-webhook-worker",
|
|
579
|
+
gitHeadSha: "a4f9c21",
|
|
580
|
+
isDirtyTree: true,
|
|
581
|
+
sourceChain: ["agy", "claude", "codex"],
|
|
582
|
+
goal: {
|
|
583
|
+
summary: "Finalize webhook worker test coverage (422 payload mismatch & DLQ) and pass full Vitest + typecheck.",
|
|
584
|
+
originalIntent: capGwV1Payload.goal.originalIntent
|
|
585
|
+
},
|
|
586
|
+
decisionsLocked: capGwV2Payload.decisionsLocked,
|
|
587
|
+
filesProgress: [
|
|
588
|
+
...capGwV2Payload.filesProgress,
|
|
589
|
+
{
|
|
590
|
+
path: "tests/webhooks/worker.test.ts",
|
|
591
|
+
status: "added",
|
|
592
|
+
lineRanges: ["L1-L118"],
|
|
593
|
+
linesAdded: 118,
|
|
594
|
+
linesRemoved: 0,
|
|
595
|
+
progressNote: "Duplicate claim & backoff tests passing; finishing 422 mismatch test at L94-L118"
|
|
596
|
+
}
|
|
597
|
+
],
|
|
598
|
+
deadEndsAvoid: capGwV2Payload.deadEndsAvoid,
|
|
599
|
+
nextSteps: [
|
|
600
|
+
{
|
|
601
|
+
order: 1,
|
|
602
|
+
task: 'Finish "rejects mismatched payload with 422" assertion in tests/webhooks/worker.test.ts:L94-L118',
|
|
603
|
+
verifyCommand: "npx vitest run tests/webhooks/worker.test.ts",
|
|
604
|
+
done: false
|
|
605
|
+
},
|
|
606
|
+
{
|
|
607
|
+
order: 2,
|
|
608
|
+
task: "Run full Vitest + tsc --noEmit verification before opening PR",
|
|
609
|
+
verifyCommand: "npx vitest run tests/webhooks/worker.test.ts && npx tsc --noEmit",
|
|
610
|
+
done: false
|
|
611
|
+
}
|
|
612
|
+
],
|
|
613
|
+
telemetry: {
|
|
614
|
+
rawSessionTokens: 16380,
|
|
615
|
+
capsuleTokens: 1142,
|
|
616
|
+
tokensSaved: 15238,
|
|
617
|
+
compressionPct: 93,
|
|
618
|
+
generatedAt: "2026-11-25T17:42:00Z",
|
|
619
|
+
trigger: "turn_checkpoint"
|
|
620
|
+
}
|
|
621
|
+
};
|
|
622
|
+
var capEdgeV1Payload = {
|
|
623
|
+
schemaVersion: "1.0",
|
|
624
|
+
capsuleId: "cap_edge_v1",
|
|
625
|
+
projectId: "proj_edge_auth",
|
|
626
|
+
projectName: "edge-auth-proxy",
|
|
627
|
+
repoRoot: "/Users/dev/work/edge-auth-proxy",
|
|
628
|
+
gitBranch: "fix/jwks-clock-skew",
|
|
629
|
+
gitHeadSha: "91e30ab",
|
|
630
|
+
isDirtyTree: false,
|
|
631
|
+
sourceChain: ["gemini", "claude"],
|
|
632
|
+
goal: {
|
|
633
|
+
summary: "Allow 30s leeway on RS256 JWT exp/nbf checks and cache JWKS by kid with singleflight refresh.",
|
|
634
|
+
originalIntent: "Resolve intermittent 401 errors during Auth0 JWKS key rotations and slight node clock skew."
|
|
635
|
+
},
|
|
636
|
+
decisionsLocked: [
|
|
637
|
+
{
|
|
638
|
+
id: "dec_07",
|
|
639
|
+
statement: "Singleflight JWKS kid cache with strict 30s clockTolerance; reject tokens without kid header",
|
|
640
|
+
rationale: "Eliminated thundering-herd 401 spikes during Auth0 key rotation.",
|
|
641
|
+
cliSource: "claude",
|
|
642
|
+
lockedAt: "2026-11-24T19:15:00Z"
|
|
643
|
+
}
|
|
644
|
+
],
|
|
645
|
+
filesProgress: [
|
|
646
|
+
{
|
|
647
|
+
path: "src/jwt/verify.ts",
|
|
648
|
+
status: "modified",
|
|
649
|
+
lineRanges: ["L18-L62"],
|
|
650
|
+
linesAdded: 34,
|
|
651
|
+
linesRemoved: 9,
|
|
652
|
+
progressNote: "Singleflight JWKS fetch lock + clockTolerance: 30"
|
|
653
|
+
}
|
|
654
|
+
],
|
|
655
|
+
deadEndsAvoid: [],
|
|
656
|
+
nextSteps: [
|
|
657
|
+
{
|
|
658
|
+
order: 1,
|
|
659
|
+
task: "Verified 24/24 JWT rotation tests passing on branch fix/jwks-clock-skew",
|
|
660
|
+
verifyCommand: "npm test -- tests/jwt/verify.test.ts",
|
|
661
|
+
done: true
|
|
662
|
+
}
|
|
663
|
+
],
|
|
664
|
+
telemetry: {
|
|
665
|
+
rawSessionTokens: 43e3,
|
|
666
|
+
capsuleTokens: 520,
|
|
667
|
+
tokensSaved: 42480,
|
|
668
|
+
compressionPct: 98.8,
|
|
669
|
+
generatedAt: "2026-11-24T19:30:00Z",
|
|
670
|
+
trigger: "mcp_checkpoint"
|
|
671
|
+
}
|
|
672
|
+
};
|
|
673
|
+
function runDemoSeed(db, reset = false) {
|
|
674
|
+
if (reset) {
|
|
675
|
+
db.exec(`
|
|
676
|
+
DELETE FROM handoff_events;
|
|
677
|
+
DELETE FROM file_snapshots;
|
|
678
|
+
DELETE FROM decision_logs;
|
|
679
|
+
DELETE FROM context_capsules;
|
|
680
|
+
DELETE FROM sessions;
|
|
681
|
+
DELETE FROM projects;
|
|
682
|
+
DELETE FROM adapter_cursors;
|
|
683
|
+
DELETE FROM memory_fts;
|
|
684
|
+
`);
|
|
685
|
+
}
|
|
686
|
+
const existing = db.prepare("SELECT COUNT(*) AS cnt FROM projects").get();
|
|
687
|
+
if (existing.cnt > 0 && !reset) {
|
|
688
|
+
return { projectsSeeded: 0 };
|
|
689
|
+
}
|
|
690
|
+
db.exec("BEGIN TRANSACTION");
|
|
691
|
+
try {
|
|
692
|
+
const insertProject = db.prepare(`
|
|
693
|
+
INSERT INTO projects (id, slug, name, repo_root, default_branch, active_branch, active_cli, created_at, updated_at)
|
|
694
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
695
|
+
`);
|
|
696
|
+
insertProject.run("proj_acme_gw", "acme-payments-gateway", "acme-payments-gateway", "/Users/dev/work/acme-payments-gateway", "main", "feat/idempotent-webhook-worker", "codex", "2026-11-25T09:10:00Z", "2026-11-25T17:42:00Z");
|
|
697
|
+
insertProject.run("proj_edge_auth", "edge-auth-proxy", "edge-auth-proxy", "/Users/dev/work/edge-auth-proxy", "main", "fix/jwks-clock-skew", "claude", "2026-11-24T14:00:00Z", "2026-11-24T19:30:00Z");
|
|
698
|
+
const insertSession = db.prepare(`
|
|
699
|
+
INSERT INTO sessions (
|
|
700
|
+
id, project_id, parent_session_id, cli_source, external_session_id, source_log_path,
|
|
701
|
+
account_label, model_name, git_branch, status, quota_limit_type, quota_reset_at,
|
|
702
|
+
turn_count, raw_input_tokens, raw_output_tokens, raw_cached_tokens,
|
|
703
|
+
started_at, ended_at, last_activity_at
|
|
704
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
705
|
+
`);
|
|
706
|
+
insertSession.run("sess_01_agy", "proj_acme_gw", null, "agy", "7b92c41e-88a1-4b92-a3f0-112233445566", "~/.gemini/antigravity-cli/brain/7b92c41e-88a1-4b92-a3f0-112233445566/.system_generated/logs/transcript.jsonl", "work-primary", "gemini-4-hydrogen-xhigh", "feat/idempotent-webhook-worker", "quota_blocked", "5h_window", "2026-11-25T16:30:00Z", 28, 61200, 7220, 41e3, "2026-11-25T09:12:00Z", "2026-11-25T11:44:00Z", "2026-11-25T11:44:00Z");
|
|
707
|
+
insertSession.run("sess_02_claude", "proj_acme_gw", "sess_01_agy", "claude", "claude-991a-40e2-9918-ffaa11223344", "~/.claude/projects/-Users-dev-work-acme-payments-gateway/claude-991a-40e2-9918-ffaa11223344.jsonl", "claude-pro-team", "claude-sonnet-4-5", "feat/idempotent-webhook-worker", "quota_blocked", "weekly_cap", "2026-11-28T00:00:00Z", 22, 47840, 6350, 29400, "2026-11-25T11:46:15Z", "2026-11-25T14:52:00Z", "2026-11-25T14:52:00Z");
|
|
708
|
+
insertSession.run("sess_03_codex", "proj_acme_gw", "sess_02_claude", "codex", "rollout-2026-11-25T14-54-09-01J9Z", "~/.codex/sessions/2026/11/25/rollout-2026-11-25T14-54-09-01J9Z.jsonl", "openai-plus-backup", "gpt-5-codex", "feat/idempotent-webhook-worker", "active", null, null, 9, 14200, 2180, 6400, "2026-11-25T14:54:09Z", null, "2026-11-25T17:42:00Z");
|
|
709
|
+
insertSession.run("sess_04_gemini", "proj_edge_auth", null, "gemini", "session-2026-11-24-jwks-01", "~/.gemini/tmp/a98f21cc/chats/session-2026-11-24-jwks-01.json", "google-dev", "gemini-2.5-pro", "fix/jwks-clock-skew", "handed_off", "rpm_429", "2026-11-24T16:15:00Z", 14, 24100, 3100, 12e3, "2026-11-24T14:05:00Z", "2026-11-24T16:02:00Z", "2026-11-24T16:02:00Z");
|
|
710
|
+
insertSession.run("sess_05_claude", "proj_edge_auth", "sess_04_gemini", "claude", "claude-edge-8821", "~/.claude/projects/-Users-dev-work-edge-auth-proxy/claude-edge-8821.jsonl", "claude-pro-team", "claude-sonnet-4-5", "fix/jwks-clock-skew", "completed", null, null, 11, 18900, 2750, 9500, "2026-11-24T16:04:00Z", "2026-11-24T19:30:00Z", "2026-11-24T19:30:00Z");
|
|
711
|
+
const insertCapsule = db.prepare(`
|
|
712
|
+
INSERT INTO context_capsules (
|
|
713
|
+
id, project_id, session_id, version, trigger_reason, git_branch, git_head_sha, is_dirty_tree,
|
|
714
|
+
goal_summary, capsule_json, capsule_markdown,
|
|
715
|
+
raw_tokens_covered, capsule_tokens, tokens_saved, source_chain_json, is_active, created_at
|
|
716
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
717
|
+
`);
|
|
718
|
+
insertCapsule.run("cap_gw_v1", "proj_acme_gw", "sess_01_agy", 1, "quota_blocked", "feat/idempotent-webhook-worker", "a4f9c21", 1, capGwV1Payload.goal.summary, JSON.stringify(capGwV1Payload), `## CMEM CONTEXT CAPSULE [v1 | agy -> handoff]
|
|
719
|
+
**Repo/Branch:** acme-payments-gateway (\`feat/idempotent-webhook-worker\` @ \`a4f9c21\` dirty)
|
|
720
|
+
**Goal:** ${capGwV1Payload.goal.summary}
|
|
721
|
+
### Decisions Locked
|
|
722
|
+
- Use raw \`pool.query\` with \`FOR UPDATE SKIP LOCKED\` instead of Prisma \`$transaction\`.
|
|
723
|
+
### Files & Line Progress
|
|
724
|
+
- \`db/migrations/014_webhook_jobs.sql\` (added \`L1-L42\`): table, partial pending index, DLQ columns.
|
|
725
|
+
- \`src/webhooks/worker.ts\` (added \`L1-L148\`): polling loop, claim query, signature verification stub.
|
|
726
|
+
### Dead Ends (DO NOT RETRY)
|
|
727
|
+
- \`pg-boss\` v10 inside Prisma \`$transaction\`: failed 3x (\`PrismaClientUnknownRequestError\`).
|
|
728
|
+
### Remaining Checklist
|
|
729
|
+
- [ ] Extract exponential backoff + full jitter into \`src/webhooks/backoff.ts\`
|
|
730
|
+
- [ ] Wire OpenTelemetry span attributes (\`webhook.event_id\`, \`webhook.attempt\`)
|
|
731
|
+
- [ ] Add Vitest suite verifying duplicate delivery + DLQ transition (\`npx vitest run tests/webhooks/worker.test.ts\`)`, 68420, 980, 67440, '["agy"]', 0, "2026-11-25T11:44:02Z");
|
|
732
|
+
insertCapsule.run("cap_gw_v2", "proj_acme_gw", "sess_02_claude", 2, "quota_blocked", "feat/idempotent-webhook-worker", "a4f9c21", 1, capGwV2Payload.goal.summary, JSON.stringify(capGwV2Payload), `## CMEM CONTEXT CAPSULE [v2 | agy -> claude -> handoff]
|
|
733
|
+
**Repo/Branch:** acme-payments-gateway (\`feat/idempotent-webhook-worker\` @ \`a4f9c21\` dirty)
|
|
734
|
+
**Goal:** ${capGwV2Payload.goal.summary}
|
|
735
|
+
### Decisions Locked
|
|
736
|
+
- Use raw \`pool.query\` (\`FOR UPDATE SKIP LOCKED\`); never wrap queue claims in Prisma \`$transaction\`.
|
|
737
|
+
- Inject \`Clock\` interface into retry loops; never call \`vi.useFakeTimers()\` with \`pg-pool\`.
|
|
738
|
+
- Payload mismatch on reused \`external_event_id\` returns HTTP \`422 IDEMPOTENCY_CONFLICT\` and moves job to \`dead_letter\`.
|
|
739
|
+
### Files & Line Progress
|
|
740
|
+
- \`db/migrations/014_webhook_jobs.sql\` (added \`L1-L42\`): \`webhook_jobs\` DDL + partial index.
|
|
741
|
+
- \`src/webhooks/backoff.ts\` (added \`L1-L64\`): \`computeFullJitterDelayMs\` + injectable \`Clock\`.
|
|
742
|
+
- \`src/webhooks/worker.ts\` (modified \`L88-L162\`): integrated \`backoff.ts\`, OTel span \`webhook.process\`, atomic payload hash check.
|
|
743
|
+
### Dead Ends (DO NOT RETRY)
|
|
744
|
+
- \`pg-boss\` v10 inside Prisma \`$transaction\` -> \`PrismaClientUnknownRequestError\` timeout (3x).
|
|
745
|
+
- \`vi.useFakeTimers()\` against \`pg-pool\` connect timeout -> Vitest hook deadlock at 5000ms (2x).
|
|
746
|
+
### Remaining Checklist
|
|
747
|
+
- [ ] Add signature/payload mismatch 422 test + DLQ test in \`tests/webhooks/worker.test.ts\`
|
|
748
|
+
- [ ] Run \`npx vitest run tests/webhooks/worker.test.ts && npx tsc --noEmit\``, 54190, 1185, 53005, '["agy","claude"]', 0, "2026-11-25T14:52:03Z");
|
|
749
|
+
insertCapsule.run("cap_gw_v3", "proj_acme_gw", "sess_03_codex", 3, "turn_checkpoint", "feat/idempotent-webhook-worker", "a4f9c21", 1, capGwV3Payload.goal.summary, JSON.stringify(capGwV3Payload), `## CMEM CONTEXT CAPSULE [v3 | agy -> claude -> codex (ACTIVE)]
|
|
750
|
+
**Repo/Branch:** acme-payments-gateway (\`feat/idempotent-webhook-worker\` @ \`a4f9c21\` dirty)
|
|
751
|
+
**Goal:** ${capGwV3Payload.goal.summary}
|
|
752
|
+
### Decisions Locked
|
|
753
|
+
- Raw \`pool.query\` (\`FOR UPDATE SKIP LOCKED\`); no Prisma \`$transaction\` around queue polling.
|
|
754
|
+
- Injectable \`Clock\` interface for retry backoff; no \`vi.useFakeTimers()\` with \`pg-pool\`.
|
|
755
|
+
- Hash mismatch on duplicate \`external_event_id\` returns \`422 IDEMPOTENCY_CONFLICT\` and routes to \`dead_letter\`.
|
|
756
|
+
### Files & Line Progress
|
|
757
|
+
- \`db/migrations/014_webhook_jobs.sql\` (added \`L1-L42\`): \`webhook_jobs\` table + partial index.
|
|
758
|
+
- \`src/webhooks/backoff.ts\` (added \`L1-L64\`): full-jitter exponential backoff + \`Clock\`.
|
|
759
|
+
- \`src/webhooks/worker.ts\` (modified \`L88-L162\`): OTel tracing + \`sha256\` payload conflict guard.
|
|
760
|
+
- \`tests/webhooks/worker.test.ts\` (added \`L1-L118\`): duplicate claim & backoff tests passing; 422 mismatch test in progress (\`L94-L118\`).
|
|
761
|
+
### Dead Ends (DO NOT RETRY)
|
|
762
|
+
- \`pg-boss\` v10 + Prisma \`$transaction\` -> tx start timeout (3x, \`agy\`).
|
|
763
|
+
- \`vi.useFakeTimers()\` + \`pg-pool\` -> Vitest timeout deadlock (2x, \`claude\`).
|
|
764
|
+
### Remaining Checklist
|
|
765
|
+
- [ ] Finish \`rejects mismatched payload with 422\` assertion in \`tests/webhooks/worker.test.ts:L94-L118\`
|
|
766
|
+
- [ ] Run \`npx vitest run tests/webhooks/worker.test.ts && npx tsc --noEmit\``, 16380, 1142, 15238, '["agy","claude","codex"]', 1, "2026-11-25T17:42:00Z");
|
|
767
|
+
insertCapsule.run("cap_edge_v1", "proj_edge_auth", "sess_05_claude", 1, "mcp_checkpoint", "fix/jwks-clock-skew", "91e30ab", 0, capEdgeV1Payload.goal.summary, JSON.stringify(capEdgeV1Payload), `## CMEM CONTEXT CAPSULE [v1 | gemini -> claude (COMPLETED)]
|
|
768
|
+
**Repo/Branch:** edge-auth-proxy (\`fix/jwks-clock-skew\` @ \`91e30ab\` clean)
|
|
769
|
+
**Goal:** ${capEdgeV1Payload.goal.summary}
|
|
770
|
+
### Decisions Locked
|
|
771
|
+
- Cap \`clockTolerance: 30\` seconds strictly; reject tokens missing \`kid\` header immediately (\`401 INVALID_KID\`).
|
|
772
|
+
### Files & Line Progress
|
|
773
|
+
- \`src/jwt/verify.ts\` (\`L18-L62\`): singleflight JWKS fetch lock + \`clockTolerance: 30\`.`, 43e3, 520, 42480, '["gemini","claude"]', 1, "2026-11-24T19:30:00Z");
|
|
774
|
+
const insertDecision = db.prepare(`
|
|
775
|
+
INSERT INTO decision_logs (
|
|
776
|
+
id, project_id, session_id, capsule_id, cli_source, category, title, body, rationale,
|
|
777
|
+
error_fingerprint, retry_count, file_refs_json, is_pinned, is_superseded, is_resolved, created_at
|
|
778
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
779
|
+
`);
|
|
780
|
+
insertDecision.run("dec_01", "proj_acme_gw", "sess_01_agy", "cap_gw_v1", "agy", "architecture", "Use raw pool.query + FOR UPDATE SKIP LOCKED for webhook claim", "Claim jobs using raw pg Pool SQL (`SELECT ... FOR UPDATE SKIP LOCKED`) instead of Prisma interactive transactions.", "Avoids Prisma transaction connection-pool exhaustion under 200+ concurrent webhook bursts.", null, 1, '["src/webhooks/worker.ts:L32-L74","db/migrations/014_webhook_jobs.sql:L1-L42"]', 1, 0, 1, "2026-11-25T10:15:00Z");
|
|
781
|
+
insertDecision.run("dec_02", "proj_acme_gw", "sess_01_agy", "cap_gw_v1", "agy", "dead_end", "pg-boss v10 advisory locks inside Prisma $transaction timeout", "Attempted to embed pg-boss v10 custom job claim inside Prisma `$transaction(async tx => ...)`", "Failed 3 consecutive runs with `PrismaClientUnknownRequestError: Unable to start a transaction in the given time`. Do not wrap queue locks in Prisma tx.", "err_prisma_tx_timeout_pgboss", 3, '["src/webhooks/worker.ts:L32-L55"]', 0, 0, 1, "2026-11-25T10:02:00Z");
|
|
782
|
+
insertDecision.run("dec_03", "proj_acme_gw", "sess_02_claude", "cap_gw_v2", "claude", "constraint", "Inject Clock interface; forbid vi.useFakeTimers() with pg-pool", "All backoff/retry functions must accept `{ sleep(ms: number): Promise<void>; now(): number }` rather than using global fake timers.", "Allows deterministic instant backoff unit tests without stalling real socket timers.", null, 1, '["src/webhooks/backoff.ts:L1-L64"]', 1, 0, 1, "2026-11-25T13:18:00Z");
|
|
783
|
+
insertDecision.run("dec_04", "proj_acme_gw", "sess_02_claude", "cap_gw_v2", "claude", "dead_end", "vi.useFakeTimers() deadlocks pg-pool connect() timeout", "Calling `vi.useFakeTimers()` in `worker.test.ts` froze `pg-pool` internal connection acquisition timers.", "Vitest hung until 5000ms hook timeout twice; replaced with fake `Clock` injection.", "err_vitest_faketimers_pgpool", 2, '["tests/webhooks/worker.test.ts:L1-L35"]', 0, 0, 1, "2026-11-25T13:05:00Z");
|
|
784
|
+
insertDecision.run("dec_05", "proj_acme_gw", "sess_02_claude", "cap_gw_v2", "claude", "architecture", "Enforce SHA-256 payload guard returning 422 IDEMPOTENCY_CONFLICT", "Compare incoming webhook body SHA-256 against stored `payload_hash` on duplicate `(provider, external_event_id)` before replaying.", "Prevents silent acceptance of mutated payloads under a reused Stripe event ID; routes mismatch to `dead_letter`.", null, 1, '["src/webhooks/worker.ts:L112-L148"]', 1, 0, 1, "2026-11-25T14:20:00Z");
|
|
785
|
+
insertDecision.run("dec_06", "proj_acme_gw", "sess_03_codex", "cap_gw_v3", "codex", "next_step", "Complete 422 payload mismatch assertion and verify Vitest + tsc", "Finish `rejects mismatched payload with 422` test in `tests/webhooks/worker.test.ts:L94-L118` and run `npx vitest run tests/webhooks/worker.test.ts && npx tsc --noEmit`.", "Final verification gate before PR.", null, 1, '["tests/webhooks/worker.test.ts:L94-L118"]', 0, 0, 0, "2026-11-25T17:40:00Z");
|
|
786
|
+
insertDecision.run("dec_07", "proj_edge_auth", "sess_05_claude", "cap_edge_v1", "claude", "architecture", "Singleflight JWKS kid cache with 30s clockTolerance", "Deduplicate concurrent JWKS key rotation fetches by `kid` using an in-flight Promise map and set JWT verification leeway to 30s.", "Eliminated thundering-herd 401 spikes during Auth0 key rotation.", null, 1, '["src/jwt/verify.ts:L18-L62"]', 1, 0, 1, "2026-11-24T19:15:00Z");
|
|
787
|
+
const insertSnap = db.prepare(`
|
|
788
|
+
INSERT INTO file_snapshots (
|
|
789
|
+
id, project_id, session_id, capsule_id, file_path, change_status, line_ranges_json,
|
|
790
|
+
lines_added, lines_removed, progress_note, content_sha256, unified_diff, captured_at
|
|
791
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
792
|
+
`);
|
|
793
|
+
insertSnap.run("snap_01", "proj_acme_gw", "sess_01_agy", "cap_gw_v1", "db/migrations/014_webhook_jobs.sql", "added", '["L1-L42"]', 42, 0, "Created webhook_jobs DDL with unique (provider, external_event_id) + partial pending index", "9f8e7d6c5b4a3210fedcba9876543210", `--- /dev/null
|
|
794
|
+
+++ b/db/migrations/014_webhook_jobs.sql
|
|
795
|
+
@@ -0,0 +1,18 @@
|
|
796
|
+
+CREATE TABLE webhook_jobs (
|
|
797
|
+
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
798
|
+
+ provider TEXT NOT NULL,
|
|
799
|
+
+ external_event_id TEXT NOT NULL,
|
|
800
|
+
+ payload_hash TEXT NOT NULL,
|
|
801
|
+
+ status TEXT NOT NULL DEFAULT 'pending',
|
|
802
|
+
+ attempts INT NOT NULL DEFAULT 0,
|
|
803
|
+
+ next_run_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
804
|
+
+ last_error TEXT,
|
|
805
|
+
+ UNIQUE (provider, external_event_id)
|
|
806
|
+
+);
|
|
807
|
+
+CREATE INDEX idx_webhook_jobs_claim
|
|
808
|
+
+ ON webhook_jobs (next_run_at)
|
|
809
|
+
+ WHERE status = 'pending';`, "2026-11-25T11:44:02Z");
|
|
810
|
+
insertSnap.run("snap_02", "proj_acme_gw", "sess_02_claude", "cap_gw_v2", "src/webhooks/backoff.ts", "added", '["L1-L64"]', 64, 0, "Added full-jitter exponential backoff + injectable Clock interface", "1a2b3c4d5e6f708192a3b4c5d6e7f809", `--- /dev/null
|
|
811
|
+
+++ b/src/webhooks/backoff.ts
|
|
812
|
+
@@ -0,0 +1,14 @@
|
|
813
|
+
+export interface Clock {
|
|
814
|
+
+ now(): number;
|
|
815
|
+
+ sleep(ms: number): Promise<void>;
|
|
816
|
+
+}
|
|
817
|
+
+
|
|
818
|
+
+export function computeFullJitterDelayMs(attempt: number, baseMs = 250, capMs = 30_000): number {
|
|
819
|
+
+ const exp = Math.min(capMs, baseMs * 2 ** Math.max(0, attempt - 1));
|
|
820
|
+
+ return Math.floor(Math.random() * exp);
|
|
821
|
+
+}`, "2026-11-25T14:52:03Z");
|
|
822
|
+
insertSnap.run("snap_03", "proj_acme_gw", "sess_02_claude", "cap_gw_v2", "src/webhooks/worker.ts", "modified", '["L88-L162"]', 48, 11, "Integrated backoff.ts, OTel span webhook.process, and 422 payload hash mismatch check", "aa11bb22cc33dd44ee55ff6677889900", `--- a/src/webhooks/worker.ts
|
|
823
|
+
+++ b/src/webhooks/worker.ts
|
|
824
|
+
@@ -88,11 +88,21 @@ export async function processClaimedJob(pool: Pool, job: WebhookJob, clock: Clock) {
|
|
825
|
+
+ return tracer.startActiveSpan("webhook.process", async (span) => {
|
|
826
|
+
+ span.setAttribute("webhook.event_id", job.external_event_id);
|
|
827
|
+
+ const incomingHash = sha256(job.rawBody);
|
|
828
|
+
+ if (incomingHash !== job.payload_hash) {
|
|
829
|
+
+ await markDeadLetter(pool, job.id, "IDEMPOTENCY_CONFLICT");
|
|
830
|
+
+ return { status: 422, code: "IDEMPOTENCY_CONFLICT" as const };
|
|
831
|
+
+ }
|
|
832
|
+
+ try {
|
|
833
|
+
+ await dispatchHandler(job);
|
|
834
|
+
+ await markSucceeded(pool, job.id);
|
|
835
|
+
+ } catch (err) {
|
|
836
|
+
+ const delay = computeFullJitterDelayMs(job.attempts + 1);
|
|
837
|
+
+ await scheduleRetry(pool, job.id, delay, clock.now());
|
|
838
|
+
+ } finally {
|
|
839
|
+
+ span.end();
|
|
840
|
+
+ }
|
|
841
|
+
+ });
|
|
842
|
+
}`, "2026-11-25T14:52:03Z");
|
|
843
|
+
insertSnap.run("snap_04", "proj_acme_gw", "sess_03_codex", "cap_gw_v3", "tests/webhooks/worker.test.ts", "added", '["L1-L118"]', 118, 0, "Added unit + integration specs; finishing 422 mismatch test at L94-L118", "ff00ee11dd22cc33bb44aa5599667788", `--- /dev/null
|
|
844
|
+
+++ b/tests/webhooks/worker.test.ts
|
|
845
|
+
@@ -0,0 +1,16 @@
|
|
846
|
+
+describe("webhook worker idempotency", () => {
|
|
847
|
+
+ it("claims pending jobs exclusively with SKIP LOCKED", async () => {
|
|
848
|
+
+ const [a, b] = await Promise.all([claimNext(pool), claimNext(pool)]);
|
|
849
|
+
+ expect([a, b].filter(Boolean)).toHaveLength(1);
|
|
850
|
+
+ });
|
|
851
|
+
+
|
|
852
|
+
+ it("rejects mismatched payload with 422 and moves to dead_letter", async () => {
|
|
853
|
+
+ const res = await processClaimedJob(pool, tamperedJob, fakeClock);
|
|
854
|
+
+ expect(res).toEqual({ status: 422, code: "IDEMPOTENCY_CONFLICT" });
|
|
855
|
+
+ });
|
|
856
|
+
+});`, "2026-11-25T17:42:00Z");
|
|
857
|
+
insertSnap.run("snap_05", "proj_edge_auth", "sess_05_claude", "cap_edge_v1", "src/jwt/verify.ts", "modified", '["L18-L62"]', 34, 9, "Singleflight JWKS fetch lock + clockTolerance: 30", "cc33aa11ee99ff228877665544332211", `--- a/src/jwt/verify.ts
|
|
858
|
+
+++ b/src/jwt/verify.ts
|
|
859
|
+
@@ -18,9 +18,14 @@ export async function verifyAccessToken(token: string) {
|
|
860
|
+
+ const { kid } = decodeProtectedHeader(token);
|
|
861
|
+
+ if (!kid) throw new AuthError("INVALID_KID", 401);
|
|
862
|
+
+ const key = await getSingleflightJwksKey(kid);
|
|
863
|
+
+ return jwtVerify(token, key, { clockTolerance: 30 });
|
|
864
|
+
}`, "2026-11-24T19:30:00Z");
|
|
865
|
+
const insertHandoff = db.prepare(`
|
|
866
|
+
INSERT INTO handoff_events (
|
|
867
|
+
id, project_id, capsule_id, from_session_id, to_session_id,
|
|
868
|
+
from_cli, to_cli, from_account, to_account, reason, delivery_method,
|
|
869
|
+
injected_tokens, raw_tokens_avoided, handoff_command, created_at
|
|
870
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
871
|
+
`);
|
|
872
|
+
insertHandoff.run("hoff_01", "proj_acme_gw", "cap_gw_v1", "sess_01_agy", "sess_02_claude", "agy", "claude", "work-primary", "claude-pro-team", "quota_exhausted", "cli_prompt", 980, 67440, "cmem resume --to claude --account claude-pro-team --capsule cap_gw_v1", "2026-11-25T11:45:40Z");
|
|
873
|
+
insertHandoff.run("hoff_02", "proj_acme_gw", "cap_gw_v2", "sess_02_claude", "sess_03_codex", "claude", "codex", "claude-pro-team", "openai-plus-backup", "quota_exhausted", "agents_md", 1185, 121425, "cmem resume --to codex --account openai-plus-backup --inject-file --capsule cap_gw_v2", "2026-11-25T14:53:48Z");
|
|
874
|
+
insertHandoff.run("hoff_03", "proj_edge_auth", "cap_edge_v1", "sess_04_gemini", "sess_05_claude", "gemini", "claude", "google-dev", "claude-pro-team", "quota_exhausted", "claude_md", 520, 26680, "cmem resume --to claude --inject-file", "2026-11-24T16:03:20Z");
|
|
875
|
+
db.exec("COMMIT");
|
|
876
|
+
return { projectsSeeded: 2 };
|
|
877
|
+
} catch (err) {
|
|
878
|
+
db.exec("ROLLBACK");
|
|
879
|
+
throw err;
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
// packages/core/dist/db/memory-store.js
|
|
884
|
+
import { randomUUID } from "node:crypto";
|
|
885
|
+
import { basename, resolve } from "node:path";
|
|
886
|
+
function makeId(prefix) {
|
|
887
|
+
return `${prefix}_${randomUUID().replaceAll("-", "").slice(0, 12)}`;
|
|
888
|
+
}
|
|
889
|
+
function slugifyRepoName(repoRoot) {
|
|
890
|
+
const base = basename(repoRoot) || "workspace";
|
|
891
|
+
return base.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-|-$/g, "") || "workspace";
|
|
892
|
+
}
|
|
893
|
+
function sanitizeFtsQuery(raw) {
|
|
894
|
+
const tokens = raw.trim().split(/\s+/).map((tok) => tok.replace(/[^a-zA-Z0-9_./:-]/g, "")).filter((tok) => tok.length > 0);
|
|
895
|
+
if (tokens.length === 0)
|
|
896
|
+
return "";
|
|
897
|
+
return tokens.map((t) => `"${t.replaceAll('"', "")}"*`).join(" OR ");
|
|
898
|
+
}
|
|
899
|
+
var MemoryStore = class {
|
|
900
|
+
db;
|
|
901
|
+
constructor(db) {
|
|
902
|
+
this.db = db;
|
|
903
|
+
}
|
|
904
|
+
seedDemo(reset = false) {
|
|
905
|
+
return runDemoSeed(this.db, reset);
|
|
906
|
+
}
|
|
907
|
+
upsertProject(input) {
|
|
908
|
+
const normalizedRoot = resolve(input.repoRoot);
|
|
909
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
910
|
+
const existing = this.getProjectByRepoRoot(normalizedRoot);
|
|
911
|
+
if (existing) {
|
|
912
|
+
const nextBranch = input.activeBranch ?? existing.active_branch;
|
|
913
|
+
const nextCli = input.activeCli !== void 0 ? input.activeCli : existing.active_cli;
|
|
914
|
+
this.db.prepare(`UPDATE projects
|
|
915
|
+
SET active_branch = ?, active_cli = ?, updated_at = ?
|
|
916
|
+
WHERE id = ?`).run(nextBranch, nextCli, now, existing.id);
|
|
917
|
+
return this.getProject(existing.id);
|
|
918
|
+
}
|
|
919
|
+
const baseSlug = slugifyRepoName(normalizedRoot);
|
|
920
|
+
const id = makeId("proj");
|
|
921
|
+
const slugExists = this.db.prepare("SELECT id FROM projects WHERE slug = ?").get(baseSlug);
|
|
922
|
+
const slug = slugExists ? `${baseSlug}-${id.slice(-4)}` : baseSlug;
|
|
923
|
+
const name = input.name ?? basename(normalizedRoot);
|
|
924
|
+
this.db.prepare(`INSERT INTO projects (id, slug, name, repo_root, default_branch, active_branch, active_cli, created_at, updated_at)
|
|
925
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(id, slug, Redactor.sanitize(name), normalizedRoot, input.defaultBranch ?? "main", input.activeBranch ?? "main", input.activeCli ?? null, now, now);
|
|
926
|
+
return this.getProject(id);
|
|
927
|
+
}
|
|
928
|
+
getProject(idOrSlug) {
|
|
929
|
+
const row = this.db.prepare("SELECT * FROM projects WHERE id = ? OR slug = ? LIMIT 1").get(idOrSlug, idOrSlug);
|
|
930
|
+
return row ?? null;
|
|
931
|
+
}
|
|
932
|
+
getProjectByRepoRoot(repoRoot) {
|
|
933
|
+
const normalizedRoot = resolve(repoRoot);
|
|
934
|
+
const row = this.db.prepare("SELECT * FROM projects WHERE repo_root = ? LIMIT 1").get(normalizedRoot);
|
|
935
|
+
return row ?? null;
|
|
936
|
+
}
|
|
937
|
+
listProjects() {
|
|
938
|
+
return this.db.prepare(`SELECT
|
|
939
|
+
p.*,
|
|
940
|
+
(SELECT COUNT(*) FROM sessions s WHERE s.project_id = p.id) AS session_count,
|
|
941
|
+
(SELECT c.id FROM context_capsules c WHERE c.project_id = p.id AND c.is_active = 1 ORDER BY c.version DESC LIMIT 1) AS active_capsule_id,
|
|
942
|
+
COALESCE((SELECT c.capsule_tokens FROM context_capsules c WHERE c.project_id = p.id AND c.is_active = 1 ORDER BY c.version DESC LIMIT 1), 0) AS active_capsule_tokens,
|
|
943
|
+
COALESCE((SELECT SUM(s.raw_input_tokens + s.raw_output_tokens) FROM sessions s WHERE s.project_id = p.id), 0) AS cumulative_raw_tokens,
|
|
944
|
+
COALESCE((SELECT SUM(c.tokens_saved) FROM context_capsules c WHERE c.project_id = p.id), 0) AS cumulative_tokens_saved,
|
|
945
|
+
(SELECT COUNT(*) FROM sessions s WHERE s.project_id = p.id AND s.status = 'quota_blocked') AS quota_blocked_count
|
|
946
|
+
FROM projects p
|
|
947
|
+
ORDER BY p.updated_at DESC`).all();
|
|
948
|
+
}
|
|
949
|
+
upsertSession(input) {
|
|
950
|
+
const now = input.lastActivityAt ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
951
|
+
const existing = this.db.prepare("SELECT * FROM sessions WHERE cli_source = ? AND external_session_id = ? LIMIT 1").get(input.cliSource, input.externalSessionId);
|
|
952
|
+
if (existing) {
|
|
953
|
+
const nextStatus = input.status ?? existing.status;
|
|
954
|
+
const endedAt = nextStatus === "quota_blocked" || nextStatus === "completed" || nextStatus === "handed_off" ? existing.ended_at ?? now : null;
|
|
955
|
+
this.db.prepare(`UPDATE sessions
|
|
956
|
+
SET model_name = COALESCE(?, model_name),
|
|
957
|
+
git_branch = COALESCE(?, git_branch),
|
|
958
|
+
account_label = COALESCE(?, account_label),
|
|
959
|
+
status = ?,
|
|
960
|
+
quota_limit_type = COALESCE(?, quota_limit_type),
|
|
961
|
+
quota_reset_at = COALESCE(?, quota_reset_at),
|
|
962
|
+
turn_count = turn_count + ?,
|
|
963
|
+
raw_input_tokens = raw_input_tokens + ?,
|
|
964
|
+
raw_output_tokens = raw_output_tokens + ?,
|
|
965
|
+
raw_cached_tokens = raw_cached_tokens + ?,
|
|
966
|
+
ended_at = ?,
|
|
967
|
+
last_activity_at = ?
|
|
968
|
+
WHERE id = ?`).run(input.modelName ?? null, input.gitBranch ?? null, input.accountLabel ?? null, nextStatus, input.quotaLimitType ?? null, input.quotaResetAt ?? null, input.turnCountDelta ?? 0, input.rawInputDelta ?? 0, input.rawOutputDelta ?? 0, input.rawCachedDelta ?? 0, endedAt, now, existing.id);
|
|
969
|
+
return this.getSession(existing.id);
|
|
970
|
+
}
|
|
971
|
+
const id = makeId("sess");
|
|
972
|
+
const startedAt = input.startedAt ?? now;
|
|
973
|
+
const status = input.status ?? "active";
|
|
974
|
+
this.db.prepare(`INSERT INTO sessions (
|
|
975
|
+
id, project_id, parent_session_id, cli_source, external_session_id, source_log_path,
|
|
976
|
+
account_label, model_name, git_branch, status, quota_limit_type, quota_reset_at,
|
|
977
|
+
turn_count, raw_input_tokens, raw_output_tokens, raw_cached_tokens,
|
|
978
|
+
started_at, ended_at, last_activity_at
|
|
979
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(id, input.projectId, input.parentSessionId ?? null, input.cliSource, input.externalSessionId, input.sourceLogPath ?? null, input.accountLabel ?? "default", input.modelName ?? "unknown", input.gitBranch ?? "main", status, input.quotaLimitType ?? null, input.quotaResetAt ?? null, input.turnCountDelta ?? 0, input.rawInputDelta ?? 0, input.rawOutputDelta ?? 0, input.rawCachedDelta ?? 0, startedAt, status === "quota_blocked" || status === "completed" || status === "handed_off" ? now : null, now);
|
|
980
|
+
return this.getSession(id);
|
|
981
|
+
}
|
|
982
|
+
getSession(id) {
|
|
983
|
+
const row = this.db.prepare("SELECT * FROM sessions WHERE id = ?").get(id);
|
|
984
|
+
return row ?? null;
|
|
985
|
+
}
|
|
986
|
+
listSessionsByProject(projectId) {
|
|
987
|
+
return this.db.prepare("SELECT * FROM sessions WHERE project_id = ? ORDER BY started_at ASC, last_activity_at ASC").all(projectId);
|
|
988
|
+
}
|
|
989
|
+
getLatestSessionForProject(projectId) {
|
|
990
|
+
const row = this.db.prepare("SELECT * FROM sessions WHERE project_id = ? ORDER BY last_activity_at DESC LIMIT 1").get(projectId);
|
|
991
|
+
return row ?? null;
|
|
992
|
+
}
|
|
993
|
+
saveCapsule(input) {
|
|
994
|
+
const sanitizedPayload = Redactor.sanitizeRecord(input.payload);
|
|
995
|
+
const sanitizedMarkdown = Redactor.sanitize(input.markdown);
|
|
996
|
+
const capsuleTokens = Math.min(2e3, estimateTokens(sanitizedMarkdown));
|
|
997
|
+
const tokensSaved = Math.max(0, input.rawTokensCovered - capsuleTokens);
|
|
998
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
999
|
+
this.db.exec("BEGIN TRANSACTION");
|
|
1000
|
+
try {
|
|
1001
|
+
const versionRow = this.db.prepare("SELECT COALESCE(MAX(version), 0) AS max_ver FROM context_capsules WHERE project_id = ?").get(input.projectId);
|
|
1002
|
+
const nextVersion = versionRow.max_ver + 1;
|
|
1003
|
+
const capsuleId = sanitizedPayload.capsuleId || makeId("cap");
|
|
1004
|
+
sanitizedPayload.capsuleId = capsuleId;
|
|
1005
|
+
sanitizedPayload.telemetry.capsuleTokens = capsuleTokens;
|
|
1006
|
+
sanitizedPayload.telemetry.tokensSaved = tokensSaved;
|
|
1007
|
+
this.db.prepare("UPDATE context_capsules SET is_active = 0 WHERE project_id = ?").run(input.projectId);
|
|
1008
|
+
this.db.prepare(`INSERT INTO context_capsules (
|
|
1009
|
+
id, project_id, session_id, version, trigger_reason, git_branch, git_head_sha, is_dirty_tree,
|
|
1010
|
+
goal_summary, capsule_json, capsule_markdown, raw_tokens_covered, capsule_tokens, tokens_saved,
|
|
1011
|
+
source_chain_json, is_active, created_at
|
|
1012
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?)`).run(capsuleId, input.projectId, input.sessionId, nextVersion, input.triggerReason, input.gitBranch, input.gitHeadSha, input.isDirtyTree ? 1 : 0, sanitizedPayload.goal.summary, JSON.stringify(sanitizedPayload), sanitizedMarkdown, input.rawTokensCovered, capsuleTokens, tokensSaved, JSON.stringify(input.sourceChain), now);
|
|
1013
|
+
if (input.snapshots && input.snapshots.length > 0) {
|
|
1014
|
+
const insertSnap = this.db.prepare(`INSERT INTO file_snapshots (
|
|
1015
|
+
id, project_id, session_id, capsule_id, file_path, change_status, line_ranges_json,
|
|
1016
|
+
lines_added, lines_removed, progress_note, content_sha256, unified_diff, captured_at
|
|
1017
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
1018
|
+
for (const snap of input.snapshots) {
|
|
1019
|
+
insertSnap.run(makeId("snap"), input.projectId, input.sessionId, capsuleId, snap.filePath, snap.changeStatus, JSON.stringify(snap.lineRanges), snap.linesAdded, snap.linesRemoved, Redactor.sanitize(snap.progressNote), snap.contentSha256, Redactor.sanitize(snap.unifiedDiff.slice(0, 65536)), now);
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
this.db.prepare("UPDATE projects SET active_branch = ?, updated_at = ? WHERE id = ?").run(input.gitBranch, now, input.projectId);
|
|
1023
|
+
this.db.exec("COMMIT");
|
|
1024
|
+
return this.getCapsuleById(capsuleId);
|
|
1025
|
+
} catch (err) {
|
|
1026
|
+
this.db.exec("ROLLBACK");
|
|
1027
|
+
throw err;
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
getActiveCapsule(projectId) {
|
|
1031
|
+
const row = this.db.prepare("SELECT * FROM context_capsules WHERE project_id = ? AND is_active = 1 ORDER BY version DESC LIMIT 1").get(projectId);
|
|
1032
|
+
return row ?? null;
|
|
1033
|
+
}
|
|
1034
|
+
getCapsuleById(id) {
|
|
1035
|
+
const row = this.db.prepare("SELECT * FROM context_capsules WHERE id = ? LIMIT 1").get(id);
|
|
1036
|
+
return row ?? null;
|
|
1037
|
+
}
|
|
1038
|
+
listCapsulesByProject(projectId) {
|
|
1039
|
+
return this.db.prepare("SELECT * FROM context_capsules WHERE project_id = ? ORDER BY version ASC").all(projectId);
|
|
1040
|
+
}
|
|
1041
|
+
addDecisionLog(input) {
|
|
1042
|
+
const sanitizedTitle = Redactor.sanitize(input.title);
|
|
1043
|
+
const sanitizedBody = Redactor.sanitize(input.body);
|
|
1044
|
+
const sanitizedRationale = Redactor.sanitize(input.rationale ?? "");
|
|
1045
|
+
if (input.category === "dead_end" && input.errorFingerprint) {
|
|
1046
|
+
const existing = this.db.prepare(`SELECT * FROM decision_logs
|
|
1047
|
+
WHERE project_id = ? AND category = 'dead_end' AND error_fingerprint = ? AND is_superseded = 0
|
|
1048
|
+
ORDER BY created_at DESC LIMIT 1`).get(input.projectId, input.errorFingerprint);
|
|
1049
|
+
if (existing) {
|
|
1050
|
+
this.db.prepare("UPDATE decision_logs SET retry_count = retry_count + 1, body = ? WHERE id = ?").run(sanitizedBody, existing.id);
|
|
1051
|
+
return this.db.prepare("SELECT * FROM decision_logs WHERE id = ?").get(existing.id);
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
const id = makeId("dec");
|
|
1055
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1056
|
+
this.db.prepare(`INSERT INTO decision_logs (
|
|
1057
|
+
id, project_id, session_id, capsule_id, cli_source, category, title, body, rationale,
|
|
1058
|
+
error_fingerprint, retry_count, file_refs_json, is_pinned, is_superseded, is_resolved, created_at
|
|
1059
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, 0, ?, ?)`).run(id, input.projectId, input.sessionId, input.capsuleId ?? null, input.cliSource, input.category, sanitizedTitle, sanitizedBody, sanitizedRationale, input.errorFingerprint ?? null, JSON.stringify(input.fileRefs ?? []), input.isPinned ? 1 : 0, input.isResolved ? 1 : 0, now);
|
|
1060
|
+
return this.db.prepare("SELECT * FROM decision_logs WHERE id = ?").get(id);
|
|
1061
|
+
}
|
|
1062
|
+
listDecisionsByProject(projectId, includeSuperseded = false) {
|
|
1063
|
+
const sql = includeSuperseded ? "SELECT * FROM decision_logs WHERE project_id = ? ORDER BY created_at DESC" : "SELECT * FROM decision_logs WHERE project_id = ? AND is_superseded = 0 ORDER BY is_pinned DESC, created_at DESC";
|
|
1064
|
+
return this.db.prepare(sql).all(projectId);
|
|
1065
|
+
}
|
|
1066
|
+
supersedeDecision(oldId, supersededById) {
|
|
1067
|
+
this.db.prepare("UPDATE decision_logs SET is_superseded = 1, superseded_by_id = ? WHERE id = ?").run(supersededById, oldId);
|
|
1068
|
+
}
|
|
1069
|
+
listSnapshotsByCapsule(capsuleId) {
|
|
1070
|
+
return this.db.prepare("SELECT * FROM file_snapshots WHERE capsule_id = ? ORDER BY file_path ASC").all(capsuleId);
|
|
1071
|
+
}
|
|
1072
|
+
listSnapshotsByProject(projectId) {
|
|
1073
|
+
return this.db.prepare("SELECT * FROM file_snapshots WHERE project_id = ? ORDER BY captured_at DESC, file_path ASC").all(projectId);
|
|
1074
|
+
}
|
|
1075
|
+
getSnapshotById(id) {
|
|
1076
|
+
const row = this.db.prepare("SELECT * FROM file_snapshots WHERE id = ? LIMIT 1").get(id);
|
|
1077
|
+
return row ?? null;
|
|
1078
|
+
}
|
|
1079
|
+
recordHandoff(input) {
|
|
1080
|
+
const id = makeId("hoff");
|
|
1081
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1082
|
+
this.db.prepare(`INSERT INTO handoff_events (
|
|
1083
|
+
id, project_id, capsule_id, from_session_id, to_session_id,
|
|
1084
|
+
from_cli, to_cli, from_account, to_account, reason, delivery_method,
|
|
1085
|
+
injected_tokens, raw_tokens_avoided, handoff_command, created_at
|
|
1086
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(id, input.projectId, input.capsuleId, input.fromSessionId ?? null, input.toSessionId ?? null, input.fromCli, input.toCli, input.fromAccount ?? "default", input.toAccount ?? "default", input.reason, input.deliveryMethod, input.injectedTokens, input.rawTokensAvoided, Redactor.sanitize(input.handoffCommand), now);
|
|
1087
|
+
return this.db.prepare("SELECT * FROM handoff_events WHERE id = ?").get(id);
|
|
1088
|
+
}
|
|
1089
|
+
listHandoffsByProject(projectId) {
|
|
1090
|
+
return this.db.prepare("SELECT * FROM handoff_events WHERE project_id = ? ORDER BY created_at ASC").all(projectId);
|
|
1091
|
+
}
|
|
1092
|
+
getCursor(filePath) {
|
|
1093
|
+
const row = this.db.prepare("SELECT * FROM adapter_cursors WHERE file_path = ? LIMIT 1").get(filePath);
|
|
1094
|
+
return row ?? null;
|
|
1095
|
+
}
|
|
1096
|
+
upsertCursor(cursor) {
|
|
1097
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1098
|
+
this.db.prepare(`INSERT INTO adapter_cursors (file_path, cli_source, inode, byte_offset, last_item_index, content_sha256, mtime_ms, updated_at)
|
|
1099
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
1100
|
+
ON CONFLICT(file_path) DO UPDATE SET
|
|
1101
|
+
cli_source = excluded.cli_source,
|
|
1102
|
+
inode = excluded.inode,
|
|
1103
|
+
byte_offset = excluded.byte_offset,
|
|
1104
|
+
last_item_index = excluded.last_item_index,
|
|
1105
|
+
content_sha256 = excluded.content_sha256,
|
|
1106
|
+
mtime_ms = excluded.mtime_ms,
|
|
1107
|
+
updated_at = excluded.updated_at`).run(cursor.file_path, cursor.cli_source, cursor.inode, cursor.byte_offset, cursor.last_item_index, cursor.content_sha256, cursor.mtime_ms, now);
|
|
1108
|
+
}
|
|
1109
|
+
searchMemory(params) {
|
|
1110
|
+
const page = Math.max(1, params.page ?? 1);
|
|
1111
|
+
const pageSize = Math.min(50, Math.max(1, params.pageSize ?? 20));
|
|
1112
|
+
const offset = (page - 1) * pageSize;
|
|
1113
|
+
const ftsQuery = sanitizeFtsQuery(params.query);
|
|
1114
|
+
if (!ftsQuery) {
|
|
1115
|
+
return { hits: [], total: 0, page, pageSize };
|
|
1116
|
+
}
|
|
1117
|
+
const whereClauses = ["memory_fts MATCH ?"];
|
|
1118
|
+
const bindArgs = [ftsQuery];
|
|
1119
|
+
if (params.projectId) {
|
|
1120
|
+
whereClauses.push("f.project_id = ?");
|
|
1121
|
+
bindArgs.push(params.projectId);
|
|
1122
|
+
}
|
|
1123
|
+
if (params.cliSource) {
|
|
1124
|
+
whereClauses.push("f.cli_source LIKE ?");
|
|
1125
|
+
bindArgs.push(`%${params.cliSource}%`);
|
|
1126
|
+
}
|
|
1127
|
+
if (params.category) {
|
|
1128
|
+
whereClauses.push("f.category = ?");
|
|
1129
|
+
bindArgs.push(params.category);
|
|
1130
|
+
}
|
|
1131
|
+
const whereSql = whereClauses.join(" AND ");
|
|
1132
|
+
const countRow = this.db.prepare(`SELECT COUNT(*) AS cnt FROM memory_fts f WHERE ${whereSql}`).get(...bindArgs);
|
|
1133
|
+
const rows = this.db.prepare(`SELECT
|
|
1134
|
+
f.entity_type,
|
|
1135
|
+
f.entity_id,
|
|
1136
|
+
f.project_id,
|
|
1137
|
+
COALESCE(p.name, f.project_id) AS project_name,
|
|
1138
|
+
f.session_id,
|
|
1139
|
+
f.cli_source,
|
|
1140
|
+
f.category,
|
|
1141
|
+
f.title,
|
|
1142
|
+
snippet(memory_fts, 7, '\xAB', '\xBB', '\u2026', 24) AS snippet,
|
|
1143
|
+
f.file_refs,
|
|
1144
|
+
bm25(memory_fts, 0.5, 0.5, 2.0, 1.0, 0.8) AS bm25_score,
|
|
1145
|
+
COALESCE(d.created_at, c.created_at, '') AS created_at
|
|
1146
|
+
FROM memory_fts f
|
|
1147
|
+
LEFT JOIN projects p ON p.id = f.project_id
|
|
1148
|
+
LEFT JOIN decision_logs d ON f.entity_type = 'decision' AND d.id = f.entity_id
|
|
1149
|
+
LEFT JOIN context_capsules c ON f.entity_type = 'capsule' AND c.id = f.entity_id
|
|
1150
|
+
WHERE ${whereSql}
|
|
1151
|
+
ORDER BY bm25_score ASC
|
|
1152
|
+
LIMIT ? OFFSET ?`).all(...bindArgs, pageSize, offset);
|
|
1153
|
+
return {
|
|
1154
|
+
hits: rows,
|
|
1155
|
+
total: countRow.cnt,
|
|
1156
|
+
page,
|
|
1157
|
+
pageSize
|
|
1158
|
+
};
|
|
1159
|
+
}
|
|
1160
|
+
};
|
|
1161
|
+
|
|
1162
|
+
// packages/adapters/dist/quota-detector.js
|
|
1163
|
+
var QUOTA_PATTERNS = [
|
|
1164
|
+
{
|
|
1165
|
+
limitType: "5h_window",
|
|
1166
|
+
pattern: /(?:5[-\s]?hour|five[-\s]?hour|session usage)\s+(?:limit|cap|quota)|usage limit reached.*resets/i
|
|
1167
|
+
},
|
|
1168
|
+
{
|
|
1169
|
+
limitType: "weekly_cap",
|
|
1170
|
+
pattern: /(?:weekly|7[-\s]?day)\s+(?:usage\s+)?(?:limit|cap|quota)|opus\s+weekly\s+limit/i
|
|
1171
|
+
},
|
|
1172
|
+
{
|
|
1173
|
+
limitType: "insufficient_quota",
|
|
1174
|
+
pattern: /insufficient_quota|exceeded your current quota|billing hard limit/i
|
|
1175
|
+
},
|
|
1176
|
+
{
|
|
1177
|
+
limitType: "rpm_429",
|
|
1178
|
+
pattern: /rate_limit_error|RESOURCE_EXHAUSTED|too many requests|\bHTTP\s*429\b|\bstatus[:\s]+429\b/i
|
|
1179
|
+
}
|
|
1180
|
+
];
|
|
1181
|
+
function detectQuotaSignal(text) {
|
|
1182
|
+
if (!text)
|
|
1183
|
+
return void 0;
|
|
1184
|
+
for (const { limitType, pattern } of QUOTA_PATTERNS) {
|
|
1185
|
+
if (pattern.test(text)) {
|
|
1186
|
+
const isoMatch = text.match(/\b(20\d{2}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)\b/);
|
|
1187
|
+
return {
|
|
1188
|
+
detected: true,
|
|
1189
|
+
limitType,
|
|
1190
|
+
resetAtIso: isoMatch?.[1],
|
|
1191
|
+
rawMessage: text.slice(0, 320).trim()
|
|
1192
|
+
};
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
return void 0;
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
// packages/adapters/dist/drivers/jsonl-adapters.js
|
|
1199
|
+
function findGitOrPackageRoot(filePath) {
|
|
1200
|
+
let curr = dirname2(filePath);
|
|
1201
|
+
for (let i = 0; i < 6; i++) {
|
|
1202
|
+
if (existsSync(join2(curr, ".git")) || existsSync(join2(curr, "package.json"))) {
|
|
1203
|
+
return curr;
|
|
1204
|
+
}
|
|
1205
|
+
const parent = dirname2(curr);
|
|
1206
|
+
if (parent === curr)
|
|
1207
|
+
break;
|
|
1208
|
+
curr = parent;
|
|
1209
|
+
}
|
|
1210
|
+
return null;
|
|
1211
|
+
}
|
|
1212
|
+
function safeJsonParse(line) {
|
|
1213
|
+
try {
|
|
1214
|
+
const parsed = JSON.parse(line);
|
|
1215
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
1216
|
+
return parsed;
|
|
1217
|
+
}
|
|
1218
|
+
return null;
|
|
1219
|
+
} catch {
|
|
1220
|
+
return null;
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
function extractFilesFromArgs(args) {
|
|
1224
|
+
if (!args)
|
|
1225
|
+
return [];
|
|
1226
|
+
const files = [];
|
|
1227
|
+
for (const key of ["Path", "file_path", "path", "target_file", "TargetFile"]) {
|
|
1228
|
+
const val = args[key];
|
|
1229
|
+
if (typeof val === "string" && val.length > 0) {
|
|
1230
|
+
files.push(val.replace(/^"|"$/g, ""));
|
|
1231
|
+
}
|
|
1232
|
+
}
|
|
1233
|
+
return files;
|
|
1234
|
+
}
|
|
1235
|
+
function extractExitCode(text) {
|
|
1236
|
+
const match = text.match(/Command exited with code (\d+)/i) ?? text.match(/exit(?:ed)?(?:\s+with)?\s+code[:\s]+(\d+)/i);
|
|
1237
|
+
if (!match?.[1])
|
|
1238
|
+
return void 0;
|
|
1239
|
+
return Number(match[1]);
|
|
1240
|
+
}
|
|
1241
|
+
function inferAgySessionId(filePath) {
|
|
1242
|
+
const logsDir = dirname2(filePath);
|
|
1243
|
+
const sysDir = dirname2(logsDir);
|
|
1244
|
+
const convDir = dirname2(sysDir);
|
|
1245
|
+
const candidate = basename2(convDir);
|
|
1246
|
+
return candidate && candidate !== "." ? candidate : basename2(filePath, ".jsonl");
|
|
1247
|
+
}
|
|
1248
|
+
function parseAgyLines(lines, filePath) {
|
|
1249
|
+
const externalSessionId = inferAgySessionId(filePath);
|
|
1250
|
+
const events = [];
|
|
1251
|
+
let inferredRoot = null;
|
|
1252
|
+
for (const line of lines) {
|
|
1253
|
+
const raw = safeJsonParse(line);
|
|
1254
|
+
if (!raw)
|
|
1255
|
+
continue;
|
|
1256
|
+
const stepIndex = typeof raw.step_index === "number" ? raw.step_index : events.length;
|
|
1257
|
+
const type = String(raw.type ?? "");
|
|
1258
|
+
const source = String(raw.source ?? "");
|
|
1259
|
+
const content = Redactor.sanitize(typeof raw.content === "string" ? raw.content : "");
|
|
1260
|
+
const timestampIso = typeof raw.created_at === "string" ? raw.created_at : (/* @__PURE__ */ new Date()).toISOString();
|
|
1261
|
+
const modelName = typeof raw.model === "string" ? raw.model : null;
|
|
1262
|
+
const rawToolCalls = Array.isArray(raw.tool_calls) ? raw.tool_calls : [];
|
|
1263
|
+
const referencedFiles = [];
|
|
1264
|
+
for (const tc of rawToolCalls) {
|
|
1265
|
+
if (tc && typeof tc === "object") {
|
|
1266
|
+
const args = tc.args;
|
|
1267
|
+
for (const f of extractFilesFromArgs(args)) {
|
|
1268
|
+
referencedFiles.push(f);
|
|
1269
|
+
if (!inferredRoot && f.includes("/")) {
|
|
1270
|
+
const foundRoot = findGitOrPackageRoot(f);
|
|
1271
|
+
if (foundRoot) {
|
|
1272
|
+
inferredRoot = foundRoot;
|
|
1273
|
+
} else {
|
|
1274
|
+
const parts = f.split("/");
|
|
1275
|
+
const idx = parts.findIndex((p) => p === "src" || p === "packages" || p === "tests");
|
|
1276
|
+
if (idx > 1)
|
|
1277
|
+
inferredRoot = parts.slice(0, idx).join("/");
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1283
|
+
const input = typeof raw.input_tokens === "number" ? raw.input_tokens : 0;
|
|
1284
|
+
const output = typeof raw.output_tokens === "number" ? raw.output_tokens : 0;
|
|
1285
|
+
const cached = typeof raw.cache_read_tokens === "number" ? raw.cache_read_tokens : 0;
|
|
1286
|
+
const exitCode = extractExitCode(content);
|
|
1287
|
+
const quotaSignal = detectQuotaSignal(content);
|
|
1288
|
+
let role = "assistant";
|
|
1289
|
+
if (source === "USER_EXPLICIT" || type === "USER_INPUT") {
|
|
1290
|
+
role = "user";
|
|
1291
|
+
} else if (type === "GENERIC") {
|
|
1292
|
+
role = exitCode !== void 0 && exitCode !== 0 ? "system_error" : "tool_result";
|
|
1293
|
+
} else if (rawToolCalls.length > 0 && !content) {
|
|
1294
|
+
role = "tool_call";
|
|
1295
|
+
}
|
|
1296
|
+
events.push({
|
|
1297
|
+
externalEventId: `${externalSessionId}:${stepIndex}`,
|
|
1298
|
+
cliSource: "agy",
|
|
1299
|
+
externalSessionId,
|
|
1300
|
+
projectRoot: inferredRoot,
|
|
1301
|
+
gitBranch: null,
|
|
1302
|
+
modelName,
|
|
1303
|
+
accountLabel: null,
|
|
1304
|
+
role,
|
|
1305
|
+
timestampIso,
|
|
1306
|
+
textContent: content,
|
|
1307
|
+
toolExitCode: exitCode,
|
|
1308
|
+
filesReferenced: referencedFiles,
|
|
1309
|
+
tokenUsage: input + output + cached > 0 ? { input, output, cached } : void 0,
|
|
1310
|
+
quotaSignal
|
|
1311
|
+
});
|
|
1312
|
+
}
|
|
1313
|
+
return events;
|
|
1314
|
+
}
|
|
1315
|
+
function parseClaudeLines(lines, filePath) {
|
|
1316
|
+
const fallbackSessionId = basename2(filePath, ".jsonl");
|
|
1317
|
+
const events = [];
|
|
1318
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1319
|
+
const raw = safeJsonParse(lines[i]);
|
|
1320
|
+
if (!raw)
|
|
1321
|
+
continue;
|
|
1322
|
+
const externalSessionId = typeof raw.sessionId === "string" ? raw.sessionId : fallbackSessionId;
|
|
1323
|
+
const eventId = typeof raw.uuid === "string" ? raw.uuid : `${externalSessionId}:${i}`;
|
|
1324
|
+
const projectRoot = typeof raw.cwd === "string" ? raw.cwd : null;
|
|
1325
|
+
const gitBranch = typeof raw.gitBranch === "string" ? raw.gitBranch : null;
|
|
1326
|
+
const timestampIso = typeof raw.timestamp === "string" ? raw.timestamp : (/* @__PURE__ */ new Date()).toISOString();
|
|
1327
|
+
const rawType = String(raw.type ?? "");
|
|
1328
|
+
const msg = raw.message && typeof raw.message === "object" ? raw.message : {};
|
|
1329
|
+
const modelName = typeof msg.model === "string" ? msg.model : null;
|
|
1330
|
+
const usage = msg.usage && typeof msg.usage === "object" ? msg.usage : {};
|
|
1331
|
+
const textParts = [];
|
|
1332
|
+
const filesReferenced = [];
|
|
1333
|
+
let toolName;
|
|
1334
|
+
let toolExitCode;
|
|
1335
|
+
let role = rawType === "user" ? "user" : "assistant";
|
|
1336
|
+
if (typeof msg.content === "string") {
|
|
1337
|
+
textParts.push(msg.content);
|
|
1338
|
+
} else if (Array.isArray(msg.content)) {
|
|
1339
|
+
for (const block of msg.content) {
|
|
1340
|
+
if (!block || typeof block !== "object")
|
|
1341
|
+
continue;
|
|
1342
|
+
const b = block;
|
|
1343
|
+
if (b.type === "text" && typeof b.text === "string") {
|
|
1344
|
+
textParts.push(b.text);
|
|
1345
|
+
} else if (b.type === "tool_use") {
|
|
1346
|
+
toolName = typeof b.name === "string" ? b.name : toolName;
|
|
1347
|
+
const inp = b.input && typeof b.input === "object" ? b.input : void 0;
|
|
1348
|
+
filesReferenced.push(...extractFilesFromArgs(inp));
|
|
1349
|
+
if (textParts.length === 0)
|
|
1350
|
+
role = "tool_call";
|
|
1351
|
+
} else if (b.type === "tool_result") {
|
|
1352
|
+
role = b.is_error === true ? "system_error" : "tool_result";
|
|
1353
|
+
if (b.is_error === true)
|
|
1354
|
+
toolExitCode = 1;
|
|
1355
|
+
if (typeof b.content === "string")
|
|
1356
|
+
textParts.push(b.content);
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
if (raw.isApiErrorMessage === true || rawType === "system") {
|
|
1361
|
+
const joined = textParts.join("\n");
|
|
1362
|
+
if (detectQuotaSignal(joined)) {
|
|
1363
|
+
role = "system_error";
|
|
1364
|
+
}
|
|
1365
|
+
}
|
|
1366
|
+
const textContent = Redactor.sanitize(textParts.join("\n").trim());
|
|
1367
|
+
if (toolExitCode === void 0) {
|
|
1368
|
+
toolExitCode = extractExitCode(textContent);
|
|
1369
|
+
}
|
|
1370
|
+
const quotaSignal = detectQuotaSignal(textContent);
|
|
1371
|
+
const input = typeof usage.input_tokens === "number" ? usage.input_tokens : 0;
|
|
1372
|
+
const output = typeof usage.output_tokens === "number" ? usage.output_tokens : 0;
|
|
1373
|
+
const cached = typeof usage.cache_read_input_tokens === "number" ? usage.cache_read_input_tokens : 0;
|
|
1374
|
+
events.push({
|
|
1375
|
+
externalEventId: eventId,
|
|
1376
|
+
cliSource: "claude",
|
|
1377
|
+
externalSessionId,
|
|
1378
|
+
projectRoot,
|
|
1379
|
+
gitBranch,
|
|
1380
|
+
modelName,
|
|
1381
|
+
accountLabel: null,
|
|
1382
|
+
role,
|
|
1383
|
+
timestampIso,
|
|
1384
|
+
textContent,
|
|
1385
|
+
toolName,
|
|
1386
|
+
toolExitCode,
|
|
1387
|
+
filesReferenced,
|
|
1388
|
+
tokenUsage: input + output + cached > 0 ? { input, output, cached } : void 0,
|
|
1389
|
+
quotaSignal
|
|
1390
|
+
});
|
|
1391
|
+
}
|
|
1392
|
+
return events;
|
|
1393
|
+
}
|
|
1394
|
+
function parseCodexLines(lines, filePath) {
|
|
1395
|
+
let externalSessionId = basename2(filePath, ".jsonl");
|
|
1396
|
+
let projectRoot = null;
|
|
1397
|
+
let gitBranch = null;
|
|
1398
|
+
let modelName = "gpt-5-codex";
|
|
1399
|
+
const events = [];
|
|
1400
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1401
|
+
const raw = safeJsonParse(lines[i]);
|
|
1402
|
+
if (!raw)
|
|
1403
|
+
continue;
|
|
1404
|
+
const timestampIso = typeof raw.timestamp === "string" ? raw.timestamp : (/* @__PURE__ */ new Date()).toISOString();
|
|
1405
|
+
const recordType = String(raw.type ?? "");
|
|
1406
|
+
const payload = raw.payload && typeof raw.payload === "object" ? raw.payload : raw;
|
|
1407
|
+
if (recordType === "session_meta") {
|
|
1408
|
+
if (typeof payload.id === "string")
|
|
1409
|
+
externalSessionId = payload.id;
|
|
1410
|
+
if (typeof payload.cwd === "string")
|
|
1411
|
+
projectRoot = payload.cwd;
|
|
1412
|
+
if (typeof payload.model === "string")
|
|
1413
|
+
modelName = payload.model;
|
|
1414
|
+
const git = payload.git;
|
|
1415
|
+
if (git && typeof git.branch === "string")
|
|
1416
|
+
gitBranch = git.branch;
|
|
1417
|
+
continue;
|
|
1418
|
+
}
|
|
1419
|
+
if (recordType === "response_item") {
|
|
1420
|
+
const itemType = String(payload.type ?? "");
|
|
1421
|
+
if (itemType === "message") {
|
|
1422
|
+
const msgRole = payload.role === "user" ? "user" : "assistant";
|
|
1423
|
+
const contentArr = Array.isArray(payload.content) ? payload.content : [];
|
|
1424
|
+
const text = contentArr.map((c) => c && typeof c === "object" && typeof c.text === "string" ? c.text : "").filter(Boolean).join("\n");
|
|
1425
|
+
const sanitized = Redactor.sanitize(text);
|
|
1426
|
+
events.push({
|
|
1427
|
+
externalEventId: `${externalSessionId}:${i}`,
|
|
1428
|
+
cliSource: "codex",
|
|
1429
|
+
externalSessionId,
|
|
1430
|
+
projectRoot,
|
|
1431
|
+
gitBranch,
|
|
1432
|
+
modelName,
|
|
1433
|
+
accountLabel: null,
|
|
1434
|
+
role: msgRole,
|
|
1435
|
+
timestampIso,
|
|
1436
|
+
textContent: sanitized,
|
|
1437
|
+
quotaSignal: detectQuotaSignal(sanitized)
|
|
1438
|
+
});
|
|
1439
|
+
} else if (itemType === "function_call") {
|
|
1440
|
+
const name = typeof payload.name === "string" ? payload.name : "shell";
|
|
1441
|
+
const argsStr = typeof payload.arguments === "string" ? payload.arguments : "";
|
|
1442
|
+
const parsedArgs = safeJsonParse(argsStr) ?? void 0;
|
|
1443
|
+
events.push({
|
|
1444
|
+
externalEventId: `${externalSessionId}:${i}`,
|
|
1445
|
+
cliSource: "codex",
|
|
1446
|
+
externalSessionId,
|
|
1447
|
+
projectRoot,
|
|
1448
|
+
gitBranch,
|
|
1449
|
+
modelName,
|
|
1450
|
+
accountLabel: null,
|
|
1451
|
+
role: "tool_call",
|
|
1452
|
+
timestampIso,
|
|
1453
|
+
textContent: Redactor.sanitize(argsStr),
|
|
1454
|
+
toolName: name,
|
|
1455
|
+
toolArgs: parsedArgs,
|
|
1456
|
+
filesReferenced: extractFilesFromArgs(parsedArgs)
|
|
1457
|
+
});
|
|
1458
|
+
} else if (itemType === "function_call_output") {
|
|
1459
|
+
const output = Redactor.sanitize(typeof payload.output === "string" ? payload.output : "");
|
|
1460
|
+
const exitCode = extractExitCode(output);
|
|
1461
|
+
events.push({
|
|
1462
|
+
externalEventId: `${externalSessionId}:${i}`,
|
|
1463
|
+
cliSource: "codex",
|
|
1464
|
+
externalSessionId,
|
|
1465
|
+
projectRoot,
|
|
1466
|
+
gitBranch,
|
|
1467
|
+
modelName,
|
|
1468
|
+
accountLabel: null,
|
|
1469
|
+
role: exitCode !== void 0 && exitCode !== 0 ? "system_error" : "tool_result",
|
|
1470
|
+
timestampIso,
|
|
1471
|
+
textContent: output,
|
|
1472
|
+
toolExitCode: exitCode,
|
|
1473
|
+
quotaSignal: detectQuotaSignal(output)
|
|
1474
|
+
});
|
|
1475
|
+
}
|
|
1476
|
+
continue;
|
|
1477
|
+
}
|
|
1478
|
+
if (recordType === "event_msg") {
|
|
1479
|
+
const evType = String(payload.type ?? "");
|
|
1480
|
+
if (evType === "token_count" && payload.info && typeof payload.info === "object") {
|
|
1481
|
+
const info = payload.info;
|
|
1482
|
+
const total = info.last_token_usage ?? info.total_token_usage;
|
|
1483
|
+
if (total) {
|
|
1484
|
+
events.push({
|
|
1485
|
+
externalEventId: `${externalSessionId}:tok:${i}`,
|
|
1486
|
+
cliSource: "codex",
|
|
1487
|
+
externalSessionId,
|
|
1488
|
+
projectRoot,
|
|
1489
|
+
gitBranch,
|
|
1490
|
+
modelName,
|
|
1491
|
+
accountLabel: null,
|
|
1492
|
+
role: "assistant",
|
|
1493
|
+
timestampIso,
|
|
1494
|
+
textContent: "",
|
|
1495
|
+
tokenUsage: {
|
|
1496
|
+
input: Number(total.input_tokens ?? 0),
|
|
1497
|
+
output: Number(total.output_tokens ?? 0),
|
|
1498
|
+
cached: Number(total.cached_input_tokens ?? 0)
|
|
1499
|
+
}
|
|
1500
|
+
});
|
|
1501
|
+
}
|
|
1502
|
+
} else if (evType === "error" || evType === "turn_aborted") {
|
|
1503
|
+
const msg = Redactor.sanitize(String(payload.message ?? payload.reason ?? ""));
|
|
1504
|
+
events.push({
|
|
1505
|
+
externalEventId: `${externalSessionId}:err:${i}`,
|
|
1506
|
+
cliSource: "codex",
|
|
1507
|
+
externalSessionId,
|
|
1508
|
+
projectRoot,
|
|
1509
|
+
gitBranch,
|
|
1510
|
+
modelName,
|
|
1511
|
+
accountLabel: null,
|
|
1512
|
+
role: "system_error",
|
|
1513
|
+
timestampIso,
|
|
1514
|
+
textContent: msg,
|
|
1515
|
+
toolExitCode: 1,
|
|
1516
|
+
quotaSignal: detectQuotaSignal(msg)
|
|
1517
|
+
});
|
|
1518
|
+
}
|
|
1519
|
+
}
|
|
1520
|
+
}
|
|
1521
|
+
return events;
|
|
1522
|
+
}
|
|
1523
|
+
function parseJsonlBySource(cliSource, lines, filePath) {
|
|
1524
|
+
switch (cliSource) {
|
|
1525
|
+
case "agy":
|
|
1526
|
+
return parseAgyLines(lines, filePath);
|
|
1527
|
+
case "claude":
|
|
1528
|
+
return parseClaudeLines(lines, filePath);
|
|
1529
|
+
case "codex":
|
|
1530
|
+
return parseCodexLines(lines, filePath);
|
|
1531
|
+
}
|
|
1532
|
+
}
|
|
1533
|
+
|
|
1534
|
+
// packages/adapters/dist/drivers/snapshot-adapters.js
|
|
1535
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
1536
|
+
import { existsSync as existsSync2, readFileSync, statSync } from "node:fs";
|
|
1537
|
+
import { basename as basename3, dirname as dirname3, join as join3 } from "node:path";
|
|
1538
|
+
import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
|
|
1539
|
+
function readGeminiSnapshotIncremental(filePath, store) {
|
|
1540
|
+
const rawText = readFileSync(filePath, "utf8");
|
|
1541
|
+
const hash = createHash2("sha256").update(rawText).digest("hex").slice(0, 16);
|
|
1542
|
+
const prev = store.getCursor(filePath);
|
|
1543
|
+
if (prev && prev.content_sha256 === hash) {
|
|
1544
|
+
return [];
|
|
1545
|
+
}
|
|
1546
|
+
let parsed;
|
|
1547
|
+
try {
|
|
1548
|
+
parsed = JSON.parse(rawText);
|
|
1549
|
+
} catch {
|
|
1550
|
+
return [];
|
|
1551
|
+
}
|
|
1552
|
+
const messages = Array.isArray(parsed.messages) ? parsed.messages : [];
|
|
1553
|
+
const startIndex = prev && prev.last_item_index <= messages.length ? prev.last_item_index : 0;
|
|
1554
|
+
const externalSessionId = parsed.sessionId ?? basename3(filePath, ".json");
|
|
1555
|
+
const projectRoot = typeof parsed.cwd === "string" ? parsed.cwd : null;
|
|
1556
|
+
const events = [];
|
|
1557
|
+
for (let i = startIndex; i < messages.length; i++) {
|
|
1558
|
+
const msg = messages[i];
|
|
1559
|
+
if (!msg)
|
|
1560
|
+
continue;
|
|
1561
|
+
let text = "";
|
|
1562
|
+
if (typeof msg.content === "string") {
|
|
1563
|
+
text = msg.content;
|
|
1564
|
+
} else if (Array.isArray(msg.content)) {
|
|
1565
|
+
text = msg.content.map((p) => p.text ?? "").filter(Boolean).join("\n");
|
|
1566
|
+
}
|
|
1567
|
+
const sanitized = Redactor.sanitize(text);
|
|
1568
|
+
const quotaSignal = detectQuotaSignal(sanitized);
|
|
1569
|
+
const role = msg.type === "user" ? "user" : msg.type === "error" ? "system_error" : "assistant";
|
|
1570
|
+
const filesReferenced = [];
|
|
1571
|
+
if (Array.isArray(msg.toolCalls)) {
|
|
1572
|
+
for (const tc of msg.toolCalls) {
|
|
1573
|
+
const argPath = tc.args?.file_path ?? tc.args?.path;
|
|
1574
|
+
if (typeof argPath === "string")
|
|
1575
|
+
filesReferenced.push(argPath);
|
|
1576
|
+
}
|
|
1577
|
+
}
|
|
1578
|
+
events.push({
|
|
1579
|
+
externalEventId: msg.id ?? `${externalSessionId}:${i}`,
|
|
1580
|
+
cliSource: "gemini",
|
|
1581
|
+
externalSessionId,
|
|
1582
|
+
projectRoot,
|
|
1583
|
+
gitBranch: null,
|
|
1584
|
+
modelName: msg.model ?? "gemini-2.5-pro",
|
|
1585
|
+
accountLabel: null,
|
|
1586
|
+
role,
|
|
1587
|
+
timestampIso: msg.timestamp ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
1588
|
+
textContent: sanitized,
|
|
1589
|
+
toolExitCode: msg.type === "error" ? 1 : void 0,
|
|
1590
|
+
filesReferenced,
|
|
1591
|
+
tokenUsage: msg.tokens ? {
|
|
1592
|
+
input: msg.tokens.input ?? 0,
|
|
1593
|
+
output: msg.tokens.output ?? 0,
|
|
1594
|
+
cached: msg.tokens.cached ?? 0
|
|
1595
|
+
} : void 0,
|
|
1596
|
+
quotaSignal
|
|
1597
|
+
});
|
|
1598
|
+
}
|
|
1599
|
+
const stat = statSync(filePath);
|
|
1600
|
+
store.upsertCursor({
|
|
1601
|
+
file_path: filePath,
|
|
1602
|
+
cli_source: "gemini",
|
|
1603
|
+
inode: Number(stat.ino),
|
|
1604
|
+
byte_offset: rawText.length,
|
|
1605
|
+
last_item_index: messages.length,
|
|
1606
|
+
content_sha256: hash,
|
|
1607
|
+
mtime_ms: Math.trunc(stat.mtimeMs)
|
|
1608
|
+
});
|
|
1609
|
+
return events;
|
|
1610
|
+
}
|
|
1611
|
+
function resolveCursorWorkspaceRoot(dbPath) {
|
|
1612
|
+
const wsJson = join3(dirname3(dbPath), "workspace.json");
|
|
1613
|
+
if (!existsSync2(wsJson))
|
|
1614
|
+
return null;
|
|
1615
|
+
try {
|
|
1616
|
+
const parsed = JSON.parse(readFileSync(wsJson, "utf8"));
|
|
1617
|
+
if (typeof parsed.folder === "string" && parsed.folder.startsWith("file://")) {
|
|
1618
|
+
return decodeURIComponent(parsed.folder.replace(/^file:\/\//, ""));
|
|
1619
|
+
}
|
|
1620
|
+
return parsed.folder ?? null;
|
|
1621
|
+
} catch {
|
|
1622
|
+
return null;
|
|
1623
|
+
}
|
|
1624
|
+
}
|
|
1625
|
+
function readCursorStateReadOnly(vscdbPath, store) {
|
|
1626
|
+
const stat = statSync(vscdbPath);
|
|
1627
|
+
const mtimeMs = Math.trunc(stat.mtimeMs);
|
|
1628
|
+
const prev = store.getCursor(vscdbPath);
|
|
1629
|
+
if (prev && prev.mtime_ms === mtimeMs) {
|
|
1630
|
+
return [];
|
|
1631
|
+
}
|
|
1632
|
+
const projectRoot = resolveCursorWorkspaceRoot(vscdbPath);
|
|
1633
|
+
const workspaceHash = basename3(dirname3(vscdbPath));
|
|
1634
|
+
const events = [];
|
|
1635
|
+
const cursorDb = new DatabaseSync2(vscdbPath, { readOnly: true });
|
|
1636
|
+
try {
|
|
1637
|
+
const tableRow = cursorDb.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='ItemTable'").get();
|
|
1638
|
+
if (tableRow?.name) {
|
|
1639
|
+
const promptsRow = cursorDb.prepare("SELECT value FROM ItemTable WHERE key = 'aiService.prompts'").get();
|
|
1640
|
+
if (promptsRow?.value) {
|
|
1641
|
+
try {
|
|
1642
|
+
const prompts = JSON.parse(promptsRow.value);
|
|
1643
|
+
const startIdx = prev ? prev.last_item_index : 0;
|
|
1644
|
+
for (let i = startIdx; i < prompts.length; i++) {
|
|
1645
|
+
const text = Redactor.sanitize(prompts[i]?.text ?? "");
|
|
1646
|
+
if (!text)
|
|
1647
|
+
continue;
|
|
1648
|
+
events.push({
|
|
1649
|
+
externalEventId: `cursor:${workspaceHash}:${i}`,
|
|
1650
|
+
cliSource: "cursor",
|
|
1651
|
+
externalSessionId: `cursor-${workspaceHash}`,
|
|
1652
|
+
projectRoot,
|
|
1653
|
+
gitBranch: null,
|
|
1654
|
+
modelName: "cursor-composer",
|
|
1655
|
+
accountLabel: null,
|
|
1656
|
+
role: "user",
|
|
1657
|
+
timestampIso: new Date(mtimeMs).toISOString(),
|
|
1658
|
+
textContent: text,
|
|
1659
|
+
quotaSignal: detectQuotaSignal(text)
|
|
1660
|
+
});
|
|
1661
|
+
}
|
|
1662
|
+
store.upsertCursor({
|
|
1663
|
+
file_path: vscdbPath,
|
|
1664
|
+
cli_source: "cursor",
|
|
1665
|
+
inode: Number(stat.ino),
|
|
1666
|
+
byte_offset: Number(stat.size),
|
|
1667
|
+
last_item_index: prompts.length,
|
|
1668
|
+
content_sha256: `${stat.size}:${mtimeMs}`,
|
|
1669
|
+
mtime_ms: mtimeMs
|
|
1670
|
+
});
|
|
1671
|
+
} catch {
|
|
1672
|
+
}
|
|
1673
|
+
}
|
|
1674
|
+
}
|
|
1675
|
+
} finally {
|
|
1676
|
+
cursorDb.close();
|
|
1677
|
+
}
|
|
1678
|
+
return events;
|
|
1679
|
+
}
|
|
1680
|
+
|
|
1681
|
+
// packages/adapters/dist/tailer.js
|
|
1682
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
1683
|
+
import { openSync, readSync, closeSync, statSync as statSync2 } from "node:fs";
|
|
1684
|
+
var FileTailer = class {
|
|
1685
|
+
store;
|
|
1686
|
+
partialLineBuffer = /* @__PURE__ */ new Map();
|
|
1687
|
+
constructor(store) {
|
|
1688
|
+
this.store = store;
|
|
1689
|
+
}
|
|
1690
|
+
readNewLines(filePath, cliSource) {
|
|
1691
|
+
const stat = statSync2(filePath);
|
|
1692
|
+
const inode = Number(stat.ino);
|
|
1693
|
+
const size = Number(stat.size);
|
|
1694
|
+
const mtimeMs = Math.trunc(stat.mtimeMs);
|
|
1695
|
+
const prev = this.store.getCursor(filePath);
|
|
1696
|
+
let offset = prev?.byte_offset ?? 0;
|
|
1697
|
+
let resetDetected = false;
|
|
1698
|
+
if (!prev || prev.inode !== inode || size < offset) {
|
|
1699
|
+
offset = 0;
|
|
1700
|
+
resetDetected = Boolean(prev);
|
|
1701
|
+
this.partialLineBuffer.delete(filePath);
|
|
1702
|
+
}
|
|
1703
|
+
if (size === offset) {
|
|
1704
|
+
return {
|
|
1705
|
+
filePath,
|
|
1706
|
+
lines: [],
|
|
1707
|
+
newOffset: offset,
|
|
1708
|
+
inode,
|
|
1709
|
+
resetDetected
|
|
1710
|
+
};
|
|
1711
|
+
}
|
|
1712
|
+
const bytesToRead = size - offset;
|
|
1713
|
+
const buffer = Buffer.allocUnsafe(bytesToRead);
|
|
1714
|
+
const fd = openSync(filePath, "r");
|
|
1715
|
+
let bytesRead = 0;
|
|
1716
|
+
try {
|
|
1717
|
+
bytesRead = readSync(fd, buffer, 0, bytesToRead, offset);
|
|
1718
|
+
} finally {
|
|
1719
|
+
closeSync(fd);
|
|
1720
|
+
}
|
|
1721
|
+
const chunkText = buffer.subarray(0, bytesRead).toString("utf8");
|
|
1722
|
+
const bufferedPrefix = this.partialLineBuffer.get(filePath) ?? "";
|
|
1723
|
+
const combined = bufferedPrefix + chunkText;
|
|
1724
|
+
const endsWithNewline = combined.endsWith("\n");
|
|
1725
|
+
const rawParts = combined.split("\n");
|
|
1726
|
+
let completeLines;
|
|
1727
|
+
if (endsWithNewline) {
|
|
1728
|
+
rawParts.pop();
|
|
1729
|
+
this.partialLineBuffer.delete(filePath);
|
|
1730
|
+
completeLines = rawParts.map((l) => l.replace(/\r$/, "")).filter((l) => l.length > 0);
|
|
1731
|
+
} else {
|
|
1732
|
+
const trailingPartial = rawParts.pop() ?? "";
|
|
1733
|
+
if (trailingPartial.length > 0) {
|
|
1734
|
+
this.partialLineBuffer.set(filePath, trailingPartial);
|
|
1735
|
+
}
|
|
1736
|
+
completeLines = rawParts.map((l) => l.replace(/\r$/, "")).filter((l) => l.length > 0);
|
|
1737
|
+
}
|
|
1738
|
+
const nextByteOffset = offset + bytesRead;
|
|
1739
|
+
const contentSha256 = createHash3("sha256").update(chunkText).digest("hex").slice(0, 16);
|
|
1740
|
+
this.store.upsertCursor({
|
|
1741
|
+
file_path: filePath,
|
|
1742
|
+
cli_source: cliSource,
|
|
1743
|
+
inode,
|
|
1744
|
+
byte_offset: nextByteOffset,
|
|
1745
|
+
last_item_index: (prev?.last_item_index ?? 0) + completeLines.length,
|
|
1746
|
+
content_sha256: contentSha256,
|
|
1747
|
+
mtime_ms: mtimeMs
|
|
1748
|
+
});
|
|
1749
|
+
return {
|
|
1750
|
+
filePath,
|
|
1751
|
+
lines: completeLines,
|
|
1752
|
+
newOffset: nextByteOffset,
|
|
1753
|
+
inode,
|
|
1754
|
+
resetDetected
|
|
1755
|
+
};
|
|
1756
|
+
}
|
|
1757
|
+
};
|
|
1758
|
+
|
|
1759
|
+
// packages/adapters/dist/git-sensor.js
|
|
1760
|
+
import { createHash as createHash4 } from "node:crypto";
|
|
1761
|
+
import { execFile } from "node:child_process";
|
|
1762
|
+
import { readFile } from "node:fs/promises";
|
|
1763
|
+
import { join as join4 } from "node:path";
|
|
1764
|
+
import { promisify } from "node:util";
|
|
1765
|
+
var execFileAsync = promisify(execFile);
|
|
1766
|
+
var MAX_FILE_DIFF_BYTES = 64 * 1024;
|
|
1767
|
+
var MAX_UNTRACKED_PREVIEW_BYTES = 24 * 1024;
|
|
1768
|
+
async function runGit(repoRoot, args) {
|
|
1769
|
+
const { stdout } = await execFileAsync("git", args, {
|
|
1770
|
+
cwd: repoRoot,
|
|
1771
|
+
env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" },
|
|
1772
|
+
maxBuffer: 4 * 1024 * 1024
|
|
1773
|
+
});
|
|
1774
|
+
return stdout;
|
|
1775
|
+
}
|
|
1776
|
+
function parseUnifiedDiffHunkRanges(unifiedDiff) {
|
|
1777
|
+
const ranges = [];
|
|
1778
|
+
const hunkRegex = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/gm;
|
|
1779
|
+
for (const match of unifiedDiff.matchAll(hunkRegex)) {
|
|
1780
|
+
const start = Number(match[1]);
|
|
1781
|
+
const count = match[2] !== void 0 ? Number(match[2]) : 1;
|
|
1782
|
+
if (count === 0) {
|
|
1783
|
+
ranges.push(`L${start}`);
|
|
1784
|
+
} else {
|
|
1785
|
+
const end = start + count - 1;
|
|
1786
|
+
ranges.push(start === end ? `L${start}` : `L${start}-L${end}`);
|
|
1787
|
+
}
|
|
1788
|
+
}
|
|
1789
|
+
return ranges;
|
|
1790
|
+
}
|
|
1791
|
+
function extractSymbolHints(unifiedDiff) {
|
|
1792
|
+
const symbols = /* @__PURE__ */ new Set();
|
|
1793
|
+
const lines = unifiedDiff.split("\n");
|
|
1794
|
+
for (const line of lines) {
|
|
1795
|
+
if (line.startsWith("@@")) {
|
|
1796
|
+
const ctx = line.split("@@")[2]?.trim();
|
|
1797
|
+
if (ctx)
|
|
1798
|
+
symbols.add(ctx.slice(0, 64));
|
|
1799
|
+
continue;
|
|
1800
|
+
}
|
|
1801
|
+
if (!line.startsWith("+") || line.startsWith("+++"))
|
|
1802
|
+
continue;
|
|
1803
|
+
const match = line.slice(1).match(/^\s*(?:export\s+)?(?:async\s+)?(?:function|class|interface|type|const|def|fn|CREATE\s+TABLE)\s+([A-Za-z0-9_]+)/i);
|
|
1804
|
+
if (match?.[1]) {
|
|
1805
|
+
symbols.add(match[1]);
|
|
1806
|
+
}
|
|
1807
|
+
if (symbols.size >= 4)
|
|
1808
|
+
break;
|
|
1809
|
+
}
|
|
1810
|
+
return [...symbols];
|
|
1811
|
+
}
|
|
1812
|
+
function mapPorcelainStatus(xy) {
|
|
1813
|
+
if (xy.includes("D"))
|
|
1814
|
+
return "deleted";
|
|
1815
|
+
if (xy.includes("R"))
|
|
1816
|
+
return "renamed";
|
|
1817
|
+
if (xy.includes("A") || xy === "??")
|
|
1818
|
+
return "added";
|
|
1819
|
+
if (xy.includes("M"))
|
|
1820
|
+
return "modified";
|
|
1821
|
+
return "modified";
|
|
1822
|
+
}
|
|
1823
|
+
var GitStateSensor = class {
|
|
1824
|
+
async capture(targetDir) {
|
|
1825
|
+
let repoRoot;
|
|
1826
|
+
try {
|
|
1827
|
+
repoRoot = (await runGit(targetDir, ["rev-parse", "--show-toplevel"])).trim();
|
|
1828
|
+
} catch {
|
|
1829
|
+
return null;
|
|
1830
|
+
}
|
|
1831
|
+
const branch = await runGit(repoRoot, ["rev-parse", "--abbrev-ref", "HEAD"]).then((s) => s.trim()).catch(() => "HEAD");
|
|
1832
|
+
const headSha = await runGit(repoRoot, ["rev-parse", "--short=7", "HEAD"]).then((s) => s.trim()).catch(() => "0000000");
|
|
1833
|
+
const statusOut = await runGit(repoRoot, ["status", "--porcelain=v1", "-z"]).catch(() => "");
|
|
1834
|
+
const entries = statusOut.split("\0").filter((e) => e.length >= 4);
|
|
1835
|
+
if (entries.length === 0) {
|
|
1836
|
+
return {
|
|
1837
|
+
repoRoot,
|
|
1838
|
+
branch,
|
|
1839
|
+
headSha,
|
|
1840
|
+
isDirtyTree: false,
|
|
1841
|
+
files: [],
|
|
1842
|
+
capturedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1843
|
+
};
|
|
1844
|
+
}
|
|
1845
|
+
const numstatRaw = await runGit(repoRoot, ["diff", "--numstat", "HEAD"]).catch(() => "");
|
|
1846
|
+
const numstatMap = /* @__PURE__ */ new Map();
|
|
1847
|
+
for (const line of numstatRaw.split("\n")) {
|
|
1848
|
+
const parts = line.split(" ");
|
|
1849
|
+
if (parts.length >= 3 && parts[2]) {
|
|
1850
|
+
const added = parts[0] === "-" ? 0 : Number(parts[0]) || 0;
|
|
1851
|
+
const removed = parts[1] === "-" ? 0 : Number(parts[1]) || 0;
|
|
1852
|
+
numstatMap.set(parts[2], { added, removed });
|
|
1853
|
+
}
|
|
1854
|
+
}
|
|
1855
|
+
const files = [];
|
|
1856
|
+
for (const entry of entries.slice(0, 40)) {
|
|
1857
|
+
const xy = entry.slice(0, 2);
|
|
1858
|
+
const rawPath = entry.slice(3);
|
|
1859
|
+
const filePath = rawPath.includes(" -> ") ? rawPath.split(" -> ").pop() : rawPath;
|
|
1860
|
+
const changeStatus = mapPorcelainStatus(xy);
|
|
1861
|
+
let unifiedDiff = "";
|
|
1862
|
+
let linesAdded = numstatMap.get(filePath)?.added ?? 0;
|
|
1863
|
+
let linesRemoved = numstatMap.get(filePath)?.removed ?? 0;
|
|
1864
|
+
if (xy === "??") {
|
|
1865
|
+
try {
|
|
1866
|
+
const content = await readFile(join4(repoRoot, filePath), "utf8");
|
|
1867
|
+
const preview = content.slice(0, MAX_UNTRACKED_PREVIEW_BYTES);
|
|
1868
|
+
const contentLines = preview.split("\n");
|
|
1869
|
+
linesAdded = contentLines.length;
|
|
1870
|
+
const plusLines = contentLines.map((l) => `+${l}`).join("\n");
|
|
1871
|
+
unifiedDiff = `--- /dev/null
|
|
1872
|
+
+++ b/${filePath}
|
|
1873
|
+
@@ -0,0 +1,${contentLines.length} @@
|
|
1874
|
+
${plusLines}`;
|
|
1875
|
+
} catch {
|
|
1876
|
+
unifiedDiff = `--- /dev/null
|
|
1877
|
+
+++ b/${filePath}
|
|
1878
|
+
@@ -0,0 +1,1 @@
|
|
1879
|
+
+[binary or unreadable untracked file]`;
|
|
1880
|
+
}
|
|
1881
|
+
} else {
|
|
1882
|
+
unifiedDiff = await runGit(repoRoot, ["diff", "--unified=3", "--no-color", "HEAD", "--", filePath]).catch(() => "");
|
|
1883
|
+
}
|
|
1884
|
+
const clippedDiff = Redactor.sanitize(unifiedDiff.slice(0, MAX_FILE_DIFF_BYTES));
|
|
1885
|
+
const lineRanges = parseUnifiedDiffHunkRanges(clippedDiff);
|
|
1886
|
+
const symbols = extractSymbolHints(clippedDiff);
|
|
1887
|
+
const progressNote = symbols.length > 0 ? `${changeStatus} (${symbols.join(", ")})` : `${changeStatus} (+${linesAdded} / -${linesRemoved})`;
|
|
1888
|
+
files.push({
|
|
1889
|
+
filePath,
|
|
1890
|
+
changeStatus,
|
|
1891
|
+
lineRanges: lineRanges.length > 0 ? lineRanges : linesAdded > 0 ? [`L1-L${linesAdded}`] : [],
|
|
1892
|
+
linesAdded,
|
|
1893
|
+
linesRemoved,
|
|
1894
|
+
progressNote,
|
|
1895
|
+
contentSha256: createHash4("sha256").update(clippedDiff).digest("hex").slice(0, 16),
|
|
1896
|
+
unifiedDiff: clippedDiff
|
|
1897
|
+
});
|
|
1898
|
+
}
|
|
1899
|
+
return {
|
|
1900
|
+
repoRoot,
|
|
1901
|
+
branch,
|
|
1902
|
+
headSha,
|
|
1903
|
+
isDirtyTree: true,
|
|
1904
|
+
files,
|
|
1905
|
+
capturedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1906
|
+
};
|
|
1907
|
+
}
|
|
1908
|
+
};
|
|
1909
|
+
|
|
1910
|
+
// packages/adapters/dist/index.js
|
|
1911
|
+
function walkFiles(dir, matcher, maxDepth = 4) {
|
|
1912
|
+
if (!existsSync3(dir) || maxDepth < 0)
|
|
1913
|
+
return [];
|
|
1914
|
+
const results = [];
|
|
1915
|
+
let entries;
|
|
1916
|
+
try {
|
|
1917
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
1918
|
+
} catch {
|
|
1919
|
+
return [];
|
|
1920
|
+
}
|
|
1921
|
+
for (const entry of entries) {
|
|
1922
|
+
const full = join5(dir, entry.name);
|
|
1923
|
+
if (entry.isDirectory()) {
|
|
1924
|
+
results.push(...walkFiles(full, matcher, maxDepth - 1));
|
|
1925
|
+
} else if (entry.isFile() && matcher(entry.name, full)) {
|
|
1926
|
+
results.push(full);
|
|
1927
|
+
}
|
|
1928
|
+
}
|
|
1929
|
+
return results;
|
|
1930
|
+
}
|
|
1931
|
+
function discoverSessionFiles(roots) {
|
|
1932
|
+
const home = homedir2();
|
|
1933
|
+
const agyRoot = roots?.agyRoot ?? join5(home, ".gemini", "antigravity-cli", "brain");
|
|
1934
|
+
const claudeRoot = roots?.claudeRoot ?? join5(home, ".claude", "projects");
|
|
1935
|
+
const geminiRoot = roots?.geminiRoot ?? join5(home, ".gemini", "tmp");
|
|
1936
|
+
const codexRoot = roots?.codexRoot ?? join5(home, ".codex", "sessions");
|
|
1937
|
+
const cursorRoot = roots?.cursorRoot ?? (process.platform === "darwin" ? join5(home, "Library", "Application Support", "Cursor", "User", "workspaceStorage") : join5(home, ".config", "Cursor", "User", "workspaceStorage"));
|
|
1938
|
+
const found = [];
|
|
1939
|
+
for (const f of walkFiles(agyRoot, (name, full) => name === "transcript.jsonl" && full.includes(".system_generated"), 3)) {
|
|
1940
|
+
found.push({ cliSource: "agy", filePath: f });
|
|
1941
|
+
}
|
|
1942
|
+
for (const f of walkFiles(claudeRoot, (name) => name.endsWith(".jsonl"), 2)) {
|
|
1943
|
+
found.push({ cliSource: "claude", filePath: f });
|
|
1944
|
+
}
|
|
1945
|
+
for (const f of walkFiles(geminiRoot, (name, full) => name.startsWith("session-") && name.endsWith(".json") && full.includes("/chats/"), 3)) {
|
|
1946
|
+
found.push({ cliSource: "gemini", filePath: f });
|
|
1947
|
+
}
|
|
1948
|
+
for (const f of walkFiles(codexRoot, (name) => name.startsWith("rollout-") && name.endsWith(".jsonl"), 4)) {
|
|
1949
|
+
found.push({ cliSource: "codex", filePath: f });
|
|
1950
|
+
}
|
|
1951
|
+
for (const f of walkFiles(cursorRoot, (name) => name === "state.vscdb", 2)) {
|
|
1952
|
+
found.push({ cliSource: "cursor", filePath: f });
|
|
1953
|
+
}
|
|
1954
|
+
return found;
|
|
1955
|
+
}
|
|
1956
|
+
var UniversalSessionAdapter = class {
|
|
1957
|
+
store;
|
|
1958
|
+
tailer;
|
|
1959
|
+
constructor(store) {
|
|
1960
|
+
this.store = store;
|
|
1961
|
+
this.tailer = new FileTailer(store);
|
|
1962
|
+
}
|
|
1963
|
+
ingestFile(filePath, cliSource) {
|
|
1964
|
+
if (cliSource === "gemini") {
|
|
1965
|
+
return readGeminiSnapshotIncremental(filePath, this.store);
|
|
1966
|
+
}
|
|
1967
|
+
if (cliSource === "cursor") {
|
|
1968
|
+
return readCursorStateReadOnly(filePath, this.store);
|
|
1969
|
+
}
|
|
1970
|
+
const { lines } = this.tailer.readNewLines(filePath, cliSource);
|
|
1971
|
+
if (lines.length === 0)
|
|
1972
|
+
return [];
|
|
1973
|
+
return parseJsonlBySource(cliSource, lines, filePath);
|
|
1974
|
+
}
|
|
1975
|
+
};
|
|
1976
|
+
|
|
1977
|
+
// packages/distiller/dist/extractors/dead-end-collapser.js
|
|
1978
|
+
import { createHash as createHash5 } from "node:crypto";
|
|
1979
|
+
function normalizeErrorSignature(text) {
|
|
1980
|
+
const normalized = text.toLowerCase().replace(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/g, "<uuid>").replace(/\b20\d{2}-\d{2}-\d{2}t\d{2}:\d{2}:\d{2}(?:\.\d+)?z?\b/g, "<ts>").replace(/:\d+:\d+/g, ":<line>").replace(/\bline\s+\d+\b/g, "line <n>").replace(/\b\d+\s*ms\b/g, "<ms>").replace(/\b0x[0-9a-f]+\b/g, "<hex>").replace(/\s+/g, " ").trim().slice(0, 260);
|
|
1981
|
+
return `err_${createHash5("sha256").update(normalized).digest("hex").slice(0, 12)}`;
|
|
1982
|
+
}
|
|
1983
|
+
function extractErrorHeadline(text) {
|
|
1984
|
+
const lines = text.split("\n").map((l) => l.trim()).filter((l) => l.length > 0);
|
|
1985
|
+
const priorityLine = lines.find((l) => /(?:Error:|Exception:|FAIL\s|TS\d{4}:|AssertionError|PrismaClient|SyntaxError|TypeError|ReferenceError|ECONNREFUSED|ENOENT)/i.test(l)) ?? lines.find((l) => !/^command exited with code/i.test(l)) ?? lines[0] ?? "Command failed";
|
|
1986
|
+
return Redactor.sanitize(priorityLine.slice(0, 180));
|
|
1987
|
+
}
|
|
1988
|
+
function isErrorTurn(event) {
|
|
1989
|
+
if (event.role === "system_error")
|
|
1990
|
+
return true;
|
|
1991
|
+
if (event.toolExitCode !== void 0 && event.toolExitCode !== 0)
|
|
1992
|
+
return true;
|
|
1993
|
+
if (event.role === "tool_result" && /(?:^|\n)\s*(?:FAIL|Error:|TypeError:|SyntaxError:|TS\d{4}:|AssertionError)/m.test(event.textContent)) {
|
|
1994
|
+
return true;
|
|
1995
|
+
}
|
|
1996
|
+
return false;
|
|
1997
|
+
}
|
|
1998
|
+
function collapseDeadEnds(events) {
|
|
1999
|
+
const byFingerprint = /* @__PURE__ */ new Map();
|
|
2000
|
+
for (let i = 0; i < events.length; i++) {
|
|
2001
|
+
const ev = events[i];
|
|
2002
|
+
if (!isErrorTurn(ev))
|
|
2003
|
+
continue;
|
|
2004
|
+
let attempted = ev.toolName ?? "Previous command/edit";
|
|
2005
|
+
const refs = new Set(ev.filesReferenced ?? []);
|
|
2006
|
+
for (let j = i - 1; j >= Math.max(0, i - 2); j--) {
|
|
2007
|
+
const prev = events[j];
|
|
2008
|
+
for (const f of prev.filesReferenced ?? [])
|
|
2009
|
+
refs.add(f);
|
|
2010
|
+
if (prev.role === "tool_call") {
|
|
2011
|
+
const cmd = typeof prev.toolArgs?.command === "string" ? prev.toolArgs.command : prev.toolArgs?.CommandLine;
|
|
2012
|
+
attempted = typeof cmd === "string" ? cmd.slice(0, 100) : `${prev.toolName ?? "tool"} call`;
|
|
2013
|
+
break;
|
|
2014
|
+
}
|
|
2015
|
+
if (prev.role === "assistant" && prev.textContent.trim().length > 0) {
|
|
2016
|
+
attempted = prev.textContent.split("\n")[0].slice(0, 100);
|
|
2017
|
+
break;
|
|
2018
|
+
}
|
|
2019
|
+
}
|
|
2020
|
+
const headline = extractErrorHeadline(ev.textContent);
|
|
2021
|
+
const fingerprint = normalizeErrorSignature(headline);
|
|
2022
|
+
const existing = byFingerprint.get(fingerprint);
|
|
2023
|
+
if (existing) {
|
|
2024
|
+
existing.occurrences += 1;
|
|
2025
|
+
existing.cliSource = ev.cliSource;
|
|
2026
|
+
for (const r of refs)
|
|
2027
|
+
existing.fileRefs.push(r);
|
|
2028
|
+
existing.fileRefs = [...new Set(existing.fileRefs)].slice(0, 5);
|
|
2029
|
+
} else {
|
|
2030
|
+
byFingerprint.set(fingerprint, {
|
|
2031
|
+
fingerprint,
|
|
2032
|
+
attempted: Redactor.sanitize(attempted),
|
|
2033
|
+
errorSummary: headline,
|
|
2034
|
+
occurrences: 1,
|
|
2035
|
+
cliSource: ev.cliSource,
|
|
2036
|
+
fileRefs: [...refs].slice(0, 5),
|
|
2037
|
+
isResolved: false
|
|
2038
|
+
});
|
|
2039
|
+
}
|
|
2040
|
+
}
|
|
2041
|
+
return [...byFingerprint.values()].sort((a, b) => b.occurrences - a.occurrences);
|
|
2042
|
+
}
|
|
2043
|
+
|
|
2044
|
+
// packages/distiller/dist/extractors/turn-extractor.js
|
|
2045
|
+
function cleanUserPrompt(text) {
|
|
2046
|
+
return Redactor.sanitize(text.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim());
|
|
2047
|
+
}
|
|
2048
|
+
function normalizeTopicKey(statement) {
|
|
2049
|
+
return statement.toLowerCase().replace(/[^a-z0-9\s]/g, " ").split(/\s+/).filter((w) => w.length > 3).slice(0, 5).sort().join(":");
|
|
2050
|
+
}
|
|
2051
|
+
function extractCommandHint(text) {
|
|
2052
|
+
const backtickCmd = text.match(/`((?:npx|npm|pnpm|node|vitest|pytest|git|tsc|cargo|go)\s+[^`]+)`/);
|
|
2053
|
+
return backtickCmd?.[1]?.trim();
|
|
2054
|
+
}
|
|
2055
|
+
function extractWorkingMemory(events) {
|
|
2056
|
+
const userMessages = [];
|
|
2057
|
+
const decisionMap = /* @__PURE__ */ new Map();
|
|
2058
|
+
const checklistMap = /* @__PURE__ */ new Map();
|
|
2059
|
+
const passingCommands = /* @__PURE__ */ new Set();
|
|
2060
|
+
const sourceChainSet = /* @__PURE__ */ new Set();
|
|
2061
|
+
let rawInputTokens = 0;
|
|
2062
|
+
let rawOutputTokens = 0;
|
|
2063
|
+
let decCounter = 1;
|
|
2064
|
+
for (const ev of events) {
|
|
2065
|
+
sourceChainSet.add(ev.cliSource);
|
|
2066
|
+
if (ev.tokenUsage) {
|
|
2067
|
+
rawInputTokens += ev.tokenUsage.input;
|
|
2068
|
+
rawOutputTokens += ev.tokenUsage.output;
|
|
2069
|
+
}
|
|
2070
|
+
const text = Redactor.sanitize(ev.textContent ?? "");
|
|
2071
|
+
if (!text)
|
|
2072
|
+
continue;
|
|
2073
|
+
if (ev.role === "user") {
|
|
2074
|
+
const cleaned = cleanUserPrompt(text);
|
|
2075
|
+
if (cleaned.length >= 6) {
|
|
2076
|
+
userMessages.push(cleaned);
|
|
2077
|
+
}
|
|
2078
|
+
for (const line of text.split("\n")) {
|
|
2079
|
+
const trimmed = line.trim();
|
|
2080
|
+
if (trimmed.length >= 16 && trimmed.length <= 240 && /\b(?:must|never|always|do not|don't|avoid|instead of|use\s+\S+\s+not)\b/i.test(trimmed)) {
|
|
2081
|
+
const key = normalizeTopicKey(trimmed) || `u_${decCounter}`;
|
|
2082
|
+
decisionMap.set(key, {
|
|
2083
|
+
id: `ext_dec_${decCounter++}`,
|
|
2084
|
+
statement: trimmed,
|
|
2085
|
+
rationale: "Explicit user constraint",
|
|
2086
|
+
cliSource: ev.cliSource,
|
|
2087
|
+
lockedAt: ev.timestampIso,
|
|
2088
|
+
category: "constraint",
|
|
2089
|
+
priority: 2
|
|
2090
|
+
});
|
|
2091
|
+
}
|
|
2092
|
+
}
|
|
2093
|
+
}
|
|
2094
|
+
if (ev.role === "assistant") {
|
|
2095
|
+
const lines = text.split("\n");
|
|
2096
|
+
for (const line of lines) {
|
|
2097
|
+
const trimmed = line.trim();
|
|
2098
|
+
if (trimmed.length >= 18 && trimmed.length <= 240 && /^(?:[-*]\s*)?(?:\*\*)?(?:Decision|Architecture|Locked|Constraint|Chosen|Use\s+|Never\s+|Always\s+)/i.test(trimmed)) {
|
|
2099
|
+
const cleanStmt = trimmed.replace(/^[-*]\s*/, "").replace(/\*\*/g, "").trim();
|
|
2100
|
+
const key = normalizeTopicKey(cleanStmt) || `a_${decCounter}`;
|
|
2101
|
+
if (!decisionMap.has(key)) {
|
|
2102
|
+
decisionMap.set(key, {
|
|
2103
|
+
id: `ext_dec_${decCounter++}`,
|
|
2104
|
+
statement: cleanStmt,
|
|
2105
|
+
rationale: `Locked during ${ev.cliSource} turn`,
|
|
2106
|
+
cliSource: ev.cliSource,
|
|
2107
|
+
lockedAt: ev.timestampIso,
|
|
2108
|
+
category: "architecture",
|
|
2109
|
+
priority: 1
|
|
2110
|
+
});
|
|
2111
|
+
}
|
|
2112
|
+
}
|
|
2113
|
+
const todoMatch = trimmed.match(/^[-*]\s+\[([ xX])\]\s+(.+)$/);
|
|
2114
|
+
if (todoMatch?.[2]) {
|
|
2115
|
+
const done = todoMatch[1].toLowerCase() === "x";
|
|
2116
|
+
const task = todoMatch[2].trim();
|
|
2117
|
+
const key = task.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
|
|
2118
|
+
checklistMap.set(key, {
|
|
2119
|
+
order: checklistMap.size + 1,
|
|
2120
|
+
task,
|
|
2121
|
+
verifyCommand: extractCommandHint(task),
|
|
2122
|
+
done
|
|
2123
|
+
});
|
|
2124
|
+
}
|
|
2125
|
+
}
|
|
2126
|
+
}
|
|
2127
|
+
if (ev.role === "tool_result" && (ev.toolExitCode === 0 || /\bpassed\b/i.test(text))) {
|
|
2128
|
+
passingCommands.add(text.toLowerCase());
|
|
2129
|
+
}
|
|
2130
|
+
}
|
|
2131
|
+
const nextSteps = [];
|
|
2132
|
+
let order = 1;
|
|
2133
|
+
for (const item of checklistMap.values()) {
|
|
2134
|
+
if (item.done)
|
|
2135
|
+
continue;
|
|
2136
|
+
if (item.verifyCommand && [...passingCommands].some((p) => p.includes(item.verifyCommand.toLowerCase()))) {
|
|
2137
|
+
continue;
|
|
2138
|
+
}
|
|
2139
|
+
nextSteps.push({ ...item, order: order++ });
|
|
2140
|
+
}
|
|
2141
|
+
const originalIntent = (userMessages[0] ?? "Continue active engineering task").slice(0, 260);
|
|
2142
|
+
const latestUser = userMessages[userMessages.length - 1] ?? originalIntent;
|
|
2143
|
+
const goalSummary = userMessages.length > 1 && latestUser !== originalIntent ? `${originalIntent.slice(0, 140)} \u2014 Latest focus: ${latestUser.slice(0, 140)}` : originalIntent;
|
|
2144
|
+
const decisions = [...decisionMap.values()].sort((a, b) => b.priority - a.priority);
|
|
2145
|
+
return {
|
|
2146
|
+
goalSummary,
|
|
2147
|
+
originalIntent,
|
|
2148
|
+
decisions,
|
|
2149
|
+
nextSteps,
|
|
2150
|
+
rawInputTokens,
|
|
2151
|
+
rawOutputTokens,
|
|
2152
|
+
sourceChain: [...sourceChainSet]
|
|
2153
|
+
};
|
|
2154
|
+
}
|
|
2155
|
+
|
|
2156
|
+
// packages/distiller/dist/markdown-renderer.js
|
|
2157
|
+
function renderCapsuleMarkdown(payload) {
|
|
2158
|
+
const chainStr = payload.sourceChain.length > 0 ? payload.sourceChain.join(" -> ") : "manual";
|
|
2159
|
+
const dirtyFlag = payload.isDirtyTree ? "dirty" : "clean";
|
|
2160
|
+
const lines = [
|
|
2161
|
+
`## CMEM CONTEXT CAPSULE [${payload.capsuleId} | ${chainStr}]`,
|
|
2162
|
+
`**Repo/Branch:** ${payload.projectName} (\`${payload.gitBranch}\` @ \`${payload.gitHeadSha}\` ${dirtyFlag})`,
|
|
2163
|
+
`**Goal:** ${payload.goal.summary}`
|
|
2164
|
+
];
|
|
2165
|
+
if (payload.decisionsLocked.length > 0) {
|
|
2166
|
+
lines.push("### Decisions Locked");
|
|
2167
|
+
for (const d of payload.decisionsLocked) {
|
|
2168
|
+
lines.push(`- [${d.cliSource}] ${d.statement}`);
|
|
2169
|
+
}
|
|
2170
|
+
}
|
|
2171
|
+
if (payload.filesProgress.length > 0) {
|
|
2172
|
+
lines.push("### Files & Line Progress");
|
|
2173
|
+
for (const f of payload.filesProgress) {
|
|
2174
|
+
const rangeStr = f.lineRanges.length > 0 ? f.lineRanges.join(",") : `+${f.linesAdded}/-${f.linesRemoved}`;
|
|
2175
|
+
lines.push(`- \`${f.path}\` (${f.status} \`${rangeStr}\`): ${f.progressNote}`);
|
|
2176
|
+
}
|
|
2177
|
+
}
|
|
2178
|
+
if (payload.deadEndsAvoid.length > 0) {
|
|
2179
|
+
lines.push("### Dead Ends (DO NOT RETRY)");
|
|
2180
|
+
for (const de of payload.deadEndsAvoid) {
|
|
2181
|
+
const countLabel = de.occurrences > 1 ? ` (${de.occurrences}x)` : "";
|
|
2182
|
+
lines.push(`- \`${de.attempted}\` -> ${de.errorSummary}${countLabel}`);
|
|
2183
|
+
}
|
|
2184
|
+
}
|
|
2185
|
+
if (payload.nextSteps.length > 0) {
|
|
2186
|
+
lines.push("### Remaining Checklist");
|
|
2187
|
+
for (const step of payload.nextSteps) {
|
|
2188
|
+
const mark = step.done ? "x" : " ";
|
|
2189
|
+
const verify = step.verifyCommand ? ` (\`${step.verifyCommand}\`)` : "";
|
|
2190
|
+
lines.push(`- [${mark}] ${step.task}${verify}`);
|
|
2191
|
+
}
|
|
2192
|
+
}
|
|
2193
|
+
return lines.join("\n");
|
|
2194
|
+
}
|
|
2195
|
+
|
|
2196
|
+
// packages/distiller/dist/compiler.js
|
|
2197
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
2198
|
+
var NoopDeterministicRefiner = class {
|
|
2199
|
+
name = "deterministic-tier1";
|
|
2200
|
+
async refine(draft) {
|
|
2201
|
+
return draft;
|
|
2202
|
+
}
|
|
2203
|
+
};
|
|
2204
|
+
function toPayload(draft, capsuleTokens) {
|
|
2205
|
+
const raw = Math.max(capsuleTokens, draft.rawSessionTokens);
|
|
2206
|
+
const tokensSaved = Math.max(0, raw - capsuleTokens);
|
|
2207
|
+
const compressionPct = raw > 0 ? Number((tokensSaved / raw * 100).toFixed(1)) : 0;
|
|
2208
|
+
return {
|
|
2209
|
+
schemaVersion: "1.0",
|
|
2210
|
+
capsuleId: draft.capsuleId,
|
|
2211
|
+
projectId: draft.projectId,
|
|
2212
|
+
projectName: draft.projectName,
|
|
2213
|
+
repoRoot: draft.repoRoot,
|
|
2214
|
+
gitBranch: draft.gitBranch,
|
|
2215
|
+
gitHeadSha: draft.gitHeadSha,
|
|
2216
|
+
isDirtyTree: draft.isDirtyTree,
|
|
2217
|
+
sourceChain: draft.sourceChain,
|
|
2218
|
+
goal: draft.goal,
|
|
2219
|
+
decisionsLocked: draft.decisionsLocked,
|
|
2220
|
+
filesProgress: draft.filesProgress,
|
|
2221
|
+
deadEndsAvoid: draft.deadEndsAvoid,
|
|
2222
|
+
nextSteps: draft.nextSteps,
|
|
2223
|
+
telemetry: {
|
|
2224
|
+
rawSessionTokens: raw,
|
|
2225
|
+
capsuleTokens,
|
|
2226
|
+
tokensSaved,
|
|
2227
|
+
compressionPct,
|
|
2228
|
+
generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2229
|
+
trigger: draft.trigger
|
|
2230
|
+
}
|
|
2231
|
+
};
|
|
2232
|
+
}
|
|
2233
|
+
function cloneDraft(d) {
|
|
2234
|
+
return {
|
|
2235
|
+
...d,
|
|
2236
|
+
sourceChain: [...d.sourceChain],
|
|
2237
|
+
goal: { ...d.goal },
|
|
2238
|
+
decisionsLocked: d.decisionsLocked.map((x) => ({ ...x })),
|
|
2239
|
+
filesProgress: d.filesProgress.map((x) => ({ ...x, lineRanges: [...x.lineRanges] })),
|
|
2240
|
+
deadEndsAvoid: d.deadEndsAvoid.map((x) => ({ ...x })),
|
|
2241
|
+
nextSteps: d.nextSteps.map((x) => ({ ...x }))
|
|
2242
|
+
};
|
|
2243
|
+
}
|
|
2244
|
+
function enforceTokenBudget(draft, maxTokens = 1500) {
|
|
2245
|
+
if (maxTokens < 300) {
|
|
2246
|
+
throw new RangeError(`maxTokens must be >= 300, received ${maxTokens}`);
|
|
2247
|
+
}
|
|
2248
|
+
const working = cloneDraft(Redactor.sanitizeRecord(draft));
|
|
2249
|
+
working.nextSteps = working.nextSteps.slice(0, 6);
|
|
2250
|
+
const renderCurrent = () => {
|
|
2251
|
+
const tentative = toPayload(working, 0);
|
|
2252
|
+
const md2 = renderCapsuleMarkdown(tentative);
|
|
2253
|
+
const tok2 = estimateTokens(md2);
|
|
2254
|
+
return { md: md2, tok: tok2 };
|
|
2255
|
+
};
|
|
2256
|
+
let { md, tok } = renderCurrent();
|
|
2257
|
+
while (tok > maxTokens && working.decisionsLocked.length > 2) {
|
|
2258
|
+
working.decisionsLocked.pop();
|
|
2259
|
+
({ md, tok } = renderCurrent());
|
|
2260
|
+
}
|
|
2261
|
+
if (tok > maxTokens && working.filesProgress.length > 8) {
|
|
2262
|
+
working.filesProgress = working.filesProgress.slice(0, 8);
|
|
2263
|
+
({ md, tok } = renderCurrent());
|
|
2264
|
+
}
|
|
2265
|
+
while (tok > maxTokens && working.filesProgress.length > 2) {
|
|
2266
|
+
working.filesProgress.pop();
|
|
2267
|
+
({ md, tok } = renderCurrent());
|
|
2268
|
+
}
|
|
2269
|
+
if (tok > maxTokens && working.deadEndsAvoid.length > 1) {
|
|
2270
|
+
working.deadEndsAvoid.sort((a, b) => b.occurrences - a.occurrences);
|
|
2271
|
+
while (tok > maxTokens && working.deadEndsAvoid.length > 1) {
|
|
2272
|
+
working.deadEndsAvoid.pop();
|
|
2273
|
+
({ md, tok } = renderCurrent());
|
|
2274
|
+
}
|
|
2275
|
+
}
|
|
2276
|
+
while (tok > maxTokens && working.decisionsLocked.length > 0) {
|
|
2277
|
+
working.decisionsLocked.pop();
|
|
2278
|
+
({ md, tok } = renderCurrent());
|
|
2279
|
+
}
|
|
2280
|
+
if (tok > maxTokens) {
|
|
2281
|
+
working.goal.summary = truncateToTokenBudget(working.goal.summary, 90);
|
|
2282
|
+
working.filesProgress = working.filesProgress.map((f) => ({
|
|
2283
|
+
...f,
|
|
2284
|
+
lineRanges: f.lineRanges.slice(0, 2),
|
|
2285
|
+
progressNote: truncateToTokenBudget(f.progressNote, 16)
|
|
2286
|
+
}));
|
|
2287
|
+
working.deadEndsAvoid = working.deadEndsAvoid.map((de) => ({
|
|
2288
|
+
...de,
|
|
2289
|
+
attempted: truncateToTokenBudget(de.attempted, 16),
|
|
2290
|
+
errorSummary: truncateToTokenBudget(de.errorSummary, 24)
|
|
2291
|
+
}));
|
|
2292
|
+
working.nextSteps = working.nextSteps.slice(0, 3).map((s) => ({
|
|
2293
|
+
...s,
|
|
2294
|
+
task: truncateToTokenBudget(s.task, 24)
|
|
2295
|
+
}));
|
|
2296
|
+
({ md, tok } = renderCurrent());
|
|
2297
|
+
}
|
|
2298
|
+
if (tok > maxTokens) {
|
|
2299
|
+
md = truncateToTokenBudget(md, maxTokens);
|
|
2300
|
+
tok = estimateTokens(md);
|
|
2301
|
+
}
|
|
2302
|
+
return {
|
|
2303
|
+
payload: toPayload(working, tok),
|
|
2304
|
+
markdown: md,
|
|
2305
|
+
capsuleTokens: tok
|
|
2306
|
+
};
|
|
2307
|
+
}
|
|
2308
|
+
var CapsuleCompiler = class {
|
|
2309
|
+
refiner;
|
|
2310
|
+
constructor(refiner = new NoopDeterministicRefiner()) {
|
|
2311
|
+
this.refiner = refiner;
|
|
2312
|
+
}
|
|
2313
|
+
async compile(input) {
|
|
2314
|
+
const start = performance.now();
|
|
2315
|
+
const maxTokens = input.maxTokens ?? 1500;
|
|
2316
|
+
const workingMemory = extractWorkingMemory(input.events);
|
|
2317
|
+
const deadEnds = collapseDeadEnds(input.events);
|
|
2318
|
+
const sourceChain = [
|
|
2319
|
+
.../* @__PURE__ */ new Set([
|
|
2320
|
+
...input.previousSourceChain ?? [],
|
|
2321
|
+
...workingMemory.sourceChain
|
|
2322
|
+
])
|
|
2323
|
+
];
|
|
2324
|
+
const decisionsLocked = [
|
|
2325
|
+
...workingMemory.decisions.map((d) => ({
|
|
2326
|
+
id: d.id,
|
|
2327
|
+
statement: d.statement,
|
|
2328
|
+
rationale: d.rationale,
|
|
2329
|
+
cliSource: d.cliSource,
|
|
2330
|
+
lockedAt: d.lockedAt
|
|
2331
|
+
}))
|
|
2332
|
+
];
|
|
2333
|
+
for (const existing of input.existingDecisions ?? []) {
|
|
2334
|
+
if (existing.is_superseded === 1)
|
|
2335
|
+
continue;
|
|
2336
|
+
if (existing.category === "dead_end") {
|
|
2337
|
+
const existsDe = deadEnds.find((d) => d.fingerprint === existing.error_fingerprint);
|
|
2338
|
+
if (!existsDe) {
|
|
2339
|
+
deadEnds.push({
|
|
2340
|
+
fingerprint: existing.error_fingerprint ?? existing.id,
|
|
2341
|
+
attempted: existing.title,
|
|
2342
|
+
errorSummary: existing.rationale || existing.body,
|
|
2343
|
+
occurrences: existing.retry_count,
|
|
2344
|
+
cliSource: existing.cli_source,
|
|
2345
|
+
fileRefs: [],
|
|
2346
|
+
isResolved: existing.is_resolved === 1
|
|
2347
|
+
});
|
|
2348
|
+
}
|
|
2349
|
+
continue;
|
|
2350
|
+
}
|
|
2351
|
+
if (existing.category === "next_step" && existing.is_resolved === 0) {
|
|
2352
|
+
const hasTask = workingMemory.nextSteps.some((n) => n.task.toLowerCase() === existing.title.toLowerCase());
|
|
2353
|
+
if (!hasTask) {
|
|
2354
|
+
workingMemory.nextSteps.push({
|
|
2355
|
+
order: workingMemory.nextSteps.length + 1,
|
|
2356
|
+
task: existing.title,
|
|
2357
|
+
done: false
|
|
2358
|
+
});
|
|
2359
|
+
}
|
|
2360
|
+
continue;
|
|
2361
|
+
}
|
|
2362
|
+
if (existing.category === "architecture" || existing.category === "constraint") {
|
|
2363
|
+
const dup = decisionsLocked.some((d) => d.statement.toLowerCase() === existing.title.toLowerCase());
|
|
2364
|
+
if (!dup) {
|
|
2365
|
+
decisionsLocked.unshift({
|
|
2366
|
+
id: existing.id,
|
|
2367
|
+
statement: existing.title,
|
|
2368
|
+
rationale: existing.rationale || existing.body,
|
|
2369
|
+
cliSource: existing.cli_source,
|
|
2370
|
+
lockedAt: existing.created_at
|
|
2371
|
+
});
|
|
2372
|
+
}
|
|
2373
|
+
}
|
|
2374
|
+
}
|
|
2375
|
+
const filesProgress = (input.gitSnapshot?.files ?? []).sort((a, b) => b.linesAdded + b.linesRemoved - (a.linesAdded + a.linesRemoved)).map((f) => ({
|
|
2376
|
+
path: f.filePath,
|
|
2377
|
+
status: f.changeStatus,
|
|
2378
|
+
lineRanges: f.lineRanges,
|
|
2379
|
+
linesAdded: f.linesAdded,
|
|
2380
|
+
linesRemoved: f.linesRemoved,
|
|
2381
|
+
progressNote: f.progressNote
|
|
2382
|
+
}));
|
|
2383
|
+
if (workingMemory.nextSteps.length === 0 && input.gitSnapshot?.isDirtyTree) {
|
|
2384
|
+
workingMemory.nextSteps.push({
|
|
2385
|
+
order: 1,
|
|
2386
|
+
task: `Review dirty changes in ${filesProgress[0]?.path ?? "workspace"} and run project tests`,
|
|
2387
|
+
done: false
|
|
2388
|
+
});
|
|
2389
|
+
}
|
|
2390
|
+
const rawTokens = workingMemory.rawInputTokens + workingMemory.rawOutputTokens;
|
|
2391
|
+
const draft = {
|
|
2392
|
+
capsuleId: input.capsuleId ?? `cap_${randomUUID2().replaceAll("-", "").slice(0, 12)}`,
|
|
2393
|
+
projectId: input.projectId,
|
|
2394
|
+
projectName: input.projectName,
|
|
2395
|
+
repoRoot: input.repoRoot,
|
|
2396
|
+
gitBranch: input.gitSnapshot?.branch ?? input.events.find((e) => e.gitBranch)?.gitBranch ?? "main",
|
|
2397
|
+
gitHeadSha: input.gitSnapshot?.headSha ?? "HEAD",
|
|
2398
|
+
isDirtyTree: input.gitSnapshot?.isDirtyTree ?? false,
|
|
2399
|
+
sourceChain: sourceChain.length > 0 ? sourceChain : ["manual"],
|
|
2400
|
+
goal: {
|
|
2401
|
+
summary: workingMemory.goalSummary,
|
|
2402
|
+
originalIntent: workingMemory.originalIntent
|
|
2403
|
+
},
|
|
2404
|
+
decisionsLocked,
|
|
2405
|
+
filesProgress,
|
|
2406
|
+
deadEndsAvoid: deadEnds.map((de) => ({
|
|
2407
|
+
fingerprint: de.fingerprint,
|
|
2408
|
+
attempted: de.attempted,
|
|
2409
|
+
errorSummary: de.errorSummary,
|
|
2410
|
+
occurrences: de.occurrences,
|
|
2411
|
+
cliSource: de.cliSource
|
|
2412
|
+
})),
|
|
2413
|
+
nextSteps: workingMemory.nextSteps,
|
|
2414
|
+
rawSessionTokens: rawTokens,
|
|
2415
|
+
trigger: input.trigger ?? "turn_checkpoint"
|
|
2416
|
+
};
|
|
2417
|
+
const refined = await this.refiner.refine(draft, maxTokens);
|
|
2418
|
+
const compiled = enforceTokenBudget(refined, maxTokens);
|
|
2419
|
+
const compileDurationMs = Number((performance.now() - start).toFixed(2));
|
|
2420
|
+
return {
|
|
2421
|
+
...compiled,
|
|
2422
|
+
compileDurationMs
|
|
2423
|
+
};
|
|
2424
|
+
}
|
|
2425
|
+
};
|
|
2426
|
+
|
|
2427
|
+
// packages/cli/src/daemon/watcher-service.ts
|
|
2428
|
+
import { EventEmitter } from "node:events";
|
|
2429
|
+
import { existsSync as existsSync4 } from "node:fs";
|
|
2430
|
+
import { join as join6 } from "node:path";
|
|
2431
|
+
import { watch } from "chokidar";
|
|
2432
|
+
var CmemWatcherService = class extends EventEmitter {
|
|
2433
|
+
constructor(store, roots) {
|
|
2434
|
+
super();
|
|
2435
|
+
this.store = store;
|
|
2436
|
+
this.roots = roots;
|
|
2437
|
+
this.adapter = new UniversalSessionAdapter(store);
|
|
2438
|
+
}
|
|
2439
|
+
store;
|
|
2440
|
+
roots;
|
|
2441
|
+
adapter;
|
|
2442
|
+
gitSensor = new GitStateSensor();
|
|
2443
|
+
compiler = new CapsuleCompiler();
|
|
2444
|
+
sessionEventsCache = /* @__PURE__ */ new Map();
|
|
2445
|
+
watcher = null;
|
|
2446
|
+
rescanTimer = null;
|
|
2447
|
+
emitEvent(event) {
|
|
2448
|
+
const full = { ...event, timestamp: (/* @__PURE__ */ new Date()).toISOString() };
|
|
2449
|
+
this.emit("cmem_event", full);
|
|
2450
|
+
}
|
|
2451
|
+
async syncOnce() {
|
|
2452
|
+
const discovered = discoverSessionFiles(this.roots);
|
|
2453
|
+
let eventsIngested = 0;
|
|
2454
|
+
let capsulesUpdated = 0;
|
|
2455
|
+
for (const file of discovered) {
|
|
2456
|
+
let events = [];
|
|
2457
|
+
try {
|
|
2458
|
+
events = this.adapter.ingestFile(file.filePath, file.cliSource);
|
|
2459
|
+
} catch {
|
|
2460
|
+
continue;
|
|
2461
|
+
}
|
|
2462
|
+
if (events.length === 0) continue;
|
|
2463
|
+
eventsIngested += events.length;
|
|
2464
|
+
const firstWithRoot = events.find((e) => e.projectRoot && existsSync4(e.projectRoot));
|
|
2465
|
+
const repoRoot = firstWithRoot?.projectRoot ?? join6(resolveCmemHome(), "unscoped-sessions");
|
|
2466
|
+
const gitSnapshot = existsSync4(repoRoot) ? await this.gitSensor.capture(repoRoot) : null;
|
|
2467
|
+
const resolvedRoot = gitSnapshot?.repoRoot ?? repoRoot;
|
|
2468
|
+
const project = this.store.upsertProject({
|
|
2469
|
+
repoRoot: resolvedRoot,
|
|
2470
|
+
activeBranch: gitSnapshot?.branch ?? events.find((e) => e.gitBranch)?.gitBranch ?? "main",
|
|
2471
|
+
activeCli: file.cliSource
|
|
2472
|
+
});
|
|
2473
|
+
const lastEv = events[events.length - 1];
|
|
2474
|
+
const quotaEvent = [...events].reverse().find((e) => e.quotaSignal?.detected);
|
|
2475
|
+
const tokenTotals = events.reduce(
|
|
2476
|
+
(acc, ev) => ({
|
|
2477
|
+
in: acc.in + (ev.tokenUsage?.input ?? 0),
|
|
2478
|
+
out: acc.out + (ev.tokenUsage?.output ?? 0),
|
|
2479
|
+
cached: acc.cached + (ev.tokenUsage?.cached ?? 0)
|
|
2480
|
+
}),
|
|
2481
|
+
{ in: 0, out: 0, cached: 0 }
|
|
2482
|
+
);
|
|
2483
|
+
const session = this.store.upsertSession({
|
|
2484
|
+
projectId: project.id,
|
|
2485
|
+
cliSource: file.cliSource,
|
|
2486
|
+
externalSessionId: lastEv.externalSessionId,
|
|
2487
|
+
sourceLogPath: file.filePath,
|
|
2488
|
+
modelName: events.find((e) => e.modelName)?.modelName ?? "unknown",
|
|
2489
|
+
gitBranch: gitSnapshot?.branch ?? events.find((e) => e.gitBranch)?.gitBranch ?? "main",
|
|
2490
|
+
status: quotaEvent ? "quota_blocked" : "active",
|
|
2491
|
+
quotaLimitType: quotaEvent?.quotaSignal?.limitType ?? null,
|
|
2492
|
+
quotaResetAt: quotaEvent?.quotaSignal?.resetAtIso ?? null,
|
|
2493
|
+
turnCountDelta: events.length,
|
|
2494
|
+
rawInputDelta: tokenTotals.in,
|
|
2495
|
+
rawOutputDelta: tokenTotals.out,
|
|
2496
|
+
rawCachedDelta: tokenTotals.cached,
|
|
2497
|
+
startedAt: events[0].timestampIso,
|
|
2498
|
+
lastActivityAt: lastEv.timestampIso
|
|
2499
|
+
});
|
|
2500
|
+
const cached = this.sessionEventsCache.get(session.id) ?? [];
|
|
2501
|
+
const mergedEvents = [...cached, ...events].slice(-400);
|
|
2502
|
+
this.sessionEventsCache.set(session.id, mergedEvents);
|
|
2503
|
+
this.emitEvent({
|
|
2504
|
+
type: "turn_ingested",
|
|
2505
|
+
projectId: project.id,
|
|
2506
|
+
sessionId: session.id,
|
|
2507
|
+
cliSource: file.cliSource,
|
|
2508
|
+
message: `Ingested ${events.length} event(s) from ${file.cliSource}`
|
|
2509
|
+
});
|
|
2510
|
+
if (quotaEvent) {
|
|
2511
|
+
this.emitEvent({
|
|
2512
|
+
type: "quota_alert",
|
|
2513
|
+
projectId: project.id,
|
|
2514
|
+
sessionId: session.id,
|
|
2515
|
+
cliSource: file.cliSource,
|
|
2516
|
+
message: `${file.cliSource} hit ${quotaEvent.quotaSignal?.limitType ?? "quota"} limit`
|
|
2517
|
+
});
|
|
2518
|
+
}
|
|
2519
|
+
for (const de of collapseDeadEnds(events)) {
|
|
2520
|
+
this.store.addDecisionLog({
|
|
2521
|
+
projectId: project.id,
|
|
2522
|
+
sessionId: session.id,
|
|
2523
|
+
cliSource: file.cliSource,
|
|
2524
|
+
category: "dead_end",
|
|
2525
|
+
title: de.attempted,
|
|
2526
|
+
body: de.errorSummary,
|
|
2527
|
+
rationale: `Detected in ${file.cliSource} tool output`,
|
|
2528
|
+
errorFingerprint: de.fingerprint,
|
|
2529
|
+
fileRefs: de.fileRefs
|
|
2530
|
+
});
|
|
2531
|
+
}
|
|
2532
|
+
const prevCapsule = this.store.getActiveCapsule(project.id);
|
|
2533
|
+
const prevChain = prevCapsule ? JSON.parse(prevCapsule.source_chain_json) : [];
|
|
2534
|
+
const existingDecisions = this.store.listDecisionsByProject(project.id);
|
|
2535
|
+
const compiled = await this.compiler.compile({
|
|
2536
|
+
projectId: project.id,
|
|
2537
|
+
projectName: project.name,
|
|
2538
|
+
repoRoot: project.repo_root,
|
|
2539
|
+
events: mergedEvents,
|
|
2540
|
+
gitSnapshot,
|
|
2541
|
+
existingDecisions,
|
|
2542
|
+
previousSourceChain: prevChain,
|
|
2543
|
+
trigger: quotaEvent ? "quota_blocked" : "turn_checkpoint"
|
|
2544
|
+
});
|
|
2545
|
+
const saved = this.store.saveCapsule({
|
|
2546
|
+
projectId: project.id,
|
|
2547
|
+
sessionId: session.id,
|
|
2548
|
+
triggerReason: quotaEvent ? "quota_blocked" : "turn_checkpoint",
|
|
2549
|
+
gitBranch: compiled.payload.gitBranch,
|
|
2550
|
+
gitHeadSha: compiled.payload.gitHeadSha,
|
|
2551
|
+
isDirtyTree: compiled.payload.isDirtyTree,
|
|
2552
|
+
payload: compiled.payload,
|
|
2553
|
+
markdown: compiled.markdown,
|
|
2554
|
+
rawTokensCovered: Math.max(
|
|
2555
|
+
compiled.payload.telemetry.rawSessionTokens,
|
|
2556
|
+
session.raw_input_tokens + session.raw_output_tokens
|
|
2557
|
+
),
|
|
2558
|
+
sourceChain: compiled.payload.sourceChain,
|
|
2559
|
+
snapshots: (gitSnapshot?.files ?? []).map((f) => ({
|
|
2560
|
+
filePath: f.filePath,
|
|
2561
|
+
changeStatus: f.changeStatus,
|
|
2562
|
+
lineRanges: f.lineRanges,
|
|
2563
|
+
linesAdded: f.linesAdded,
|
|
2564
|
+
linesRemoved: f.linesRemoved,
|
|
2565
|
+
progressNote: f.progressNote,
|
|
2566
|
+
contentSha256: f.contentSha256,
|
|
2567
|
+
unifiedDiff: f.unifiedDiff
|
|
2568
|
+
}))
|
|
2569
|
+
});
|
|
2570
|
+
capsulesUpdated += 1;
|
|
2571
|
+
this.emitEvent({
|
|
2572
|
+
type: "capsule_updated",
|
|
2573
|
+
projectId: project.id,
|
|
2574
|
+
sessionId: session.id,
|
|
2575
|
+
capsuleId: saved.id,
|
|
2576
|
+
cliSource: file.cliSource,
|
|
2577
|
+
message: `Compiled capsule v${saved.version} (${saved.capsule_tokens} tok)`
|
|
2578
|
+
});
|
|
2579
|
+
}
|
|
2580
|
+
return {
|
|
2581
|
+
filesChecked: discovered.length,
|
|
2582
|
+
eventsIngested,
|
|
2583
|
+
capsulesUpdated
|
|
2584
|
+
};
|
|
2585
|
+
}
|
|
2586
|
+
start() {
|
|
2587
|
+
const discovered = discoverSessionFiles(this.roots);
|
|
2588
|
+
const paths = discovered.map((d) => d.filePath);
|
|
2589
|
+
if (paths.length > 0) {
|
|
2590
|
+
this.watcher = watch(paths, { ignoreInitial: true, awaitWriteFinish: { stabilityThreshold: 120, pollInterval: 40 } });
|
|
2591
|
+
this.watcher.on("change", () => {
|
|
2592
|
+
void this.syncOnce();
|
|
2593
|
+
});
|
|
2594
|
+
this.watcher.on("add", () => {
|
|
2595
|
+
void this.syncOnce();
|
|
2596
|
+
});
|
|
2597
|
+
}
|
|
2598
|
+
this.rescanTimer = setInterval(() => {
|
|
2599
|
+
void this.syncOnce();
|
|
2600
|
+
}, 15e3);
|
|
2601
|
+
this.rescanTimer.unref();
|
|
2602
|
+
}
|
|
2603
|
+
async stop() {
|
|
2604
|
+
if (this.rescanTimer) {
|
|
2605
|
+
clearInterval(this.rescanTimer);
|
|
2606
|
+
this.rescanTimer = null;
|
|
2607
|
+
}
|
|
2608
|
+
if (this.watcher) {
|
|
2609
|
+
await this.watcher.close();
|
|
2610
|
+
this.watcher = null;
|
|
2611
|
+
}
|
|
2612
|
+
}
|
|
2613
|
+
};
|
|
2614
|
+
|
|
2615
|
+
// packages/cli/src/injectors/fenced-file.ts
|
|
2616
|
+
import { existsSync as existsSync5, mkdirSync as mkdirSync2, readFileSync as readFileSync2, unlinkSync, writeFileSync } from "node:fs";
|
|
2617
|
+
import { dirname as dirname4, join as join7, relative } from "node:path";
|
|
2618
|
+
var BLOCK_REGEX = /<!--\s*CMEM:CAPSULE:START[^>]*-->[\s\S]*?<!--\s*CMEM:CAPSULE:END\s*-->\n?/g;
|
|
2619
|
+
function getTargetFileForCli(cli) {
|
|
2620
|
+
switch (cli) {
|
|
2621
|
+
case "claude":
|
|
2622
|
+
return { relativePath: "CLAUDE.md", deliveryMethod: "claude_md" };
|
|
2623
|
+
case "codex":
|
|
2624
|
+
return { relativePath: "AGENTS.md", deliveryMethod: "agents_md" };
|
|
2625
|
+
case "gemini":
|
|
2626
|
+
case "agy":
|
|
2627
|
+
return { relativePath: "GEMINI.md", deliveryMethod: "gemini_md" };
|
|
2628
|
+
case "cursor":
|
|
2629
|
+
return {
|
|
2630
|
+
relativePath: ".cursor/rules/cmem-active-handoff.mdc",
|
|
2631
|
+
deliveryMethod: "cursor_rule"
|
|
2632
|
+
};
|
|
2633
|
+
case "manual":
|
|
2634
|
+
return { relativePath: "AGENTS.md", deliveryMethod: "agents_md" };
|
|
2635
|
+
}
|
|
2636
|
+
}
|
|
2637
|
+
function buildFencedBlock(capsuleId, version, markdown) {
|
|
2638
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
2639
|
+
return [
|
|
2640
|
+
`<!-- CMEM:CAPSULE:START version="v${version}" capsule_id="${capsuleId}" generated_at="${timestamp}" -->`,
|
|
2641
|
+
markdown.trim(),
|
|
2642
|
+
`<!-- CMEM:CAPSULE:END -->`
|
|
2643
|
+
].join("\n");
|
|
2644
|
+
}
|
|
2645
|
+
function upsertFencedCapsuleContent(existingContent, capsuleId, version, markdown, isCursorRule = false) {
|
|
2646
|
+
const block = buildFencedBlock(capsuleId, version, markdown);
|
|
2647
|
+
BLOCK_REGEX.lastIndex = 0;
|
|
2648
|
+
if (BLOCK_REGEX.test(existingContent)) {
|
|
2649
|
+
BLOCK_REGEX.lastIndex = 0;
|
|
2650
|
+
return existingContent.replace(BLOCK_REGEX, `${block}
|
|
2651
|
+
`).trimEnd() + "\n";
|
|
2652
|
+
}
|
|
2653
|
+
const trimmed = existingContent.trimEnd();
|
|
2654
|
+
if (!trimmed) {
|
|
2655
|
+
if (isCursorRule) {
|
|
2656
|
+
return `---
|
|
2657
|
+
description: Active Cross-Memory Handoff Capsule
|
|
2658
|
+
alwaysApply: true
|
|
2659
|
+
---
|
|
2660
|
+
|
|
2661
|
+
${block}
|
|
2662
|
+
`;
|
|
2663
|
+
}
|
|
2664
|
+
return `${block}
|
|
2665
|
+
`;
|
|
2666
|
+
}
|
|
2667
|
+
return `${trimmed}
|
|
2668
|
+
|
|
2669
|
+
${block}
|
|
2670
|
+
`;
|
|
2671
|
+
}
|
|
2672
|
+
function stripFencedCapsuleContent(existingContent) {
|
|
2673
|
+
BLOCK_REGEX.lastIndex = 0;
|
|
2674
|
+
return existingContent.replace(BLOCK_REGEX, "").replace(/\n{3,}/g, "\n\n").trim();
|
|
2675
|
+
}
|
|
2676
|
+
function injectFencedCapsuleFile(params) {
|
|
2677
|
+
const info = getTargetFileForCli(params.targetCli);
|
|
2678
|
+
const fullPath = join7(params.repoRoot, info.relativePath);
|
|
2679
|
+
mkdirSync2(dirname4(fullPath), { recursive: true });
|
|
2680
|
+
const existing = existsSync5(fullPath) ? readFileSync2(fullPath, "utf8") : "";
|
|
2681
|
+
const updated = upsertFencedCapsuleContent(
|
|
2682
|
+
existing,
|
|
2683
|
+
params.capsuleId,
|
|
2684
|
+
params.version,
|
|
2685
|
+
params.markdown,
|
|
2686
|
+
info.deliveryMethod === "cursor_rule"
|
|
2687
|
+
);
|
|
2688
|
+
writeFileSync(fullPath, updated, "utf8");
|
|
2689
|
+
if (params.gitExclude) {
|
|
2690
|
+
ensureGitExclude(params.repoRoot, info.relativePath);
|
|
2691
|
+
}
|
|
2692
|
+
return {
|
|
2693
|
+
filePath: fullPath,
|
|
2694
|
+
relativePath: info.relativePath,
|
|
2695
|
+
deliveryMethod: info.deliveryMethod
|
|
2696
|
+
};
|
|
2697
|
+
}
|
|
2698
|
+
function cleanFencedCapsuleFiles(repoRoot) {
|
|
2699
|
+
const candidates = [
|
|
2700
|
+
"CLAUDE.md",
|
|
2701
|
+
"AGENTS.md",
|
|
2702
|
+
"GEMINI.md",
|
|
2703
|
+
".cursor/rules/cmem-active-handoff.mdc"
|
|
2704
|
+
];
|
|
2705
|
+
const cleaned = [];
|
|
2706
|
+
for (const rel of candidates) {
|
|
2707
|
+
const full = join7(repoRoot, rel);
|
|
2708
|
+
if (!existsSync5(full)) continue;
|
|
2709
|
+
const raw = readFileSync2(full, "utf8");
|
|
2710
|
+
BLOCK_REGEX.lastIndex = 0;
|
|
2711
|
+
if (!BLOCK_REGEX.test(raw)) continue;
|
|
2712
|
+
const stripped = stripFencedCapsuleContent(raw);
|
|
2713
|
+
if (!stripped || rel === ".cursor/rules/cmem-active-handoff.mdc") {
|
|
2714
|
+
if (!stripped || stripped.startsWith("---\ndescription: Active Cross-Memory Handoff Capsule")) {
|
|
2715
|
+
unlinkSync(full);
|
|
2716
|
+
cleaned.push(rel);
|
|
2717
|
+
continue;
|
|
2718
|
+
}
|
|
2719
|
+
}
|
|
2720
|
+
writeFileSync(full, `${stripped}
|
|
2721
|
+
`, "utf8");
|
|
2722
|
+
cleaned.push(rel);
|
|
2723
|
+
}
|
|
2724
|
+
return cleaned;
|
|
2725
|
+
}
|
|
2726
|
+
function ensureGitExclude(repoRoot, relPath) {
|
|
2727
|
+
const excludeFile = join7(repoRoot, ".git", "info", "exclude");
|
|
2728
|
+
if (!existsSync5(join7(repoRoot, ".git"))) return;
|
|
2729
|
+
mkdirSync2(dirname4(excludeFile), { recursive: true });
|
|
2730
|
+
const existing = existsSync5(excludeFile) ? readFileSync2(excludeFile, "utf8") : "";
|
|
2731
|
+
const normalized = relative(repoRoot, join7(repoRoot, relPath));
|
|
2732
|
+
const lines = existing.split("\n").map((l) => l.trim());
|
|
2733
|
+
if (!lines.includes(normalized)) {
|
|
2734
|
+
const prefix = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";
|
|
2735
|
+
writeFileSync(excludeFile, `${existing}${prefix}${normalized}
|
|
2736
|
+
`, "utf8");
|
|
2737
|
+
}
|
|
2738
|
+
}
|
|
2739
|
+
|
|
2740
|
+
// packages/cli/src/injectors/resume-builder.ts
|
|
2741
|
+
import { spawnSync } from "node:child_process";
|
|
2742
|
+
function buildStartupPrompt(capsule) {
|
|
2743
|
+
return [
|
|
2744
|
+
"Resume the active engineering task using the distilled Cross-Memory Context Capsule below.",
|
|
2745
|
+
"Respect all locked decisions and DO NOT retry listed dead ends. Confirm the first remaining checklist item and proceed.",
|
|
2746
|
+
"",
|
|
2747
|
+
capsule.capsule_markdown.trim()
|
|
2748
|
+
].join("\n");
|
|
2749
|
+
}
|
|
2750
|
+
function buildHandoffPlan(params) {
|
|
2751
|
+
const targetAccount = params.targetAccount ?? "default";
|
|
2752
|
+
const startupPrompt = buildStartupPrompt(params.capsule);
|
|
2753
|
+
let binary = params.targetCli;
|
|
2754
|
+
let args = [];
|
|
2755
|
+
let defaultDelivery = "cli_prompt";
|
|
2756
|
+
switch (params.targetCli) {
|
|
2757
|
+
case "claude":
|
|
2758
|
+
binary = "claude";
|
|
2759
|
+
args = [
|
|
2760
|
+
"--append-system-prompt",
|
|
2761
|
+
params.capsule.capsule_markdown.trim(),
|
|
2762
|
+
"Resume the active task from the injected Cross-Memory Context Capsule. Confirm the next step before editing."
|
|
2763
|
+
];
|
|
2764
|
+
defaultDelivery = params.injectFile ? "claude_md" : "cli_prompt";
|
|
2765
|
+
break;
|
|
2766
|
+
case "codex":
|
|
2767
|
+
binary = "codex";
|
|
2768
|
+
args = [startupPrompt];
|
|
2769
|
+
defaultDelivery = params.injectFile ? "agents_md" : "cli_prompt";
|
|
2770
|
+
break;
|
|
2771
|
+
case "gemini":
|
|
2772
|
+
binary = "gemini";
|
|
2773
|
+
args = ["-i", startupPrompt];
|
|
2774
|
+
defaultDelivery = params.injectFile ? "gemini_md" : "cli_prompt";
|
|
2775
|
+
break;
|
|
2776
|
+
case "agy":
|
|
2777
|
+
binary = "agy";
|
|
2778
|
+
args = [startupPrompt];
|
|
2779
|
+
defaultDelivery = params.injectFile ? "gemini_md" : "cli_prompt";
|
|
2780
|
+
break;
|
|
2781
|
+
case "cursor":
|
|
2782
|
+
binary = "cursor";
|
|
2783
|
+
args = ["."];
|
|
2784
|
+
defaultDelivery = params.injectFile ? "cursor_rule" : "clipboard";
|
|
2785
|
+
break;
|
|
2786
|
+
case "manual":
|
|
2787
|
+
binary = "echo";
|
|
2788
|
+
args = [startupPrompt];
|
|
2789
|
+
defaultDelivery = "clipboard";
|
|
2790
|
+
break;
|
|
2791
|
+
}
|
|
2792
|
+
const flags = [`--to ${params.targetCli}`];
|
|
2793
|
+
if (targetAccount !== "default") flags.push(`--account ${targetAccount}`);
|
|
2794
|
+
if (params.injectFile) flags.push("--inject-file");
|
|
2795
|
+
flags.push(`--capsule ${params.capsule.id}`);
|
|
2796
|
+
return {
|
|
2797
|
+
targetCli: params.targetCli,
|
|
2798
|
+
targetAccount,
|
|
2799
|
+
deliveryMethod: defaultDelivery,
|
|
2800
|
+
startupPrompt,
|
|
2801
|
+
binary,
|
|
2802
|
+
args,
|
|
2803
|
+
handoffCommand: `cmem resume ${flags.join(" ")}`
|
|
2804
|
+
};
|
|
2805
|
+
}
|
|
2806
|
+
function copyToClipboard(text) {
|
|
2807
|
+
const candidates = process.platform === "darwin" ? [{ cmd: "pbcopy", args: [] }] : [
|
|
2808
|
+
{ cmd: "wl-copy", args: [] },
|
|
2809
|
+
{ cmd: "xclip", args: ["-selection", "clipboard"] }
|
|
2810
|
+
];
|
|
2811
|
+
for (const { cmd, args } of candidates) {
|
|
2812
|
+
const res = spawnSync(cmd, args, { input: text, encoding: "utf8" });
|
|
2813
|
+
if (!res.error && res.status === 0) {
|
|
2814
|
+
return { copied: true, method: cmd };
|
|
2815
|
+
}
|
|
2816
|
+
}
|
|
2817
|
+
return { copied: false, method: "none" };
|
|
2818
|
+
}
|
|
2819
|
+
|
|
2820
|
+
// packages/cli/src/mcp/server.ts
|
|
2821
|
+
import { resolve as resolve2 } from "node:path";
|
|
2822
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2823
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
2824
|
+
import { z } from "zod";
|
|
2825
|
+
function resolveProjectForMcp(store, projectPath) {
|
|
2826
|
+
if (projectPath) {
|
|
2827
|
+
const byRoot = store.getProjectByRepoRoot(resolve2(projectPath));
|
|
2828
|
+
if (byRoot) return byRoot;
|
|
2829
|
+
}
|
|
2830
|
+
const byCwd = store.getProjectByRepoRoot(resolve2(process.cwd()));
|
|
2831
|
+
if (byCwd) return byCwd;
|
|
2832
|
+
const all = store.listProjects();
|
|
2833
|
+
return all[0] ?? null;
|
|
2834
|
+
}
|
|
2835
|
+
function createCmemMcpServer(store, onMutation) {
|
|
2836
|
+
const server = new McpServer({
|
|
2837
|
+
name: "cmem",
|
|
2838
|
+
version: "0.1.0"
|
|
2839
|
+
});
|
|
2840
|
+
const compiler = new CapsuleCompiler();
|
|
2841
|
+
server.registerTool(
|
|
2842
|
+
"get_active_context",
|
|
2843
|
+
{
|
|
2844
|
+
description: "Retrieve the compact (<1,500 tokens) Cross-Memory Context Capsule for the active workspace, including goal, locked decisions, touched files with line ranges, dead ends to avoid, and remaining checklist.",
|
|
2845
|
+
inputSchema: z.object({
|
|
2846
|
+
project_path: z.string().optional().describe("Absolute repository path; defaults to active workspace"),
|
|
2847
|
+
session_id: z.string().optional().describe("Optional specific session ID"),
|
|
2848
|
+
max_tokens: z.number().int().min(300).max(2e3).default(1500).optional(),
|
|
2849
|
+
format: z.enum(["markdown", "json"]).default("markdown").optional()
|
|
2850
|
+
})
|
|
2851
|
+
},
|
|
2852
|
+
async (args) => {
|
|
2853
|
+
const project = resolveProjectForMcp(store, args.project_path);
|
|
2854
|
+
if (!project) {
|
|
2855
|
+
return {
|
|
2856
|
+
isError: true,
|
|
2857
|
+
content: [{ type: "text", text: "No tracked project found in Cross-Memory database." }]
|
|
2858
|
+
};
|
|
2859
|
+
}
|
|
2860
|
+
const capsule = args.session_id ? store.listCapsulesByProject(project.id).find((c) => c.session_id === args.session_id) ?? store.getActiveCapsule(project.id) : store.getActiveCapsule(project.id);
|
|
2861
|
+
if (!capsule) {
|
|
2862
|
+
return {
|
|
2863
|
+
isError: true,
|
|
2864
|
+
content: [{ type: "text", text: `No Context Capsule available yet for project ${project.name}.` }]
|
|
2865
|
+
};
|
|
2866
|
+
}
|
|
2867
|
+
const format = args.format ?? "markdown";
|
|
2868
|
+
const payload = JSON.parse(capsule.capsule_json);
|
|
2869
|
+
const body = format === "json" ? JSON.stringify(payload, null, 2) : `${capsule.capsule_markdown}
|
|
2870
|
+
|
|
2871
|
+
<!-- meta: capsule=${capsule.id} v${capsule.version} tokens=${capsule.capsule_tokens} saved=${capsule.tokens_saved} -->`;
|
|
2872
|
+
return {
|
|
2873
|
+
content: [{ type: "text", text: body }],
|
|
2874
|
+
structuredContent: {
|
|
2875
|
+
capsule_id: capsule.id,
|
|
2876
|
+
version: capsule.version,
|
|
2877
|
+
project_id: project.id,
|
|
2878
|
+
project_name: project.name,
|
|
2879
|
+
capsule_tokens: capsule.capsule_tokens,
|
|
2880
|
+
raw_tokens_covered: capsule.raw_tokens_covered,
|
|
2881
|
+
tokens_saved: capsule.tokens_saved,
|
|
2882
|
+
source_chain: JSON.parse(capsule.source_chain_json)
|
|
2883
|
+
}
|
|
2884
|
+
};
|
|
2885
|
+
}
|
|
2886
|
+
);
|
|
2887
|
+
server.registerTool(
|
|
2888
|
+
"search_past_decisions",
|
|
2889
|
+
{
|
|
2890
|
+
description: "Full-text FTS5 BM25 search across historical architectural decisions, constraints, dead ends, and capsules across all CLIs and projects.",
|
|
2891
|
+
inputSchema: z.object({
|
|
2892
|
+
query: z.string().min(2).describe('Keyword or technical phrase (e.g. "SKIP LOCKED", "useFakeTimers")'),
|
|
2893
|
+
project_path: z.string().optional().describe("Filter to a specific repo path; omit for cross-project search"),
|
|
2894
|
+
cli_source: z.enum(CLI_SOURCES).optional(),
|
|
2895
|
+
category: z.enum([...DECISION_CATEGORIES, "capsule"]).optional(),
|
|
2896
|
+
limit: z.number().int().min(1).max(30).default(10).optional()
|
|
2897
|
+
})
|
|
2898
|
+
},
|
|
2899
|
+
async (args) => {
|
|
2900
|
+
const project = args.project_path ? store.getProjectByRepoRoot(resolve2(args.project_path)) : null;
|
|
2901
|
+
const results = store.searchMemory({
|
|
2902
|
+
query: args.query,
|
|
2903
|
+
projectId: project?.id,
|
|
2904
|
+
cliSource: args.cli_source,
|
|
2905
|
+
category: args.category,
|
|
2906
|
+
page: 1,
|
|
2907
|
+
pageSize: args.limit ?? 10
|
|
2908
|
+
});
|
|
2909
|
+
return {
|
|
2910
|
+
content: [{ type: "text", text: JSON.stringify(results.hits, null, 2) }],
|
|
2911
|
+
structuredContent: {
|
|
2912
|
+
total: results.total,
|
|
2913
|
+
hits: results.hits
|
|
2914
|
+
}
|
|
2915
|
+
};
|
|
2916
|
+
}
|
|
2917
|
+
);
|
|
2918
|
+
server.registerTool(
|
|
2919
|
+
"log_checkpoint",
|
|
2920
|
+
{
|
|
2921
|
+
description: "Emit a structured mid-session working-memory checkpoint (locked decisions, dead ends discovered, or remaining steps) and recompile the active Context Capsule.",
|
|
2922
|
+
inputSchema: z.object({
|
|
2923
|
+
project_path: z.string().optional(),
|
|
2924
|
+
cli_source: z.enum(CLI_SOURCES).default("manual").optional(),
|
|
2925
|
+
summary: z.string().min(4).max(1e3),
|
|
2926
|
+
decisions: z.array(z.string()).optional(),
|
|
2927
|
+
dead_ends: z.array(z.string()).optional(),
|
|
2928
|
+
next_steps: z.array(z.string()).optional(),
|
|
2929
|
+
files: z.array(z.string()).optional()
|
|
2930
|
+
})
|
|
2931
|
+
},
|
|
2932
|
+
async (args) => {
|
|
2933
|
+
const cliSource = args.cli_source ?? "manual";
|
|
2934
|
+
const resolvedPath = resolve2(args.project_path ?? process.cwd());
|
|
2935
|
+
const project = store.upsertProject({
|
|
2936
|
+
repoRoot: resolvedPath,
|
|
2937
|
+
activeCli: cliSource
|
|
2938
|
+
});
|
|
2939
|
+
const session = store.getLatestSessionForProject(project.id) ?? store.upsertSession({
|
|
2940
|
+
projectId: project.id,
|
|
2941
|
+
cliSource,
|
|
2942
|
+
externalSessionId: `mcp-${Date.now()}`,
|
|
2943
|
+
gitBranch: project.active_branch,
|
|
2944
|
+
modelName: "mcp-agent"
|
|
2945
|
+
});
|
|
2946
|
+
const createdDecisionIds = [];
|
|
2947
|
+
for (const stmt of args.decisions ?? []) {
|
|
2948
|
+
const rec = store.addDecisionLog({
|
|
2949
|
+
projectId: project.id,
|
|
2950
|
+
sessionId: session.id,
|
|
2951
|
+
cliSource,
|
|
2952
|
+
category: "architecture",
|
|
2953
|
+
title: stmt,
|
|
2954
|
+
body: stmt,
|
|
2955
|
+
rationale: args.summary,
|
|
2956
|
+
fileRefs: args.files ?? [],
|
|
2957
|
+
isPinned: true
|
|
2958
|
+
});
|
|
2959
|
+
createdDecisionIds.push(rec.id);
|
|
2960
|
+
}
|
|
2961
|
+
for (const de of args.dead_ends ?? []) {
|
|
2962
|
+
const rec = store.addDecisionLog({
|
|
2963
|
+
projectId: project.id,
|
|
2964
|
+
sessionId: session.id,
|
|
2965
|
+
cliSource,
|
|
2966
|
+
category: "dead_end",
|
|
2967
|
+
title: de,
|
|
2968
|
+
body: de,
|
|
2969
|
+
rationale: args.summary,
|
|
2970
|
+
errorFingerprint: `mcp_${de.toLowerCase().replace(/[^a-z0-9]+/g, "_").slice(0, 28)}`,
|
|
2971
|
+
fileRefs: args.files ?? []
|
|
2972
|
+
});
|
|
2973
|
+
createdDecisionIds.push(rec.id);
|
|
2974
|
+
}
|
|
2975
|
+
for (const step of args.next_steps ?? []) {
|
|
2976
|
+
const rec = store.addDecisionLog({
|
|
2977
|
+
projectId: project.id,
|
|
2978
|
+
sessionId: session.id,
|
|
2979
|
+
cliSource,
|
|
2980
|
+
category: "next_step",
|
|
2981
|
+
title: step,
|
|
2982
|
+
body: step,
|
|
2983
|
+
fileRefs: args.files ?? []
|
|
2984
|
+
});
|
|
2985
|
+
createdDecisionIds.push(rec.id);
|
|
2986
|
+
}
|
|
2987
|
+
const prevCapsule = store.getActiveCapsule(project.id);
|
|
2988
|
+
const prevChain = prevCapsule ? JSON.parse(prevCapsule.source_chain_json) : [];
|
|
2989
|
+
const compiled = await compiler.compile({
|
|
2990
|
+
projectId: project.id,
|
|
2991
|
+
projectName: project.name,
|
|
2992
|
+
repoRoot: project.repo_root,
|
|
2993
|
+
events: [
|
|
2994
|
+
{
|
|
2995
|
+
externalEventId: `mcp_${Date.now()}`,
|
|
2996
|
+
cliSource,
|
|
2997
|
+
externalSessionId: session.external_session_id,
|
|
2998
|
+
projectRoot: project.repo_root,
|
|
2999
|
+
gitBranch: project.active_branch,
|
|
3000
|
+
modelName: session.model_name,
|
|
3001
|
+
accountLabel: session.account_label,
|
|
3002
|
+
role: "user",
|
|
3003
|
+
timestampIso: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3004
|
+
textContent: args.summary
|
|
3005
|
+
}
|
|
3006
|
+
],
|
|
3007
|
+
existingDecisions: store.listDecisionsByProject(project.id),
|
|
3008
|
+
previousSourceChain: prevChain,
|
|
3009
|
+
trigger: "mcp_checkpoint"
|
|
3010
|
+
});
|
|
3011
|
+
const saved = store.saveCapsule({
|
|
3012
|
+
projectId: project.id,
|
|
3013
|
+
sessionId: session.id,
|
|
3014
|
+
triggerReason: "mcp_checkpoint",
|
|
3015
|
+
gitBranch: compiled.payload.gitBranch,
|
|
3016
|
+
gitHeadSha: compiled.payload.gitHeadSha,
|
|
3017
|
+
isDirtyTree: compiled.payload.isDirtyTree,
|
|
3018
|
+
payload: compiled.payload,
|
|
3019
|
+
markdown: compiled.markdown,
|
|
3020
|
+
rawTokensCovered: Math.max(prevCapsule?.raw_tokens_covered ?? 0, compiled.capsuleTokens),
|
|
3021
|
+
sourceChain: compiled.payload.sourceChain
|
|
3022
|
+
});
|
|
3023
|
+
onMutation?.({ type: "capsule_updated", projectId: project.id, capsuleId: saved.id });
|
|
3024
|
+
return {
|
|
3025
|
+
content: [
|
|
3026
|
+
{
|
|
3027
|
+
type: "text",
|
|
3028
|
+
text: `Checkpoint logged. Capsule v${saved.version} (${saved.id}) active at ${saved.capsule_tokens} tokens.`
|
|
3029
|
+
}
|
|
3030
|
+
],
|
|
3031
|
+
structuredContent: {
|
|
3032
|
+
capsule_id: saved.id,
|
|
3033
|
+
version: saved.version,
|
|
3034
|
+
capsule_tokens: saved.capsule_tokens,
|
|
3035
|
+
decision_ids_created: createdDecisionIds
|
|
3036
|
+
}
|
|
3037
|
+
};
|
|
3038
|
+
}
|
|
3039
|
+
);
|
|
3040
|
+
server.registerTool(
|
|
3041
|
+
"prepare_handoff",
|
|
3042
|
+
{
|
|
3043
|
+
description: "Generate a target-CLI-ready handoff payload and shell resume command, and record the handoff event.",
|
|
3044
|
+
inputSchema: z.object({
|
|
3045
|
+
target_cli: z.enum(CLI_SOURCES),
|
|
3046
|
+
target_account: z.string().default("default").optional(),
|
|
3047
|
+
reason: z.enum(HANDOFF_REASONS).default("quota_exhausted").optional(),
|
|
3048
|
+
project_path: z.string().optional()
|
|
3049
|
+
})
|
|
3050
|
+
},
|
|
3051
|
+
async (args) => {
|
|
3052
|
+
const project = resolveProjectForMcp(store, args.project_path);
|
|
3053
|
+
if (!project) {
|
|
3054
|
+
return { isError: true, content: [{ type: "text", text: "No active project found." }] };
|
|
3055
|
+
}
|
|
3056
|
+
const capsule = store.getActiveCapsule(project.id);
|
|
3057
|
+
if (!capsule) {
|
|
3058
|
+
return { isError: true, content: [{ type: "text", text: "No active capsule found." }] };
|
|
3059
|
+
}
|
|
3060
|
+
const latestSession = store.getLatestSessionForProject(project.id);
|
|
3061
|
+
const plan = buildHandoffPlan({
|
|
3062
|
+
capsule,
|
|
3063
|
+
targetCli: args.target_cli,
|
|
3064
|
+
targetAccount: args.target_account
|
|
3065
|
+
});
|
|
3066
|
+
const handoff = store.recordHandoff({
|
|
3067
|
+
projectId: project.id,
|
|
3068
|
+
capsuleId: capsule.id,
|
|
3069
|
+
fromSessionId: latestSession?.id ?? null,
|
|
3070
|
+
fromCli: latestSession?.cli_source ?? "manual",
|
|
3071
|
+
toCli: args.target_cli,
|
|
3072
|
+
fromAccount: latestSession?.account_label ?? "default",
|
|
3073
|
+
toAccount: plan.targetAccount,
|
|
3074
|
+
reason: args.reason ?? "quota_exhausted",
|
|
3075
|
+
deliveryMethod: plan.deliveryMethod,
|
|
3076
|
+
injectedTokens: capsule.capsule_tokens,
|
|
3077
|
+
rawTokensAvoided: capsule.tokens_saved,
|
|
3078
|
+
handoffCommand: plan.handoffCommand
|
|
3079
|
+
});
|
|
3080
|
+
onMutation?.({ type: "handoff_created", projectId: project.id, capsuleId: capsule.id });
|
|
3081
|
+
return {
|
|
3082
|
+
content: [
|
|
3083
|
+
{
|
|
3084
|
+
type: "text",
|
|
3085
|
+
text: `Handoff ${handoff.id} ready.
|
|
3086
|
+
Command: ${plan.handoffCommand}
|
|
3087
|
+
|
|
3088
|
+
${plan.startupPrompt}`
|
|
3089
|
+
}
|
|
3090
|
+
],
|
|
3091
|
+
structuredContent: {
|
|
3092
|
+
handoff_id: handoff.id,
|
|
3093
|
+
command: plan.handoffCommand,
|
|
3094
|
+
capsule_markdown: capsule.capsule_markdown,
|
|
3095
|
+
capsule_tokens: capsule.capsule_tokens
|
|
3096
|
+
}
|
|
3097
|
+
};
|
|
3098
|
+
}
|
|
3099
|
+
);
|
|
3100
|
+
server.registerResource(
|
|
3101
|
+
"active-capsule",
|
|
3102
|
+
"cmem://active/capsule",
|
|
3103
|
+
{
|
|
3104
|
+
description: "Live distilled Context Capsule (<1,500 tokens) for the primary workspace",
|
|
3105
|
+
mimeType: "text/markdown"
|
|
3106
|
+
},
|
|
3107
|
+
async () => {
|
|
3108
|
+
const project = resolveProjectForMcp(store);
|
|
3109
|
+
const capsule = project ? store.getActiveCapsule(project.id) : null;
|
|
3110
|
+
return {
|
|
3111
|
+
contents: [
|
|
3112
|
+
{
|
|
3113
|
+
uri: "cmem://active/capsule",
|
|
3114
|
+
mimeType: "text/markdown",
|
|
3115
|
+
text: capsule?.capsule_markdown ?? "# No active Context Capsule"
|
|
3116
|
+
}
|
|
3117
|
+
]
|
|
3118
|
+
};
|
|
3119
|
+
}
|
|
3120
|
+
);
|
|
3121
|
+
server.registerResource(
|
|
3122
|
+
"active-decisions",
|
|
3123
|
+
"cmem://active/decisions",
|
|
3124
|
+
{
|
|
3125
|
+
description: "Locked architectural decisions, constraints, and dead ends for the active workspace",
|
|
3126
|
+
mimeType: "application/json"
|
|
3127
|
+
},
|
|
3128
|
+
async () => {
|
|
3129
|
+
const project = resolveProjectForMcp(store);
|
|
3130
|
+
const decisions = project ? store.listDecisionsByProject(project.id) : [];
|
|
3131
|
+
return {
|
|
3132
|
+
contents: [
|
|
3133
|
+
{
|
|
3134
|
+
uri: "cmem://active/decisions",
|
|
3135
|
+
mimeType: "application/json",
|
|
3136
|
+
text: JSON.stringify(decisions, null, 2)
|
|
3137
|
+
}
|
|
3138
|
+
]
|
|
3139
|
+
};
|
|
3140
|
+
}
|
|
3141
|
+
);
|
|
3142
|
+
return server;
|
|
3143
|
+
}
|
|
3144
|
+
async function startMcpStdioServer(store) {
|
|
3145
|
+
const server = createCmemMcpServer(store);
|
|
3146
|
+
const transport = new StdioServerTransport();
|
|
3147
|
+
await server.connect(transport);
|
|
3148
|
+
}
|
|
3149
|
+
|
|
3150
|
+
// packages/cli/src/server/http.ts
|
|
3151
|
+
import { existsSync as existsSync6 } from "node:fs";
|
|
3152
|
+
import { dirname as dirname5, join as join8 } from "node:path";
|
|
3153
|
+
import { fileURLToPath } from "node:url";
|
|
3154
|
+
import Fastify from "fastify";
|
|
3155
|
+
import fastifyStatic from "@fastify/static";
|
|
3156
|
+
import { z as z2 } from "zod";
|
|
3157
|
+
var PatchCapsuleSchema = z2.object({
|
|
3158
|
+
goalSummary: z2.string().min(4).max(500).optional(),
|
|
3159
|
+
decisionsLocked: z2.array(
|
|
3160
|
+
z2.object({
|
|
3161
|
+
id: z2.string(),
|
|
3162
|
+
statement: z2.string().min(1),
|
|
3163
|
+
rationale: z2.string().default(""),
|
|
3164
|
+
cliSource: z2.enum(CLI_SOURCES),
|
|
3165
|
+
lockedAt: z2.string()
|
|
3166
|
+
})
|
|
3167
|
+
).optional(),
|
|
3168
|
+
deadEndsAvoid: z2.array(
|
|
3169
|
+
z2.object({
|
|
3170
|
+
fingerprint: z2.string(),
|
|
3171
|
+
attempted: z2.string().min(1),
|
|
3172
|
+
errorSummary: z2.string().min(1),
|
|
3173
|
+
occurrences: z2.number().int().min(1),
|
|
3174
|
+
cliSource: z2.enum(CLI_SOURCES)
|
|
3175
|
+
})
|
|
3176
|
+
).optional(),
|
|
3177
|
+
nextSteps: z2.array(
|
|
3178
|
+
z2.object({
|
|
3179
|
+
order: z2.number().int().min(1),
|
|
3180
|
+
task: z2.string().min(1),
|
|
3181
|
+
verifyCommand: z2.string().optional(),
|
|
3182
|
+
done: z2.boolean()
|
|
3183
|
+
})
|
|
3184
|
+
).optional()
|
|
3185
|
+
});
|
|
3186
|
+
var CreateHandoffSchema = z2.object({
|
|
3187
|
+
projectId: z2.string().min(1),
|
|
3188
|
+
capsuleId: z2.string().optional(),
|
|
3189
|
+
targetCli: z2.enum(CLI_SOURCES),
|
|
3190
|
+
targetAccount: z2.string().default("default").optional(),
|
|
3191
|
+
reason: z2.enum(HANDOFF_REASONS).default("quota_exhausted").optional(),
|
|
3192
|
+
injectFile: z2.boolean().default(false).optional(),
|
|
3193
|
+
gitExclude: z2.boolean().default(true).optional()
|
|
3194
|
+
});
|
|
3195
|
+
var SearchQuerySchema = z2.object({
|
|
3196
|
+
q: z2.string().default(""),
|
|
3197
|
+
projectId: z2.string().optional(),
|
|
3198
|
+
cliSource: z2.enum(CLI_SOURCES).optional(),
|
|
3199
|
+
category: z2.enum([...DECISION_CATEGORIES, "capsule"]).optional(),
|
|
3200
|
+
page: z2.coerce.number().int().min(1).default(1),
|
|
3201
|
+
pageSize: z2.coerce.number().int().min(1).max(50).default(20)
|
|
3202
|
+
});
|
|
3203
|
+
function resolveWebDistPath() {
|
|
3204
|
+
const here = dirname5(fileURLToPath(import.meta.url));
|
|
3205
|
+
const candidates = [
|
|
3206
|
+
join8(here, "../public"),
|
|
3207
|
+
join8(here, "../../public"),
|
|
3208
|
+
join8(here, "../../../../dist/public"),
|
|
3209
|
+
join8(here, "../../../web/dist"),
|
|
3210
|
+
join8(here, "../../../../packages/web/dist"),
|
|
3211
|
+
join8(process.cwd(), "dist/public"),
|
|
3212
|
+
join8(process.cwd(), "packages/web/dist")
|
|
3213
|
+
];
|
|
3214
|
+
for (const c of candidates) {
|
|
3215
|
+
if (existsSync6(join8(c, "index.html"))) return c;
|
|
3216
|
+
}
|
|
3217
|
+
return null;
|
|
3218
|
+
}
|
|
3219
|
+
function createControlPlaneServer(params) {
|
|
3220
|
+
const { store, watcher } = params;
|
|
3221
|
+
const app = Fastify({ logger: false });
|
|
3222
|
+
const sseClients = /* @__PURE__ */ new Set();
|
|
3223
|
+
const broadcast = (ev) => {
|
|
3224
|
+
const payload = `event: ${ev.type}
|
|
3225
|
+
data: ${JSON.stringify(ev)}
|
|
3226
|
+
|
|
3227
|
+
`;
|
|
3228
|
+
for (const client of sseClients) {
|
|
3229
|
+
try {
|
|
3230
|
+
client.write(payload);
|
|
3231
|
+
} catch {
|
|
3232
|
+
sseClients.delete(client);
|
|
3233
|
+
}
|
|
3234
|
+
}
|
|
3235
|
+
};
|
|
3236
|
+
if (watcher) {
|
|
3237
|
+
watcher.on("cmem_event", broadcast);
|
|
3238
|
+
}
|
|
3239
|
+
app.get("/favicon.ico", async (_req, reply) => {
|
|
3240
|
+
return reply.status(204).send();
|
|
3241
|
+
});
|
|
3242
|
+
app.get("/api/v1/health", async () => {
|
|
3243
|
+
const projects = store.listProjects();
|
|
3244
|
+
return {
|
|
3245
|
+
data: {
|
|
3246
|
+
status: "ok",
|
|
3247
|
+
host: "127.0.0.1",
|
|
3248
|
+
sqliteWal: true,
|
|
3249
|
+
projectCount: projects.length,
|
|
3250
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
3251
|
+
}
|
|
3252
|
+
};
|
|
3253
|
+
});
|
|
3254
|
+
app.get("/api/v1/projects", async () => {
|
|
3255
|
+
const projects = store.listProjects();
|
|
3256
|
+
return { data: projects };
|
|
3257
|
+
});
|
|
3258
|
+
app.get("/api/v1/projects/:id/timeline", async (req, reply) => {
|
|
3259
|
+
const { id } = req.params;
|
|
3260
|
+
const project = store.getProject(id);
|
|
3261
|
+
if (!project) {
|
|
3262
|
+
return reply.status(404).send({
|
|
3263
|
+
error: { code: "PROJECT_NOT_FOUND", message: `Project '${id}' not found` }
|
|
3264
|
+
});
|
|
3265
|
+
}
|
|
3266
|
+
const sessions = store.listSessionsByProject(project.id);
|
|
3267
|
+
const capsules = store.listCapsulesByProject(project.id);
|
|
3268
|
+
const handoffs = store.listHandoffsByProject(project.id);
|
|
3269
|
+
const decisions = store.listDecisionsByProject(project.id);
|
|
3270
|
+
const snapshots = store.listSnapshotsByProject(project.id);
|
|
3271
|
+
return {
|
|
3272
|
+
data: {
|
|
3273
|
+
project,
|
|
3274
|
+
sessions,
|
|
3275
|
+
capsules,
|
|
3276
|
+
handoffs,
|
|
3277
|
+
decisions,
|
|
3278
|
+
snapshots
|
|
3279
|
+
}
|
|
3280
|
+
};
|
|
3281
|
+
});
|
|
3282
|
+
app.get("/api/v1/capsules/:id", async (req, reply) => {
|
|
3283
|
+
const { id } = req.params;
|
|
3284
|
+
const capsule = store.getCapsuleById(id);
|
|
3285
|
+
if (!capsule) {
|
|
3286
|
+
return reply.status(404).send({
|
|
3287
|
+
error: { code: "CAPSULE_NOT_FOUND", message: `Capsule '${id}' not found` }
|
|
3288
|
+
});
|
|
3289
|
+
}
|
|
3290
|
+
const snapshots = store.listSnapshotsByCapsule(capsule.id);
|
|
3291
|
+
return {
|
|
3292
|
+
data: {
|
|
3293
|
+
capsule,
|
|
3294
|
+
payload: JSON.parse(capsule.capsule_json),
|
|
3295
|
+
snapshots
|
|
3296
|
+
}
|
|
3297
|
+
};
|
|
3298
|
+
});
|
|
3299
|
+
app.patch("/api/v1/capsules/:id", async (req, reply) => {
|
|
3300
|
+
const { id } = req.params;
|
|
3301
|
+
const existing = store.getCapsuleById(id);
|
|
3302
|
+
if (!existing) {
|
|
3303
|
+
return reply.status(404).send({
|
|
3304
|
+
error: { code: "CAPSULE_NOT_FOUND", message: `Capsule '${id}' not found` }
|
|
3305
|
+
});
|
|
3306
|
+
}
|
|
3307
|
+
const parsed = PatchCapsuleSchema.safeParse(req.body);
|
|
3308
|
+
if (!parsed.success) {
|
|
3309
|
+
return reply.status(422).send({
|
|
3310
|
+
error: {
|
|
3311
|
+
code: "VALIDATION_ERROR",
|
|
3312
|
+
message: "Invalid capsule update payload",
|
|
3313
|
+
details: parsed.error.flatten()
|
|
3314
|
+
}
|
|
3315
|
+
});
|
|
3316
|
+
}
|
|
3317
|
+
const project = store.getProject(existing.project_id);
|
|
3318
|
+
const prevPayload = JSON.parse(existing.capsule_json);
|
|
3319
|
+
const patch = parsed.data;
|
|
3320
|
+
const draft = {
|
|
3321
|
+
capsuleId: "",
|
|
3322
|
+
projectId: project.id,
|
|
3323
|
+
projectName: project.name,
|
|
3324
|
+
repoRoot: project.repo_root,
|
|
3325
|
+
gitBranch: existing.git_branch,
|
|
3326
|
+
gitHeadSha: existing.git_head_sha,
|
|
3327
|
+
isDirtyTree: existing.is_dirty_tree === 1,
|
|
3328
|
+
sourceChain: JSON.parse(existing.source_chain_json),
|
|
3329
|
+
goal: {
|
|
3330
|
+
summary: patch.goalSummary ?? prevPayload.goal.summary,
|
|
3331
|
+
originalIntent: prevPayload.goal.originalIntent
|
|
3332
|
+
},
|
|
3333
|
+
decisionsLocked: patch.decisionsLocked ?? prevPayload.decisionsLocked,
|
|
3334
|
+
filesProgress: prevPayload.filesProgress,
|
|
3335
|
+
deadEndsAvoid: patch.deadEndsAvoid ?? prevPayload.deadEndsAvoid,
|
|
3336
|
+
nextSteps: patch.nextSteps ?? prevPayload.nextSteps,
|
|
3337
|
+
rawSessionTokens: existing.raw_tokens_covered,
|
|
3338
|
+
trigger: "manual_edit"
|
|
3339
|
+
};
|
|
3340
|
+
const compiled = enforceTokenBudget(draft, 1500);
|
|
3341
|
+
const saved = store.saveCapsule({
|
|
3342
|
+
projectId: project.id,
|
|
3343
|
+
sessionId: existing.session_id,
|
|
3344
|
+
triggerReason: "manual_edit",
|
|
3345
|
+
gitBranch: existing.git_branch,
|
|
3346
|
+
gitHeadSha: existing.git_head_sha,
|
|
3347
|
+
isDirtyTree: existing.is_dirty_tree === 1,
|
|
3348
|
+
payload: compiled.payload,
|
|
3349
|
+
markdown: compiled.markdown,
|
|
3350
|
+
rawTokensCovered: existing.raw_tokens_covered,
|
|
3351
|
+
sourceChain: compiled.payload.sourceChain
|
|
3352
|
+
});
|
|
3353
|
+
const prevSnaps = store.listSnapshotsByCapsule(existing.id);
|
|
3354
|
+
if (prevSnaps.length > 0) {
|
|
3355
|
+
const insertSnap = store.db.prepare(
|
|
3356
|
+
`INSERT INTO file_snapshots (
|
|
3357
|
+
id, project_id, session_id, capsule_id, file_path, change_status, line_ranges_json,
|
|
3358
|
+
lines_added, lines_removed, progress_note, content_sha256, unified_diff, captured_at
|
|
3359
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
|
3360
|
+
);
|
|
3361
|
+
for (const s of prevSnaps) {
|
|
3362
|
+
insertSnap.run(
|
|
3363
|
+
`snap_${saved.id.slice(-6)}_${Math.random().toString(36).slice(2, 6)}`,
|
|
3364
|
+
s.project_id,
|
|
3365
|
+
saved.session_id,
|
|
3366
|
+
saved.id,
|
|
3367
|
+
s.file_path,
|
|
3368
|
+
s.change_status,
|
|
3369
|
+
s.line_ranges_json,
|
|
3370
|
+
s.lines_added,
|
|
3371
|
+
s.lines_removed,
|
|
3372
|
+
s.progress_note,
|
|
3373
|
+
s.content_sha256,
|
|
3374
|
+
s.unified_diff,
|
|
3375
|
+
saved.created_at
|
|
3376
|
+
);
|
|
3377
|
+
}
|
|
3378
|
+
}
|
|
3379
|
+
const ev = {
|
|
3380
|
+
type: "capsule_updated",
|
|
3381
|
+
projectId: project.id,
|
|
3382
|
+
sessionId: saved.session_id,
|
|
3383
|
+
capsuleId: saved.id,
|
|
3384
|
+
message: `Manual capsule edit saved as v${saved.version} (${saved.capsule_tokens} tok)`,
|
|
3385
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
3386
|
+
};
|
|
3387
|
+
broadcast(ev);
|
|
3388
|
+
return reply.status(200).send({
|
|
3389
|
+
data: {
|
|
3390
|
+
capsule: saved,
|
|
3391
|
+
payload: JSON.parse(saved.capsule_json)
|
|
3392
|
+
}
|
|
3393
|
+
});
|
|
3394
|
+
});
|
|
3395
|
+
app.get("/api/v1/snapshots/:id/diff", async (req, reply) => {
|
|
3396
|
+
const { id } = req.params;
|
|
3397
|
+
const snap = store.getSnapshotById(id);
|
|
3398
|
+
if (!snap) {
|
|
3399
|
+
return reply.status(404).send({
|
|
3400
|
+
error: { code: "SNAPSHOT_NOT_FOUND", message: `Snapshot '${id}' not found` }
|
|
3401
|
+
});
|
|
3402
|
+
}
|
|
3403
|
+
return { data: snap };
|
|
3404
|
+
});
|
|
3405
|
+
app.post("/api/v1/handoffs", async (req, reply) => {
|
|
3406
|
+
const parsed = CreateHandoffSchema.safeParse(req.body);
|
|
3407
|
+
if (!parsed.success) {
|
|
3408
|
+
return reply.status(422).send({
|
|
3409
|
+
error: {
|
|
3410
|
+
code: "VALIDATION_ERROR",
|
|
3411
|
+
message: "Invalid handoff request",
|
|
3412
|
+
details: parsed.error.flatten()
|
|
3413
|
+
}
|
|
3414
|
+
});
|
|
3415
|
+
}
|
|
3416
|
+
const input = parsed.data;
|
|
3417
|
+
const project = store.getProject(input.projectId);
|
|
3418
|
+
if (!project) {
|
|
3419
|
+
return reply.status(404).send({
|
|
3420
|
+
error: { code: "PROJECT_NOT_FOUND", message: `Project '${input.projectId}' not found` }
|
|
3421
|
+
});
|
|
3422
|
+
}
|
|
3423
|
+
const capsule = input.capsuleId ? store.getCapsuleById(input.capsuleId) : store.getActiveCapsule(project.id);
|
|
3424
|
+
if (!capsule) {
|
|
3425
|
+
return reply.status(404).send({
|
|
3426
|
+
error: { code: "CAPSULE_NOT_FOUND", message: "No capsule found for handoff" }
|
|
3427
|
+
});
|
|
3428
|
+
}
|
|
3429
|
+
const latestSession = store.getLatestSessionForProject(project.id);
|
|
3430
|
+
const plan = buildHandoffPlan({
|
|
3431
|
+
capsule,
|
|
3432
|
+
targetCli: input.targetCli,
|
|
3433
|
+
targetAccount: input.targetAccount,
|
|
3434
|
+
injectFile: input.injectFile
|
|
3435
|
+
});
|
|
3436
|
+
let injectedFilePath = null;
|
|
3437
|
+
if (input.injectFile && existsSync6(project.repo_root)) {
|
|
3438
|
+
const injected = injectFencedCapsuleFile({
|
|
3439
|
+
repoRoot: project.repo_root,
|
|
3440
|
+
targetCli: input.targetCli,
|
|
3441
|
+
capsuleId: capsule.id,
|
|
3442
|
+
version: capsule.version,
|
|
3443
|
+
markdown: capsule.capsule_markdown,
|
|
3444
|
+
gitExclude: input.gitExclude
|
|
3445
|
+
});
|
|
3446
|
+
injectedFilePath = injected.relativePath;
|
|
3447
|
+
}
|
|
3448
|
+
const handoff = store.recordHandoff({
|
|
3449
|
+
projectId: project.id,
|
|
3450
|
+
capsuleId: capsule.id,
|
|
3451
|
+
fromSessionId: latestSession?.id ?? null,
|
|
3452
|
+
fromCli: latestSession?.cli_source ?? "manual",
|
|
3453
|
+
toCli: input.targetCli,
|
|
3454
|
+
fromAccount: latestSession?.account_label ?? "default",
|
|
3455
|
+
toAccount: plan.targetAccount,
|
|
3456
|
+
reason: input.reason ?? "quota_exhausted",
|
|
3457
|
+
deliveryMethod: plan.deliveryMethod,
|
|
3458
|
+
injectedTokens: capsule.capsule_tokens,
|
|
3459
|
+
rawTokensAvoided: capsule.tokens_saved,
|
|
3460
|
+
handoffCommand: plan.handoffCommand
|
|
3461
|
+
});
|
|
3462
|
+
broadcast({
|
|
3463
|
+
type: "handoff_created",
|
|
3464
|
+
projectId: project.id,
|
|
3465
|
+
capsuleId: capsule.id,
|
|
3466
|
+
cliSource: input.targetCli,
|
|
3467
|
+
message: `Handoff generated for ${input.targetCli} (${capsule.capsule_tokens} tok)`,
|
|
3468
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
3469
|
+
});
|
|
3470
|
+
return reply.status(201).send({
|
|
3471
|
+
data: {
|
|
3472
|
+
handoff,
|
|
3473
|
+
handoffCommand: plan.handoffCommand,
|
|
3474
|
+
startupPrompt: plan.startupPrompt,
|
|
3475
|
+
capsuleMarkdown: capsule.capsule_markdown,
|
|
3476
|
+
capsuleTokens: estimateTokens(capsule.capsule_markdown),
|
|
3477
|
+
injectedFilePath
|
|
3478
|
+
}
|
|
3479
|
+
});
|
|
3480
|
+
});
|
|
3481
|
+
app.get("/api/v1/search", async (req, reply) => {
|
|
3482
|
+
const parsed = SearchQuerySchema.safeParse(req.query);
|
|
3483
|
+
if (!parsed.success) {
|
|
3484
|
+
return reply.status(422).send({
|
|
3485
|
+
error: {
|
|
3486
|
+
code: "VALIDATION_ERROR",
|
|
3487
|
+
message: "Invalid search query parameters",
|
|
3488
|
+
details: parsed.error.flatten()
|
|
3489
|
+
}
|
|
3490
|
+
});
|
|
3491
|
+
}
|
|
3492
|
+
const result = store.searchMemory({
|
|
3493
|
+
query: parsed.data.q,
|
|
3494
|
+
projectId: parsed.data.projectId,
|
|
3495
|
+
cliSource: parsed.data.cliSource,
|
|
3496
|
+
category: parsed.data.category,
|
|
3497
|
+
page: parsed.data.page,
|
|
3498
|
+
pageSize: parsed.data.pageSize
|
|
3499
|
+
});
|
|
3500
|
+
return {
|
|
3501
|
+
data: result.hits,
|
|
3502
|
+
pagination: {
|
|
3503
|
+
page: result.page,
|
|
3504
|
+
pageSize: result.pageSize,
|
|
3505
|
+
totalItems: result.total,
|
|
3506
|
+
totalPages: Math.max(1, Math.ceil(result.total / result.pageSize))
|
|
3507
|
+
}
|
|
3508
|
+
};
|
|
3509
|
+
});
|
|
3510
|
+
app.get("/api/v1/events", async (req, reply) => {
|
|
3511
|
+
reply.raw.writeHead(200, {
|
|
3512
|
+
"Content-Type": "text/event-stream",
|
|
3513
|
+
"Cache-Control": "no-cache, no-transform",
|
|
3514
|
+
Connection: "keep-alive"
|
|
3515
|
+
});
|
|
3516
|
+
reply.raw.write("retry: 2000\n");
|
|
3517
|
+
const hello = { type: "connected", message: "cmem SSE connected", timestamp: (/* @__PURE__ */ new Date()).toISOString() };
|
|
3518
|
+
reply.raw.write(`event: connected
|
|
3519
|
+
data: ${JSON.stringify(hello)}
|
|
3520
|
+
|
|
3521
|
+
`);
|
|
3522
|
+
const client = {
|
|
3523
|
+
write: (chunk) => {
|
|
3524
|
+
reply.raw.write(chunk);
|
|
3525
|
+
}
|
|
3526
|
+
};
|
|
3527
|
+
sseClients.add(client);
|
|
3528
|
+
const keepalive = setInterval(() => {
|
|
3529
|
+
client.write(": heartbeat\n\n");
|
|
3530
|
+
}, 2e4);
|
|
3531
|
+
keepalive.unref();
|
|
3532
|
+
req.raw.on("close", () => {
|
|
3533
|
+
clearInterval(keepalive);
|
|
3534
|
+
sseClients.delete(client);
|
|
3535
|
+
});
|
|
3536
|
+
return reply;
|
|
3537
|
+
});
|
|
3538
|
+
const staticRoot = params.webDistPath === void 0 ? resolveWebDistPath() : params.webDistPath;
|
|
3539
|
+
if (staticRoot && existsSync6(staticRoot)) {
|
|
3540
|
+
app.register(fastifyStatic, {
|
|
3541
|
+
root: staticRoot,
|
|
3542
|
+
prefix: "/"
|
|
3543
|
+
});
|
|
3544
|
+
}
|
|
3545
|
+
return app;
|
|
3546
|
+
}
|
|
3547
|
+
|
|
3548
|
+
// packages/cli/src/commands/handlers.ts
|
|
3549
|
+
function parseCliArgs(argv) {
|
|
3550
|
+
const args = [...argv];
|
|
3551
|
+
const command = args.shift() ?? "status";
|
|
3552
|
+
const positionals = [];
|
|
3553
|
+
const flags = {};
|
|
3554
|
+
for (let i = 0; i < args.length; i++) {
|
|
3555
|
+
const token = args[i];
|
|
3556
|
+
if (token.startsWith("--")) {
|
|
3557
|
+
const eqIdx = token.indexOf("=");
|
|
3558
|
+
if (eqIdx > 2) {
|
|
3559
|
+
flags[token.slice(2, eqIdx)] = token.slice(eqIdx + 1);
|
|
3560
|
+
} else {
|
|
3561
|
+
const key = token.slice(2);
|
|
3562
|
+
const next = args[i + 1];
|
|
3563
|
+
if (next && !next.startsWith("-")) {
|
|
3564
|
+
flags[key] = next;
|
|
3565
|
+
i += 1;
|
|
3566
|
+
} else {
|
|
3567
|
+
flags[key] = true;
|
|
3568
|
+
}
|
|
3569
|
+
}
|
|
3570
|
+
} else if (token.startsWith("-") && token.length === 2) {
|
|
3571
|
+
const key = token.slice(1);
|
|
3572
|
+
const next = args[i + 1];
|
|
3573
|
+
if (next && !next.startsWith("-")) {
|
|
3574
|
+
flags[key] = next;
|
|
3575
|
+
i += 1;
|
|
3576
|
+
} else {
|
|
3577
|
+
flags[key] = true;
|
|
3578
|
+
}
|
|
3579
|
+
} else {
|
|
3580
|
+
positionals.push(token);
|
|
3581
|
+
}
|
|
3582
|
+
}
|
|
3583
|
+
return { command, positionals, flags };
|
|
3584
|
+
}
|
|
3585
|
+
function resolveActiveProject(store, projectFlag) {
|
|
3586
|
+
if (typeof projectFlag === "string") {
|
|
3587
|
+
return store.getProjectByRepoRoot(resolve3(projectFlag)) ?? store.getProject(projectFlag);
|
|
3588
|
+
}
|
|
3589
|
+
const byCwd = store.getProjectByRepoRoot(resolve3(process.cwd()));
|
|
3590
|
+
if (byCwd) return byCwd;
|
|
3591
|
+
return store.listProjects()[0] ?? null;
|
|
3592
|
+
}
|
|
3593
|
+
function assertCliSource(val, flagName) {
|
|
3594
|
+
if (typeof val === "string" && CLI_SOURCES.includes(val)) {
|
|
3595
|
+
return val;
|
|
3596
|
+
}
|
|
3597
|
+
throw new Error(`Invalid ${flagName}. Expected one of: ${CLI_SOURCES.join(", ")}`);
|
|
3598
|
+
}
|
|
3599
|
+
async function runCli(argv) {
|
|
3600
|
+
const parsed = parseCliArgs(argv);
|
|
3601
|
+
const db = openDatabase();
|
|
3602
|
+
const store = new MemoryStore(db);
|
|
3603
|
+
try {
|
|
3604
|
+
switch (parsed.command) {
|
|
3605
|
+
case "help":
|
|
3606
|
+
case "--help":
|
|
3607
|
+
case "-h": {
|
|
3608
|
+
console.log(
|
|
3609
|
+
[
|
|
3610
|
+
"cmem \u2014 Universal Cross-CLI Agent Memory & Quota-Switch Handoff Engine",
|
|
3611
|
+
"",
|
|
3612
|
+
"Commands:",
|
|
3613
|
+
" cmem init [--seed] [--json]",
|
|
3614
|
+
" cmem capture [-m <summary>] [--project <path>] [--cli <source>] [--json]",
|
|
3615
|
+
" cmem status [--project <path>] [--json]",
|
|
3616
|
+
" cmem capsule [--project <path>] [--json]",
|
|
3617
|
+
" cmem resume --to <claude|codex|gemini|agy|cursor> [--account <label>] [--inject-file] [--dry-run] [--exec]",
|
|
3618
|
+
" cmem handoff --to <cli> [--account <label>] [--inject-file] [--dry-run]",
|
|
3619
|
+
" cmem copy [--format md|json] [--project <path>]",
|
|
3620
|
+
" cmem clean [--project <path>]",
|
|
3621
|
+
" cmem checkpoint -m <message> [--type architecture|constraint|dead_end|tradeoff|next_step]",
|
|
3622
|
+
" cmem search <query> [--cli <source>] [--limit 20] [--json]",
|
|
3623
|
+
" cmem seed [--reset]",
|
|
3624
|
+
" cmem watch",
|
|
3625
|
+
" cmem ui [--port 4319]",
|
|
3626
|
+
" cmem mcp"
|
|
3627
|
+
].join("\n")
|
|
3628
|
+
);
|
|
3629
|
+
return 0;
|
|
3630
|
+
}
|
|
3631
|
+
case "init": {
|
|
3632
|
+
const seed = Boolean(parsed.flags.seed);
|
|
3633
|
+
let seededCount = 0;
|
|
3634
|
+
if (seed) {
|
|
3635
|
+
seededCount = store.seedDemo(false).projectsSeeded;
|
|
3636
|
+
}
|
|
3637
|
+
const gitSensor = new GitStateSensor();
|
|
3638
|
+
const gitSnap = await gitSensor.capture(process.cwd());
|
|
3639
|
+
let registeredProject = null;
|
|
3640
|
+
if (gitSnap) {
|
|
3641
|
+
registeredProject = store.upsertProject({
|
|
3642
|
+
repoRoot: gitSnap.repoRoot,
|
|
3643
|
+
activeBranch: gitSnap.branch
|
|
3644
|
+
});
|
|
3645
|
+
}
|
|
3646
|
+
const dbPath = resolveDatabasePath();
|
|
3647
|
+
const projectCount = store.listProjects().length;
|
|
3648
|
+
if (parsed.flags.json) {
|
|
3649
|
+
console.log(
|
|
3650
|
+
JSON.stringify(
|
|
3651
|
+
{ dbPath, projectCount, seededProjects: seededCount, registeredProject },
|
|
3652
|
+
null,
|
|
3653
|
+
2
|
|
3654
|
+
)
|
|
3655
|
+
);
|
|
3656
|
+
return 0;
|
|
3657
|
+
}
|
|
3658
|
+
console.log(`Initialized cmem memory store at ${dbPath} (${projectCount} project(s) tracked).`);
|
|
3659
|
+
if (registeredProject) {
|
|
3660
|
+
console.log(`Registered repo: ${registeredProject.name} (${registeredProject.active_branch})`);
|
|
3661
|
+
}
|
|
3662
|
+
console.log("Next: run `cmem capture` in any workspace, `cmem ui` for the web dashboard, or wire `cmem mcp` in your AI CLI.");
|
|
3663
|
+
return 0;
|
|
3664
|
+
}
|
|
3665
|
+
case "capture": {
|
|
3666
|
+
const cliSource = typeof parsed.flags.cli === "string" ? assertCliSource(parsed.flags.cli, "--cli") : "manual";
|
|
3667
|
+
const targetDir = typeof parsed.flags.project === "string" ? resolve3(parsed.flags.project) : resolve3(process.cwd());
|
|
3668
|
+
const note = typeof parsed.flags.m === "string" ? parsed.flags.m : parsed.positionals.length > 0 ? parsed.positionals.join(" ").trim() : "";
|
|
3669
|
+
const watcher = new CmemWatcherService(store);
|
|
3670
|
+
const syncSummary = await watcher.syncOnce();
|
|
3671
|
+
const gitSensor = new GitStateSensor();
|
|
3672
|
+
const gitSnapshot = existsSync7(targetDir) ? await gitSensor.capture(targetDir) : null;
|
|
3673
|
+
const resolvedRoot = gitSnapshot?.repoRoot ?? targetDir;
|
|
3674
|
+
const activeBranch = gitSnapshot?.branch ?? "main";
|
|
3675
|
+
const project = store.upsertProject({
|
|
3676
|
+
repoRoot: resolvedRoot,
|
|
3677
|
+
activeBranch,
|
|
3678
|
+
activeCli: cliSource
|
|
3679
|
+
});
|
|
3680
|
+
const session = store.getLatestSessionForProject(project.id) ?? store.upsertSession({
|
|
3681
|
+
projectId: project.id,
|
|
3682
|
+
cliSource,
|
|
3683
|
+
externalSessionId: `capture-${project.slug}`,
|
|
3684
|
+
gitBranch: activeBranch,
|
|
3685
|
+
modelName: cliSource === "manual" ? "workspace-capture" : cliSource
|
|
3686
|
+
});
|
|
3687
|
+
const captureMessage = note || (gitSnapshot?.isDirtyTree ? `Captured ${gitSnapshot.files.length} modified file(s) in ${project.name} (${activeBranch})` : `Captured workspace checkpoint for ${project.name} (${resolvedRoot})`);
|
|
3688
|
+
store.addDecisionLog({
|
|
3689
|
+
projectId: project.id,
|
|
3690
|
+
sessionId: session.id,
|
|
3691
|
+
cliSource,
|
|
3692
|
+
category: "architecture",
|
|
3693
|
+
title: captureMessage,
|
|
3694
|
+
body: captureMessage,
|
|
3695
|
+
rationale: `Captured via \`cmem capture\` at ${resolvedRoot}`,
|
|
3696
|
+
fileRefs: (gitSnapshot?.files ?? []).map((f) => `${f.filePath}:${f.lineRanges[0] ?? "L1"}`),
|
|
3697
|
+
isPinned: Boolean(note)
|
|
3698
|
+
});
|
|
3699
|
+
const prev = store.getActiveCapsule(project.id);
|
|
3700
|
+
const compiler = new CapsuleCompiler();
|
|
3701
|
+
const compiled = await compiler.compile({
|
|
3702
|
+
projectId: project.id,
|
|
3703
|
+
projectName: project.name,
|
|
3704
|
+
repoRoot: project.repo_root,
|
|
3705
|
+
events: [
|
|
3706
|
+
{
|
|
3707
|
+
externalEventId: `cap_${Date.now()}`,
|
|
3708
|
+
cliSource,
|
|
3709
|
+
externalSessionId: session.external_session_id,
|
|
3710
|
+
projectRoot: project.repo_root,
|
|
3711
|
+
gitBranch: activeBranch,
|
|
3712
|
+
modelName: session.model_name,
|
|
3713
|
+
accountLabel: session.account_label,
|
|
3714
|
+
role: "user",
|
|
3715
|
+
timestampIso: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3716
|
+
textContent: captureMessage
|
|
3717
|
+
}
|
|
3718
|
+
],
|
|
3719
|
+
gitSnapshot,
|
|
3720
|
+
existingDecisions: store.listDecisionsByProject(project.id),
|
|
3721
|
+
previousSourceChain: prev ? JSON.parse(prev.source_chain_json) : [cliSource],
|
|
3722
|
+
trigger: "turn_checkpoint"
|
|
3723
|
+
});
|
|
3724
|
+
const saved = store.saveCapsule({
|
|
3725
|
+
projectId: project.id,
|
|
3726
|
+
sessionId: session.id,
|
|
3727
|
+
triggerReason: "turn_checkpoint",
|
|
3728
|
+
gitBranch: compiled.payload.gitBranch,
|
|
3729
|
+
gitHeadSha: compiled.payload.gitHeadSha,
|
|
3730
|
+
isDirtyTree: compiled.payload.isDirtyTree,
|
|
3731
|
+
payload: compiled.payload,
|
|
3732
|
+
markdown: compiled.markdown,
|
|
3733
|
+
rawTokensCovered: Math.max(prev?.raw_tokens_covered ?? 0, compiled.capsuleTokens),
|
|
3734
|
+
sourceChain: compiled.payload.sourceChain,
|
|
3735
|
+
snapshots: (gitSnapshot?.files ?? []).map((f) => ({
|
|
3736
|
+
filePath: f.filePath,
|
|
3737
|
+
changeStatus: f.changeStatus,
|
|
3738
|
+
lineRanges: f.lineRanges,
|
|
3739
|
+
linesAdded: f.linesAdded,
|
|
3740
|
+
linesRemoved: f.linesRemoved,
|
|
3741
|
+
progressNote: f.progressNote,
|
|
3742
|
+
contentSha256: f.contentSha256,
|
|
3743
|
+
unifiedDiff: f.unifiedDiff
|
|
3744
|
+
}))
|
|
3745
|
+
});
|
|
3746
|
+
if (parsed.flags.json) {
|
|
3747
|
+
console.log(
|
|
3748
|
+
JSON.stringify(
|
|
3749
|
+
{
|
|
3750
|
+
project,
|
|
3751
|
+
capsuleId: saved.id,
|
|
3752
|
+
version: saved.version,
|
|
3753
|
+
capsuleTokens: saved.capsule_tokens,
|
|
3754
|
+
filesCaptured: gitSnapshot?.files.length ?? 0,
|
|
3755
|
+
syncSummary
|
|
3756
|
+
},
|
|
3757
|
+
null,
|
|
3758
|
+
2
|
|
3759
|
+
)
|
|
3760
|
+
);
|
|
3761
|
+
return 0;
|
|
3762
|
+
}
|
|
3763
|
+
console.log(
|
|
3764
|
+
`Captured ${project.name} (${saved.git_branch}) -> capsule v${saved.version} (${saved.capsule_tokens} tok, ${gitSnapshot?.files.length ?? 0} file diff(s), ${syncSummary.eventsIngested} log event(s) synced).`
|
|
3765
|
+
);
|
|
3766
|
+
return 0;
|
|
3767
|
+
}
|
|
3768
|
+
case "seed": {
|
|
3769
|
+
const reset = Boolean(parsed.flags.reset);
|
|
3770
|
+
const res = store.seedDemo(reset);
|
|
3771
|
+
console.log(
|
|
3772
|
+
res.projectsSeeded > 0 ? `Seeded ${res.projectsSeeded} projects (agy -> claude -> codex chain ready).` : "Database already populated. Pass --reset to re-seed."
|
|
3773
|
+
);
|
|
3774
|
+
return 0;
|
|
3775
|
+
}
|
|
3776
|
+
case "status": {
|
|
3777
|
+
const projects = store.listProjects();
|
|
3778
|
+
if (parsed.flags.json) {
|
|
3779
|
+
console.log(JSON.stringify(projects, null, 2));
|
|
3780
|
+
return 0;
|
|
3781
|
+
}
|
|
3782
|
+
if (projects.length === 0) {
|
|
3783
|
+
console.log("No projects captured yet. Run `cmem seed` for realistic demo data or `cmem watch` to monitor local CLIs.");
|
|
3784
|
+
return 0;
|
|
3785
|
+
}
|
|
3786
|
+
for (const p of projects) {
|
|
3787
|
+
const pct = p.cumulative_raw_tokens > 0 ? ((p.cumulative_raw_tokens - p.active_capsule_tokens) / p.cumulative_raw_tokens * 100).toFixed(1) : "0.0";
|
|
3788
|
+
console.log(
|
|
3789
|
+
`[${p.active_cli ?? "none"}] ${p.name} (${p.active_branch}) | capsule: ${p.active_capsule_tokens} tok | raw: ${p.cumulative_raw_tokens} tok (${pct}% saved) | quota_blocks: ${p.quota_blocked_count}`
|
|
3790
|
+
);
|
|
3791
|
+
}
|
|
3792
|
+
return 0;
|
|
3793
|
+
}
|
|
3794
|
+
case "capsule": {
|
|
3795
|
+
const project = resolveActiveProject(store, parsed.flags.project);
|
|
3796
|
+
if (!project) {
|
|
3797
|
+
console.error("No project found. Pass --project <path> or run `cmem seed`.");
|
|
3798
|
+
return 1;
|
|
3799
|
+
}
|
|
3800
|
+
const capsule = store.getActiveCapsule(project.id);
|
|
3801
|
+
if (!capsule) {
|
|
3802
|
+
console.error(`No active Context Capsule for ${project.name}.`);
|
|
3803
|
+
return 1;
|
|
3804
|
+
}
|
|
3805
|
+
console.log(parsed.flags.json ? capsule.capsule_json : capsule.capsule_markdown);
|
|
3806
|
+
return 0;
|
|
3807
|
+
}
|
|
3808
|
+
case "copy": {
|
|
3809
|
+
const project = resolveActiveProject(store, parsed.flags.project);
|
|
3810
|
+
const capsule = project ? store.getActiveCapsule(project.id) : null;
|
|
3811
|
+
if (!project || !capsule) {
|
|
3812
|
+
console.error("No active Context Capsule to copy.");
|
|
3813
|
+
return 1;
|
|
3814
|
+
}
|
|
3815
|
+
const text = parsed.flags.format === "json" ? capsule.capsule_json : capsule.capsule_markdown;
|
|
3816
|
+
const clip = copyToClipboard(text);
|
|
3817
|
+
console.log(
|
|
3818
|
+
clip.copied ? `Copied ${capsule.capsule_tokens}-token capsule for ${project.name} via ${clip.method}.` : `Clipboard unavailable in this environment; printed below:
|
|
3819
|
+
|
|
3820
|
+
${text}`
|
|
3821
|
+
);
|
|
3822
|
+
return 0;
|
|
3823
|
+
}
|
|
3824
|
+
case "handoff":
|
|
3825
|
+
case "resume": {
|
|
3826
|
+
const targetCli = assertCliSource(parsed.flags.to, "--to");
|
|
3827
|
+
const project = resolveActiveProject(store, parsed.flags.project);
|
|
3828
|
+
const capsule = project ? store.getActiveCapsule(project.id) : null;
|
|
3829
|
+
if (!project || !capsule) {
|
|
3830
|
+
console.error("No active Context Capsule found for handoff.");
|
|
3831
|
+
return 1;
|
|
3832
|
+
}
|
|
3833
|
+
const injectFile = Boolean(parsed.flags["inject-file"]);
|
|
3834
|
+
const dryRun = Boolean(parsed.flags["dry-run"]);
|
|
3835
|
+
const targetAccount = typeof parsed.flags.account === "string" ? parsed.flags.account : "default";
|
|
3836
|
+
const latestSession = store.getLatestSessionForProject(project.id);
|
|
3837
|
+
const plan = buildHandoffPlan({
|
|
3838
|
+
capsule,
|
|
3839
|
+
targetCli,
|
|
3840
|
+
targetAccount,
|
|
3841
|
+
injectFile
|
|
3842
|
+
});
|
|
3843
|
+
if (injectFile && !dryRun && existsSync7(project.repo_root)) {
|
|
3844
|
+
const res = injectFencedCapsuleFile({
|
|
3845
|
+
repoRoot: project.repo_root,
|
|
3846
|
+
targetCli,
|
|
3847
|
+
capsuleId: capsule.id,
|
|
3848
|
+
version: capsule.version,
|
|
3849
|
+
markdown: capsule.capsule_markdown,
|
|
3850
|
+
gitExclude: Boolean(parsed.flags["git-exclude"])
|
|
3851
|
+
});
|
|
3852
|
+
console.log(`Injected fenced Context Capsule into ${res.relativePath}`);
|
|
3853
|
+
}
|
|
3854
|
+
if (!dryRun) {
|
|
3855
|
+
store.recordHandoff({
|
|
3856
|
+
projectId: project.id,
|
|
3857
|
+
capsuleId: capsule.id,
|
|
3858
|
+
fromSessionId: latestSession?.id ?? null,
|
|
3859
|
+
fromCli: latestSession?.cli_source ?? "manual",
|
|
3860
|
+
toCli: targetCli,
|
|
3861
|
+
fromAccount: latestSession?.account_label ?? "default",
|
|
3862
|
+
toAccount: targetAccount,
|
|
3863
|
+
reason: "quota_exhausted",
|
|
3864
|
+
deliveryMethod: plan.deliveryMethod,
|
|
3865
|
+
injectedTokens: capsule.capsule_tokens,
|
|
3866
|
+
rawTokensAvoided: capsule.tokens_saved,
|
|
3867
|
+
handoffCommand: plan.handoffCommand
|
|
3868
|
+
});
|
|
3869
|
+
copyToClipboard(plan.startupPrompt);
|
|
3870
|
+
}
|
|
3871
|
+
if (parsed.flags.exec && !dryRun) {
|
|
3872
|
+
const res = spawnSync2(plan.binary, plan.args, {
|
|
3873
|
+
cwd: existsSync7(project.repo_root) ? project.repo_root : process.cwd(),
|
|
3874
|
+
stdio: "inherit"
|
|
3875
|
+
});
|
|
3876
|
+
return res.status ?? 0;
|
|
3877
|
+
}
|
|
3878
|
+
console.log(
|
|
3879
|
+
[
|
|
3880
|
+
`Handoff staged: ${latestSession?.cli_source ?? "manual"} -> ${targetCli} (${capsule.capsule_tokens} tok, saved ${capsule.tokens_saved} tok)`,
|
|
3881
|
+
`Delivery: ${plan.deliveryMethod}${dryRun ? " [DRY RUN]" : ""}`,
|
|
3882
|
+
`Launch command: ${plan.binary} ${plan.args.map((a) => JSON.stringify(a.slice(0, 60) + (a.length > 60 ? "..." : ""))).join(" ")}`,
|
|
3883
|
+
"",
|
|
3884
|
+
plan.startupPrompt
|
|
3885
|
+
].join("\n")
|
|
3886
|
+
);
|
|
3887
|
+
return 0;
|
|
3888
|
+
}
|
|
3889
|
+
case "clean": {
|
|
3890
|
+
const targetDir = typeof parsed.flags.project === "string" ? resolve3(parsed.flags.project) : resolveActiveProject(store)?.repo_root ?? process.cwd();
|
|
3891
|
+
const cleaned = cleanFencedCapsuleFiles(targetDir);
|
|
3892
|
+
console.log(
|
|
3893
|
+
cleaned.length > 0 ? `Removed CMEM capsule blocks from: ${cleaned.join(", ")}` : "No CMEM fenced blocks found."
|
|
3894
|
+
);
|
|
3895
|
+
return 0;
|
|
3896
|
+
}
|
|
3897
|
+
case "checkpoint": {
|
|
3898
|
+
const msg = typeof parsed.flags.m === "string" ? parsed.flags.m : parsed.positionals.join(" ");
|
|
3899
|
+
if (!msg) {
|
|
3900
|
+
console.error('Provide checkpoint message with -m "..."');
|
|
3901
|
+
return 1;
|
|
3902
|
+
}
|
|
3903
|
+
const category = typeof parsed.flags.type === "string" && DECISION_CATEGORIES.includes(parsed.flags.type) ? parsed.flags.type : "architecture";
|
|
3904
|
+
const repoRoot = typeof parsed.flags.project === "string" ? resolve3(parsed.flags.project) : resolve3(process.cwd());
|
|
3905
|
+
const project = store.upsertProject({ repoRoot, activeCli: "manual" });
|
|
3906
|
+
const session = store.getLatestSessionForProject(project.id) ?? store.upsertSession({
|
|
3907
|
+
projectId: project.id,
|
|
3908
|
+
cliSource: "manual",
|
|
3909
|
+
externalSessionId: `manual-${Date.now()}`,
|
|
3910
|
+
gitBranch: project.active_branch,
|
|
3911
|
+
modelName: "human-cli"
|
|
3912
|
+
});
|
|
3913
|
+
const dec = store.addDecisionLog({
|
|
3914
|
+
projectId: project.id,
|
|
3915
|
+
sessionId: session.id,
|
|
3916
|
+
cliSource: "manual",
|
|
3917
|
+
category,
|
|
3918
|
+
title: msg,
|
|
3919
|
+
body: msg,
|
|
3920
|
+
isPinned: true
|
|
3921
|
+
});
|
|
3922
|
+
const compiler = new CapsuleCompiler();
|
|
3923
|
+
const prev = store.getActiveCapsule(project.id);
|
|
3924
|
+
const compiled = await compiler.compile({
|
|
3925
|
+
projectId: project.id,
|
|
3926
|
+
projectName: project.name,
|
|
3927
|
+
repoRoot: project.repo_root,
|
|
3928
|
+
events: [],
|
|
3929
|
+
existingDecisions: store.listDecisionsByProject(project.id),
|
|
3930
|
+
previousSourceChain: prev ? JSON.parse(prev.source_chain_json) : ["manual"],
|
|
3931
|
+
trigger: "mcp_checkpoint"
|
|
3932
|
+
});
|
|
3933
|
+
const saved = store.saveCapsule({
|
|
3934
|
+
projectId: project.id,
|
|
3935
|
+
sessionId: session.id,
|
|
3936
|
+
triggerReason: "mcp_checkpoint",
|
|
3937
|
+
gitBranch: compiled.payload.gitBranch,
|
|
3938
|
+
gitHeadSha: compiled.payload.gitHeadSha,
|
|
3939
|
+
isDirtyTree: compiled.payload.isDirtyTree,
|
|
3940
|
+
payload: compiled.payload,
|
|
3941
|
+
markdown: compiled.markdown,
|
|
3942
|
+
rawTokensCovered: Math.max(prev?.raw_tokens_covered ?? 0, compiled.capsuleTokens),
|
|
3943
|
+
sourceChain: compiled.payload.sourceChain
|
|
3944
|
+
});
|
|
3945
|
+
console.log(`Logged ${category} (${dec.id}); capsule v${saved.version} now ${saved.capsule_tokens} tokens.`);
|
|
3946
|
+
return 0;
|
|
3947
|
+
}
|
|
3948
|
+
case "search": {
|
|
3949
|
+
const query = parsed.positionals.join(" ").trim();
|
|
3950
|
+
if (!query) {
|
|
3951
|
+
console.error("Usage: cmem search <query>");
|
|
3952
|
+
return 1;
|
|
3953
|
+
}
|
|
3954
|
+
const limit = typeof parsed.flags.limit === "string" ? Number(parsed.flags.limit) : 20;
|
|
3955
|
+
const cliSource = typeof parsed.flags.cli === "string" ? assertCliSource(parsed.flags.cli, "--cli") : void 0;
|
|
3956
|
+
const result = store.searchMemory({ query, cliSource, pageSize: limit });
|
|
3957
|
+
if (parsed.flags.json) {
|
|
3958
|
+
console.log(JSON.stringify(result, null, 2));
|
|
3959
|
+
return 0;
|
|
3960
|
+
}
|
|
3961
|
+
if (result.hits.length === 0) {
|
|
3962
|
+
console.log(`No matches for "${query}".`);
|
|
3963
|
+
return 0;
|
|
3964
|
+
}
|
|
3965
|
+
for (const h of result.hits) {
|
|
3966
|
+
console.log(`[${h.project_name} | ${h.category} | ${h.cli_source}] ${h.title}`);
|
|
3967
|
+
console.log(` ${h.snippet.replace(/\n+/g, " ")}`);
|
|
3968
|
+
}
|
|
3969
|
+
return 0;
|
|
3970
|
+
}
|
|
3971
|
+
case "mcp": {
|
|
3972
|
+
await startMcpStdioServer(store);
|
|
3973
|
+
return 0;
|
|
3974
|
+
}
|
|
3975
|
+
case "watch":
|
|
3976
|
+
case "ui": {
|
|
3977
|
+
const port = typeof parsed.flags.port === "string" ? Number(parsed.flags.port) : 4319;
|
|
3978
|
+
const watcher = new CmemWatcherService(store);
|
|
3979
|
+
await watcher.syncOnce();
|
|
3980
|
+
watcher.start();
|
|
3981
|
+
const server = createControlPlaneServer({ store, watcher });
|
|
3982
|
+
await server.listen({ host: "127.0.0.1", port });
|
|
3983
|
+
console.log(`cmem control plane listening at http://127.0.0.1:${port}`);
|
|
3984
|
+
const shutdown = async () => {
|
|
3985
|
+
await watcher.stop();
|
|
3986
|
+
await server.close();
|
|
3987
|
+
process.exit(0);
|
|
3988
|
+
};
|
|
3989
|
+
process.on("SIGINT", () => void shutdown());
|
|
3990
|
+
process.on("SIGTERM", () => void shutdown());
|
|
3991
|
+
await new Promise(() => {
|
|
3992
|
+
});
|
|
3993
|
+
return 0;
|
|
3994
|
+
}
|
|
3995
|
+
default:
|
|
3996
|
+
console.error(`Unknown command "${parsed.command}". Run \`cmem --help\`.`);
|
|
3997
|
+
return 1;
|
|
3998
|
+
}
|
|
3999
|
+
} finally {
|
|
4000
|
+
if (parsed.command !== "mcp" && parsed.command !== "watch" && parsed.command !== "ui") {
|
|
4001
|
+
db.close();
|
|
4002
|
+
}
|
|
4003
|
+
}
|
|
4004
|
+
}
|
|
4005
|
+
|
|
4006
|
+
// packages/cli/src/bin.ts
|
|
4007
|
+
var code = await runCli(process.argv.slice(2));
|
|
4008
|
+
if (code !== 0) {
|
|
4009
|
+
process.exit(code);
|
|
4010
|
+
}
|