encore-science 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ """Encore: check a dataset against the paper it came from, on your own machine (docs/encore.md)."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
encore_science/cli.py ADDED
@@ -0,0 +1,141 @@
1
+ """encore: check a dataset against the paper it came from (docs/encore.md).
2
+
3
+ encore check DATA --paper PAPER [--doi DOI] [--title T] [--full] [--out DIR] [--model M]
4
+ encore status [DIR]
5
+ encore request DATASET --why TEXT [--draft | --version V]
6
+ encore queue
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import datetime
13
+ import json
14
+ import shutil
15
+ import subprocess
16
+ import sys
17
+ import urllib.request
18
+ from pathlib import Path
19
+
20
+ from . import __version__
21
+ from .run import Dataset, Run, Stop, dataset_of, slug
22
+
23
+ REPO = "catalystneuro/encore"
24
+ MODEL = "claude-opus-5-5"
25
+
26
+
27
+ def check(args) -> int:
28
+ out = args.out
29
+ if out is None:
30
+ name = args.data.rstrip("/").rsplit("/", 1)[-1] or "dataset"
31
+ out = Path(f"encore-{slug(name)}-{datetime.date.today():%Y-%m-%d}")
32
+ out = Path(out)
33
+ state = out / "state.json"
34
+ if state.is_file():
35
+ saved = json.loads(state.read_text())
36
+ dataset = Dataset(**saved["dataset"])
37
+ else:
38
+ dataset = dataset_of(args.data, args.version or ("draft" if args.draft else ""))
39
+ run = Run(out, dataset, args.paper, args.doi, args.title, args.full, args.model, args.ref, sandbox=not args.no_sandbox)
40
+ report = run.go()
41
+ print(f"\n{report.read_text()}\nReport: {report}")
42
+ return 0
43
+
44
+
45
+ def status(args) -> int:
46
+ out = Path(args.dir) if args.dir else max(Path(".").glob("encore-*/state.json"), default=None,
47
+ key=lambda p: p.stat().st_mtime)
48
+ if out is None:
49
+ print("No encore run here. Give its directory: encore status DIR")
50
+ return 1
51
+ state_path = out if out.name == "state.json" else out / "state.json"
52
+ state = json.loads(state_path.read_text())
53
+ print(f"{state['title']} · {state['dataset']['location']} · {state['mode']} run, started {state['started'][:16]}")
54
+ for role, r in state["roles"].items():
55
+ print(f" {role:<18} {r['status']:<8} {r.get('started', '')[11:16]}–{r.get('finished', '')[11:16]}")
56
+ running = [r for r, v in state["roles"].items() if v["status"] == "running"]
57
+ if running:
58
+ stream = state_path.parent / "logs" / f"{running[0]}.jsonl"
59
+ tools = state_path.parent / "registry" / "tools" / "progress.py"
60
+ if stream.is_file() and tools.is_file():
61
+ lines = subprocess.run([sys.executable, str(tools)], input=stream.read_text(), capture_output=True,
62
+ text=True).stdout.splitlines()
63
+ print(f"\nThe last steps of {running[0]}:")
64
+ print("\n".join(" " + line for line in lines[-8:]))
65
+ if state.get("finished"):
66
+ print(f"\nFinished {state['finished'][:16]}: {state_path.parent / 'report.md'}")
67
+ return 0
68
+
69
+
70
+ def request(args) -> int:
71
+ if shutil.which("gh") is None:
72
+ print("encore request needs the GitHub CLI (gh), signed in: https://cli.github.com")
73
+ return 1
74
+ version = ("draft" if args.draft else "the published version below" if args.version else "latest published")
75
+ body = (f"### Dataset\n\n{args.dataset}\n\n### Version\n\n{version}\n\n### Published version\n\n"
76
+ f"{args.version or '_No response_'}\n\n### Why\n\n{args.why}\n")
77
+ url = subprocess.run(["gh", "issue", "create", "--repo", REPO, "--title", f"Run request: {args.dataset}",
78
+ "--label", "run-request", "--body", body], check=True, capture_output=True,
79
+ text=True).stdout.strip()
80
+ print(f"Requested: {url}\nIts place in the queue: encore queue")
81
+ return 0
82
+
83
+
84
+ def queue(args) -> int:
85
+ api = f"https://api.github.com/repos/{REPO}/issues?labels=queue-board&state=open"
86
+ with urllib.request.urlopen(urllib.request.Request(api, headers={"Accept": "application/vnd.github+json"})) as r:
87
+ boards = json.load(r)
88
+ if not boards:
89
+ print("The queue board is not up yet.")
90
+ return 1
91
+ print(boards[0]["body"])
92
+ return 0
93
+
94
+
95
+ def main(argv: list[str] | None = None) -> int:
96
+ parser = argparse.ArgumentParser(prog="encore", description="Check a dataset against the paper it came from.")
97
+ parser.add_argument("--version", action="version", version=f"encore {__version__}")
98
+ sub = parser.add_subparsers(dest="command", required=True)
99
+
100
+ c = sub.add_parser("check", help="test a paper's claims on a dataset, on this machine")
101
+ c.add_argument("data", help="a directory of files, a URL, or a dataset in an archive (DANDI:000147)")
102
+ c.add_argument("--paper", type=Path, help="the paper, as a PDF or a text file")
103
+ c.add_argument("--doi", help="the paper's DOI, when the PDF does not show it")
104
+ c.add_argument("--title", help="the paper's title, for the report")
105
+ c.add_argument("--full", action="store_true", help="add the verification rounds (several hours more)")
106
+ c.add_argument("--draft", action="store_true", help="for a DANDI dataset: use its draft")
107
+ c.add_argument("--version", dest="version", help="for an archive dataset: the version to use")
108
+ c.add_argument("--out", help="where the run and its report go (default: ./encore-<name>-<date>)")
109
+ c.add_argument("--model", default=MODEL)
110
+ c.add_argument("--ref", default="main", help="the registry's branch or tag to take the protocol from")
111
+ c.add_argument("--no-sandbox", action="store_true", help="run the agents' commands outside Claude Code's sandbox")
112
+ c.set_defaults(func=check)
113
+
114
+ s = sub.add_parser("status", help="how far a run has got")
115
+ s.add_argument("dir", nargs="?")
116
+ s.set_defaults(func=status)
117
+
118
+ r = sub.add_parser("request", help="ask for an attempt on the registry's shared queue")
119
+ r.add_argument("dataset", help="as in the registry: 000147, DANDI:000147, CRCNS:ret-1")
120
+ r.add_argument("--why", required=True, help="what changed; links to the conversion's issue or pull request")
121
+ g = r.add_mutually_exclusive_group()
122
+ g.add_argument("--draft", action="store_true")
123
+ g.add_argument("--version", dest="version")
124
+ r.set_defaults(func=request)
125
+
126
+ q = sub.add_parser("queue", help="the registry's shared queue")
127
+ q.set_defaults(func=queue)
128
+
129
+ args = parser.parse_args(argv)
130
+ try:
131
+ return args.func(args)
132
+ except Stop as stop:
133
+ print(f"\nencore: {stop}", file=sys.stderr)
134
+ return 1
135
+ except KeyboardInterrupt:
136
+ print("\nencore: stopped. Run the same command again to go on from where it was.", file=sys.stderr)
137
+ return 130
138
+
139
+
140
+ if __name__ == "__main__":
141
+ sys.exit(main())
@@ -0,0 +1,101 @@
1
+ """The report at the end of `encore check`: what came of each claim, and what the run found about the data."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import Counter
6
+ from pathlib import Path
7
+
8
+ import yaml
9
+
10
+ LABELS = {"reproduced": "reproduced", "partially_reproduced": "partially reproduced",
11
+ "not_reproduced": "not reproduced", "blocked": "blocked"}
12
+ ORDER = list(LABELS)
13
+ KINDS = {"metadata_error": "Metadata error", "data_missing": "Data missing", "identifier_missing": "Identifier missing",
14
+ "metadata_insufficient": "Metadata insufficient", "selection_undocumented": "Selection undocumented",
15
+ "methods_unavailable": "Methods unavailable", "format_error": "Format error", "code_mismatch": "Code mismatch",
16
+ "paper_inconsistency": "Paper inconsistency", "other": "Other"}
17
+
18
+
19
+ def latest_attempt(registry: Path, folder: str) -> dict | None:
20
+ found = sorted((registry / "attempts").glob(f"{folder}-*.yaml"))
21
+ return yaml.safe_load(found[-1].read_text()) if found else None
22
+
23
+
24
+ def claims_of(registry: Path, folder: str) -> dict[str, dict]:
25
+ out = {}
26
+ for path in sorted((registry / "claims" / folder).glob("*.yaml")):
27
+ for c in (yaml.safe_load(path.read_text()) or {}).get("claims") or []:
28
+ out[c["id"]] = c
29
+ return out
30
+
31
+
32
+ def open_questions(registry: Path, folder: str) -> list[dict]:
33
+ path = registry / "questions" / f"{folder}.yaml"
34
+ if not path.is_file():
35
+ return []
36
+ q = yaml.safe_load(path.read_text()) or []
37
+ q = q.get("questions", []) if isinstance(q, dict) else q
38
+ return [x for x in q if not x.get("answered")]
39
+
40
+
41
+ def one_line(text: str, width: int = 300) -> str:
42
+ text = " ".join(str(text or "").split())
43
+ return text if len(text) <= width else text[:width - 1] + "…"
44
+
45
+
46
+ def summary(record: dict | None) -> str:
47
+ if not record:
48
+ return "no attempt record"
49
+ counts = Counter(o["outcome"] for o in record.get("outcomes", []))
50
+ return ", ".join(f"{counts[k]} {LABELS[k]}" for k in ORDER if counts[k])
51
+
52
+
53
+ def write_report(out: Path, registry: Path, state: dict) -> Path:
54
+ folder = state["folder"]
55
+ record = latest_attempt(registry, folder)
56
+ claims = claims_of(registry, folder)
57
+ d = state["dataset"]
58
+ lines = [f"# Encore report: {state['title']}", "",
59
+ f"- **Dataset:** `{d['location']}`" + (f" (fingerprint `{d['fingerprint']}`)" if d.get("fingerprint") else ""),
60
+ f"- **Paper:** doi:{state['doi']}",
61
+ f"- **Run:** {state['mode']} ({', '.join(r for r, v in state['roles'].items() if v.get('status') == 'success')}), "
62
+ f"model {state['model']}, protocol {state['protocol']}, finished {state.get('finished', '')[:16]}",
63
+ "", "Encore's agents read the paper, wrote down its claims and how to test each, and then tested them "
64
+ "on the dataset. A failure to reproduce may be the agent's, not the paper's or the data's: read the "
65
+ "notes and the notebooks before acting on one."
66
+ + ("" if state["mode"] == "full" else " This was a quick run, with no verification rounds: an "
67
+ "independent agent has not checked the author's work. Run with --full for that."), ""]
68
+ if record is None:
69
+ lines += ["**The author wrote no attempt record**, so there are no outcomes to report. Its report is in "
70
+ f"`registry/transcripts/{folder}/author-report.md`.", ""]
71
+ else:
72
+ lines += [f"## Claims: {summary(record)}", "", "| Claim | Outcome | Notes |", "|---|---|---|"]
73
+ for o in sorted(record.get("outcomes", []), key=lambda o: ORDER.index(o["outcome"])):
74
+ c = claims.get(o["claim"], {})
75
+ outcome = LABELS[o["outcome"]] + (f" ({o['blocked_by'].replace('_', ' ')})" if o.get("blocked_by") else "")
76
+ lines.append(f"| **{o['claim']}**<br>{one_line(c.get('statement'), 200)} | {outcome} | "
77
+ f"{one_line(o.get('notes')).replace('|', '/')} |")
78
+ findings = record.get("findings") or []
79
+ lines += ["", f"## Findings about the data: {len(findings)}", ""]
80
+ if findings:
81
+ lines += [f"- **{KINDS.get(f['kind'], f['kind'])}.** {one_line(f['statement'], 600)}" for f in findings]
82
+ else:
83
+ lines.append("None.")
84
+ lines.append("")
85
+ questions = open_questions(registry, folder)
86
+ if questions:
87
+ lines += [f"## Open questions: {len(questions)}", "",
88
+ "The author needed a method detail the claims file does not give, and left these claims blocked "
89
+ "on it." + ("" if state["mode"] == "full" else " A --full run has a reader answer them."), ""]
90
+ lines += [f"- {one_line(q.get('question') or q.get('text') or q, 400)}" for q in questions]
91
+ lines.append("")
92
+ entry = record.get("entry") if record else None
93
+ lines += ["## Where everything is", "",
94
+ f"- The claims and how each was tested: `registry/claims/{folder}/`"]
95
+ if entry:
96
+ lines.append(f"- The notebooks: `registry/entries/{entry}/`")
97
+ lines.append(f"- The attempt record: `registry/attempts/{record['id']}.yaml`")
98
+ lines += [f"- What each agent did: `registry/transcripts/{folder}/`", ""]
99
+ path = out / "report.md"
100
+ path.write_text("\n".join(lines))
101
+ return path
encore_science/run.py ADDED
@@ -0,0 +1,390 @@
1
+ """One `encore check`: the registry's protocol run on a dataset, on this machine, with the user's own Claude login.
2
+
3
+ A run lives in its output directory:
4
+
5
+ <out>/registry/ a copy of the registry, on a branch of its own: the protocol, the prompts, the tools,
6
+ and what the run writes (claims, entry, attempt record, transcripts)
7
+ <out>/registry/paper the paper's text and PDF; never committed
8
+ <out>/logs/ each role's stream from Claude Code (<role>.jsonl)
9
+ <out>/work-<role>/ what a verifier is given, outside the registry
10
+ <out>/state.json which roles are done; a second `encore check` with the same --out goes on from there
11
+ <out>/report.md the outcome of every claim and the findings about the data
12
+
13
+ Each role is one `claude -p` with the same prompt, tools and limits as in the registry's workflows
14
+ (.github/workflows/attempt.yml and papers.yml), in Claude Code's sandbox: its commands may write only inside the
15
+ run's directory and reach only the hosts in NETWORK.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import datetime
21
+ import hashlib
22
+ import json
23
+ import os
24
+ import re
25
+ import shutil
26
+ import subprocess
27
+ import sys
28
+ from dataclasses import dataclass
29
+ from pathlib import Path
30
+
31
+ REPO_URL = "https://github.com/catalystneuro/encore.git"
32
+ TOOLS = "Bash,Read,Write,Edit,Glob,Grep,WebFetch,WebSearch,Agent,TodoWrite"
33
+ NOT_TOOLS = "ScheduleWakeup,CronCreate,CronDelete,CronList,Monitor,RemoteTrigger,Workflow"
34
+ QUICK = ("claims", "claims-check", "author")
35
+ FULL = QUICK + ("answer", "author-answers", "verifier-1", "author-revise-1", "verifier-2", "author-revise-2",
36
+ "verifier-3", "author-revise-3")
37
+ # The hosts an agent's commands may reach: the archives, Python packages, and the paper's DOI.
38
+ NETWORK = ["dandiarchive.org", "*.dandiarchive.org", "*.amazonaws.com", "crcns.org", "*.ebrains.eu",
39
+ "pypi.org", "files.pythonhosted.org", "github.com", "*.githubusercontent.com", "doi.org", "*.doi.org"]
40
+ DOI = re.compile(r"\b(10\.[0-9]{4,9}/[^\s\"<>]+)")
41
+ # The one finished attempt the prompts point to for file formats. Every other dataset's work is taken out of a
42
+ # run's copy of the registry, so that no agent can read another attempt on the same paper or data.
43
+ EXAMPLE = {"claims": "001453", "entries": "001453-fouke-2025", "attempts": "001453-fouke-2025-01.yaml"}
44
+
45
+
46
+ class Stop(Exception):
47
+ """The run cannot go on; the message says why and what to do."""
48
+
49
+
50
+ @dataclass
51
+ class Dataset:
52
+ archive: str # local, remote, or an archive the registry knows (dandi, crcns, ebrains)
53
+ id: str
54
+ location: str # the directory or URL; for an archive, its key
55
+ fingerprint: str # stands in for a version; "" for an archive
56
+ version: str = "" # for an archive: a version, or draft
57
+
58
+ @property
59
+ def folder(self) -> str:
60
+ return self.id if self.archive == "dandi" else f"{self.archive}-{self.id}"
61
+
62
+
63
+ def git(*args: str, cwd: Path | None = None) -> str:
64
+ return subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True).stdout
65
+
66
+
67
+ def slug(name: str) -> str:
68
+ """A dataset's id from a directory's or URL's last part: lower case letters, digits and hyphens."""
69
+ s = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")
70
+ return s[:40].strip("-") or "dataset"
71
+
72
+
73
+ def fingerprint(directory: Path) -> str:
74
+ """A short hash of a directory's files: their paths, sizes, and first and last megabyte. Cheap on large
75
+ NWB files, and changed by any rewrite of a file that a conversion would make."""
76
+ h = hashlib.sha256()
77
+ for path in sorted(p for p in directory.rglob("*") if p.is_file() and not p.name.startswith(".")):
78
+ size = path.stat().st_size
79
+ h.update(f"{path.relative_to(directory).as_posix()}\0{size}\0".encode())
80
+ with path.open("rb") as f:
81
+ h.update(f.read(1 << 20))
82
+ if size > 2 << 20:
83
+ f.seek(-(1 << 20), os.SEEK_END)
84
+ h.update(f.read())
85
+ return "files-" + h.hexdigest()[:12]
86
+
87
+
88
+ def dataset_of(spec: str, version: str = "") -> Dataset:
89
+ """A local directory, a URL, or a dataset in an archive (DANDI:000147, CRCNS:ret-1)."""
90
+ if re.match(r"^[a-z][a-z0-9+.-]*://", spec):
91
+ name = spec.rstrip("/").rsplit("/", 1)[-1]
92
+ return Dataset("remote", slug(name), spec, "url-" + hashlib.sha256(spec.encode()).hexdigest()[:12])
93
+ path = Path(spec).expanduser()
94
+ if path.is_dir():
95
+ path = path.resolve()
96
+ return Dataset("local", slug(path.name), str(path), fingerprint(path))
97
+ if path.exists():
98
+ raise Stop(f"{spec} is a file; give the directory that holds the dataset's files.")
99
+ m = re.fullmatch(r"([A-Za-z][A-Za-z0-9]*):([A-Za-z0-9._-]+)|([0-9]{6})", spec.strip())
100
+ if not m:
101
+ raise Stop(f"{spec} is not a directory, a URL, or a dataset in an archive (such as DANDI:000147).")
102
+ archive, id_ = (m.group(1).lower(), m.group(2)) if m.group(1) else ("dandi", m.group(3))
103
+ return Dataset(archive, id_, f"{archive}:{id_}", "", version)
104
+
105
+
106
+ def registry_source(ref: str) -> Path:
107
+ """The registry to copy for a run: the clone this package sits in, when it is installed from one; else a
108
+ cached clone of the public repository at REF, brought up to date."""
109
+ here = Path(__file__).resolve().parents[1]
110
+ if (here / "docs" / "protocol.md").is_file() and (here / ".git").exists():
111
+ return here
112
+ cache = Path(os.environ.get("ENCORE_CACHE") or Path.home() / ".cache" / "encore") / "registry"
113
+ if (cache / ".git").exists():
114
+ git("fetch", "-q", "--depth", "1", "origin", ref, cwd=cache)
115
+ git("checkout", "-q", "-f", "FETCH_HEAD", cwd=cache)
116
+ else:
117
+ cache.parent.mkdir(parents=True, exist_ok=True)
118
+ git("clone", "-q", "--depth", "1", "--branch", ref, REPO_URL, str(cache))
119
+ return cache
120
+
121
+
122
+ def paper_text(path: Path) -> tuple[str, list[str]]:
123
+ """A paper's text, page by page as the paper store keeps it, and the pages' text for finding its DOI."""
124
+ if path.suffix.lower() in (".txt", ".md"):
125
+ text = path.read_text(errors="replace")
126
+ return text, [text[:20000]]
127
+ if path.suffix.lower() != ".pdf":
128
+ raise Stop(f"{path.name}: give the paper as a PDF or a text file.")
129
+ import pymupdf # as the paper store uses
130
+ pages = [page.get_text() for page in pymupdf.open(path)]
131
+ return "".join(f"\n=== page {n} ===\n{t}" for n, t in enumerate(pages, 1)), pages[:2]
132
+
133
+
134
+ def find_doi(texts: list[str]) -> str | None:
135
+ for t in texts:
136
+ m = DOI.search(t)
137
+ if m:
138
+ return m.group(1).rstrip(".,;)]").lower()
139
+ return None
140
+
141
+
142
+ class Run:
143
+ def __init__(self, out: Path, dataset: Dataset, paper: Path | None, doi: str | None, title: str | None,
144
+ full: bool, model: str, ref: str, sandbox: bool = True):
145
+ self.out, self.dataset, self.paper, self.doi, self.title = out.resolve(), dataset, paper, doi, title
146
+ self.full, self.model, self.ref, self.sandbox = full, model, ref, sandbox
147
+ self.registry = self.out / "registry"
148
+ self.logs = self.out / "logs"
149
+ self.state_path = self.out / "state.json"
150
+ self.state = json.loads(self.state_path.read_text()) if self.state_path.is_file() else {}
151
+
152
+ # Setting up -------------------------------------------------------------------------------------------
153
+
154
+ def prepare(self) -> None:
155
+ if self.state.get("prepared"):
156
+ say(f"Going on with the run in {self.out}")
157
+ return
158
+ if self.paper is None:
159
+ raise Stop("Give the paper with --paper (a PDF or a text file).")
160
+ text, first_pages = paper_text(self.paper)
161
+ doi = (self.doi or find_doi(first_pages) or "").lower().removeprefix("doi:").removeprefix("https://doi.org/")
162
+ if not doi:
163
+ raise Stop("Found no DOI in the paper. Give it with --doi; a preprint's DOI is fine.")
164
+ title = self.title or self.paper.stem
165
+
166
+ self.out.mkdir(parents=True, exist_ok=True)
167
+ self.logs.mkdir(exist_ok=True)
168
+ shutil.rmtree(self.registry, ignore_errors=True) # a setup that stopped part-way
169
+ source = registry_source(self.ref)
170
+ say(f"Copying the registry's protocol from {source}")
171
+ git("clone", "-q", str(source), str(self.registry))
172
+ git("checkout", "-q", "-b", f"encore/{self.dataset.folder}", cwd=self.registry)
173
+ git("config", "user.name", "encore", cwd=self.registry)
174
+ git("config", "user.email", "encore@localhost", cwd=self.registry)
175
+ self.prune()
176
+ protocol = (self.registry / "docs" / "protocol.md").read_text().split("Version: `", 1)[1].split("`", 1)[0]
177
+ name = doi.replace("/", "-")
178
+ paper_dir = self.registry / "paper"
179
+ paper_dir.mkdir()
180
+ header = (f"DOI: {doi}\nVersion: as supplied\nSource: given to encore check ({self.paper.name})\n"
181
+ f"Stored: {datetime.date.today().isoformat()}\nExtracted: "
182
+ f"{'PyMuPDF' if self.paper.suffix.lower() == '.pdf' else 'as given'}\n" + "-" * 72 + "\n")
183
+ (paper_dir / f"{name}.txt").write_text(header + text)
184
+ if self.paper.suffix.lower() == ".pdf":
185
+ shutil.copy(self.paper, paper_dir / f"{name}.pdf")
186
+
187
+ d = self.dataset
188
+ if d.archive in ("local", "remote"):
189
+ target = {"archive": d.archive, "id": d.id, "name": title, "fingerprint": d.fingerprint,
190
+ "papers": [{"doi": doi, "title": title, "preprint": False}]}
191
+ target["path" if d.archive == "local" else "url"] = d.location
192
+ (self.registry / "targets" / "local.json").write_text(json.dumps({"targets": [target]}, indent=1))
193
+ self.state = {"prepared": True, "dataset": d.__dict__, "folder": d.folder, "doi": doi, "title": title,
194
+ "mode": "full" if self.full else "quick", "model": self.model, "protocol": protocol,
195
+ "source": str(source), "started": now(), "roles": {}}
196
+ self.save()
197
+
198
+ def prune(self) -> None:
199
+ """Take every other dataset's claims, entries, attempts, questions and transcripts out of the copy."""
200
+ for kind in ("claims", "entries", "attempts", "questions", "transcripts"):
201
+ for path in (self.registry / kind).glob("*"):
202
+ if path.name != EXAMPLE.get(kind) and path.name != ".gitkeep":
203
+ shutil.rmtree(path) if path.is_dir() else path.unlink()
204
+ # The notes on earlier attempts, and the README's table of their outcomes, go too.
205
+ stub = "Left out of an `encore check`: this page describes other attempts.\n"
206
+ for name in ("docs/pilot-notes.md", "docs/conversion-tracker.md"):
207
+ if (self.registry / name).is_file():
208
+ (self.registry / name).write_text(stub)
209
+ readme = self.registry / "README.md"
210
+ if readme.is_file():
211
+ readme.write_text("".join(line for line in readme.read_text().splitlines(keepends=True)
212
+ if not re.match(r"^\| \[", line)))
213
+ git("add", "-A", "--", *[p for p in ("claims", "entries", "attempts", "questions", "transcripts", "docs",
214
+ "README.md") if (self.registry / p).exists()], cwd=self.registry)
215
+ git("commit", "-q", "-m", "encore check: only the example attempt", cwd=self.registry)
216
+
217
+ def save(self) -> None:
218
+ self.state_path.write_text(json.dumps(self.state, indent=1))
219
+
220
+ # Running roles ----------------------------------------------------------------------------------------
221
+
222
+ def env(self) -> dict:
223
+ env = dict(os.environ, CLAUDE_CODE_SUBPROCESS_ENV_SCRUB="1", CLAUDE_CODE_DISABLE_AUTO_MEMORY="1",
224
+ DISABLE_AUTOUPDATER="1", DISABLE_TELEMETRY="1", CLAUDE_CODE_DISABLE_BACKGROUND_TASKS="1",
225
+ BASH_DEFAULT_TIMEOUT_MS="3600000", BASH_MAX_TIMEOUT_MS="7200000")
226
+ if self.dataset.archive == "local":
227
+ env["ENCORE_LOCAL_DATA"] = self.dataset.location
228
+ return env
229
+
230
+ def settings(self, cwd: Path) -> str:
231
+ """Claude Code settings for a role: the sandbox, writable only inside the run's directory."""
232
+ network = list(NETWORK)
233
+ if self.dataset.archive == "remote":
234
+ network.append(re.sub(r"^[a-z0-9+.-]+://([^/:]+).*$", r"\1", self.dataset.location))
235
+ caches = [str(Path.home() / p) for p in (".cache", "Library/Caches", ".local/share/jupyter", "Library/Jupyter")]
236
+ return json.dumps({"sandbox": {
237
+ "enabled": self.sandbox, "autoAllowBashIfSandboxed": True, "allowUnsandboxedCommands": False,
238
+ "filesystem": {"allowWrite": [str(self.out), str(cwd), "/tmp", os.environ.get("TMPDIR", "/tmp"), *caches]},
239
+ "network": {"allowedDomains": network}}})
240
+
241
+ def prompt(self, role: str) -> str:
242
+ args = [sys.executable, "tools/agent_run.py", "prompt", role, self.dataset.folder, "--model", self.model]
243
+ if self.dataset.version and role == "author":
244
+ args += ["--version", self.dataset.version]
245
+ return subprocess.run(args, cwd=self.registry, check=True, capture_output=True, text=True,
246
+ env=self.env()).stdout
247
+
248
+ def claude(self, role: str, prompt: str, cwd: Path) -> int:
249
+ """Run one role and keep its stream; print one line per step as it goes."""
250
+ if shutil.which("claude") is None:
251
+ raise Stop("Claude Code is not installed: see https://docs.claude.com/en/docs/claude-code")
252
+ stream = self.logs / f"{role}.jsonl"
253
+ cmd = ["claude", "-p", prompt, "--model", self.model, "--output-format", "stream-json", "--verbose",
254
+ "--forward-subagent-text", "--permission-prompts", "none", "--allowedTools", TOOLS,
255
+ "--disallowedTools", NOT_TOOLS, "--settings", self.settings(cwd)]
256
+ progress = subprocess.Popen([sys.executable, str(self.registry / "tools" / "progress.py")],
257
+ stdin=subprocess.PIPE, text=True)
258
+ with stream.open("w") as log, open(self.logs / f"{role}.stderr", "w") as err:
259
+ agent = subprocess.Popen(cmd, cwd=cwd, env=self.env(), stdout=subprocess.PIPE, stderr=err, text=True)
260
+ for line in agent.stdout:
261
+ log.write(line)
262
+ log.flush()
263
+ try:
264
+ progress.stdin.write(line)
265
+ progress.stdin.flush()
266
+ except BrokenPipeError:
267
+ pass
268
+ agent.wait()
269
+ progress.stdin.close()
270
+ progress.wait()
271
+ return agent.returncode
272
+
273
+ def transcript(self, role: str) -> None:
274
+ dest = self.registry / "transcripts" / self.dataset.folder
275
+ dest.mkdir(parents=True, exist_ok=True)
276
+ subprocess.run([sys.executable, str(self.registry / "tools" / "transcript.py"), str(self.logs / f"{role}.jsonl"),
277
+ str(dest / f"{role}.md"), "--omit", "paper/", "--report", str(dest / f"{role}-report.md"),
278
+ "--home", str(Path.home()), "--title", f"{self.dataset.folder} · {role} · encore check"],
279
+ cwd=self.registry, check=True, capture_output=True, text=True)
280
+
281
+ def commit(self, role: str) -> None:
282
+ paths = [p for p in ("attempts", "claims", "entries", "questions", "transcripts", "README.md")
283
+ if (self.registry / p).exists()]
284
+ git("add", "-A", "--", *paths, cwd=self.registry)
285
+ if subprocess.run(["git", "diff", "--cached", "--quiet"], cwd=self.registry).returncode:
286
+ git("commit", "-q", "-m", f"encore check: {role}", cwd=self.registry)
287
+
288
+ def role(self, role: str) -> None:
289
+ done = self.state["roles"].get(role, {})
290
+ if done.get("status") == "success":
291
+ return
292
+ say(f"\n{role}: starting")
293
+ cwd = self.registry
294
+ if role.startswith("verifier"):
295
+ cwd = self.verifier_package(role)
296
+ self.state["roles"][role] = {"status": "running", "started": now()}
297
+ self.save()
298
+ code = self.claude(role, self.prompt(role), cwd)
299
+ self.transcript(role)
300
+ self.commit(role)
301
+ self.state["roles"][role].update(status="success" if code == 0 else "failed", finished=now())
302
+ self.save()
303
+ if code != 0:
304
+ tail = (self.logs / f"{role}.stderr").read_text()[-800:]
305
+ limit = "limit" in tail.lower() or "limit" in (self.logs / f"{role}.jsonl").read_text()[-3000:].lower()
306
+ raise Stop(f"{role} stopped (Claude Code exited with {code})."
307
+ + (" It looks like a usage limit: run the same command again once it resets, and the run "
308
+ "goes on from this role." if limit else f" The end of its log:\n{tail}"))
309
+ say(f"{role}: done")
310
+
311
+ def sandboxed(self, command: str, cwd: Path, name: str) -> None:
312
+ """Run one shell command of ours inside the same sandbox as the agents, by asking Claude Code to run it:
313
+ the notebooks it executes were written by an agent."""
314
+ prompt = (f"Use the Bash tool to run exactly this command, once, and wait for it to finish:\n\n{command}\n\n"
315
+ "Then reply with only the last line it printed and its exit status.")
316
+ if self.claude(name, prompt, cwd) != 0:
317
+ raise Stop(f"Running `{command}` failed; see {self.logs / (name + '.jsonl')}.")
318
+
319
+ def verifier_package(self, role: str) -> Path:
320
+ """What a verifier is given, in a directory outside the registry, as attempt.yml prepares it."""
321
+ entry = subprocess.run([sys.executable, "tools/agent_run.py", "entry", role, self.dataset.folder],
322
+ cwd=self.registry, check=True, capture_output=True, text=True).stdout.strip()
323
+ if role == "verifier-1":
324
+ self.sandboxed(f"{sys.executable} tools/entry.py run entries/{entry} && "
325
+ f"{sys.executable} tools/entry.py handover entries/{entry}", self.registry, "entry-run")
326
+ work = self.out / f"work-{role}"
327
+ shutil.rmtree(work, ignore_errors=True)
328
+ subprocess.run([sys.executable, "tools/agent_run.py", "package", role, self.dataset.folder, str(work)],
329
+ cwd=self.registry, check=True, capture_output=True, text=True)
330
+ shutil.copytree(self.registry / "paper", work / "paper")
331
+ return work
332
+
333
+ # The sequence -----------------------------------------------------------------------------------------
334
+
335
+ def claims_ready(self) -> bool:
336
+ import yaml
337
+ files = sorted((self.registry / "claims" / self.dataset.folder).glob("*.yaml"))
338
+ if not files:
339
+ return False
340
+ checks = (yaml.safe_load(files[0].read_text()) or {}).get("checks") or [{}]
341
+ return bool(checks[-1].get("ready"))
342
+
343
+ def open_questions(self) -> int:
344
+ import yaml
345
+ path = self.registry / "questions" / f"{self.dataset.folder}.yaml"
346
+ if not path.is_file():
347
+ return 0
348
+ q = yaml.safe_load(path.read_text()) or []
349
+ q = q.get("questions", []) if isinstance(q, dict) else q
350
+ return sum(1 for x in q if not x.get("answered"))
351
+
352
+ def proposals(self) -> bool:
353
+ out = subprocess.run([sys.executable, "tools/agent_run.py", "proposals", "author", self.dataset.folder],
354
+ cwd=self.registry, capture_output=True, text=True).stdout.strip()
355
+ return out == "true"
356
+
357
+ def go(self) -> Path:
358
+ self.prepare()
359
+ # The claims, unless the registry already has a checked claims file for this dataset (an archive's).
360
+ if not self.claims_ready() or self.state["roles"].get("claims"):
361
+ self.role("claims")
362
+ if not (self.registry / "claims" / self.dataset.folder).is_dir():
363
+ raise Stop("The reader wrote no claims file: see "
364
+ f"{self.registry / 'transcripts' / self.dataset.folder / 'claims-report.md'}.")
365
+ self.role("claims-check")
366
+ if not self.claims_ready():
367
+ raise Stop("The claims check says the claims file is not ready: see "
368
+ f"{self.registry / 'transcripts' / self.dataset.folder / 'claims-check-report.md'}.")
369
+ self.role("author")
370
+ if self.full:
371
+ if self.open_questions() or self.state["roles"].get("answer"):
372
+ self.role("answer")
373
+ self.role("author-answers")
374
+ for role in ("verifier-1", "author-revise-1", "verifier-2", "author-revise-2"):
375
+ self.role(role)
376
+ if self.proposals():
377
+ self.role("verifier-3")
378
+ self.role("author-revise-3")
379
+ from .report import write_report
380
+ self.state["finished"] = now()
381
+ self.save()
382
+ return write_report(self.out, self.registry, self.state)
383
+
384
+
385
+ def now() -> str:
386
+ return datetime.datetime.now().astimezone().isoformat(timespec="seconds")
387
+
388
+
389
+ def say(text: str) -> None:
390
+ print(text, flush=True)
@@ -0,0 +1,66 @@
1
+ Metadata-Version: 2.5
2
+ Name: encore-science
3
+ Version: 0.1.0
4
+ Summary: Check a dataset against the paper it came from: an AI agent reads the paper's claims and tests them on the data.
5
+ Project-URL: Homepage, https://encorescience.org
6
+ Project-URL: Source, https://github.com/catalystneuro/encore
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Requires-Python: >=3.10
10
+ Requires-Dist: jsonschema
11
+ Requires-Dist: nbformat
12
+ Requires-Dist: pymupdf
13
+ Requires-Dist: pyyaml
14
+ Requires-Dist: uv
15
+ Description-Content-Type: text/markdown
16
+
17
+ # Encore
18
+
19
+ Encore checks a dataset against the paper it came from. AI agents read the paper, write down each of its claims and how to test it, and then test the claims on the data, without being able to change them. You get back what came of each claim and, often more useful, what the run found wrong with the data along the way: units that do not match, metadata that is missing, data the paper describes but the files do not hold.
20
+
21
+ It runs on your own machine, with your own Claude login, on a dataset in any of three places:
22
+
23
+ ```
24
+ pip install encore-science
25
+
26
+ encore check ./nwb/ --paper paper.pdf # a directory of files, before you upload them
27
+ encore check s3://bucket/smith-2024/ --paper paper.pdf # files at a URL
28
+ encore check DANDI:001234 --draft --paper paper.pdf # a dataset in an archive
29
+ ```
30
+
31
+ Encore follows the same protocol ([protocol.md](https://github.com/catalystneuro/encore/blob/main/docs/protocol.md)) as the [registry](https://encorescience.org/), the public record of these checks on published datasets. A check you run yourself stays on your machine; to put a dataset on the record, ask for a run with `encore request`.
32
+
33
+ ## What you need
34
+
35
+ - [Claude Code](https://docs.claude.com/en/docs/claude-code), signed in to a Claude account or with an API key. Encore uses whatever login Claude Code has, and the run counts against that account's usage.
36
+ - Python 3.10 or later, and git.
37
+ - The paper, as a PDF or a text file. Encore takes the DOI from the PDF; give `--doi` when it does not show one. A preprint is fine.
38
+
39
+ ## Checking a dataset
40
+
41
+ ```
42
+ encore check DATA --paper PAPER [--doi DOI] [--title TITLE] [--full] [--out DIR]
43
+ ```
44
+
45
+ A quick check, the default, has three agents in turn: a reader writes the claims file from the paper, a second reader checks it, and an author tests the claims on the data. It takes one to three hours. `--full` adds two rounds of verification, in which an independent agent checks the author's work, and takes several hours more.
46
+
47
+ The run and its report go to `./encore-<name>-<date>/`, or `--out`. `report.md` there lists every claim with its outcome (reproduced, partially reproduced, not reproduced, or blocked) and every finding about the data, and points to the notebooks the author wrote. A failure to reproduce may be the agent's, not the paper's or the data's: read the notes and the notebooks before acting on one.
48
+
49
+ If a run stops, for example when the account reaches a usage limit, run the same command again: it goes on from the role that stopped.
50
+
51
+ ```
52
+ encore status [DIR] # which roles are done, and what the running one is doing
53
+ ```
54
+
55
+ ## What the agents can do
56
+
57
+ Each agent is Claude Code, run with the same prompt, tools and limits as in the registry. Its commands run in Claude Code's sandbox: they may write only inside the run's directory (and the package caches), and reach only the archives, Python's package index, GitHub and doi.org. A local dataset is read in place and never changed. `--no-sandbox` turns the sandbox off, for a machine where it cannot run; use it only on data and a machine you are comfortable with.
58
+
59
+ ## The registry's queue
60
+
61
+ ```
62
+ encore request DANDI:001234 --draft --why "Fixed the units, see lab-to-nwb#12"
63
+ encore queue
64
+ ```
65
+
66
+ `request` asks for an attempt on the registry's shared queue ([queue.md](https://github.com/catalystneuro/encore/blob/main/docs/queue.md)): a repeat attempt after a conversion was fixed, or a first one on a dataset with a paper. It needs the [GitHub CLI](https://cli.github.com), signed in. `queue` shows the queue in order.
@@ -0,0 +1,10 @@
1
+ encore_science/__init__.py,sha256=vQZT2amTdUH-cVxa-vs-HV50Vud-IWKpUNpCD3wtsfQ,123
2
+ encore_science/__main__.py,sha256=E6Gls0DNz8GQK2K-kOUIx8cYhgANW_CH54VKrfCfs14,52
3
+ encore_science/cli.py,sha256=eUoQFilfTrDfsWsPDxdzGkReyOJwimbhOwviK_9bENc,6441
4
+ encore_science/report.py,sha256=IcO3TzGFZKyAdVUBsk5P_1QGQIZIDWz83VoBuWxdXBE,5300
5
+ encore_science/run.py,sha256=HIO67OX4rSOeCBYVHNQsVPH3MYnIFVqiuiu7XgB0P0o,20925
6
+ encore_science-0.1.0.dist-info/METADATA,sha256=lcY62ikDUNf_yntZEAmlibPldNwVVHa-OLNjiTWqvZ4,4086
7
+ encore_science-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
8
+ encore_science-0.1.0.dist-info/entry_points.txt,sha256=3z9KKgo2P48IykqdbH5_VY1cP7N-u1sD70A7ElXgGko,51
9
+ encore_science-0.1.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
10
+ encore_science-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ encore = encore_science.cli:main
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.