LibreChat/.github/scripts/expressions.mjs
Danny Avila 97f7fcdbac
🥅 ci: Run Playwright After Merges to Dev and Guard Specs Under Test Selection (#18049)
* 🥅 ci: Run Playwright After Every Merge to Dev

The mock e2e suite ran on pull requests, nightly on main and on demand, so
when a spec broke on dev no run on dev could go red: the vote workflow that
runs the suite after merges cannot fail by design.

Add a push trigger for dev with the pull request path filter. A push runs
the pull request profile with no lane narrowed (10 memory shards, 2 Redis
transport shards, both MCP lanes and MCP Apps), and the gate job reports it.

Pushes take their own concurrency group that never cancels: the run in
progress finishes, and GitHub keeps one pending run per group, so merges
that land meanwhile collapse into one run of the newest commit. Pull
request, nightly and manual runs keep their per-ref cancelling group.

The matrix test now evaluates the workflow's own expressions per event
rather than matching their text.

* 🔭 ci: Always Run Source-Scanning Guard Specs Under Test Selection

Codegraph test selection narrows a pull request run to the test files an
import graph reaches. A spec that reads source with fs has no import edge
to what it reads: toolCapabilityGates.spec.js scans four source trees, was
not selected when #17864 changed one of the files it counts, and failed on
dev afterwards.

List every such spec, with the paths it reads, in .github/guard-specs.json.
Both selectors now add a workspace's guards to a FILES decision and turn a
NONE into a guards-only run when the change touches a path one of them
reads, renames a file, or edits the list. A list that cannot be read runs
the workspace FULL. FULL decisions and every earlier fail-open path are
unchanged.

The rule keys off the decision, not the event. A selection with no file
left in the checkout gets no guards, so the test job still runs FULL on a
stale selection instead of running only the guards.

guard-specs.test.mjs fails when a spec in a gated workspace reads the
repository through fs without being listed, when a listed path is missing,
and when a workflow would not run for a path one of its guards reads. That
last check adds the five backend and one frontend paths the triggers
lacked. The test also runs both real select steps against canned codegraph
responses.
2026-11-11 10:30:09 -05:00

169 lines
5.5 KiB
JavaScript

/**
* Evaluates the subset of GitHub Actions expressions the workflows here use, so a test can
* state what a job condition, matrix or concurrency group resolves to for a given event
* instead of matching the expression's text. Covers literals, context lookups, `!`, `==`,
* `!=`, `&&`, `||`, parentheses and the functions passed in `functions`.
*/
const TOKEN =
/\s*(?:('(?:[^']|'')*')|(-?\d+(?:\.\d+)?)|(==|!=|&&|\|\||[!(),])|([A-Za-z_][\w-]*(?:\.[\w-]+)*))/y;
function tokenize(source) {
const tokens = [];
TOKEN.lastIndex = 0;
while (TOKEN.lastIndex < source.length) {
const start = TOKEN.lastIndex;
const match = TOKEN.exec(source);
if (!match) {
if (source.slice(start).trim() === '') break;
throw new Error(`Unsupported expression syntax at: ${source.slice(start, start + 40)}`);
}
const [, string, number, operator, name] = match;
if (string !== undefined) {
tokens.push({ type: 'value', value: string.slice(1, -1).replaceAll("''", "'") });
} else if (number !== undefined) {
tokens.push({ type: 'value', value: Number(number) });
} else if (operator !== undefined) {
tokens.push({ type: operator });
} else {
tokens.push({ type: 'name', name });
}
}
return tokens;
}
const truthy = (value) =>
!(value === false || value === 0 || value === '' || value == null || Number.isNaN(value));
function toNumber(value) {
if (value == null || value === '') return 0;
if (typeof value === 'boolean') return value ? 1 : 0;
if (typeof value === 'number') return value;
return typeof value === 'string' ? Number(value) : NaN;
}
/** Same-type values compare directly (strings ignoring case); mixed types compare as numbers. */
function equal(left, right) {
if (typeof left === 'string' && typeof right === 'string') {
return left.toLowerCase() === right.toLowerCase();
}
if (left === right) return true;
const sameType = typeof left === typeof right && left != null && right != null;
return sameType ? false : toNumber(left) === toNumber(right);
}
const BUILTINS = {
fromJSON: (text) => JSON.parse(text),
contains: (haystack, needle) =>
Array.isArray(haystack)
? haystack.some((item) => equal(item, needle))
: String(haystack ?? '')
.toLowerCase()
.includes(String(needle ?? '').toLowerCase()),
};
const LITERALS = new Map([
['true', true],
['false', false],
['null', null],
]);
/** A missing property is null, as in Actions. */
const lookup = (context, path) =>
path.split('.').reduce((value, key) => (value == null ? null : (value[key] ?? null)), context);
export function evaluate(source, context = {}, functions = {}) {
const tokens = tokenize(source);
const calls = { ...BUILTINS, ...functions };
let position = 0;
const peek = () => tokens[position]?.type;
const take = (type) => {
const token = tokens[position];
if (!token || (type && token.type !== type)) {
throw new Error(`Expected ${type ?? 'a token'} in: ${source}`);
}
position += 1;
return token;
};
/** `evaluating` is false on the short-circuited side, which is parsed but never called. */
function primary(evaluating) {
if (peek() === '(') {
take('(');
const value = or(evaluating);
take(')');
return value;
}
if (peek() === 'value') return take('value').value;
const { name } = take('name');
if (peek() !== '(') return LITERALS.has(name) ? LITERALS.get(name) : lookup(context, name);
take('(');
const args = [];
while (peek() !== ')') {
args.push(or(evaluating));
if (peek() === ',') take(',');
}
take(')');
if (!evaluating) return null;
if (!calls[name]) throw new Error(`Unsupported function ${name}() in: ${source}`);
return calls[name](...args);
}
function unary(evaluating) {
if (peek() !== '!') return primary(evaluating);
take('!');
return !truthy(unary(evaluating));
}
function comparison(evaluating) {
let left = unary(evaluating);
while (peek() === '==' || peek() === '!=') {
const { type } = take();
const right = unary(evaluating);
left = type === '==' ? equal(left, right) : !equal(left, right);
}
return left;
}
function and(evaluating) {
let left = comparison(evaluating);
while (peek() === '&&') {
take('&&');
const right = comparison(evaluating && truthy(left));
left = truthy(left) ? right : left;
}
return left;
}
function or(evaluating) {
let left = and(evaluating);
while (peek() === '||') {
take('||');
const right = and(evaluating && !truthy(left));
left = truthy(left) ? left : right;
}
return left;
}
const value = or(true);
if (position !== tokens.length) throw new Error(`Trailing tokens in: ${source}`);
return value;
}
/** A job-level `if` is an expression whether or not it is wrapped in `${{ }}`. */
export function condition(source, context, functions) {
const text = String(source).trim();
const wrapped = /^\$\{\{([\s\S]*)\}\}$/.exec(text);
return truthy(evaluate(wrapped ? wrapped[1] : text, context, functions));
}
/** Resolves every `${{ }}` in a string; a value that is only an expression keeps its type. */
export function interpolate(template, context, functions) {
const text = String(template).trim();
const whole = /^\$\{\{((?:(?!\}\})[\s\S])*)\}\}$/.exec(text);
if (whole) return evaluate(whole[1], context, functions);
return text.replace(/\$\{\{((?:(?!\}\})[\s\S])*)\}\}/g, (_, expression) => {
const value = evaluate(expression, context, functions);
return value == null ? '' : String(value);
});
}