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
3 changes: 2 additions & 1 deletion demos/research-loop/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,8 @@ All paths are under `demos/research-loop/`. Everything is a static file; no serv
| --- | --- | --- |
| `research/index.json` | JSON: `{system, claims: [{name, file, about, role, source: {kind, id, title, url}, statement, status, p_transfer}], seen, steering}` | every claim, phase 0's and phase 1's, with the path of its file: the list a static site cannot get by listing a folder |
| `claims/**/NAME.yaml` | YAML, one `EvidenceClaim` (`schemas/evidence-claim.v1.json`) | the claim in full: source, quote, conditions, prediction, trial |
| `research/queue.json` | JSON: `{system, date, how, queue: [{claim, file, role, about, p_transfer, information_bits, cost_hours, plan, prioritised_by, rejected_by, score, reason}]}`, best first | what to test next |
| `research/queue.json` | JSON: `{system, date, how, queue: [{claim, file, role, about, p_transfer, information_bits, cost_hours, plan, prioritised_by, rejected_by, disputed_by, score, currency, cost_money, pledged, received, funded_fraction, funding_source, ready, reason}]}`, best first (funded and `ready` first) | what to test next |
| `research/funding.yaml` (optional) | YAML: `{currency, rate_per_hour, funds: {claim id: {pledged, received, source}}}` | money earmarked for a test; `rank` multiplies the score by 1 + 3 x the fraction funded and marks a fully paid claim `ready` (docs/research-loop.md, Funding). The example is illustrative: no money has been received |
| `research/seen.jsonl` | JSON lines: `{id, version, title, abstract, published, category, topics, roles, status, reason, claims}` | every paper the watch returned, and what became of it |
| `research/steering.jsonl` | JSON lines: `{issue, url, kind, target, title, text, author, association, applied, why, recorded}` | every steering issue recorded |
| `research/watch.yaml` | YAML: `{system, conditions, topics: [{name, question, roles, terms, categories}]}` | what the agent watches, and why |
Expand Down
8 changes: 8 additions & 0 deletions demos/research-loop/research/funding.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Example only: illustrative figures, no money has been received. One entry per claim id.
currency: USD
rate_per_hour: 12
funds:
pd-program-beats-ppo:
pledged: 4
received: 0
source: "example: GitHub Sponsors, one-time, ref EXAMPLE-1"
23 changes: 23 additions & 0 deletions docs/research-loop.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,29 @@ question or proposal becomes a watch topic waiting for its terms. Every issue is
those from the repository's owner, members and collaborators (the REST API's `author_association`) are applied, so
a stranger's issue cannot steer the agent.

### Funding

An optional `research/funding.yaml` lets money steer the queue. Keys under `funds` are claim ids (a funded
direction is a claim); `rate_per_hour` turns the trial's `cost_hours` into a price:

```yaml
currency: USD
rate_per_hour: 12
funds:
pd-program-beats-ppo:
pledged: 5 # promised, not yet paid
received: 6 # paid
source: "GitHub Sponsors, one-time, ref 1234" # provider and reference only; no names, no emails
```

`rank` computes `funded_fraction = min(1, (pledged + received) / (cost_hours x rate_per_hour))` and multiplies the
claim's score by `1 + 3 x funded_fraction` (unfunded x1, half funded x2.5, fully funded x4), on top of the steering
doubling. A claim is `ready` only when `received` alone covers the price; ready claims sort first in `queue.json`,
whatever their score (a rejected claim is never ready). The queue rows record `currency`, `cost_money`, `pledged`,
`received`, `funded_fraction`, `funding_source` and `ready`. Money is a priority, not a verdict: it does not change a
claim's prediction, and the result is recorded whichever way it falls. Ids that match no claim are ignored. Money
without a `rate_per_hour` is refused.

**To turn it on**, on GitHub (nothing is enabled by this change):

1. Create the three labels: `research:prioritise`, `research:reject`, `research:question`.
Expand Down
43 changes: 40 additions & 3 deletions morphogen/research.py
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,25 @@ def steering(self) -> list[dict]:
f = self.dir / "steering.jsonl"
return [json.loads(x) for x in f.read_text().splitlines() if x.strip()] if f.exists() else []

def funding(self) -> dict:
"""research/funding.yaml (optional): {currency, rate_per_hour, funds: {claim-or-direction id: {pledged,
received, source}}}. The source is a free-text note (provider and reference); no personal data."""
f = self.dir / "funding.yaml"
d = load_yaml(f) if f.exists() else None
d = d or {}
funds = d.get("funds") or {}
if not isinstance(funds, dict):
raise ResearchError("research/funding.yaml: funds must map an id to {pledged, received, source}")
for k, v in funds.items():
for n in ("pledged", "received"):
x = (v or {}).get(n, 0)
if isinstance(x, bool) or not isinstance(x, (int, float)) or x < 0:
raise ResearchError(f"research/funding.yaml: {k}.{n} must be a number, 0 or more")
rate = d.get("rate_per_hour")
if funds and (isinstance(rate, bool) or not isinstance(rate, (int, float)) or rate <= 0):
raise ResearchError("research/funding.yaml: rate_per_hour (money per trial hour) must be above 0")
return {"currency": d.get("currency", "USD"), "rate_per_hour": rate, "funds": funds}

def claims(self) -> dict[str, tuple[Path, dict]]:
out = {}
for f in sorted((self.root / "claims").rglob("*.yaml")):
Expand Down Expand Up @@ -768,6 +787,14 @@ def entropy(p: float) -> float:
return -(p * math.log2(p) + (1 - p) * math.log2(1 - p))


FUNDING_GAIN = 3.0 # a fully funded claim's score is multiplied by 1 + FUNDING_GAIN; the factor is capped there


def funding_factor(fraction: float) -> float:
"""1 + 3 x the fraction funded, the fraction capped at 1: unfunded x1, half funded x2.5, fully funded x4."""
return 1 + FUNDING_GAIN * min(1.0, max(0.0, fraction))


def rank(p: Project) -> dict:
"""research/queue.json: the claims predicted for this system and not yet tested, ranked by what a trial would
teach (the entropy of its prediction) for its cost, with steering applied; research/index.json: every claim, for
Expand All @@ -785,6 +812,7 @@ def hit(ev, name, doc):
or (t["kind"] == "role" and backstage.parse_ref(t["name"], "component") == s["role"])
or (t["kind"] == "option" and backstage.parse_ref(t["name"], "component") ==
backstage.parse_ref(s["about"], "component")))
fund = p.funding()
rows, index = [], []
for name, (f, doc) in sorted(p.claims().items()):
s = doc["spec"]
Expand All @@ -803,15 +831,24 @@ def hit(ev, name, doc):
trial = a.get("trial") or {}
cost = float(trial.get("cost_hours") or 0) or None
info = entropy(pt)
score = None if rej or cost is None else round(info * (2 if pri else 1) / cost, 4)
fd = fund["funds"].get(name) or {}
pledged, received = float(fd.get("pledged") or 0), float(fd.get("received") or 0)
price = cost * fund["rate_per_hour"] if cost and fund["funds"] else None
fraction = round(min(1.0, (pledged + received) / price), 4) if price and (pledged or received) else 0.0
ready = bool(price and received >= price and not rej)
score = None if rej or cost is None else round(info * (2 if pri else 1) * funding_factor(fraction) / cost, 4)
rows.append({"claim": name, "file": rel, "role": s["role"], "about": s["about"], "p_transfer": pt,
"information_bits": round(info, 3), "cost_hours": cost, "plan": trial.get("plan"),
"prioritised_by": pri, "rejected_by": rej, "disputed_by": dis, "score": score,
"currency": fund["currency"], "cost_money": price, "pledged": pledged, "received": received,
"funded_fraction": fraction, "funding_source": fd.get("source"), "ready": ready,
"reason": a["prediction"]["reason"]})
rows.sort(key=lambda r: (r["score"] is None, -(r["score"] or 0), -r["p_transfer"], r["claim"]))
rows.sort(key=lambda r: (not r["ready"], r["score"] is None, -(r["score"] or 0), -r["p_transfer"], r["claim"]))
queue = {"system": w["system"], "date": today(),
"how": "score = bits of information in the outcome, H(p_transfer), times 2 if prioritised by "
"steering, divided by the trial's cost in hours; rejected or uncosted claims have no score",
"steering, times 1 + 3 x the fraction funded (research/funding.yaml: pledged plus received over the "
"trial's cost at rate_per_hour, at most 1), divided by the trial's cost in hours; rejected or "
"uncosted claims have no score. ready: received covers the whole cost; those come first",
"queue": rows}
p.dir.mkdir(exist_ok=True)
(p.dir / "queue.json").write_text(json.dumps(queue, indent=1, ensure_ascii=False) + "\n")
Expand Down
30 changes: 30 additions & 0 deletions tests/test_research.py
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,36 @@ def test_the_claim_sites_body_lines_come_first(self):
self.assertEqual((e["kind"], e["target"], e["applied"]), ("propose-role", None, True))
self.assertIsNone(rs.parse_issue(issue(4, "x", "research-action: delete-everything\n")))

def test_funding_raises_rank_and_marks_ready(self):
t = Toy()
try:
t.draft([claim("table-row", "Ours 83.2", prediction={"p_transfer": 0.5, "reason": "r"},
trial={"plan": "p", "cost_hours": 4}),
claim("abstract", "We cut cost by 50%", prediction={"p_transfer": 0.9, "reason": "r"},
trial={"plan": "p", "cost_hours": 1})])
q = rs.rank(t.p)["queue"]
self.assertEqual([r["claim"] for r in q], ["abstract", "table-row"])
self.assertFalse(q[0]["ready"])
(t.root / "research/funding.yaml").write_text(yaml.safe_dump(
{"currency": "USD", "rate_per_hour": 10, "funds": {
"table-row": {"pledged": 10, "received": 10, "source": "sponsors, ref 12"},
"no-such-claim": {"received": 5}}}))
q = {r["claim"]: r for r in rs.rank(t.p)["queue"]}
r = q["table-row"] # 20 of 40: half funded, x2.5
self.assertEqual((r["funded_fraction"], r["ready"], r["cost_money"]), (0.5, False, 40.0))
self.assertAlmostEqual(r["score"], 1.0 * 2.5 / 4)
(t.root / "research/funding.yaml").write_text(yaml.safe_dump(
{"rate_per_hour": 10, "funds": {"table-row": {"received": 50}}})) # over-funded: capped at x4
rows = rs.rank(t.p)["queue"]
self.assertEqual([r["claim"] for r in rows], ["table-row", "abstract"]) # ready comes first
self.assertEqual((rows[0]["ready"], rows[0]["funded_fraction"]), (True, 1.0))
self.assertAlmostEqual(rows[0]["score"], 4 / 4)
(t.root / "research/funding.yaml").write_text(yaml.safe_dump({"funds": {"table-row": {"received": 5}}}))
with self.assertRaises(rs.ResearchError): # money without a rate is refused
rs.rank(t.p)
finally:
t.close()

def test_steer_applies_once_and_rank_uses_it(self):
t = Toy()
try:
Expand Down
Loading