From 848560a97577450122fe676630db5a2239d69c79 Mon Sep 17 00:00:00 2001 From: sisi Date: Wed, 25 Nov 2026 22:16:18 -0700 Subject: [PATCH] learn: owner tag only for words found in the person's recent messages; agent-attributed tag otherwise; --means line; organize flags concurrency smells and doubtful owner lines --- sisi/hooks.py | 1 + sisi/rules.py | 50 ++++++++++++++++++++++++++++++++++++++-------- tests/test_core.py | 47 ++++++++++++++++++++++++++++++++++++++----- 3 files changed, 85 insertions(+), 13 deletions(-) diff --git a/sisi/hooks.py b/sisi/hooks.py index f658ea1..38f29f2 100644 --- a/sisi/hooks.py +++ b/sisi/hooks.py @@ -133,6 +133,7 @@ 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 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 diff --git a/sisi/rules.py b/sisi/rules.py index e0ed870..51c39ed 100644 --- a/sisi/rules.py +++ b/sisi/rules.py @@ -10,8 +10,10 @@ USER, PROJECT = "user", "project" OWNER = re.compile(r"\[owner\b[^\]]*\]") _owner, _retro = lambda l: bool(OWNER.search(l)), lambda ls: [l for l in ls if not _owner(l)] _snap = lambda u, p: hashlib.sha1(("\n".join(u) + "\0" + "\n".join(p)).encode()).hexdigest()[:16] -HEAD_USER = "## Learned here\n\nAdded by retros and by the person. These add to the rules above and never relax them.\n" -HEAD_PROJECT = "sisi: learned in this project (these add to the rules and never relax them):" +_TAGS = " [owner] lines are the person's words; [agent ...] lines are an agent's reading, which a later owner statement or a measurement overrides." +HEAD_USER = "## Learned here\n\nAdded by retros and by the person. These add to the rules above and never relax them." + _TAGS + "\n" +HEAD_PROJECT = "sisi: learned in this project (these add to the rules and never relax them)." + _TAGS +SMELL = re.compile(r"(?i)\bone (?:build|test|run|worker|job)\b.{0,60}\bat a time|\bflock\b|\b(?:shared?|one)\b.{0,30}\bbuild (?:folder|dir)") ORGANIZE = """You are a worker. Do this task yourself; do not delegate it further. @@ -28,7 +30,11 @@ Rewrite both lists so they serve that objective best: - A rule seen in more than one project, or about how the person wants to be worked with, belongs in the first list. A rule about this project's own code belongs in the second. - Lines marked [owner ...] are the person's own words: copy every one of them verbatim, unchanged by even - one character (you may reorder them). Only [retro ...] lines may be merged, reworded or dropped. + one character (you may reorder them). Only the other lines ([retro ...], [agent ...]) may be merged, reworded or dropped. +- Flag, but do not change, any [owner ...] line whose text does not read as the person's own words (a paraphrase, an + agent's conclusion, third person), and any rule that limits builds, tests or workers to one at a time or tells + checkouts to share one build folder. List each under a final `## flags` section with its proposed corrected or + retagged form, for the person to accept. - Keep the [source date] mark at the end of every line. - A `better` that recurs across retros has earned a rule: add it, worded as an instruction, marked [retro ]. - Non-owner ([retro ...]) lines in each list: at most %(lines)d lines and %(chars)d characters. Fewer is better. @@ -38,6 +44,8 @@ Answer with exactly this shape and nothing else: - ... ## project - ... +## flags +- ... (only if there are any) === The first list now (all projects) === %(user)s @@ -45,6 +53,9 @@ Answer with exactly this shape and nothing else: === The second list now (project "%(name)s") === %(project)s +=== Flagged for the person (likely wrong; propose a fix) === +%(flagged)s + === What recent retros found, newest last (context only) === %(retros)s """ @@ -286,6 +297,7 @@ def organize_brief(cwd): return ORGANIZE % { "name": os.path.basename(store.project_root(cwd)), "objective": objective(), "lines": cfg["rules_lines"], "chars": cfg["rules_chars"], + "flagged": "\n".join(l for l in u + p if SMELL.search(l)) or "(none)", "user": "\n".join(u) or "(none)", "project": "\n".join(p) or "(none)", "retros": "\n".join(store.read(store.data("retro.jsonl")).splitlines()[-40:]) or "(none)"} @@ -293,7 +305,9 @@ 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() - parts = re.split(r"(?m)^## (user|project)[ \t]*$", store.read(answer_file)) + body, *flags = re.split(r"(?m)^## flags[ \t]*$", 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("- ")] for i in range(1, len(parts) - 1, 2)} if set(got) != {USER, PROJECT}: @@ -350,6 +364,7 @@ def organize_record(answer_file, cwd): build_rulebook() for scope in (USER, PROJECT): print("%s rules: %d lines (were %d)" % (scope, len(got[scope]), len(had[scope]))) + flags.strip() and print("Flagged for you (not changed):" + flags.rstrip()) return None @@ -425,18 +440,37 @@ def run(args, cwd=None): return 1 if why else 0 +_norm = lambda t: " ".join(re.sub(r"[\W_]+", " ", t.lower()).split()) + + +def _said(words, cwd): + """True when the words are a quotation of one of the person's recent messages in this session.""" + try: + sid = store.current_session(cwd) + said = json.loads(store.read(store._session_path(sid)) or "{}").get("said") if sid else None + except (OSError, ValueError, AttributeError): + return False + return isinstance(said, list) and any(" %s " % _norm(words) in " %s " % _norm(m) for m in said if isinstance(m, str)) + + def learn(args, cwd=None): - """`sisi learn [--project] TEXT`: the person's own words become a rule at once.""" + """`sisi learn [--project] "" [--means ""]`: a rule at once; the + owner tag only when the words are found in the person's recent messages, else the agent's own tag.""" + i = args.index("--means") if "--means" in args else len(args) + args, means = list(args[:i]), " ".join(args[i + 1:]) scope = PROJECT if "--project" in args else USER text = " ".join(a for a in args if a != "--project").strip() - if len(text.split()) < 3: - print('usage: sisi learn [--project] ""') + if len(text.split()) < 3 or (means and len(means.split()) < 3): + print('usage: sisi learn [--project] "" [--means ""]') return 1 + 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", cwd, (log, "%s %s %s" % (time.strftime("%Y-%m-%d"), scope, " ".join(text.split())))) + 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) 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 + heard or print("sisi learn: these words were not found in the person's recent messages, so the rule carries the weaker tag [agent, attributed to owner]; a later owner statement or a measurement overrides it.") print(warn or "in force from the next session: %s" % line) return 0 diff --git a/tests/test_core.py b/tests/test_core.py index d3a4b9e..adce61b 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -973,7 +973,7 @@ class Core(unittest.TestCase): self.assertFalse(os.path.exists(old_b)) rc2, out2, _ = self.sisi("rules", "revert") self.assertEqual(rc2, 0, out2) - self.assertIn("undone: rule added (user, owner)", out2) + self.assertIn("undone: rule added (user,", out2) self.assertFalse(os.path.exists(old_b)) self.assertEqual(self.read(beta, ".sisi", "rules.md"), rows) self.assertFalse(os.path.exists(os.path.join(self.data, "rules", "user.md"))) @@ -1348,7 +1348,7 @@ cli.main(["tick"]) rc, out, err = self.sisi("learn", "--project", "Rule saved even when store rules dir is read only") self.assertEqual((rc, err), (0, ""), out) self.assertIn("Rule saved even when store rules dir is read only", self.read(self.proj, ".sisi", "rules.md")) - self.assertEqual(len(out.strip().splitlines()), 1, out) + self.assertEqual(len(out.strip().splitlines()), 2, out) self.assertIn("the rule is in", out) self.assertIn("could not be recorded for undo", out) self.assertNotIn("Nothing was changed", out) @@ -1359,7 +1359,7 @@ cli.main(["tick"]) rc, out, err = self.sisi("learn", "--project", "Project rule while index lock blocks commit") self.assertEqual((rc, err), (0, ""), out) self.assertIn("Project rule while index lock blocks commit", self.read(self.proj, ".sisi", "rules.md")) - self.assertEqual(len(out.strip().splitlines()), 1, out) + self.assertEqual(len(out.strip().splitlines()), 2, out) self.assertIn("could not be recorded for undo", out) os.remove(lock) rc_rev, out_rev, _ = self.sisi("rules", "revert") @@ -1526,7 +1526,8 @@ cli.main(["tick"]) def test_the_models_table_is_researched_recorded_and_goes_stale(self): self.assertIn("no models table yet", self.hook("tick")[1]) - self.sisi("learn", "Only the cheapest models on the shared plan") + self.hook("prompt", prompt="Only the cheapest models on the shared plan") + self.sisi("learn", "Only the cheapest models on the shared plan", sid="s1") brief = self.sisi("models", "research")[1] self.assertIn("Fallback order:", brief) self.assertIn("Only the cheapest models on the shared plan", brief) # the person's words bind the researcher @@ -3451,6 +3452,42 @@ cli.main(["tick"]) self.assertIn("organize", out.lower()) self.assertIn("New rule added while organizer was working", self.read(p_race, ".sisi", "rules.md")) + def test_owner_tag_means_the_persons_own_words(self): + said = "Please, ALWAYS name the check that failed first!" + rc, out, _ = self.sisi("learn", "always name the check that failed first", sid="o1") # no message of the person yet + rules_u = lambda: self.read(self.data, "rules", "user.md") + self.assertEqual(rc, 0, out) + self.assertIn("[agent, attributed to owner", rules_u()) + self.assertNotIn("[owner ", rules_u()) + self.assertIn("not found in the person's recent messages", out) + self.hook("prompt", sid="o1", prompt=said) + self.hook("prompt", sid="w1", prompt="You are a worker. Do this task yourself.\nnever use tabs anywhere") + self.assertEqual(self.sisi("learn", "ALWAYS name the check -- that failed first", sid="o1")[0], 0) + self.assertRegex(rules_u().splitlines()[-1], r"first \[owner \d{4}-\d\d-\d\d\]$") + self.assertEqual(self.sisi("learn", "never use tabs anywhere", sid="w1")[0], 0) # a worker records nothing + self.assertIn("never use tabs anywhere [agent, attributed", rules_u()) + rc, out, _ = self.sisi("learn", "ALWAYS name the check that failed first", "--means", "name the failing check in every report", sid="o1") + last = rules_u().splitlines()[-2:] + self.assertRegex(last[0], r"failed first \[owner \d{4}-\d\d-\d\d\]$") + self.assertRegex(last[1], r"^- name the failing check in every report \[agent reading \d{4}-\d\d-\d\d\]$") + from sisi import rules + self.assertFalse(rules.OWNER.search("- x [agent, attributed to owner 2026-11-25]") or rules.OWNER.search(last[1])) + self.write(os.path.join(self.mkdir(self.proj, ".sisi"), "rules.md"), "- Old plain rule [owner 2026-11-20]\n") # before this change + self.assertIn("- Old plain rule [owner 2026-11-20]", self.sisi("rules")[1]) + + def test_organize_brief_flags_build_limits_for_the_person(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") + brief = self.sisi("rules", "organize")[1] + flagged = brief.split("=== Flagged for the person (likely wrong; propose a fix) ===")[1].split("===")[0] + self.assertIn(bad, flagged) + self.assertNotIn("Keep it simple", flagged) + 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- %s: reword it\n" % (bad, bad[2:])) + 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() @@ -3459,7 +3496,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, 1997, "sisi is two loops. If it needs more than this, find the simpler shape.") + self.assertLessEqual(code, 2040, "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()), 135) self.assertLessEqual(len(rulebook), 9872)