diff --git a/docs/learning.md b/docs/learning.md index 0063e3e..f49a58c 100644 --- a/docs/learning.md +++ b/docs/learning.md @@ -171,7 +171,6 @@ 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/done/feature.md b/done/feature.md index 9fd2564..f54525d 100644 --- a/done/feature.md +++ b/done/feature.md @@ -11,6 +11,8 @@ applies_to: A new capability in a product that already exists and already has us - Each requirement has an acceptance check, and the checks for the core logic are strong (property, differential or fuzz checks where the input space is broad). - Empty, large, invalid and repeated use of the new capability behave sensibly, and existing data, settings and workflows still work with it. - The capability is discoverable and usable in the product's own terms (labels, help, errors), with loading, empty and error states where it has a surface. +- The first usable increment is named, the work is ordered to reach it early, and every status update gives its estimated time, labelled as an estimate. +- Where the design depends on a heuristic, classifier or matcher being right most of the time, a throwaway version was first scored on labels a different worker wrote, and the measured ceiling and what stands behind the heuristic are in the design. ## Checks - Requirements: `requirement-to-check-map` (completeness), `acceptance-examples` (intent), rung 3; every requirement maps to a check or a recorded deferral. @@ -18,6 +20,7 @@ applies_to: A new capability in a product that already exists and already has us - Nothing else broke: `baseline-before-change`, `characterization-tests` (regression), rung 3; invariants from before the first edit. - Real surface: `e2e-playwright` (real-world) for a web capability, `cli-transcript-tests` for a command, rung 3. - Hostile and odd input: `hostile-input-from-schema` (many-inputs), rung 2, for any new parser, import or boundary. +- Tests are stable: `repeat-under-parallel-load` (test-quality), rung 3, for each new test module. - Finished cleanly: `no-stubs-scan`, `single-gate-command` (completeness), rung 3. ## Common false finishes diff --git a/done/new-product.md b/done/new-product.md index 29fab5f..bd86a1c 100644 --- a/done/new-product.md +++ b/done/new-product.md @@ -12,11 +12,14 @@ applies_to: Turning a one-line or short description (an app, a service, a tool) - It is safe: dependencies audited, secrets handled, trust boundaries modelled, data stored survives crashes and upgrades. - One command defines done; documentation says how to run and verify it; a release path exists. - The owner walked it and accepted it, and what was assumed is reported. +- The first usable increment is named, the work is ordered to reach it early, and every status update gives its estimated time, labelled as an estimate. +- Where the design depends on a heuristic, classifier or matcher being right most of the time, a throwaway version was first scored on labels a different worker wrote, and the measured ceiling and what stands behind the heuristic are in the design. ## Checks - What to build: `acceptance-examples`, `requirement-to-check-map` (completeness), `spec-traceability`; design: `tlaplus` or `quint` for state machines (design). - Logic: `lean4-proofs`, `kani` or `proptest` (prove, many-inputs), rung 1 to 2; `stateful-model-test`, `differential-reference`, `round-trip`. - Tests are real: `cargo-mutants` or the language's mutation tool, `vacuity-check`, `assertion-strength-review` (test-quality). +- Tests are stable: `repeat-under-parallel-load` (test-quality), rung 3. - Real world: `e2e-playwright` or `cli-transcript-tests`, `clean-clone-build`, `packaging-install-upgrade`, `cross-platform-matrix`. - Safety: `rust-lints-strict`, `dependency-audit-rust`, `secret-scanning`, `threat-model-checklist`, `licence-notices`. - Done: `single-gate-command`, `no-stubs-scan`, `check-tiering`, `release-gate`; the human: `owner-acceptance-runbook` (intent), rung 6. 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/assure.py b/sisi/assure.py index 26a7e27..3016626 100644 --- a/sisi/assure.py +++ b/sisi/assure.py @@ -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 diff --git a/sisi/brief.py b/sisi/brief.py index f7d8900..6503e67 100644 --- a/sisi/brief.py +++ b/sisi/brief.py @@ -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 diff --git a/sisi/cli.py b/sisi/cli.py index 2af214b..3875ae4 100644 --- a/sisi/cli.py +++ b/sisi/cli.py @@ -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] "" - 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 ""] - archive the unit to .sisi/units/.json with its scorecard; --abandon records why it stopped - sisi unit pause "" - 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 ""` 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 "" 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 "" 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) diff --git a/sisi/contract.py b/sisi/contract.py index d12b86b..afdf1ce 100644 --- a/sisi/contract.py +++ b/sisi/contract.py @@ -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): diff --git a/sisi/cycle.py b/sisi/cycle.py index c59b88d..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)] @@ -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 diff --git a/sisi/deep.py b/sisi/deep.py index 9bbcdfd..b538828 100644 --- a/sisi/deep.py +++ b/sisi/deep.py @@ -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} diff --git a/sisi/documents.py b/sisi/documents.py index 19ae699..72a8ec3 100644 --- a/sisi/documents.py +++ b/sisi/documents.py @@ -22,10 +22,6 @@ def check_rule_text(text, rid=None): return r -def traces_for_lesson(lesson_id): - return [] # the per-lesson trace regime is retired; provenance lives on the learning record - - def trace_lines(kind, entry_id): return [] diff --git a/sisi/gate.py b/sisi/gate.py index 3087a7c..f5dc46e 100644 --- a/sisi/gate.py +++ b/sisi/gate.py @@ -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: 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/helptext.py b/sisi/helptext.py new file mode 100644 index 0000000..58568b2 --- /dev/null +++ b/sisi/helptext.py @@ -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] ""\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 ""]\n archive the unit to .sisi/units/.json with its scorecard; --abandon records why it stopped\n sisi unit pause ""\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 ""` 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 "" 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 "" 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|TIME] | 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 \"\"]", "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 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/overlay.py b/sisi/overlay.py index 5213f33..9d69109 100644 --- a/sisi/overlay.py +++ b/sisi/overlay.py @@ -28,7 +28,6 @@ from . import paths # games must not load more text. A learning round still may not grow the book without shortening. MAX_LINES = 200 MAX_CHARS = 12000 -HOUSE_WIDTH = 100 KINDS = ("rule", "verifier", "recipe") ID_TAIL = re.compile(r"\s*\{#([A-Za-z0-9][A-Za-z0-9_-]*)\}\s*$") NUM = re.compile(r"^\d+\.\s+") @@ -98,30 +97,6 @@ def rule_text(r): return "## %s\n\n%s\n" % (r["title"], r["body"]) -def wrap_rule_body(body, width=HOUSE_WIDTH): - """Re-wrap rule prose to the house width, preserving paragraphs, bullets and code fences.""" - import textwrap - out, in_fence = [], False - for line in (body or "").split("\n"): - if line.strip().startswith("```"): - in_fence = not in_fence - out.append(line) - continue - if in_fence or not line.strip(): - out.append(line) - continue - stripped = line.lstrip() - indent = "" - if stripped.startswith(("- ", "* ")): - indent = " " - elif re.match(r"^\d+\.\s", stripped): - indent = " " - wrapped = textwrap.wrap(line, width=width, subsequent_indent=indent, - break_long_words=False, break_on_hyphens=False) - out.extend(wrapped or [""]) - return "\n".join(out).strip("\n") - - def _read(p): with open(p, encoding="utf-8") as f: return f.read() 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/rulecmd.py b/sisi/rulecmd.py index 360908e..84dc316 100644 --- a/sisi/rulecmd.py +++ b/sisi/rulecmd.py @@ -3,7 +3,7 @@ full with its reasons, history and the lessons folded into it. The generated rul `More: sisi rule N` at the end of each rule, so every rule an agent sees names the command that explains it. The enforcement wording is derived from code facts (which hooks are wired, whether the gate carries -the question check, whether the floors exist), not from prose: if a mechanism is removed, this +the question check and the risk requirements exist), not from prose: if a mechanism is removed, this output stops claiming it. A rule with no entry below is reported honestly as depending on the agent. """ import os, sys @@ -17,22 +17,6 @@ def _gate_wired(): return False -def _floors(): - try: - from . import contract, paths - return os.path.exists(paths.canon("floors.json")) and callable(contract.floor_failures) - except Exception: - return False - - -def _question_gate(): - try: - from . import gate - return bool(gate.QUESTION_DIALOG_TOOLS) and callable(gate.ends_with_question) - except Exception: - return False - - def _has(module, *attrs): """Does this code exist? Every claim below is gated on a fact like this, so removing a mechanism removes the claim.""" @@ -66,26 +50,32 @@ def _say(enforced=(), measured=(), judgement=()): return " | ".join(parts) if (enforced or measured) else _NOT + (" (%s)" % "; ".join(judgement) if judgement else "") -# One function per rule, so its wording can be tightened on its own when the end-of-turn gate -# rebuild (gate.py, contract.py, risk.json) merges. They describe what exists on this branch. +# One function per rule. Each names the module that holds the mechanism: the question check is in +# questions.py, the requirements per risk profile in assure.py and risk.py, the end-of-turn decision and +# the retro offer in gate.py, closing a unit in unit.py, the commit-time notice in watch.py. def _dialog_names(): try: - from . import gate - return ", ".join(sorted({t for v in gate.QUESTION_DIALOG_TOOLS.values() for t in v})) + from . import questions + return ", ".join(sorted({t for v in questions.QUESTION_DIALOG_TOOLS.values() for t in v})) except Exception: return "the question dialog" def _own_the_outcome(): return _say(enforced=["ending a reply on a question instead of the question dialog (%s) is sent back by the end-of-turn gate" - % _dialog_names() if _has("gate", "ends_with_question", "QUESTION_DIALOG_TOOLS") and _gate_wired() else None], + % _dialog_names() if _has("questions", "ends_with_question", "sendback", "QUESTION_DIALOG_TOOLS") + and _gate_wired() else None], judgement=["reading the request as the outcome, the requirement list, assume or ask, amendments"]) def _size_by_risk(): - return _say(enforced=["the end-of-turn gate demands the contract and evidence the risk floor calls for" - if _gate_wired() and _has("risk", "floor_for_working_tree") and _has("contract", "floor_failures") else None], + return _say(enforced=["the end-of-turn gate computes the risk floor of the change, takes the profile the contract declares " + "(lowering it needs a reason) and sends the agent back for whatever that profile requires" + if _gate_wired() and _has("risk", "assess", "requirements_for") + and _has("assure", "effective_profile", "missing") else None, + "a contract without a declared `risk.profile` is invalid" + if _has("contract", "RISK_PROFILES") and _has("assure", "missing") else None], measured=["`sisi risk` prints the floor and what the profile requires, the unit record keeps the profile" if _has("risk", "assess") else None], judgement=["raising the profile when you know better; lowering it needs a reason"]) @@ -94,21 +84,26 @@ def _size_by_risk(): def _define_done(): return _say(enforced=["contract check refuses a check with no command or one that cannot fail (vacuous)" if _has("contract", "vacuous_reason") else None, - "end-of-turn gate sends the agent back when a sizeable change has no contract" - if _gate_wired() else None], + "end-of-turn gate sends the agent back when the profile needs a contract and there is none, " + "or when a check lacks what it covers, invariants or the requirement list are missing" + if _gate_wired() and _has("assure", "missing") else None], judgement=["the goal in the person's words, one check on the purpose, invariants captured before the first edit"]) def _verify_enough(): return _say(enforced=["`sisi verify` runs the checks with five statuses (passed, failed, skipped, not-applicable, not-run), nothing unrun passes" if _has("verify", "STATUSES") else None, - "minimum rungs refused when the contract is checked" if _floors() else None, - "the end-of-turn gate runs verify and sends the agent back on a failure" if _gate_wired() else None], + "the end-of-turn gate runs the fast checks and sends the agent back on a failure, with the failing evidence lines" + if _gate_wired() and _has("assure", "failure_lines") else None, + "high-risk profiles need evidence from someone or something other than the author" + if _has("assure", "independent_evidence") else None], + measured=["a commit or merge with no passing `sisi verify` for the tree gets a notice, never a block" + if _has("watch", "commit_notice") else None], judgement=["choosing the technique, which checks the change can affect, watching a test fail once"]) def _deliver_fast(): - return _say(measured=["the unit record keeps timings (checks, delivery), `sisi status` shows trends and the slow steps" + return _say(measured=["the unit record keeps timings (checks, delivery), `sisi status` shows trends by project, risk profile, model and policy version" if _has("delivery", "record") and _has("scorecard", "cmd_status") else None, "a slower learned change is flagged for reversal" if _has("delivery", "record") else None], judgement=["parallel work, background checks, handing over early, changing approach when stuck"]) @@ -116,7 +111,7 @@ def _deliver_fast(): def _orchestrate(): return _say(enforced=["a delegation brief without outcome, acceptance or files it may change is refused (`sisi delegate`)" - if _has("workers", "cmd_delegate") else None], + if _has("workers", "cmd_delegate") and _has("brief", "missing_required") else None], measured=["the delegation ledger and `sisi delegate judge`, `sisi route` recommends the worker from that record" if _has("routing", "choose") and _has("workers", "cmd_delegate") else None], judgement=["who gets the task, how much to check what comes back, recording the judgement"]) @@ -129,9 +124,9 @@ def _report_plainly(): def _close_with_retro(): - return _say(enforced=["a retro is required before the unit closes; the gate sends the agent back, with a limit on reminders" - if _gate_wired() and _has("retro", "cmd_retro") else None], - measured=["`sisi cycle` due-ness is a counter of recorded lessons" if _has("cycle", "protected_rules") else None], + return _say(enforced=["the end-of-turn gate asks for a retro once per state of the tree and closes the unit when a finding is recorded" + if _gate_wired() and _has("learning", "findings_for_unit") and _has("unit", "close_unit") else None], + measured=["`sisi cycle` due-ness is a counter of recorded lessons" if _has("cycle", "due_notice") else None], judgement=["whether a finding is concrete, names a root cause and picks the right disposition"]) diff --git a/sisi/scope.py b/sisi/scope.py index 56197d1..649c52b 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 \"\"") @@ -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 \"\"" % rec["id"]) return 0 diff --git a/sisi/scorecard.py b/sisi/scorecard.py index fc59b13..82a4bee 100644 --- a/sisi/scorecard.py +++ b/sisi/scorecard.py @@ -369,7 +369,9 @@ def open_units(cwd=None): if not isinstance(c, dict) or not c.get("id") or c.get("status") == "closed" or C.is_unedited_skeleton(c): return out project = C.project_dir(p) - row = {"id": c["id"], "status": c.get("status", "open"), "age": _age(c.get("started")), "goal": c.get("goal") or ""} + started, basis = U.start_of(c, p) + row = {"id": c["id"], "status": c.get("status", "open"), "age": _age(started), "goal": c.get("goal") or "", + "age_basis": basis} if row["status"] == "paused": pz = next((x for x in reversed(c.get("pauses") or []) if isinstance(x, dict) and not x.get("until")), {}) row["waiting_for"], row["paused_for"] = pz.get("what"), _age(pz.get("since")) @@ -394,13 +396,17 @@ def _lowered_note(u): (": " + str(rk["why"])) if rk.get("why") else "") +def _basis_note(r): + return " (inferred from the contract file)" if r.get("age_basis") == "inferred" else "" + + def format_open(rows): lines = [] for r in rows: if r["status"] == "paused": - lines.append("paused %-24s age %s waiting for: %s (for %s)" % (r["id"], r["age"], r.get("waiting_for") or "?", r.get("paused_for"))) + lines.append("paused %-24s age %s%s waiting for: %s (for %s)" % (r["id"], r["age"], _basis_note(r), r.get("waiting_for") or "?", r.get("paused_for"))) else: - lines.append("open %-24s age %s %s" % (r["id"], r["age"], r["goal"][:80])) + lines.append("open %-24s age %s%s %s" % (r["id"], r["age"], _basis_note(r), r["goal"][:80])) if r.get("lowered"): lines.append(" lowered: " + r["lowered"]) if r.get("unverified"): 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 41b744a..affbe1e 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.""" @@ -231,11 +219,26 @@ def _transcript_stats(project, t0, t1): return agg -def build_telemetry(c, project, results, t0, t1): +def start_of(c, contract_path=None): + """(ISO UTC start, basis). A unit records `started` itself ("measured"). A contract written before the + unit record existed has none: the contract file's modification time stands in for it, and the basis + says "inferred" so nothing downstream reads it as measured. (None, None) when neither is known.""" + if isinstance(c.get("started"), str) and c["started"]: + return c["started"], "measured" + try: + mt = os.stat(contract_path).st_mtime if contract_path else None + except OSError: + mt = None + if mt is None: + return None, None + return time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(mt)) + "Z", "inferred" + + +def build_telemetry(c, project, results, t0, t1, t0_basis="measured"): """Every value classed. Sources: deliveries, results, pauses on the contract, the host transcript where a session record names one, git, and the delegation ledger.""" tel = {} - tel["time_to_validated_completion_s"] = val(round(t1 - t0, 1), "measured") if t0 is not None else unavailable() + tel["time_to_validated_completion_s"] = val(round(t1 - t0, 1), t0_basis) if t0 is not None else unavailable() if results: tel["time_in_checks_s"] = val(round(sum(float(r["duration_s"]) for r in results if isinstance(r.get("duration_s"), (int, float))), 3), "measured") @@ -412,7 +415,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", @@ -468,10 +471,11 @@ def decide_status(c, rows, abandon=None): return "delivered", block, unrun -def build_record(c, project, delivery_status, ended_epoch, abandon_reason=None, rows=None): - t0 = harvest.epoch(c["started"]) if isinstance(c.get("started"), str) else None +def build_record(c, project, delivery_status, ended_epoch, abandon_reason=None, rows=None, contract_path=None): + started, basis = start_of(c, contract_path) + t0 = harvest.epoch(started) if isinstance(started, str) else None rows = _unit_results(c, project, c.get("started")) if rows is None else rows - tel = build_telemetry(c, project, rows, t0, ended_epoch) + tel = build_telemetry(c, project, rows, t0, ended_epoch, basis or "measured") models = tel.pop("_models") delegation_rows = tel.pop("_delegation_rows") changed = tel.pop("_changed") @@ -500,7 +504,7 @@ def build_record(c, project, delivery_status, ended_epoch, abandon_reason=None, "plan": c.get("plan") or [], "workers": delegation_rows, "models": models, "budgets": c.get("budgets"), - "started": c.get("started"), "ended": ended, "closed_at": ended, "telemetry": tel, + "started": started, "started_basis": basis, "ended": ended, "closed_at": ended, "telemetry": tel, "start_commit": c.get("base_head"), "closing_commit": gitutil.head(project) if gitutil.root(project) else None, "summary": c.get("summary"), @@ -615,7 +619,8 @@ def close_unit(c, contract_path, project, abandon=None, now=None): return None, ("sisi: unit %s cannot close as delivered: %s. Fix and re-run `sisi verify`, " "record a deviation with `sisi contract waive \"\"`, or close it with " "`sisi unit close --abandon \"\"`." % (c["id"], bad)), False - rec = build_record(c, project, status, ended_epoch, abandon_reason=abandon, rows=rows) + rec = build_record(c, project, status, ended_epoch, abandon_reason=abandon, rows=rows, + contract_path=contract_path) _, created = archive_record(rec, project) if created: _capture_case(rec) 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/verify.py b/sisi/verify.py index edb1627..0d60ec6 100644 --- a/sisi/verify.py +++ b/sisi/verify.py @@ -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