AgentArk / compatibility.py
P90-RushB's picture
Define task environment labels as minimum supported versions
90cd4d1 verified
Raw History Blame Contribute Delete
4.88 kB
"""AgentArk task catalog compatibility and selection (standard library only).
A task's labeled env_version is its minimum supported environment version.
All later environment versions are supported by project policy. This is not
a statement that every task has been executed on every later environment.
"""
import argparse
import json
import re
from pathlib import Path
COMPATIBILITY_POLICY = {
"id": "minimum-env-version-v1",
"rule": "environment_version >= min_env_version",
"minimum_field": "min_env_version",
"legacy_minimum_field": "env_version",
"specifier_field": "env_version_spec",
"forward_compatible": True,
"version_comparison": "numeric dotted components; missing components are zero",
"compatible_env_versions_semantics": "known published compatible versions; not exhaustive and not a test matrix",
"validation_semantics": "existing validation fields and evidence describe actual tests only",
"requirements_semantics": "platform and separately declared wrapper/capability requirements still apply",
}
def version_key(value: str) -> tuple[int, ...]:
"""Compare 1.0.10 numerically; regard 1.0 and 1.0.0 as equal."""
if not isinstance(value, str) or not re.fullmatch(r"\d+(?:\.\d+)*", value):
raise ValueError(f"Expected a numeric dotted environment version, got {value!r}")
parts = [int(part) for part in value.split(".")]
while len(parts) > 1 and parts[-1] == 0:
parts.pop()
return tuple(parts)
def minimum_env_version(row: dict) -> str:
labeled = row["env_version"]
minimum = row.get("min_env_version", labeled)
if version_key(minimum) != version_key(labeled):
raise ValueError(f"Minimum contradicts labeled env_version for {row.get('path', row.get('task_id'))}")
return minimum
def supports_environment(row: dict, env_version: str) -> bool:
return version_key(env_version) >= version_key(minimum_env_version(row))
def normalize_task(row: dict, published_env_versions) -> dict:
"""Add range metadata without altering artifact identity or test evidence."""
minimum = minimum_env_version(row)
known = set(published_env_versions) | set(row.get("compatible_env_versions", [])) | {minimum}
for version in known:
version_key(version)
compatible = sorted((v for v in known if supports_environment(row, v)), key=lambda v: (version_key(v), v))
return {
**row,
"min_env_version": minimum,
"env_version_spec": f">={minimum}",
"env_compatibility_policy": COMPATIBILITY_POLICY["id"],
"compatible_env_versions": compatible,
}
def select_tasks(rows: list[dict], env_version: str, platform: str | None = None,
task_ids: set[int] | None = None) -> list[dict]:
"""Latest compatible task version per task/platform; no downloads or install.
An unsupported new task version must not hide an older compatible version.
Separately declared requirements are returned intact for the caller to honor.
"""
version_key(env_version)
selected = {}
def rank(row):
task_version = row["task_version"]
if task_version.startswith("v"):
task_version = task_version[1:]
return version_key(task_version), version_key(minimum_env_version(row)), row["path"]
for row in rows:
if platform is not None and row["platform"] != platform:
continue
if task_ids is not None and int(row["task_id"]) not in task_ids:
continue
if not supports_environment(row, env_version):
continue
key = (int(row["task_id"]), row["platform"])
if key not in selected or rank(row) > rank(selected[key]):
selected[key] = row
return [selected[key] for key in sorted(selected)]
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--registry", type=Path, required=True, help="Downloaded registry/tasks.jsonl")
parser.add_argument("--env-version", required=True)
parser.add_argument("--platform", choices=("windows", "linux"))
parser.add_argument("--task-id", type=int, action="append", help="Repeat to select multiple task IDs")
args = parser.parse_args()
rows = [json.loads(line) for line in args.registry.read_text(encoding="utf-8-sig").splitlines() if line.strip()]
try:
selected = select_tasks(rows, args.env_version, args.platform, set(args.task_id) if args.task_id else None)
if args.task_id and {int(r["task_id"]) for r in selected} != set(args.task_id):
parser.error("At least one requested task has no compatible artifact for this environment/platform")
except (ValueError, KeyError) as exc:
parser.error(str(exc))
for row in selected:
print(json.dumps(row, ensure_ascii=False, sort_keys=True))
if __name__ == "__main__":
main()