Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions .agents/skills/import-standard/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,9 @@ interpreter: it copies a bundled entry's whole folder to the user catalogue
and returns the writable path. For a new key, create the returned directory,
or let `cli new` create it. A user folder replaces the bundled folder **in
full**, even if incomplete: keep its JSON, drivers, wrappers, model templates
and other resources together. `new version`, `conform` and `prove` write user
copies too. Never edit `site-packages`.
and other resources together. `new version` writes a user copy too; `conform`
and `prove` copy nothing: a bundled entry's proofs go to `paths.proofs_dir()`.
Never edit `site-packages`.

Default to a personal import in `paths.catalogue_dir()` (Linux default:
`~/.local/share/nullius/catalogue/`), in `benchmarks/KEY`, `agents/KEY` or
Expand Down
2 changes: 1 addition & 1 deletion .claude/rules/running.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ automatically: `nullius migrate --from CHECKOUT` previews, `--apply` copies.
A set `WORKSPACES_DIR` and raw runs stay where they are; default workspaces are copied.

Migrated catalogue entries keep their versions across upgrades as user overrides; **Use bundled entry** on an entry's page removes
its user override, including local proof records, to resume bundled updates.
its user override, keeping its local proof records, to resume bundled updates.
Existing destination entries must match exactly.
Conflicts stop migration before copying.

Expand Down
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ Add neither by default.
another source or someone's fixes; never a change of our driver. Bring an
official version first.
- Definitions hold configuration. Proof runs write only `proofs.json`: a bundled
entry's in a user copy, which then hides the bundled one. Read both through
entry's under `paths.proofs_dir()`, copying nothing. Read both through
`contract/definitions.py`; never infer proven ports from raw JSON.

## Issues and pull requests
Expand Down
3 changes: 2 additions & 1 deletion app/nullius/catalogue/catalog.py
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,8 @@ def entry_dir(key: str, root: str | None = None) -> str | None:


def writable_dir(key: str, root: str | None = None) -> str:
return storage.writable_dir(BENCHMARKS, key, ROOT, root)
from nullius.standard.contract import definitions # it reads this module
return definitions.copied("benchmark", key, root, ROOT)


def signature(root: str | None = None) -> tuple:
Expand Down
7 changes: 5 additions & 2 deletions app/nullius/catalogue/storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,11 +65,12 @@ def ensure_writable(target: str, bundled: str) -> None:
raise ValueError("the bundled catalogue is read-only; use the user catalogue")


def writable_dir(group: str, key: str, bundled: str, root: str | None = None) -> str:
def writable_dir(group: str, key: str, bundled: str, root: str | None = None, prepare=None) -> str:
"""Copy a selected bundled folder in full before returning its user copy.

An existing user folder is left intact. Staging keeps an interrupted copy
from shadowing a bundled entry with half of its files.
from shadowing a bundled entry with half of its files; ``prepare`` is given
the staged copy before it takes its place.
"""
if not key or key in (".", "..") or os.path.basename(key) != key:
raise ValueError("an entry key is a folder name")
Expand All @@ -94,6 +95,8 @@ def writable_dir(group: str, key: str, bundled: str, root: str | None = None) ->
for name in files:
path = os.path.join(folder, name)
os.chmod(path, os.stat(path).st_mode | stat.S_IWUSR)
if prepare:
prepare(copied)
os.rename(copied, target)
return target

Expand Down
7 changes: 6 additions & 1 deletion app/nullius/paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,11 @@ def catalogue_dir(env=None) -> str:
return env.get("NULLIUS_CATALOGUE") or os.path.join(data_dir(env), "catalogue")


def proofs_dir(env=None) -> str:
"""The user's proofs of bundled catalogue entries."""
return os.path.join(data_dir(env), "proofs")


def workspaces_dir(env=None) -> str:
env = os.environ if env is None else env
return env.get("WORKSPACES_DIR") or os.path.join(data_dir(env), "workspaces")
Expand All @@ -85,7 +90,7 @@ def main(argv=None) -> int:
parser = argparse.ArgumentParser(prog="nullius paths", description="Show Nullius's persistent user directories (no secret values).")
parser.add_argument("--json", action="store_true")
args = parser.parse_args(argv)
values = {"settings": settings_file(), "secrets": secrets_dir(), "prices": prices_file(), "own prices": own_prices_file(), "catalogue": catalogue_dir(),
values = {"settings": settings_file(), "secrets": secrets_dir(), "prices": prices_file(), "own prices": own_prices_file(), "catalogue": catalogue_dir(), "proofs": proofs_dir(),
"workspaces": workspaces_dir(), "runs": runs_dir(), "recipes": recipes_dir(), "cache": cache_dir()}
if args.json:
print(json.dumps(values, indent=2))
Expand Down
152 changes: 135 additions & 17 deletions app/nullius/standard/contract/definitions.py
Original file line number Diff line number Diff line change
Expand Up @@ -1874,14 +1874,115 @@ def writable_dir(kind: str, key: str, root: Optional[str] = None) -> str:
"""The user folder, copying all bundled files before an edit if needed."""
if not _KEY.fullmatch(key):
raise ValueError("a key is lower case letters, digits and dashes")
return storage.writable_dir(KINDS[names.kind(kind)]["dir"], key, CATALOGUE, root)
return copied(kind, key, root)


def copied(kind: str, key: str, root: Optional[str] = None, bundled: Optional[str] = None) -> str:
"""The user folder of an entry, first copied from ``bundled`` if it is
there alone. The user's proofs of the bundled entry are written into the
copy before it takes its place."""
kind = names.kind(kind)
group = KINDS[kind]["dir"]
with _lock(f"{group}/{key}"):
source = storage.entry_dir(group, key, bundled or CATALOGUE, root)
evidence = with_own(source, kind) if source else None
return storage.writable_dir(group, key, bundled or CATALOGUE, root,
(lambda staged: proofs.write(staged, evidence)) if evidence else None)


def _own(folder: str, kind: str) -> Optional[str]:
"""Where the user's proofs of a bundled entry are kept, apart from the
package and the user catalogue; None for a folder outside the bundle."""
try:
storage.ensure_writable(folder, CATALOGUE)
except ValueError:
return os.path.join(paths.proofs_dir(), KINDS[names.kind(kind)]["dir"], os.path.basename(folder))
return None


def with_own(folder: str, kind: str) -> Optional[dict]:
"""A bundled entry's evidence with the user's proofs of it, as its copy
or a host is given it in one ``proofs.json``; None when the user has none."""
kind = names.kind(kind)
user, path = _own(folder, kind), definition_path(folder, kind)
if not user or not os.path.lexists(os.path.join(user, proofs.FILE)) or not os.path.isfile(path):
return None
with open(path) as f:
return proofs.combined(names.definition(json.load(f)), kind, folder, user)


class Unfit(ValueError):
"""A user copy's proofs that the bundled entry cannot take: the copy stays."""


def _held(folder: str, d: Optional[dict], kind: str) -> dict:
"""The version blocks a user copy holds as evidence of the bundled ``d``:
its ``proofs.json``, else what its definition embeds. A bundled entry
without a definition, ``d`` None, can take none."""
file = os.path.join(folder, proofs.FILE)
try:
value = proofs.read(folder)
except ValueError:
value = [] # not a document: said below
if value is None:
file = definition_path(folder, kind)
try:
with open(file) as f:
value = proofs.document(names.definition(json.load(f)), kind)
except (FileNotFoundError, ValueError, TypeError, AttributeError, KeyError):
return {} # a definition that does not read embeds no evidence
value["versions"] = {v: b for v, b in value["versions"].items() if b}
if not value["versions"]:
return {}
if d is None:
vs = value.get("versions") if isinstance(value, dict) else None
bad = sorted(v for v, b in vs.items() if b and (not isinstance(b, dict) or any(b.values()))) \
if isinstance(vs, dict) else [""]
value = {"versions": {}}
else:
bad = proofs.unfit(value, d, kind)
if bad:
of = ", ".join(v for v in bad if v)
raise Unfit(f"{said(kind).capitalize()} {os.path.basename(folder)}: the copy is kept. Its proofs"
f"{' of ' + of if of else ''} do not fit the bundled entry; remove them from {file} first.")
return value["versions"]


def use_bundled(group: str, key: str, bundled_root: Optional[str] = None) -> None:
"""Remove the user's copy of a bundled entry, of ``bundled_root`` for a
catalogue-only benchmark. The proofs it holds that the bundle does not
are kept, as the user's proofs of the bundled entry, and replace the ones
kept before of the versions it holds; ``Unfit`` before anything is
removed when the bundled entry cannot take them."""
kind = next((k for k, spec in KINDS.items() if spec["dir"] == group), None)
with _lock(f"{group}/{key}"):
bundled = kind and storage.can_restore(group, key, CATALOGUE) and entry_dir(kind, key, root=CATALOGUE)
if bundled:
path, d, held = definition_path(bundled, kind), None, {}
if os.path.isfile(path):
with open(path) as f:
d = names.definition(json.load(f))
for directory in (storage.LEGACY if group == "modules" else (group,)):
folder = os.path.join(paths.catalogue_dir(), directory, key)
if os.path.isdir(folder):
held.update(_held(folder, d, kind))
if held:
shipped = (proofs.read(bundled) or proofs.document(d, kind))["versions"]
user = _own(bundled, kind)
was = proofs.own(d, kind, user) or dict(proofs.document(d, kind), versions={})
mine = {v: b for v, b in held.items() if b != shipped.get(v)}
if mine or set(held) & set(was["versions"]):
kept = {v: b for v, b in was["versions"].items() if v not in held}
proofs.write_own(user, dict(was, versions={**kept, **mine}), d, kind)
storage.use_bundled(group, key, bundled_root or CATALOGUE)


def read_document(path: str, kind: str) -> dict:
"""An authored definition with sibling evidence, before semantic checks."""
with open(path) as f:
d = names.definition(json.load(f))
return proofs.attach(d, names.kind(kind), os.path.dirname(path))
folder = os.path.dirname(path)
return proofs.attach(d, names.kind(kind), folder, _own(folder, kind))


def _read(path: str, kind: str, key: str) -> Tuple[Optional[dict], List[str]]:
Expand Down Expand Up @@ -2091,17 +2192,34 @@ def path_of(d: dict) -> str:
return definition_path(d["_here"], d["_kind"])


def _slot(folder: str) -> Optional[str]:
"""``group/key`` for an entry folder of the bundled or the user catalogue."""
parent, key = os.path.split(os.path.realpath(folder))
base, group = os.path.split(parent)
group = "modules" if group in storage.LEGACY else group
if group in {spec["dir"] for spec in KINDS.values()} and base in {os.path.realpath(r) for r in storage.roots(CATALOGUE)}:
return f"{group}/{key}"
return None


@contextlib.contextmanager
def _locked(path: str):
"""One writer of a definition file at a time, across processes."""
def _lock(name: str):
where = os.path.join(paths.cache_dir(), "locks")
os.makedirs(where, exist_ok=True)
with ondisk.locked(os.path.join(where, hashlib.sha256(os.path.realpath(path).encode()).hexdigest()[:24])):
with ondisk.locked(os.path.join(where, hashlib.sha256(name.encode()).hexdigest()[:24])):
yield


def _locked(path: str):
"""One writer of an entry at a time, across processes: of its definition,
its proofs, its copy and the copy's removal. A catalogue entry is one
whichever folder holds it; any other is its file."""
return _lock(_slot(os.path.dirname(path)) or os.path.realpath(path))


def save(d: dict, change: Optional[Callable[[dict], None]] = None) -> None:
"""Write only generated evidence to the entry's sibling ``proofs.json``.
"""Write only generated evidence to the entry's sibling ``proofs.json``;
a bundled entry's to the user's proofs of it, its version alone.

``change``: what the run decided, applied to the definition as it is on
disk now, under a lock - not to the copy loaded when a long run started,
Expand All @@ -2111,18 +2229,13 @@ def save(d: dict, change: Optional[Callable[[dict], None]] = None) -> None:
Without it, save the caller's evidence for its version. Authored fields
are never written, including legacy embedded evidence; the sibling then
supersedes that evidence. A deleted or replaced definition is refused."""
# Explicit fixture roots remain local. Only a loaded bundled entry needs
# copying; helpers and model files beside its definition must follow it.
folder = d["_here"]
inside = os.path.realpath(folder).startswith(os.path.join(os.path.realpath(CATALOGUE), "")) # never scan the bundle for a user entry
bundled = inside and entry_dir(d["_kind"], d["key"], root=CATALOGUE) # under any of a Module's folder names
if bundled and os.path.realpath(folder) == os.path.realpath(bundled):
d["_here"] = writable_dir(d["_kind"], d["key"])
storage.ensure_writable(d["_here"], CATALOGUE)
user = _own(d["_here"], d["_kind"]) # explicit fixture roots remain local
path = path_of(d)
with _locked(path):
current = read_document(path, d["_kind"])
if not isinstance(current, dict) or current.get("key") != d["key"] or current.get("schema") != KINDS[d["_kind"]]["schema"]:
selected = user and entry_dir(d["_kind"], d["key"]) # a copy made since hides the bundled entry
if (not isinstance(current, dict) or current.get("key") != d["key"] or current.get("schema") != KINDS[d["_kind"]]["schema"]
or (selected and os.path.realpath(selected) != os.path.realpath(d["_here"]))):
raise ValueError("the definition changed identity while its proof ran")
version = d.get("_version", str((d.get("upstream") or {}).get("version") or ""))
resolved = resolve(current, version)
Expand All @@ -2134,10 +2247,15 @@ def save(d: dict, change: Optional[Callable[[dict], None]] = None) -> None:
else:
work = {"offers": d.get("offers") or [], "proven": d.get("proven") or {}}
evidence = proofs.document(current, d["_kind"])
if user:
evidence["versions"] = dict((proofs.own(current, d["_kind"], user) or {}).get("versions") or {})
fields = ("proven",) if d["_kind"] == "benchmark" or "versions" in current else proofs.FIELDS
evidence["versions"][version] = {f: work[f] for f in fields}
proofs.validate(evidence, current, d["_kind"])
proofs.write(d["_here"], evidence)
if user:
proofs.write_own(user, evidence, current, d["_kind"])
else:
proofs.validate(evidence, current, d["_kind"])
proofs.write(d["_here"], evidence)
d["proven"] = work["proven"]
if d["_kind"] != "benchmark":
d["offers"] = ([p for p in ports.PORTS if p in d["proven"]]
Expand Down
81 changes: 74 additions & 7 deletions app/nullius/standard/contract/proofs.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
Versioned participants derive offers from their own proven ports as before.

An existing document replaces all embedded evidence; an absent document keeps
legacy definitions readable. Never combine evidence from different folders.
legacy definitions readable. Never combine evidence from different folders,
but for a bundled entry: the user's proofs of it are kept apart, in the same
document, and each version block there replaces the bundle's.
Writers hold the definition's lock while reading, changing and replacing it.
"""
from __future__ import annotations
Expand Down Expand Up @@ -98,16 +100,81 @@ def _unique(pairs):
return out


def attach(d: dict, kind: str, folder: str) -> dict:
"""Read sibling evidence, or keep embedded legacy evidence when absent."""
if not isinstance(d, dict):
return d
def read(folder: str):
"""A folder's evidence document as written, or None without one."""
try:
with open(os.path.join(folder, FILE)) as f:
value = json.load(f, object_pairs_hook=_unique)
return json.load(f, object_pairs_hook=_unique)
except FileNotFoundError:
return d
return None


def own(d: dict, kind: str, folder: str):
"""The user's proofs of a bundled entry, kept in ``folder``, or None.
A version the bundle no longer declares is left out, never refused."""
value = read(folder)
if value is None:
return None
if isinstance(value, dict) and isinstance(value.get("versions"), dict):
declared = blocks(d)
value = dict(value, versions={v: b for v, b in value["versions"].items() if v in declared})
validate(value, d, kind)
return value


def unfit(value, d: dict, kind: str) -> list:
"""The versions of ``value`` that ``validate`` refuses for ``d``, each on
its own; all of them for another entry's document. A version ``d`` does
not declare is none of them."""
vs = value.get("versions") if isinstance(value, dict) else None
if not isinstance(vs, dict):
return [""]
try:
validate(dict(value, versions={}), d, kind)
except ValueError:
return list(vs) or [""]
bad = []
for v in set(vs) & set(blocks(d)):
try:
validate(dict(value, versions={v: vs[v]}), d, kind)
except ValueError:
bad.append(v)
return sorted(bad)


def write_own(folder: str, value: dict, d: dict, kind: str) -> None:
"""Replace the user's proofs of a bundled entry, kept in ``folder``. The
blocks there of versions ``d`` does not declare stay, unread, for a bundle
that declares them again."""
declared = blocks(d)
validate(dict(value, versions={v: b for v, b in value["versions"].items() if v in declared}), d, kind)
was = read(folder)
old = was.get("versions") if isinstance(was, dict) else None
extra = {v: b for v, b in old.items() if v not in declared} if isinstance(old, dict) else {}
os.makedirs(folder, exist_ok=True)
write(folder, dict(value, versions={**extra, **value["versions"]}))


def combined(d: dict, kind: str, folder: str, user: str | None = None):
"""The evidence read with ``d``: its folder's document, with the version
blocks of a bundled entry's ``user`` proofs over it. None without either."""
value = read(folder)
if value is not None:
validate(value, d, kind)
mine = own(d, kind, user) if user else None
if mine is None:
return value
value = value or document(d, kind)
return dict(value, versions={**value["versions"], **mine["versions"]})


def attach(d: dict, kind: str, folder: str, user: str | None = None) -> dict:
"""Read sibling evidence, or keep embedded legacy evidence when absent."""
if not isinstance(d, dict):
return d
value = combined(d, kind, folder, user)
if value is None:
return d
out = strip(d)
for v, b in blocks(out).items():
evidence = names.definition(copy.deepcopy(value["versions"].get(v, {})))
Expand Down
6 changes: 6 additions & 0 deletions app/nullius/standard/runner/payload.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,12 @@ def build(cache: str, *, package: Path | None = None, catalogue: str | None = No
contents = _entry(entry)
except json.JSONDecodeError:
continue # Unfinished JSON drafts are not runnable catalogue entries.
try: # the user's proofs of a bundled entry travel in its one document
own = definitions.with_own(str(entry), kind[:-1])
except (OSError, ValueError, TypeError, AttributeError):
continue # refused here when read, so not sent as if it ran
if own:
contents["proofs.json"] = ((json.dumps(own, indent=2) + "\n").encode(), 0o644)
files.update({f"catalogue/{kind}/{name}/{r}": value for r, value in contents.items()})
for bench, name in sets or ():
try:
Expand Down
Loading
Loading