Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

chore: files changed scripts/__tests__/process-statics.test.mjs,scripts/ci/check-process-statics.mjs

Steven Enamakel950626fb8fd4
diff --git a/scripts/__tests__/process-statics.test.mjs b/scripts/__tests__/process-statics.test.mjs
index 848680ea7a..e89a20d8e9 100644
--- a/scripts/__tests__/process-statics.test.mjs
+++ b/scripts/__tests__/process-statics.test.mjs
@@ -1,75 +1,161 @@
-import assert from 'node:assert/strict';
-import test from 'node:test';
-import { execFileSync } from 'node:child_process';
-import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
-import { declarations, reviewChanges, checkRepository } from '../ci/check-process-statics.mjs';
+import assert from "node:assert/strict";
+import test from "node:test";
+import { execFileSync } from "node:child_process";
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import {
+ declarations,
+ reviewChanges,
+ checkRepository,
+} from "../ci/check-process-statics.mjs";
-const file = 'crates/openhuman-core/src/example/ops.rs';
-const source = 'static CACHE: OnceLock<Mutex<Map>> = OnceLock::new();';
+const file = "crates/openhuman-core/src/example/ops.rs";
+const source = "static CACHE: OnceLock<Mutex<Map>> = OnceLock::new();";
const entry = {
- file, name: 'CACHE', type: 'OnceLock<Mutex<Map>>', count: 1,
- category: 'B', reason: 'Keys include the authenticated profile.',
- verification: 'example/ops_tests.rs: profiles_cannot_share_cache',
+ file,
+ name: "CACHE",
+ type: "OnceLock<Mutex<Map>>",
+ count: 1,
+ category: "B",
+ reason: "Keys include the authenticated profile.",
+ verification: "example/ops_tests.rs: profiles_cannot_share_cache",
};
const scan = (text) => declarations(text, file);
-test('finds multiline, qualified, mutable and lazy_static declarations', () => {
- assert.deepEqual(scan('static CACHE:\n std::sync::OnceLock<Mutex<Map>> = x;\nstatic mut FLAG: bool = false;\nlazy_static! { static ref OTHER: Alias = x; }').map(({name,type}) => ({name,type})), [
- {name:'CACHE',type:'std::sync::OnceLock<Mutex<Map>>'},
- {name:'FLAG',type:'mut bool'}, {name:'OTHER',type:'ref Alias'},
- ]);
+test("finds multiline, qualified, mutable and lazy_static declarations", () => {
+ assert.deepEqual(
+ scan(
+ "static CACHE:\n std::sync::OnceLock<Mutex<Map>> = x;\nstatic mut FLAG: bool = false;\nlazy_static! { static ref OTHER: Alias = x; }",
+ ).map(({ name, type }) => ({ name, type })),
+ [
+ { name: "CACHE", type: "std::sync::OnceLock<Mutex<Map>>" },
+ { name: "FLAG", type: "mut bool" },
+ { name: "OTHER", type: "ref Alias" },
+ ],
+ );
});
-test('ignores comments and quoted Rust fixtures', () => {
- assert.deepEqual(scan('// '+source+'\n/* outer /* '+source+' */ */\nconst S: &str = r###"'+source+'"###;'), []);
+test("ignores comments and quoted Rust fixtures", () => {
+ assert.deepEqual(
+ scan(
+ "// " +
+ source +
+ "\n/* outer /* " +
+ source +
+ ' */ */\nconst S: &str = r###"' +
+ source +
+ '"###;',
+ ),
+ [],
+ );
});
-test('unreviewed new statics fail even when their type hides a mutex', () => {
- assert.equal(reviewChanges([], scan('static CACHE: Alias = x;'), []).length, 1);
+test("unreviewed new statics fail even when their type hides a mutex", () => {
+ assert.equal(
+ reviewChanges([], scan("static CACHE: Alias = x;"), []).length,
+ 1,
+ );
});
-test('unchanged existing statics need no retrospective approval', () => {
+test("unchanged existing statics need no retrospective approval", () => {
assert.deepEqual(reviewChanges(scan(source), scan(source), []), []);
});
-test('a new declaration passes with an exact ownership record', () => {
+test("a new declaration passes with an exact ownership record", () => {
assert.deepEqual(reviewChanges([], scan(source), [entry]), []);
});
-test('type changes and duplicate declarations require a matching record', () => {
- assert.equal(reviewChanges(scan(source), scan(source.replace('Map', 'Other')), [entry]).length > 0, true);
- assert.equal(reviewChanges(scan(source), scan(source+'\nmod nested { '+source+' }'), [entry]).length > 0, true);
+test("type changes and duplicate declarations require a matching record", () => {
+ assert.equal(
+ reviewChanges(scan(source), scan(source.replace("Map", "Other")), [entry])
+ .length > 0,
+ true,
+ );
+ assert.equal(
+ reviewChanges(
+ scan(source),
+ scan(source + "\nmod nested { " + source + " }"),
+ [entry],
+ ).length > 0,
+ true,
+ );
});
-test('removed or mismatched approvals fail', () => {
+test("removed or mismatched approvals fail", () => {
assert.equal(reviewChanges([], [], [entry]).length > 0, true);
- assert.equal(reviewChanges([], scan(source), [{...entry, count:2}]).length > 0, true);
+ assert.equal(
+ reviewChanges([], scan(source), [{ ...entry, count: 2 }]).length > 0,
+ true,
+ );
});
-test('classification, reason and verification are mandatory', () => {
- for (const patch of [{category:'Z'}, {reason:''}, {verification:''}]) {
- assert.equal(reviewChanges([], scan(source), [{...entry,...patch}]).length > 0, true);
+test("classification, reason and verification are mandatory", () => {
+ for (const patch of [
+ { category: "Z" },
+ { reason: "" },
+ { verification: "" },
+ ]) {
+ assert.equal(
+ reviewChanges([], scan(source), [{ ...entry, ...patch }]).length > 0,
+ true,
+ );
}
});
-test('duplicate approval records fail', () => {
- assert.equal(reviewChanges([], scan(source), [entry,entry]).length > 0, true);
+test("duplicate approval records fail", () => {
+ assert.equal(
+ reviewChanges([], scan(source), [entry, entry]).length > 0,
+ true,
+ );
});
-test('lifetimes and associated types are not declarations', () => {
- assert.deepEqual(scan("fn value() -> &'static tinyagents_harness::Value { todo!() }"), []);
+test("lifetimes and associated types are not declarations", () => {
+ assert.deepEqual(
+ scan("fn value() -> &'static tinyagents_harness::Value { todo!() }"),
+ [],
+ );
});
-test('const generic equality and function arrows do not terminate a type', () => {
- assert.equal(scan('static X: Wrapper<{1 == 1}, fn() -> usize> = x;')[0].type, 'Wrapper<{1==1},fn()->usize>');
+test("const generic equality and function arrows do not terminate a type", () => {
+ assert.equal(
+ scan("static X: Wrapper<{1 == 1}, fn() -> usize> = x;")[0].type,
+ "Wrapper<{1==1},fn()->usize>",
+ );
});
-test('repository scan reads the merge base, enforces records, and fails without history', () => {
- const root = mkdtempSync(join(tmpdir(), 'process-statics-'));
- const git = (...args) => execFileSync('git', args, {cwd:root, stdio:'pipe', env:{...process.env, GIT_CONFIG_COUNT:'0'}}).toString().trim();
+test("repository scan reads the merge base, enforces records, and fails without history", () => {
+ const root = mkdtempSync(join(tmpdir(), "process-statics-"));
+ const git = (...args) =>
+ execFileSync("git", args, {
+ cwd: root,
+ stdio: "pipe",
+ env: { ...process.env, GIT_CONFIG_COUNT: "0" },
+ })
+ .toString()
+ .trim();
try {
- mkdirSync(join(root, 'crates/openhuman-core/src/example'), {recursive:true});
- mkdirSync(join(root, 'scripts/ci'), {recursive:true});
- writeFileSync(join(root,file), 'pub fn example() {}');
- writeFileSync(join(root,'scripts/ci/process-statics.json'), '[]');
- git('init'); git('add','.');
- git('-c','user.name=Test','-c','[email protected]','-c','core.hooksPath=/dev/null','commit','-m','base');
- const base = git('rev-parse','HEAD');
- writeFileSync(join(root,file), source);
- assert.equal(checkRepository(root,base).errors.length, 1);
- writeFileSync(join(root,'scripts/ci/process-statics.json'), JSON.stringify([entry]));
- assert.deepEqual(checkRepository(root,base).errors, []);
- assert.throws(() => checkRepository(root,'missing-base'), /fetch the base/);
- } finally { rmSync(root,{recursive:true,force:true}); }
+ mkdirSync(join(root, "crates/openhuman-core/src/example"), {
+ recursive: true,
+ });
+ mkdirSync(join(root, "scripts/ci"), { recursive: true });
+ writeFileSync(join(root, file), "pub fn example() {}");
+ writeFileSync(join(root, "scripts/ci/process-statics.json"), "[]");
+ git("init");
+ git("add", ".");
+ git(
+ "-c",
+ "user.name=Test",
+ "-c",
+ "-c",
+ "core.hooksPath=/dev/null",
+ "commit",
+ "-m",
+ "base",
+ );
+ const base = git("rev-parse", "HEAD");
+ writeFileSync(join(root, file), source);
+ assert.equal(checkRepository(root, base).errors.length, 1);
+ writeFileSync(
+ join(root, "scripts/ci/process-statics.json"),
+ JSON.stringify([entry]),
+ );
+ assert.deepEqual(checkRepository(root, base).errors, []);
+ assert.throws(
+ () => checkRepository(root, "missing-base"),
+ /fetch the base/,
+ );
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
});
diff --git a/scripts/ci/check-process-statics.mjs b/scripts/ci/check-process-statics.mjs
index 131229beff..f99a18f703 100644
--- a/scripts/ci/check-process-statics.mjs
+++ b/scripts/ci/check-process-statics.mjs
@@ -1,40 +1,51 @@
#!/usr/bin/env node
-import { execFileSync } from 'node:child_process';
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-import { pathToFileURL } from 'node:url';
-import { stripRustComments } from './check-crate-chain.mjs';
+import { execFileSync } from "node:child_process";
+import { readFileSync } from "node:fs";
+import { resolve } from "node:path";
+import { pathToFileURL } from "node:url";
+import { stripRustComments } from "./check-crate-chain.mjs";
-const CORE = 'crates/openhuman-core/src/';
-const MANIFEST = 'scripts/ci/process-statics.json';
-const production = (file) => typeof file === 'string' && file.startsWith(CORE) && file.endsWith('.rs') && !file.endsWith('_tests.rs');
-const signature = (entry) => JSON.stringify([entry.file, entry.name, entry.type]);
+const CORE = "crates/openhuman-core/src/";
+const MANIFEST = "scripts/ci/process-statics.json";
+const production = (file) =>
+ typeof file === "string" &&
+ file.startsWith(CORE) &&
+ file.endsWith(".rs") &&
+ !file.endsWith("_tests.rs");
+const signature = (entry) =>
+ JSON.stringify([entry.file, entry.name, entry.type]);
/** Source declarations only: includes aliases and lazy_static!, not macro expansion. */
export function declarations(text, file) {
const code = stripRustComments(text);
const found = [];
- const pattern = /(?<!')\bstatic\s+(?:(mut|ref)\s+)?([A-Za-z_][A-Za-z_0-9]*)\s*:(?!:)/g;
+ const pattern =
+ /(?<!')\bstatic\s+(?:(mut|ref)\s+)?([A-Za-z_][A-Za-z_0-9]*)\s*:(?!:)/g;
for (const match of code.matchAll(pattern)) {
let end = match.index + match[0].length;
const start = end;
const stack = [];
for (; end < code.length; end++) {
const char = code[end];
- if (!stack.length && (char === '=' || char === ';')) break;
- if ('<([{'.includes(char)) stack.push(char);
- else if ('>)]}'.includes(char) && stack.length) {
+ if (!stack.length && (char === "=" || char === ";")) break;
+ if ("<([{".includes(char)) stack.push(char);
+ else if (">)]}".includes(char) && stack.length) {
// An arrow inside a function type is not a generic closing bracket.
- if (char === '>' && code[end - 1] === '-') continue;
- const expected = { '>': '<', ')': '(', ']': '[', '}': '{' }[char];
+ if (char === ">" && code[end - 1] === "-") continue;
+ const expected = { ">": "<", ")": "(", "]": "[", "}": "{" }[char];
if (stack.at(-1) === expected) stack.pop();
}
}
- if (end === code.length) throw new Error(`${file}: cannot parse static ${match[2]}`);
- const type = code.slice(start, end).replace(/\s+/g, '');
+ if (end === code.length)
+ throw new Error(`${file}: cannot parse static ${match[2]}`);
+ const type = code.slice(start, end).replace(/\s+/g, "");
if (!type) throw new Error(`${file}: static ${match[2]} has no type`);
- found.push({file, name: match[2], type: (match[1] ? match[1]+' ' : '')+type,
- line: code.slice(0, match.index).split('\n').length});
+ found.push({
+ file,
+ name: match[2],
+ type: (match[1] ? match[1] + " " : "") + type,
+ line: code.slice(0, match.index).split("\n").length,
+ });
}
return found;
}
@@ -43,35 +54,53 @@ function counts(entries) {
const result = new Map();
for (const entry of entries) {
const key = signature(entry);
- result.set(key, (result.get(key) ?? 0)+1);
+ result.set(key, (result.get(key) ?? 0) + 1);
}
return result;
}
/** Require exact, non-stale ownership records for added or changed declaration types. */
export function reviewChanges(before, after, approvals) {
- if (!Array.isArray(approvals)) throw new Error('process-statics.json must contain an array');
+ if (!Array.isArray(approvals))
+ throw new Error("process-statics.json must contain an array");
const oldCounts = counts(before);
const newCounts = counts(after);
const reviewed = new Map();
const errors = [];
for (const entry of approvals) {
- if (!entry || typeof entry !== 'object') { errors.push('Invalid ownership record'); continue; }
+ if (!entry || typeof entry !== "object") {
+ errors.push("Invalid ownership record");
+ continue;
+ }
const key = signature(entry);
if (reviewed.has(key)) errors.push(`Duplicate ownership record: ${key}`);
reviewed.set(key, entry);
- if (!production(entry.file ?? '') || typeof entry.name !== 'string' || !entry.name ||
- typeof entry.type !== 'string' || !entry.type ||
- !Number.isInteger(entry.count) || entry.count < 1 ||
- !['A','B','C','D'].includes(entry.category) ||
- !['reason','verification'].every((field) => typeof entry[field] === 'string' && entry[field].trim())) {
+ if (
+ !production(entry.file ?? "") ||
+ typeof entry.name !== "string" ||
+ !entry.name ||
+ typeof entry.type !== "string" ||
+ !entry.type ||
+ !Number.isInteger(entry.count) ||
+ entry.count < 1 ||
+ !["A", "B", "C", "D"].includes(entry.category) ||
+ !["reason", "verification"].every(
+ (field) => typeof entry[field] === "string" && entry[field].trim(),
+ )
+ ) {
errors.push(`Incomplete ownership record: ${key}`);
}
- if (newCounts.get(key) !== entry.count) errors.push(`Stale ownership record: ${key}`);
+ if (newCounts.get(key) !== entry.count)
+ errors.push(`Stale ownership record: ${key}`);
}
for (const [key, count] of newCounts) {
- if (count > (oldCounts.get(key) ?? 0) && reviewed.get(key)?.count !== count) {
- errors.push(`New static requires an ownership record: ${key} (count ${count})`);
+ if (
+ count > (oldCounts.get(key) ?? 0) &&
+ reviewed.get(key)?.count !== count
+ ) {
+ errors.push(
+ `New static requires an ownership record: ${key} (count ${count})`,
+ );
}
}
return errors;
@@ -79,31 +108,66 @@ export function reviewChanges(before, after, approvals) {
/** Compare tracked working sources with the merge base; missing history is a failure. */
export function checkRepository(root, baseRef) {
- const git = (args) => execFileSync('git', args, {cwd:root, encoding:'utf8', stdio:['ignore','pipe','pipe']}).trim();
+ const git = (args) =>
+ execFileSync("git", args, {
+ cwd: root,
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "pipe"],
+ }).trim();
if (!baseRef) {
- if (process.env.GITHUB_BASE_REF) baseRef = `origin/${process.env.GITHUB_BASE_REF}`;
+ if (process.env.GITHUB_BASE_REF)
+ baseRef = `origin/${process.env.GITHUB_BASE_REF}`;
else {
- try { git(['rev-parse','--verify','upstream/main^{commit}']); baseRef = 'upstream/main'; }
- catch { baseRef = 'origin/main'; }
+ try {
+ git(["rev-parse", "--verify", "upstream/main^{commit}"]);
+ baseRef = "upstream/main";
+ } catch {
+ baseRef = "origin/main";
+ }
}
}
let base;
- try { base = git(['merge-base',baseRef,'HEAD']); }
- catch { throw new Error(`Cannot resolve merge base ${baseRef}; fetch the base with full history before running this gate.`); }
- const previousFiles = git(['ls-tree','-r','--name-only',base,'--',CORE]).split('\n').filter(production);
- const currentFiles = git(['ls-files','--',CORE]).split('\n').filter(production);
- if (!currentFiles.length) throw new Error('No tracked core production sources; refusing an empty scan.');
- const before = previousFiles.flatMap((file) => declarations(git(['show',`${base}:${file}`]),file));
- const after = currentFiles.flatMap((file) => declarations(readFileSync(resolve(root,file),'utf8'),file));
- const approvals = JSON.parse(readFileSync(resolve(root,MANIFEST),'utf8'));
- return {base, files:currentFiles.length, errors:reviewChanges(before,after,approvals)};
+ try {
+ base = git(["merge-base", baseRef, "HEAD"]);
+ } catch {
+ throw new Error(
+ `Cannot resolve merge base ${baseRef}; fetch the base with full history before running this gate.`,
+ );
+ }
+ const previousFiles = git(["ls-tree", "-r", "--name-only", base, "--", CORE])
+ .split("\n")
+ .filter(production);
+ const currentFiles = git(["ls-files", "--", CORE])
+ .split("\n")
+ .filter(production);
+ if (!currentFiles.length)
+ throw new Error(
+ "No tracked core production sources; refusing an empty scan.",
+ );
+ const before = previousFiles.flatMap((file) =>
+ declarations(git(["show", `${base}:${file}`]), file),
+ );
+ const after = currentFiles.flatMap((file) =>
+ declarations(readFileSync(resolve(root, file), "utf8"), file),
+ );
+ const approvals = JSON.parse(readFileSync(resolve(root, MANIFEST), "utf8"));
+ return {
+ base,
+ files: currentFiles.length,
+ errors: reviewChanges(before, after, approvals),
+ };
}
-if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
+if (
+ process.argv[1] &&
+ import.meta.url === pathToFileURL(resolve(process.argv[1])).href
+) {
try {
- const report = checkRepository(process.cwd(),process.argv[2]);
- if (report.errors.length) throw new Error(report.errors.join('\n'));
- console.log(`Process statics: ${report.files} core files checked against ${report.base}; ownership records valid.`);
+ const report = checkRepository(process.cwd(), process.argv[2]);
+ if (report.errors.length) throw new Error(report.errors.join("\n"));
+ console.log(
+ `Process statics: ${report.files} core files checked against ${report.base}; ownership records valid.`,
+ );
} catch (error) {
console.error(`Process statics FAILED: ${error.message}`);
process.exitCode = 1;
diff --git a/scripts/ci/process-statics.md b/scripts/ci/process-statics.md
index d9e145cb2f..394b1a419d 100644
--- a/scripts/ci/process-statics.md
+++ b/scripts/ci/process-statics.md
@@ -38,12 +38,12 @@ source fail. Update or remove the record when its declaration changes.
Choose the ownership category and explain why it applies:
-| Category | Ownership |
-| --- | --- |
-| A | Process configuration or infrastructure; carries no tenant data |
-| B | Tenant data explicitly partitioned by authenticated scope |
-| C | Durable authoritative state reached through a storage driver |
-| D | A routing handle whose target enforces the ownership boundary |
+| Category | Ownership |
+| -------- | --------------------------------------------------------------- |
+| A | Process configuration or infrastructure; carries no tenant data |
+| B | Tenant data explicitly partitioned by authenticated scope |
+| C | Durable authoritative state reached through a storage driver |
+| D | A routing handle whose target enforces the ownership boundary |
Reviewers must inspect the reason and verification reference. The gate
checks their presence and the source declaration; it does not execute the