Item 4: remove guarded seams and dead code between the merged pieces. done 4 / next 5 (grouped help)

This commit is contained in:
swaits committed 2026-11-23 12:26:42 -07:00
1 parent ed018a364c
commit 6787ef0ae9
23 files changed
+82 -261

No files matched your search

+1 -5
View File
@@ -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"
+10 -14
View File
@@ -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)
-1
View File
@@ -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):
-4
View File
@@ -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)]
+1 -1
View File
@@ -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
-12
View File
@@ -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)
-5
View File
@@ -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()
+1 -1
View File
@@ -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"
-24
View File
@@ -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)
+4 -55
View File
@@ -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 \"<what happened, with the evidence>\" --cause \"<root cause>\" "
"--impact value|correctness|time|cost|attention --disposition promote|record|drop\n"
" promote also needs: --change \"<exact improvement>\" --mechanism policy|orchestration|skill|tool|"
"infrastructure|verification|knowledge|benchmark --expect \"<observable effect>\" --validate \"<how it will be tested>\"\n"
" record also needs: --limits \"<where it applies and where it does not>\"\n"
" drop also needs: --why-not \"<why it is not worth promoting>\"\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])
-1
View File
@@ -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"}
-4
View File
@@ -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] \"<what you want>\"\n"
" sisi learn --withdraw ID --reason \"<why it was recorded by mistake>\"")
-1
View File
@@ -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
+1 -4
View File
@@ -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 ())
-12
View File
@@ -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."""
+1 -1
View File
@@ -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
+1 -31
View File
@@ -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 <personal>/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 = {}
-35
View File
@@ -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: