@meshpoint/cli 1.0.0-rc.4 → 1.1.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.
@@ -0,0 +1,125 @@
1
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ // Per-session state for the edit hook: the branch's items as seen at session start (with the
4
+ // local verdicts) and the files already noticed, so one file gets one notice per session.
5
+ export const EDIT_ITEMS_MAX = 2;
6
+ export const EDIT_KINDS = new Set(["gotcha", "decision", "convention"]);
7
+ function safe(name) {
8
+ return name.replace(/[^A-Za-z0-9._-]/g, "_");
9
+ }
10
+ export class SessionCache {
11
+ dir;
12
+ constructor(dir) {
13
+ this.dir = dir;
14
+ }
15
+ recallFile(session) {
16
+ return path.join(this.dir, "recall", `${safe(session)}.json`);
17
+ }
18
+ editsFile(session) {
19
+ return path.join(this.dir, "edits", `${safe(session)}.json`);
20
+ }
21
+ write(file, value) {
22
+ mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
23
+ writeFileSync(file, `${JSON.stringify(value)}\n`, { mode: 0o600 });
24
+ }
25
+ saveRecall(session, cached) {
26
+ this.write(this.recallFile(session), cached);
27
+ }
28
+ loadRecall(session) {
29
+ try {
30
+ const parsed = JSON.parse(readFileSync(this.recallFile(session), "utf8"));
31
+ return Array.isArray(parsed.items) ? parsed : null;
32
+ }
33
+ catch {
34
+ return null;
35
+ }
36
+ }
37
+ // True the first time a file is seen in the session; false afterwards.
38
+ firstEdit(session, filePath) {
39
+ const file = this.editsFile(session);
40
+ let seen = [];
41
+ try {
42
+ seen = JSON.parse(readFileSync(file, "utf8"));
43
+ }
44
+ catch {
45
+ seen = [];
46
+ }
47
+ if (seen.includes(filePath))
48
+ return false;
49
+ this.write(file, [...seen, filePath]);
50
+ return true;
51
+ }
52
+ forget(session) {
53
+ rmSync(this.recallFile(session), { force: true });
54
+ rmSync(this.editsFile(session), { force: true });
55
+ }
56
+ // The import nudge shows once per project branch on this machine. True the first time.
57
+ firstImportNudge(project, branch) {
58
+ const file = path.join(this.dir, "import", `${safe(`${project}--${branch}`)}`);
59
+ try {
60
+ readFileSync(file);
61
+ return false;
62
+ }
63
+ catch {
64
+ this.write(file, { at: Date.now() });
65
+ return true;
66
+ }
67
+ }
68
+ }
69
+ // Items worth showing when a file is edited: those naming it, of the kinds that bite, not dropped
70
+ // locally stale, ranked the way recall ranks them (kind weight, then recency, then confirmations).
71
+ const KIND_WEIGHT = { decision: 5, gotcha: 4, convention: 3, fact: 2, status: 2, todo: 1 };
72
+ export function itemsForFile(items, verdicts, filePath) {
73
+ return items
74
+ .filter((i) => !i.retracted && i.state !== "dropped" && EDIT_KINDS.has(i.kind) && verdicts[i.id] !== "stale")
75
+ .filter((i) => i.refs.includes(filePath) || i.paths.includes(filePath))
76
+ .sort((a, b) => (KIND_WEIGHT[b.kind] ?? 0) - (KIND_WEIGHT[a.kind] ?? 0) || b.created_at - a.created_at || b.confirmations - a.confirmations)
77
+ .slice(0, EDIT_ITEMS_MAX);
78
+ }
79
+ function age(ms) {
80
+ const m = Math.floor(ms / 60_000);
81
+ return m < 1 ? "just now" : `${m}m ago`;
82
+ }
83
+ // The notice injected around an edit, or "" when there is nothing to say.
84
+ export function renderEditNotice(filePath, items, presence, now) {
85
+ if (items.length === 0 && presence.length === 0)
86
+ return "";
87
+ const lines = [`Meshpoint, ${filePath}:`];
88
+ for (const p of presence)
89
+ lines.push(`- ${p.user}'s ${p.agent} edited this file ${age(now - p.updated_at)} on ${p.branch}.`);
90
+ for (const i of items)
91
+ lines.push(`- [${i.kind}] ${i.title}: ${i.body}`);
92
+ return lines.join("\n");
93
+ }
94
+ // Committed instruction files that can seed a branch with no memory yet. Only tracked files
95
+ // count, so a stray local note never triggers the import nudge.
96
+ export const INSTRUCTION_FILE_PATTERNS = [
97
+ "CLAUDE.md",
98
+ "AGENTS.md",
99
+ "GEMINI.md",
100
+ ".cursorrules",
101
+ ".claude/CLAUDE.md",
102
+ ".claude/rules/*.md",
103
+ ".cursor/rules/*",
104
+ ".codex/AGENTS.md",
105
+ ".github/copilot-instructions.md",
106
+ ".kiro/steering/*.md",
107
+ ".junie/guidelines.md",
108
+ ];
109
+ export function instructionFiles(git) {
110
+ const out = git(["ls-files", "--", ...INSTRUCTION_FILE_PATTERNS]);
111
+ if (!out)
112
+ return [];
113
+ return out
114
+ .split("\n")
115
+ .map((l) => l.trim())
116
+ .filter(Boolean)
117
+ .slice(0, 20);
118
+ }
119
+ export function renderImportNudge(files) {
120
+ return [
121
+ "This branch has no team knowledge yet.",
122
+ `Instruction files found: ${files.join(", ")}.`,
123
+ "Run the meshpoint-import skill once to seed items from them, then continue.",
124
+ ].join("\n");
125
+ }
@@ -1,11 +1,12 @@
1
1
  import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import path from "node:path";
4
- import { skillMarkdown, SKILL_NAME } from "../claude-code/skill.js";
4
+ import { IMPORT_SKILL_NAME, importSkillMarkdown, skillMarkdown, SKILL_NAME } from "../claude-code/skill.js";
5
5
  export const CURSOR_TAP_COMMAND = "meshpoint tap cursor";
6
6
  const HOOK_TIMEOUT_S = 30;
7
- // afterAgentResponse carries the reply text; stop only decides on the checkpoint nudge.
8
- export const CURSOR_EVENTS = ["sessionStart", "beforeSubmitPrompt", "afterAgentResponse", "stop", "preCompact", "sessionEnd"];
7
+ // afterAgentResponse carries the reply text; stop only decides on the checkpoint nudge;
8
+ // postToolUse is where a file notice can reach the agent (additional_context).
9
+ export const CURSOR_EVENTS = ["sessionStart", "beforeSubmitPrompt", "postToolUse", "afterAgentResponse", "stop", "preCompact", "sessionEnd"];
9
10
  function isManaged(hook) {
10
11
  return typeof hook.command === "string" && (hook.command.startsWith("meshpoint tap ") || hook.command.startsWith("meshpoint-tap "));
11
12
  }
@@ -53,6 +54,7 @@ export function connectCursor(opts) {
53
54
  else
54
55
  rmSync(paths.hooks, { force: true });
55
56
  rmSync(paths.skillDir, { recursive: true, force: true });
57
+ rmSync(path.join(path.dirname(paths.skillDir), IMPORT_SKILL_NAME), { recursive: true, force: true });
56
58
  return `removed meshpoint hooks from ${paths.hooks} and ${paths.skillDir}`;
57
59
  }
58
60
  mkdirSync(path.dirname(paths.hooks), { recursive: true });
@@ -60,5 +62,8 @@ export function connectCursor(opts) {
60
62
  mkdirSync(paths.skillDir, { recursive: true });
61
63
  // Cursor's SKILL.md frontmatter takes name and description; allowed-tools is Claude Code only.
62
64
  writeFileSync(path.join(paths.skillDir, "SKILL.md"), skillMarkdown({ allowedTools: false }));
65
+ const importDir = path.join(path.dirname(paths.skillDir), IMPORT_SKILL_NAME);
66
+ mkdirSync(importDir, { recursive: true });
67
+ writeFileSync(path.join(importDir, "SKILL.md"), importSkillMarkdown({ allowedTools: false }));
63
68
  return `installed meshpoint hooks in ${paths.hooks} (${CURSOR_EVENTS.join(", ")}) and ${paths.skillDir}/SKILL.md. Cursor reloads hooks.json on save; the Hooks tab under Customize lists them.`;
64
69
  }
@@ -1,3 +1,4 @@
1
+ import { toolFilePaths } from "../claude-code/tap.js";
1
2
  import { lastAssistantTurn } from "../claude-code/transcript.js";
2
3
  import { NUDGE_PREFIX, Tap } from "../tap.js";
3
4
  import { parseCursorTranscript } from "./transcript.js";
@@ -22,6 +23,9 @@ export async function runCursorTap(payload, deps) {
22
23
  ...(deps.fetch ? { fetch: deps.fetch } : {}),
23
24
  ...(deps.presenceWaitMs !== undefined ? { presenceWaitMs: deps.presenceWaitMs } : {}),
24
25
  ...(deps.refresh ? { refresh: deps.refresh } : {}),
26
+ ...(deps.touched ? { touched: deps.touched } : {}),
27
+ ...(deps.cache ? { cache: deps.cache } : {}),
28
+ ...(deps.local ? { local: deps.local(repo.root) } : {}),
25
29
  });
26
30
  const transcript = () => {
27
31
  if (!payload.transcript_path)
@@ -44,6 +48,17 @@ export async function runCursorTap(payload, deps) {
44
48
  await tap.user(prompt.startsWith(NUDGE_PREFIX) ? "" : prompt);
45
49
  return CONTINUE;
46
50
  }
51
+ case "postToolUse": {
52
+ // After a file edit: the only Cursor event around a tool call that takes additional_context.
53
+ const files = payload.file_path ? [payload.file_path] : toolFilePaths(payload.tool_input);
54
+ const notices = [];
55
+ for (const file of files) {
56
+ const text = await tap.edit(file);
57
+ if (text)
58
+ notices.push(text);
59
+ }
60
+ return notices.length > 0 ? JSON.stringify({ additional_context: notices.join("\n\n") }) : "{}";
61
+ }
47
62
  case "afterAgentResponse": {
48
63
  // The documented text field is the reply; the transcript, when readable, adds the touched paths.
49
64
  await tap.assistant(payload.text ?? "", lastAssistantTurn(transcript())?.paths ?? []);
package/dist/items.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { KINDS, MeshpointClient } from "@meshpoint/sdk";
3
+ import { extractRefs, headSha } from "./refs.js";
3
4
  export const ITEMS_MAX = 60;
4
5
  export const ID_PREFIX_CHARS = 8;
5
6
  const ALL_ITEMS_BUDGET = 100_000;
@@ -60,21 +61,32 @@ function clientFor(deps) {
60
61
  ...(deps.fetch ? { fetch: deps.fetch } : {}),
61
62
  });
62
63
  }
64
+ // Each item gets its refs (paths named in its text that exist in the checkout), the paths edited
65
+ // since the branch's last checkpoint, and HEAD. Path-like tokens that resolve to nothing come
66
+ // back as `missing` so the writer can fix a typo.
63
67
  export async function putItems(drafts, deps) {
64
68
  const now = deps.now ?? Date.now;
65
- const items = drafts.map((d) => ({ id: randomUUID(), ...d }));
69
+ const { project, branch, root } = deps.repo;
70
+ const since = deps.checkpoints.lastCheckpoint(project, branch);
71
+ const paths = deps.touched?.since(project, branch, since) ?? [];
72
+ const commit_sha = (deps.sha ?? headSha)(root);
73
+ const missing = new Set();
74
+ const items = drafts.map((d) => {
75
+ const found = extractRefs(`${d.title}\n${d.body}`, root, deps.exists);
76
+ for (const m of found.missing)
77
+ missing.add(m);
78
+ return { id: randomUUID(), ...d, refs: found.refs, paths, ...(commit_sha ? { commit_sha } : {}) };
79
+ });
66
80
  const out = await clientFor(deps).putItems(items);
67
- deps.checkpoints.markCheckpoint(deps.repo.project, deps.repo.branch, now());
68
- return out;
81
+ deps.checkpoints.markCheckpoint(project, branch, now());
82
+ deps.touched?.clear(project, branch);
83
+ return { ...out, missing: [...missing] };
69
84
  }
70
- // The inject shows the first ID_PREFIX_CHARS of each id, so a retract takes a prefix and resolves it
71
- // against the branch's live items; an ambiguous or unknown prefix is an error, never a guess.
72
- export async function retractItems(prefixes, deps) {
73
- if (prefixes.length === 0)
74
- throw new Error("retract needs at least one item id");
75
- const client = clientFor(deps);
85
+ // Resolves inject-style id prefixes against the branch's live items; ambiguous or unknown is an
86
+ // error, never a guess.
87
+ async function resolveIds(prefixes, deps, client) {
76
88
  const { items } = await client.recall({ budget: ALL_ITEMS_BUDGET, fresh: true });
77
- const ids = prefixes.map((prefix) => {
89
+ return prefixes.map((prefix) => {
78
90
  const matches = items.filter((i) => i.id.startsWith(prefix)).map((i) => i.id);
79
91
  if (matches.length === 0)
80
92
  throw new Error(`no item on ${deps.repo.branch} starts with ${prefix}`);
@@ -82,8 +94,26 @@ export async function retractItems(prefixes, deps) {
82
94
  throw new Error(`${prefix} matches ${matches.length} items; give more characters`);
83
95
  return matches[0];
84
96
  });
97
+ }
98
+ export async function confirmItems(prefixes, deps) {
99
+ if (prefixes.length === 0)
100
+ throw new Error("confirm needs at least one item id");
101
+ const client = clientFor(deps);
102
+ const confirmed = [];
103
+ for (const id of await resolveIds(prefixes, deps, client)) {
104
+ if ((await client.confirm(id)).found)
105
+ confirmed.push(id);
106
+ }
107
+ return { confirmed };
108
+ }
109
+ // The inject shows the first ID_PREFIX_CHARS of each id, so a retract takes a prefix and resolves it
110
+ // against the branch's live items; an ambiguous or unknown prefix is an error, never a guess.
111
+ export async function retractItems(prefixes, deps) {
112
+ if (prefixes.length === 0)
113
+ throw new Error("retract needs at least one item id");
114
+ const client = clientFor(deps);
85
115
  const retracted = [];
86
- for (const id of ids) {
116
+ for (const id of await resolveIds(prefixes, deps, client)) {
87
117
  if ((await client.retract(id)).found)
88
118
  retracted.push(id);
89
119
  }
@@ -2,7 +2,7 @@ import { lstatSync, mkdirSync, rmSync, symlinkSync, writeFileSync } from "node:f
2
2
  import { homedir } from "node:os";
3
3
  import path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
- import { skillMarkdown, SKILL_NAME } from "../claude-code/skill.js";
5
+ import { IMPORT_SKILL_NAME, importSkillMarkdown, skillMarkdown, SKILL_NAME } from "../claude-code/skill.js";
6
6
  export function opencodeConfigDir(env = process.env, home = homedir()) {
7
7
  return path.join(env.XDG_CONFIG_HOME || path.join(home, ".config"), "opencode");
8
8
  }
@@ -28,6 +28,7 @@ export function connectOpencode(opts) {
28
28
  if (opts.remove) {
29
29
  rmSync(paths.plugin, { force: true });
30
30
  rmSync(paths.skillDir, { recursive: true, force: true });
31
+ rmSync(path.join(path.dirname(paths.skillDir), IMPORT_SKILL_NAME), { recursive: true, force: true });
31
32
  return `removed meshpoint plugin ${paths.plugin} and ${paths.skillDir}`;
32
33
  }
33
34
  const target = opts.pluginFile ?? PLUGIN_FILE;
@@ -36,5 +37,8 @@ export function connectOpencode(opts) {
36
37
  symlinkSync(target, paths.plugin);
37
38
  mkdirSync(paths.skillDir, { recursive: true });
38
39
  writeFileSync(path.join(paths.skillDir, "SKILL.md"), skillMarkdown({ allowedTools: false }));
40
+ const importDir = path.join(path.dirname(paths.skillDir), IMPORT_SKILL_NAME);
41
+ mkdirSync(importDir, { recursive: true });
42
+ writeFileSync(path.join(importDir, "SKILL.md"), importSkillMarkdown({ allowedTools: false }));
39
43
  return `installed meshpoint plugin ${paths.plugin} -> ${target} and ${paths.skillDir}/SKILL.md. Restart opencode to load it.`;
40
44
  }
@@ -159,13 +159,19 @@ export function createOpencodeHooks(deps) {
159
159
  }
160
160
  await enqueue(s, (tap) => tap.assistant(text, paths));
161
161
  },
162
- "tool.execute.after": async (input) => {
162
+ "tool.execute.after": async (input, output) => {
163
163
  const s = tracked(input.sessionID);
164
164
  if (!s || !WRITE_TOOLS.has(input.tool) || !isRecord(input.args))
165
165
  return;
166
166
  const file = input.args.filePath;
167
- if (typeof file === "string" && file)
168
- s.paths.push(file);
167
+ if (typeof file !== "string" || !file)
168
+ return;
169
+ s.paths.push(file);
170
+ // The file notice rides on the tool result, the one place opencode lets a plugin speak mid-run.
171
+ await s.opened;
172
+ const notice = s.tap ? await s.tap.edit(file).catch(() => "") : "";
173
+ if (notice && output && typeof output.output === "string")
174
+ output.output = `${output.output}\n\n${notice}`;
169
175
  },
170
176
  "experimental.session.compacting": async (input) => {
171
177
  const s = tracked(input.sessionID);
@@ -2,7 +2,7 @@ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node
2
2
  import { homedir } from "node:os";
3
3
  import path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
- import { skillMarkdown, SKILL_NAME } from "../claude-code/skill.js";
5
+ import { IMPORT_SKILL_NAME, importSkillMarkdown, skillMarkdown, SKILL_NAME } from "../claude-code/skill.js";
6
6
  // pi auto-loads every *.js in <agent-dir>/extensions, so no settings.json edit is needed.
7
7
  export function piPaths(piDir, env = process.env, home = homedir()) {
8
8
  const dir = piDir ?? env.PI_CODING_AGENT_DIR ?? path.join(home, ".pi", "agent");
@@ -37,6 +37,7 @@ export function connectPi(opts) {
37
37
  if (opts.remove) {
38
38
  rmSync(paths.extension, { force: true });
39
39
  rmSync(paths.skillDir, { recursive: true, force: true });
40
+ rmSync(path.join(path.dirname(paths.skillDir), IMPORT_SKILL_NAME), { recursive: true, force: true });
40
41
  return `removed ${paths.extension} and ${paths.skillDir}`;
41
42
  }
42
43
  const source = opts.source ?? builtExtension();
@@ -46,5 +47,8 @@ export function connectPi(opts) {
46
47
  writeFileSync(paths.extension, extensionStub(source));
47
48
  mkdirSync(paths.skillDir, { recursive: true });
48
49
  writeFileSync(path.join(paths.skillDir, "SKILL.md"), skillMarkdown({ allowedTools: false }));
50
+ const importDir = path.join(path.dirname(paths.skillDir), IMPORT_SKILL_NAME);
51
+ mkdirSync(importDir, { recursive: true });
52
+ writeFileSync(path.join(importDir, "SKILL.md"), importSkillMarkdown({ allowedTools: false }));
49
53
  return `wrote ${paths.extension} (loads ${source}) and ${paths.skillDir}/SKILL.md. Restart pi (or /reload) to load it.`;
50
54
  }
@@ -79,6 +79,18 @@ export function meshpointExtension(pi, deps = {}) {
79
79
  paths.push(path.resolve(ctx.cwd, p));
80
80
  return undefined;
81
81
  });
82
+ // The file notice rides on the edit's result: pi lets a handler patch `content`, and a patch
83
+ // without `structuredContent` would drop it, so both go back.
84
+ pi.on("tool_result", (event, ctx) => quiet(async () => {
85
+ const p = event.input.path;
86
+ if (!tap || !EDITING_TOOLS.has(event.toolName) || typeof p !== "string" || !p)
87
+ return undefined;
88
+ const notice = await tap.edit(path.resolve(ctx.cwd, p));
89
+ if (!notice)
90
+ return undefined;
91
+ const content = [...event.content, { type: "text", text: notice }];
92
+ return event.structuredContent === undefined ? { content } : { content, structuredContent: event.structuredContent };
93
+ }));
82
94
  pi.on("agent_before_settle", (event) => quiet(async () => {
83
95
  if (!tap)
84
96
  return undefined;
package/dist/refs.js ADDED
@@ -0,0 +1,86 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import path from "node:path";
4
+ // Refs are the repository paths an item depends on, read out of its own text. Only paths that
5
+ // exist in the checkout when the item is written count; the rest are reported so the agent can
6
+ // fix a typo. Verification later checks these same paths against other checkouts.
7
+ export const REFS_MAX = 50;
8
+ const KNOWN_EXTENSIONS = new Set([
9
+ "ts", "tsx", "js", "jsx", "mjs", "cjs", "mts", "cts", "json", "jsonc", "md", "mdx", "yml", "yaml", "toml", "ini", "cfg", "conf",
10
+ "py", "rs", "go", "java", "kt", "kts", "rb", "php", "c", "h", "cc", "cpp", "hpp", "cs", "swift", "m", "mm", "scala", "ex", "exs",
11
+ "sh", "bash", "zsh", "fish", "nix", "sql", "html", "css", "scss", "sass", "less", "vue", "svelte", "astro", "txt", "lock", "env",
12
+ "xml", "proto", "graphql", "gql", "tf", "hcl", "tfvars", "dockerfile", "mk", "cmake", "gradle", "properties", "csv", "svg", "wasm",
13
+ ]);
14
+ const TOKEN_RE = /[A-Za-z0-9_@~./-]+/g;
15
+ const BACKTICK_RE = /`([^`\n]+)`/g;
16
+ const STRIP_LEAD = /^[([{'"<]+/;
17
+ const STRIP_TRAIL = /[.,;:!?)\]}'">]+$/;
18
+ const VERSION_RE = /^v?\d+(\.\d+)+$/;
19
+ const DOMAIN_RE = /\.(com|dev|io|org|net|ai|app|sh|co|us|uk|de|fr|cloud|edu|gov)$/i;
20
+ function clean(token) {
21
+ return token.replace(STRIP_LEAD, "").replace(STRIP_TRAIL, "");
22
+ }
23
+ // A token is path-like when it has a directory separator or a known file extension. URLs,
24
+ // flags, versions and bare domains are not.
25
+ export function looksLikePath(token) {
26
+ if (!token || token.length > 512)
27
+ return false;
28
+ if (token.includes("://") || token.startsWith("www.") || token.startsWith("-") || token.startsWith("@"))
29
+ return false;
30
+ if (VERSION_RE.test(token))
31
+ return false;
32
+ if (token.includes("/"))
33
+ return !token.split("/").some((seg) => seg === "..");
34
+ const dot = token.lastIndexOf(".");
35
+ if (dot <= 0)
36
+ return false;
37
+ if (DOMAIN_RE.test(token))
38
+ return false;
39
+ return KNOWN_EXTENSIONS.has(token.slice(dot + 1).toLowerCase());
40
+ }
41
+ // Resolves a token against the repo root; null when it leaves the root or does not exist.
42
+ function resolve(token, root, exists) {
43
+ const abs = path.isAbsolute(token) ? token : path.join(root, token.startsWith("~/") ? token.slice(2) : token);
44
+ const rel = path.relative(root, abs);
45
+ if (!rel || rel.startsWith("..") || path.isAbsolute(rel))
46
+ return null;
47
+ return exists(abs) ? rel.split(path.sep).join("/") : null;
48
+ }
49
+ export function extractRefs(text, root, exists = existsSync) {
50
+ const refs = new Set();
51
+ const missing = new Set();
52
+ const consider = (raw, strict) => {
53
+ const token = clean(raw);
54
+ if (!token)
55
+ return;
56
+ const pathLike = looksLikePath(token);
57
+ // Backticked tokens may be bare file names (Makefile); they count only when they exist.
58
+ if (!pathLike && strict)
59
+ return;
60
+ const rel = resolve(token, root, exists);
61
+ if (rel)
62
+ refs.add(rel);
63
+ else if (pathLike)
64
+ missing.add(token);
65
+ };
66
+ for (const m of text.matchAll(BACKTICK_RE)) {
67
+ const span = m[1] ?? "";
68
+ if (!/\s/.test(span.trim()))
69
+ consider(span.trim(), false);
70
+ else
71
+ for (const t of span.match(TOKEN_RE) ?? [])
72
+ consider(t, true);
73
+ }
74
+ for (const t of text.replace(BACKTICK_RE, " ").match(TOKEN_RE) ?? [])
75
+ consider(t, true);
76
+ return { refs: [...refs].slice(0, REFS_MAX), missing: [...missing].slice(0, REFS_MAX) };
77
+ }
78
+ export function headSha(root) {
79
+ try {
80
+ const out = execFileSync("git", ["rev-parse", "HEAD"], { cwd: root, stdio: ["ignore", "pipe", "ignore"], timeout: 2000 }).toString().trim();
81
+ return /^[0-9a-f]{40}$/.test(out) ? out : "";
82
+ }
83
+ catch {
84
+ return "";
85
+ }
86
+ }
package/dist/runtime.js CHANGED
@@ -1,8 +1,10 @@
1
1
  import { Checkpoints } from "./checkpoints.js";
2
2
  import { loadConfig, repoContext, spoolDir, stateDir } from "./config.js";
3
+ import { SessionCache } from "./context.js";
3
4
  import { freshConfig } from "./control.js";
4
5
  import { Spool } from "./spool.js";
5
- import { Tap } from "./tap.js";
6
+ import { localChecks, Tap } from "./tap.js";
7
+ import { Touched } from "./touched.js";
6
8
  // A Tap for one harness session, wired to the stored login and the on-disk spool. Null when the
7
9
  // machine is not logged in or the directory is not a repo with an origin remote. In-process
8
10
  // adapters (pi, opencode, openclaw) call this once per harness session.
@@ -21,6 +23,9 @@ export async function openTap(session, cwd) {
21
23
  session,
22
24
  spool: new Spool(spoolDir()),
23
25
  checkpoints: new Checkpoints(stateDir()),
26
+ touched: new Touched(stateDir()),
27
+ cache: new SessionCache(stateDir()),
28
+ local: localChecks(repo.root),
24
29
  refresh: () => freshConfig(config, { force: true }).catch(() => null),
25
30
  });
26
31
  }
package/dist/tap.js CHANGED
@@ -1,8 +1,26 @@
1
1
  import path from "node:path";
2
2
  import { MeshpointClient, MeshpointError, redact } from "@meshpoint/sdk";
3
3
  import { SKILL_NAME } from "./claude-code/skill.js";
4
+ import { instructionFiles, itemsForFile, renderEditNotice, renderImportNudge } from "./context.js";
4
5
  import { ID_PREFIX_CHARS } from "./items.js";
6
+ import { gitRunner, sightings, verifyItems } from "./verify.js";
7
+ export function localChecks(root) {
8
+ const git = gitRunner(root);
9
+ return {
10
+ verify: (items) => verifyItems(items, root, { git }),
11
+ instructionFiles: () => instructionFiles(git),
12
+ };
13
+ }
5
14
  const DEFAULT_PRESENCE_WAIT_MS = 1500;
15
+ // The inject is cut to this many tokens of items; the request asks for everything so the
16
+ // verification pass and the edit hook see the whole branch.
17
+ export const INJECT_BUDGET_TOKENS = 3000;
18
+ const ALL_ITEMS_BUDGET = 100_000;
19
+ // Longest the session-start hook waits for the platform to take the sightings.
20
+ const VERIFY_SEND_WAIT_MS = 800;
21
+ // Longest an edit waits for presence from the origin before the local items go out alone.
22
+ const EDIT_WAIT_MS = 1000;
23
+ const STALE_LIST_MAX = 20;
6
24
  // Harnesses that feed the nudge back as a user prompt (Cursor) match on this to keep it out of the capture.
7
25
  export const NUDGE_PREFIX = "Meshpoint checkpoint due";
8
26
  // One harness session's side of the mesh, independent of how the harness delivers events: recall
@@ -23,24 +41,68 @@ export class Tap {
23
41
  async start() {
24
42
  try {
25
43
  const { recall, presence } = await this.client(this.repo.branch)
26
- .sessionStart()
44
+ .sessionStart({ budget: ALL_ITEMS_BUDGET })
27
45
  .catch(async (err) => {
28
46
  if (!is401(err) || !(await this.reauth()))
29
47
  throw err;
30
- return this.client(this.repo.branch).sessionStart();
48
+ return this.client(this.repo.branch).sessionStart({ budget: ALL_ITEMS_BUDGET });
49
+ });
50
+ const verdicts = this.deps.local ? this.deps.local.verify(recall.items) : new Map();
51
+ this.deps.cache?.saveRecall(this.deps.session, {
52
+ project: this.repo.project,
53
+ branch: this.repo.branch,
54
+ items: recall.items,
55
+ verdicts: Object.fromEntries(verdicts),
56
+ at: this.now(),
31
57
  });
58
+ const report = sightings(verdicts);
59
+ const sent = report.length > 0 ? this.client(this.repo.branch).verify(report).catch(() => undefined) : Promise.resolve(undefined);
32
60
  const teammates = await Promise.race([
33
61
  presence,
34
62
  new Promise((r) => setTimeout(() => r([]), this.deps.presenceWaitMs ?? DEFAULT_PRESENCE_WAIT_MS)),
35
63
  ]);
36
- const text = renderInject(this.repo, recall, teammates, this.now());
64
+ let text = renderInject(this.repo, recall, teammates, this.now(), verdicts);
65
+ const nudge = this.importNudge(recall);
66
+ if (nudge)
67
+ text = `${text || `# Meshpoint: ${this.repo.project} @ ${this.repo.branch}`}\n\n${nudge}`;
37
68
  await this.flush(false);
69
+ await Promise.race([sent, new Promise((r) => setTimeout(r, VERIFY_SEND_WAIT_MS))]);
38
70
  return text;
39
71
  }
40
72
  catch {
41
73
  return "";
42
74
  }
43
75
  }
76
+ // A branch with no memory and committed instruction files gets one invitation to import them.
77
+ importNudge(recall) {
78
+ if (!this.deps.local || !this.deps.cache || recall.items.length > 0 || recall.checkpoint)
79
+ return "";
80
+ const files = this.deps.local.instructionFiles();
81
+ if (files.length === 0 || !this.deps.cache.firstImportNudge(this.repo.project, this.repo.branch))
82
+ return "";
83
+ return renderImportNudge(files);
84
+ }
85
+ // The notice for one file about to be edited (or just edited), or "". Items come from the
86
+ // session-start cache with the local verdicts; presence comes from the origin, briefly.
87
+ async edit(filePath) {
88
+ try {
89
+ const rel = this.relative(filePath);
90
+ if (!rel)
91
+ return "";
92
+ if (this.deps.cache && !this.deps.cache.firstEdit(this.deps.session, rel))
93
+ return "";
94
+ const cached = this.deps.cache?.loadRecall(this.deps.session);
95
+ const ctx = await Promise.race([
96
+ this.client(this.repo.branch).context(rel).catch(() => null),
97
+ new Promise((r) => setTimeout(() => r(null), EDIT_WAIT_MS)),
98
+ ]);
99
+ const items = cached ? itemsForFile(cached.items, cached.verdicts, rel) : (ctx?.items ?? []);
100
+ return renderEditNotice(rel, items, ctx?.presence ?? [], this.now());
101
+ }
102
+ catch {
103
+ return "";
104
+ }
105
+ }
44
106
  async user(prompt) {
45
107
  if (prompt)
46
108
  this.spoolTurn(`[user] ${prompt}`);
@@ -49,6 +111,7 @@ export class Tap {
49
111
  async assistant(text, paths = []) {
50
112
  if (text || paths.length > 0)
51
113
  this.spoolTurn(`[assistant] ${text}`, paths);
114
+ this.deps.touched?.append(this.repo.project, this.repo.branch, this.relativeAll(paths), this.now());
52
115
  await this.flush(false);
53
116
  }
54
117
  // The nudge to show the agent when a checkpoint is due, else null. Recording the nudge keeps an
@@ -101,10 +164,20 @@ export class Tap {
101
164
  this.config = next;
102
165
  return true;
103
166
  }
167
+ // Repo-relative with forward slashes, or null for a path outside the repository.
168
+ relative(p) {
169
+ const rel = path.isAbsolute(p) ? path.relative(this.repo.root, p) : path.normalize(p);
170
+ if (!rel || rel.startsWith("..") || path.isAbsolute(rel))
171
+ return null;
172
+ return rel.split(path.sep).join("/");
173
+ }
174
+ relativeAll(paths) {
175
+ return [...new Set(paths.map((p) => this.relative(p)).filter((p) => p !== null))];
176
+ }
104
177
  // Credentials are masked before the turn touches the spool file, so nothing on disk or on the
105
178
  // wire holds them. The SDK masks again on send for callers that bypass the spool.
106
179
  spoolTurn(body, paths = []) {
107
- const rel = paths.map((p) => (path.isAbsolute(p) ? path.relative(this.repo.root, p) : p)).filter((p) => p && !p.startsWith(".."));
180
+ const rel = this.relativeAll(paths);
108
181
  const turn = { branch: this.repo.branch, body: redact(body), at: this.now(), ...(rel.length ? { paths: rel } : {}) };
109
182
  this.deps.spool.append(this.deps.session, turn);
110
183
  }
@@ -146,7 +219,14 @@ function age(ms) {
146
219
  const h = Math.floor(m / 60);
147
220
  return h < 48 ? `${h}h ago` : `${Math.floor(h / 24)}d ago`;
148
221
  }
149
- export function renderInject(repo, recall, presence, now) {
222
+ function estimateTokens(item) {
223
+ return Math.ceil((item.title.length + item.body.length) / 4) + 8;
224
+ }
225
+ // Items arrive ranked from the platform; the budget cut happens here. Stale items (a referenced
226
+ // file is gone in this checkout) leave the list for a short section of their own; suspect items
227
+ // (a referenced file changed since) stay, marked. Items the platform already marks suspect from
228
+ // other checkouts carry the mark too.
229
+ export function renderInject(repo, recall, presence, now, verdicts = new Map()) {
150
230
  if (recall.items.length === 0 && !recall.checkpoint && presence.length === 0)
151
231
  return "";
152
232
  const lines = [`# Meshpoint: ${repo.project} @ ${repo.branch}`];
@@ -158,10 +238,37 @@ export function renderInject(repo, recall, presence, now) {
158
238
  if (recall.checkpoint) {
159
239
  lines.push("", `## Last checkpoint (${age(now - recall.checkpoint.created_at)})`, recall.checkpoint.body);
160
240
  }
161
- if (recall.items.length > 0) {
162
- lines.push("", `## Team knowledge (${recall.items.length}; first column is the item id)`);
163
- for (const i of recall.items)
164
- lines.push(`- ${i.id.slice(0, ID_PREFIX_CHARS)} [${i.kind}] ${i.title}: ${i.body}`);
241
+ const stale = recall.items.filter((i) => verdicts.get(i.id) === "stale");
242
+ const live = [];
243
+ let used = 0;
244
+ for (const i of recall.items) {
245
+ if (verdicts.get(i.id) === "stale")
246
+ continue;
247
+ const t = estimateTokens(i);
248
+ if (used + t > INJECT_BUDGET_TOKENS)
249
+ break;
250
+ live.push(i);
251
+ used += t;
252
+ }
253
+ if (live.length > 0) {
254
+ const marked = live.some((i) => isSuspect(i, verdicts));
255
+ lines.push("", `## Team knowledge (${live.length}; first column is the item id${marked ? ", ? means a referenced file changed since" : ""})`);
256
+ for (const i of live)
257
+ lines.push(`- ${i.id.slice(0, ID_PREFIX_CHARS)}${isSuspect(i, verdicts) ? "?" : ""} [${i.kind}] ${i.title}: ${i.body}`);
258
+ }
259
+ if (stale.length > 0) {
260
+ lines.push("", "## Possibly stale (a referenced file is gone; verify, then retract or rewrite)");
261
+ for (const i of stale.slice(0, STALE_LIST_MAX))
262
+ lines.push(`- ${i.id.slice(0, ID_PREFIX_CHARS)} [${i.kind}] ${i.title}`);
165
263
  }
166
264
  return lines.join("\n");
167
265
  }
266
+ // A local verdict wins; without one (or when the checkout could not judge) the platform's state stands.
267
+ function isSuspect(item, verdicts) {
268
+ const local = verdicts.get(item.id);
269
+ if (local === "verified")
270
+ return false;
271
+ if (local === "suspect")
272
+ return true;
273
+ return (local === undefined || local === "skipped") && item.state === "suspect";
274
+ }