Merge t3/close-rebuild-seam-gaps: grouped help carries workers note/only; routing adjustments, notes, limits, host-native and with_commit all kept. done / next: fix 1 (rule map)

This commit is contained in:
swaits committed 2026-11-23 13:01:27 -07:00
commit 6cff3a0667
42 files changed
+777 -420

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"
+16 -3
View File
@@ -103,6 +103,11 @@ def missing(profile, c, project, results=None, errors=None, deep_state=None, now
absent = True
else:
absent = False
rk = c.get("risk") if isinstance(c.get("risk"), dict) else {}
if not absent and rk.get("profile") not in C.RISK_PROFILES:
out.append(("a declared risk profile (your own judgement of the change)",
'"risk": {"profile": %s}; `sisi risk` shows the floor' % "|".join(C.RISK_PROFILES)))
errors = [e for e in errors or [] if "risk.profile" not in e and not e.startswith("risk must be")]
if errors:
shown = "; ".join(errors[:3]) + ("; and %d more" % (len(errors) - 3) if len(errors) > 3 else "")
out.append(("a valid contract: %s" % shown, "fix it, then `sisi contract check`"))
@@ -160,16 +165,24 @@ def fit(lines, limit=MAX_LINES):
% (len(flat) - limit + 1)])
def shown_lines(r, evidence_lines, tail_lines):
"""The lines to show for one result: the evidence that identifies the failure first, then the last
lines of its output that the evidence did not already include."""
ev = [ln for ln in str(r.get("evidence") or "").splitlines() if ln.strip()][:evidence_lines]
tail = [ln for ln in str(r.get("tail") or "").splitlines() if ln.strip() and ln not in ev][-tail_lines:]
return ev + tail
def failure_lines(results, per_check=4, checks=4):
"""A short report of the blocking results: id, status, and the last lines of what they printed."""
"""A short report of the blocking results: id, status, the lines that identify each failure, then
the last lines of what it printed."""
from . import verify as V
out = []
bad = V.blocking(results)
for r in bad[:checks]:
head = "- %s [%s%s]" % (r["id"], r["status"], (": " + r["reason"]) if r.get("reason") else "")
out.append(head)
tail = [ln for ln in str(r.get("tail") or "").splitlines() if ln.strip()][-per_check:]
out += [" " + ln[:200] for ln in tail]
out += [" " + ln[:200] for ln in shown_lines(r, per_check, 1)]
if len(bad) > checks:
out.append("- and %d more failing" % (len(bad) - checks))
return out
+57
View File
@@ -37,15 +37,21 @@ def template():
"",
"## Acceptance",
"[How the result will be judged: the check that decides accepted or rejected.]",
"[Every size, speed or brevity requirement is a number with the command that measures it.]",
"[If the worker writes data for another module to read, name that reader and require one end-to-end test that shows the reader's behaviour changes.]",
"[If you ask for a classifier, matcher or heuristic and a labelled set, the labels come from a different worker, or a held-out part is written first.]",
"",
"## Deliverables and report format",
"[What to send back, and in what shape: a short report, what changed, the check run.]",
"[For numbered items: a commit after each, with a one-line \"done / next\" note in the message.]",
"",
"## Files you may change",
"[The files or folders the worker may change; everything else is read-only.]",
"",
"## Verification",
"[The check the worker must run before reporting, and what output to include.]",
"[For an approval gate, trust check or validation step, list the abuse cases the tests must cover: omit the field that triggers the gate, forge the field that marks trust, make the failing-before step fail for an unrelated reason.]",
"[New test modules are run about 30 times, with copies in parallel, before the report.]",
"",
"## Budget and escalation",
"[Time or cost budget; when to stop and escalate instead of guessing.]",
@@ -114,3 +120,54 @@ def missing_required(text):
found = sections(text)
return [title for key, title, _n, _r in PARTS
if key in _REQUIRED and (key not in found or not _filled(found[key]))]
# ---------------------------------------------------------------- advice (never blocks)
_VAGUE = re.compile(r"\b(short|fast|small|brief|concise|quick)\b", re.I)
_GATE = re.compile(r"\b(approv\w*|trust\w*|validat\w*|untrusted)\b", re.I)
_ABUSE = re.compile(r"\b(abuse|misuse)\b", re.I)
_TESTS = re.compile(r"\btests?\b", re.I)
_REPEAT = re.compile(r"\brepeat|\b\d+ times\b|in parallel", re.I)
_FOR_OTHERS = re.compile(r"(for|that) (other|another|downstream) modules? (to|will|that)? ?(read|consume|use)|"
r"(other|another) modules? (reads?|will read|consumes?)", re.I)
_READER = re.compile(r"\b(read by|reader is|reader:|the reader|consumer is|consumer:)\s+[`\w./]+", re.I)
_HEURISTIC = re.compile(r"\b(classifier|matcher|heuristic)\b", re.I)
_LABELS = re.compile(r"\blabell?ed\b|\blabels\b|ground truth", re.I)
_LABELS_INDEPENDENT = re.compile(r"different worker|another worker|other worker|held[- ]?out|blind", re.I)
_NUMBERED = re.compile(r"^\s*(\d+[.)]|item \d+)\s", re.I | re.M)
_COMMIT_PER_ITEM = re.compile(r"commit (after|per|for) each|done ?/ ?next", re.I)
def _written(text):
"""The lines the brief's author wrote: the template's bracketed guidance does not count."""
return [ln for ln in (text or "").splitlines()
if not (ln.strip().startswith("[") and ln.strip().endswith("]"))]
def advice(text):
"""Short pieces of advice about a brief, each with its reason. Advice never blocks a delegation."""
lines = _written(text)
body = "\n".join(lines)
acceptance = sections("\n".join(lines)).get("acceptance", [])
out = []
vague = sorted({m.group(1).lower() for ln in acceptance if not re.search(r"\d", ln) for m in _VAGUE.finditer(ln)})
if vague:
out.append("Acceptance says %s with no number: state each size, speed or brevity limit as a number "
"and the command that measures it." % "/".join(vague))
if _GATE.search(body) and not _ABUSE.search(body):
out.append("It mentions approval, trust or validation but lists no abuse cases: name them (omit the "
"trigger field, forge the trust mark, fail the before-step for an unrelated reason).")
if _TESTS.search(body) and not _REPEAT.search(body):
out.append("It asks for tests but not a repeat run: run new test modules about 30 times, with copies "
"in parallel, before reporting (exposes time and order dependence).")
if _FOR_OTHERS.search(body) and not _READER.search(body):
out.append("The worker writes data for other modules to read, but no reader is named: name it and ask "
"for one end-to-end test showing its behaviour changes.")
if _HEURISTIC.search(body) and _LABELS.search(body) and not _LABELS_INDEPENDENT.search(body):
out.append("It asks for a classifier, matcher or heuristic and a labelled set from the same worker: the "
"labels should come from a different worker, or a held-out part be written first.")
if len(_NUMBERED.findall(body)) >= 2 and not _COMMIT_PER_ITEM.search(body):
out.append("It has numbered items but no commit per item: ask for a commit after each, with a "
"\"done / next\" note, so an interruption loses at most one.")
return out
+29 -120
View File
@@ -1,109 +1,6 @@
"""Command dispatch. Heavy modules are imported lazily so hooks (tick, gate) stay fast."""
import json, os, sys
HELP = """sisi is still improving
A shared rulebook and enforced definitions of done for every AI coding CLI.
sisi contract init [--goal TEXT] start a work unit: create .sisi/contract.json here (refuses while one is open)
sisi contract check validate the contract (vacuous checks are refused)
sisi contract waive [--check ID] "<reason>"
record a deviation: a waived check does not pass; the unit closes as a deviation and the report must say so
sisi contract trust | untrust allow / stop allowing this project's contract to run commands
sisi unit close [--abandon "<reason>"]
archive the unit to .sisi/units/<id>.json with its scorecard; --abandon records why it stopped
sisi unit pause "<what it waits for>"
record a wait; the turn may end with no demands
sisi unit show [ID] | list print the open unit or an archived record; list this project's units
sisi verify [--json] run the selected fast checks (five statuses; nothing unrun passes); exit 0 ok, 1 failure, 2 no contract, 3 untrusted
sisi verify --deep [--background] run the deep (long) checks; --background detaches and returns at once
sisi verify --all | --state run every check in both tiers; print only the deep-check state (with --json)
sisi gate [--tool NAME] end-of-turn hook (reads hook JSON on stdin; NAME selects the tool's hook shape)
sisi tick [--tool NAME] session-start hook
sisi prompt [--tool NAME] prompt-submission hook: prints the matching recipe and lessons for the human's request as added context (silent when nothing strictly matches); `sisi prompt "<request>"` tries it by hand
sisi rule [N|ID] the effective rules and how each is enforced; with N or ID: one rule in full (reasons, history, lessons behind it, how it is enforced)
sisi watch [--before|--after] before/after shell-tool hook: measures whether the command changed the project
sisi install [--dry-run] | uninstall | doctor
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|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 | --new] [--target ID]
record one finding; promote also needs --change, --mechanism,
--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] 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-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 list
sisi oracle print what the human wants: the standing principles from
`sisi learn`, live at once (project-scoped ones only in their project)
sisi status [--json] [--learning] recent units with their scorecards, then trends by project, risk profile, model and policy version (median and p95; no single score)
sisi verifiers [WORDS] [--lang L] [--kind K] [--rung N] [--section S] [--installed] [--json]
list ways to know work is correct, by section
sisi verifiers show ID [--trace] one entry in full, and whether its tool is installed here; --trace also prints where each folded lesson lives in it
sisi verifiers for "<claim>" best-matching verifiers for a claim or piece of work
sisi verifiers doctor | lint which tools are installed; validate the library
sisi done [ID] [--trace] recipes: which checks make a kind of work done; --trace also prints where each folded lesson lives in the recipe
sisi done for "<work>" best-matching recipe
sisi workers [--refresh] the agent tools and models found here, what is usable now and why not, allowance and price where known, delegations waiting for a judgement, and the judged record as three tables
sisi workers fact W --price N|--score N --source S record a price (per million tokens) or benchmark standing (0-100), with its source and date
sisi workers avoid|prefer PATTERN --why TEXT your own routing constraints, honoured by `sisi route`
sisi workers only PROVIDER PATTERN... --why TEXT | --remove make only the matching models of that provider routable
sisi workers note PATTERN "TEXT" --why SOURCE | --remove a standing fact about workers matching PATTERN, shown with route results
sisi workers down W --reason limit|auth|missing|error [--until DATE] | up W mark a worker unavailable / available again
sisi workers import FILE merge another ledger file into the delegation ledger (row counts printed; safe to repeat)
sisi route --kind K --difficulty N [--review-of W] [--explain]
the most affordable usable worker for this kind and difficulty, and the mechanism to start it with (host subagents, host cross-provider delegation, or sisi delegate); --explain says why
sisi delegate brief | check FILE | guide the delegation-contract template (eight parts); which parts a brief lacks; the orchestration playbook
sisi delegate --kind K --difficulty N --brief FILE [--worker W] [--review-of W] [--cwd DIR]
run one brief on the chosen worker unattended; prints only its final report, the transcript path, and the judge command; a brief without outcome, acceptance or files it may change is refused
sisi delegate judge ID --outcome accepted|rejected --check none|diffstat|tests|read|review [--minutes N]
record your judgement of a delegation run, so the next choice learns from it; judge work run any other way with --worker W --type K --difficulty N instead of ID
sisi delegate amend ID | recent [-n N] [--project P] mark a judged delegation that later proved wrong; list recent judgements to find an id
sisi eval list|add|run|compare|shadow|judge|status|import
the evaluation harness: benchmark cases from real work, isolated
replay, policy comparison and independent judging (see docs/evaluation.md);
`sisi eval` alone prints status; run without --tasks replays check cases only
sisi version | --version print the product version (the VERSION file in the product folder)
sisi help this text
Three places: the product (this clone, never written at run time), your personal data
(~/.local/share/sisi, its own git repository), and scratch (~/.local/state/sisi).
Environment: SISI_HOME (stands in for the home directory), SISI_DATA (personal data folder),
SISI_STATE (scratch dir), SISI_LIB (where stable releases live, default ~/.local/lib/sisi), SISI_TOOL (name recorded with results), SISI_VERIFIERS and SISI_DONE
(library directories, default verifiers/ and done/ in the product).
"""
def _pop_opt(args, name):
"""Remove `name VALUE` from args, return value or None."""
@@ -145,7 +42,7 @@ def cmd_contract(args):
except Exception as e:
store.log_error("contract-init-archive", e)
os.makedirs(os.path.dirname(p), exist_ok=True)
skel = C.skeleton(goal)
skel = C.skeleton(goal, project)
from . import unit as _U
skel["id"] = _U.fresh_id(skel["id"], project)
skel["base_head"] = gitutil.head(project)
@@ -287,12 +184,29 @@ def cmd_personal(cmd, args):
return 64
def cmd_help(args):
"""`sisi help` (four groups, one line per command) or `sisi help COMMAND` (that command in full)."""
from . import helptext
if not args:
print(helptext.short(), end="")
return 0
text = helptext.long(args[0])
if text is None:
print("sisi: no command %r (try `sisi help`)" % args[0], file=sys.stderr)
return 64
print(text, end="" if text.endswith("\n") else "\n")
return 0
def main(argv):
args = list(argv)
t = _pop_opt(args, "--tool")
if t:
os.environ["SISI_TOOL"] = t
cmd = args.pop(0) if args else "help"
if args[:1] in (["--help"], ["-h"]) and cmd not in ("help", "-h", "--help"):
args = [cmd]
cmd = "help"
if cmd == "gate":
if t and t != "claude-code":
from . import hookio
@@ -334,8 +248,7 @@ def main(argv):
return 1
return 0
if cmd in ("help", "-h", "--help"):
print(HELP, end="")
return 0
return cmd_help(args)
if cmd == "contract":
return cmd_contract(args)
if cmd == "verify":
@@ -411,17 +324,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)
+17 -14
View File
@@ -39,19 +39,24 @@ def is_unedited_skeleton(c):
REQ_KINDS = ("explicit", "implied", "contextual", "anticipated", "experiential")
REQ_DECISIONS = ("now", "architect", "defer", "ignore")
RISK_PROFILES = ("trivial", "isolated", "logic", "integration", "data", "critical", "release")
RISK_HINT = ("one of %s, your own judgement of the change; `sisi risk` shows the floor worked out from paths"
% ", ".join(RISK_PROFILES))
UNIT_STATUSES = ("open", "paused", "closed")
def skeleton(goal=None, cwd=None):
name = re.sub(r"[^a-z0-9]+", "-", os.path.basename(os.path.abspath(cwd or os.getcwd())).lower()).strip("-")
from . import store as _store
"""A new contract. `risk.profile` starts at the floor of the current change; the agent judges it from there."""
cwd = cwd or os.getcwd()
name = re.sub(r"[^a-z0-9]+", "-", os.path.basename(os.path.abspath(cwd)).lower()).strip("-")
from . import store as _store, risk as _risk
floor = _risk.floor_for_working_tree(cwd)[0]
return {
"id": name or "work",
"parent": None,
"goal": goal or "TODO: one sentence describing the outcome",
"scope": {"in": [], "out": []},
"requirements": [],
"risk": {},
"risk": {"profile": floor},
"checks": [{
"id": "c1",
"claim": "PLACEHOLDER (fast tier, runs at the end of every turn, 60 s at most): replace with what this check shows to be true",
@@ -185,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):
@@ -337,16 +341,15 @@ def _validate_new_top(c, ids, errs):
errs.append("%s: check %r is not a check or invariant id" % (w, r["check"]))
if "added" in r and not _str(r["added"]):
errs.append(w + ": added must be a non-empty string")
if "risk" in c:
rk = c["risk"]
if not isinstance(rk, dict):
errs.append("risk must be an object")
else:
if "profile" in rk and rk["profile"] not in RISK_PROFILES:
errs.append("risk.profile must be one of %s" % ", ".join(RISK_PROFILES))
for k in ("why", "blast_radius", "rollback"):
if k in rk and not _str(rk[k]):
errs.append("risk.%s must be a non-empty string" % k)
rk = c.get("risk")
if not isinstance(rk, dict):
errs.append("risk must be an object that states its profile: " + RISK_HINT)
else:
if rk.get("profile") not in RISK_PROFILES:
errs.append("risk.profile is required: " + RISK_HINT)
for k in ("why", "blast_radius", "rollback"):
if k in rk and not _str(rk[k]):
errs.append("risk.%s must be a non-empty string" % k)
if "deferred" in c:
df = c["deferred"]
if not isinstance(df, list):
+2 -6
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)]
@@ -183,8 +179,8 @@ def enforced_results(c, project, deadline=None, default_timeout=60):
to = float(e.get("timeout_s") or default_timeout)
if deadline is not None:
to = min(to, deadline - time.time())
st, dur, tail = V.run_cmd(e["cmd"], project, to, e.get("expect") or {"exit": 0})
out.append(dict(base, status=st, duration_s=round(dur, 3), tail=tail,
st, dur, tail, ev = V.run_cmd(e["cmd"], project, to, e.get("expect") or {"exit": 0})
out.append(dict(base, status=st, duration_s=round(dur, 3), tail=tail, evidence=ev,
claim="enforced learning %s: %s" % (lid, e["cmd"])))
return out
+2 -1
View File
@@ -90,7 +90,8 @@ def release(project):
def save_state(project, contract_id, fp, results, deep_ids):
items = [{"id": r["id"], "status": r["status"], "tail": (r.get("tail") or "")[-1500:]}
items = [{"id": r["id"], "status": r["status"], "tail": (r.get("tail") or "")[-1500:],
"evidence": r.get("evidence") or ""}
for r in results if r.get("tier") == "deep"]
st = {"contract": contract_id, "fp": fp, "epoch": time.time(), "ids": sorted(deep_ids),
"ok": all(i["status"] in ("passed", "skipped", "not-applicable") for i in items), "items": items}
+2 -1
View File
@@ -374,7 +374,8 @@ def _decide(payload):
store.log_error("gate-deep", e)
failing = V.blocking(results)
if ds and ds["state"] == "failed" and ds["fresh"]:
failing = failing + [{"id": i["id"], "status": "failed", "reason": "deep", "tail": i["tail"]} for i in ds["failed"]]
failing = failing + [{"id": i["id"], "status": "failed", "reason": "deep", "tail": i["tail"],
"evidence": i.get("evidence") or ""} for i in ds["failed"]]
miss = assure.missing(profile, c, project, results, errs, ds["state"] if ds else None)
if miss or failing:
+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
+123
View File
@@ -0,0 +1,123 @@
"""Help text for `sisi help`: four groups of commands, one line each, and the long text per command.
`sisi help` must fit 60 lines of 110 characters (tests/test_public.py checks it); the long explanation of a
command is printed by `sisi help COMMAND` and `sisi COMMAND --help`.
"""
LONG = {
'contract': ' sisi contract init [--goal TEXT] start a work unit: create .sisi/contract.json here (refuses while one is open)\n sisi contract check validate the contract (vacuous checks are refused)\n sisi contract waive [--check ID] "<reason>"\n record a deviation: a waived check does not pass; the unit closes as a deviation and the report must say so\n sisi contract trust | untrust allow / stop allowing this project\'s contract to run commands',
'unit': ' sisi unit close [--abandon "<reason>"]\n archive the unit to .sisi/units/<id>.json with its scorecard; --abandon records why it stopped\n sisi unit pause "<what it waits for>"\n record a wait; the turn may end with no demands\n sisi unit show [ID] | list print the open unit or an archived record; list this project\'s units',
'verify': ' sisi verify [--json] run the selected fast checks (five statuses; nothing unrun passes); exit 0 ok, 1 failure, 2 no contract, 3 untrusted\n sisi verify --deep [--background] run the deep (long) checks; --background detaches and returns at once\n sisi verify --all | --state run every check in both tiers; print only the deep-check state (with --json)',
'gate': " sisi gate [--tool NAME] end-of-turn hook (reads hook JSON on stdin; NAME selects the tool's hook shape)",
'tick': ' sisi tick [--tool NAME] session-start hook',
'prompt': ' sisi prompt [--tool NAME] prompt-submission hook: prints the matching recipe and lessons for the human\'s request as added context (silent when nothing strictly matches); `sisi prompt "<request>"` tries it by hand',
'rule': ' sisi rule [N|ID] the effective rules and how each is enforced; with N or ID: one rule in full (reasons, history, lessons behind it, how it is enforced)',
'watch': ' sisi watch [--before|--after] before/after shell-tool hook: measures whether the command changed the project',
'install': ' sisi install [--dry-run] | uninstall | doctor\n wire sisi into the tools (by reference), undo, inspect; --dry-run only prints what would change',
'release': " sisi release [--deep] run the source's checks, then make the stable copy the tools run (see docs/developing.md)",
'rollback': ' sisi rollback switch the stable copy back to the previous release',
'promote': ' sisi promote [ID|L-NNNN] [--apply] | --export [PATH]\n no ID: list items not yet in the product (learnings that change\n sisi itself, or earned organization scope); an ID scrubs a\n personal overlay item into the source folder and drops the\n personal copy once the product contains it (dry run unless\n --apply); L-NNNN promotes the rule or recipe a learning was\n folded into, from the clone; --export writes a contribution file\n (universal text only; nothing is sent anywhere)',
'update': ' sisi update fast-forward the product clone, then back up, migrate and rebuild personal data',
'export': ' sisi export [PATH] | import PATH one tar.gz of personal data, results and session records; restore it',
'overlay': ' sisi overlay list|diff|add-rule|replace-rule|disable-rule|enable-rule|add-verifier|...|revert COMMIT\n learned changes to rules, verifiers and recipes; each one a commit in your personal repo',
'retro': " sisi retro print the unit's record and what stands out in it\n sisi retro --finding F --cause C --impact value|correctness|time|cost|attention --disposition promote|record|drop [--same-as ID | --new] [--target ID]\n record one finding; promote also needs --change, --mechanism,\n --expect and --validate; record needs --limits; drop needs --why-not;\n a match in scope is printed and attached as a recurrence (--new records\n a learning of its own); --target names the rule or recipe it concerns\n sisi retro --adopt ID a parent adopts a subagent's candidate learning, by id",
'lessons': ' sisi lessons [--json] | show ID the learning records and their statuses',
'cycle': ' sisi cycle [due|apply FILE|check FILE|revert [ID]|help]\n turn proposed learnings into mechanisms (no scheduler:\n due-ness is a counter); apply validates and replays before\n promoting; help prints the cycle file format',
'approve': " sisi approve [ID --yes|--no] list, in full, the consequential changes waiting for the owner; decide one\n (in a terminal: an agent's --yes without one is refused)",
'learn': ' sisi learn [--scope user|project] TEXT\n record an owner statement; it takes effect at once and\n `sisi oracle` prints it. Scope for other learnings is\n earned by evidence, never claimed\n sisi learn --withdraw ID --reason WHY\n take a statement recorded by mistake out of delivery (kept in history)',
'risk': ' sisi risk [--json] risk floor for the working-tree change, with reasons and\n what that profile requires',
'handover': " sisi handover [--all] | done ID --where PATH [--quote FRAGMENT]\n project-scope learnings waiting to be filed in this project's own docs or\n work list; done confirms one is filed (the named file must contain\n its key text) and removes it from the list",
'oracle': ' sisi oracle print what the human wants: the standing principles from\n `sisi learn`, live at once (project-scoped ones only in their project)',
'status': ' sisi status [--json] [--learning] recent units with their scorecards, then trends by project, risk profile, model and policy version (median and p95; no single score)',
'verifiers': ' sisi verifiers [WORDS] [--lang L] [--kind K] [--rung N] [--section S] [--installed] [--json]\n list ways to know work is correct, by section\n sisi verifiers show ID [--trace] one entry in full, and whether its tool is installed here; --trace also prints where each folded lesson lives in it\n sisi verifiers for "<claim>" best-matching verifiers for a claim or piece of work\n sisi verifiers doctor | lint which tools are installed; validate the library',
'done': ' sisi done [ID] [--trace] recipes: which checks make a kind of work done; --trace also prints where each folded lesson lives in the recipe\n sisi done for "<work>" best-matching recipe',
'workers': ' sisi workers [--refresh] the agent tools and models found here, what is usable now and why not, allowance and price where known, delegations waiting for a judgement, and the judged record as three tables\n sisi workers fact W --price N|--score N --source S record a price (per million tokens) or benchmark standing (0-100), with its source and date\n sisi workers avoid|prefer PATTERN --why TEXT your own routing constraints, honoured by `sisi route`\n sisi workers only PROVIDER PATTERN... --why TEXT | --remove make only the matching models of that provider routable\n sisi workers note PATTERN \"TEXT\" --why SOURCE | --remove a standing fact about workers matching PATTERN, shown with route results\n sisi workers down W --reason limit|auth|missing|error [--until DATE] | up W mark a worker unavailable / available again\n sisi workers import FILE merge another ledger file into the delegation ledger (row counts printed; safe to repeat)',
'route': ' sisi route --kind K --difficulty N [--review-of W] [--explain]\n the most affordable usable worker for this kind and difficulty, and the mechanism to start it with (host subagents, host cross-provider delegation, or sisi delegate); --explain says why',
'delegate': ' sisi delegate brief | check FILE | guide the delegation-contract template (eight parts); which parts a brief lacks; the orchestration playbook\n sisi delegate --kind K --difficulty N --brief FILE [--worker W] [--review-of W] [--cwd DIR]\n run one brief on the chosen worker unattended; prints only its final report, the transcript path, and the judge command; a brief without outcome, acceptance or files it may change is refused\n sisi delegate judge ID --outcome accepted|rejected --check none|diffstat|tests|read|review [--minutes N]\n record your judgement of a delegation run, so the next choice learns from it; judge work run any other way with --worker W --type K --difficulty N instead of ID\n sisi delegate amend ID | recent [-n N] [--project P] mark a judged delegation that later proved wrong; list recent judgements to find an id',
'eval': ' sisi eval list|add|run|compare|shadow|judge|status|import\n the evaluation harness: benchmark cases from real work, isolated\n replay, policy comparison and independent judging (see docs/evaluation.md);\n `sisi eval` alone prints status; run without --tasks replays check cases only',
'version': ' sisi version | --version print the product version (the VERSION file in the product folder)',
'help': ' sisi help this text',
}
ENV = (
"Three places: the product (this clone, read-only at run time), your personal data (~/.local/share/sisi,\n"
"its own git repository), and scratch (~/.local/state/sisi). Environment: SISI_HOME, SISI_DATA, SISI_STATE,\n"
"SISI_LIB, SISI_TOOL, SISI_VERIFIERS, SISI_DONE (what each means: `sisi help help`).\n")
# (heading, [(command names, usage shown, one line)]) in reading order. Every command the dispatcher
# accepts is named in exactly one row.
GROUPS = (
("For the person", (
(("install", "uninstall", "doctor"), "install [--dry-run] | uninstall | doctor", "wire sisi into your tools, undo it, check it"),
(("update",), "update", "update the product; back up, migrate, rebuild your data"),
(("status",), "status [--json] [--learning]", "recent units with scorecards, then trends"),
(("rollback",), "rollback", "switch the stable copy back to the previous release"),
(("approve",), "approve [ID --yes|--no]", "list what waits for you; decide one (terminal only)"),
(("oracle",), "oracle", "what you want: the principles recorded by `sisi learn`"),
(("export", "import"), "export [PATH] | import PATH", "one tar.gz of personal data and results; restore it"),
)),
("For the agent at work", (
(("contract",), "contract init|check|waive|trust|untrust", "start, validate and bend the unit's contract"),
(("unit",), "unit close|pause|show|list", "close a unit with its scorecard, record a wait, look back"),
(("risk",), "risk [--json]", "the risk floor of the working-tree change; what it requires"),
(("verify",), "verify [--deep|--all|--state] [--json]", "run the contract's checks; nothing unrun passes"),
(("retro",), "retro [--finding F ...|--adopt ID]", "the unit's record; record a finding, with its cause and fix"),
(("learn",), "learn [--scope S] TEXT | --withdraw ID", "record what the owner said; take a mistaken one back"),
(("route",), "route --kind K --difficulty N [--explain]", "the most affordable usable worker for a task"),
(("delegate",), "delegate brief|check|guide|judge|amend", "write, check, run and judge a brief for a worker"),
(("workers",), "workers [fact|avoid|prefer|only|note|down|up]", "workers found here, what each costs, the judged record"),
(("verifiers",), "verifiers show|for|doctor|lint|WORDS", "ways to know work is correct"),
(("done",), "done [ID|for \"<work>\"]", "the recipe saying what makes a kind of work done"),
(("rule",), "rule [N|ID]", "the rules and how each is enforced"),
(("handover",), "handover [--all] | done ID --where PATH", "learnings waiting to be filed in this project's docs"),
(("lessons",), "lessons [--json] | show ID", "the learning records and their statuses"),
(("eval",), "eval list|add|run|compare|shadow|status", "the evaluation harness: cases, replay, comparison"),
)),
("Hooks (the tools call these)", (
(("tick",), "tick [--tool NAME]", "session start"),
(("prompt",), "prompt [--tool NAME]", "each request: the matching recipe and lessons as context"),
(("gate",), "gate [--tool NAME]", "end of turn: sends the agent back if the work is not ready"),
(("watch",), "watch [--before|--after]", "around shell commands: did the project change?"),
)),
("Maintaining sisi", (
(("release",), "release [--deep]", "check the source, then make the stable copy the tools run"),
(("promote",), "promote [ID|L-NNNN] [--apply] | --export", "move a personal item or learning into the product"),
(("cycle",), "cycle [due|apply|check|revert|help]", "turn proposed learnings into mechanisms"),
(("overlay",), "overlay list|diff|add-rule|...|revert", "your learned changes to rules, verifiers, recipes"),
(("harvest", "tasks", "escapes", "checks"), "harvest | tasks | escapes | checks", "the data layer behind `sisi eval`"),
(("version",), "version", "print the product version"),
(("help",), "help [COMMAND]", "this text, or one command in full"),
)),
)
LONG["help"] = (
" sisi help [COMMAND] this text, or one command in full (also `sisi COMMAND --help`)\n"
" Environment: SISI_HOME (stands in for the home directory), SISI_DATA (personal data folder),\n"
" SISI_STATE (scratch dir), SISI_LIB (where stable releases live, default ~/.local/lib/sisi),\n"
" SISI_TOOL (name recorded with results), SISI_VERIFIERS and SISI_DONE (library directories,\n"
" default verifiers/ and done/ in the product).\n")
def names():
"""Every command named in GROUPS."""
return [n for _h, rows in GROUPS for row in rows for n in row[0]]
def short():
out = ["sisi: a shared rulebook and enforced definitions of done for every AI coding CLI.",
"`sisi help COMMAND` or `sisi COMMAND --help` explains one command in full."]
for heading, rows in GROUPS:
out += ["", heading]
out += [" sisi %-41s %s" % (usage, text) for _names, usage, text in rows]
out += ["", ENV.rstrip("\n")]
return "\n".join(out) + "\n"
def long(cmd):
"""The full text for one command, or None when `cmd` is not a command."""
for _h, rows in GROUPS:
for names_, usage, text in rows:
if cmd in names_:
return LONG.get(cmd) or " sisi %s %s\n" % (usage, text)
return None
-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 -6
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>\"")
@@ -69,6 +65,8 @@ def cmd_learn(argv):
os.getcwd(), L.unit_id(), change=statement, mechanism="knowledge",
scope=scope, expect="the agent acts on this statement",
owner_statement=True, entered_via="learn", origin=origin)
print("recorded owner statement %s (%s; printed by `sisi oracle`; withdraw a mistake with "
"`sisi learn --withdraw %s --reason ...`)" % (rec["id"], origin, rec["id"]))
print("recorded owner statement %s (%s)" % (rec["id"], origin))
print(" stored: %s" % rec["observation"]["evidence"])
print(" scope: %s; it takes effect at once and `sisi oracle` prints it" % rec["proposed"]["scope"])
print(" to take it back: sisi learn --withdraw %s --reason \"<why it was recorded by mistake>\"" % rec["id"])
return 0
-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 ())
+1 -13
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."""
@@ -412,7 +400,7 @@ def latest_results(c, rows):
ever_failed.add(cid)
latest[cid] = {"item": r["item"], "id": cid, "status": st, "reason": r.get("reason"),
"duration_s": r.get("duration_s", 0.0), "mandatory": r.get("mandatory", True),
"tier": r.get("tier", "fast"), "ts": r.get("ts")}
"tier": r.get("tier", "fast"), "ts": r.get("ts"), "evidence": r.get("evidence") or ""}
for x in (c.get("checks") or []) + (c.get("invariants") or []):
if isinstance(x, dict) and x.get("id") and x["id"] not in latest:
latest[x["id"]] = {"item": "check", "id": x["id"], "status": "not-run",
+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
+68 -16
View File
@@ -6,7 +6,7 @@ change selection is skipped (not affected by this change), or not-applicable whe
file it watches exists; an identical-inputs pass is skipped (reused: passed at <time>).
Nothing that did not run is ever reported as passed, on any path.
"""
import hashlib, json, os, signal, subprocess, time
import hashlib, json, os, re, signal, subprocess, time
from fnmatch import fnmatch
from pathlib import PurePosixPath
@@ -21,16 +21,65 @@ def _tail(s):
return s[-TAIL:] if len(s) > TAIL else s
EVIDENCE_LINES = 60 # at most this many lines of evidence per failed check
EVIDENCE_CHARS = 3000
EVIDENCE_LINE = 300 # and each line is cut here
EDGE = 30 # unknown output: this many lines from the start and from the end
# What names a failure in each known runner's output. A line that matches is kept, with the few lines
# after it that carry the assertion or the panic message.
_RUNNERS = (
("unittest", re.compile(r"^(FAIL|ERROR): \S+ \(.+\)"), re.compile(r"^\s*(\w+\.)*\w*(Error|Exception|Failure)\b.*|^\s+self\.assert\w+\(.*")),
("pytest", re.compile(r"^(FAILED|ERROR) \S+|^_{3,} .+ _{3,}$"), re.compile(r"^E\s+.*|^\S+:\d+: \w+")),
("cargo test", re.compile(r"^test \S+ \.\.\. FAILED$|^---- \S+ stdout ----$"), re.compile(r"^thread '.*' panicked at.*|^\s+(left|right):.*|^assertion .*")),
("go test", re.compile(r"^\s*--- FAIL: \S+"), re.compile(r"^\s+\S+\.go:\d+:.*|^\s+(expected|actual|got|want).*|^panic: .*")),
("jest", re.compile(r"^\s*● .+ › .+|^FAIL \S+"), re.compile(r"^\s*(expect\(|Expected|Received).*|^\s*(\w*Error):? .*")),
)
def _clip(lines):
out, chars = [], 0
for ln in lines:
ln = ln.rstrip()[:EVIDENCE_LINE]
chars += len(ln) + 1
if len(out) >= EVIDENCE_LINES or chars > EVIDENCE_CHARS:
break
out.append(ln)
return out
def evidence(text):
"""The lines that identify a failure, scrubbed of secrets and bounded in size. For output of a known
test runner (unittest, pytest, cargo test, go test, jest): each failing test's name line and the
assertion lines after it. Otherwise the first and the last 30 lines. A runner prints its summary last,
so the tail alone loses the failing test; these lines are what the agent needs first."""
lines = [ln for ln in str(text or "").splitlines() if ln.strip()]
picked = []
for _name, head, detail in _RUNNERS:
if not any(head.match(ln) for ln in lines):
continue
for i, ln in enumerate(lines):
if head.match(ln):
picked.append(ln)
picked += [d for d in lines[i + 1:i + 40] if detail.match(d) and not head.match(d)][:3]
break
if not picked:
picked = lines if len(lines) <= 2 * EDGE else lines[:EDGE] + ["... (%d lines not shown)" % (len(lines) - 2 * EDGE)] + lines[-EDGE:]
from . import learning
return "\n".join(learning.scrub_secrets(ln) for ln in _clip(dict.fromkeys(picked)))
def run_cmd(cmd, cwd, timeout, expect):
"""Return (status, duration, tail). status: passed/failed/not-run (a timeout never ran to a verdict)."""
"""Return (status, duration, tail, evidence). status: passed/failed/not-run (a timeout never ran to a
verdict). `evidence` is empty unless the check failed or timed out."""
t0 = time.time()
if timeout <= 0:
return "not-run", 0.0, "not run: time budget exhausted"
return "not-run", 0.0, "not run: time budget exhausted", ""
try:
p = subprocess.Popen(cmd, shell=True, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
stdin=subprocess.DEVNULL, start_new_session=True)
except OSError as e:
return "failed", 0.0, "could not start: %s" % e
return "failed", 0.0, "could not start: %s" % e, "could not start: %s" % e
try:
out, err = p.communicate(timeout=timeout)
except subprocess.TimeoutExpired:
@@ -39,20 +88,21 @@ def run_cmd(cmd, cwd, timeout, expect):
except OSError:
pass
try:
p.communicate(timeout=5)
out, err = p.communicate(timeout=5)
except Exception:
pass
return "not-run", time.time() - t0, "timed out after %gs" % timeout
out = err = b""
seen = (out or b"").decode("utf-8", "replace") + "\n" + (err or b"").decode("utf-8", "replace")
return "not-run", time.time() - t0, "timed out after %gs" % timeout, evidence(seen)
dur = time.time() - t0
o, e = out.decode("utf-8", "replace"), err.decode("utf-8", "replace")
tail = _tail(o + ("\n" if o and e else "") + e)
want = expect.get("exit", 0)
if p.returncode != want:
return "failed", dur, "exit %d, expected %d\n%s" % (p.returncode, want, tail)
return "failed", dur, "exit %d, expected %d\n%s" % (p.returncode, want, tail), evidence(o + "\n" + e)
sc = expect.get("stdout_contains")
if sc is not None and sc not in o:
return "failed", dur, "stdout does not contain %r\n%s" % (sc, tail)
return "passed", dur, tail
return "failed", dur, "stdout does not contain %r\n%s" % (sc, tail), evidence(o + "\n" + e)
return "passed", dur, tail, ""
def tree_fp(project, contract_path):
@@ -200,16 +250,16 @@ def _run_item(item, x, tier, project, deadline, default_timeout):
"tier": tier, "mandatory": x.get("mandatory", True), "independent": bool(x.get("independent", False)),
"covers": x.get("covers"), "reason": None, "saved_s": 0.0}
if x.get("rung") in (5, 6):
r.update(status="not-run", reason="needs human", duration_s=0.0, tail="")
r.update(status="not-run", reason="needs human", duration_s=0.0, tail="", evidence="")
else:
to = float(x.get("timeout_s", default_timeout))
if deadline is not None:
to = min(to, deadline - time.time())
st, dur, tail = run_cmd(x["cmd"], project, to, x.get("expect", {"exit": 0}))
st, dur, tail, ev = run_cmd(x["cmd"], project, to, x.get("expect", {"exit": 0}))
reason = None
if st == "not-run":
reason = "timed out" if tail.startswith("timed out") else tail.removeprefix("not run: ")
r.update(status=st, reason=reason, duration_s=round(dur, 3), tail=tail)
r.update(status=st, reason=reason, duration_s=round(dur, 3), tail=tail, evidence=ev)
return r
@@ -217,7 +267,7 @@ def _not_run_result(base_item, x, tier, status, reason, saved=0.0):
return {"item": base_item, "id": x["id"], "kind": x.get("kind"), "rung": x.get("rung"),
"claim": x.get("claim"), "tier": tier, "mandatory": x.get("mandatory", True),
"independent": bool(x.get("independent", False)), "covers": x.get("covers"),
"status": status, "reason": reason, "duration_s": 0.0, "tail": "", "saved_s": round(saved, 3)}
"status": status, "reason": reason, "duration_s": 0.0, "tail": "", "evidence": "", "saved_s": round(saved, 3)}
def run(c, project, deadline=None, default_timeout=60, tiers=("fast",), changed=None, reuse=True,
@@ -326,7 +376,7 @@ def record(c, project, results, fp=None):
"seen_failing": bool(r.get("seen_failing")), "mandatory": r.get("mandatory", True),
"independent": bool(r.get("independent", False)), "covers": r.get("covers"),
"tool": store.tool(), "session": store.session_id(), "run": run_id,
"tier": r.get("tier", "fast"), "fp": fp})
"tier": r.get("tier", "fast"), "fp": fp, "evidence": r.get("evidence") or ""})
return run_id
@@ -340,13 +390,15 @@ def format_table(results):
def failure_report(results, limit=4000):
"""What failed and why: the lines that identify each failure first, then the last lines of the output."""
from . import assure
parts = []
bad = {id(r) for r in blocking(results)} | {id(r) for r in results if r["status"] == "failed"}
for r in results:
if id(r) in bad:
label = r["status"] + ((": " + r["reason"]) if r.get("reason") else "")
parts.append("- %s %s [%s]: %s\n%s" % (r["item"], r["id"], label, r.get("claim") or "",
"\n".join(" " + l for l in (r["tail"] or "").splitlines()[-15:])))
"\n".join(" " + l for l in assure.shown_lines(r, 20, 5))))
s = "\n".join(parts)
return s if len(s) <= limit else s[:limit] + "\n... (truncated)"
+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 = {}
+29 -43
View File
@@ -474,36 +474,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")}
@@ -762,6 +732,21 @@ def with_commit(fn, args, label):
pdata.commit("sisi %s%s: worker data changed" % (label, (" " + sub) if sub else ""), list(DATA_FILES))
def effective_prefs(kind, difficulty, project):
"""The user's avoid/prefer patterns plus the routing adjustments a learning cycle wrote that apply in
this project for this kind (and difficulty, when the adjustment names one). A learned entry carries
its learning id as its reason, so `sisi route --explain` shows where it came from."""
from . import cycle
prefs = load_prefs()
for a in cycle.routing_adjustments(project):
if a.get("kind") != kind or a.get("difficulty") not in (None, difficulty):
continue
for key in ("avoid", "prefer"):
if a.get(key):
prefs[key].append({"pattern": str(a[key]), "why": "learning %s" % a.get("learning")})
return prefs
def _fact_dates():
dates = []
prices = load_prices()
@@ -1102,7 +1087,7 @@ def run_delegation(candidates, kind, difficulty, prompt, cwd, explicit=None, rev
timeout = DEFAULT_RUN_TIMEOUT_S
tried = []
cand = explicit
prefs = load_prefs()
prefs = effective_prefs(kind, difficulty, cwd)
if cand is not None and cand.get("host_native"):
notes.append("sisi: %s is a host-native worker; start it with the host's own subagent tool "
"(`sisi delegate` runs only command-line tools)" % cand["worker"])
@@ -1110,6 +1095,7 @@ def run_delegation(candidates, kind, difficulty, prompt, cwd, explicit=None, rev
candidates = [c for c in apply_limits(candidates, prefs)[0] if not c.get("host_native")]
while True:
if cand is None:
prefs = effective_prefs(kind, difficulty, cwd)
result = routing.choose(candidates, read_records(), read_availability(), kind, difficulty,
review_of=review_of, now=time.time(), exclude=tried,
avoid=prefs["avoid"], prefer=prefs["prefer"])
@@ -1333,7 +1319,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()
@@ -1377,9 +1362,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 "
@@ -1420,7 +1402,6 @@ def _down_lines(down, limit=3):
def _route_setup(args):
ensure_imported()
kind = _opt(args, "--kind")
difficulty = _opt(args, "--difficulty")
if not kind or difficulty is None:
@@ -1442,7 +1423,7 @@ def cmd_route(args=()):
kind, difficulty = setup
records = read_records()
candidates, cold, excluded = routable_candidates(build_candidates(), records)
prefs = load_prefs()
prefs = effective_prefs(kind, difficulty, os.getcwd())
everyone = candidates
candidates, limited = apply_limits(candidates, prefs)
result = routing.choose(candidates, records, read_availability(), kind, difficulty,
@@ -1736,12 +1717,17 @@ def _cmd_brief_check(args):
missing = brief_contract.missing_parts(text)
if not missing:
print("brief ok: all %d parts present" % len(brief_contract.PARTS))
return 0
print("brief lacks:")
for title in missing:
print(" - %s" % title)
print("`sisi delegate brief` prints the template.")
return 1
else:
print("brief lacks:")
for title in missing:
print(" - %s" % title)
print("`sisi delegate brief` prints the template.")
advice = brief_contract.advice(text)
if advice:
print("advice (does not block):")
for line in advice:
print(" - %s" % line)
return 1 if missing else 0
def _cmd_down(args):