gate rebuild 2: profile requirements module, new gate flow, floors removed
This commit is contained in:
1 parent
720173a50a
commit
f39ca03233
14 files changed
+750
-904
No files matched your search
@@ -1,7 +0,0 @@
|
|||||||
{
|
|
||||||
"concurrency": 2,
|
|
||||||
"parsing": 2,
|
|
||||||
"money": 2,
|
|
||||||
"state-machine": 2,
|
|
||||||
"migration": 2
|
|
||||||
}
|
|
||||||
+7
-7
@@ -1,13 +1,13 @@
|
|||||||
{
|
{
|
||||||
"profiles": ["trivial", "isolated", "logic", "integration", "data", "critical", "release"],
|
"profiles": ["trivial", "isolated", "logic", "integration", "data", "critical", "release"],
|
||||||
"requirements": {
|
"requirements": {
|
||||||
"trivial": {"contract": false, "checks": "the diff; a targeted check when one exists", "requirement_model": false, "risk_note": false, "independent_evidence": false, "retro": "only on an anomaly (two send-backs, or a human correction)"},
|
"trivial": {"contract": false, "checks": "the diff; a targeted check when one exists", "requirement_model": false, "risk_note": false, "independent_evidence": false, "retro": "only on an anomaly (two send-backs, or a human correction)", "min_checks": 0, "covers": false, "invariants": false, "approach": false, "all_checks": false, "retro_when": "anomaly"},
|
||||||
"isolated": {"contract": true, "checks": "at least one that is not vacuous", "requirement_model": false, "risk_note": false, "independent_evidence": false, "retro": "yes"},
|
"isolated": {"contract": true, "checks": "at least one that is not vacuous", "requirement_model": false, "risk_note": false, "independent_evidence": false, "retro": "yes", "min_checks": 1, "covers": false, "invariants": false, "approach": false, "all_checks": false, "retro_when": "close"},
|
||||||
"logic": {"contract": true, "checks": "as isolated, each with covers", "requirement_model": false, "risk_note": false, "independent_evidence": false, "retro": "yes"},
|
"logic": {"contract": true, "checks": "as isolated, each with covers", "requirement_model": false, "risk_note": false, "independent_evidence": false, "retro": "yes", "min_checks": 1, "covers": true, "invariants": false, "approach": false, "all_checks": false, "retro_when": "close"},
|
||||||
"integration": {"contract": true, "checks": "as logic, plus invariants", "requirement_model": true, "risk_note": true, "independent_evidence": false, "retro": "yes"},
|
"integration": {"contract": true, "checks": "as logic, plus invariants", "requirement_model": true, "risk_note": true, "independent_evidence": false, "retro": "yes", "min_checks": 1, "covers": true, "invariants": true, "approach": true, "all_checks": false, "retro_when": "close"},
|
||||||
"data": {"contract": true, "checks": "as integration", "requirement_model": true, "risk_note": true, "independent_evidence": true, "retro": "yes"},
|
"data": {"contract": true, "checks": "as integration", "requirement_model": true, "risk_note": true, "independent_evidence": true, "retro": "yes", "min_checks": 1, "covers": true, "invariants": true, "approach": true, "all_checks": false, "retro_when": "close"},
|
||||||
"critical": {"contract": true, "checks": "as integration", "requirement_model": true, "risk_note": true, "independent_evidence": true, "retro": "yes"},
|
"critical": {"contract": true, "checks": "as integration", "requirement_model": true, "risk_note": true, "independent_evidence": true, "retro": "yes", "min_checks": 1, "covers": true, "invariants": true, "approach": true, "all_checks": false, "retro_when": "close"},
|
||||||
"release": {"contract": true, "checks": "every check (--all)", "requirement_model": true, "risk_note": true, "independent_evidence": true, "retro": "yes"}
|
"release": {"contract": true, "checks": "every check (--all)", "requirement_model": true, "risk_note": true, "independent_evidence": true, "retro": "yes", "min_checks": 1, "covers": true, "invariants": true, "approach": true, "all_checks": true, "retro_when": "close"}
|
||||||
},
|
},
|
||||||
"patterns": [
|
"patterns": [
|
||||||
{"stage": "code", "glob": "**/*.{py,pyi,pyw,js,mjs,cjs,jsx,ts,tsx,mts,cts,vue,svelte,astro,java,kt,kts,scala,groovy,clj,cljs,go,rs,c,h,cc,cpp,cxx,hpp,hh,hxx,m,mm,cs,fs,vb,swift,dart,rb,php,pl,pm,lua,r,jl,ex,exs,erl,hs,ml,mli,nim,zig,sh,bash,zsh,fish,ps1,bat,cmd,sol,sv,vhd,tcl,awk,asm,sql}", "profile": "isolated", "reason": "source code: never trivial, whatever its name or directory"},
|
{"stage": "code", "glob": "**/*.{py,pyi,pyw,js,mjs,cjs,jsx,ts,tsx,mts,cts,vue,svelte,astro,java,kt,kts,scala,groovy,clj,cljs,go,rs,c,h,cc,cpp,cxx,hpp,hh,hxx,m,mm,cs,fs,vb,swift,dart,rb,php,pl,pm,lua,r,jl,ex,exs,erl,hs,ml,mli,nim,zig,sh,bash,zsh,fish,ps1,bat,cmd,sol,sv,vhd,tcl,awk,asm,sql}", "profile": "isolated", "reason": "source code: never trivial, whatever its name or directory"},
|
||||||
|
|||||||
+1
-3
@@ -2,9 +2,7 @@
|
|||||||
"gate": {
|
"gate": {
|
||||||
"enabled": true,
|
"enabled": true,
|
||||||
"budget_s": 120,
|
"budget_s": 120,
|
||||||
"max_blocks": 3,
|
"max_blocks": 3
|
||||||
"growth_lines": 40,
|
|
||||||
"growth_files": 3
|
|
||||||
},
|
},
|
||||||
"verify": {
|
"verify": {
|
||||||
"default_timeout_s": 60,
|
"default_timeout_s": 60,
|
||||||
|
|||||||
+175
@@ -0,0 +1,175 @@
|
|||||||
|
"""What a risk profile requires, and what is missing from a unit (target section 3).
|
||||||
|
|
||||||
|
The gate enforces the `requirements` table in canon/risk.json and nothing else. This module reads
|
||||||
|
that table, looks at the contract and the evidence, and returns the missing items in plain words,
|
||||||
|
each with the command or field that supplies it. It never decides anything about the tree itself.
|
||||||
|
|
||||||
|
The profile that applies is the floor (what the changed paths say, by sisi/risk.py) unless the
|
||||||
|
contract declares a higher one. A contract may declare a lower one only by giving `risk.why`: the
|
||||||
|
unit then runs at the declared profile and is recorded as lowered, with floor, declared profile and
|
||||||
|
reason kept side by side (`sisi status` shows it).
|
||||||
|
"""
|
||||||
|
import os, time
|
||||||
|
|
||||||
|
from . import contract as C, harvest, risk, store
|
||||||
|
|
||||||
|
ORDER = {name: i for i, name in enumerate(risk.PROFILES)}
|
||||||
|
|
||||||
|
|
||||||
|
def effective_profile(floor, c):
|
||||||
|
"""(profile, info). `info` = {floor, declared, lowered, why, refused}: `refused` is set when a
|
||||||
|
contract declared a lower profile without a reason, so the floor was kept."""
|
||||||
|
rk = (c.get("risk") if isinstance(c, dict) else None) or {}
|
||||||
|
declared = rk.get("profile") if rk.get("profile") in ORDER else None
|
||||||
|
info = {"floor": floor, "declared": declared, "lowered": False, "why": rk.get("why"), "refused": False}
|
||||||
|
if declared is None or ORDER[declared] >= ORDER[floor]:
|
||||||
|
return (declared if declared and ORDER[declared] > ORDER[floor] else floor), info
|
||||||
|
if C.is_placeholder(rk.get("why")):
|
||||||
|
info["refused"] = True
|
||||||
|
return floor, info
|
||||||
|
info["lowered"] = True
|
||||||
|
return declared, info
|
||||||
|
|
||||||
|
|
||||||
|
def is_lowered(floor, declared, why):
|
||||||
|
"""True when a unit declared a profile below its floor and gave a reason (what `sisi status` flags)."""
|
||||||
|
return bool(floor in ORDER and declared in ORDER and ORDER[declared] < ORDER[floor]
|
||||||
|
and not C.is_placeholder(why))
|
||||||
|
|
||||||
|
|
||||||
|
def requirements(profile):
|
||||||
|
return risk.requirements_for(profile)
|
||||||
|
|
||||||
|
|
||||||
|
def stronger_technique(c):
|
||||||
|
"""True when some check or invariant uses a technique stronger than example tests: a proof or
|
||||||
|
model check (rung 1), or properties, fuzzing or a reference comparison (rung 2)."""
|
||||||
|
items = list((c or {}).get("checks") or []) + list((c or {}).get("invariants") or [])
|
||||||
|
return any(isinstance(x, dict) and x.get("rung") in (1, 2) for x in items)
|
||||||
|
|
||||||
|
|
||||||
|
def _real(items, key):
|
||||||
|
"""Entries of a list whose `key` says something (not empty, not a placeholder)."""
|
||||||
|
return [x for x in items or [] if isinstance(x, dict) and not C.is_placeholder(x.get(key))]
|
||||||
|
|
||||||
|
|
||||||
|
def _passing(r):
|
||||||
|
return r.get("status") == "passed" or (r.get("status") == "skipped"
|
||||||
|
and str(r.get("reason") or "").startswith("reused: passed"))
|
||||||
|
|
||||||
|
|
||||||
|
def review_evidence(project, c, now=None):
|
||||||
|
"""The accepted review delegations of this project inside the unit's window whose result was
|
||||||
|
checked by something stronger than `none`. The ledger names a project by its folder name."""
|
||||||
|
t0 = harvest.epoch(c["started"]) if isinstance(c.get("started"), str) else None
|
||||||
|
if t0 is None:
|
||||||
|
return []
|
||||||
|
try:
|
||||||
|
from . import workers
|
||||||
|
dg = workers.delegations_for_project(os.path.basename(project.rstrip(os.sep)), t0,
|
||||||
|
time.time() if now is None else now)
|
||||||
|
except Exception as e:
|
||||||
|
store.log_error("assure-delegations", e)
|
||||||
|
return []
|
||||||
|
return [r for r in dg["delegations"] if r.get("type") == "review" and r.get("outcome") == "accepted"
|
||||||
|
and r.get("check") not in (None, "", "none")]
|
||||||
|
|
||||||
|
|
||||||
|
def independent_evidence(project, c, results, now=None):
|
||||||
|
"""What stands behind a unit as independent evidence: a judged review in the ledger, or a
|
||||||
|
passing check that is marked independent AND says by whom or what it was produced."""
|
||||||
|
out = []
|
||||||
|
for r in review_evidence(project, c, now):
|
||||||
|
out.append("review by %s" % (r.get("worker") or "a reviewer"))
|
||||||
|
named = {x.get("id"): x for x in list(c.get("checks") or []) + list(c.get("invariants") or [])
|
||||||
|
if isinstance(x, dict) and x.get("independent") is True and not C.is_placeholder(x.get("by"))}
|
||||||
|
for r in results or []:
|
||||||
|
if r.get("id") in named and _passing(r):
|
||||||
|
out.append("check %s by %s" % (r["id"], named[r["id"]]["by"]))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def missing(profile, c, project, results=None, errors=None, deep_state=None, now=None):
|
||||||
|
"""[(what is missing, how to supply it)] for this profile. `c` is None when no contract is open.
|
||||||
|
`errors` are the contract's validation errors. Nothing is asked that the table does not require."""
|
||||||
|
req = requirements(profile)
|
||||||
|
out = []
|
||||||
|
if not req.get("contract"):
|
||||||
|
return out
|
||||||
|
if c is None:
|
||||||
|
out.append(("a contract for this %s change" % profile,
|
||||||
|
"`sisi contract init`, then write at least one check that can fail"))
|
||||||
|
c = {}
|
||||||
|
absent = True
|
||||||
|
else:
|
||||||
|
absent = False
|
||||||
|
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`"))
|
||||||
|
checks = [x for x in c.get("checks") or [] if isinstance(x, dict)]
|
||||||
|
if not absent and not errors and int(req.get("min_checks", 0)) > len(checks):
|
||||||
|
out.append(("at least one check that can fail", 'add it under "checks"'))
|
||||||
|
if req.get("covers"):
|
||||||
|
bare = [x.get("id") or "?" for x in checks if C.is_placeholder(x.get("covers"))]
|
||||||
|
if bare or absent:
|
||||||
|
out.append(("every check says what it covers" + (" (missing on %s)" % ", ".join(bare) if bare else ""),
|
||||||
|
'"covers": the failure that check would catch'))
|
||||||
|
if req.get("invariants") and not _real(c.get("invariants"), "claim"):
|
||||||
|
out.append(("invariants: what must not get worse",
|
||||||
|
'"invariants": a command that can fail, e.g. the existing tests'))
|
||||||
|
if req.get("requirement_model") and not _real(c.get("requirements"), "text"):
|
||||||
|
out.append(("a requirement list",
|
||||||
|
'"requirements": entries with "kind", "text" and "decision" (now, architect, defer, ignore)'))
|
||||||
|
if req.get("risk_note"):
|
||||||
|
rk = c.get("risk") if isinstance(c.get("risk"), dict) else {}
|
||||||
|
lacking = [k for k in ("blast_radius", "rollback") if C.is_placeholder(rk.get(k))]
|
||||||
|
if lacking:
|
||||||
|
out.append(("a risk note: %s" % " and ".join(lacking),
|
||||||
|
'"risk": {"blast_radius": what this can break, "rollback": how to undo it}'))
|
||||||
|
if req.get("approach"):
|
||||||
|
ap = c.get("approach") if isinstance(c.get("approach"), dict) else {}
|
||||||
|
if C.is_placeholder(ap.get("chosen")) or C.is_placeholder(ap.get("why")) \
|
||||||
|
or not [a for a in ap.get("alternatives") or [] if not C.is_placeholder(a)]:
|
||||||
|
out.append(("the approach: what you chose, why, and an alternative you rejected",
|
||||||
|
'"approach": {"chosen", "why", "alternatives": [...]}'))
|
||||||
|
if req.get("independent_evidence") and not independent_evidence(project, c, results, now):
|
||||||
|
out.append(("independent evidence that someone or something else checked this",
|
||||||
|
"a reviewer's judged result (`sisi delegate judge --type review --outcome accepted "
|
||||||
|
"--check review`), or a passing check with \"independent\": true and \"by\": \"<who or what>\""))
|
||||||
|
if req.get("all_checks") and deep_state is not None and deep_state not in ("fresh-pass", "none"):
|
||||||
|
out.append(("every check, deep ones included, passing on this tree (release)",
|
||||||
|
"`sisi verify --deep --background`, then `sisi verify --state`"))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- messages
|
||||||
|
|
||||||
|
MAX_LINES = 25
|
||||||
|
|
||||||
|
|
||||||
|
def fit(lines, limit=MAX_LINES):
|
||||||
|
"""No message to the agent is longer than `limit` lines: over it, the tail is replaced by one line
|
||||||
|
saying how many were cut. Every line is also kept short."""
|
||||||
|
flat = []
|
||||||
|
for ln in lines:
|
||||||
|
for sub in str(ln).split("\n"):
|
||||||
|
flat.append(sub if len(sub) <= 300 else sub[:297] + "...")
|
||||||
|
if len(flat) <= limit:
|
||||||
|
return "\n".join(flat)
|
||||||
|
return "\n".join(flat[:limit - 1] + ["... (%d more lines; run `sisi verify` for the full output)"
|
||||||
|
% (len(flat) - limit + 1)])
|
||||||
|
|
||||||
|
|
||||||
|
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."""
|
||||||
|
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]
|
||||||
|
if len(bad) > checks:
|
||||||
|
out.append("- and %d more failing" % (len(bad) - checks))
|
||||||
|
return out
|
||||||
@@ -168,10 +168,6 @@ def cmd_contract(args):
|
|||||||
errs = C.validate(c)
|
errs = C.validate(c)
|
||||||
for e in errs:
|
for e in errs:
|
||||||
print(" - " + e)
|
print(" - " + e)
|
||||||
if not errs:
|
|
||||||
for f in C.floor_failures(c):
|
|
||||||
errs.append(f["message"])
|
|
||||||
print(" - " + f["message"])
|
|
||||||
if not errs:
|
if not errs:
|
||||||
for w in C.warnings(c):
|
for w in C.warnings(c):
|
||||||
print("warning: " + w)
|
print("warning: " + w)
|
||||||
|
|||||||
+21
-22
@@ -1,4 +1,4 @@
|
|||||||
"""Contract file: location, skeleton, validation, floors."""
|
"""Contract file: location, skeleton, validation."""
|
||||||
import json, os, re
|
import json, os, re
|
||||||
|
|
||||||
from . import paths, gitutil
|
from . import paths, gitutil
|
||||||
@@ -108,14 +108,6 @@ def deferred_checks(c):
|
|||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
def floors():
|
|
||||||
try:
|
|
||||||
with open(paths.canon("floors.json"), encoding="utf-8") as f:
|
|
||||||
return {k: int(v) for k, v in json.load(f).items()}
|
|
||||||
except (OSError, ValueError):
|
|
||||||
return {}
|
|
||||||
|
|
||||||
|
|
||||||
def _num(x):
|
def _num(x):
|
||||||
return isinstance(x, (int, float)) and not isinstance(x, bool)
|
return isinstance(x, (int, float)) and not isinstance(x, bool)
|
||||||
|
|
||||||
@@ -124,6 +116,24 @@ def _str(x):
|
|||||||
return isinstance(x, str) and x.strip() != ""
|
return isinstance(x, str) and x.strip() != ""
|
||||||
|
|
||||||
|
|
||||||
|
_PLACEHOLDER_WORDS = {"todo", "tbd", "tba", "fixme", "xxx", "wip", "none", "nothing", "no", "n/a", "na", "nil",
|
||||||
|
"null", "unknown", "placeholder", "later", "see above", "same", "as above", "not applicable",
|
||||||
|
"no risk", "no rollback", "none needed", "not needed", "nothing needed", "-", "--", "...",
|
||||||
|
"?", "yes", "ok", "fine", "tests", "all"}
|
||||||
|
|
||||||
|
|
||||||
|
def is_placeholder(x):
|
||||||
|
"""True for text that fills a field without saying anything: empty, `TODO`, `n/a`, `none`,
|
||||||
|
`tbd`, a bare punctuation mark, or anything that begins with TODO/TBD/FIXME. The gate asks for
|
||||||
|
a requirement list, a risk note, an approach and a reason; these words do not provide one."""
|
||||||
|
if not isinstance(x, str):
|
||||||
|
return True
|
||||||
|
t = " ".join(x.lower().split()).strip(" .,:;!-_*")
|
||||||
|
if len(re.findall(r"[a-z0-9]", t)) < 3 and t not in ("ui",):
|
||||||
|
return True
|
||||||
|
return t in _PLACEHOLDER_WORDS or bool(re.match(r"^(todo|tbd|fixme|placeholder|xxx)\b", t))
|
||||||
|
|
||||||
|
|
||||||
TIERS = ("fast", "deep")
|
TIERS = ("fast", "deep")
|
||||||
|
|
||||||
|
|
||||||
@@ -274,6 +284,8 @@ def _check_new_fields(ch, w, errs):
|
|||||||
for k in ("mandatory", "independent"):
|
for k in ("mandatory", "independent"):
|
||||||
if k in ch and not isinstance(ch[k], bool):
|
if k in ch and not isinstance(ch[k], bool):
|
||||||
errs.append("%s: %s must be true or false" % (w, k))
|
errs.append("%s: %s must be true or false" % (w, k))
|
||||||
|
if "by" in ch and not _str(ch["by"]):
|
||||||
|
errs.append(w + ": by must name who or what produced the independent evidence")
|
||||||
|
|
||||||
|
|
||||||
def _validate_new_top(c, ids, errs):
|
def _validate_new_top(c, ids, errs):
|
||||||
@@ -473,16 +485,3 @@ def validate(c):
|
|||||||
errs.append("questions[%d] needs q and default" % i)
|
errs.append("questions[%d] needs q and default" % i)
|
||||||
_validate_new_top(c, ids, errs)
|
_validate_new_top(c, ids, errs)
|
||||||
return errs
|
return errs
|
||||||
|
|
||||||
|
|
||||||
def floor_failures(c, floor_map=None):
|
|
||||||
"""Kinds with a floor where every check of that kind is weaker than the floor."""
|
|
||||||
fm = floors() if floor_map is None else floor_map
|
|
||||||
out = []
|
|
||||||
for kind, fl in sorted(fm.items()):
|
|
||||||
of_kind = [ch for ch in c.get("checks", []) if ch.get("kind") == kind]
|
|
||||||
if of_kind and not any(ch["rung"] <= fl for ch in of_kind):
|
|
||||||
out.append({"kind": kind, "floor": fl,
|
|
||||||
"message": "floor: %s claims need a check at rung %d or stronger; best is rung %d"
|
|
||||||
% (kind, fl, min(ch["rung"] for ch in of_kind))})
|
|
||||||
return out
|
|
||||||
+411
-820
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,130 @@
|
|||||||
|
"""Rule 5 at the end of a turn: a reply that ends by asking the human a question must have asked it
|
||||||
|
through the tool's question dialog. Sent back at most once per final message, never a subagent."""
|
||||||
|
import hashlib, json, os, re
|
||||||
|
|
||||||
|
from . import store
|
||||||
|
|
||||||
|
|
||||||
|
def _session_key(payload, cwd):
|
||||||
|
sid = payload.get("session_id")
|
||||||
|
return sid if isinstance(sid, str) and sid else "cwd-" + hashlib.sha1(cwd.encode()).hexdigest()[:12]
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- rule 5: ask through the dialog
|
||||||
|
# Tools with a confirmed question dialog whose transcripts sisi can read in Claude-Code shape.
|
||||||
|
# Codex's request_user_input is behind a flag that is off by default, OpenCode's question tool has
|
||||||
|
# no readable transcript file here, and the other tools name no dialog at all, so they are exempt.
|
||||||
|
QUESTION_DIALOG_TOOLS = {"claude-code": ("AskUserQuestion",), "qwen": ("ask_user_question",)}
|
||||||
|
_RHETORICAL = (r"^who (wouldn'?t|couldn'?t|doesn'?t)\b", r"^what could possibly\b",
|
||||||
|
r"^(isn'?t|aren'?t) it (obvious|clear)\b")
|
||||||
|
|
||||||
|
|
||||||
|
def ends_with_question(text):
|
||||||
|
"""True when a final message ends by asking the reader a question. The rule, exactly: after
|
||||||
|
removing fenced code blocks, blockquote lines and inline code, the last sentence of the last
|
||||||
|
paragraph ends with a question mark that is not inside a closing quote (a quoted question),
|
||||||
|
and the sentence does not start with a known rhetorical form."""
|
||||||
|
if not isinstance(text, str) or not text.strip():
|
||||||
|
return False
|
||||||
|
kept, in_fence = [], False
|
||||||
|
for line in text.split("\n"):
|
||||||
|
if line.strip().startswith("```"):
|
||||||
|
in_fence = not in_fence
|
||||||
|
continue
|
||||||
|
if in_fence or line.lstrip().startswith(">"):
|
||||||
|
continue
|
||||||
|
kept.append(re.sub(r"`[^`]*`", "", line))
|
||||||
|
paras = [p.strip() for p in re.split(r"\n\s*\n", "\n".join(kept)) if p.strip()]
|
||||||
|
if not paras:
|
||||||
|
return False
|
||||||
|
para = " ".join(paras[-1].split())
|
||||||
|
t = para.rstrip("*_ ")
|
||||||
|
if t.endswith(('?"', "?\"", "?'", "?’", "?”")): # the question mark sits inside a quotation
|
||||||
|
return False
|
||||||
|
t = t.rstrip(')]*_ ')
|
||||||
|
if not t.endswith("?"):
|
||||||
|
return False
|
||||||
|
start = max(t.rfind(".", 0, len(t) - 1), t.rfind("!", 0, len(t) - 1), t.rfind("?", 0, len(t) - 1)) + 1
|
||||||
|
sentence = t[start:].strip().lower()
|
||||||
|
return not any(re.match(p, sentence) for p in _RHETORICAL)
|
||||||
|
|
||||||
|
|
||||||
|
def _last_turn(tp):
|
||||||
|
"""(final assistant text, tool names used) after the last message the human typed, from the
|
||||||
|
transcript tail. None when the turn cannot be bounded (the caller then exempts the turn)."""
|
||||||
|
try:
|
||||||
|
size = os.path.getsize(os.path.expanduser(tp))
|
||||||
|
with open(os.path.expanduser(tp), "rb") as f:
|
||||||
|
f.seek(max(0, size - 2 * 1024 * 1024))
|
||||||
|
data = f.read()
|
||||||
|
except OSError:
|
||||||
|
return None
|
||||||
|
from . import harvest
|
||||||
|
recs = []
|
||||||
|
for raw in data.split(b"\n"):
|
||||||
|
if not raw.strip():
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
d = json.loads(raw.decode("utf-8", "replace"))
|
||||||
|
except ValueError:
|
||||||
|
continue # a cut first line or a corrupt one: it cannot be the turn's evidence either way
|
||||||
|
if isinstance(d, dict):
|
||||||
|
recs.append(d)
|
||||||
|
last_human = -1
|
||||||
|
for i, d in enumerate(recs):
|
||||||
|
if d.get("type") == "user":
|
||||||
|
try:
|
||||||
|
if harvest.typed_text(d)[0] is not None:
|
||||||
|
last_human = i
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
if last_human < 0:
|
||||||
|
return None
|
||||||
|
final, tools = "", set()
|
||||||
|
for d in recs[last_human + 1:]:
|
||||||
|
content = (d.get("message") or {}).get("content") if isinstance(d.get("message"), dict) else None
|
||||||
|
texts = []
|
||||||
|
for x in content if isinstance(content, list) else []:
|
||||||
|
if not isinstance(x, dict):
|
||||||
|
continue
|
||||||
|
if x.get("type") == "tool_use" and isinstance(x.get("name"), str):
|
||||||
|
tools.add(x["name"])
|
||||||
|
elif x.get("type") == "text" and isinstance(x.get("text"), str):
|
||||||
|
texts.append(x["text"])
|
||||||
|
if texts and d.get("type") in ("assistant", None):
|
||||||
|
final = "\n".join(texts)
|
||||||
|
return final, tools
|
||||||
|
|
||||||
|
|
||||||
|
def sendback(payload):
|
||||||
|
"""('block', reason) when this turn ended by asking in reply text and no question dialog was
|
||||||
|
used in it; None otherwise. At most once per final message, keyed by its hash in the session
|
||||||
|
record, so a session can never be trapped. Subagents and dialog-less tools are exempt."""
|
||||||
|
tool = store.tool()
|
||||||
|
dialogs = QUESTION_DIALOG_TOOLS.get(tool or "")
|
||||||
|
if not dialogs:
|
||||||
|
return None
|
||||||
|
if payload.get("agent_id") or payload.get("agent_transcript_path"):
|
||||||
|
return None # a subagent has no human to ask through a dialog
|
||||||
|
cwd = payload.get("cwd") if isinstance(payload.get("cwd"), str) and os.path.isdir(payload.get("cwd")) else os.getcwd()
|
||||||
|
sid = _session_key(payload, cwd)
|
||||||
|
sess = store.load_session(sid)
|
||||||
|
tp = payload.get("transcript_path") if isinstance(payload.get("transcript_path"), str) else sess.get("transcript_path")
|
||||||
|
if not isinstance(tp, str) or not tp:
|
||||||
|
return None
|
||||||
|
turn = _last_turn(tp)
|
||||||
|
if not turn:
|
||||||
|
return None
|
||||||
|
final, tools = turn
|
||||||
|
if any(d in tools for d in dialogs) or not ends_with_question(final):
|
||||||
|
return None
|
||||||
|
key = hashlib.sha1(final.encode("utf-8", "replace")).hexdigest()[:16]
|
||||||
|
if sess.get("q_block_key") == key:
|
||||||
|
return None
|
||||||
|
sess["q_block_key"] = key
|
||||||
|
sess["req_blocks"] = int(sess.get("req_blocks", 0)) + 1
|
||||||
|
store.save_session(sid, sess)
|
||||||
|
return "block", ("sisi: you ended by asking the human a question in the text of your reply. Ask it through the "
|
||||||
|
"tool's question dialog (%s), with options to pick from and the one you recommend marked — or "
|
||||||
|
"decide it yourself, record the assumption, and finish without the question. "
|
||||||
|
"(The rule in full: `sisi rule decide-dont-ask`.)" % dialogs[0])
|
||||||
+2
-2
@@ -5,7 +5,7 @@ from . import paths
|
|||||||
|
|
||||||
FILES = {"results": "results.jsonl",
|
FILES = {"results": "results.jsonl",
|
||||||
"learn": "learn.jsonl", "quarantine": "learn.jsonl", "waivers": "waivers.jsonl",
|
"learn": "learn.jsonl", "quarantine": "learn.jsonl", "waivers": "waivers.jsonl",
|
||||||
"deliveries": "deliveries.jsonl", "units": "units.jsonl"}
|
"deliveries": "deliveries.jsonl", "units": "units.jsonl", "subagents": "subagents.jsonl"}
|
||||||
|
|
||||||
|
|
||||||
def _migrate_learn():
|
def _migrate_learn():
|
||||||
@@ -154,7 +154,7 @@ def stamp(extra):
|
|||||||
return rec
|
return rec
|
||||||
|
|
||||||
|
|
||||||
DEFAULTS = {"gate": {"enabled": True, "budget_s": 120, "max_blocks": 3, "growth_lines": 40, "growth_files": 3},
|
DEFAULTS = {"gate": {"enabled": True, "budget_s": 120, "max_blocks": 3},
|
||||||
"verify": {"default_timeout_s": 60, "fast_limit_s": 60},
|
"verify": {"default_timeout_s": 60, "fast_limit_s": 60},
|
||||||
"retro": {"required": True},
|
"retro": {"required": True},
|
||||||
"scratch": {"session_max_age_days": 30, "prune_every": 20, "prune_max_delete": 1000,
|
"scratch": {"session_max_age_days": 30, "prune_every": 20, "prune_max_delete": 1000,
|
||||||
|
|||||||
+2
-2
@@ -137,14 +137,14 @@ def _row_epoch(r):
|
|||||||
|
|
||||||
|
|
||||||
def policy_version(project, c):
|
def policy_version(project, c):
|
||||||
"""Hash of the policies in force: the effective rulebook, the floors and risk tables,
|
"""Hash of the policies in force: the effective rulebook, the risk tables,
|
||||||
the enforced checks, and the gate/verify config."""
|
the enforced checks, and the gate/verify config."""
|
||||||
h = hashlib.sha256()
|
h = hashlib.sha256()
|
||||||
rulebook = paths.generated()
|
rulebook = paths.generated()
|
||||||
if not os.path.exists(rulebook):
|
if not os.path.exists(rulebook):
|
||||||
rulebook = paths.canon("core.md")
|
rulebook = paths.canon("core.md")
|
||||||
# named by role, never by path: the same policies hash the same in any clone or project
|
# named by role, never by path: the same policies hash the same in any clone or project
|
||||||
for role, p in (("rulebook", rulebook), ("floors", paths.canon("floors.json")),
|
for role, p in (("rulebook", rulebook),
|
||||||
("risk table", paths.canon("risk.json")),
|
("risk table", paths.canon("risk.json")),
|
||||||
("project risk table", os.path.join(project, ".sisi", "risk.json"))):
|
("project risk table", os.path.join(project, ".sisi", "risk.json"))):
|
||||||
try:
|
try:
|
||||||
|
|||||||
+1
-10
@@ -455,21 +455,12 @@ def cmd_for(args):
|
|||||||
ranked = [(s + (1.0 if inst[e["path"]] == "yes" else 0.0), e) for s, e in cands]
|
ranked = [(s + (1.0 if inst[e["path"]] == "yes" else 0.0), e) for s, e in cands]
|
||||||
ranked.sort(key=lambda x: (-round(x[0], 1), x[1]["rung"], x[1]["id"]))
|
ranked.sort(key=lambda x: (-round(x[0], 1), x[1]["rung"], x[1]["id"]))
|
||||||
top = ranked[:8]
|
top = ranked[:8]
|
||||||
fl = None
|
|
||||||
if "kind" in opts:
|
|
||||||
fl = C.floors().get(opts["kind"].lower())
|
|
||||||
if fl:
|
|
||||||
print("Floor: %s claims need rung %d or stronger (canon/floors.json). Results marked [floor ok] satisfy it.\n"
|
|
||||||
% (opts["kind"], fl))
|
|
||||||
if not top:
|
if not top:
|
||||||
print("no verifier matches that description; try `sisi verifiers` to browse")
|
print("no verifier matches that description; try `sisi verifiers` to browse")
|
||||||
_print_lessons(desc, "verifiers-for", loose=True)
|
_print_lessons(desc, "verifiers-for", loose=True)
|
||||||
return 0
|
return 0
|
||||||
for i, (f, e) in enumerate(top, 1):
|
for i, (f, e) in enumerate(top, 1):
|
||||||
mark = ""
|
print("%d. %s rung %s cost %s installed: %s%s" % (i, e["id"], e["rung"], e["cost"] or "-", inst[e["path"]], origin_tag(e)))
|
||||||
if fl:
|
|
||||||
mark = " [floor ok]" if e["rung"] <= fl else " [below floor]"
|
|
||||||
print("%d. %s rung %s cost %s installed: %s%s%s" % (i, e["id"], e["rung"], e["cost"] or "-", inst[e["path"]], mark, origin_tag(e)))
|
|
||||||
print(" %s" % (e["answers"] or e["title"]))
|
print(" %s" % (e["answers"] or e["title"]))
|
||||||
print("\nsisi verifiers show ID for set-up and a worked example")
|
print("\nsisi verifiers show ID for set-up and a worked example")
|
||||||
_print_lessons(desc, "verifiers-for", extra=" ".join(e["id"] for _, e in top[:3]), loose=True,
|
_print_lessons(desc, "verifiers-for", extra=" ".join(e["id"] for _, e in top[:3]), loose=True,
|
||||||
|
|||||||
@@ -285,11 +285,6 @@ def run(c, project, deadline=None, default_timeout=60, tiers=("fast",), changed=
|
|||||||
dirty_cache = True
|
dirty_cache = True
|
||||||
if dirty_cache:
|
if dirty_cache:
|
||||||
_save_cache(cache)
|
_save_cache(cache)
|
||||||
for f in (C.floor_failures(c) if "fast" in tiers else []):
|
|
||||||
res.append({"item": "floor", "tier": "fast", "id": "floor:" + f["kind"], "kind": f["kind"], "rung": None,
|
|
||||||
"claim": f["message"], "status": "failed", "reason": None, "duration_s": 0.0,
|
|
||||||
"tail": f["message"], "mandatory": True, "independent": False, "covers": None,
|
|
||||||
"seen_failing": True, "saved_s": 0.0})
|
|
||||||
if "fast" in tiers: # enforced lessons ride the same path as floors (personal overlay, trusted commands)
|
if "fast" in tiers: # enforced lessons ride the same path as floors (personal overlay, trusted commands)
|
||||||
try:
|
try:
|
||||||
from . import cycle
|
from . import cycle
|
||||||
|
|||||||
@@ -40,17 +40,6 @@ class ContractTests(SisiCase):
|
|||||||
def test_rung_5_6_valid_without_cmd(self):
|
def test_rung_5_6_valid_without_cmd(self):
|
||||||
self.assertEqual(C.validate(contract([check("a", "true"), human("h", 5), human("i", 6)])), [])
|
self.assertEqual(C.validate(contract([check("a", "true"), human("h", 5), human("i", 6)])), [])
|
||||||
|
|
||||||
def test_floors(self):
|
|
||||||
weak = contract([check("m", "true", rung=3, kind="money")])
|
|
||||||
self.assertEqual(len(C.floor_failures(weak)), 1)
|
|
||||||
self.assertEqual(C.floor_failures(contract([check("m", "true", rung=2, kind="money")])), [])
|
|
||||||
# one strong check among weak ones satisfies the floor
|
|
||||||
self.assertEqual(C.floor_failures(contract([check("m", "true", rung=3, kind="money"),
|
|
||||||
check("n", "true", rung=1, kind="money")])), [])
|
|
||||||
self.assertEqual(C.floor_failures(contract([check("u", "true", rung=4, kind="ui")])), [])
|
|
||||||
for k in ("concurrency", "parsing", "money", "state-machine", "migration"):
|
|
||||||
self.assertEqual(C.floors()[k], 2)
|
|
||||||
|
|
||||||
def test_find_stops_at_git_root(self):
|
def test_find_stops_at_git_root(self):
|
||||||
self.git_init()
|
self.git_init()
|
||||||
self.write_contract(contract([check("a", "true")]))
|
self.write_contract(contract([check("a", "true")]))
|
||||||
|
|||||||
@@ -161,17 +161,6 @@ class ShowAndChooseTests(LibCase):
|
|||||||
out = self.sisi("verifiers", "for", "widget").stdout
|
out = self.sisi("verifiers", "for", "widget").stdout
|
||||||
self.assertEqual(len([l for l in out.splitlines() if l[:1].isdigit()]), 8)
|
self.assertEqual(len([l for l in out.splitlines() if l[:1].isdigit()]), 8)
|
||||||
|
|
||||||
def test_for_kind_floor_marking(self):
|
|
||||||
self.seed()
|
|
||||||
out = self.sisi("verifiers", "for", "parsing round trip", "--kind", "parsing").stdout
|
|
||||||
self.assertIn("Floor: parsing claims need rung 2", out)
|
|
||||||
self.assertIn("[floor ok]", out)
|
|
||||||
self.put("prove/weakparse.md", vfile("weakparse", rung=4, kinds="parsing", answers="Does parsing look fine?"))
|
|
||||||
out = self.sisi("verifiers", "for", "parsing looks fine", "--kind", "parsing").stdout
|
|
||||||
self.assertIn("[below floor]", out)
|
|
||||||
out = self.sisi("verifiers", "for", "page looks", "--kind", "ui").stdout
|
|
||||||
self.assertNotIn("Floor:", out)
|
|
||||||
|
|
||||||
def test_for_lang_and_kind_filters(self):
|
def test_for_lang_and_kind_filters(self):
|
||||||
self.seed()
|
self.seed()
|
||||||
out = self.sisi("verifiers", "for", "random inputs parsing", "--lang", "rust").stdout
|
out = self.sisi("verifiers", "for", "random inputs parsing", "--lang", "rust").stdout
|
||||||
|
|||||||
Reference in new issue
Block a user