diff --git a/docs/design.md b/docs/design.md index 030b7f8..9dff1f0 100644 --- a/docs/design.md +++ b/docs/design.md @@ -30,9 +30,8 @@ with a weaker check or a smaller result. Time to delivery is measured, not guessed. Each time the end-of-turn gate lets a turn end it records one delivery row: the time since the last message the human actually typed (hook feedback and tool results do not -count), how many times the gate sent the agent back, and how long the checks ran. `sisi status` shows the median -and 90th percentile for the last 7 days against the 7 days before, the share spent in checks, and the five -slowest checks; `sisi status` shows the 7-day median. +count), how many times the gate sent the agent back, and how long the checks ran. `sisi status` shows the +median and 90th percentile by project, risk profile, model and policy version. A learned change that speeds things up but fails a check is rejected. A learned change that keeps every check passing but makes median delivery slower is flagged for reversal. (Built: `sisi cycle status` flags a cycle @@ -126,12 +125,10 @@ runs alone. Results are reported in contract order either way. **Enforcement.** The tool's end-of-turn hook calls `sisi verify`. If a contract exists and a check fails or was not run, the agent is sent back with the failures and cannot report the work as done. If no contract exists and -the change is larger than a small threshold, the agent is sent back to write one; a change that size -with a contract whose design section is missing or fails validation is sent back to fill it. Small +the change is larger than its risk profile allows without one, the agent is sent back to write one. Small edits and subagents pass untouched, and the same send-back budget bounds every send-back, so no -session is trapped. Request-time delivery hands the standing principles and the design instruction -over when a request reads as design or build work, and `sisi design` prints them before a contract -exists. +session is trapped. Request-time delivery hands the standing principles over when a request reads as +design or build work. Claude Code supports a blocking stop hook. The equivalent in OpenCode, Codex and Muse is not verified; where it does not exist, verification is meant to run at the next session start and failures to be reported then (that fallback is a design intention, not built). @@ -316,18 +313,17 @@ Built and covered by tests: - The rulebook (`canon/core.md`), the risk table, the verifier library and the recipes. - Retrospectives and lessons (`sisi retro`, `sisi lessons`), `sisi learn` live at once, time to delivery (`sisi status`). -- Choosing the approach as a checked step: the contract design section, `sisi design`, the gate's - design send-back on large changes, and request-time delivery of the standing principles for design - or build requests. The rulebook's first rule states it and `sisi rule` reports its enforcement. +- Choosing the approach as a checked step: the contract's `approach` and the request-time delivery of the + standing principles for design or build requests. `sisi rule` reports the rulebook's enforcement. - Patterns: each retro names the general failure of thinking behind the incident; patterns are first-class, merged in rounds, and promoted into the rulebook as strategic behaviours past a - threshold; the digest and `sisi improve` show them first. Three tiers (`core`, `user`, `project`) + threshold; `sisi status --learning` shows them first. Three tiers (`core`, `user`, `project`) replace the two-way scope, with older universal items tiered by the next round, and `sisi promote` listing, writing (from the clone) or exporting core items. -- The lesson loop: immediate effects in the overlay (field notes, draft recipes, learned notes, `sisi backlog`), +- The lesson loop: immediate effects in the overlay (field notes, draft recipes, learned notes), moment-of-use delivery with recorded showings, per-lesson measurement, the strength ladder with enforced checks, `sisi cycle` (due counter, brief, validated apply under lock and base version, exact revert, status - with worse-cycle flagging) and `sisi improve`. + with worse-cycle flagging). - Personal data, the overlay, update, export and import, releases and rollback, promotion of a personal item into the product. - The data layer for learning: harvest of Claude Code transcripts, task set, ground truth, escape candidates, diff --git a/docs/learning.md b/docs/learning.md index b395689..5f6cd73 100644 --- a/docs/learning.md +++ b/docs/learning.md @@ -173,6 +173,5 @@ learnings in scope that target that entry. - `cycle.risk_patterns(cwd)` — the learned risk patterns that apply in a project (`risk.load_patterns`). - `cycle.routing_adjustments(project)` — the learned routing adjustments that apply in a project. - `cycle.due_notice()` — the session-start lines (cycle due, decision waiting). -- `retro.satisfied(repo, since, fp)` and `retro.TEMPLATE` — what the gate asks. - `learning.delivery_text(project, query, targets=())` — what the prompt hook may add. - `evaluate.validate_command(repo, before, after, cmd)` — the replay. diff --git a/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/gate.py b/sisi/gate.py index eace829..34ca584 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..e37eaf0 --- /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] | 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/paths.py b/sisi/paths.py index 93714d2..20cbe59 100644 --- a/sisi/paths.py +++ b/sisi/paths.py @@ -98,30 +98,6 @@ def personal_config(): return {} -def set_personal_config(keys, value, msg): - """Set (or with None remove) a nested key in the personal config.json; one commit in the personal repository.""" - import json - from . import pdata - cfg = personal_config() - d = cfg - for k in keys[:-1]: - d = d.setdefault(k, {}) if isinstance(d.get(k, {}), dict) else d.setdefault(k, {}) - if value is None: - d.pop(keys[-1], None) - if not d and len(keys) > 1: - cfg.pop(keys[0], None) - else: - d[keys[-1]] = value - os.makedirs(data(), exist_ok=True) - p = data_file("config.json") - tmp = p + ".sisi-tmp" - with open(tmp, "w", encoding="utf-8") as f: - json.dump(cfg, f, indent=2, sort_keys=True) - f.write("\n") - os.replace(tmp, p) - pdata.commit(msg, ["config.json"]) - - def state_file(name): return os.path.join(state(), name) diff --git a/sisi/retro.py b/sisi/retro.py index f2b744d..73a38a1 100644 --- a/sisi/retro.py +++ b/sisi/retro.py @@ -4,28 +4,11 @@ No arguments: print the unit's record and what stands out. With --finding: recor finding with a disposition. Only the fields the disposition needs are asked for; search terms, topics and short lines are derived by the tool. A finding that resembles an existing learning is attached to it as a recurrence candidate, never refused in a loop. - -Gate compatibility (gate.py calls these; its control flow is unchanged): TEMPLATE, -satisfied(), repo_of(), lessons_block(). """ import hashlib, json, os, subprocess, sys from . import learning as L, paths -TEMPLATE = ( - "Before this turn ends, record the retro for this unit ({n}).\n" - "Run `sisi retro` first: it prints the unit's record. Then record at least one finding:\n" - " sisi retro --finding \"\" --cause \"\" " - "--impact value|correctness|time|cost|attention --disposition promote|record|drop\n" - " promote also needs: --change \"\" --mechanism policy|orchestration|skill|tool|" - "infrastructure|verification|knowledge|benchmark --expect \"\" --validate \"\"\n" - " record also needs: --limits \"\"\n" - " drop also needs: --why-not \"\"\n" - "Generic findings are refused. A finding that resembles a learning in scope here is attached to it as\n" - "a recurrence (--new records it as its own); --same-as ID names the learning it repeats.\n" - "A parent adopts a subagent's candidate by id: sisi retro --adopt ID." -) - def repo_of(cwd): return L.project_key(cwd) @@ -40,39 +23,12 @@ def _git_head(cwd): return None -def satisfied(repo, since, fp): - """Gate seam: was a retro recorded for the current unit of this project?""" - try: - uid = L.unit_id(repo) - if L.findings_for_unit(repo, uid): - return True - # A finding recorded in this project since the request started also counts: - # the gate passes `since` from its own session bookkeeping. - pk = L.project_key(repo) - return any(f.get("project") == pk and (since is None or str(f.get("ts", "")) >= str(since)) - for f in L.load_findings()) if since else False - except Exception: - return False - - -def lessons_block(query, place, session=None, limit=3, max_chars=600, extra=""): - """Gate seam: learnings in scope as background information. Nothing is recorded as shown.""" - try: - text = L.delivery_text(os.getcwd(), str(query)) - return text[:max_chars] if text else "" - except Exception: - return "" - - def unit_summary(project): """What `sisi retro` with no arguments prints: the unit's record and what stands out.""" - try: - from . import unit as _unit # work-unit worker's module, when merged - text = _unit.summary_for_retro(project) - if text: - return text - except Exception: - pass + from . import unit as _unit + text = _unit.summary_for_retro(project) + if text: + return text lines = [] try: with open(os.path.join(project, ".sisi", "contract.json"), encoding="utf-8") as f: @@ -91,13 +47,6 @@ def unit_summary(project): lines.append("recent verification: %d result(s) on record, %d failed" % (len(rows), len(fails))) except (OSError, ValueError): pass - try: - from . import delivery - d = delivery.current(project) if hasattr(delivery, "current") else None - if d: - lines.append("delivery: %s" % d) - except Exception: - pass head = _git_head(project) if head: lines.append("project HEAD: %s" % head[:12]) diff --git a/sisi/risk.py b/sisi/risk.py index aa684e6..5e0c55b 100644 --- a/sisi/risk.py +++ b/sisi/risk.py @@ -38,7 +38,6 @@ import fnmatch, json, os, re, subprocess PROFILES = ["trivial", "isolated", "logic", "integration", "data", "critical", "release"] _ORDER = {name: i for i, name in enumerate(PROFILES)} -_TRIVIAL_PROFILES = {"trivial"} _DEFAULT_REASON = "ordinary source file: one module's behaviour" _CONTAINERS = {"src", "lib", "app", "packages", "apps", "services", "crates", "modules", "libs", "cmd", "internal", "pkg"} diff --git a/sisi/scope.py b/sisi/scope.py index 56197d1..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/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..a90765d 100644 --- a/sisi/unit.py +++ b/sisi/unit.py @@ -124,18 +124,6 @@ def delegations(project, t0, t1): return None -def _row_epoch(r): - for k in ("ts", "t", "started", "ended", "time"): - v = r.get(k) - if isinstance(v, (int, float)) and not isinstance(v, bool): - return float(v) - if isinstance(v, str): - t = harvest.epoch(v) - if t is not None: - return t - return None - - def policy_version(project, c): """Hash of the policies in force: the effective rulebook, the risk tables, the enforced checks, and the gate/verify config.""" @@ -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", 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