diff --git a/docs/workers.md b/docs/workers.md index a27256b..64e7597 100644 --- a/docs/workers.md +++ b/docs/workers.md @@ -17,6 +17,16 @@ or learned from judged results. The strategy is [canon/orchestration.md](../cano [--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 only PROVIDER PATTERN... --why TEXT` — only the matching models of that provider are + routable; anything else from it (a newly discovered model, say) is passed over with the reason. + `--remove` deletes the limit. +- `sisi workers note PATTERN "TEXT" --why SOURCE` — a standing operational fact about workers that + match PATTERN. Shown in `sisi workers` and, for the chosen and passed-over workers it applies to, + in `sisi route`, as information for the agent. The product ships none; `--remove` deletes one. +- A worker id with no provider prefix is a host-native worker (the host's own subagent model): it + needs no command-line tool, is usable unless marked down, and `sisi route` says to start it with + the host's own subagent tool. Everything `sisi workers` and `sisi delegate` write to the user + store is committed there, one small commit per command. - `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, diff --git a/sisi/cli.py b/sisi/cli.py index 9e95802..2af214b 100644 --- a/sisi/cli.py +++ b/sisi/cli.py @@ -78,6 +78,8 @@ A shared rulebook and enforced definitions of done for every AI coding CLI. 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 only PROVIDER PATTERN... --why TEXT | --remove make only the matching models of that provider routable + sisi workers note PATTERN "TEXT" --why SOURCE | --remove a standing fact about workers matching PATTERN, shown with route results 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] @@ -388,13 +390,13 @@ def main(argv): return verifiers.done_main(args) if cmd == "workers": from . import workers - return workers.cmd_workers(args) + return workers.with_commit(workers.cmd_workers, args, "workers") if cmd == "route": from . import workers return workers.cmd_route(args) if cmd == "delegate": from . import workers - return workers.cmd_delegate(args) + return workers.with_commit(workers.cmd_delegate, args, "delegate") if cmd == "eval": from . import evaluate return evaluate.cmd_eval(args) diff --git a/sisi/lifecycle.py b/sisi/lifecycle.py index 7df7729..f3b05fa 100644 --- a/sisi/lifecycle.py +++ b/sisi/lifecycle.py @@ -337,7 +337,8 @@ def migrate_learnings(): origin = L.normalize_project(old.get("project")) or (prov[0]["project"] if prov else "") if not prov: prov = [{"unit": "legacy:%s" % lid, "project": origin, "ts": old.get("created") or "", "kind": "origin"}] - status = {"applied": "implemented", "retired": "reverted"}.get(old.get("status"), "observed") + # an old open lesson waits for a cycle, as before: it stays counted by `sisi cycle due` + status = {"applied": "implemented", "retired": "reverted", "open": "proposed"}.get(old.get("status"), "observed") kind = old.get("change_kind") target = str(old.get("target") or "") rec = { @@ -444,9 +445,9 @@ def cmd_update(args): try: top = _pgit("rev-parse", "--show-toplevel") if top.returncode != 0 or os.path.realpath(top.stdout.strip()) != os.path.realpath(paths.REPO): - say("sisi update: %s is not a git clone, so there is nothing to fetch. Replace it with a newer copy and run " - "`sisi update --post` to rebuild." % paths.REPO) - return 1 + say("sisi update: %s is not a git clone, so the product itself is updated by a release; " + "backing up, migrating and rebuilding your data now." % paths.REPO) + return post_update() if _pgit("rev-parse", "--verify", "-q", "HEAD").returncode != 0: say("sisi update: the product repository has no commits yet; nothing to update.") return 1 @@ -483,11 +484,44 @@ def cmd_update(args): return p.returncode +UPDATE_MARK = ".made-by-sisi-update" +DEFAULT_KEEP_UPDATE_BACKUPS = 5 + + +def backups_to_keep(): + """How many of the update step's own snapshots to keep (config backups.keep_update; at least 1).""" + try: + n = int((store.config().get("backups") or {}).get("keep_update", DEFAULT_KEEP_UPDATE_BACKUPS)) + except (TypeError, ValueError): + n = DEFAULT_KEEP_UPDATE_BACKUPS + return max(n, 1) + + +def prune_update_backups(current): + """Mark the snapshot just taken as made by the update step, then delete the oldest snapshots + carrying that mark beyond the configured number. A folder without the mark is never touched, + and the newest one is never deleted. Returns how many were deleted.""" + base = paths.data_file("backups") + try: + open(os.path.join(current, UPDATE_MARK), "w").close() + mine = sorted(n for n in os.listdir(base) if os.path.isfile(os.path.join(base, n, UPDATE_MARK))) + except OSError: + return 0 + doomed = mine[:-backups_to_keep()] + for n in doomed: + shutil.rmtree(os.path.join(base, n), ignore_errors=True) + return len(doomed) + + def post_update(): """After the product changed: back up personal data, migrate its format, keep replacements, rebuild, check.""" try: pdata.ensure() - print("backup: %s" % snapshot("update")) + bdir = snapshot("update") + print("backup: %s" % bdir) + pruned = prune_update_backups(bdir) + if pruned: + print("removed %d older update backup(s) (keeping %d)" % (pruned, backups_to_keep())) for n in run(): print(n) for r in overlay.scan_retests(): diff --git a/sisi/routing.py b/sisi/routing.py index e0507c9..98ad253 100644 --- a/sisi/routing.py +++ b/sisi/routing.py @@ -221,6 +221,8 @@ def choose(candidates, records, availability, kind, difficulty, review_of=None, def load_ratio(c): left = c.get("allowance_pct_left") + if left is None and c.get("host_native"): + return 0.0 # a host worker has no allowance to spread work across: the record decides weight = float(left) if left else UNKNOWN_ALLOWANCE return stats.get(c["worker"], {}).get("uses", 0) / max(weight, 1.0) diff --git a/sisi/workers.py b/sisi/workers.py index 49810a4..0d097d2 100644 --- a/sisi/workers.py +++ b/sisi/workers.py @@ -19,7 +19,11 @@ Personal files (all in the personal data folder): model-strength.json worker facts (benchmark standing): {"models": {"": {"score": 0..100, "source": text, "date": "YYYY-MM-DD"}}} worker-prefs.json the user's own routing constraints: {"avoid": [{"pattern", "why"}], - "prefer": [...]}, written by `sisi workers avoid|prefer` + "prefer": [...], "only": [{"provider", "patterns", "why"}]}, written by + `sisi workers avoid|prefer|only` + worker-notes.json standing operational facts about workers: {"notes": [{"pattern", "text", + "why", "date"}]}, written by `sisi workers note`; shown to the agent as + information, never applied by sisi itself 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. """ @@ -615,6 +619,14 @@ def build_candidates(disc=None, records=None): w = r.get("worker") if not w or str(w).lower() in alias_set or r.get("kind") not in ("attempt", "run"): continue + if "/" not in str(w): + # No provider prefix: the host tool's own subagent model. It needs no discovered + # command-line tool and is usable unless marked down (routing checks that). + c = add(None, str(w), usable=True) + if c is not None: + c["host_native"] = True + alias_set.add(str(w).lower()) + continue tool = _guess_tool(w, disc_tools) installed = any(t["name"] == tool and t.get("installed", True) for t in disc_tools) if tool else False c = add(tool, r.get("model") or str(w), @@ -653,9 +665,103 @@ def load_prefs(): 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 [] + rows = d.get("only") + out["only"] = [r for r in rows if isinstance(r, dict) and r.get("provider") and isinstance(r.get("patterns"), list) + and r["patterns"]] if isinstance(rows, list) else [] return out +def apply_limits(candidates, prefs): + """(kept, excluded): `sisi workers only PROVIDER PATTERN...` leaves only the matching models of + that provider routable; anything else from it is passed over with the reason.""" + limits = {str(e["provider"]).lower(): e for e in prefs.get("only") or []} + if not limits: + return candidates, [] + kept, excluded = [], [] + for c in candidates: + worker = str(c.get("worker") or "") + prefix = worker.split("/", 1)[0].lower() if "/" in worker else "" + entry = limits.get(prefix) + if entry is None: + kept.append(c) + continue + model = worker.split("/", 1)[1].lower() + if any(str(p).lower() in model for p in entry["patterns"]): + kept.append(c) + else: + excluded.append((worker, "outside the user's own limit on %s to %s%s" + % (entry["provider"], ", ".join(str(p) for p in entry["patterns"]), + (" (%s)" % entry["why"]) if entry.get("why") else ""))) + return kept, excluded + + +# ---- notes: standing facts about workers, shown to the agent as information + + +def notes_path(): + return _data_file("worker-notes.json") + + +def load_notes(): + rows = read_json(notes_path()).get("notes") + return [r for r in rows if isinstance(r, dict) and r.get("pattern") and r.get("text")] if isinstance(rows, list) else [] + + +def note_line(n): + bits = [n["why"] if n.get("why") else None, n.get("date")] + return "%s (pattern %r; %s)" % (n["text"], n["pattern"], ", ".join(b for b in bits if b) or "no source stated") + + +def notes_for(candidates_by_worker, chosen, passed, notes=None, limit=5): + """Lines of notes that apply to the chosen worker or a passed-over one. Each note is shown once, + with who it applies to. Information for the agent, not an instruction.""" + notes = load_notes() if notes is None else notes + lines = [] + for n in notes: + hit = [] + if chosen is not None and routing._pattern_match(chosen, [n]): + hit.append("the chosen worker") + names = [w for w, _r in passed if w in candidates_by_worker and routing._pattern_match(candidates_by_worker[w], [n])] + if names: + hit.append("passed over: %s%s" % (", ".join(names[:3]), " and %d more" % (len(names) - 3) if len(names) > 3 else "")) + if hit: + lines.append("note (information, not an instruction) for %s: %s" % ("; ".join(hit), note_line(n))) + if len(lines) > limit: + lines = lines[:limit] + ["and %d more notes apply (`sisi workers`)" % (len(lines) - limit)] + return lines + + +# ---- keeping the user store's own files in its history + + +DATA_FILES = ("delegations.jsonl", "worker-availability.json", "worker-prices.json", + "model-strength.json", "worker-prefs.json", "worker-notes.json") + + +def _data_state(): + out = [] + for name in DATA_FILES: + try: + st = os.stat(_data_file(name)) + out.append((st.st_mtime_ns, st.st_size)) + except OSError: + out.append(None) + return out + + +def with_commit(fn, args, label): + """Run a command; when it changed any of the worker files in the user store, commit just those + files (one small commit per command; the user's other uncommitted files are never swept up).""" + before = _data_state() + try: + return fn(args) + finally: + if _data_state() != before: + from . import pdata + sub = " ".join(str(a) for a in list(args)[:1] if not str(a).startswith("-")) + pdata.commit("sisi %s%s: worker data changed" % (label, (" " + sub) if sub else ""), list(DATA_FILES)) + + def _fact_dates(): dates = [] prices = load_prices() @@ -704,8 +810,8 @@ def facts_line(now=None): 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) + "and `sisi workers fact WORKER --score N --source S`. Until then routing " + "goes by the judged record alone." % what) def estimate_cost(tokens, price_entry): @@ -751,6 +857,8 @@ 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 cand.get("host_native"): + return "use the host's own subagent tool with model %s" % (cand.get("model") or cand["worker"]) 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"): @@ -995,6 +1103,11 @@ def run_delegation(candidates, kind, difficulty, prompt, cwd, explicit=None, rev tried = [] cand = explicit prefs = load_prefs() + if cand is not None and cand.get("host_native"): + notes.append("sisi: %s is a host-native worker; start it with the host's own subagent tool " + "(`sisi delegate` runs only command-line tools)" % cand["worker"]) + return None, None, notes + candidates = [c for c in apply_limits(candidates, prefs)[0] if not c.get("host_native")] while True: if cand is None: result = routing.choose(candidates, read_records(), read_availability(), kind, difficulty, @@ -1095,9 +1208,7 @@ def strength_scores(candidates, records): def _cached_candidates(records=None): """Candidates from the discovery cache only: session start must stay fast and run no tool.""" cached = load_discovery() - if not cached.get("tools"): - return [], [] - return build_candidates(cached, read_records() if records is None else records), cached["tools"] + return build_candidates(cached, read_records() if records is None else records), cached.get("tools") or [] def is_subagent_payload(payload): @@ -1117,44 +1228,47 @@ def _with_facts(lines): def session_lines(model, payload=None): - """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.""" + """Plain lines at session start about delegating, or nothing for a session another agent + started. When the main model's standing is unknown it says nothing about whether to delegate: + a missing number never argues against orchestrating. At most one extra line asks for worker + facts to be researched when they are missing or stale (the caller shows these lines once per + session). Uses only cached discovery and the record.""" if not model or is_subagent_payload(payload or {}): return [] records = read_records() candidates, _tools = _cached_candidates(records) waiting = len(unjudged_runs(records)) suffix = "" - if waiting: - suffix = " %d delegation%s waiting for a judgement: run `sisi workers` to see, then `sisi delegate judge`." \ - % (waiting, " is" if waiting == 1 else "s are") - if waiting == 1: - suffix = " One delegation is waiting for a judgement: run `sisi workers`, then `sisi delegate judge`." - if not candidates: - 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) + if waiting == 1: + suffix = " One delegation is waiting for a judgement: run `sisi workers`, then `sisi delegate judge`." + elif waiting: + suffix = " %d delegations are waiting for a judgement: run `sisi workers` to see, then `sisi delegate judge`." % waiting + scores = strength_scores(candidates, records) if candidates else {} + cand = resolve_worker(model, candidates) if candidates else None own = scores.get(cand["worker"]) if cand else None - if own is None and cand is None: + if own is None: prior = load_strength_prior().get(model) if isinstance(prior, dict) and isinstance(prior.get("score"), (int, float)): 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 _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)]) - 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 _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 _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)]) + lines = [] + if own is not None: + best_score = max([s for s, _h in scores.values()] + [own[0]]) + if own[0] >= best_score - routing.STRONG_BAND: + lines.append("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)) + else: + stronger = [w for w, _s in sorted(scores.items(), key=lambda kv: -kv[1][0])[:3] if scores[w][0] > own[0]] + lines.append("sisi: this session's model (%s) stands at %g (%s)%s. 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[0], own[1], + ("; stronger models available here, strongest first: %s" % ", ".join(stronger)) if stronger else "", + suffix)) + elif suffix: + lines.append("sisi:" + suffix) + return _with_facts(lines) # ---------------------------------------------------------------- commands @@ -1209,6 +1323,10 @@ def cmd_workers(args=()): return _cmd_fact(args[1:]) if args[:1] in (["avoid"], ["prefer"]): return _cmd_pref(args[0], args[1:]) + if args[:1] == ["only"]: + return _cmd_only(args[1:]) + if args[:1] == ["note"]: + return _cmd_note(args[1:]) if args[:1] == ["down"]: return _cmd_down(args[1:]) if args[:1] == ["up"]: @@ -1272,6 +1390,11 @@ def cmd_workers(args=()): for entry in prefs[key]: print("%s: %s%s" % (key.capitalize(), entry["pattern"], (" (%s)" % entry["why"]) if entry.get("why") else "")) + for entry in prefs["only"]: + print("Only on %s: %s%s" % (entry["provider"], ", ".join(str(p) for p in entry["patterns"]), + (" (%s)" % entry["why"]) if entry.get("why") else "")) + for n in load_notes(): + print("Note (information for the agent): %s" % note_line(n)) line = facts_line() if line: print(line) @@ -1280,6 +1403,22 @@ def cmd_workers(args=()): return 0 +def _down_now(avail, now): + """[(key, entry)] for every provider or worker marked down whose retry time is still ahead.""" + return [(k, v) for k, v in sorted((avail or {}).items()) + if isinstance(v, dict) and float(v.get("retry_at") or 0) > now] + + +def _down_lines(down, limit=3): + """One line naming what is down and when each is due for another try, or nothing.""" + if not down: + return [] + shown = ["%s (%s, next try %s)" % (k, v.get("reason") or "down", _when(v.get("retry_at"))) + for k, v in down[:limit]] + more = " and %d more" % (len(down) - limit) if len(down) > limit else "" + return ["down now: %s%s" % ("; ".join(shown), more)] + + def _route_setup(args): ensure_imported() kind = _opt(args, "--kind") @@ -1304,17 +1443,31 @@ def cmd_route(args=()): records = read_records() candidates, cold, excluded = routable_candidates(build_candidates(), records) prefs = load_prefs() + everyone = candidates + candidates, limited = apply_limits(candidates, 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"]) + result["passed_over"] = list(result["passed_over"]) + limited + by_worker = {c["worker"]: c for c in everyone} + down = _down_now(read_availability(), time.time()) if result["choice"] is None: print("no usable worker for kind %s at difficulty %d" % (kind, difficulty)) + for line in _down_lines(down): + print(line) + print("nothing is usable right now: the main agent does this task itself meanwhile, " + "and tries `sisi route` again after the next-try time above%s." + % ("" if down else " or once a worker is recorded or fixed (`sisi workers`)")) if "--explain" in args: for line in routing.explain_choice(result, kind, difficulty)[1:]: print(line) return 1 print(result["choice"]["worker"]) print("mechanism: %s" % mechanism_for(result["choice"])) + for line in _down_lines(down): + print(line) + for line in notes_for(by_worker, result["choice"], result["passed_over"]): + print(line) if "--explain" in args: for line in routing.explain_choice(result, kind, difficulty): print(line) @@ -1323,7 +1476,7 @@ def cmd_route(args=()): "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. " + "prior yet, so nothing is known yet about this pick. " "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() @@ -1636,6 +1789,9 @@ def _cmd_import(args): if not os.path.isfile(args[0]): print("sisi: no such ledger file: %s" % args[0], file=sys.stderr) return 1 + if not any(r.get("kind") in ("attempt", "run", "amend", "down", "up") for r in read_records(args[0])): + print("sisi: warning: %s contains no ledger rows (no line with a kind of attempt, run, amend, " + "down or up); is it the right file?" % args[0], file=sys.stderr) 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)) @@ -1710,3 +1866,75 @@ def _cmd_pref(kind, args): write_json(prefs_path(), prefs) print("%s %s recorded%s" % (kind, pattern, (" (%s)" % why) if why else "")) return 0 + + +def _cmd_only(args): + usage = "usage: sisi workers only PROVIDER PATTERN [PATTERN...] --why TEXT | only PROVIDER --remove" + plain = _positional(args, ("--why",)) + if not plain: + print(usage) + return 1 + provider, patterns = plain[0].strip().lower().rstrip("/"), plain[1:] + prefs = load_prefs() + rows = [e for e in prefs["only"] if str(e["provider"]).lower() != provider] + if "--remove" in args: + removed = len(rows) != len(prefs["only"]) + _store_only(rows) + print("limit on %s removed" % provider if removed else "no limit was recorded for %s" % provider) + return 0 + if not patterns: + print(usage) + return 1 + why = _opt(args, "--why") + rows.append({"provider": provider, "patterns": patterns, "why": why}) + _store_only(rows) + print("only %s routable from %s%s" % (", ".join(patterns), provider, (" (%s)" % why) if why else "")) + return 0 + + +def _store_only(rows): + d = read_json(prefs_path()) + d["only"] = rows + write_json(prefs_path(), d) + + +def _positional(args, value_opts): + out, skip = [], False + for a in args: + if skip: + skip = False + elif a in value_opts: + skip = True + elif not a.startswith("--"): + out.append(a) + return out + + +def _cmd_note(args): + usage = ('usage: sisi workers note PATTERN "TEXT" --why SOURCE | note PATTERN --remove | note (lists)') + plain = _positional(args, ("--why",)) + notes = load_notes() + if not plain: + for n in notes: + print("note: %s" % note_line(n)) + if not notes: + print("no worker notes recorded") + return 0 + pattern = plain[0] + if "--remove" in args: + keep = [n for n in notes if n["pattern"] != pattern] + write_json(notes_path(), {"notes": keep}) + print("removed %d note(s) for %r" % (len(notes) - len(keep), pattern)) + return 0 + if len(plain) < 2: + print(usage) + return 1 + why = _opt(args, "--why") + if not why: + print("sisi: a note needs its --why (where the fact came from); nothing recorded", file=sys.stderr) + return 1 + notes = [n for n in notes if not (n["pattern"] == pattern and n["text"] == plain[1])] + notes.append({"pattern": pattern, "text": plain[1], "why": why, "date": time.strftime("%Y-%m-%d", time.localtime())}) + write_json(notes_path(), {"notes": notes}) + print("note recorded for %r (from %s)" % (pattern, why)) + return 0 diff --git a/tests/test_personal.py b/tests/test_personal.py index 875f98a..ec9350a 100644 --- a/tests/test_personal.py +++ b/tests/test_personal.py @@ -377,10 +377,32 @@ class UpdateTests(PersonalCase): self.assertIn("already up to date", r.stdout) self.assertEqual(len([l for l in open(os.path.join(self.data, "retest.jsonl"))]), 1) - def test_update_refuses_outside_a_git_clone(self): + def test_update_outside_a_git_clone_runs_the_post_step(self): + """R-14.4-1, R-3.2-4: an installed copy is updated by a release, but plain `sisi update` still + backs up, migrates and rebuilds the user's data and exits 0.""" r = self.sisi("update") - self.assertEqual(r.returncode, 1) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) self.assertIn("not a git clone", r.stdout) + self.assertIn("backup:", r.stdout) + self.assertIn("rulebook rebuilt", r.stdout) + + def test_update_keeps_a_bounded_number_of_its_own_backups(self): + """R-3.2-4: the update step keeps at most N of its own snapshots, never one it did not + make, and never the newest.""" + pdata.ensure() + json.dump({"backups": {"keep_update": 2}}, open(os.path.join(self.data, "config.json"), "w")) + foreign = os.path.join(self.data, "backups", "20200101T000000-update") # someone else's, same look + os.makedirs(foreign) + for _ in range(4): + self.ok("update") + bk = os.path.join(self.data, "backups") + mine = sorted(d for d in os.listdir(bk) if os.path.exists(os.path.join(bk, d, ".made-by-sisi-update"))) + self.assertEqual(len(mine), 2, os.listdir(bk)) + self.assertTrue(os.path.isdir(foreign)) + json.dump({"backups": {"keep_update": 0}}, open(os.path.join(self.data, "config.json"), "w")) + self.ok("update") + mine = [d for d in os.listdir(bk) if os.path.exists(os.path.join(bk, d, ".made-by-sisi-update"))] + self.assertEqual(len(mine), 1) # never fewer than the newest one def _seed_legacy_db(path, lessons, proj): @@ -473,6 +495,18 @@ class MigrationTests(PersonalCase): self.assertEqual(self.lessons_of(os.path.join(self.data, "retro.db")), before) self.assertEqual(self.ok("lessons", "--json").stdout.count('"id": "L-'), 2) + def test_a_due_cycle_stays_due_after_migration(self): + """R-3.1-2: five open lessons made a cycle due in the old store; migrated, they still do.""" + os.makedirs(os.path.join(self.state, "backups")) + _seed_legacy_db(os.path.join(self.state, "retro.db"), + [dict(aim="speed", moment="moment %d" % i, cause="cause %d" % i, change_kind="rule", + change="Change number %d to the way of working" % i, target=None) for i in range(5)], + self.proj) + self.ok("update", "--post") + out = self.ok("cycle", "due").stdout + self.assertIn("a learning cycle is due", out) + self.assertIn("5 proposed", out) + def test_old_layout_keeps_working_before_migration(self): self.legacy_state() self.ok("update", "--post") # lessons now live in learnings.jsonl; migration is the one path in diff --git a/tests/test_worker_routes.py b/tests/test_worker_routes.py new file mode 100644 index 0000000..a9bb704 --- /dev/null +++ b/tests/test_worker_routes.py @@ -0,0 +1,222 @@ +"""Routing with host-native workers (bare names), notes, provider limits, session-start wording. +Fixture ledger is shaped like a real one: bare host names with hundreds of attempts beside +prefixed provider workers. Requirement ids: R-7.2-1..3, R-7.1-1, R-17-3, R-17-8.""" +import json, os, stat, subprocess, time, unittest +from support import * + +FAKE_MUSE = """#!/bin/sh +case "$1" in + exec) + if [ "$2" = "--list-models" ]; then echo "beta-1"; echo "beta-2"; exit 0; fi + echo "done" ;; + *) echo 'muse help' ;; +esac +exit 0 +""" +FAKE_CODEX = """#!/bin/sh +case "$1 $2" in + "debug models") echo '{"models":[{"slug":"alpha-1"}]}' ;; + *) echo 'codex help' ;; +esac +exit 0 +""" + + +class RouteCase(SisiCase): + def setUp(self): + super().setUp() + self.bindir = os.path.join(self.tmp, "bin") + os.makedirs(self.bindir) + for name, body in (("muse", FAKE_MUSE), ("codex", FAKE_CODEX)): + p = os.path.join(self.bindir, name) + open(p, "w").write(body) + os.chmod(p, os.stat(p).st_mode | stat.S_IXUSR) + + def env(self, **kw): + return dict(PATH=self.bindir, **kw) + + def seed(self, spec, type="impl", difficulty=2): + """spec: [(worker, attempts, accepted)]""" + os.makedirs(self.data, exist_ok=True) + n = 0 + with open(os.path.join(self.data, "delegations.jsonl"), "a") as f: + for worker, attempts, accepted in spec: + for i in range(attempts): + n += 1 + f.write(json.dumps({"kind": "attempt", "id": "r%d" % n, "ts": 1760000000 + n, + "project": "p", "type": type, "difficulty": difficulty, + "worker": worker, "outcome": "accepted" if i < accepted else "rejected", + "check": "tests", "minutes": 5}) + "\n") + + def seed_real_shape(self): + self.seed([("wk-fast", 300, 290), ("wk-mid", 120, 100), ("muse/beta-1", 12, 11), ("codex/alpha-1", 9, 8)]) + + def down(self, *providers): + for p in providers: + r = self.sisi("workers", "down", p, "--reason", "limit", "--until", "2099-01-02", env=self.env()) + self.assertEqual(r.returncode, 0, r.stderr) + + +class HostNativeTests(RouteCase): + def test_bare_names_are_routable_host_workers(self): + """R-7.2-1, R-7.2-3, R-7.1-1: a worker id without a provider prefix is a host subagent: routable + with no discovered tool, and the mechanism line says to use the host's subagent tool.""" + self.seed_real_shape() + r = self.sisi("route", "--kind", "impl", "--difficulty", "2", env=dict(PATH="")) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + first = r.stdout.splitlines()[0] + self.assertTrue(first.startswith("wk-"), r.stdout) + self.assertIn("host's own subagent tool with model %s" % first, r.stdout) + self.assertNotIn("no tool for it", r.stdout) + + def test_down_host_worker_is_skipped(self): + """R-7.2-3: a host worker marked down is passed over like any other.""" + self.seed_real_shape() + self.sisi("workers", "down", "wk-fast", "--reason", "limit", "--until", "2099-01-02", env=self.env()) + self.sisi("workers", "down", "wk-mid", "--reason", "limit", "--until", "2099-01-02", env=self.env()) + r = self.sisi("route", "--kind", "impl", "--difficulty", "2", "--explain", env=self.env()) + self.assertNotIn("wk-", r.stdout.splitlines()[0]) + + +class DownProvidersTests(RouteCase): + def test_host_worker_recommended_while_providers_are_down(self): + """R-7.2-1, R-7.2-3, R-17-5: every provider down, a record exists: route still names the best + host worker, says which providers are down and when each is due, and gives the mechanism.""" + self.seed_real_shape() + self.down("muse", "codex") + r = self.sisi("route", "--kind", "impl", "--difficulty", "2", env=self.env()) + self.assertEqual(r.returncode, 0, r.stdout) + lines = r.stdout.splitlines() + self.assertTrue(lines[0].startswith("wk-"), r.stdout) + self.assertIn("host's own subagent tool", r.stdout) + down = [l for l in lines if l.startswith("down now")] + self.assertEqual(len(down), 1, r.stdout) + self.assertIn("muse", down[0]) + self.assertIn("codex", down[0]) + self.assertIn("2099-01-02", down[0]) + + def test_nothing_usable_says_exactly_what_to_do(self): + """R-7.2-3, R-17-5: only when nothing is usable does route say so, with providers, due times + and that the main agent does the task itself meanwhile.""" + self.seed([("muse/beta-1", 12, 11), ("codex/alpha-1", 9, 8)]) + self.down("muse", "codex") + r = self.sisi("route", "--kind", "impl", "--difficulty", "2", env=self.env()) + self.assertEqual(r.returncode, 1) + self.assertIn("no usable worker", r.stdout) + self.assertIn("2099-01-02", r.stdout) + self.assertIn("main agent does this task itself", r.stdout) + + +class NotesAndLimitsTests(RouteCase): + def test_notes_show_for_chosen_and_passed_over_workers(self): + """R-7.2-1, R-17-5: a note appears in plain route output for the chosen worker and for a + passed-over worker it applies to, framed as information; --remove deletes it.""" + self.seed_real_shape() + self.sisi("workers", "note", "wk-fast", "reasoning effort defaults to maximum; set it lower", + "--why", "owner, 2026-11", env=self.env()) + self.sisi("workers", "note", "beta", "ask before using a flag that turns off approvals", + "--why", "owner", env=self.env()) + r = self.sisi("route", "--kind", "impl", "--difficulty", "2", env=self.env()) + self.assertEqual(r.returncode, 0, r.stdout) + self.assertTrue(r.stdout.splitlines()[0].startswith("wk-"), r.stdout) + notes = [l for l in r.stdout.splitlines() if l.startswith("note")] + text = "\n".join(notes) + self.assertIn("set it lower", text) + self.assertIn("information, not an instruction", text) + self.assertIn("passed over", text) + self.assertIn("approvals", text) + listing = self.sisi("workers", env=self.env()) + self.assertIn("set it lower", listing.stdout) + self.sisi("workers", "note", "wk-fast", "--remove", env=self.env()) + after = self.sisi("route", "--kind", "impl", "--difficulty", "2", env=self.env()) + self.assertNotIn("set it lower", after.stdout) + + def test_only_limits_a_provider_to_named_models(self): + """R-7.2-1, R-7.3-3: a newly discovered, cheap model on a limited provider is not routed.""" + self.seed([("muse/beta-1", 9, 9)], difficulty=1) + self.sisi("workers", "fact", "muse/beta-2", "--price", "0.01", "--source", "fixture", env=self.env()) + free = self.sisi("route", "--kind", "impl", "--difficulty", "1", env=self.env()) + self.assertEqual(free.stdout.splitlines()[0], "muse/beta-2", free.stdout) + r = self.sisi("workers", "only", "muse", "beta-1", "--why", "fixture limit", env=self.env()) + self.assertEqual(r.returncode, 0, r.stderr) + got = self.sisi("route", "--kind", "impl", "--difficulty", "1", "--explain", env=self.env()) + self.assertEqual(got.stdout.splitlines()[0], "muse/beta-1", got.stdout) + self.assertIn("fixture limit", got.stdout) + self.assertIn("Only on muse", self.sisi("workers", env=self.env()).stdout) + self.sisi("workers", "only", "muse", "--remove", env=self.env()) + back = self.sisi("route", "--kind", "impl", "--difficulty", "1", env=self.env()) + self.assertEqual(back.stdout.splitlines()[0], "muse/beta-2") + + +class StoreHistoryTests(RouteCase): + def test_worker_files_are_committed_and_unrelated_files_are_not(self): + """R-7.2-3, R-3.2-4: ledger, facts, notes, limits and availability written by a command are + committed in the data folder's history, one small commit each, and a user's own uncommitted + file is neither committed nor touched.""" + from sisi import pdata + pdata.ensure() + mine = os.path.join(self.data, "oracle.md") + open(mine, "w").write("mine\n") + pdata.commit("test: tracked file", ["oracle.md"], strict=True) + open(mine, "a").write("edited, not committed\n") + for args in (("delegate", "judge", "--worker", "wk-fast", "--type", "read", "--difficulty", "1", + "--outcome", "accepted", "--check", "read", "--project", "proj"), + ("workers", "note", "wk-fast", "a standing fact", "--why", "fixture"), + ("workers", "only", "muse", "beta-1", "--why", "fixture"), + ("workers", "down", "muse", "--reason", "limit", "--until", "2099-01-02"), + ("workers", "fact", "wk-fast", "--price", "1", "--source", "fixture")): + r = self.sisi(*args) + self.assertEqual(r.returncode, 0, r.stderr) + status = subprocess.run(["git", "status", "--porcelain"], cwd=self.data, capture_output=True, + text=True).stdout.splitlines() + self.assertEqual([l.strip() for l in status], ["M oracle.md"], status) + log = subprocess.run(["git", "log", "--format=%s"], cwd=self.data, capture_output=True, text=True).stdout + self.assertGreaterEqual(log.count("worker data changed"), 5, log) + shown = subprocess.run(["git", "show", "--stat", "--format=", "HEAD~1"], cwd=self.data, + capture_output=True, text=True).stdout + self.assertNotIn("oracle.md", shown) + + +class ImportWarningTests(RouteCase): + def test_import_of_a_file_without_ledger_rows_warns(self): + """R-7.2-3: importing the wrong file is said out loud, not reported as a quiet success.""" + src = os.path.join(self.tmp, "not-a-ledger.jsonl") + open(src, "w").write('{"hello": "world"}\nnot json\n') + r = self.sisi("workers", "import", src, env=self.env()) + self.assertIn("contains no ledger rows", r.stderr) + good = os.path.join(self.tmp, "ledger.jsonl") + open(good, "w").write(json.dumps({"kind": "attempt", "id": "a1", "ts": 1760000000, "worker": "wk-x", + "type": "read", "difficulty": 1, "outcome": "accepted"}) + "\n") + ok = self.sisi("workers", "import", good, env=self.env()) + self.assertNotIn("no ledger rows", ok.stderr) + + +class SessionStartTests(RouteCase): + def tick(self, sid, model="mystery-9", source="startup"): + return self.sisi("tick", stdin=json.dumps({"session_id": sid, "cwd": self.proj, "source": source, + "model": model})) + + def test_unknown_standing_says_nothing_about_delegating(self): + """R-7.1-1, R-17-3: with no facts and an unknown main model, session start argues + neither for nor against delegating; at most one line asks for facts, once per session.""" + r = self.tick("s-unk") + self.assertEqual(r.returncode, 0, r.stderr) + low = r.stdout.lower() + for bad in ("yourself", "rather than delegating", "on a guess", "do the work"): + self.assertNotIn(bad, low) + sisi_lines = [l for l in r.stdout.splitlines() if "worker facts" in l] + self.assertEqual(len(sisi_lines), 1, r.stdout) + again = self.tick("s-unk", source="resume") + self.assertNotIn("worker facts", again.stdout) + + def test_unknown_standing_with_a_recorded_ledger(self): + """The same holds with a thick ledger and no discovered tools.""" + self.seed_real_shape() + r = self.sisi("tick", stdin=json.dumps({"session_id": "s-led", "cwd": self.proj, "source": "startup", + "model": "mystery-9"}), env=dict(PATH="")) + self.assertNotIn("yourself", r.stdout.lower()) + self.assertNotIn("rather than", r.stdout.lower()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_workers.py b/tests/test_workers.py index 770cd8f..e0c096c 100644 --- a/tests/test_workers.py +++ b/tests/test_workers.py @@ -214,7 +214,7 @@ class SessionModelTests(WorkerCase): def test_tick_weak_line_names_stronger(self): self.seed_strength({"beta-1": 95, "alpha-1": 60}) r = self.tick({"session_id": "weak-1", "cwd": self.proj, "source": "startup", "model": "alpha-1"}) - self.assertIn("do the work yourself", r.stdout) + self.assertNotIn("do the work yourself", r.stdout) # a lower standing never argues against orchestrating self.assertIn("beta-1", r.stdout) def test_tick_subagent_gets_no_delegation_line(self): @@ -226,7 +226,7 @@ class SessionModelTests(WorkerCase): def test_tick_unknown_strength_says_so(self): r = self.tick({"session_id": "unk-1", "cwd": self.proj, "source": "startup", "model": "mystery-9"}) - self.assertIn("unknown", r.stdout.lower()) + self.assertNotIn("yourself", r.stdout.lower()) # unknown standing says nothing about delegating class RoutingPropertyTests(unittest.TestCase):