Generic orchestration: ledger, facts, routing, brief contract, playbook
This commit is contained in:
1 parent
9fcd617391
commit
e8d29e80e0
8 files changed
+1391
-196
No files matched your search
@@ -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.
|
||||
+59
-93
@@ -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": {"<model or worker>": {"plan": "flat" or "per-use",
|
||||
"cost_per_million_tokens": number, "maker": name, "source": text, "date": "YYYY-MM-DD"}},
|
||||
"tools": {"<tool>": entries of the same shape}}`.
|
||||
- `model-strength.json`: `{"models": {"<model or worker>": {"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`.
|
||||
+116
@@ -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]))]
|
||||
+10
-5
@@ -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 "<work>" 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
|
||||
|
||||
|
||||
+83
-17
@@ -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 = {}, []
|
||||
|
||||
+739
-80
File diff suppressed because it is too large.
Load diff
@@ -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()
|
||||
+10
-1
@@ -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
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user