@h-rig/memory-plugin 0.0.6-alpha.156 → 0.0.6-alpha.158

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/src/index.js CHANGED
@@ -76,11 +76,12 @@ function eventFeedbackOutcome(event) {
76
76
  }
77
77
  function normalizeStatement(statement, args) {
78
78
  if (typeof statement === "string") {
79
- return { sql: statement, args };
79
+ return { sql: statement, ...args !== undefined ? { args } : {} };
80
80
  }
81
+ const resolvedArgs = statement.args ?? args;
81
82
  return {
82
83
  sql: statement.sql,
83
- args: statement.args ?? args
84
+ ...resolvedArgs !== undefined ? { args: resolvedArgs } : {}
84
85
  };
85
86
  }
86
87
  function normalizeBindings(bindings) {
@@ -115,7 +116,7 @@ function executeSqlite(sqlite, statement, args) {
115
116
  const normalized = normalizeStatement(statement, args);
116
117
  const bindings = normalizeBindings(normalized.args);
117
118
  if (isMutationStatement(normalized.sql)) {
118
- const result = bindings.length > 0 ? sqlite.run(normalized.sql, ...bindings) : sqlite.run(normalized.sql);
119
+ const result = bindings.length > 0 ? sqlite.run(normalized.sql, bindings) : sqlite.run(normalized.sql);
119
120
  return {
120
121
  rows: [],
121
122
  rowsAffected: Number(result.changes)
@@ -876,7 +877,7 @@ function createConfiguredMemoryEmbedder(options = {}) {
876
877
  apiKey,
877
878
  model: env.RIG_MEMORY_EMBEDDING_MODEL?.trim() || DEFAULT_EMBEDDING_MODEL,
878
879
  apiBaseUrl: options.apiBaseUrl ?? env.RIG_MEMORY_EMBEDDING_API_BASE_URL?.trim() ?? DEFAULT_EMBEDDING_API_BASE_URL,
879
- fetchImpl: options.fetchImpl
880
+ ...options.fetchImpl ? { fetchImpl: options.fetchImpl } : {}
880
881
  });
881
882
  }
882
883
  function warnMissingMemoryEmbedderOnce(warn) {
@@ -952,12 +953,412 @@ var init_embed = __esm(() => {
952
953
  init_db();
953
954
  });
954
955
 
955
- // packages/memory-plugin/src/read.ts
956
- import { mkdtempSync, rmSync, writeFileSync } from "fs";
956
+ // packages/memory-plugin/src/embedded-native-assets.ts
957
+ var embeddedNatives = null;
958
+
959
+ // packages/memory-plugin/src/native-extract.ts
960
+ import { existsSync, mkdirSync as mkdirSync2, readFileSync, renameSync, statSync, writeFileSync } from "fs";
957
961
  import { tmpdir } from "os";
962
+ import { resolve } from "path";
963
+ function extractEmbeddedNative(name) {
964
+ if (name in extractionCache) {
965
+ return extractionCache[name] ?? null;
966
+ }
967
+ const entry = embeddedNatives?.[name];
968
+ if (!entry) {
969
+ extractionCache[name] = null;
970
+ return null;
971
+ }
972
+ try {
973
+ const targetPath = resolve(sharedNativeOutputDir, entry.fileName);
974
+ mkdirSync2(sharedNativeOutputDir, { recursive: true });
975
+ const upToDate = existsSync(targetPath) && statSync(targetPath).size === entry.size;
976
+ if (!upToDate) {
977
+ const bytes = readFileSync(entry.filePath);
978
+ const tempPath = `${targetPath}.${process.pid}.${Date.now()}.tmp`;
979
+ writeFileSync(tempPath, bytes, { mode: 493 });
980
+ renameSync(tempPath, targetPath);
981
+ }
982
+ extractionCache[name] = targetPath;
983
+ } catch {
984
+ extractionCache[name] = null;
985
+ }
986
+ return extractionCache[name] ?? null;
987
+ }
988
+ var sharedNativeOutputDir, extractionCache;
989
+ var init_native_extract = __esm(() => {
990
+ sharedNativeOutputDir = resolve(tmpdir(), "rig-native");
991
+ extractionCache = {};
992
+ });
993
+
994
+ // packages/memory-plugin/src/native-git.ts
995
+ import { chmodSync, copyFileSync, existsSync as existsSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync2, renameSync as renameSync2, rmSync, writeFileSync as writeFileSync2 } from "fs";
996
+ import { tmpdir as tmpdir2 } from "os";
997
+ import { dirname as dirname2, isAbsolute, resolve as resolve2 } from "path";
998
+ import { createHash as createHash2 } from "crypto";
999
+ function isTextTreeCommitUpdate(update) {
1000
+ return typeof update.content === "string";
1001
+ }
1002
+ function temporaryGitBinaryOutputPath(outputPath) {
1003
+ const suffix = process.platform === "win32" ? ".exe" : "";
1004
+ return resolve2(dirname2(outputPath), `.rig-git-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}${suffix}`);
1005
+ }
1006
+ function publishGitBinary(tempOutputPath, outputPath) {
1007
+ try {
1008
+ renameSync2(tempOutputPath, outputPath);
1009
+ } catch (error) {
1010
+ if (process.platform === "win32" && existsSync2(outputPath)) {
1011
+ rmSync(outputPath, { force: true });
1012
+ renameSync2(tempOutputPath, outputPath);
1013
+ return;
1014
+ }
1015
+ throw error;
1016
+ }
1017
+ }
1018
+ function isSharedGitNativeOutputPath(outputPath) {
1019
+ return resolve2(outputPath) === sharedGitNativeOutputPath;
1020
+ }
1021
+ function materializeFromSharedGitBinarySync(outputPath, buildKey) {
1022
+ if (isSharedGitNativeOutputPath(outputPath))
1023
+ return null;
1024
+ const sharedManifest = nativeBuildManifestPath(sharedGitNativeOutputPath);
1025
+ if (!existsSync2(sharedGitNativeOutputPath) || !hasMatchingNativeBuildManifestSync(sharedManifest, buildKey) || !binarySupportsTrackerCommandsSync(sharedGitNativeOutputPath)) {
1026
+ return null;
1027
+ }
1028
+ mkdirSync3(dirname2(outputPath), { recursive: true });
1029
+ copyFileSync(sharedGitNativeOutputPath, outputPath);
1030
+ chmodSync(outputPath, 493);
1031
+ writeFileSync2(nativeBuildManifestPath(outputPath), `${JSON.stringify({ version: 1, buildKey }, null, 2)}
1032
+ `, "utf8");
1033
+ return outputPath;
1034
+ }
1035
+ function runtimeRigGitFileName() {
1036
+ return `rig-git${process.platform === "win32" ? ".exe" : ""}`;
1037
+ }
1038
+ function rigGitSourceCandidates() {
1039
+ const execDir = process.execPath?.trim() ? dirname2(process.execPath.trim()) : "";
1040
+ const cwd = process.cwd()?.trim() || "";
1041
+ const projectRoot = process.env.PROJECT_RIG_ROOT?.trim() || "";
1042
+ const hostProjectRoot = process.env.RIG_HOST_PROJECT_ROOT?.trim() || "";
1043
+ const moduleRelativeSource = resolve2(import.meta.dir, "../native/rig-git.zig");
1044
+ return [...new Set([
1045
+ process.env.RIG_NATIVE_GIT_SOURCE?.trim() || "",
1046
+ moduleRelativeSource,
1047
+ projectRoot ? resolve2(projectRoot, "packages/memory-plugin/native/rig-git.zig") : "",
1048
+ hostProjectRoot ? resolve2(hostProjectRoot, "packages/memory-plugin/native/rig-git.zig") : "",
1049
+ cwd ? resolve2(cwd, "packages/memory-plugin/native/rig-git.zig") : "",
1050
+ execDir ? resolve2(execDir, "..", "..", "packages/memory-plugin/native/rig-git.zig") : "",
1051
+ execDir ? resolve2(execDir, "..", "native", "rig-git.zig") : ""
1052
+ ].filter(Boolean))];
1053
+ }
1054
+ function nativePackageBinaryCandidates(fromDir, fileName) {
1055
+ const candidates = [];
1056
+ let cursor = resolve2(fromDir);
1057
+ for (let index = 0;index < 8; index += 1) {
1058
+ candidates.push(resolve2(cursor, "native", `${process.platform}-${process.arch}`, fileName), resolve2(cursor, "native", `${process.platform}-${process.arch}`, "bin", fileName), resolve2(cursor, "native", fileName), resolve2(cursor, "native", "bin", fileName));
1059
+ const parent = dirname2(cursor);
1060
+ if (parent === cursor)
1061
+ break;
1062
+ cursor = parent;
1063
+ }
1064
+ return candidates;
1065
+ }
1066
+ function rigGitBinaryCandidates() {
1067
+ const execDir = process.execPath?.trim() ? dirname2(process.execPath.trim()) : "";
1068
+ const fileName = runtimeRigGitFileName();
1069
+ const explicit = process.env.RIG_NATIVE_GIT_BIN?.trim() || "";
1070
+ return [...new Set([
1071
+ explicit,
1072
+ ...nativePackageBinaryCandidates(import.meta.dir, fileName),
1073
+ execDir ? resolve2(execDir, fileName) : "",
1074
+ execDir ? resolve2(execDir, "..", fileName) : "",
1075
+ execDir ? resolve2(execDir, "..", "bin", fileName) : "",
1076
+ sharedGitNativeOutputPath
1077
+ ].filter(Boolean))];
1078
+ }
1079
+ function resolveGitSourcePath() {
1080
+ for (const candidate of rigGitSourceCandidates()) {
1081
+ if (candidate && existsSync2(candidate)) {
1082
+ return candidate;
1083
+ }
1084
+ }
1085
+ return null;
1086
+ }
1087
+ function resolveGitBinaryPath() {
1088
+ if (process.env.RIG_DISABLE_ZIG_NATIVE === "1") {
1089
+ return null;
1090
+ }
1091
+ for (const candidate of rigGitBinaryCandidates()) {
1092
+ if (candidate && existsSync2(candidate)) {
1093
+ return candidate;
1094
+ }
1095
+ }
1096
+ return null;
1097
+ }
1098
+ function preferredGitBinaryOutputPath() {
1099
+ const explicit = process.env.RIG_NATIVE_GIT_BIN?.trim() || "";
1100
+ return explicit || sharedGitNativeOutputPath;
1101
+ }
1102
+ function binarySupportsTrackerCommandsSync(binaryPath) {
1103
+ try {
1104
+ const probe = Bun.spawnSync([binaryPath, "fetch-ref", "."], {
1105
+ stdout: "pipe",
1106
+ stderr: "pipe"
1107
+ });
1108
+ const stdout = probe.stdout.toString().trim();
1109
+ const stderr = probe.stderr.toString().trim();
1110
+ if (stdout.includes('"error":"unknown command"')) {
1111
+ return false;
1112
+ }
1113
+ return probe.exitCode === 2 && stderr.includes(trackerCommandUsageProbe);
1114
+ } catch {
1115
+ return false;
1116
+ }
1117
+ }
1118
+ function nativeBuildManifestPath(outputPath) {
1119
+ return `${outputPath}.build-manifest.json`;
1120
+ }
1121
+ function hasMatchingNativeBuildManifestSync(manifestPath, buildKey) {
1122
+ if (!existsSync2(manifestPath)) {
1123
+ return false;
1124
+ }
1125
+ try {
1126
+ const manifest = JSON.parse(readFileSync2(manifestPath, "utf8"));
1127
+ return manifest.version === 1 && manifest.buildKey === buildKey;
1128
+ } catch {
1129
+ return false;
1130
+ }
1131
+ }
1132
+ function sha256FileSync(path) {
1133
+ return createHash2("sha256").update(readFileSync2(path)).digest("hex");
1134
+ }
1135
+ function ensureRigGitBinaryPathSync(outputPath = preferredGitBinaryOutputPath()) {
1136
+ if (process.env.RIG_DISABLE_ZIG_NATIVE === "1") {
1137
+ throw new Error("Zig native git is disabled via RIG_DISABLE_ZIG_NATIVE=1");
1138
+ }
1139
+ const explicitBin = process.env.RIG_NATIVE_GIT_BIN?.trim();
1140
+ if (explicitBin && existsSync2(explicitBin)) {
1141
+ return explicitBin;
1142
+ }
1143
+ const embedded = extractEmbeddedNative("rig-git");
1144
+ if (embedded) {
1145
+ return embedded;
1146
+ }
1147
+ const sourcePath = resolveGitSourcePath();
1148
+ if (!sourcePath) {
1149
+ const binaryPath = resolveGitBinaryPath();
1150
+ if (binaryPath) {
1151
+ return binaryPath;
1152
+ }
1153
+ throw new Error("rig-git.zig source file not found.");
1154
+ }
1155
+ const zigBinary = Bun.which("zig");
1156
+ if (!zigBinary) {
1157
+ throw new Error("zig is required to build native Rig git tools.");
1158
+ }
1159
+ mkdirSync3(dirname2(outputPath), { recursive: true });
1160
+ const sourceDigest = sha256FileSync(sourcePath);
1161
+ const buildKey = JSON.stringify({
1162
+ version: 1,
1163
+ zigBinary,
1164
+ platform: process.platform,
1165
+ arch: process.arch,
1166
+ sourcePath,
1167
+ sourceDigest
1168
+ });
1169
+ const manifestPath = nativeBuildManifestPath(outputPath);
1170
+ const needsBuild = !existsSync2(outputPath) || !hasMatchingNativeBuildManifestSync(manifestPath, buildKey) || !binarySupportsTrackerCommandsSync(outputPath);
1171
+ if (!needsBuild) {
1172
+ chmodSync(outputPath, 493);
1173
+ return outputPath;
1174
+ }
1175
+ const materialized = materializeFromSharedGitBinarySync(outputPath, buildKey);
1176
+ if (materialized)
1177
+ return materialized;
1178
+ const tempOutputPath = temporaryGitBinaryOutputPath(outputPath);
1179
+ const build = Bun.spawnSync([
1180
+ zigBinary,
1181
+ "build-exe",
1182
+ sourcePath,
1183
+ "-O",
1184
+ "ReleaseFast",
1185
+ `-femit-bin=${tempOutputPath}`
1186
+ ], {
1187
+ cwd: dirname2(sourcePath),
1188
+ stdout: "pipe",
1189
+ stderr: "pipe"
1190
+ });
1191
+ if (build.exitCode !== 0 || !existsSync2(tempOutputPath)) {
1192
+ const stderr = build.stderr.toString().trim();
1193
+ const stdout = build.stdout.toString().trim();
1194
+ const details = [stderr, stdout].filter(Boolean).join(`
1195
+ `);
1196
+ throw new Error(`Failed to build native Rig git tools: ${details || `zig exited with code ${build.exitCode}`}`);
1197
+ }
1198
+ chmodSync(tempOutputPath, 493);
1199
+ if (existsSync2(outputPath) && hasMatchingNativeBuildManifestSync(manifestPath, buildKey)) {
1200
+ rmSync(tempOutputPath, { force: true });
1201
+ chmodSync(outputPath, 493);
1202
+ return outputPath;
1203
+ }
1204
+ publishGitBinary(tempOutputPath, outputPath);
1205
+ if (!binarySupportsTrackerCommandsSync(outputPath)) {
1206
+ rmSync(outputPath, { force: true });
1207
+ throw new Error("Failed to build native Rig git tools: tracker command probe failed");
1208
+ }
1209
+ writeFileSync2(manifestPath, `${JSON.stringify({ version: 1, buildKey }, null, 2)}
1210
+ `, "utf8");
1211
+ return outputPath;
1212
+ }
1213
+ function gitNativeEnv() {
1214
+ const env = { ...process.env };
1215
+ const token = env.GITHUB_TOKEN?.trim() || env.GH_TOKEN?.trim() || env.RIG_GITHUB_TOKEN?.trim() || "";
1216
+ if (token) {
1217
+ env.RIG_GITHUB_TOKEN = env.RIG_GITHUB_TOKEN || token;
1218
+ env.GITHUB_TOKEN = env.GITHUB_TOKEN || token;
1219
+ env.GH_TOKEN = env.GH_TOKEN || token;
1220
+ env.GIT_TERMINAL_PROMPT = "0";
1221
+ env.GIT_CONFIG_COUNT = "2";
1222
+ env.GIT_CONFIG_KEY_0 = "credential.helper";
1223
+ env.GIT_CONFIG_VALUE_0 = "";
1224
+ env.GIT_CONFIG_KEY_1 = "credential.helper";
1225
+ env.GIT_CONFIG_VALUE_1 = '!f() { test "$1" = get || exit 0; token="${GITHUB_TOKEN:-${GH_TOKEN:-${RIG_GITHUB_TOKEN:-}}}"; test -n "$token" || exit 0; echo username=x-access-token; echo password="$token"; }; f';
1226
+ }
1227
+ return env;
1228
+ }
1229
+ function runGitNative(command, args) {
1230
+ if (process.env.RIG_DISABLE_ZIG_NATIVE === "1") {
1231
+ return { ok: false, error: "rig-git native disabled" };
1232
+ }
1233
+ const trackerCommand = command === "fetch-ref" || command === "read-blob-at-ref" || command === "write-tree-commit" || command === "push-ref-with-lease";
1234
+ let binaryPath = null;
1235
+ if (trackerCommand) {
1236
+ try {
1237
+ binaryPath = ensureRigGitBinaryPathSync(preferredGitBinaryOutputPath());
1238
+ } catch (error) {
1239
+ const message = error instanceof Error ? error.message : String(error);
1240
+ if (message.includes("rig-git.zig source file not found")) {
1241
+ return { ok: false, error: "rig-git binary not found" };
1242
+ }
1243
+ return { ok: false, error: message };
1244
+ }
1245
+ } else {
1246
+ const explicitBinaryPath = process.env.RIG_NATIVE_GIT_BIN?.trim() || "";
1247
+ binaryPath = explicitBinaryPath && existsSync2(explicitBinaryPath) ? explicitBinaryPath : !explicitBinaryPath ? resolveGitBinaryPath() : null;
1248
+ if (!binaryPath) {
1249
+ try {
1250
+ binaryPath = ensureRigGitBinaryPathSync(preferredGitBinaryOutputPath());
1251
+ } catch (error) {
1252
+ const message = error instanceof Error ? error.message : String(error);
1253
+ if (message.includes("rig-git.zig source file not found")) {
1254
+ return { ok: false, error: "rig-git binary not found" };
1255
+ }
1256
+ return { ok: false, error: message };
1257
+ }
1258
+ }
1259
+ }
1260
+ try {
1261
+ const proc = Bun.spawnSync([binaryPath, command, ...args], {
1262
+ stdout: "pipe",
1263
+ stderr: "pipe",
1264
+ env: gitNativeEnv()
1265
+ });
1266
+ if (proc.exitCode !== 0) {
1267
+ const stdoutText = proc.stdout.toString().trim();
1268
+ if (stdoutText) {
1269
+ try {
1270
+ const parsed = JSON.parse(stdoutText);
1271
+ if (!parsed.ok) {
1272
+ return parsed;
1273
+ }
1274
+ } catch {}
1275
+ }
1276
+ const errText = proc.stderr.toString().trim() || `exit code ${proc.exitCode}`;
1277
+ return { ok: false, error: errText };
1278
+ }
1279
+ const output = proc.stdout.toString().trim();
1280
+ return JSON.parse(output);
1281
+ } catch (err) {
1282
+ return { ok: false, error: String(err) };
1283
+ }
1284
+ }
1285
+ function requireGitNative(command, args) {
1286
+ const result = runGitNative(command, args);
1287
+ if (result.ok === false) {
1288
+ throw new Error(`rig-git ${command} failed: ${result.error}`);
1289
+ }
1290
+ return result;
1291
+ }
1292
+ function requireGitNativeString(command, args) {
1293
+ const result = requireGitNative(command, args);
1294
+ if ("value" in result && typeof result.value === "string") {
1295
+ return result.value;
1296
+ }
1297
+ throw new Error(`rig-git ${command} returned an unexpected result payload`);
1298
+ }
1299
+ function nativeFetchRef(repoPath, remote, branch) {
1300
+ return requireGitNativeString("fetch-ref", [repoPath, remote, branch]);
1301
+ }
1302
+ function nativeReadBlobBytesAtRef(repoPath, ref, path) {
1303
+ const requestDir = resolve2(sharedGitNativeOutputDir, "reads", `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`);
1304
+ mkdirSync3(requestDir, { recursive: true });
1305
+ const outputPath = resolve2(requestDir, "blob.bin");
1306
+ try {
1307
+ requireGitNative("read-blob-at-ref", [repoPath, ref, path, outputPath]);
1308
+ return readFileSync2(outputPath);
1309
+ } finally {
1310
+ rmSync(requestDir, { recursive: true, force: true });
1311
+ }
1312
+ }
1313
+ function serializeTreeCommitUpdates(updates) {
1314
+ return updates.map((update) => {
1315
+ if (isTextTreeCommitUpdate(update)) {
1316
+ return { path: update.path, kind: "text", content: update.content };
1317
+ }
1318
+ if (!isAbsolute(update.sourceFilePath)) {
1319
+ throw new Error("tree commit binary updates require an absolute sourceFilePath");
1320
+ }
1321
+ return { path: update.path, kind: "file", sourceFilePath: update.sourceFilePath };
1322
+ });
1323
+ }
1324
+ function buildTreeCommitUpdatesJson(updates) {
1325
+ return `${JSON.stringify(serializeTreeCommitUpdates(updates), null, 2)}
1326
+ `;
1327
+ }
1328
+ function nativeWriteTreeCommit(repoPath, baseRef, updates, message) {
1329
+ const requestDir = resolve2(sharedGitNativeOutputDir, "requests", `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`);
1330
+ mkdirSync3(requestDir, { recursive: true });
1331
+ const messagePath = resolve2(requestDir, "message.txt");
1332
+ const updatesPath = resolve2(requestDir, "updates.json");
1333
+ try {
1334
+ writeFileSync2(messagePath, message, "utf8");
1335
+ writeFileSync2(updatesPath, buildTreeCommitUpdatesJson(updates), "utf8");
1336
+ return requireGitNativeString("write-tree-commit", [repoPath, baseRef, messagePath, updatesPath]);
1337
+ } finally {
1338
+ rmSync(requestDir, { recursive: true, force: true });
1339
+ }
1340
+ }
1341
+ function nativePushRefWithLease(repoPath, localOid, remoteRef, expectedOldOid, remote = "origin") {
1342
+ return requireGitNativeString("push-ref-with-lease", [
1343
+ repoPath,
1344
+ localOid,
1345
+ remoteRef,
1346
+ expectedOldOid,
1347
+ remote
1348
+ ]);
1349
+ }
1350
+ var sharedGitNativeOutputDir, sharedGitNativeOutputPath, trackerCommandUsageProbe = "usage: rig-git fetch-ref <repo-path> <remote> <branch>";
1351
+ var init_native_git = __esm(() => {
1352
+ init_native_extract();
1353
+ sharedGitNativeOutputDir = resolve2(tmpdir2(), "rig-native");
1354
+ sharedGitNativeOutputPath = resolve2(sharedGitNativeOutputDir, `rig-git-${process.platform}-${process.arch}${process.platform === "win32" ? ".exe" : ""}`);
1355
+ });
1356
+
1357
+ // packages/memory-plugin/src/read.ts
1358
+ import { mkdtempSync, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
1359
+ import { tmpdir as tmpdir3 } from "os";
958
1360
  import { join } from "path";
959
- import { nativeFetchRef, nativeReadBlobBytesAtRef } from "@rig/runtime/control-plane/native/git-native";
960
- import { resolveMonorepoRoot } from "@rig/runtime/control-plane/native/utils";
1361
+ import { resolveCheckoutRoot as resolveMonorepoRoot } from "@rig/core/checkout-root";
961
1362
  function isMissingCanonicalMemoryBlobError(error) {
962
1363
  const message = error instanceof Error ? error.message : String(error);
963
1364
  return message.includes(`path '${CANONICAL_MEMORY_DB_PATH}' does not exist in`) || message.includes(`path '${CANONICAL_MEMORY_DB_PATH}' exists on disk, but not in`) || message.includes(`pathspec '${CANONICAL_MEMORY_DB_PATH}' did not match any file(s) known to git`);
@@ -994,7 +1395,7 @@ async function readCanonicalMemoryDb(projectRoot, deps = {}) {
994
1395
  } else {
995
1396
  try {
996
1397
  const bytes = readDeps.readBlobBytesAtRef(repoPath, baseOid, CANONICAL_MEMORY_DB_PATH);
997
- writeFileSync(dbPath, bytes);
1398
+ writeFileSync3(dbPath, bytes);
998
1399
  } catch (error) {
999
1400
  if (!isMissingCanonicalMemoryBlobError(error)) {
1000
1401
  throw error;
@@ -1021,18 +1422,18 @@ async function readCanonicalMemoryDb(projectRoot, deps = {}) {
1021
1422
  }
1022
1423
  var CANONICAL_MEMORY_DB_PATH = "rig/memory/project-memory.db", DEFAULT_READ_DEPS;
1023
1424
  var init_read = __esm(() => {
1425
+ init_native_git();
1024
1426
  init_db();
1025
1427
  DEFAULT_READ_DEPS = {
1026
1428
  fetchRef: nativeFetchRef,
1027
1429
  readBlobBytesAtRef: nativeReadBlobBytesAtRef,
1028
1430
  openMemoryDb,
1029
- makeTempDir: () => mkdtempSync(join(tmpdir(), "memory-sync-read-")),
1030
- removeDir: (path) => rmSync(path, { recursive: true, force: true })
1431
+ makeTempDir: () => mkdtempSync(join(tmpdir3(), "memory-sync-read-")),
1432
+ removeDir: (path) => rmSync2(path, { recursive: true, force: true })
1031
1433
  };
1032
1434
  });
1033
1435
 
1034
1436
  // packages/memory-plugin/src/write.ts
1035
- import { nativePushRefWithLease, nativeWriteTreeCommit } from "@rig/runtime/control-plane/native/git-native";
1036
1437
  async function promoteCanonicalMemoryEvent(projectRoot, input, deps = {}) {
1037
1438
  const writeDeps = { ...DEFAULT_WRITE_DEPS, ...deps };
1038
1439
  let lastError;
@@ -1081,6 +1482,7 @@ async function promoteCanonicalMemoryEvent(projectRoot, input, deps = {}) {
1081
1482
  }
1082
1483
  var CANONICAL_MEMORY_DB_PATH2 = "rig/memory/project-memory.db", MAX_PROMOTION_ATTEMPTS = 2, DEFAULT_WRITE_DEPS;
1083
1484
  var init_write = __esm(() => {
1485
+ init_native_git();
1084
1486
  init_db();
1085
1487
  init_embed();
1086
1488
  init_read();
@@ -1098,7 +1500,7 @@ var init_write = __esm(() => {
1098
1500
  // packages/memory-plugin/src/query.ts
1099
1501
  import {
1100
1502
  DEFAULT_RUNTIME_MEMORY_RETRIEVAL
1101
- } from "@rig/runtime/control-plane/runtime/context";
1503
+ } from "@rig/core/runtime-context";
1102
1504
  function tokenize(text) {
1103
1505
  return (text.toLowerCase().match(/[a-z0-9_./:-]+/g) ?? []).flatMap((token) => {
1104
1506
  const split = token.split(/[./:_-]+/).filter(Boolean);
@@ -1202,9 +1604,11 @@ var init_query = __esm(() => {
1202
1604
  });
1203
1605
 
1204
1606
  // packages/memory-plugin/src/cli.ts
1205
- import { existsSync } from "fs";
1607
+ import { existsSync as existsSync3 } from "fs";
1206
1608
  import { randomUUID } from "crypto";
1207
- import { NO_MATCH_RETRIEVAL_CANONICAL_KEY as NO_MATCH_RETRIEVAL_CANONICAL_KEY2 } from "@rig/contracts";
1609
+ import {
1610
+ NO_MATCH_RETRIEVAL_CANONICAL_KEY as NO_MATCH_RETRIEVAL_CANONICAL_KEY2
1611
+ } from "@rig/contracts";
1208
1612
  function takeOption(args, option) {
1209
1613
  const rest = [];
1210
1614
  let value;
@@ -1226,7 +1630,7 @@ function takeOption(args, option) {
1226
1630
  rest.push(current);
1227
1631
  }
1228
1632
  }
1229
- return { value, rest };
1633
+ return { ...value !== undefined ? { value } : {}, rest };
1230
1634
  }
1231
1635
  function usage(verb) {
1232
1636
  switch (verb) {
@@ -1278,7 +1682,7 @@ function requireRuntimeMemoryContext(runtimeContext) {
1278
1682
  }
1279
1683
  async function ensureRuntimeMemoryUsable(runtimeContext) {
1280
1684
  const memory = requireRuntimeMemoryContext(runtimeContext);
1281
- if (!existsSync(memory.hydratedPath)) {
1685
+ if (!existsSync3(memory.hydratedPath)) {
1282
1686
  throw new Error(`Shared memory database is missing: ${memory.hydratedPath}`);
1283
1687
  }
1284
1688
  const db = await openMemoryDb(memory.hydratedPath);
@@ -1354,7 +1758,7 @@ function requestedPayload(verb, mutationKind, canonicalKey, extra) {
1354
1758
  return {
1355
1759
  command: verb,
1356
1760
  mutationKind,
1357
- canonicalKey,
1761
+ ...canonicalKey !== undefined ? { canonicalKey } : {},
1358
1762
  ...extra
1359
1763
  };
1360
1764
  }
@@ -1580,19 +1984,19 @@ init_service();
1580
1984
 
1581
1985
  // packages/memory-plugin/src/plugin.ts
1582
1986
  import { definePlugin } from "@rig/core/config";
1583
- import { MEMORY_SERVICE_CAPABILITY_ID } from "@rig/contracts";
1987
+ import { defineCapability } from "@rig/core/capability";
1988
+ import { MEMORY } from "@rig/contracts";
1584
1989
  var MEMORY_PLUGIN_NAME = "@rig/memory-plugin";
1990
+ var MemoryCap = defineCapability(MEMORY);
1585
1991
  var memoryPlugin = definePlugin({
1586
1992
  name: MEMORY_PLUGIN_NAME,
1587
1993
  version: "0.0.0-alpha.1",
1588
1994
  contributes: {
1589
1995
  capabilities: [
1590
- {
1591
- id: MEMORY_SERVICE_CAPABILITY_ID,
1996
+ MemoryCap.provide(async () => (await Promise.resolve().then(() => (init_service(), exports_service))).svc, {
1592
1997
  title: "Shared project memory",
1593
- description: "Observe/recall/supersede shared project memory and hydrate runtime memory snapshots.",
1594
- run: async () => (await Promise.resolve().then(() => (init_service(), exports_service))).svc
1595
- }
1998
+ description: "Observe/recall/supersede shared project memory and hydrate runtime memory snapshots."
1999
+ })
1596
2000
  ]
1597
2001
  }
1598
2002
  });
@@ -0,0 +1,2 @@
1
+ export declare function hasEmbeddedNatives(): boolean;
2
+ export declare function extractEmbeddedNative(name: string): string | null;
@@ -0,0 +1,44 @@
1
+ // @bun
2
+ // packages/memory-plugin/src/native-extract.ts
3
+ import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "fs";
4
+ import { tmpdir } from "os";
5
+ import { resolve } from "path";
6
+
7
+ // packages/memory-plugin/src/embedded-native-assets.ts
8
+ var embeddedNatives = null;
9
+
10
+ // packages/memory-plugin/src/native-extract.ts
11
+ var sharedNativeOutputDir = resolve(tmpdir(), "rig-native");
12
+ var extractionCache = {};
13
+ function hasEmbeddedNatives() {
14
+ return embeddedNatives != null;
15
+ }
16
+ function extractEmbeddedNative(name) {
17
+ if (name in extractionCache) {
18
+ return extractionCache[name] ?? null;
19
+ }
20
+ const entry = embeddedNatives?.[name];
21
+ if (!entry) {
22
+ extractionCache[name] = null;
23
+ return null;
24
+ }
25
+ try {
26
+ const targetPath = resolve(sharedNativeOutputDir, entry.fileName);
27
+ mkdirSync(sharedNativeOutputDir, { recursive: true });
28
+ const upToDate = existsSync(targetPath) && statSync(targetPath).size === entry.size;
29
+ if (!upToDate) {
30
+ const bytes = readFileSync(entry.filePath);
31
+ const tempPath = `${targetPath}.${process.pid}.${Date.now()}.tmp`;
32
+ writeFileSync(tempPath, bytes, { mode: 493 });
33
+ renameSync(tempPath, targetPath);
34
+ }
35
+ extractionCache[name] = targetPath;
36
+ } catch {
37
+ extractionCache[name] = null;
38
+ }
39
+ return extractionCache[name] ?? null;
40
+ }
41
+ export {
42
+ hasEmbeddedNatives,
43
+ extractEmbeddedNative
44
+ };
@@ -0,0 +1,28 @@
1
+ export type PendingFile = {
2
+ path: string;
3
+ status: string;
4
+ };
5
+ export type TreeCommitUpdate = {
6
+ path: string;
7
+ content: string;
8
+ sourceFilePath?: never;
9
+ } | {
10
+ path: string;
11
+ sourceFilePath: string;
12
+ content?: never;
13
+ };
14
+ export declare function runtimeRigGitFileName(): string;
15
+ export declare function ensureRigGitBinaryPath(outputPath?: string): Promise<string>;
16
+ export declare function ensureRigGitBinaryPathSync(outputPath?: string): string;
17
+ export declare function materializeRigGitBinary(targetDir: string): Promise<string>;
18
+ export declare function nativeBranchName(repoPath: string): string | null;
19
+ export declare function nativeHeadOid(repoPath: string): string | null;
20
+ export declare function nativeChangeCount(repoPath: string): number | null;
21
+ export declare function nativePendingFiles(repoPath: string): PendingFile[] | null;
22
+ export declare function nativeFileHasChanges(repoPath: string, filePath: string): boolean | null;
23
+ export declare function nativeFetchRef(repoPath: string, remote: string, branch: string): string;
24
+ export declare function nativeReadBlobAtRef(repoPath: string, ref: string, path: string): string;
25
+ export declare function nativeReadBlobBytesAtRef(repoPath: string, ref: string, path: string): Uint8Array;
26
+ export declare function buildTreeCommitUpdatesJson(updates: TreeCommitUpdate[]): string;
27
+ export declare function nativeWriteTreeCommit(repoPath: string, baseRef: string, updates: TreeCommitUpdate[], message: string): string;
28
+ export declare function nativePushRefWithLease(repoPath: string, localOid: string, remoteRef: string, expectedOldOid: string, remote?: string): string;