herdr-orchestra 6.32.0 → 6.34.0

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.
package/bin/orch CHANGED
@@ -173,7 +173,7 @@ def state_lock():
173
173
  # usable while autopilot drives: reads, and the lead's requests (the event manager carries them out)
174
174
  LEASE_FREE = {"status", "ready", "pick", "report", "approve", "autopilot", "events", "dispatch", "answer", "defer",
175
175
  "fix", "team", "resume", "bench", "stop", "doctor", "plan", "story", "check", "free", "manual", "view",
176
- "board", "changes"}
176
+ "board", "changes", "onboard"}
177
177
  _LEASE = None
178
178
 
179
179
 
@@ -1664,6 +1664,21 @@ def cmd_sync(args):
1664
1664
  if not path_allowed(pth, files[tid]):
1665
1665
  warns.append(f"{tid}'s acceptance criteria name {pth}, which is not in its Likely files — add it, so "
1666
1666
  f"the coder may write it")
1667
+ sk_all = None
1668
+ for tid in enabled: # `Skills:` names skills the repo has, and none that clash with a run
1669
+ vals = by_id[tid]["fields"].get("skills", [])
1670
+ names = [w.strip(" `*-") for v in vals for w in re.split(r"[,;]", v)]
1671
+ names = [w for w in names if w and w.lower() not in ("none", "n/a")]
1672
+ if not names:
1673
+ continue
1674
+ if sk_all is None:
1675
+ sk_all = project_skills(ROOT, registry(required=False) or {})
1676
+ have, clash = {x["name"] for x in sk_all}, clash_skills(sk_all)
1677
+ for n in names:
1678
+ if n in clash:
1679
+ warns.append(f"{tid} Skills: {n} does orch's job in a run ({clash[n]}) — leave it out")
1680
+ elif n not in have:
1681
+ warns.append(f"{tid} Skills: {n} is not a skill in this repo (`orch onboard skills` lists them)")
1667
1682
  max_tasks = int(os.environ.get("ORCH_MAX_TASKS", "0") or 0) # no limit unless you set one
1668
1683
  if max_tasks and len(enabled) > max_tasks:
1669
1684
  warns.append(f"{len(enabled)} enabled milestones (> ORCH_MAX_TASKS={max_tasks}). Merge coupled milestones "
@@ -2221,7 +2236,6 @@ RESULT_FORMAT = {
2221
2236
  "check": {"ran": True, "passed": True, "summary": "lint ok, 42 tests pass"},
2222
2237
  "criteria": [{"id": "AC1", "met": True, "evidence": "test 'rejects a missing amount column' passes"}],
2223
2238
  "questions": ["only when status is question: what you need decided, with 2-3 options"],
2224
- "usage": {"input_tokens": None, "output_tokens": None, "cost_usd": None},
2225
2239
  "proof": "only when task.md says the milestone is hard to undo: what you ran to show it is safe, and what it showed",
2226
2240
  }
2227
2241
  REVIEW_FORMAT = {
@@ -2257,10 +2271,473 @@ def read_result(path):
2257
2271
  return d, None
2258
2272
 
2259
2273
 
2260
- def read_usage(path):
2261
- d, _ = read_json(path) if path else (None, None)
2262
- u = d.get("usage") if isinstance(d, dict) else None
2263
- return {k: v for k, v in u.items() if v is not None} or None if isinstance(u, dict) else None
2274
+ # ---- token usage, read from each tool's OWN session log (6.33.0). Nothing is guessed: a job whose log orch can't
2275
+ # find or read gets {"na": "<why>"} and shows as "not available (<why>)". In = everything the agent read (cached
2276
+ # included), cached = the part it re-read from its own chat, out = everything it wrote (thinking included).
2277
+ TOKEN_GRACE_S = int(os.environ.get("ORCH_TOKEN_GRACE_S", "20")) # let the tool write its last reply first
2278
+ TOKEN_GIVE_UP_S = int(os.environ.get("ORCH_TOKEN_GIVE_UP_S", "600")) # no log after this: "not available"
2279
+ TOKEN_KINDS = ("claude", "codex", "pi", "agy")
2280
+
2281
+
2282
+ class TokenNA(Exception):
2283
+ """Why this job's tokens are not available (shown to the developer as is)."""
2284
+
2285
+
2286
+ def token_roots(kind):
2287
+ """Where each tool keeps its session logs (each tool's own setting first)."""
2288
+ home = Path.home()
2289
+ test = os.environ.get("ORCH_TOKEN_HOME") # tests: every tool's logs under one folder, never the real ones
2290
+ if test:
2291
+ return [Path(test) / {"claude": "claude/projects", "codex": "codex/sessions", "pi": "pi/sessions",
2292
+ "agy": "agy/brain"}.get(kind, kind)]
2293
+ if kind == "claude":
2294
+ return [Path(os.environ.get("CLAUDE_CONFIG_DIR") or home / ".claude") / "projects"]
2295
+ if kind == "codex":
2296
+ return [Path(os.environ.get("CODEX_HOME") or home / ".codex") / "sessions"]
2297
+ if kind == "pi":
2298
+ return [Path(os.environ.get("PI_CODING_AGENT_SESSION_DIR") or home / ".pi" / "agent" / "sessions")]
2299
+ if kind == "agy":
2300
+ return [home / ".gemini" / "antigravity-cli" / "brain"]
2301
+ return []
2302
+
2303
+
2304
+ TOKEN_GLOBS = {"claude": "*/*.jsonl", "codex": "**/rollout-*.jsonl*", "pi": "*/*.jsonl",
2305
+ "agy": "*/.system_generated/logs/transcript_full.jsonl"}
2306
+
2307
+
2308
+ def _tok_text(path):
2309
+ p = str(path)
2310
+ if p.endswith(".zst"):
2311
+ if not shutil.which("zstd"):
2312
+ raise TokenNA("the log is compressed (.zst) and the `zstd` tool is not installed")
2313
+ r = subprocess.run(["zstd", "-dcq", p], capture_output=True, timeout=120)
2314
+ if r.returncode:
2315
+ raise TokenNA("the compressed log could not be unpacked")
2316
+ return r.stdout.decode("utf-8", "replace")
2317
+ try:
2318
+ return Path(p).read_text(errors="replace")
2319
+ except OSError:
2320
+ raise TokenNA("the log could not be read")
2321
+
2322
+
2323
+ def _tok_rows(text):
2324
+ for ln in text.splitlines():
2325
+ if not ln.startswith("{"):
2326
+ continue
2327
+ try:
2328
+ d = json.loads(ln)
2329
+ except ValueError:
2330
+ continue
2331
+ if isinstance(d, dict):
2332
+ yield d
2333
+
2334
+
2335
+ def _tok_ts(v):
2336
+ """A log timestamp (ISO text, or epoch seconds / milliseconds) as epoch seconds, or None."""
2337
+ if isinstance(v, bool):
2338
+ return None
2339
+ if isinstance(v, (int, float)):
2340
+ return v / 1000 if v > 1e11 else float(v)
2341
+ if isinstance(v, str) and v:
2342
+ import datetime as _dt
2343
+ try:
2344
+ t = _dt.datetime.fromisoformat(v.strip().replace("Z", "+00:00"))
2345
+ except ValueError:
2346
+ return None
2347
+ return (t if t.tzinfo else t.replace(tzinfo=_dt.timezone.utc)).timestamp()
2348
+ return None
2349
+
2350
+
2351
+ def _tok_str(c):
2352
+ """Message content (a string, or a list of text parts) as one string."""
2353
+ if isinstance(c, str):
2354
+ return c
2355
+ if isinstance(c, list):
2356
+ return "\n".join(_tok_str(x.get("text") if isinstance(x, dict) else x) for x in c)
2357
+ return ""
2358
+
2359
+
2360
+ def _tok_user_text(kind, d):
2361
+ """What the PERSON (here: orch typing into the pane) said in this log line, else ""."""
2362
+ if kind == "claude":
2363
+ if d.get("type") == "user" and not d.get("toolUseResult") and isinstance(d.get("message"), dict):
2364
+ c = d["message"].get("content")
2365
+ if isinstance(c, list) and any(isinstance(x, dict) and x.get("type") == "tool_result" for x in c):
2366
+ return ""
2367
+ return _tok_str(c)
2368
+ elif kind == "codex":
2369
+ p = d.get("payload") if isinstance(d.get("payload"), dict) else {}
2370
+ if d.get("type") == "event_msg" and p.get("type") == "user_message":
2371
+ return _tok_str(p.get("message"))
2372
+ if d.get("type") == "response_item" and p.get("role") == "user":
2373
+ return _tok_str(p.get("content"))
2374
+ elif kind == "pi":
2375
+ m = d.get("message") if isinstance(d.get("message"), dict) else {}
2376
+ if d.get("type") == "message" and m.get("role") == "user":
2377
+ return _tok_str(m.get("content"))
2378
+ elif kind == "agy":
2379
+ if d.get("source") == "USER_EXPLICIT" or d.get("type") == "USER_INPUT":
2380
+ return _tok_str(d.get("content"))
2381
+ return ""
2382
+
2383
+
2384
+ def token_log_has(kind, path, marker):
2385
+ """True when orch's own prompt with this marker is a user message in the log."""
2386
+ try:
2387
+ text = _tok_text(path)
2388
+ except TokenNA:
2389
+ return False
2390
+ if marker not in text:
2391
+ return False
2392
+ return any(marker in _tok_user_text(kind, d) for d in _tok_rows(text))
2393
+
2394
+
2395
+ def token_log_find(kind, marker, since, known=()):
2396
+ """The session log of `kind` in which orch typed the prompt holding `marker` (unique per job), or None. Logs
2397
+ orch already tied to this pane are tried first; then every log of that tool changed since the job started."""
2398
+ for p in known:
2399
+ if Path(p).exists() and token_log_has(kind, p, marker):
2400
+ return str(p)
2401
+ cands = []
2402
+ for r in token_roots(kind):
2403
+ if not r.is_dir():
2404
+ continue
2405
+ for p in r.glob(TOKEN_GLOBS.get(kind, "*.jsonl")):
2406
+ try:
2407
+ mt = p.stat().st_mtime
2408
+ except OSError:
2409
+ continue
2410
+ if mt >= since - 5 and str(p) not in known:
2411
+ cands.append((mt, p))
2412
+ for _, p in sorted(cands, reverse=True):
2413
+ if token_log_has(kind, p, marker):
2414
+ return str(p)
2415
+ return None
2416
+
2417
+
2418
+ def _tok_add(acc, ts, start, end, inp, cached, out):
2419
+ if ts is None or ts < start or ts > end:
2420
+ return
2421
+ acc["in"] += int(inp or 0)
2422
+ acc["cached"] += int(cached or 0)
2423
+ acc["out"] += int(out or 0)
2424
+ acc["replies"] += 1
2425
+
2426
+
2427
+ def token_window(kind, path, start, end):
2428
+ """Tokens one session log used between start and end (epoch seconds): {"in", "cached", "out", "replies"}.
2429
+ Raises TokenNA when the log has no token counts at all."""
2430
+ acc = {"in": 0, "cached": 0, "out": 0, "replies": 0}
2431
+ text = _tok_text(path)
2432
+ seen_counts = False
2433
+ if kind == "claude":
2434
+ files = [text] + [_tok_text(s) for s in sorted((Path(path).with_suffix("") / "subagents").glob("*.jsonl"))]
2435
+ for tx in files:
2436
+ msgs = {} # one reply is often written as several lines with the same message id
2437
+ for d in _tok_rows(tx):
2438
+ m = d.get("message") if isinstance(d.get("message"), dict) else {}
2439
+ u = m.get("usage")
2440
+ if d.get("type") != "assistant" or not isinstance(u, dict):
2441
+ continue
2442
+ seen_counts = True
2443
+ key = (m.get("id"), d.get("requestId")) if m.get("id") else d.get("uuid") or id(d)
2444
+ ts = _tok_ts(d.get("timestamp"))
2445
+ row = (int(u.get("input_tokens") or 0) + int(u.get("cache_creation_input_tokens") or 0)
2446
+ + int(u.get("cache_read_input_tokens") or 0), int(u.get("cache_read_input_tokens") or 0),
2447
+ int(u.get("output_tokens") or 0))
2448
+ old = msgs.get(key)
2449
+ msgs[key] = (ts if old is None else old[0], tuple(max(a, b) for a, b in zip(row, old[1])) if old else row)
2450
+ for ts, (i, c, o) in msgs.values():
2451
+ _tok_add(acc, ts, start, end, i, c, o)
2452
+ elif kind == "codex":
2453
+ before = last = None # Codex writes a running total: the job's share is end total - start total
2454
+ for d in _tok_rows(text):
2455
+ p = d.get("payload") if isinstance(d.get("payload"), dict) else {}
2456
+ if d.get("type") != "event_msg" or p.get("type") != "token_count":
2457
+ continue
2458
+ tot = (p.get("info") or {}).get("total_token_usage") if isinstance(p.get("info"), dict) else None
2459
+ if not isinstance(tot, dict):
2460
+ continue
2461
+ seen_counts = True
2462
+ ts = _tok_ts(d.get("timestamp"))
2463
+ if ts is None:
2464
+ continue
2465
+ row = (int(tot.get("input_tokens") or 0), int(tot.get("cached_input_tokens") or 0),
2466
+ int(tot.get("output_tokens") or 0))
2467
+ if ts < start:
2468
+ before = row
2469
+ elif ts <= end:
2470
+ if last is not None and row != last:
2471
+ acc["replies"] += 1
2472
+ elif last is None:
2473
+ acc["replies"] += 1
2474
+ last = row
2475
+ if last is not None:
2476
+ b = before or (0, 0, 0)
2477
+ acc.update({"in": max(0, last[0] - b[0]), "cached": max(0, last[1] - b[1]), "out": max(0, last[2] - b[2])})
2478
+ elif kind == "pi":
2479
+ for d in _tok_rows(text):
2480
+ m = d.get("message") if isinstance(d.get("message"), dict) else {}
2481
+ u = m.get("usage") if d.get("type") == "message" and m.get("role") == "assistant" else d.get("usage")
2482
+ if not isinstance(u, dict) or d.get("type") == "message" and m.get("role") != "assistant":
2483
+ continue
2484
+ seen_counts = True
2485
+ _tok_add(acc, _tok_ts(d.get("timestamp")) or _tok_ts(m.get("timestamp")), start, end,
2486
+ int(u.get("input") or 0) + int(u.get("cacheRead") or 0) + int(u.get("cacheWrite") or 0),
2487
+ u.get("cacheRead"), u.get("output"))
2488
+ elif kind == "agy":
2489
+ steps = 0
2490
+ for d in _tok_rows(text):
2491
+ if d.get("source") == "MODEL" or d.get("type") == "PLANNER_RESPONSE":
2492
+ steps += 1
2493
+ if not any(k in d for k in ("input_tokens", "output_tokens")):
2494
+ continue
2495
+ seen_counts = True
2496
+ _tok_add(acc, _tok_ts(d.get("created_at")), start, end,
2497
+ int(d.get("input_tokens") or 0) + int(d.get("cache_read_tokens") or 0),
2498
+ d.get("cache_read_tokens"), d.get("output_tokens"))
2499
+ if steps and not seen_counts:
2500
+ raise TokenNA("this agy version saves no token counts (update agy)")
2501
+ else:
2502
+ raise TokenNA(f"orch can't read {kind}'s logs")
2503
+ if not seen_counts:
2504
+ raise TokenNA(f"{kind}'s log has no token counts")
2505
+ return acc
2506
+
2507
+
2508
+ def agent_kind_of(st, agent):
2509
+ if (st.get("lead") or {}).get("name") == agent:
2510
+ return st["lead"].get("kind")
2511
+ if agent and agent == st.get("reviewer"):
2512
+ return (st.get("reviewer_info") or {}).get("kind")
2513
+ return (st.get("workers", {}).get(agent) or {}).get("kind")
2514
+
2515
+
2516
+ def token_marker(prompt):
2517
+ """The part of orch's job prompt that is unique to that one job: the result or review file it names."""
2518
+ m = re.search(r"[\w./-]*(?:result-\d+\.json|review-task-\d+\.md)", prompt or "")
2519
+ return m.group(0) if m else None
2520
+
2521
+
2522
+ def token_measure(st, agent, kind, marker, start, end, cap=None):
2523
+ """{"in", "cached", "out", "log"} for one job, or {"na": why}, or None (not written yet: try again later)."""
2524
+ if not kind:
2525
+ return {"na": "orch does not know which tool this agent runs"}
2526
+ if kind not in TOKEN_KINDS:
2527
+ return {"na": f"orch can't read {kind}'s logs"}
2528
+ if not marker:
2529
+ return {"na": "no job prompt to find the log by"}
2530
+ logs = st.setdefault("token_logs", {})
2531
+ known = logs.get(agent) or []
2532
+ try:
2533
+ path = token_log_find(kind, marker, start, known)
2534
+ if not path:
2535
+ return None if now() - end < TOKEN_GIVE_UP_S else {"na": f"no {kind} log has this job's prompt"}
2536
+ acc = token_window(kind, path, start, min(end + TOKEN_GRACE_S, cap or float("inf")))
2537
+ except TokenNA as e:
2538
+ return {"na": str(e)}
2539
+ if path not in known:
2540
+ logs[agent] = (known + [path])[-6:]
2541
+ if not acc["replies"]:
2542
+ return None if now() - end < TOKEN_GIVE_UP_S else {"na": "no replies in the log during this job"}
2543
+ return {"in": acc["in"], "cached": acc["cached"], "out": acc["out"], "log": kind}
2544
+
2545
+
2546
+ def token_fill(st, force=False):
2547
+ """Read the tokens of every finished job that has none yet (each tool's log, read only). True if any changed.
2548
+ `force` (summary, report): don't wait for the grace time and give up on logs that are not there."""
2549
+ changed = False
2550
+ starts = {} # the agent's next job starts where this one's window must end
2551
+ for t in st.get("tasks", {}).values():
2552
+ for a in t.get("attempts") or []:
2553
+ starts.setdefault(a.get("agent"), []).append(a.get("start", 0))
2554
+ for w in st.get("tasks", {}).values():
2555
+ if w.get("wait"):
2556
+ starts.setdefault(w["wait"].get("agent"), []).append(w["wait"].get("started", w["wait"].get("since", 0)))
2557
+ for tid in st.get("order", []):
2558
+ for a in (st["tasks"].get(tid) or {}).get("attempts") or []:
2559
+ if "tokens" in a or not a.get("tok_marker"):
2560
+ continue
2561
+ if not force and now() - a.get("end", 0) < TOKEN_GRACE_S:
2562
+ continue
2563
+ r = token_measure(st, a.get("agent"), a.get("tok_kind") or agent_kind_of(st, a.get("agent")),
2564
+ a["tok_marker"], a.get("start", 0), a.get("end", now()),
2565
+ min([x for x in starts.get(a.get("agent"), []) if x > a.get("start", 0)] or [None],
2566
+ key=lambda x: x or float("inf")))
2567
+ if r is not None:
2568
+ a["tokens"] = r
2569
+ changed = True
2570
+ return changed
2571
+
2572
+
2573
+ def token_fill_saved():
2574
+ """token_fill on the saved state, under the state lock (orch report, orch tokens, orch view)."""
2575
+ if not STATE.exists():
2576
+ return
2577
+ try:
2578
+ with state_lock():
2579
+ st = load()
2580
+ if token_fill(st, force=True):
2581
+ save(st)
2582
+ except Exception as e: # a strange log never stops a report
2583
+ print(f"(token count skipped: {e})", file=sys.stderr)
2584
+
2585
+
2586
+ def lead_tokens(st):
2587
+ """The lead's tokens from the run's start to its end (or now), found by orch's wake-up text."""
2588
+ ld, run = st.get("lead") or {}, st.get("run") or {}
2589
+ if not ld.get("name"):
2590
+ return None
2591
+ if not run.get("started"):
2592
+ return {"na": "the run has not started"}
2593
+ marker = f"in the run on {st.get('branch')} need the lead"
2594
+ r = token_measure(st, ld["name"], ld.get("kind"), marker, run["started"], run.get("ended") or now()) \
2595
+ or {"na": "the lead was never woken by orch, so its log can't be told apart"}
2596
+ saved = run.get("lead_tokens") # read at ALL_DONE: still good if the tool deleted the log since
2597
+ return saved if "na" in r and isinstance(saved, dict) and "na" not in saved else r
2598
+
2599
+
2600
+ def between_tokens(st, account_rows):
2601
+ """Tokens agents used outside every job window during the run (their /compact, the developer typing into the
2602
+ pane between jobs): the logs' run total minus what the jobs got."""
2603
+ run = st.get("run") or {}
2604
+ if not run.get("started"):
2605
+ return None
2606
+ start, end = run["started"], run.get("ended") or now()
2607
+ total = {"in": 0, "cached": 0, "out": 0}
2608
+ got = {"in": 0, "cached": 0, "out": 0}
2609
+ lead = (st.get("lead") or {}).get("name")
2610
+ for agent, paths in (st.get("token_logs") or {}).items():
2611
+ if agent == lead:
2612
+ continue
2613
+ kind = agent_kind_of(st, agent)
2614
+ for p in paths:
2615
+ try:
2616
+ w = token_window(kind, p, start, end)
2617
+ except TokenNA:
2618
+ return None
2619
+ for k in total:
2620
+ total[k] += w[k]
2621
+ for r in account_rows:
2622
+ for part in ("coder", "review"):
2623
+ u = r[part]
2624
+ if u and "na" not in u:
2625
+ for k in got:
2626
+ got[k] += u[k]
2627
+ out = {k: max(0, total[k] - got[k]) for k in total}
2628
+ return out if any(out.values()) else None
2629
+
2630
+
2631
+ def _tok_merge(rows):
2632
+ """Add up job token rows: {"in", "cached", "out", "jobs", "na": [why, ...]} or None for no jobs."""
2633
+ if not rows:
2634
+ return None
2635
+ acc = {"in": 0, "cached": 0, "out": 0, "jobs": 0, "known": 0, "na": []}
2636
+ for u in rows:
2637
+ acc["jobs"] += 1
2638
+ if not isinstance(u, dict) or "na" in u:
2639
+ acc["na"].append((u or {}).get("na") if isinstance(u, dict) else "not read yet")
2640
+ continue
2641
+ acc["known"] += 1
2642
+ for k in ("in", "cached", "out"):
2643
+ acc[k] += int(u.get(k) or 0)
2644
+ return acc
2645
+
2646
+
2647
+ _TOK_CACHE = {}
2648
+
2649
+
2650
+ def _tok_cached(key, fn, ttl=60):
2651
+ """For the live board and view: read the logs at most once a minute."""
2652
+ hit = _TOK_CACHE.get(key)
2653
+ if hit and time.time() - hit[0] < ttl:
2654
+ return hit[1]
2655
+ v = fn()
2656
+ _TOK_CACHE[key] = (time.time(), v)
2657
+ return v
2658
+
2659
+
2660
+ def token_account(st, live=False):
2661
+ """Tokens per milestone (coder jobs, review rounds), the lead, between jobs and the total. Only what the logs
2662
+ said: a milestone with a job whose log was missing is marked so the total reads "at least"."""
2663
+ rows = []
2664
+ for tid in st.get("order", []):
2665
+ t = st["tasks"][tid]
2666
+ if t.get("status") == "skipped":
2667
+ continue
2668
+ at = [a for a in t.get("attempts") or [] if isinstance(a, dict)]
2669
+ at = [a for a in at if a.get("tok_marker") or a.get("tokens")] # jobs that were really sent
2670
+ co = [a for a in at if a.get("kind") != "reviewer"]
2671
+ rv = [a for a in at if a.get("kind") == "reviewer"]
2672
+ fixes = [a for a in co if a.get("file") and a["file"] != "task.md"]
2673
+ rows.append({"task": tid, "title": t.get("title") or tid,
2674
+ "coders": list(dict.fromkeys(a.get("agent") for a in co if a.get("agent"))),
2675
+ "reviewers": list(dict.fromkeys(a.get("agent") for a in rv if a.get("agent"))),
2676
+ "coder": _tok_merge([a.get("tokens") for a in co]),
2677
+ "fixes": _tok_merge([a.get("tokens") for a in fixes]),
2678
+ "review": _tok_merge([a.get("tokens") for a in rv])})
2679
+ if live: # board / view redraw often: lead once a minute, "between jobs" only in the summary
2680
+ lead = _tok_cached(("lead", st.get("branch")), lambda: lead_tokens(json.loads(json.dumps(st)))) \
2681
+ if st.get("lead") else None
2682
+ between = None
2683
+ else:
2684
+ lead = lead_tokens(st) if st.get("lead") else None
2685
+ between = between_tokens(st, rows)
2686
+ total, partial = 0, False
2687
+ for r in rows:
2688
+ r["total"] = sum(r[p]["in"] + r[p]["out"] for p in ("coder", "review") if r[p])
2689
+ r["partial"] = any(r[p] and r[p]["na"] for p in ("coder", "review"))
2690
+ total += r["total"]
2691
+ partial |= r["partial"]
2692
+ if lead and "na" not in lead:
2693
+ total += lead["in"] + lead["out"]
2694
+ elif lead:
2695
+ partial = True
2696
+ if between:
2697
+ total += between["in"] + between["out"]
2698
+ return {"tasks": rows, "lead": lead, "between": between, "total": total, "partial": partial}
2699
+
2700
+
2701
+ def _tk(n):
2702
+ n = int(n or 0)
2703
+ return f"{n / 1e6:.1f}M" if n >= 1_000_000 else f"{round(n / 1000)}k" if n >= 1000 else str(n)
2704
+
2705
+
2706
+ def _tok_cell(u, who=""):
2707
+ if not u:
2708
+ return "-"
2709
+ if not u["known"]:
2710
+ return f"not available ({u['na'][0]})"
2711
+ s = f"{_tk(u['in'] + u['out'])} (in {_tk(u['in'])}, of which {_tk(u['cached'])} cached; out {_tk(u['out'])})"
2712
+ if u["na"]:
2713
+ s += f" + {len(u['na'])} job(s) not available ({u['na'][0]})"
2714
+ return s + (f" {who}" if who else "")
2715
+
2716
+
2717
+ def token_lines(acct):
2718
+ """Tokens per milestone as markdown."""
2719
+ out = ["| Milestone | Built by | Coder tokens | Review tokens | Total |", "|---|---|---|---|---|"]
2720
+ for r in acct["tasks"]:
2721
+ fx = r["fixes"]
2722
+ coder = _tok_cell(r["coder"]) + (f"; fixes {_tk(fx['in'] + fx['out'])}" if fx and fx["known"] else "")
2723
+ out.append(f"| {r['task']} {r['title']} | {', '.join(r['coders']) or '-'} | {coder} | "
2724
+ f"{_tok_cell(r['review'], '(' + ', '.join(r['reviewers']) + ')' if r['reviewers'] else '')} | "
2725
+ f"{_tk(r['total'])}{'+' if r['partial'] else ''} |")
2726
+ ld = acct["lead"]
2727
+ if ld:
2728
+ out.append("| Lead (whole run) | | " + (f"not available ({ld['na']})" if "na" in ld else
2729
+ f"{_tk(ld['in'] + ld['out'])} (in {_tk(ld['in'])}, of which {_tk(ld['cached'])} cached; out "
2730
+ f"{_tk(ld['out'])})") + f" | | {'-' if 'na' in ld else _tk(ld['in'] + ld['out'])} |")
2731
+ bt = acct["between"]
2732
+ if bt:
2733
+ out.append(f"| Between jobs (/compact, typing in a pane) | | {_tk(bt['in'] + bt['out'])} | | "
2734
+ f"{_tk(bt['in'] + bt['out'])} |")
2735
+ out.append(f"| **Total** | | | | **{_tk(acct['total'])}{'+' if acct['partial'] else ''}** |")
2736
+ out += ["", "Read from each agent's own log. In = what the agent read (its chat included; the cached part is its "
2737
+ "own chat read again, much cheaper), out = what it wrote."]
2738
+ if acct["partial"]:
2739
+ out.append("`+` = some jobs' tokens are not available (reason in the row), so the real number is higher.")
2740
+ return out
2264
2741
 
2265
2742
 
2266
2743
  def finding_axis(f):
@@ -2620,6 +3097,7 @@ def cmd_start(args):
2620
3097
  git("worktree", "add", "--detach", str(p), st["branch"], cwd=ROOT)
2621
3098
  w["setup_done"] = False
2622
3099
  print(f"CREATED worktree {p}")
3100
+ onboard_overlay(p)
2623
3101
  w["dir"] = str(p)
2624
3102
  else:
2625
3103
  for w in st["workers"].values():
@@ -2848,6 +3326,8 @@ def cmd_prepare(args):
2848
3326
  src = task_ref(st, tid)
2849
3327
  if not in_place:
2850
3328
  git("switch", "-q", "--detach", src or st["branch"], cwd=d)
3329
+ for rel in onboard_overlay(d): # project setup kept on this machine: git can't bring it there
3330
+ print(f"LINKED {rel} into {worker}'s folder (project setup, hidden from git)")
2851
3331
  else:
2852
3332
  if git("rev-parse", "--abbrev-ref", "HEAD", cwd=ROOT).stdout.strip() != st["branch"]:
2853
3333
  die(f"main tree is not on {st['branch']}")
@@ -2978,6 +3458,9 @@ def record_attempt(t, outcome, usage=None):
2978
3458
  a["blocked_s"] = min(blocked, a["secs"]) # time herdr showed the agent stopped at a prompt in its pane
2979
3459
  if usage:
2980
3460
  a["usage"] = usage
3461
+ mk = token_marker(w.get("prompt")) if outcome != "not delivered" else None
3462
+ if mk:
3463
+ a["tok_marker"] = mk # the job's own prompt: how orch finds its tokens in the tool's log
2981
3464
  t.setdefault("attempts", []).append(a)
2982
3465
  del t["attempts"][:-100]
2983
3466
 
@@ -3360,7 +3843,7 @@ def cmd_poll(args):
3360
3843
  agent, sentinel = w["agent"], Path(w["sentinel"])
3361
3844
  age = now() - w["since"]
3362
3845
  if sentinel.exists():
3363
- record_attempt(t, "done", read_usage(w.get("result")))
3846
+ record_attempt(t, "done")
3364
3847
  if w["kind"] == "coder":
3365
3848
  move(st, tid, "verifying")
3366
3849
  t["last_report"] = w["report"]
@@ -4389,6 +4872,615 @@ def project_rules_lines(st, rules):
4389
4872
  return out + [""]
4390
4873
 
4391
4874
 
4875
+ # ---------------------------------------------------------------- onboard: set a project up for its agents (6.33.0)
4876
+ # `orch onboard` looks at a repo (stack, commands, rule files, the skills each agent can see) with no AI. The lead then
4877
+ # proposes only what is missing (`orch lead onboard`), the developer ticks what they want, and `orch onboard done`
4878
+ # keeps it on their machine only (.git/info/exclude) or puts it on its own branch with a PR. `orch lead plan` runs the
4879
+ # look by itself, so the developer never has to remember the command.
4880
+ ONBOARD_FILE = "onboard.json" # .orchestrate/onboard.json: done or skipped, the mode, the files orch wrote
4881
+ ONBOARD_NOTES = "onboard-notes.md" # .orchestrate/onboard-notes.md: notes for coders that a tracked file can't take
4882
+ ONBOARD_MARK = ("<!-- orch-onboard -->", "<!-- /orch-onboard -->")
4883
+ ONBOARD_BRANCH = "orch/onboard"
4884
+ # project skill folders orch looks in (each agent's own list is `project_skills_reads` in the agent registry)
4885
+ PROJECT_SKILL_DIRS = (".agent/skills", ".agents/skills", ".claude/skills", ".pi/skills", ".opencode/skills")
4886
+ RULE_FILES = ("AGENTS.md", "CLAUDE.md", "GEMINI.md", ".agent/rules", ".agents/rules", ".cursor/rules", ".cursorrules",
4887
+ ".github/copilot-instructions.md")
4888
+ # skills that run the work themselves (their own git folder, merging, helper agents): in a run orch does that
4889
+ CLASH_SKILLS = {
4890
+ "using-git-worktrees": "it makes its own git worktree; orch already gave you a folder",
4891
+ "finishing-a-development-branch": "it merges or pushes the branch; orch lands your work and a person merges the PR",
4892
+ "dispatching-parallel-agents": "it starts helper agents; orch already split the work into milestones",
4893
+ "subagent-driven-development": "it starts helper agents; orch already split the work into milestones",
4894
+ }
4895
+ CLASH_RE = re.compile(r"git worktree|\bworktrees?\b|\bmerg(?:e|es|ing) (?:the |a |this |your )?(?:feature |development )?"
4896
+ r"branch|\bparallel (?:sub)?agents\b", re.I)
4897
+ # package.json dependency -> what it means, in the words a developer uses
4898
+ STACK_NPM = (("next", "Next.js"), ("react-native", "React Native"), ("expo", "Expo"), ("react", "React"),
4899
+ ("nuxt", "Nuxt"), ("vue", "Vue"), ("@sveltejs/kit", "SvelteKit"), ("svelte", "Svelte"),
4900
+ ("@angular/core", "Angular"), ("@nestjs/core", "NestJS"), ("express", "Express"), ("fastify", "Fastify"),
4901
+ ("hono", "Hono"), ("@supabase/supabase-js", "Supabase"), ("@supabase/ssr", "Supabase"),
4902
+ ("firebase", "Firebase"), ("@prisma/client", "Prisma"), ("prisma", "Prisma"),
4903
+ ("drizzle-orm", "Drizzle"), ("mongoose", "MongoDB (Mongoose)"), ("@trpc/server", "tRPC"),
4904
+ ("tailwindcss", "Tailwind"), ("@tanstack/react-query", "TanStack Query"), ("zod", "Zod"),
4905
+ ("stripe", "Stripe"), ("razorpay", "Razorpay"), ("next-intl", "i18n (next-intl)"),
4906
+ ("i18next", "i18n (i18next)"), ("vitest", "Vitest"), ("jest", "Jest"),
4907
+ ("@playwright/test", "Playwright"), ("cypress", "Cypress"), ("typescript", "TypeScript"))
4908
+ # a file in the repo -> what it means
4909
+ STACK_FILES = (("supabase/config.toml", "Supabase"), ("prisma/schema.prisma", "Prisma"), ("go.mod", "Go"),
4910
+ ("Cargo.toml", "Rust"), ("pubspec.yaml", "Flutter"), ("Gemfile", "Ruby"), ("composer.json", "PHP"),
4911
+ ("pyproject.toml", "Python"), ("requirements.txt", "Python"), ("docker-compose.yml", "Docker Compose"),
4912
+ ("compose.yaml", "Docker Compose"))
4913
+ STACK_PY = (("django", "Django"), ("fastapi", "FastAPI"), ("flask", "Flask"), ("pytest", "pytest"))
4914
+ SCRIPT_KEYS = ("dev", "build", "test", "lint", "typecheck", "type-check", "check", "format", "e2e")
4915
+
4916
+
4917
+ def onboard_root(cwd=None):
4918
+ """The repo's main folder (a coder's worktree counts as its main repo), or None outside a git repo."""
4919
+ gd = git_common_dir(cwd or Path.cwd())
4920
+ return Path(gd).parent if gd else None
4921
+
4922
+
4923
+ def onboard_state(root):
4924
+ p = Path(root) / ".orchestrate" / ONBOARD_FILE
4925
+ try:
4926
+ d = json.loads(p.read_text()) if p.is_file() else {}
4927
+ except (OSError, ValueError):
4928
+ d = {}
4929
+ return d if isinstance(d, dict) else {}
4930
+
4931
+
4932
+ def onboard_save(root, d):
4933
+ p = Path(root) / ".orchestrate" / ONBOARD_FILE
4934
+ p.parent.mkdir(parents=True, exist_ok=True)
4935
+ ex = exclude_file(root) # .orchestrate/ is orch's own: never shown by git (as `orch start` does)
4936
+ lines = ex.read_text().splitlines() if ex.exists() else []
4937
+ if ".orchestrate/" not in lines:
4938
+ ex.parent.mkdir(parents=True, exist_ok=True)
4939
+ ex.write_text("\n".join(lines + [".orchestrate/"]) + "\n")
4940
+ p.write_text(json.dumps(d, indent=2) + "\n")
4941
+
4942
+
4943
+ def skill_front(path):
4944
+ """SKILL.md -> (name, description) from its front matter (plain `key: value` lines, quoted or folded)."""
4945
+ try:
4946
+ text = Path(path).read_text(errors="replace")
4947
+ except OSError:
4948
+ return None, ""
4949
+ m = re.match(r"?---\s*\n(.*?)\n---", text, re.S)
4950
+ if not m:
4951
+ return None, ""
4952
+ out, key = {}, None
4953
+ for line in m.group(1).splitlines():
4954
+ km = re.match(r"([A-Za-z_-]+):\s*(.*)$", line)
4955
+ if km and not line.startswith((" ", "\t")):
4956
+ key, val = km.group(1).lower(), km.group(2).strip()
4957
+ out[key] = "" if val in (">", "|", ">-", "|-") else val.strip("'\"")
4958
+ elif key and line.strip():
4959
+ out[key] = (out[key] + " " + line.strip()).strip()
4960
+ return out.get("name") or None, out.get("description", "")
4961
+
4962
+
4963
+ def project_skill_dirs(reg):
4964
+ """Every project skill folder orch knows of: its own list plus each agent's `project_skills_reads`."""
4965
+ out = list(PROJECT_SKILL_DIRS)
4966
+ for v in (reg or {}).values():
4967
+ for d in v.get("project_skills_reads", []) or []:
4968
+ if d not in out:
4969
+ out.append(d)
4970
+ return out
4971
+
4972
+
4973
+ def project_skills(root, reg):
4974
+ """[{name, description, folder, path, real}] of every SKILL.md in the repo's project skill folders. `folder` is the
4975
+ folder as the repo writes it (`.agent/skills`); `real` is where the skill really is (a link counts once)."""
4976
+ out, real_dirs = [], set()
4977
+ for d in project_skill_dirs(reg):
4978
+ base = Path(root) / d
4979
+ if not base.is_dir() or os.path.realpath(base) in real_dirs: # a linked folder holds the same skills
4980
+ continue
4981
+ real_dirs.add(os.path.realpath(base))
4982
+ for child in sorted(base.iterdir(), key=lambda p: p.name):
4983
+ f = child / "SKILL.md"
4984
+ if not f.is_file():
4985
+ continue
4986
+ name, desc = skill_front(f)
4987
+ out.append({"name": name or child.name, "description": desc, "folder": d, "path": f"{d}/{child.name}",
4988
+ "real": os.path.realpath(child)})
4989
+ return out
4990
+
4991
+
4992
+ def global_skill_names(v):
4993
+ """Names of the skills in the home folders an agent reads (orch's own and the developer's)."""
4994
+ names = set()
4995
+ for d in agent_reads(v, "skills"):
4996
+ if d.is_dir():
4997
+ names |= {c.name for c in d.iterdir() if (c / "SKILL.md").is_file()}
4998
+ return names
4999
+
5000
+
5001
+ def agent_project_view(root, kind, v, skills):
5002
+ """What one agent sees of the repo's skills: {reads, skills (one per real folder), twice: names it sees twice}."""
5003
+ reads = list(v.get("project_skills_reads", []) or [])
5004
+ real_dirs, seen, twice = set(), {}, set()
5005
+ for d in reads:
5006
+ p = Path(root) / d
5007
+ if not p.is_dir():
5008
+ continue
5009
+ rd = os.path.realpath(p)
5010
+ if rd in real_dirs: # two names for one folder (a link): one copy
5011
+ continue
5012
+ real_dirs.add(rd)
5013
+ for s in skills:
5014
+ if os.path.realpath(Path(root) / s["folder"]) != rd:
5015
+ continue
5016
+ if s["name"] in seen and seen[s["name"]]["real"] != s["real"]:
5017
+ twice.add(s["name"])
5018
+ seen.setdefault(s["name"], s)
5019
+ home = {n for n in global_skill_names(v) if not n.startswith("orch-")}
5020
+ if v.get("skills_one_wins") is not True:
5021
+ twice |= set(seen) & home # a project skill with the name of one in its home folder: listed twice
5022
+ return {"reads": reads, "skills": list(seen.values()), "twice": sorted(twice)}
5023
+
5024
+
5025
+ def stack_of(root):
5026
+ """(stack names, commands, package manager) found in the repo's manifests. Plain file reading, no AI."""
5027
+ root = Path(root)
5028
+ stack, cmds, pm = [], [], None
5029
+ pj = root / "package.json"
5030
+ if pj.is_file():
5031
+ try:
5032
+ data = json.loads(pj.read_text(errors="replace"))
5033
+ except ValueError:
5034
+ data = {}
5035
+ deps = {**(data.get("dependencies") or {}), **(data.get("devDependencies") or {})}
5036
+ for dep, label in STACK_NPM:
5037
+ if dep in deps and label not in stack:
5038
+ stack.append(label)
5039
+ pm = ("pnpm" if (root / "pnpm-lock.yaml").exists() else "yarn" if (root / "yarn.lock").exists()
5040
+ else "bun" if (root / "bun.lockb").exists() or (root / "bun.lock").exists() else "npm")
5041
+ scripts = data.get("scripts") or {}
5042
+ for k in SCRIPT_KEYS:
5043
+ if k in scripts:
5044
+ cmds.append(f"{pm} test" if k == "test" and pm in ("npm", "yarn", "pnpm") else f"{pm} run {k}")
5045
+ for f, label in STACK_FILES:
5046
+ if (root / f).exists() and label not in stack:
5047
+ stack.append(label)
5048
+ py = " ".join((root / f).read_text(errors="replace").lower() for f in ("pyproject.toml", "requirements.txt")
5049
+ if (root / f).is_file())
5050
+ for word, label in STACK_PY:
5051
+ if re.search(r"\b" + word + r"\b", py) and label not in stack:
5052
+ stack.append(label)
5053
+ if "pytest" in stack:
5054
+ cmds.append("pytest")
5055
+ if (root / "go.mod").exists():
5056
+ cmds.append("go test ./...")
5057
+ if (root / "Cargo.toml").exists():
5058
+ cmds.append("cargo test")
5059
+ mk = root / "Makefile"
5060
+ if mk.is_file():
5061
+ targets = re.findall(r"^([A-Za-z][\w-]*):", mk.read_text(errors="replace"), re.M)
5062
+ cmds += [f"make {t}" for t in ("test", "lint", "check", "build") if t in targets]
5063
+ return stack, cmds, pm
5064
+
5065
+
5066
+ def rule_files(root):
5067
+ return [f for f in RULE_FILES if (Path(root) / f).exists()] + \
5068
+ [f"docs/{f}" for f in ("glossary.md", "coding-standards.md", "adr") if (Path(root) / "docs" / f).exists()]
5069
+
5070
+
5071
+ def clash_skills(skills):
5072
+ """The repo's skills that run the work themselves, with why they clash with a run: {name: why}."""
5073
+ out = {}
5074
+ for s in skills:
5075
+ why = CLASH_SKILLS.get(s["name"])
5076
+ if not why and CLASH_RE.search(s["description"] or ""):
5077
+ why = "it runs the work itself (its own branch, worktree or helper agents); orch does that in a run"
5078
+ if why:
5079
+ out[s["name"]] = why
5080
+ return out
5081
+
5082
+
5083
+ def is_tracked(root, rel):
5084
+ return git("ls-files", "--error-unmatch", "--", rel, cwd=root, check=False).returncode == 0
5085
+
5086
+
5087
+ def onboard_scan(root, reg=None):
5088
+ """The whole look at one repo, as a dict (`orch onboard --json`): stack, commands, rule files, skills, what each
5089
+ installed agent sees, the gaps, and what to do now: full (no project skills: set it up), gaps (never set up, and
5090
+ something is missing), quiet (set up or skipped before, or nothing missing)."""
5091
+ root = Path(root)
5092
+ reg = reg if reg is not None else (registry(required=False) or {})
5093
+ stack, cmds, pm = stack_of(root)
5094
+ rules = rule_files(root)
5095
+ skills = project_skills(root, reg)
5096
+ installed = {k: v for k, v in reg.items() if shutil.which(v.get("binary", k))}
5097
+ agents = {k: agent_project_view(root, k, v, skills) for k, v in sorted(installed.items())}
5098
+ clashes = clash_skills(skills)
5099
+ rules_text = ""
5100
+ for f in rules:
5101
+ p = root / f
5102
+ files = [p] if p.is_file() else sorted(p.rglob("*.md")) if p.is_dir() else []
5103
+ for q in files[:50]:
5104
+ try:
5105
+ rules_text += q.read_text(errors="replace") + "\n"
5106
+ except OSError:
5107
+ pass
5108
+ gaps = []
5109
+ if not skills:
5110
+ gaps.append({"id": "skills", "say": "no project skills: no agent here has a skill about this project"})
5111
+ non_claude = [k for k in installed if k != "claude"]
5112
+ if "AGENTS.md" not in rules and (non_claude or "CLAUDE.md" not in rules):
5113
+ gaps.append({"id": "agents-md", "say": "no AGENTS.md: coders don't know the commands and where things live"})
5114
+ elif cmds and not any(c in rules_text for c in cmds):
5115
+ gaps.append({"id": "commands", "say": f"the rule files don't name the commands ({', '.join(cmds[:4])})"})
5116
+ names = {s["name"] for s in skills}
5117
+ for k, a in agents.items():
5118
+ if skills and a["reads"] and not a["skills"]:
5119
+ src = sorted({s["folder"] for s in skills})[0]
5120
+ gaps.append({"id": f"link:{k}", "say": f"{k} can't see the {len(names)} skill(s) in {src} (it reads "
5121
+ f"{', '.join(a['reads'])})", "link": [a["reads"][0], src]})
5122
+ if a["twice"]:
5123
+ gaps.append({"id": f"twice:{k}", "say": f"{k} sees these skills twice: {', '.join(a['twice'])}"})
5124
+ if clashes:
5125
+ gaps.append({"id": "clash", "say": f"{len(clashes)} skill(s) clash with orch in a run: {', '.join(clashes)}"})
5126
+ st = onboard_state(root)
5127
+ if st.get("status") in ("done", "skipped"):
5128
+ decide = "quiet"
5129
+ elif not skills:
5130
+ decide = "full"
5131
+ else:
5132
+ decide = "gaps" if any(g["id"] != "clash" for g in gaps) else "quiet"
5133
+ return {"root": str(root), "stack": stack, "commands": cmds, "package_manager": pm, "rules": rules,
5134
+ "skills": [{k: s[k] for k in ("name", "description", "path")} for s in skills],
5135
+ "agents": {k: {"reads": a["reads"], "sees": len(a["skills"]), "twice": a["twice"]} for k, a in agents.items()},
5136
+ "clash": clashes, "gaps": gaps, "state": st.get("status") or "never", "when": st.get("when"),
5137
+ "decide": decide}
5138
+
5139
+
5140
+ def onboard_report_lines(r):
5141
+ out = [f"Stack: {', '.join(r['stack']) or 'nothing found in the manifests'}",
5142
+ f"Commands: {', '.join(r['commands']) or 'none found'}",
5143
+ f"Rule files: {', '.join(r['rules']) or 'none'}",
5144
+ f"Project skills: {len(r['skills'])}" + (f" ({', '.join(sorted({s['path'].rsplit('/', 1)[0] for s in r['skills']}))})"
5145
+ if r["skills"] else "")]
5146
+ for k, a in r["agents"].items():
5147
+ out.append(f" {k} reads {', '.join(a['reads']) or 'no project folder (not known)'}: sees {a['sees']}"
5148
+ + (f", TWICE: {', '.join(a['twice'])}" if a["twice"] else ""))
5149
+ out.append("Gaps:" if r["gaps"] else "Gaps: none")
5150
+ out += [f" - {g['say']}" for g in r["gaps"]]
5151
+ out.append(f"Set up before: {r['state']}" + (f" ({r['when']})" if r.get("when") else ""))
5152
+ return out
5153
+
5154
+
5155
+ def onboard_plan_note(cwd=None):
5156
+ """What `orch lead plan` prints about project setup before the playbook: the ONBOARD step when the project needs
5157
+ it, the project's skills for `Skills:` lines, or nothing. Never stops the plan."""
5158
+ if os.environ.get("ORCH_ONBOARD") == "0":
5159
+ return ""
5160
+ try:
5161
+ root = onboard_root(cwd)
5162
+ if root is None or find_workspace(Path.cwd()) is not None:
5163
+ return ""
5164
+ r = onboard_scan(root)
5165
+ except Exception as e: # a problem here never stops the plan
5166
+ return f"NOTE project setup check failed ({e}); planning goes on without it.\n\n"
5167
+ out = []
5168
+ if r["decide"] in ("full", "gaps"):
5169
+ why = ("this project has no skills for its agents yet" if r["decide"] == "full"
5170
+ else "this project was never checked for its agents: " + "; ".join(g["say"] for g in r["gaps"]
5171
+ if g["id"] != "clash"))
5172
+ out += [f"PROJECT SETUP: {why}.",
5173
+ " Do this right after step 1 (preflight), before step 2: run `orch lead onboard` and follow it. It asks the developer in one "
5174
+ "list and writes nothing without their tick; the developer can say skip.",
5175
+ " Then come back here and plan the feature request as usual, in the same turn."]
5176
+ if r["skills"]:
5177
+ names = ", ".join(s["name"] for s in r["skills"][:40]) + (" ..." if len(r["skills"]) > 40 else "")
5178
+ out.append(f"PROJECT SKILLS ({len(r['skills'])}, `orch onboard skills` shows what each is for): {names}")
5179
+ if r["clash"]:
5180
+ out.append(f" Never give a milestone these (orch does their job in a run): {', '.join(r['clash'])}")
5181
+ return ("\n".join(out) + "\n\n") if out else ""
5182
+
5183
+
5184
+ def exclude_file(root):
5185
+ return Path(git_common_dir(root)) / "info" / "exclude"
5186
+
5187
+
5188
+ def exclude_add(root, rels):
5189
+ """Hide paths from git on this machine only: .git/info/exclude (the repo's .gitignore is never touched)."""
5190
+ ex = exclude_file(root)
5191
+ ex.parent.mkdir(parents=True, exist_ok=True)
5192
+ lines = ex.read_text().splitlines() if ex.exists() else []
5193
+ added = []
5194
+ for rel in rels:
5195
+ pat = "/" + rel.strip("/")
5196
+ if pat not in lines:
5197
+ if "# orch onboard: only on this machine" not in lines:
5198
+ lines.append("# orch onboard: only on this machine")
5199
+ lines.append(pat)
5200
+ added.append(pat)
5201
+ ex.write_text("\n".join(lines) + "\n")
5202
+ return added
5203
+
5204
+
5205
+ def take_marked_block(root, rel):
5206
+ """A tracked file the lead added an orch-onboard block to: take the block out (the file is as git has it again)
5207
+ and return its text, so it reaches the coders through the notes file instead of a quiet change to a tracked file."""
5208
+ p = Path(root) / rel
5209
+ text = p.read_text(errors="replace") if p.is_file() else ""
5210
+ a, b = ONBOARD_MARK
5211
+ i, j = text.find(a), text.find(b)
5212
+ if i < 0 or j < i:
5213
+ return None
5214
+ block = text[i + len(a):j].strip()
5215
+ git("checkout", "-q", "--", rel, cwd=root)
5216
+ return block
5217
+
5218
+
5219
+ def onboard_links(root, d):
5220
+ return [x for x in d.get("files", []) if x.get("type") == "link"]
5221
+
5222
+
5223
+ def cmd_onboard(args):
5224
+ """orch onboard [scan] [--json] | skills [--json] | check | link <folder> <to> | done --mode local|shared [paths]
5225
+ | skip | status."""
5226
+ args = list(args)
5227
+ root = onboard_root() or die("not inside a git repository")
5228
+ sub = args[0] if args and not args[0].startswith("-") else "scan"
5229
+ rest = args[1:] if args and not args[0].startswith("-") else args
5230
+ reg = registry(required=False) or {}
5231
+ if sub == "scan":
5232
+ r = onboard_scan(root, reg)
5233
+ if "--json" in rest:
5234
+ print(json.dumps(r, indent=2))
5235
+ return
5236
+ print("\n".join(onboard_report_lines(r)))
5237
+ print({"full": "NEEDED this project has no skills for its agents: `orch lead onboard` sets it up",
5238
+ "gaps": "NEEDED some things are missing: `orch lead onboard` offers them",
5239
+ "quiet": "OK nothing to set up now"}[r["decide"]])
5240
+ return
5241
+ if sub == "skills":
5242
+ skills = project_skills(root, reg)
5243
+ clashes = clash_skills(skills)
5244
+ if "--json" in rest:
5245
+ print(json.dumps([{**{k: s[k] for k in ("name", "description", "path")}, "clash": s["name"] in clashes}
5246
+ for s in skills], indent=2))
5247
+ return
5248
+ if not skills:
5249
+ print("no project skills (`orch lead onboard` can write some)")
5250
+ for s in skills:
5251
+ print(f"{s['name']} ({s['path']}){' [clashes with orch in a run]' if s['name'] in clashes else ''}: "
5252
+ f"{s['description'][:160]}")
5253
+ return
5254
+ if sub == "check":
5255
+ r = onboard_scan(root, reg)
5256
+ bad = False
5257
+ for k, a in r["agents"].items():
5258
+ if a["twice"]:
5259
+ bad = True
5260
+ print(f"TWICE {k} sees {', '.join(a['twice'])} twice (in two folders it reads)")
5261
+ else:
5262
+ print(f"OK {k} sees {a['sees']} project skill(s), each once")
5263
+ sys.exit(1 if bad else 0)
5264
+ if sub == "link":
5265
+ if len(rest) < 2:
5266
+ die("usage: orch onboard link <folder> <to-folder> e.g. orch onboard link .agents/skills .agent/skills")
5267
+ link, to = rest[0].strip("/"), rest[1].strip("/")
5268
+ lp, tp = root / link, root / to
5269
+ if not tp.is_dir():
5270
+ die(f"{to} is not a folder in this repo")
5271
+ if lp.exists() or lp.is_symlink():
5272
+ die(f"{link} already exists: orch never replaces a folder (put the skills in one of them by hand)")
5273
+ lp.parent.mkdir(parents=True, exist_ok=True)
5274
+ os.symlink(os.path.relpath(tp, lp.parent), lp)
5275
+ twice = {k: a["twice"] for k, a in onboard_scan(root, reg)["agents"].items() if a["twice"]}
5276
+ if twice:
5277
+ lp.unlink()
5278
+ die("not linked: then " + "; ".join(f"{k} would see {', '.join(n)} twice" for k, n in twice.items()))
5279
+ d = onboard_state(root)
5280
+ d.setdefault("files", []).append({"path": link, "type": "link", "to": to})
5281
+ onboard_save(root, d)
5282
+ print(f"LINKED {link} -> {to} (one copy of the skills; no file copied)")
5283
+ return
5284
+ if sub == "skip":
5285
+ d = onboard_state(root)
5286
+ d.update({"status": "skipped", "when": time.strftime("%Y-%m-%d")})
5287
+ onboard_save(root, d)
5288
+ print("SKIPPED project setup: orch won't ask again here (`orch lead onboard` still sets it up by hand)")
5289
+ return
5290
+ if sub == "status":
5291
+ d = onboard_state(root)
5292
+ print(f"{d.get('status') or 'never'}" + (f" {d.get('when')}" if d.get("when") else "")
5293
+ + (f", mode {d['mode']}" if d.get("mode") else ""))
5294
+ for x in d.get("files", []):
5295
+ print(f" {x['path']}" + (f" -> {x['to']}" if x.get("type") == "link" else ""))
5296
+ return
5297
+ if sub == "done":
5298
+ cmd_onboard_done(root, rest)
5299
+ return
5300
+ die("usage: orch onboard [scan|skills|check|link <folder> <to>|done --mode local|shared <paths>|skip|status]")
5301
+
5302
+
5303
+ def cmd_onboard_done(root, args):
5304
+ """Record what onboarding wrote. local: hide each new path with .git/info/exclude. shared: commit them on their own
5305
+ branch (the working folder and the current branch stay as they are), push it and open a PR. Either way a tracked
5306
+ file's orch-onboard block moves to .orchestrate/onboard-notes.md for this run's coders."""
5307
+ args = list(args)
5308
+ mode = None
5309
+ if "--mode" in args:
5310
+ i = args.index("--mode")
5311
+ mode = args[i + 1] if i + 1 < len(args) else None
5312
+ del args[i:i + 2]
5313
+ no_push = "--no-push" in args
5314
+ no_clash = "--no-clash-note" in args
5315
+ paths = [a.strip("/") for a in args if not a.startswith("--")]
5316
+ if mode not in ("local", "shared"):
5317
+ die("usage: orch onboard done --mode local|shared [--no-push] [--no-clash-note] <path>...")
5318
+ d = onboard_state(root)
5319
+ links = [x["path"] for x in onboard_links(root, d)]
5320
+ missing = [p for p in paths if not (root / p).exists() and not (root / p).is_symlink()]
5321
+ if missing:
5322
+ die(f"not found: {', '.join(missing)}")
5323
+ notes, new, changed, marked = [], [], [], []
5324
+ for p in paths:
5325
+ if (root / p).is_file() and is_tracked(root, p):
5326
+ text = (root / p).read_text(errors="replace")
5327
+ if ONBOARD_MARK[0] in text and ONBOARD_MARK[1] in text:
5328
+ marked.append(p)
5329
+ elif mode == "local":
5330
+ die(f"{p} is tracked by git and has no {ONBOARD_MARK[0]} block: orch never changes a tracked file "
5331
+ f"quietly. Put the lines between {ONBOARD_MARK[0]} and {ONBOARD_MARK[1]}.")
5332
+ changed.append(p)
5333
+ elif p not in links:
5334
+ new.append(p)
5335
+ if mode == "local":
5336
+ for p in marked:
5337
+ notes.append((p, take_marked_block(root, p)))
5338
+ pr = None
5339
+ if mode == "local":
5340
+ exclude_add(root, new + links)
5341
+ else:
5342
+ pr = onboard_commit(root, new + changed + links, no_push)
5343
+ for p in changed: # committed on the branch; here the file is as git has it again
5344
+ block = take_marked_block(root, p) if p in marked else None
5345
+ if block:
5346
+ notes.append((p, block))
5347
+ else:
5348
+ git("checkout", "-q", "--", p, cwd=root)
5349
+ exclude_add(root, new + links) # until the PR merges, this run's coders still get them
5350
+ if notes:
5351
+ np = root / ".orchestrate" / ONBOARD_NOTES
5352
+ np.write_text("".join(f"From orch onboard (for {p}):\n{b}\n\n" for p, b in notes))
5353
+ d.update({"status": "done", "when": time.strftime("%Y-%m-%d"), "mode": mode, "clash_note": not no_clash,
5354
+ "files": [x for x in d.get("files", []) if x.get("type") == "link"]
5355
+ + [{"path": p, "type": "file"} for p in new]})
5356
+ if pr:
5357
+ d["branch"] = pr["branch"]
5358
+ onboard_save(root, d)
5359
+ print(f"DONE project setup ({'only on this machine' if mode == 'local' else 'shared with the repo'}): "
5360
+ f"{len(new)} new, {len(links)} link(s)" + (f", notes for {', '.join(p for p, _ in notes)}" if notes else ""))
5361
+ if mode == "local":
5362
+ print(" hidden from git on this machine only (.git/info/exclude); the repo's .gitignore is unchanged")
5363
+ print(" every coder's folder gets them when its milestone starts")
5364
+
5365
+
5366
+ def onboard_commit(root, rels, no_push):
5367
+ """Commit `rels` (as they are in the working folder) on top of HEAD into branch orch/onboard, without switching
5368
+ branch or touching the index: a separate index file. Push it and open a PR when there is an origin."""
5369
+ head = git("rev-parse", "HEAD", cwd=root).stdout.strip()
5370
+ base = git("rev-parse", "--abbrev-ref", "HEAD", cwd=root).stdout.strip()
5371
+ branch, n = ONBOARD_BRANCH, 1
5372
+ while git("rev-parse", "-q", "--verify", f"refs/heads/{branch}", cwd=root, check=False).returncode == 0:
5373
+ n += 1
5374
+ branch = f"{ONBOARD_BRANCH}-{n}"
5375
+ fd, idx = tempfile.mkstemp(prefix="orch-onboard-index-")
5376
+ os.close(fd)
5377
+ env = {**os.environ, "GIT_INDEX_FILE": idx}
5378
+ try:
5379
+ subprocess.run(["git", "read-tree", head], cwd=root, env=env, check=True, capture_output=True)
5380
+ subprocess.run(["git", "add", "-f", "--", *rels], cwd=root, env=env, check=True, capture_output=True)
5381
+ tree = subprocess.run(["git", "write-tree"], cwd=root, env=env, check=True, capture_output=True,
5382
+ text=True).stdout.strip()
5383
+ finally:
5384
+ with contextlib.suppress(OSError):
5385
+ os.unlink(idx)
5386
+ msg = "chore: set up agent rules and skills (orch onboard)"
5387
+ commit = git("commit-tree", tree, "-p", head, "-m", msg, cwd=root).stdout.strip()
5388
+ git("update-ref", f"refs/heads/{branch}", commit, cwd=root)
5389
+ print(f"COMMITTED {len(rels)} path(s) on branch {branch} (your branch {base} and folder are unchanged)")
5390
+ if no_push:
5391
+ print(f"NOT PUSHED (--no-push): push {branch} and open a PR into {base} when ready")
5392
+ return {"branch": branch}
5393
+ remote = git("remote", "get-url", "origin", cwd=root, check=False)
5394
+ if remote.returncode != 0:
5395
+ print(f"NO REMOTE: no `origin` remote — merge {branch} into {base} yourself")
5396
+ return {"branch": branch}
5397
+ r = git("push", "-q", "-u", "origin", branch, cwd=root, check=False)
5398
+ if r.returncode != 0:
5399
+ print(f"NOTE push failed: {(r.stdout + r.stderr).strip()} — push {branch} yourself")
5400
+ return {"branch": branch}
5401
+ print(f"PUSHED {branch} to origin")
5402
+ compare = github_compare_url(remote.stdout.strip(), base, branch)
5403
+ if compare and shutil.which("gh"):
5404
+ body = ("Agent rules and skills for this repo, set up by `orch onboard`. Nothing in the app changes.\n\n"
5405
+ + "".join(f"- `{p}`\n" for p in rels))
5406
+ try:
5407
+ g = subprocess.run(["gh", "pr", "create", "--base", base, "--head", branch, "--title", msg, "--body", body],
5408
+ cwd=root, text=True, capture_output=True, timeout=120)
5409
+ except (OSError, subprocess.TimeoutExpired) as e:
5410
+ g = subprocess.CompletedProcess([], 1, "", str(e))
5411
+ if g.returncode == 0:
5412
+ print(f"PR {g.stdout.strip().splitlines()[-1] if g.stdout.strip() else 'created'}")
5413
+ return {"branch": branch}
5414
+ print(f"NOTE gh pr create failed: {(g.stdout + g.stderr).strip()}")
5415
+ print(f"OPEN A PR from {branch} into {base}" + (f": {compare}" if compare else ""))
5416
+ return {"branch": branch}
5417
+
5418
+
5419
+ def onboard_overlay(dest):
5420
+ """Put what onboarding kept on this machine into a coder's folder: a link to each new file or skill (git can't
5421
+ carry them, they are hidden from it), and the same folder links. Paths that already exist there are left alone."""
5422
+ if ROOT is None or Path(dest).resolve() == Path(ROOT).resolve():
5423
+ return []
5424
+ d = onboard_state(ROOT)
5425
+ if d.get("status") != "done":
5426
+ return []
5427
+ made = []
5428
+ for x in d.get("files", []):
5429
+ rel = x["path"]
5430
+ dst = Path(dest) / rel
5431
+ if dst.exists() or dst.is_symlink():
5432
+ continue
5433
+ if x.get("type") == "link":
5434
+ target = os.readlink(ROOT / rel) if (ROOT / rel).is_symlink() else None
5435
+ if not target:
5436
+ continue
5437
+ else:
5438
+ src = ROOT / rel
5439
+ if not src.exists():
5440
+ continue
5441
+ target = str(src)
5442
+ with contextlib.suppress(OSError):
5443
+ dst.parent.mkdir(parents=True, exist_ok=True)
5444
+ os.symlink(target, dst)
5445
+ made.append(rel)
5446
+ return made
5447
+
5448
+
5449
+ def plan_skills(section):
5450
+ """The skill names a milestone's `Skills:` line gives (`Skills: supabase-changes, test-driven-development`)."""
5451
+ _, tasks = parse_plan(section)
5452
+ vals = tasks[0]["fields"].get("skills", []) if tasks else []
5453
+ names = [w.strip(" `*-") for v in vals for w in re.split(r"[,;]", v)]
5454
+ return [w for w in names if w and w.lower() not in ("none", "n/a")]
5455
+
5456
+
5457
+ def task_skill_lines(section):
5458
+ """The task file's skills blocks: the skills the plan gave this milestone (`Skills:`), and the skills the coder
5459
+ must not use in a run because orch does their job."""
5460
+ root = ROOT
5461
+ reg = registry(required=False) or {}
5462
+ skills = project_skills(root, reg)
5463
+ by_name = {s["name"]: s for s in skills}
5464
+ want = plan_skills(section)
5465
+ out = []
5466
+ if want:
5467
+ out += ["## Skills for this step", "Use these skills while you work on this task (your tool lists them):"]
5468
+ for w in want:
5469
+ s = by_name.get(w)
5470
+ out.append(f"- {w}" + (f" ({s['path']}): {s['description'][:200]}" if s else " (not found in this repo)"))
5471
+ out.append("")
5472
+ clashes = clash_skills(skills)
5473
+ if clashes and onboard_state(root).get("clash_note", True):
5474
+ out += ["## Skills orch does for you",
5475
+ "orch handles your folder, the branch, merging and splitting the work. In this task don't use:"]
5476
+ out += [f"- {n}: {why}" for n, why in clashes.items()]
5477
+ out.append("")
5478
+ np = root / ".orchestrate" / ONBOARD_NOTES
5479
+ if np.is_file() and np.read_text(errors="replace").strip():
5480
+ out += ["## Project notes (orch onboard)", np.read_text(errors="replace").strip(), ""]
5481
+ return out, want
5482
+
5483
+
4392
5484
  WORKER_RULES = """## Rules for you (the coder)
4393
5485
  - You own the HOW: the approach, the design inside this milestone, the code, the tests and every fix. This file says what and why; it deliberately doesn't say how.
4394
5486
  - Follow the repo's existing patterns (AGENTS.md / CLAUDE.md) and any Interfaces listed above exactly; other milestones rely on them.
@@ -4396,7 +5488,7 @@ WORKER_RULES = """## Rules for you (the coder)
4396
5488
  - Do NOT commit, push, or switch branches. orch commits your work for you.
4397
5489
  - Never push to main (or master, or the repo's default branch) and never merge a PR, in any situation, even when the developer or the lead asks you to. Say no and offer the run's branch and a PR instead; a person merges by hand. The repo's pre-push guard refuses such a push anyway: never get around it (no `--no-verify`, no editing or deleting `.git/hooks`).
4398
5490
  - Stay inside the files listed under Likely files (`files_allowed` in task.json) unless the task can't be done otherwise; say why in your report if you leave them. orch compares your diff with that list.
4399
- - Finish with a result file (the prompt names it) in the `result_format` shape from task.json: `status` done / question / blocked, `commit`, `files_changed`, the `check` you ran, one entry per acceptance criterion (`id`, `met`, `evidence`), and `usage` if your tool shows tokens or cost. orch reads it, so keep it valid JSON.
5491
+ - Finish with a result file (the prompt names it) in the `result_format` shape from task.json: `status` done / question / blocked, `commit`, `files_changed`, the `check` you ran, and one entry per acceptance criterion (`id`, `met`, `evidence`). orch reads it, so keep it valid JSON.
4400
5492
  - The commit message (`commit` in the result, and the last report line `COMMIT: <commit message>`) says what changed, in the repo's commit style (for example `feat(api): add categories endpoint`). It becomes the commit message, so describe the change, not the milestone.
4401
5493
  - If anything is ambiguous, do not guess: set status `question`, put the question in `questions` and on a report line starting `QUESTION:`, finish the files and the done file, and stop.
4402
5494
  - If an acceptance criterion can't be met in this repo (it needs an outside API, service or account that doesn't exist), don't keep trying: ask (status `question`), name the criterion and why, and offer to build the rest. A criterion marked DEFERRED above was approved to stay undone: don't build it, and report it `met: false`.
@@ -4405,7 +5497,7 @@ WORKER_RULES = """## Rules for you (the coder)
4405
5497
 
4406
5498
 
4407
5499
  # plan.md lines that are for the lead and orch, not the coder: they stay in plan.md and task.json
4408
- LEAD_ONLY_FIELDS = {"depends on", "why separate", "prefer", "model", "tier", "needs", "model why", "estimate", "role", "door",
5500
+ LEAD_ONLY_FIELDS = {"depends on", "why separate", "prefer", "model", "tier", "needs", "model why", "estimate", "role", "door", "skills",
4409
5501
  "review", "parallel", "plain", "side", "repo"}
4410
5502
 
4411
5503
 
@@ -4449,6 +5541,10 @@ def cmd_write_task(args):
4449
5541
  parts += ["## Global instructions", glob, ""]
4450
5542
  rules = project_rules(st, secs[tid] + "\n" + (glob or ""))
4451
5543
  parts += project_rules_lines(st, rules)
5544
+ skill_lines, skill_names = task_skill_lines(secs[tid])
5545
+ parts += skill_lines
5546
+ if skill_names:
5547
+ contract["skills"] = skill_names
4452
5548
  if t.get("door") == "one-way":
4453
5549
  parts += ["## Hard to undo: show proof",
4454
5550
  "This milestone is hard to undo once it runs" + (f" ({t['door_why']})" if t.get("door_why") else "")
@@ -6229,6 +7325,22 @@ def _autopilot(args):
6229
7325
  return s_["workers"].get(name) if name in s_.get("workers", {}) else \
6230
7326
  (s_.get("reviewer_info") if name == s_.get("reviewer") else None)
6231
7327
 
7328
+ tok_tick = [0.0]
7329
+
7330
+ def tend_tokens():
7331
+ """Read the tokens of jobs that finished (each tool's own log, read only) soon after they end, so the numbers
7332
+ are saved in state.json before the tool may delete its old logs. At most every 30s, only when a job waits."""
7333
+ if time.time() - tok_tick[0] < 30:
7334
+ return
7335
+ tok_tick[0] = time.time()
7336
+ st_ = load()
7337
+ if any("tokens" not in a and a.get("tok_marker") and now() - a.get("end", 0) >= TOKEN_GRACE_S
7338
+ for t in st_["tasks"].values() for a in t.get("attempts") or []):
7339
+ try:
7340
+ patch_state(lambda s_: token_fill(s_))
7341
+ except Exception as e: # a strange log must never stop the run
7342
+ say(f"token count skipped this time: {e}")
7343
+
6232
7344
  def tend_compacts():
6233
7345
  """Coders and the reviewer whose milestone landed get their tool's compact command while they are idle and
6234
7346
  hold no job; one that is compacting is free again once herdr shows it idle (or after COMPACT_MAX_S)."""
@@ -6497,6 +7609,7 @@ def _autopilot(args):
6497
7609
  watch_herdr()
6498
7610
  tend_stops()
6499
7611
  tend_compacts()
7612
+ tend_tokens()
6500
7613
  # 0. budget: driving time adds up across restarts (time spent only waiting for an answer doesn't count)
6501
7614
  el, last_tick = time.time() - last_tick, time.time()
6502
7615
  asleep = slept()
@@ -6561,8 +7674,14 @@ def _autopilot(args):
6561
7674
  sugg += [f"- {k}: {s}" for s in review_findings(k, rnd)[1]]
6562
7675
  if v.get("out_of_scope"):
6563
7676
  scope.append(f"- {k}: {', '.join(v['out_of_scope'])}")
6564
- _, report = run("report", "--no-time", ok=(0, 1, 2))
7677
+ _, report = run("report", "--no-time", "--no-tokens", ok=(0, 1, 2))
6565
7678
  timing = "\n".join(time_lines(time_account(load())))
7679
+ try:
7680
+ patch_state(lambda s_: token_fill(s_, force=True))
7681
+ tokens_md = "\n".join(token_lines(token_account(load())))
7682
+ except Exception as e: # a strange log must never stop the summary
7683
+ tokens_md = f"not available ({e})"
7684
+ patch_state(lambda s_: s_["run"].update(lead_tokens=lead_tokens(s_)) if s_.get("lead") else None)
6566
7685
  models = []
6567
7686
  for k, v in tasks.items():
6568
7687
  used = [a for a in v.get("attempts") or [] if a.get("kind") == "coder" and a.get("model")]
@@ -6590,6 +7709,7 @@ def _autopilot(args):
6590
7709
  + ("## Models: planned and actual\n| Milestone | Planned tier | Ran on | Escalated | Why this tier |\n"
6591
7710
  "|---|---|---|---|---|\n" + "\n".join(models) + "\n\n" if models else "") +
6592
7711
  f"## Time: estimate vs actual\n{timing}\n\n"
7712
+ f"## Tokens: per milestone\n{tokens_md}\n\n"
6593
7713
  f"## Waiting: time milestones sat still\nA finished or ready milestone that waited for something else "
6594
7714
  f"first (counted in the times above).\n{wait_table(tasks)}\n\n"
6595
7715
  f"## Checked automatically\nAlready verified by the run; nobody needs to redo these by hand.\n"
@@ -6717,7 +7837,7 @@ def run_report(st):
6717
7837
  """Numbers for one run, from what orch recorded (attempts, checks, rounds). No guesses: unknown stays unknown."""
6718
7838
  rows, tot = [], {"tasks": 0, "merged": 0, "failed": 0, "first_pass": 0, "reviewed": 0, "re_reviewed": 0,
6719
7839
  "conflicts": 0, "lost": 0, "fix_rounds": 0, "agent_s": 0, "wasted_s": 0, "check_s": 0,
6720
- "input_tokens": 0, "output_tokens": 0, "cost_usd": 0.0, "usage_known": 0}
7840
+ }
6721
7841
  for tid in st["order"]:
6722
7842
  t = st["tasks"][tid]
6723
7843
  if t["status"] == "skipped":
@@ -6729,13 +7849,6 @@ def run_report(st):
6729
7849
  check_s = sum(c.get("secs", 0) for c in t.get("checks") or [])
6730
7850
  first = (t["status"] == "merged" and t.get("fix", 0) == 0 and t.get("review_round", 0) <= 1
6731
7851
  and not t.get("conflicts") and len([a for a in coder if a.get("outcome") == "done"]) <= 1)
6732
- for a in at:
6733
- u = a.get("usage") or {}
6734
- if u:
6735
- tot["usage_known"] += 1
6736
- for k in ("input_tokens", "output_tokens", "cost_usd"):
6737
- if isinstance(u.get(k), (int, float)):
6738
- tot[k] += u[k]
6739
7852
  rows.append({"task": tid, "status": t["status"], "attempts": len(coder), "fix_rounds": t.get("fix", 0),
6740
7853
  "review_rounds": t.get("review_round", 0), "conflicts": t.get("conflicts", 0),
6741
7854
  "lost": t.get("lost", 0), "agent_s": agent_s, "wasted_s": wasted, "check_s": check_s,
@@ -7015,14 +8128,27 @@ def time_lines(acct):
7015
8128
  return out
7016
8129
 
7017
8130
 
8131
+ def cmd_tokens(args):
8132
+ """orch tokens [--json] -> tokens per milestone, read from each agent's own session log (read only)."""
8133
+ token_fill_saved()
8134
+ acct = token_account(load())
8135
+ if "--json" in args:
8136
+ print(json.dumps(acct, indent=2))
8137
+ return
8138
+ print("\n".join(token_lines(acct)))
8139
+
8140
+
7018
8141
  def cmd_report(args):
7019
- """orch report [--json] [--no-time] -> estimated vs actual time (and why it took longer), rounds, first-pass
7020
- rate and wasted work for this run."""
8142
+ """orch report [--json] [--no-time] [--no-tokens] -> estimated vs actual time (and why it took longer), tokens
8143
+ per milestone, rounds, first-pass rate and wasted work for this run."""
8144
+ if "--no-tokens" not in args or "--json" in args:
8145
+ token_fill_saved()
7021
8146
  st = load()
7022
8147
  rep_ = run_report(st)
7023
8148
  by_axis, rules_broken = review_axes(st)
7024
8149
  if "--json" in args:
7025
8150
  rep_["time"] = time_account(st)
8151
+ rep_["tokens"] = token_account(st)
7026
8152
  rep_["review_axes"] = {"spec": len(by_axis["spec"]), "rules": len(by_axis["rules"]), "rules_broken": rules_broken}
7027
8153
  rep_["risk"] = [{"task": k, "door": v.get("door") or "two-way", "door_why": v.get("door_why"),
7028
8154
  "blast": v.get("blast"), "proof": v.get("proof")}
@@ -7031,6 +8157,8 @@ def cmd_report(args):
7031
8157
  return
7032
8158
  if "--no-time" not in args:
7033
8159
  print("Estimate vs actual\n" + "\n".join(time_lines(time_account(st))) + "\n")
8160
+ if "--no-tokens" not in args:
8161
+ print("Tokens per milestone\n" + "\n".join(token_lines(token_account(st))) + "\n")
7034
8162
  tot = rep_["totals"]
7035
8163
  print(f"{'task':<5} {'status':<15} {'tries':>5} {'fix':>4} {'review':>6} {'confl':>5} {'lost':>4} "
7036
8164
  f"{'agent time':>10} {'wasted':>8} {'checks':>8} first pass")
@@ -7051,11 +8179,6 @@ def cmd_report(args):
7051
8179
  f"{m['first_pass']:>10} {m['escalated_away']:>8} {_fmt_secs(m['agent_s']):>10}")
7052
8180
  print("(moved up = milestones this model could not finish, escalated to a stronger one; compare with "
7053
8181
  "`orch models`)")
7054
- if tot["usage_known"]:
7055
- print(f"usage reported by agents on {tot['usage_known']} attempt(s): {tot['input_tokens']} input tokens, "
7056
- f"{tot['output_tokens']} output tokens, ${tot['cost_usd']:.2f}")
7057
- else:
7058
- print("tokens/cost: unknown (no agent reported `usage` in its result file)")
7059
8182
  if "--no-time" in args: # the summary (its only caller) has its own sections for the lines below
7060
8183
  return
7061
8184
  rows = risk_rows(st)
@@ -7589,6 +8712,16 @@ VIEW_WORDS = {"pending": "waiting", "coding": "building", "needs-fix": "fix roun
7589
8712
  VIEW_PORT = int(os.environ.get("ORCH_VIEW_PORT", "47231"))
7590
8713
 
7591
8714
 
8715
+ def _tok_view(r):
8716
+ """One milestone's tokens for the board and the browser view (None: no job sent yet)."""
8717
+ if not r or not (r["coder"] or r["review"]):
8718
+ return None
8719
+ part = {p: (None if not r[p] else {"total": r[p]["in"] + r[p]["out"], "in": r[p]["in"], "cached": r[p]["cached"],
8720
+ "out": r[p]["out"], "known": r[p]["known"], "jobs": r[p]["jobs"],
8721
+ "na": r[p]["na"][:1]}) for p in ("coder", "review")}
8722
+ return {"total": r["total"], "partial": r["partial"], **part}
8723
+
8724
+
7592
8725
  def _usage_sum(rows):
7593
8726
  tok = cost = 0
7594
8727
  known = False
@@ -7688,6 +8821,11 @@ def view_model(st=None, recent=40):
7688
8821
  "notices": run_notices(None)}
7689
8822
  tasks, t_now = st.get("tasks", {}), now()
7690
8823
  ms, by_model = [], {}
8824
+ try:
8825
+ tacct = token_account(st, live=True)
8826
+ except Exception:
8827
+ tacct = {"tasks": [], "lead": None, "total": 0, "partial": False}
8828
+ trow = {r["task"]: r for r in tacct["tasks"]}
7691
8829
  for tid in st.get("order", []):
7692
8830
  t = tasks.get(tid) or {}
7693
8831
  w = t.get("wait") or {}
@@ -7711,6 +8849,7 @@ def view_model(st=None, recent=40):
7711
8849
  "estimate_s": t.get("estimate_s"), "started": (w.get("started") or w.get("since")) if cur else None,
7712
8850
  "spent_s": int(sum(a.get("secs", 0) for a in atts) + cur),
7713
8851
  "usage": _usage_sum([a.get("usage") for a in atts if a.get("usage")]),
8852
+ "tokens": _tok_view(trow.get(tid)),
7714
8853
  "attempts": [{"kind": a.get("kind"), "agent": a.get("agent"), "model": a.get("model"),
7715
8854
  "tier": a.get("tier"), "secs": a.get("secs"), "outcome": a.get("outcome")}
7716
8855
  for a in atts[-12:]],
@@ -7751,6 +8890,11 @@ def view_model(st=None, recent=40):
7751
8890
  "active": len([g for g in groups if g in ("building", "checking", "review", "landing")]),
7752
8891
  "waiting": groups.count("waiting")},
7753
8892
  "time": {"driven_s": int(run.get("driven_s", 0)), "estimate_s": st.get("estimate_s")},
8893
+ "tokens": {"total": tacct["total"], "partial": tacct["partial"],
8894
+ "lead": None if not tacct["lead"] else
8895
+ {"na": tacct["lead"]["na"]} if "na" in tacct["lead"] else
8896
+ {"total": tacct["lead"]["in"] + tacct["lead"]["out"], "in": tacct["lead"]["in"],
8897
+ "cached": tacct["lead"]["cached"], "out": tacct["lead"]["out"]}},
7754
8898
  "usage": {"total": _usage_sum([u for v in by_model.values() for u in v]),
7755
8899
  "by_model": {k: _usage_sum(v) for k, v in by_model.items()}},
7756
8900
  "milestones": ms, "agents": agents,
@@ -8568,9 +9712,12 @@ def render_board(vm, width=100, color=True, sel=None, note=""):
8568
9712
  + (" · " + c("r", f"{cn['needs_you']} needs you") if cn["needs_you"] else "")
8569
9713
  + c("d", f" · {_fmt_min(vm['time']['driven_s'])} so far"
8570
9714
  + (f" of ~{_fmt_min(vm['time']['estimate_s'])}" if vm["time"].get("estimate_s") else ""))]
8571
- u = (vm.get("usage") or {}).get("total")
8572
- if u:
8573
- out.append(c("d", f"tokens {u['tokens'] / 1e6:.1f}M · cost ~${u['cost_usd']:.2f}"))
9715
+ tk = vm.get("tokens") or {}
9716
+ if tk.get("total") or tk.get("lead"):
9717
+ ld = tk.get("lead") or {}
9718
+ out.append(c("d", f"tokens {_tk(tk.get('total'))}{'+' if tk.get('partial') else ''} so far"
9719
+ + (f" · lead {_tk(ld['total'])}" if ld.get("total") else
9720
+ " · lead: not available" if ld.get("na") else "")))
8574
9721
  if vm.get("all_done"):
8575
9722
  out.append(c("g", "ALL DONE — `orch finish` pushes the branch and opens the PR"))
8576
9723
  out += notes
@@ -8586,6 +9733,10 @@ def render_board(vm, width=100, color=True, sel=None, note=""):
8586
9733
  who = m.get("worker") or ""
8587
9734
  extra = (f"{_fmt_min(m['spent_s'])} of ~{_fmt_min(m['estimate_s'])}" if m.get("started")
8588
9735
  and m.get("estimate_s") else f"{_fmt_min(m['spent_s'])}" if m["spent_s"] else "")
9736
+ mt = m.get("tokens")
9737
+ if mt:
9738
+ extra += (" " if extra else "") + (f"{_tk(mt['total'])}{'+' if mt['partial'] else ''} tok"
9739
+ if mt["total"] else "tokens n/a")
8589
9740
  if g == "waiting" and m["deps"]:
8590
9741
  word = "waits for " + ",".join(d for d in m["deps"] if ms.get(d, {}).get("group") != "landed") \
8591
9742
  if any(ms.get(d, {}).get("group") != "landed" for d in m["deps"]) else "ready"
@@ -8968,14 +10119,15 @@ COMMANDS = {
8968
10119
  "write-task": cmd_write_task, "nudge": cmd_nudge, "autopilot": cmd_autopilot,
8969
10120
  "send-job": cmd_send_job, "handoff": cmd_handoff, "needs-fix": cmd_needs_fix, "review-ok": cmd_review_ok,
8970
10121
  "requeue-review": cmd_requeue_review, "finish": cmd_finish, "resend": cmd_resend, "approve": cmd_approve,
8971
- "report": cmd_report, "events": cmd_events, "dispatch": cmd_dispatch, "answer": cmd_answer, "defer": cmd_defer,
10122
+ "report": cmd_report, "tokens": cmd_tokens, "events": cmd_events, "dispatch": cmd_dispatch, "answer": cmd_answer, "defer": cmd_defer,
8972
10123
  "escalate": cmd_escalate, "fix": cmd_fix, "plan": cmd_plan, "story": cmd_story, "manual": cmd_manual, "team": cmd_team, "bench": cmd_bench, "stop": cmd_stop,
8973
10124
  "free": cmd_free, "doctor": lambda a: cmd_doctor_crash(a), "check": lambda a: cmd_check(a), "sub": lambda a: cmd_sub(a),
8974
10125
  "view": lambda a: cmd_view(a), "board": lambda a: cmd_board(a), "changes": lambda a: cmd_changes(a),
10126
+ "onboard": lambda a: cmd_onboard(a),
8975
10127
  }
8976
10128
  # they lock per step instead of for the whole command (long-running, or they start the event manager after)
8977
10129
  UNLOCKED = {"manual", "autopilot", "poll", "merge", "events", "dispatch", "answer", "defer", "fix", "team", "resume", "bench", "stop",
8978
- "doctor", "check", "free", "view", "board", "changes"}
10130
+ "doctor", "check", "free", "view", "board", "changes", "onboard"}
8979
10131
 
8980
10132
  USAGE = """usage: orch <command> [args]
8981
10133
  version print the installed herdr-orchestra version
@@ -8986,6 +10138,17 @@ USAGE = """usage: orch <command> [args]
8986
10138
  lead plan|run print the lead playbook (any agent can lead: "Run `orch lead plan` and follow it")
8987
10139
  lead plan quick|full the rest of the plan playbook: a quick run's rules, or steps 3-10 of the full process
8988
10140
  lead run --section <EVENT|ALL_DONE|rules> one part of the run playbook (orch events prints these for you)
10141
+ lead onboard the setup playbook: set this project up for its agents (rules, skills) with the
10142
+ developer's tick; `orch lead plan` points the lead to it when a project needs it
10143
+ onboard [--json] what the project has for its agents: stack, commands, rule files, the skills each
10144
+ installed agent sees, and what is missing (no AI, changes nothing)
10145
+ onboard skills|check|status the project's skills (for a milestone's `Skills:`) / skills an agent sees twice /
10146
+ what setup did here
10147
+ onboard link <folder> <to> one folder link so another agent sees the same skills (.agents/skills -> .agent/skills)
10148
+ onboard done --mode local|shared [--no-push] [--no-clash-note] <path>... record the setup: local hides the
10149
+ files from git on this machine only (.git/info/exclude); shared commits them on branch
10150
+ orch/onboard and opens a PR. Coders' folders get them either way
10151
+ onboard skip don't offer project setup here again
8989
10152
  lead check preflight: is this agent in a Herdr pane / can it reach herdr?
8990
10153
  lead whoami show the lead's own herdr pane and name it as the plan's `Lead:` (default `lead`)
8991
10154
  team <kind> [--coders N] [--models a,b] [--no-reviewer] [--prefix <name>]
@@ -9024,7 +10187,7 @@ USAGE = """usage: orch <command> [args]
9024
10187
  rounds or escalation for them; the summary lists them as NOT done, with a follow-up
9025
10188
  fix <Mn> <text> [--to <worker>] a change to something Mn already landed: a small follow-up milestone, sent
9026
10189
  straight to the coder who built Mn (no new plan; check, review and summary still apply)
9027
- agents sync [kind...] install the orch-plan / orch-run / orch-explain skills so every installed agent sees each one exactly once,
10190
+ agents sync [kind...] install the orch-plan / orch-run / orch-explain / orch-onboard skills so every installed agent sees each one exactly once,
9028
10191
  and remove old copies (run it after adding a new agent; the installer runs it)
9029
10192
  agents check check every installed agent sees each orch skill once (not missing, not twice)
9030
10193
  guard [status|--print] install the pre-push guard: no agent ever pushes to main/master/the default branch
@@ -9045,7 +10208,10 @@ USAGE = """usage: orch <command> [args]
9045
10208
  [f] or [enter] on a milestone shows its changed files, [enter] on a file its diff
9046
10209
  changes [Mn [file]] [--json] what each milestone changed: files with +/- counts, or one file's diff
9047
10210
  (live while a coder works, unsaved files included; landed = its commit). Read-only
9048
- report [--json] estimate vs actual time (why longer, who), rounds, first-pass rate, wasted work, tokens/cost
10211
+ report [--json] [--no-tokens] estimate vs actual time (why longer, who), tokens per milestone, rounds,
10212
+ first-pass rate, wasted work
10213
+ tokens [--json] tokens per milestone (coder, review, fix rounds), the lead and the total, read from each
10214
+ agent's own log (Claude Code, Codex, Pi, agy); "not available" when a log has none
9049
10215
  ready free coder slots, FIX jobs (do these first), then READY milestones
9050
10216
  pick <Mn> first available worker for the task (respects Tier, then Prefer), or NONE (exit 3)
9051
10217
  escalate <Mn> [reason] out of rounds: one more go on a stronger model, if the team has one (exit 3 if not)
@@ -9348,10 +10514,23 @@ def cmd_lead(args):
9348
10514
  guard_ensure(say_changes=False) # no agent pushes to main: the repo refuses it from the start
9349
10515
  if sub == "plan" and not part:
9350
10516
  print(picker_note(lead_kind()), end="")
10517
+ print(onboard_plan_note(), end="") # a project never set up for its agents: set it up first
9351
10518
  if subagent and sub == "plan":
9352
10519
  print(SUBAGENT_PLAN_NOTE, end="")
9353
10520
  print(plan_playbook_part(pb.read_text(), part) if sub == "plan" else pb.read_text(), end="")
9354
10521
  return
10522
+ if sub == "onboard":
10523
+ pb = asset("playbooks/onboard.md") or die("playbooks/onboard.md not found next to orch or in the install")
10524
+ root = onboard_root() or die("not inside a git repository: run it in the repo to set up")
10525
+ if find_workspace(Path.cwd()) is not None:
10526
+ die("this folder is a workspace of several repos: run `orch lead onboard` inside each repo")
10527
+ r = onboard_scan(root)
10528
+ print(f"herdr-orchestra {installed_version()} — lead playbook: onboard\n")
10529
+ print(picker_note(lead_kind()), end="")
10530
+ print("WHAT ORCH FOUND (`orch onboard --json` has all of it):")
10531
+ print("\n".join(" " + l for l in onboard_report_lines(r)) + "\n")
10532
+ print(pb.read_text(), end="")
10533
+ return
9355
10534
  if sub == "check":
9356
10535
  lead_check()
9357
10536
  return
@@ -9383,7 +10562,7 @@ def cmd_lead(args):
9383
10562
  print(f"This pane is YOU (the lead). Name it: herdr agent rename {pid or '<pane id>'} {name}")
9384
10563
  print(f"Write `Lead: {name} (<your kind>)` in the plan header, and never prompt this pane.")
9385
10564
  return
9386
- die("usage: orch lead plan | run | check | whoami")
10565
+ die("usage: orch lead plan | run | onboard | check | whoami")
9387
10566
 
9388
10567
 
9389
10568
  def manifest_path():
@@ -9702,7 +10881,7 @@ def cmd_agents(args):
9702
10881
  missing = [k for k, v in reg.items()
9703
10882
  if installed[k] and any(st != "ok" for _, st in agent_assets(v))]
9704
10883
  if missing:
9705
- print(f"\n{', '.join(missing)}: orch skills (orch-plan/orch-run/orch-explain) missing or listed twice — run: orch agents sync")
10884
+ print(f"\n{', '.join(missing)}: orch skills (orch-plan/orch-run/orch-explain/orch-onboard) missing or listed twice — run: orch agents sync")
9706
10885
  print(f"\nOverride or add kinds in {user_agents_file()}")
9707
10886
 
9708
10887
 
@@ -11027,6 +12206,8 @@ def workspace_main(ws, cmd, args):
11027
12206
  print(f"== {name} ({paths[name]})")
11028
12207
  sys.stdout.flush()
11029
12208
  return subprocess.run(me + [cmd, *a], cwd=paths[name]).returncode
12209
+ if cmd == "onboard":
12210
+ die(f"project setup is per repo: run `orch onboard` inside each repo ({', '.join(paths.values())})")
11030
12211
  if cmd in ("view", "board"):
11031
12212
  die(f"`orch {cmd}` shows one repo's run: run it inside one of the repos ({', '.join(paths.values())})")
11032
12213
  if cmd == "sub":