/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format * @oncall memory_lab */ /** * Imported first by every test script (and `--import`ed by `node --test`), so * a test run never writes into the user's own state: on a host with the Meta * CLI the server records every session into `~/.memlab-mcp/records` and * uploads it, and a test's fixture rounds would land in the runs app as real * runs. * * The run gets a fresh HOME, which every default location follows (records, * findings index, round index, job state), the variables that point * somewhere else are dropped so those defaults apply, and a `meta` on the * PATH is hidden so nothing is uploaded: a directory holding one is replaced * by a copy of it, made of links to everything else in it. Child processes * inherit all of it. A test that needs one of these sets its own. The * process that made the HOME removes it when it exits. */ import fs from 'fs'; import os from 'os'; import path from 'path'; const MARK = 'MEMLAB_TEST_HOME'; const UPLOADER = 'meta'; function isExecutableFile(file) { try { if (!fs.statSync(file).isFile()) return false; fs.accessSync(file, fs.constants.X_OK); return true; } catch { return false; } } /** `dir` without its `meta`: a directory under `home` linking to the rest. */ function withoutUploader(dir, home, n) { const copy = path.join(home, '.path', String(n)); fs.mkdirSync(copy, {recursive: true}); for (const name of fs.readdirSync(dir)) { if (name === UPLOADER) continue; try { fs.symlinkSync(path.join(dir, name), path.join(copy, name)); } catch { // Unreadable or racing entry: left out. } } return copy; } const POINTERS = [ 'MEMLAB_RECORDS_DIR', 'MEMLAB_RECORD_FILE', 'MEMLAB_RECORD_UPLOAD_CMD', 'MEMLAB_FINDINGS_INDEX', 'MEMLAB_STATE_DIR', 'MEMLAB_UPLOAD_STATUS_FILE', ]; if ( process.env[MARK] == null || process.env[MARK] !== process.env.HOME || !fs.existsSync(process.env[MARK]) ) { const realHome = os.homedir(); const home = fs.mkdtempSync(path.join(os.tmpdir(), 'memlab-test-home-')); process.on('exit', () => fs.rmSync(home, {recursive: true, force: true})); process.env.HOME = home; process.env[MARK] = home; for (const k of POINTERS) delete process.env[k]; process.env.PATH = (process.env.PATH ?? '') .split(path.delimiter) .map((dir, n) => dir !== '' && isExecutableFile(path.join(dir, UPLOADER)) ? withoutUploader(dir, home, n) : dir, ) .join(path.delimiter); if (os.homedir() !== home || os.homedir() === realHome) { console.error( `test-isolation: HOME did not take effect (home is still ${os.homedir()}); refusing to run tests against it.`, ); process.exit(1); } }