From 6787ef0ae9095e323e974e5adf607974af765015 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 12:26:42 -0700 Subject: [PATCH] Item 4: remove guarded seams and dead code between the merged pieces. done 4 / next 5 (grouped help) --- docs/design.md | 28 ++++++++---------- docs/learning.md | 1 - sisi/adapters.py | 6 +--- sisi/cli.py | 24 +++++++-------- sisi/contract.py | 1 - sisi/cycle.py | 4 --- sisi/harvest.py | 2 +- sisi/hookjson.py | 12 -------- sisi/learn_cli.py | 5 ---- sisi/learning.py | 2 +- sisi/paths.py | 24 --------------- sisi/retro.py | 59 +++---------------------------------- sisi/risk.py | 1 - sisi/scope.py | 4 --- sisi/taskset.py | 1 - sisi/tick.py | 5 +--- sisi/unit.py | 12 -------- sisi/verifiers.py | 2 +- sisi/wiring.py | 32 +------------------- sisi/workers.py | 35 ---------------------- tests/test_learning_loop.py | 19 +++++++++++- tests/test_wiring.py | 33 ++++++++++++++++++++- tests/test_workers.py | 31 ------------------- 23 files changed, 82 insertions(+), 261 deletions(-) diff --git a/docs/design.md b/docs/design.md index 1ef3c6d..9dff1f0 100644 --- a/docs/design.md +++ b/docs/design.md @@ -18,7 +18,7 @@ that shows it: | Work at a higher level (functions, modules, products) | size of verified work delivered per human message | | Verifiable outcomes, formal where possible | share of delivered claims backed by a check that ran, by rung | | Hands off | human minutes and blocking questions per delivered piece of work | -| Delivered sooner, with no weaker check | median time from request to verified result (`sisi time`) | +| Delivered sooner, with no weaker check | median time from request to verified result (`sisi status`) | | Improves itself from use, everywhere | the numbers above, as trends, across all tools | ## The objective @@ -30,9 +30,8 @@ with a weaker check or a smaller result. Time to delivery is measured, not guessed. Each time the end-of-turn gate lets a turn end it records one delivery row: the time since the last message the human actually typed (hook feedback and tool results do not -count), how many times the gate sent the agent back, and how long the checks ran. `sisi time` shows the median -and 90th percentile for the last 7 days against the 7 days before, the share spent in checks, and the five -slowest checks; `sisi status` shows the 7-day median. +count), how many times the gate sent the agent back, and how long the checks ran. `sisi status` shows the +median and 90th percentile by project, risk profile, model and policy version. A learned change that speeds things up but fails a check is rejected. A learned change that keeps every check passing but makes median delivery slower is flagged for reversal. (Built: `sisi cycle status` flags a cycle @@ -126,12 +125,10 @@ runs alone. Results are reported in contract order either way. **Enforcement.** The tool's end-of-turn hook calls `sisi verify`. If a contract exists and a check fails or was not run, the agent is sent back with the failures and cannot report the work as done. If no contract exists and -the change is larger than a small threshold, the agent is sent back to write one; a change that size -with a contract whose design section is missing or fails validation is sent back to fill it. Small +the change is larger than its risk profile allows without one, the agent is sent back to write one. Small edits and subagents pass untouched, and the same send-back budget bounds every send-back, so no -session is trapped. Request-time delivery hands the standing principles and the design instruction -over when a request reads as design or build work, and `sisi design` prints them before a contract -exists. +session is trapped. Request-time delivery hands the standing principles over when a request reads as +design or build work. Claude Code supports a blocking stop hook. The equivalent in OpenCode, Codex and Muse is not verified; where it does not exist, verification is meant to run at the next session start and failures to be reported then (that fallback is a design intention, not built). @@ -315,19 +312,18 @@ Built and covered by tests: where nothing blocks. - The rulebook (`canon/core.md`), the risk table, the verifier library and the recipes. - Retrospectives and lessons (`sisi retro`, `sisi lessons`), `sisi learn` live at once, time to delivery - (`sisi time`). -- Choosing the approach as a checked step: the contract design section, `sisi design`, the gate's - design send-back on large changes, and request-time delivery of the standing principles for design - or build requests. The rulebook's first rule states it and `sisi rule` reports its enforcement. + (`sisi status`). +- Choosing the approach as a checked step: the contract's `approach` and the request-time delivery of the + standing principles for design or build requests. `sisi rule` reports the rulebook's enforcement. - Patterns: each retro names the general failure of thinking behind the incident; patterns are first-class, merged in rounds, and promoted into the rulebook as strategic behaviours past a - threshold; the digest and `sisi improve` show them first. Three tiers (`core`, `user`, `project`) + threshold; `sisi status --learning` shows them first. Three tiers (`core`, `user`, `project`) replace the two-way scope, with older universal items tiered by the next round, and `sisi promote` listing, writing (from the clone) or exporting core items. -- The lesson loop: immediate effects in the overlay (field notes, draft recipes, learned notes, `sisi backlog`), +- The lesson loop: immediate effects in the overlay (field notes, draft recipes, learned notes), moment-of-use delivery with recorded showings, per-lesson measurement, the strength ladder with enforced checks, `sisi cycle` (due counter, brief, validated apply under lock and base version, exact revert, status - with worse-cycle flagging) and `sisi improve`. + with worse-cycle flagging). - Personal data, the overlay, update, export and import, releases and rollback, promotion of a personal item into the product. - The data layer for learning: harvest of Claude Code transcripts, task set, ground truth, escape candidates, diff --git a/docs/learning.md b/docs/learning.md index b395689..5f6cd73 100644 --- a/docs/learning.md +++ b/docs/learning.md @@ -173,6 +173,5 @@ learnings in scope that target that entry. - `cycle.risk_patterns(cwd)` — the learned risk patterns that apply in a project (`risk.load_patterns`). - `cycle.routing_adjustments(project)` — the learned routing adjustments that apply in a project. - `cycle.due_notice()` — the session-start lines (cycle due, decision waiting). -- `retro.satisfied(repo, since, fp)` and `retro.TEMPLATE` — what the gate asks. - `learning.delivery_text(project, query, targets=())` — what the prompt hook may add. - `evaluate.validate_command(repo, before, after, cmd)` — the replay. diff --git a/sisi/adapters.py b/sisi/adapters.py index 41d35d2..71d952b 100644 --- a/sisi/adapters.py +++ b/sisi/adapters.py @@ -7,7 +7,7 @@ whose config folder does not exist is skipped and reported, never an error. Only from the tool's own documentation, `--help`, installed files or a local spike are wired here (see docs/harnesses.md); anything unconfirmed is reported in doctor, not guessed into a config. """ -import copy, difflib, hashlib, json, os, shlex +import difflib, hashlib, json, os from . import hookjson, paths, store, wiring @@ -515,10 +515,6 @@ class Adapter: "detail": "not wired", "action": None} -def _st(a, rulebook, tick, wired, detail, action=None): - return {"tool": a.name, "detected": True, "rulebook": rulebook, "tick": tick, - "enforcement": a.enforcement, "via": a.via, "wired": wired, "detail": detail, "action": action} - class Codex(Adapter): name, enforcement, via = "codex", "blocks", "Stop" diff --git a/sisi/cli.py b/sisi/cli.py index b46d5ff..e3907e3 100644 --- a/sisi/cli.py +++ b/sisi/cli.py @@ -409,17 +409,13 @@ def main(argv): def _learn_cli(cmd, args): - """Data-layer commands (harvest, tasks, ...) live in learn_cli. The CLI works without it, even if it is broken.""" - try: - import argparse - from . import learn_cli - ap = argparse.ArgumentParser(prog="sisi") - sub = ap.add_subparsers(dest="cmd") - learn_cli.register(sub) - if cmd not in sub.choices: - return None - ns = ap.parse_args([cmd] + args) - return ns.func(ns) - except (ImportError, AttributeError, TypeError) as e: - print("sisi: the %r command is unavailable (%s)" % (cmd, e), file=sys.stderr) - return 70 + """Data-layer commands (harvest, tasks, ...) live in learn_cli; None when `cmd` is not one of them.""" + import argparse + from . import learn_cli + ap = argparse.ArgumentParser(prog="sisi") + sub = ap.add_subparsers(dest="cmd") + learn_cli.register(sub) + if cmd not in sub.choices: + return None + ns = ap.parse_args([cmd] + args) + return ns.func(ns) diff --git a/sisi/contract.py b/sisi/contract.py index 1db3d9c..afdf1ce 100644 --- a/sisi/contract.py +++ b/sisi/contract.py @@ -190,7 +190,6 @@ _PRINT_WORDS = {"echo", "printf"} _SHELLS = {"sh", "bash", "dash", "zsh", "/bin/sh", "/bin/bash", "/usr/bin/env"} _WRAPPERS = {"env", "command", "exec", "time", "nohup", "builtin"} _TESTERS = {"test", "["} -_OPS = {"&&", "||", ";", "|", "&"} def _lex(s): diff --git a/sisi/cycle.py b/sisi/cycle.py index 75f144b..3468258 100644 --- a/sisi/cycle.py +++ b/sisi/cycle.py @@ -134,10 +134,6 @@ def routing_adjustments(project): # ---- enforced checks (verify.py seam) ---------------------------------------------- -def enforced_path(): - return paths.overlay_dir("enforced.json") - - 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)] diff --git a/sisi/harvest.py b/sisi/harvest.py index a759b08..e0622a0 100644 --- a/sisi/harvest.py +++ b/sisi/harvest.py @@ -37,7 +37,7 @@ sub-agents is not machine-written. Pasted content does not count towards length (it is a human attachment). The heuristic errs towards calling things machine-written: a false "machine" only removes a session from the human task set. """ -import json, os, re, sys, time +import json, os, re from collections import namedtuple from . import paths diff --git a/sisi/hookjson.py b/sisi/hookjson.py index d71599e..013bc2b 100644 --- a/sisi/hookjson.py +++ b/sisi/hookjson.py @@ -234,18 +234,6 @@ def replace_node(text, node, new_text): return text[:node.start] + new_text + text[node.end:] -def get_path(text, root, keys): - node = root - for k in keys: - if node.kind == "lit" and node.value == "null": - return node - found = member(node, k) - if found is None: - return None - node = found[1] - return node - - def _dump(v): return json.dumps(v, ensure_ascii=False) diff --git a/sisi/learn_cli.py b/sisi/learn_cli.py index 9e7c502..41eae50 100644 --- a/sisi/learn_cli.py +++ b/sisi/learn_cli.py @@ -9,11 +9,6 @@ import argparse, json, sys, time from . import store -def _con(): - from . import harvest - return harvest.connect() - - def cmd_harvest(args): from . import groundtruth, harvest t = time.time() diff --git a/sisi/learning.py b/sisi/learning.py index b4272d9..69f5321 100644 --- a/sisi/learning.py +++ b/sisi/learning.py @@ -583,7 +583,7 @@ def statement_origin(statement): text = harvest.typed_text(d)[0] if text and want in _norm_words(text): return "typed by the owner" - except (OSError, ImportError): + except OSError: pass return "relayed by an agent" diff --git a/sisi/paths.py b/sisi/paths.py index 93714d2..20cbe59 100644 --- a/sisi/paths.py +++ b/sisi/paths.py @@ -98,30 +98,6 @@ def personal_config(): return {} -def set_personal_config(keys, value, msg): - """Set (or with None remove) a nested key in the personal config.json; one commit in the personal repository.""" - import json - from . import pdata - cfg = personal_config() - d = cfg - for k in keys[:-1]: - d = d.setdefault(k, {}) if isinstance(d.get(k, {}), dict) else d.setdefault(k, {}) - if value is None: - d.pop(keys[-1], None) - if not d and len(keys) > 1: - cfg.pop(keys[0], None) - else: - d[keys[-1]] = value - os.makedirs(data(), exist_ok=True) - p = data_file("config.json") - tmp = p + ".sisi-tmp" - with open(tmp, "w", encoding="utf-8") as f: - json.dump(cfg, f, indent=2, sort_keys=True) - f.write("\n") - os.replace(tmp, p) - pdata.commit(msg, ["config.json"]) - - def state_file(name): return os.path.join(state(), name) diff --git a/sisi/retro.py b/sisi/retro.py index f2b744d..73a38a1 100644 --- a/sisi/retro.py +++ b/sisi/retro.py @@ -4,28 +4,11 @@ No arguments: print the unit's record and what stands out. With --finding: recor finding with a disposition. Only the fields the disposition needs are asked for; search terms, topics and short lines are derived by the tool. A finding that resembles an existing learning is attached to it as a recurrence candidate, never refused in a loop. - -Gate compatibility (gate.py calls these; its control flow is unchanged): TEMPLATE, -satisfied(), repo_of(), lessons_block(). """ import hashlib, json, os, subprocess, sys from . import learning as L, paths -TEMPLATE = ( - "Before this turn ends, record the retro for this unit ({n}).\n" - "Run `sisi retro` first: it prints the unit's record. Then record at least one finding:\n" - " sisi retro --finding \"\" --cause \"\" " - "--impact value|correctness|time|cost|attention --disposition promote|record|drop\n" - " promote also needs: --change \"\" --mechanism policy|orchestration|skill|tool|" - "infrastructure|verification|knowledge|benchmark --expect \"\" --validate \"\"\n" - " record also needs: --limits \"\"\n" - " drop also needs: --why-not \"\"\n" - "Generic findings are refused. A finding that resembles a learning in scope here is attached to it as\n" - "a recurrence (--new records it as its own); --same-as ID names the learning it repeats.\n" - "A parent adopts a subagent's candidate by id: sisi retro --adopt ID." -) - def repo_of(cwd): return L.project_key(cwd) @@ -40,39 +23,12 @@ def _git_head(cwd): return None -def satisfied(repo, since, fp): - """Gate seam: was a retro recorded for the current unit of this project?""" - try: - uid = L.unit_id(repo) - if L.findings_for_unit(repo, uid): - return True - # A finding recorded in this project since the request started also counts: - # the gate passes `since` from its own session bookkeeping. - pk = L.project_key(repo) - return any(f.get("project") == pk and (since is None or str(f.get("ts", "")) >= str(since)) - for f in L.load_findings()) if since else False - except Exception: - return False - - -def lessons_block(query, place, session=None, limit=3, max_chars=600, extra=""): - """Gate seam: learnings in scope as background information. Nothing is recorded as shown.""" - try: - text = L.delivery_text(os.getcwd(), str(query)) - return text[:max_chars] if text else "" - except Exception: - return "" - - def unit_summary(project): """What `sisi retro` with no arguments prints: the unit's record and what stands out.""" - try: - from . import unit as _unit # work-unit worker's module, when merged - text = _unit.summary_for_retro(project) - if text: - return text - except Exception: - pass + from . import unit as _unit + text = _unit.summary_for_retro(project) + if text: + return text lines = [] try: with open(os.path.join(project, ".sisi", "contract.json"), encoding="utf-8") as f: @@ -91,13 +47,6 @@ def unit_summary(project): lines.append("recent verification: %d result(s) on record, %d failed" % (len(rows), len(fails))) except (OSError, ValueError): pass - try: - from . import delivery - d = delivery.current(project) if hasattr(delivery, "current") else None - if d: - lines.append("delivery: %s" % d) - except Exception: - pass head = _git_head(project) if head: lines.append("project HEAD: %s" % head[:12]) diff --git a/sisi/risk.py b/sisi/risk.py index aa684e6..5e0c55b 100644 --- a/sisi/risk.py +++ b/sisi/risk.py @@ -38,7 +38,6 @@ import fnmatch, json, os, re, subprocess PROFILES = ["trivial", "isolated", "logic", "integration", "data", "critical", "release"] _ORDER = {name: i for i, name in enumerate(PROFILES)} -_TRIVIAL_PROFILES = {"trivial"} _DEFAULT_REASON = "ordinary source file: one module's behaviour" _CONTAINERS = {"src", "lib", "app", "packages", "apps", "services", "crates", "modules", "libs", "cmd", "internal", "pkg"} diff --git a/sisi/scope.py b/sisi/scope.py index 56197d1..9b1f26e 100644 --- a/sisi/scope.py +++ b/sisi/scope.py @@ -18,10 +18,6 @@ def project_label(pid): return os.path.basename(str(pid).rstrip("/")) if pid else "(unknown project)" -def visible_in(rec, cwd): - return L.in_scope(rec, cwd) - - USAGE = ("usage: sisi learn [--scope user|project] \"\"\n" " sisi learn --withdraw ID --reason \"\"") diff --git a/sisi/taskset.py b/sisi/taskset.py index f7a834a..9dce278 100644 --- a/sisi/taskset.py +++ b/sisi/taskset.py @@ -24,7 +24,6 @@ Split: sha256(task id) mod 100 < 70 is `dev`, else `holdout`. It depends on the """ import hashlib, json, os, time -from . import harvest, paths DEV_PERCENT = 70 MATCH_SLACK_S = 1200 diff --git a/sisi/tick.py b/sisi/tick.py index 03ed8c0..7c8dc36 100644 --- a/sisi/tick.py +++ b/sisi/tick.py @@ -1,12 +1,9 @@ """Session-start hook. Records the session baseline, checks wiring, prints at most one line. Must be fast.""" -import json, os, sys, time +import json, os, sys from . import store -MAX_AGE_S = 30 * 86400 - - def _prune(now=None, sid=None): """Delete old per-session state files, bounded and on a counter (see store.prune_sessions).""" return store.prune_sessions(now=now, active_ids=(sid,) if sid else ()) diff --git a/sisi/unit.py b/sisi/unit.py index 976b2a0..a90765d 100644 --- a/sisi/unit.py +++ b/sisi/unit.py @@ -124,18 +124,6 @@ def delegations(project, t0, t1): return None -def _row_epoch(r): - for k in ("ts", "t", "started", "ended", "time"): - v = r.get(k) - if isinstance(v, (int, float)) and not isinstance(v, bool): - return float(v) - if isinstance(v, str): - t = harvest.epoch(v) - if t is not None: - return t - return None - - def policy_version(project, c): """Hash of the policies in force: the effective rulebook, the risk tables, the enforced checks, and the gate/verify config.""" diff --git a/sisi/verifiers.py b/sisi/verifiers.py index 766697c..9c5ab9e 100644 --- a/sisi/verifiers.py +++ b/sisi/verifiers.py @@ -1,5 +1,5 @@ """The verifier library and the recipes for "done": parse, list, show, choose, doctor, lint. No model calls.""" -import concurrent.futures as cf, json, os, re, subprocess, sys +import concurrent.futures as cf, json, os, re, subprocess from . import contract as C, paths diff --git a/sisi/wiring.py b/sisi/wiring.py index 37a4036..0436521 100644 --- a/sisi/wiring.py +++ b/sisi/wiring.py @@ -1,7 +1,7 @@ """install / uninstall / doctor. Wiring by reference (import line, symlink, hook entry); never copies canon text. The tools load the generated rulebook in the personal data folder (base rules with the overlay applied), not the product's canon/core.md. Every modified file is backed up into /install/ first; uninstall restores it exactly.""" -import copy, hashlib, json, os, re, shlex, shutil, stat as _stat +import copy, hashlib, json, os, re, stat as _stat from . import hookjson, paths, store @@ -321,36 +321,6 @@ def add_hooks(obj): return changed -def remove_hooks(obj): - changed = False - hooks = obj.get("hooks") - if not isinstance(hooks, dict): - return False - for ev, sub in (("SessionStart", "tick"), ("UserPromptSubmit", "prompt"), ("Stop", "gate"), ("SubagentStop", "gate"), - ("PreToolUse", "watch"), ("PostToolUse", "watch")): - groups = hooks.get(ev) - if not isinstance(groups, list): - continue - keep, ev_changed = [], False - for g in groups: - hs = g.get("hooks") if isinstance(g, dict) else None - if isinstance(hs, list) and any(_is_ours(h, sub) for h in hs): - changed = ev_changed = True - rest = [h for h in hs if not _is_ours(h, sub)] - if rest: - g = dict(g, hooks=rest) - else: - continue - keep.append(g) - if keep: - hooks[ev] = keep - elif ev_changed: - del hooks[ev] - if changed and not hooks: - del obj["hooks"] - return changed - - def _hooks_wired(obj): hooks = obj.get("hooks") if isinstance(obj, dict) else None out = {} diff --git a/sisi/workers.py b/sisi/workers.py index 4b81cc5..86061d1 100644 --- a/sisi/workers.py +++ b/sisi/workers.py @@ -470,36 +470,6 @@ def import_ledger(src, now=None): return before, before + added, added -def ensure_imported(now=None): - """Import the previously hand-kept ledger once, losslessly. Returns the row count, or None - when there was nothing (more) to import. The original file is only read.""" - now = time.time() if now is None else now - marker = _data_file("delegations-import.json") - if os.path.exists(marker): - return None - try: - from . import taskset - src = taskset.ledger_path() - except Exception: - src = None - if not src or not os.path.isfile(src): - return None - if os.path.realpath(src) == os.path.realpath(ledger_path()): - return None - _before, _after, count = import_ledger(src, now=now) - # Merge the availability file that sat beside the old ledger, so nothing is forgotten. - sibling = os.path.join(os.path.dirname(src), "availability.json") - if os.path.isfile(sibling): - avail = read_availability() - for k, v in read_json(sibling).items(): - if isinstance(v, dict): - avail[str(k).lower()] = v - if avail: - write_json(availability_path(), avail) - write_json(marker, {"source": src, "rows": count, "ts": now}) - return count - - def unjudged_runs(records=None): records = read_records() if records is None else records judged = {r.get("run_id") for r in records if r.get("kind") == "attempt" and r.get("run_id")} @@ -1230,7 +1200,6 @@ def cmd_workers(args=()): return _cmd_up(args[1:]) if args[:1] == ["import"]: return _cmd_import(args[1:]) - imported = ensure_imported() disc = discover(force="--refresh" in args) records = read_records() avail = read_availability() @@ -1274,9 +1243,6 @@ def cmd_workers(args=()): continue print("Unavailable: %s - %s, next try %s%s" % (k, v.get("reason") or "down", _when(v.get("retry_at")), (" (%s)" % v["note"]) if v.get("note") else "")) - if imported is not None: - print("Imported the existing delegation ledger: imported %d rows, once, without changing the original." - % imported) waiting = unjudged_runs(records) if waiting: print("%d delegation%s waiting for a judgement (%s). Judge with `sisi delegate judge ID " @@ -1296,7 +1262,6 @@ def cmd_workers(args=()): def _route_setup(args): - ensure_imported() kind = _opt(args, "--kind") difficulty = _opt(args, "--difficulty") if not kind or difficulty is None: diff --git a/tests/test_learning_loop.py b/tests/test_learning_loop.py index 0b5e179..7412127 100644 --- a/tests/test_learning_loop.py +++ b/tests/test_learning_loop.py @@ -983,7 +983,7 @@ class Store(Base): root = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) bad = [] for n in sorted(os.listdir(os.path.join(root, "sisi"))): - if not n.endswith(".py") or n == "gate.py": # gate.py's retro.lessons_block is the live gate seam + if not n.endswith(".py"): continue with open(os.path.join(root, "sisi", n)) as f: for i, line in enumerate(f, 1): @@ -992,6 +992,23 @@ class Store(Base): bad.append("%s:%d" % (n, i)) self.assertEqual(bad, []) + def test_no_guarded_seams_between_modules_that_always_exist(self): + """Item 4: no `except ImportError` or `hasattr(module, ...)` probe stands in for a module of this + package, and nothing names a removed seam. The one platform probe (fcntl, absent on Windows, in pdata) stays.""" + import re + root = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + bad = [] + for n in sorted(os.listdir(os.path.join(root, "sisi"))): + if not n.endswith(".py"): + continue + with open(os.path.join(root, "sisi", n)) as f: + for i, line in enumerate(f, 1): + if n != "pdata.py" and re.search(r"except \(?ImportError|hasattr\((delivery|unit|gate|retro|learning|cycle)\b", line): + bad.append("%s:%d" % (n, i)) + if re.search(r"retro\.(TEMPLATE|satisfied|lessons_block)|ensure_imported", line): + bad.append("%s:%d" % (n, i)) + self.assertEqual(bad, []) + def test_no_resource_warnings_from_the_learning_commands(self): """Item 13: file handles are closed; every learning command runs clean under -W always.""" _contract(self) diff --git a/tests/test_wiring.py b/tests/test_wiring.py index 3100eb9..f186dca 100644 --- a/tests/test_wiring.py +++ b/tests/test_wiring.py @@ -19,6 +19,37 @@ def snapshot(root): return snap +def remove_hooks(obj): + """Test oracle: strip our hook groups from a settings object (the product removes them structurally).""" + changed = False + hooks = obj.get("hooks") + if not isinstance(hooks, dict): + return False + for ev, sub in (("SessionStart", "tick"), ("UserPromptSubmit", "prompt"), ("Stop", "gate"), ("SubagentStop", "gate"), + ("PreToolUse", "watch"), ("PostToolUse", "watch")): + groups = hooks.get(ev) + if not isinstance(groups, list): + continue + keep, ev_changed = [], False + for g in groups: + hs = g.get("hooks") if isinstance(g, dict) else None + if isinstance(hs, list) and any(wiring._is_ours(h, sub) for h in hs): + changed = ev_changed = True + rest = [h for h in hs if not wiring._is_ours(h, sub)] + if rest: + g = dict(g, hooks=rest) + else: + continue + keep.append(g) + if keep: + hooks[ev] = keep + elif ev_changed: + del hooks[ev] + if changed and not hooks: + del obj["hooks"] + return changed + + class WiringBase(SisiCase): def setUp(self): super().setUp() @@ -127,7 +158,7 @@ class WiringPropertyTests(WiringBase): if st is not None and st.strip(): orig = json.loads(st) now = json.loads(self.path(".claude/settings.json") and open(self.path(".claude/settings.json"), "rb").read()) - wiring.remove_hooks(now) + remove_hooks(now) def norm(d): # empty hook lists/objects may legitimately disappear in the structural path h = d.get("hooks") diff --git a/tests/test_workers.py b/tests/test_workers.py index 770cd8f..da3bb1d 100644 --- a/tests/test_workers.py +++ b/tests/test_workers.py @@ -88,37 +88,6 @@ class DiscoveryTests(WorkerCase): self.assertFalse(tools["cursor-agent"]["usable"]) -class LedgerImportTests(WorkerCase): - def test_existing_ledger_imported_once_losslessly(self): - src = os.path.join(self.tmp, "orch-log.jsonl") - rows = [ - {"kind": "attempt", "id": "abc123", "ts": 1700000000, "project": "p", "type": "impl", - "difficulty": 2, "worker": "beta-1", "outcome": "accepted", "check": "tests", - "minutes": 3, "tokens": None, "retry_of": None, "note": "keep me", "extra": [1, 2]}, - {"kind": "attempt", "id": "def456", "ts": 1700000100, "project": "p", "type": "impl", - "difficulty": 2, "worker": "beta-1", "outcome": "rejected", "check": "read", - "minutes": 4, "tokens": 9, "retry_of": "abc123", "note": None}, - {"kind": "amend", "id": "abc123", "ts": 1700000200, "note": "later wrong"}, - ] - with open(src, "w") as f: - for row in rows: - f.write(json.dumps(row) + "\n") - before = open(src).read() - r = self.sisi("workers", env=self.env(SISI_LEDGER=src)) - self.assertEqual(r.returncode, 0, r.stderr) - self.assertIn("imported 3 rows", r.stdout) - self.assertEqual(open(src).read(), before, "the original ledger must not be modified") - got = [json.loads(l) for l in open(os.path.join(self.data, "delegations.jsonl"))] - self.assertEqual(len(got), 3) - for want, have in zip(rows, got): - for k, v in want.items(): - self.assertEqual(have.get(k), v, k) - # a second run imports nothing more - self.sisi("workers", env=self.env(SISI_LEDGER=src)) - got2 = [json.loads(l) for l in open(os.path.join(self.data, "delegations.jsonl"))] - self.assertEqual(len(got2), 3) - - class RouteTests(WorkerCase): def test_route_explains_and_skips_contributor_and_logged_out(self): r = self.sisi("route", "--kind", "impl", "--difficulty", "2", "--explain", env=self.env())