@slashml/memory 1.0.8 → 1.0.10

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/bin/cli.js CHANGED
@@ -10,7 +10,7 @@ const readline = require("readline");
10
10
 
11
11
  const DEFAULT_BASE_URL = "https://api.slashml.ai";
12
12
  const DEFAULT_CONSOLE_URL = "https://app.slashml.ai";
13
- const PACKAGE_VERSION = "1.0.8";
13
+ const PACKAGE_VERSION = "1.0.10";
14
14
 
15
15
  function printHelp() {
16
16
  console.log(`@slashml/memory v${PACKAGE_VERSION} -- Official CLI & MCP Stdio Server for / ml (SlashML · https://slashml.ai)
@@ -37,8 +37,13 @@ Options:
37
37
  --write-env Save SLASHML_API_KEY to .env in the current directory
38
38
  --hook Run as an ambient IDE/agent lifecycle hook (reads hook JSON from stdin)
39
39
  --install-hooks Register ambient / ml hooks in ~/.claude/settings.json & .cursor/hooks.json
40
+ sync-rules, --sync-rules Sync active / ml project rules into CLAUDE.md and AGENTS.md (for cloud sandboxes)
41
+ watch-sandbox, --watch-sandbox Tail live sandbox transcripts to assimilate rules and inject mid-turn course corrections
42
+ --daemon Run watch-sandbox as a detached background process (exits 0 immediately)
43
+ --once Run a single watch-sandbox transcript scan pass and exit
44
+ --transcript-dir <dir> Additional directory to scan for .jsonl agent transcripts
40
45
  status, --status Show ambient memory ROI telemetry (tokens processed, % noise filtered, rules assimilated, amnesia intercepted)
41
- --json Format status output as JSON
46
+ --json Format status/sync output as JSON
42
47
  --signup <work-email> Request a 6-digit OTP to provision a / ml free API key (requires work/custom domain @company.com; for @gmail.com / @hotmail.com sign in with Google/GitHub at https://app.slashml.ai)
43
48
  --verify <work-email> <code> Verify 6-digit code and print the new SLASHML_API_KEY to stdout`);
44
49
  }
@@ -183,6 +188,13 @@ function parseCliArgs(argv) {
183
188
  let isInstallHooks = false;
184
189
  let isStatus = false;
185
190
  let jsonOutput = false;
191
+ let isSyncRules = false;
192
+ let isWatchSandbox = false;
193
+ let isDaemon = false;
194
+ let isOnce = false;
195
+ let intervalMs = 1500;
196
+ let transcriptDir = process.env.SLASHML_TRANSCRIPT_DIR || null;
197
+ let forgetId = null;
186
198
 
187
199
  for (let i = 0; i < argv.length; i++) {
188
200
  const arg = argv[i];
@@ -198,6 +210,20 @@ function parseCliArgs(argv) {
198
210
  hookEvent = argv[++i];
199
211
  } else if (arg === "--install-hooks" || arg === "install-hooks") {
200
212
  isInstallHooks = true;
213
+ } else if (arg === "--sync-rules" || arg === "sync-rules") {
214
+ isSyncRules = true;
215
+ } else if (arg === "--watch-sandbox" || arg === "watch-sandbox") {
216
+ isWatchSandbox = true;
217
+ } else if ((arg === "--forget" || arg === "forget") && i + 1 < argv.length) {
218
+ forgetId = argv[++i];
219
+ } else if (arg === "--daemon") {
220
+ isDaemon = true;
221
+ } else if (arg === "--once") {
222
+ isOnce = true;
223
+ } else if (arg === "--interval-ms" && i + 1 < argv.length) {
224
+ intervalMs = Math.max(250, Number(argv[++i]) || 1500);
225
+ } else if (arg === "--transcript-dir" && i + 1 < argv.length) {
226
+ transcriptDir = argv[++i];
201
227
  } else if (arg === "--status" || arg === "status") {
202
228
  isStatus = true;
203
229
  } else if (arg === "--json") {
@@ -258,6 +284,13 @@ function parseCliArgs(argv) {
258
284
  isInstallHooks,
259
285
  isStatus,
260
286
  jsonOutput,
287
+ isSyncRules,
288
+ isWatchSandbox,
289
+ isDaemon,
290
+ isOnce,
291
+ intervalMs,
292
+ transcriptDir,
293
+ forgetId,
261
294
  };
262
295
  }
263
296
 
@@ -1124,13 +1157,52 @@ async function runAmbientHookMode(opts) {
1124
1157
  if (!dedupState.whispered_blocks_by_session || typeof dedupState.whispered_blocks_by_session !== "object") {
1125
1158
  dedupState.whispered_blocks_by_session = {};
1126
1159
  }
1160
+ if (!dedupState.blocked_by_session || typeof dedupState.blocked_by_session !== "object") {
1161
+ dedupState.blocked_by_session = {};
1162
+ }
1163
+ if (!dedupState.overridden_by_session || typeof dedupState.overridden_by_session !== "object") {
1164
+ dedupState.overridden_by_session = {};
1165
+ }
1166
+ if (!dedupState.blocked_actions_by_session || typeof dedupState.blocked_actions_by_session !== "object") {
1167
+ dedupState.blocked_actions_by_session = {};
1168
+ }
1127
1169
  const whisperKey = sessionKey || scopeStateKey;
1128
1170
  const isMidTurnContinuation =
1129
1171
  rawEventName === "PreInvocation" && Number(payload.invocationNum || 1) > 1;
1172
+ const targetSig = toolIn
1173
+ ? String(
1174
+ toolIn.file_path ||
1175
+ toolIn.path ||
1176
+ toolIn.Path ||
1177
+ toolIn.command ||
1178
+ toolIn.CommandLine ||
1179
+ deltaText.slice(0, 120)
1180
+ )
1181
+ .trim()
1182
+ .toLowerCase()
1183
+ : deltaText.slice(0, 120).toLowerCase();
1184
+
1130
1185
  if (hookEvent === "UserPromptSubmit" && !isMidTurnContinuation && whisperKey) {
1131
- dedupState.whispered_by_session[whisperKey] = [];
1132
1186
  dedupState.whispered_blocks_by_session[whisperKey] = [];
1133
1187
  }
1188
+ if (hookEvent === "PreToolUse" && whisperKey) {
1189
+ const prevAct = Array.isArray(dedupState.blocked_actions_by_session[whisperKey])
1190
+ ? dedupState.blocked_actions_by_session[whisperKey]
1191
+ : [];
1192
+ const prevOv = Array.isArray(dedupState.overridden_by_session[whisperKey])
1193
+ ? dedupState.overridden_by_session[whisperKey]
1194
+ : [];
1195
+ const suffix = `:${toolName || ""}:${targetSig}`;
1196
+ const matchedIds = prevAct
1197
+ .filter((entry) => typeof entry === "string" && entry.endsWith(suffix))
1198
+ .map((entry) => entry.slice(0, entry.length - suffix.length))
1199
+ .filter(Boolean);
1200
+ if (matchedIds.length > 0) {
1201
+ dedupState.overridden_by_session[whisperKey] = Array.from(
1202
+ new Set([...prevOv, ...matchedIds])
1203
+ ).slice(-32);
1204
+ }
1205
+ }
1134
1206
  const transcriptWhispered = extractWhisperedContextFromCurrentTurn(
1135
1207
  payload.transcriptPath || payload.transcript_path
1136
1208
  );
@@ -1142,6 +1214,18 @@ async function runAmbientHookMode(opts) {
1142
1214
  whisperKey && Array.isArray(dedupState.whispered_blocks_by_session[whisperKey])
1143
1215
  ? dedupState.whispered_blocks_by_session[whisperKey]
1144
1216
  : [];
1217
+ const sessionOverridden = [
1218
+ ...(whisperKey && Array.isArray(dedupState.overridden_by_session[whisperKey])
1219
+ ? dedupState.overridden_by_session[whisperKey]
1220
+ : []),
1221
+ ...(Array.isArray(dedupState.overridden_by_session._global)
1222
+ ? dedupState.overridden_by_session._global
1223
+ : []),
1224
+ ...(Array.isArray(payload.overridden_memory_ids) ? payload.overridden_memory_ids : []),
1225
+ ...(toolIn && Array.isArray(toolIn.override_memory_ids) ? toolIn.override_memory_ids : []),
1226
+ ...(toolIn && Array.isArray(toolIn.overridden_memory_ids) ? toolIn.overridden_memory_ids : []),
1227
+ ];
1228
+ const overriddenMemoryIds = Array.from(new Set(sessionOverridden.map(String).filter(Boolean)));
1145
1229
  const whisperedMemoryIds = Array.from(new Set([...transcriptWhispered.ids, ...sessionWhispered]));
1146
1230
  const whisperedBlocks = Array.from(new Set([...transcriptWhispered.blocks, ...sessionWhisperedBlocks]));
1147
1231
  const streamTextForIntervene =
@@ -1183,6 +1267,7 @@ async function runAmbientHookMode(opts) {
1183
1267
  tool_input: effectiveToolIn,
1184
1268
  tool_response: payload.tool_response || payload.toolResponse || null,
1185
1269
  whispered_memory_ids: whisperedMemoryIds,
1270
+ ...(overriddenMemoryIds.length > 0 ? { overridden_memory_ids: overriddenMemoryIds } : {}),
1186
1271
  commit_writes: isMidTurnContinuation ? false : true,
1187
1272
  model: process.env.SLASHML_MODEL || undefined,
1188
1273
  user_id: opts.userId,
@@ -1222,6 +1307,23 @@ async function runAmbientHookMode(opts) {
1222
1307
  : [];
1223
1308
  const merged = Array.from(new Set([...prev, ...triggeredIds]));
1224
1309
  dedupState.whispered_by_session[whisperKey] = merged.slice(-16);
1310
+ if (resp.intervention_severity === "BLOCK") {
1311
+ const prevBlk = Array.isArray(dedupState.blocked_by_session[whisperKey])
1312
+ ? dedupState.blocked_by_session[whisperKey]
1313
+ : [];
1314
+ dedupState.blocked_by_session[whisperKey] = Array.from(
1315
+ new Set([...prevBlk, ...triggeredIds])
1316
+ ).slice(-16);
1317
+ if (hookEvent === "PreToolUse") {
1318
+ const prevAct = Array.isArray(dedupState.blocked_actions_by_session[whisperKey])
1319
+ ? dedupState.blocked_actions_by_session[whisperKey]
1320
+ : [];
1321
+ const actKeys = triggeredIds.map((id) => `${id}:${toolName || ""}:${targetSig}`);
1322
+ dedupState.blocked_actions_by_session[whisperKey] = Array.from(
1323
+ new Set([...prevAct, ...actKeys])
1324
+ ).slice(-32);
1325
+ }
1326
+ }
1225
1327
  }
1226
1328
  if (whisperKey && resp.intervention_message) {
1227
1329
  const msgTags = String(resp.intervention_message).match(/<memory>[\s\S]*?<\/memory>/gi);
@@ -1301,11 +1403,684 @@ async function runAmbientHookMode(opts) {
1301
1403
  }
1302
1404
  }
1303
1405
 
1406
+ const SANDBOX_INTERVENTION_PATH =
1407
+ process.env.SLASHML_SANDBOX_INTERVENTION_PATH || "/tmp/slashml-sandbox-intervention.json";
1408
+ const SANDBOX_OFFSETS_PATH =
1409
+ process.env.SLASHML_SANDBOX_OFFSETS_PATH || "/tmp/slashml-sandbox-offsets.json";
1410
+ const SANDBOX_PID_PATH =
1411
+ process.env.SLASHML_SANDBOX_PID_PATH || "/tmp/slashml-watch-sandbox.pid";
1412
+
1413
+ function resolveSandboxTargets(explicitRepo) {
1414
+ if (explicitRepo && String(explicitRepo).trim()) {
1415
+ return [path.resolve(String(explicitRepo).trim())];
1416
+ }
1417
+ const cwd = process.cwd();
1418
+ const targets = new Set();
1419
+ const repoIndicators = [".git", ".ellipsis", "CLAUDE.md", "AGENTS.md", "package.json", "pyproject.toml"];
1420
+ if (repoIndicators.some((f) => fs.existsSync(path.join(cwd, f)))) {
1421
+ targets.add(cwd);
1422
+ }
1423
+ try {
1424
+ const entries = fs.readdirSync(cwd, { withFileTypes: true });
1425
+ let subCount = 0;
1426
+ for (const entry of entries) {
1427
+ if (subCount >= 6) break;
1428
+ if (!entry.isDirectory() || entry.name.startsWith(".") || entry.name === "node_modules") continue;
1429
+ const subPath = path.join(cwd, entry.name);
1430
+ if (repoIndicators.some((f) => fs.existsSync(path.join(subPath, f)))) {
1431
+ targets.add(subPath);
1432
+ subCount += 1;
1433
+ }
1434
+ }
1435
+ } catch {
1436
+ // ignore directory scan errors
1437
+ }
1438
+ if (targets.size === 0) {
1439
+ targets.add(cwd);
1440
+ }
1441
+ return Array.from(targets);
1442
+ }
1443
+
1444
+ function upsertAmbientMarkdownSection(filePath, sectionBody) {
1445
+ const startMarker = "<!-- SLASHML-AMBIENT-MEMORY:START -->";
1446
+ const endMarker = "<!-- SLASHML-AMBIENT-MEMORY:END -->";
1447
+ const block = `${startMarker}\n${sectionBody.trim()}\n${endMarker}`;
1448
+ let existing = "";
1449
+ if (fs.existsSync(filePath)) {
1450
+ try {
1451
+ existing = fs.readFileSync(filePath, "utf8");
1452
+ } catch {
1453
+ existing = "";
1454
+ }
1455
+ }
1456
+ const startIdx = existing.indexOf(startMarker);
1457
+ const endIdx = existing.indexOf(endMarker);
1458
+ let updated = "";
1459
+ if (startIdx !== -1 && endIdx !== -1 && endIdx > startIdx) {
1460
+ updated =
1461
+ existing.slice(0, startIdx).replace(/\n*$/, "\n\n") +
1462
+ block +
1463
+ "\n" +
1464
+ existing.slice(endIdx + endMarker.length).replace(/^\n*/, "");
1465
+ } else if (existing.trim()) {
1466
+ updated = `${existing.replace(/\n*$/, "")}\n\n${block}\n`;
1467
+ } else {
1468
+ updated = `${block}\n`;
1469
+ }
1470
+ fs.writeFileSync(filePath, updated.replace(/^\n+/, ""), "utf8");
1471
+ }
1472
+
1473
+ async function runSyncRulesCommand(opts) {
1474
+ const targets = resolveSandboxTargets(opts.repo);
1475
+ const primaryDir = targets[0] || process.cwd();
1476
+ const projectId =
1477
+ process.env.SLASHML_PROJECT_ID || path.basename(primaryDir.replace(/[\\/]+$/, "")) || "default";
1478
+
1479
+ if (!opts.apiKey) {
1480
+ if (!opts.silent) {
1481
+ const msg = {
1482
+ status: "skipped",
1483
+ reason: "SLASHML_API_KEY not set",
1484
+ targets,
1485
+ };
1486
+ if (opts.jsonOutput) {
1487
+ process.stdout.write(JSON.stringify(msg, null, 2) + "\n");
1488
+ } else {
1489
+ console.log("[/ ml] SLASHML_API_KEY not set; skipping sync-rules.");
1490
+ }
1491
+ }
1492
+ return { synced_count: 0, targets };
1493
+ }
1494
+
1495
+ const memories = [];
1496
+ const seenText = new Set();
1497
+
1498
+ try {
1499
+ const targetUserId = opts.userId || "default";
1500
+ const q = new URLSearchParams({
1501
+ user_id: targetUserId,
1502
+ limit: "200",
1503
+ include_code: "false",
1504
+ });
1505
+ const listResp = await apiRequest(opts, "GET", `/v1/memories?${q.toString()}`);
1506
+ const rawItems = Array.isArray(listResp)
1507
+ ? listResp
1508
+ : Array.isArray(listResp?.results)
1509
+ ? listResp.results
1510
+ : Array.isArray(listResp?.memories)
1511
+ ? listResp.memories
1512
+ : [];
1513
+ const reversedItems = rawItems.slice().reverse();
1514
+ const orderedItems = [
1515
+ ...reversedItems.filter((item) => item && item.user_id === targetUserId),
1516
+ ...reversedItems.filter((item) => item && item.user_id !== targetUserId),
1517
+ ];
1518
+ for (const item of orderedItems) {
1519
+ if (!item || typeof item !== "object") continue;
1520
+ const meta = item.metadata && typeof item.metadata === "object" ? item.metadata : {};
1521
+ if (meta.kind === "code_symbol" || meta.modality === "code") continue;
1522
+ const text = String(item.memory || item.text || item.content || "").trim();
1523
+ if (!text || text.startsWith("[FILE] ")) continue;
1524
+ const norm = text.toLowerCase();
1525
+ if (seenText.has(norm)) continue;
1526
+ seenText.add(norm);
1527
+ memories.push({
1528
+ id: String(item.id || item.memory_id || `mem_${memories.length + 1}`),
1529
+ user_id: item.user_id || null,
1530
+ text,
1531
+ });
1532
+ }
1533
+ } catch {
1534
+ // Fail-open if listing memories fails
1535
+ }
1536
+
1537
+ let activeIntervention = opts.activeIntervention || "";
1538
+ if (!activeIntervention && fs.existsSync(SANDBOX_INTERVENTION_PATH)) {
1539
+ try {
1540
+ const saved = JSON.parse(fs.readFileSync(SANDBOX_INTERVENTION_PATH, "utf8"));
1541
+ if (saved && saved.intervention_message && Date.now() - Number(saved.timestamp || 0) < 600000) {
1542
+ activeIntervention = String(saved.intervention_message);
1543
+ }
1544
+ } catch {
1545
+ // ignore
1546
+ }
1547
+ }
1548
+
1549
+ const lines = [
1550
+ "## / ml Ambient Project Memory (Auto-Synced)",
1551
+ "",
1552
+ "The following architectural rules, project invariants, and PR review corrections are persisted across ephemeral sandbox sessions by `/ ml` (`https://slashml.ai`). Follow them strictly:",
1553
+ "",
1554
+ ];
1555
+ if (activeIntervention) {
1556
+ lines.push("> [!CAUTION]");
1557
+ lines.push("> **ACTIVE / ml MID-TURN COURSE CORRECTION:**");
1558
+ for (const l of activeIntervention.split(/\r?\n/)) {
1559
+ lines.push(`> ${l}`);
1560
+ }
1561
+ lines.push("");
1562
+ }
1563
+ if (memories.length === 0) {
1564
+ lines.push("- *(No project rules recorded yet for this workspace namespace. New rules and PR review corrections will be assimilated automatically during this session.)*");
1565
+ } else {
1566
+ for (const m of memories.slice(0, 20)) {
1567
+ lines.push(`- **[${m.id}]** ${m.text}`);
1568
+ }
1569
+ }
1570
+
1571
+ const sectionBody = lines.join("\n");
1572
+ const updatedFiles = [];
1573
+ for (const dir of targets) {
1574
+ for (const fname of ["CLAUDE.md", "AGENTS.md"]) {
1575
+ const fpath = path.join(dir, fname);
1576
+ try {
1577
+ upsertAmbientMarkdownSection(fpath, sectionBody);
1578
+ updatedFiles.push(fpath);
1579
+ } catch {
1580
+ // ignore unwritable paths
1581
+ }
1582
+ }
1583
+ }
1584
+
1585
+ const result = {
1586
+ status: "synced",
1587
+ project_id: projectId,
1588
+ user_id: opts.userId || "default",
1589
+ synced_count: memories.length,
1590
+ memories,
1591
+ active_intervention: Boolean(activeIntervention),
1592
+ updated_files: updatedFiles,
1593
+ };
1594
+ if (!opts.silent) {
1595
+ if (opts.jsonOutput) {
1596
+ process.stdout.write(JSON.stringify(result, null, 2) + "\n");
1597
+ } else {
1598
+ console.log(
1599
+ `[/ ml] Synced ${memories.length} project memories into ${updatedFiles.length} workspace file(s) (${targets.join(", ")}).`
1600
+ );
1601
+ }
1602
+ }
1603
+ return result;
1604
+ }
1605
+
1606
+ function collectSandboxTranscriptFiles(extraDir) {
1607
+ const roots = [];
1608
+ const onlyExplicitDir = Boolean(extraDir && String(extraDir).trim());
1609
+ if (onlyExplicitDir) {
1610
+ roots.push(path.resolve(String(extraDir).trim()));
1611
+ } else {
1612
+ const home = os.homedir();
1613
+ roots.push(
1614
+ path.join(home, ".claude", "projects"),
1615
+ path.join(home, ".codex", "sessions"),
1616
+ "/tmp/slashml-transcripts"
1617
+ );
1618
+ }
1619
+ const nowMs = Date.now();
1620
+ const maxAgeMs = 30 * 60 * 1000;
1621
+ const found = [];
1622
+ function walk(dir, depth = 0) {
1623
+ if (depth > 5 || !fs.existsSync(dir)) return;
1624
+ let entries = [];
1625
+ try {
1626
+ entries = fs.readdirSync(dir, { withFileTypes: true });
1627
+ } catch {
1628
+ return;
1629
+ }
1630
+ for (const e of entries) {
1631
+ const full = path.join(dir, e.name);
1632
+ if (e.isDirectory()) {
1633
+ walk(full, depth + 1);
1634
+ } else if (e.isFile() && e.name.endsWith(".jsonl")) {
1635
+ if (!onlyExplicitDir) {
1636
+ try {
1637
+ const st = fs.statSync(full);
1638
+ if (nowMs - st.mtimeMs > maxAgeMs) continue;
1639
+ } catch {
1640
+ continue;
1641
+ }
1642
+ }
1643
+ found.push(full);
1644
+ }
1645
+ }
1646
+ }
1647
+ for (const r of roots) {
1648
+ walk(r, 0);
1649
+ }
1650
+ return found;
1651
+ }
1652
+
1653
+ function extractEventsFromTranscriptEntry(entry) {
1654
+ const events = [];
1655
+ if (!entry || typeof entry !== "object") return events;
1656
+
1657
+ if (entry.hook_event_name || entry.hookEventName) {
1658
+ events.push({
1659
+ hook_event_name: String(entry.hook_event_name || entry.hookEventName),
1660
+ text: String(entry.text || entry.prompt || ""),
1661
+ prompt: String(entry.prompt || entry.text || ""),
1662
+ tool_name: entry.tool_name || entry.toolName || null,
1663
+ tool_input: entry.tool_input || entry.toolInput || null,
1664
+ });
1665
+ return events;
1666
+ }
1667
+
1668
+ const msg = entry.message && typeof entry.message === "object" ? entry.message : entry;
1669
+ const role = String(msg.role || entry.type || "").toLowerCase();
1670
+
1671
+ if (role === "user" || entry.type === "USER_INPUT") {
1672
+ let text = "";
1673
+ if (typeof msg.content === "string") {
1674
+ text = msg.content;
1675
+ } else if (typeof entry.content === "string") {
1676
+ text = entry.content;
1677
+ } else if (Array.isArray(msg.content)) {
1678
+ text = msg.content
1679
+ .filter((b) => b && (b.type === "text" || typeof b.text === "string"))
1680
+ .map((b) => String(b.text || ""))
1681
+ .join("\n");
1682
+ }
1683
+ if (text && text.trim()) {
1684
+ events.push({
1685
+ hook_event_name: "UserPromptSubmit",
1686
+ text: text.trim(),
1687
+ prompt: text.trim(),
1688
+ tool_name: null,
1689
+ tool_input: null,
1690
+ });
1691
+ }
1692
+ return events;
1693
+ }
1694
+
1695
+ if (role === "assistant" || entry.type === "PLANNER_RESPONSE") {
1696
+ const textParts = [];
1697
+ if (typeof msg.content === "string" && msg.content.trim()) {
1698
+ textParts.push(msg.content.trim());
1699
+ } else if (typeof entry.content === "string" && entry.content.trim()) {
1700
+ textParts.push(entry.content.trim());
1701
+ } else if (Array.isArray(msg.content)) {
1702
+ for (const b of msg.content) {
1703
+ if (!b || typeof b !== "object") continue;
1704
+ if (b.type === "text" && typeof b.text === "string" && b.text.trim()) {
1705
+ textParts.push(b.text.trim());
1706
+ } else if (b.type === "tool_use" && b.name) {
1707
+ const toolIn = b.input && typeof b.input === "object" ? b.input : {};
1708
+ const toolSummary =
1709
+ toolIn.command ||
1710
+ toolIn.CommandLine ||
1711
+ toolIn.content ||
1712
+ toolIn.Content ||
1713
+ toolIn.new_string ||
1714
+ toolIn.Replacement ||
1715
+ JSON.stringify(toolIn);
1716
+ events.push({
1717
+ hook_event_name: "PreToolUse",
1718
+ text: String(toolSummary || ""),
1719
+ tool_name: String(b.name),
1720
+ tool_input: toolIn,
1721
+ });
1722
+ }
1723
+ }
1724
+ }
1725
+ if (Array.isArray(entry.tool_calls)) {
1726
+ for (const tc of entry.tool_calls) {
1727
+ if (!tc || typeof tc !== "object") continue;
1728
+ const name = tc.name || (tc.function && tc.function.name);
1729
+ const toolIn = tc.args || tc.arguments || tc.input || (tc.function && tc.function.arguments) || {};
1730
+ if (name) {
1731
+ const parsedIn =
1732
+ typeof toolIn === "string"
1733
+ ? (() => {
1734
+ try {
1735
+ return JSON.parse(toolIn);
1736
+ } catch {
1737
+ return { raw: toolIn };
1738
+ }
1739
+ })()
1740
+ : toolIn;
1741
+ const toolSummary =
1742
+ parsedIn.command ||
1743
+ parsedIn.CommandLine ||
1744
+ parsedIn.content ||
1745
+ parsedIn.Content ||
1746
+ parsedIn.new_string ||
1747
+ parsedIn.Replacement ||
1748
+ JSON.stringify(parsedIn);
1749
+ events.push({
1750
+ hook_event_name: "PreToolUse",
1751
+ text: String(toolSummary || ""),
1752
+ tool_name: String(name),
1753
+ tool_input: parsedIn,
1754
+ });
1755
+ }
1756
+ }
1757
+ }
1758
+ if (textParts.length > 0) {
1759
+ events.push({
1760
+ hook_event_name: "Stop",
1761
+ text: textParts.join("\n"),
1762
+ tool_name: null,
1763
+ tool_input: null,
1764
+ });
1765
+ }
1766
+ }
1767
+ return events;
1768
+ }
1769
+
1770
+ async function scanSandboxTranscriptsOnce(opts, state) {
1771
+ state.whisperedBySession = state.whisperedBySession || {};
1772
+ const files = collectSandboxTranscriptFiles(opts.transcriptDir);
1773
+ const targets = resolveSandboxTargets(opts.repo);
1774
+ const primaryDir = targets[0] || process.cwd();
1775
+ const projectId =
1776
+ process.env.SLASHML_PROJECT_ID || path.basename(primaryDir.replace(/[\\/]+$/, "")) || "default";
1777
+
1778
+ let processedEvents = 0;
1779
+ let assimilatedCount = 0;
1780
+ let intervenedCount = 0;
1781
+ const interventions = [];
1782
+
1783
+ for (const filePath of files) {
1784
+ let stat = null;
1785
+ try {
1786
+ stat = fs.statSync(filePath);
1787
+ } catch {
1788
+ continue;
1789
+ }
1790
+ const prevOffset = Number(state.offsets[filePath] || 0);
1791
+ const startOffset = stat.size < prevOffset ? 0 : prevOffset;
1792
+ if (stat.size <= startOffset) continue;
1793
+
1794
+ const len = stat.size - startOffset;
1795
+ const fd = fs.openSync(filePath, "r");
1796
+ const buf = Buffer.alloc(len);
1797
+ fs.readSync(fd, buf, 0, len, startOffset);
1798
+ fs.closeSync(fd);
1799
+
1800
+ const chunkStr = buf.toString("utf8");
1801
+ const lastNewline = chunkStr.lastIndexOf("\n");
1802
+ if (lastNewline === -1) continue;
1803
+
1804
+ const completeStr = chunkStr.slice(0, lastNewline + 1);
1805
+ state.offsets[filePath] = startOffset + Buffer.byteLength(completeStr, "utf8");
1806
+
1807
+ const sessionId = path.basename(filePath, ".jsonl");
1808
+ const lines = completeStr.split(/\r?\n/);
1809
+ for (const rawLine of lines) {
1810
+ const line = rawLine.trim();
1811
+ if (!line || !line.startsWith("{")) continue;
1812
+ let entry = null;
1813
+ try {
1814
+ entry = JSON.parse(line);
1815
+ } catch {
1816
+ continue;
1817
+ }
1818
+ const evList = extractEventsFromTranscriptEntry(entry);
1819
+ for (const ev of evList) {
1820
+ if (ev.hook_event_name === "UserPromptSubmit" && ev.prompt) {
1821
+ state.lastPromptBySession[sessionId] = ev.prompt;
1822
+ }
1823
+ if (
1824
+ ev.hook_event_name === "PreToolUse" &&
1825
+ ev.tool_name &&
1826
+ HOOK_READ_ONLY_TOOLS.has(String(ev.tool_name).toLowerCase())
1827
+ ) {
1828
+ recordLocalHookDrop(estimateTokens(ev.text));
1829
+ continue;
1830
+ }
1831
+ const deltaText = String(ev.text || "").trim().slice(0, 1024);
1832
+ if (!deltaText || deltaText.length < 4) continue;
1833
+ if (!opts.apiKey) continue;
1834
+
1835
+ const promptContext = state.lastPromptBySession[sessionId] || deltaText;
1836
+ const rawTok = estimateTokens(deltaText);
1837
+ const telem = loadHookTelemetry();
1838
+
1839
+ try {
1840
+ const sessionWhispered = Array.isArray(state.whisperedBySession[sessionId])
1841
+ ? state.whisperedBySession[sessionId]
1842
+ : [];
1843
+ const resp = await apiRequest(opts, "POST", "/v1/memory/intervene", {
1844
+ hook_event_name: ev.hook_event_name,
1845
+ prompt: promptContext,
1846
+ text: deltaText,
1847
+ ...(ev.hook_event_name === "Stop" ? { last_assistant_message: deltaText } : {}),
1848
+ ...(ev.hook_event_name !== "UserPromptSubmit" && sessionWhispered.length > 0
1849
+ ? { whispered_memory_ids: sessionWhispered }
1850
+ : {}),
1851
+ tool_name: ev.tool_name || null,
1852
+ tool_input: ev.tool_input || null,
1853
+ commit_writes: true,
1854
+ user_id: opts.userId || "default",
1855
+ project_id: projectId,
1856
+ session_id: sessionId,
1857
+ });
1858
+ processedEvents += 1;
1859
+ telem.conversation_tokens_processed = (telem.conversation_tokens_processed || 0) + rawTok;
1860
+ telem.events_processed = (telem.events_processed || 0) + 1;
1861
+
1862
+ if (ev.hook_event_name === "UserPromptSubmit" && resp && resp.should_intervene) {
1863
+ const recalledIds =
1864
+ Array.isArray(resp.violated_memory_ids) && resp.violated_memory_ids.length > 0
1865
+ ? resp.violated_memory_ids
1866
+ : resp.triggered_memory_id
1867
+ ? [resp.triggered_memory_id]
1868
+ : [];
1869
+ if (recalledIds.length > 0) {
1870
+ state.whisperedBySession[sessionId] = recalledIds;
1871
+ }
1872
+ }
1873
+
1874
+ const isMidTurnBlock =
1875
+ ev.hook_event_name !== "UserPromptSubmit" &&
1876
+ Boolean(resp && resp.should_intervene && resp.intervention_message);
1877
+
1878
+ if (resp && (resp.should_write || isMidTurnBlock)) {
1879
+ const spanTok = estimateTokens(resp.extracted_write_span || deltaText);
1880
+ telem.noise_tokens_filtered =
1881
+ (telem.noise_tokens_filtered || 0) + Math.max(0, rawTok - spanTok);
1882
+ if (resp.should_write) {
1883
+ assimilatedCount += 1;
1884
+ telem.memories_assimilated = (telem.memories_assimilated || 0) + 1;
1885
+ if (resp.write_novelty_action === "SUPERSEDES") {
1886
+ telem.memories_superseded = (telem.memories_superseded || 0) + 1;
1887
+ }
1888
+ await runSyncRulesCommand({ ...opts, silent: true });
1889
+ }
1890
+ if (isMidTurnBlock) {
1891
+ intervenedCount += 1;
1892
+ telem.amnesia_episodes_intercepted = (telem.amnesia_episodes_intercepted || 0) + 1;
1893
+ const interventionRecord = {
1894
+ timestamp: Date.now(),
1895
+ session_id: sessionId,
1896
+ severity: resp.intervention_severity || "BLOCK",
1897
+ intervention_message: resp.intervention_message,
1898
+ violated_memory_ids: resp.violated_memory_ids || [],
1899
+ };
1900
+ interventions.push(interventionRecord);
1901
+ await runSyncRulesCommand({
1902
+ ...opts,
1903
+ silent: true,
1904
+ activeIntervention: resp.intervention_message,
1905
+ });
1906
+ try {
1907
+ fs.writeFileSync(
1908
+ SANDBOX_INTERVENTION_PATH,
1909
+ JSON.stringify(interventionRecord, null, 2) + "\n",
1910
+ "utf8"
1911
+ );
1912
+ } catch {
1913
+ // ignore
1914
+ }
1915
+
1916
+ const ellipsisSessionId = process.env.ELLIPSIS_SESSION_ID;
1917
+ const ellipsisToken =
1918
+ process.env.ELLIPSIS_API_TOKEN || process.env.ELLIPSIS_SESSION_TOKEN;
1919
+ const ellipsisBase = (
1920
+ process.env.ELLIPSIS_API_URL || "https://api.ellipsis.dev"
1921
+ ).replace(/\/+$/, "");
1922
+ if (ellipsisSessionId && ellipsisToken && !state.notifiedSessions[sessionId]) {
1923
+ state.notifiedSessions[sessionId] = true;
1924
+ try {
1925
+ await fetch(`${ellipsisBase}/v1/sessions/${ellipsisSessionId}/messages`, {
1926
+ method: "POST",
1927
+ headers: {
1928
+ Authorization: `Bearer ${ellipsisToken}`,
1929
+ "Content-Type": "application/json",
1930
+ },
1931
+ body: JSON.stringify({
1932
+ message: resp.intervention_message,
1933
+ }),
1934
+ });
1935
+ } catch {
1936
+ // fail-open if session follow-up API is not reachable
1937
+ }
1938
+ }
1939
+ }
1940
+ } else {
1941
+ telem.noise_tokens_filtered = (telem.noise_tokens_filtered || 0) + rawTok;
1942
+ telem.events_filtered_noise = (telem.events_filtered_noise || 0) + 1;
1943
+ }
1944
+ saveHookTelemetry(telem);
1945
+ } catch {
1946
+ // fail-open on transient API error
1947
+ }
1948
+ }
1949
+ }
1950
+ }
1951
+
1952
+ try {
1953
+ fs.writeFileSync(SANDBOX_OFFSETS_PATH, JSON.stringify(state, null, 2) + "\n", "utf8");
1954
+ } catch {
1955
+ // ignore offset persistence error
1956
+ }
1957
+
1958
+ return {
1959
+ scanned_files: files.length,
1960
+ processed_events: processedEvents,
1961
+ memories_assimilated: assimilatedCount,
1962
+ interventions_triggered: intervenedCount,
1963
+ interventions,
1964
+ };
1965
+ }
1966
+
1967
+ async function runWatchSandboxCommand(opts) {
1968
+ if (opts.isDaemon) {
1969
+ const { spawn } = require("child_process");
1970
+ const forwarded = process.argv
1971
+ .slice(2)
1972
+ .filter((a) => a !== "--daemon");
1973
+ const child = spawn(process.execPath, [__filename, ...forwarded], {
1974
+ detached: true,
1975
+ stdio: "ignore",
1976
+ env: process.env,
1977
+ });
1978
+ child.unref();
1979
+ try {
1980
+ fs.writeFileSync(SANDBOX_PID_PATH, String(child.pid) + "\n", "utf8");
1981
+ } catch {
1982
+ // ignore
1983
+ }
1984
+ if (opts.jsonOutput) {
1985
+ process.stdout.write(
1986
+ JSON.stringify({ status: "daemon_started", pid: child.pid }, null, 2) + "\n"
1987
+ );
1988
+ } else {
1989
+ console.log(`[/ ml] Started watch-sandbox background daemon (PID ${child.pid}).`);
1990
+ }
1991
+ return;
1992
+ }
1993
+
1994
+ let state = {
1995
+ offsets: {},
1996
+ lastPromptBySession: {},
1997
+ whisperedBySession: {},
1998
+ notifiedSessions: {},
1999
+ };
2000
+ if (fs.existsSync(SANDBOX_OFFSETS_PATH)) {
2001
+ try {
2002
+ const loaded = JSON.parse(fs.readFileSync(SANDBOX_OFFSETS_PATH, "utf8"));
2003
+ if (loaded && typeof loaded === "object") {
2004
+ state = {
2005
+ offsets: loaded.offsets || {},
2006
+ lastPromptBySession: loaded.lastPromptBySession || {},
2007
+ whisperedBySession: loaded.whisperedBySession || {},
2008
+ notifiedSessions: loaded.notifiedSessions || {},
2009
+ };
2010
+ }
2011
+ } catch {
2012
+ // ignore corrupt offsets file
2013
+ }
2014
+ }
2015
+
2016
+ if (opts.isOnce) {
2017
+ const res = await scanSandboxTranscriptsOnce(opts, state);
2018
+ if (opts.jsonOutput) {
2019
+ process.stdout.write(JSON.stringify(res, null, 2) + "\n");
2020
+ } else {
2021
+ console.log(
2022
+ `[/ ml] Sandbox scan complete: ${res.processed_events} event(s) evaluated, ${res.memories_assimilated} rule(s) assimilated, ${res.interventions_triggered} intervention(s) triggered.`
2023
+ );
2024
+ }
2025
+ return;
2026
+ }
2027
+
2028
+ while (true) {
2029
+ await scanSandboxTranscriptsOnce(opts, state);
2030
+ await new Promise((r) => setTimeout(r, opts.intervalMs || 1500));
2031
+ }
2032
+ }
2033
+
2034
+ function drainPendingSandboxIntervention() {
2035
+ try {
2036
+ if (!fs.existsSync(SANDBOX_INTERVENTION_PATH)) return null;
2037
+ const saved = JSON.parse(fs.readFileSync(SANDBOX_INTERVENTION_PATH, "utf8"));
2038
+ fs.unlinkSync(SANDBOX_INTERVENTION_PATH);
2039
+ if (saved && saved.intervention_message && Date.now() - Number(saved.timestamp || 0) < 600000) {
2040
+ return String(saved.intervention_message);
2041
+ }
2042
+ } catch {
2043
+ // ignore
2044
+ }
2045
+ return null;
2046
+ }
2047
+
1304
2048
  if (parsed.isInstallHooks) {
1305
2049
  installAmbientHooks(parsed.apiKey);
1306
2050
  process.exit(0);
1307
2051
  }
1308
2052
 
2053
+ if (parsed.forgetId) {
2054
+ apiRequest(parsed, "DELETE", `/v1/memories/${encodeURIComponent(parsed.forgetId)}`)
2055
+ .then((res) => {
2056
+ if (parsed.jsonOutput) {
2057
+ process.stdout.write(JSON.stringify(res || { status: "deleted" }, null, 2) + "\n");
2058
+ } else {
2059
+ console.log(`[/ ml] Deleted memory ${parsed.forgetId}.`);
2060
+ }
2061
+ process.exit(0);
2062
+ })
2063
+ .catch((err) => {
2064
+ console.error(`Error: ${err.message || err}`);
2065
+ process.exit(1);
2066
+ });
2067
+ return;
2068
+ }
2069
+
2070
+ if (parsed.isSyncRules) {
2071
+ runSyncRulesCommand(parsed)
2072
+ .then(() => process.exit(0))
2073
+ .catch(() => process.exit(0));
2074
+ return;
2075
+ }
2076
+
2077
+ if (parsed.isWatchSandbox) {
2078
+ runWatchSandboxCommand(parsed)
2079
+ .then(() => process.exit(0))
2080
+ .catch(() => process.exit(0));
2081
+ return;
2082
+ }
2083
+
1309
2084
  if (parsed.isStatus) {
1310
2085
  runStatusCommand(parsed)
1311
2086
  .then(() => process.exit(0))
@@ -1326,7 +2101,7 @@ if (parsed.isHook) {
1326
2101
  return;
1327
2102
  }
1328
2103
 
1329
- const STANDARD_TOOLS = [
2104
+ const MEMORY_TOOLS = [
1330
2105
  {
1331
2106
  name: "add_memory",
1332
2107
  description:
@@ -1338,6 +2113,30 @@ const STANDARD_TOOLS = [
1338
2113
  user_id: { type: "string" },
1339
2114
  memory_id: { type: "string" },
1340
2115
  metadata: { type: "object" },
2116
+ record_tier: { type: "string", enum: ["fact", "rule"] },
2117
+ slot_key: { type: "string" },
2118
+ scope: { type: "object" },
2119
+ },
2120
+ required: ["text"],
2121
+ },
2122
+ },
2123
+ {
2124
+ name: "add_scoped_rule",
2125
+ description:
2126
+ "Store an operational rule or constraint (Tier B) with optional negative contrastive enforcement (DO / DON'T) and execution scope.",
2127
+ inputSchema: {
2128
+ type: "object",
2129
+ properties: {
2130
+ text: { type: "string", description: "Natural language rule or constraint text" },
2131
+ rule_id: { type: "string", description: "Optional unique rule identifier" },
2132
+ do: { type: "string", description: "Positive behavior statement" },
2133
+ dont: { type: "string", description: "Negative prohibition statement" },
2134
+ scope: {
2135
+ type: "object",
2136
+ description: "Rule scope matching criteria (file_paths, tool_names, environments, git_branches)",
2137
+ },
2138
+ user_id: { type: "string" },
2139
+ metadata: { type: "object" },
1341
2140
  },
1342
2141
  required: ["text"],
1343
2142
  },
@@ -1351,10 +2150,30 @@ const STANDARD_TOOLS = [
1351
2150
  query: { type: "string" },
1352
2151
  user_id: { type: "string" },
1353
2152
  limit: { type: "integer", default: 5 },
2153
+ record_tier: { type: "string", enum: ["fact", "rule"] },
1354
2154
  },
1355
2155
  required: ["query"],
1356
2156
  },
1357
2157
  },
2158
+ {
2159
+ name: "get_cache_aligned_prompt",
2160
+ description:
2161
+ "Retrieve scoped rules and dynamic facts formatted into Zone 1 (static rules) and Zone 2 (dynamic facts) with cache breakpoint delimiter for optimal KV prefix reuse.",
2162
+ inputSchema: {
2163
+ type: "object",
2164
+ properties: {
2165
+ user_turn: { type: "string", description: "Current user prompt or task turn" },
2166
+ context: {
2167
+ type: "object",
2168
+ description: "Active environment context (file_path, tool_name, environment, git_branch)",
2169
+ },
2170
+ top_k: { type: "integer", default: 5 },
2171
+ user_id: { type: "string" },
2172
+ enable_cache_breakpoint: { type: "boolean", default: true },
2173
+ },
2174
+ required: ["user_turn"],
2175
+ },
2176
+ },
1358
2177
  {
1359
2178
  name: "get_memories",
1360
2179
  description: "List stored memories for a user or project scope.",
@@ -1377,6 +2196,9 @@ const STANDARD_TOOLS = [
1377
2196
  required: ["memory_id"],
1378
2197
  },
1379
2198
  },
2199
+ ];
2200
+
2201
+ const CODE_TOOLS = [
1380
2202
  {
1381
2203
  name: "index_repository",
1382
2204
  description:
@@ -1435,11 +2257,13 @@ const STANDARD_TOOLS = [
1435
2257
  },
1436
2258
  ];
1437
2259
 
2260
+ const STANDARD_TOOLS = [...MEMORY_TOOLS, ...CODE_TOOLS];
2261
+
1438
2262
  const CODE_MODE_TOOLS = [
1439
2263
  {
1440
2264
  name: "execute_memory_code",
1441
2265
  description:
1442
- "Compact meta-tool (91% token savings) dispatching memory & code actions (`add_memory`, `search_memories`, `get_memories`, `forget_memory`, `index_repository`, `search_code_by_behavior`, `find_bug_candidates`, `intervene_memory`) to `/ ml` Cloud.",
2266
+ "Compact meta-tool (91% token savings) dispatching memory & code actions (`add_memory`, `add_scoped_rule`, `search_memories`, `get_memories`, `get_cache_aligned_prompt`, `forget_memory`, `index_repository`, `search_code_by_behavior`, `find_bug_candidates`, `intervene_memory`) to `/ ml` Cloud.",
1443
2267
  inputSchema: {
1444
2268
  type: "object",
1445
2269
  properties: {
@@ -1447,13 +2271,16 @@ const CODE_MODE_TOOLS = [
1447
2271
  type: "string",
1448
2272
  enum: [
1449
2273
  "add_memory",
2274
+ "add_scoped_rule",
1450
2275
  "search_memories",
1451
2276
  "get_memories",
2277
+ "get_cache_aligned_prompt",
1452
2278
  "forget_memory",
1453
2279
  "index_repository",
1454
2280
  "search_code_by_behavior",
1455
2281
  "find_bug_candidates",
1456
2282
  "intervene_memory",
2283
+ "dismiss_intervention",
1457
2284
  ],
1458
2285
  },
1459
2286
  params: { type: "object" },
@@ -1642,6 +2469,12 @@ async function dispatchTool(opts, name, args = {}) {
1642
2469
 
1643
2470
  if (name === "add_memory") {
1644
2471
  const rawText = args.text !== undefined ? args.text : args.messages;
2472
+ const meta = {
2473
+ ...(args.metadata || {}),
2474
+ ...(args.record_tier ? { record_tier: String(args.record_tier) } : {}),
2475
+ ...(args.slot_key ? { slot_key: String(args.slot_key) } : {}),
2476
+ ...(args.scope ? { scope: args.scope } : {}),
2477
+ };
1645
2478
  const messagesPayload = Array.isArray(rawText)
1646
2479
  ? rawText
1647
2480
  : [
@@ -1649,14 +2482,38 @@ async function dispatchTool(opts, name, args = {}) {
1649
2482
  role: "user",
1650
2483
  content: String(rawText || ""),
1651
2484
  ...(args.memory_id ? { id: String(args.memory_id) } : {}),
1652
- ...(args.metadata ? { metadata: args.metadata } : {}),
2485
+ metadata: meta,
1653
2486
  },
1654
2487
  ];
1655
2488
  return apiRequest(opts, "POST", "/v1/memories", {
1656
2489
  messages: messagesPayload,
1657
2490
  user_id: uid,
1658
2491
  memory_id: args.memory_id,
1659
- metadata: args.metadata || {},
2492
+ metadata: meta,
2493
+ ...(args.record_tier ? { record_tier: String(args.record_tier) } : {}),
2494
+ ...(args.slot_key ? { slot_key: String(args.slot_key) } : {}),
2495
+ });
2496
+ }
2497
+ if (name === "add_scoped_rule") {
2498
+ const text = String(args.text || args.rule || "");
2499
+ const ruleId = args.rule_id || args.ruleId || `rule_${Math.floor(Math.random() * 900000 + 100000)}`;
2500
+ const contrastiveObj = args.contrastive && typeof args.contrastive === "object" ? args.contrastive : {};
2501
+ const doVal = args.do || contrastiveObj.canonical || contrastiveObj.do || text;
2502
+ const dontVal = args.dont || contrastiveObj.negative_pattern || contrastiveObj.dont || "";
2503
+ const meta = {
2504
+ ...(args.metadata || {}),
2505
+ rule_id: ruleId,
2506
+ record_tier: "rule",
2507
+ scope: args.scope || {},
2508
+ contrastive: { do: doVal, dont: dontVal },
2509
+ };
2510
+ return apiRequest(opts, "POST", "/v1/memory/ingest", {
2511
+ text,
2512
+ user_id: uid,
2513
+ record_tier: "rule",
2514
+ slot_key: args.slot_key,
2515
+ documents: [{ text, id: ruleId, user_id: uid, metadata: meta }],
2516
+ metadata: meta,
1660
2517
  });
1661
2518
  }
1662
2519
  if (name === "search_memories") {
@@ -1664,6 +2521,7 @@ async function dispatchTool(opts, name, args = {}) {
1664
2521
  const mergedFilters = {
1665
2522
  ...(args.filters && typeof args.filters === "object" ? args.filters : {}),
1666
2523
  ...(args.include_code !== undefined ? { include_code: Boolean(args.include_code) } : {}),
2524
+ ...(args.record_tier ? { record_tier: String(args.record_tier) } : {}),
1667
2525
  ...(args.kind ? { kind: String(args.kind) } : {}),
1668
2526
  };
1669
2527
  return apiRequest(opts, "POST", "/v1/memories/search", {
@@ -1674,6 +2532,84 @@ async function dispatchTool(opts, name, args = {}) {
1674
2532
  ...(Object.keys(mergedFilters).length > 0 ? { filters: mergedFilters } : {}),
1675
2533
  });
1676
2534
  }
2535
+ if (name === "get_cache_aligned_prompt") {
2536
+ const userTurn = String(args.user_turn || args.query || args.prompt || "");
2537
+ const topK = Number(args.top_k || 5);
2538
+ const resolvedContext = args.context && typeof args.context === "object"
2539
+ ? args.context
2540
+ : {
2541
+ ...(args.active_file ? { file_path: args.active_file } : {}),
2542
+ ...(args.branch ? { git_branch: args.branch } : {}),
2543
+ ...(args.env ? { environment: args.env } : {}),
2544
+ };
2545
+ const rulesRes = await apiRequest(opts, "POST", "/v1/memory/query", {
2546
+ prompt: userTurn,
2547
+ user_id: uid,
2548
+ top_k: 20,
2549
+ record_tier: "rule",
2550
+ context: resolvedContext,
2551
+ });
2552
+ const factsRes = await apiRequest(opts, "POST", "/v1/memory/query", {
2553
+ prompt: userTurn,
2554
+ user_id: uid,
2555
+ top_k: topK,
2556
+ record_tier: "fact",
2557
+ });
2558
+ const rawRules = rulesRes.results || rulesRes.memories || [];
2559
+ const rawFacts = factsRes.results || factsRes.memories || [];
2560
+ const activeRules = rawRules.map((r) => {
2561
+ const rMeta = r.metadata || {};
2562
+ const c = rMeta.contrastive || {};
2563
+ return {
2564
+ rule_id: String(r.id || rMeta.rule_id || "rule"),
2565
+ do: String(c.do || r.text || ""),
2566
+ dont: String(c.dont || ""),
2567
+ };
2568
+ });
2569
+ const zone1Lines = [];
2570
+ if (activeRules.length > 0) {
2571
+ zone1Lines.push("<rules>");
2572
+ for (const r of activeRules) {
2573
+ zone1Lines.push(` <rule id="${r.rule_id}">\n <do>${r.do}</do>\n <dont>${r.dont}</dont>\n </rule>`);
2574
+ }
2575
+ zone1Lines.push("</rules>");
2576
+ }
2577
+ const zone1Text = zone1Lines.join("\n");
2578
+ const zone2Lines = [];
2579
+ if (rawFacts.length > 0) {
2580
+ zone2Lines.push("<facts>");
2581
+ for (const f of rawFacts) {
2582
+ const t = typeof f === "string" ? f : f.text || f.memory || "";
2583
+ if (t) zone2Lines.push(` <fact>${t}</fact>`);
2584
+ }
2585
+ zone2Lines.push("</facts>");
2586
+ }
2587
+ const zone2Text = zone2Lines.join("\n");
2588
+ const enableBp = args.enable_cache_breakpoint !== false;
2589
+ const parts = [];
2590
+ if (zone1Text) parts.push(zone1Text);
2591
+ if (enableBp && zone1Text) parts.push("<!-- cache_control: ephemeral_breakpoint -->");
2592
+ if (zone2Text) parts.push(zone2Text);
2593
+ parts.push(userTurn);
2594
+ const fullPrompt = parts.filter(Boolean).join("\n\n");
2595
+ const z1Tok = zone1Text ? Math.max(1, Math.floor(zone1Text.length / 4)) : 0;
2596
+ const z2Tok = zone2Text ? Math.max(1, Math.floor(zone2Text.length / 4)) : 0;
2597
+ const uTok = Math.max(1, Math.floor(userTurn.length / 4));
2598
+ const totTok = z1Tok + z2Tok + uTok;
2599
+ return {
2600
+ full_prompt_text: fullPrompt,
2601
+ zone1_rules_text: zone1Text,
2602
+ zone2_facts_text: zone2Text,
2603
+ has_cache_breakpoint: enableBp && Boolean(zone1Text),
2604
+ token_economics: {
2605
+ zone1_tokens_estimated: z1Tok,
2606
+ zone2_tokens_estimated: z2Tok,
2607
+ user_tokens_estimated: uTok,
2608
+ total_tokens_estimated: totTok,
2609
+ prefix_cache_eligible_ratio: totTok > 0 ? Number((z1Tok / totTok).toFixed(3)) : 0.0,
2610
+ },
2611
+ };
2612
+ }
1677
2613
  if (name === "get_memories") {
1678
2614
  const paramsObj = { user_id: uid, limit: String(args.limit || 50) };
1679
2615
  if (args.include_code !== undefined) paramsObj.include_code = String(Boolean(args.include_code));
@@ -1757,6 +2693,11 @@ async function dispatchTool(opts, name, args = {}) {
1757
2693
  args.project_id || args.projectId || process.env.SLASHML_PROJECT_ID || undefined;
1758
2694
  const resolvedSessionId =
1759
2695
  args.session_id || args.sessionId || process.env.SLASHML_SESSION_ID || undefined;
2696
+ const overriddenIds = [
2697
+ ...(Array.isArray(args.overridden_memory_ids) ? args.overridden_memory_ids : []),
2698
+ ...(Array.isArray(args.dismiss_memory_ids) ? args.dismiss_memory_ids : []),
2699
+ ...(args.override_memory_id ? [String(args.override_memory_id)] : []),
2700
+ ].filter(Boolean);
1760
2701
  return apiRequest(opts, "POST", "/v1/memory/intervene", {
1761
2702
  hook_event_name: args.hook_event_name || "UserPromptSubmit",
1762
2703
  prompt: args.prompt || rawText,
@@ -1764,6 +2705,7 @@ async function dispatchTool(opts, name, args = {}) {
1764
2705
  tool_name: args.tool_name || null,
1765
2706
  tool_input: args.tool_input || null,
1766
2707
  tool_response: args.tool_response || null,
2708
+ ...(overriddenIds.length > 0 ? { overridden_memory_ids: overriddenIds } : {}),
1767
2709
  model: args.model || process.env.SLASHML_MODEL || undefined,
1768
2710
  user_id: uid,
1769
2711
  ...(resolvedProjectId ? { project_id: String(resolvedProjectId) } : {}),
@@ -1772,6 +2714,72 @@ async function dispatchTool(opts, name, args = {}) {
1772
2714
  top_k: Number(args.top_k || args.limit || 5),
1773
2715
  });
1774
2716
  }
2717
+ if (name === "dismiss_intervention") {
2718
+ const memIds = [
2719
+ ...(args.memory_id ? [String(args.memory_id)] : []),
2720
+ ...(Array.isArray(args.memory_ids) ? args.memory_ids.map(String) : []),
2721
+ ...(Array.isArray(args.overridden_memory_ids) ? args.overridden_memory_ids.map(String) : []),
2722
+ ].filter(Boolean);
2723
+ if (memIds.length === 0) {
2724
+ throw new Error("dismiss_intervention requires memory_id or memory_ids");
2725
+ }
2726
+ const reason = String(args.reason || "Dismissed false-positive intervention for session");
2727
+ const dedupPath =
2728
+ process.env.SLASHML_HOOK_STATE_PATH ||
2729
+ path.join(os.homedir(), ".slashml", "hook_state.json");
2730
+ try {
2731
+ let dedupState = { hashes: [] };
2732
+ if (fs.existsSync(dedupPath)) {
2733
+ dedupState = JSON.parse(fs.readFileSync(dedupPath, "utf8")) || { hashes: [] };
2734
+ }
2735
+ if (!dedupState.overridden_by_session || typeof dedupState.overridden_by_session !== "object") {
2736
+ dedupState.overridden_by_session = {};
2737
+ }
2738
+ const prevGlobal = Array.isArray(dedupState.overridden_by_session._global)
2739
+ ? dedupState.overridden_by_session._global
2740
+ : [];
2741
+ dedupState.overridden_by_session._global = Array.from(
2742
+ new Set([...prevGlobal, ...memIds])
2743
+ ).slice(-64);
2744
+ const sessKey = String(args.session_id || args.sessionId || process.env.SLASHML_SESSION_ID || "").trim();
2745
+ if (sessKey) {
2746
+ const prevSess = Array.isArray(dedupState.overridden_by_session[sessKey])
2747
+ ? dedupState.overridden_by_session[sessKey]
2748
+ : [];
2749
+ dedupState.overridden_by_session[sessKey] = Array.from(
2750
+ new Set([...prevSess, ...memIds])
2751
+ ).slice(-64);
2752
+ }
2753
+ fs.mkdirSync(path.dirname(dedupPath), { recursive: true });
2754
+ fs.writeFileSync(dedupPath, JSON.stringify(dedupState), "utf8");
2755
+ } catch {
2756
+ // ignore local state persistence error
2757
+ }
2758
+ const resolvedProjectId =
2759
+ args.project_id || args.projectId || process.env.SLASHML_PROJECT_ID || undefined;
2760
+ const resolvedSessionId =
2761
+ args.session_id || args.sessionId || process.env.SLASHML_SESSION_ID || undefined;
2762
+ try {
2763
+ await apiRequest(opts, "POST", "/v1/memory/intervene", {
2764
+ hook_event_name: "UserPromptSubmit",
2765
+ prompt: `Dismiss intervention for ${memIds.join(", ")}: ${reason}`,
2766
+ text: `Dismiss intervention for ${memIds.join(", ")}: ${reason}`,
2767
+ overridden_memory_ids: memIds,
2768
+ dismiss_memory_ids: memIds,
2769
+ commit_writes: false,
2770
+ user_id: uid,
2771
+ ...(resolvedProjectId ? { project_id: String(resolvedProjectId) } : {}),
2772
+ ...(resolvedSessionId ? { session_id: String(resolvedSessionId) } : {}),
2773
+ });
2774
+ } catch {
2775
+ // local hook_state override is already persisted
2776
+ }
2777
+ return {
2778
+ status: "dismissed",
2779
+ overridden_memory_ids: memIds,
2780
+ reason,
2781
+ };
2782
+ }
1775
2783
  throw new Error(`Unknown MCP tool: ${name}`);
1776
2784
  }
1777
2785
 
@@ -1831,7 +2839,7 @@ rl.on("line", (line) => {
1831
2839
  const tools = parsed.codeMode
1832
2840
  ? CODE_MODE_TOOLS
1833
2841
  : parsed.codeOnly
1834
- ? STANDARD_TOOLS.slice(4)
2842
+ ? CODE_TOOLS
1835
2843
  : parsed.passiveWrites
1836
2844
  ? STANDARD_TOOLS.filter((t) => t.name !== "add_memory")
1837
2845
  : STANDARD_TOOLS;
@@ -1841,11 +2849,16 @@ rl.on("line", (line) => {
1841
2849
  if (method === "tools/call") {
1842
2850
  try {
1843
2851
  const result = await dispatchTool(parsed, params?.name, params?.arguments);
2852
+ const contentBlocks = [{ type: "text", text: JSON.stringify(result) }];
2853
+ const pendingIntervention = drainPendingSandboxIntervention();
2854
+ if (pendingIntervention) {
2855
+ contentBlocks.push({ type: "text", text: pendingIntervention });
2856
+ }
1844
2857
  process.stdout.write(
1845
2858
  JSON.stringify({
1846
2859
  jsonrpc: "2.0",
1847
2860
  id,
1848
- result: { content: [{ type: "text", text: JSON.stringify(result) }] },
2861
+ result: { content: contentBlocks },
1849
2862
  }) + "\n"
1850
2863
  );
1851
2864
  } catch (err) {