dragonlimited commited on
Commit
658e4ae
·
verified ·
1 Parent(s): b96f66b

ops+docs: repaired runner/watchdog, authored queue, and the question-set reproducibility correction

Browse files
ops/AGENT.md ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AGENT.md — read this first
2
+
3
+ You are the autonomous worker on the **model half** of the `dragonlimited` project. The corpus half
4
+ (12 product repos, its own notebook) is **not your job**. Yours is the finance agent: a 7B model plus
5
+ tools over a local facts database.
6
+
7
+ Everything durable lives on the Hub, not on this box:
8
+ `dragonlimited/dragon-state` (state, runs, docs) and `dragonlimited/dragon-harness` (the tools, the ops
9
+ scripts). A relaunch wipes this container; it does not wipe those. **Push your work, or it is gone.**
10
+
11
+ ## The rule that governs everything
12
+
13
+ > **one measured step at a time; a gate is a command, not a judgement**
14
+
15
+ * A job is retired **only when its marker exists AND its gate passes**. A marker says "a script ran";
16
+ the gate says "the result is good enough". Conflating them is how a queue reports progress it did
17
+ not make — it happened on this project's first run.
18
+ * **Never fabricate work to avoid idleness.** An unproven lane, or a re-run that cannot change the
19
+ number, is churn. If the queue is exhausted, write an `ask` and stop; do not invent tasks.
20
+ * **One model job at a time.** Two runs of the same instrument write the same result file, so a second
21
+ start corrupts evidence rather than advancing the queue.
22
+
23
+ ## The processes, and how it restarts itself
24
+
25
+ | process | role |
26
+ |---|---|
27
+ | `ops/plan_runner.py` | works `ops/plan_queue.json`: next job with deps met and gate unmet, runs it, records the attempt in `ops/plan_ledger.jsonl`, retires on marker+gate, caps retries, moves on |
28
+ | `ops/plan_watchdog.py` | **the clock that kicks.** Every 5 min: is the runner / llama-server / night agent alive? Restart any that are not. Writes `ops/health.json`, publishes a heartbeat hourly. If this dies, the box goes quiet — which is why it publishes |
29
+ | `ops/night_agent.py` | a local model on the night shift; whitelist only (`noop` / `restart` / `sweep` / `note` / `ask`). It cannot publish, cannot edit the plan, cannot see the token |
30
+ | `ops/STOP` | touch it to stop the runner and the watchdog |
31
+ | `ops/prompts_for_agent.jsonl` | **the channel back to a human. Read it first, every session.** |
32
+
33
+ Operate it with `tail -f plan_runner.log`, `cat ops/health.json`, `python ops/plan_status.py`.
34
+
35
+ ## Where the work actually stands (measured 2026-11-21)
36
+
37
+ * **Quantisation gate: PASSED.** Q4_K_M is within one question in 60 of the f16 control, and the
38
+ published GGUF is byte-exact against the artefact that was measured.
39
+ * **The only unmet target** is `answer_ok` — 0.750 (bf16) / 0.767 (Q4_K_M) against 0.80 — and the
40
+ strict-call measure at the same margin. The residual is **tag selection, not tool use**.
41
+ * **Eliminated by measurement, do not re-try:** the tools' arithmetic (j9/j10); the candidate-set
42
+ width (`DRAGON_CAND_MAX=40` made the shipped selection byte-identical and V1 did not move);
43
+ `query_financials` (never called); a stale harness (installed copy hashes identical to the Hub);
44
+ and the question sample (frozen 0.483 vs regenerated 0.500 — real, but small).
45
+ * **The open lead:** the two agent loops. The benchmark drives a **bare user turn with no system
46
+ prompt and 3 tools**; the product prepends a **6-rule `SYSTEM_PROMPT` and offers a 4th tool,
47
+ `resolve_question`**. That is the whole remaining gap, and it is being measured now (`j12`).
48
+ * Also known: `resolve_filer` returns filings **newest-first**, so a period-specific question shows
49
+ the wrong period first and the model reports "No filing is registered". 23 of 31 product failures
50
+ read that way while the tool returns 8 rows for the same name.
51
+
52
+ ## Rules of engagement
53
+
54
+ 1. **Publish with keywords.** `huggingface_hub` 2.x: `api.create_commit(repo_id=..., repo_type="model",
55
+ operations=[...], commit_message=...)`. A positional call raises
56
+ `takes 3 positional arguments but 5 were given` — that is what killed the last session's publish.
57
+ 2. **The token comes from the ENVIRONMENT**, never a cell, never a file that syncs. `sync_state.py`
58
+ pushes this workspace to the Hub.
59
+ 3. **Write results next to their provenance, in `dragon-state`** (`runs/dragon-lora-v7/quant/...`), and
60
+ append one line to `docs/SESSION-LOG.md`.
61
+ 4. **When a decision is not yours — a gate that keeps failing, hardware, spend — write `ask` into
62
+ `ops/prompts_for_agent.jsonl` and move on.** Do not guess at the owner's intent.
63
+ 5. **A claim needs a number.** If you cannot measure it, say "unmeasured" rather than implying it.
64
+
65
+ ## Boot, if you have just arrived on a fresh box
66
+
67
+ `dragon-state:docs/AGENT-START-HERE.md` is the ordered runbook: restore state → `python restore_state.py`
68
+ → `python check_resume.py` (expect 60/61) → **`python run_harness.py`, which must print `6,791 hit`** →
69
+ fetch the eval data → start `sync_state.py --watch`. If `run_harness.py` does not print that, the data
70
+ moved, not the harness: stop and read `docs/04-HOW-TO-VERIFY.md`.
ops/plan_runner.py CHANGED
@@ -115,16 +115,16 @@ def main():
115
  rc, out = 1, f"{type(e).__name__}: {e}"
116
  done = (W / j["marker"]).exists() and gate_met(j)
117
  if (W / j["marker"]).exists() and not gate_met(j):
118
- g = j.get("gate_met") or {{}}
119
- log(f" {{jid}} marker present but GATE UNMET ({{g.get('file')}}:{{g.get('path')}} "
120
- f"{{g.get('op')}} {{g.get('value')}})")
121
  try:
122
  with open(O / "prompts_for_agent.jsonl", "a") as fh:
123
- fh.write(json.dumps({{"utc": time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()),
124
  "priority": "high",
125
- "prompt": f"{{jid}} ran and its gate is unmet "
126
- f"({{g.get('file')}}:{{g.get('path')}}): decide whether "
127
- f"the gate or the approach is wrong"}}) + "\n")
128
  except Exception:
129
  pass
130
  mark({"job": jid, "attempt": st["attempts"][jid], "rc": rc, "seconds": round(time.time()-t0, 1),
 
115
  rc, out = 1, f"{type(e).__name__}: {e}"
116
  done = (W / j["marker"]).exists() and gate_met(j)
117
  if (W / j["marker"]).exists() and not gate_met(j):
118
+ g = j.get("gate_met") or {}
119
+ log(f" {jid} marker present but GATE UNMET ({g.get('file')}:{g.get('path')} "
120
+ f"{g.get('op')} {g.get('value')})")
121
  try:
122
  with open(O / "prompts_for_agent.jsonl", "a") as fh:
123
+ fh.write(json.dumps({"utc": time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()),
124
  "priority": "high",
125
+ "prompt": f"{jid} ran and its gate is unmet "
126
+ f"({g.get('file')}:{g.get('path')}): decide whether "
127
+ f"the gate or the approach is wrong"}) + "\n")
128
  except Exception:
129
  pass
130
  mark({"job": jid, "attempt": st["attempts"][jid], "rc": rc, "seconds": round(time.time()-t0, 1),
ops/plan_watchdog.py CHANGED
@@ -14,6 +14,7 @@ HEALTH = O / "health.json"
14
  INTERVAL = int(os.environ.get("DRAGON_WATCHDOG_S", "300"))
15
  PUBLISH_S = int(os.environ.get("DRAGON_HEALTH_PUBLISH_S", "3600"))
16
  _last_pub = [0.0]
 
17
 
18
  def log(*a):
19
  line = time.strftime("%Y-%m-%d %H:%M:%S") + " [watchdog] " + " ".join(str(x) for x in a)
@@ -25,7 +26,22 @@ def alive(pat):
25
  r = subprocess.run(["pgrep", "-f", pat], capture_output=True, text=True)
26
  return bool(r.stdout.strip())
27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  def start(cmd, name):
 
 
29
  subprocess.Popen(["bash", "-lc", cmd], start_new_session=True)
30
  log("restarted", name)
31
 
@@ -73,12 +89,20 @@ def main():
73
  while not STOP.exists():
74
  try:
75
  h = heartbeat()
76
- if not h["runner_alive"]:
77
  start(f"cd {W} && python ops/plan_runner.py >> plan_runner.log 2>&1 &", "plan_runner")
78
  if not h["llama_alive"]:
79
  start("bash /home/marimo/tools/serve_q4.sh &", "llama-server")
80
  if not h["night_agent_alive"]:
81
  start(f"cd {W} && python ops/night_agent.py >> night_agent.log 2>&1 &", "night_agent")
 
 
 
 
 
 
 
 
82
  r = publish(h)
83
  log(f"runner={h['runner_alive']} llama={h['llama_alive']} night={h['night_agent_alive']} "
84
  f"job={h['current_job']} gpu={h['gpu']} index={h['index_rows']} publish={r}")
 
14
  INTERVAL = int(os.environ.get("DRAGON_WATCHDOG_S", "300"))
15
  PUBLISH_S = int(os.environ.get("DRAGON_HEALTH_PUBLISH_S", "3600"))
16
  _last_pub = [0.0]
17
+ _IDLE = [0] # consecutive samples with the GPU under 5%
18
 
19
  def log(*a):
20
  line = time.strftime("%Y-%m-%d %H:%M:%S") + " [watchdog] " + " ".join(str(x) for x in a)
 
26
  r = subprocess.run(["pgrep", "-f", pat], capture_output=True, text=True)
27
  return bool(r.stdout.strip())
28
 
29
+ def busy():
30
+ """True while a measurement owns the model server.
31
+
32
+ Added 2026-11-21: two runs of the same instrument write the same result file
33
+ (`v1_test.json`), so a kick that starts the runner during a live measurement corrupts
34
+ evidence rather than advancing the queue. One model job at a time.
35
+ """
36
+ import re as _re
37
+ pats = _re.compile(r"(v1_test\.py|bench_agent|strict60\.py|tool_fix\.py|j1[0-9]_|index_corpus\.py)")
38
+ out = subprocess.run(["ps", "-eo", "args"], capture_output=True, text=True).stdout
39
+ return any(pats.search(l) for l in out.splitlines() if "grep" not in l and "ps -eo" not in l)
40
+
41
+
42
  def start(cmd, name):
43
+ os.environ.setdefault("PATH", "")
44
+ os.environ["PATH"] = "/tmp/uv-venv/bin:" + os.environ["PATH"]
45
  subprocess.Popen(["bash", "-lc", cmd], start_new_session=True)
46
  log("restarted", name)
47
 
 
89
  while not STOP.exists():
90
  try:
91
  h = heartbeat()
92
+ if not h["runner_alive"] and not busy():
93
  start(f"cd {W} && python ops/plan_runner.py >> plan_runner.log 2>&1 &", "plan_runner")
94
  if not h["llama_alive"]:
95
  start("bash /home/marimo/tools/serve_q4.sh &", "llama-server")
96
  if not h["night_agent_alive"]:
97
  start(f"cd {W} && python ops/night_agent.py >> night_agent.log 2>&1 &", "night_agent")
98
+ try:
99
+ _u = int(h["gpu"].split(",")[0].strip().rstrip("%"))
100
+ except Exception:
101
+ _u = -1
102
+ _IDLE[0] = _IDLE[0] + 1 if 0 <= _u < 5 else 0
103
+ if _IDLE[0] >= 3 and not busy():
104
+ log(f"IDLE HARDWARE: gpu {_u}% for {_IDLE[0]} checks and no measurement running "
105
+ f"- the queue is the feeder, so this is a defect to report, not a default")
106
  r = publish(h)
107
  log(f"runner={h['runner_alive']} llama={h['llama_alive']} night={h['night_agent_alive']} "
108
  f"job={h['current_job']} gpu={h['gpu']} index={h['index_rows']} publish={r}")
ops/publish_evidence.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """publish_evidence.py - land a result on dragon-state, one commit, in ONE call.
2
+
3
+ Authored 2026-11-21. The previous session's publisher died on:
4
+
5
+ TypeError: HfApi.create_commit() takes 3 positional arguments but 5 were given
6
+
7
+ because it passed (repo_id, repo_type, operations, message) positionally. huggingface_hub 2.x
8
+ requires keywords. The token comes from the ENVIRONMENT only - never a file, never a cell: this
9
+ workspace is synced to the Hub by sync_state.py.
10
+
11
+ Usage: python ops/publish_evidence.py <path_in_repo>=<local file> [more ...] --message "..."
12
+ """
13
+ import os, sys, time, pathlib
14
+ from huggingface_hub import CommitOperationAdd, HfApi
15
+
16
+ REPO = "dragonlimited/dragon-state"
17
+
18
+ def main(argv):
19
+ msg, pairs = None, []
20
+ i = 0
21
+ while i < len(argv):
22
+ if argv[i] == "--message":
23
+ msg = argv[i + 1]; i += 2; continue
24
+ if "=" in argv[i]:
25
+ pairs.append(tuple(argv[i].split("=", 1)))
26
+ i += 1
27
+ if not pairs:
28
+ print("nothing to publish"); return 1
29
+ tok = os.environ.get("HF_TOKEN", "")
30
+ if not tok:
31
+ print("no HF_TOKEN in the environment - refusing to try"); return 2
32
+ ops = []
33
+ for dest, src in pairs:
34
+ p = pathlib.Path(src)
35
+ if not p.exists():
36
+ print(f" MISSING {src} -> {dest}"); continue
37
+ ops.append(CommitOperationAdd(path_in_repo=dest, path_or_fileobj=p.read_bytes()))
38
+ print(f" {src} -> {dest} ({p.stat().st_size:,} B)")
39
+ if not ops:
40
+ print("nothing to publish"); return 1
41
+ api = HfApi(token=tok)
42
+ c = api.create_commit(repo_id=REPO, repo_type="model", operations=ops,
43
+ commit_message=msg or f"evidence {time.strftime('%Y-%m-%d %H:%M UTC', time.gmtime())}")
44
+ print("PUBLISHED", c.oid[:12])
45
+ return 0
46
+
47
+ if __name__ == "__main__":
48
+ sys.exit(main(sys.argv[1:]))