From bbf21ef1781e5598885120c9f0d3961e14774c3f Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Tue, 1 Dec 2026 15:45:21 -0700 Subject: [PATCH] Strict rule placement: every rule names its level; core queue; rules move; level audit; unknown flags refused Co-Authored-By: Claude Opus 5.5 --- README.md | 5 +- canon/core.md | 2 +- sisi/hooks.py | 2 +- sisi/retro.py | 20 ++-- sisi/rules.py | 139 ++++++++++++++++++----- sisi/store.py | 2 +- tests/test_core.py | 188 +++++++++++++++++++++++++------- tests/test_organize_evidence.py | 14 +-- tests/test_problems.py | 6 +- 9 files changed, 291 insertions(+), 87 deletions(-) diff --git a/README.md b/README.md index e7ff190..e492cf7 100644 --- a/README.md +++ b/README.md @@ -87,10 +87,11 @@ its limits are. | `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] [--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 and known problems, to set against the objective | -| `sisi retro --gap … --cause … --improve … --term T --problem N\|"…" [--scope user]` | Record the gap, the term of the objective it fell short on, and the problem (`N` to cite an existing one or words to open a new one); the improvement is a rule at once, and a 2nd miss (3rd citation) opens a fault | +| `sisi retro --gap … --cause … --improve … --term T --problem N\|"…" --level core\|user\|project` | Record the gap, the term of the objective it fell short on, and the problem (`N` to cite an existing one or words to open a new one); the improvement is a rule at once, and a 2nd miss (3rd citation) opens a fault | | `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] "…" [--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 learn --level core\|user\|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 move "" core\|user\|project [--project PATH]` | Move one rule line, verbatim, to another level (core is a queue for the product, never loaded elsewhere); a level is always named, `project` needs a git repo, and organize also audits placement every `audit_after` (12) retros | | `sisi rules` / `sisi rules organize [--record FILE]` / `sisi rules revert` | See the learned rules; have a worker organize them (using known problems, prior attempts, and past drop reasons; an optional `## drops` section can record a reason and matching problem number for any dropped or merged rule, with `none given` recorded when omitted); undo the last rule change made with `learn`, a retro or `organize` (including any drop reasons recorded by that `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`), and each worker that is out with when it is back on the wheel; have a worker rebuild it | | `sisi judge WORKER good\|bad\|out "…" [--minutes N] [--newest]` | How a delegation went (`out` with the provider's own message when it hit a limit: off the wheel for 6 hours, then tried again); 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 | diff --git a/canon/core.md b/canon/core.md index 50f61bf..04ce473 100644 --- a/canon/core.md +++ b/canon/core.md @@ -113,7 +113,7 @@ tests, evidence and completion. When work ends, the lead runs `sisi retro` to see what happened and known problems. Set it against the objective by term: where did work fall short, why, and what instruction prevents it? Record `sisi retro --gap … --cause … --improve … --term T --problem N|""` (`--problem` is required with `--gap` or refused: cite `N` or name a new one; each citation after opening is a miss; at the 2nd miss a fault opens). The improvement becomes a rule at -once: product (every user, in the product), user (how this person works across projects, in their store), or project (`.sisi/rules.md` at root, in git its main checkout's, which may be checked in). Name the root cause, not general +once, at the --level you name: core (every sisi user; queued), user (how this person works across projects), or project (`.sisi/rules.md` at root, in git its main checkout's). Name the root cause, not general advice. Prefer a rule that makes next work do more by itself over a caution; a caution says what stays allowed without asking. Work can always be done better: when nothing fell short, name the one thing that would have scored better (`--no-gap … --term T --better …`). When the person states a lasting preference, record their words at once with `sisi learn`. When session start says diff --git a/sisi/hooks.py b/sisi/hooks.py index a910002..5ef9737 100644 --- a/sisi/hooks.py +++ b/sisi/hooks.py @@ -119,7 +119,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, sid)) if x)) and print(text) + (text := "\n".join(x for x in (rules.project_text(cwd), rules.core_note(cwd), rules.due(cwd, claim=True), models.stale(), "" if worker else _faults(cwd, False, free, sid)) if x)) and print(text) return 0 diff --git a/sisi/retro.py b/sisi/retro.py index 6a8593e..8b3e509 100644 --- a/sisi/retro.py +++ b/sisi/retro.py @@ -6,7 +6,7 @@ from . import rules, store DONE_USAGE = """usage: sisi done --goal "" --check "" [--check ...] \\ --next "" sisi done --pass N "" | --fail N "" sisi done: show it""" -FLAGS = ("--gap", "--cause", "--improve", "--no-gap", "--later", "--scope", "--term", "--better", "--problem") +FLAGS = ("--gap", "--cause", "--improve", "--no-gap", "--later", "--scope", "--level", "--term", "--better", "--problem") TERMS = {"value": "what the person wanted", "evidence": "verified by checks that fit the risk", "time": "elapsed time", "cost": "compute and tool cost", "attention": "the person's attention", "learning": "getting better at the next piece of work"} TERM_HELP = "--term is one of: %s." % ", ".join(TERMS) @@ -14,8 +14,8 @@ clean = store.clean USAGE = """Record one of these: sisi retro --gap "" \\ --cause "" \\ - --improve "" --term TERM --problem N|"..." [--scope user] - Cite an existing problem number N from the list above, or give new words to open one. The improvement becomes a rule at once: in this project, or with --scope user in all your work. + --improve "" --term TERM --problem N|"..." --level core|user|project + Cite an existing problem number N from the list above, or give new words to open one. The improvement becomes a rule at once: --level project: this git repo only; user: all your work; core: queued for the sisi product (never loaded). --scope works as --level. sisi retro --no-gap "" --term TERM \\ --better "" TERM is where the work fell short, or could most have scored better: %s. @@ -210,9 +210,9 @@ def run(args, cwd=None): if not args: return report(sid, cwd) or 0 opt = _options(args) - scope, term, better, problem = [(opt or {}).pop(k, None) for k in ("scope", "term", "better", "problem")] - scope = scope or rules.PROJECT - kind = (None if not opt or scope not in (rules.USER, rules.PROJECT) + scope, level, term, better, problem = [(opt or {}).pop(k, None) for k in ("scope", "level", "term", "better", "problem")] + scope = level or scope + kind = (None if not opt or (scope is not None and scope not in (rules.CORE, rules.USER, rules.PROJECT)) else "later" if set(opt) == {"later"} and _words(opt, "later", 3) else "no-gap" if set(opt) == {"no-gap"} and _words(opt, "no-gap", 5) else "gap" if set(opt) == {"gap", "cause", "improve"} and all(_words(opt, k, 4) for k in opt) else None) @@ -221,6 +221,9 @@ def run(args, cwd=None): print("sisi retro: that is not a retro yet (each part needs a real sentence; an improvement is at most " "400 characters).\n" + USAGE) return 1 + if kind == "gap" and (why := rules.refuse_level(scope, cwd, "sisi retro --gap ...")): + print("sisi retro: " + why) + return 1 if kind != "gap" and problem is not None: print("sisi retro: --problem goes only with --gap.") return 1 @@ -270,8 +273,9 @@ def run(args, cwd=None): print("opened problem %d '%s'." % (prob["num"], prob["name"])) try: added, warn = rules.add(opt["improve"], scope, "retro", cwd) - print(warn or "recorded. In force from the next session%s: %s" % ( - " in every project" if scope == rules.USER else " in this project", added)) + print(warn or ("recorded. In force from the next session%s: %s" % ( + " in every project" if scope == rules.USER else " in this project", added) if scope != rules.CORE else "recorded, queued for the product: %s" % added)) + print(rules.filed(scope, opt["improve"], cwd)) except OSError as e: print("recorded, but could not write %s (%s)." % (rules.path(scope, cwd) or cwd, e)) if misses >= 2: diff --git a/sisi/rules.py b/sisi/rules.py index 3bda6ee..ed929ee 100644 --- a/sisi/rules.py +++ b/sisi/rules.py @@ -6,7 +6,9 @@ Now and then a cheap worker audits and organizes them. Store changes are committ import contextlib, hashlib, json, os, re, time from . import store -USER, PROJECT = "user", "project" +USER, PROJECT, CORE = "user", "project", "core" +LEVELS = """The three levels: core = the sisi product itself, for every sisi user anywhere, nothing personal (queued for its maintainers, never loaded); +user = how this person works across all projects, their machine, accounts, providers; project = this one git repo only (its .sisi/rules.md).""" 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] @@ -30,8 +32,11 @@ Rewrite both lists so they serve that objective best: - Merge rules that say the same thing. Drop fragments, rules that are stale or contradicted by a later one, and rules too specific to come up again. - Word each rule as a direct instruction with its reason, on one line, standing on its own. -- 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. +- Audit where each rule is filed. %(levels)s Move a rule that sits at the wrong level, in either direction, + with its words byte-identical: a user line about one project goes to `## project` (this one; if it names another + project leave it and flag it); a project line that applies to all the person's work goes to `## user`; a line + that applies to every sisi user goes under `## core` (a queue for the product's maintainers). [owner ...] lines + may move between levels too, never reworded. - 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 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 @@ -48,6 +53,8 @@ Answer with exactly this shape and nothing else: - ... ## project - ... +## core +- ... (only lines moved to the product queue) ## drops - | # | (optional; only if any non-owner rules were dropped) ## flags @@ -70,7 +77,31 @@ Answer with exactly this shape and nothing else: def path(scope, cwd=None): """Where a list is kept; for a project "" inside a git directory or bare repository, where none is kept.""" top, inside = store.root(cwd) if scope == PROJECT else ("", False) - return store.data("rules", "user.md") if scope == USER else "" if inside else os.path.join(top, ".sisi", "rules.md") + return store.data("rules", scope + ".md") if scope in (USER, CORE) else "" if inside else os.path.join(top, ".sisi", "rules.md") + + +def has_project(cwd=None): + """True inside a git repository whose root is not the home folder: the only place a project list may be written.""" + top, inside = store.root(cwd) + return not inside and os.path.lexists(os.path.join(top, ".git")) and os.path.realpath(top) != os.path.realpath(store.HOME) + + +def refuse_level(level, cwd, cmd): + """Why a rule may not be filed at this level (with the command to rerun), or "".""" + if level not in (CORE, USER, PROJECT): + return "name the level of this rule. %s\nRerun with --level core|user|project, e.g. `%s --level user ...`." % (LEVELS, cmd) + return "no project here (not inside a git repository, or it is the home folder), use user: `%s --level user ...`." % cmd if level == PROJECT and not has_project(cwd) else "" + + +def filed(level, text, cwd): + return 'filed as %s rule in %s. Wrong level? sisi rules move "%s" core|user|project' % (level, path(level, cwd), " ".join(text.split()[:5])) + + +def core_note(cwd): + """At session start in the sisi repo itself: how many rules wait in the product queue.""" + top = store.project_root(cwd) + n = len(lines(path(CORE))) if all(os.path.isfile(os.path.join(top, *f)) for f in (("canon", "core.md"), ("sisi", "rules.py"))) else 0 + return "sisi: %d rule%s proposed for the product: add each to canon/core.md or move it (sisi rules move)." % (n, "" if n == 1 else "s") if n else "" def _legacy(cwd=None): @@ -186,13 +217,16 @@ def _commit(msg, *paths, snap=None, put=None): raise OSError("store git commit failed (%s)" % store.GIT_ERROR) -def add(text, scope, source, cwd=None, log=None, means=""): +def add(text, scope, source, cwd=None, log=None, means="", raw=None): """Put one rule in force; returns (line, warning). Raises OSError before writing when the list cannot be written.""" + if scope == PROJECT and not has_project(cwd): + raise OSError("no project here, use user") 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 + line, more = (raw, []) if raw else (line, more) 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: + if scope != PROJECT: [store.append(dest, l) for l in [line, *more]] else: _check_writable(dest) @@ -204,7 +238,7 @@ def add(text, scope, source, cwd=None, log=None, means=""): note(dest) try: log and store.append(*log) - extra = ([dest] if scope == USER else []) + ([log[0]] if log else []) + extra = ([dest] if scope != PROJECT else []) + ([log[0]] if log else []) _commit("rule added (%s, %s)" % (scope, source), *extra, snap=(dest, before, after) if scope == PROJECT else None) warn = "" except OSError as e: @@ -275,8 +309,9 @@ def due(cwd, claim=False): ls, k = _retro(scope_lines(scope, cwd, migrate=False)), _mark_key(scope, cwd) prev = int(seen.get(k, seen.get("rules/projects/%s.md" % store.project_key(cwd), 0) if scope == PROJECT else 0)) over = len(ls) > cfg["rules_lines"] or sum(map(len, ls)) > cfg["rules_chars"] - if not active(cl, k) and (over or len(ls) - prev >= cfg["organize_after"]): - need.append((k, "%s rules: %d lines, %s" % (scope, len(ls), "over the budget" if over else "%d new" % (len(ls) - prev)))) + audit = scope == USER and has_project(cwd) and len(store.read(store.data("retro.jsonl")).splitlines()) - int(seen.get("retros", 0)) >= cfg["audit_after"] + if not active(cl, k) and (over or audit or len(ls) - prev >= cfg["organize_after"]): + need.append((k, "%s rules: %d lines, %s" % (scope, len(ls), "over the budget" if over else "%d new" % (len(ls) - prev) if len(ls) - prev >= cfg["organize_after"] else "time to audit their levels"))) if not need: return "" if claim: @@ -328,7 +363,7 @@ def organize_brief(cwd): cl["snap:" + _mark_key(PROJECT, cwd)] = _snap(u, p) store.write(store.data("locks", "organize.json"), json.dumps(cl)) return ORGANIZE % { - "name": os.path.basename(store.project_root(cwd)), "objective": objective(), + "name": os.path.basename(store.project_root(cwd)), "levels": LEVELS.replace("\n", " "), "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)", @@ -339,10 +374,10 @@ 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() - secs = re.split(r"(?m)^(#{2,3}[ \t]*(?i:drops)\b[^\n]*|##[ \t]*(?i:flags)[ \t]*|## (?:user|project)[ \t]*|## [^\n]*)$", store.read(answer_file)) + secs = re.split(r"(?m)^(#{2,3}[ \t]*(?i:drops)\b[^\n]*|##[ \t]*(?i:flags)[ \t]*|## (?:user|project|core)[ \t]*|## [^\n]*)$", store.read(answer_file)) got, flags, drops = {}, "", {} for h, chunk in ((secs[i], secs[i + 1]) for i in range(1, len(secs) - 1, 2)): - if re.fullmatch(r"## (user|project)[ \t]*", h): + if re.fullmatch(r"## (user|project|core)[ \t]*", h): got[h[3:].strip()] = [l.rstrip() for l in chunk.splitlines() if l.startswith("- ")] elif re.fullmatch(r"(?i)##[ \t]*flags[ \t]*", h): flags += chunk @@ -350,6 +385,7 @@ def organize_record(answer_file, cwd): for l in chunk.splitlines(): if (m := _DROP.match(l.strip())) and (rk := _DKEY(m[1])) and (why := store.clean(m[3])[:300]): drops.setdefault(rk, (m[2], why)) + core = got.pop(CORE, []) if set(got) != {USER, PROJECT}: return "the answer needs a `## user` section and a `## project` section, each a list of `- ` lines" for scope, ls in got.items(): @@ -357,7 +393,9 @@ def organize_record(answer_file, cwd): if len(r) > cfg["rules_lines"] or sum(map(len, r)) > cfg["rules_chars"]: return "the %s list is over the budget of %d lines and %d characters (it has %d and %d)" % ( scope, cfg["rules_lines"], cfg["rules_chars"], len(r), sum(map(len, r))) - up, pp = path(USER), path(PROJECT, cwd) + up, pp, cp = path(USER), path(PROJECT, cwd), path(CORE) + if not has_project(cwd): + return "no project here, so there is no project list to organize; run it from inside a git project" if not pp or os.path.islink(os.path.dirname(pp)): return _migrate(cwd)[1].removeprefix("sisi: ") with store.lock(pp): @@ -367,10 +405,10 @@ def organize_record(answer_file, cwd): had = {USER: lines(up), PROJECT: scope_lines(PROJECT, cwd, migrate=False)} if (want := _organized(("locks", "organize.json")).get("snap:" + _mark_key(PROJECT, cwd))) and _snap(had[USER], had[PROJECT]) != want: return "the rules changed since `sisi rules organize` ran; run `sisi rules organize` again" - for scope in (USER, PROJECT): - if miss := [l for l in had[scope] if _owner(l) and got[scope].count(l) < had[scope].count(l)]: - return "owner rule missing or changed (%s): %s" % (scope, miss[0]) - kept = list(got[USER]) + list(got[PROJECT]) + every = got[USER] + got[PROJECT] + core # an owner line may change level, never a word + if miss := [l for l in had[USER] + had[PROJECT] if _owner(l) and every.count(l) < (had[USER] + had[PROJECT]).count(l)]: + return "owner rule missing or changed: %s" % miss[0] + kept = every[:] dropped = [r for r in had[USER] + had[PROJECT] if not _owner(r) and not (r in kept and kept.remove(r) is None)] from . import retro nprobs = len(retro._problems()) if dropped else 0 @@ -391,12 +429,13 @@ def organize_record(answer_file, cwd): utext = "".join(l + "\n" for l in got[USER]) try: seen = _organized() + seen["retros"] = len(store.read(store.data("retro.jsonl")).splitlines()) seen.update({_mark_key(USER): len(_retro(got[USER])), _mark_key(PROJECT, cwd): len(_retro(got[PROJECT]))}) seen.pop("rules/projects/%s.md" % store.project_key(cwd), None) dp, ts = store.data(DROPS), time.strftime("%Y-%m-%dT%H:%M:%S") for r, pn, why in recs: store.append(dp, json.dumps({"ts": ts, "rule": r, "problem": pn, "reason": why}, sort_keys=True)) - _commit("rules organized", *([dp] if recs else []), snap=(pp, before, after), put={up: utext, store.data("rules", "organized.json"): json.dumps(seen)}) + _commit("rules organized", *([dp] if recs else []), snap=(pp, before, after), put={up: utext, **({cp: "".join(l + "\n" for l in dict.fromkeys(lines(cp) + core))} if core else {}), store.data("rules", "organized.json"): json.dumps(seen)}) except OSError as e: (wrote_u := store.regular(up, True)[1] == utext.encode()) and build_rulebook() if not wrote and not wrote_u: @@ -417,7 +456,7 @@ def organize_record(answer_file, cwd): def revert(): """Undo the last rule change (learn, retro or organize): a project's list only while it holds what that change left.""" - files = ("rules/user.md", "rules/last-project.json", "rules/owner.log", "rules/organized.json", DROPS) + files = ("rules/user.md", "rules/core.md", "rules/last-project.json", "rules/owner.log", "rules/organized.json", DROPS) advice = " (edit by hand or restore with git)" if os.path.isdir(os.path.join(store.DATA, ".git")) and store.git(["status", "--porcelain", "--", *files], store.DATA)[1].strip(): return "the store has uncommitted rule changes, so the previous change cannot be undone" + advice @@ -478,15 +517,53 @@ def run(args, cwd=None): return 0 if args[0] == "organize" and len(args) == 3 and args[1] == "--record": why = organize_record(args[2], cwd) + elif args[:1] == ["move"]: + why = move(args[1:], cwd) elif args == ["revert"]: why = revert() else: - why = "usage: sisi rules | sisi rules organize [--record FILE] | sisi rules revert" + why = "usage: sisi rules | sisi rules organize [--record FILE] | sisi rules move \"\" core|user|project [--project PATH] | sisi rules revert" if why: print("sisi rules: %s. Nothing was changed." % why if not why.startswith("usage") else why) return 1 if why else 0 +def move(args, cwd): + """`sisi rules move "" LEVEL [--project PATH]`: one line, verbatim, to another level. Returns why not, or None.""" + top = None + if "--project" in args: + i = args.index("--project") + top, args = os.path.abspath((args[i + 1:i + 2] or [""])[0]), args[:i] + args[i + 2:] + if not has_project(top) or os.path.realpath(store.root(top)[0]) != os.path.realpath(top): + return "--project needs the folder of a git repository (its root)" + if len(args) != 2 or args[1] not in (CORE, USER, PROJECT): + return 'usage: sisi rules move "" core|user|project [--project PATH]' + start, to = args[0].strip().removeprefix("- ").strip(), args[1] + homes = [(CORE, cwd), (USER, cwd)] + [(PROJECT, c) for c in dict.fromkeys(c for c in (cwd if has_project(cwd) else None, top) if c)] + hits = [(lv, c, l) for lv, c in homes for l in dict.fromkeys(scope_lines(lv, c, migrate=False) if lv == PROJECT else lines(path(lv))) if l[2:].startswith(start)] if start else [] + if len(hits) != 1: + return "no rule line starts with that" if not hits else "more than one rule starts with that; give more of it:\n" + "\n".join(" [%s] %s" % (lv, l) for lv, _, l in hits) + lv, c, line = hits[0] + to_cwd = top or cwd + if path(lv, c) == path(to, to_cwd): + return "that rule is already a %s rule" % to + if why := refuse_level(to, to_cwd, "sisi rules move"): + return why.split(": `")[0] + add(line, to, "move", to_cwd, raw=line) + src = path(lv, c) + with store.lock(src if lv == PROJECT else "user"): + keep = (_text(src) or "").splitlines(True) + keep.remove(next(x for x in keep if x.rstrip("\r\n") == line)) + if lv == PROJECT: + _check_writable(src) + store.write(src, "".join(keep)) + else: + _commit("rule moved (%s to %s)" % (lv, to), put={src: "".join(keep)}) + lv == USER and build_rulebook() + print("moved to %s: %s" % (to, line)) + return None + + _norm = lambda t: " ".join(re.sub(r"[\W_]+", " ", t.lower()).split()) @@ -501,14 +578,23 @@ def _said(words, cwd): def learn(args, cwd=None): - """`sisi learn [--project] "" [--means ""]`: a rule at once; the + """`sisi learn --level core|user|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 or (means and len(means.split()) < 3): - print('usage: sisi learn [--project] "" [--means ""]') + scope, words, i = PROJECT if "--project" in args else None, [], 0 + while i < len(args): + if args[i] in ("--level", "--scope") and i + 1 < len(args): + scope, i = args[i + 1], i + 2 + else: + words += [args[i]] * (args[i] != "--project") + i += 1 + text = " ".join(words).strip() + if len(text.split()) < 3 or (means and len(means.split()) < 3) or any(w.startswith("--") for w in words): + print('usage: sisi learn --level core|user|project "" [--means ""]') + return 1 + if why := refuse_level(scope, cwd, 'sisi learn'): + print("sisi learn: " + why) 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 @@ -518,5 +604,6 @@ def learn(args, cwd=None): 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) + print(warn or ("in force from the next session: %s" if scope != CORE else "queued for the product, not in force: %s") % line) + print(filed(scope, text, cwd)) return 0 diff --git a/sisi/store.py b/sisi/store.py index 78aff25..40fd412 100644 --- a/sisi/store.py +++ b/sisi/store.py @@ -24,7 +24,7 @@ GIT_ERROR = "" # why the last git call that failed did: the first line of its s # Every setting there is. The person overrides one under "core" in config.json in their store. DEFAULTS = {"gate": True, "meter": True, "direct_calls": 8, "direct_extension": 8, - "rules_lines": 30, "rules_chars": 4000, "organize_after": 8, "research_days": 7, "shell_workers": False, + "rules_lines": 30, "rules_chars": 4000, "organize_after": 8, "audit_after": 12, "research_days": 7, "shell_workers": False, "worker_minutes": 90, "retro_minutes": 5, "disk_free_percent": 20, "disk_drop_percent": 5, "checkouts": 8} def config(): diff --git a/tests/test_core.py b/tests/test_core.py index ab9a13b..102a9d4 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -7,9 +7,10 @@ import glob, hashlib, json, os, random, re, shutil, subprocess, sys, tempfile, t from unittest import mock REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +IMP = ("--improve", "Always name the level of a rule you file") GAP = ("--gap", "the export dropped rows with empty names until the person noticed", "--cause", "no check compared the row counts before and after", "--term", "evidence", - "--problem", "export drops empty names") + "--problem", "export drops empty names", "--level", "project") NG = ("--term", "time", "--better", "start the first build in the same turn as research") @@ -140,7 +141,7 @@ class Core(unittest.TestCase): self.assertEqual(self.hook("gate")[1], "") # held: the turn may end self.assertIn("Compare row counts", self.hook("tick", sid="s2")[1]) # next session here self.assertNotIn("Compare row counts", self.hook("tick", sid="s3", cwd=self.project("beta"))[1]) # not elsewhere - self.sisi("retro", *GAP, "--improve", "Ask one question with options, never three open ones", "--scope", "user", sid="s1") + self.sisi("retro", *GAP[:-2], "--improve", "Ask one question with options, never three open ones", "--scope", "user", sid="s1") book = self.read(self.data, "generated", "core.md") self.assertIn("## 8. Close with a retro", book) self.assertIn("## Learned here", book) @@ -157,7 +158,7 @@ class Core(unittest.TestCase): first = self.records()[-1]["rules"] self.assertEqual(first, {"hash": hashlib.sha256(book.encode()).hexdigest()[:12], "chars": len(book), "lines": sum(l.startswith("- ") for l in book.splitlines())}) - self.assertEqual(self.sisi("learn", "Always name the rulebook in every retro record", sid="s1")[0], 0) + self.assertEqual(self.sisi("learn", "--level", "user", "Always name the rulebook in every retro record", sid="s1")[0], 0) self.sisi("retro", *GAP, "--improve", "Name the rulebook in every retro record", sid="s1") second = self.records()[-1]["rules"] self.assertNotEqual(second["hash"], first["hash"]) @@ -168,7 +169,7 @@ class Core(unittest.TestCase): self.done() self.tool("Write") for args in (["--gap", "bad"], ["--no-gap", "fine"], GAP + ("--improve", "be careful"), ["--later", "x"], - GAP + ("--improve", "Compare the row counts every time", "--scope", "everyone")): + GAP[:-2] + ("--improve", "Compare the row counts every time", "--scope", "everyone")): self.assertEqual(self.sisi("retro", *args, sid="s1")[0], 1, args) self.assertIn('"block"', self.hook("gate")[1]) self.assertEqual(self.sisi("retro", "--no-gap", "the person accepted it first time and every check passed", *NG, sid="s1")[0], 0) @@ -197,7 +198,7 @@ class Core(unittest.TestCase): self.hook("tick") self.done() self.tool("Write") - base = GAP[:4] + ("--improve", "Compare row counts before and after every export change") + base = GAP[:4] + ("--level", "project", "--improve", "Compare row counts before and after every export change") for extra in ((), ("--term", "speed")): rc, out, _ = self.sisi("retro", *base, *extra, sid="s1") self.assertEqual(rc, 1, extra) @@ -241,7 +242,7 @@ class Core(unittest.TestCase): def test_a_secret_never_reaches_a_rule(self): self.hook("tick") - self.sisi("retro", "--gap", "the deploy failed because the key was pasted wrong", "--cause", "the key was typed by hand each time", + self.sisi("retro", "--level", "project", "--gap", "the deploy failed because the key was pasted wrong", "--cause", "the key was typed by hand each time", "--term", "evidence", "--problem", "deploy key typed by hand", "--improve", "Read the deploy key from the keyring, never paste api_key=sk-abcdefghijklmnopqrstuvwx into a command", sid="s1") stored = "".join(self.read(p) for p in glob.glob(os.path.join(self.data, "**", "*.*"), recursive=True)) proj_rules = self.read(self.proj, ".sisi", "rules.md") @@ -314,12 +315,10 @@ class Core(unittest.TestCase): def test_outside_git_a_subfolder_is_its_own_project(self): root = self.mkdir(self.tmp, "plain-proj") - self.assertEqual(self.sisi("learn", "--project", "Rule of the outer plain folder", cwd=root)[0], 0) sub = self.mkdir(root, "a", "b") - self.assertNotIn("Rule of the outer plain folder", self.hook("tick", sid="ng1", cwd=sub)[1]) - self.assertEqual(self.sisi("learn", "--project", "Rule of the inner plain folder", cwd=sub)[0], 0) - self.assertIn("Rule of the inner plain folder", self.read(sub, ".sisi", "rules.md")) - self.assertNotIn("Rule of the inner plain folder", self.read(root, ".sisi", "rules.md")) + for where in (root, sub): # outside git no folder is a project: nothing is written + self.assertEqual(self.sisi("learn", "--project", "Rule of a plain folder", cwd=where)[0], 1) + self.assertFalse(os.path.lexists(os.path.join(where, ".sisi"))) def test_reading_project_with_no_rules_creates_no_sisi_dir(self): plain = self.mkdir(self.tmp, "plain-empty") @@ -328,8 +327,8 @@ class Core(unittest.TestCase): self.assertEqual(self.sisi("rules", cwd=folder)[0], 0) self.assertEqual(self.sisi("doctor", cwd=folder)[0], 0) self.assertFalse(os.path.lexists(os.path.join(folder, ".sisi")), folder) - self.assertEqual(self.sisi("learn", "--project", "First rule creates the sisi directory", cwd=plain)[0], 0) - self.assertTrue(os.path.isfile(os.path.join(plain, ".sisi", "rules.md"))) + self.assertEqual(self.sisi("learn", "--project", "First rule creates the sisi directory", cwd=plain)[0], 1) + self.assertFalse(os.path.lexists(os.path.join(plain, ".sisi"))) def test_legacy_project_rules_migrate_on_read_and_stay_idempotent(self): real_rows = [ @@ -584,7 +583,7 @@ class Core(unittest.TestCase): self.write(os.path.join(p, "app.txt"), "v2\n") for n, why in (("1", "row counts match at 10"), ("2", "empty name exported as row")): self.assertEqual(self.sisi("done", "--pass", n, why, cwd=p, sid=sid)[0], 0) - rc, out, _ = self.sisi("retro", *GAP[:4], "--improve", rule_text, "--term", "time", "--problem", "problem-" + sid, cwd=p, sid=sid) + rc, out, _ = self.sisi("retro", *GAP[:4], "--level", "project", "--improve", rule_text, "--term", "time", "--problem", "problem-" + sid, cwd=p, sid=sid) self.assertEqual(rc, 0, out) # 1. Exact four-step sequence: retro writes tracked .sisi/rules.md, commit that one file -> no demand @@ -636,7 +635,7 @@ class Core(unittest.TestCase): self.assertIn('"block"', self.hook("gate", sid="r5", cwd=p5)[1]) for n, why in (("1", "row counts match at 10"), ("2", "empty name exported as row")): self.assertEqual(self.sisi("done", "--pass", n, why, cwd=p5, sid="r5")[0], 0) - self.assertEqual(self.sisi("retro", *GAP, "--improve", "Non-git project rules still record cleanly", cwd=p5, sid="r5")[0], 0) + self.assertEqual(self.sisi("retro", *GAP[:-2], "--level", "user", "--improve", "Non-git project rules still record cleanly", cwd=p5, sid="r5")[0], 0) self.assertEqual(self.hook("gate", sid="r5", cwd=p5)[1], "") def test_doctor_reports_project_agents_note_without_writing(self): @@ -996,7 +995,7 @@ class Core(unittest.TestCase): self.assertEqual(self.read(self.proj, ".sisi", "rules.md"), rows) beta = self.project("mig-with-prior") - self.assertEqual(self.sisi("learn", "User rule recorded before migration")[0], 0) + self.assertEqual(self.sisi("learn", "--level", "user", "User rule recorded before migration")[0], 0) old_b = self.legacy(beta, rows) self.hook("tick", sid="mb", cwd=beta) self.assertFalse(os.path.exists(old_b)) @@ -1191,7 +1190,7 @@ class Core(unittest.TestCase): ([sys.executable, os.path.join(REPO, "bin", "sisi"), "learn", "--project", "Alpha one rule round %d" % rnd], pa, ""), ([sys.executable, os.path.join(REPO, "bin", "sisi"), "learn", "--project", "Alpha two rule round %d" % rnd], pa, ""), ([sys.executable, os.path.join(REPO, "bin", "sisi"), "retro", *GAP, "--improve", "Beta one rule round %d" % rnd], pb, ""), - ([sys.executable, os.path.join(REPO, "bin", "sisi"), "retro", *GAP, "--scope", "user", "--improve", "User rule round %d" % rnd], pa, ""), + ([sys.executable, os.path.join(REPO, "bin", "sisi"), "retro", *GAP[:-2], "--scope", "user", "--improve", "User rule round %d" % rnd], pa, ""), ([sys.executable, os.path.join(REPO, "bin", "sisi"), "retro", *GAP, "--improve", "Retro rule round %d" % rnd], pa, ""), ([sys.executable, os.path.join(REPO, "bin", "sisi"), "tick"], pc, json.dumps({"session_id": "c1-%d" % rnd, "cwd": pc})), ([sys.executable, os.path.join(REPO, "bin", "sisi"), "tick"], pc, json.dumps({"session_id": "c2-%d" % rnd, "cwd": pc})), @@ -1290,7 +1289,7 @@ class Core(unittest.TestCase): # organize replaced rules/user.md under a project's lock; a user rule's concurrent `git add` read it as it # shrank: "short read while indexing rules/user.md". from sisi import rules, store - self.sisi("learn", "User rule before organizing") + self.sisi("learn", "--level", "user", "User rule before organizing") user, real_lock, seen = os.path.join(self.data, "rules", "user.md"), store.lock, [] before = self.read(user) @@ -1308,8 +1307,8 @@ class Core(unittest.TestCase): def test_folders_outside_git_are_each_their_own_project(self): notes, other, thing = (self.mkdir(self.tmp, *p) for p in (("notes",), ("code", "other"), ("code", "thing"))) - self.assertEqual(self.sisi("learn", "--project", "A rule written at the home folder", cwd=self.tmp)[0], 0) - self.assertEqual(self.sisi("learn", "--project", "A rule written in the notes folder", cwd=notes)[0], 0) + self.assertEqual(self.sisi("learn", "--project", "A rule written at the home folder", cwd=self.tmp)[0], 1) + self.assertEqual(self.sisi("learn", "--project", "A rule written in the notes folder", cwd=notes)[0], 1) old = self.legacy(thing, "- Old rule of the thing folder [owner 2026-11-20]\n") out = self.hook("tick", sid="o1", cwd=other)[1] self.assertNotIn("home folder", out) @@ -1430,18 +1429,18 @@ 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()), 2, out) + self.assertEqual(len(out.strip().splitlines()), 3, out) self.assertIn("the rule is in", out) self.assertIn("could not be recorded for undo", out) self.assertNotIn("Nothing was changed", out) def test_failed_store_commit_reports_failure_and_blocks_older_revert(self): - self.assertEqual(self.sisi("learn", "Older user rule that revert must not silently undo")[0], 0) + self.assertEqual(self.sisi("learn", "--level", "user", "Older user rule that revert must not silently undo")[0], 0) lock = self.write(os.path.join(self.data, ".git", "index.lock"), "") 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()), 2, out) + self.assertEqual(len(out.strip().splitlines()), 3, out) self.assertIn("could not be recorded for undo", out) os.remove(lock) rc_rev, out_rev, _ = self.sisi("rules", "revert") @@ -1469,9 +1468,9 @@ cli.main(["tick"]) dot_git = os.path.join(self.proj, ".git") for where in (dot_git, os.path.join(dot_git, "refs")): rc, out, err = self.sisi("retro", *GAP, "--improve", "Never write rules inside a git directory", cwd=where) - self.assertEqual((rc, err), (0, ""), (where, out)) - self.assertNotIn("could not write (", out) - self.assertIn("could not write %s (" % where, out) + self.assertEqual((rc, err), (1, ""), (where, out)) + self.assertIn("no project here", out) + self.assertFalse(os.path.lexists(os.path.join(where, ".sisi"))) def test_byte_order_mark_and_non_utf8_project_file(self): old = os.path.join(self.mkdir(self.data, "rules", "projects"), self.project_key_for(self.proj) + ".md") @@ -1508,7 +1507,7 @@ cli.main(["tick"]) self.sisi("learn", "--project", "A rule that must not land here", cwd=where)): rc, out = (r.returncode, r.stdout) if hasattr(r, "returncode") else r[:2] self.assertEqual((rc, len(out.strip().splitlines())), (1, 1), (where, out)) - self.assertIn("inside a git directory or a bare repository", out) + self.assertIn("no project here", out) self.assertEqual(self.hook("tick", sid="b", cwd=where)[0], 0) self.assertFalse(os.path.lexists(os.path.join(where, ".sisi")), where) self.assertFalse(os.path.lexists(os.path.join(self.tmp, ".sisi"))) @@ -1609,7 +1608,7 @@ 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.hook("prompt", prompt="Only the cheapest models on the shared plan") - self.sisi("learn", "Only the cheapest models on the shared plan", sid="s1") + self.sisi("learn", "--level", "user", "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 @@ -2502,7 +2501,7 @@ cli.main(["tick"]) book = self.read(self.data, "generated", "core.md") text = self.read(mine) self.assertEqual(text, "\n%s\n# my notes\nno newline at the end" % book) - self.assertEqual(self.sisi("learn", "Always say which check proved it")[0], 0) # a rebuild refreshes the block + self.assertEqual(self.sisi("learn", "--level", "user", "Always say which check proved it")[0], 0) # a rebuild refreshes the block new = self.read(mine) self.assertIn("Always say which check proved it", new) self.assertTrue(new.endswith("\n# my notes\nno newline at the end")) @@ -2512,7 +2511,7 @@ cli.main(["tick"]) self.assertFalse(os.path.lexists(os.path.join(home, ".pi", "agent", "AGENTS.md"))) self.assertEqual(os.readlink(os.path.join(home, ".gemini", "GEMINI.md")), elsewhere) # a rebuild alone never creates anything in a tool - self.sisi("learn", "Name the check that failed first") + self.sisi("learn", "--level", "user", "Name the check that failed first") self.assertFalse(os.path.lexists(os.path.join(home, ".pi", "agent", "AGENTS.md"))) self.assertEqual(self.read(mine), "# my notes\nno newline at the end") @@ -2524,7 +2523,7 @@ cli.main(["tick"]) self.assertEqual(self.sisi("install")[0], 0) book = self.read(self.data, "generated", "core.md") self.assertEqual(self.read(target), "\n%s\n# my notes\n%s" % (book, second)) - self.assertEqual(self.sisi("learn", "Keep second marked block in global instructions")[0], 0) + self.assertEqual(self.sisi("learn", "--level", "user", "Keep second marked block in global instructions")[0], 0) new_book = self.read(self.data, "generated", "core.md") self.assertIn("Keep second marked block in global instructions", new_book) self.assertEqual(self.read(target), "\n%s\n# my notes\n%s" % (new_book, second)) @@ -2618,7 +2617,7 @@ cli.main(["tick"]) subprocess.run(["git", "clone", "-q", src, mine], check=True, capture_output=True) # the person's checkout, with its remote self.assertEqual(run(os.path.join(mine, "bin", "sisi"), "release").returncode, 0) self.assertEqual(self.read(self.env["SISI_LIB"], "current", "SOURCE").split("\n")[0], src) - self.sisi("learn", "Always keep what the person wrote") + self.sisi("learn", "--level", "user", "Always keep what the person wrote") self.write(os.path.join(self.data, "models.md"), WORKERS) self.write(os.path.join(self.data, "retro.jsonl"), '{"gap": "g"}\n') keep = {n: self.read(self.data, n) for n in ("models.md", "retro.jsonl", "rules/user.md")} @@ -3749,7 +3748,7 @@ cli.main(["tick"]) 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 + rc, out, _ = self.sisi("learn", "--level", "user", "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()) @@ -3757,11 +3756,11 @@ cli.main(["tick"]) 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.assertEqual(self.sisi("learn", "--level", "user", "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.assertEqual(self.sisi("learn", "--level", "user", "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") + rc, out, _ = self.sisi("learn", "--level", "user", "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\]$") @@ -3889,7 +3888,7 @@ cli.main(["tick"]) 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) + self.assertEqual(self.sisi("learn", "--level", "user", "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) @@ -3946,9 +3945,122 @@ cli.main(["tick"]) with open(os.path.join(REPO, rel), "rb") as f: self.assertEqual(hashlib.sha256(f.read()).hexdigest(), digest, rel) + # strict placement: every rule names its level + + def user_file(self, text): + os.makedirs(os.path.join(self.data, "rules"), exist_ok=True) + return self.write(os.path.join(self.data, "rules", "user.md"), text) + + def test_learn_and_retro_without_a_level_are_refused_and_write_nothing(self): + rc, out, _ = self.sisi("learn", "Always name the level of a rule") + self.assertEqual(rc, 1) + self.assertIn("core = ", out) + self.assertIn("--level core|user|project", out) + rc, out, _ = self.sisi("retro", *GAP[:-2], *IMP) + self.assertEqual(rc, 1) + self.assertIn("user = ", out) + self.assertFalse(os.path.exists(os.path.join(self.data, "rules", "user.md"))) + self.assertFalse(os.path.exists(os.path.join(self.proj, ".sisi"))) + self.assertEqual(self.sisi("retro", "--no-gap", "the export kept every row", *NG)[0], 0) # no rule, no level needed + self.assertEqual(self.sisi("retro", *GAP[:-2], *IMP, "--scope", "user")[0], 0) # --scope is an alias + + def test_unknown_options_are_refused_not_folded_into_the_rule(self): + for args in (("learn", "--level", "user", "Always name the level", "--scopee", "project"), + ("learn", "--level", "user", "--bogus", "Always name the level")): + rc, out, _ = self.sisi(*args) + self.assertEqual(rc, 1, args) + self.assertIn("usage: sisi learn", out) + self.assertEqual(self.sisi("retro", *GAP[:-2], *IMP, "--level", "user", "--bogus", "x")[0], 1) + self.assertFalse(os.path.exists(os.path.join(self.data, "rules", "user.md"))) + + def test_project_level_needs_a_git_repo_and_never_creates_sisi_elsewhere(self): + plain = os.path.join(self.tmp, "plain") + os.makedirs(plain) + for where in (plain, self.tmp): # a plain folder, and the home folder + for args in (("learn", "--level", "project", "Always check this folder first"), ("retro", *GAP[:-2], *IMP, "--level", "project")): + rc, out, _ = self.sisi(*args, cwd=where) + self.assertEqual(rc, 1, args) + self.assertIn("no project here", out) + self.assertIn("use user", out) + self.assertFalse(os.path.exists(os.path.join(where, ".sisi")), where) + rc, out, _ = self.sisi("learn", "--level", "project", "Always check this folder first") + self.assertEqual(rc, 0, out) + self.assertIn('filed as project rule in %s' % os.path.join(self.proj, ".sisi", "rules.md"), out) + self.assertIn('Wrong level? sisi rules move "Always check this folder first"', out) + + def test_core_rules_are_queued_shown_in_the_sisi_repo_and_never_loaded(self): + rc, out, _ = self.sisi("learn", "--level", "core", "Every sisi user should see this line") + self.assertEqual(rc, 0, out) + self.assertIn("Every sisi user should see this line", self.read(self.data, "rules", "core.md")) + self.assertEqual(self.sisi("retro", *GAP[:-2], *IMP, "--level", "core")[0], 0) + self.assertEqual(len(self.read(self.data, "rules", "core.md").splitlines()), 2) + self.sisi("rulebook") + self.assertNotIn("Every sisi user", self.read(self.data, "generated", "core.md")) + self.assertNotIn("Every sisi user", self.hook("tick", sid="c1")[1]) + repo = self.project("sisi-checkout") + for rel in (("canon", "core.md"), ("sisi", "rules.py")): + os.makedirs(os.path.join(repo, rel[0]), exist_ok=True) + self.write(os.path.join(repo, *rel), "x\n") + out = self.hook("tick", sid="c2", cwd=repo)[1] + self.assertIn("2 rules proposed for the product: add each to canon/core.md or move it", out) + + def test_rules_move_carries_an_owner_line_verbatim_between_levels(self): + line = "- Keep the words exactly as spoken [owner 2026-11-20]" + self.user_file(line + "\n- Another user rule [retro 2026-11-21]\n") + rc, out, _e = self.sisi("rules", "move", "Keep the words", "project"); out += _e + self.assertEqual(rc, 0, out) + self.assertEqual(self.read(self.proj, ".sisi", "rules.md"), line + "\n") + self.assertEqual(self.read(self.data, "rules", "user.md"), "- Another user rule [retro 2026-11-21]\n") + self.assertEqual(self.sisi("rules", "move", "Keep the words", "user")[0], 0) + self.assertEqual(self.read(self.data, "rules", "user.md").splitlines()[-1], line) + self.assertEqual(self.read(self.proj, ".sisi", "rules.md"), "") + self.assertEqual(self.sisi("rules", "move", "Keep the words", "core")[0], 0) + self.assertEqual(self.read(self.data, "rules", "core.md"), line + "\n") + other = self.project("other") + self.assertEqual(self.sisi("rules", "move", "Keep the words", "project", "--project", other)[0], 0) + self.assertEqual(self.read(other, ".sisi", "rules.md"), line + "\n") + self.assertEqual(self.sisi("rules", "move", "Keep the words", "project", "--project", self.tmp)[0], 1) # not a repo root + + def test_rules_move_refuses_no_match_or_several(self): + self.user_file("- Same start one [owner 2026-11-20]\n- Same start two [owner 2026-11-20]\n") + before = self.read(self.data, "rules", "user.md") + for start, want in (("Nothing like this", "no rule line"), ("Same start", "more than one")): + rc, out, _ = self.sisi("rules", "move", start, "project") + self.assertEqual(rc, 1) + self.assertIn(want, out) + self.assertIn("Same start two", self.sisi("rules", "move", "Same start", "core")[1]) + self.assertEqual(self.read(self.data, "rules", "user.md"), before) + self.assertFalse(os.path.exists(os.path.join(self.proj, ".sisi"))) + + def test_organize_moves_an_owner_line_across_levels_but_never_rewords_it(self): + mine = "- Words about this one project [owner 2026-11-20]" + self.user_file(mine + "\n") + self.assertEqual(self.sisi("rules", "organize")[0], 0) + ok = self.write(os.path.join(self.tmp, "ok.md"), "## user\n## project\n%s\n## core\n" % mine) + rc, out, _ = self.sisi("rules", "organize", "--record", ok) + self.assertEqual(rc, 0, out) + self.assertEqual(self.read(self.proj, ".sisi", "rules.md"), mine + "\n") + self.assertEqual(self.read(self.data, "rules", "user.md"), "") + self.assertEqual(self.sisi("rules", "organize")[0], 0) + bad = self.write(os.path.join(self.tmp, "bad.md"), "## user\n- Words about this one project, reworded [owner 2026-11-20]\n## project\n") + rc, out, _ = self.sisi("rules", "organize", "--record", bad) + self.assertEqual(rc, 1) + self.assertIn("owner rule missing or changed", out) + self.assertEqual(self.read(self.proj, ".sisi", "rules.md"), mine + "\n") + + def test_the_level_audit_becomes_due_by_a_retro_count(self): + self.user_file("- A user rule [retro 2026-11-20]\n") + os.makedirs(self.data, exist_ok=True) + self.write(os.path.join(self.data, "retro.jsonl"), '{"x": 1}\n' * 3) + self.assertNotIn("need organizing", self.hook("tick", sid="a1")[1]) + self.write(os.path.join(self.data, "retro.jsonl"), '{"x": 1}\n' * 12) + out = self.hook("tick", sid="a2")[1] + self.assertIn("need organizing", out) + self.assertIn("time to audit their levels", out) + 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, 2290, "sisi is two loops. If it needs more than this, find the simpler shape.") + self.assertLessEqual(code, 2381, "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()), 139) self.assertLessEqual(len(rulebook), 10711) diff --git a/tests/test_organize_evidence.py b/tests/test_organize_evidence.py index 5bf08cb..79600d4 100644 --- a/tests/test_organize_evidence.py +++ b/tests/test_organize_evidence.py @@ -11,7 +11,7 @@ import unittest REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) GAP = ("--gap", "the export dropped rows with empty names until the person noticed", - "--cause", "no check compared the row counts before and after", "--term", "evidence") + "--cause", "no check compared the row counts before and after", "--term", "evidence", "--level", "project") def tree(): @@ -61,11 +61,11 @@ class OrganizeEvidence(unittest.TestCase): return f.read() def test_brief_has_problem_evidence_and_respects_caps(self): - self.assertEqual(self.sisi("retro", "--gap", "export dropped rows with empty names in table", + self.assertEqual(self.sisi("retro", "--level", "project", "--gap", "export dropped rows with empty names in table", "--cause", "first cause missed null guard", "--improve", "Check null names before exporting rows", "--term", "evidence", "--problem", "row count mismatch")[0], 0) - self.assertEqual(self.sisi("retro", "--gap", "export dropped rows again on blank fields", + self.assertEqual(self.sisi("retro", "--level", "project", "--gap", "export dropped rows again on blank fields", "--cause", "second cause forgot whitespace trim", "--improve", "Strip whitespace and assert total row count matches", "--term", "evidence", "--problem", "1")[0], 0) @@ -85,7 +85,7 @@ class OrganizeEvidence(unittest.TestCase): long_cause = "word " * 1000 for i in range(2, 19): cause = long_cause if i == 18 else "cause number %02d in batch" % i - self.assertEqual(self.sisi("retro", "--gap", "gap number %02d failed verification check" % i, + self.assertEqual(self.sisi("retro", "--level", "project", "--gap", "gap number %02d failed verification check" % i, "--cause", cause, "--improve", "Rule number %02d for problem" % i, "--term", "evidence", "--problem", "problem item %02d" % i)[0], 0) @@ -116,7 +116,7 @@ class OrganizeEvidence(unittest.TestCase): shape = brief.split("Answer with exactly this shape")[1].split("===")[0] self.assertLess(shape.index("## project"), shape.index("## drops")) self.assertLess(shape.index("## drops"), shape.index("## flags")) - self.assertEqual(len(brief.split("=== The first list now")[0].splitlines()), 35) + self.assertEqual(len(brief.split("=== The first list now")[0].splitlines()), 40) proj_line = self.read(self.proj, ".sisi", "rules.md").splitlines()[0] ans = self.write(os.path.join(self.tmp, "ans.md"), "## user\n## project\n- Kept project rule [retro 2026-11-26]\n" @@ -165,7 +165,7 @@ class OrganizeEvidence(unittest.TestCase): def test_owner_rules_stay_verbatim_with_drops_format(self): self.sisi("prompt", sid="o1", stdin=json.dumps({"session_id": "o1", "cwd": self.proj, "prompt": "Always keep the owner rule verbatim"})) - self.assertEqual(self.sisi("learn", "Always keep the owner rule verbatim", sid="o1")[0], 0) + self.assertEqual(self.sisi("learn", "--level", "user", "Always keep the owner rule verbatim", sid="o1")[0], 0) self.assertEqual(self.sisi("retro", *GAP, "--improve", "Check row counts before export", "--problem", "empty names")[0], 0) own = self.read(self.data, "rules", "user.md").splitlines()[0] ret = self.read(self.proj, ".sisi", "rules.md").splitlines()[0] @@ -297,7 +297,7 @@ class OrganizeEvidence(unittest.TestCase): def test_drops_ignore_kept_owner_and_invented_rules(self): self.sisi("prompt", sid="o1", stdin=json.dumps({"session_id": "o1", "cwd": self.proj, "prompt": "Always keep the owner rule verbatim"})) - self.assertEqual(self.sisi("learn", "Always keep the owner rule verbatim", sid="o1")[0], 0) + self.assertEqual(self.sisi("learn", "--level", "user", "Always keep the owner rule verbatim", sid="o1")[0], 0) self.assertEqual(self.sisi("retro", *GAP, "--improve", "Kept retro rule always here", "--problem", "empty names")[0], 0) own = self.read(self.data, "rules", "user.md").splitlines()[0] ret = self.read(self.proj, ".sisi", "rules.md").splitlines()[0] diff --git a/tests/test_problems.py b/tests/test_problems.py index 1a9a068..7380a8c 100644 --- a/tests/test_problems.py +++ b/tests/test_problems.py @@ -16,7 +16,7 @@ REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, REPO) from sisi import retro, store GAP = ("--gap", "the export dropped rows with empty names until the person noticed", - "--cause", "no check compared the row counts before and after", "--term", "evidence") + "--cause", "no check compared the row counts before and after", "--term", "evidence", "--level", "project") def tree(): @@ -87,7 +87,7 @@ class Problems(unittest.TestCase): self.assertNotIn("has come back", out) # Open problem #2 by words - rc, out, err = self.sisi("retro", "--gap", "build script left stale artifacts in output", + rc, out, err = self.sisi("retro", "--level", "project", "--gap", "build script left stale artifacts in output", "--cause", "clean step was skipped on incremental runs", "--improve", "Always clean output directory before packaging release", "--term", "value", "--problem", "stale build artifacts") @@ -125,7 +125,7 @@ class Problems(unittest.TestCase): # Add more non-problem records and cite #2; numbers stay stable self.assertEqual(self.sisi("retro", "--no-gap", "the build passed cleanly on first run", "--term", "time", "--better", "parallelize the test suite run here")[0], 0) - rc, out, _ = self.sisi("retro", "--gap", "build script left stale artifacts again", + rc, out, _ = self.sisi("retro", "--level", "project", "--gap", "build script left stale artifacts again", "--cause", "incremental cache kept old binary", "--improve", "Hash inputs before reusing build artifacts", "--term", "value", "--problem", "2")