Datasets:

Modalities:
Text
Languages:
English
Size:
< 1K
ArXiv:
Libraries:
Datasets
Harbor
License:
loubnabnl's picture
loubnabnl HF Staff
Release v3.1, interim (copy of misc-org/collaborative-intelligence-harbor)
5873600 verified
Raw History Blame Contribute Delete
10.5 kB
"""Content identities for code/profile provenance, separate from task identities.
These hashes identify source and provider settings, not the full kernel/network
environment. Never put scenario instructions, private facts or seeds in a common
profile. Deployment details for optional services belong outside scoring config.
"""
from __future__ import annotations
import copy
import hashlib
import json
import re
import tomllib
from pathlib import Path
_SOURCE_SUFFIXES = {".py", ".js", ".mjs", ".lock"}
_HASH = re.compile(r"[0-9a-f]{64}")
def _hash(value):
data = json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()
return hashlib.sha256(data).hexdigest()
def _files_identity(files):
files = dict(sorted(files.items()))
return {"schema_version": 1, "files": files, "sha256": _hash(files)}
def _tree_identity(root, *, source_only=False):
root = Path(root)
if not root.is_dir():
raise FileNotFoundError(root)
files = {}
for file in sorted(root.rglob("*")):
if "__pycache__" in file.parts or file.suffix == ".pyc":
continue
if file.is_symlink():
raise ValueError("Code identity cannot follow symlinks")
if file.is_file() and (not source_only or file.suffix in _SOURCE_SUFFIXES):
files[file.relative_to(root).as_posix()] = hashlib.sha256(file.read_bytes()).hexdigest()
if not files:
raise ValueError("Code identity has no source files")
return _files_identity(files)
def runtime_code_identity(root=None):
"""Hash actual deployed package source, including JS and dependency locks."""
return _tree_identity(root or Path(__file__).parent, source_only=True)
def code_profile_identity(package_root=None, *, provider_settings=None, provider_files=None):
"""Common expected source/profile hash for strict reuse before task creation.
Callers supply only scenario-independent provider settings. The actual agent
context is independently retained by task_code_identity after all overlays.
"""
components = {"adapter": runtime_code_identity(package_root),
"provider_settings": _files_identity({"provider-settings.json": _hash(provider_settings or {})})}
if provider_files:
components["provider_files"] = _files_identity({
name: hashlib.sha256(Path(path).read_bytes()).hexdigest() for name, path in sorted(provider_files.items())})
return {"schema_version": 1, "components": components, "sha256": _hash(components)}
def task_code_identity(task):
"""Hash effective build code/settings after overlays, excluding task content.
This full manifest includes optional worker details; store it in the adapter
evidence, not the common scoring configuration. Only its agent component is
common to all scenarios of a fixed provider/scaffold profile.
"""
from .compact_runtime import FORMAT, runtime_manifest, runtime_view
task = Path(task)
team_compact = runtime_manifest(task / "environment/team")
verifier_compact = runtime_manifest(task / "tests")
team_runtime = runtime_view(task / "environment/team") if team_compact else task / "environment/team"
verifier_runtime = runtime_view(task / "tests") if verifier_compact else task / "tests"
components = {"agent": _tree_identity(task / "environment/agent")}
for name, root in (("team_adapter", team_runtime / "adapter/collab_harbor"),
("verifier_adapter", verifier_runtime / "adapter/collab_harbor"),
("team_upstream", team_runtime / "upstream/src"),
("verifier_upstream", verifier_runtime / "upstream/src")):
components[name] = runtime_code_identity(root)
for role, context in (("team", task / "environment/team"), ("verifier", task / "tests")):
compact = runtime_manifest(context)
if compact is not None:
components[role + "_runtime_distribution"] = _files_identity({
name: hashlib.sha256((context / name).read_bytes()).hexdigest()
for name in ("runtime.tar.gz", "runtime.json", "runtime-unpack.py")})
if (team_compact is None) != (verifier_compact is None) or team_compact != verifier_compact:
raise ValueError("Service and verifier must use the same runtime distribution")
if team_compact is not None:
distribution = {"format": FORMAT, "archive_sha256": team_compact["archive_sha256"]}
components["runtime_distribution"] = _files_identity({"runtime-distribution.json": _hash(distribution)})
if (task / "task.toml").exists() or (task / "environment/docker-compose.yaml").exists():
policy = tomllib.loads((task / "task.toml").read_text())
components["environment_policy"] = _files_identity({
"docker-compose.yaml": hashlib.sha256((task / "environment/docker-compose.yaml").read_bytes()).hexdigest(),
"task-runtime-policy.json": _hash({name: policy.get(name, {}) for name in ("agent", "environment")}),
})
for name, folder in (("team_build", "environment/team"), ("verifier_build", "tests")):
components[name] = _files_identity({file: hashlib.sha256((task / folder / file).read_bytes()).hexdigest()
for file in ("Dockerfile", "requirements.txt")})
components["verifier_entrypoint"] = _files_identity({
"test.sh": hashlib.sha256((task / "tests/test.sh").read_bytes()).hexdigest()})
worker = task / "environment/worker"
if worker.exists():
components["worker_build"] = _tree_identity(worker)
# Give chat and coding tasks one common execution-code profile. For coding
# it is the actual worker source; for chat it is the same unused source
# shipped with the service. Optional worker presence must not split tasks.
worker_sources = {}
adapter = team_runtime / "adapter/collab_harbor"
for name in ("coding.py", "pytest_child.py", "provenance.py"):
source = worker / name if worker.exists() else adapter / name
if source.exists():
worker_sources[name] = hashlib.sha256(source.read_bytes()).hexdigest()
sandbox_name = "collab_intel/harness/sandbox.py"
sandbox = worker / sandbox_name if worker.exists() else team_runtime / "upstream/src" / sandbox_name
if sandbox.exists():
worker_sources[sandbox_name] = hashlib.sha256(sandbox.read_bytes()).hexdigest()
for name in ("collab_intel/__init__.py", "collab_intel/harness/__init__.py"):
source = worker / name
worker_sources[name] = hashlib.sha256(source.read_bytes() if worker.exists() and source.exists() else b"").hexdigest()
components["execution_profile"] = _files_identity(worker_sources)
return {"schema_version": 1, "components": components, "sha256": _hash(components)}
def validate_code_identity(value):
"""Reject malformed or stale manifest hashes; return the verified hash."""
if not isinstance(value, dict) or value.get("schema_version") != 1:
raise ValueError("Invalid code identity schema")
if "files" in value:
entries = value["files"]
if not isinstance(entries, dict) or not entries:
raise ValueError("Code identity has no file inventory")
for name, digest in entries.items():
if (not isinstance(name, str) or not name or Path(name).is_absolute() or ".." in Path(name).parts
or not isinstance(digest, str) or not _HASH.fullmatch(digest)):
raise ValueError("Invalid code file identity")
else:
entries = value.get("components")
if not isinstance(entries, dict) or not entries:
raise ValueError("Code identity has no component inventory")
for component in entries.values():
validate_code_identity(component)
if value.get("sha256") != _hash(entries):
raise ValueError("Code identity hash differs from its inventory")
return value["sha256"]
def record_runtime_provenance(configuration, role="verifier", *, package_root=None):
"""Return a copied config with this role's actual code bytes identified."""
result = copy.deepcopy(configuration)
provenance = result.setdefault("code_provenance", {"schema_version": 1})
if not isinstance(provenance, dict) or provenance.get("schema_version") != 1:
raise ValueError("Invalid runtime code provenance")
provenance[role] = runtime_code_identity(package_root)
entrypoint = Path("/tests/test.sh")
if role == "verifier" and entrypoint.is_file():
actual = _files_identity({"test.sh": hashlib.sha256(entrypoint.read_bytes()).hexdigest()})
if provenance.get("verifier_entrypoint", actual) != actual:
raise ValueError("Verifier entrypoint differs from declared source")
provenance["verifier_entrypoint"] = actual
return result
def executor_runtime_identity(url):
"""Read additive worker metadata; old workers remain explicitly unreported."""
import urllib.request
try:
with urllib.request.urlopen(url.rstrip("/") + "/health", timeout=5) as response:
data = json.loads(response.read(512 * 1024))
identity = data.get("code_identity")
if identity is None:
return {"state": "legacy-unreported"}
validate_code_identity(identity)
return {"state": "reported", "identity": identity}
except (OSError, ValueError, TypeError, AttributeError) as error:
return {"state": "unreported", "reason": type(error).__name__}
def configuration_code_group(configuration):
"""Explicitly separate legacy records and verify new common code hashes."""
provenance = configuration.get("code_provenance")
profile = configuration.get("agent", {}).get("code_profile") or configuration.get("code_profile")
if provenance is None and profile is None:
return {"state": "legacy-unhashed"}
if provenance is not None:
if not isinstance(provenance, dict) or provenance.get("schema_version") != 1:
raise ValueError("Invalid runtime code provenance")
roles = {k: v for k, v in provenance.items() if k != "schema_version"}
if not roles:
raise ValueError("Empty runtime code provenance")
for value in roles.values():
validate_code_identity(value)
if profile is not None:
validate_code_identity(profile)
return {"state": "hashed", "sha256": _hash({"runtime": provenance, "profile": profile})}