open-memex
Version:
Local-first memory layer and protocol for AI coding agents. Markdown source of truth, SQLite FTS5 index, zero cloud.
139 lines (126 loc) • 7.33 kB
text/typescript
// Regression check for issue #92 (D98) — session-start injection.
// Runs against a fresh scratch home it creates itself; never touches real
// data. Usage: node --experimental-strip-types scripts/injection-check.ts
// (repo root; no OPEN_MEMEX_HOME needed — the script sets its own.)
import { execSync } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { bootstrapPlugin, injectOnce, surfaceWorkingStateOnce, MAX_INJECTION_ATTEMPTS } from "../src/plugin-core.ts";
import { buildContextBlock } from "../src/retrieve/inject.ts";
import { lastInjectionAttempt, recordInjectionAttempt } from "../src/store/injection.ts";
import { db } from "../src/store/db.ts";
import { writeWorkingState } from "../src/working-state.ts";
const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const HOME = fs.mkdtempSync(path.join(os.tmpdir(), "om-injection-"));
const PROJECT = fs.mkdtempSync(path.join(os.tmpdir(), "om-injection-proj-"));
process.env.OPEN_MEMEX_HOME = HOME;
const CLI = `node --experimental-strip-types ${path.join(REPO_ROOT, "src", "cli.ts")}`;
const CLI_ENV = { ...process.env, OPEN_MEMEX_HOME: HOME };
let fails = 0;
function check(label: string, cond: boolean, detail = ""): void {
console.log(`${cond ? "PASS" : "FAIL"} ${label}${detail ? ` — ${detail}` : ""}`);
if (!cond) fails++;
}
function add(content: string, type: string): void {
// A seed failure must say so plainly — swallowing CLI output turns it
// into a confusing downstream failure (review Minor 3).
try {
execSync(`${CLI} add ${JSON.stringify(content)} --scope personal --type ${type}`, {
env: CLI_ENV,
stdio: "pipe",
});
} catch (err) {
const e = err as { stderr?: Buffer };
throw new Error(`seed failed for ${JSON.stringify(content)}: ${e.stderr?.toString().trim() ?? String(err)}`);
}
}
/** Run a CLI verb, tolerating a non-zero exit (doctor FAILs by design). */
function runCli(...args: string[]): string {
try {
return execSync(`${CLI} ${args.join(" ")}`, { env: CLI_ENV, encoding: "utf8" });
} catch (err) {
return (err as { stdout?: string }).stdout ?? "";
}
}
// Seed the #92 shape: oldest preference + 5 newer facts (cap is 5).
add("Respond to the user in Chinese; write all documentation and code in English", "preference");
add("Prefers concise diffs over long explanations", "fact");
add("Standup is at 9:30 on weekdays", "fact");
add("Uses pnpm for JavaScript projects", "fact");
add("Lives in the America/New_York timezone", "fact");
add("Drinks black coffee, no sugar", "fact");
const state = bootstrapPlugin(PROJECT);
const pref = "Respond to the user in Chinese";
// A: a transient first-turn failure must NOT lose the session.
const pushed: string[] = [];
const throwingPush = (_b: string): void => { throw new Error("simulated ev.system.push failure"); };
const workingPush = (b: string): void => { pushed.push(b); };
check("first injectOnce (throwing push) returns false", injectOnce("sess-A", state, throwingPush) === false);
check("second injectOnce (working push) retries and returns true", injectOnce("sess-A", state, workingPush) === true);
check("block was pushed on retry", pushed.length === 1);
check("retried block contains the oldest preference", pushed[0]?.includes(pref) ?? false);
// A: the persistent record names the latest attempt.
const lastAfterRetry = lastInjectionAttempt();
check(
"last injection attempt recorded and ok",
lastAfterRetry !== null && lastAfterRetry.ok === true,
lastAfterRetry ? `ok=${lastAfterRetry.ok} profile=${lastAfterRetry.profileCount} project=${lastAfterRetry.projectCount}` : "none",
);
// A: retry cap — failures, then the session gives up.
const state2 = bootstrapPlugin(PROJECT);
const results: boolean[] = [];
for (let i = 0; i < 4; i++) results.push(injectOnce("sess-B", state2, throwingPush));
check(
`failure cap is ${MAX_INJECTION_ATTEMPTS} (attempts: ${results.join(",")})`,
results.join(",") === "false,false,false,false" &&
// Cap exhaustion moves the session to the done set and drops the
// failure count (review Minor 5) — deleting the count alone would
// reset the cap, so the done set is what remembers the give-up.
state2.injectedSessions.has("sess-B") &&
!state2.injectionFailures.has("sess-B"),
);
const lastAfterCap = lastInjectionAttempt();
check(
"last attempt after the cap is the recorded failure",
lastAfterCap !== null && lastAfterCap.ok === false && lastAfterCap.sessionId === "sess-B",
lastAfterCap ? `ok=${lastAfterCap.ok} session=${lastAfterCap.sessionId} error=${lastAfterCap.error}` : "none",
);
// D98 surfaces: doctor + sync-status render the last (failed) attempt.
const doctorOut = runCli("doctor");
check(
"doctor renders the last injection line",
doctorOut.includes("last injection") && doctorOut.includes("FAILED"),
doctorOut.split("\n").find((l) => l.includes("last injection"))?.trim() ?? "no line",
);
const statusOut = runCli("sync-status");
check(
"sync-status renders the last injection line",
statusOut.includes("Last injection:") && statusOut.includes("FAILED"),
statusOut.split("\n").find((l) => l.includes("Last injection"))?.trim() ?? "no line",
);
// A: the working-state note gets the same retry discipline.
const state3 = bootstrapPlugin(PROJECT);
writeWorkingState(state3.scope.key, "resume the deploy; run smoke tests", 7, []);
const wstatePushed: string[] = [];
check("working-state first surfacing (throwing push) returns false", surfaceWorkingStateOnce("sess-C", state3, throwingPush) === false);
check("working-state retry (working push) returns true", surfaceWorkingStateOnce("sess-C", state3, (b) => { wstatePushed.push(b); }) === true);
check("retried working-state note contains the seeded text", wstatePushed[0]?.includes("resume the deploy") ?? false);
// Prune-to-20 + 240-char error truncation.
for (let i = 0; i < 24; i++) {
recordInjectionAttempt({ sessionId: `sess-prune-${i}`, atMs: Date.now(), ok: true, profileCount: 0, projectCount: 0, error: null });
}
recordInjectionAttempt({ sessionId: "sess-long-error", atMs: Date.now(), ok: false, profileCount: 0, projectCount: 0, error: "x".repeat(500) });
const rowCount = (db().prepare("SELECT COUNT(*) AS n FROM injection_attempts").get() as { n: number }).n;
check("injection_attempts prunes to the newest 20 rows", rowCount === 20, `rows=${rowCount}`);
const lastLong = lastInjectionAttempt();
check("stored error truncates to 240 chars", lastLong !== null && (lastLong.error?.length ?? 0) === 240, `len=${lastLong?.error?.length}`);
// B: preferences first + disclosure.
const built = buildContextBlock(state.scope, state.cfg);
check("block built", built !== null);
check("oldest preference is in the block", built?.block.includes(pref) ?? false);
check("disclosure names the 1 hidden memory", built?.block.includes("1 more personal memory not shown") ?? false);
check("profile count is 5 (cap)", built?.profileCount === 5, `profileCount=${built?.profileCount}`);
console.log(fails === 0 ? "ALL PASS" : `${fails} FAILURES`);
process.exit(fails === 0 ? 0 : 1);