/** * 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 */ import type {IHeapEdge, IHeapNode} from '@memlab/core'; import {createHash} from 'crypto'; import fs from 'fs'; import os from 'os'; import path from 'path'; import {getSnapshotMetadata} from './heap-state.js'; import {lastSnapshotReadInScope, noteRoundPath} from './read-scope.js'; import { recordsDir, recordUploadCommand, scheduleRecordUpload, } from './record-upload.js'; import {SERVER_VERSION} from './server-version.js'; /** * Machine-readable records of a session, for a program that wraps the server * and keeps what each tool concluded. * * Records go to `MEMLAB_RECORD_FILE` when it names a file (`memlab-cli * --record ` sets it). On a host with a records uploader (see * `recordUploadCommand`) they also always go to a file of this process in the * records directory, whatever launched the server, so every session's rounds * are uploaded: a file named outside that directory gets a copy there. Each * recording tool appends one JSON line, and every tool call appends a * `tool_call` line with its duration and whether it failed. The tool's answer * is the same either way. * * Each record names the round it belongs to: the directory of the snapshot * ladder the call read, as a hash of host and path, plus the directory's name * and the `app` and `combos` of its `run.json`. A wrapper groups records into * rounds by that hash. * * A record holds verdicts, counts, class names and that round summary. It * never holds snapshot paths, string contents or the answer text. The one * kind with prose, `finding_note`, holds only what the agent wrote about a * finding, after `scrubNote` has hashed what it quoted. */ /** Bumped when a field changes meaning or goes away; new fields keep it. */ export const RECORD_CONTRACT_VERSION = 1; export type RecordKind = | 'round_audit' | 'leak_report' | 'verify_fix' | 'finding_check' | 'optimization' | 'retainer_trace' | 'finding_note' | 'tool_call'; export interface RecordRound { key: string; label: string | null; app: string | null; combos: string[]; } export interface SessionRecord { contract: number; tool: string; kind: RecordKind; at: string; server_version: string; round?: RecordRound; data: Record; } /** `MEMLAB_RECORD_FILE`, when set. */ export function recordFile(): string | null { const file = process.env.MEMLAB_RECORD_FILE; return file != null && file !== '' ? file : null; } let ownFile: {dir: string; file: string} | null = null; /** * The last creation failure reported (directory, call and error code), so a * retry that fails alike stays quiet although the file name it tried differs. */ let ownFileError: string | null = null; /** * This process's file in the records directory, created owner-only once. * A failed creation is retried on the next record, so one transient error * (ENOSPC, a network filesystem hiccup) does not end recording. */ function ownRecordFile(dir: string): string | null { if (ownFile?.dir === dir) return ownFile.file; try { fs.mkdirSync(dir, {recursive: true, mode: 0o700}); const stamp = new Date().toISOString().replace(/[-:]/g, '').slice(0, 15); const file = path.join(dir, `${stamp}Z-${process.pid}.jsonl`); fs.closeSync(fs.openSync(file, 'a', 0o600)); ownFile = {dir, file}; ownFileError = null; return file; } catch (err) { const message = `could not create a session-record file in ${dir}: ${err instanceof Error ? err.message : String(err)}`; const {syscall, code} = (err ?? {}) as NodeJS.ErrnoException; const key = code != null ? `${dir}\0${syscall ?? ''}\0${code}` : `${dir}\0${message}`; if (key !== ownFileError) console.error(`memlab: ${message}`); ownFileError = key; return null; } } function isInside(file: string, dir: string): boolean { const rel = path.relative(dir, path.resolve(file)); return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel); } /** * Every file a record goes to: `MEMLAB_RECORD_FILE`, plus this process's file * in the records directory when the host has an uploader and that file is not * already inside it. */ export function recordFiles(): string[] { const named = recordFile(); const files = named != null ? [named] : []; if (recordUploadCommand() != null) { const dir = recordsDir(); if (named == null || !isInside(named, dir)) { const own = ownRecordFile(dir); if (own != null) files.push(own); } } return files; } /** For tests: forget this process's records file. */ export function resetRecordFilesForTests(): void { ownFile = null; ownFileError = null; } /** * Append one record when recording is on. Never throws: a record that cannot * be written is reported on stderr, and the wrapper, which knows which tools * it called, treats the missing line as a failed session. */ export function noteRecord( tool: string, kind: RecordKind, data: Record, ): void { const files = recordFiles(); if (files.length === 0) { return; } const round = currentRound(); const record: SessionRecord = { contract: RECORD_CONTRACT_VERSION, tool, kind, at: new Date().toISOString(), server_version: SERVER_VERSION, ...(round != null ? {round} : {}), data, }; const line = JSON.stringify(record) + '\n'; let written = false; for (const file of files) { try { fs.appendFileSync(file, line); written = true; } catch (err) { console.error( `memlab: could not write the ${tool} record to ${file}: ${err instanceof Error ? err.message : String(err)}`, ); } } // A report closes a round's analysis; per-call lines alone are not worth // an upload. if (written && kind !== 'tool_call') scheduleRecordUpload(); } function shortHash(text: string): string { return createHash('sha256').update(text).digest('hex').slice(0, 12); } /** Node types whose whole name is a value: a string, a regexp's source, a symbol's description, a number. */ const VALUE_NAMED_TYPE = /string|^regexp$|^symbol$|^number$|^bigint$/i; /** A URL in a name: `Window / https://…`, `system / NativeContext / blob:…`. */ const NAME_URL = /\b(?:[a-z][a-z0-9+.-]*:\/\/|(?:about|blob|data|file|javascript|mailto):)[^\s"'<>]*/gi; /** An attribute value in a DOM node's name (`
`). */ const NAME_ATTRIBUTE = /="([^"]*)"/g; const CSS_TOKEN = /^-?[A-Za-z_][\w-]{0,63}$/; /** * A heap class name fit for a record. For a node whose name is a value (a * string's content, a regexp's source) the label is a short hash: still the * same across sessions, so two runs can be matched on it. In any other name, * a URL and an attribute value that is not a plain class token are hashed * the same way, so `Window / ` keeps `Window`. */ export function recordLabel(name: string, type: string): string { if (VALUE_NAMED_TYPE.test(type)) { const kind = /string/i.test(type) ? 'string' : type.toLowerCase(); return `(${kind} ${shortHash(name)})`; } const scrubbed = name .replace(NAME_ATTRIBUTE, (_, value: string) => { const tokens = value .split(/\s+/) .filter(Boolean) .map(token => CSS_TOKEN.test(token) && !DATA_SHAPED.test(token) ? token : `(value ${shortHash(token)})`, ); return `="${tokens.join(' ')}"`; }) .replace(NAME_URL, url => `(url ${shortHash(url)})`); return scrubbed.length > 200 ? `${scrubbed.slice(0, 199)}…` : scrubbed; } const IDENTIFIER = /^[A-Za-z_$][\w$]{0,63}$/; /** A run of digits or of hex in an identifier: an id or a token used as a key. */ const DATA_SHAPED = /\d{4}|[0-9a-f]{16}/i; /** * Element indices below this stay. An object keyed by an integer id (a phone * number, an FBID) stores it as an element, so a larger index can be data. */ const RECORD_INDEX_MAX = 65_536; /** * An edge name fit for a record. A small index or a code identifier * (`_listeners`, `next`) stays, since it is what a reader fixes. Anything * else is a key of an object used as a dictionary, which can be data (a chat * id, a URL, `user_8812`), so it becomes a short hash, still the same across * sessions. */ export function recordEdge(name: string | number): string { const text = String(name); const kept = typeof name === 'number' ? Number.isInteger(name) && name >= 0 && name < RECORD_INDEX_MAX : IDENTIFIER.test(text) && !DATA_SHAPED.test(text); if (kept) return text; return `(key ${shortHash(text)})`; } /** One hop of a recorded retainer path; `edge` is the edge into the next hop. */ export interface RecordHop { name: string; type: string; edge?: string; edge_type?: string; } /** Hops a recorded path keeps: the root end for context, the rest nearest the object. */ const RECORD_PATH_ROOT_HOPS = 3; const RECORD_PATH_MAX = 16; /** * A retainer path fit for a record, root first and the retained object last, * from `[{node, edgeName, edgeType}]` in that order. Labels go through * `recordLabel` and edges through `recordEdge`. A longer chain keeps its first * hops and the hops nearest the object, and says how many it left out. */ export function recordPath( items: ReadonlyArray<{ node: {name: string; type: string}; edgeName?: string | number; edgeType?: string; }>, ): {path: RecordHop[]; elided: number} { const hops = items.map(item => ({ name: recordLabel(item.node.name, item.node.type), type: item.node.type, ...(item.edgeName != null ? {edge: recordEdge(item.edgeName), edge_type: item.edgeType ?? ''} : {}), })); if (hops.length <= RECORD_PATH_MAX) return {path: hops, elided: 0}; const tail = RECORD_PATH_MAX - RECORD_PATH_ROOT_HOPS; return { path: [...hops.slice(0, RECORD_PATH_ROOT_HOPS), ...hops.slice(-tail)], elided: hops.length - RECORD_PATH_MAX, }; } /** `node`'s shortest path from a GC root, as `recordPath` items, root first. */ export function shortestPathItems(node: IHeapNode): Array<{ node: IHeapNode; edgeName?: string | number; edgeType?: string; }> { const items: Array<{ node: IHeapNode; edgeName?: string | number; edgeType?: string; }> = [{node}]; const visited = new Set([node.id]); let cur: IHeapNode | null = node; while (cur != null && cur.hasPathEdge) { const edge: IHeapEdge | null = cur.pathEdge; if (edge == null) break; const from: IHeapNode = edge.fromNode; if (visited.has(from.id)) break; visited.add(from.id); items.push({node: from, edgeName: edge.name_or_index, edgeType: edge.type}); cur = from; } return items.reverse(); } /** * Run one tool call and, when recording is on, append its `tool_call` record. * A call that throws (a timeout, say) is recorded as an error and rethrown. * The round its parameters name counts as read, so a tool that loads rungs * without noting them still names its round; files it reads take precedence. */ export async function withToolCallRecord( tool: string, params: unknown, call: () => Promise, ): Promise { if (recordFiles().length === 0) { return call(); } const pointed = roundPathOfParams(params); if (pointed != null) { noteRoundPath(pointed); } const started = Date.now(); let isError = true; try { const result = await call(); isError = (result as {isError?: unknown} | null)?.isError === true; return result; } finally { noteRecord(tool, 'tool_call', { ms: Date.now() - started, is_error: isError, }); } } /** * The file a call's parameters point at: its round's `run.json` for `run_dir`, * else the last of `after_paths` or `paths`, else `file_path`. */ function roundPathOfParams(params: unknown): string | null { if (params == null || typeof params !== 'object') { return null; } const {run_dir, after_paths, paths, file_path} = params as Record< string, unknown >; if (typeof run_dir === 'string' && run_dir !== '') { return run_dir.endsWith('.json') ? run_dir : path.join(run_dir, 'run.json'); } for (const list of [after_paths, paths]) { const last = Array.isArray(list) ? list.at(-1) : undefined; if (typeof last === 'string' && last !== '') { return last; } } return typeof file_path === 'string' && file_path !== '' ? file_path : null; } /** A rung's round: its directory, or the one above a `snapshots/` directory. */ export function roundDirOf(filePath: string): string { const dir = path.dirname(path.resolve(filePath)); return path.basename(dir) === 'snapshots' ? path.dirname(dir) : dir; } const MAX_LABEL_CHARS = 64; const MAX_COMBO_CHARS = 128; const MAX_COMBOS = 20; function cleanName(value: unknown, maxChars: number): string | null { if (typeof value !== 'string') { return null; } const name = value.replace(/[^A-Za-z0-9._-]/g, '_').slice(0, maxChars); return name === '' ? null : name; } interface RoundManifest { mtimeMs: number; app: string | null; combos: string[]; } const manifests = new Map(); /** `app` and `combos` from the round's `run.json`, re-read when it changes. */ function readManifest(dir: string): Omit { const file = path.join(dir, 'run.json'); let mtimeMs: number; try { mtimeMs = fs.statSync(file).mtimeMs; } catch { return {app: null, combos: []}; } const cached = manifests.get(dir); if (cached != null && cached.mtimeMs === mtimeMs) { return cached; } let app: string | null = null; let combos: string[] = []; try { const manifest = JSON.parse(fs.readFileSync(file, 'utf8')) as { app?: unknown; combos?: unknown; config?: {combos?: unknown} | null; }; app = cleanName(manifest.app, MAX_LABEL_CHARS); // hunt_runner writes the combos under `config`. const named = manifest.combos ?? manifest.config?.combos; if (Array.isArray(named)) { combos = named .map(combo => cleanName(combo, MAX_COMBO_CHARS)) .filter((combo): combo is string => combo != null) .slice(0, MAX_COMBOS); } } catch { // An unreadable or half-written manifest leaves the round unnamed. } const entry = {mtimeMs, app, combos}; manifests.set(dir, entry); return entry; } export function roundOf(dir: string): RecordRound { const key = createHash('sha256') .update(`${os.hostname()}\0${dir}`) .digest('hex') .slice(0, 16); const {app, combos} = readManifest(dir); return { key, label: cleanName(path.basename(dir), MAX_LABEL_CHARS), app, combos, }; } /** * The round of the snapshot the current call read last, else of the resident * snapshot; none when the call touched no snapshot. */ function currentRound(): RecordRound | undefined { const file = lastSnapshotReadInScope() ?? getSnapshotMetadata()?.filePath ?? null; return file == null ? undefined : roundOf(roundDirOf(file)); }