@meshpoint/cli 1.2.0 → 1.4.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/README.md +4 -0
- package/dist/bin.js +42 -0
- package/dist/import/discover.js +327 -0
- package/dist/import/distill.js +134 -0
- package/dist/import/report.js +54 -0
- package/dist/import/run.js +183 -0
- package/dist/import/runner.js +90 -0
- package/dist/refs.js +3 -0
- package/dist/tap.js +1 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -103,6 +103,10 @@ Distillation is agent-side: the platform runs no model. `connect` installs the `
|
|
|
103
103
|
|
|
104
104
|
The session-start inject shows each item's id prefix so the skill can retract what the session made obsolete (`meshpoint items retract <prefix>...`, resolved against a fresh recall; ambiguous prefixes are refused).
|
|
105
105
|
|
|
106
|
+
## Importing old sessions
|
|
107
|
+
|
|
108
|
+
`meshpoint import sessions` seeds a repository from the transcripts your harnesses already keep: `~/.claude/projects/*/*.jsonl` (cwd and gitBranch per record), `~/.codex/sessions/**/rollout-*.jsonl` (session_meta has cwd and git), `~/.pi/agent/sessions/*/*.jsonl`, opencode's `storage/{session,message,part}`, Antigravity chats under `~/.gemini/tmp/<sha256 of the directory>/chats/`. Each session maps to a project through its directory's origin remote. Every session is distilled with your own agent CLI (`claude -p --tools "" --setting-sources ""`, or `codex exec`) using the checkpoint skill's rules; a second call per branch merges duplicates, keys conventions, marks recurring gotchas and names live items the proposals supersede; items naming files the checkout no longer has are dropped and listed. The proposal and a report (sessions per harness, span, most-touched files, items by kind, recurring gotchas first) land under `~/.local/state/meshpoint/import/`. Nothing is uploaded without `--apply`; `--with-turns` adds the last 30 days of turns as sessions. Current repo and 90 days by default; `--since <days>` past that or `--all-repos` asks y/N first.
|
|
109
|
+
|
|
106
110
|
## Refs, verification and the edit hook
|
|
107
111
|
|
|
108
112
|
`items put` reads repo-relative paths out of each item's title and body (`src/auth.ts`, `package.json`, backticked `Makefile`), keeps the ones that exist as the item's `refs`, attaches the files edited on the branch since the last checkpoint (recorded by every adapter under `~/.local/state/meshpoint/touched/`) as `paths`, and records HEAD as `commit_sha`. Path-like tokens that resolve to nothing print `ref not found: <path>` so the agent can fix a typo.
|
package/dist/bin.js
CHANGED
|
@@ -24,6 +24,8 @@ import { api, ApiError, canOpenBrowser, deviceLogin, freshConfig, login } from "
|
|
|
24
24
|
import { detectHarnesses, renderDetected } from "./detect.js";
|
|
25
25
|
import { renderDoctor, runDoctor } from "./doctor.js";
|
|
26
26
|
import { confirmItems, parseItemArgs, parseItems, putItems, retractItems } from "./items.js";
|
|
27
|
+
import { DEFAULT_SINCE_DAYS, importSessions } from "./import/run.js";
|
|
28
|
+
import { detectRunner } from "./import/runner.js";
|
|
27
29
|
import { Spool } from "./spool.js";
|
|
28
30
|
const USAGE = `meshpoint <command>
|
|
29
31
|
|
|
@@ -72,6 +74,15 @@ const USAGE = `meshpoint <command>
|
|
|
72
74
|
stdin form takes a JSON array of {kind, title, body}
|
|
73
75
|
items retract <id>... retract items on the current branch; an id may be a prefix
|
|
74
76
|
items confirm <id>... confirm items on the current branch (counts toward their rank)
|
|
77
|
+
import sessions [--since <days>] [--all-repos] [--with-turns] [--apply] [--yes]
|
|
78
|
+
[--runner claude|codex] [--model <m>] [--min-turns <n>]
|
|
79
|
+
read this machine's harness transcripts (Claude Code, Codex, pi,
|
|
80
|
+
opencode, Antigravity, Cursor) for the current repo and the last
|
|
81
|
+
90 days, distill them into items with your own agent CLI, and
|
|
82
|
+
write a proposal + report under ~/.local/state/meshpoint/import/.
|
|
83
|
+
Nothing is uploaded without --apply; older than 90 days or
|
|
84
|
+
--all-repos asks first (--yes skips). --with-turns also uploads
|
|
85
|
+
the last 30 days of turns as sessions.
|
|
75
86
|
tap claude-code | codex | cursor | antigravity [<event>] | openclaw
|
|
76
87
|
hook entry point; reads one hook payload on stdin
|
|
77
88
|
`;
|
|
@@ -257,6 +268,37 @@ async function main(argv) {
|
|
|
257
268
|
console.log(JSON.stringify({ ...out, project: repo.project, branch: repo.branch }));
|
|
258
269
|
return 0;
|
|
259
270
|
}
|
|
271
|
+
case "import": {
|
|
272
|
+
if (rest[0] !== "sessions")
|
|
273
|
+
throw new Error("import supports: sessions");
|
|
274
|
+
const config = await requireConfig();
|
|
275
|
+
const repo = repoContext(process.cwd());
|
|
276
|
+
const sinceDays = Number(flag(rest, "--since") ?? DEFAULT_SINCE_DAYS);
|
|
277
|
+
if (!Number.isInteger(sinceDays) || sinceDays < 1)
|
|
278
|
+
throw new Error("--since takes a whole number of days");
|
|
279
|
+
const minTurns = Number(flag(rest, "--min-turns") ?? 6);
|
|
280
|
+
const prefer = flag(rest, "--runner");
|
|
281
|
+
if (prefer !== undefined && prefer !== "claude" && prefer !== "codex")
|
|
282
|
+
throw new Error("--runner takes claude or codex");
|
|
283
|
+
const model = flag(rest, "--model");
|
|
284
|
+
const runner = detectRunner(process.env, prefer, model);
|
|
285
|
+
if (!runner)
|
|
286
|
+
throw new Error("no agent CLI found on PATH (claude or codex); install one to distill transcripts, or write items by hand with meshpoint items put");
|
|
287
|
+
const defaultBranch = repo ? repo.branch : "master";
|
|
288
|
+
const out = await withAuth(config, (c) => importSessions({
|
|
289
|
+
config: c,
|
|
290
|
+
current: repo ? { project: repo.project, root: repo.root, defaultBranch } : null,
|
|
291
|
+
sinceDays,
|
|
292
|
+
allRepos: rest.includes("--all-repos"),
|
|
293
|
+
withTurns: rest.includes("--with-turns"),
|
|
294
|
+
apply: rest.includes("--apply"),
|
|
295
|
+
yes: rest.includes("--yes"),
|
|
296
|
+
minTurns,
|
|
297
|
+
runner,
|
|
298
|
+
stateDir: stateDir(),
|
|
299
|
+
}));
|
|
300
|
+
return out.cancelled ? 1 : 0;
|
|
301
|
+
}
|
|
260
302
|
case "tap": {
|
|
261
303
|
const harness = rest[0];
|
|
262
304
|
if (!TAP_HARNESSES.has(harness ?? ""))
|
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { execFileSync } from "node:child_process";
|
|
3
|
+
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { projectIdFromRemote } from "@meshpoint/sdk";
|
|
7
|
+
import { parseAntigravityTranscript } from "../antigravity/transcript.js";
|
|
8
|
+
import { parseTranscript as parseClaudeCodeTranscript } from "../claude-code/transcript.js";
|
|
9
|
+
import { parseCodexTranscript } from "../codex/transcript.js";
|
|
10
|
+
import { parseCursorTranscript } from "../cursor/transcript.js";
|
|
11
|
+
function isRecord(v) {
|
|
12
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
13
|
+
}
|
|
14
|
+
function readJsonl(file) {
|
|
15
|
+
const out = [];
|
|
16
|
+
for (const line of readFileSync(file, "utf8").split("\n")) {
|
|
17
|
+
if (!line.trim())
|
|
18
|
+
continue;
|
|
19
|
+
try {
|
|
20
|
+
const v = JSON.parse(line);
|
|
21
|
+
if (isRecord(v))
|
|
22
|
+
out.push(v);
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return out;
|
|
29
|
+
}
|
|
30
|
+
function walk(dir, pick, depth = 6) {
|
|
31
|
+
if (depth < 0 || !existsSync(dir))
|
|
32
|
+
return [];
|
|
33
|
+
const out = [];
|
|
34
|
+
let names;
|
|
35
|
+
try {
|
|
36
|
+
names = readdirSync(dir);
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return [];
|
|
40
|
+
}
|
|
41
|
+
for (const name of names) {
|
|
42
|
+
const p = path.join(dir, name);
|
|
43
|
+
let st;
|
|
44
|
+
try {
|
|
45
|
+
st = statSync(p);
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
if (st.isDirectory())
|
|
51
|
+
out.push(...walk(p, pick, depth - 1));
|
|
52
|
+
else if (pick(p))
|
|
53
|
+
out.push(p);
|
|
54
|
+
}
|
|
55
|
+
return out;
|
|
56
|
+
}
|
|
57
|
+
function span(entries, fallback) {
|
|
58
|
+
const times = entries.map((e) => e.at).filter((t) => t > 0);
|
|
59
|
+
return { startedAt: times.length ? Math.min(...times) : fallback, endedAt: times.length ? Math.max(...times) : fallback };
|
|
60
|
+
}
|
|
61
|
+
// The default project resolver: git's origin remote for the recorded directory, cached per directory.
|
|
62
|
+
export function gitProjectResolver() {
|
|
63
|
+
const cache = new Map();
|
|
64
|
+
return (cwd) => {
|
|
65
|
+
if (cache.has(cwd))
|
|
66
|
+
return cache.get(cwd) ?? null;
|
|
67
|
+
let id = null;
|
|
68
|
+
if (existsSync(cwd)) {
|
|
69
|
+
try {
|
|
70
|
+
const remote = execFileSync("git", ["-C", cwd, "remote", "get-url", "origin"], { stdio: ["ignore", "pipe", "ignore"], timeout: 2000 }).toString().trim();
|
|
71
|
+
id = remote ? projectIdFromRemote(remote) : null;
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
id = null;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
cache.set(cwd, id);
|
|
78
|
+
return id;
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
// --- readers -----------------------------------------------------------------------------------
|
|
82
|
+
function claudeCode(home, env) {
|
|
83
|
+
const root = env.CLAUDE_CONFIG_DIR || path.join(home, ".claude");
|
|
84
|
+
const out = [];
|
|
85
|
+
for (const file of walk(path.join(root, "projects"), (f) => f.endsWith(".jsonl"), 2)) {
|
|
86
|
+
try {
|
|
87
|
+
const raw = readFileSync(file, "utf8");
|
|
88
|
+
const entries = parseClaudeCodeTranscript(raw);
|
|
89
|
+
if (entries.length === 0)
|
|
90
|
+
continue;
|
|
91
|
+
let cwd = null;
|
|
92
|
+
let branch = null;
|
|
93
|
+
let id = path.basename(file, ".jsonl");
|
|
94
|
+
for (const r of readJsonl(file)) {
|
|
95
|
+
if (typeof r.cwd === "string" && !cwd)
|
|
96
|
+
cwd = r.cwd;
|
|
97
|
+
if (typeof r.gitBranch === "string" && !branch)
|
|
98
|
+
branch = r.gitBranch;
|
|
99
|
+
if (typeof r.sessionId === "string")
|
|
100
|
+
id = r.sessionId;
|
|
101
|
+
if (cwd && branch)
|
|
102
|
+
break;
|
|
103
|
+
}
|
|
104
|
+
out.push({ harness: "claude-code", file, id, cwd, branch, ...span(entries, statSync(file).mtimeMs), entries, project: null });
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return out;
|
|
111
|
+
}
|
|
112
|
+
function codex(home, env) {
|
|
113
|
+
const root = env.CODEX_HOME || path.join(home, ".codex");
|
|
114
|
+
const out = [];
|
|
115
|
+
for (const file of walk(path.join(root, "sessions"), (f) => path.basename(f).startsWith("rollout-") && f.endsWith(".jsonl"), 4)) {
|
|
116
|
+
try {
|
|
117
|
+
const raw = readFileSync(file, "utf8");
|
|
118
|
+
const entries = parseCodexTranscript(raw);
|
|
119
|
+
if (entries.length === 0)
|
|
120
|
+
continue;
|
|
121
|
+
const meta = readJsonl(file).find((r) => r.type === "session_meta");
|
|
122
|
+
const payload = isRecord(meta?.payload) ? meta.payload : {};
|
|
123
|
+
const git = isRecord(payload.git) ? payload.git : {};
|
|
124
|
+
out.push({
|
|
125
|
+
harness: "codex",
|
|
126
|
+
file,
|
|
127
|
+
id: typeof payload.id === "string" ? payload.id : path.basename(file, ".jsonl"),
|
|
128
|
+
cwd: typeof payload.cwd === "string" ? payload.cwd : null,
|
|
129
|
+
branch: typeof git.branch === "string" ? git.branch : null,
|
|
130
|
+
...span(entries, statSync(file).mtimeMs),
|
|
131
|
+
entries,
|
|
132
|
+
project: null,
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return out;
|
|
140
|
+
}
|
|
141
|
+
function textOf(content) {
|
|
142
|
+
if (typeof content === "string")
|
|
143
|
+
return content.trim();
|
|
144
|
+
if (!Array.isArray(content))
|
|
145
|
+
return "";
|
|
146
|
+
return content
|
|
147
|
+
.map((c) => (isRecord(c) && c.type === "text" && typeof c.text === "string" ? c.text : ""))
|
|
148
|
+
.filter(Boolean)
|
|
149
|
+
.join("\n")
|
|
150
|
+
.trim();
|
|
151
|
+
}
|
|
152
|
+
function pi(home, env) {
|
|
153
|
+
const root = env.PI_CODING_AGENT_DIR || path.join(home, ".pi", "agent");
|
|
154
|
+
const out = [];
|
|
155
|
+
for (const file of walk(path.join(root, "sessions"), (f) => f.endsWith(".jsonl"), 2)) {
|
|
156
|
+
try {
|
|
157
|
+
const records = readJsonl(file);
|
|
158
|
+
const head = records.find((r) => r.type === "session");
|
|
159
|
+
const entries = [];
|
|
160
|
+
for (const r of records) {
|
|
161
|
+
if (r.type !== "message" || !isRecord(r.message))
|
|
162
|
+
continue;
|
|
163
|
+
const role = r.message.role;
|
|
164
|
+
if (role !== "user" && role !== "assistant")
|
|
165
|
+
continue;
|
|
166
|
+
const text = textOf(r.message.content);
|
|
167
|
+
if (!text)
|
|
168
|
+
continue;
|
|
169
|
+
entries.push({ role, text, paths: [], at: typeof r.timestamp === "string" ? Date.parse(r.timestamp) || 0 : 0 });
|
|
170
|
+
}
|
|
171
|
+
if (entries.length === 0)
|
|
172
|
+
continue;
|
|
173
|
+
out.push({
|
|
174
|
+
harness: "pi",
|
|
175
|
+
file,
|
|
176
|
+
id: typeof head?.id === "string" ? head.id : path.basename(file, ".jsonl"),
|
|
177
|
+
cwd: typeof head?.cwd === "string" ? head.cwd : null,
|
|
178
|
+
branch: null,
|
|
179
|
+
...span(entries, statSync(file).mtimeMs),
|
|
180
|
+
entries,
|
|
181
|
+
project: null,
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
return out;
|
|
189
|
+
}
|
|
190
|
+
function opencode(home, env) {
|
|
191
|
+
const root = path.join(env.XDG_DATA_HOME || path.join(home, ".local", "share"), "opencode", "storage");
|
|
192
|
+
const out = [];
|
|
193
|
+
for (const file of walk(path.join(root, "session"), (f) => f.endsWith(".json"), 2)) {
|
|
194
|
+
try {
|
|
195
|
+
const s = JSON.parse(readFileSync(file, "utf8"));
|
|
196
|
+
if (typeof s.id !== "string")
|
|
197
|
+
continue;
|
|
198
|
+
const msgDir = path.join(root, "message", s.id);
|
|
199
|
+
const messages = walk(msgDir, (f) => f.endsWith(".json"), 0)
|
|
200
|
+
.map((f) => JSON.parse(readFileSync(f, "utf8")))
|
|
201
|
+
.filter((m) => m.role === "user" || m.role === "assistant")
|
|
202
|
+
.sort((a, b) => Number(a.time?.created ?? 0) - Number(b.time?.created ?? 0));
|
|
203
|
+
const entries = [];
|
|
204
|
+
for (const m of messages) {
|
|
205
|
+
const parts = walk(path.join(root, "part", String(m.id)), (f) => f.endsWith(".json"), 0)
|
|
206
|
+
.map((f) => JSON.parse(readFileSync(f, "utf8")))
|
|
207
|
+
.filter((p) => p.type === "text" && typeof p.text === "string" && !p.synthetic)
|
|
208
|
+
.map((p) => String(p.text).trim())
|
|
209
|
+
.filter(Boolean);
|
|
210
|
+
if (parts.length === 0)
|
|
211
|
+
continue;
|
|
212
|
+
entries.push({ role: m.role, text: parts.join("\n"), paths: [], at: Number(m.time?.created ?? 0) });
|
|
213
|
+
}
|
|
214
|
+
if (entries.length === 0)
|
|
215
|
+
continue;
|
|
216
|
+
const time = isRecord(s.time) ? s.time : {};
|
|
217
|
+
out.push({
|
|
218
|
+
harness: "opencode",
|
|
219
|
+
file,
|
|
220
|
+
id: s.id,
|
|
221
|
+
cwd: typeof s.directory === "string" ? s.directory : null,
|
|
222
|
+
branch: null,
|
|
223
|
+
startedAt: Number(time.created ?? 0) || span(entries, statSync(file).mtimeMs).startedAt,
|
|
224
|
+
endedAt: Number(time.updated ?? 0) || span(entries, statSync(file).mtimeMs).endedAt,
|
|
225
|
+
entries,
|
|
226
|
+
project: null,
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
catch {
|
|
230
|
+
continue;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
return out;
|
|
234
|
+
}
|
|
235
|
+
// Antigravity keeps chats under a sha256 of the project directory; the directory itself is not
|
|
236
|
+
// stored. Candidate directories are the cwds other harnesses recorded plus the user's code roots.
|
|
237
|
+
function antigravity(home, env, candidates) {
|
|
238
|
+
const root = env.GEMINI_CLI_HOME || path.join(home, ".gemini");
|
|
239
|
+
const byHash = new Map();
|
|
240
|
+
for (const dir of candidates)
|
|
241
|
+
byHash.set(createHash("sha256").update(dir).digest("hex"), dir);
|
|
242
|
+
const out = [];
|
|
243
|
+
for (const file of walk(path.join(root, "tmp"), (f) => f.endsWith(".json") && path.basename(path.dirname(f)) === "chats", 3)) {
|
|
244
|
+
try {
|
|
245
|
+
const s = JSON.parse(readFileSync(file, "utf8"));
|
|
246
|
+
const messages = Array.isArray(s.messages) ? s.messages : [];
|
|
247
|
+
const jsonl = messages
|
|
248
|
+
.filter((m) => isRecord(m) && (m.type === "user" || m.type === "gemini"))
|
|
249
|
+
.map((m) => JSON.stringify({ role: m.type === "user" ? "user" : "model", content: typeof m.content === "string" ? m.content : textOf(m.content), timestamp: m.timestamp }))
|
|
250
|
+
.join("\n");
|
|
251
|
+
const entries = parseAntigravityTranscript(jsonl);
|
|
252
|
+
if (entries.length === 0)
|
|
253
|
+
continue;
|
|
254
|
+
const hash = typeof s.projectHash === "string" ? s.projectHash : path.basename(path.dirname(path.dirname(file)));
|
|
255
|
+
out.push({
|
|
256
|
+
harness: "antigravity",
|
|
257
|
+
file,
|
|
258
|
+
id: typeof s.sessionId === "string" ? s.sessionId : path.basename(file, ".json"),
|
|
259
|
+
cwd: byHash.get(hash) ?? null,
|
|
260
|
+
branch: null,
|
|
261
|
+
startedAt: typeof s.startTime === "string" ? Date.parse(s.startTime) || 0 : 0,
|
|
262
|
+
endedAt: typeof s.lastUpdated === "string" ? Date.parse(s.lastUpdated) || 0 : 0,
|
|
263
|
+
entries,
|
|
264
|
+
project: null,
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
catch {
|
|
268
|
+
continue;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
return out;
|
|
272
|
+
}
|
|
273
|
+
// Cursor documents no transcript store; anything that looks like one under ~/.cursor is tried.
|
|
274
|
+
function cursor(home, _env) {
|
|
275
|
+
const root = path.join(home, ".cursor");
|
|
276
|
+
const out = [];
|
|
277
|
+
for (const file of walk(root, (f) => /transcript/i.test(f) && (f.endsWith(".jsonl") || f.endsWith(".json")), 5)) {
|
|
278
|
+
try {
|
|
279
|
+
const entries = parseCursorTranscript(readFileSync(file, "utf8"));
|
|
280
|
+
if (entries.length === 0)
|
|
281
|
+
continue;
|
|
282
|
+
out.push({ harness: "cursor", file, id: path.basename(file).replace(/\.jsonl?$/, ""), cwd: null, branch: null, ...span(entries, statSync(file).mtimeMs), entries, project: null });
|
|
283
|
+
}
|
|
284
|
+
catch {
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
return out;
|
|
289
|
+
}
|
|
290
|
+
export const ALL_HARNESSES = ["claude-code", "codex", "pi", "opencode", "antigravity", "cursor", "openclaw"];
|
|
291
|
+
export function discoverSessions(opts = {}) {
|
|
292
|
+
const env = opts.env ?? process.env;
|
|
293
|
+
const home = opts.home ?? homedir();
|
|
294
|
+
const wanted = new Set(opts.harnesses ?? ALL_HARNESSES);
|
|
295
|
+
const sessions = [];
|
|
296
|
+
if (wanted.has("claude-code"))
|
|
297
|
+
sessions.push(...claudeCode(home, env));
|
|
298
|
+
if (wanted.has("codex"))
|
|
299
|
+
sessions.push(...codex(home, env));
|
|
300
|
+
if (wanted.has("pi"))
|
|
301
|
+
sessions.push(...pi(home, env));
|
|
302
|
+
if (wanted.has("opencode"))
|
|
303
|
+
sessions.push(...opencode(home, env));
|
|
304
|
+
if (wanted.has("cursor"))
|
|
305
|
+
sessions.push(...cursor(home, env));
|
|
306
|
+
if (wanted.has("antigravity")) {
|
|
307
|
+
const candidates = new Set(sessions.map((s) => s.cwd).filter((c) => c !== null));
|
|
308
|
+
for (const rootName of ["Code", "code", "src", "projects", "work", "dev"]) {
|
|
309
|
+
const root = path.join(home, rootName);
|
|
310
|
+
if (!existsSync(root))
|
|
311
|
+
continue;
|
|
312
|
+
try {
|
|
313
|
+
for (const name of readdirSync(root))
|
|
314
|
+
candidates.add(path.join(root, name));
|
|
315
|
+
}
|
|
316
|
+
catch {
|
|
317
|
+
// unreadable root
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
sessions.push(...antigravity(home, env, candidates));
|
|
321
|
+
}
|
|
322
|
+
// OpenClaw keeps no transcript on disk that hooks or this reader can see.
|
|
323
|
+
const projectOf = opts.projectOf ?? gitProjectResolver();
|
|
324
|
+
for (const s of sessions)
|
|
325
|
+
s.project = s.cwd ? projectOf(s.cwd) : null;
|
|
326
|
+
return sessions.sort((a, b) => b.endedAt - a.endedAt);
|
|
327
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { KINDS, redact } from "@meshpoint/sdk";
|
|
2
|
+
import { extractRefs } from "../refs.js";
|
|
3
|
+
import { jsonBlock } from "./runner.js";
|
|
4
|
+
// Transcript text kept per call: the start sets the task, the end holds what was established.
|
|
5
|
+
export const HEAD_CHARS = 20_000;
|
|
6
|
+
export const TAIL_CHARS = 40_000;
|
|
7
|
+
export const SESSION_ITEMS_MAX = 20;
|
|
8
|
+
export const BRANCH_ITEMS_MAX = 60;
|
|
9
|
+
const KEY_RE = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/;
|
|
10
|
+
const RULES = `Write what a teammate's agent would need to resume work in this repository correctly, as items.
|
|
11
|
+
Each item is {"kind", "title", "body"}. kind is one of: decision (a choice made and why), gotcha (something that bit or will bite), convention (how things are done here), fact (a stable truth about the code or environment), status (where the work stands), todo (an agreed next step).
|
|
12
|
+
title is one line. body is one to three sentences, concrete: file names by repo-relative path, commands, values, reasons.
|
|
13
|
+
Rules: only what this session established, never invent; prefer durable knowledge over moment-to-moment detail; at most one status; no secrets, tokens or credentials; skip chit-chat and anything true of every project.`;
|
|
14
|
+
export function renderTranscript(entries) {
|
|
15
|
+
const lines = entries.map((e) => `[${e.role}] ${e.text}${e.paths.length ? `\n(files: ${e.paths.slice(0, 8).join(", ")})` : ""}`);
|
|
16
|
+
const text = lines.join("\n\n");
|
|
17
|
+
if (text.length <= HEAD_CHARS + TAIL_CHARS)
|
|
18
|
+
return text;
|
|
19
|
+
return `${text.slice(0, HEAD_CHARS)}\n\n[... ${text.length - HEAD_CHARS - TAIL_CHARS} characters omitted ...]\n\n${text.slice(-TAIL_CHARS)}`;
|
|
20
|
+
}
|
|
21
|
+
export function sessionPrompt(s) {
|
|
22
|
+
return [
|
|
23
|
+
RULES,
|
|
24
|
+
"",
|
|
25
|
+
`Harness: ${s.harness}. Repository directory: ${s.cwd ?? "unknown"}. Branch: ${s.branch ?? "unknown"}. Session started ${new Date(s.startedAt).toISOString()}.`,
|
|
26
|
+
"",
|
|
27
|
+
`Output only a JSON array of at most ${SESSION_ITEMS_MAX} items. Output [] if the session established nothing worth keeping.`,
|
|
28
|
+
"",
|
|
29
|
+
"Transcript:",
|
|
30
|
+
renderTranscript(s.entries),
|
|
31
|
+
].join("\n");
|
|
32
|
+
}
|
|
33
|
+
function isRecord(v) {
|
|
34
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
35
|
+
}
|
|
36
|
+
export function parseProposed(raw, session) {
|
|
37
|
+
let parsed;
|
|
38
|
+
try {
|
|
39
|
+
parsed = jsonBlock(raw);
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return [];
|
|
43
|
+
}
|
|
44
|
+
if (!Array.isArray(parsed))
|
|
45
|
+
return [];
|
|
46
|
+
const out = [];
|
|
47
|
+
for (const v of parsed) {
|
|
48
|
+
if (!isRecord(v) || typeof v.kind !== "string" || !KINDS.includes(v.kind))
|
|
49
|
+
continue;
|
|
50
|
+
if (typeof v.title !== "string" || !v.title.trim() || typeof v.body !== "string" || !v.body.trim())
|
|
51
|
+
continue;
|
|
52
|
+
const item = { kind: v.kind, title: redact(v.title.trim().slice(0, 200)), body: redact(v.body.trim().slice(0, 2000)), sessions: [session] };
|
|
53
|
+
if (typeof v.key === "string" && KEY_RE.test(v.key))
|
|
54
|
+
item.key = v.key;
|
|
55
|
+
if (v.recurring === true)
|
|
56
|
+
item.recurring = true;
|
|
57
|
+
out.push(item);
|
|
58
|
+
if (out.length >= SESSION_ITEMS_MAX)
|
|
59
|
+
break;
|
|
60
|
+
}
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
export async function distillSession(runner, s) {
|
|
64
|
+
return parseProposed(await runner.run(sessionPrompt(s)), s.id);
|
|
65
|
+
}
|
|
66
|
+
export function consolidatePrompt(items, live) {
|
|
67
|
+
return [
|
|
68
|
+
"You merge knowledge items proposed from several coding sessions on one repository branch into one list.",
|
|
69
|
+
"Input items carry the ids of the sessions that produced them. Rules:",
|
|
70
|
+
"- Merge duplicates and near-duplicates into one item; keep every session id in \"sessions\".",
|
|
71
|
+
"- When a fact or decision changed across sessions, keep only the newest statement (later session ids are newer in the list).",
|
|
72
|
+
"- Give conventions a short stable \"key\" (letters, digits, . _ : / -) such as test-runner or deploy-target.",
|
|
73
|
+
"- Mark a gotcha \"recurring\": true when the same problem appears in two or more sessions.",
|
|
74
|
+
"- Drop status items and todos that read as finished; keep at most one status.",
|
|
75
|
+
"- Items already live on the branch are listed; do not repeat them, and when a proposed item supersedes a live one, add \"supersedes\": [\"<live id>\"].",
|
|
76
|
+
`- Output only a JSON array of at most ${BRANCH_ITEMS_MAX} items: {"kind","title","body","key"?,"recurring"?,"supersedes"?,"sessions"}.`,
|
|
77
|
+
"",
|
|
78
|
+
`Live items on the branch:\n${JSON.stringify(live.map((i) => ({ id: i.id, kind: i.kind, title: i.title, body: i.body })))}`,
|
|
79
|
+
"",
|
|
80
|
+
`Proposed items:\n${JSON.stringify(items)}`,
|
|
81
|
+
].join("\n");
|
|
82
|
+
}
|
|
83
|
+
export function parseMerged(raw, fallback) {
|
|
84
|
+
let parsed;
|
|
85
|
+
try {
|
|
86
|
+
parsed = jsonBlock(raw);
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
return [...fallback];
|
|
90
|
+
}
|
|
91
|
+
if (!Array.isArray(parsed))
|
|
92
|
+
return [...fallback];
|
|
93
|
+
const out = [];
|
|
94
|
+
for (const v of parsed) {
|
|
95
|
+
if (!isRecord(v) || typeof v.kind !== "string" || !KINDS.includes(v.kind))
|
|
96
|
+
continue;
|
|
97
|
+
if (typeof v.title !== "string" || !v.title.trim() || typeof v.body !== "string" || !v.body.trim())
|
|
98
|
+
continue;
|
|
99
|
+
const item = {
|
|
100
|
+
kind: v.kind,
|
|
101
|
+
title: redact(v.title.trim().slice(0, 200)),
|
|
102
|
+
body: redact(v.body.trim().slice(0, 2000)),
|
|
103
|
+
sessions: Array.isArray(v.sessions) ? v.sessions.filter((x) => typeof x === "string").slice(0, 50) : [],
|
|
104
|
+
};
|
|
105
|
+
if (typeof v.key === "string" && KEY_RE.test(v.key))
|
|
106
|
+
item.key = v.key;
|
|
107
|
+
if (v.recurring === true)
|
|
108
|
+
item.recurring = true;
|
|
109
|
+
if (Array.isArray(v.supersedes))
|
|
110
|
+
item.supersedes = v.supersedes.filter((x) => typeof x === "string").slice(0, 20);
|
|
111
|
+
out.push(item);
|
|
112
|
+
if (out.length >= BRANCH_ITEMS_MAX)
|
|
113
|
+
break;
|
|
114
|
+
}
|
|
115
|
+
return out;
|
|
116
|
+
}
|
|
117
|
+
export async function consolidate(runner, items, live) {
|
|
118
|
+
if (items.length === 0)
|
|
119
|
+
return [];
|
|
120
|
+
return parseMerged(await runner.run(consolidatePrompt(items, live)), items);
|
|
121
|
+
}
|
|
122
|
+
// Items that name a file the checkout no longer has are left out of the proposal.
|
|
123
|
+
export function prune(items, root, exists) {
|
|
124
|
+
const kept = [];
|
|
125
|
+
const dropped = [];
|
|
126
|
+
for (const i of items) {
|
|
127
|
+
const found = extractRefs(`${i.title}\n${i.body}`, root, exists);
|
|
128
|
+
if (found.missing.length > 0)
|
|
129
|
+
dropped.push({ ...i, missing: found.missing });
|
|
130
|
+
else
|
|
131
|
+
kept.push({ ...i, refs: found.refs });
|
|
132
|
+
}
|
|
133
|
+
return { kept, dropped };
|
|
134
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
function plural(n, word) {
|
|
2
|
+
return `${n} ${word}${n === 1 ? "" : "s"}`;
|
|
3
|
+
}
|
|
4
|
+
function topPaths(sessions, max = 8) {
|
|
5
|
+
const counts = new Map();
|
|
6
|
+
for (const s of sessions)
|
|
7
|
+
for (const e of s.entries)
|
|
8
|
+
for (const p of e.paths)
|
|
9
|
+
counts.set(p, (counts.get(p) ?? 0) + 1);
|
|
10
|
+
return [...counts].sort((a, b) => b[1] - a[1]).slice(0, max).map(([p, n]) => `${p} (${n})`);
|
|
11
|
+
}
|
|
12
|
+
export function renderReport(results, unmapped, skipped) {
|
|
13
|
+
const lines = [];
|
|
14
|
+
for (const r of results) {
|
|
15
|
+
const byHarness = new Map();
|
|
16
|
+
for (const s of r.sessions)
|
|
17
|
+
byHarness.set(s.harness, (byHarness.get(s.harness) ?? 0) + 1);
|
|
18
|
+
const turns = r.sessions.reduce((n, s) => n + s.entries.length, 0);
|
|
19
|
+
const first = Math.min(...r.sessions.map((s) => s.startedAt));
|
|
20
|
+
const last = Math.max(...r.sessions.map((s) => s.endedAt));
|
|
21
|
+
lines.push(`== ${r.project}`, `${plural(r.sessions.length, "session")} (${[...byHarness].map(([h, n]) => `${h} ${n}`).join(", ")}), ${plural(turns, "turn")}, ${new Date(first).toISOString().slice(0, 10)} to ${new Date(last).toISOString().slice(0, 10)}`);
|
|
22
|
+
const paths = topPaths(r.sessions);
|
|
23
|
+
if (paths.length)
|
|
24
|
+
lines.push(`most touched: ${paths.join(", ")}`);
|
|
25
|
+
for (const b of r.branches) {
|
|
26
|
+
const kinds = new Map();
|
|
27
|
+
for (const i of b.items)
|
|
28
|
+
kinds.set(i.kind, (kinds.get(i.kind) ?? 0) + 1);
|
|
29
|
+
lines.push("", `-- ${b.branch}: ${plural(b.items.length, "item")} proposed (${[...kinds].map(([k, n]) => `${n} ${k}`).join(", ") || "none"})${b.dropped.length ? `, ${b.dropped.length} dropped for naming files that are gone` : ""}`);
|
|
30
|
+
const recurring = b.items.filter((i) => i.recurring);
|
|
31
|
+
if (recurring.length) {
|
|
32
|
+
lines.push("recurring gotchas:");
|
|
33
|
+
for (const i of recurring)
|
|
34
|
+
lines.push(` * ${i.title} (${plural(i.sessions.length, "session")})`);
|
|
35
|
+
}
|
|
36
|
+
for (const i of b.items.filter((x) => !x.recurring))
|
|
37
|
+
lines.push(` - [${i.kind}] ${i.title}${i.key ? ` #${i.key}` : ""}`);
|
|
38
|
+
for (const d of b.dropped)
|
|
39
|
+
lines.push(` x [${d.kind}] ${d.title}: missing ${d.missing.join(", ")}`);
|
|
40
|
+
}
|
|
41
|
+
for (const e of r.errors)
|
|
42
|
+
lines.push(`! ${e}`);
|
|
43
|
+
lines.push("");
|
|
44
|
+
}
|
|
45
|
+
if (unmapped.length) {
|
|
46
|
+
const byHarness = new Map();
|
|
47
|
+
for (const s of unmapped)
|
|
48
|
+
byHarness.set(s.harness, (byHarness.get(s.harness) ?? 0) + 1);
|
|
49
|
+
lines.push(`${plural(unmapped.length, "session")} could not be mapped to a repository (${[...byHarness].map(([h, n]) => `${h} ${n}`).join(", ")}): the recorded directory is gone, has no origin remote, or the store records no directory.`);
|
|
50
|
+
}
|
|
51
|
+
for (const [h, why] of Object.entries(skipped))
|
|
52
|
+
lines.push(`${h}: ${why}`);
|
|
53
|
+
return lines.join("\n");
|
|
54
|
+
}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { createInterface } from "node:readline";
|
|
5
|
+
import { MeshpointClient } from "@meshpoint/sdk";
|
|
6
|
+
import { headSha } from "../refs.js";
|
|
7
|
+
import { discoverSessions } from "./discover.js";
|
|
8
|
+
import { consolidate, distillSession, prune } from "./distill.js";
|
|
9
|
+
import { renderReport } from "./report.js";
|
|
10
|
+
// `meshpoint import sessions`: the whole flow, dry run by default. Nothing leaves the machine
|
|
11
|
+
// without --apply; anything older than the default window or outside the current repo asks first.
|
|
12
|
+
export const DEFAULT_SINCE_DAYS = 90;
|
|
13
|
+
export const TURNS_WINDOW_DAYS = 30;
|
|
14
|
+
const DISTILL_CONCURRENCY = 2;
|
|
15
|
+
const ALL_ITEMS_BUDGET = 100_000;
|
|
16
|
+
const CAPTURE_SESSIONS_MAX = 100;
|
|
17
|
+
async function askTty(question) {
|
|
18
|
+
if (!process.stdin.isTTY)
|
|
19
|
+
return false;
|
|
20
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
21
|
+
const answer = await new Promise((r) => rl.question(`${question} [y/N] `, r));
|
|
22
|
+
rl.close();
|
|
23
|
+
return /^y(es)?$/i.test(answer.trim());
|
|
24
|
+
}
|
|
25
|
+
async function mapPool(items, size, fn) {
|
|
26
|
+
const out = new Array(items.length);
|
|
27
|
+
let i = 0;
|
|
28
|
+
await Promise.all(Array.from({ length: Math.min(size, items.length) }, async () => {
|
|
29
|
+
while (i < items.length) {
|
|
30
|
+
const n = i++;
|
|
31
|
+
out[n] = await fn(items[n]);
|
|
32
|
+
}
|
|
33
|
+
}));
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
function safe(name) {
|
|
37
|
+
return name.replace(/[^A-Za-z0-9._-]/g, "_");
|
|
38
|
+
}
|
|
39
|
+
export async function importSessions(opts) {
|
|
40
|
+
const now = opts.now ?? Date.now;
|
|
41
|
+
const log = opts.log ?? ((l) => process.stderr.write(`${l}\n`));
|
|
42
|
+
const confirm = opts.confirm ?? askTty;
|
|
43
|
+
const discover = opts.discover ?? discoverSessions;
|
|
44
|
+
const since = now() - opts.sinceDays * 86_400_000;
|
|
45
|
+
const all = discover({ ...(opts.env ? { env: opts.env } : {}), ...(opts.home ? { home: opts.home } : {}) });
|
|
46
|
+
const inWindow = all.filter((s) => s.endedAt >= since && s.entries.length >= opts.minTurns);
|
|
47
|
+
const unmapped = inWindow.filter((s) => s.project === null);
|
|
48
|
+
let selected = inWindow.filter((s) => s.project !== null);
|
|
49
|
+
if (!opts.allRepos) {
|
|
50
|
+
if (!opts.current)
|
|
51
|
+
throw new Error("not inside a git repo with an origin remote; pass --all-repos to import every repository");
|
|
52
|
+
selected = selected.filter((s) => s.project === opts.current.project);
|
|
53
|
+
}
|
|
54
|
+
const empty = { results: [], unmapped, reportFile: "", itemsFiles: [], uploaded: { items: 0, turns: 0 }, cancelled: false };
|
|
55
|
+
if (selected.length === 0) {
|
|
56
|
+
log(`no sessions found${opts.allRepos ? "" : ` for ${opts.current?.project}`} in the last ${opts.sinceDays} days (${inWindow.length} in the window, ${unmapped.length} unmapped)`);
|
|
57
|
+
return empty;
|
|
58
|
+
}
|
|
59
|
+
// Confirm before reading beyond the defaults.
|
|
60
|
+
const needsConfirm = opts.sinceDays > DEFAULT_SINCE_DAYS || opts.allRepos;
|
|
61
|
+
if (needsConfirm && !opts.yes) {
|
|
62
|
+
const projects = [...new Set(selected.map((s) => s.project))];
|
|
63
|
+
log(`About to read ${selected.length} session transcripts from ${projects.length} repositor${projects.length === 1 ? "y" : "ies"} going back ${opts.sinceDays} days:`);
|
|
64
|
+
for (const p of projects.slice(0, 30))
|
|
65
|
+
log(` ${p} (${selected.filter((s) => s.project === p).length})`);
|
|
66
|
+
if (projects.length > 30)
|
|
67
|
+
log(` ... and ${projects.length - 30} more`);
|
|
68
|
+
if (!(await confirm("Continue? Transcripts are distilled with your own agent CLI; nothing is uploaded without --apply."))) {
|
|
69
|
+
log("cancelled");
|
|
70
|
+
return { ...empty, cancelled: true };
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
const byProject = new Map();
|
|
74
|
+
for (const s of selected)
|
|
75
|
+
byProject.set(s.project, [...(byProject.get(s.project) ?? []), s]);
|
|
76
|
+
const results = [];
|
|
77
|
+
const itemsFiles = [];
|
|
78
|
+
const uploaded = { items: 0, turns: 0 };
|
|
79
|
+
const outDir = path.join(opts.stateDir, "import");
|
|
80
|
+
mkdirSync(outDir, { recursive: true, mode: 0o700 });
|
|
81
|
+
for (const [project, sessions] of byProject) {
|
|
82
|
+
const root = opts.current?.project === project ? opts.current.root : (sessions.find((s) => s.cwd && existsSync(s.cwd))?.cwd ?? "");
|
|
83
|
+
const defaultBranch = opts.current?.project === project ? opts.current.defaultBranch : "master";
|
|
84
|
+
const result = { project, root, sessions, branches: [], errors: [] };
|
|
85
|
+
log(`${project}: distilling ${sessions.length} session${sessions.length === 1 ? "" : "s"} with ${opts.runner.name}`);
|
|
86
|
+
const proposals = await mapPool(sessions, DISTILL_CONCURRENCY, async (s) => {
|
|
87
|
+
try {
|
|
88
|
+
const items = await distillSession(opts.runner, s);
|
|
89
|
+
log(` ${s.harness} ${s.id.slice(0, 8)} (${s.entries.length} turns): ${items.length} proposed`);
|
|
90
|
+
return { s, items };
|
|
91
|
+
}
|
|
92
|
+
catch (err) {
|
|
93
|
+
result.errors.push(`${s.harness} ${s.id.slice(0, 8)}: ${err instanceof Error ? err.message : String(err)}`);
|
|
94
|
+
return { s, items: [] };
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
// Oldest first, so the consolidation pass can treat later sessions as newer.
|
|
98
|
+
proposals.sort((a, b) => a.s.endedAt - b.s.endedAt);
|
|
99
|
+
const byBranch = new Map();
|
|
100
|
+
for (const p of proposals) {
|
|
101
|
+
const branch = p.s.branch ?? defaultBranch;
|
|
102
|
+
byBranch.set(branch, [...(byBranch.get(branch) ?? []), ...p.items]);
|
|
103
|
+
}
|
|
104
|
+
const client = (branch) => new MeshpointClient({ baseUrl: opts.config.baseUrl, token: opts.config.token, project, branch, ...(opts.fetch ? { fetch: opts.fetch } : {}) });
|
|
105
|
+
for (const [branch, proposed] of byBranch) {
|
|
106
|
+
if (proposed.length === 0)
|
|
107
|
+
continue;
|
|
108
|
+
let live = [];
|
|
109
|
+
try {
|
|
110
|
+
live = (await client(branch).recall({ budget: ALL_ITEMS_BUDGET, fresh: true })).items;
|
|
111
|
+
}
|
|
112
|
+
catch (err) {
|
|
113
|
+
result.errors.push(`${branch}: could not read live items (${err instanceof Error ? err.message : String(err)}); consolidating without them`);
|
|
114
|
+
}
|
|
115
|
+
let merged;
|
|
116
|
+
try {
|
|
117
|
+
merged = await consolidate(opts.runner, proposed, live);
|
|
118
|
+
}
|
|
119
|
+
catch (err) {
|
|
120
|
+
result.errors.push(`${branch}: consolidation failed (${err instanceof Error ? err.message : String(err)}); using the per-session proposals`);
|
|
121
|
+
merged = proposed;
|
|
122
|
+
}
|
|
123
|
+
const liveIds = new Set(live.map((i) => i.id));
|
|
124
|
+
for (const m of merged)
|
|
125
|
+
if (m.supersedes)
|
|
126
|
+
m.supersedes = m.supersedes.filter((id) => liveIds.has(id));
|
|
127
|
+
const { kept, dropped } = root ? prune(merged, root, opts.exists) : { kept: merged.map((m) => ({ ...m, refs: [] })), dropped: [] };
|
|
128
|
+
const branchResult = { branch, items: kept, dropped };
|
|
129
|
+
result.branches.push(branchResult);
|
|
130
|
+
log(` ${branch}: ${kept.length} items proposed, ${dropped.length} dropped`);
|
|
131
|
+
}
|
|
132
|
+
const file = path.join(outDir, `${safe(project)}.items.json`);
|
|
133
|
+
writeFileSync(file, `${JSON.stringify(result.branches.map((b) => ({ branch: b.branch, items: b.items, dropped: b.dropped })), null, 2)}\n`, { mode: 0o600 });
|
|
134
|
+
itemsFiles.push(file);
|
|
135
|
+
if (opts.apply) {
|
|
136
|
+
const sha = root ? headSha(root) : "";
|
|
137
|
+
for (const b of result.branches) {
|
|
138
|
+
if (b.items.length === 0)
|
|
139
|
+
continue;
|
|
140
|
+
const inputs = b.items.map((i) => ({
|
|
141
|
+
id: randomUUID(),
|
|
142
|
+
kind: i.kind,
|
|
143
|
+
title: i.title,
|
|
144
|
+
body: i.body,
|
|
145
|
+
refs: i.refs,
|
|
146
|
+
paths: [],
|
|
147
|
+
...(sha ? { commit_sha: sha } : {}),
|
|
148
|
+
...(i.key ? { key: i.key } : {}),
|
|
149
|
+
...(i.supersedes && i.supersedes.length ? { supersedes: i.supersedes } : {}),
|
|
150
|
+
provenance: JSON.stringify({ agent: `import:${[...new Set(sessions.filter((s) => i.sessions.includes(s.id)).map((s) => s.harness))].join("+") || opts.runner.name}`, user: opts.config.user ?? "", sessions: i.sessions.slice(0, 20) }),
|
|
151
|
+
}));
|
|
152
|
+
try {
|
|
153
|
+
const out = await client(b.branch).putItems(inputs);
|
|
154
|
+
uploaded.items += out.count;
|
|
155
|
+
log(` ${b.branch}: uploaded ${out.count} items${out.superseded ? `, ${out.superseded} superseded` : ""}`);
|
|
156
|
+
}
|
|
157
|
+
catch (err) {
|
|
158
|
+
result.errors.push(`${b.branch}: upload failed (${err instanceof Error ? err.message : String(err)})`);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
if (opts.withTurns) {
|
|
162
|
+
const cutoff = now() - TURNS_WINDOW_DAYS * 86_400_000;
|
|
163
|
+
for (const s of sessions.filter((x) => x.endedAt >= cutoff).slice(0, CAPTURE_SESSIONS_MAX)) {
|
|
164
|
+
const c = new MeshpointClient({ baseUrl: opts.config.baseUrl, token: opts.config.token, project, branch: s.branch ?? defaultBranch, session: s.id, flushMaxTurns: 200, ...(opts.fetch ? { fetch: opts.fetch } : {}), onError: (e) => result.errors.push(`${s.id.slice(0, 8)}: turns upload: ${e.message}`) });
|
|
165
|
+
for (const e of s.entries)
|
|
166
|
+
c.capture({ body: `[${e.role}] ${e.text}`, at: e.at || s.startedAt, ...(e.paths.length ? { paths: e.paths.map((p) => (root && path.isAbsolute(p) ? path.relative(root, p) : p)).filter((p) => p && !p.startsWith("..")) } : {}) });
|
|
167
|
+
await c.close();
|
|
168
|
+
uploaded.turns += s.entries.length;
|
|
169
|
+
}
|
|
170
|
+
log(` turns uploaded for sessions in the last ${TURNS_WINDOW_DAYS} days: ${uploaded.turns}`);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
results.push(result);
|
|
174
|
+
}
|
|
175
|
+
const report = renderReport(results, unmapped, { openclaw: "keeps no transcript on disk; nothing to import", cursor: "transcript store is undocumented; only files named like transcripts under ~/.cursor are tried" });
|
|
176
|
+
const reportFile = path.join(outDir, `report-${new Date(now()).toISOString().slice(0, 10)}.txt`);
|
|
177
|
+
writeFileSync(reportFile, `${report}\n`, { mode: 0o600 });
|
|
178
|
+
log("");
|
|
179
|
+
log(report);
|
|
180
|
+
log("");
|
|
181
|
+
log(opts.apply ? `uploaded ${uploaded.items} items${opts.withTurns ? ` and ${uploaded.turns} turns` : ""}; proposals saved in ${outDir}` : `dry run: proposals saved in ${outDir}; run again with --apply to upload`);
|
|
182
|
+
return { results, unmapped, reportFile, itemsFiles, uploaded, cancelled: false };
|
|
183
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { execFileSync, spawnSync } from "node:child_process";
|
|
2
|
+
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
const SYSTEM = "You are a careful assistant. Follow the instructions in the message exactly. No tools, no preamble, output only what is asked.";
|
|
6
|
+
const TIMEOUT_MS = 10 * 60_000;
|
|
7
|
+
function onPath(bin, env) {
|
|
8
|
+
for (const dir of (env.PATH ?? "").split(path.delimiter)) {
|
|
9
|
+
if (!dir)
|
|
10
|
+
continue;
|
|
11
|
+
try {
|
|
12
|
+
execFileSync("test", ["-x", path.join(dir, bin)], { stdio: "ignore" });
|
|
13
|
+
return true;
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
continue;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
// CLAUDE* variables are dropped so the CLI does not refuse to nest inside a running Claude Code session.
|
|
22
|
+
function cleanEnv(env) {
|
|
23
|
+
return Object.fromEntries(Object.entries(env).filter(([k, v]) => v !== undefined && !k.startsWith("CLAUDE")));
|
|
24
|
+
}
|
|
25
|
+
export function claudeRunner(env, model) {
|
|
26
|
+
return {
|
|
27
|
+
name: "claude",
|
|
28
|
+
async run(prompt) {
|
|
29
|
+
const args = ["-p", "--output-format", "json", "--no-session-persistence", "--tools", "", "--setting-sources", "", "--system-prompt", SYSTEM];
|
|
30
|
+
if (model)
|
|
31
|
+
args.push("--model", model);
|
|
32
|
+
const dir = mkdtempSync(path.join(tmpdir(), "meshpoint-import-"));
|
|
33
|
+
try {
|
|
34
|
+
const res = spawnSync("claude", args, { input: prompt, env: cleanEnv(env), cwd: dir, timeout: TIMEOUT_MS, maxBuffer: 64 * 1024 * 1024 });
|
|
35
|
+
if (res.status !== 0)
|
|
36
|
+
throw new Error(`claude exited ${res.status}: ${(res.stderr ?? "").toString().slice(0, 300) || (res.stdout ?? "").toString().slice(0, 300)}`);
|
|
37
|
+
const data = JSON.parse(res.stdout.toString());
|
|
38
|
+
if (data.is_error)
|
|
39
|
+
throw new Error(`claude: ${String(data.result).slice(0, 300)}`);
|
|
40
|
+
return data.result ?? "";
|
|
41
|
+
}
|
|
42
|
+
finally {
|
|
43
|
+
rmSync(dir, { recursive: true, force: true });
|
|
44
|
+
}
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
// codex exec writes the final message to a file; the prompt goes in on stdin.
|
|
49
|
+
export function codexRunner(env, model) {
|
|
50
|
+
return {
|
|
51
|
+
name: "codex",
|
|
52
|
+
async run(prompt) {
|
|
53
|
+
const dir = mkdtempSync(path.join(tmpdir(), "meshpoint-import-"));
|
|
54
|
+
const out = path.join(dir, "last.md");
|
|
55
|
+
try {
|
|
56
|
+
const args = ["exec", "--skip-git-repo-check", "--sandbox", "read-only", "--output-last-message", out];
|
|
57
|
+
if (model)
|
|
58
|
+
args.push("-m", model);
|
|
59
|
+
args.push("-");
|
|
60
|
+
const res = spawnSync("codex", args, { input: `${SYSTEM}\n\n${prompt}`, env: cleanEnv(env), cwd: dir, timeout: TIMEOUT_MS, maxBuffer: 64 * 1024 * 1024 });
|
|
61
|
+
if (res.status !== 0)
|
|
62
|
+
throw new Error(`codex exited ${res.status}: ${(res.stderr ?? "").toString().slice(0, 300)}`);
|
|
63
|
+
return readFileSync(out, "utf8");
|
|
64
|
+
}
|
|
65
|
+
finally {
|
|
66
|
+
rmSync(dir, { recursive: true, force: true });
|
|
67
|
+
}
|
|
68
|
+
},
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
export function detectRunner(env, prefer, model) {
|
|
72
|
+
const order = prefer ? [prefer, ...["claude", "codex"].filter((n) => n !== prefer)] : ["claude", "codex"];
|
|
73
|
+
for (const name of order) {
|
|
74
|
+
if (!onPath(name, env))
|
|
75
|
+
continue;
|
|
76
|
+
return name === "claude" ? claudeRunner(env, model) : codexRunner(env, model);
|
|
77
|
+
}
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
// The first JSON array or object in a model reply, code fences tolerated.
|
|
81
|
+
export function jsonBlock(text) {
|
|
82
|
+
let s = text.trim();
|
|
83
|
+
if (s.startsWith("```")) {
|
|
84
|
+
s = s.includes("\n") ? s.slice(s.indexOf("\n") + 1) : s.slice(3);
|
|
85
|
+
s = s.lastIndexOf("```") >= 0 ? s.slice(0, s.lastIndexOf("```")) : s;
|
|
86
|
+
}
|
|
87
|
+
const starts = [s.indexOf("["), s.indexOf("{")].filter((i) => i >= 0);
|
|
88
|
+
const start = starts.length ? Math.min(...starts) : 0;
|
|
89
|
+
return JSON.parse(s.slice(start));
|
|
90
|
+
}
|
package/dist/refs.js
CHANGED
|
@@ -57,6 +57,9 @@ export function extractRefs(text, root, exists = existsSync) {
|
|
|
57
57
|
// Backticked tokens may be bare file names (Makefile); they count only when they exist.
|
|
58
58
|
if (!pathLike && strict)
|
|
59
59
|
return;
|
|
60
|
+
// An absolute path outside the repository (/dev/null, /etc/hosts) is not a ref and not a miss.
|
|
61
|
+
if (path.isAbsolute(token) && path.relative(root, token).startsWith(".."))
|
|
62
|
+
return;
|
|
60
63
|
const rel = resolve(token, root, exists);
|
|
61
64
|
if (rel)
|
|
62
65
|
refs.add(rel);
|
package/dist/tap.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@meshpoint/cli",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.0",
|
|
4
4
|
"description": "Meshpoint CLI and harness adapters: shared agent memory for developer teams",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"meshpoint",
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
"prepublishOnly": "npm run check && npm run build"
|
|
39
39
|
},
|
|
40
40
|
"dependencies": {
|
|
41
|
-
"@meshpoint/sdk": "^1.
|
|
41
|
+
"@meshpoint/sdk": "^1.3.0"
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
44
|
"@types/node": "^22.0.0",
|