diff --git a/canon/orchestration.md b/canon/orchestration.md new file mode 100644 index 0000000..cede6d0 --- /dev/null +++ b/canon/orchestration.md @@ -0,0 +1,100 @@ +# Orchestration + +Objectives, not tactics. Work out the tactics for the tools and models actually +present; nothing here names one. Read on demand: `sisi delegate guide`. + +## Who owns what + +- The main agent owns the outcome. Delegation never transfers accountability: + it plans, splits, integrates, verifies, and answers for the whole. +- Workers are specialists and critics. Their reports are evidence to judge, + not facts to relay. +- Keep the strongest model's context for judgement: intent, design, trade-offs, + integration, the final call. Raw material belongs in worker reports, judged + and summarised before it reaches the main thread. + +## Delegate, or do it directly + +- Delegate reading, searching, bounded implementation, tests, research, + mechanical change, log triage, and first-pass review. +- Do it directly when delegation costs more than the work: a few lines in a + file already understood, one short command, a question the current context + already answers. +- Watch for drift: several quick direct steps in a row on growing work means + the rest should have been delegated, with what is known so far in the brief. + +## Choosing a worker + +- Give each task to the least expensive worker that is sufficiently capable, + counting rework as cost: cheap work that must be redone is expensive. +- Evidence decides, in this order: the judged record for that kind of task and + difficulty; then price; then benchmark standing. A thin record is a reason + for care, not a verdict. +- Ask `sisi route --kind K --difficulty N` before delegating; `--explain` says + why. Difficulty is 1 routine, 2 ordinary, 3 hard. Say the guess out loud; + the record shows how good the guesses were. +- Use the host's own subagent mechanism first when the worker belongs to the + host; the host's cross-provider delegation when it has one; otherwise + `sisi delegate` through the worker's own command line. +- Spread work instead of draining one allowance; every budget runs out. +- Reviews go to a different maker than the author when one is available. +- About one low-stakes task in ten deliberately tries a cheaper worker with a + thin record, so the record keeps learning. Low-stakes only. +- When the user is waiting, speed can beat the last increment of cheapness. +- Never route work to a tier that trains on its prompts. + +## Parallelism + +- Run independent work in parallel when it shortens the critical path enough + to pay for coordination and integration. Useful parallelism is the goal, + not the number of workers. +- Parallel writers need disjoint files or separate worktrees, clear + boundaries, and an integration point named in advance. +- Measure it: worker minutes against wall time, from the ledger. + +## The brief + +- Every delegation carries a contract: outcome and scope; context and sources + of truth; constraints and interfaces; acceptance; deliverables and report + format; files the worker may change; verification expected; budget and + when to escalate. `sisi delegate brief` prints it; `sisi delegate check` + tests a draft. +- A worker starts cold. Include what is already known and ruled out, the hard + part if there is one, and what done looks like. Most failures are brief + failures: retry once with a better brief before blaming the worker. + +## Judging + +- Judge in proportion to risk: a diff summary for routine work; the tests, + the hunks themselves, or an independent reviewer for anything touching + authorisation, data, money, or public interfaces. +- Record every judgement with `sisi delegate judge`: outcome, the strongest + check actually applied, minutes and tokens where known, and the retry link + when this attempt follows a rejection. Accepted on a light check is + recorded as such; the tables keep the two apart. +- When accepted work later proves wrong, amend it. The record is the + routing policy; an honest record is the whole mechanism. +- Unavailability is temporary and is never a quality judgement: record it + with `sisi workers down`, use the next worker, and try again when due. + A rejected result never marks a worker down. + +## Keeping the picture current + +- What exists, what it costs, and how good it is all change. Discovery is + `sisi workers`; prices and benchmark standing are worker facts, each with + a source and a date, recorded with `sisi workers fact`. +- When facts are missing or stale, hand the research itself to a fast, cheap + worker: find current prices and software-engineering benchmark standing, + then record them. Treat a newly appeared model as unproven: low-stakes + tasks first, checked one level more carefully, until its record is thick. +- Orchestration legwork is delegable like any other legwork: discovery, + price and benchmark research, routing lookups, first-pass review, and + summarising the record can all go to a fast, cheap worker. The judgement + about what to do with the result stays with the main agent. + +## Objective + +All of this serves one objective: the most verified user value per unit of +wall time, cost, and human attention. A choice that saves money by spending +the user's time, or saves time by shipping unverified work, has optimised +the wrong term. diff --git a/docs/workers.md b/docs/workers.md index bc0c23b..a27256b 100644 --- a/docs/workers.md +++ b/docs/workers.md @@ -1,108 +1,74 @@ # Workers: discovery, choice and delegation sisi finds the agent command-line tools on the machine, keeps a judged record of work given to -them, and chooses the most affordable worker that is good enough for each new piece of work. No -list of preferred models is shipped in code, and nothing is scheduled: information refreshes when -a command runs and the stored copy is old, or after a failure. +them, and recommends the most affordable worker that is good enough. No model, price or ranking +ships in the product: everything specific is discovered here, researched into the user store, +or learned from judged results. The strategy is [canon/orchestration.md](../canon/orchestration.md) +(`sisi delegate guide` prints it); this page is the mechanics. ## The commands -- `sisi workers` prints, in plain words, each tool found on `PATH`, the models it lists, whether - it is usable now and why not (not logged in, limit reached until a stated time), the allowance - left where the tool itself reports one, and the price where one is known. A tool with no model - listing command is shown as "models learned by use": the record names its models as they are - used. `sisi workers --refresh` reads the tools again instead of using the stored copy. -- `sisi route --kind K --difficulty N [--review-of W] [--explain]` prints the worker the record - chooses for a kind of task (such as `search`, `impl`, `tests`, `review`) at a difficulty of 1, 2 - or 3. It is plain arithmetic over the record; no model is called. `--explain` also prints why - each other candidate was passed over. `--review-of W` chooses a reviewer from a different maker - than the author `W`, peer review style. +- `sisi workers [--refresh]` — each tool found, the models it lists, whether it is usable now + and why not, allowance and price where known, runs waiting for a judgement, then the judged + record as three tables: by task type and difficulty (attempts, accepted, checked well, later + wrong, median minutes; thin rows marked), what fixed each rejection, and difficulty-guess + calibration. +- `sisi workers fact WORKER --price N|--score N --source S [--date D] [--plan flat|per-use] + [--maker M]` — record a price (per million tokens) or a benchmark standing (0–100), each with + its source and date, in the user store. A fact without a source is refused. +- `sisi workers avoid|prefer PATTERN --why TEXT` — the user's own routing constraints. +- `sisi workers down WORKER --reason limit|auth|missing|error [--until DATE] [--note TEXT]` and + `sisi workers up WORKER` — availability. Without `--until`, the wait widens on repeat failures. +- `sisi workers import FILE` — merge another ledger file into the delegation ledger, idempotently, + printing row counts before and after. The source file is only read. +- `sisi route --kind K --difficulty 1|2|3 [--review-of W] [--explain]` — the recommended worker + and the mechanism to start it with (the host's own subagents, its cross-provider delegation, + or `sisi delegate`). `--explain` says why, briefly, and why the rest were passed over. +- `sisi delegate brief` prints the delegation-contract template (eight parts); + `sisi delegate check FILE` lists the parts a brief lacks. - `sisi delegate --kind K --difficulty N --brief FILE [--worker W] [--review-of W] [--cwd DIR]` - runs the brief unattended on the chosen worker in the given folder, writes the full transcript - to a file under the state folder, and prints only the worker's final report, the transcript path - and the command that records the judgement. -- `sisi delegate judge ID --outcome accepted|rejected --check none|diffstat|tests|read|review - [--minutes N]` records how a run turned out and how strongly it was checked. That judgement is - what later choices learn from. A run nobody judged is listed by `sisi workers` and named at - session start. -- `sisi delegate amend ID` marks a judged result that later proved wrong, so it stops counting as - a success. + runs a brief through the worker's own CLI when the host has no delegation of its own. A brief + lacking outcome, acceptance or the files it may change is refused. +- `sisi delegate judge` is the only way a result enters the ledger: by run id for + `sisi delegate` runs, or directly (`--worker --type --difficulty`) for work run any other way. + It carries outcome, the strongest check applied, minutes, tokens, cost, retry-of, and project, + session and start/end times when known. `sisi delegate amend ID` marks one later proved + wrong; `sisi delegate recent [-n N] [--project P]` lists judgements to find an id. ## How the choice is made -In order: a model whose id contains "contributor" is never chosen, because those tiers train on -prompts. A worker marked unavailable is skipped until its retry time, as is a flat-rate plan whose -allowance is known to be spent. For a review, the author's maker is skipped while another maker -is available. +Candidates are only workers with a judged record, a known price or a benchmark prior; discovered +catalogue models with none of those are listed but never routed to. On a cold start nobody +qualifies: the pick is then a trial among usable workers, `--explain` says so, and asks for the +result to be judged and facts recorded. -A worker counts as proven for a kind and difficulty after enough judged attempts (one threshold -constant in code) with an accepted rate at or above the bar, where accepted means accepted and not -later found wrong. Above the lowest difficulty, proven workers come first. At the lowest -difficulty, workers with a thin record stay in the pool, so low-stakes work is what gathers their -first attempts. A worker with enough attempts and a rate below the bar is passed over while -anything else remains. +In order: a tier that trains on prompts is never chosen; unavailable and allowance-spent workers +are skipped and named; `avoid` patterns remove a worker unless that leaves nobody; a reviewer +comes from a different maker than the author (a stored `maker` fact, else derived from the model +id). Proven workers (enough attempts at or above the accepted-rate bar, not later found wrong) +come first above difficulty 1; proven-bad workers are passed over. Cheapest first within that: +flat-rate allowance before per-use prices, unknown prices last, the benchmark prior ordering a +thin record at equal price, `prefer` patterns first, then load balancing across allowances. +About one difficulty-1 task in ten goes to a cheaper thin-record worker instead, so cheaper +options gather evidence. The choice is deterministic for one fixed record. -Cheapest means: a flat-rate plan with allowance left and no recent failure comes before anything -billed per use, because one more task on it costs nothing extra. Per-use workers order by their -known price. An unknown price is treated as the most expensive of its class until it is learned; -`--explain` says so rather than inventing a number. +## Costs and failures -Work is then spread, not drained: within one price tier and price, the worker that has taken the -least work relative to the allowance it has left goes first. Every delegation is recorded, so the -choice rotates as work is done, yet is deterministic for one fixed record. Ties break on the -worker id. +Tokens and cost are captured where the worker's output reports them, and marked `unavailable` +otherwise; when tokens are known but cost is not, cost is estimated from the price fact and +marked `estimated`. Failure is recognised from output text, never the exit status alone: a +limit, login, missing tool or outage is unavailability with a retry time, the brief falls +through to the next choice, and quality is untouched. Poor work is a rejected judgement, which +never marks a worker down. No approval- or sandbox-switching flag is passed unless the config +allows it per tool (`workers.allow_bypass`). -On a fresh install the record is empty and no prices are known, so every worker is thin and -unpriced: the first usable worker in id order is chosen, with flat-rate allowance winning where a -tool reports it. Each judgement then shapes the next choice. That is the whole bootstrap; there is -no shipped roster to fall back on. +## Stored, and when facts go stale -## Failures that are not bad work - -Some tools report a limit or a missing login with a success exit status, so failure is recognised -from the output text, never from the exit status alone. A limit, login, missing tool or outage is -recorded as unavailability, with a retry time that grows on repeat failures, and the same brief is -tried on the next choice at once. Unavailability never counts against a worker's quality. A worker -that ran and did poor work is a different thing: that is a rejected judgement. - -sisi never passes a flag that switches off a tool's approvals or sandbox unless the config -explicitly allows it for that tool (`workers.allow_bypass`). When a run times out, the message -says it may be stalled on such a decision and names that setting. - -## The main thread - -Hook payloads carry the session's model; sisi keeps it with the session record. Model strength -comes from the judged record where it is thick enough, otherwise from a stored prior table in -which every figure carries its source and date. No ranking ships in code: with no prior and no -record, the strength of a model is stated as unknown. - -At session start, one plain line follows from that: a session whose model is among the strongest -available on the machine is told to plan, delegate with `sisi delegate` and judge; a weaker one is -told to do the work itself, and told once which stronger models are available. A session another -agent started (a subagent, or a worker run by `sisi delegate`) is told nothing about delegating. - -## What is stored, and the seams left open - -In the personal data folder: `workers.json` (discovery, with the time it was read), -`delegations.jsonl` (the ledger: runs, judged attempts, amendments), `worker-availability.json` -(unavailable workers and retry times), and two tables that start empty: - -- `worker-prices.json`: `{"models": {"": {"plan": "flat" or "per-use", - "cost_per_million_tokens": number, "maker": name, "source": text, "date": "YYYY-MM-DD"}}, - "tools": {"": entries of the same shape}}`. -- `model-strength.json`: `{"models": {"": {"score": number from 0 to 100, - "source": text, "date": "YYYY-MM-DD"}}}`. - -A ledger kept by the earlier hand-written orchestrator is imported once, without changing the -original, when its path is named by the `ledger` config key or the `SISI_LEDGER` environment -variable; `sisi workers` reports how many rows came in. - -Settings live under a `workers` key in the config: `refresh_after_s` (how old discovery may get -before a command refreshes it), `timeout_s` (how long one delegated run may take), and -`allow_bypass` (per tool, whether approval- or sandbox-switching flags may be passed; off unless -named). - -Deliberately not built in this slice, with the tables above ready for them: refreshing prices and -published benchmark scores by web research into those tables; using a cheap fast model to classify -tasks, match lessons or draft review plans; a driver for hosts that delegate through their own -interface rather than a command line; and removing the prose orchestrator this replaces. +In the user store: `workers.json` (discovery cache), `delegations.jsonl` (the ledger), +`worker-availability.json`, `worker-prices.json` and `model-strength.json` (worker facts), +`worker-prefs.json` (avoid/prefer). When facts are missing or older than +`workers.facts_max_age_days` (default 30), session start prints one line asking for a fast, +cheap worker to research current prices and benchmark standing and record them — an age check +during normal use, never a scheduler. Settings live under `workers` in the config: +`refresh_after_s`, `timeout_s`, `allow_bypass`, `facts_max_age_days`, `digest_days`, +`host_cross_provider`. diff --git a/sisi/brief.py b/sisi/brief.py new file mode 100644 index 0000000..f7d8900 --- /dev/null +++ b/sisi/brief.py @@ -0,0 +1,116 @@ +"""The delegation contract: what a brief must contain before work is handed to a worker. + +Eight parts. Three of them (outcome, acceptance, the files the worker may change) are +required before `sisi delegate` will run a brief at all; `sisi delegate check` reports +every part a brief lacks. A part counts as present only when its heading is there and +the text under it is more than a placeholder. +""" +import re + +PARTS = [ + ("outcome", "Outcome and scope", ("outcome", "scope", "goal"), True), + ("context", "Context and sources of truth", ("context", "source"), False), + ("constraints", "Constraints and interfaces", ("constraint", "interface"), False), + ("acceptance", "Acceptance", ("acceptance", "accept"), True), + ("deliverables", "Deliverables and report format", ("deliverable", "report"), False), + ("files", "Files you may change", ("files", "may change"), True), + ("verification", "Verification", ("verification", "verify"), False), + ("budget", "Budget and escalation", ("budget", "escalat"), False), +] + +_REQUIRED = {p[0] for p in PARTS if p[3]} +_PLACEHOLDER = re.compile(r"^[\s\[\]().>-]*(\.\.\.|todo|tbd|fill in|replace me)?[\s\[\]().>-]*$", re.I) + + +def template(): + lines = [ + "You are a worker. Do this task yourself; do not delegate it further.", + "", + "## Outcome and scope", + "[The outcome wanted, and what is out of scope.]", + "", + "## Context and sources of truth", + "[What the worker needs to know, and which files or documents are authoritative.]", + "", + "## Constraints and interfaces", + "[What must not change: interfaces, formats, behaviour others depend on.]", + "", + "## Acceptance", + "[How the result will be judged: the check that decides accepted or rejected.]", + "", + "## Deliverables and report format", + "[What to send back, and in what shape: a short report, what changed, the check run.]", + "", + "## Files you may change", + "[The files or folders the worker may change; everything else is read-only.]", + "", + "## Verification", + "[The check the worker must run before reporting, and what output to include.]", + "", + "## Budget and escalation", + "[Time or cost budget; when to stop and escalate instead of guessing.]", + "", + ] + return "\n".join(lines) + + +def _heading_part(line): + text = line.strip().lower().lstrip("#-*> ").rstrip(":").strip() + if not text: + return None + for key, _title, needles, _req in PARTS: + if any(n in text for n in needles): + return key + return None + + +def _filled(lines): + for line in lines: + text = line.strip() + if not text: + continue + if text.startswith("[") and text.endswith("]"): + continue + if _PLACEHOLDER.match(text): + continue + return True + return False + + +_TITLES = {t.lower() for _k, t, _n, _r in PARTS} + + +def _is_heading(line): + stripped = line.strip() + if stripped.startswith("#") or stripped.endswith(":"): + return True + return stripped.lower().lstrip("#-*> ").rstrip(":").strip() in _TITLES + + +def sections(text): + """{part key: [content lines]} for every part heading found in the brief.""" + out = {} + current = None + for line in (text or "").splitlines(): + part = _heading_part(line) if _is_heading(line) else None + if part is not None: + current = part + out.setdefault(current, []) + continue + if current is not None: + out[current].append(line) + return out + + +def missing_parts(text): + """Titles of the parts that are absent or still placeholders, in template order.""" + found = sections(text) + return [title for key, title, _n, _r in PARTS + if key not in found or not _filled(found[key])] + + +def missing_required(text): + """Titles of the parts `sisi delegate` refuses to run without.""" + found = sections(text) + return [title for key, title, _n, _r in PARTS + if key in _REQUIRED and (key not in found or not _filled(found[key]))] diff --git a/sisi/cli.py b/sisi/cli.py index a4e5e7a..b56e6c9 100644 --- a/sisi/cli.py +++ b/sisi/cli.py @@ -86,14 +86,19 @@ A shared rulebook and enforced definitions of done for every AI coding CLI. sisi verifiers doctor | lint which tools are installed; validate the library sisi done [ID] [--trace] recipes: which checks make a kind of work done; --trace also prints where each folded lesson lives in the recipe sisi done for "" best-matching recipe - sisi workers [--refresh] the agent tools and models found here, what is usable now and why not, allowance and price where known, and delegations waiting for a judgement + sisi workers [--refresh] the agent tools and models found here, what is usable now and why not, allowance and price where known, delegations waiting for a judgement, and the judged record as three tables + sisi workers fact W --price N|--score N --source S record a price (per million tokens) or benchmark standing (0-100), with its source and date + sisi workers avoid|prefer PATTERN --why TEXT your own routing constraints, honoured by `sisi route` + sisi workers down W --reason limit|auth|missing|error [--until DATE] | up W mark a worker unavailable / available again + sisi workers import FILE merge another ledger file into the delegation ledger (row counts printed; safe to repeat) sisi route --kind K --difficulty N [--review-of W] [--explain] - the most affordable usable worker for this kind and difficulty, by the judged record alone; --explain says why, and why the rest were passed over + the most affordable usable worker for this kind and difficulty, and the mechanism to start it with (host subagents, host cross-provider delegation, or sisi delegate); --explain says why + sisi delegate brief | check FILE | guide the delegation-contract template (eight parts); which parts a brief lacks; the orchestration playbook sisi delegate --kind K --difficulty N --brief FILE [--worker W] [--review-of W] [--cwd DIR] - run one brief on the chosen worker unattended; prints only its final report, the transcript path, and the judge command + run one brief on the chosen worker unattended; prints only its final report, the transcript path, and the judge command; a brief without outcome, acceptance or files it may change is refused sisi delegate judge ID --outcome accepted|rejected --check none|diffstat|tests|read|review [--minutes N] - record your judgement of a delegation run, so the next choice learns from it - sisi delegate amend ID mark a judged delegation that later proved wrong + record your judgement of a delegation run, so the next choice learns from it; judge work run any other way with --worker W --type K --difficulty N instead of ID + sisi delegate amend ID | recent [-n N] [--project P] mark a judged delegation that later proved wrong; list recent judgements to find an id sisi version | --version print the product version (the VERSION file in the product folder) sisi help this text diff --git a/sisi/routing.py b/sisi/routing.py index 903c874..d56f98b 100644 --- a/sisi/routing.py +++ b/sisi/routing.py @@ -7,8 +7,10 @@ reason (why not usable), and aliases (every spelling the record may use for this The rule, in order: 1. Never a model whose id contains "contributor" (those tiers train on prompts). 2. Never a worker marked unavailable whose retry time is still ahead, nor one whose flat - allowance is known to be spent. - 3. For a review, never the author's maker while another maker is available. + allowance is known to be spent. A user's own `avoid` patterns also remove a worker, unless + that would leave nobody. + 3. For a review, never the author's maker while another maker is available. A stored `maker` + fact wins; otherwise the maker is derived from the model id (see maker_of). 4. Among the rest, a worker is proven for a kind and difficulty with MIN_ATTEMPTS judged attempts and an accepted rate of at least MIN_ACCEPTED_RATE (accepted and not later found wrong). Above difficulty 1, proven workers are preferred; at difficulty 1, workers with a thin record stay in @@ -16,15 +18,21 @@ The rule, in order: below the bar) is passed over whenever anything else remains. 5. Cheapest first: a flat-rate plan with allowance left costs nothing more per task, so it comes before anything billed per use; per-use workers order by their known price; an unknown price is - treated as the most expensive until learned. - 6. Load balancing: within the same price tier and price, the worker that has taken the least work + treated as the most expensive until learned. A stored benchmark prior (`prior_score`) ranks + within the same price, so a thin record is ordered by price and prior, never arbitrarily. + A user's `prefer` patterns put a worker first within the eligible pool. + 6. About one low-stakes task in ten (difficulty 1, every tenth judged attempt for that kind and + difficulty) goes to a cheaper worker with a thin record instead, so cheaper options keep + gathering evidence. The slot is a function of the record, so the choice stays deterministic + for one fixed record. + 7. Load balancing: within the same price tier and price, the worker that has taken the least work relative to its remaining allowance goes first (recorded uses divided by allowance left, an unknown allowance counting as half). Because every delegation is recorded, the choice rotates as work is done, yet stays deterministic for one fixed record. Ties break on the worker id. -On a fresh install the record is empty and no prices are known, so every candidate is thin and -priced unknown: the first in worker-id order among the usable ones is chosen, and each judged -result from then on shapes the next choice. +Candidates reach here already restricted to workers with a judged record, a known price or a +benchmark prior (see workers.routable_candidates); on a cold start none qualifies and every usable +worker is offered, with the explanation saying so. """ import re @@ -32,19 +40,31 @@ MIN_ATTEMPTS = 8 # below this, a worker's record for a kind and difficu MIN_ACCEPTED_RATE = 0.6 # "good enough" among workers with at least MIN_ATTEMPTS attempts UNKNOWN_ALLOWANCE = 50.0 # allowance weight when a tool reports none STRONG_BAND = 10.0 # strength points from the best still counts as among the strongest - -_MAKER_ALIASES = {"haiku": "claude", "sonnet": "claude", "opus": "claude", "fable": "claude"} +EXPLORE_EVERY = 10 # about one low-stakes task in ten tries a cheaper thin-record worker def maker_of(name): - """A best-effort maker from a worker or model id: the first word of the model part. - Stored tables may state a maker explicitly; those win wherever a candidate carries one.""" + """A best-effort maker derived from a worker or model id: the first word of the model part. + A stored `maker` fact wins wherever a candidate carries one; no table of names ships here.""" s = str(name or "").strip().lower() if not s: return "" model = s.rsplit("/", 1)[-1] - token = re.split(r"[-_:. ]", model)[0] or model - return _MAKER_ALIASES.get(token, token) + return re.split(r"[-_:. ]", model)[0] or model + + +def _pattern_match(c, patterns): + """The (pattern, why) a candidate matches, or None. A pattern matches as a substring of the + worker, model or tool name, case aside.""" + hay = " ".join(str(x or "").lower() for x in (c.get("worker"), c.get("model"), c.get("tool"))) + for entry in patterns or []: + if isinstance(entry, dict): + pat, why = str(entry.get("pattern") or ""), str(entry.get("why") or "") + else: + pat, why = str(entry), "" + if pat and pat.lower() in hay: + return pat, why + return None def _alias_map(candidates): @@ -109,9 +129,11 @@ def _cell(stats, worker, kind, difficulty): return stats.get(worker, {}).get("by_cell", {}).get((kind, difficulty), {"n": 0, "good": 0}) -def choose(candidates, records, availability, kind, difficulty, review_of=None, now=0.0, exclude=()): +def choose(candidates, records, availability, kind, difficulty, review_of=None, now=0.0, exclude=(), + avoid=None, prefer=None): """Pick one candidate, or none. Returns {"choice", "passed_over", "stats", "author_maker"}. - `passed_over` is [(worker, plain reason)] covering every candidate not chosen.""" + `passed_over` is [(worker, plain reason)] covering every candidate not chosen. `avoid` and + `prefer` are the user's own [{"pattern", "why"}] constraints.""" now = float(now or 0) exclude = {str(x) for x in exclude} stats = candidate_stats(candidates, records) @@ -138,6 +160,16 @@ def choose(candidates, records, availability, kind, difficulty, review_of=None, continue eligible.append(c) + avoided = [(c, _pattern_match(c, avoid)) for c in eligible] + kept = [c for c, m in avoided if m is None] + if kept: + for c, m in avoided: + if m is not None: + pat, why = m + passed.append((c["worker"], "avoided by the user's own pattern %r%s" + % (pat, (" (%s)" % why) if why else ""))) + eligible = kept + author_maker = "" if review_of: target = str(review_of).lower() @@ -192,19 +224,45 @@ def choose(candidates, records, availability, kind, difficulty, review_of=None, weight = float(left) if left else UNKNOWN_ALLOWANCE return stats.get(c["worker"], {}).get("uses", 0) / max(weight, 1.0) + def prior_key(c): + score = c.get("prior_score") + return -float(score) if isinstance(score, (int, float)) else 1.0 + def key(c): r = rate(c) - return (_price_tier(c), + return (0 if _pattern_match(c, prefer) else 1, + _price_tier(c), float(c["cost"]) if c.get("cost") is not None else float("inf"), + prior_key(c), load_ratio(c), -(r if r is not None else -1.0), c["worker"]) + def price_of(c): + return (_price_tier(c), float(c["cost"]) if c.get("cost") is not None else float("inf")) + pool.sort(key=key) choice = pool[0] if pool else None + explored = None + if choice is not None and difficulty == 1 and not _pattern_match(choice, prefer): + total = sum(_cell(stats, c["worker"], kind, difficulty)["n"] for c in candidates) + if total >= EXPLORE_EVERY and total % EXPLORE_EVERY == EXPLORE_EVERY - 1: + thinner = [c for c in pool + if _cell(stats, c["worker"], kind, difficulty)["n"] < MIN_ATTEMPTS + and price_of(c) < price_of(choice)] + if thinner: + thinner.sort(key=key) + explored, choice = choice, thinner[0] + pool = [choice] + [c for c in pool if c is not choice] if choice is not None: for c in pool[1:]: - if _price_tier(c) > _price_tier(choice) or (c.get("cost") is not None and choice.get("cost") is not None + if explored is not None and c is explored: + reason = ("the usual choice, passed over this once so a cheaper thin-record worker " + "gathers evidence on low-stakes work (about one task in %d)" % EXPLORE_EVERY) + elif _pattern_match(choice, prefer) and not _pattern_match(c, prefer): + _pat, _why = _pattern_match(choice, prefer) + reason = "the choice matches the user's own prefer pattern %r%s" % (_pat, (" (%s)" % _why) if _why else "") + elif _price_tier(c) > _price_tier(choice) or (c.get("cost") is not None and choice.get("cost") is not None and float(c["cost"]) > float(choice["cost"])): reason = "more expensive than the choice (per-use price or unknown price counts as most expensive)" elif load_ratio(c) > load_ratio(choice): @@ -216,6 +274,7 @@ def choose(candidates, records, availability, kind, difficulty, review_of=None, "equal on price and load; the choice came first in worker-id order") passed.append((c["worker"], reason)) return {"choice": choice, "passed_over": passed, "stats": stats, "author_maker": author_maker, + "explored": explored["worker"] if explored else None, "load_ratios": {c["worker"]: load_ratio(c) for c in candidates}} @@ -244,6 +303,13 @@ def explain_choice(result, kind, difficulty): lines.append("chose %s: %s; %s; load so far is %s recorded use(s) against the allowance it has left, " "the lowest in its price tier, so work spreads instead of draining one plan" % (choice["worker"], price, record, result["stats"].get(choice["worker"], {}).get("uses", 0))) + if isinstance(choice.get("prior_score"), (int, float)) and cell["n"] < MIN_ATTEMPTS: + lines.append("its benchmark prior is %g (%s, %s); with a thin record, price and prior decide the order" + % (float(choice["prior_score"]), choice.get("prior_source") or "no source stated", + choice.get("prior_date") or "no date stated")) + if result.get("explored"): + lines.append("this is an exploration pick: %s was the usual choice, passed over once so a cheaper " + "thin-record worker gathers evidence" % result["explored"]) if result.get("author_maker"): lines.append("it is from a different maker than the author (%s)" % result["author_maker"]) groups, order = {}, [] diff --git a/sisi/workers.py b/sisi/workers.py index 32c80c2..49810a4 100644 --- a/sisi/workers.py +++ b/sisi/workers.py @@ -9,25 +9,36 @@ configured age, or after a failure marks it stale. Personal files (all in the personal data folder): workers.json the discovery cache, with the time it was read - delegations.jsonl the ledger: judged attempts, runs awaiting judgement, amendments + delegations.jsonl the ledger: judged attempts, runs awaiting judgement, amendments. + `sisi delegate judge` is the only way a result enters it. worker-availability.json unavailability (limit, login, missing, error) with retry times - worker-prices.json stored prices: {"models": {"": {"plan": "flat"|"per-use", - "cost_per_million_tokens": number, "maker": name, "source": text, - "date": "YYYY-MM-DD"}}, "tools": {"": same shape}} - model-strength.json stored strength prior: {"models": {"": + worker-prices.json worker facts (prices): {"models": {"": + {"plan": "flat"|"per-use", "cost_per_million_tokens": number, + "maker": name, "source": text, "date": "YYYY-MM-DD"}}, + "tools": {"": same shape}}, written by `sisi workers fact` + model-strength.json worker facts (benchmark standing): {"models": {"": {"score": 0..100, "source": text, "date": "YYYY-MM-DD"}}} -The last two start empty and are the seam later research fills in; unknown simply means unknown. + worker-prefs.json the user's own routing constraints: {"avoid": [{"pattern", "why"}], + "prefer": [...]}, written by `sisi workers avoid|prefer` +The fact tables start empty; unknown simply means unknown, and session start asks for them to be +researched when they are missing or old. No price, score or model name ships in the product. """ -import json, os, re, shutil, subprocess, sys, time, uuid +import datetime, json, os, re, shutil, statistics, subprocess, sys, time, uuid +from . import brief as brief_contract from . import paths, routing, store LIST_TIMEOUT_S = 30 DEFAULT_REFRESH_AFTER_S = 24 * 3600 DEFAULT_RUN_TIMEOUT_S = 900 CHECKS = ("none", "diffstat", "tests", "read", "review") +STRONG_CHECKS = ("tests", "read", "review") # a result checked one of these ways was checked well OUTCOMES = ("accepted", "rejected") +REASONS = ("limit", "auth", "missing", "error") EFFORTS = {1: "low", 2: "medium", 3: "high"} +DIGEST_DAYS = 45 # the judged-record tables cover this window; older evidence goes stale +MAX_DIGEST_ROWS = 40 +FACTS_MAX_AGE_DAYS = 30 # older worker facts than this (config: workers.facts_max_age_days) are stale # One small driver per tool. Run templates use tokens expanded by build_command(): # {prompt} the brief text, {model_flag} / {effort_flag} / {cwd_flag} the driver's flag pair (dropped @@ -357,9 +368,27 @@ def _wait_s(reason, fails): return min(24 * 3600 * 2 ** (fails - 1), 7 * 24 * 3600) -def record_down(keys, reason, note=None, now=None, retry_after_s=None): +def _parse_time(value): + """Epoch seconds from a number, an epoch string, or an ISO date/datetime; None if unparsable.""" + if value is None: + return None + if isinstance(value, (int, float)): + return float(value) + text = str(value).strip() + try: + return float(text) + except ValueError: + pass + try: + return datetime.datetime.fromisoformat(text).timestamp() + except ValueError: + return None + + +def record_down(keys, reason, note=None, now=None, retry_after_s=None, until_ts=None): """Record unavailability under one or more keys (a worker, its tool, its plan prefix). - Unavailability is kept apart from judged work: it never counts against quality.""" + Unavailability is kept apart from judged work: it never counts against quality. Without an + explicit `until_ts`, the wait before the next try widens with each repeat failure.""" now = time.time() if now is None else now avail = read_availability() for key in keys: @@ -371,7 +400,10 @@ def record_down(keys, reason, note=None, now=None, retry_after_s=None): entry["reason"] = reason if note: entry["note"] = note - entry["retry_at"] = now + (retry_after_s if retry_after_s else _wait_s(reason, entry["fails"])) + if until_ts is not None: + entry["retry_at"] = float(until_ts) + else: + entry["retry_at"] = now + (retry_after_s if retry_after_s else _wait_s(reason, entry["fails"])) avail[key] = entry write_json(availability_path(), avail) return avail @@ -389,6 +421,55 @@ def clear_down(worker): write_json(availability_path(), keep) +def _row_signature(row): + return json.dumps(row, sort_keys=True, ensure_ascii=False, separators=(",", ":"), default=str) + + +def import_ledger(src, now=None): + """Merge another ledger file into the delegation ledger, losslessly and idempotently. + Returns (rows before, rows after, rows added). The source file is only read. Down/up rows + are replayed into availability, so what was known to be down stays known.""" + now = time.time() if now is None else now + existing = read_records() + before = len(existing) + seen = {_row_signature(r) for r in existing} + seen_attempt_ids = {r.get("id") for r in existing if r.get("kind") == "attempt" and r.get("id")} + added = 0 + new_rows = [] + for row in read_records(src): + if _row_signature(row) in seen: + continue + if row.get("kind") == "attempt" and row.get("id") in seen_attempt_ids: + continue + append_record(dict(row)) + seen.add(_row_signature(row)) + if row.get("kind") == "attempt" and row.get("id"): + seen_attempt_ids.add(row.get("id")) + new_rows.append(row) + added += 1 + avail = read_availability() + changed = False + for row in new_rows: + ts = row.get("ts") if isinstance(row.get("ts"), (int, float)) else now + if row.get("kind") == "down" and row.get("worker"): + key = str(row["worker"]).lower() + e = avail.get(key) or {"since": ts, "fails": 0} + e["fails"] = int(e.get("fails") or 0) + 1 + e["reason"] = row.get("reason") or "error" + if row.get("note"): + e["note"] = row["note"] + until = _parse_time(row.get("until")) + e["retry_at"] = until if until is not None else ts + _wait_s(e["reason"], e["fails"]) + avail[key] = e + changed = True + elif row.get("kind") == "up" and row.get("worker"): + if avail.pop(str(row["worker"]).lower(), None) is not None: + changed = True + if changed: + write_json(availability_path(), avail) + return before, before + added, added + + def ensure_imported(now=None): """Import the previously hand-kept ledger once, losslessly. Returns the row count, or None when there was nothing (more) to import. The original file is only read.""" @@ -405,37 +486,16 @@ def ensure_imported(now=None): return None if os.path.realpath(src) == os.path.realpath(ledger_path()): return None - rows = read_records(src) - existing_ids = {r.get("id") for r in read_records() if r.get("kind") == "attempt"} - count = 0 - for row in rows: - if row.get("kind") == "attempt" and row.get("id") in existing_ids: - continue - append_record(dict(row)) - count += 1 - # Replay its down/up rows, and merge the availability file that sat beside it, so what was - # known to be down stays known. - avail = read_availability() - for row in rows: - ts = row.get("ts") if isinstance(row.get("ts"), (int, float)) else now - if row.get("kind") == "down" and row.get("worker"): - key = str(row["worker"]).lower() - e = avail.get(key) or {"since": ts, "fails": 0} - e["fails"] = int(e.get("fails") or 0) + 1 - e["reason"] = row.get("reason") or "error" - if row.get("note"): - e["note"] = row["note"] - e["retry_at"] = ts + _wait_s(e["reason"], e["fails"]) - avail[key] = e - elif row.get("kind") == "up" and row.get("worker"): - avail.pop(str(row["worker"]).lower(), None) + _before, _after, count = import_ledger(src, now=now) + # Merge the availability file that sat beside the old ledger, so nothing is forgotten. sibling = os.path.join(os.path.dirname(src), "availability.json") if os.path.isfile(sibling): + avail = read_availability() for k, v in read_json(sibling).items(): if isinstance(v, dict): avail[str(k).lower()] = v - if avail: - write_json(availability_path(), avail) + if avail: + write_json(availability_path(), avail) write_json(marker, {"source": src, "rows": count, "ts": now}) return count @@ -496,12 +556,9 @@ def _guess_tool(worker, disc_tools): return t["name"] if head in DRIVER_BY_NAME: return head - if model.startswith("muse-"): - return "muse" - if model.startswith("claude") or routing.maker_of(model) == "claude": - return "claude" - if model.startswith("grok"): - return "grok" + for name in DRIVER_BY_NAME: + if model == name or model.startswith(name + "-") or model.startswith(name + "_"): + return name return None @@ -511,6 +568,7 @@ def build_candidates(disc=None, records=None): disc = discover() if disc is None else disc records = read_records() if records is None else records prices = load_prices() + prior = load_strength_prior() disc_tools = disc.get("tools") or [] cands, seen = [], set() @@ -521,12 +579,17 @@ def build_candidates(disc=None, records=None): seen.add(worker.lower()) price = _price_for(prices, tool, model, worker) cost = price.get("cost_per_million_tokens", price.get("cost")) + prior_entry = next((prior[k] for k in (worker, model) + if k and isinstance(prior.get(k), dict)), {}) + score = prior_entry.get("score") c = {"worker": worker, "tool": tool, "model": model, - "maker": price.get("maker") or routing.maker_of(model or worker), + "maker": price.get("maker") or prior_entry.get("maker") or routing.maker_of(model or worker), "plan": price.get("plan") or tool_plan, "cost": float(cost) if isinstance(cost, (int, float)) else None, "allowance_pct_left": allowance, "usable": usable, "reason": reason, "price_source": price.get("source"), "price_date": price.get("date"), + "prior_score": float(score) if isinstance(score, (int, float)) else None, + "prior_source": prior_entry.get("source"), "prior_date": prior_entry.get("date"), "aliases": [worker, model, ("%s/%s" % (tool, model)) if tool and model else None, tool if model is None else None]} c["aliases"] = [a for a in c["aliases"] if a] @@ -577,6 +640,265 @@ def resolve_worker(name, candidates): return None +# ---------------------------------------------------------------- facts, prefs, digest + + +def prefs_path(): + return _data_file("worker-prefs.json") + + +def load_prefs(): + d = read_json(prefs_path()) + out = {} + for key in ("avoid", "prefer"): + rows = d.get(key) + out[key] = [r for r in rows if isinstance(r, dict) and r.get("pattern")] if isinstance(rows, list) else [] + return out + + +def _fact_dates(): + dates = [] + prices = load_prices() + for table in ("models", "tools"): + rows = prices.get(table) + if isinstance(rows, dict): + for entry in rows.values(): + if isinstance(entry, dict) and entry.get("date"): + dates.append(str(entry["date"])) + for entry in load_strength_prior().values(): + if isinstance(entry, dict) and entry.get("date"): + dates.append(str(entry["date"])) + return sorted(dates) + + +def facts_status(now=None): + """{"state": "missing"|"stale"|"ok", "newest": date or None, "max_age_days": n}. + Missing means no price and no benchmark prior is recorded at all; stale means the newest + recorded fact is older than the configured age (workers.facts_max_age_days).""" + now = time.time() if now is None else now + try: + max_age = float(workers_cfg().get("facts_max_age_days", FACTS_MAX_AGE_DAYS)) + except (TypeError, ValueError): + max_age = FACTS_MAX_AGE_DAYS + prices = load_prices() + has_price = any(isinstance(prices.get(t), dict) and prices[t] for t in ("models", "tools")) + if not has_price and not load_strength_prior(): + return {"state": "missing", "newest": None, "max_age_days": max_age} + dates = _fact_dates() + newest = dates[-1] if dates else None + newest_ts = _parse_time(newest) if newest else None + if newest_ts is None or now - newest_ts > max_age * 86400: + return {"state": "stale", "newest": newest, "max_age_days": max_age} + return {"state": "ok", "newest": newest, "max_age_days": max_age} + + +def facts_line(now=None): + """One session-start line asking for worker facts to be researched, or "" when they are fresh.""" + status = facts_status(now) + if status["state"] == "ok": + return "" + if status["state"] == "missing": + what = "worker facts are missing (no prices or benchmark standing recorded yet)" + else: + what = "worker facts are stale (newest from %s)" % (status["newest"] or "an unstated date") + return ("sisi: %s: ask a fast, cheap worker to research current prices and " + "software-engineering benchmark standing for the workers found here (`sisi workers`) " + "and record each with its source: `sisi workers fact WORKER --price N --source S` " + "and `sisi workers fact WORKER --score N --source S`. Until then routing has no " + "price or prior to go on." % what) + + +def estimate_cost(tokens, price_entry): + """Estimated cost from a known per-million-token price, or None. The caller labels it estimated.""" + if not isinstance(tokens, (int, float)) or not isinstance(price_entry, dict): + return None + per_million = price_entry.get("cost_per_million_tokens", price_entry.get("cost")) + if not isinstance(per_million, (int, float)): + return None + return float(tokens) / 1000000.0 * float(per_million) + + +def routable_candidates(candidates, records): + """(candidates, cold_start, excluded) for routing. Only a worker with a judged record, a + known price or a benchmark prior is a candidate; discovered catalogue models with none of + those are listed by `sisi workers` but never routed to. When nobody qualifies (a cold + start), every candidate is returned and cold_start says so: the pick is a trial to judge, + not a recommendation from evidence.""" + stats = routing.candidate_stats(candidates, records) + keep = [] + for c in candidates: + judged = sum(cell["n"] for cell in stats.get(c["worker"], {}).get("by_cell", {}).values()) + if judged or c.get("price_source") or c.get("prior_score") is not None: + keep.append(c) + if not keep: + return list(candidates), True, 0 + return keep, False, len(candidates) - len(keep) + + +_HOST_TOOL = {"claude-code": "claude", "cursor": "cursor-agent"} + + +def host_tool(): + """The driver name of the tool hosting this session, or None when it is unknown.""" + host = (store.tool() or "").strip().lower() + if not host: + return None + host = _HOST_TOOL.get(host, host) + return host if host in DRIVER_BY_NAME else None + + +def mechanism_for(cand, host=None): + """How to start the chosen worker: the host's own subagents first, its cross-provider + delegation when the config says it has one (workers.host_cross_provider), else sisi itself.""" + host = host_tool() if host is None else host + if host and cand.get("tool") == host: + return "use the host's own subagent mechanism (the worker belongs to the host tool)" + if host and workers_cfg().get("host_cross_provider"): + return "use the host's cross-provider delegation" + return "use `sisi delegate` (the host has no delegation of its own for this worker)" + + +def _pct(ok, n): + return ("%d%%" % round(100.0 * ok / n)) if n else "-" + + +def digest_lines(records=None, days=None, now=None): + """The judged record as three tables: by task type and difficulty (attempts, accepted, + checked well, later wrong, median minutes; thin rows marked), what fixed each rejection, + and how good the difficulty guesses were. Accepted on a light check shows as such.""" + records = read_records() if records is None else records + now = time.time() if now is None else now + if days is None: + try: + days = float(workers_cfg().get("digest_days", DIGEST_DAYS)) + except (TypeError, ValueError): + days = DIGEST_DAYS + late = {r.get("id") for r in records if r.get("kind") == "amend"} + attempts = [r for r in records if r.get("kind") == "attempt" + and isinstance(r.get("ts"), (int, float)) and r["ts"] >= now - days * 86400] + + def good(a): + return a.get("outcome") == "accepted" and a.get("id") not in late + + lines = ["Judged record (last %g days, %d delegations; rows under %d attempts are too thin to act on):" + % (days, len(attempts), routing.MIN_ATTEMPTS)] + if not attempts: + lines.append(" No judged delegations yet. Judge each result with `sisi delegate judge`; " + "until then routing goes on price and benchmark prior alone.") + return lines + cells = {} + for a in attempts: + cells.setdefault((a.get("type"), a.get("difficulty"), a.get("worker")), []).append(a) + rows = [] + for (typ, diff, worker), group in cells.items(): + ok = [a for a in group if good(a)] + strong = [a for a in ok if a.get("check") in STRONG_CHECKS] + minutes = [a["minutes"] for a in group if isinstance(a.get("minutes"), (int, float))] + rows.append({"type": typ, "diff": diff, "worker": worker, "n": len(group), "ok": len(ok), + "strong": len(strong), "late": sum(1 for a in group if a.get("id") in late), + "mins": statistics.median(minutes) if minutes else None}) + rows.sort(key=lambda r: -r["n"]) + dropped = max(0, len(rows) - MAX_DIGEST_ROWS) + rows = rows[:MAX_DIGEST_ROWS] + rows.sort(key=lambda r: (str(r["type"]), r["diff"] or 0, -(r["ok"] / r["n"] if r["n"] else 0), -r["n"])) + lines += ["", "Workers by task", "", + "Accepted counts results that passed the check and were not reported wrong later. " + "Checked well is the share of those verified by tests, a read, or a second reviewer; " + "the rest were accepted on a lighter check.", "", + "| Type | Diff | Worker | Attempts | Accepted | Checked well | Later wrong | Median min |", + "|---|---|---|---|---|---|---|---|"] + for r in rows: + thin = " (thin)" if r["n"] < routing.MIN_ATTEMPTS else "" + mins = ("%g" % r["mins"]) if r["mins"] is not None else "-" + lines.append("| %s | %s | %s | %d%s | %s | %s | %d | %s |" + % (r["type"], r["diff"], r["worker"], r["n"], thin, + _pct(r["ok"], r["n"]), _pct(r["strong"], r["ok"]), r["late"], mins)) + if dropped: + lines.append("%d rows with the fewest attempts are not shown." % dropped) + children = {} + for a in attempts: + if a.get("retry_of"): + children.setdefault(a["retry_of"], []).append(a) + + def later(a): + for b in children.get(a.get("id"), []): + yield b + yield from later(b) + + fixes = {} + for a in attempts: + if a.get("outcome") != "rejected": + continue + entry = fixes.setdefault(a.get("worker"), {"brief": 0, "stronger": 0, "open": 0}) + fixed_by = [b.get("worker") for b in later(a) if good(b)] + if a.get("worker") in fixed_by: + entry["brief"] += 1 + elif fixed_by: + entry["stronger"] += 1 + else: + entry["open"] += 1 + if fixes: + lines += ["", "What fixed each rejection", "", + "A better brief points at the brief. A stronger worker points at that worker's " + "limit. Not fixed points at a task that was harder or vaguer than it looked.", "", + "| Worker | Rejected | Better brief | Stronger worker | Not fixed |", + "|---|---|---|---|---|"] + for worker in sorted(fixes, key=str): + f = fixes[worker] + lines.append("| %s | %d | %d | %d | %d |" + % (worker, f["brief"] + f["stronger"] + f["open"], f["brief"], f["stronger"], f["open"])) + + def chain_size(a): + return 1 + sum(chain_size(b) for b in children.get(a.get("id"), [])) + + roots = {} + for a in attempts: + if not a.get("retry_of"): + roots.setdefault(a.get("difficulty"), []).append(a) + lines += ["", "Difficulty guesses", "", + "If tasks guessed at 1 often need more than one attempt, guess higher or start one tier up.", "", + "| Guess | Tasks | Done first try | Mean attempts |", "|---|---|---|---|"] + for diff in sorted(roots, key=lambda d: d or 0): + group = roots[diff] + first = sum(1 for a in group if good(a)) + lines.append("| %s | %d | %s | %.1f |" + % (diff, len(group), _pct(first, len(group)), + statistics.mean(chain_size(a) for a in group))) + return lines + + +def delegations_for_project(project, start_ts, end_ts, records=None): + """Delegations for one project between two times, for the scorecard: the judged attempts in + the window, worker minutes against wall time, and how many pairs overlapped (the parallelism + measure). An attempt's interval is its recorded start/end when known, else its judgement + time minus its recorded minutes.""" + records = read_records() if records is None else records + rows, intervals = [], [] + for r in records: + if r.get("kind") != "attempt" or r.get("project") != project: + continue + ts = r.get("ts") + if not isinstance(ts, (int, float)) or not (start_ts <= ts <= end_ts): + continue + rows.append(r) + end = _parse_time(r.get("ended")) or float(ts) + start = _parse_time(r.get("started")) + if start is None: + minutes = r.get("minutes") + start = end - float(minutes) * 60 if isinstance(minutes, (int, float)) else end + intervals.append((start, end)) + pairs = 0 + for i in range(len(intervals)): + for j in range(i + 1, len(intervals)): + if intervals[i][0] < intervals[j][1] and intervals[j][0] < intervals[i][1]: + pairs += 1 + worker_minutes = sum(e - s for s, e in intervals) / 60.0 + wall_minutes = ((max(e for _s, e in intervals) - min(s for s, _e in intervals)) / 60.0) if intervals else 0.0 + return {"project": project, "delegations": rows, "count": len(rows), + "worker_minutes": worker_minutes, "wall_minutes": wall_minutes, + "overlapping_pairs": pairs} + + # ---------------------------------------------------------------- running @@ -672,10 +994,12 @@ def run_delegation(candidates, kind, difficulty, prompt, cwd, explicit=None, rev timeout = DEFAULT_RUN_TIMEOUT_S tried = [] cand = explicit + prefs = load_prefs() while True: if cand is None: result = routing.choose(candidates, read_records(), read_availability(), kind, difficulty, - review_of=review_of, now=time.time(), exclude=tried) + review_of=review_of, now=time.time(), exclude=tried, + avoid=prefs["avoid"], prefer=prefs["prefer"]) cand = result["choice"] if cand is None: notes.append("sisi: no usable worker remains for kind %s at difficulty %s" % (kind, difficulty)) @@ -696,6 +1020,7 @@ def run_delegation(candidates, kind, difficulty, prompt, cwd, explicit=None, rev continue cmd = build_command(driver, cand, prompt, cwd, difficulty) env = dict(os.environ, SISI_WORKER_RUN="1") + started = time.time() try: r = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, cwd=cwd, env=env) rc, out, err = r.returncode, r.stdout or "", r.stderr or "" @@ -718,10 +1043,19 @@ def run_delegation(candidates, kind, difficulty, prompt, cwd, explicit=None, rev cand = None continue tokens, cost = extract_usage(out + "\n" + err) + cost_class = "measured" if cost is not None else "unavailable" + if cost is None: + estimated = estimate_cost(tokens, _price_for(load_prices(), cand.get("tool"), + cand.get("model"), cand["worker"])) + if estimated is not None: + cost, cost_class = estimated, "estimated" rec = {"kind": "run", "id": run_id, "ts": round(time.time()), "type": kind, "difficulty": difficulty, "worker": cand["worker"], "model": cand.get("model"), "tool": cand.get("tool"), "cwd": cwd, "brief": brief_path, - "transcript": transcript, "exit": rc, "tokens": tokens, "cost": cost, + "started": round(started), "ended": round(time.time()), + "transcript": transcript, "exit": rc, "tokens": tokens, + "tokens_class": "measured" if tokens is not None else "unavailable", + "cost": cost, "cost_class": cost_class, "status": "waiting" if rc == 0 else "failed"} append_record(rec) if rc == 0: @@ -777,9 +1111,15 @@ def is_subagent_payload(payload): return "/subagents/" in tp or tp.endswith("/subagents") +def _with_facts(lines): + line = facts_line() + return lines + [line] if line else lines + + def session_lines(model, payload=None): - """One or two plain lines at session start about delegating, or nothing for a session another - agent started. Uses only cached discovery and the record.""" + """One or two plain lines at session start about delegating (plus one asking for worker + facts when they are missing or stale), or nothing for a session another agent started. + Uses only cached discovery and the record.""" if not model or is_subagent_payload(payload or {}): return [] records = read_records() @@ -792,8 +1132,8 @@ def session_lines(model, payload=None): if waiting == 1: suffix = " One delegation is waiting for a judgement: run `sisi workers`, then `sisi delegate judge`." if not candidates: - return ["sisi: the strength of this session's model (%s) is unknown here: no workers have been " - "discovered yet (`sisi workers` finds them), so do the work yourself for now.%s" % (model, suffix)] + return _with_facts(["sisi: the strength of this session's model (%s) is unknown here: no workers have been " + "discovered yet (`sisi workers` finds them), so do the work yourself for now.%s" % (model, suffix)]) cand = resolve_worker(model, candidates) scores = strength_scores(candidates, records) own = scores.get(cand["worker"]) if cand else None @@ -803,18 +1143,18 @@ def session_lines(model, payload=None): own = (float(prior["score"]), "stored prior (%s, %s)" % (prior.get("source") or "no source stated", prior.get("date") or "no date stated")) if own is None: - return ["sisi: the strength of this session's model (%s) is unknown here (no stored prior and no " + return _with_facts(["sisi: the strength of this session's model (%s) is unknown here (no stored prior and no " "measured record yet), so do the work yourself rather than delegating on a guess.%s" - % (model, suffix)] + % (model, suffix)]) best_worker, (best_score, _how) = max(scores.items(), key=lambda kv: kv[1][0]) if scores else (None, (own[0], "")) if own[0] >= best_score - routing.STRONG_BAND: - return ["sisi: this session's model (%s) is among the strongest available here (%s): plan, ask `sisi route` who " + return _with_facts(["sisi: this session's model (%s) is among the strongest available here (%s): plan, ask `sisi route` who " "should do each piece, start that worker with this tool's own subagents (use `sisi delegate` " - "only if it has none), and judge what comes back.%s" % (model, own[1], suffix)] - return ["sisi: this session's model (%s) is not among the strongest available here (%s): do the work " + "only if it has none), and judge what comes back.%s" % (model, own[1], suffix)]) + return _with_facts(["sisi: this session's model (%s) is not among the strongest available here (%s): do the work " "yourself rather than delegating. Stronger models are available here, strongest first: %s.%s" % (model, own[1], ", ".join(w for w, _s in sorted(scores.items(), key=lambda kv: -kv[1][0])[:3] - if scores[w][0] > own[0]), suffix)] + if scores[w][0] > own[0]), suffix)]) # ---------------------------------------------------------------- commands @@ -864,6 +1204,17 @@ def _price_lines(tool_name, models, prices): def cmd_workers(args=()): + args = list(args) + if args[:1] == ["fact"]: + return _cmd_fact(args[1:]) + if args[:1] in (["avoid"], ["prefer"]): + return _cmd_pref(args[0], args[1:]) + if args[:1] == ["down"]: + return _cmd_down(args[1:]) + if args[:1] == ["up"]: + return _cmd_up(args[1:]) + if args[:1] == ["import"]: + return _cmd_import(args[1:]) imported = ensure_imported() disc = discover(force="--refresh" in args) records = read_records() @@ -916,6 +1267,16 @@ def cmd_workers(args=()): print("%d delegation%s waiting for a judgement (%s). Judge with `sisi delegate judge ID " "--outcome accepted|rejected --check none|diffstat|tests|read|review`." % (len(waiting), "" if len(waiting) == 1 else "s", ", ".join(r["id"] for r in waiting))) + prefs = load_prefs() + for key in ("avoid", "prefer"): + for entry in prefs[key]: + print("%s: %s%s" % (key.capitalize(), entry["pattern"], + (" (%s)" % entry["why"]) if entry.get("why") else "")) + line = facts_line() + if line: + print(line) + for ln in digest_lines(records): + print(ln) return 0 @@ -940,9 +1301,12 @@ def cmd_route(args=()): print("usage: sisi route --kind K --difficulty 1|2|3 [--review-of WORKER] [--explain]") return 1 kind, difficulty = setup - candidates = build_candidates() - result = routing.choose(candidates, read_records(), read_availability(), kind, difficulty, - review_of=_opt(args, "--review-of"), now=time.time()) + records = read_records() + candidates, cold, excluded = routable_candidates(build_candidates(), records) + prefs = load_prefs() + result = routing.choose(candidates, records, read_availability(), kind, difficulty, + review_of=_opt(args, "--review-of"), now=time.time(), + avoid=prefs["avoid"], prefer=prefs["prefer"]) if result["choice"] is None: print("no usable worker for kind %s at difficulty %d" % (kind, difficulty)) if "--explain" in args: @@ -950,9 +1314,21 @@ def cmd_route(args=()): print(line) return 1 print(result["choice"]["worker"]) + print("mechanism: %s" % mechanism_for(result["choice"])) if "--explain" in args: for line in routing.explain_choice(result, kind, difficulty): print(line) + if excluded: + print("%d discovered model(s) with no judged record, known price or benchmark prior " + "are not candidates" % excluded) + if cold: + print("cold start: no worker here has a judged record, a known price or a benchmark " + "prior yet, so this pick is a trial, not a recommendation from evidence. " + "Judge its result (`sisi delegate judge`) and record worker facts " + "(`sisi workers fact`) so the next choice has something to go on.") + line = facts_line() + if line: + print(line) return 0 @@ -962,6 +1338,25 @@ def cmd_delegate(args=()): return _cmd_judge(args[1:]) if args[:1] == ["amend"]: return _cmd_amend(args[1:]) + if args[:1] == ["recent"]: + return _cmd_recent(args[1:]) + if args[:1] == ["brief"]: + sys.stdout.write(brief_contract.template()) + return 0 + if args[:1] == ["check"]: + return _cmd_brief_check(args[1:]) + if args[:1] == ["guide"]: + try: + with open(paths.canon("orchestration.md"), encoding="utf-8") as f: + sys.stdout.write(f.read()) + return 0 + except OSError as e: + print("sisi delegate: cannot read the orchestration playbook: %s" % e, file=sys.stderr) + return 1 + if args[:1] == ["down"]: + return _cmd_down(args[1:]) + if args[:1] == ["up"]: + return _cmd_up(args[1:]) setup = _route_setup(args) brief = _opt(args, "--brief") if setup is None or not brief: @@ -974,6 +1369,12 @@ def cmd_delegate(args=()): except OSError as e: print("sisi delegate: cannot read the brief %s: %s" % (brief, e), file=sys.stderr) return 1 + missing = brief_contract.missing_required(prompt) + if missing: + print("sisi delegate: refusing to run this brief; it lacks %s. " + "`sisi delegate brief` prints the template; `sisi delegate check FILE` lists every missing part." + % ", ".join(missing), file=sys.stderr) + return 1 cwd = _opt(args, "--cwd") or os.getcwd() if not os.path.isdir(cwd): print("sisi delegate: not a folder: %s" % cwd, file=sys.stderr) @@ -986,6 +1387,8 @@ def cmd_delegate(args=()): if explicit is None: print("sisi delegate: no such worker found here: %s (see `sisi workers`)" % worker, file=sys.stderr) return 1 + else: + candidates, _cold, _excluded = routable_candidates(candidates, read_records()) rec, final, notes = run_delegation(candidates, kind, difficulty, prompt, cwd, explicit=explicit, review_of=_opt(args, "--review-of"), brief_path=os.path.abspath(brief)) @@ -1002,35 +1405,121 @@ def cmd_delegate(args=()): return 0 if rec.get("exit") == 0 else 1 +def _number_opt(args, name): + value = _opt(args, name) + if value is None: + return None, True + try: + return float(value), True + except ValueError: + return None, False + + +def _judge_extras(args, base): + """Shared optional fields for both judge forms. Returns an error string or None.""" + minutes, ok = _number_opt(args, "--minutes") + if not ok: + return "--minutes wants a number" + if minutes is not None: + base["minutes"] = minutes + tokens = _opt(args, "--tokens") + if tokens is not None: + try: + base["tokens"] = int(float(tokens)) + except ValueError: + return "--tokens wants a number" + cost, ok = _number_opt(args, "--cost") + if not ok: + return "--cost wants a number" + if cost is not None: + base["cost"], base["cost_class"] = cost, "measured" + for opt, key in (("--started", "started"), ("--ended", "ended")): + value = _opt(args, opt) + if value is not None: + parsed = _parse_time(value) + if parsed is None: + return "%s wants an epoch number or an ISO date like 2026-12-01T09:00" % opt + base[key] = round(parsed) + project = _opt(args, "--project") + if project: + base["project"] = project + session = _opt(args, "--session") or os.environ.get("SISI_SESSION_ID") + if session: + base["session"] = session + retry_of = _opt(args, "--retry-of") + if retry_of: + base["retry_of"] = retry_of + note = _opt(args, "--note") + if note is not None: + base["note"] = note + return None + + def _cmd_judge(args): - if not args: - print("usage: sisi delegate judge ID --outcome accepted|rejected --check CHECK [--minutes N] [--retry-of ID] [--note TEXT]") - return 1 - run_id, outcome, check = args[0], _opt(args, "--outcome"), _opt(args, "--check") + """The only way a result enters the ledger. Two forms: judge a `sisi delegate` run by its + id, or judge work run any other way (the host's own subagents, a shell-launched worker) + by naming the worker, kind and difficulty directly.""" + usage = ("usage: sisi delegate judge ID --outcome accepted|rejected --check CHECK [--minutes N]\n" + " sisi delegate judge --worker W --type K --difficulty 1|2|3 --outcome accepted|rejected " + "--check CHECK [--minutes N] [--tokens N] [--cost N] [--retry-of ID] [--project P] " + "[--session S] [--started T] [--ended T] [--note TEXT]") + outcome, check = _opt(args, "--outcome"), _opt(args, "--check") if outcome not in OUTCOMES or check not in CHECKS: - print("usage: sisi delegate judge ID --outcome accepted|rejected --check none|diffstat|tests|read|review [--minutes N]") + print(usage) return 1 records = read_records() - run = next((r for r in records if r.get("kind") == "run" and r.get("id") == run_id), None) - if run is None: - print("sisi delegate: no delegation run with id %s" % run_id, file=sys.stderr) + run_id = args[0] if args and not args[0].startswith("--") else None + if run_id is not None: + run = next((r for r in records if r.get("kind") == "run" and r.get("id") == run_id), None) + if run is None: + print("sisi delegate: no delegation run with id %s" % run_id, file=sys.stderr) + return 1 + if any(r.get("kind") == "attempt" and r.get("run_id") == run_id for r in records): + print("sisi delegate: run %s was already judged" % run_id, file=sys.stderr) + return 1 + rec = {"kind": "attempt", "id": uuid.uuid4().hex[:6], "run_id": run_id, "ts": round(time.time()), + "project": os.path.basename(str(run.get("cwd") or "").rstrip("/")) or None, + "type": run.get("type"), "difficulty": run.get("difficulty"), "worker": run.get("worker"), + "model": run.get("model"), "tool": run.get("tool"), "outcome": outcome, "check": check, + "minutes": None, "tokens": run.get("tokens"), "tokens_class": run.get("tokens_class"), + "cost": run.get("cost"), "cost_class": run.get("cost_class"), + "started": run.get("started"), "ended": run.get("ended"), + "retry_of": run.get("retry_of"), "note": None} + else: + worker = _opt(args, "--worker") + kind = _opt(args, "--type") or _opt(args, "--kind") + difficulty = _opt(args, "--difficulty") + try: + difficulty = int(difficulty) if difficulty is not None else None + except ValueError: + difficulty = None + if not worker or not kind or difficulty not in (1, 2, 3): + print(usage) + return 1 + rec = {"kind": "attempt", "id": uuid.uuid4().hex[:6], "run_id": None, "ts": round(time.time()), + "project": os.path.basename(os.getcwd().rstrip("/")) or None, + "type": kind, "difficulty": difficulty, "worker": worker.strip().lower(), + "model": _opt(args, "--model"), "tool": _opt(args, "--tool"), + "outcome": outcome, "check": check, "minutes": None, "tokens": None, + "cost": None, "cost_class": "unavailable", "retry_of": None, "note": None} + error = _judge_extras(args, rec) + if error: + print("sisi delegate: %s" % error, file=sys.stderr) return 1 - if any(r.get("kind") == "attempt" and r.get("run_id") == run_id for r in records): - print("sisi delegate: run %s was already judged" % run_id, file=sys.stderr) + if rec.get("retry_of") and rec["retry_of"] not in {r.get("id") for r in records if r.get("kind") == "attempt"}: + print("sisi delegate: no judged delegation with id %s (see `sisi delegate recent`)" % rec["retry_of"], + file=sys.stderr) return 1 - minutes = _opt(args, "--minutes") - try: - minutes = float(minutes) if minutes is not None else None - except ValueError: - print("sisi delegate: --minutes wants a number", file=sys.stderr) - return 1 - rec = {"kind": "attempt", "id": uuid.uuid4().hex[:6], "run_id": run_id, "ts": round(time.time()), - "project": os.path.basename(str(run.get("cwd") or "").rstrip("/")) or None, - "type": run.get("type"), "difficulty": run.get("difficulty"), "worker": run.get("worker"), - "model": run.get("model"), "tool": run.get("tool"), "outcome": outcome, "check": check, - "minutes": minutes, "tokens": run.get("tokens"), "cost": run.get("cost"), - "retry_of": _opt(args, "--retry-of") or run.get("retry_of"), "note": _opt(args, "--note")} + if rec.get("cost") is None and rec.get("tokens") is not None: + estimated = estimate_cost(rec["tokens"], _price_for(load_prices(), rec.get("tool"), + rec.get("model"), rec.get("worker"))) + if estimated is not None: + rec["cost"], rec["cost_class"] = estimated, "estimated" + if rec.get("tokens") is not None and not rec.get("tokens_class"): + rec["tokens_class"] = "measured" append_record(rec) + # A worker that returned a result, good or bad, is reachable. A rejection judges the work; + # it never marks the worker unavailable. clear_down(rec["worker"]) print(rec["id"]) return 0 @@ -1051,3 +1540,173 @@ def _cmd_amend(args): append_record({"kind": "amend", "id": attempt["id"], "ts": round(time.time()), "note": _opt(args, "--note")}) print("%s marked as later wrong" % attempt["id"]) return 0 + + +def _cmd_recent(args): + count = _opt(args, "-n") or _opt(args, "--count") or _opt(args, "--limit") + try: + count = int(count) if count is not None else 10 + except ValueError: + print("usage: sisi delegate recent [-n N] [--project P]") + return 1 + records = read_records() + late = {r.get("id") for r in records if r.get("kind") == "amend"} + attempts = [r for r in records if r.get("kind") == "attempt"] + project = _opt(args, "--project") + if project: + attempts = [r for r in attempts if r.get("project") == project] + for r in attempts[-count:] if count > 0 else attempts: + try: + day = time.strftime("%Y-%m-%d", time.localtime(float(r.get("ts") or 0))) + except (TypeError, ValueError, OSError): + day = "unknown date" + outcome = "later wrong" if r.get("id") in late else (r.get("outcome") or "?") + checked = r.get("check") or "?" + suffix = " (checked well)" if checked in STRONG_CHECKS else " (light check)" + note = (" %s" % r["note"]) if r.get("note") else "" + print("%s %s %s %s/%s %s %s, check %s%s%s" + % (r.get("id"), day, r.get("project"), r.get("type"), r.get("difficulty"), + r.get("worker"), outcome, checked, suffix, note)) + return 0 + + +def _cmd_brief_check(args): + if not args: + print("usage: sisi delegate check FILE") + return 1 + try: + with open(args[0], encoding="utf-8") as f: + text = f.read() + except OSError as e: + print("sisi delegate: cannot read %s: %s" % (args[0], e), file=sys.stderr) + return 1 + missing = brief_contract.missing_parts(text) + if not missing: + print("brief ok: all %d parts present" % len(brief_contract.PARTS)) + return 0 + print("brief lacks:") + for title in missing: + print(" - %s" % title) + print("`sisi delegate brief` prints the template.") + return 1 + + +def _cmd_down(args): + if not args: + print("usage: sisi workers down WORKER --reason limit|auth|missing|error [--until DATE] [--note TEXT]") + return 1 + worker = str(args[0]).strip().lower().rstrip("/") + reason = _opt(args, "--reason") + if reason not in REASONS: + print("usage: sisi workers down WORKER --reason limit|auth|missing|error [--until DATE] [--note TEXT]") + return 1 + until = _opt(args, "--until") + until_ts = _parse_time(until) if until is not None else None + if until is not None and until_ts is None: + print("sisi: --until wants a date like 2026-12-01 or 2026-12-01T09:00", file=sys.stderr) + return 1 + note = _opt(args, "--note") + record_down([worker], reason, note, until_ts=until_ts) + append_record({"kind": "down", "worker": worker, "ts": round(time.time()), + "reason": reason, "note": note, "until": until}) + entry = read_availability()[worker] + print("%s down (%s), next try %s" % (worker, reason, _when(entry.get("retry_at")))) + return 0 + + +def _cmd_up(args): + if not args: + print("usage: sisi workers up WORKER") + return 1 + worker = str(args[0]).strip().lower().rstrip("/") + before = read_availability() + clear_down(worker) + after = read_availability() + back = sorted(set(before) - set(after)) + for key in back: + append_record({"kind": "up", "worker": key, "ts": round(time.time())}) + print("available again: %s" % ", ".join(back) if back else "%s was not marked down" % worker) + return 0 + + +def _cmd_import(args): + if not args: + print("usage: sisi workers import FILE") + return 1 + if not os.path.isfile(args[0]): + print("sisi: no such ledger file: %s" % args[0], file=sys.stderr) + return 1 + before, after, added = import_ledger(args[0]) + print("imported %d rows from %s (before: %d, after: %d); the original file is unchanged" + % (added, args[0], before, after)) + return 0 + + +def _cmd_fact(args): + usage = ("usage: sisi workers fact WORKER --price N [--plan flat|per-use] [--maker M] --source S [--date YYYY-MM-DD]\n" + " sisi workers fact WORKER --score 0..100 --source S [--date YYYY-MM-DD]") + if not args: + print(usage) + return 1 + worker = args[0] + source = _opt(args, "--source") + date = _opt(args, "--date") or time.strftime("%Y-%m-%d", time.localtime()) + price, price_ok = _number_opt(args, "--price") + score, score_ok = _number_opt(args, "--score") + if not price_ok or not score_ok or (price is None and score is None): + print(usage) + return 1 + if not source: + print("sisi: a fact needs its --source (where the figure came from); nothing recorded", file=sys.stderr) + return 1 + if price is not None: + plan = _opt(args, "--plan") + if plan is not None and plan not in ("flat", "per-use"): + print("sisi: --plan wants flat or per-use", file=sys.stderr) + return 1 + prices = load_prices() + models = prices.get("models") if isinstance(prices.get("models"), dict) else {} + entry = dict(models.get(worker) or {}) + entry.update({"cost_per_million_tokens": price, "source": source, "date": date}) + if plan: + entry["plan"] = plan + maker = _opt(args, "--maker") + if maker: + entry["maker"] = maker + models[worker] = entry + prices["models"] = models + write_json(prices_path(), prices) + print("recorded price for %s: %g per million tokens (from %s, %s)" % (worker, price, source, date)) + if score is not None: + if not (0 <= score <= 100): + print("sisi: --score wants a number from 0 to 100", file=sys.stderr) + return 1 + data = read_json(strength_path()) + models = data.get("models") if isinstance(data.get("models"), dict) else {} + entry = dict(models.get(worker) or {}) + entry.update({"score": score, "source": source, "date": date}) + maker = _opt(args, "--maker") + if maker: + entry["maker"] = maker + models[worker] = entry + data["models"] = models + write_json(strength_path(), data) + print("recorded benchmark standing for %s: %g (from %s, %s)" % (worker, score, source, date)) + return 0 + + +def _cmd_pref(kind, args): + prefs = load_prefs() + if not args: + for entry in prefs[kind]: + print("%s: %s%s" % (kind, entry["pattern"], (" (%s)" % entry["why"]) if entry.get("why") else "")) + if not prefs[kind]: + print("no %s patterns recorded" % kind) + return 0 + pattern = args[0] + why = _opt(args, "--why") + prefs[kind] = [e for e in prefs[kind] if e.get("pattern") != pattern] + prefs[kind].append({"pattern": pattern, "why": why}) + write_json(prefs_path(), prefs) + print("%s %s recorded%s" % (kind, pattern, (" (%s)" % why) if why else "")) + return 0 diff --git a/tests/test_orchestration.py b/tests/test_orchestration.py new file mode 100644 index 0000000..ca961b6 --- /dev/null +++ b/tests/test_orchestration.py @@ -0,0 +1,274 @@ +import json, os, re, stat, time, unittest +from support import * + +FAKE_TOOL = """#!/bin/sh +case "$1" in + exec) + if [ "$2" = "--list-models" ]; then echo "beta-1"; echo "beta-2"; exit 0; fi + echo '{"usage":{"total_tokens":2000000}}' + echo "worker final report: done ok" ;; + usage) echo '{"allowance":{"tier":"flat plan","weekly":{"usedPercent":25},"window":{"usedPercent":10}}}' ;; + *) echo 'help' ;; +esac +exit 0 +""" + + +def valid_brief(): + return ( + "You are a worker.\n\n" + "## Outcome and scope\nDo the toy task.\n\n" + "## Context and sources of truth\nThe brief itself.\n\n" + "## Constraints and interfaces\nNo interface changes.\n\n" + "## Acceptance\nThe report says done and the toy check passes.\n\n" + "## Deliverables and report format\nA short report.\n\n" + "## Files you may change\ntoy.txt only.\n\n" + "## Verification\nRun the toy check.\n\n" + "## Budget and escalation\nTen minutes; escalate if blocked.\n") + + +class OrchCase(SisiCase): + def setUp(self): + super().setUp() + self.bindir = os.path.join(self.tmp, "bin") + os.makedirs(self.bindir) + p = os.path.join(self.bindir, "muse") + open(p, "w").write(FAKE_TOOL) + os.chmod(p, os.stat(p).st_mode | stat.S_IXUSR) + + def env(self, **kw): + return dict(PATH=self.bindir, **kw) + + def ledger(self): + p = os.path.join(self.data, "delegations.jsonl") + if not os.path.exists(p): + return [] + return [json.loads(l) for l in open(p)] + + def seed_attempts(self, rows): + os.makedirs(self.data, exist_ok=True) + with open(os.path.join(self.data, "delegations.jsonl"), "w") as f: + for row in rows: + f.write(json.dumps(row) + "\n") + + def attempt(self, id, worker="muse/beta-1", outcome="accepted", check="tests", + type="impl", difficulty=2, minutes=5, retry_of=None, ts=None): + return {"kind": "attempt", "id": id, "ts": round(time.time()) if ts is None else ts, + "project": "proj", "type": type, "difficulty": difficulty, "worker": worker, + "outcome": outcome, "check": check, "minutes": minutes, "tokens": None, + "retry_of": retry_of, "note": None} + + +class BriefTests(OrchCase): + def test_brief_template_has_eight_parts(self): + """R-7.5-1..R-7.5-9: delegate brief prints a template with every contract part.""" + r = self.sisi("delegate", "brief", env=self.env()) + self.assertEqual(r.returncode, 0, r.stderr) + for title in ("Outcome and scope", "Context and sources of truth", + "Constraints and interfaces", "Acceptance", + "Deliverables and report format", "Files you may change", + "Verification", "Budget and escalation"): + self.assertIn(title, r.stdout) + + def test_check_reports_missing_parts(self): + """R-7.5-2, R-7.5-4, R-7.5-6: delegate check names the parts a brief lacks.""" + p = os.path.join(self.proj, "thin.md") + open(p, "w").write("Do the thing.\n") + r = self.sisi("delegate", "check", p, env=self.env()) + self.assertNotEqual(r.returncode, 0) + self.assertIn("Outcome and scope", r.stdout) + self.assertIn("Acceptance", r.stdout) + self.assertIn("Files you may change", r.stdout) + + def test_check_passes_a_full_brief(self): + p = os.path.join(self.proj, "full.md") + open(p, "w").write(valid_brief()) + r = self.sisi("delegate", "check", p, env=self.env()) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + + def test_delegate_refuses_brief_without_acceptance(self): + """R-7.5-4, R-7.5-10: running a brief that lacks acceptance is refused.""" + p = os.path.join(self.proj, "noacc.md") + open(p, "w").write(valid_brief().replace("## Acceptance\nThe report says done and the toy check passes.", "## Acceptance\n[...]")) + r = self.sisi("delegate", "--kind", "impl", "--difficulty", "2", "--brief", p, + "--worker", "muse/beta-1", env=self.env()) + self.assertNotEqual(r.returncode, 0) + self.assertIn("Acceptance", r.stdout + r.stderr) + + +class LedgerTests(OrchCase): + def test_direct_judge_records_without_a_run(self): + """R-7.2-3: judge is the write path even for work run through the host's own subagents.""" + r = self.sisi("delegate", "judge", "--worker", "muse/beta-1", "--type", "read", + "--difficulty", "1", "--outcome", "accepted", "--check", "read", + "--minutes", "3", "--tokens", "1200", "--project", "proj", + env=self.env()) + self.assertEqual(r.returncode, 0, r.stderr) + rows = [x for x in self.ledger() if x.get("kind") == "attempt"] + self.assertEqual(len(rows), 1) + self.assertEqual(rows[0]["worker"], "muse/beta-1") + self.assertEqual(rows[0]["tokens"], 1200) + + def test_recent_lists_judgements_with_check_strength(self): + self.seed_attempts([self.attempt("a1", check="none"), self.attempt("a2", check="tests")]) + r = self.sisi("delegate", "recent", env=self.env()) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn("a1", r.stdout) + self.assertIn("a2", r.stdout) + + def test_down_with_until_and_up(self): + """Unavailability is temporary and carries an until-date; it is not a quality judgement.""" + r = self.sisi("workers", "down", "muse/beta-1", "--reason", "limit", + "--until", "2999-01-01", "--note", "monthly limit", env=self.env()) + self.assertEqual(r.returncode, 0, r.stderr) + avail = json.load(open(os.path.join(self.data, "worker-availability.json"))) + self.assertIn("muse/beta-1", avail) + self.assertEqual(avail["muse/beta-1"]["reason"], "limit") + self.assertEqual(avail["muse/beta-1"]["note"], "monthly limit") + r2 = self.sisi("workers", "up", "muse/beta-1", env=self.env()) + self.assertEqual(r2.returncode, 0, r2.stderr) + avail2 = json.load(open(os.path.join(self.data, "worker-availability.json"))) + self.assertNotIn("muse/beta-1", avail2) + + def test_rejection_never_marks_worker_down(self): + """A rejected judgement must not make the worker unavailable.""" + r = self.sisi("delegate", "judge", "--worker", "muse/beta-1", "--type", "impl", + "--difficulty", "2", "--outcome", "rejected", "--check", "tests", + env=self.env()) + self.assertEqual(r.returncode, 0, r.stderr) + p = os.path.join(self.data, "worker-availability.json") + avail = json.load(open(p)) if os.path.exists(p) else {} + self.assertNotIn("muse/beta-1", avail) + + def test_import_is_idempotent_and_counts_rows(self): + src = os.path.join(self.tmp, "orch.jsonl") + rows = [self.attempt("x1", ts=1700000000), self.attempt("x2", outcome="rejected", ts=1700000100), + {"kind": "amend", "id": "x1", "ts": 1700000200, "note": "later wrong"}] + with open(src, "w") as f: + for row in rows: + f.write(json.dumps(row) + "\n") + r = self.sisi("workers", "import", src, env=self.env()) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn("before: 0", r.stdout) + self.assertIn("after: 3", r.stdout) + r2 = self.sisi("workers", "import", src, env=self.env()) + self.assertEqual(r2.returncode, 0, r2.stderr) + self.assertIn("after: 3", r2.stdout) + self.assertEqual(len(self.ledger()), 3) + + +class FactsTests(OrchCase): + def test_fact_requires_source_and_is_stored(self): + """Prices and benchmark standing carry a source and date (worker facts).""" + bad = self.sisi("workers", "fact", "muse/beta-1", "--price", "3", env=self.env()) + self.assertNotEqual(bad.returncode, 0) + r = self.sisi("workers", "fact", "muse/beta-1", "--price", "3", + "--source", "test fixture pricing page", env=self.env()) + self.assertEqual(r.returncode, 0, r.stderr) + prices = json.load(open(os.path.join(self.data, "worker-prices.json"))) + entry = prices["models"]["muse/beta-1"] + self.assertEqual(entry["cost_per_million_tokens"], 3) + self.assertEqual(entry["source"], "test fixture pricing page") + self.assertTrue(entry["date"]) + + def test_fact_score_is_stored(self): + r = self.sisi("workers", "fact", "muse/beta-1", "--score", "70", + "--source", "test fixture benchmark", env=self.env()) + self.assertEqual(r.returncode, 0, r.stderr) + prior = json.load(open(os.path.join(self.data, "model-strength.json"))) + self.assertEqual(prior["models"]["muse/beta-1"]["score"], 70) + + def test_avoid_and_prefer_are_honoured(self): + """A user's own avoid/prefer constraints shape the recommendation.""" + self.sisi("workers", "fact", "muse/beta-1", "--price", "1", "--source", "fixture", env=self.env()) + self.sisi("workers", "fact", "muse/beta-2", "--price", "2", "--source", "fixture", env=self.env()) + plain = self.sisi("route", "--kind", "impl", "--difficulty", "2", env=self.env()) + self.assertEqual(plain.returncode, 0, plain.stderr) + self.assertEqual(plain.stdout.splitlines()[0], "muse/beta-1") + r = self.sisi("workers", "avoid", "beta-1", "--why", "fixture reason", env=self.env()) + self.assertEqual(r.returncode, 0, r.stderr) + after = self.sisi("route", "--kind", "impl", "--difficulty", "2", "--explain", env=self.env()) + self.assertEqual(after.returncode, 0, after.stderr) + self.assertEqual(after.stdout.splitlines()[0], "muse/beta-2") + self.assertIn("fixture reason", after.stdout) + + +class RouteTests(OrchCase): + def test_route_names_a_mechanism(self): + """R-7.1-1: the recommendation says how to start the worker.""" + r = self.sisi("route", "--kind", "impl", "--difficulty", "2", env=self.env()) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn("mechanism:", r.stdout) + + def test_unpriced_catalogue_models_are_not_candidates(self): + """Candidates need a judged record, a price or a benchmark prior.""" + self.seed_attempts([self.attempt("j%d" % i) for i in range(8)]) + r = self.sisi("route", "--kind", "impl", "--difficulty", "2", "--explain", env=self.env()) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertEqual(r.stdout.splitlines()[0], "muse/beta-1") + self.assertNotIn("beta-2\" is chosen", r.stdout) + + def test_cost_is_estimated_from_facts(self): + """R-7.3-1: tokens without a reported cost get an estimated cost from known prices.""" + self.sisi("workers", "fact", "muse/beta-1", "--price", "2", "--source", "fixture", env=self.env()) + p = os.path.join(self.proj, "b.md") + open(p, "w").write(valid_brief()) + r = self.sisi("delegate", "--kind", "read", "--difficulty", "1", "--brief", p, + "--worker", "muse/beta-1", env=self.env()) + self.assertEqual(r.returncode, 0, r.stderr) + runs = [x for x in self.ledger() if x.get("kind") == "run"] + self.assertEqual(len(runs), 1) + self.assertEqual(runs[0]["tokens"], 2000000) + self.assertEqual(runs[0]["cost"], 4.0) + self.assertEqual(runs[0]["cost_class"], "estimated") + + +class DigestTests(OrchCase): + def test_workers_shows_three_tables_and_thin_marks(self): + """R-7.2-3: the judged record is shown honestly, thin rows marked, checks named.""" + rows = [self.attempt("a%d" % i, check="tests") for i in range(8)] + rows.append(self.attempt("r1", outcome="rejected", check="read")) + rows.append(self.attempt("r2", retry_of="r1")) + rows.append({"kind": "amend", "id": "a0", "ts": round(time.time()), "note": "later wrong"}) + self.seed_attempts(rows) + r = self.sisi("workers", env=self.env()) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn("Workers by task", r.stdout) + self.assertIn("What fixed each rejection", r.stdout) + self.assertIn("Difficulty guesses", r.stdout) + self.assertIn("Checked well", r.stdout) + + def test_delegations_for_project_reports_overlap(self): + """Scorecard seam: delegations for a project in a window, with overlap (parallelism).""" + from sisi import workers + now = time.time() + rows = [self.attempt("p1", minutes=20, ts=round(now - 600)), + self.attempt("p2", minutes=20, ts=round(now - 300))] + self.seed_attempts(rows) + got = workers.delegations_for_project("proj", now - 3600, now + 60) + self.assertEqual(got["count"], 2) + self.assertEqual(got["overlapping_pairs"], 1) + got2 = workers.delegations_for_project("proj", now + 3600, now + 7200) + self.assertEqual(got2["count"], 0) + + +class GenericTests(unittest.TestCase): + def test_no_model_names_or_prices_in_product_files(self): + """The product ships no model id, model-family name or price.""" + forbidden = ["haiku", "sonnet", "opus", "fable", "muse-wonder", "muse-ember", + "muse-spark", "gpt-", "glm-", "deepseek", "mimo-", "opencode-go/", + "_MAKER_ALIASES"] + for rel in ("sisi/workers.py", "sisi/routing.py", "sisi/brief.py", + "canon/orchestration.md", "docs/workers.md"): + text = open(os.path.join(REPO, rel), encoding="utf-8").read().lower() + for bad in forbidden: + self.assertNotIn(bad, text, "%s in %s" % (bad, rel)) + self.assertIsNone(re.search(r"\$\d", text), "a price in %s" % rel) + + def test_guide_prints_the_playbook(self): + text = open(os.path.join(REPO, "canon", "orchestration.md"), encoding="utf-8").read() + self.assertLessEqual(len(text.splitlines()), 120) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_workers.py b/tests/test_workers.py index 699ad27..770cd8f 100644 --- a/tests/test_workers.py +++ b/tests/test_workers.py @@ -54,7 +54,16 @@ class WorkerCase(SisiCase): def brief(self): p = os.path.join(self.proj, "brief.md") - open(p, "w").write("You are a worker. Do the toy task and report back.\n") + open(p, "w").write( + "You are a worker.\n\n" + "## Outcome and scope\nDo the toy task.\n\n" + "## Context and sources of truth\nThis brief.\n\n" + "## Constraints and interfaces\nNone.\n\n" + "## Acceptance\nThe final report says done.\n\n" + "## Deliverables and report format\nA short report.\n\n" + "## Files you may change\ntoy.txt only.\n\n" + "## Verification\nNone needed.\n\n" + "## Budget and escalation\nFive minutes; escalate if blocked.\n") return p