From 4821a1b6a48cf91a35994b8f3ce1aff4000b1658 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 11:55:51 -0700 Subject: [PATCH 1/2] Learning loop: replay validated only when it ran, mechanisms carry earned scope, owner approval shown and gated, ledger of rows sisi wrote, subagent quarantine from session state, migration merges and reports, dead paths rewritten --- SECURITY.md | 34 + sisi/cli.py | 31 +- sisi/cycle.py | 959 ++++++++++++++++-------- sisi/evaluate.py | 126 +++- sisi/handover.py | 132 +--- sisi/learning.py | 524 +++++++++++--- sisi/lifecycle.py | 241 ++++--- sisi/overlay.py | 69 +- sisi/principles.py | 65 +- sisi/release.py | 207 +++--- sisi/retro.py | 126 ++-- sisi/risk.py | 4 +- sisi/rulecmd.py | 71 +- sisi/scope.py | 44 +- sisi/verifiers.py | 61 +- sisi/watch.py | 12 + tests/test_hooks_rework.py | 8 +- tests/test_learning_loop.py | 1360 ++++++++++++++++++++++++++++++----- tests/test_personal.py | 43 +- 19 files changed, 3017 insertions(+), 1100 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index 1d80d28..776a69b 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -16,6 +16,40 @@ written by someone else, and it is treated as such. - Every check has a time limit. After a few send-backs in a row the gate lets the agent through and marks the result unverified, so a broken check cannot hold a session forever. +## What learning can change, and who decides + +A learning cycle can install checks, rules and risk patterns that shape later sessions. What it may do alone is +limited, and the rest waits for you: + +- A mechanism a cycle installs carries its learning's id and the scope that learning has earned (its own project, + unless it was seen in two units in two projects, or you stated it at user scope). Nothing the cycle file claims + about scope or project is trusted: a request for more only makes the change wait. +- These always wait for you: more scope than earned, a shell command that was not seen to fail and then pass in its + own trusted project, a risk pattern that lowers a profile, any replaced or disabled rule, and rule text or a + library entry from a learning confined to one project. Protected rules (`canon/protected.json`) cannot be changed + by a cycle or by `sisi overlay` at all, and if that file cannot be read, no rule can be changed. +- Replaying a command check runs it, so a replay happens only in a repository on the trust list, only if the + command exists at both commits, and only if the earlier commit is an ancestor of the later one. + +`sisi approve` lists every waiting change in full (the exact command, the pattern and profile, the rule text as a +diff) and decides it with `--yes` or `--no`. What this does guarantee: a decision from a process with no terminal +(an agent, a script, a pipe) is refused, unless your config has `learning.agent_relayed_approval` set (off by +default), and then the record says `relayed by an agent`; every decision is written to `approvals.jsonl` with the +time, the session if known, and whether it came from a terminal. What it does not guarantee: sisi cannot tell a +person at a terminal from a program that allocates one, and anyone who can write your personal data folder can +edit the config, the pending list or the ledger directly. The protection is that an agent is told to show you the +change and to give you the command to type yourself, and that the cycle cannot apply anything consequential on its +own; it is not a defence against code that already runs with your permissions. + +The same limit applies to who recorded something. A learning recorded from a subagent is held as a candidate until +the parent adopts it by id. "Recorded by a subagent" is read from what the hooks recorded in the session record, not +from the environment; a tool without those hooks, or a process that picks another session id, is not detected. A +row added or edited by hand in `learnings.jsonl` is never delivered: only rows that sisi's own commands wrote, as +they wrote them, are in the ledger. `sisi learn` records whether your words appear in a message you typed in the +session transcript; when they do not, or there is no transcript, the statement is marked `relayed by an agent` +and `sisi oracle` shows that. `sisi learn --withdraw ID --reason ...` takes a statement recorded by mistake out of +delivery for good. + ## What sisi does not protect against - A trusted project's contract runs with your permissions. Trust only projects you trust. diff --git a/sisi/cli.py b/sisi/cli.py index 63db004..e2b10da 100644 --- a/sisi/cli.py +++ b/sisi/cli.py @@ -21,39 +21,46 @@ A shared rulebook and enforced definitions of done for every AI coding CLI. wire sisi into the tools (by reference), undo, inspect; --dry-run only prints what would change sisi release [--deep] run the source's checks, then make the stable copy the tools run (see docs/developing.md) sisi rollback switch the stable copy back to the previous release - sisi promote [ID|lesson:N] [--apply] | --export [PATH] - no ID: list core-tier items not yet in the product; an ID - scrubs a personal overlay item into the source folder and - drops the personal copy once the product contains it (dry - run unless --apply); lesson:N promotes a core lesson on a - from the clone; --export writes a contribution file + sisi promote [ID|L-NNNN] [--apply] | --export [PATH] + no ID: list items not yet in the product (learnings that change + sisi itself, or earned organization scope); an ID scrubs a + personal overlay item into the source folder and drops the + personal copy once the product contains it (dry run unless + --apply); L-NNNN promotes the rule or recipe a learning was + folded into, from the clone; --export writes a contribution file (universal text only; nothing is sent anywhere) sisi update fast-forward the product clone, then back up, migrate and rebuild personal data sisi export [PATH] | import PATH one tar.gz of personal data, results and session records; restore it sisi overlay list|diff|add-rule|replace-rule|disable-rule|enable-rule|add-verifier|...|revert COMMIT learned changes to rules, verifiers and recipes; each one a commit in your personal repo sisi retro print the unit's record and what stands out in it - sisi retro --finding F --cause C --impact value|correctness|time|cost|attention --disposition promote|record|drop [--same-as ID] + sisi retro --finding F --cause C --impact value|correctness|time|cost|attention --disposition promote|record|drop [--same-as ID | --new] [--target ID] record one finding; promote also needs --change, --mechanism, - --expect and --validate; record needs --limits; drop needs --why-not + --expect and --validate; record needs --limits; drop needs --why-not; + a match in scope is printed and attached as a recurrence (--new records + a learning of its own); --target names the rule or recipe it concerns + sisi retro --adopt ID a parent adopts a subagent's candidate learning, by id sisi lessons [--json] | show ID the learning records and their statuses sisi cycle [due|apply FILE|check FILE|revert [ID]|help] turn proposed learnings into mechanisms (no scheduler: due-ness is a counter); apply validates and replays before promoting; help prints the cycle file format - sisi approve [ID --yes|--no] decide a consequential learning change a cycle parked + sisi approve [ID --yes|--no] list, in full, the consequential changes waiting for the owner; decide one + (in a terminal: an agent's --yes without one is refused) sisi learn [--scope user|project] TEXT record an owner statement; it takes effect at once and `sisi oracle` prints it. Scope for other learnings is earned by evidence, never claimed + sisi learn --withdraw ID --reason WHY + take a statement recorded by mistake out of delivery (kept in history) sisi risk [--json] risk floor for the working-tree change, with reasons and what that profile requires sisi handover [--all] | done ID --where PATH [--quote FRAGMENT] - project items waiting to be filed in this project's own docs or + project-scope learnings waiting to be filed in this project's own docs or work list; done confirms one is filed (the named file must contain - its key text) and removes it from the pile + its key text) and removes it from the list sisi oracle print what the human wants: the standing principles from - `sisi learn`, live at once (oracle.md in the personal folder) + `sisi learn`, live at once (project-scoped ones only in their project) sisi status verification statistics from the store sisi time [--json] time from request to verified result: 7 days against the 7 before, slowest checks sisi verifiers [WORDS] [--lang L] [--kind K] [--rung N] [--section S] [--installed] [--json] diff --git a/sisi/cycle.py b/sisi/cycle.py index 4a1d804..5e78ca2 100644 --- a/sisi/cycle.py +++ b/sisi/cycle.py @@ -1,12 +1,21 @@ """The learning cycle: proposed learnings become mechanisms in the user store. Due by a counter (no scheduler). A worker writes a cycle file; `sisi cycle apply FILE` -treats it as untrusted input, validates everything before changing anything, replays -command checks against the originating unit's commits in a temporary worktree, refuses -protected rules, parks consequential changes for `sisi approve`, and commits each change -to the user store so revert is exact. What cannot be replayed is promoted as -`unvalidated` and always reported as such; nothing is labelled `validated` without a -validation run that passed. +treats it as untrusted input, validates and plans everything before writing anything, +replays command checks against the originating unit's commits in a temporary worktree +(one replay implementation: evaluate.validate_command), refuses protected rules, parks +consequential changes for the owner (`sisi approve`), and commits each change to the user +store so revert is exact. What cannot be replayed is `unvalidated` and always reported as +such; nothing is labelled `validated` without a validation run that passed. + +What a mechanism reaches is decided here from the learning, never from the cycle file: a +mechanism is written with the learning's id and the scope the learning has *earned* +(learning.earned_scope: its origin project, unless it was seen in two units in two projects or +is an owner statement made at user scope). A scope or `every_project` flag in the file is only +a request for more; a request for more than the learning has earned, any enforced command that +is not proven in its origin project, any risk pattern that lowers a profile, any replacement or +disabling of a rule, and any rule or library entry from a learning confined to one project +wait for the owner. Readers filter by project; nothing reads a flag the cycle author wrote. Cycle file (JSON): {"base": "", "actions": [ @@ -26,39 +35,118 @@ Cycle file (JSON): "name": "csv-import", "case": {"...": "..."}}, {"action": "revise"|"revert"|"reject", "learning": "L-0008", "why": "..."}]} -Mechanism data files other modules read (all in the user store overlay): - enforced.json {"checks": [{"type": "command"|"contract-requirement", "lesson": id, ...}]} - risk-adjustments.json {"adjustments": [{"pattern", "profile", "learning"}]} - routing-adjustments.json {"adjustments": [{"kind", "difficulty", "prefer"|"avoid", "learning"}]} +Mechanism data files (user store overlay); every entry carries learning, scope, project: + enforced.json {"checks": [{"type": "command"|"contract-requirement", "learning": id, ...}]} + risk-adjustments.json {"adjustments": [{"pattern", "profile", "learning", ...}]} + routing-adjustments.json {"adjustments": [{"kind", "difficulty", "prefer"|"avoid", "learning", ...}]} benchmarks/.json one benchmark case per file """ -import json, os, shutil, subprocess, sys, tempfile, time +import copy, difflib, json, os, re, sys, time -from . import documents, 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) MECHANISM_KINDS = ("contract-requirement", "command-check", "library", "rule-text", "risk", "routing", "benchmark") +GLOBAL_KINDS = ("rule-text", "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 +# and findings written after the cycle survive a revert. +CYCLE_FIELDS = ("status", "validation", "mechanism_ref", "mechanism_scope", "promoted_at", + "flagged_not_working", "recurrences_after_promotion", "version", "history", "proposed") +STORE_FILES = {"learnings.jsonl", "learnings-ledger.jsonl", "pending.json", "findings.jsonl", + "approvals.jsonl"} +SAFE_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]*$") class CycleError(Exception): pass -# ---- enforced checks (verify.py seam; shape unchanged) -------------------------- +def protected_rules(): + try: + return overlay.protected_rules() + except overlay.OverlayError as e: + raise CycleError(str(e)) + + +# ---- mechanism entries and who they apply to ------------------------------------ + +def _overlay_json(rel, key): + try: + with open(paths.overlay_dir(rel), encoding="utf-8") as f: + d = json.load(f) + return d if isinstance(d, dict) else {key: []} + except (OSError, ValueError): + return {key: []} + + +def _put_json(rel, d, msg): + pdata.write_text("overlay/" + rel, json.dumps(d, indent=2, sort_keys=True) + "\n") + pdata.commit(msg, ["overlay/" + rel]) + + +class _Authority: + """Reads, once per call, what decides whether a wider-than-project entry may apply.""" + + def __init__(self): + self.rows = {r["id"]: r for r in L.load_learnings()} + self.ledger = L.load_ledger() + self.approved = L.approved_ids() + + def allows(self, e): + sc = e.get("scope") + if e.get("approval") in self.approved: + return True + rec = self.rows.get(e.get("learning")) + return bool(rec is not None and L.is_registered(rec, self.ledger) + and L.SCOPE_RANK.get(L.earned_scope(rec), 0) >= L.SCOPE_RANK.get(sc, 99)) + + +def entry_applies(e, project, auth=None): + """Does this mechanism entry apply in this project? A project entry only in its own project; + a wider entry only while the learning has earned that scope or the owner approved it.""" + sc = e.get("scope") + if sc == "project": + return bool(e.get("project")) and e.get("project") == L.project_key(project) + if sc in ("user", "organization"): + return (auth or _Authority()).allows(e) + return False # an entry that names no scope applies nowhere + + +def adjustments(rel, project): + d = _overlay_json(rel, "adjustments") + items = [x for x in d.get("adjustments", []) if isinstance(x, dict)] + if not items: + return [] + auth = _Authority() + return [x for x in items if entry_applies(x, project, auth)] + + +def risk_patterns(cwd): + """Risk-table patterns learned by cycles that apply in this project (risk.py reads these).""" + return [{"glob": e["pattern"], "profile": e["profile"], "reason": "learning %s" % e.get("learning")} + for e in adjustments("risk-adjustments.json", cwd) if e.get("pattern") and e.get("profile")] + + +def routing_adjustments(project): + return adjustments("routing-adjustments.json", project) + + +# ---- enforced checks (verify.py seam) ---------------------------------------------- def enforced_path(): return paths.overlay_dir("enforced.json") -def load_enforced(): - try: - with open(enforced_path(), encoding="utf-8") as f: - d = json.load(f) - checks = d.get("checks") if isinstance(d, dict) else None - return [c for c in checks if isinstance(c, dict)] if isinstance(checks, list) else [] - except (OSError, ValueError): +def load_enforced(project=None): + """Enforced checks; with a project, only those that apply in it.""" + checks = [c for c in _overlay_json("enforced.json", "checks").get("checks", []) if isinstance(c, dict)] + if project is None: + return checks + if not checks: return [] + auth = _Authority() + return [c for c in checks if entry_applies(c, project, auth)] def _requirement_met(c, entry): @@ -74,17 +162,17 @@ def _requirement_met(c, entry): def enforced_results(c, project, deadline=None, default_timeout=60): - """Result rows for enforced checks, in the shape verify.run returns. Command checks run - only in trusted projects; only checks installed by a validated cycle run.""" + """Result rows for enforced checks, in the shape verify.run returns. Only checks whose + scope reaches this project; command checks run only in trusted projects.""" out = [] - checks = load_enforced() + checks = load_enforced(project) if not checks: return out from . import trust, verify as V trusted = trust.is_trusted(project) for e in checks: - lid = e.get("lesson") - base = {"item": "enforced", "tier": "fast", "id": "enforced:lesson-%s" % lid, "kind": None, + lid = e.get("learning") + base = {"item": "enforced", "tier": "fast", "id": "enforced:learning-%s" % lid, "kind": None, "rung": None, "claim": "enforced learning %s" % lid, "duration_s": 0.0, "tail": ""} if e.get("type") == "contract-requirement": if not _requirement_met(c, e): @@ -105,36 +193,44 @@ def enforced_results(c, project, deadline=None, default_timeout=60): def proposed(rows=None): rows = L.load_learnings() if rows is None else rows - return [r for r in rows if r.get("status") == "proposed" and not r.get("candidate")] + ledger = L.load_ledger() + return [r for r in rows if r.get("status") == "proposed" and not r.get("candidate") + and L.is_registered(r, ledger)] def due_notice(session=None): + """Session-start lines: a cycle is due, and/or a decision waits for the owner.""" try: - pend = L.pending_notice() n = len(proposed()) fl = len(L.flagged()) - parts = [] + lines = [] if n >= DUE_AFTER or fl: - parts.append("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 "")) + pend = L.pending_notice() if pend: - parts.append(pend) - return "sisi: " + "; ".join(parts) if parts else "" + lines.append(pend) + return "\n".join(lines) except Exception: return "" def brief_text(): rows = L.load_learnings() + changed = L.monitor(rows) + if changed: + L.save_learnings(rows, "monitoring: %d learning(s) now monitored" % len(changed), touched=changed, via="cycle") lines = ["Learning cycle brief. Base: %s" % L.store_base(rows), "", "Write one cycle file (JSON, format in `sisi cycle help`) turning proposed " "learnings into mechanisms. Prefer an executable mechanism over rule text. " "A command check is replayed against its unit's commits and must fail before " - "the fix and pass after. Protected rules (canon/protected.json) cannot be " - "touched. Consequential changes wait for the owner.", ""] + "the fix and pass after (the repository must be trusted and the command must exist " + "at both commits). A mechanism reaches only the scope its learning has earned; " + "anything wider, any command that is not proven, any replaced or disabled rule " + "waits for the owner. Protected rules (canon/protected.json) cannot be touched.", ""] for r in proposed(rows): - lines.append("- %s [%s] %s\n change: %s\n expect: %s validate: %s" - % (r["id"], r.get("proposed", {}).get("mechanism"), r.get("title"), + lines.append("- %s [%s] %s (earned scope: %s)\n change: %s\n expect: %s validate: %s" + % (r["id"], r.get("proposed", {}).get("mechanism"), r.get("title"), L.earned_scope(r), r.get("proposed", {}).get("description"), r.get("expected_effect"), (r.get("validation") or {}).get("method"))) for r in L.flagged(rows): @@ -143,368 +239,633 @@ def brief_text(): return "\n".join(lines) + "\n" -# ---- protected rules -------------------------------------------------------------- - -def protected_rules(): - try: - with open(paths.canon("protected.json"), encoding="utf-8") as f: - d = json.load(f) - return set(d.get("rules") or []) - except (OSError, ValueError): - return set() - - -# ---- replay validation -------------------------------------------------------------- - -def _run_at(repo, sha, cmd, timeout=120): - """Run cmd in a temporary worktree at sha. Never touches the user's working tree.""" - tmp = tempfile.mkdtemp(prefix="sisi-replay-") - wt = os.path.join(tmp, "wt") - try: - p = subprocess.run(["git", "worktree", "add", "--detach", "-q", wt, sha], cwd=repo, - capture_output=True, text=True, timeout=60) - if p.returncode != 0: - return None, "worktree at %s failed: %s" % (sha[:12], (p.stderr or "").strip()[:200]) - try: - p = subprocess.run(cmd, shell=True, cwd=wt, capture_output=True, text=True, timeout=timeout) - return p.returncode, (p.stdout + p.stderr)[-400:] - except subprocess.TimeoutExpired: - return None, "timed out" - finally: - subprocess.run(["git", "worktree", "remove", "--force", wt], cwd=repo, - capture_output=True, timeout=60) - shutil.rmtree(tmp, ignore_errors=True) - +# ---- replay validation (one implementation: evaluate.validate_command) ----------------- def replay_validate(rec, action): - """(result, detail): 'validated' only when the check fails before and passes after.""" + """(result, detail): `validated` only when the command ran and failed before the fix and ran + and passed after it, in the learning's own, trusted project; `unvalidated` (with the reason) + when it could not be shown; `failed` when it ran and did not behave so.""" cmd = action.get("cmd") or "" exp = (action.get("expect") or {}).get("exit", 0) replay = rec.get("replay") or {} - repo = action.get("repo") or replay.get("repo") or rec.get("origin_project") + repo = L.normalize_project(action.get("repo") or replay.get("repo") or rec.get("origin_project")) before = action.get("before") or replay.get("before") after = action.get("after") or replay.get("after") - if not before or not after: - # ask groundtruth for the unit's commits when it knows them - try: - from . import groundtruth - if repo and not before: - before = None # no start commit on the record: honestly unvalidated below - except Exception: - pass if not (repo and before and after and cmd): - return "unvalidated", "no before/after commits known; promoted as unvalidated" - rb, db = _run_at(repo, before, cmd) - ra, da = _run_at(repo, after, cmd) - if rb is None or ra is None: - return "unvalidated", "replay could not run (%s / %s); promoted as unvalidated" % (db, da) - if rb != exp and ra == exp: - return "validated", "replay: failed at %s (exit %d), passed at %s" % (before[:12], rb, after[:12]) - return "failed", "replay: exit %d before, %d after (expected fail then %d)" % (rb, ra, exp) + return "unvalidated", "no before/after commits are known, so the command was never replayed" + if repo != rec.get("origin_project"): + return "unvalidated", "the repository is not this learning's origin project; no replay was run" + out = evaluate.validate_command(repo, before, after, cmd, exp) + if out["outcome"] == "validated": + return "validated", "replay: failed at %s, passed at %s" % (str(before)[:12], str(after)[:12]) + if out["outcome"] == "not-run": + return "unvalidated", "replay did not establish it: %s" % out.get("reason") + return "failed", "replay: %s" % (out.get("reason") or out["outcome"]) -# ---- validation of a cycle file (untrusted input; all-or-nothing) ------------------- +# ---- planning a cycle file (untrusted input; nothing is written here) ------------------- -def _consequential(action, rec): - """Disabling a rule, widening scope to all projects, or a command in every project.""" - if action.get("action") == "disable-rule": +def _need(cond, msg): + if not cond: + raise CycleError(msg) + + +def _text(a, key, rid): + v = a.get(key) + _need(isinstance(v, str) and v.strip(), "%s for %s needs %s" % (a.get("mechanism_kind"), rid, key)) + return v + + +def _risk_lowers(pattern, profile): + from . import risk + if profile == "trivial": return True - if action.get("scope") == "organization": - return True - if action.get("mechanism_kind") == "command-check" and action.get("every_project"): - return True - return False + sample = re.sub(r"\*+", "x", pattern) + cur, _why = risk.assess([sample], patterns=risk._patterns_from(risk.default_table())) + return risk._ORDER[profile] < risk._ORDER[cur] + + +def _plan_promote(a, rec, virtual_rules): + """(normalized action, reasons that make it consequential, granted scope, replay).""" + kind = a.get("mechanism_kind") + lid = rec["id"] + _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", + "learning %s is a tool change to sisi itself; it goes to the backlog and the contribution " + "export (`sisi promote --export`), not a cycle mechanism" % lid) + _need(not rec.get("candidate"), "learning %s is a subagent candidate; a parent retro must adopt it first " + "(`sisi retro --adopt %s`)" % (lid, lid)) + n = {"action": "promote", "learning": lid, "mechanism_kind": kind} + reasons, replay = [], None + earned = L.earned_scope(rec) + asked = a.get("scope") or ("organization" if a.get("every_project") else None) + _need(asked in (None, "project", "user", "organization"), "scope for %s must be project|user|organization" % lid) + base = "user" if kind in GLOBAL_KINDS else ("project" if kind == "command-check" else earned) + granted = base + if asked and L.SCOPE_RANK[asked] > L.SCOPE_RANK[base]: + granted = asked + 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"]: + reasons.append("%s changes what every project loads, and learning %s has earned only its own project" + % (kind, lid)) + 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)) + + if kind == "command-check": + n["cmd"] = _text(a, "cmd", lid).strip() + exp = a.get("expect") if isinstance(a.get("expect"), dict) else {} + n["expect"] = {"exit": exp.get("exit", 0)} + for k in ("before", "after", "repo"): + if isinstance(a.get(k), str): + n[k] = a[k] + if a.get("timeout_s") is not None: + _need(isinstance(a["timeout_s"], (int, float)) and 0 < a["timeout_s"] <= 600, + "timeout_s for %s must be between 0 and 600" % lid) + n["timeout_s"] = a["timeout_s"] + replay = replay_validate(rec, n) + _need(replay[0] != "failed", "replay validation failed for %s: %s; nothing is applied" % (lid, replay[1])) + if replay[0] != "validated": + reasons.append("an enforced command nobody has seen fail and then pass in its own project (%s)" % replay[1]) + if L.SCOPE_RANK[granted] > 0: + reasons.append("an enforced command that would run outside the origin project") + elif kind == "contract-requirement": + n["when"], n["require_kind"] = _text(a, "when", lid), _text(a, "require_kind", lid) + if a.get("max_rung") is not None: + _need(isinstance(a["max_rung"], int), "max_rung for %s must be an integer" % lid) + n["max_rung"] = a["max_rung"] + elif kind == "rule-text": + rid = a.get("rule_id") + _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": + _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) + eid = a.get("entry_id") + _need(eid is None or (isinstance(eid, str) and overlay.ID_OK.match(eid)), "entry_id for %s is not a plain id" % lid) + n["entry_id"], n["replacing"] = eid, bool(a.get("replacing")) + try: + n["entry_id"], _rel, _mine = overlay._put_entry(n["library_kind"], n["entry_text"], eid, n["replacing"]) + except overlay.OverlayError as e: + raise CycleError("library entry for %s: %s" % (lid, e)) + if n["replacing"]: + reasons.append("replaces the existing %s %s" % (n["library_kind"], n["entry_id"])) + elif kind == "risk": + from . import risk + pat, prof = _text(a, "pattern", lid), a.get("profile") + _need(prof in risk.PROFILES, "risk profile for %s must be one of %s" % (lid, "|".join(risk.PROFILES))) + n["pattern"], n["profile"] = pat, prof + if _risk_lowers(pat, prof): + reasons.append("a risk pattern that lowers a profile (%s -> %s)" % (pat, prof)) + elif kind == "routing": + _need(a.get("kind") and (a.get("prefer") or a.get("avoid")), "routing for %s needs kind and prefer|avoid" % lid) + n.update({k: a[k] for k in ("kind", "difficulty", "prefer", "avoid") if a.get(k) is not None}) + elif kind == "benchmark": + name = a.get("name") + _need(isinstance(name, str) and SAFE_NAME.match(name) and ".." not in name, + "benchmark for %s needs a plain name" % lid) + _need(isinstance(a.get("case"), dict), "benchmark for %s needs a case object" % lid) + n["name"], n["case"] = name, a["case"] + return n, reasons, granted, replay def validate_doc(doc, rows): - """Every refusal is raised before anything is applied. Returns (normal, pending).""" + """Every refusal is raised before anything is applied. Returns the plan: a list of + {"kind": status|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"]: raise CycleError("the cycle file must be JSON with a non-empty \"actions\" list") base = doc.get("base") if base != L.store_base(rows): raise CycleError("stale base: the cycle was written against %r but the store is at %r; " "take a fresh brief (`sisi cycle`)" % (base, L.store_base(rows))) - prot = protected_rules() - normal, pending = [], [] - acted = set() + ledger = L.load_ledger() + plan, acted, virtual = [], set(), {} for a in doc["actions"]: - if not isinstance(a, dict): - raise CycleError("every action must be an object") + _need(isinstance(a, dict), "every action must be an object") act = a.get("action") if act == "disable-rule": rid = a.get("rule_id") - if rid in prot: - raise CycleError("rule %r is protected (canon/protected.json); a cycle may not touch it" % rid) - pending.append(a) # disabling any rule is consequential + _need(isinstance(rid, str) and rid, "disable-rule needs a rule_id") + _need(rid not in protected_rules(), "rule %r is protected (canon/protected.json); a cycle may not touch it" % rid) + known = {x["id"] for x in overlay.base_rules()[1]} | set(overlay.overlay_rules()) + _need(rid in known, "no rule %r" % rid) + plan.append({"kind": "disable-rule", "action": {"action": "disable-rule", "rule_id": rid}, + "rec": None, "pending": True, "scope": None, "replay": None, + "reasons": ["disables the rule %s" % rid]}) continue rec = L.get(rows, a.get("learning") or "") - if rec is None: - raise CycleError("no learning %r" % a.get("learning")) + _need(rec is not None, "no learning %r" % a.get("learning")) + _need(L.is_registered(rec, ledger), "learning %s was not written by sisi's own commands " + "(added or edited by hand); a cycle does not act on it" % rec["id"]) acted.add(rec["id"]) if act in ("revise", "revert", "reject"): - if not (a.get("why") or "").strip(): - raise CycleError("%s of %s needs a why" % (act, rec["id"])) - normal.append((a, rec)) + _need((a.get("why") or "").strip(), "%s of %s needs a why" % (act, rec["id"])) + plan.append({"kind": "status", "action": {"action": act, "learning": rec["id"], "why": a["why"]}, + "rec": rec, "pending": False, "scope": None, "replay": None, "reasons": []}) continue - if act != "promote": - raise CycleError("unknown action %r" % act) - if rec.get("candidate"): - raise CycleError("learning %s is a subagent candidate; a parent retro must adopt it first" % rec["id"]) - kind = a.get("mechanism_kind") - if kind not in MECHANISM_KINDS: - raise CycleError("mechanism_kind for %s must be one of %s" % (rec["id"], "|".join(MECHANISM_KINDS))) - if rec.get("proposed", {}).get("mechanism") == "tool": - raise CycleError("learning %s is a tool change to sisi itself; it goes to the backlog " - "and the contribution export, not a cycle mechanism" % rec["id"]) - if kind == "command-check": - if not (a.get("cmd") or "").strip(): - raise CycleError("command-check for %s needs a cmd" % rec["id"]) - if not _consequential(a, rec): # replay now, so a failed replay refuses before anything applies - a["_replay"] = replay_validate(rec, a) - if a["_replay"][0] == "failed": - raise CycleError("replay validation failed for %s: %s; nothing is applied" - % (rec["id"], a["_replay"][1])) - if kind == "contract-requirement" and not (a.get("require_kind") and a.get("when")): - raise CycleError("contract-requirement for %s needs when and require_kind" % rec["id"]) - if kind == "rule-text": - rid = a.get("rule_id") - if rid in prot: - raise CycleError("rule %r is protected (canon/protected.json); a cycle may not touch it" % rid) - documents.check_rule_text(a.get("rule_text") or "", rid) - if kind == "library" and a.get("library_kind") not in ("recipe", "verifier"): - raise CycleError("library for %s needs library_kind recipe|verifier and entry_text" % rec["id"]) - if kind == "risk" and not (a.get("pattern") and a.get("profile")): - raise CycleError("risk for %s needs pattern and profile" % rec["id"]) - if kind == "routing" and not (a.get("kind") and (a.get("prefer") or a.get("avoid"))): - raise CycleError("routing for %s needs kind and prefer|avoid" % rec["id"]) - if kind == "benchmark" and not (a.get("name") and isinstance(a.get("case"), dict)): - raise CycleError("benchmark for %s needs a name and a case object" % rec["id"]) - (pending if _consequential(a, rec) else normal).append((a, rec) if not _consequential(a, rec) else a) + _need(act == "promote", "unknown action %r" % act) + n, reasons, granted, replay = _plan_promote(a, rec, virtual) + plan.append({"kind": "promote", "action": n, "rec": rec, "pending": bool(reasons), + "scope": granted, "replay": replay, "reasons": reasons}) ignored = [r["id"] for r in L.flagged(rows) if r["id"] not in acted] - if ignored: - raise CycleError("this cycle ignores learning(s) flagged not working: %s; " - "revise or revert each one" % ", ".join(ignored)) - return normal, pending + _need(not ignored, "this cycle ignores learning(s) flagged not working: %s; " + "revise or revert each one" % ", ".join(ignored)) + return plan # ---- applying ----------------------------------------------------------------------- -def _overlay_json(rel, key): - try: - with open(paths.overlay_dir(rel), encoding="utf-8") as f: - d = json.load(f) - return d if isinstance(d, dict) else {key: []} - except (OSError, ValueError): - return {key: []} +def _remove_mechanisms(lid, msg): + for rel, key in (("enforced.json", "checks"), ("risk-adjustments.json", "adjustments"), + ("routing-adjustments.json", "adjustments")): + d = _overlay_json(rel, key) + kept = [c for c in d.get(key, []) if c.get("learning") != lid] + if kept != d.get(key, []): + d[key] = kept + _put_json(rel, d, "cycle: %s removes its %s" % (msg, rel)) -def _apply_one(a, rec, rows): - """Apply one validated action; commits to the user store. Returns a report line.""" - lid = rec["id"] - kind = a.get("mechanism_kind") - ref, result, detail = None, "unvalidated", "no replay for this mechanism kind" +def _stamp(entry, rec, granted, approval): + entry.update({"learning": rec["id"], "scope": granted, "project": rec.get("origin_project")}) + if approval: + entry["approval"] = approval + return entry + + +def _apply_mechanism(a, rec, granted, approval=None): + """Write one mechanism. Returns its reference text.""" + lid, kind = rec["id"], a["mechanism_kind"] if kind == "command-check": - result, detail = a.get("_replay") or replay_validate(rec, a) - if result == "failed": - raise CycleError("replay validation failed for %s: %s" % (lid, detail)) d = _overlay_json("enforced.json", "checks") - d.setdefault("checks", []).append( - {"type": "command", "lesson": lid, "cmd": a["cmd"], - "expect": a.get("expect") or {"exit": 0}, "timeout_s": a.get("timeout_s")}) - pdata.write_text("overlay/enforced.json", json.dumps(d, indent=2, sort_keys=True) + "\n") - pdata.commit("cycle: enforced command check for %s" % lid, ["overlay/enforced.json"]) - ref = "enforced command check" - elif kind == "contract-requirement": + d.setdefault("checks", []).append(_stamp( + {"type": "command", "cmd": a["cmd"], "expect": a.get("expect") or {"exit": 0}, + "timeout_s": a.get("timeout_s")}, rec, granted, approval)) + _put_json("enforced.json", d, "cycle: enforced command check for %s" % lid) + return "enforced command check" + if kind == "contract-requirement": d = _overlay_json("enforced.json", "checks") - d.setdefault("checks", []).append( - {"type": "contract-requirement", "lesson": lid, "when": a["when"], - "require_kind": a["require_kind"], "max_rung": a.get("max_rung")}) - pdata.write_text("overlay/enforced.json", json.dumps(d, indent=2, sort_keys=True) + "\n") - pdata.commit("cycle: enforced contract requirement for %s" % lid, ["overlay/enforced.json"]) - ref = "enforced contract requirement" - elif kind == "rule-text": + d.setdefault("checks", []).append(_stamp( + {"type": "contract-requirement", "when": a["when"], "require_kind": a["require_kind"], + "max_rung": a.get("max_rung")}, rec, granted, approval)) + _put_json("enforced.json", d, "cycle: enforced contract requirement for %s" % lid) + return "enforced contract requirement" + if kind == "rule-text": rid = a["rule_id"] known = {x["id"] for x in overlay.base_rules()[1]} | set(overlay.overlay_rules()) if rid in known: overlay.replace_rule(rid, a["rule_text"]) else: overlay.add_rule(a["rule_text"], rid) - ok, msg = documents.check_budgets() - if not ok: - raise CycleError("rule-text for %s breaks the rulebook budget: %s" % (lid, msg)) overlay.build_canon() - ref = "rule %s" % rid - elif kind == "library": - eid = overlay.put_entry("recipe" if a["library_kind"] == "recipe" else "verifier", - a["entry_text"], a.get("entry_id"), + rec.setdefault("proposed", {})["target"] = rec.get("proposed", {}).get("target") or rid + return "rule %s" % rid + if kind == "library": + eid = overlay.put_entry(a["library_kind"], a["entry_text"], a.get("entry_id"), replacing=bool(a.get("replacing"))) - ref = "%s %s" % (a["library_kind"], eid) - elif kind == "risk": + rec.setdefault("proposed", {})["target"] = rec.get("proposed", {}).get("target") or eid + return "%s %s" % (a["library_kind"], eid) + if kind == "risk": d = _overlay_json("risk-adjustments.json", "adjustments") - d.setdefault("adjustments", []).append( - {"pattern": a["pattern"], "profile": a["profile"], "learning": lid}) - pdata.write_text("overlay/risk-adjustments.json", json.dumps(d, indent=2, sort_keys=True) + "\n") - pdata.commit("cycle: risk adjustment for %s" % lid, ["overlay/risk-adjustments.json"]) - ref = "risk %s -> %s" % (a["pattern"], a["profile"]) - elif kind == "routing": + d.setdefault("adjustments", []).append(_stamp( + {"pattern": a["pattern"], "profile": a["profile"]}, rec, granted, approval)) + _put_json("risk-adjustments.json", d, "cycle: risk adjustment for %s" % lid) + return "risk %s -> %s" % (a["pattern"], a["profile"]) + if kind == "routing": d = _overlay_json("routing-adjustments.json", "adjustments") - adj = {"kind": a["kind"], "difficulty": a.get("difficulty"), "learning": lid} - if a.get("prefer"): - adj["prefer"] = a["prefer"] - if a.get("avoid"): - adj["avoid"] = a["avoid"] - d.setdefault("adjustments", []).append(adj) - pdata.write_text("overlay/routing-adjustments.json", json.dumps(d, indent=2, sort_keys=True) + "\n") - pdata.commit("cycle: routing adjustment for %s" % lid, ["overlay/routing-adjustments.json"]) - ref = "routing %s" % a["kind"] - elif kind == "benchmark": + adj = {k: a[k] for k in ("kind", "difficulty", "prefer", "avoid") if a.get(k) is not None} + d.setdefault("adjustments", []).append(_stamp(adj, rec, granted, approval)) + _put_json("routing-adjustments.json", d, "cycle: routing adjustment for %s" % lid) + return "routing %s" % a["kind"] + if kind == "benchmark": rel = "overlay/benchmarks/%s.json" % a["name"] - pdata.write_text(rel, json.dumps(dict(a["case"], learning=lid), indent=2, sort_keys=True) + "\n") + case = _stamp(dict(a["case"]), rec, granted, approval) + pdata.write_text(rel, json.dumps(case, indent=2, sort_keys=True) + "\n") pdata.commit("cycle: benchmark case for %s" % lid, [rel]) - ref = "benchmark %s" % a["name"] - method = rec["validation"].get("method") or ("replay" if kind == "command-check" else "") + return "benchmark %s" % a["name"] + raise CycleError("unknown mechanism kind %r" % kind) + + +def _promoted(rec, ref, granted, replay): + result, detail = replay if replay else ("unvalidated", "no replay for this mechanism kind") + method = rec["validation"].get("method") or ("replay" if replay else "") rec["validation"].update(result=result, detail=detail, method=method) rec["status"] = "promoted" rec["mechanism_ref"] = ref + rec["mechanism_scope"] = granted rec["promoted_at"] = L.now() - rec["promoted_unit_seq"] = L.unit_seq() rec["flagged_not_working"] = False rec["recurrences_after_promotion"] = 0 rec["version"] = int(rec.get("version") or 1) + 1 - L.save_learnings(rows, "cycle: promote %s (%s)" % (lid, result)) - return "%s promoted as %s: %s (%s)" % (lid, result, ref, detail) + return "%s promoted as %s: %s (%s)" % (rec["id"], result, ref, detail) -def _apply_status(a, rec, rows): +def _apply_status(a, rec): act = a["action"] rec["status"] = {"revise": "revised", "revert": "reverted", "reject": "rejected"}[act] rec["flagged_not_working"] = False - rec.setdefault("history", []).append({"ts": L.now(), "action": act, "why": a.get("why", "")}) + rec.setdefault("history", []).append({"ts": L.now(), "action": act, "why": L.scrub_secrets(a.get("why", ""))}) if act in ("revert", "revise"): - d = _overlay_json("enforced.json", "checks") - kept = [c for c in d.get("checks", []) if c.get("lesson") != rec["id"]] - if kept != d.get("checks", []): - d["checks"] = kept - pdata.write_text("overlay/enforced.json", json.dumps(d, indent=2, sort_keys=True) + "\n") - pdata.commit("cycle: %s %s removes its enforced check" % (act, rec["id"]), ["overlay/enforced.json"]) - L.save_learnings(rows, "cycle: %s %s" % (act, rec["id"])) + _remove_mechanisms(rec["id"], "%s %s" % (act, rec["id"])) return "%s %s: %s" % (rec["id"], rec["status"], a.get("why", "")) +def _park(item_action, rec, reasons, granted, replay, items, added): + pid = L.next_pending_id(items) + items.append({"id": pid, "ts": L.now(), "learning": rec["id"] if rec else None, "action": item_action, + "reasons": reasons, "scope": granted, "replay": list(replay) if replay else None}) + added.append(pid) + return pid + + def _head(): p = pdata.git("rev-parse", "HEAD", check=False) return p.stdout.strip() if p.returncode == 0 else None -def apply_file(path): - """Validate everything, then apply. A refusal changes nothing.""" +def _show(rev, rel): + p = pdata.git("show", "%s:%s" % (rev, rel), check=False) + return p.stdout if p.returncode == 0 else None + + +def _changed(a, b): + p = pdata.git("diff", "--name-only", a, b, check=False) + return [x for x in p.stdout.splitlines() if x] + + +def _restore_files(before, files): + """Put each of these store files back as it was at `before` (or remove it if it did not exist).""" + done = [] + for f in files: + old = _show(before, f) + p = paths.data_file(f) + if old is None: + if os.path.exists(p): + os.remove(p) + else: + pdata.write_text(f, old) + done.append(f) + return done + + +def _cycle_records(): + d = paths.data_file("cycles") + out = [] + for n in sorted(os.listdir(d)) if os.path.isdir(d) else []: + if n.endswith(".json"): + try: + with open(os.path.join(d, n), encoding="utf-8") as f: + r = json.load(f) + if isinstance(r, dict): + out.append(r) + except (OSError, ValueError): + pass + return out + + +def cycle_records(): + """The cycle records, oldest first (id, ts, before, after, lines, changed, ...).""" + return _cycle_records() + + +def _transact(label, fn): + """Run fn() -> (report lines, touched learning ids, pending ids added) as one cycle: every + write is committed, the cycle is recorded with what it needs to be reverted exactly, and a + failure part-way restores every file it changed.""" pdata.ensure() - with open(path, encoding="utf-8") as f: - try: - doc = json.load(f) - except ValueError as e: - raise CycleError("the cycle file is not JSON: %s" % e) - rows = L.load_learnings() - normal, pending = validate_doc(doc, rows) before = _head() - lines = [] - for a, rec in normal: - lines.append(_apply_status(a, rec, rows) if a["action"] != "promote" - else _apply_one(a, rec, rows)) - if pending: - items = L.load_pending() - for a in pending: - pid = "P-%04d" % (len(items) + 1) - items.append({"id": pid, "action": a, "ts": L.now()}) - lines.append("%s is consequential and waits for the owner: `sisi approve %s --yes|--no`" - % (a.get("learning") or a.get("rule_id"), pid)) - L.save_pending(items, "cycle: consequential change(s) pending") + rows_before = {r["id"]: {k: copy.deepcopy(r[k]) for k in CYCLE_FIELDS if k in r} for r in L.load_learnings()} + try: + lines, touched, added = fn() + except BaseException: + if before: + changed = _changed(before, "HEAD") + _restore_files(before, changed) + pdata.commit("cycle aborted: store restored", changed or None) + try: + overlay.build_canon() + except Exception: + pass + raise after = _head() - cycles = [n for n in os.listdir(paths.data_file("cycles")) if n.endswith(".json")] \ - if os.path.isdir(paths.data_file("cycles")) else [] - cid = "cycle-%04d" % (len(cycles) + 1) - rec = {"id": cid, "ts": L.now(), "before": before, "after": after, "lines": lines} + n = len(_cycle_records()) + 1 + cid = "cycle-%04d" % n + rec = {"id": cid, "label": label, "ts": L.now(), "before": before, "after": after, "lines": lines, + "changed": _changed(before, after) if before and after else [], + "rows_before": {i: rows_before[i] for i in touched if i in rows_before}, + "pending_added": added} pdata.write_text("cycles/%s.json" % cid, json.dumps(rec, indent=2, sort_keys=True) + "\n") pdata.commit("cycle %s applied" % cid, ["cycles/%s.json" % cid]) return cid, lines +def apply_file(path): + """Validate and plan everything, then apply. A refusal changes nothing.""" + pdata.ensure() + try: + with open(path, encoding="utf-8") as f: + doc = json.load(f) + except ValueError as e: + raise CycleError("the cycle file is not JSON: %s" % e) + rows = L.load_learnings() + plan = validate_doc(doc, rows) + + def run(): + lines, touched, added = [], [], [] + items = L.load_pending() + for p in plan: + a, rec = p["action"], p["rec"] + if p["kind"] == "status": + lines.append(_apply_status(a, rec)) + touched.append(rec["id"]) + elif p["kind"] == "promote" and not p["pending"]: + ref = _apply_mechanism(a, rec, p["scope"]) + lines.append(_promoted(rec, ref, p["scope"], p["replay"])) + touched.append(rec["id"]) + else: + pid = _park(a, rec, p["reasons"], p["scope"], p["replay"], items, added) + if rec is not None: + if p["replay"] and p["replay"][0] == "validated": + rec["validation"].update(result="validated", detail=p["replay"][1], + method=rec["validation"].get("method") or "replay") + if rec.get("status") in ("observed", "analyzed", "proposed", "implemented"): + rec["status"] = "validated" + touched.append(rec["id"]) + 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"), + "; ".join(p["reasons"]), pid)) + if added: + L.save_pending(items, "cycle: consequential change(s) pending") + if touched: + L.save_learnings(rows, "cycle: %d learning(s) changed" % len(set(touched)), touched=sorted(set(touched)), via="cycle") + changed = L.monitor(rows) + if changed: + L.save_learnings(rows, "monitoring: learning(s) now monitored", touched=changed, via="cycle") + return lines, sorted(set(touched) | {r["id"] for r in changed}), added + + return _transact("apply", run) + + def revert_cycle(cid=None): - d = paths.data_file("cycles") - files = sorted(n for n in os.listdir(d) if n.endswith(".json")) if os.path.isdir(d) else [] - if not files: + """Undo one cycle's effects and nothing else: the mechanism files it wrote go back, the + learning records it changed get back the fields it changed, the decisions it parked are + dropped. Findings, statements and recurrences recorded after the cycle stay.""" + recs = [r for r in _cycle_records() if not r.get("reverted")] + if not recs: raise CycleError("no cycles to revert") - name = (cid + ".json") if cid else files[-1] - if name not in files: - raise CycleError("no cycle %r" % cid) - with open(os.path.join(d, name), encoding="utf-8") as f: - rec = json.load(f) + if cid: + rec = next((r for r in recs if r.get("id") == cid), None) + if rec is None: + raise CycleError("no cycle %r that can be reverted" % cid) + else: + rec = recs[-1] before, after = rec.get("before"), rec.get("after") - if not before: - raise CycleError("cycle %s has no recorded before-commit; cannot revert exactly" % rec["id"]) - # exact revert: restore the store tree to the before-commit, as one new commit - pdata.git("restore", "--source", before, "--staged", "--worktree", "--", ".") - # files the cycle added are not in `before`: remove paths tracked now but absent there - now_files = set(pdata.git("ls-files").stdout.split()) - then_files = set(pdata.git("ls-tree", "-r", "--name-only", before).stdout.split()) - for extra in now_files - then_files: - if extra.startswith("cycles/"): - continue # keep the cycle records themselves - p = paths.data_file(extra) - if os.path.exists(p): - os.remove(p) - pdata.git("add", "-A", "--", ".") - pdata.git("commit", "-q", "-m", "revert %s (exact: restore %s)" % (rec["id"], before[:12])) + if not before or not after: + raise CycleError("cycle %s has no recorded commits; cannot revert exactly" % rec["id"]) + files = [f for f in rec.get("changed", []) if f not in STORE_FILES and not f.startswith("cycles/")] + for f in files: + if _changed(after, "HEAD") and f in _changed(after, "HEAD"): + raise CycleError("%s was changed after this cycle; revert the later change first" % f) + _restore_files(before, files) + rows = L.load_learnings() + touched = [] + for lid, fields in (rec.get("rows_before") or {}).items(): + r = L.get(rows, lid) + if r is None: + continue + for k in CYCLE_FIELDS: + if k in fields: + r[k] = copy.deepcopy(fields[k]) + else: + r.pop(k, None) + r.setdefault("history", []).append({"ts": L.now(), "action": "cycle-reverted", "cycle": rec["id"]}) + touched.append(r) + if touched: + L.save_learnings(rows, "revert %s: learning records restored" % rec["id"], touched=touched, via="cycle") + gone = set(rec.get("pending_added") or []) + if gone: + L.save_pending([i for i in L.load_pending() if i.get("id") not in gone], "revert %s: parked changes dropped" % rec["id"]) + pdata.commit("revert %s" % rec["id"], files or None) + rec["reverted"] = L.now() + pdata.write_text("cycles/%s.json" % rec["id"], json.dumps(rec, indent=2, sort_keys=True) + "\n") + pdata.commit("revert %s recorded" % rec["id"], ["cycles/%s.json" % rec["id"]]) + try: + overlay.build_canon() + except Exception: + pass return rec["id"] # ---- approval ------------------------------------------------------------------------- -def apply_pending(pid, yes): +def _stdin_is_tty(): + try: + return bool(sys.stdin is not None and sys.stdin.isatty()) + except (ValueError, OSError): + return False + + +def relay_allowed(): + """May an agent relay the owner's decision? Off unless the user's config says so.""" + try: + from . import store + return bool((store.config().get("learning") or {}).get("agent_relayed_approval")) + except Exception: + return False + + +def describe_pending(item): + """The full action, in words and text, so the owner can see exactly what he approves.""" + a = item.get("action") or {} + rec = L.get(L.load_learnings(), item.get("learning") or "") + out = ["%s: %s" % (item["id"], (a.get("action") if a.get("action") != "promote" else + "install a %s" % a.get("mechanism_kind")))] + if rec: + out.append(" learning %s: %s" % (rec["id"], L.derive_title(rec.get("title") or "", 120))) + out.append(" seen in: %d unit(s), %d project(s); earned scope: %s" + % (len({p.get("unit") for p in rec.get("provenance") or []}), + len({p.get("project") for p in rec.get("provenance") or []}), L.earned_scope(rec))) + out.append(" origin project: %s" % rec.get("origin_project")) + kind = a.get("mechanism_kind") + if kind == "command-check": + out.append(" COMMAND (runs through the shell on every verify): %s" % a.get("cmd")) + out.append(" expected exit: %s timeout: %s" % ((a.get("expect") or {}).get("exit", 0), a.get("timeout_s") or "default")) + elif kind == "contract-requirement": + out.append(" a contract that mentions %r must contain a check of kind %s%s" + % (a.get("when"), a.get("require_kind"), + " at rung <= %s" % a["max_rung"] if a.get("max_rung") is not None else "")) + elif kind == "risk": + out.append(" risk pattern: %s -> profile %s" % (a.get("pattern"), a.get("profile"))) + elif kind == "routing": + out.append(" routing: %s" % json.dumps({k: a[k] for k in ("kind", "difficulty", "prefer", "avoid") if k in a}, sort_keys=True)) + elif kind == "benchmark": + out.append(" benchmark %s: %s" % (a.get("name"), json.dumps(a.get("case"), sort_keys=True)[:600])) + elif kind == "library": + 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")) + out += [" | " + l for l in str(a.get("entry_text") or "").splitlines()[:60]] + if kind == "rule-text" or a.get("action") == "replace-rule": + rid, new = a.get("rule_id"), a.get("rule_text") or "" + 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")) + old_text = overlay.rule_text(cur).splitlines() if cur else [] + try: + new_text = overlay.rule_text(overlay.parse_rule_file(new, rid)).splitlines() + except Exception: + new_text = new.splitlines() + 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])] + if a.get("action") == "disable-rule": + 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)")) + for r in item.get("reasons") or []: + out.append(" needs you because: %s" % r) + rp = item.get("replay") + if rp: + out.append(" replay: %s (%s)" % (rp[0], rp[1])) + return out + + +def apply_pending(pid, yes, how=None): + how = how or {} items = L.load_pending() item = next((i for i in items if i.get("id") == pid), None) if item is None: raise CycleError("no pending change %r (`sisi approve` lists them)" % pid) - a = item["action"] - items = [i for i in items if i.get("id") != pid] + row = {"id": pid, "decision": "yes" if yes else "no", "ts": L.now(), "learning": item.get("learning"), + "session": os.environ.get("SISI_SESSION_ID") or None, "terminal": bool(how.get("terminal")), + "relayed": "relayed by an agent" if how.get("relayed") else None, + "action": item.get("action")} + left = [i for i in items if i.get("id") != pid] if not yes: - L.save_pending(items, "approve: %s refused by the owner" % pid) + L.record_approval(row) + L.save_pending(left, "approve: %s refused by the owner" % pid) return "%s refused; nothing changed" % pid - rows = L.load_learnings() - if a.get("action") == "disable-rule": - if a.get("rule_id") in protected_rules(): - raise CycleError("rule %r is protected; even approval cannot disable it by cycle" % a.get("rule_id")) - overlay.set_disabled("rule", a["rule_id"], True) - overlay.build_canon() - L.save_pending(items, "approve: %s applied" % pid) - return "rule %s disabled (approved)" % a["rule_id"] - rec = L.get(rows, a.get("learning") or "") - if rec is None: - raise CycleError("learning %r no longer exists" % a.get("learning")) - line = _apply_one(a, rec, rows) - L.save_pending(items, "approve: %s applied" % pid) - return line + " (approved)" + a = item["action"] + + def run(): + lines, touched = [], [] + if a.get("action") in ("disable-rule", "replace-rule"): + rid = a.get("rule_id") + _need(rid not in protected_rules(), "rule %r is protected; even approval cannot change it by cycle" % rid) + if a["action"] == "disable-rule": + overlay.set_disabled("rule", rid, True) + lines.append("rule %s disabled (approved)" % rid) + else: + overlay.replace_rule(rid, a["rule_text"]) + lines.append("rule %s replaced (approved)" % rid) + overlay.build_canon() + else: + rows = L.load_learnings() + 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(L.is_registered(rec), "learning %s was changed outside sisi's own commands" % rec["id"]) + if a.get("mechanism_kind") == "rule-text": + rid = a["rule_id"] + _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)})) + _need(ok, "rule-text for %s breaks the rulebook budget: %s" % (rec["id"], msg)) + replay = tuple(item["replay"]) if item.get("replay") else None + ref = _apply_mechanism(a, rec, item.get("scope") or "project", approval=pid) + lines.append(_promoted(rec, ref, item.get("scope") or "project", replay) + " (approved)") + L.save_learnings(rows, "approve: %s promotes %s" % (pid, rec["id"]), touched=[rec], via="cycle") + touched.append(rec["id"]) + L.record_approval(row) + L.save_pending(left, "approve: %s applied" % pid) + return lines, touched, [] + + cid, lines = _transact("approve %s" % pid, run) + return lines[0] + + +def park_rule_change(action, reasons): + """A rule change typed through `sisi overlay` waits for the owner like a cycle's.""" + items = L.load_pending() + added = [] + pid = _park(action, None, reasons, None, None, items, added) + L.save_pending(items, "overlay: %s waits for the owner" % action.get("action")) + return pid def cmd_approve(argv): + items = L.load_pending() if not argv: - items = L.load_pending() if not items: print("nothing waits for a decision") return 0 for i in items: - a = i["action"] - print("%s: %s %s" % (i["id"], a.get("action"), a.get("learning") or a.get("rule_id"))) - print("decide with: sisi approve ID --yes | --no") + print("\n".join(describe_pending(i))) + print() + print("The owner decides, in a terminal: sisi approve ID --yes | --no") return 0 pid, yes = argv[0], "--yes" in argv if not yes and "--no" not in argv: - print("usage: sisi approve ID --yes | --no", file=sys.stderr) + print("usage: sisi approve [ID --yes | --no]", file=sys.stderr) return 2 + tty = _stdin_is_tty() + relayed = False + if not tty: + if not relay_allowed(): + item = next((i for i in items if i.get("id") == pid), None) + if item: + print("\n".join(describe_pending(item)), file=sys.stderr) + print("sisi approve: refused. A decision must be made by the owner in a terminal: this was run " + "without one (an agent, a script, a pipe). Show the owner what it does (the listing above) " + "and give him the command to type himself. To allow an agent to relay a decision, set " + "learning.agent_relayed_approval in the user config (off by default).", file=sys.stderr) + return 2 + relayed = True try: - print(apply_pending(pid, yes)) + print(apply_pending(pid, yes, {"terminal": tty, "relayed": relayed})) return 0 - except CycleError as e: + except (CycleError, overlay.OverlayError, documents.DocumentError) as e: print("sisi approve: %s" % e, file=sys.stderr) return 2 @@ -512,7 +873,8 @@ def cmd_approve(argv): HELP = """sisi cycle: turn proposed learnings into mechanisms. JSON cycle file: {"base": "", "actions": [ ... ]} promote actions, by mechanism_kind: - command-check {learning, cmd, expect?, before?, after?} replayed; fail-before/pass-after = validated + command-check {learning, cmd, expect?, before?, after?} replayed in the origin project's trusted + repository: it must exist at both commits, fail before and pass after contract-requirement {learning, when, require_kind, max_rung?} rule-text {learning, rule_id, rule_text} (protected rules refused) library {learning, library_kind: recipe|verifier, entry_text, entry_id?, replacing?} @@ -520,8 +882,12 @@ promote actions, by mechanism_kind: routing {learning, kind, difficulty?, prefer|avoid} -> overlay/routing-adjustments.json benchmark {learning, name, case:{...}} -> overlay/benchmarks/.json other actions: {action: revise|revert|reject, learning, why}; {action: disable-rule, rule_id} -Consequential actions (disable-rule, scope organization, every_project command) are stored -as pending for `sisi approve ID --yes|--no`. A cycle that ignores a flagged learning is refused. +Every mechanism is written with its learning's id and the scope that learning has earned (its origin +project unless it was seen in two units in two projects, or is an owner statement); a scope or +every_project flag only asks for more. These wait for the owner (`sisi approve`, in a terminal): +more scope than earned, a command not proven by replay, a risk pattern that lowers a profile, a +replaced or disabled rule, a rule or library entry from a learning confined to one project. +A cycle that ignores a flagged learning is refused. `sisi cycle revert` undoes only that cycle's changes. """ @@ -532,7 +898,7 @@ def cmd_cycle(args): if args and args[0] == "apply" and len(args) > 1: try: cid, lines = apply_file(args[1]) - except (CycleError, OSError) as e: + except (CycleError, OSError, documents.DocumentError, overlay.OverlayError) as e: print("sisi cycle: %s" % e, file=sys.stderr) return 2 print("%s applied:" % cid) @@ -543,11 +909,12 @@ def cmd_cycle(args): try: with open(args[1], encoding="utf-8") as f: doc = json.load(f) - normal, pending = validate_doc(doc, L.load_learnings()) - except (CycleError, OSError, ValueError) as e: + plan = validate_doc(doc, L.load_learnings()) + except (CycleError, OSError, ValueError, documents.DocumentError, overlay.OverlayError) as e: print("sisi cycle: %s" % e, file=sys.stderr) return 2 - print("valid: %d action(s) apply at once, %d wait for the owner" % (len(normal), len(pending))) + wait = sum(1 for p in plan if p["pending"]) + print("valid: %d action(s) apply at once, %d wait for the owner" % (len(plan) - wait, wait)) return 0 if args and args[0] == "revert": try: @@ -555,7 +922,7 @@ def cmd_cycle(args): except (CycleError, OSError) as e: print("sisi cycle: %s" % e, file=sys.stderr) return 2 - print("%s reverted exactly in the user store" % cid) + print("%s reverted in the user store (only what that cycle changed)" % cid) return 0 if args and args[0] == "due": print(due_notice() or "no cycle is due") diff --git a/sisi/evaluate.py b/sisi/evaluate.py index 4dbf152..7cade3b 100644 --- a/sisi/evaluate.py +++ b/sisi/evaluate.py @@ -6,14 +6,15 @@ checks the named commit out into a temporary git worktree and removes it afterwa Seams for the other parts of sisi (plain functions, see docs/evaluation.md): capture_case(unit_record) called when a work unit closes - validate_check(case) called by the learning cycle before it promotes a command check + validate_check(case) replay a stored case's checks at its two commits + validate_command(repo, before, after, cmd) the learning cycle's replay of one command (trusted repo, ancestry, ran-and-failed) compare_for_candidate(dir, sample) called for a consequential policy change before the owner is asked Standard library only. Replay of ``task`` cases goes through the existing delegation runner (``sisi.workers.run_delegation``) unless a caller injects ``worker_runner`` or names a ``--worker-cmd``; tests always inject a fake, so no test calls a real AI tool. """ -import hashlib, json, math, os, re, shutil, statistics, subprocess, sys, tempfile, time, uuid +import hashlib, json, math, os, re, shlex, shutil, statistics, subprocess, sys, tempfile, time, uuid from . import paths, store @@ -395,8 +396,81 @@ class _Worktree: return False +SHELL_BUILTINS = frozenset((":", "true", "false", "test", "[", "[[", "echo", "printf", "exit", "cd", "set", + "export", "unset", "read", "type", "command", "eval", "exec", "return", "source", ".", + "if", "then", "else", "elif", "fi", "for", "while", "until", "do", "done", "case", + "esac", "!", "{", "}", "(", ")", "time", "wait")) +INTERPRETERS = frozenset(("python", "python3", "sh", "bash", "zsh", "dash", "node", "ruby", "perl")) +SCRIPT_EXT = (".py", ".sh", ".js", ".rb", ".pl", ".mjs") +_OPERATORS = frozenset((";", "&&", "||", "|", "&", "(", ")", ";;", "|&")) + + +def exit_not_ran(code): + """True when an exit status says the command never really ran: not found (127), not + executable (126), a negative status (killed by a signal, as Python reports it), or the + 128+signal a shell reports for a child that was killed.""" + return code is None or code < 0 or code in (126, 127) or 129 <= code <= 159 + + +def _segments(cmd): + """The simple commands of a shell line, as token lists (operators split them). None when the + line does not parse.""" + try: + lex = shlex.shlex(str(cmd), posix=True, punctuation_chars=True) + lex.whitespace_split = True + toks = list(lex) + except ValueError: + return None + segs, cur = [], [] + for t in toks: + if t in _OPERATORS: + if cur: + segs.append(cur) + cur = [] + else: + cur.append(t) + if cur: + segs.append(cur) + return segs + + +def unresolved_program(cmd, cwd): + """Why the command's program(s) cannot be found in the tree at ``cwd`` (None when every one + resolves). A path program, and a script given to an interpreter, must exist in this tree, so a + check that only exists in the later commit cannot count as failing in the earlier one.""" + segs = _segments(cmd) + if not segs: + return "the command does not parse or is empty" + for seg in segs: + i = 0 + while i < len(seg) and re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", seg[i]): + i += 1 # leading VAR=value assignments + if i >= len(seg): + continue + prog = seg[i] + if prog in SHELL_BUILTINS: + continue + if "/" in prog: + target = prog if os.path.isabs(prog) else os.path.join(cwd, prog) + if not (os.path.isfile(target) and os.access(target, os.X_OK)): + return "program %s does not exist in this commit" % prog + elif shutil.which(prog) is None: + return "program %s is not on PATH" % prog + if os.path.basename(prog) in INTERPRETERS: + rest = seg[i + 1:] + if "-c" in rest or "-m" in rest or "-e" in rest: + continue + script = next((t for t in rest if not t.startswith("-")), None) + if script and ("/" in script or script.endswith(SCRIPT_EXT)): + target = script if os.path.isabs(script) else os.path.join(cwd, script) + if not os.path.isfile(target): + return "script %s does not exist in this commit" % script + return None + + def _run_checks(case, cwd, timeout_s): - """Run the case's checks in ``cwd``. Returns (rows, timed_out); rows carry exit/passed.""" + """Run the case's checks in ``cwd``. Returns (rows, timed_out); rows carry exit/passed and + ``ran``: False when the command never really ran (program missing, exit 126/127, killed).""" rows, timed_out = [], False for c in case.get("checks") or []: expect = (c.get("expect") or {}) @@ -405,17 +479,23 @@ def _run_checks(case, cwd, timeout_s): want = int(want) except (TypeError, ValueError): want = 0 + why = unresolved_program(c.get("cmd"), cwd) + if why: + rows.append({"id": c.get("id"), "cmd": c.get("cmd"), "exit": None, "ran": False, + "expected_exit": want, "passed": False, "error": why}) + continue try: r = subprocess.run(str(c.get("cmd")), shell=True, cwd=cwd, capture_output=True, text=True, timeout=timeout_s) rows.append({"id": c.get("id"), "cmd": c.get("cmd"), "exit": r.returncode, + "ran": not exit_not_ran(r.returncode), "expected_exit": want, "passed": r.returncode == want}) except subprocess.TimeoutExpired: timed_out = True - rows.append({"id": c.get("id"), "cmd": c.get("cmd"), "exit": None, + rows.append({"id": c.get("id"), "cmd": c.get("cmd"), "exit": None, "ran": False, "expected_exit": want, "passed": False, "timed_out": True}) except OSError as e: - rows.append({"id": c.get("id"), "cmd": c.get("cmd"), "exit": None, + rows.append({"id": c.get("id"), "cmd": c.get("cmd"), "exit": None, "ran": False, "expected_exit": want, "passed": False, "error": str(e)}) return rows, timed_out @@ -452,8 +532,14 @@ def _replay_check(case, timeout_s): if timed_out: return {"outcome": "not-run", "reason": "check timed out at the %s commit" % label, "check_results": results + [dict(r, at=label) for r in rows]} - seen[label] = passed results += [dict(r, at=label) for r in rows] + stuck = [r for r in rows if not r.get("ran", True)] + if stuck: + return {"outcome": "not-run", "check_results": results, + "reason": "the check could not run at the %s commit (%s); a check that did " + "not run proves nothing" % (label, stuck[0].get("error") + or "exit %s" % stuck[0].get("exit"))} + seen[label] = passed except RuntimeError as e: return {"outcome": "not-run", "reason": str(e), "check_results": results} if case.get("split") == "counterexample": @@ -492,6 +578,34 @@ def validate_check(case, store_dir=None, timeout_s=None, record=False): return out +def validate_command(repo, before, after, cmd, expect_exit=0, timeout_s=None, store_dir=None): + """Replay one command at two commits of a local, trusted repository: ``validated`` only when + it ran and failed at ``before`` and ran and passed at ``after``. Anything that stops the + command from really running (program missing at either commit, exit 126/127, a timeout, a + signal) is ``not-run`` with the reason, never a failure. ``before`` must be an ancestor of + ``after``; the repository must be a project on the trust list. Returns the replay outcome + dict (``outcome``, ``reason``, ``check_results``); nothing is recorded.""" + from . import trust + repo = os.path.realpath(str(repo or "")) + if not os.path.isdir(repo) or _is_remote(repo): + return {"outcome": "not-run", "reason": "the repository is not a local directory", "check_results": []} + if not trust.is_trusted(repo): + return {"outcome": "not-run", "check_results": [], + "reason": "the repository is not on the trust list (`sisi contract trust` in it), " + "so its commands are not replayed"} + if not _commit_exists(repo, before) or not _commit_exists(repo, after): + return {"outcome": "not-run", "reason": "a commit is missing in the repository", "check_results": []} + rc, _o, _e = _git(repo, "merge-base", "--is-ancestor", str(before), str(after)) + if rc != 0: + return {"outcome": "not-run", "check_results": [], + "reason": "the before commit is not an ancestor of the after commit"} + case = {"id": "replay", "kind": "check", "split": "dev", + "project": {"repo": repo, "start_commit": str(before), "fix_commit": str(after)}, + "checks": [{"id": "c", "cmd": str(cmd), "expect": {"exit": expect_exit}}]} + timeout_s = float(timeout_s or _eval_config(store_dir)["timeout_s"]) + return _replay_check(case, timeout_s) + + def _rulebook_text(policy_dir): for p in (os.path.join(policy_dir, "generated", "core.md"), paths.canon("core.md")): try: diff --git a/sisi/handover.py b/sisi/handover.py index f5a7124..1b4d33e 100644 --- a/sisi/handover.py +++ b/sisi/handover.py @@ -1,80 +1,53 @@ -"""Project handover pile: project-scoped items leave the global store. +"""Project handover: project-scope records leave sisi's care for the project's own documents. -Scoping a lesson or a `sisi learn` statement to a project moves it here: a pile in -the personal store, keyed by project id, kept only until an agent files it in that -project's own design documentation or work list and confirms with -`sisi handover done ID --where PATH`. After confirmation the item is gone from -every global listing; a small filed log (id, project, path, date) keeps the trace, -and the personal store's git history keeps the rest. +A learning or `sisi learn` statement the owner (or the retro) scoped to a project, explicitly, +waits here until an agent files it in that project's own design documentation or work list and +confirms with `sisi handover done ID --where PATH`. The items are read from the learning store; +a small filed log (id, project, path, date) keeps the trace of what was filed, and the user +store's git history keeps the rest. """ import json, os -from . import paths, scope, store - - -def pile_path(): - return paths.data_file("handover.json") +from . import learning as L, paths, scope def filed_path(): return paths.data_file("handover-filed.jsonl") +def _filed(): + return {r.get("hid") for r in L._read_jsonl(filed_path())[0]} + + +def _item(r): + pr = r.get("proposed") or {} + return {"hid": r["id"], "kind": "learn" if r.get("owner_statement") else "lesson", "lesson_id": r["id"], + "project": r.get("origin_project"), "date": r.get("created") or "", + "text": pr.get("description") or r.get("title"), "change": pr.get("description"), + "short": r.get("title"), "aim": (r.get("observation") or {}).get("impact"), + "change_kind": pr.get("mechanism"), "moment": (r.get("observation") or {}).get("evidence"), + "cause": r.get("root_cause"), + "occurrences": [{"ts": p.get("ts"), "repo": p.get("project"), "tool": None} + for p in r.get("provenance") or []]} + + def load_pile(): - try: - with open(pile_path(), encoding="utf-8") as f: - d = json.load(f) - return d if isinstance(d, list) else [] - except (OSError, ValueError): - return [] - - -def save_pile(items): - os.makedirs(os.path.dirname(pile_path()), exist_ok=True) - tmp = pile_path() + ".tmp%d" % os.getpid() - with open(tmp, "w", encoding="utf-8") as f: - json.dump(items, f, indent=1, sort_keys=True, ensure_ascii=False) - f.write("\n") - os.replace(tmp, pile_path()) - - -def _next_hid(items): - n = len(items) - try: - with open(filed_path(), encoding="utf-8") as f: - n += sum(1 for _ in f) - except OSError: - pass - return "h%d" % (n + 1) - - -def add_item(item): - items = load_pile() - item = dict(item) - item.setdefault("hid", _next_hid(items)) - item.setdefault("date", store.now()) - items.append(item) - save_pile(items) - return item + """Project-scope records waiting to be filed: explicitly scoped to a project, written by sisi's + own commands, not withdrawn, not yet filed.""" + ledger = L.load_ledger() + done = _filed() + return [_item(r) for r in L.load_learnings() + if (r.get("proposed") or {}).get("scope_asked") == "project" and L.is_registered(r, ledger) + and r.get("status") not in L.ENDED and not r.get("candidate") and r["id"] not in done] def for_project(pid): return [it for it in load_pile() if it.get("project") == pid] -def counts_by_project(): - out = {} - for it in load_pile(): - out[it.get("project") or ""] = out.get(it.get("project") or "", 0) + 1 - return out - - def notice(cwd): """The session-start / request-time line inside the owning project only.""" - try: - items = for_project(scope.project_id(cwd)) - except Exception: - return "" + items = for_project(scope.project_id(cwd)) if not items: return "" return ("sisi: %d item(s) recorded by sisi belong to this project. File each in this project's own " @@ -88,37 +61,6 @@ def _norm(t): return " ".join(str(t or "").split()).lower() -def move_lesson(con, lesson_id, pid): - """Copy a lesson (with its occurrences, the historical example) into the pile and remove - it from the delivered global data. Returns the pile item, or None.""" - r = con.execute("SELECT * FROM lessons WHERE id=?", (lesson_id,)).fetchone() - if r is None: - return None - d = dict(r) - occ = [dict(o) for o in con.execute("SELECT * FROM occurrences WHERE lesson_id=? ORDER BY id", (lesson_id,))] - item = {"kind": "lesson", "lesson_id": d["id"], "project": pid, - "date": d.get("created") or store.now(), - "aim": d.get("aim"), "change_kind": d.get("change_kind"), "target": d.get("target"), - "change": d.get("change"), "short": d.get("short"), "when": d.get("when_terms"), - "moment": d.get("moment"), "cause": d.get("cause"), - "occurrences": [{"ts": o.get("ts"), "repo": o.get("repo"), "cwd": o.get("cwd"), - "tool": o.get("tool"), "session": o.get("session"), "moment": o.get("moment")} - for o in occ]} - con.execute("DELETE FROM impressions WHERE lesson_id=?", (lesson_id,)) - con.execute("DELETE FROM sightings WHERE lesson_id=?", (lesson_id,)) - # the occurrence rows stay: they are the history of the work itself (and what satisfies - # the retro gate for that session), not delivered lesson data - con.execute("DELETE FROM lessons WHERE id=?", (lesson_id,)) - return add_item(item) - - -def move_learn(rec, pid): - item = {"kind": "learn", "project": pid, "date": rec.get("ts") or store.now(), - "text": rec.get("text"), "cwd": rec.get("cwd"), - "occurrences": [{"ts": rec.get("ts"), "repo": rec.get("cwd"), "tool": rec.get("tool")}]} - return add_item(item) - - def _find(items, ident): for it in items: if str(ident) in (str(it.get("hid")), str(it.get("lesson_id") or "")): @@ -138,7 +80,7 @@ def _item_lines(it): if it.get("kind") == "learn": out.append(' what the owner said: "%s"' % " ".join(str(it.get("text") or "").split())) else: - out.append(" lesson #%s (%s/%s): %s" % (it.get("lesson_id"), it.get("aim"), it.get("change_kind"), + out.append(" learning %s (%s/%s): %s" % (it.get("lesson_id"), it.get("aim"), it.get("change_kind"), " ".join(str(it.get("change") or "").split()))) if it.get("short"): out.append(" short: %s" % it["short"]) @@ -201,12 +143,12 @@ def main(argv): "first, or pass --quote with a quoted fragment of the item that the file does contain." % (where, " ".join(str(need).split())[:120])) return 1 - save_pile([x for x in items if x is not it]) rec = {"hid": it.get("hid"), "kind": it.get("kind"), "lesson_id": it.get("lesson_id"), - "project": it.get("project"), "where": ap, "date": store.now()} - os.makedirs(os.path.dirname(filed_path()), exist_ok=True) - with open(filed_path(), "a", encoding="utf-8") as f: - f.write(json.dumps(rec, sort_keys=True, ensure_ascii=False) + "\n") + "project": it.get("project"), "where": ap, "date": L.now()} + from . import pdata + pdata.write_text("handover-filed.jsonl", (pdata.read_text("handover-filed.jsonl", "") or "") + + json.dumps(rec, sort_keys=True, ensure_ascii=False) + "\n") + pdata.commit("handover: %s filed in %s" % (it.get("hid"), ap), ["handover-filed.jsonl"]) print("filed %s in %s; removed from the handover pile" % (ident, where)) return 0 if argv not in ([], ["--all"]): diff --git a/sisi/learning.py b/sisi/learning.py index 4fefaf9..8f9d13c 100644 --- a/sisi/learning.py +++ b/sisi/learning.py @@ -3,6 +3,11 @@ One store: learnings.jsonl in the user store (one JSON object per learning, rewritten atomically; git in the user store is the history). Findings of a retro live in findings.jsonl. Showings are never recorded as evidence. See docs/learning.md. + +Trust in a row comes from the ledger, never from the row itself: learnings-ledger.jsonl +is appended by sisi's own commands, in the same commit as the row they wrote, and holds +the id and content digest of what they wrote. A row that is not in the ledger with its +current digest (added or edited by hand) is never delivered. """ import hashlib, json, os, re, subprocess, time @@ -10,14 +15,27 @@ from . import paths, pdata STATUSES = ("observed", "analyzed", "proposed", "implemented", "validated", "promoted", "monitored", "revised", "reverted", "rejected") +ENDED = ("rejected", "reverted") MECHANISMS = ("policy", "orchestration", "skill", "tool", "infrastructure", "verification", "knowledge", "benchmark") IMPACTS = ("value", "correctness", "time", "cost", "attention") SCOPES = ("organization", "user", "project", "task-class") -GENERIC = re.compile(r"^\s*(nothing|none|n/?a|be more careful|write better tests|" - r"use cheaper models|do better|all good|no issues?)\W*$", re.I) +SCOPE_RANK = {"project": 0, "user": 1, "organization": 2} +MONITOR_UNITS = 5 # units in a learning's own scope before it can be called "holding" STOP = set("the a an and or of to in is was were be been it its this that with for on at by as not no do does did when then than from we i".split()) +# Words that carry no information about what happened. A finding made only of these is advice, +# not evidence ("be more careful when writing tests in future"). +GENERIC_WORDS = set(( + "be being more most careful carefully better best write writing written test tests testing code coding " + "future next time times always never should must need needs try trying remember make sure ensure check " + "checks checking double pay attention use using cheaper cheap models model do does doing done good bad " + "great nothing none na issue issues problem problems thing things work works working improve improved " + "improving improvement quality thorough thoroughly review reviewing think thinking plan planning ahead " + "going forward all any some general generally just really very much many bit little slightly again once " + "ever also too so can could would will may might worse avoid mistakes mistake fine ok okay well everything " + "anything something stuff careless carelessness sloppy rushed hasty lazy diligent diligence").split()) + class LearningError(Exception): pass @@ -46,6 +64,15 @@ def project_key(cwd): return os.path.realpath(cwd) +def normalize_project(value): + """The project key for an old `repo`/`cwd` value: the same key new code uses when the folder + still exists, else the cleaned path.""" + if not value: + return "" + value = str(value) + return project_key(value) if os.path.isdir(value) else os.path.realpath(value) + + def unit_id(project=None): """Seam with the work-unit worker: the id in .sisi/contract.json, else a session fallback.""" project = project or os.getcwd() @@ -60,8 +87,32 @@ def unit_id(project=None): hashlib.sha1(os.path.realpath(project).encode()).hexdigest()[:12]) +# ---- who is recording: from recorded session state, never from the caller's environment ---- + +def session_record(): + """(session id, its recorded state). The id names which record to read; what decides + anything is what the hooks recorded there.""" + sid = os.environ.get("SISI_SESSION_ID") or "" + if not sid: + return "", {} + from . import store + return sid, store.load_session(sid) + + def is_subagent_session(): - return os.environ.get("SISI_SUBAGENT") == "1" or os.environ.get("SISI_AGENT_DEPTH", "") not in ("", "0") + """Was this retro recorded by a subagent? Decided from the session record: tick marks a + session that started as a subagent, and the watch hook records, for each shell command, whether + its hook payload came from a subagent (an agent id or a subagent transcript path). The latest + retro command on record decides.""" + _sid, sess = session_record() + if not sess: + return False + if sess.get("subagent"): + return True + for sh in reversed(sess.get("shells") or []): + if isinstance(sh, dict) and "retro" in str(sh.get("cmd") or ""): + return bool(sh.get("subagent")) + return False # ---- store io ----------------------------------------------------------------- @@ -70,6 +121,10 @@ def learnings_path(): return paths.data_file("learnings.jsonl") +def ledger_path(): + return paths.data_file("learnings-ledger.jsonl") + + def findings_path(): return paths.data_file("findings.jsonl") @@ -78,25 +133,85 @@ def pending_path(): return paths.data_file("pending.json") -def load_learnings(): - out = [] +def approvals_path(): + return paths.data_file("approvals.jsonl") + + +def _read_jsonl(path): + """(rows, skipped): the JSON objects in a jsonl file and how many lines were not one.""" + rows, skipped = [], 0 try: - with open(learnings_path(), encoding="utf-8") as f: + with open(path, encoding="utf-8") as f: for line in f: - if line.strip(): + if not line.strip(): + continue + try: d = json.loads(line) - if isinstance(d, dict) and d.get("id"): - out.append(d) + except ValueError: + skipped += 1 + continue + if isinstance(d, dict): + rows.append(d) + else: + skipped += 1 except OSError: pass - return out + return rows, skipped -def save_learnings(rows, msg): +_LOADED = {} # id -> digest of the row as it was on disk at the last read + + +def load_learnings(): + rows = [d for d in _read_jsonl(learnings_path())[0] if d.get("id")] + _LOADED.clear() + _LOADED.update({r["id"]: row_digest(r) for r in rows}) + return rows + + +def row_digest(rec): + return hashlib.sha256(json.dumps(rec, sort_keys=True).encode()).hexdigest()[:20] + + +def load_ledger(): + """{id: digest of the row as sisi last wrote it}.""" + return {d["id"]: d.get("digest") for d in _read_jsonl(ledger_path())[0] if d.get("id")} + + +def is_registered(rec, ledger=None): + ledger = load_ledger() if ledger is None else ledger + return ledger.get(rec.get("id")) == row_digest(rec) + + +def save_learnings(rows, msg, touched=(), via="retro", created=()): + """Rewrite the store. Only the rows a sisi command wrote are entered in the ledger: `created` + (new rows) and `touched` (rows changed by this command, which must have been as sisi last wrote + them when read). A row added or edited by hand never gets a ledger entry, and a later sisi + command that touches it does not launder it.""" pdata.ensure() text = "".join(json.dumps(r, sort_keys=True) + "\n" for r in rows) pdata.write_text("learnings.jsonl", text) - pdata.commit(msg, ["learnings.jsonl"]) + ids = {t["id"] if isinstance(t, dict) else t for t in touched} + new = {t["id"] if isinstance(t, dict) else t for t in created} + ledger = load_ledger() + add = "" + for r in rows: + i = r.get("id") + if i not in ids and i not in new: + continue + d = row_digest(r) + prior = ledger.get(i) + if i in new: + ok = prior is None + else: + ok = prior is not None and _LOADED.get(i) == prior + if ok and prior != d: + add += json.dumps({"id": i, "digest": d, "via": via, "ts": now()}, sort_keys=True) + "\n" + if add: + pdata.write_text("learnings-ledger.jsonl", (pdata.read_text("learnings-ledger.jsonl", "") or "") + add) + pdata.commit(msg, ["learnings.jsonl", "learnings-ledger.jsonl"]) + _LOADED.clear() + _LOADED.update({r["id"]: row_digest(r) for r in rows if r.get("id")}) def store_base(rows=None): @@ -109,17 +224,7 @@ def store_base(rows=None): def load_findings(): - out = [] - try: - with open(findings_path(), encoding="utf-8") as f: - for line in f: - if line.strip(): - d = json.loads(line) - if isinstance(d, dict): - out.append(d) - except OSError: - pass - return out + return _read_jsonl(findings_path())[0] def append_finding(f, msg="retro: finding"): @@ -145,6 +250,53 @@ def get(rows, lid): return None +# ---- text checks: generic findings, secrets ----------------------------------------------- + +def is_generic(text): + """True when the text is only generic advice, wherever the filler appears. A number, a + path, a quoted name or any other specific word makes it concrete.""" + toks = re.findall(r"[a-z0-9_]+", (text or "").lower()) + if not toks: + return True + if any(any(c.isdigit() for c in t) for t in toks): + return False + return not [t for t in toks if len(t) >= 2 and t not in STOP and t not in GENERIC_WORDS] + + +_SECRET_PATTERNS = [ + (re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)"), ""), + (re.compile(r"\b(?:sk|pk|rk)-[A-Za-z0-9_-]{16,}"), ""), + (re.compile(r"\bgh[pousr]_[A-Za-z0-9]{20,}"), ""), + (re.compile(r"\bgithub_pat_[A-Za-z0-9_]{20,}"), ""), + (re.compile(r"\bAKIA[0-9A-Z]{16}\b"), ""), + (re.compile(r"\bxox[abprs]-[A-Za-z0-9-]{10,}"), ""), + (re.compile(r"\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{5,}"), ""), + (re.compile(r"(?i)\b(bearer)\s+[A-Za-z0-9._~+/=-]{16,}"), r"\1 "), + (re.compile(r"(?i)\b([A-Za-z0-9_.-]*(?:api[_-]?key|secret|token|passw(?:or)?d|passwd|pwd|credentials?|authorization)" + r"[A-Za-z0-9_.-]*)\s*([:=])\s*(['\"]?)[^\s'\",;]{4,}"), r"\1\2 \3"), + (re.compile(r"://([^/\s:@]+):[^/\s@]+@"), r"://\1:@"), +] +_OPAQUE = re.compile(r"(? before anything is stored.""" + s = str(text or "") + for rx, rep in _SECRET_PATTERNS: + s = rx.sub(rep, s) + + def opaque(m): + t = m.group(0) + if re.fullmatch(r"[0-9a-f]{40,64}", t): + return t # a git object id is evidence, not a secret + if "/" in t and not re.search(r"[0-9]", t): + return t # a long path of words + if any(c.isdigit() for c in t) and any(c.isalpha() for c in t): + return "" + return t + return _OPAQUE.sub(opaque, s) + + # ---- derived text (the tool derives search terms, topics, short lines) --------- def _stem(w): @@ -179,8 +331,17 @@ def stems(text): if len(w) > 2 and w not in STOP} -def derive_terms(*texts): - return sorted(set().union(*[stems(t) for t in texts]))[:24] +def derive_terms(*texts, limit=32): + """The learning's own search terms, in order of first appearance (never cut alphabetically).""" + out, seen = [], set() + for t in texts: + for w in re.findall(r"[a-z0-9_]+", (t or "").lower()): + if len(w) > 2 and w not in STOP: + s = _stem(w) + if s not in seen: + seen.add(s) + out.append(s) + return out[:limit] def derive_title(text, limit=90): @@ -190,66 +351,98 @@ def derive_title(text, limit=90): def similar_learnings(rows, text, limit=3): + """Learnings whose own terms are found in the text. The share is taken of the smaller of the + two term sets, so a long prompt does not dilute a match: what counts is how much of the + learning's own vocabulary the text uses.""" q = stems(text) scored = [] for r in rows: - if r.get("status") in ("rejected", "reverted"): + if r.get("status") in ENDED: continue - hay = set(r.get("terms") or []) | stems(r.get("observation", {}).get("evidence", "")) \ - | stems(r.get("proposed", {}).get("description", "")) - inter = len(q & hay) - if inter >= 1: - scored.append((inter / max(1, len(q)), inter, r)) - scored.sort(key=lambda x: -x[0]) - return [r for s, inter, r in scored - if s >= 0.3 or (inter >= 1 and s >= 0.25 and len(q) <= 4)][:limit] + own = set(r.get("terms") or []) or stems((r.get("title") or "") + " " + (r.get("proposed", {}).get("description") or "")) + if not own: + continue + inter = len(q & own) + share = inter / max(1, min(len(q), len(own))) + if (inter >= 3 and share >= 0.25) or (inter >= 2 and share >= 0.3) \ + or (inter >= 1 and len(q) <= 4 and inter / len(q) >= 0.25): # a short, focused request + scored.append((share, inter, r)) + scored.sort(key=lambda x: (-x[0], -x[1])) + return [r for _s, _i, r in scored][:limit] # ---- scope (earned, never claimed) --------------------------------------------- -def earned(rec): - """Cross-project delivery is earned: >=2 units in >=2 projects, or an owner statement.""" +def earned_scope(rec): + """The widest scope this learning has earned: `organization` for a learning seen in at least + two units in at least two projects, `user`/`organization` for an owner statement made at that + scope (a project-scoped statement stays in its project), else `project`. Nothing a cycle + author writes can change this.""" if rec.get("owner_statement"): - return True + s = (rec.get("proposed") or {}).get("scope") + return s if s in ("user", "organization") else "project" prov = rec.get("provenance") or [] units = {p.get("unit") for p in prov if p.get("unit")} projects = {p.get("project") for p in prov if p.get("project")} - return len(units) >= 2 and len(projects) >= 2 + return "organization" if len(units) >= 2 and len(projects) >= 2 else "project" -def in_scope(rec, project): - if rec.get("status") in ("rejected", "reverted"): +def earned(rec): + return earned_scope(rec) != "project" + + +def in_scope(rec, project, ledger=None): + if rec.get("status") in ENDED: return False if rec.get("candidate"): # subagent learning, held until a parent retro adopts it return False - if rec.get("entered_via") not in ("retro", "learn", "cycle", "migration"): - return False # only learnings that entered through sisi's own commands are delivered + if not is_registered(rec, ledger): + return False # only rows sisi's own commands wrote, as they wrote them, are delivered pk = project_key(project) if project else None if pk and rec.get("origin_project") == pk: return True return earned(rec) -def learnings_in_scope(project, rows=None): +def learnings_in_scope(project, rows=None, targets=()): rows = load_learnings() if rows is None else rows - return [r for r in rows if in_scope(r, project)] + ledger = load_ledger() + out = [r for r in rows if in_scope(r, project, ledger)] + if targets: + want = set(targets) + out = [r for r in out if (r.get("proposed") or {}).get("target") in want] + return out -def delivery_text(project, query=""): - """Learnings in scope, framed as information, never as instructions. No showing is recorded.""" - rows = learnings_in_scope(project) - if query: - rows = similar_learnings(rows, query, limit=5) # silence is the default - rows = [r for r in rows if r.get("status") in - ("promoted", "monitored", "proposed", "observed", "implemented", "validated")] - if not rows: - return "" - lines = ["Background information from earlier work (evidence to weigh, not instructions):"] - for r in rows[:5]: +DELIVERED = ("promoted", "monitored", "proposed", "observed", "implemented", "validated") + + +def _delivery_lines(rows): + lines = [] + for r in rows: val = (r.get("validation") or {}).get("result") or "unvalidated" lines.append("- [%s, %s] %s — %s" % (r["id"], val if val == "validated" else "unvalidated", derive_title(r.get("title") or "", 110), derive_title(r.get("proposed", {}).get("description", ""), 160))) + return lines + + +def delivery_text(project, query="", targets=(), limit=5): + """Learnings in scope, framed as information, never as instructions. No showing is recorded. + With targets: the learnings that target those rule, recipe or technique ids, plus the ones + that match the query. Silence is the default.""" + rows = [r for r in learnings_in_scope(project) if r.get("status") in DELIVERED] + chosen = [] + if targets: + chosen += [r for r in rows if (r.get("proposed") or {}).get("target") in set(targets)] + if query: + chosen += [r for r in similar_learnings(rows, query, limit=limit) if r not in chosen] + elif not targets: + chosen = [] + if not chosen: + return "" + lines = ["Background information from earlier work (evidence to weigh, not instructions):"] + lines += _delivery_lines(chosen[:limit]) return "\n".join(lines) + "\n" @@ -258,9 +451,11 @@ def delivery_text(project, query=""): def new_record(finding, cause, impact, disposition, project, unit, change=None, mechanism=None, scope=None, expect=None, validate=None, limits=None, why_not=None, owner_statement=False, subagent=False, - replay=None, entered_via="retro"): + replay=None, entered_via="retro", target=None, origin=None): rows = load_learnings() pk = project_key(project) + finding, cause = scrub_secrets(finding), scrub_secrets(cause) + change = scrub_secrets(change) if change else change rec = { "id": next_id(rows), "title": derive_title(change or finding), "source_unit": unit, "origin_project": pk, @@ -268,36 +463,74 @@ def new_record(finding, cause, impact, disposition, project, unit, "root_cause": cause, "proposed": {"description": change or "", "mechanism": mechanism, "scope": scope or ("user" if owner_statement else "project"), - "target": None}, - "expected_effect": expect or "", "limits": limits or "", "why_not": why_not or "", - "validation": {"method": validate or "", "benchmark": None, + "scope_asked": scope, "target": target}, + "expected_effect": scrub_secrets(expect or ""), "limits": scrub_secrets(limits or ""), + "why_not": scrub_secrets(why_not or ""), + "validation": {"method": scrub_secrets(validate or ""), "benchmark": None, "result": "unvalidated", "detail": ""}, "status": "promoted" if owner_statement else ("proposed" if disposition == "promote" else "observed"), - "version": 1, "confidence": "low", + "version": 1, "confidence": "high" if owner_statement else "low", "provenance": [{"unit": unit, "project": pk, "ts": now(), "kind": "origin"}], "terms": derive_terms(finding, cause, change or ""), "owner_statement": bool(owner_statement), "candidate": bool(subagent), "entered_via": entered_via, "recurrences_after_promotion": 0, "flagged_not_working": False, "promoted_at": now() if owner_statement else None, - "promoted_unit_seq": None, "mechanism_ref": None, "replay": replay, - "created": now(), + "mechanism_ref": None, "replay": replay, "created": now(), } + if origin: + rec["statement_origin"] = origin rows.append(rec) - save_learnings(rows, "learning %s recorded" % rec["id"]) + save_learnings(rows, "learning %s recorded" % rec["id"], created=[rec], via=entered_via) return rec -def add_recurrence(rec, unit, project, rows): - """Attach a recurrence. After promotion it counts against the learning.""" +def add_recurrence(rec, unit, project, rows, finding=None): + """Attach a recurrence, once per unit. The finding (a recorded finding of this unit in this + project) is the evidence; a unit already in the provenance is not counted again. After + promotion a new recurrence counts against the learning. Returns True when one was added.""" pk = project_key(project) - rec.setdefault("provenance", []).append( - {"unit": unit, "project": pk, "ts": now(), "kind": "recurrence"}) + prov = rec.setdefault("provenance", []) + if any(p.get("unit") == unit and p.get("project") == pk for p in prov): + return False + prov.append({"unit": unit, "project": pk, "ts": now(), "kind": "recurrence", "finding": finding}) if rec.get("status") in ("promoted", "monitored", "validated", "implemented") and rec.get("promoted_at"): rec["recurrences_after_promotion"] = int(rec.get("recurrences_after_promotion") or 0) + 1 if rec["recurrences_after_promotion"] >= 2: rec["flagged_not_working"] = True - save_learnings(rows, "learning %s recurrence" % rec["id"]) + if rec["status"] == "promoted": + rec["status"] = "monitored" + save_learnings(rows, "learning %s recurrence" % rec["id"], touched=[rec]) + return True + + +def adopt(lid, unit, project): + """A parent adopts a subagent's candidate, by id and in its own project only.""" + rows = load_learnings() + rec = get(rows, lid) + if rec is None: + raise LearningError("no learning %r" % lid) + if not rec.get("candidate"): + raise LearningError("learning %s is not a candidate" % lid) + if rec.get("origin_project") != project_key(project): + raise LearningError("learning %s was recorded in another project; adopt it there" % lid) + rec["candidate"] = False + rec.setdefault("history", []).append({"ts": now(), "action": "adopt", "unit": unit}) + save_learnings(rows, "learning %s adopted" % lid, touched=[rec]) + return rec + + +def withdraw(lid, why): + """Withdraw an owner statement recorded by mistake: kept in history, never delivered again.""" + rows = load_learnings() + rec = get(rows, lid) + if rec is None or not rec.get("owner_statement"): + raise LearningError("no owner statement %r" % lid) + if rec.get("status") in ENDED: + raise LearningError("%s is already withdrawn" % lid) + rec["status"] = "rejected" + rec.setdefault("history", []).append({"ts": now(), "action": "withdraw", "why": scrub_secrets(why)}) + save_learnings(rows, "learning %s withdrawn" % lid, touched=[rec], via="learn") return rec @@ -307,25 +540,94 @@ def findings_for_unit(project, uid): return [f for f in load_findings() if f.get("unit") == uid and f.get("project") == pk] -def units_seen(): - """Closed-unit summary lines from the unit worker's store, when it exists.""" - out = [] +# ---- owner statements: who said it ------------------------------------------------------ + +def _norm_words(t): + return " ".join(str(t or "").lower().split()) + + +def statement_origin(statement): + """`typed by the owner` when the quoted words appear in a human-typed message of this + session's transcript (read with harvest.typed_text, the one definition of "typed by the + human"); `relayed by an agent` when they do not, or when no transcript is available.""" + _sid, sess = session_record() + tp = sess.get("transcript_path") if isinstance(sess, dict) else None + if not isinstance(tp, str) or not tp: + return "relayed by an agent" + want = _norm_words(statement) try: - with open(paths.data_file("units.jsonl"), encoding="utf-8") as f: - for line in f: - if line.strip(): - out.append(json.loads(line)) - except (OSError, ValueError): + from . import harvest + path = os.path.expanduser(tp) + size = os.path.getsize(path) + with open(path, "rb") as f: + start = max(0, size - 8 * 1024 * 1024) + f.seek(start) + data = f.read() + lines = data.split(b"\n") + if start: + lines = lines[1:] + for raw in lines: + if b'"user"' not in raw: + continue + try: + d = json.loads(raw) + except ValueError: + continue + if not isinstance(d, dict): + continue + text = harvest.typed_text(d)[0] + if text and want in _norm_words(text): + return "typed by the owner" + except (OSError, ImportError): pass + return "relayed by an agent" + + +# ---- units and monitoring -------------------------------------------------------------- + +def units_seen(): + """Closed units from the unit record's summary file in the user store (one JSON object per + line: id, project, closed_at, risk). The file may not exist yet: then there are none.""" + return _read_jsonl(paths.data_file("units.jsonl"))[0] + + +def units_since_promotion(rec, units=None): + """Closed units that count for this learning: after its promotion, and in its own scope (its + origin project when the scope is project, any project when it has earned more).""" + units = units_seen() if units is None else units + since = str(rec.get("promoted_at") or "") + if not since: + return [] + wide = earned_scope(rec) != "project" + out, cache = [], {} + for u in units: + closed = str(u.get("closed_at") or "") + if not closed or closed < since: + continue + if not wide: + p = u.get("project") + if p not in cache: + cache[p] = normalize_project(p) + if cache[p] != rec.get("origin_project"): + continue + out.append(u) return out -def unit_seq(): - return len(units_seen()) +def monitor(rows=None, units=None): + """Move promoted learnings to `monitored` once monitoring has something to say (a unit in + scope has closed since promotion, or one recurred). Returns the changed records.""" + rows = load_learnings() if rows is None else rows + units = units_seen() if units is None else units + changed = [] + for r in rows: + if r.get("status") == "promoted" and not r.get("owner_statement") and r.get("promoted_at") \ + and (units_since_promotion(r, units) or int(r.get("recurrences_after_promotion") or 0)): + r["status"] = "monitored" + changed.append(r) + return changed -# ---- monitoring ----------------------------------------------------------------- - def flagged(rows=None): rows = load_learnings() if rows is None else rows return [r for r in rows if r.get("flagged_not_working") and r.get("status") not in ("revised", "reverted", "rejected")] @@ -336,51 +638,51 @@ def learning_report(): rows = load_learnings() findings = load_findings() units = units_seen() + ledger = load_ledger() lines = ["Learning loop (recorded facts; no improvement is claimed from counts):", "learnings: %d findings: %d closed units known: %d" % (len(rows), len(findings), len(units))] + odd = [r["id"] for r in rows if not is_registered(r, ledger)] + if odd: + lines.append("not delivered (not written by sisi's own commands, or edited by hand): " + ", ".join(odd)) promoted = [r for r in rows if r.get("status") in ("promoted", "monitored") and not r.get("owner_statement")] if promoted: lines.append("promoted learnings:") holding = 0 relevant = 0 for r in promoted: - since = None - if r.get("promoted_unit_seq") is not None: - since = len(units) - int(r["promoted_unit_seq"]) - else: - since = sum(1 for u in units if str(u.get("ts", "")) >= str(r.get("promoted_at") or "")) + since = len(units_since_promotion(r, units)) rec = int(r.get("recurrences_after_promotion") or 0) val = (r.get("validation") or {}).get("result") or "unvalidated" if r.get("flagged_not_working"): verdict = "not working (flagged: next cycle must revise or revert)" - elif since >= 5 and rec == 0: + elif since >= MONITOR_UNITS and rec == 0: verdict = "holding" elif rec: verdict = "recurred, watching" else: verdict = "too few units to judge" - if since >= 5: + if since >= MONITOR_UNITS: relevant += 1 if rec == 0: holding += 1 - lines.append("- %s: %d unit(s) since promotion, %d recurrence(s), %s — %s" + lines.append("- %s: %d unit(s) in scope since promotion, %d recurrence(s), %s — %s" % (r["id"], since, rec, val if val == "validated" else "unvalidated", verdict)) if relevant < 5: lines.append("realization rate: too few (fewer than five promoted learnings have " "five relevant units; no rate is claimed)") else: lines.append("realization rate: %d of %d promoted learnings holding with no recurrence " - "over at least five units" % (holding, relevant)) + "over at least five units in their scope" % (holding, relevant)) fl = flagged(rows) if fl: lines.append("flagged not working: " + ", ".join(r["id"] for r in fl)) pend = load_pending() if pend: - lines.append("waiting for the owner's decision: %d change(s) (`sisi approve ID --yes|--no`)" + lines.append("waiting for the owner's decision: %d change(s) (`sisi approve` lists them in full)" % len(pend)) tool = [r for r in rows if r.get("proposed", {}).get("mechanism") == "tool" - and r.get("status") not in ("rejected", "reverted")] + and r.get("status") not in ENDED] if tool: lines.append("tool backlog (changes to sisi itself):") for r in tool[:8]: @@ -405,13 +707,49 @@ def save_pending(items, msg="pending decision updated"): pdata.commit(msg, ["pending.json"]) +def next_pending_id(items): + n = 0 + for i in items: + m = re.match(r"P-(\d+)$", str(i.get("id", ""))) + if m: + n = max(n, int(m.group(1))) + try: + n = max(n, max(int(re.sub(r"\D", "", str(a.get("id"))) or 0) for a in load_approvals())) + except ValueError: + pass + return "P-%04d" % (n + 1) + + +def load_approvals(): + return _read_jsonl(approvals_path())[0] + + +def record_approval(row): + """Append-only record of an owner decision; committed with the change it decided.""" + pdata.ensure() + pdata.write_text("approvals.jsonl", (pdata.read_text("approvals.jsonl", "") or "") + + json.dumps(row, sort_keys=True) + "\n") + pdata.commit("approval %s recorded" % row.get("id"), ["approvals.jsonl"]) + + +def approved_ids(): + return {a["id"] for a in load_approvals() if a.get("decision") == "yes" and a.get("id")} + + def pending_notice(): n = len(load_pending()) - return "sisi: %d learning change(s) wait for your decision (`sisi approve`)." % n if n else "" + if not n: + return "" + return ("sisi: %d learning change(s) wait for the owner's decision. Ask the owner through the host's " + "question dialog (`sisi approve` lists each change in full; show him what it would do) and give " + "him the command to run himself in a terminal: `sisi approve ID --yes` or `--no`. " + "Do not run it for him." % n) # ---- owner statements (one path: learn writes, oracle prints) --------------------- def owner_statements(rows=None): rows = load_learnings() if rows is None else rows - return [r for r in rows if r.get("owner_statement") and r.get("status") not in ("rejected", "reverted")] + ledger = load_ledger() + return [r for r in rows if r.get("owner_statement") and r.get("status") not in ENDED + and is_registered(r, ledger)] diff --git a/sisi/lifecycle.py b/sisi/lifecycle.py index ea46d55..8d25c7f 100644 --- a/sisi/lifecycle.py +++ b/sisi/lifecycle.py @@ -245,78 +245,111 @@ def run(): return notes -def migrate_learnings(): - """Old lesson store -> learning records. Idempotent, with a backup first, lossless. - - lessons.jsonl mixed lesson rows with occurrence and impression rows. Lessons become - learning records with honest statuses (folded into prose is `implemented`, always - unvalidated; nothing becomes `validated`); occurrences become provenance; impressions - (sisi's own showings) are dropped, never evidence. learn.jsonl owner statements become - owner-statement records in the same store. Returns notes with before/after counts. - """ - from . import learning as L - if os.path.exists(L.learnings_path()): - return [] - src = paths.data_file("lessons.jsonl") - learn_src = paths.data_file("learn.jsonl") - if not os.path.exists(src) and not os.path.exists(learn_src) \ - and not os.path.exists(paths.data_file("retro.db")): - return [] - bdir = snapshot("learning-migration") - lessons, occs, impressions = {}, {}, 0 - db = paths.data_file("retro.db") - if not os.path.exists(src) and os.path.exists(db): - # an install whose committed dump was never written: read the sqlite store directly - con = sqlite3.connect(db, timeout=30) - con.row_factory = sqlite3.Row - try: - for r in con.execute("SELECT * FROM lessons ORDER BY id"): - lessons[r["id"]] = dict(r) - for r in con.execute("SELECT * FROM occurrences ORDER BY id"): - occs.setdefault(r["lesson_id"], []).append(dict(r)) - except sqlite3.Error: - lessons, occs = {}, {} - finally: - con.close() - if os.path.exists(src): - with open(src, encoding="utf-8") as f: +def _jsonl_rows(path): + """(rows, malformed line count) of a jsonl file that may not exist.""" + rows, bad = [], 0 + try: + with open(path, encoding="utf-8") as f: for line in f: if not line.strip(): continue try: - r = json.loads(line) + d = json.loads(line) except ValueError: + bad += 1 continue - t = r.get("t") - if t == "lesson": - lessons[r.get("id")] = r - elif t == "occurrence": - occs.setdefault(r.get("lesson_id"), []).append(r) - elif t == "impression": - impressions += 1 - rows = [] + if isinstance(d, dict): + rows.append(d) + else: + bad += 1 + except OSError: + pass + return rows, bad + + +def migrate_learnings(): + """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 + carried twice, so running `sisi learn` before the first migration loses nothing). + + lessons.jsonl and the sqlite store hold lesson rows, occurrence rows, impression rows (sisi's + own showings, dropped: never evidence) and pattern rows (not carried; the backup keeps them). + Lessons become learning records with honest statuses (folded into prose is `implemented`, + always unvalidated; nothing becomes `validated`); occurrences become provenance, with the old + repo values normalised to the project key new code uses; a learning is earned wider only under + the same two-units-two-projects rule as a new one. learn.jsonl owner statements become + owner-statement records, keeping their scope. Malformed lines are counted, not hidden. Returns + notes with the counts. + """ + from . import learning as L + marker = paths.data_file("learnings-migrated.json") + if os.path.exists(marker): + return [] + src = paths.data_file("lessons.jsonl") + learn_src = paths.data_file("learn.jsonl") + db = paths.data_file("retro.db") + if not (os.path.exists(src) or os.path.exists(learn_src) or os.path.exists(db)): + return [] + bdir = snapshot("learning-migration") + lessons, occs = {}, {} + dropped = {"impression": 0, "sighting": 0, "pattern": 0} + malformed = {"lessons.jsonl": 0, "learn.jsonl": 0} + jrows, malformed["lessons.jsonl"] = _jsonl_rows(src) + for r in jrows: + t = r.get("t") + if t == "lesson": + lessons[r.get("id")] = r + elif t == "occurrence": + occs[r.get("id")] = r + elif t in dropped: + dropped[t] += 1 + if os.path.exists(db): + con = sqlite3.connect(db, timeout=30) + con.row_factory = sqlite3.Row + try: + for r in con.execute("SELECT * FROM lessons ORDER BY id"): + lessons.setdefault(r["id"], dict(r)) + for r in con.execute("SELECT * FROM occurrences ORDER BY id"): + occs.setdefault(r["id"], dict(r)) + except sqlite3.Error: + pass + finally: + con.close() + rows = L.load_learnings() + have_legacy = {r.get("legacy_id") for r in rows if r.get("legacy_id") is not None} + have_text = {" ".join(str((r.get("proposed") or {}).get("description") or "").lower().split()) + for r in rows if r.get("owner_statement")} + by_lesson = {} + for o in occs.values(): + by_lesson.setdefault(o.get("lesson_id"), []).append(o) + added, already, attached, touched = 0, 0, 0, [] for lid in sorted(lessons, key=lambda x: (x is None, x)): + if lid in have_legacy: + already += 1 + continue old = lessons[lid] prov = [] - for o in occs.get(lid, []): - prov.append({"unit": "session:%s" % (o.get("session") or o.get("id")), - "project": o.get("repo") or o.get("cwd") or old.get("project") or "", - "ts": o.get("ts") or "", "kind": "occurrence"}) - origin = old.get("project") or (prov[0]["project"] if prov else "") + for o in sorted(by_lesson.get(lid, []), key=lambda x: x.get("id") or 0): + proj = L.normalize_project(o.get("repo") or o.get("cwd") or old.get("project")) + unit = ("session:%s" % o["session"]) if o.get("session") else "legacy:%s:%s" % (lid, proj) + prov.append({"unit": unit, "project": proj, "ts": o.get("ts") or "", "kind": "occurrence"}) + attached += len(prov) + origin = L.normalize_project(old.get("project")) or (prov[0]["project"] if prov else "") 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"}] status = {"applied": "implemented", "retired": "reverted"}.get(old.get("status"), "observed") kind = old.get("change_kind") - rows.append({ - "id": "L-%04d" % (len(rows) + 1), "legacy_id": lid, + target = str(old.get("target") or "") + rec = { + "id": L.next_id(rows), "legacy_id": lid, "title": L.derive_title(old.get("short") or old.get("change") or old.get("moment") or ""), "source_unit": prov[0]["unit"], "origin_project": origin, - "observation": {"evidence": old.get("moment") or "", "impact": "correctness"}, - "root_cause": old.get("cause") or "", - "proposed": {"description": old.get("change") or "", + "observation": {"evidence": L.scrub_secrets(old.get("moment") or ""), "impact": "correctness"}, + "root_cause": L.scrub_secrets(old.get("cause") or ""), + "proposed": {"description": L.scrub_secrets(old.get("change") or ""), "mechanism": "tool" if kind == "tool" else ("verification" if kind in ("check", "test") else "policy"), - "scope": "project", "target": old.get("target")}, + "scope": "project", "scope_asked": None, + "target": target[5:] if target.startswith("rule:") else (target or None)}, "expected_effect": "", "limits": "", "why_not": "", "validation": {"method": "", "benchmark": None, "result": "unvalidated", "detail": "migrated from the old lesson store; never replay-validated"}, @@ -324,45 +357,61 @@ def migrate_learnings(): "terms": L.derive_terms(old.get("moment") or "", old.get("cause") or "", old.get("change") or ""), "owner_statement": False, "candidate": False, "entered_via": "migration", "recurrences_after_promotion": 0, "flagged_not_working": False, - "promoted_at": None, "promoted_unit_seq": None, "mechanism_ref": old.get("folded_into"), - "replay": None, "created": old.get("created") or L.now()}) - statements = 0 - if os.path.exists(learn_src): - with open(learn_src, encoding="utf-8") as f: - for line in f: - if not line.strip(): - continue - try: - r = json.loads(line) - except ValueError: - continue - text = r.get("text") or r.get("statement") or "" - if not text: - continue - statements += 1 - rows.append({ - "id": "L-%04d" % (len(rows) + 1), "title": L.derive_title(text), - "source_unit": "owner", "origin_project": r.get("cwd") or "", - "observation": {"evidence": text, "impact": "value"}, - "root_cause": "owner statement", - "proposed": {"description": text, "mechanism": "knowledge", - "scope": "user", "target": None}, - "expected_effect": "the agent acts on this statement", "limits": "", "why_not": "", - "validation": {"method": "", "benchmark": None, "result": "unvalidated", "detail": ""}, - "status": "promoted", "version": 1, "confidence": "high", - "provenance": [{"unit": "owner", "project": r.get("cwd") or "", - "ts": r.get("ts") or "", "kind": "origin"}], - "terms": L.derive_terms(text), "owner_statement": True, "candidate": False, - "entered_via": "migration", "recurrences_after_promotion": 0, - "flagged_not_working": False, "promoted_at": r.get("ts") or L.now(), - "promoted_unit_seq": None, "mechanism_ref": None, "replay": None, - "created": r.get("ts") or L.now()}) - L.save_learnings(rows, "migrate: lessons and owner statements become learning records") - return ["learning migration: backed up to %s; %d lesson(s) and %d owner statement(s) became " - "%d learning record(s); %d occurrence(s) became provenance; %d impression(s) dropped " - "(showings are never evidence); nothing is validated" - % (bdir, len(lessons), statements, len(rows), - sum(len(v) for v in occs.values()), impressions)] + "promoted_at": None, "mechanism_ref": old.get("folded_into"), + "replay": None, "created": old.get("created") or L.now()} + rows.append(rec) + touched.append(rec) + added += 1 + orphans = sum(len(v) for k, v in by_lesson.items() if k not in lessons) + srows, malformed["learn.jsonl"] = _jsonl_rows(learn_src) + statements, dup = 0, 0 + for r in srows: + text = r.get("text") or r.get("statement") or "" + if not text: + continue + key = " ".join(text.lower().split()) + if key in have_text: + dup += 1 + continue + have_text.add(key) + statements += 1 + scope = r.get("scope") if r.get("scope") in ("user", "project", "organization") else "user" + proj = L.normalize_project(r.get("cwd")) + text = L.scrub_secrets(text) + rec = { + "id": L.next_id(rows), "title": L.derive_title(text), + "source_unit": "owner", "origin_project": proj, + "observation": {"evidence": text, "impact": "value"}, + "root_cause": "owner statement", + "proposed": {"description": text, "mechanism": "knowledge", "scope": scope, + "scope_asked": scope, "target": None}, + "expected_effect": "the agent acts on this statement", "limits": "", "why_not": "", + "validation": {"method": "", "benchmark": None, "result": "unvalidated", "detail": ""}, + "status": "promoted", "version": 1, "confidence": "high", + "provenance": [{"unit": "owner", "project": proj, "ts": r.get("ts") or "", "kind": "origin"}], + "terms": L.derive_terms(text), "owner_statement": True, "candidate": False, + "statement_origin": "migrated from the old statement file", + "entered_via": "migration", "recurrences_after_promotion": 0, + "flagged_not_working": False, "promoted_at": r.get("ts") or L.now(), + "mechanism_ref": None, "replay": None, "created": r.get("ts") or L.now()} + rows.append(rec) + touched.append(rec) + counts = {"lessons_in_old_store": len(lessons), "lessons_migrated": added, "lessons_already_migrated": already, + "owner_statements_migrated": statements, "owner_statements_duplicate": dup, + "occurrences_attached": attached, "occurrences_without_a_lesson": orphans, + "malformed_lines_skipped": dict(malformed), "dropped_rows": dict(dropped), + "learning_records_after": len(rows)} + pdata.ensure() + pdata.write_text("learnings-migrated.json", json.dumps(dict(counts, ts=L.now(), backup=bdir), indent=2, sort_keys=True) + "\n") + L.save_learnings(rows, "migrate: lessons and owner statements become learning records", created=touched, via="migration") + pdata.commit("migrate: learning migration recorded", ["learnings-migrated.json"]) + return ["learning migration: backed up to %s; %d lesson(s) in the old store, %d carried over (%d already there); " + "%d owner statement(s) carried over (%d duplicate); %d occurrence(s) attached as provenance, %d without " + "a lesson left out; %d malformed line(s) skipped (lessons.jsonl %d, learn.jsonl %d); dropped as not " + "evidence or not carried: %d impression(s), %d sighting(s), %d pattern row(s); now %d learning record(s); " + "nothing is validated" % (bdir, len(lessons), added, already, statements, dup, attached, orphans, + sum(malformed.values()), malformed["lessons.jsonl"], malformed["learn.jsonl"], + dropped["impression"], dropped["sighting"], dropped["pattern"], len(rows))] # ---- snapshots (before an update) ------------------------------------------------------------- diff --git a/sisi/overlay.py b/sisi/overlay.py index cd7a84c..10e1fb2 100644 --- a/sisi/overlay.py +++ b/sisi/overlay.py @@ -216,10 +216,10 @@ def more_line(n): return "More: `sisi rule %d` (reasons, history, lessons behind it, how it is enforced)." % n -def render(): - pre, rules = effective() +def _render(pre, rules): try: - base_h = sha(open(paths.canon("core.md"), "rb").read())[:8] + with open(paths.canon("core.md"), "rb") as f: + base_h = sha(f.read())[:8] except OSError: base_h = "missing" head = "