diff --git a/README.md b/README.md index cdf0396..d6f4ffe 100644 --- a/README.md +++ b/README.md @@ -83,15 +83,16 @@ its limits are. | `sisi done --goal … --check … [--check …] --next …` | Record what done means and what comes next; nothing starts before | | `sisi done --pass N "…"` / `--fail N "…"` | Give a check its verdict and evidence; `sisi done` alone shows it | | `sisi fault ""` / `--started\|--blocked\|--fixed N "…"` | Record an open fault in this project, start a fix, name a blocker, or close it; `sisi fault` alone lists them | -| `sisi pick routine\|ordinary\|hard [--review-of WORKER] [--not WORKER]` | The wheel gives one worker; a review goes to a different maker | +| `sisi pick routine\|ordinary\|hard [--review-of WORKER] [--not WORKER] [--limit MINUTES] [--branch REF]` | The wheel gives one worker; a review goes to a different maker. `--limit` sets this delegation's lateness limit (default `worker_minutes`) and `--branch` names the branch whose last commit shows its progress; picks of one worker are matched to its delegations in order. A job past twice its limit becomes a late-worker fault in the session that started it (only that session is stopped by it; `sisi fault --fixed N "…"` from any other session clears it) | | `sisi retro` | Print what happened in this piece of work, to set against the objective | | `sisi retro --gap … --cause … --improve … --term T [--scope user]` | Record the gap and the term of the objective it fell short on; the improvement is a rule at once | | `sisi retro --no-gap … --term T --better …` | Nothing fell short, but work can always be done better: name the term and the one concrete thing that would have scored better (recorded with the retro; it becomes a rule only if it recurs, when the rules are organized) | | `sisi retro --later …` | The work is not finished yet | -| `sisi learn [--project] "…"` | The person's own words become a rule at once | +| `sisi learn [--project] "…" [--means "…"]` | The person's own words become a rule at once, tagged `[owner]` only when they appear in the person's recent messages in this session. `--means` adds, in the same undoable step, one line saying how the agent will apply it | | `sisi rules` / `sisi rules organize [--record FILE]` / `sisi rules revert` | See the learned rules; have a worker organize them; undo the last rule change made with `learn`, a retro or `organize`, in the user list or a project's `.sisi/rules.md` (not the one-time move of old rules; a second `revert` re-applies what the first undid; it declines, changing nothing, when the project file changed since or its folder moved or is gone) | | `sisi models` / `sisi models research [--record FILE]` | The workers table (the shared baseline table ships with sisi in `canon/models.md`); have a worker rebuild it | | `sisi judge WORKER good\|bad "…" [--minutes N] [--newest]` | How a delegation went; the minutes are measured from the pick's delegation (or `--minutes N`) and make the wheel favour faster workers. With several of one worker's jobs open, the oldest is judged first, `--newest` the newest | +| `sisi judge WORKER extend MINUTES "" [--newest]` | Give a late job more time instead of judging it: the job that is past its limit (past twice it first, else past once, else the oldest) gets MINUTES more from now, and its late fault clears | | `sisi direct "…"` | Allow more direct tool calls this turn, with the reason | ## Where things live @@ -125,7 +126,7 @@ Rules live at three levels: Releases live in `$SISI_LIB`, else `~/.local/lib/sisi`. Settings go under `"core"` in `config.json` in your store: `gate`, `meter`, `direct_calls` (8), -`direct_extension` (8), `rules_lines` (30), `rules_chars` (4000), `organize_after` (8), `research_days` (7), `worker_minutes` (15), +`direct_extension` (8), `rules_lines` (30), `rules_chars` (4000), `organize_after` (8), `research_days` (7), `worker_minutes` (90: a delegation is late after this many minutes, or its own `--limit`), `shell_workers` (false), `retro_minutes` (5: work that passed every check, delegated nothing and took less than this many minutes from `sisi done` closes without a retro), `disk_free_percent` (20), `disk_drop_percent` (5), `checkouts` (8; setting any of these three to 0 turns that tripwire off). Workers are started with the host's own delegation tool, so by default a shell command that starts a worker (`opencode`, `muse`, `agy`: the first word of a command line in your models table) is diff --git a/sisi/faults.py b/sisi/faults.py index b997451..25dc24f 100644 --- a/sisi/faults.py +++ b/sisi/faults.py @@ -8,7 +8,8 @@ BLOCK = 'sisi: open fault(s) with no fix started and no blocker named: %s. Start _path = lambda cwd=None: os.path.join(store.STATE, "core-faults", store.project_key(cwd) + ".json") _gb = lambda b: "%d GB" % round(b / 1e9) if b >= 1e9 else "%.1f GB" % (b / 1e9) _safe = lambda s: str(s).encode("utf-8", "replace").decode("utf-8") -lines = lambda cwd=None: [_fmt(f) for f in _load(_path(cwd))[0]["items"]] +_mine = lambda f, sid: not f.get("kind", "").startswith("late:") or bool(sid) and f["kind"].startswith("late:%s:" % sid[:8]) # a late fault belongs to the session that started the job +lines = lambda cwd=None, sid="": [_fmt(f) for f in _load(_path(cwd))[0]["items"] if _mine(f, sid)] def _load(p): empty = {"next": 1, "items": []} @@ -30,8 +31,8 @@ def _fmt(f): age = "%ds" % s if s < 60 else "%dm" % (s // 60) if s < 3600 else "%dh" % (s // 3600) if s < 86400 else "%dd" % (s // 86400) return "#%d [%s, %s] %s%s" % (f["id"], f["state"], age, _safe(f["text"]), " — " + _safe(f["note"]) if f.get("note") else "") -def gate(cwd=None): - opened = [f for f in _load(_path(cwd))[0]["items"] if f["state"] == "open"] +def gate(cwd=None, sid=""): + opened = [f for f in _load(_path(cwd))[0]["items"] if f["state"] == "open" and _mine(f, sid)] return BLOCK % "; ".join("#%d %s" % (f["id"], _safe(f["text"])) for f in opened) if opened else "" def add(cwd, text, kind="", flag="", fid=0): @@ -44,8 +45,8 @@ def add(cwd, text, kind="", flag="", fid=0): hit = next((f for f in doc["items"] if f["id"] == fid), None) if not hit: return None - if hit.get("kind", "").startswith("late:"): - raise OSError('sisi fault: #%d is a late worker fault; run `sisi judge WORKER good|bad ""` or `sisi judge WORKER extend MINUTES ""`.' % fid) + if hit.get("kind", "").startswith("late:") and (flag != "--fixed" or hit["kind"].startswith("late:%s:" % (store.current_session(cwd) or "")[:8])): + raise OSError('#%d is a late worker fault; run `sisi judge WORKER good|bad ""` or `sisi judge WORKER extend MINUTES ""`.' % fid) doc["items"] = [f for f in doc["items"] if f["id"] != fid] if flag == "--fixed" else doc["items"] hit.update(state=flag[2:], note=text) elif kind and any(f.get("kind") == kind for f in doc["items"]): @@ -82,7 +83,7 @@ def _checkouts(cwd): except OSError: return 0 -def check(cwd, start_free=None): +def check(cwd, start_free=None, sid=""): cfg, hits, pos = store.config(), [], lambda k: type(cfg[k]) in (int, float) and cfg[k] > 0 try: st = os.statvfs(cwd) if pos("disk_free_percent") or (pos("disk_drop_percent") and type(start_free) in (int, float)) else None @@ -102,7 +103,7 @@ def check(cwd, start_free=None): add(cwd, text, kind) except OSError: unsaved.append("[open] " + text) - ls = ([] if err else lines(cwd)) + unsaved + ls = ([] if err else lines(cwd, sid)) + unsaved return "\n".join(([err] if err else []) + ([HEAD] + ls[:10] + (["and %d more: sisi fault" % (len(ls) - 10)] if len(ls) > 10 else []) if ls else [])) def run(args, cwd=None): diff --git a/sisi/hooks.py b/sisi/hooks.py index fce2d59..b40c988 100644 --- a/sisi/hooks.py +++ b/sisi/hooks.py @@ -99,11 +99,11 @@ def _begin(state, cwd): pass -def _faults(cwd, gate=False, free=None): +def _faults(cwd, gate=False, free=None, sid=""): if gate and not os.path.lexists(os.path.join(store.STATE, "core-faults", store.project_key(cwd) + ".json")): return "" from . import faults - return faults.gate(cwd) if gate else faults.check(cwd, free) + return faults.gate(cwd, sid) if gate else faults.check(cwd, free, sid) def tick(p): @@ -118,7 +118,7 @@ def tick(p): store.append(env, "export SISI_SESSION_ID=%s" % sid, once=True) # so `sisi retro` knows its session if not os.path.exists(os.path.join(store.DATA, "generated", "core.md")): rules.build_rulebook() - text = "\n".join(x for x in (rules.project_text(cwd), rules.due(cwd, claim=True), models.stale(), "" if worker else _faults(cwd, False, free)) if x) + text = "\n".join(x for x in (rules.project_text(cwd), rules.due(cwd, claim=True), models.stale(), "" if worker else _faults(cwd, False, free, sid)) if x) if text: print(text) return 0 @@ -141,13 +141,13 @@ def prompt(p): if not s.get("prompts") and WORKER.search(p["prompt"][:2000]): s["worker"] = True worker, free = worker or bool(s.get("worker")), s.get("free_bytes") - worker or not p["prompt"].strip() or s.update(said=(s.get("said", []) + [" ".join(p["prompt"].split())[:8000]])[-20:]) # the person's own words + worker or not p["prompt"].strip() or WORKER.search(p["prompt"][:2000]) or s.update(said=((s["said"] if isinstance(s.get("said"), list) else []) + [" ".join(p["prompt"].split())[:8000]])[-20:]) # the person's own words s["prompts"] = s.get("prompts", 0) + 1 s.get("prompts_since") or s.update(began=time.time()) # the first request of a piece of work s["prompts_since"] = s.get("prompts_since", 0) + 1 s["direct"], s["extra"], s["blocks"] = 0, 0, 0 not worker and (models.sync_late(s, cwd, sid), late1 := models.late(s, 1)) - not worker and (text := "\n".join(x for x in [_faults(cwd, False, free)] + _late_lines(late1, cwd) if x)) and print(text) + not worker and (text := "\n".join(x for x in [_faults(cwd, False, free, sid)] + _late_lines(late1, cwd) if x)) and print(text) return 0 @@ -218,7 +218,7 @@ def gate(p, for_subagent=False): if s.get("worker"): return 0 models.sync_late(s, cwd, sid) - open_f, starts = _faults(cwd, True), s["starts"] if isinstance(s.get("starts"), dict) else {} + open_f, starts = _faults(cwd, True, None, sid), s["starts"] if isinstance(s.get("starts"), dict) else {} seen = [x for x in (s["reminded"] if isinstance(s.get("reminded"), list) else []) if isinstance(x, list) and len(x) == 2 and x[1] in (starts.get(x[0]) if isinstance(starts.get(x[0]), list) else ())] late = models.overdue({"starts": {w: [t for t in v if [w, t] not in seen] for w, v in starts.items() if isinstance(v, list)}, "meta": s.get("meta")}) diff --git a/sisi/models.py b/sisi/models.py index d650709..90b3c76 100644 --- a/sisi/models.py +++ b/sisi/models.py @@ -165,7 +165,7 @@ def claim(s, text, segment=False): t, starts = time.time(), (s["starts"] if isinstance(s.get("starts"), dict) else {}) starts[name] = (starts[name] if isinstance(starts.get(name), list) else []) + [t] s["starts"] = starts # `sisi judge` times the job from here - if isinstance(s.get("pending"), dict) and isinstance(meta := s["pending"].pop(name, None), dict): + if isinstance(s.get("pending"), dict) and isinstance(q := s["pending"].get(name), list) and q and isinstance(meta := q.pop(0), dict): s["meta"] = {**(s["meta"] if isinstance(s.get("meta"), dict) else {}), "%s %r" % (name, t): meta} s.setdefault("workers_since", []).append(name) return True @@ -276,7 +276,8 @@ def pick(args, cwd=None, rand=None): if sid: with store.session(sid) as s: s.setdefault("picked", []).append(w := short(r[0])) - if limit is not None or branch is not None: s["pending"] = {**(s["pending"] if isinstance(s.get("pending"), dict) else {}), w: {"limit": limit, "branch": branch}} + q = s["pending"] if isinstance(s.get("pending"), dict) else {} + s["pending"] = {**q, w: (q[w] if isinstance(q.get(w), list) else []) + [{"limit": limit, "branch": branch}]} # one entry per pick, claimed in order print("worker: %s (model id: %s)\nstart it with the host's delegation tool; one pick buys one delegation" % (r[0], short(r[0]))) if store.config()["shell_workers"] or not command(r): print("how to call it: " + r[1]) @@ -363,6 +364,8 @@ def judge(args, cwd=None): with store.session(sid) as s: starts = s["starts"].get(wkey) if isinstance(s.get("starts"), dict) else None cand = (starts.pop(-1 if newest else 0) if not ext else starts[-1 if newest else 0]) if isinstance(starts, list) and starts else None + if ext and not newest: # the job that is late, not just the oldest open one + cand = next((min(t for w, t, *_ in l if w == wkey) for l in (late(s, 2), late(s, 1)) if any(w == wkey for w, *_ in l)), cand) ok_t = type(cand) in (int, float) and math.isfinite(cand) and cand <= now if ext: if not ok_t: return print("sisi judge: no open job for %s." % args[0]) or 1 diff --git a/sisi/retro.py b/sisi/retro.py index bf64daf..714a314 100644 --- a/sisi/retro.py +++ b/sisi/retro.py @@ -45,7 +45,7 @@ def facts(state, cwd): "evidence (measured): %d check(s) passed, %d failed" % (n["checks_pass"], n["checks_fail"])] + d[1:-1] out += ["value (judged): did the person get what they wanted? changed: %d commit(s), %d file(s) uncommitted" % (n["commits"], len(dirty))] from . import faults - fs = faults.lines(cwd) + fs = faults.lines(cwd, store.current_session(cwd)) return out + d[:1] + d[1:][-1:] + (["open faults (%d):" % len(fs)] + [" " + l for l in fs] if fs else []) + ["learning (measured): last 10 pieces of work named: %s" % (named or "none yet")] diff --git a/sisi/rules.py b/sisi/rules.py index 51c39ed..9fd2fe3 100644 --- a/sisi/rules.py +++ b/sisi/rules.py @@ -182,20 +182,20 @@ def _commit(msg, *paths, snap=None): raise OSError("store git commit failed") -def add(text, scope, source, cwd=None, log=None): +def add(text, scope, source, cwd=None, log=None, means=""): """Put one rule in force; returns (line, warning). Raises OSError before writing when the list cannot be written.""" - line = "- %s [%s %s]" % (" ".join(str(text).split()), source, time.strftime("%Y-%m-%d")) + line, *more = ["- %s [%s %s]" % (" ".join(str(t).split()), src, time.strftime("%Y-%m-%d")) for t, src in ((text, source), (means, "agent reading")) if t] # one commit holds both dest = path(scope, cwd) scope == PROJECT and not dest and _check_writable(dest) with store.lock(dest if scope == PROJECT else "user"): if scope == USER: - store.append(dest, line) + [store.append(dest, l) for l in [line, *more]] else: _check_writable(dest) msg = _move(dest, _legacy(cwd)) msg and print(msg) before = _text(dest) - after = _append(before, [line]) + after = _append(before, [line, *more]) store.write(dest, after) note(dest) try: @@ -305,7 +305,7 @@ def organize_brief(cwd): def organize_record(answer_file, cwd): """Replace both lists with the worker's answer. Returns why not, or None when it is done.""" cfg = store.config() - body, *flags = re.split(r"(?m)^## flags[ \t]*$", store.read(answer_file), 1) # the flags are for the person, not rules + body, *flags = re.split(r"(?im)^##\s*flags\s*$", store.read(answer_file), 1) # the flags are for the person, not rules flags = "".join(flags) parts = re.split(r"(?m)^## (user|project)[ \t]*$", body) got = {parts[i]: [l.rstrip() for l in parts[i + 1].splitlines() if l.startswith("- ")] @@ -466,8 +466,7 @@ def learn(args, cwd=None): heard = _said(text, cwd) log = os.path.join(store.DATA, "rules", "owner.log") # their exact words are kept, whatever organizing later does to the rule try: - line, warn = add(text, scope, "owner" if heard else "agent, attributed to owner", cwd, (log, "%s %s %s" % (time.strftime("%Y-%m-%d"), scope, " ".join(text.split())))) - means and add(means, scope, "agent reading", cwd) + line, warn = add(text, scope, "owner" if heard else "agent, attributed to owner", cwd, (log, "%s %s %s" % (time.strftime("%Y-%m-%d"), scope, " ".join(text.split()))), means) except OSError as e: print("sisi learn: could not write %s (%s). Nothing was changed, and your words were not kept." % (path(scope, cwd) or cwd or os.getcwd(), e)) return 1 diff --git a/tests/test_core.py b/tests/test_core.py index b88f2ab..0761f06 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -3569,6 +3569,85 @@ cli.main(["tick"]) self.assertEqual(self.sisi("judge", "sonnet", verdict, why, sid="s1")[0], 0) self.assertNotIn("has run", self.hook("gate")[1]) + def _late_job(self, sid, limit, mins_ago, w="sonnet"): + self.assertEqual((self.sisi("pick", "hard", "--limit", str(limit), sid=sid)[0], self.tool("Agent", sid=sid, tool_input={"model": w})[0]), (0, 0)) + path = os.path.join(self.tmp, "state", "core-sessions", sid + ".json") + with open(path, "r+") as f: + st = json.load(f) + old, t = st["starts"][w][-1], time.time() - mins_ago * 60 + st["starts"][w][-1] = t + st["meta"]["%s %r" % (w, t)] = st["meta"].pop("%s %r" % (w, old)) + f.seek(0), f.truncate(), json.dump(st, f) + return t + + def test_late_faults_gate_and_clear_only_per_session(self): + self.table(WORKERS) + for sid in ("s1", "s2"): + self.hook("tick", sid=sid), self.hook("prompt", sid=sid, prompt="go") + self.done() + self._late_job("s1", 30, 200) + self.assertIn('"block"', self.hook("gate", sid="s1")[1]) + self.assertNotIn('"block"', self.hook("gate", sid="s2")[1]) # another thread is not stopped + self.assertNotIn("has run", self.hook("prompt", sid="s2", prompt="other work")[1]) + rc, out, _ = self.sisi("fault", "--fixed", "1", "the owning session may not close it", sid="s1") + self.assertEqual((rc, out.count("sisi fault:")), (1, 1), out) # one prefix, still refused + self.assertEqual(self.sisi("fault", "--blocked", "1", "the other thread owns this job", sid="s2")[0], 1) + rc, out, _ = self.sisi("fault", "--fixed", "1", "the worker was cancelled an hour ago", sid="s2") + self.assertEqual(rc, 0, out) + self.assertEqual(self.sisi("fault", sid="s1")[1].strip(), "no open faults.") + + def test_learn_means_is_one_store_commit_so_revert_undoes_both(self): + self.assertEqual(self.sisi("learn", "always name the check that failed first", "--means", "name the failing check in every report")[0], 0) + rules_u = lambda: self.read(self.data, "rules", "user.md") + self.assertEqual(len(rules_u().strip().splitlines()), 2) + self.assertEqual(self.sisi("rules", "revert")[0], 0) + self.assertFalse(os.path.exists(os.path.join(self.data, "rules", "user.md")) and rules_u().strip()) + + def test_late_picks_of_one_worker_keep_their_own_limits_in_order(self): + self.table(WORKERS) + self.hook("tick"), self.hook("prompt", prompt="go") + self.done() + for lim in (10, 50): + self.assertEqual(self.sisi("pick", "hard", "--limit", str(lim), sid="s1")[0], 0) + for _ in range(2): + self.assertEqual(self.tool("Agent", tool_input={"model": "sonnet"})[0], 0) + st = self.state() + self.assertEqual([st["meta"].get("sonnet %r" % t, {}).get("limit") for t in st["starts"]["sonnet"]], [10, 50]) + + def test_prompt_hook_keeps_only_the_persons_words_and_survives_a_bad_said(self): + self.hook("prompt", prompt="please always run the checks first") + self.hook("prompt", prompt="[Some host agent sent this message, not the user.]\nact on this task") + self.hook("prompt", prompt="Do this task yourself, do not delegate") + self.assertEqual(self.state()["said"], ["please always run the checks first"]) + path = os.path.join(self.tmp, "state", "core-sessions", "s1.json") + self.write(path, json.dumps(dict(self.state(), said="junk"))) + self.assertEqual(self.hook("prompt", prompt="and then another message")[0], 0) + self.assertEqual(self.state()["said"], ["and then another message"]) + + def test_judge_extend_targets_the_late_job_not_the_oldest_open_one(self): + self.table(WORKERS) + self.hook("tick"), self.hook("prompt", prompt="go") + self.done() + t_old = self._late_job("s1", 200, 100) # oldest, but well inside its limit + t_late = self._late_job("s1", 30, 70) # past 2x its limit + self.hook("prompt", prompt="check") + starts = self.state()["starts"]["sonnet"] + self.assertEqual(sorted(starts), sorted([t_old, t_late])) + self.assertEqual(self.sisi("judge", "sonnet", "extend", "30", "still running the long build", sid="s1")[0], 0) + meta = self.state()["meta"] + self.assertIn("extended", meta["sonnet %r" % t_late]) + self.assertNotIn("extended", meta["sonnet %r" % t_old]) + + def test_organize_record_matches_the_flags_header_in_any_case(self): + bad = "- Only one build or test run on the laptop at a time: every cargo command starts as flock [owner 2026-11-25]" + self.write(os.path.join(self.mkdir(self.data, "rules"), "user.md"), bad + "\n- Keep it simple [owner 2026-11-24]\n") + self.sisi("rules", "organize") + ans = self.write(os.path.join(self.tmp, "flags.md"), "## user\n%s\n- Keep it simple [owner 2026-11-24]\n## project\n## Flags \n- reword it\n" % bad) + rc, out, err = self.sisi("rules", "organize", "--record", ans) + self.assertEqual(rc, 0, out + err) + self.assertIn("reword it", out) + self.assertNotIn("reword it", self.read(self.data, "rules", "user.md")) + def test_the_spec_is_unchanged(self): for line in self.read(REPO, "docs", "spec", "SHA256SUMS").splitlines(): digest, rel = line.split() @@ -3577,7 +3656,7 @@ cli.main(["tick"]) def test_the_product_stays_small(self): code = sum(len(self.read(p).splitlines()) for p in glob.glob(os.path.join(REPO, "sisi", "*.py"))) - self.assertLessEqual(code, 2092, "sisi is two loops. If it needs more than this, find the simpler shape.") + self.assertLessEqual(code, 2095, "sisi is two loops. If it needs more than this, find the simpler shape.") rulebook = self.read(REPO, "canon", "core.md") self.assertLess(len(rulebook.splitlines()), 137) self.assertLessEqual(len(rulebook), 10530)