Skip to content

Multi-tier framework for evaluating AI agent skills and plugins with quality gates, security scanning, harness compatibility checks, semantic overlap detection, synthetic evaluation dataset generation, and live agent evaluation that measures how skills affect agent behavior. Ships reusable CI templates that bring every check to any repository.

fix(tier3): decode Codex array/map wrappers and make the rubric supplement budget configurable (#502)

Narendran Raghavana29db5e66d9d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 69928234..55017c30 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -81,6 +81,17 @@ All notable changes to SkillEvaluator are documented in this file.
### Changed
+- The rubric judge's reference supplement budget is configurable through
+ `SKILLEVALUATOR_RUBRIC_SUPPLEMENT_BYTES` and defaults to one mebibyte instead
+ of 30,000 bytes, which a real linked guide graph outgrows. Required linked
+ Markdown is bounded only by that budget, so a guide larger than an optional
+ preview is collected whole; optional script and reference previews keep their
+ own small per-file bound. The budget decides how many bytes of the skill's own
+ guidance are collected, never which paths may be read: every reference is still
+ confined to the skill's declared root by the same secure reader, and guidance
+ that does not fit still stops the evaluation with an explicit unsafe-input
+ finding rather than being dropped from the judge's prompt.
+
- The `default` policy no longer blocks a skill for its author attribution,
because the Agent Skills baseline requires only `name` and `description`
(#43). A missing `metadata.author` is now a LOW advisory, and a person, team,
@@ -214,6 +225,23 @@ All notable changes to SkillEvaluator are documented in this file.
`/bin/bash -lc 'cat skills/x/SKILL.md'`, which some agent harnesses record
instead of the bare command. Searches inside a wrapper (`bash -c 'grep SKILL
config.json'`) are still not counted.
+- Tier 3 reads the native Codex wrapper that runs a literal command array
+ through `.map`, so a skill read batched that way is graded instead of scoring
+ as an unsupported wrapper. The decoder stays a bounded static one: every array
+ element is still a literal, the callback may only hand that element to one
+ named tool, and a reused or shadowed binding, a changed index or payload, a
+ computed key or tool name, or a duplicate, missing, extra, reordered or
+ truncated result record leaves the whole wrapper unsupported. Each command is
+ matched to the settled result at its own position and carries that result's
+ own exit code or rejection. The form that prints inside the callback settles
+ out of array order, so it is read only for a single command and otherwise
+ stops grading rather than guessing which result belongs to which command.
+ That inline form is graded only on evidence it actually produced: the callback
+ must `await` the call, because an un-awaited one prints a pending promise
+ rather than the tool's result, and it must print something, because
+ `Promise.allSettled` swallows a rejection and would otherwise let a call that
+ never ran exit cleanly and read as a successful command.
+
- A Tier 1 security scan keeps a SkillSpector `partial` report `INCOMPLETE` when
its only ledger row is a referenced image but its `references` list records a
`missing` reference on a line without a ledger row, an `ambiguous` reference,
diff --git a/docs/environment-variables.mdx b/docs/environment-variables.mdx
index 277645e4..c9fd1cdd 100644
--- a/docs/environment-variables.mdx
+++ b/docs/environment-variables.mdx
@@ -136,6 +136,7 @@ These variables tune the static and security checks. The check-by-check guide is
| `SKILLEVALUATOR_SEMGREP_PATH` | auto-discovered | Absolute path to the Semgrep executable. |
| `SKILLEVALUATOR_SKILLSPECTOR_PATH` | auto-discovered | Absolute path to the SkillSpector executable. |
| `SKILLEVALUATOR_SKILLSPECTOR_TIMEOUT_SECONDS` | `1200` | Watchdog for each SkillSpector run, in seconds. The static stage and, with `--llm`, the LLM stage each get the full value. A run that exceeds it is stopped and the security scan is `INCOMPLETE`. Set a positive integer; values above `86400` are capped, and other values fall back to the default with a warning. Keep it above `SKILLSPECTOR_MAX_WORKFLOW_SECONDS` so SkillSpector's own deadline ends a slow scan first. The effective value is recorded as `skillspector_timeout_seconds` in the security result. |
+| `SKILLEVALUATOR_RUBRIC_SUPPLEMENT_BYTES` | `1048576` (1 MiB) | Total bytes of supplementary content `rubric-eval` collects for the judge: first the complete linked Markdown that `SKILL.md` requires, then bounded optional previews of `scripts/` and `references/`. Required linked guidance is never truncated — a document that does not fit the remaining budget fails the evaluation with an `unsafe_skill_input` finding instead of reaching the judge in part. Set a positive integer; values above `8388608` (8 MiB) are capped, and other values fall back to the default with a warning. The budget bounds how many bytes are read, never which paths: every reference is still confined to the skill's own declared root. |
| `SKILLEVALUATOR_SCHEMA_ALLOWED_DIRS` | — | Extra allowed skill-root directory names (comma- or whitespace-separated), e.g. `data,fixtures`. Additive only — names extend the built-in allowlist and never replace it. |
| `SKILLEVALUATOR_SUBMITTER` | auto-detected | Explicit submitter identity for the home-path PII check. It is combined with `GITHUB_ACTOR`, `USER`, `LOGNAME`, `USERNAME`, the OS login name, and the skill's declared author — every identity that resolves is protected. If none resolves, the home-path check is disabled with a warning. |
| `SKILLEVALUATOR_PREVIOUS_VERSION` | — | The previously published skill version that the default version check compares against. Without this value or `--previous-version`, the check validates the current version's format but does not enforce an increase. |
diff --git a/src/skillevaluator/tier3/eval_core/codex_tool_call_normalizer.py b/src/skillevaluator/tier3/eval_core/codex_tool_call_normalizer.py
index 77dadf7b..ec2af945 100644
--- a/src/skillevaluator/tier3/eval_core/codex_tool_call_normalizer.py
+++ b/src/skillevaluator/tier3/eval_core/codex_tool_call_normalizer.py
@@ -1046,18 +1046,120 @@ def _settled_renderer(cursor: _StaticExecSource, results: str, taken: set[str])
return record_format
+# ── Dynamic literal array/map wrappers (#236) ──
+# Codex also batches a literal command array through `Array.prototype.map`: either collecting the
+# promises for one settled renderer, or printing each result inside the callback. Only the array is
+# "dynamic": every element is still a literal, the callback may do nothing but hand that element to
+# one fixed tool, and no binding may be reused or shadow a global the grammar relies on. The
+# collected form keeps `Promise.allSettled`'s input order, so the element at an index owns the
+# record at that index. The inline form prints when each promise settles, not in array order, so it
+# is decoded only when the array holds exactly one element; anything else leaves the wrapper
+# unsupported rather than guessing which command produced which result.
+
+
+def _mapped_arguments(cursor: _StaticExecSource, parameter: str) -> tuple[str | None, dict[str, Any]]:
+ """Read a mapped call's argument: the element itself, or an object literal naming it once.
+
+ Returns ``(shorthand_key, literal_properties)``. ``shorthand_key`` is None when the whole
+ element is the argument. Every other property must be a literal, so no element can reach the
+ tool changed, renamed or combined with another binding.
+ """
+ if cursor.peek() != "{":
+ if cursor.name() != parameter:
+ raise _NotStatic("arguments")
+ return None, {}
+ cursor.expect("{")
+ shorthand: str | None = None
+ properties: dict[str, Any] = {}
+ while not cursor.take("}"):
+ if shorthand is not None or properties:
+ cursor.expect(",")
+ if cursor.take("}"):
+ break
+ quoted = cursor.peek() in ("'", '"')
+ key = cursor.string() if quoted else cursor.name()
+ if key in ("__proto__", shorthand) or key in properties:
+ raise _NotStatic(key)
+ if cursor.take(":"):
+ properties[key] = cursor.literal()
+ continue
+ # A shorthand property: only the callback's own parameter, and only once.
+ if quoted or key != parameter or shorthand is not None:
+ raise _NotStatic(key)
+ shorthand = key
+ if shorthand is None:
+ raise _NotStatic("arguments")
+ return shorthand, properties
+
+
+def _mapped_tool_calls(
+ cursor: _StaticExecSource,
+ arrays: dict[str, list[Any]],
+ taken: set[str],
+ *,
+ inline: bool,
+) -> list[tuple[str, dict[str, Any]]] | None:
+ """Read ``<array>.map(<callback>)`` and return one call per literal element, in array order."""
+ elements = arrays.get(cursor.name())
+ if elements is None:
+ raise _NotStatic("map source")
+ cursor.expect(".", "map", "(")
+ if cursor.take("async"):
+ # `async` may not be separated from an async arrow's parameters by a line break.
+ cursor.same_line()
+ parenthesized = cursor.take("(")
+ parameter = cursor.binding(taken)
+ if parenthesized:
+ cursor.expect(")")
+ cursor.same_line()
+ cursor.expect("=>")
+ if inline:
+ cursor.expect("text", "(")
+ # The inline callback prints whatever the call expression evaluates to, so without `await`
+ # it renders the pending Promise instead of the tool's result and the outer output proves
+ # nothing about the call. The collected form may omit it: `Promise.allSettled` awaits
+ # whatever `.map` returns, so its record still describes the settled call.
+ cursor.expect("await")
+ else:
+ cursor.take("await")
+ cursor.expect("tools", ".")
+ function_name = cursor.name()
+ cursor.expect("(")
+ shorthand, properties = _mapped_arguments(cursor, parameter)
+ cursor.expect(")")
+ if inline:
+ cursor.expect(")")
+ cursor.expect(")")
+ if not elements or len(elements) > _MAX_TOOL_CALLS:
+ return None
+ calls: list[tuple[str, dict[str, Any]]] = []
+ for element in elements:
+ if shorthand is None:
+ if not isinstance(element, dict):
+ return None
+ calls.append((function_name, element))
+ continue
+ calls.append((function_name, {**properties, shorthand: element}))
+ return calls
+
+
def _extended_codex_program(source: str) -> tuple[list[tuple[str, dict[str, Any]]], int | None, tuple] | None:
"""Decode the extended grammar into ``(calls, owner, record_format)``, or None outside it.
- A single call keeps the upstream ownership: ``owner`` 0 owns the whole outer observation,
+ The statements are a literal command array, one `Promise.allSettled` over a literal batch or
+ over `.map` of such an array, bound calls, and renders. A single call keeps the upstream
+ ownership: ``owner`` 0 owns the whole outer observation,
-1 renders nothing. A lone call that prints its whole result has the ``("single",)`` format,
- so its own exit code can mark it failed. With records, ``owner`` is None and ``record_format``
+ so its own exit code can mark it failed; the same call inlined into `Promise.allSettled`, whose
+ rejection the wrapper swallows, has the ``("settled_single",)`` format and is graded only once
+ its printed output proves it settled fulfilled. With records, ``owner`` is None and ``record_format``
says how to split the outer observation; for inline renders it lists the call of each record
in output order.
"""
cursor = _StaticExecSource(source)
calls: list[tuple[str, dict[str, Any]]] = []
bindings: dict[str, int] = {}
+ arrays: dict[str, list[Any]] = {}
renders: list[tuple[int, bool]] = []
taken: set[str] = set()
statements = 0
@@ -1068,19 +1170,37 @@ def _extended_codex_program(source: str) -> tuple[list[tuple[str, dict[str, Any]
return None
if cursor.take("const"):
variable = cursor.binding(taken)
- cursor.expect("=", "await")
+ cursor.expect("=")
+ if cursor.peek() == "[":
+ # A literal command array; only `.map` over it may turn it into calls.
+ if calls:
+ return None
+ elements = cursor.literal()
+ # `literal()` re-reads the same `[`, so it either returns the array or raises
+ # `_NotStatic`; this narrows the `Any` it is declared to return.
+ assert isinstance(elements, list)
+ arrays[variable] = elements
+ cursor.end_statement()
+ continue
+ cursor.expect("await")
if cursor.take("Promise"):
if calls:
return None
- cursor.expect(".", "allSettled", "(", "[")
- while not cursor.take("]"):
- if calls:
- cursor.expect(",")
- if cursor.take("]"):
- break
- if len(calls) >= _MAX_TOOL_CALLS:
+ cursor.expect(".", "allSettled", "(")
+ if cursor.take("["):
+ while not cursor.take("]"):
+ if calls:
+ cursor.expect(",")
+ if cursor.take("]"):
+ break
+ if len(calls) >= _MAX_TOOL_CALLS:
+ return None
+ calls.append(cursor.tool_call())
+ else:
+ mapped = _mapped_tool_calls(cursor, arrays, taken, inline=False)
+ if mapped is None:
return None
- calls.append(cursor.tool_call())
+ calls.extend(mapped)
cursor.expect(")")
cursor.end_statement()
record_format = _settled_renderer(cursor, variable, taken)
@@ -1088,6 +1208,23 @@ def _extended_codex_program(source: str) -> tuple[list[tuple[str, dict[str, Any]
return (calls, None, record_format) if calls and cursor.at_end() else None
bindings[variable] = len(calls)
calls.append(cursor.tool_call())
+ elif cursor.take("await"):
+ if calls:
+ return None
+ cursor.expect("Promise", ".", "allSettled", "(")
+ mapped = _mapped_tool_calls(cursor, arrays, taken, inline=True)
+ if mapped is None:
+ return None
+ cursor.expect(")")
+ cursor.end_statement()
+ # Each callback prints when its own promise settles, so with more than one element
+ # no record can be proven to belong to the command at its position.
+ if len(mapped) != 1 or not cursor.at_end():
+ return None
+ # `Promise.allSettled` swallows a rejection, so a clean script exit does not prove
+ # this call ran: only the callback's own printed output does. Its own format keeps
+ # that weaker guarantee apart from a top-level lone call's.
+ return mapped, 0, ("settled_single",)
else:
cursor.expect("text", "(")
if cursor.take("("):
@@ -1146,7 +1283,7 @@ def _exec_record(value: object, record_format: tuple, record_index: int) -> tupl
form the scorers read, that makes an explicit outcome visible in the record's observation.
"""
kind = record_format[0]
- if kind in ("result", "single"):
+ if kind in ("result", "single", "settled_single"):
return _returned_outcome(value) if isinstance(value, dict) else None
if kind == "settled":
settled = _settled_result(value)
@@ -1261,13 +1398,17 @@ def _resolve_exec_records(
duplicate = False
except _DuplicateKey:
records, duplicate = None, True
- if record_format == ("single",):
+ if record_format[0] in ("single", "settled_single"):
header = _EXEC_OUTPUT_RE.match(observation)
+ printed = observation[header.end() :] if header is not None else observation
# A lone call may print plain text, but a body that opens like a record and does not parse
# is incomplete evidence: a cut-off failure must not score as a clean run.
- incomplete = duplicate or (
- records is None and header is not None and observation[header.end() :].lstrip()[:1] == "{"
- )
+ incomplete = duplicate or (records is None and header is not None and printed.lstrip()[:1] == "{")
+ # An inlined call's rejection is swallowed by `Promise.allSettled`, so the script completes
+ # with nothing printed and a clean exit says only that the wrapper finished. The callback
+ # renders after its own `await` resolves, so printed output is the one proof it fulfilled.
+ if record_format[0] == "settled_single" and not printed.strip():
+ incomplete = True
if incomplete:
outer = {key: value for key, value in tool_call.items() if not key.startswith("_atif_")}
return [{**outer, "_atif_normalization_status": UNSUPPORTED_NATIVE_CODEX_EXEC}]
diff --git a/src/skillevaluator/validators/rubric_eval.py b/src/skillevaluator/validators/rubric_eval.py
index b85ecb69..37a2c1ac 100644
--- a/src/skillevaluator/validators/rubric_eval.py
+++ b/src/skillevaluator/validators/rubric_eval.py
@@ -21,6 +21,7 @@ import posixpath
import re
import stat
from collections import Counter, deque
+from collections.abc import Mapping
from pathlib import Path
from typing import Any
from urllib.parse import unquote, urlsplit
@@ -49,8 +50,17 @@ logger = get_logger(__name__)
_IMPORTANCE_WEIGHTS = {"high": 3, "medium": 2, "low": 1}
_CRITERION_PASS_SCORE = 7
_MAX_SKILL_CONTENT_BYTES = 1024 * 1024
+# Optional previews are summaries, so each one stays small and may be truncated. Required linked
+# guidance is not a preview: it is bounded only by the whole supplement budget below, and a
+# document that does not fit stops the evaluation instead of reaching the judge in part.
_MAX_SUPPLEMENTARY_FILE_BYTES = 3000
-_MAX_SUPPLEMENTARY_TOTAL_BYTES = 30000
+# A real linked guide graph runs to tens of kilobytes, so the stock budget matches the mebibyte
+# already allowed for the manifest itself. The budget bounds how many bytes are collected, never
+# which paths may be read: every reference is still confined to the skill's own declared root by
+# the secure reader below.
+_DEFAULT_SUPPLEMENTARY_TOTAL_BYTES = 1024 * 1024
+_MAX_CONFIGURED_SUPPLEMENTARY_TOTAL_BYTES = 8 * 1024 * 1024
+_SUPPLEMENTARY_TOTAL_BYTES_ENV = "SKILLEVALUATOR_RUBRIC_SUPPLEMENT_BYTES"
_MAX_LINKED_MARKDOWN_FILES = 256
# A rejected judge reply's problem text kept in the log line and retry note.
# 500 characters hold every missing and some unexpected criterion ids.
@@ -436,16 +446,52 @@ def _extract_json(content: str) -> dict:
raise json.JSONDecodeError(msg, content[:200], 0)
+def supplementary_total_bytes(environ: Mapping[str, str] | None = None) -> int:
+ """Return the configured supplement budget, which never widens the declared root.
+
+ The operator may raise or lower how many bytes of skill-owned guidance are collected. A
+ reference is still read only from the skill's own root, so a larger budget never reaches a
+ path a smaller one could not.
+ """
+ source = os.environ if environ is None else environ
+ raw = source.get(_SUPPLEMENTARY_TOTAL_BYTES_ENV, "").strip()
+ if not raw:
+ return _DEFAULT_SUPPLEMENTARY_TOTAL_BYTES
+ try:
+ budget: int | None = int(raw)
+ except ValueError:
+ budget = None
+ if budget is None or budget <= 0:
+ logger.warning(
+ "Ignoring %s=%r: expected a positive integer number of bytes; using %s",
+ _SUPPLEMENTARY_TOTAL_BYTES_ENV,
+ raw,
+ _DEFAULT_SUPPLEMENTARY_TOTAL_BYTES,
+ )
+ return _DEFAULT_SUPPLEMENTARY_TOTAL_BYTES
+ if budget > _MAX_CONFIGURED_SUPPLEMENTARY_TOTAL_BYTES:
+ logger.warning(
+ "Capping %s=%r at %s bytes",
+ _SUPPLEMENTARY_TOTAL_BYTES_ENV,
+ raw,
+ _MAX_CONFIGURED_SUPPLEMENTARY_TOTAL_BYTES,
+ )
+ return _MAX_CONFIGURED_SUPPLEMENTARY_TOTAL_BYTES
+ return budget
+
+
def _collect_supplementary_content(
skill_path: Path,
max_bytes_per_file: int = _MAX_SUPPLEMENTARY_FILE_BYTES,
- max_total_bytes: int = _MAX_SUPPLEMENTARY_TOTAL_BYTES,
+ max_total_bytes: int | None = None,
*,
manifest: Path | None = None,
skill_content: str | None = None,
) -> dict[str, dict[str, str]]:
"""Collect complete linked Markdown before optional bounded previews."""
result: dict[str, dict[str, str]] = {"scripts": {}, "references": {}}
+ if max_total_bytes is None:
+ max_total_bytes = supplementary_total_bytes()
total = 0
try:
resolved_root = skill_path.resolve(strict=True)
@@ -499,9 +545,9 @@ def _collect_supplementary_content(
metadata = (resolved_root / relative).lstat()
identity = (metadata.st_dev, metadata.st_ino)
cached = seen_payloads.get(identity) if metadata.st_ino else None
- read_limit = (
- len(cached) if cached is not None else min(max_bytes_per_file, max_total_bytes - total)
- )
+ # Required guidance is never truncated, so the only bound is what is left of
+ # the supplement budget: a document that does not fit stops the collection.
+ read_limit = len(cached) if cached is not None else max_total_bytes - total
payload, _ = reader.read_bytes(Path(relative), read_limit, expected=metadata)
seen.add(relative)
if cached is not None:
diff --git a/tests/tier3/test_codex_tool_call_normalization.py b/tests/tier3/test_codex_tool_call_normalization.py
index bb31dfc1..e3accf6f 100644
--- a/tests/tier3/test_codex_tool_call_normalization.py
+++ b/tests/tier3/test_codex_tool_call_normalization.py
@@ -1869,3 +1869,524 @@ def test_lone_call_record_after_leading_whitespace_is_graded(extractor, source,
assert "normalization_status" not in calls[0]
assert calls[0]["is_error"] is True
assert _error_recovery(trajectory, extractor)["score"] == 0.0
+
+
+# ── Dynamic literal array/map wrappers (#236) ──
+
+_MAP_ARRAY = 'const cmds=["cat a.md","cat b.md"];'
+_MAP_COLLECTED = _MAP_ARRAY + "const results=await Promise.allSettled(cmds.map(async cmd=>tools.exec_command({cmd})));"
+# The wrapper reported in #236: a literal array mapped by an async arrow that prints each result.
+_MAP_INLINE_ONE = 'const cmds = ["cat guide.md"];\nawait Promise.allSettled(cmds.map(async cmd => text(await tools.exec_command({cmd}))));'
+
+
[email protected]("extractor", _EXTRACTORS)
+ "callback",
+ [
+ pytest.param("async cmd=>tools.exec_command({cmd})", id="async-arrow"),
+ pytest.param("cmd=>tools.exec_command({cmd})", id="plain-arrow"),
+ pytest.param("async (cmd) => await tools.exec_command({cmd})", id="parenthesized-await"),
+ ],
+)
[email protected](("renderer", "shape"), _RENDERERS)
+def test_dynamic_map_gives_each_command_its_own_record(extractor, callback, renderer, shape):
+ source = f"{_MAP_ARRAY}const results=await Promise.allSettled(cmds.map({callback}));{renderer}"
+ records = _failed_exit_records(shape, 0)
+ calls = extractor(_trajectory(source, _record_observation(records)))
+
+ assert [call["action"] for call in calls] == ["exec_command", "exec_command"]
+ assert [call["action_input"] for call in calls] == [{"cmd": "cat a.md"}, {"cmd": "cat b.md"}]
+ assert [call["observation_status"] for call in calls] == ["mapped_outer_exec_result"] * 2
+ assert [call["observation"] for call in calls] == _expected_records(records)
+
+
[email protected]("extractor", _EXTRACTORS)
+def test_dynamic_map_of_object_literals_passes_each_element_whole(extractor):
+ source = (
+ 'const args=[{cmd:"cat a.md"},{session_id:1,chars:""}];'
+ "const results=await Promise.allSettled(args.map(async a=>tools.exec_command(a)));"
+ "results.forEach(text);"
+ )
+ records = [{"status": "fulfilled", "value": {"exit_code": 0}}] * 2
+ calls = extractor(_trajectory(source, _record_observation(records)))
+
+ assert [call["action_input"] for call in calls] == [{"cmd": "cat a.md"}, {"session_id": 1, "chars": ""}]
+
+
[email protected]("extractor", _EXTRACTORS)
+def test_dynamic_map_inline_single_command_owns_its_own_record(extractor):
+ record = {"exit_code": 0, "output": "# Guide\n"}
+ trajectory = _trajectory(_MAP_INLINE_ONE, _record_observation([record]))
+ calls = extractor(trajectory)
+
+ assert [call["action"] for call in calls] == ["exec_command"]
+ assert calls[0]["action_input"] == {"cmd": "cat guide.md"}
+ assert calls[0]["observation_status"] == "mapped_outer_exec_result"
+ assert "normalization_status" not in calls[0]
+ assert _error_recovery(trajectory, extractor)["first_attempt_clean"] is True
+
+
[email protected]("extractor", _EXTRACTORS)
+def test_dynamic_map_inline_failed_read_carries_its_exit_status(extractor):
+ record = {"exit_code": 1, "output": "cat: guide.md: No such file\n"}
+ trajectory = _trajectory(_MAP_INLINE_ONE, _record_observation([record]))
+ calls = extractor(trajectory)
+
+ assert calls[0]["is_error"] is True
+ assert calls[0]["observation"].endswith("\nexit_code=1")
+ assert _error_recovery(trajectory, extractor)["first_attempt_clean"] is False
+
+
[email protected]("extractor", _EXTRACTORS)
+def test_dynamic_map_inline_failed_skill_read_gets_no_activation_credit(extractor):
+ source = (
+ 'const cmds=["cat /skills/example/SKILL.md"];'
+ "await Promise.allSettled(cmds.map(async cmd=>text(await tools.exec_command({cmd}))));"
+ )
+ record = {"exit_code": 1, "output": "cat: No such file\n"}
+ calls = extractor(_trajectory(source, _record_observation([record])))
+ result = _scorer(extractor, "check_activation")(calls, "example")
+
+ assert calls[0]["is_error"] is True
+ assert result["score"] == 0.0
+
+
[email protected]("extractor", _EXTRACTORS)
+def test_dynamic_map_destructive_command_is_still_flagged(extractor):
+ source = (
+ 'const cmds=["rm -rf /workspace/project"];'
+ "await Promise.allSettled(cmds.map(async cmd=>text(await tools.exec_command({cmd}))));"
+ )
+ result = _security_result(source, extractor)
+
+ assert result["passed"] is False
+ assert [finding["type"] for finding in result["findings"]] == ["destructive_command"]
+
+
[email protected]("extractor", _EXTRACTORS)
+ "source",
+ [
+ # Ambiguous ownership: each callback prints when its own promise settles, not in array order.
+ pytest.param(
+ 'const cmds=["cat a.md","cat b.md"];'
+ "await Promise.allSettled(cmds.map(async cmd=>text(await tools.exec_command({cmd}))));",
+ id="inline-batch-without-provable-owner",
+ ),
+ # Dynamic arguments that are not literals.
+ pytest.param(
+ 'const base="cat a.md";const cmds=[base];'
+ "await Promise.allSettled(cmds.map(async cmd=>text(await tools.exec_command({cmd}))));",
+ id="identifier-element",
+ ),
+ pytest.param(
+ "const cmds=[`cat a.md`];"
+ "await Promise.allSettled(cmds.map(async cmd=>text(await tools.exec_command({cmd}))));",
+ id="template-literal-element",
+ ),
+ pytest.param(
+ 'const cmds=["cat a.md",...more];'
+ "await Promise.allSettled(cmds.map(async cmd=>text(await tools.exec_command({cmd}))));",
+ id="spread-element",
+ ),
+ pytest.param(
+ 'const cmds=["cat a.md"];await Promise.allSettled(cmds.map(async cmd=>text(await tools[name]({cmd}))));',
+ id="computed-tool-member",
+ ),
+ pytest.param(
+ "await Promise.allSettled(other.map(async cmd=>text(await tools.exec_command({cmd}))));",
+ id="undeclared-array",
+ ),
+ pytest.param(
+ "const cmds=[];await Promise.allSettled(cmds.map(async cmd=>text(await tools.exec_command({cmd}))));",
+ id="empty-array",
+ ),
+ # Changed payloads: the element must reach the tool exactly as the array declared it.
+ pytest.param(
+ 'const cmds=["cat a.md"];'
+ 'await Promise.allSettled(cmds.map(async cmd=>text(await tools.exec_command({cmd:cmd+" -n"}))));',
+ id="derived-payload",
+ ),
+ pytest.param(
+ 'const cmds=["cat a.md"];'
+ "await Promise.allSettled(cmds.map(async c=>text(await tools.exec_command({cmd:c}))));",
+ id="renamed-payload-key",
+ ),
+ pytest.param(
+ 'const cmds=["cat a.md"];'
+ 'await Promise.allSettled(cmds.map(async cmd=>text(await tools.exec_command({["cmd"]:cmd}))));',
+ id="computed-payload-key",
+ ),
+ pytest.param(
+ 'const cmds=["cat a.md"];'
+ "await Promise.allSettled(cmds.map(async cmd=>text(await tools.exec_command({cmd,cmd}))));",
+ id="duplicate-payload-key",
+ ),
+ pytest.param(
+ 'const cmds=["cat a.md"];'
+ "await Promise.allSettled(cmds.map(async cmd=>text(await tools.exec_command({...cmd}))));",
+ id="spread-payload",
+ ),
+ pytest.param(
+ _MAP_ARRAY + "const results=await Promise.allSettled(cmds.map(async cmd=>tools.exec_command(cmd)));"
+ "results.forEach(text);",
+ id="whole-element-is-not-an-object",
+ ),
+ # Shadowed bindings.
+ pytest.param(
+ 'const cmds=["cat a.md"];'
+ "await Promise.allSettled(cmds.map(async text=>text(await tools.exec_command({cmd:text}))));",
+ id="shadowed-text",
+ ),
+ pytest.param(
+ 'const cmds=["cat a.md"];'
+ "await Promise.allSettled(cmds.map(async tools=>text(await tools.exec_command({cmd:tools}))));",
+ id="shadowed-tools",
+ ),
+ pytest.param(
+ 'const cmds=["cat a.md"];'
+ "await Promise.allSettled(cmds.map(async cmds=>text(await tools.exec_command({cmds}))));",
+ id="shadowed-array-binding",
+ ),
+ pytest.param(
+ _MAP_COLLECTED + "results.forEach((results,i)=>text({i,...results}));",
+ id="shadowed-results-binding",
+ ),
+ pytest.param(
+ _MAP_ARRAY + "const cmds=await Promise.allSettled(cmds.map(async cmd=>tools.exec_command({cmd})));"
+ "cmds.forEach(text);",
+ id="reused-array-binding",
+ ),
+ # Changed indexes: a renderer must print each record at its own position.
+ pytest.param(
+ _MAP_COLLECTED + "results.forEach((r,i)=>text({i:i+1,...r}));",
+ id="shifted-record-index",
+ ),
+ pytest.param(
+ _MAP_COLLECTED + "for (let i = 0; i < results.length; i++) text({i, ...results[i+1]});",
+ id="shifted-results-index",
+ ),
+ pytest.param(
+ _MAP_COLLECTED + "results.map((r,i)=>text({i,...r}));",
+ id="unsupported-renderer-map",
+ ),
+ # Other wrappers the grammar does not prove.
+ pytest.param(
+ 'const cmds=["cat a.md"];await Promise.all(cmds.map(async cmd=>text(await tools.exec_command({cmd}))));',
+ id="promise-all",
+ ),
+ pytest.param(
+ 'const cmds=["cat a.md"];'
+ "await Promise.allSettled(cmds.filter(async cmd=>text(await tools.exec_command({cmd}))));",
+ id="filter-not-map",
+ ),
+ pytest.param(
+ _MAP_INLINE_ONE + 'text(await tools.exec_command({cmd:"pwd"}));',
+ id="statement-after-inline-batch",
+ ),
+ pytest.param(
+ 'text(await tools.exec_command({cmd:"pwd"}));' + _MAP_INLINE_ONE,
+ id="call-before-array-batch",
+ ),
+ ],
+)
+def test_dynamic_map_forms_it_cannot_prove_stay_unsupported(extractor, source):
+ calls = extractor(_trajectory(source, _record_observation([{"exit_code": 0, "output": "ok\n"}])))
+
+ assert len(calls) == 1
+ assert calls[0]["action"] == "exec"
+ assert calls[0]["normalization_status"] == "unsupported_native_codex_exec_wrapper"
+
+
[email protected]("extractor", _EXTRACTORS)
+ "records",
+ [
+ pytest.param(_ALL_SETTLED_SPREAD_RECORDS[:1], id="missing-record"),
+ pytest.param([*_ALL_SETTLED_SPREAD_RECORDS, {"i": 2, "status": "fulfilled", "value": {}}], id="extra-record"),
+ pytest.param(list(reversed(_ALL_SETTLED_SPREAD_RECORDS)), id="reordered-records"),
+ pytest.param([_ALL_SETTLED_SPREAD_RECORDS[0], _ALL_SETTLED_SPREAD_RECORDS[0]], id="duplicate-index"),
+ pytest.param([{"i": 0, "status": "fulfilled"}, _ALL_SETTLED_SPREAD_RECORDS[1]], id="malformed-record"),
+ pytest.param(
+ [{**_ALL_SETTLED_SPREAD_RECORDS[0], "extra": True}, _ALL_SETTLED_SPREAD_RECORDS[1]],
+ id="extra-key",
+ ),
+ ],
+)
+def test_dynamic_map_untrusted_records_stay_unsupported(extractor, records):
+ source = _MAP_COLLECTED + "results.forEach((r,i)=>text({i,...r}));"
+ calls = extractor(_trajectory(source, _record_observation(records)))
+
+ assert len(calls) == 1
+ assert calls[0]["action"] == "exec"
+ assert calls[0]["normalization_status"] == "unsupported_native_codex_exec_wrapper"
+
+
[email protected]("extractor", _EXTRACTORS)
+ "records",
+ [
+ '{"i":0,"i":1,"status":"fulfilled","value":{}}\n{"i":1,"status":"fulfilled","value":{}}',
+ '{"i":0,"status":"fulfilled","value":{"exit_code":1,"exit_code":0}}\n{"i":1,"status":"fulfilled","value":{}}',
+ ],
+ ids=["index", "nested"],
+)
+def test_dynamic_map_duplicate_record_keys_stay_unsupported(extractor, records):
+ source = _MAP_COLLECTED + "results.forEach((r,i)=>text({i,...r}));"
+ calls = extractor(_trajectory(source, _RECORD_FRAME[0] + records))
+
+ assert len(calls) == 1
+ assert calls[0]["normalization_status"] == "unsupported_native_codex_exec_wrapper"
+
+
[email protected]("extractor", _EXTRACTORS)
+ "observation",
+ [
+ pytest.param("", id="empty"),
+ pytest.param("partial", id="without-output-header"),
+ pytest.param(_record_observation(_ALL_SETTLED_SPREAD_RECORDS).rsplit("\n", 1)[0], id="truncated"),
+ pytest.param(_record_observation(_ALL_SETTLED_SPREAD_RECORDS) + "\nextra", id="trailing-text"),
+ ],
+)
+def test_dynamic_map_incomplete_observation_stays_unsupported(extractor, observation):
+ source = _MAP_COLLECTED + "results.forEach((r,i)=>text({i,...r}));"
+ calls = extractor(_trajectory(source, observation))
+
+ assert len(calls) == 1
+ assert calls[0]["normalization_status"] == "unsupported_native_codex_exec_wrapper"
+
+
[email protected]("extractor", _EXTRACTORS)
+ "body",
+ [
+ pytest.param('{"exit_code":0,"out', id="truncated-record"),
+ pytest.param('{"exit_code":1,"exit_code":0}', id="duplicate-key"),
+ ],
+)
+def test_dynamic_map_inline_incomplete_record_stays_unsupported(extractor, body):
+ calls = extractor(_trajectory(_MAP_INLINE_ONE, _RECORD_FRAME[0] + body))
+
+ assert len(calls) == 1
+ assert calls[0]["action"] == "exec"
+ assert calls[0]["normalization_status"] == "unsupported_native_codex_exec_wrapper"
+
+
[email protected]("extractor", _EXTRACTORS)
+ ("record", "is_error"),
+ [
+ pytest.param({"i": 0, "status": "fulfilled", "value": {"exit_code": 0}}, False, id="exit-zero"),
+ pytest.param({"i": 0, "status": "fulfilled", "value": {"exit_code": 4}}, True, id="nonzero-exit"),
+ pytest.param({"i": 0, "status": "rejected", "reason": {"error": "boom"}}, True, id="rejected"),
+ pytest.param({"i": 0, "status": "fulfilled", "value": {"output": "x"}}, None, id="no-exit-code"),
+ ],
+)
+def test_dynamic_map_record_carries_its_own_outcome(extractor, record, is_error):
+ source = (
+ 'const cmds=["cat a.md"];'
+ "const results=await Promise.allSettled(cmds.map(async cmd=>tools.exec_command({cmd})));"
+ "results.forEach((r,i)=>text({i,...r}));"
+ )
+ calls = extractor(_trajectory(source, _record_observation([record])))
+
+ assert len(calls) == 1
+ assert calls[0].get("is_error") is is_error
+
+
[email protected]("extractor", _EXTRACTORS)
+def test_dynamic_map_array_longer_than_the_call_limit_stays_unsupported(extractor):
+ commands = ",".join(f'"cat {index}.md"' for index in range(129))
+ source = (
+ f"const cmds=[{commands}];"
+ "await Promise.allSettled(cmds.map(async cmd=>text(await tools.exec_command({cmd}))));"
+ )
+ calls = extractor(_trajectory(source))
+
+ assert len(calls) == 1
+ assert calls[0]["normalization_status"] == "unsupported_native_codex_exec_wrapper"
+
+
[email protected]("extractor", _EXTRACTORS)
+def test_dynamic_map_with_incomplete_records_stops_grading(extractor):
+ # A truncated batch is missing evidence, not a partial score: every deterministic check
+ # reports an unsupported wrapper instead of grading what little came back.
+ source = (
+ 'const cmds=["cat /skills/example/SKILL.md","python /skills/example/scripts/run.py"];'
+ "const results=await Promise.allSettled(cmds.map(async cmd=>tools.exec_command({cmd})));"
+ "results.forEach((r,i)=>text({i,...r}));"
+ )
+ complete = _record_observation(
+ [
+ {"i": 0, "status": "fulfilled", "value": {"exit_code": 0, "output": "# Example\n"}},
+ {"i": 1, "status": "fulfilled", "value": {"exit_code": 0, "output": "run.py completed\n"}},
+ ]
+ )
+ calls = extractor(_trajectory(source, complete.rsplit("\n", 1)[0]))
+ results = [
+ _scorer(extractor, "check_activation")(calls, "example"),
+ _scorer(extractor, "check_script_execution")(calls, "run.py"),
+ _scorer(extractor, "check_workflow_order")(calls, expected_skill="example"),
+ _scorer(extractor, "check_negative_case")(calls, "example"),
+ _scorer(extractor, "check_routing")(calls, "example"),
+ _scorer(extractor, "check_tool_efficiency")(calls, expected_skill="example", expected_script="run.py"),
+ _scorer(extractor, "check_error_recovery")(calls),
+ ]
+
+ assert {result["passed"] for result in results} == {None}
+ assert {result["score"] for result in results} == {0.5}
+ assert {result["supported"] for result in results} == {False}
+
+
+# ── The inline wrapper's two missing proofs (#502 review) ──
+
+
[email protected]("extractor", _EXTRACTORS)
+ "callback",
+ [
+ pytest.param("async cmd=>text(tools.exec_command({cmd}))", id="async-arrow"),
+ pytest.param("cmd=>text(tools.exec_command({cmd}))", id="plain-arrow"),
+ pytest.param("async (cmd) => text(tools.exec_command({cmd}))", id="parenthesized"),
+ ],
+)
+def test_inline_map_without_await_prints_a_promise_and_stays_unsupported(extractor, callback):
+ # Without `await` the callback renders the pending Promise, not the tool's result, so the
+ # outer output records nothing about the call. The same program written as a top-level
+ # `text(tools.exec_command(...))` is rejected for exactly this reason.
+ source = f'const cmds=["cat guide.md"];await Promise.allSettled(cmds.map({callback}));'
+ calls = extractor(_trajectory(source, _RECORD_FRAME[0] + "[object Promise]"))
+
+ assert len(calls) == 1
+ assert calls[0]["action"] == "exec"
+ assert calls[0]["normalization_status"] == "unsupported_native_codex_exec_wrapper"
+
+
[email protected]("extractor", _EXTRACTORS)
+def test_inline_map_with_await_is_still_graded(extractor):
+ # The companion of the test above: requiring `await` must not reject the awaited form.
+ calls = extractor(_trajectory(_MAP_INLINE_ONE, _record_observation([{"exit_code": 0, "output": "# Guide\n"}])))
+
+ assert "normalization_status" not in calls[0]
+ assert calls[0]["action_input"] == {"cmd": "cat guide.md"}
+ assert calls[0]["is_error"] is False
+
+
[email protected]("extractor", _EXTRACTORS)
+def test_collected_map_callback_may_still_omit_await(extractor):
+ # Only the inline form needs `await`: `Promise.allSettled` awaits whatever `.map` returns, so
+ # the collected form's own record still describes the settled call.
+ source = _MAP_COLLECTED + "results.forEach((r,i)=>text({i,...r}));"
+ records = [
+ {"i": 0, "status": "fulfilled", "value": {"exit_code": 0}},
+ {"i": 1, "status": "fulfilled", "value": {"exit_code": 0}},
+ ]
+ calls = extractor(_trajectory(source, _record_observation(records)))
+
+ assert [call["action"] for call in calls] == ["exec_command", "exec_command"]
+ assert [call["is_error"] for call in calls] == [False, False]
+
+
[email protected]("extractor", _EXTRACTORS)
+ "body",
+ [
+ pytest.param("", id="nothing-printed"),
+ pytest.param(" \n\t", id="whitespace-only"),
+ ],
+)
+def test_inline_map_swallowed_rejection_stays_unsupported(extractor, body):
+ # A rejected call throws inside the callback, so `text()` never runs and `Promise.allSettled`
+ # lets the script exit cleanly with an empty body. Unlike a top-level lone call, whose
+ # unhandled rejection would fail the script, that clean exit proves nothing.
+ calls = extractor(_trajectory(_MAP_INLINE_ONE, _RECORD_FRAME[0] + body))
+
+ assert len(calls) == 1
+ assert calls[0]["action"] == "exec"
+ assert calls[0]["normalization_status"] == "unsupported_native_codex_exec_wrapper"
+
+
[email protected]("extractor", _EXTRACTORS)
+def test_inline_map_rejected_skill_read_earns_no_activation_credit(extractor):
+ source = (
+ 'const cmds=["cat /skills/example/SKILL.md"];'
+ "await Promise.allSettled(cmds.map(async cmd=>text(await tools.exec_command({cmd}))));"
+ )
+ calls = extractor(_trajectory(source, _RECORD_FRAME[0]))
+ result = _scorer(extractor, "check_activation")(calls, "example")
+
+ assert result["passed"] is None
+ assert result["score"] == 0.5
+ assert result["supported"] is False
+
+
[email protected]("extractor", _EXTRACTORS)
+ ("body", "is_error"),
+ [
+ pytest.param('{"exit_code":0,"output":"# Example\\n"}', False, id="record-exit-zero"),
+ pytest.param("# Example\nplain guidance\n", None, id="plain-text"),
+ ],
+)
+def test_inline_map_printed_output_proves_the_call_settled(extractor, body, is_error):
+ # The callback renders only after its own `await` resolves, so anything printed proves the
+ # call fulfilled. Refusing the empty body must not become a blanket rejection of the form.
+ source = (
+ 'const cmds=["cat /skills/example/SKILL.md"];'
+ "await Promise.allSettled(cmds.map(async cmd=>text(await tools.exec_command({cmd}))));"
+ )
+ calls = extractor(_trajectory(source, _RECORD_FRAME[0] + body))
+ result = _scorer(extractor, "check_activation")(calls, "example")
+
+ assert "normalization_status" not in calls[0]
+ assert calls[0].get("is_error") is is_error
+ assert result["passed"] is True
+ assert result["score"] == 0.75
+
+
[email protected]("extractor", _EXTRACTORS)
+def test_dynamic_map_complete_records_are_graded(extractor):
+ # The headline of #236: a skill read batched through `.map` is graded rather than written off
+ # as an unsupported wrapper. `test_dynamic_map_with_incomplete_records_stops_grading` pins the
+ # other half, from the same source and the same complete observation.
+ source = (
+ 'const cmds=["cat /skills/example/SKILL.md","python /skills/example/scripts/run.py"];'
+ "const results=await Promise.allSettled(cmds.map(async cmd=>tools.exec_command({cmd})));"
+ "results.forEach((r,i)=>text({i,...r}));"
+ )
+ complete = _record_observation(
+ [
+ {"i": 0, "status": "fulfilled", "value": {"exit_code": 0, "output": "# Example\n"}},
+ {"i": 1, "status": "fulfilled", "value": {"exit_code": 0, "output": "run.py completed\n"}},
+ ]
+ )
+ calls = extractor(_trajectory(source, complete))
+
+ assert [call["action"] for call in calls] == ["exec_command", "exec_command"]
+ assert [call["is_error"] for call in calls] == [False, False]
+ assert _scorer(extractor, "check_activation")(calls, "example")["score"] == 0.75
+ assert _scorer(extractor, "check_script_execution")(calls, "run.py")["score"] == 1.0
+ assert _scorer(extractor, "check_workflow_order")(calls, expected_skill="example")["score"] == 1.0
+
+
[email protected]("extractor", _EXTRACTORS)
+ "argument",
+ [
+ pytest.param("{cmd,timeout:5}", id="shorthand-first"),
+ pytest.param("{timeout:5,cmd}", id="literal-first"),
+ ],
+)
+def test_dynamic_map_merges_literal_siblings_with_the_mapped_element(extractor, argument):
+ # A mixed argument object: the element still reaches the tool unchanged under its own key and
+ # the literal sibling is carried through, on either side of the shorthand.
+ source = (
+ 'const cmds=["cat a.md"];'
+ f"const results=await Promise.allSettled(cmds.map(async cmd=>tools.exec_command({argument})));"
+ "results.forEach(text);"
+ )
+ calls = extractor(_trajectory(source, _record_observation([{"status": "fulfilled", "value": {"exit_code": 0}}])))
+
+ assert [call["action_input"] for call in calls] == [{"timeout": 5, "cmd": "cat a.md"}]
+ assert "normalization_status" not in calls[0]
diff --git a/tests/validators/test_rubric_eval.py b/tests/validators/test_rubric_eval.py
index f8ab16c5..4b73e472 100644
--- a/tests/validators/test_rubric_eval.py
+++ b/tests/validators/test_rubric_eval.py
@@ -20,12 +20,16 @@ from skillevaluator.inference.types import LLMClientError, LLMClientRefusedError
from skillevaluator.reporting import HTMLReporter
from skillevaluator.validators import rubric_eval
from skillevaluator.validators.rubric_eval import (
+ _DEFAULT_SUPPLEMENTARY_TOTAL_BYTES,
+ _MAX_CONFIGURED_SUPPLEMENTARY_TOTAL_BYTES,
+ _SUPPLEMENTARY_TOTAL_BYTES_ENV,
RUBRIC_JSON_SCHEMA,
RubricEvalValidator,
RubricJudge,
_collect_supplementary_content,
_extract_json,
_UnsafeRubricInputError,
+ supplementary_total_bytes,
)
@@ -334,14 +338,51 @@ class TestLinkedRubricGuidance:
assert collected["linked_markdown"] == {"GUIDE.md": "π"}
- @pytest.mark.parametrize(("per_file", "total"), [(1, 10), (10, 1)])
- def test_required_utf8_content_is_never_truncated(self, tmp_path, per_file, total):
+ @pytest.mark.parametrize(
+ ("earlier_guides", "total", "remaining"),
+ [
+ # The budget itself splits the character: nothing has been collected yet.
+ pytest.param(0, 1, 1, id="budget-splits-the-first-document"),
+ # The running total does: an earlier document leaves too few bytes for this one.
+ pytest.param(1, 8, 0, id="earlier-document-exhausts-the-budget"),
+ ],
+ )
+ def test_required_utf8_content_is_never_truncated(self, tmp_path, earlier_guides, total, remaining):
+ # The supplement budget is the only bound on required guidance, so it must stop the
+ # collection rather than cut a multi-byte character in half -- whether the budget is too
+ # small from the start or an earlier document has already spent it.
root = _write_skill(tmp_path)
- (root / "SKILL.md").write_text("[Guide](GUIDE.md)")
+ links = [f"[Earlier](earlier{index}.md)" for index in range(earlier_guides)]
+ (root / "SKILL.md").write_text("\n".join([*links, "[Guide](GUIDE.md)"]))
+ for index in range(earlier_guides):
+ (root / f"earlier{index}.md").write_text("x" * 8)
(root / "GUIDE.md").write_text("π", encoding="utf-8")
- with pytest.raises(_UnsafeRubricInputError):
- _collect_supplementary_content(root, max_bytes_per_file=per_file, max_total_bytes=total)
+ with pytest.raises(_UnsafeRubricInputError, match=f"{remaining}-byte limit: GUIDE.md"):
+ _collect_supplementary_content(root, max_bytes_per_file=10, max_total_bytes=total)
+
+ def test_required_guidance_fits_when_the_budget_covers_every_document(self, tmp_path):
+ # The companion of the case above: the same two documents are collected whole as soon as
+ # the budget holds both, so the earlier read is spending the budget, not failing on it.
+ root = _write_skill(tmp_path)
+ (root / "SKILL.md").write_text("[Earlier](earlier0.md)\n[Guide](GUIDE.md)")
+ (root / "earlier0.md").write_text("x" * 8)
+ (root / "GUIDE.md").write_text("π", encoding="utf-8")
+
+ collected = _collect_supplementary_content(root, max_bytes_per_file=10, max_total_bytes=10)
+
+ assert collected["linked_markdown"] == {"earlier0.md": "x" * 8, "GUIDE.md": "π"}
+
+ def test_required_guidance_is_not_bounded_by_the_preview_size(self, tmp_path):
+ # The per-file bound summarizes optional previews; required guidance answers to the
+ # supplement budget alone, so a guide larger than a preview is still collected whole.
+ root = _write_skill(tmp_path)
+ (root / "SKILL.md").write_text("[Guide](GUIDE.md)")
+ (root / "GUIDE.md").write_text("g" * 9000)
+
+ collected = _collect_supplementary_content(root, max_bytes_per_file=100, max_total_bytes=10000)
+
+ assert collected["linked_markdown"] == {"GUIDE.md": "g" * 9000}
@pytest.mark.parametrize(
"case",
@@ -359,7 +400,7 @@ class TestLinkedRubricGuidance:
"fifo",
],
)
- def test_incomplete_required_guidance_stops_before_judge(self, tmp_path, case):
+ def test_incomplete_required_guidance_stops_before_judge(self, tmp_path, case, monkeypatch):
root = _write_skill(tmp_path)
target = root / "GUIDE.md"
link = "GUIDE.md"
@@ -372,8 +413,11 @@ class TestLinkedRubricGuidance:
elif case == "invalid_utf8":
target.write_bytes(b"\xff")
elif case == "oversized":
+ # A single document larger than the configured budget cannot be collected whole.
+ monkeypatch.setenv("SKILLEVALUATOR_RUBRIC_SUPPLEMENT_BYTES", "3000")
target.write_text("x" * 3001)
elif case == "total_budget":
+ monkeypatch.setenv("SKILLEVALUATOR_RUBRIC_SUPPLEMENT_BYTES", "30000")
for index in range(11):
(root / f"guide{index}.md").write_text("x" * 3000)
(root / "SKILL.md").write_text("\n".join(f"[Guide](guide{i}.md)" for i in range(11)))
@@ -527,6 +571,88 @@ class TestLinkedRubricGuidance:
assert (root / "SKILL.md").read_bytes() == source.encode("utf-8")
+class TestSupplementaryBudget:
+ def test_default_budget_holds_a_real_linked_guide_graph(self, tmp_path):
+ # The reporter's graph in #236 is about 65 KB over 13 documents; the stock budget takes it.
+ root = _write_skill(tmp_path)
+ (root / "SKILL.md").write_text("\n".join(f"[Guide](guide{index}.md)" for index in range(13)))
+ for index in range(13):
+ (root / f"guide{index}.md").write_text("g" * 5000)
+
+ collected = _collect_supplementary_content(root)
+
+ assert len(collected["linked_markdown"]) == 13
+ assert all(len(text) == 5000 for text in collected["linked_markdown"].values())
+
+ def test_budget_default_and_overrides(self, monkeypatch):
+ monkeypatch.delenv(_SUPPLEMENTARY_TOTAL_BYTES_ENV, raising=False)
+ assert supplementary_total_bytes() == _DEFAULT_SUPPLEMENTARY_TOTAL_BYTES
+ assert supplementary_total_bytes({_SUPPLEMENTARY_TOTAL_BYTES_ENV: " 65536 "}) == 65536
+
+ @pytest.mark.parametrize("raw", ["", " ", "0", "-1", "1.5", "lots", "0x10"])
+ def test_unusable_budget_falls_back_to_the_default(self, raw):
+ assert supplementary_total_bytes({_SUPPLEMENTARY_TOTAL_BYTES_ENV: raw}) == _DEFAULT_SUPPLEMENTARY_TOTAL_BYTES
+
+ def test_budget_is_capped(self):
+ oversized = str(_MAX_CONFIGURED_SUPPLEMENTARY_TOTAL_BYTES * 4)
+ budget = supplementary_total_bytes({_SUPPLEMENTARY_TOTAL_BYTES_ENV: oversized})
+
+ assert budget == _MAX_CONFIGURED_SUPPLEMENTARY_TOTAL_BYTES
+
+ def test_configured_budget_reaches_the_collector(self, tmp_path, monkeypatch):
+ root = _write_skill(tmp_path)
+ (root / "SKILL.md").write_text("[Guide](GUIDE.md)")
+ (root / "GUIDE.md").write_text("g" * 4096)
+ monkeypatch.setenv(_SUPPLEMENTARY_TOTAL_BYTES_ENV, "4095")
+
+ with pytest.raises(_UnsafeRubricInputError):
+ _collect_supplementary_content(root)
+
+ monkeypatch.setenv(_SUPPLEMENTARY_TOTAL_BYTES_ENV, "4096")
+ assert _collect_supplementary_content(root)["linked_markdown"] == {"GUIDE.md": "g" * 4096}
+
+ @pytest.mark.parametrize("case", ["escape", "encoded_escape", "symlink", "ancestor_symlink", "hardlink"])
+ def test_a_larger_budget_never_widens_the_declared_root(self, tmp_path, monkeypatch, case):
+ # Raising the byte budget buys more of the skill's own guidance, never another path.
+ monkeypatch.setenv(_SUPPLEMENTARY_TOTAL_BYTES_ENV, str(_MAX_CONFIGURED_SUPPLEMENTARY_TOTAL_BYTES))
+ root = _write_skill(tmp_path)
+ (tmp_path / "outside.md").write_text("outside guidance")
+ link = "GUIDE.md"
+ if case == "escape":
+ link = "../outside.md"
+ elif case == "encoded_escape":
+ link = "%2e%2e%5coutside.md"
+ elif case == "symlink":
+ (root / "GUIDE.md").symlink_to(tmp_path / "outside.md")
+ elif case == "ancestor_symlink":
+ (tmp_path / "outside").mkdir()
+ (tmp_path / "outside/guide.md").write_text("outside guidance")
+ (root / "docs").symlink_to(tmp_path / "outside", target_is_directory=True)
+ link = "docs/guide.md"
+ else:
+ os.link(tmp_path / "outside.md", root / "GUIDE.md")
+ (root / "SKILL.md").write_text(f"[Guide]({link})")
+
+ with patch.object(RubricJudge, "process") as judge:
+ result = RubricEvalValidator().validate(root)
+
+ judge.assert_not_called()
+ assert result.metadata["rubric_eval"]["execution_status"] == "failed"
+ assert result.metadata["rubric_eval"]["overall_score"] is None
+ assert any(finding.check_name == "unsafe_skill_input" for finding in result.findings)
+
+ def test_optional_previews_still_stay_small_under_a_large_budget(self, tmp_path, monkeypatch):
+ monkeypatch.setenv(_SUPPLEMENTARY_TOTAL_BYTES_ENV, str(_MAX_CONFIGURED_SUPPLEMENTARY_TOTAL_BYTES))
+ root = _write_skill(tmp_path)
+ (root / "scripts").mkdir()
+ (root / "scripts/main.py").write_text("x" * 20000)
+
+ collected = _collect_supplementary_content(root)
+
+ assert collected["scripts"]["main.py"].endswith("... [truncated]")
+ assert len(collected["scripts"]["main.py"]) < 3100
+
+
class TestRubricEvalValidator:
def test_no_skills_found_records_failed_execution_status(self, tmp_path):
validator = RubricEvalValidator()