Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : SP Wallet8 * File : services/research-runner/src/ledger.ts9 * Module : services10 * Repository : https://git.spboucher.ai/sp-wallet11 * Project Website : https://wallet.spboucher.ai12 * Created : 2026-11-1113 * Last Modified : 2026-11-1114 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: support@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243// The trial ledger of a job, seen from outside the agent.44//45// The laboratory (spq.research.Experiment, SPQ_JOB_LEDGER) appends one JSON line per trial and per look at the inner test46// split to a file INSIDE the job directory — the agent's processes must be able to write it. This class copies every complete47// line, as it appears, into a file in the runner's own state directory, which the sandbox profile does not let the agent48// read or write. The copy is append-only: it never shrinks, whatever happens to the agent's file. If the agent's file is49// truncated or rewritten, that is recorded (`tampered`) and everything in the new file counts again as new lines.50import { appendFileSync, closeSync, existsSync, fstatSync, openSync, readSync, writeFileSync } from 'node:fs';5152const TAIL = 64, MAX_LINE = 4000;5354export class LedgerTail {55 private offset = 0;56 private last = Buffer.alloc(0);57 private carry = '';58 lines = 0;59 bytes = 0;60 tampered = false;61 private readonly source: string;62 private readonly copy: string;63 private readonly maxBytes: number;6465 constructor(source: string, copy: string, maxBytes: number) {66 this.source = source; this.copy = copy; this.maxBytes = maxBytes;67 writeFileSync(copy, '', { flag: 'a', mode: 0o600 });68 }6970 /** Copy what is new. Returns the number of lines added. Never throws on a missing or odd source file. */71 sync(): number {72 if (!existsSync(this.source)) { if (this.offset > 0) this.reset(); return 0; }73 let fd: number;74 try { fd = openSync(this.source, 'r'); } catch { return 0; }75 try {76 const st = fstatSync(fd);77 if (!st.isFile()) return 0;78 if (st.size < this.offset) this.reset();79 else if (this.last.length) {80 // the bytes just before our position must still be the ones we copied: otherwise the file was rewritten in place81 const probe = Buffer.alloc(this.last.length);82 readSync(fd, probe, 0, probe.length, this.offset - probe.length);83 if (!probe.equals(this.last)) this.reset();84 }85 let added = 0;86 const buf = Buffer.alloc(64 * 1024);87 for (;;) {88 const n = readSync(fd, buf, 0, buf.length, this.offset);89 if (n <= 0) break;90 this.offset += n;91 this.last = Buffer.concat([this.last, buf.subarray(0, n)]).subarray(-TAIL);92 const parts = (this.carry + buf.subarray(0, n).toString('utf8')).split('\n');93 this.carry = parts.pop() ?? '';94 if (this.carry.length > MAX_LINE * 4) this.carry = this.carry.slice(0, MAX_LINE * 4); // an endless line is cut, not buffered for ever95 for (const raw of parts) {96 if (!raw.trim()) continue;97 const line = raw.length > MAX_LINE ? JSON.stringify({ kind: 'oversized', bytes: raw.length }) : raw;98 this.lines += 1; added += 1;99 if (this.bytes + line.length + 1 <= this.maxBytes) { appendFileSync(this.copy, line + '\n'); this.bytes += line.length + 1; }100 }101 }102 return added;103 } finally { closeSync(fd); }104 }105106 private reset(): void { this.tampered = true; this.offset = 0; this.last = Buffer.alloc(0); this.carry = ''; }107}108