The new rulebook: nine rules in the order work happens, with an enforcement map and old-id handling

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-23 12:19:17 -07:00
commit bcc093f436
16 files changed
+435 -191

No files matched your search

+4 -1
View File
@@ -491,7 +491,10 @@ def post_update():
for n in run():
print(n)
for r in overlay.scan_retests():
print("kept your version of %s %s; its base changed in this update, queued in retest.jsonl" % (r["kind"], r["id"]))
if str(r.get("action", "")).startswith("stale"):
print("rule %s: %s (queued in retest.jsonl)" % (r["id"], r["action"]))
else:
print("kept your version of %s %s; its base changed in this update, queued in retest.jsonl" % (r["kind"], r["id"]))
b = overlay.build_canon()
print("rulebook rebuilt: %d lines%s" % (b["lines"], " - OVER THE %d-LINE BUDGET; shorten or replace a rule" % overlay.MAX_LINES if b["over_budget"] else ""))
except pdata.DataError as e:
+66 -3
View File
@@ -145,7 +145,34 @@ def disabled(kind):
return _lines(paths.overlay_dir({"rule": "rules", "verifier": "verifiers", "recipe": "done"}[kind], "disabled.txt"))
def overlay_rules():
def retired_ids():
"""{old rule id: the rule that now carries its subject, or None} from canon/rule-ids.json.
An unreadable file reads as empty here; the protection check uses retired_strict()."""
try:
return retired_strict()
except OverlayError:
return {}
def retired_strict():
try:
with open(paths.canon("rule-ids.json"), encoding="utf-8") as f:
d = json.load(f)["retired"]
if not isinstance(d, dict) or not all(isinstance(k, str) and (v is None or isinstance(v, str)) for k, v in d.items()):
raise ValueError("retired must map ids to an id or null")
return d
except FileNotFoundError:
return {} # a product without the map has retired nothing
except (OSError, ValueError, KeyError, TypeError) as e:
raise OverlayError("canon/rule-ids.json cannot be read (%s)" % e)
def _is_retired(rid):
"""A retired id that no base rule uses: an overlay entry under it is stale, never applied."""
return rid in retired_ids() and rid not in {r["id"] for r in base_rules()[1]}
def overlay_rules(include_stale=False):
d = paths.overlay_dir("rules")
out = {}
try:
@@ -160,6 +187,22 @@ def overlay_rules():
except (OverlayError, OSError):
continue # a broken file is ignored here; `overlay list` reports it
out[stem] = r
if not include_stale:
out = {k: v for k, v in out.items() if not _is_retired(k)}
return out
def stale_entries():
"""Overlay rule entries keyed by a retired id: [(id, 'replacement'|'disabling', new id or None)].
They stay in the store and are not applied."""
out = []
ret = retired_ids()
for rid in sorted(overlay_rules(include_stale=True)):
if _is_retired(rid):
out.append((rid, "replacement", ret[rid]))
for rid in disabled("rule"):
if _is_retired(rid):
out.append((rid, "disabling", ret[rid]))
return out
@@ -228,6 +271,7 @@ def _render(pre, rules):
if pre.strip():
parts.append(pre)
for n, r in enumerate(rules, 1):
# the pointer rides on the body's last line: it costs no line of the always-loaded budget
parts.append("## %d. %s {#%s}\n\n%s\n%s" % (n, r["title"], r["id"], r["body"], more_line(n)))
return "\n\n".join(parts) + "\n"
@@ -262,7 +306,9 @@ def protected_rules():
rules = d["rules"]
if not isinstance(rules, list) or not all(isinstance(x, str) for x in rules):
raise ValueError("rules must be a list of ids")
return set(rules)
prot = set(rules)
# a retired id whose subject is now a protected rule stays untouchable: the map is no way round
return prot | {old for old, new in retired_strict().items() if new in prot}
except (OSError, ValueError, KeyError, TypeError) as e:
raise OverlayError("canon/protected.json cannot be read (%s): changes to rules are refused until it can" % e)
@@ -462,6 +508,8 @@ def add_rule(text, rid=None):
r = parse_rule_file(text, rid)
if r["id"] in {x["id"] for x in base_rules()[1]}:
raise OverlayError("%r is a base rule id; use replace-rule to change it" % r["id"])
if r["id"] in retired_ids():
raise OverlayError("%r is a retired rule id (now %s); choose another id" % (r["id"], retired_ids()[r["id"]] or "split across several rules"))
if r["id"] in overlay_rules():
raise OverlayError("an added rule %r already exists; use replace-rule to change it" % r["id"])
with _txn("overlay: add rule %s" % r["id"]):
@@ -596,6 +644,9 @@ def cmd_list():
for i in o[kind][how]:
print("%-8s %-9s %s" % (kind, how, i))
n += 1
for rid, how, repl in stale_entries():
print("%-8s %-9s %s (retired id, %s; not applied, kept in your store)" % ("rule", "stale", rid, "now " + repl if repl else "split across several rules"))
n += 1
if not n:
print("the overlay is empty: base rules, verifiers and recipes are used as they are")
q = retest_queue()
@@ -672,6 +723,8 @@ def scan_retests():
kind, _, id = key.partition(":")
if kind not in KINDS:
continue
if kind == "rule" and _is_retired(id):
continue # reported below as stale, not as a kept personal version
old, cur = b[key], base_hash(kind, id)
if old == cur:
continue
@@ -681,6 +734,16 @@ def scan_retests():
"old_base_hash": old, "new_base_hash": cur, "action": "kept the personal version"})
b[key] = cur
changed = True
seen = {(r.get("kind"), r.get("id")) for r in retest_queue() if str(r.get("action", "")).startswith("stale")}
for rid, how, repl in stale_entries():
if ("rule", rid) in seen:
continue # reported once
# not the 'kept your version' route: this text was written against a rule that no longer exists
new.append({"ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "kind": "rule", "id": rid,
"old_base_hash": b.get("rule:" + rid), "new_base_hash": None,
"action": "stale: your %s of the retired rule %s was written against the old wording; "
"not applied to %s, kept in your store" % (how, rid, repl or "the rules that replaced it")})
changed = True
if changed:
with pdata.lock():
p = paths.data_file("retest.jsonl")
@@ -688,7 +751,7 @@ def scan_retests():
for r in new:
f.write(json.dumps(r, sort_keys=True) + "\n")
_write("bases.json", json.dumps(b, indent=1, sort_keys=True) + "\n")
pdata.commit("update: %d replaced item(s) changed in the product, personal versions kept, queued for retest" % len(new),
pdata.commit("update: %d overlay item(s) queued (base changed, personal versions kept; or stale under a retired rule id)" % len(new),
["overlay", "retest.jsonl"])
return new
+2 -2
View File
@@ -10,7 +10,7 @@ def _session_key(payload, cwd):
return sid if isinstance(sid, str) and sid else "cwd-" + hashlib.sha1(cwd.encode()).hexdigest()[:12]
# ---------------------------------------------------------------- rule 5: ask through the dialog
# ---------------------------------------------------------------- rule 1 (own the outcome): ask through the dialog
# Tools with a confirmed question dialog whose transcripts sisi can read in Claude-Code shape.
# Codex's request_user_input is behind a flag that is off by default, OpenCode's question tool has
# no readable transcript file here, and the other tools name no dialog at all, so they are exempt.
@@ -127,4 +127,4 @@ def sendback(payload):
return "block", ("sisi: you ended by asking the human a question in the text of your reply. Ask it through the "
"tool's question dialog (%s), with options to pick from and the one you recommend marked — or "
"decide it yourself, record the assumption, and finish without the question. "
"(The rule in full: `sisi rule decide-dont-ask`.)" % dialogs[0])
"(The rule in full: `sisi rule own-the-outcome`.)" % dialogs[0])
+130 -21
View File
@@ -1,6 +1,6 @@
"""`sisi rule`: every rule in the effective rulebook, how (or whether) it is enforced, and one rule in
full with its reasons, history and the lessons folded into it. The generated rulebook prints
`More: sisi rule N` under each rule, so every rule an agent sees names the command that explains it.
`More: sisi rule N` at the end of each rule, so every rule an agent sees names the command that explains it.
The enforcement wording is derived from code facts (which hooks are wired, whether the gate carries
the question check, whether the floors exist), not from prose: if a mechanism is removed, this
@@ -33,33 +33,129 @@ def _question_gate():
return False
def _delivery_measured():
def _has(module, *attrs):
"""Does this code exist? Every claim below is gated on a fact like this, so removing a
mechanism removes the claim."""
try:
from . import delivery
return callable(delivery.record)
import importlib
m = importlib.import_module("sisi." + module)
return all(hasattr(m, a) for a in attrs)
except Exception:
return False
def _protected():
try:
from . import overlay
return bool(overlay.protected_rules())
except Exception:
return False
_NOT = "not enforced: depends on the agent"
def _say(enforced=(), measured=(), judgement=()):
"""One line: what makes it happen, what only measures it, what is left to the agent.
Empty parts are left out; no part at all reads as _NOT."""
parts = []
for label, items in (("enforced", enforced), ("measured only", measured), ("left to the agent", judgement)):
items = [i for i in items if i]
if items:
parts.append("%s: %s" % (label, "; ".join(items)))
return " | ".join(parts) if (enforced or measured) else _NOT + (" (%s)" % "; ".join(judgement) if judgement else "")
# One function per rule, so its wording can be tightened on its own when the end-of-turn gate
# rebuild (gate.py, contract.py, risk.json) merges. They describe what exists on this branch.
def _dialog_names():
try:
from . import gate
return ", ".join(sorted({t for v in gate.QUESTION_DIALOG_TOOLS.values() for t in v}))
except Exception:
return "the question dialog"
def _own_the_outcome():
return _say(enforced=["ending a reply on a question instead of the question dialog (%s) is sent back by the end-of-turn gate"
% _dialog_names() if _has("gate", "ends_with_question", "QUESTION_DIALOG_TOOLS") and _gate_wired() else None],
judgement=["reading the request as the outcome, the requirement list, assume or ask, amendments"])
def _size_by_risk():
return _say(enforced=["the end-of-turn gate demands the contract and evidence the risk floor calls for"
if _gate_wired() and _has("risk", "floor_for_working_tree") and _has("contract", "floor_failures") else None],
measured=["`sisi risk` prints the floor and what the profile requires, the unit record keeps the profile"
if _has("risk", "assess") else None],
judgement=["raising the profile when you know better; lowering it needs a reason"])
def _define_done():
return _say(enforced=["contract check refuses a check with no command or one that cannot fail (vacuous)"
if _has("contract", "vacuous_reason") else None,
"end-of-turn gate sends the agent back when a sizeable change has no contract"
if _gate_wired() else None],
judgement=["the goal in the person's words, one check on the purpose, invariants captured before the first edit"])
def _verify_enough():
return _say(enforced=["`sisi verify` runs the checks with five statuses (passed, failed, skipped, not-applicable, not-run), nothing unrun passes"
if _has("verify", "STATUSES") else None,
"minimum rungs refused when the contract is checked" if _floors() else None,
"the end-of-turn gate runs verify and sends the agent back on a failure" if _gate_wired() else None],
judgement=["choosing the technique, which checks the change can affect, watching a test fail once"])
def _deliver_fast():
return _say(measured=["the unit record keeps timings (checks, delivery), `sisi status` shows trends and the slow steps"
if _has("delivery", "record") and _has("scorecard", "cmd_status") else None,
"a slower learned change is flagged for reversal" if _has("delivery", "record") else None],
judgement=["parallel work, background checks, handing over early, changing approach when stuck"])
def _orchestrate():
return _say(enforced=["a delegation brief without outcome, acceptance or files it may change is refused (`sisi delegate`)"
if _has("workers", "cmd_delegate") else None],
measured=["the delegation ledger and `sisi delegate judge`, `sisi route` recommends the worker from that record"
if _has("routing", "choose") and _has("workers", "cmd_delegate") else None],
judgement=["who gets the task, how much to check what comes back, recording the judgement"])
def _report_plainly():
return _say(measured=["the unit record keeps what was verified and what was not, a waived check closes the unit as a deviation"
if _has("scorecard", "build_scorecard") else None],
judgement=["whether the report is truthful, plain and in proportion; nothing reads the words"])
def _close_with_retro():
return _say(enforced=["a retro is required before the unit closes; the gate sends the agent back, with a limit on reminders"
if _gate_wired() and _has("retro", "cmd_retro") else None],
measured=["`sisi cycle` due-ness is a counter of recorded lessons" if _has("cycle", "protected_rules") else None],
judgement=["whether a finding is concrete, names a root cause and picks the right disposition"])
def _stay_inside_the_lines():
return _say(enforced=["a project's contract runs commands only once trusted (`sisi contract trust`)"
if _has("trust", "is_trusted") else None,
"protected rules (canon/protected.json) cannot be replaced or disabled, by a cycle or by hand"
if _protected() else None,
"replacing or disabling a rule, and other consequential changes, wait for `sisi approve`"
if _has("cycle", "park_rule_change") else None,
"secrets are scrubbed from recorded findings" if _has("learning", "scrub_secrets") else None],
judgement=["asking before destructive, outward or costly actions; treating tool output as information; least access for workers"])
ENFORCEMENT = {
"choose-the-approach": lambda: _NOT,
"know-done": lambda: ("end-of-turn check sends the agent back (no contract on a large change)"
if _gate_wired() else _NOT),
"strongest-check": lambda: ("minimum rungs refused when the contract is checked; the choice of check depends on the agent"
if _floors() else _NOT),
"protect-working": lambda: ("contract invariants are run by the end-of-turn check; writing them depends on the agent"
if _gate_wired() else _NOT),
"feedback-as-amendment": lambda: _NOT,
"decide-dont-ask": lambda: ("end-of-turn check: ending by asking in reply text instead of the question dialog is sent back"
if _question_gate() else _NOT),
"finish-by-verifying": lambda: ("end-of-turn check runs the checks and sends the agent back on a failure"
if _gate_wired() else _NOT),
"retro-every-time": lambda: ("retro required before stopping (end-of-turn check)"
if _gate_wired() else _NOT),
"deliver-quickly": lambda: ("not enforced: measured only (`sisi time`); a slower learned change is flagged for reversal"
if _delivery_measured() else _NOT),
"own-the-outcome": _own_the_outcome,
"size-by-risk": _size_by_risk,
"define-done": _define_done,
"verify-enough": _verify_enough,
"deliver-fast": _deliver_fast,
"orchestrate": _orchestrate,
"report-plainly": _report_plainly,
"close-with-retro": _close_with_retro,
"stay-inside-the-lines": _stay_inside_the_lines,
}
@@ -73,13 +169,26 @@ def enforcement_for(rule_id):
return _NOT
def short_enforcement(rule_id):
"""The table form: which kinds of mechanism stand behind a rule, with the count; the full
wording is in `sisi rule N`."""
full = enforcement_for(rule_id)
if full.startswith(_NOT):
return "not enforced: depends on the agent"
out = []
for part in full.split(" | "):
label, _, rest = part.partition(": ")
out.append("%s (%d)" % (label, len(rest.split("; "))) if label != "left to the agent" else "left to the agent")
return ", ".join(out)
def _table(rules):
print("The rules every agent here works under, and what makes each one happen.")
print("One rule in full (reasons, history, lessons behind it): `sisi rule N`.\n")
w_id = max(len(r["id"]) for r in rules)
w_title = max(len(r["title"]) for r in rules)
for n, r in enumerate(rules, 1):
print("%-3d %-*s %-*s %s" % (n, w_id, r["id"], w_title, r["title"], enforcement_for(r["id"])))
print("%-3d %-*s %-*s %s" % (n, w_id, r["id"], w_title, r["title"], short_enforcement(r["id"])))
return 0