@meshpoint/cli 0.0.0-stage → 1.0.0-rc.1

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/dist/bin.js ADDED
@@ -0,0 +1,310 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { connectAntigravity } from "./antigravity/connect.js";
5
+ import { runAntigravityTap } from "./antigravity/tap.js";
6
+ import { connectClaudeCode } from "./claude-code/connect.js";
7
+ import { runClaudeCodeTap } from "./claude-code/tap.js";
8
+ import { connectCodex } from "./codex/connect.js";
9
+ import { parseCodexTranscript } from "./codex/transcript.js";
10
+ import { connectCursor } from "./cursor/connect.js";
11
+ import { runCursorTap } from "./cursor/tap.js";
12
+ import { connectOpenclaw } from "./openclaw/connect.js";
13
+ import { connectOpencode } from "./opencode/connect.js";
14
+ import { ReplyLog, runOpenclawTap } from "./openclaw/tap.js";
15
+ import { connectPi } from "./pi/connect.js";
16
+ import { Checkpoints } from "./checkpoints.js";
17
+ import { configPath, deleteConfig, loadConfig, repoContext, saveConfig, spoolDir, stateDir } from "./config.js";
18
+ import { MeshpointError } from "@meshpoint/sdk";
19
+ import { api, ApiError, canOpenBrowser, deviceLogin, freshConfig, login } from "./control.js";
20
+ import { detectHarnesses, renderDetected } from "./detect.js";
21
+ import { renderDoctor, runDoctor } from "./doctor.js";
22
+ import { parseItemArgs, parseItems, putItems, retractItems } from "./items.js";
23
+ import { Spool } from "./spool.js";
24
+ const USAGE = `meshpoint <command>
25
+
26
+ login [--base-url <url>] [--agent <name>] [--org <id>] [--device | --browser]
27
+ log in; stores tokens in ${configPath()}
28
+ (default base url: https://api.meshpoint.dev). Opens a browser
29
+ when one can run, else prints a code to approve in the console;
30
+ --device or --browser forces one flow
31
+ login --base-url <url> --token <token> store a pasted agent token instead
32
+ logout end the session and delete the stored tokens
33
+ whoami account, org and role for the stored token
34
+ status show config and the project for the current directory
35
+ doctor [--json] check login, repo, connected harnesses, last capture, spool;
36
+ exits 1 when something is wrong
37
+ org org, members and key ids
38
+ org invite <email> [--owner] invite by email (owner only); accepted at their next login
39
+ org invites pending invites (owner only)
40
+ org remove <user-id> remove a member and revoke their sessions (owner only)
41
+ org sessions logged-in agents (own; all for owners)
42
+ org revoke <session-id> revoke a session
43
+ org rotate-key [--revoke-sessions] rotate the org signing key (owner only)
44
+ org projects projects recorded for the org
45
+ connect [--json] list the harnesses on this machine and whether each is connected
46
+ connect <harness> [--project <dir>] [--remove]
47
+ install (or remove) the hooks and checkpoint skill for one harness
48
+ in your user config, so every repo is covered; --project <dir>
49
+ writes into that repo instead. Harnesses and their files:
50
+ claude-code ~/.claude/settings.json + ~/.claude/skills/meshpoint
51
+ (--project: <dir>/.claude/)
52
+ codex ~/.codex/{hooks.json,rules/meshpoint.rules} + ~/.agents/skills/meshpoint
53
+ (--project: <dir>/.codex, <dir>/.agents)
54
+ cursor ~/.cursor/{hooks.json,skills/meshpoint} (--project: <dir>/.cursor)
55
+ antigravity ~/.gemini/config/{hooks.json,skills/meshpoint}
56
+ (--project: <dir>/.agents)
57
+ pi [--pi-dir <dir>] <dir>/extensions/meshpoint.js + <dir>/skills/meshpoint
58
+ (default dir: $PI_CODING_AGENT_DIR or ~/.pi/agent)
59
+ opencode [--config-dir <dir>] <dir>/plugins/meshpoint.js + <dir>/skills/meshpoint
60
+ (default dir: ~/.config/opencode)
61
+ openclaw hook pack installed through 'openclaw plugins install'
62
+ items put --item <kind> <title> <body> [--item ...]
63
+ items put --file <path> | items put < items.json
64
+ write items for the current repo and branch; the file or
65
+ stdin form takes a JSON array of {kind, title, body}
66
+ items retract <id>... retract items on the current branch; an id may be a prefix
67
+ tap claude-code | codex | cursor | antigravity [<event>] | openclaw
68
+ hook entry point; reads one hook payload on stdin
69
+ `;
70
+ const TAP_HARNESSES = new Set(["claude-code", "codex", "cursor", "antigravity", "openclaw"]);
71
+ function flag(args, name) {
72
+ const i = args.indexOf(name);
73
+ return i >= 0 ? args[i + 1] : undefined;
74
+ }
75
+ const DEFAULT_BASE_URL = "https://api.meshpoint.dev";
76
+ async function requireConfig() {
77
+ const config = loadConfig();
78
+ if (!config)
79
+ throw new Error(`not logged in; run meshpoint login (${configPath()})`);
80
+ return freshConfig(config);
81
+ }
82
+ // A 401 on a stored session token means the org key rotated or the token was revoked early:
83
+ // refresh once and retry before giving up.
84
+ async function withAuth(config, fn) {
85
+ try {
86
+ return await fn(config);
87
+ }
88
+ catch (err) {
89
+ const status = err instanceof ApiError || err instanceof MeshpointError ? err.status : 0;
90
+ if (status !== 401 || !config.refresh)
91
+ throw err;
92
+ return fn(await freshConfig(config, { force: true }));
93
+ }
94
+ }
95
+ async function orgCommand(args, config) {
96
+ const call = (method, path, body) => api(config.baseUrl, method, path, { token: config.token, ...(body === undefined ? {} : { body }) });
97
+ switch (args[0]) {
98
+ case undefined:
99
+ return call("GET", "/v1/org");
100
+ case "invite": {
101
+ if (!args[1])
102
+ throw new Error("org invite needs an email");
103
+ return call("POST", "/v1/org/invites", { email: args[1], role: args.includes("--owner") ? "owner" : "member" });
104
+ }
105
+ case "invites":
106
+ return call("GET", "/v1/org/invites");
107
+ case "remove": {
108
+ if (!args[1])
109
+ throw new Error("org remove needs a user id");
110
+ return call("DELETE", `/v1/org/members/${encodeURIComponent(args[1])}`);
111
+ }
112
+ case "sessions":
113
+ return call("GET", "/v1/org/sessions");
114
+ case "revoke": {
115
+ if (!args[1])
116
+ throw new Error("org revoke needs a session id");
117
+ return call("POST", "/v1/org/sessions/revoke", { id: args[1] });
118
+ }
119
+ case "rotate-key":
120
+ return call("POST", "/v1/org/keys/rotate", { revoke_sessions: args.includes("--revoke-sessions") });
121
+ case "projects":
122
+ return call("GET", "/v1/org/projects");
123
+ default:
124
+ throw new Error("org supports: invite, invites, remove, sessions, revoke, rotate-key, projects");
125
+ }
126
+ }
127
+ async function readStdin() {
128
+ const chunks = [];
129
+ for await (const chunk of process.stdin)
130
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
131
+ return Buffer.concat(chunks).toString("utf8");
132
+ }
133
+ async function main(argv) {
134
+ const [cmd, ...rest] = argv;
135
+ switch (cmd) {
136
+ case "login": {
137
+ const baseUrl = flag(rest, "--base-url") ?? DEFAULT_BASE_URL;
138
+ const token = flag(rest, "--token");
139
+ if (token) {
140
+ console.log(`saved ${saveConfig({ baseUrl, token })}`);
141
+ return 0;
142
+ }
143
+ const agent = flag(rest, "--agent");
144
+ const org = flag(rest, "--org");
145
+ const useDevice = rest.includes("--device") || (!rest.includes("--browser") && !canOpenBrowser());
146
+ const config = useDevice
147
+ ? await deviceLogin({ baseUrl, ...(agent ? { agent } : {}), log: (line) => console.log(line) })
148
+ : await login({ baseUrl, ...(agent ? { agent } : {}), ...(org ? { org } : {}), log: (line) => console.error(line) });
149
+ console.log(`logged in as ${config.email} (org ${config.orgName}); saved ${saveConfig(config)}`);
150
+ return 0;
151
+ }
152
+ case "logout": {
153
+ const config = loadConfig();
154
+ if (config?.refresh)
155
+ await api(config.baseUrl, "POST", "/v1/auth/logout", { body: { refresh: config.refresh } }).catch(() => undefined);
156
+ deleteConfig();
157
+ console.log(`removed ${configPath()}`);
158
+ return 0;
159
+ }
160
+ case "whoami": {
161
+ const config = await requireConfig();
162
+ console.log(JSON.stringify(await withAuth(config, (c) => api(c.baseUrl, "GET", "/v1/me", { token: c.token })), null, 2));
163
+ return 0;
164
+ }
165
+ case "org": {
166
+ const config = await requireConfig();
167
+ console.log(JSON.stringify(await withAuth(config, (c) => orgCommand(rest, c)), null, 2));
168
+ return 0;
169
+ }
170
+ case "status": {
171
+ const config = loadConfig();
172
+ const repo = repoContext(process.cwd());
173
+ console.log(JSON.stringify({ config: config ? { baseUrl: config.baseUrl, token: "set" } : null, repo }, null, 2));
174
+ return 0;
175
+ }
176
+ case "doctor": {
177
+ const report = await runDoctor();
178
+ console.log(rest.includes("--json") ? JSON.stringify(report, null, 2) : renderDoctor(report));
179
+ return report.ok ? 0 : 1;
180
+ }
181
+ case "connect": {
182
+ if (rest[0] === undefined || rest[0] === "--json") {
183
+ const rows = detectHarnesses();
184
+ console.log(rest.includes("--json") ? JSON.stringify(rows, null, 2) : renderDetected(rows));
185
+ return 0;
186
+ }
187
+ const project = flag(rest, "--project");
188
+ if (project !== undefined && !path.isAbsolute(project))
189
+ throw new Error("--project must be an absolute path");
190
+ const piDir = flag(rest, "--pi-dir");
191
+ if (piDir !== undefined && !path.isAbsolute(piDir))
192
+ throw new Error("--pi-dir must be an absolute path");
193
+ const configDir = flag(rest, "--config-dir");
194
+ if (configDir !== undefined && !path.isAbsolute(configDir))
195
+ throw new Error("--config-dir must be an absolute path");
196
+ const remove = rest.includes("--remove");
197
+ const inProject = project ? { projectDir: project } : {};
198
+ if (rest[0] === "claude-code")
199
+ console.log(connectClaudeCode({ remove, ...(project ? { configDir: path.join(project, ".claude") } : {}) }));
200
+ else if (rest[0] === "codex")
201
+ console.log(connectCodex({ remove, ...inProject }));
202
+ else if (rest[0] === "cursor")
203
+ console.log(connectCursor({ remove, ...inProject }));
204
+ else if (rest[0] === "antigravity")
205
+ console.log(connectAntigravity({ remove, ...inProject }));
206
+ else if (rest[0] === "pi")
207
+ console.log(connectPi({ remove, ...(piDir ? { piDir } : {}) }));
208
+ else if (rest[0] === "openclaw")
209
+ console.log(connectOpenclaw({ remove }));
210
+ else if (rest[0] === "opencode")
211
+ console.log(connectOpencode({ remove, ...(configDir ? { configDir } : {}) }));
212
+ else
213
+ throw new Error("connect supports: claude-code, codex, cursor, antigravity, pi, opencode, openclaw");
214
+ return 0;
215
+ }
216
+ case "items": {
217
+ if (rest[0] !== "put" && rest[0] !== "retract")
218
+ throw new Error("items supports: put, retract");
219
+ const config = await requireConfig();
220
+ const repo = repoContext(process.cwd());
221
+ if (!repo)
222
+ throw new Error("not inside a git repo with an origin remote");
223
+ if (rest[0] === "retract") {
224
+ console.log(JSON.stringify(await withAuth(config, (c) => retractItems(rest.slice(1), { config: c, repo }))));
225
+ return 0;
226
+ }
227
+ const file = flag(rest, "--file");
228
+ const drafts = rest.includes("--item") ? parseItemArgs(rest.slice(1)) : parseItems(file ? readFileSync(file, "utf8") : await readStdin());
229
+ const out = await withAuth(config, (c) => putItems(drafts, { config: c, repo, checkpoints: new Checkpoints(stateDir()) }));
230
+ console.log(JSON.stringify({ ...out, project: repo.project, branch: repo.branch }));
231
+ return 0;
232
+ }
233
+ case "tap": {
234
+ const harness = rest[0];
235
+ if (!TAP_HARNESSES.has(harness ?? ""))
236
+ throw new Error(`tap supports: ${[...TAP_HARNESSES].join(", ")}`);
237
+ const stored = loadConfig();
238
+ // A failed refresh keeps the stored token: the hook must never break the harness.
239
+ const config = stored ? await freshConfig(stored).catch(() => stored) : null;
240
+ const raw = await readStdin();
241
+ const parse = () => {
242
+ try {
243
+ return JSON.parse(raw);
244
+ }
245
+ catch {
246
+ return {};
247
+ }
248
+ };
249
+ const hookDeps = (c) => ({
250
+ config: c,
251
+ refresh: () => freshConfig(c, { force: true }).catch(() => null),
252
+ repo: repoContext,
253
+ readTranscript: (file) => readFileSync(file, "utf8"),
254
+ spool: new Spool(spoolDir()),
255
+ checkpoints: new Checkpoints(stateDir()),
256
+ });
257
+ // Each harness has its own "do nothing" answer, needed even without a login.
258
+ if (harness === "cursor") {
259
+ const payload = parse();
260
+ if (!config)
261
+ process.stdout.write(payload.hook_event_name === "beforeSubmitPrompt" ? '{"continue":true}' : "{}");
262
+ else
263
+ process.stdout.write(await runCursorTap(payload, hookDeps(config)));
264
+ return 0;
265
+ }
266
+ if (harness === "antigravity") {
267
+ // Antigravity payloads carry no event name; the installed command passes it as an argument.
268
+ let payload = parse();
269
+ if (rest[1])
270
+ payload = { ...payload, hookEventName: rest[1] };
271
+ if (!config)
272
+ process.stdout.write(payload.hookEventName === "Stop" ? '{"decision":"stop"}' : "{}");
273
+ else
274
+ process.stdout.write(await runAntigravityTap(payload, { ...hookDeps(config), stateDir: stateDir() }));
275
+ return 0;
276
+ }
277
+ if (harness === "openclaw") {
278
+ if (!config)
279
+ process.stdout.write("{}");
280
+ else {
281
+ const { readTranscript: _unused, ...deps } = hookDeps(config);
282
+ process.stdout.write(await runOpenclawTap(parse(), { ...deps, env: process.env, replies: new ReplyLog(stateDir()) }));
283
+ }
284
+ return 0;
285
+ }
286
+ const payload = parse();
287
+ if (!config) {
288
+ process.stdout.write(payload.hook_event_name === "Stop" ? '{"decision":"continue"}' : "{}");
289
+ return 0;
290
+ }
291
+ process.stdout.write(await runClaudeCodeTap(payload, { ...hookDeps(config), ...(harness === "codex" ? { parseTranscript: parseCodexTranscript } : {}) }));
292
+ return 0;
293
+ }
294
+ default:
295
+ process.stdout.write(USAGE);
296
+ return cmd === undefined || cmd === "--help" || cmd === "-h" ? 0 : 2;
297
+ }
298
+ }
299
+ main(process.argv.slice(2)).then((code) => {
300
+ process.exitCode = code;
301
+ }, (err) => {
302
+ // The tap is the non-fatal boundary: a hook must never break the harness.
303
+ if (process.argv[2] === "tap") {
304
+ process.stdout.write("{}");
305
+ process.exitCode = 0;
306
+ return;
307
+ }
308
+ console.error(err instanceof Error ? err.message : String(err));
309
+ process.exitCode = 1;
310
+ });
@@ -0,0 +1,58 @@
1
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ // A checkpoint is the agent writing items for a project branch. Its time is recorded here so the
4
+ // Stop hook can tell how much of the session has gone unrecorded. Nudges are recorded per harness
5
+ // session so an ignored nudge is not repeated on every Stop.
6
+ export const CHECKPOINT_TURNS = 20;
7
+ export const CHECKPOINT_CHARS = 60_000;
8
+ function safe(name) {
9
+ return name.replace(/[^A-Za-z0-9._-]/g, "_");
10
+ }
11
+ export class Checkpoints {
12
+ dir;
13
+ constructor(dir) {
14
+ this.dir = dir;
15
+ }
16
+ file(kind, name) {
17
+ return path.join(this.dir, kind, `${safe(name)}.json`);
18
+ }
19
+ readAt(file) {
20
+ try {
21
+ const v = JSON.parse(readFileSync(file, "utf8")).at;
22
+ return typeof v === "number" ? v : 0;
23
+ }
24
+ catch {
25
+ return 0;
26
+ }
27
+ }
28
+ writeAt(file, at) {
29
+ mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
30
+ writeFileSync(file, `${JSON.stringify({ at })}\n`, { mode: 0o600 });
31
+ }
32
+ lastCheckpoint(project, branch) {
33
+ return this.readAt(this.file("checkpoints", `${project}--${branch}`));
34
+ }
35
+ markCheckpoint(project, branch, at) {
36
+ this.writeAt(this.file("checkpoints", `${project}--${branch}`), at);
37
+ }
38
+ lastNudge(session) {
39
+ return this.readAt(this.file("nudges", session));
40
+ }
41
+ markNudge(session, at) {
42
+ this.writeAt(this.file("nudges", session), at);
43
+ }
44
+ // Due when the assistant has produced enough since the later of the last checkpoint and the
45
+ // last nudge: CHECKPOINT_TURNS replies or CHECKPOINT_CHARS of text.
46
+ due(session, project, branch, entries) {
47
+ const since = Math.max(this.lastCheckpoint(project, branch), this.lastNudge(session));
48
+ let turns = 0;
49
+ let chars = 0;
50
+ for (const e of entries) {
51
+ if (e.role !== "assistant" || e.at <= since)
52
+ continue;
53
+ turns += 1;
54
+ chars += e.text.length;
55
+ }
56
+ return turns >= CHECKPOINT_TURNS || chars >= CHECKPOINT_CHARS ? { turns, chars } : null;
57
+ }
58
+ }
@@ -0,0 +1,35 @@
1
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import path from "node:path";
4
+ import { installTapHooks, removeTapHooks } from "./settings.js";
5
+ import { SKILL_MD, SKILL_NAME } from "./skill.js";
6
+ export function claudeConfigDir(env = process.env, home = homedir()) {
7
+ return env.CLAUDE_CONFIG_DIR || path.join(home, ".claude");
8
+ }
9
+ // Installs or removes the managed hook entries in <config dir>/settings.json and the checkpoint
10
+ // skill in <config dir>/skills/.
11
+ export function connectClaudeCode(opts) {
12
+ const configDir = opts.configDir ?? claudeConfigDir();
13
+ const settingsPath = path.join(configDir, "settings.json");
14
+ const skillDir = path.join(configDir, "skills", SKILL_NAME);
15
+ let settings = {};
16
+ try {
17
+ settings = JSON.parse(readFileSync(settingsPath, "utf8"));
18
+ }
19
+ catch (err) {
20
+ if (err.code !== "ENOENT")
21
+ throw new Error(`could not read ${settingsPath}: ${err.message}`);
22
+ if (opts.remove)
23
+ return `no settings at ${settingsPath}; nothing to remove`;
24
+ }
25
+ const next = opts.remove ? removeTapHooks(settings) : installTapHooks(settings);
26
+ mkdirSync(configDir, { recursive: true });
27
+ writeFileSync(settingsPath, `${JSON.stringify(next, null, 2)}\n`);
28
+ if (opts.remove) {
29
+ rmSync(skillDir, { recursive: true, force: true });
30
+ return `removed meshpoint hooks from ${settingsPath} and ${skillDir}`;
31
+ }
32
+ mkdirSync(skillDir, { recursive: true });
33
+ writeFileSync(path.join(skillDir, "SKILL.md"), SKILL_MD);
34
+ return `installed meshpoint hooks in ${settingsPath} (SessionStart, UserPromptSubmit, Stop, PreCompact, SessionEnd) and ${skillDir}/SKILL.md`;
35
+ }
@@ -0,0 +1,45 @@
1
+ // Idempotent hook installation for Claude Code's settings.json. Every managed entry shells to the
2
+ // meshpoint tap, so re-running connect upgrades in place and never touches hooks the user wrote.
3
+ export const TAP_COMMAND = "meshpoint tap claude-code";
4
+ const HOOK_TIMEOUT_S = 30;
5
+ // SessionStart includes "compact": the items are what survives a context loss.
6
+ export const MANAGED_EVENTS = [
7
+ { event: "SessionStart", matcher: "startup|resume|clear|compact" },
8
+ { event: "UserPromptSubmit" },
9
+ { event: "Stop" },
10
+ { event: "PreCompact" },
11
+ { event: "SessionEnd" },
12
+ ];
13
+ const CLAUDE_CODE_SPEC = { command: TAP_COMMAND, events: MANAGED_EVENTS };
14
+ function isManaged(hook) {
15
+ return hook.command.startsWith("meshpoint tap ") || hook.command.startsWith("meshpoint-tap ");
16
+ }
17
+ function withoutManaged(groups) {
18
+ return (groups ?? [])
19
+ .map((group) => ({ ...group, hooks: group.hooks.filter((hook) => !isManaged(hook)) }))
20
+ .filter((group) => group.hooks.length > 0);
21
+ }
22
+ export function installTapHooks(settings, spec = CLAUDE_CODE_SPEC) {
23
+ const hooks = { ...settings.hooks };
24
+ for (const { event, matcher } of spec.events) {
25
+ hooks[event] = [
26
+ ...withoutManaged(hooks[event]),
27
+ { ...(matcher === undefined ? {} : { matcher }), hooks: [{ type: "command", command: spec.command, timeout: HOOK_TIMEOUT_S, ...spec.extra }] },
28
+ ];
29
+ }
30
+ return { ...settings, hooks };
31
+ }
32
+ export function removeTapHooks(settings) {
33
+ if (settings.hooks === undefined)
34
+ return settings;
35
+ const hooks = {};
36
+ for (const [event, groups] of Object.entries(settings.hooks)) {
37
+ const kept = withoutManaged(groups);
38
+ if (kept.length > 0)
39
+ hooks[event] = kept;
40
+ }
41
+ const next = { ...settings, hooks };
42
+ if (Object.keys(hooks).length === 0)
43
+ delete next.hooks;
44
+ return next;
45
+ }
@@ -0,0 +1,56 @@
1
+ // The checkpoint skill: the agent distills its own session into items. Installed next to the hooks
2
+ // so the Stop hook can ask for it by name.
3
+ export const SKILL_NAME = "meshpoint";
4
+ // Claude Code pre-approves the two commands through the skill; Codex does it with a rules file.
5
+ export function skillMarkdown(opts) {
6
+ return `---
7
+ name: ${SKILL_NAME}
8
+ description: Record what this session learned as Meshpoint team knowledge items. Use when a Meshpoint checkpoint is due, before ending a long session, or after a decision worth keeping.
9
+ ${opts.allowedTools ? "allowed-tools: Bash(meshpoint items put:*), Bash(meshpoint items retract:*)\n" : ""}---
10
+ ${SKILL_BODY}`;
11
+ }
12
+ const SKILL_BODY = `
13
+ # Meshpoint
14
+
15
+ Write the knowledge a teammate's agent would need to resume this work correctly, as items.
16
+
17
+ ## Items
18
+
19
+ Each item is an object \`{"kind", "title", "body"}\`. \`kind\` is one of:
20
+
21
+ - \`decision\`: a choice made and why
22
+ - \`gotcha\`: something that bit or will bite
23
+ - \`convention\`: how things are done here
24
+ - \`fact\`: a stable truth about the code or environment
25
+ - \`status\`: where the work stands
26
+ - \`todo\`: an agreed next step
27
+
28
+ \`title\` is one line. \`body\` is one to three sentences, concrete: file names, commands, values, reasons.
29
+
30
+ ## Rules
31
+
32
+ - Only what this session established. Never invent.
33
+ - Skip anything already listed under "Team knowledge" in the session-start context unless it changed; a changed decision or status gets a new item.
34
+ - Retract items that this session made wrong or obsolete: a finished todo, a superseded status, a reversed decision. The first column of "Team knowledge" is the item id.
35
+ - Prefer durable knowledge over moment-to-moment detail. Aim for 5 to 30 items; one \`status\` item at most.
36
+ - No secrets, tokens, or credentials.
37
+
38
+ ## Procedure
39
+
40
+ Run \`meshpoint items put\` once, one \`--item kind title body\` per item. Single-quote title and body and keep the single quote character out of them (write "do not", not "don't"). No JSON, no heredoc.
41
+
42
+ \`\`\`bash
43
+ meshpoint items put \\
44
+ --item decision 'Short title' 'What was chosen and why, with file names and values.' \\
45
+ --item gotcha 'Short title' 'What bit and how to avoid it.'
46
+ \`\`\`
47
+
48
+ Retract by id, several at once:
49
+
50
+ \`\`\`bash
51
+ meshpoint items retract 3f9c1a2b 7d0e44aa
52
+ \`\`\`
53
+
54
+ Then continue the work you were doing.
55
+ `;
56
+ export const SKILL_MD = skillMarkdown({ allowedTools: true });
@@ -0,0 +1,58 @@
1
+ import { Tap } from "../tap.js";
2
+ import { lastAssistantTurn, parseTranscript as parseClaudeCodeTranscript } from "./transcript.js";
3
+ export { renderInject } from "../tap.js";
4
+ // One hook event in, one JSON answer out. Claude Code and Codex share the hook protocol (event
5
+ // names, payload fields, additionalContext, Stop block), so one wrapper serves both. The Tap
6
+ // swallows mesh failures; this layer only speaks the hook protocol.
7
+ export async function runClaudeCodeTap(payload, deps) {
8
+ const event = payload.hook_event_name ?? "";
9
+ const empty = event === "Stop" ? '{"decision":"continue"}' : "{}";
10
+ const repo = deps.repo(payload.cwd ?? process.cwd());
11
+ if (!repo)
12
+ return empty;
13
+ const tap = new Tap({
14
+ config: deps.config,
15
+ repo,
16
+ session: payload.session_id ?? "unknown",
17
+ spool: deps.spool,
18
+ checkpoints: deps.checkpoints,
19
+ ...(deps.now ? { now: deps.now } : {}),
20
+ ...(deps.fetch ? { fetch: deps.fetch } : {}),
21
+ ...(deps.presenceWaitMs !== undefined ? { presenceWaitMs: deps.presenceWaitMs } : {}),
22
+ ...(deps.refresh ? { refresh: deps.refresh } : {}),
23
+ });
24
+ const transcript = () => {
25
+ if (!payload.transcript_path)
26
+ return [];
27
+ try {
28
+ return (deps.parseTranscript ?? parseClaudeCodeTranscript)(deps.readTranscript(payload.transcript_path));
29
+ }
30
+ catch {
31
+ return [];
32
+ }
33
+ };
34
+ switch (event) {
35
+ case "SessionStart": {
36
+ const text = await tap.start();
37
+ return text ? JSON.stringify({ hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: text } }) : "{}";
38
+ }
39
+ case "UserPromptSubmit":
40
+ await tap.user(payload.prompt ?? "");
41
+ return "{}";
42
+ case "Stop": {
43
+ const entries = transcript();
44
+ const turn = lastAssistantTurn(entries);
45
+ await tap.assistant(turn?.text ?? "", turn?.paths ?? []);
46
+ // A due checkpoint keeps the turn going so the agent writes its items now. stop_hook_active
47
+ // means this Stop is already a continuation; never nudge twice in a row.
48
+ const reason = payload.stop_hook_active ? null : tap.nudge(entries);
49
+ return reason ? JSON.stringify({ decision: "block", reason }) : '{"decision":"continue"}';
50
+ }
51
+ case "PreCompact":
52
+ case "SessionEnd":
53
+ await tap.end();
54
+ return "{}";
55
+ default:
56
+ return empty;
57
+ }
58
+ }
@@ -0,0 +1,75 @@
1
+ // Reads what matters out of a Claude Code transcript (JSONL): user and assistant text, and the
2
+ // files the assistant touched through tools. Pure functions over the file contents.
3
+ const PATH_KEYS = ["file_path", "path", "notebook_path"];
4
+ function isRecord(v) {
5
+ return typeof v === "object" && v !== null && !Array.isArray(v);
6
+ }
7
+ export function parseTranscript(jsonl) {
8
+ const entries = [];
9
+ for (const line of jsonl.split("\n")) {
10
+ if (!line.trim())
11
+ continue;
12
+ let parsed;
13
+ try {
14
+ parsed = JSON.parse(line);
15
+ }
16
+ catch {
17
+ continue;
18
+ }
19
+ if (!isRecord(parsed) || (parsed.type !== "user" && parsed.type !== "assistant"))
20
+ continue;
21
+ const message = isRecord(parsed.message) ? parsed.message : undefined;
22
+ const content = message?.content;
23
+ const texts = [];
24
+ const paths = [];
25
+ if (typeof content === "string")
26
+ texts.push(content);
27
+ else if (Array.isArray(content)) {
28
+ for (const block of content) {
29
+ if (!isRecord(block))
30
+ continue;
31
+ if (block.type === "text" && typeof block.text === "string")
32
+ texts.push(block.text);
33
+ if (block.type === "tool_use" && isRecord(block.input)) {
34
+ for (const key of PATH_KEYS) {
35
+ const v = block.input[key];
36
+ if (typeof v === "string" && v)
37
+ paths.push(v);
38
+ }
39
+ }
40
+ }
41
+ }
42
+ const text = texts.join("\n").trim();
43
+ if (!text && paths.length === 0)
44
+ continue;
45
+ // Tool results arrive as "user" records with no prose; skip those so turns stay human.
46
+ if (parsed.type === "user" && !text)
47
+ continue;
48
+ const at = typeof parsed.timestamp === "string" ? Date.parse(parsed.timestamp) || 0 : 0;
49
+ entries.push({ role: parsed.type, text, paths, at });
50
+ }
51
+ return entries;
52
+ }
53
+ // The assistant's whole reply to the latest prompt: every assistant record after the last user
54
+ // record, text joined, touched paths deduplicated in order.
55
+ export function lastAssistantTurn(entries) {
56
+ let start = entries.length;
57
+ while (start > 0 && entries[start - 1]?.role === "assistant")
58
+ start -= 1;
59
+ const reply = entries.slice(start);
60
+ if (reply.length === 0)
61
+ return null;
62
+ const texts = reply.map((e) => e.text).filter(Boolean);
63
+ const paths = [...new Set(reply.flatMap((e) => e.paths))];
64
+ if (texts.length === 0 && paths.length === 0)
65
+ return null;
66
+ return { text: texts.join("\n\n"), paths };
67
+ }
68
+ export function lastUserText(entries) {
69
+ for (let i = entries.length - 1; i >= 0; i -= 1) {
70
+ const e = entries[i];
71
+ if (e?.role === "user" && e.text)
72
+ return e.text;
73
+ }
74
+ return null;
75
+ }